import {
  createHash,
  createPrivateKey,
  createPublicKey,
  generateKeyPairSync,
  randomBytes,
  sign as signBytes,
  verify as verifyBytes
} from "node:crypto";
import {
  chmod,
  link,
  lstat,
  mkdir,
  open,
  readFile,
  rename,
  rm,
  unlink
} from "node:fs/promises";
import os from "node:os";
import path from "node:path";
import { fileURLToPath } from "node:url";
import {
  RUNRAIL_PLAN_CATALOG_REVISION,
  runrailPlanForCode
} from "../apps/shared/runrail-plan-catalog.mjs";
import {
  RUNRAIL_ENTITLEMENT_LEASE_V2_DURATION_MILLISECONDS,
  RUNRAIL_ENTITLEMENT_LEASE_V2_OFFLINE_GRACE_DURATION_MILLISECONDS,
  RUNRAIL_ENTITLEMENT_LEASE_V2_RENEW_AFTER_MILLISECONDS
} from "../apps/pilot/src/runrail-entitlement-lease.mjs";
import {
  buildRunrailDeviceSignedReviewPassport,
  canonicalRunrailDeviceSignedPassportMessage,
  verifyRunrailReviewPassport
} from "./runrail-review-passport-core.mjs";

export const RUNRAIL_DEVICE_ENROLLMENT_REQUEST_SCHEMA_VERSION = 1;
export const RUNRAIL_DEVICE_ENTITLEMENT_LEASE_SCHEMA_VERSION_V2 = 2;
export const RUNRAIL_DEVICE_ENTITLEMENT_LEASE_SCHEMA_VERSION = 3;
export const RUNRAIL_ENTITLEMENT_PRODUCTION_ORIGIN = "https://app.veyact.com";
export const RUNRAIL_DEVICE_ENTITLEMENT_MAX_GRACE_MILLISECONDS =
  RUNRAIL_ENTITLEMENT_LEASE_V2_OFFLINE_GRACE_DURATION_MILLISECONDS;

const MAX_ENTITLEMENT_FILE_BYTES = 256 * 1024;
const MAX_TICKET_FILE_BYTES = 64 * 1024;
const MAX_RESPONSE_BYTES = 128 * 1024;
const DEFAULT_FETCH_TIMEOUT_MILLISECONDS = 10_000;
const OPPORTUNISTIC_RENEWAL_TIMEOUT_MILLISECONDS = 2_000;
const PRIVATE_FILE_MODE = 0o600;
const PRIVATE_DIRECTORY_MODE = 0o700;
const ACTIVE_BUNDLE_NAME = "device-entitlement.json";
const PREVIOUS_BUNDLE_NAME = "device-entitlement.previous.json";
const PENDING_BUNDLE_NAME = "device-enrollment-pending.json";
const DEFAULT_REQUEST_NAME = "device-enrollment-request.json";
const legacyCompatibleDistributionVersions = new Set(["1.3.0"]);
const moduleDistributionRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
const OPAQUE_ID_PATTERN = /^[A-Za-z0-9][A-Za-z0-9_-]{15,127}$/;
const ENROLLMENT_ID_PATTERN = /^enroll_[A-Za-z0-9_-]{32}$/;
const KEY_ID_PATTERN = /^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/;
const BASE64URL_PATTERN = /^[A-Za-z0-9_-]+$/;
const SHA256_PATTERN = /^[a-f0-9]{64}$/;
const REQUEST_KEYS = Object.freeze([
  "schemaVersion",
  "artifactType",
  "devicePublicKeyPem",
  "devicePublicKeySha256",
  "installationFingerprint",
  "clientNonce",
  "signature",
  "authority"
]);
const TICKET_KEYS = Object.freeze([
  "schemaVersion",
  "artifactType",
  "serverOrigin",
  "enrollmentId",
  "secret",
  "challenge",
  "expiresAt",
  "planCode",
  "catalogRevision",
  "devicePublicKeySha256",
  "installationFingerprint",
  "authority"
]);
const ACTIVATION_KEYS = Object.freeze([
  "schemaVersion",
  "artifactType",
  "deviceId",
  "lease",
  "publicKeys",
  "renewAfter",
  "graceUntil",
  "serverOrigin",
  "authority",
  "executionAuthorityGranted"
]);
const LEASE_PAYLOAD_KEYS_V2 = Object.freeze([
  "schemaVersion",
  "catalogRevision",
  "accountId",
  "workspaceId",
  "deviceId",
  "devicePublicKeySha256",
  "leaseSequence",
  "planCode",
  "features",
  "issuedAt",
  "renewAfter",
  "expiresAt",
  "graceUntil",
  "keyId",
  "authority",
  "executionAuthorityGranted"
]);
const LEASE_PAYLOAD_KEYS_V3 = Object.freeze([
  "schemaVersion",
  "catalogRevision",
  "accountId",
  "workspaceId",
  "deviceId",
  "devicePublicKeySha256",
  "leaseSequence",
  "planCode",
  "features",
  "subscriptionStatus",
  "trialStartedAt",
  "trialEndsAt",
  "maxDevices",
  "featureSet",
  "issuedAt",
  "renewAfter",
  "expiresAt",
  "graceUntil",
  "keyId",
  "authority",
  "executionAuthorityGranted"
]);
const BUNDLE_KEYS = Object.freeze([
  "schemaVersion",
  "artifactType",
  "serverOrigin",
  "deviceId",
  "installationFingerprint",
  "devicePublicKeySha256",
  "devicePublicKeyPem",
  "devicePrivateKeyPem",
  "activation",
  "authority",
  "executionAuthorityGranted"
]);
const PENDING_KEYS = Object.freeze([
  "schemaVersion",
  "artifactType",
  "devicePrivateKeyPem",
  "request",
  "authority"
]);
const legacyFeatures = Object.freeze([
  "guided-sample",
  "candidate-branch-review",
  "audit-export",
  "deterministic-advisory",
  "deepseek-byok-advisory",
  "revision-comparison",
  "reusable-policy-profiles",
  "advanced-evidence-exports"
]);
const publicPreviewFeatures = Object.freeze([
  "guided-sample",
  "public-preview-candidate-review"
]);
const commandFeatures = new Map([
  ["sample", "guided-sample"],
  ["review", "candidate-branch-review"],
  ["focus", "candidate-branch-review"],
  ["coverage", "candidate-branch-review"],
  ["recheck", "revision-comparison"],
  ["audit", "audit-export"],
  ["prepare", "audit-export"],
  ["compare", "revision-comparison"],
  ["lineage", "advanced-evidence-exports"],
  ["handoff", "candidate-branch-review"],
  ["assure", "candidate-branch-review"],
  ["desktop", "candidate-branch-review"]
]);
const explicitCommands = new Set([
  "desktop",
  "doctor",
  "sample",
  "prepare",
  "audit",
  "review",
  "focus",
  "coverage",
  "recheck",
  "compare",
  "lineage",
  "handoff",
  "assure",
  "recommend",
  "advise",
  "license"
]);

function entitlementError(code, message) {
  const error = new Error(message);
  error.code = code;
  return error;
}

function exactObject(value, keys, label) {
  if (!value || typeof value !== "object" || Array.isArray(value)) {
    throw entitlementError("runrail-entitlement-schema-invalid", `${label} must be an object.`);
  }
  const actual = Object.keys(value).sort();
  const expected = [...keys].sort();
  if (actual.length !== expected.length || actual.some((key, index) => key !== expected[index])) {
    throw entitlementError(
      "runrail-entitlement-schema-invalid",
      `${label} contains missing or unsupported fields.`
    );
  }
}

function sha256(value) {
  return createHash("sha256").update(value).digest("hex");
}

function stableValue(value) {
  if (Array.isArray(value)) return value.map(stableValue);
  if (value && typeof value === "object") {
    return Object.fromEntries(Object.keys(value).sort().map((key) => [key, stableValue(value[key])]));
  }
  return value;
}

function stableJson(value) {
  return `${JSON.stringify(stableValue(value), null, 2)}\n`;
}

function canonicalTimestamp(value, label) {
  if (typeof value !== "string") {
    throw entitlementError("runrail-entitlement-schema-invalid", `${label} must be a canonical UTC timestamp.`);
  }
  const milliseconds = Date.parse(value);
  if (!Number.isFinite(milliseconds) || new Date(milliseconds).toISOString() !== value) {
    throw entitlementError("runrail-entitlement-schema-invalid", `${label} must be a canonical UTC timestamp.`);
  }
  return milliseconds;
}

function nowMilliseconds(value) {
  const date = value instanceof Date ? new Date(value.getTime()) : new Date(value);
  if (!Number.isFinite(date.getTime())) {
    throw entitlementError("runrail-entitlement-time-invalid", "The entitlement clock value is invalid.");
  }
  return date.getTime();
}

function assertOpaqueId(value, label) {
  if (typeof value !== "string" || !OPAQUE_ID_PATTERN.test(value)) {
    throw entitlementError("runrail-entitlement-schema-invalid", `${label} is invalid.`);
  }
}

function assertBase64url(value, label, minimumBytes = 16, maximumBytes = 512) {
  if (typeof value !== "string" || !BASE64URL_PATTERN.test(value)) {
    throw entitlementError("runrail-entitlement-schema-invalid", `${label} must be canonical base64url.`);
  }
  const decoded = Buffer.from(value, "base64url");
  if (
    decoded.length < minimumBytes ||
    decoded.length > maximumBytes ||
    decoded.toString("base64url") !== value
  ) {
    throw entitlementError("runrail-entitlement-schema-invalid", `${label} must be canonical base64url.`);
  }
  return decoded;
}

function assertSha256(value, label) {
  if (typeof value !== "string" || !SHA256_PATTERN.test(value)) {
    throw entitlementError("runrail-entitlement-schema-invalid", `${label} must be a lowercase SHA-256 digest.`);
  }
}

function publicEd25519Key(value, label = "Device public key") {
  let key;
  try {
    key = value?.type === "public" ? value : createPublicKey(value);
  } catch {
    throw entitlementError("runrail-entitlement-key-invalid", `${label} must be a valid Ed25519 public key.`);
  }
  if (key.type !== "public" || key.asymmetricKeyType !== "ed25519") {
    throw entitlementError("runrail-entitlement-key-invalid", `${label} must be a valid Ed25519 public key.`);
  }
  return key;
}

function privateEd25519Key(value) {
  let key;
  try {
    key = value?.type === "private" ? value : createPrivateKey(value);
  } catch {
    throw entitlementError(
      "runrail-entitlement-key-invalid",
      "The pending device private key is not a valid Ed25519 private key."
    );
  }
  if (key.type !== "private" || key.asymmetricKeyType !== "ed25519") {
    throw entitlementError(
      "runrail-entitlement-key-invalid",
      "The pending device private key is not a valid Ed25519 private key."
    );
  }
  return key;
}

function publicKeyPem(value) {
  return publicEd25519Key(value).export({ format: "pem", type: "spki" }).toString("utf8");
}

function privateKeyPem(value) {
  return privateEd25519Key(value).export({ format: "pem", type: "pkcs8" }).toString("utf8");
}

export function runrailDevicePublicKeySha256(value) {
  const key = publicEd25519Key(value);
  return sha256(key.export({ format: "der", type: "spki" }));
}

function assertPrivateFileMode(info, label) {
  if (process.platform !== "win32" && (info.mode & 0o077) !== 0) {
    throw entitlementError(
      "runrail-entitlement-file-permissions-invalid",
      `${label} must not be readable or writable by group or other users.`
    );
  }
}

async function pathInfo(target) {
  try {
    return await lstat(target);
  } catch (error) {
    if (error?.code === "ENOENT") return null;
    throw error;
  }
}

async function readBoundedRegularFile(
  filePath,
  label,
  { maximumBytes = MAX_ENTITLEMENT_FILE_BYTES, privateMode = false } = {}
) {
  const absolute = path.resolve(String(filePath || ""));
  let info;
  try {
    info = await lstat(absolute);
  } catch (error) {
    if (error?.code === "ENOENT") {
      throw entitlementError("runrail-entitlement-file-missing", `${label} does not exist.`);
    }
    throw error;
  }
  if (!info.isFile() || info.isSymbolicLink() || info.size > maximumBytes) {
    throw entitlementError(
      "runrail-entitlement-file-invalid",
      `${label} must be a regular file no larger than ${maximumBytes} bytes.`
    );
  }
  if (privateMode) assertPrivateFileMode(info, label);
  return readFile(absolute);
}

async function readJsonRegularFile(filePath, label, options = {}) {
  const bytes = await readBoundedRegularFile(filePath, label, options);
  try {
    return { bytes, value: JSON.parse(bytes.toString("utf8")) };
  } catch {
    throw entitlementError("runrail-entitlement-json-invalid", `${label} must contain valid JSON.`);
  }
}

async function ensureSecureDirectory(directory) {
  const absolute = path.resolve(directory);
  await mkdir(absolute, { recursive: true, mode: PRIVATE_DIRECTORY_MODE });
  const info = await lstat(absolute);
  if (!info.isDirectory() || info.isSymbolicLink()) {
    throw entitlementError(
      "runrail-entitlement-directory-invalid",
      "The Runrail entitlement directory must be an ordinary directory."
    );
  }
  if (process.platform !== "win32") {
    await chmod(absolute, PRIVATE_DIRECTORY_MODE);
  }
  return absolute;
}

async function writePrivateFile(filePath, bytes, { exclusive = false } = {}) {
  const handle = await open(filePath, exclusive ? "wx" : "w", PRIVATE_FILE_MODE);
  try {
    await handle.writeFile(bytes);
    await handle.sync();
  } finally {
    await handle.close();
  }
  if (process.platform !== "win32") await chmod(filePath, PRIVATE_FILE_MODE);
}

async function createPrivateFileAtomically(filePath, bytes, verifyFile) {
  const directory = path.dirname(filePath);
  const temporaryPath = path.join(
    directory,
    `.${path.basename(filePath)}.${randomBytes(12).toString("hex")}.pending`
  );
  try {
    await writePrivateFile(temporaryPath, bytes, { exclusive: true });
    await verifyFile(temporaryPath);
    await link(temporaryPath, filePath);
  } finally {
    await rm(temporaryPath, { force: true }).catch(() => {});
  }
}

async function replaceRegularFile(sourcePath, targetPath, label) {
  const existing = await pathInfo(targetPath);
  if (existing && (!existing.isFile() || existing.isSymbolicLink())) {
    throw entitlementError(
      "runrail-entitlement-file-invalid",
      `${label} replacement target must be a regular file.`
    );
  }
  try {
    await rename(sourcePath, targetPath);
  } catch (error) {
    if (process.platform !== "win32" || !existing || !["EEXIST", "EPERM"].includes(error?.code)) {
      throw error;
    }
    await rm(targetPath, { force: true });
    await rename(sourcePath, targetPath);
  }
}

export function defaultRunrailEntitlementDirectory({
  env = process.env,
  platform = process.platform,
  homeDirectory
} = {}) {
  const resolvedHomeDirectory = path.resolve(
    homeDirectory ||
      env.HOME ||
      env.USERPROFILE ||
      os.homedir()
  );
  if (platform === "win32") {
    return path.join(
      env.LOCALAPPDATA || path.join(resolvedHomeDirectory, "AppData", "Local"),
      "Runrail",
      "entitlement"
    );
  }
  if (platform === "darwin") {
    return path.join(
      resolvedHomeDirectory,
      "Library",
      "Application Support",
      "Runrail",
      "entitlement"
    );
  }
  return path.join(
    env.XDG_DATA_HOME || path.join(resolvedHomeDirectory, ".local", "share"),
    "runrail",
    "entitlement"
  );
}

export function runrailManagedEntitlementPaths(options = {}) {
  const directory = path.resolve(
    options.managedDirectory || defaultRunrailEntitlementDirectory(options)
  );
  return Object.freeze({
    directory,
    activeBundlePath: path.join(directory, ACTIVE_BUNDLE_NAME),
    previousBundlePath: path.join(directory, PREVIOUS_BUNDLE_NAME),
    pendingBundlePath: path.join(directory, PENDING_BUNDLE_NAME),
    defaultRequestPath: path.join(directory, DEFAULT_REQUEST_NAME)
  });
}

function canonicalRequestMessageObject(request) {
  return {
    schemaVersion: 1,
    artifactType: "runrail-device-enrollment-request",
    devicePublicKeySha256: request.devicePublicKeySha256,
    installationFingerprint: request.installationFingerprint,
    clientNonce: request.clientNonce,
    authority: "none"
  };
}

function canonicalDeviceMessage(domain, payload) {
  return Buffer.from(`${domain}\n${JSON.stringify(payload)}`, "utf8");
}

export function canonicalRunrailDeviceEnrollmentRequestMessage(request) {
  return canonicalDeviceMessage(
    "RUNRAIL-DEVICE-ENROLLMENT-REQUEST-V1",
    canonicalRequestMessageObject(request)
  );
}

export function verifyRunrailDeviceEnrollmentRequest(request) {
  exactObject(request, REQUEST_KEYS, "Runrail device enrollment request");
  if (
    request.schemaVersion !== RUNRAIL_DEVICE_ENROLLMENT_REQUEST_SCHEMA_VERSION ||
    request.artifactType !== "runrail-device-enrollment-request" ||
    request.authority !== "none"
  ) {
    throw entitlementError(
      "runrail-enrollment-request-invalid",
      "The Runrail device enrollment request contract is invalid."
    );
  }
  assertSha256(request.devicePublicKeySha256, "devicePublicKeySha256");
  assertBase64url(request.installationFingerprint, "installationFingerprint", 32, 32);
  assertBase64url(request.clientNonce, "clientNonce", 32, 32);
  const publicKey = publicEd25519Key(request.devicePublicKeyPem);
  if (
    publicKeyPem(publicKey) !== request.devicePublicKeyPem ||
    runrailDevicePublicKeySha256(publicKey) !== request.devicePublicKeySha256
  ) {
    throw entitlementError(
      "runrail-enrollment-request-key-binding-invalid",
      "The enrollment request public key does not match its SHA-256 binding."
    );
  }
  const signature = assertBase64url(request.signature, "Enrollment request signature", 64, 64);
  const message = canonicalRunrailDeviceEnrollmentRequestMessage(request);
  if (!verifyBytes(null, message, publicKey, signature)) {
    throw entitlementError(
      "runrail-enrollment-request-signature-invalid",
      "The enrollment request proof-of-possession signature is invalid."
    );
  }
  return Object.freeze({ request: Object.freeze({ ...request }), publicKey });
}

function verifyPendingBundle(pending) {
  exactObject(pending, PENDING_KEYS, "Pending Runrail device enrollment");
  if (
    pending.schemaVersion !== 1 ||
    pending.artifactType !== "runrail-device-enrollment-pending" ||
    pending.authority !== "none"
  ) {
    throw entitlementError(
      "runrail-enrollment-pending-invalid",
      "The pending Runrail device enrollment record is invalid."
    );
  }
  const verifiedRequest = verifyRunrailDeviceEnrollmentRequest(pending.request);
  const privateKey = privateEd25519Key(pending.devicePrivateKeyPem);
  if (
    privateKeyPem(privateKey) !== pending.devicePrivateKeyPem ||
    publicKeyPem(createPublicKey(privateKey)) !== pending.request.devicePublicKeyPem
  ) {
    throw entitlementError(
      "runrail-enrollment-pending-key-mismatch",
      "The pending private key does not match the public enrollment request."
    );
  }
  return Object.freeze({
    pending: Object.freeze({ ...pending, request: verifiedRequest.request }),
    privateKey,
    publicKey: verifiedRequest.publicKey
  });
}

async function readPendingBundle(paths) {
  const info = await pathInfo(paths.pendingBundlePath);
  if (!info) return null;
  const { value } = await readJsonRegularFile(
    paths.pendingBundlePath,
    "Pending Runrail device enrollment",
    { privateMode: true }
  );
  return verifyPendingBundle(value);
}

async function assertPublicRequestTarget(requestPath, expectedBytes = null) {
  if (!path.isAbsolute(requestPath)) {
    throw entitlementError(
      "runrail-enrollment-request-output-invalid",
      "The enrollment request output path must be absolute."
    );
  }
  const parent = path.dirname(requestPath);
  const parentInfo = await pathInfo(parent);
  if (!parentInfo || !parentInfo.isDirectory() || parentInfo.isSymbolicLink()) {
    throw entitlementError(
      "runrail-enrollment-request-output-invalid",
      "The enrollment request output directory must be an ordinary existing directory."
    );
  }
  const existing = await pathInfo(requestPath);
  if (!existing) return false;
  if (!existing.isFile() || existing.isSymbolicLink() || existing.size > MAX_ENTITLEMENT_FILE_BYTES) {
    throw entitlementError(
      "runrail-enrollment-request-output-invalid",
      "The enrollment request output target must be a bounded regular file."
    );
  }
  if (expectedBytes) {
    const actual = await readFile(requestPath);
    if (actual.equals(expectedBytes)) return true;
  }
  throw entitlementError(
    "runrail-enrollment-request-output-exists",
    "The enrollment request output path already exists and was not overwritten."
  );
}

async function writePublicRequest(requestPath, request, { allowMatching = false } = {}) {
  const bytes = Buffer.from(stableJson(request), "utf8");
  const matching = await assertPublicRequestTarget(requestPath, allowMatching ? bytes : null);
  if (!matching) await writePrivateFile(requestPath, bytes, { exclusive: true });
  return path.resolve(requestPath);
}

export async function createRunrailDeviceEnrollmentRequest({
  env = process.env,
  managedDirectory,
  outputPath
} = {}) {
  const paths = runrailManagedEntitlementPaths({ env, managedDirectory });
  await ensureSecureDirectory(paths.directory);
  const resolvedOutputPath = path.resolve(outputPath || paths.defaultRequestPath);
  const active = await loadRunrailManagedEntitlementBundle({
    env,
    managedDirectory: paths.directory
  });
  if (active) {
    throw entitlementError(
      "runrail-enrollment-replacement-required",
      "A verified Runrail device is already enrolled. This client does not provide an implicit device-replacement flow."
    );
  }
  const existingPending = await readPendingBundle(paths);
  if (existingPending) {
    const requestPath = await writePublicRequest(
      resolvedOutputPath,
      existingPending.pending.request,
      { allowMatching: true }
    );
    return Object.freeze({
      ok: true,
      status: "request-ready",
      requestPath,
      devicePublicKeySha256: existingPending.pending.request.devicePublicKeySha256,
      installationFingerprint: existingPending.pending.request.installationFingerprint,
      pendingKeyReused: true,
      privateKeyStoredLocally: true,
      networkUsed: false,
      authority: "none"
    });
  }

  await assertPublicRequestTarget(resolvedOutputPath);
  const keyPair = generateKeyPairSync("ed25519");
  const devicePublicKeyPem = publicKeyPem(keyPair.publicKey);
  const devicePrivateKeyPem = privateKeyPem(keyPair.privateKey);
  const request = {
    schemaVersion: RUNRAIL_DEVICE_ENROLLMENT_REQUEST_SCHEMA_VERSION,
    artifactType: "runrail-device-enrollment-request",
    devicePublicKeyPem,
    devicePublicKeySha256: runrailDevicePublicKeySha256(keyPair.publicKey),
    installationFingerprint: randomBytes(32).toString("base64url"),
    clientNonce: randomBytes(32).toString("base64url"),
    signature: "",
    authority: "none"
  };
  request.signature = signBytes(
    null,
    canonicalRunrailDeviceEnrollmentRequestMessage(request),
    keyPair.privateKey
  ).toString("base64url");
  verifyRunrailDeviceEnrollmentRequest(request);
  const pending = {
    schemaVersion: 1,
    artifactType: "runrail-device-enrollment-pending",
    devicePrivateKeyPem,
    request,
    authority: "none"
  };
  verifyPendingBundle(pending);

  let pendingWritten = false;
  let requestWritten = false;
  try {
    await createPrivateFileAtomically(
      paths.pendingBundlePath,
      Buffer.from(stableJson(pending), "utf8"),
      async (temporaryPath) => {
        const { value } = await readJsonRegularFile(
          temporaryPath,
          "Candidate pending Runrail device enrollment",
          { privateMode: true }
        );
        verifyPendingBundle(value);
      }
    );
    pendingWritten = true;
    await readPendingBundle(paths);
    await writePublicRequest(resolvedOutputPath, request);
    requestWritten = true;
  } catch (error) {
    if (requestWritten) await rm(resolvedOutputPath, { force: true }).catch(() => {});
    if (pendingWritten) await rm(paths.pendingBundlePath, { force: true }).catch(() => {});
    throw error;
  }

  return Object.freeze({
    ok: true,
    status: "request-ready",
    requestPath: resolvedOutputPath,
    devicePublicKeySha256: request.devicePublicKeySha256,
    installationFingerprint: request.installationFingerprint,
    pendingKeyReused: false,
    privateKeyStoredLocally: true,
    networkUsed: false,
    authority: "none"
  });
}

export async function createRunrailNativeEnrollmentHandoff({
  serverOrigin = RUNRAIL_ENTITLEMENT_PRODUCTION_ORIGIN,
  env = process.env,
  managedDirectory,
  now = new Date(),
  fetchImpl = globalThis.fetch,
  timeoutMilliseconds = DEFAULT_FETCH_TIMEOUT_MILLISECONDS
} = {}) {
  const approvedOrigin = validateRunrailEntitlementServerOrigin(serverOrigin, { env });
  const created = await createRunrailDeviceEnrollmentRequest({ env, managedDirectory });
  const requestRecord = await readJsonRegularFile(
    created.requestPath,
    "Runrail device enrollment request",
    { maximumBytes: MAX_TICKET_FILE_BYTES }
  );
  const enrollmentRequest = verifyRunrailDeviceEnrollmentRequest(requestRecord.value);
  const response = await postEntitlementJson(
    `${approvedOrigin}/api/account/devices/enroll/request`,
    enrollmentRequest,
    {
      fetchImpl,
      timeoutMilliseconds,
      label: "Runrail native enrollment request",
      rejectionCode: "runrail-enrollment-handoff-request-rejected"
    }
  );
  exactObject(
    response,
    [
      "ok",
      "requestId",
      "browserUrl",
      "expiresAt",
      "devicePublicKeySha256",
      "authority",
      "executionAuthorityGranted"
    ],
    "Runrail native enrollment request response"
  );
  const browserUrl = new URL(response.browserUrl);
  if (
    response.ok !== true ||
    response.authority !== "none" ||
    response.executionAuthorityGranted !== false ||
    response.devicePublicKeySha256 !== enrollmentRequest.devicePublicKeySha256 ||
    browserUrl.origin !== approvedOrigin ||
    browserUrl.pathname !== "/app/customer/enroll" ||
    browserUrl.hash ||
    browserUrl.searchParams.getAll("requestId").length !== 1 ||
    [...browserUrl.searchParams.keys()].some((key) => key !== "requestId") ||
    !/^request_[A-Za-z0-9_-]{32}$/.test(String(response.requestId || "")) ||
    browserUrl.searchParams.get("requestId") !== response.requestId ||
    canonicalTimestamp(response.expiresAt, "expiresAt") <= nowMilliseconds(now)
  ) {
    throw entitlementError(
      "runrail-enrollment-handoff-request-invalid",
      "The native enrollment request response is invalid."
    );
  }
  return Object.freeze({
    ...response,
    requestPath: created.requestPath,
    pendingKeyReused: created.pendingKeyReused,
    privateKeyStoredLocally: true,
    networkUsed: true
  });
}

export function validateRunrailDeviceEnrollmentTicket(ticket, {
  env = process.env,
  now = new Date()
} = {}) {
  exactObject(ticket, TICKET_KEYS, "Runrail device enrollment ticket");
  if (
    ticket.schemaVersion !== 1 ||
    ticket.artifactType !== "runrail-device-enrollment-ticket" ||
    ticket.authority !== "none"
  ) {
    throw entitlementError(
      "runrail-enrollment-ticket-invalid",
      "The Runrail device enrollment ticket contract is invalid."
    );
  }
  const serverOrigin = validateRunrailEntitlementServerOrigin(ticket.serverOrigin, { env });
  if (!ENROLLMENT_ID_PATTERN.test(ticket.enrollmentId)) {
    throw entitlementError(
      "runrail-enrollment-ticket-invalid",
      "The Runrail device enrollment ticket ID is invalid."
    );
  }
  assertBase64url(ticket.secret, "ticket secret", 32, 32);
  assertBase64url(ticket.challenge, "ticket challenge", 32, 32);
  const expiresAt = canonicalTimestamp(ticket.expiresAt, "expiresAt");
  if (expiresAt <= nowMilliseconds(now)) {
    throw entitlementError(
      "runrail-enrollment-ticket-expired",
      "The Runrail device enrollment ticket has expired."
    );
  }
  if (
    typeof ticket.planCode !== "string" ||
    !runrailPlanForCode(ticket.planCode) ||
    ticket.catalogRevision !== RUNRAIL_PLAN_CATALOG_REVISION
  ) {
    throw entitlementError(
      "runrail-enrollment-ticket-catalog-invalid",
      "The Runrail device enrollment ticket does not use the current plan catalog."
    );
  }
  assertSha256(ticket.devicePublicKeySha256, "devicePublicKeySha256");
  assertBase64url(ticket.installationFingerprint, "installationFingerprint", 32, 32);
  return Object.freeze({ ...ticket, serverOrigin });
}

export function validateRunrailEntitlementServerOrigin(value, { env = process.env } = {}) {
  if (typeof value !== "string" || value.length > 255) {
    throw entitlementError(
      "runrail-entitlement-origin-unapproved",
      "The entitlement server origin must be a bounded string."
    );
  }
  let parsed;
  try {
    parsed = new URL(value);
  } catch {
    throw entitlementError(
      "runrail-entitlement-origin-unapproved",
      "The entitlement server origin is invalid."
    );
  }
  if (
    value !== parsed.origin ||
    parsed.username ||
    parsed.password ||
    parsed.pathname !== "/" ||
    parsed.search ||
    parsed.hash
  ) {
    throw entitlementError(
      "runrail-entitlement-origin-unapproved",
      "The entitlement server must be a canonical origin with no credentials or path."
    );
  }
  if (parsed.origin === RUNRAIL_ENTITLEMENT_PRODUCTION_ORIGIN) {
    return parsed.origin;
  }
  const explicitLoopbackTest =
    String(env.RUNRAIL_ALLOW_INSECURE_LOOPBACK_TEST || "").trim() === "1";
  const literalLoopback =
    parsed.protocol === "http:" &&
    (parsed.hostname === "127.0.0.1" || parsed.hostname === "[::1]");
  if (!explicitLoopbackTest || !literalLoopback) {
    throw entitlementError(
      "runrail-entitlement-origin-unapproved",
      `Runrail entitlement requests require ${RUNRAIL_ENTITLEMENT_PRODUCTION_ORIGIN}. Literal HTTP loopback is test-only and must be explicitly enabled.`
    );
  }
  return parsed.origin;
}

function canonicalEnrollmentCompletionMessageObject(ticket) {
  return {
    schemaVersion: 1,
    artifactType: "runrail-device-enrollment-challenge",
    serverOrigin: ticket.serverOrigin,
    enrollmentId: ticket.enrollmentId,
    ticketSecretSha256: sha256(`runrail-enrollment-secret:${ticket.secret}`),
    challenge: ticket.challenge,
    expiresAt: ticket.expiresAt,
    planCode: ticket.planCode,
    catalogRevision: ticket.catalogRevision,
    devicePublicKeySha256: ticket.devicePublicKeySha256,
    installationFingerprint: ticket.installationFingerprint,
    authority: "none"
  };
}

export function canonicalRunrailDeviceEnrollmentCompletionMessage(ticket) {
  return canonicalDeviceMessage(
    "RUNRAIL-DEVICE-ENROLLMENT-CHALLENGE-V1",
    canonicalEnrollmentCompletionMessageObject(ticket)
  );
}

export function canonicalRunrailDeviceEnrollmentChallengeMessage({
  ticket,
  devicePublicKeyPem,
  installationFingerprint
}) {
  const publicKeySha256 = runrailDevicePublicKeySha256(devicePublicKeyPem);
  if (
    publicKeySha256 !== ticket?.devicePublicKeySha256 ||
    installationFingerprint !== ticket?.installationFingerprint
  ) {
    throw entitlementError(
      "runrail-enrollment-ticket-device-mismatch",
      "The enrollment challenge key or fingerprint does not match its ticket."
    );
  }
  return canonicalRunrailDeviceEnrollmentCompletionMessage(ticket);
}

function canonicalRenewalMessageObject({
  serverOrigin,
  deviceId,
  devicePublicKeySha256,
  leaseSequence,
  nonce
}) {
  return {
    schemaVersion: 1,
    artifactType: "runrail-device-renewal-challenge",
    serverOrigin,
    deviceId,
    devicePublicKeySha256,
    leaseSequence,
    nonce,
    authority: "none"
  };
}

export function canonicalRunrailDeviceEntitlementRenewalMessage(input) {
  return canonicalDeviceMessage(
    "RUNRAIL-DEVICE-RENEWAL-V1",
    canonicalRenewalMessageObject(input)
  );
}

export function canonicalRunrailDeviceRenewalMessage(input) {
  return canonicalRunrailDeviceEntitlementRenewalMessage(input);
}

function trustedPublicKeys(document, expectedServerOrigin) {
  exactObject(
    document,
    [
      "schemaVersion",
      "artifactType",
      "serverOrigin",
      "catalogRevision",
      "keys",
      "authority"
    ],
    "Entitlement public-key document"
  );
  if (
    document.schemaVersion !== 1 ||
    document.artifactType !== "runrail-entitlement-public-keys" ||
    document.serverOrigin !== expectedServerOrigin ||
    document.catalogRevision !== RUNRAIL_PLAN_CATALOG_REVISION ||
    document.authority !== "none" ||
    !Array.isArray(document.keys) ||
    document.keys.length === 0 ||
    document.keys.length > 8
  ) {
    throw entitlementError(
      "runrail-entitlement-public-keys-invalid",
      "The entitlement public-key document is invalid."
    );
  }
  const keys = new Map();
  for (const entry of document.keys) {
    exactObject(entry, ["keyId", "algorithm", "publicKeyPem"], "Entitlement public key");
    if (
      typeof entry.keyId !== "string" ||
      !KEY_ID_PATTERN.test(entry.keyId) ||
      entry.algorithm !== "Ed25519" ||
      typeof entry.publicKeyPem !== "string" ||
      keys.has(entry.keyId)
    ) {
      throw entitlementError(
        "runrail-entitlement-public-keys-invalid",
        "The entitlement public-key document contains an invalid or duplicate key."
      );
    }
    const key = publicEd25519Key(entry.publicKeyPem, "Entitlement signing public key");
    if (publicKeyPem(key) !== entry.publicKeyPem) {
      throw entitlementError(
        "runrail-entitlement-public-keys-invalid",
        "The entitlement signing public key must use canonical PEM encoding."
      );
    }
    keys.set(entry.keyId, key);
  }
  return keys;
}

function validateLeasePayload(payload) {
  const schemaVersion = payload?.schemaVersion;
  const payloadKeys =
    schemaVersion === RUNRAIL_DEVICE_ENTITLEMENT_LEASE_SCHEMA_VERSION_V2
      ? LEASE_PAYLOAD_KEYS_V2
      : schemaVersion === RUNRAIL_DEVICE_ENTITLEMENT_LEASE_SCHEMA_VERSION
        ? LEASE_PAYLOAD_KEYS_V3
        : null;
  if (!payloadKeys) {
    throw entitlementError(
      "runrail-entitlement-lease-schema-invalid",
      "The signed entitlement lease schema is unsupported."
    );
  }
  exactObject(payload, payloadKeys, "Entitlement lease payload");
  if (
    payload.catalogRevision !== RUNRAIL_PLAN_CATALOG_REVISION ||
    payload.authority !== "subscription-entitlement-only" ||
    payload.executionAuthorityGranted !== false
  ) {
    throw entitlementError(
      "runrail-entitlement-lease-schema-invalid",
      "The signed entitlement lease contract is invalid."
    );
  }
  assertOpaqueId(payload.accountId, "accountId");
  assertOpaqueId(payload.workspaceId, "workspaceId");
  assertOpaqueId(payload.deviceId, "deviceId");
  assertSha256(payload.devicePublicKeySha256, "devicePublicKeySha256");
  if (!Number.isSafeInteger(payload.leaseSequence) || payload.leaseSequence < 1) {
    throw entitlementError(
      "runrail-entitlement-lease-sequence-invalid",
      "The entitlement lease sequence must be a positive safe integer."
    );
  }
  if (typeof payload.keyId !== "string" || !KEY_ID_PATTERN.test(payload.keyId)) {
    throw entitlementError(
      "runrail-entitlement-lease-key-invalid",
      "The entitlement lease key ID is invalid."
    );
  }
  const plan = runrailPlanForCode(payload.planCode);
  if (!plan || plan.code !== payload.planCode) {
    throw entitlementError(
      "runrail-entitlement-lease-plan-invalid",
      "The entitlement lease plan is not in the canonical catalog."
    );
  }
  if (
    !Array.isArray(payload.features) ||
    payload.features.length !== plan.features.length ||
    payload.features.some((feature, index) => feature !== plan.features[index])
  ) {
    throw entitlementError(
      "runrail-entitlement-lease-features-invalid",
      "The entitlement lease features do not match the canonical plan."
    );
  }
  const issuedAt = canonicalTimestamp(payload.issuedAt, "issuedAt");
  const expiresAt = canonicalTimestamp(payload.expiresAt, "expiresAt");
  const renewAfter = canonicalTimestamp(payload.renewAfter, "renewAfter");
  const graceUntil = canonicalTimestamp(payload.graceUntil, "graceUntil");
  if (schemaVersion === RUNRAIL_DEVICE_ENTITLEMENT_LEASE_SCHEMA_VERSION_V2) {
    if (
      renewAfter - issuedAt !== RUNRAIL_ENTITLEMENT_LEASE_V2_RENEW_AFTER_MILLISECONDS ||
      expiresAt - issuedAt !== RUNRAIL_ENTITLEMENT_LEASE_V2_DURATION_MILLISECONDS ||
      graceUntil - expiresAt !== RUNRAIL_DEVICE_ENTITLEMENT_MAX_GRACE_MILLISECONDS ||
      !(issuedAt < renewAfter && renewAfter < expiresAt && expiresAt < graceUntil)
    ) {
      throw entitlementError(
        "runrail-entitlement-lease-window-invalid",
        "The entitlement lease renewal, expiry, or bounded grace window is invalid."
      );
    }
  } else {
    if (!["active", "trialing"].includes(payload.subscriptionStatus)) {
      throw entitlementError(
        "runrail-entitlement-subscription-status-invalid",
        "The entitlement subscription status must be active or trialing."
      );
    }
    if (payload.featureSet !== plan.code) {
      throw entitlementError(
        "runrail-entitlement-feature-set-invalid",
        "The entitlement feature set must match the canonical plan."
      );
    }
    const expectedMaxDevices =
      payload.subscriptionStatus === "trialing"
        ? 1
        : Number.isSafeInteger(plan.maxDevices)
          ? plan.maxDevices
          : null;
    if (payload.maxDevices !== expectedMaxDevices) {
      throw entitlementError(
        "runrail-entitlement-device-limit-invalid",
        "The entitlement device limit does not match the canonical plan."
      );
    }
    if (payload.subscriptionStatus === "trialing" && plan.code !== "starter") {
      throw entitlementError(
        "runrail-entitlement-trial-plan-invalid",
        "Trial entitlements are limited to Starter."
      );
    }
    if (
      !(
        issuedAt < renewAfter &&
        renewAfter < expiresAt &&
        expiresAt <= graceUntil
      ) ||
      renewAfter - issuedAt > RUNRAIL_ENTITLEMENT_LEASE_V2_RENEW_AFTER_MILLISECONDS ||
      expiresAt - issuedAt > RUNRAIL_ENTITLEMENT_LEASE_V2_DURATION_MILLISECONDS ||
      graceUntil - issuedAt >
        RUNRAIL_ENTITLEMENT_LEASE_V2_DURATION_MILLISECONDS +
          RUNRAIL_DEVICE_ENTITLEMENT_MAX_GRACE_MILLISECONDS
    ) {
      throw entitlementError(
        "runrail-entitlement-lease-window-invalid",
        "The entitlement lease exceeds the bounded renewal or grace window."
      );
    }
    if (payload.subscriptionStatus === "active") {
      if (
        payload.trialStartedAt !== null ||
        payload.trialEndsAt !== null ||
        renewAfter - issuedAt !== RUNRAIL_ENTITLEMENT_LEASE_V2_RENEW_AFTER_MILLISECONDS ||
        expiresAt - issuedAt !== RUNRAIL_ENTITLEMENT_LEASE_V2_DURATION_MILLISECONDS ||
        graceUntil - expiresAt !== RUNRAIL_DEVICE_ENTITLEMENT_MAX_GRACE_MILLISECONDS
      ) {
        throw entitlementError(
          "runrail-entitlement-active-window-invalid",
          "The active entitlement must use the fixed Runrail lease window."
        );
      }
    } else {
      const trialStartedAt = canonicalTimestamp(
        payload.trialStartedAt,
        "trialStartedAt"
      );
      const trialEndsAt = canonicalTimestamp(payload.trialEndsAt, "trialEndsAt");
      if (
        trialStartedAt > issuedAt ||
        trialEndsAt <= issuedAt ||
        graceUntil > trialEndsAt
      ) {
        throw entitlementError(
          "runrail-entitlement-trial-window-invalid",
          "The trial entitlement cannot start before the trial or outlive trial expiry."
        );
      }
    }
  }
  return Object.freeze({
    plan,
    issuedAt,
    expiresAt,
    renewAfter,
    graceUntil
  });
}

export function serializeRunrailDeviceEntitlementLeasePayload(payload) {
  validateLeasePayload(payload);
  const payloadKeys =
    payload.schemaVersion === RUNRAIL_DEVICE_ENTITLEMENT_LEASE_SCHEMA_VERSION_V2
      ? LEASE_PAYLOAD_KEYS_V2
      : LEASE_PAYLOAD_KEYS_V3;
  return JSON.stringify(
    Object.fromEntries(payloadKeys.map((key) => [key, payload[key]]))
  );
}

export function verifyRunrailDeviceEntitlementLease(lease, {
  publicKeys,
  expectedServerOrigin,
  expectedDeviceId,
  expectedDevicePublicKeySha256,
  now = new Date()
}) {
  exactObject(lease, ["payload", "signature"], "Entitlement lease");
  const payloadBytes = assertBase64url(lease.payload, "Entitlement lease payload", 1, 64 * 1024);
  const signature = assertBase64url(lease.signature, "Entitlement lease signature", 64, 64);
  let payload;
  try {
    payload = JSON.parse(payloadBytes.toString("utf8"));
  } catch {
    throw entitlementError(
      "runrail-entitlement-lease-json-invalid",
      "The entitlement lease payload must contain valid JSON."
    );
  }
  const window = validateLeasePayload(payload);
  if (
    !payloadBytes.equals(
      Buffer.from(serializeRunrailDeviceEntitlementLeasePayload(payload), "utf8")
    )
  ) {
    throw entitlementError(
      "runrail-entitlement-lease-canonical-invalid",
      "The entitlement lease payload JSON is not canonical."
    );
  }
  const keys = trustedPublicKeys(publicKeys, expectedServerOrigin);
  const signingKey = keys.get(payload.keyId);
  if (!signingKey || !verifyBytes(null, payloadBytes, signingKey, signature)) {
    throw entitlementError(
      "runrail-entitlement-lease-signature-invalid",
      "The entitlement lease signature is invalid."
    );
  }
  if (
    payload.deviceId !== expectedDeviceId ||
    payload.devicePublicKeySha256 !== expectedDevicePublicKeySha256
  ) {
    throw entitlementError(
      "runrail-entitlement-device-binding-invalid",
      "The entitlement lease is not bound to this device key."
    );
  }
  const current = nowMilliseconds(now);
  if (window.issuedAt > current) {
    throw entitlementError(
      "runrail-entitlement-not-yet-valid",
      "The entitlement lease is not valid before its issuance time."
    );
  }
  let status = "valid";
  if (current >= window.graceUntil) status = "expired";
  else if (current >= window.expiresAt) status = "offline-grace";
  else if (current >= window.renewAfter) status = "renewal-needed";
  return Object.freeze({
    payload: Object.freeze({ ...payload, features: Object.freeze([...payload.features]) }),
    status,
    usable: status !== "expired"
  });
}

function validateActivation(activation, {
  serverOrigin,
  devicePublicKeySha256,
  now = new Date()
}) {
  exactObject(activation, ACTIVATION_KEYS, "Runrail device entitlement activation");
  if (
    activation.schemaVersion !== 1 ||
    activation.artifactType !== "runrail-device-entitlement-activation" ||
    activation.authority !== "subscription-entitlement-only" ||
    activation.executionAuthorityGranted !== false ||
    activation.serverOrigin !== serverOrigin
  ) {
    throw entitlementError(
      "runrail-entitlement-activation-invalid",
      "The Runrail device entitlement activation contract is invalid."
    );
  }
  assertOpaqueId(activation.deviceId, "deviceId");
  const lease = verifyRunrailDeviceEntitlementLease(activation.lease, {
    publicKeys: activation.publicKeys,
    expectedServerOrigin: serverOrigin,
    expectedDeviceId: activation.deviceId,
    expectedDevicePublicKeySha256: devicePublicKeySha256,
    now
  });
  if (
    activation.renewAfter !== lease.payload.renewAfter ||
    activation.graceUntil !== lease.payload.graceUntil
  ) {
    throw entitlementError(
      "runrail-entitlement-activation-window-mismatch",
      "The activation envelope does not match its signed renewal and grace window."
    );
  }
  return Object.freeze({ activation: Object.freeze({ ...activation }), lease });
}

function verifyManagedBundle(bundle, { env = process.env, now = new Date() } = {}) {
  exactObject(bundle, BUNDLE_KEYS, "Managed Runrail device entitlement bundle");
  if (
    bundle.schemaVersion !== 1 ||
    bundle.artifactType !== "runrail-device-entitlement-managed-bundle" ||
    bundle.authority !== "subscription-entitlement-only" ||
    bundle.executionAuthorityGranted !== false ||
    bundle.deviceId !== bundle.activation?.deviceId ||
    bundle.serverOrigin !== bundle.activation?.serverOrigin
  ) {
    throw entitlementError(
      "runrail-entitlement-bundle-invalid",
      "The managed Runrail device entitlement bundle contract is invalid."
    );
  }
  validateRunrailEntitlementServerOrigin(bundle.serverOrigin, { env });
  assertOpaqueId(bundle.deviceId, "deviceId");
  assertBase64url(bundle.installationFingerprint, "installationFingerprint", 32, 32);
  assertSha256(bundle.devicePublicKeySha256, "devicePublicKeySha256");
  const privateKey = privateEd25519Key(bundle.devicePrivateKeyPem);
  const derivedPublicPem = publicKeyPem(createPublicKey(privateKey));
  if (
    privateKeyPem(privateKey) !== bundle.devicePrivateKeyPem ||
    derivedPublicPem !== bundle.devicePublicKeyPem ||
    runrailDevicePublicKeySha256(derivedPublicPem) !== bundle.devicePublicKeySha256
  ) {
    throw entitlementError(
      "runrail-entitlement-bundle-key-mismatch",
      "The managed device keypair does not match its lease binding."
    );
  }
  const activation = validateActivation(bundle.activation, {
    serverOrigin: bundle.serverOrigin,
    devicePublicKeySha256: bundle.devicePublicKeySha256,
    now
  });
  return Object.freeze({
    bundle: Object.freeze({ ...bundle }),
    privateKey,
    publicKey: publicEd25519Key(bundle.devicePublicKeyPem),
    activation: activation.activation,
    lease: activation.lease
  });
}

export async function loadRunrailManagedEntitlementBundle({
  env = process.env,
  managedDirectory,
  now = new Date(),
  usePrevious = false
} = {}) {
  const paths = runrailManagedEntitlementPaths({ env, managedDirectory });
  const bundlePath = usePrevious ? paths.previousBundlePath : paths.activeBundlePath;
  const info = await pathInfo(bundlePath);
  if (info) {
    const { value } = await readJsonRegularFile(
      bundlePath,
      usePrevious ? "Previous Runrail entitlement bundle" : "Runrail entitlement bundle",
      { privateMode: true }
    );
    return Object.freeze({
      paths,
      bundlePath,
      recoveredFromPrevious: false,
      ...verifyManagedBundle(value, { env, now })
    });
  }
  if (usePrevious) return null;

  const previousInfo = await pathInfo(paths.previousBundlePath);
  if (!previousInfo) return null;
  const previousRecord = await readJsonRegularFile(
    paths.previousBundlePath,
    "Previous Runrail entitlement bundle",
    { privateMode: true }
  );
  const verifiedPrevious = verifyManagedBundle(previousRecord.value, { env, now });
  await ensureSecureDirectory(paths.directory);
  const recoveryPath = path.join(
    paths.directory,
    `.device-entitlement.${randomBytes(12).toString("hex")}.recovery`
  );
  try {
    await writePrivateFile(recoveryPath, previousRecord.bytes, { exclusive: true });
    const recoveryRecord = await readJsonRegularFile(
      recoveryPath,
      "Recovered Runrail entitlement bundle",
      { privateMode: true }
    );
    verifyManagedBundle(recoveryRecord.value, { env, now });
    if (await pathInfo(paths.activeBundlePath)) {
      await rm(recoveryPath, { force: true });
      return loadRunrailManagedEntitlementBundle({
        env,
        managedDirectory: paths.directory,
        now
      });
    }
    await replaceRegularFile(
      recoveryPath,
      paths.activeBundlePath,
      "Recovered Runrail entitlement bundle"
    );
  } finally {
    await rm(recoveryPath, { force: true }).catch(() => {});
  }
  return Object.freeze({
    paths,
    bundlePath: paths.activeBundlePath,
    recoveredFromPrevious: true,
    ...verifiedPrevious
  });
}

export async function writeRunrailManagedEntitlementBundle(bundle, {
  env = process.env,
  managedDirectory,
  now = new Date(),
  afterPromote
} = {}) {
  const paths = runrailManagedEntitlementPaths({ env, managedDirectory });
  await ensureSecureDirectory(paths.directory);
  verifyManagedBundle(bundle, { env, now });
  const current = await loadRunrailManagedEntitlementBundle({
    env,
    managedDirectory: paths.directory,
    now
  });
  const previousInfo = await pathInfo(paths.previousBundlePath);
  if (previousInfo) {
    await loadRunrailManagedEntitlementBundle({
      env,
      managedDirectory: paths.directory,
      now,
      usePrevious: true
    });
  }

  const token = randomBytes(12).toString("hex");
  const candidatePath = path.join(paths.directory, `.device-entitlement.${token}.candidate`);
  const previousCandidatePath = path.join(paths.directory, `.device-entitlement.${token}.previous`);
  const rollbackPath = path.join(paths.directory, `.device-entitlement.${token}.rollback`);
  const candidateBytes = Buffer.from(stableJson(bundle), "utf8");
  const currentBytes = current
    ? await readBoundedRegularFile(paths.activeBundlePath, "Runrail entitlement bundle", {
      privateMode: true
    })
    : null;

  try {
    await writePrivateFile(candidatePath, candidateBytes, { exclusive: true });
    const candidateRecord = await readJsonRegularFile(candidatePath, "Candidate Runrail entitlement bundle", {
      privateMode: true
    });
    verifyManagedBundle(candidateRecord.value, { env, now });

    if (currentBytes) {
      await writePrivateFile(previousCandidatePath, currentBytes, { exclusive: true });
      const previousRecord = await readJsonRegularFile(
        previousCandidatePath,
        "Candidate previous Runrail entitlement bundle",
        { privateMode: true }
      );
      verifyManagedBundle(previousRecord.value, { env, now });
      await replaceRegularFile(
        previousCandidatePath,
        paths.previousBundlePath,
        "Previous Runrail entitlement bundle"
      );
    }

    await replaceRegularFile(candidatePath, paths.activeBundlePath, "Runrail entitlement bundle");
    try {
      if (afterPromote) await afterPromote(paths.activeBundlePath);
      await loadRunrailManagedEntitlementBundle({
        env,
        managedDirectory: paths.directory,
        now
      });
    } catch (error) {
      if (currentBytes) {
        await writePrivateFile(rollbackPath, currentBytes, { exclusive: true });
        const rollbackRecord = await readJsonRegularFile(
          rollbackPath,
          "Rollback Runrail entitlement bundle",
          { privateMode: true }
        );
        verifyManagedBundle(rollbackRecord.value, { env, now });
        await replaceRegularFile(rollbackPath, paths.activeBundlePath, "Runrail entitlement bundle");
      } else {
        await rm(paths.activeBundlePath, { force: true });
      }
      throw entitlementError(
        "runrail-entitlement-bundle-rollback",
        "The replacement entitlement bundle failed verification and the prior verified bundle was restored."
      );
    }
  } finally {
    await Promise.all([
      rm(candidatePath, { force: true }).catch(() => {}),
      rm(previousCandidatePath, { force: true }).catch(() => {}),
      rm(rollbackPath, { force: true }).catch(() => {})
    ]);
  }
  return loadRunrailManagedEntitlementBundle({
    env,
    managedDirectory: paths.directory,
    now
  });
}

async function readBoundedJsonResponse(response, label) {
  const contentType = String(response.headers.get("content-type") || "").trim();
  if (!/^application\/json(?:\s*;\s*charset=utf-8)?$/i.test(contentType)) {
    throw entitlementError(
      "runrail-entitlement-response-content-type-invalid",
      `${label} must return application/json with optional UTF-8 charset.`
    );
  }
  const declaredLength = response.headers.get("content-length");
  if (
    declaredLength !== null &&
    (!/^\d+$/.test(declaredLength) || Number(declaredLength) > MAX_RESPONSE_BYTES)
  ) {
    throw entitlementError(
      "runrail-entitlement-response-oversized",
      `${label} exceeded the bounded response size.`
    );
  }
  const chunks = [];
  let total = 0;
  const reader = response.body?.getReader();
  if (reader) {
    while (true) {
      const { done, value } = await reader.read();
      if (done) break;
      total += value.byteLength;
      if (total > MAX_RESPONSE_BYTES) {
        await reader.cancel().catch(() => {});
        throw entitlementError(
          "runrail-entitlement-response-oversized",
          `${label} exceeded the bounded response size.`
        );
      }
      chunks.push(Buffer.from(value));
    }
  }
  const bytes = Buffer.concat(chunks, total);
  try {
    return JSON.parse(bytes.toString("utf8"));
  } catch {
    throw entitlementError(
      "runrail-entitlement-response-json-invalid",
      `${label} returned invalid JSON.`
    );
  }
}

async function postEntitlementJson(url, body, {
  fetchImpl = globalThis.fetch,
  timeoutMilliseconds = DEFAULT_FETCH_TIMEOUT_MILLISECONDS,
  label,
  rejectionCode
} = {}) {
  if (typeof fetchImpl !== "function") {
    throw entitlementError(
      "runrail-entitlement-fetch-unavailable",
      "This Node.js runtime does not provide fetch."
    );
  }
  if (
    !Number.isSafeInteger(timeoutMilliseconds) ||
    timeoutMilliseconds < 100 ||
    timeoutMilliseconds > 30_000
  ) {
    throw entitlementError(
      "runrail-entitlement-timeout-invalid",
      "The entitlement request timeout must be between 100 and 30000 milliseconds."
    );
  }
  const controller = new AbortController();
  const timeout = setTimeout(() => controller.abort(), timeoutMilliseconds);
  let response;
  try {
    response = await fetchImpl(url, {
      method: "POST",
      redirect: "error",
      cache: "no-store",
      referrerPolicy: "no-referrer",
      headers: {
        accept: "application/json",
        "content-type": "application/json"
      },
      body: JSON.stringify(body),
      signal: controller.signal
    });
  } catch (error) {
    if (controller.signal.aborted) {
      throw entitlementError(
        "runrail-entitlement-network-timeout",
        "The entitlement server request timed out."
      );
    }
    throw entitlementError(
      "runrail-entitlement-network-failed",
      "The entitlement server request failed without changing local entitlement state."
    );
  } finally {
    clearTimeout(timeout);
  }
  if (!response || typeof response.status !== "number" || response.status !== 200) {
    if (response?.body) {
      await readBoundedJsonResponse(response, label).catch(() => {});
    }
    throw entitlementError(
      rejectionCode,
      `The entitlement server rejected the ${label.toLowerCase()} request without changing local entitlement state.`
    );
  }
  return readBoundedJsonResponse(response, label);
}

function activationResponse(document, options) {
  exactObject(document, ["ok", "activation"], "Runrail entitlement server response");
  if (document.ok !== true) {
    throw entitlementError(
      "runrail-entitlement-response-invalid",
      "The entitlement server did not return a successful activation."
    );
  }
  return validateActivation(document.activation, options);
}

async function consumeTicketFile(ticketPath, expectedSha256) {
  const bytes = await readBoundedRegularFile(ticketPath, "Runrail device enrollment ticket", {
    maximumBytes: MAX_TICKET_FILE_BYTES
  });
  if (sha256(bytes) !== expectedSha256) {
    throw entitlementError(
      "runrail-enrollment-ticket-changed",
      "The enrollment ticket changed during completion and was not removed."
    );
  }
  await unlink(ticketPath);
}

async function consumePendingBundle(paths, expectedRequestSha256) {
  const consumedPath = path.join(
    paths.directory,
    `.device-enrollment-pending.${randomBytes(12).toString("hex")}.consumed`
  );
  await rename(paths.pendingBundlePath, consumedPath);
  try {
    const { value } = await readJsonRegularFile(
      consumedPath,
      "Consumed pending Runrail device enrollment",
      { privateMode: true }
    );
    const pending = verifyPendingBundle(value);
    if (sha256(stableJson(pending.pending.request)) !== expectedRequestSha256) {
      throw entitlementError(
        "runrail-enrollment-pending-changed",
        "The pending device key changed during enrollment completion."
      );
    }
    await unlink(consumedPath);
  } catch (error) {
    const currentInfo = await pathInfo(paths.pendingBundlePath);
    if (!currentInfo) await rename(consumedPath, paths.pendingBundlePath).catch(() => {});
    throw error;
  }
}

async function activateRunrailDeviceFromTicket({
  ticket,
  pending,
  paths,
  env = process.env,
  now = new Date(),
  fetchImpl = globalThis.fetch,
  timeoutMilliseconds = DEFAULT_FETCH_TIMEOUT_MILLISECONDS,
  cleanupTicket = null,
  cleanupPending = consumePendingBundle,
  handoffCodeConsumed = false
}) {
  const signature = signBytes(
    null,
    canonicalRunrailDeviceEnrollmentChallengeMessage({
      ticket,
      devicePublicKeyPem: pending.pending.request.devicePublicKeyPem,
      installationFingerprint: pending.pending.request.installationFingerprint
    }),
    pending.privateKey
  ).toString("base64url");
  const requestBody = {
    ticket,
    devicePublicKeyPem: pending.pending.request.devicePublicKeyPem,
    installationFingerprint: pending.pending.request.installationFingerprint,
    signature
  };
  const response = await postEntitlementJson(
    `${ticket.serverOrigin}/api/account/devices/enroll/complete`,
    requestBody,
    {
      fetchImpl,
      timeoutMilliseconds,
      label: "Runrail device enrollment",
      rejectionCode: "runrail-enrollment-server-rejected"
    }
  );
  const verified = activationResponse(response, {
    serverOrigin: ticket.serverOrigin,
    devicePublicKeySha256: pending.pending.request.devicePublicKeySha256,
    now
  });
  if (
    verified.lease.payload.planCode !== ticket.planCode ||
    verified.lease.payload.catalogRevision !== ticket.catalogRevision
  ) {
    throw entitlementError(
      "runrail-enrollment-activation-plan-mismatch",
      "The returned activation does not match the enrollment ticket plan."
    );
  }
  const bundle = {
    schemaVersion: 1,
    artifactType: "runrail-device-entitlement-managed-bundle",
    serverOrigin: ticket.serverOrigin,
    deviceId: verified.activation.deviceId,
    installationFingerprint: pending.pending.request.installationFingerprint,
    devicePublicKeySha256: pending.pending.request.devicePublicKeySha256,
    devicePublicKeyPem: pending.pending.request.devicePublicKeyPem,
    devicePrivateKeyPem: pending.pending.devicePrivateKeyPem,
    activation: verified.activation,
    authority: "subscription-entitlement-only",
    executionAuthorityGranted: false
  };
  await writeRunrailManagedEntitlementBundle(bundle, {
    env,
    managedDirectory: paths.directory,
    now
  });
  let ticketRemoved = cleanupTicket === null;
  let pendingKeyRemoved = false;
  const cleanupIncomplete = [];
  if (cleanupTicket) {
    try {
      await cleanupTicket();
      ticketRemoved = true;
    } catch {
      cleanupIncomplete.push("ticket");
    }
  }
  try {
    await cleanupPending(paths, sha256(stableJson(pending.pending.request)));
    pendingKeyRemoved = true;
  } catch {
    cleanupIncomplete.push("pending-key");
  }
  const status = await runrailLocalEntitlementStatus({
    env,
    managedDirectory: paths.directory,
    now
  });
  return Object.freeze({
    ...status,
    enrollmentCompleted: true,
    handoffCodeConsumed,
    ticketRemoved,
    pendingKeyRemoved,
    cleanupWarning: cleanupIncomplete.length
      ? Object.freeze({
        code: "runrail-enrollment-local-cleanup-incomplete",
        incomplete: Object.freeze([...cleanupIncomplete]),
        message:
          "Device activation succeeded, but one or more consumed local enrollment artifacts could not be removed."
      })
      : null,
    networkUsed: true
  });
}

async function enrollmentPreparation({ env, managedDirectory, now }) {
  const paths = runrailManagedEntitlementPaths({ env, managedDirectory });
  await ensureSecureDirectory(paths.directory);
  const existingActive = await loadRunrailManagedEntitlementBundle({
    env,
    managedDirectory: paths.directory,
    now
  });
  if (existingActive) {
    throw entitlementError(
      "runrail-enrollment-replacement-required",
      "A verified Runrail device is already enrolled. Enrollment cannot replace it implicitly."
    );
  }
  const pending = await readPendingBundle(paths);
  if (!pending) {
    throw entitlementError(
      "runrail-enrollment-request-required",
      "Create a local device enrollment request before completing browser enrollment."
    );
  }
  return { paths, pending };
}

function assertTicketMatchesPending(ticket, pending) {
  if (
    ticket.devicePublicKeySha256 !== pending.pending.request.devicePublicKeySha256 ||
    ticket.installationFingerprint !== pending.pending.request.installationFingerprint
  ) {
    throw entitlementError(
      "runrail-enrollment-ticket-device-mismatch",
      "The enrollment ticket is bound to a different pending device key or installation."
    );
  }
}

export async function enrollRunrailDeviceFromTicket({
  ticketPath,
  env = process.env,
  managedDirectory,
  now = new Date(),
  fetchImpl = globalThis.fetch,
  timeoutMilliseconds = DEFAULT_FETCH_TIMEOUT_MILLISECONDS,
  cleanupTicket = consumeTicketFile,
  cleanupPending = consumePendingBundle
} = {}) {
  if (!ticketPath || !path.isAbsolute(ticketPath)) {
    throw entitlementError(
      "runrail-enrollment-ticket-path-invalid",
      "Enrollment requires an absolute --ticket path."
    );
  }
  const { paths, pending } = await enrollmentPreparation({ env, managedDirectory, now });
  const ticketRecord = await readJsonRegularFile(
    ticketPath,
    "Runrail device enrollment ticket",
    { maximumBytes: MAX_TICKET_FILE_BYTES }
  );
  if (process.platform !== "win32") await chmod(ticketPath, PRIVATE_FILE_MODE);
  const ticket = validateRunrailDeviceEnrollmentTicket(ticketRecord.value, { env, now });
  assertTicketMatchesPending(ticket, pending);
  return activateRunrailDeviceFromTicket({
    ticket,
    pending,
    paths,
    env,
    now,
    fetchImpl,
    timeoutMilliseconds,
    cleanupTicket: () => cleanupTicket(ticketPath, sha256(ticketRecord.bytes)),
    cleanupPending
  });
}

export async function enrollRunrailDeviceFromHandoff({
  code,
  serverOrigin = RUNRAIL_ENTITLEMENT_PRODUCTION_ORIGIN,
  env = process.env,
  managedDirectory,
  now = new Date(),
  fetchImpl = globalThis.fetch,
  timeoutMilliseconds = DEFAULT_FETCH_TIMEOUT_MILLISECONDS,
  cleanupPending = consumePendingBundle
} = {}) {
  if (!/^[A-Za-z0-9_-]{43}$/.test(String(code || ""))) {
    throw entitlementError(
      "runrail-enrollment-handoff-code-invalid",
      "Native enrollment requires one bounded handoff code."
    );
  }
  const approvedOrigin = validateRunrailEntitlementServerOrigin(serverOrigin, { env });
  const { paths, pending } = await enrollmentPreparation({ env, managedDirectory, now });
  const exchange = await postEntitlementJson(
    `${approvedOrigin}/api/account/devices/enroll/exchange`,
    {
      code,
      devicePublicKeySha256: pending.pending.request.devicePublicKeySha256,
      installationFingerprint: pending.pending.request.installationFingerprint
    },
    {
      fetchImpl,
      timeoutMilliseconds,
      label: "Runrail native enrollment handoff",
      rejectionCode: "runrail-enrollment-handoff-rejected"
    }
  );
  exactObject(
    exchange,
    ["ok", "ticket", "authority", "executionAuthorityGranted"],
    "Runrail native enrollment handoff response"
  );
  if (
    exchange.ok !== true ||
    exchange.authority !== "none" ||
    exchange.executionAuthorityGranted !== false
  ) {
    throw entitlementError(
      "runrail-enrollment-handoff-response-invalid",
      "The native enrollment handoff response is invalid."
    );
  }
  const ticket = validateRunrailDeviceEnrollmentTicket(exchange.ticket, { env, now });
  if (ticket.serverOrigin !== approvedOrigin) {
    throw entitlementError(
      "runrail-enrollment-handoff-origin-invalid",
      "The native enrollment handoff returned a ticket for a different server."
    );
  }
  assertTicketMatchesPending(ticket, pending);
  return activateRunrailDeviceFromTicket({
    ticket,
    pending,
    paths,
    env,
    now,
    fetchImpl,
    timeoutMilliseconds,
    cleanupPending,
    handoffCodeConsumed: true
  });
}

export async function renewRunrailDeviceEntitlement({
  env = process.env,
  managedDirectory,
  now = new Date(),
  fetchImpl = globalThis.fetch,
  timeoutMilliseconds = DEFAULT_FETCH_TIMEOUT_MILLISECONDS
} = {}) {
  const current = await loadRunrailManagedEntitlementBundle({
    env,
    managedDirectory,
    now
  });
  if (!current) {
    throw entitlementError(
      "runrail-entitlement-required",
      "No managed Runrail device entitlement is enrolled."
    );
  }
  const nonce = randomBytes(32).toString("base64url");
  const unsignedRequest = {
    serverOrigin: current.bundle.serverOrigin,
    deviceId: current.bundle.deviceId,
    devicePublicKeySha256: current.bundle.devicePublicKeySha256,
    leaseSequence: current.lease.payload.leaseSequence,
    nonce
  };
  const signature = signBytes(
    null,
    canonicalRunrailDeviceEntitlementRenewalMessage(unsignedRequest),
    current.privateKey
  ).toString("base64url");
  const response = await postEntitlementJson(
    `${current.bundle.serverOrigin}/api/account/devices/renew`,
    {
      deviceId: unsignedRequest.deviceId,
      leaseSequence: unsignedRequest.leaseSequence,
      nonce,
      signature
    },
    {
      fetchImpl,
      timeoutMilliseconds,
      label: "Runrail device entitlement renewal",
      rejectionCode: "runrail-entitlement-renewal-rejected"
    }
  );
  const verified = activationResponse(response, {
    serverOrigin: current.bundle.serverOrigin,
    devicePublicKeySha256: current.bundle.devicePublicKeySha256,
    now
  });
  if (
    verified.activation.deviceId !== current.bundle.deviceId ||
    verified.lease.payload.leaseSequence !== current.lease.payload.leaseSequence + 1
  ) {
    throw entitlementError(
      "runrail-entitlement-renewal-sequence-invalid",
      "The renewal activation must advance the exact device lease sequence by one."
    );
  }
  const replacement = {
    ...current.bundle,
    activation: verified.activation
  };
  await writeRunrailManagedEntitlementBundle(replacement, {
    env,
    managedDirectory: current.paths.directory,
    now
  });
  const status = await runrailLocalEntitlementStatus({
    env,
    managedDirectory: current.paths.directory,
    now
  });
  return Object.freeze({
    ...status,
    renewed: true,
    networkUsed: true
  });
}

export async function signRunrailDeviceReviewPassport(
  passport,
  {
    env = process.env,
    managedDirectory,
    now = new Date()
  } = {}
) {
  verifyRunrailReviewPassport(passport);
  const access = await assertRunrailLocalFeatureAccess(
    "advanced-evidence-exports",
    {
      env,
      managedDirectory,
      now,
      opportunisticRenewal: false
    }
  );
  if (access.mode !== "managed-device-entitlement") {
    throw entitlementError(
      "runrail-device-signature-managed-entitlement-required",
      "Device-signed Change Passports require an enrolled managed Runrail device."
    );
  }
  const managed = await loadRunrailManagedEntitlementBundle({
    env,
    managedDirectory,
    now
  });
  if (!managed || !managed.lease.payload.features.includes("advanced-evidence-exports")) {
    throw entitlementError(
      "runrail-feature-not-entitled",
      "The active Runrail entitlement does not include device-signed Change Passports."
    );
  }
  const signature = signBytes(
    null,
    canonicalRunrailDeviceSignedPassportMessage(passport),
    managed.privateKey
  ).toString("base64url");
  return buildRunrailDeviceSignedReviewPassport({
    passport,
    devicePublicKeyPem: managed.bundle.devicePublicKeyPem,
    devicePublicKeySha256: managed.bundle.devicePublicKeySha256,
    signature
  });
}

async function legacyCompatibilityBuildMarker(env, trustedDistributionRoot) {
  const distributionRoot = String(env.RUNRAIL_DISTRIBUTION_ROOT || "").trim();
  if (
    !distributionRoot ||
    path.resolve(distributionRoot) !== path.resolve(trustedDistributionRoot)
  ) {
    return null;
  }
  let manifest;
  try {
    manifest = (
      await readJsonRegularFile(
        path.join(path.resolve(distributionRoot), "RUNRAIL_DISTRIBUTION.json"),
        "Runrail distribution manifest",
        { maximumBytes: 64 * 1024 }
      )
    ).value;
  } catch {
    return null;
  }
  if (
    manifest?.schemaVersion !== 1 ||
    manifest?.artifactType !== "runrail-local-distribution" ||
    manifest?.product !== "Runrail Local Audit Runner" ||
    !legacyCompatibleDistributionVersions.has(String(manifest?.version || "")) ||
    manifest?.signedPlanEntitlementAvailable !== true ||
    manifest?.signedPlanEntitlementEnforcementDefault !== false ||
    manifest?.signedPlanEntitlementAuthority !== "subscription-entitlement-only" ||
    !Array.isArray(manifest?.files) ||
    manifest.files.length === 0
  ) {
    return null;
  }
  return Object.freeze({
    version: manifest.version,
    source: "distribution-build-marker-v1"
  });
}

export async function runrailLocalEntitlementStatus({
  env = process.env,
  now = new Date(),
  managedDirectory,
  trustedDistributionRoot = moduleDistributionRoot
} = {}) {
  const managed = await loadRunrailManagedEntitlementBundle({
    env,
    managedDirectory,
    now
  });
  if (managed) {
    const payload = managed.lease.payload;
    return Object.freeze({
      ok: true,
      enforcementRequired: true,
      verified: true,
      mode: "managed-device-entitlement",
      status: managed.lease.status,
      usable: managed.lease.usable,
      readOnlyAvailable:
        managed.lease.status === "expired" &&
        payload.schemaVersion === RUNRAIL_DEVICE_ENTITLEMENT_LEASE_SCHEMA_VERSION &&
        payload.subscriptionStatus === "trialing",
      renewalNeeded: managed.lease.status !== "valid",
      planCode: payload.planCode,
      features: payload.features,
      subscriptionStatus:
        payload.schemaVersion === RUNRAIL_DEVICE_ENTITLEMENT_LEASE_SCHEMA_VERSION
          ? payload.subscriptionStatus
          : "active",
      trialStartedAt:
        payload.schemaVersion === RUNRAIL_DEVICE_ENTITLEMENT_LEASE_SCHEMA_VERSION
          ? payload.trialStartedAt
          : null,
      trialEndsAt:
        payload.schemaVersion === RUNRAIL_DEVICE_ENTITLEMENT_LEASE_SCHEMA_VERSION
          ? payload.trialEndsAt
          : null,
      maxDevices:
        payload.schemaVersion === RUNRAIL_DEVICE_ENTITLEMENT_LEASE_SCHEMA_VERSION
          ? payload.maxDevices
          : null,
      featureSet:
        payload.schemaVersion === RUNRAIL_DEVICE_ENTITLEMENT_LEASE_SCHEMA_VERSION
          ? payload.featureSet
          : payload.planCode,
      deviceId: payload.deviceId,
      leaseSequence: payload.leaseSequence,
      issuedAt: payload.issuedAt,
      renewAfter: payload.renewAfter,
      expiresAt: payload.expiresAt,
      graceUntil: payload.graceUntil,
      serverOrigin: managed.bundle.serverOrigin,
      startupRecoveryPerformed: managed.recoveredFromPrevious,
      authority: payload.authority,
      executionAuthorityGranted: false,
      networkUsed: false
    });
  }

  const legacyMarker = await legacyCompatibilityBuildMarker(env, trustedDistributionRoot);
  if (legacyMarker) {
    return Object.freeze({
      ok: true,
      enforcementRequired: false,
      verified: false,
      mode: "legacy-subscriber-package",
      status: "valid",
      usable: true,
      readOnlyAvailable: false,
      renewalNeeded: false,
      legacyCompatibilitySource: legacyMarker.source,
      distributionVersion: legacyMarker.version,
      planCode: "legacy",
      features: legacyFeatures,
      expiresAt: null,
      authority: "none",
      executionAuthorityGranted: false,
      networkUsed: false
    });
  }

  return Object.freeze({
    ok: true,
    enforcementRequired: true,
    verified: false,
    mode: "public-preview",
    status: "preview",
    usable: true,
    readOnlyAvailable: false,
    renewalNeeded: false,
    planCode: "preview",
    features: publicPreviewFeatures,
    subscriptionStatus: "none",
    trialStartedAt: null,
    trialEndsAt: null,
    maxDevices: 0,
    featureSet: "guided-sample-only",
    expiresAt: null,
    authority: "none",
    executionAuthorityGranted: false,
    networkUsed: false
  });
}

export async function assertRunrailLocalFeatureAccess(feature, options = {}) {
  const {
    opportunisticRenewal = false,
    fetchImpl,
    renewalTimeoutMilliseconds = OPPORTUNISTIC_RENEWAL_TIMEOUT_MILLISECONDS,
    ...statusOptions
  } = options;
  let status = await runrailLocalEntitlementStatus(statusOptions);
  if (!status.features.includes(feature)) {
    throw entitlementError(
      "runrail-feature-not-entitled",
      `The active Runrail ${status.planCode} entitlement does not include ${feature}.`
    );
  }
  if (
    opportunisticRenewal &&
    status.mode === "managed-device-entitlement" &&
    status.status !== "valid"
  ) {
    let renewedStatus;
    try {
      renewedStatus = await renewRunrailDeviceEntitlement({
        ...statusOptions,
        fetchImpl,
        timeoutMilliseconds: renewalTimeoutMilliseconds
      });
    } catch (error) {
      if (!status.usable) {
        throw entitlementError(
          "runrail-entitlement-expired",
          "Runrail could not renew the device entitlement after its signed offline grace window ended."
        );
      }
      return Object.freeze({
        ...status,
        opportunisticRenewalAttempted: true,
        opportunisticRenewalSucceeded: false,
        renewalWarning: Object.freeze({
          code: "runrail-entitlement-renewal-deferred",
          causeCode: String(error?.code || "runrail-entitlement-renewal-failed"),
          status: status.status,
          message:
            "Runrail could not refresh entitlement metadata, so this command is continuing under the existing signed lease window."
        })
      });
    }
    if (!renewedStatus.features.includes(feature)) {
      throw entitlementError(
        "runrail-feature-not-entitled",
        `The renewed Runrail ${renewedStatus.planCode} entitlement does not include ${feature}.`
      );
    }
    return Object.freeze({
      ...renewedStatus,
      opportunisticRenewalAttempted: true,
      opportunisticRenewalSucceeded: true
    });
  }
  if (!status.usable) {
    throw entitlementError(
      "runrail-entitlement-expired",
      "The Runrail device entitlement and bounded offline grace window have expired."
    );
  }
  return status;
}

export async function assertRunrailLocalDesktopAccess(options = {}) {
  const status = await runrailLocalEntitlementStatus(options);
  if (
    status.mode === "public-preview" &&
    status.features.includes("guided-sample")
  ) {
    return Object.freeze({
      ...status,
      readOnlyMode: false,
      previewMode: true,
      sampleOnlyMode: true,
      publicPreviewCandidateReview: status.features.includes(
        "public-preview-candidate-review"
      )
    });
  }
  if (status.usable) {
    if (!status.features.includes("candidate-branch-review")) {
      throw entitlementError(
        "runrail-feature-not-entitled",
        `The active Runrail ${status.planCode} entitlement does not include candidate-branch-review.`
      );
    }
    return Object.freeze({
      ...status,
      readOnlyMode: false,
      previewMode: false,
      sampleOnlyMode: false
    });
  }
  if (status.readOnlyAvailable) {
    return Object.freeze({
      ...status,
      readOnlyMode: true,
      previewMode: false,
      sampleOnlyMode: false
    });
  }
  throw entitlementError(
    "runrail-entitlement-expired",
    "The Runrail device entitlement has expired and does not permit Desktop access."
  );
}

export async function assertRunrailLocalHistoryAccess(options = {}) {
  const access = await assertRunrailLocalDesktopAccess(options);
  if (access.sampleOnlyMode) {
    throw entitlementError(
      "runrail-feature-not-entitled",
      "Local review history requires an active trial, an active subscription, or preserved read-only access from an expired verified trial."
    );
  }
  return access;
}

export function runrailLocalFeatureForArgs(args = []) {
  const values = Array.from(args, (value) => String(value));
  const requested = String(values[0] || "").trim().toLowerCase();
  const command = explicitCommands.has(requested) ? requested : "audit";
  if (command === "license" || command === "doctor") return null;
  if (command === "advise") return "deepseek-byok-advisory";
  if (command === "recommend") {
    const providerIndex = values.indexOf("--provider");
    return values[providerIndex + 1] === "deepseek"
      ? "deepseek-byok-advisory"
      : "deterministic-advisory";
  }
  if (command === "coverage" && values.includes("--previous")) {
    return "revision-comparison";
  }
  return commandFeatures.get(command) || "audit-export";
}
