{"version":3,"file":"utils-Dap_iIVV.cjs","names":["defineNiceError","StatusCodes","err","err","StatusCodes","err","StatusCodes","err","StatusCodes","err","StatusCodes","err","StatusCodes","v","v","v","v","v","v","isActionPayload_Request_JsonObject","base64","v","isActionPayload_Request_JsonObject","isActionPayload_Result_JsonObject","hex","base64urlnopad","v","createActionRootDomain","v","actionSchema","err","v","vEncryptedAesGcmPayload","base58","actionSchema","v","v","actionSchema","v","v","v","base64urlnopad","encryptJsonWithGeneratedKey","decryptJsonWithKeyString","base58","sha512","v","v","vRawNearAccessKeyEntry","vRawNearAccessKeyList","base32","v","v","v","v","defineRealm","t","base64","serializeEd25519Key_Jwk","serializeEd25519Key_Raw","serializeX25519Key_Jwk","serializeX25519Key_Raw","importEd25519Key","importX25519Key"],"sources":["../src/error/merr_meteor_connect.ts","../src/error/merr_bridge.ts","../src/error/merr_bridge_session.ts","../src/error/merr_connect_client.ts","../src/error/merr_new_key_account_transfer.ts","../src/error/merr_partner_client.ts","../src/error/merr_wallet_client.ts","../src/model/core/meteor_core.schema.ts","../src/model/core/wallet_protocol.schema.ts","../src/model/core/core_valibot_schemas.ts","../src/model/crypto/crypto.schema.ts","../src/model/durable_object/client/partner/partner_client.schema.ts","../src/model/durable_object/bridge/bridge.schema.ts","../src/utils/serialization/canonical_json.ts","../src/model/durable_object/bridge/session/session.schema.ts","../src/model/durable_object/bridge/bridge_lease_codec.ts","../src/model/durable_object/bridge/session/session_link.schema.ts","../src/nice_action/actions/act_root_meteor_connect.ts","../src/nice_action/actions/impl/act_impl_meteor_connect_demo.ts","../src/nice_action/actions/impl/act_impl_meteor_wallet_core.schemas.ts","../src/nice_action/actions/impl/act_impl_meteor_wallet_core.ts","../src/nice_action/actions/impl/act_impl_near.schemas.ts","../src/nice_action/actions/impl/act_impl_near.ts","../src/nice_action/action_policies.ts","../src/nice_action/actions/impl/account_transfer_import_receipt.ts","../src/nice_action/actions/impl/act_impl_meteor_wallet_core.utils.ts","../src/nice_action/actions/impl/new_key_account_transfer_proof.ts","../src/nice_action/actions/impl/new_key_account_transfer_proof_normalize.ts","../src/nice_action/actions/impl/new_key_account_transfer_state.ts","../src/nice_action/actions/impl/new_key_transfer_reconciliation.ts","../src/nice_action/actions/impl/new_key_transfer_add_key_journal.ts","../src/nice_action/actions/impl/new_key_transfer_add_key_runner.ts","../src/model/durable_object/bridge/session/session_link_confirmation.ts","../src/nice_realm/session_realm.ts","../src/utils/hashing/hashTextSha256ToBase64.ts","../src/utils/serialization/client_keys/ClientKeySerialization.ts"],"sourcesContent":["import { defineNiceError, err } from \"@meteorwallet/connect-core/error\";\nimport { StatusCodes } from \"http-status-codes\";\n\nexport enum EErr_MeteorConnect {\n  dur_obj_state_load_failed = \"dur_obj_state_load_failed\",\n  dur_obj_state_persist_failed = \"dur_obj_state_persist_failed\",\n  dur_obj_bad_state = \"dur_obj_bad_state\",\n}\n\nexport const merr_meteor_connect = defineNiceError({\n  domain: \"merr_meteor_connect\",\n  defaultHttpStatusCode: StatusCodes.INTERNAL_SERVER_ERROR,\n  schema: {\n    [EErr_MeteorConnect.dur_obj_state_load_failed]: err({\n      message: \"Failed to load durable object state\",\n    }),\n    [EErr_MeteorConnect.dur_obj_state_persist_failed]: err({\n      message: \"Failed to persist durable object state\",\n    }),\n    [EErr_MeteorConnect.dur_obj_bad_state]: err({\n      message: \"Durable object is in a bad state\",\n    }),\n  },\n} as const);\n","import { err } from \"@meteorwallet/connect-core/error\";\nimport { StatusCodes } from \"http-status-codes\";\nimport { merr_meteor_connect } from \"./merr_meteor_connect\";\n\nexport enum EErr_Bridge {\n  bridge_expired = \"bridge_expired\",\n  bridge_not_found = \"bridge_not_found\",\n  bridge_already_exists = \"bridge_already_exists\",\n  bridge_no_exchange_key_found = \"bridge_no_exchange_key_found\",\n  websocket_upgrade_failed = \"websocket_upgrade_failed\",\n  invalid_websocket_path = \"invalid_websocket_path\",\n  idempotency_conflict = \"idempotency_conflict\",\n  invalid_action_request = \"invalid_action_request\",\n  /** The creation proof's `issuedAt` is outside the freshness window (or the version is unknown). */\n  creation_proof_stale = \"creation_proof_stale\",\n  /** The creation proof signature does not verify against the presented partner verify key. */\n  creation_proof_invalid = \"creation_proof_invalid\",\n  /** Operator/circuit control is temporarily refusing NEW bridge allocation. */\n  allocation_halted = \"allocation_halted\",\n  /**\n   * Terminal, non-retryable (Phase 2c): this bridge is missing — expired, deleted, or never\n   * created. After whole-object deletion the server cannot distinguish those histories, so every\n   * post-lifetime request shares this one stable outcome. Clients must stop retrying, release the\n   * connection, and (if appropriate) create a NEW bridge request.\n   */\n  bridge_gone = \"bridge_gone\",\n}\n\nexport const merr_bridge = merr_meteor_connect.createChildDomain({\n  domain: \"bridge\",\n  schema: {\n    [EErr_Bridge.bridge_expired]: err({\n      message: \"Bridge has expired\",\n      httpStatusCode: StatusCodes.GATEWAY_TIMEOUT,\n    }),\n    [EErr_Bridge.bridge_not_found]: err({\n      message: \"Bridge not found\",\n      httpStatusCode: StatusCodes.NOT_FOUND,\n    }),\n    [EErr_Bridge.bridge_already_exists]: err({\n      message: \"A bridge for this partner_client already exists\",\n      httpStatusCode: StatusCodes.CONFLICT,\n    }),\n    [EErr_Bridge.bridge_no_exchange_key_found]: err({\n      message: \"No exchange key found for the bridge\",\n      httpStatusCode: StatusCodes.NOT_FOUND,\n    }),\n    [EErr_Bridge.invalid_websocket_path]: err({\n      message: \"Invalid WebSocket path\",\n      httpStatusCode: StatusCodes.BAD_REQUEST,\n    }),\n    [EErr_Bridge.websocket_upgrade_failed]: err({\n      message: \"WebSocket upgrade failed\",\n      httpStatusCode: StatusCodes.INTERNAL_SERVER_ERROR,\n    }),\n    [EErr_Bridge.idempotency_conflict]: err({\n      message: \"The bridge idempotency key was reused with different request data\",\n      httpStatusCode: StatusCodes.CONFLICT,\n    }),\n    [EErr_Bridge.invalid_action_request]: err({\n      message:\n        \"The bridge action request is invalid: oversized, or malformed for its action domain\",\n      httpStatusCode: StatusCodes.BAD_REQUEST,\n    }),\n    [EErr_Bridge.creation_proof_stale]: err({\n      message:\n        \"The bridge creation proof is outside the freshness window — re-sign the request with a current issuedAt\",\n      httpStatusCode: StatusCodes.BAD_REQUEST,\n    }),\n    [EErr_Bridge.creation_proof_invalid]: err({\n      message: \"The bridge creation proof signature is invalid for the presented partner identity\",\n      httpStatusCode: StatusCodes.UNAUTHORIZED,\n    }),\n    [EErr_Bridge.allocation_halted]: err({\n      message: \"New bridge allocation is temporarily halted; retry later\",\n      httpStatusCode: StatusCodes.SERVICE_UNAVAILABLE,\n    }),\n    [EErr_Bridge.bridge_gone]: err({\n      message:\n        \"This bridge no longer exists (expired, deleted, or never created). Do not retry — create a new bridge request\",\n      httpStatusCode: StatusCodes.GONE,\n    }),\n  },\n});\n","import { err } from \"@meteorwallet/connect-core/error\";\nimport { StatusCodes } from \"http-status-codes\";\nimport { merr_meteor_connect } from \"./merr_meteor_connect\";\n\n/**\n * Typed errors for `session_v1` sessions — the exact matrix in\n * `docs/multiple-actions-bridge-protocol.md` §7 (scope and retryability live there). Bounded,\n * payload-free text only: no hashes, bridge/turn IDs, signatures, ciphertext, or native exception\n * messages may enter these messages or retained telemetry (plan §8.3).\n */\nexport enum EErr_Bridge_Session {\n  session_unsupported = \"session_unsupported\",\n  session_disabled = \"session_disabled\",\n  pin_incorrect = \"pin_incorrect\",\n  partner_secret_hash_mismatch = \"partner_secret_hash_mismatch\",\n  wallet_update_required = \"wallet_update_required\",\n  turn_limit_reached = \"turn_limit_reached\",\n  sequence_mismatch = \"sequence_mismatch\",\n  phase_mismatch = \"phase_mismatch\",\n  state_revision_conflict = \"state_revision_conflict\",\n  turn_mismatch = \"turn_mismatch\",\n  turn_already_active = \"turn_already_active\",\n  result_not_ready = \"result_not_ready\",\n  ack_mismatch = \"ack_mismatch\",\n  conflicting_replay = \"conflicting_replay\",\n  request_hash_mismatch = \"request_hash_mismatch\",\n  recovery_contract_mismatch = \"recovery_contract_mismatch\",\n  action_ineligible = \"action_ineligible\",\n  resource_profile_not_permitted = \"resource_profile_not_permitted\",\n  external_work_not_permitted = \"external_work_not_permitted\",\n  external_work_hold_consumed = \"external_work_hold_consumed\",\n  external_work_journal_mismatch = \"external_work_journal_mismatch\",\n  session_closing = \"session_closing\",\n  close_not_permitted = \"close_not_permitted\",\n  wallet_capability_required = \"wallet_capability_required\",\n  session_authorization_insufficient = \"session_authorization_insufficient\",\n  trusted_link_revoked = \"trusted_link_revoked\",\n  request_too_large = \"request_too_large\",\n  result_too_large = \"result_too_large\",\n  stale_operation = \"stale_operation\",\n  idle_expired = \"idle_expired\",\n  absolute_expired = \"absolute_expired\",\n  projection_repair_pending = \"projection_repair_pending\",\n  valid_lease_rate_limited = \"valid_lease_rate_limited\",\n}\n\nexport const merr_bridge_session = merr_meteor_connect.createChildDomain({\n  domain: \"bridge_session\",\n  schema: {\n    [EErr_Bridge_Session.session_unsupported]: err({\n      message: \"The session protocol is not supported by this endpoint or wallet\",\n      httpStatusCode: StatusCodes.BAD_REQUEST,\n    }),\n    [EErr_Bridge_Session.session_disabled]: err({\n      message: \"Session admission is currently disabled\",\n      httpStatusCode: StatusCodes.SERVICE_UNAVAILABLE,\n    }),\n    [EErr_Bridge_Session.pin_incorrect]: err({\n      message: \"Incorrect PIN provided\",\n      httpStatusCode: StatusCodes.UNAUTHORIZED,\n    }),\n    [EErr_Bridge_Session.partner_secret_hash_mismatch]: err({\n      message: \"Provided partner secret hash does not match this session\",\n      httpStatusCode: StatusCodes.UNAUTHORIZED,\n    }),\n    [EErr_Bridge_Session.wallet_update_required]: err<{\n      requiredWalletProtocolVersion: number;\n      requiredWalletCapabilities: string[];\n    }>({\n      message: \"The wallet must be updated before it can execute this request\",\n      httpStatusCode: StatusCodes.UPGRADE_REQUIRED,\n      context: { required: true },\n    }),\n    [EErr_Bridge_Session.turn_limit_reached]: err({\n      message: \"This session has reached its maximum number of action turns\",\n      httpStatusCode: StatusCodes.CONFLICT,\n    }),\n    [EErr_Bridge_Session.sequence_mismatch]: err({\n      message: \"The operation's turn sequence does not match the session's current sequence\",\n      httpStatusCode: StatusCodes.CONFLICT,\n    }),\n    [EErr_Bridge_Session.phase_mismatch]: err({\n      message: \"The session is not in a phase that accepts this operation\",\n      httpStatusCode: StatusCodes.CONFLICT,\n    }),\n    [EErr_Bridge_Session.state_revision_conflict]: err({\n      message:\n        \"The session changed while this operation was being authorized; read current facts and retry if still applicable\",\n      httpStatusCode: StatusCodes.CONFLICT,\n    }),\n    [EErr_Bridge_Session.turn_mismatch]: err({\n      message: \"The operation does not reference the session's current turn\",\n      httpStatusCode: StatusCodes.CONFLICT,\n    }),\n    [EErr_Bridge_Session.turn_already_active]: err({\n      message: \"A turn is already in flight; acknowledge or advance it before submitting another\",\n      httpStatusCode: StatusCodes.CONFLICT,\n    }),\n    [EErr_Bridge_Session.result_not_ready]: err({\n      message: \"No wallet result is available for acknowledgement on the current turn\",\n      httpStatusCode: StatusCodes.CONFLICT,\n    }),\n    [EErr_Bridge_Session.ack_mismatch]: err({\n      message: \"The acknowledgement does not exactly match the retained result identity\",\n      httpStatusCode: StatusCodes.CONFLICT,\n    }),\n    [EErr_Bridge_Session.conflicting_replay]: err({\n      message: \"A turn or operation identity was reused with different request data\",\n      httpStatusCode: StatusCodes.CONFLICT,\n    }),\n    [EErr_Bridge_Session.request_hash_mismatch]: err({\n      // These two render directly to people (the SDK's transfer UI shows the message as its\n      // headline), and the realistic cause for a real user is a stale cached app after an\n      // upgrade — so the message itself must carry the remedy, not just the protocol fact.\n      message:\n        \"This app and the transfer service are running different versions of the transfer protocol (signed request hash mismatch). Refresh or update the app, then try again — nothing was changed.\",\n      httpStatusCode: StatusCodes.CONFLICT,\n    }),\n    [EErr_Bridge_Session.recovery_contract_mismatch]: err({\n      message:\n        \"This app and the transfer service are running different versions of the transfer protocol (recovery contract mismatch). Refresh or update the app, then try again — the request was stopped before anything happened.\",\n      httpStatusCode: StatusCodes.CONFLICT,\n    }),\n    [EErr_Bridge_Session.action_ineligible]: err({\n      message: \"This action has no implemented recovery contract and cannot ride a session\",\n      httpStatusCode: StatusCodes.BAD_REQUEST,\n    }),\n    [EErr_Bridge_Session.resource_profile_not_permitted]: err({\n      message: \"The selected resource profile is not permitted for this action\",\n      httpStatusCode: StatusCodes.BAD_REQUEST,\n    }),\n    [EErr_Bridge_Session.external_work_not_permitted]: err({\n      message: \"This session profile or action recovery contract does not permit external work\",\n      httpStatusCode: StatusCodes.FORBIDDEN,\n    }),\n    [EErr_Bridge_Session.external_work_hold_consumed]: err({\n      message: \"This session has already consumed its one external-work hold\",\n      httpStatusCode: StatusCodes.CONFLICT,\n    }),\n    [EErr_Bridge_Session.external_work_journal_mismatch]: err({\n      message: \"The host journal attestation does not match the retained result\",\n      httpStatusCode: StatusCodes.CONFLICT,\n    }),\n    [EErr_Bridge_Session.session_closing]: err({\n      message: \"The session is closing; no further turns are accepted\",\n      httpStatusCode: StatusCodes.CONFLICT,\n    }),\n    [EErr_Bridge_Session.close_not_permitted]: err({\n      message: \"This close operation is not permitted for the caller's role in the current phase\",\n      httpStatusCode: StatusCodes.FORBIDDEN,\n    }),\n    [EErr_Bridge_Session.wallet_capability_required]: err({\n      message: \"The claimed wallet does not advertise a capability this session or turn requires\",\n      httpStatusCode: StatusCodes.BAD_REQUEST,\n    }),\n    [EErr_Bridge_Session.session_authorization_insufficient]: err({\n      message: \"This action requires a stronger session authorization than the session holds\",\n      httpStatusCode: StatusCodes.FORBIDDEN,\n    }),\n    [EErr_Bridge_Session.trusted_link_revoked]: err({\n      message:\n        \"The trusted wallet-partner link was revoked or replaced; recover in a fresh session\",\n      httpStatusCode: StatusCodes.FORBIDDEN,\n    }),\n    [EErr_Bridge_Session.request_too_large]: err({\n      message: \"The action request exceeds the canonical size cap\",\n      httpStatusCode: StatusCodes.REQUEST_TOO_LONG,\n    }),\n    [EErr_Bridge_Session.result_too_large]: err({\n      message: \"The action result exceeds the canonical size cap\",\n      httpStatusCode: StatusCodes.REQUEST_TOO_LONG,\n    }),\n    [EErr_Bridge_Session.stale_operation]: err({\n      message:\n        \"The operation's issuedAt is outside the freshness window and no exact prior record exists — re-sign with a current issuedAt\",\n      httpStatusCode: StatusCodes.BAD_REQUEST,\n    }),\n    [EErr_Bridge_Session.idle_expired]: err({\n      message: \"The session's idle window elapsed; the bridge is being reclaimed\",\n      httpStatusCode: StatusCodes.GONE,\n    }),\n    [EErr_Bridge_Session.absolute_expired]: err({\n      message: \"The session's absolute lifetime elapsed; the bridge is being reclaimed\",\n      httpStatusCode: StatusCodes.GONE,\n    }),\n    [EErr_Bridge_Session.projection_repair_pending]: err({\n      message:\n        \"The operation committed but its view projection needs repair — retry the exact operation\",\n      httpStatusCode: StatusCodes.SERVICE_UNAVAILABLE,\n    }),\n    [EErr_Bridge_Session.valid_lease_rate_limited]: err({\n      message: \"This bridge has exceeded its valid-lease request budget; retry after the cooldown\",\n      httpStatusCode: StatusCodes.TOO_MANY_REQUESTS,\n    }),\n  },\n});\n","import { merr_meteor_connect } from \"./merr_meteor_connect\";\n\nexport enum EErr_ConnectClient {\n  runtime_unspecified = \"runtime_unspecified\",\n}\n\nexport const merr_connect_client = merr_meteor_connect.createChildDomain({\n  domain: \"connect_client\",\n  schema: {\n    [EErr_ConnectClient.runtime_unspecified]: {\n      message: \"Client runtime not specified for running actions or API requests\",\n    },\n  },\n});\n","import { err } from \"@meteorwallet/connect-core/error\";\nimport { StatusCodes } from \"http-status-codes\";\nimport { merr_meteor_connect } from \"./merr_meteor_connect\";\n\nexport enum EErr_NewKeyAccountTransfer {\n  wallet_declined = \"wallet_declined\",\n  client_transfer_id_conflict = \"client_transfer_id_conflict\",\n}\n\nexport const merr_new_key_account_transfer = merr_meteor_connect.createChildDomain({\n  domain: \"new_key_account_transfer\",\n  schema: {\n    [EErr_NewKeyAccountTransfer.wallet_declined]: err({\n      message: \"The wallet declined the account transfer request\",\n      httpStatusCode: StatusCodes.BAD_REQUEST,\n    }),\n    [EErr_NewKeyAccountTransfer.client_transfer_id_conflict]: err({\n      message: \"The client transfer id was already used with different account data\",\n      httpStatusCode: StatusCodes.CONFLICT,\n    }),\n  },\n});\n","import { err } from \"@meteorwallet/connect-core/error\";\nimport { StatusCodes } from \"http-status-codes\";\nimport { merr_meteor_connect } from \"./merr_meteor_connect\";\n\nexport enum EErr_PartnerClient {\n  partner_not_found = \"partner_not_found\",\n  partner_invalid_signature = \"partner_invalid_signature\",\n  partner_no_verify_key_found = \"partner_no_verify_key_found\",\n  partner_already_exists = \"partner_already_exists\",\n}\n\nexport const merr_partner_client = merr_meteor_connect.createChildDomain({\n  domain: \"merr_partner_client\",\n  schema: {\n    [EErr_PartnerClient.partner_already_exists]: err({\n      message: \"Partner already exists\",\n      httpStatusCode: StatusCodes.CONFLICT,\n    }),\n    [EErr_PartnerClient.partner_not_found]: err({\n      message: \"Partner not found\",\n      httpStatusCode: StatusCodes.NOT_FOUND,\n    }),\n    [EErr_PartnerClient.partner_invalid_signature]: err({\n      message: \"Invalid signature for partner_client\",\n      httpStatusCode: StatusCodes.UNAUTHORIZED,\n    }),\n    [EErr_PartnerClient.partner_no_verify_key_found]: err({\n      message: \"No verify public key found for partner_client\",\n      httpStatusCode: StatusCodes.NOT_FOUND,\n    }),\n  },\n});\n","import { err } from \"@meteorwallet/connect-core/error\";\nimport { StatusCodes } from \"http-status-codes\";\nimport { merr_meteor_connect } from \"./merr_meteor_connect\";\n\nexport enum EErr_WalletClient {\n  already_exists = \"already_exists\",\n  not_found = \"not_found\",\n  invalid_signature = \"invalid_signature\",\n  id_mismatch = \"id_mismatch\",\n  /** The registration proof's issuedAt is outside the freshness window (or unknown version). */\n  registration_proof_stale = \"registration_proof_stale\",\n  /** The wallet DO exists but is owned by a different verified identity/app tuple. */\n  owner_mismatch = \"owner_mismatch\",\n  /** Operator/circuit control is temporarily refusing NEW wallet allocation. */\n  allocation_halted = \"allocation_halted\",\n  link_capacity = \"link_capacity\",\n  /** An authenticated destructive request is outside its bounded freshness window. */\n  operation_stale = \"operation_stale\",\n  /** The same operationId was replayed with different signed contents. */\n  operation_conflict = \"operation_conflict\",\n  /** The bounded idempotency-result window is full. */\n  operation_capacity = \"operation_capacity\",\n  /** Local deletion has begun but raw storage cleanup has not yet been verified. */\n  deletion_pending = \"deletion_pending\",\n}\n\nexport const merr_wallet_client = merr_meteor_connect.createChildDomain({\n  domain: \"merr_wallet_client\",\n  schema: {\n    [EErr_WalletClient.already_exists]: err({\n      message: \"User wallet client already exists\",\n      httpStatusCode: StatusCodes.CONFLICT,\n    }),\n    [EErr_WalletClient.not_found]: err({\n      message: \"User wallet client not found\",\n      httpStatusCode: StatusCodes.NOT_FOUND,\n    }),\n    [EErr_WalletClient.invalid_signature]: err({\n      message: \"Invalid signature for wallet client\",\n      httpStatusCode: StatusCodes.UNAUTHORIZED,\n    }),\n    [EErr_WalletClient.id_mismatch]: err({\n      message: \"User wallet client ID mismatch\",\n      httpStatusCode: StatusCodes.BAD_REQUEST,\n    }),\n    [EErr_WalletClient.registration_proof_stale]: err({\n      message:\n        \"The wallet registration proof is outside the freshness window — re-sign with a current issuedAt\",\n      httpStatusCode: StatusCodes.BAD_REQUEST,\n    }),\n    [EErr_WalletClient.owner_mismatch]: err({\n      message: \"This wallet identity is already registered with different owner details\",\n      httpStatusCode: StatusCodes.CONFLICT,\n    }),\n    [EErr_WalletClient.allocation_halted]: err({\n      message: \"New wallet allocation is temporarily halted; retry later\",\n      httpStatusCode: StatusCodes.SERVICE_UNAVAILABLE,\n    }),\n    [EErr_WalletClient.link_capacity]: err({\n      message: \"This wallet has reached its maximum trusted-partner count\",\n      httpStatusCode: StatusCodes.CONFLICT,\n    }),\n    [EErr_WalletClient.operation_stale]: err({\n      message: \"The wallet operation is outside its freshness window\",\n      httpStatusCode: StatusCodes.BAD_REQUEST,\n    }),\n    [EErr_WalletClient.operation_conflict]: err({\n      message: \"This wallet operation ID was already used for different contents\",\n      httpStatusCode: StatusCodes.CONFLICT,\n    }),\n    [EErr_WalletClient.operation_capacity]: err({\n      message: \"Too many recent wallet operations; retry after the idempotency window\",\n      httpStatusCode: StatusCodes.TOO_MANY_REQUESTS,\n    }),\n    [EErr_WalletClient.deletion_pending]: err({\n      message: \"Wallet deletion is pending durable storage cleanup\",\n      httpStatusCode: StatusCodes.SERVICE_UNAVAILABLE,\n    }),\n  },\n});\n","import type {\n  TSerializedCryptoKeyData_Ed25519_Raw,\n  TTypeAndId,\n} from \"@meteorwallet/connect-core/util\";\nimport * as v from \"valibot\";\n\nexport enum EWalletPlatform {\n  web = \"web\",\n  mobile = \"mobile\",\n}\n\nexport enum ERuntimeEnvironment {\n  wallet = \"wallet\",\n  partner = \"partner\",\n  mc_backend = \"mc_backend\",\n  mc_bridge_session = \"mc_bridge_session\",\n  mc_admin = \"mc_admin\",\n  impl_near_connect = \"impl_near_connect\",\n}\n\nexport const vWalletPlatform = v.enum(EWalletPlatform);\n\nexport enum EMeteorAppId {\n  meteor_bridge_test_mobile = \"meteor_bridge_test_mobile\",\n  meteor_bridge_test_web = \"meteor_bridge_test_web\",\n  meteor_wallet_web = \"meteor_wallet_web\",\n  meteor_wallet_web_dev = \"meteor_wallet_web_dev\",\n  meteor_wallet_mobile = \"meteor_wallet_mobile\",\n  meteor_wallet_mobile_dev = \"meteor_wallet_mobile_dev\",\n}\n\nexport const META_METEOR_APP: {\n  [key in EMeteorAppId]: TWalletMetaData;\n} = {\n  meteor_bridge_test_mobile: {\n    appId: EMeteorAppId.meteor_bridge_test_mobile,\n    walletName: \"Meteor Bridge Test (Mobile)\",\n    walletDescription: \"Meteor Bridge testing mobile wallet\",\n    platform: EWalletPlatform.mobile,\n  },\n  meteor_bridge_test_web: {\n    appId: EMeteorAppId.meteor_bridge_test_web,\n    walletName: \"Meteor Bridge Test (Web)\",\n    walletDescription: \"Meteor Bridge testing web wallet\",\n    platform: EWalletPlatform.web,\n  },\n  meteor_wallet_web: {\n    appId: EMeteorAppId.meteor_wallet_web,\n    walletName: \"Meteor Wallet Web\",\n    walletDescription: \"The main Meteor Wallet web wallet\",\n    platform: EWalletPlatform.web,\n  },\n  meteor_wallet_web_dev: {\n    appId: EMeteorAppId.meteor_wallet_web_dev,\n    walletName: \"Meteor Wallet Web Dev\",\n    walletDescription: \"The development version of the Meteor Wallet web wallet\",\n    platform: EWalletPlatform.web,\n  },\n  meteor_wallet_mobile: {\n    appId: EMeteorAppId.meteor_wallet_mobile,\n    walletName: \"Meteor Wallet Mobile\",\n    walletDescription: \"The main Meteor Wallet mobile wallet\",\n    platform: EWalletPlatform.mobile,\n  },\n  meteor_wallet_mobile_dev: {\n    appId: EMeteorAppId.meteor_wallet_mobile_dev,\n    walletName: \"Meteor Wallet Mobile Dev\",\n    walletDescription: \"The development version of the Meteor Wallet mobile wallet\",\n    platform: EWalletPlatform.mobile,\n  },\n};\n\nexport const vMeteorAppId = v.enum(EMeteorAppId);\nexport const vMeteorAppIds = v.pipe(\n  v.array(vMeteorAppId),\n  v.maxLength(Object.keys(EMeteorAppId).length),\n  v.check((appIds) => new Set(appIds).size === appIds.length, \"Duplicate Meteor app id\"),\n);\n\n/** Canonical Cloudflare Durable Object id; validate before `idFromString()`/namespace lookup. */\nexport const vDurableObjectId = v.pipe(\n  v.string(),\n  v.length(64),\n  v.regex(/^[0-9a-f]{64}$/u, \"Invalid Durable Object id\"),\n);\n\n/** Random account/link/operation incarnation generated with `crypto.randomUUID()`. */\nexport const vIncarnationId = v.pipe(\n  v.string(),\n  v.uuid(),\n  v.regex(/^[0-9a-f-]{36}$/u, \"Incarnation id must use canonical lower-case UUID form\"),\n);\n\nexport const vWalletMetaData = v.object({\n  appId: vMeteorAppId,\n  walletName: v.string(),\n  walletDescription: v.string(),\n  platform: vWalletPlatform,\n});\n\nexport enum EPartnerOrigin {\n  web_url = \"web_url\",\n}\n\nexport type TWalletMetaData = v.InferInput<typeof vWalletMetaData>;\n\nexport enum EBridgeLinkType {\n  web_app_url = \"web_app_url\",\n  app_deep_link = \"app_deep_link\",\n}\n\nexport const vMeteorBridgeWalletLink = v.object({\n  linkString: v.string(),\n  linkType: v.enum(EBridgeLinkType),\n});\n\nexport type TMeteorBridgeWalletLink = v.InferInput<typeof vMeteorBridgeWalletLink>;\n\nexport const vMeteorBridgeWalletLinkWithMeta = v.intersect([\n  vWalletMetaData,\n  vMeteorBridgeWalletLink,\n]);\n\nexport type TMeteorBridgeWalletLinkWithMeta = v.InferInput<typeof vMeteorBridgeWalletLinkWithMeta>;\n\nexport const vClientSourceId_Wallet = v.pipe(\n  v.custom<`${ERuntimeEnvironment.wallet}:${string}`>((input) => {\n    return typeof input === \"string\" && input.startsWith(`${ERuntimeEnvironment.wallet}:`);\n  }, `Invalid app source ID format, expected '${ERuntimeEnvironment.wallet}:<id>'`),\n);\n\nexport const vClientSourceId_Partner = v.pipe(\n  v.custom<`${ERuntimeEnvironment.partner}:${string}`>((input) => {\n    return typeof input === \"string\" && input.startsWith(`${ERuntimeEnvironment.partner}:`);\n  }, `Invalid partner source ID format, expected '${ERuntimeEnvironment.partner}:<id>'`),\n);\n\nconst runtimeEnvironmentIds: ERuntimeEnvironment[] = Object.values(ERuntimeEnvironment);\n\nexport const vClientSourceId_Any = v.pipe(\n  v.custom<`${ERuntimeEnvironment}:${string}`>((input) => {\n    if (typeof input !== \"string\") {\n      return false;\n    }\n\n    for (const env in runtimeEnvironmentIds) {\n      if (input.startsWith(env)) return true;\n    }\n\n    return false;\n  }, `Invalid partner source ID format, expected '<runtime_environment>:<id>'`),\n);\n\nexport type TClientSourceId_Wallet = v.InferInput<typeof vClientSourceId_Wallet>;\nexport type TClientSourceId_Partner = v.InferInput<typeof vClientSourceId_Partner>;\nexport type TClientSourceId_Any = v.InferInput<typeof vClientSourceId_Any>;\n\n/**\n * The canonical `<runtime_environment>::<id>` client source id, used as the opaque key for a\n * {@link ClientCryptoKeyLink} linked client. Uses the shared `nice-code/util` `TTypeAndId` (`::`)\n * convention so the link's keys are typed without any local fork or casting.\n */\nexport const buildClientSourceId = (\n  runtimeEnvironment: ERuntimeEnvironment,\n  id: string,\n): TTypeAndId => {\n  return `${runtimeEnvironment}::${id}`;\n};\n\nexport interface IVerifiedClientState<S> {\n  isValid: true;\n  state: S;\n  /**\n   * The verify key the client REGISTERED with (the DO-authoritative identity, never\n   * caller-supplied). Returned here so one verified read answers everything a bridge transition\n   * needs — the separate `getVerifyPublicKey()` round trip is gone (Phase 8c RPC budget).\n   */\n  verifyPublicKey: TSerializedCryptoKeyData_Ed25519_Raw;\n}\n","import * as v from \"valibot\";\n\n/**\n * Protocol 3 requires wallet-owned first-link confirmation and action-scoped fresh PIN. Capabilities below describe only\n * genuinely optional action families; mandatory bridge behavior is versioned here instead of\n * being advertised piecemeal.\n */\nexport const METEOR_WALLET_PROTOCOL_VERSION = 3;\n\nexport enum EWalletProtocolCapability {\n  // Deliberately action/version-specific: supporting one wallet-core action must not imply\n  // support for future ones. These are app-advertised, not protocol-baseline requirements.\n  transfer_accounts_v1 = \"transfer_accounts_v1\",\n  // Covers the start + verify-active pair. Deliberately not implied by transfer_accounts_v1.\n  new_key_account_transfer_v1 = \"new_key_account_transfer_v1\",\n  // Test-harness only: production wallets must never advertise this capability. It isolates the\n  // harmless feature-independent multi-turn demo action from every real wallet action surface.\n  session_demo_review_v1 = \"session_demo_review_v1\",\n}\n\n/** Mandatory bridge behavior is represented by protocol version 3, not capability flags. */\nexport const REQUIRED_METEOR_WALLET_CAPABILITIES = [] as const;\n\nexport const vWalletProtocolVersion = v.pipe(v.number(), v.integer(), v.minValue(1));\nexport const vWalletProtocolCapability = v.enum(EWalletProtocolCapability);\nexport const vWalletProtocolCapabilities = v.pipe(\n  v.array(vWalletProtocolCapability),\n  v.maxLength(Object.keys(EWalletProtocolCapability).length),\n  v.check(\n    (capabilities) => new Set(capabilities).size === capabilities.length,\n    \"Duplicate capability\",\n  ),\n  // Capability sets are semantic sets. Normalize at every parse boundary so possession hashes and\n  // creation/idempotency bindings cannot vary merely because two callers supplied a different\n  // list order.\n  v.transform((capabilities) => [...capabilities].sort()),\n);\n\nexport const hasRequiredWalletCapabilities = (\n  walletProtocolVersion: number,\n  walletCapabilities: EWalletProtocolCapability[],\n  requiredWalletProtocolVersion: number,\n  requiredWalletCapabilities: EWalletProtocolCapability[],\n): boolean => {\n  return (\n    walletProtocolVersion >= requiredWalletProtocolVersion &&\n    requiredWalletCapabilities.every((capability) => walletCapabilities.includes(capability))\n  );\n};\n","import * as v from \"valibot\";\n\nconst BASE64_ALPHABET = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/\";\nconst STRICT_PADDED_BASE64 = /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/u;\n\n/** Decoded length for canonical padded Base64, or `undefined` for malformed/non-canonical input. */\nexport const canonicalBase64DecodedLength = (input: string): number | undefined => {\n  if (!STRICT_PADDED_BASE64.test(input)) return undefined;\n  const padding = input.endsWith(\"==\") ? 2 : input.endsWith(\"=\") ? 1 : 0;\n  // Canonical RFC 4648 encoding requires unused trailing bits to be zero. Regex-only validators\n  // accept alternate spellings of the same bytes, weakening signatures and dedupe keys.\n  if (padding === 2 && (BASE64_ALPHABET.indexOf(input.charAt(input.length - 3)) & 0x0f) !== 0) {\n    return undefined;\n  }\n  if (padding === 1 && (BASE64_ALPHABET.indexOf(input.charAt(input.length - 2)) & 0x03) !== 0) {\n    return undefined;\n  }\n  return (input.length / 4) * 3 - padding;\n};\n\nexport const createCanonicalBase64Schema = ({\n  minBytes = 0,\n  maxBytes,\n}: {\n  minBytes?: number;\n  maxBytes: number;\n}) =>\n  v.custom<string>((input) => {\n    if (typeof input !== \"string\") return false;\n    const decodedLength = canonicalBase64DecodedLength(input);\n    return decodedLength != null && decodedLength >= minBytes && decodedLength <= maxBytes;\n  }, `Expected canonical padded Base64 containing ${minBytes}–${maxBytes} decoded bytes`);\n\n/** General encrypted-envelope field: still bounded before any decoder allocates. */\nexport const vBase64 = createCanonicalBase64Schema({ maxBytes: 512 * 1024 });\nexport const vBase64HashSha256 = createCanonicalBase64Schema({ minBytes: 32, maxBytes: 32 });\nexport const vBase64SignatureEd25519 = createCanonicalBase64Schema({\n  minBytes: 64,\n  maxBytes: 64,\n});\n\nexport const vCreateSchema_TypePrefixedDataString = <P extends string>(\n  typeValues: P[],\n  typeKind: string,\n) => {\n  const _typeKind = typeKind ?? \"data_type\";\n\n  return v.pipe(\n    v.custom<`${P}::${string}`>(\n      (input) => {\n        return (\n          typeof input === \"string\" && typeValues.some((prefix) => input.startsWith(`${prefix}::`))\n        );\n      },\n      `Invalid format, expected '<${_typeKind}>::<value>' where \"${_typeKind}\" is one of [${typeValues.join(\", \")}] and \"value\" is a string of base64-encoded data of that type`,\n    ),\n  );\n};\n\nexport interface ICreateTypePrefixedDataStringResult<T extends string, F extends string> {\n  type: T;\n  format: F;\n  typeKind: string;\n  formatKind?: string;\n  transformJson?: boolean;\n  /** Exact decoded size for `raw_base64` key material. */\n  base64DecodedBytes?: number;\n}\n\nexport const vCreateSchema_TypeAndFormatPrefixedDataString = <T extends string, F extends string>({\n  type,\n  format,\n  typeKind,\n  formatKind,\n  base64DecodedBytes,\n  // transformJson = false,\n}: ICreateTypePrefixedDataStringResult<T, F>) => {\n  const _typeKind = typeKind ?? \"data_type\";\n  const _formatKind = formatKind ?? \"data_format\";\n\n  return v.pipe(\n    v.custom<`${T}::${F}::${string}`>((input) => {\n      if (typeof input !== \"string\") return false;\n\n      const parts = input.split(\"::\");\n      if (parts.length !== 3) return false;\n      const [typePart, formatPart, dataPart] = parts;\n\n      return (\n        typePart === type &&\n        formatPart === format &&\n        typeof dataPart === \"string\" &&\n        (base64DecodedBytes == null ||\n          canonicalBase64DecodedLength(dataPart) === base64DecodedBytes)\n      );\n    }, `Invalid format, expected '<${_typeKind}>::<${_formatKind}>::<value>' where \"${_typeKind}\" is \"${type}\", \"${_formatKind}\" is \"${format}\", and \"value\" is a string in the specified format`),\n  );\n};\n","import * as v from \"valibot\";\nimport {\n  createCanonicalBase64Schema,\n  vCreateSchema_TypeAndFormatPrefixedDataString,\n} from \"../core/core_valibot_schemas\";\n\nexport enum ECryptoKeyAlgo {\n  ed25519 = \"ed25519\",\n  x25519 = \"x25519\",\n}\n\nexport enum ECryptoKeyFormat {\n  raw_base64 = \"raw_base64\",\n  jwk = \"jwk\",\n}\n\nexport const vSerializedCryptoKeyDataEd25519_Raw = vCreateSchema_TypeAndFormatPrefixedDataString<\n  ECryptoKeyAlgo.ed25519,\n  ECryptoKeyFormat.raw_base64\n>({\n  format: ECryptoKeyFormat.raw_base64,\n  type: ECryptoKeyAlgo.ed25519,\n  typeKind: \"algo\",\n  base64DecodedBytes: 32,\n});\n\nexport const vSerializedCryptoKeyDataEd25519_Jwk = vCreateSchema_TypeAndFormatPrefixedDataString<\n  ECryptoKeyAlgo.ed25519,\n  ECryptoKeyFormat.jwk\n>({\n  format: ECryptoKeyFormat.jwk,\n  type: ECryptoKeyAlgo.ed25519,\n  typeKind: \"algo\",\n  transformJson: true,\n});\n\nexport type TSerializedCryptoKeyData_Ed25519_Raw = v.InferInput<\n  typeof vSerializedCryptoKeyDataEd25519_Raw\n>;\n\nexport type TSerializedCryptoKeyData_Ed25519_Raw_Transformed = {\n  formattedString: `${ECryptoKeyAlgo.ed25519}::${ECryptoKeyFormat.raw_base64}::${string}`;\n  type: ECryptoKeyAlgo.ed25519;\n  format: ECryptoKeyFormat.raw_base64;\n  data: string;\n};\n\nexport type TSerializedCryptoKeyData_Ed25519_Jwk = v.InferInput<\n  typeof vSerializedCryptoKeyDataEd25519_Jwk\n>;\n\nexport type TSerializedCryptoKeyData_Ed25519_Jwk_Transformed = {\n  formattedString: `${ECryptoKeyAlgo.ed25519}::${ECryptoKeyFormat.jwk}::${string}`;\n  type: ECryptoKeyAlgo.ed25519;\n  format: ECryptoKeyFormat.jwk;\n  data: JsonWebKey;\n};\n\nexport const vSerializedCryptoKeyDataX25519_Raw = vCreateSchema_TypeAndFormatPrefixedDataString<\n  ECryptoKeyAlgo.x25519,\n  ECryptoKeyFormat.raw_base64\n>({\n  format: ECryptoKeyFormat.raw_base64,\n  type: ECryptoKeyAlgo.x25519,\n  typeKind: \"algo\",\n  base64DecodedBytes: 32,\n});\n\nexport const vSerializedCryptoKeyDataX25519_Jwk = vCreateSchema_TypeAndFormatPrefixedDataString<\n  ECryptoKeyAlgo.x25519,\n  ECryptoKeyFormat.jwk\n>({\n  format: ECryptoKeyFormat.jwk,\n  type: ECryptoKeyAlgo.x25519,\n  typeKind: \"algo\",\n  transformJson: true,\n});\n\nexport const vCryptoKeyPairDataX25519 = v.object({\n  publicKey: vSerializedCryptoKeyDataX25519_Raw,\n  privateKey: vSerializedCryptoKeyDataX25519_Jwk,\n});\n\nexport type TSerializedCryptoKeyPairDataX25519 = v.InferInput<typeof vCryptoKeyPairDataX25519>;\n\nexport const vCryptoKeyPairDataEd25519 = v.object({\n  publicKey: vSerializedCryptoKeyDataEd25519_Raw,\n  privateKey: vSerializedCryptoKeyDataEd25519_Jwk,\n});\n\nexport type TSerializedCryptoKeyPairDataEd25519 = v.InferInput<typeof vCryptoKeyPairDataEd25519>;\n\nexport type TSerializedCryptoKeyData_X25519_Raw = v.InferInput<\n  typeof vSerializedCryptoKeyDataX25519_Raw\n>;\n\nexport type TSerializedCryptoKeyData_X25519_Raw_Transformed = {\n  formattedString: `${ECryptoKeyAlgo.x25519}::${ECryptoKeyFormat.raw_base64}::${string}`;\n  type: ECryptoKeyAlgo.x25519;\n  format: ECryptoKeyFormat.raw_base64;\n  data: string;\n};\n\nexport type TSerializedCryptoKeyData_X25519_Jwk = v.InferInput<\n  typeof vSerializedCryptoKeyDataX25519_Jwk\n>;\n\nexport type TSerializedCryptoKeyData_X25519_Jwk_Transformed = {\n  formattedString: `${ECryptoKeyAlgo.x25519}::${ECryptoKeyFormat.jwk}::${string}`;\n  type: ECryptoKeyAlgo.x25519;\n  format: ECryptoKeyFormat.jwk;\n  data: JsonWebKey;\n};\n\nexport const vEncryptedAesGcmPayload = v.object({\n  nonce: createCanonicalBase64Schema({ minBytes: 12, maxBytes: 12 }),\n  // AES-GCM always includes a 16-byte tag. The 512 KiB ceiling keeps every decoder allocation\n  // below the Worker's 1 MiB outer envelope while accommodating the 400 KB action lane.\n  ciphertext: createCanonicalBase64Schema({ minBytes: 16, maxBytes: 512 * 1024 }),\n});\n\nexport type TEncryptedAesGcmPayload = v.InferInput<typeof vEncryptedAesGcmPayload>;\nexport type TEncryptedAesGcmPayload_Transformed = v.InferOutput<typeof vEncryptedAesGcmPayload>;\n\ninterface ISerializedKeyData<T, P> {\n  transformed: T;\n  prefixed: P;\n}\n\nexport interface ISerializedKeyData_Ed25519_Raw\n  extends ISerializedKeyData<\n    TSerializedCryptoKeyData_Ed25519_Raw_Transformed,\n    TSerializedCryptoKeyData_Ed25519_Raw\n  > {}\n\nexport interface ISerializedKeyData_Ed25519_Jwk\n  extends ISerializedKeyData<\n    TSerializedCryptoKeyData_Ed25519_Jwk_Transformed,\n    TSerializedCryptoKeyData_Ed25519_Jwk\n  > {}\n\nexport interface ISerializedKeyData_X25519_Raw\n  extends ISerializedKeyData<\n    TSerializedCryptoKeyData_X25519_Raw_Transformed,\n    TSerializedCryptoKeyData_X25519_Raw\n  > {}\n\nexport interface ISerializedKeyData_X25519_Jwk\n  extends ISerializedKeyData<\n    TSerializedCryptoKeyData_X25519_Jwk_Transformed,\n    TSerializedCryptoKeyData_X25519_Jwk\n  > {}\n\nexport type TSerializedKeyData =\n  | ISerializedKeyData_Ed25519_Raw\n  | ISerializedKeyData_Ed25519_Jwk\n  | ISerializedKeyData_X25519_Raw\n  | ISerializedKeyData_X25519_Jwk;\n","import * as v from \"valibot\";\nimport { vCreateSchema_TypePrefixedDataString } from \"../../../core/core_valibot_schemas\";\nimport {\n  EPartnerOrigin,\n  vDurableObjectId,\n  vIncarnationId,\n  vMeteorAppId,\n} from \"../../../core/meteor_core.schema\";\nimport {\n  vWalletProtocolCapabilities,\n  vWalletProtocolVersion,\n} from \"../../../core/wallet_protocol.schema\";\nimport {\n  vSerializedCryptoKeyDataEd25519_Raw,\n  vSerializedCryptoKeyDataX25519_Raw,\n} from \"../../../crypto/crypto.schema\";\n\n/**\n * Rejects Unicode control and format characters — `\\p{Cc}` (C0/C1 controls, incl. newlines) and\n * `\\p{Cf}` (bidi overrides like U+202E, zero-width joiners, and friends).\n *\n * Load-bearing for `name`: the session push sender interpolates it into the FCM notification body,\n * which the OS renders on the lock screen — outside the app's own chrome, where none of the wallet's\n * framing applies. Unbounded free text there lets an already-paired partner display a rival wallet's\n * name, inject fake extra lines, or reverse the reading order of the notification.\n */\nconst NO_CONTROL_OR_FORMAT_CHARACTERS = /^[^\\p{Cc}\\p{Cf}]+$/u;\n\nexport const vPartnerMetadata = v.object({\n  // Bounded and sanitized because it reaches the OS notification shade (see the regex note above).\n  // 64 chars is generous for a display name and short enough that it cannot crowd out the rest of\n  // the notification text.\n  name: v.pipe(\n    v.string(),\n    v.trim(),\n    v.minLength(1),\n    v.maxLength(64),\n    v.regex(NO_CONTROL_OR_FORMAT_CHARACTERS),\n  ),\n  origin: v.pipe(\n    vCreateSchema_TypePrefixedDataString(Object.values(EPartnerOrigin), \"origin\"),\n    v.maxLength(2100),\n  ),\n  // Not rendered in any notification today, but same class of untrusted partner-authored text —\n  // bound it before something starts displaying it.\n  description: v.optional(\n    v.pipe(v.string(), v.trim(), v.maxLength(280), v.regex(NO_CONTROL_OR_FORMAT_CHARACTERS)),\n  ),\n  // `https://` only: an unconstrained URL string here could carry `javascript:` or `data:` into\n  // whatever surface eventually renders the partner's icon.\n  iconUrl: v.optional(v.pipe(v.string(), v.trim(), v.maxLength(2048), v.startsWith(\"https://\"))),\n});\n\nexport type TPartnerMetadata = v.InferInput<typeof vPartnerMetadata>;\n\n/**\n * One wallet the partner has paired with, stored on the PartnerClientDO. The partner never handles\n * `walletPerId` itself — it addresses a wallet only by its verify key (the E2E handle it already\n * holds); the DO resolves that handle to `walletPerId` internally when relaying a push. Holding the\n * wallet's exchange + verify keys here also lets a push be sealed for a wallet the partner is not\n * currently bridged to.\n */\nexport const vPartnerWalletClientLink = v.object({\n  walletPerId: vDurableObjectId,\n  accountIncarnation: vIncarnationId,\n  linkIncarnation: vIncarnationId,\n  walletVerifyPublicKey: vSerializedCryptoKeyDataEd25519_Raw,\n  walletExchangePublicKey: vSerializedCryptoKeyDataX25519_Raw,\n  meteorAppId: vMeteorAppId,\n  linkedAt: v.number(),\n  walletProtocolVersion: vWalletProtocolVersion,\n  walletCapabilities: vWalletProtocolCapabilities,\n});\n\nexport type TPartnerWalletClientLink = v.InferInput<typeof vPartnerWalletClientLink>;\n\nexport const vPartnerClientDO_State = v.object({\n  metadata: vPartnerMetadata,\n});\n\nexport type TPartnerClientDO_State = v.InferInput<typeof vPartnerClientDO_State>;\n\nexport const vRegisterPartnerConnection_Input = v.object({\n  partnerVerifyPublicKey: vSerializedCryptoKeyDataEd25519_Raw,\n  partnerMetadata: vPartnerMetadata,\n  walletPerId: vDurableObjectId,\n  accountIncarnation: vIncarnationId,\n  linkIncarnation: vIncarnationId,\n  walletVerifyPublicKey: vSerializedCryptoKeyDataEd25519_Raw,\n  walletExchangePublicKey: vSerializedCryptoKeyDataX25519_Raw,\n  meteorAppId: vMeteorAppId,\n  walletProtocolVersion: vWalletProtocolVersion,\n  walletCapabilities: vWalletProtocolCapabilities,\n});\n\nexport type TRegisterPartnerConnection_Input = v.InferInput<\n  typeof vRegisterPartnerConnection_Input\n>;\n\nexport const vWalletClientConnectionInfo = v.object({\n  meteorAppId: vMeteorAppId,\n  walletExchangePublicKey: vSerializedCryptoKeyDataX25519_Raw,\n  // Relayed to the partner so it can verify the wallet's end-to-end signatures. Authenticated by\n  // being bound into the HKDF info of the E2E key (bindVerifyKeysIntoDerivation on the crypto\n  // link) — tampering breaks decryption on both sides.\n  walletVerifyPublicKey: vSerializedCryptoKeyDataEd25519_Raw,\n  walletProtocolVersion: vWalletProtocolVersion,\n  walletCapabilities: vWalletProtocolCapabilities,\n});\n\nexport type TWalletClientConnectionInfo = v.InferInput<typeof vWalletClientConnectionInfo>;\n","import type { IActionPayload_Request_JsonObject } from \"@meteorwallet/connect-core/action\";\nimport { isActionPayload_Request_JsonObject } from \"@meteorwallet/connect-core/action\";\nimport * as v from \"valibot\";\nimport { vBase64HashSha256, vBase64SignatureEd25519 } from \"../../core/core_valibot_schemas\";\nimport { vDurableObjectId, vIncarnationId, vMeteorAppId } from \"../../core/meteor_core.schema\";\nimport {\n  vWalletProtocolCapabilities,\n  vWalletProtocolVersion,\n} from \"../../core/wallet_protocol.schema\";\nimport {\n  vEncryptedAesGcmPayload,\n  vSerializedCryptoKeyDataEd25519_Raw,\n  vSerializedCryptoKeyDataX25519_Raw,\n} from \"../../crypto/crypto.schema\";\nimport { vPartnerMetadata } from \"../client/partner/partner_client.schema\";\n\n/** Canonical Cloudflare Durable Object id, as a raw pattern for non-valibot call sites. */\nexport const CANONICAL_DURABLE_OBJECT_ID_PATTERN = /^[0-9a-f]{64}$/u;\n\nexport const isCanonicalDurableObjectId = (value: string): boolean =>\n  CANONICAL_DURABLE_OBJECT_ID_PATTERN.test(value);\n\n/**\n * Opaque backend-signed routing capability for a session Durable Object.\n *\n * The lower bound is the exact length of a `v2` lease (71 characters, see `bridge_lease_codec.ts`).\n * It used to be 80 — sized for the `v1` JSON layout — which would have rejected every `v2` lease on\n * the push and claim paths, one file away from where anyone changing the lease would be looking.\n */\nexport const BRIDGE_LEASE_MAX_LENGTH = 512;\nexport const vBridgeLease = v.pipe(\n  v.string(),\n  v.minLength(71),\n  v.maxLength(BRIDGE_LEASE_MAX_LENGTH),\n  v.regex(/^[A-Za-z0-9._-]+$/u, \"Invalid bridge lease encoding\"),\n);\nexport type TBridgeLease = v.InferInput<typeof vBridgeLease>;\n\n/** Persisted behavior discriminator for the session-only resource model. */\nexport const RESOURCE_BEHAVIOR_VERSION = \"resource-v2-session\" as const;\nexport const RESOURCE_COHORT_BUCKET_COUNT = 10_000;\nexport const vResourceBehaviorVersion = v.literal(RESOURCE_BEHAVIOR_VERSION);\nexport const vResourceCohort = v.pipe(\n  v.number(),\n  v.integer(),\n  v.minValue(0),\n  v.maxValue(RESOURCE_COHORT_BUCKET_COUNT - 1),\n);\n\nexport function resourceCohortForBridgeId(bridgeId: string): number {\n  let hash = 0x811c9dc5;\n  for (const byte of new TextEncoder().encode(`meteor-resource-cohort-v2-session:${bridgeId}`)) {\n    hash ^= byte;\n    hash = Math.imul(hash, 0x01000193);\n  }\n  return (hash >>> 0) % RESOURCE_COHORT_BUCKET_COUNT;\n}\n\n/** Partner identity and E2E material retained by a session. */\nexport const vSessionPartnerData = v.strictObject({\n  metadata: vPartnerMetadata,\n  verifyPublicKey: vSerializedCryptoKeyDataEd25519_Raw,\n  exchangePublicKey: vSerializedCryptoKeyDataX25519_Raw,\n  saltHash: vBase64HashSha256,\n});\nexport type TSessionPartnerData = v.InferOutput<typeof vSessionPartnerData>;\n\n/** Partner material supplied while allocating a session. */\nexport const vSessionCreatePartnerData = v.strictObject({\n  ...vSessionPartnerData.entries,\n  saltAndExchangePublicKeySignature: vBase64SignatureEd25519,\n});\nexport type TSessionCreatePartnerData = v.InferInput<typeof vSessionCreatePartnerData>;\nexport type TSessionCreatePartnerDataTransformed = v.InferOutput<typeof vSessionCreatePartnerData>;\n\nexport const vSessionCreationProof = v.strictObject({\n  version: v.pipe(v.number(), v.safeInteger(), v.minValue(1), v.maxValue(255)),\n  issuedAt: v.pipe(v.number(), v.safeInteger(), v.minValue(1), v.maxValue(4_102_444_800_000)),\n  signatureBase64: vBase64SignatureEd25519,\n});\nexport type TSessionCreationProofInput = v.InferInput<typeof vSessionCreationProof>;\n\nexport const vSessionWalletClaimOutputData = v.strictObject({\n  pinCodeEncrypted: v.optional(vEncryptedAesGcmPayload),\n  bridgeSaltEncrypted: vEncryptedAesGcmPayload,\n  partnerIdEncrypted: vEncryptedAesGcmPayload,\n  bridgeExchangePublicKey: vSerializedCryptoKeyDataX25519_Raw,\n  partner: v.omit(vSessionPartnerData, [\"saltHash\"]),\n});\nexport type TSessionWalletClaimOutputData = v.InferInput<typeof vSessionWalletClaimOutputData>;\n\nexport const vSessionWalletClaim = v.strictObject({\n  walletPerId: vDurableObjectId,\n  accountIncarnation: vIncarnationId,\n  linkIncarnation: v.optional(vIncarnationId),\n  appExchangePublicKey: vSerializedCryptoKeyDataX25519_Raw,\n  walletVerifyPublicKey: vSerializedCryptoKeyDataEd25519_Raw,\n  meteorAppId: vMeteorAppId,\n  connectedAt: v.number(),\n  pinCode: v.optional(v.string()),\n  pinCodeVerified: v.optional(v.boolean()),\n  linkProgress: v.optional(v.picklist([\"wallet_pending\", \"partner_pending\"])),\n  pinCodeAttempts: v.optional(v.number()),\n  pinCodeVerifiedAt: v.optional(v.number()),\n  lastPinCodeAttemptAt: v.optional(v.number()),\n  walletProtocolVersion: vWalletProtocolVersion,\n  walletCapabilities: vWalletProtocolCapabilities,\n  actionRequestEncryptedForWallet: v.optional(vEncryptedAesGcmPayload),\n  appClaimOutputData: v.custom<TSessionWalletClaimOutputData>(\n    (input) => input != null,\n    \"Session wallet claim output data is required\",\n  ),\n});\nexport type TSessionWalletClaim = v.InferInput<typeof vSessionWalletClaim>;\n\nexport enum ESessionNotifyWalletReason {\n  link_not_found = \"link_not_found\",\n  not_trusted = \"not_trusted\",\n  no_token = \"no_token\",\n  send_failed = \"send_failed\",\n  capability_missing = \"capability_missing\",\n  /**\n   * The backend deployment has wallet push delivery switched off (`WALLET_PUSH_DELIVERY`), so no\n   * push was attempted. Expected/informational: live-session delivery is unaffected and the\n   * session link/QR remains the way to (re)open the wallet.\n   */\n  push_disabled = \"push_disabled\",\n}\n\nexport const vActionPayloadJsonObject = v.custom<IActionPayload_Request_JsonObject>((value) =>\n  isActionPayload_Request_JsonObject(value),\n);\n","import { sha256 } from \"@noble/hashes/sha2.js\";\nimport { bytesToHex } from \"@noble/hashes/utils.js\";\nimport { base64 } from \"@scure/base\";\n\n/**\n * Signing-grade canonical JSON and the hashes/challenges built on it.\n *\n * These bytes are a frozen protocol contract: creation proofs, idempotency bindings, deterministic\n * names and every signed challenge hash them, and already-shipped clients compute the same bytes.\n * `canonicalJsonFrozenVectors.test.ts` pins them; never change an accepted output.\n *\n * Rules (not RFC 8785):\n * - `null`, booleans, strings and finite numbers use native `JSON.stringify` spelling (`-0` → `0`).\n * - Objects emit their own enumerable string keys, sorted by UTF-16 code unit (`Array#sort`),\n *   skipping entries whose value is `undefined`. `toJSON` is never called.\n * - Arrays keep order; a sparse hole emits `null`, an explicit `undefined` element throws.\n * - Non-finite numbers, bigint, function, symbol, top-level `undefined` and cycles throw.\n *   Repeated non-cyclic references are fine.\n */\n\n/** A strict JSON value: the input type for anything that gets signed. */\nexport type TCanonicalJsonValue =\n  | null\n  | boolean\n  | number\n  | string\n  | readonly TCanonicalJsonValue[]\n  | { readonly [key: string]: TCanonicalJsonValue };\n\nexport function stringifyCanonicalJson(value: unknown): string {\n  return serialize(value, \"$\", new Set<object>());\n}\n\nfunction serialize(value: unknown, path: string, stack: Set<object>): string {\n  if (value === null) return \"null\";\n  const kind = typeof value;\n  if (kind === \"string\") return JSON.stringify(value);\n  if (kind === \"boolean\") return value ? \"true\" : \"false\";\n  if (kind === \"number\") {\n    if (!Number.isFinite(value)) throw new Error(`canonical JSON: non-finite number at ${path}`);\n    return JSON.stringify(value);\n  }\n  if (kind !== \"object\") throw new Error(`canonical JSON: unsupported ${kind} at ${path}`);\n\n  const node = value as object;\n  if (stack.has(node)) throw new Error(`canonical JSON: circular reference at ${path}`);\n  stack.add(node);\n  try {\n    if (Array.isArray(node)) {\n      const items: string[] = [];\n      for (let index = 0; index < node.length; index++) {\n        items.push(index in node ? serialize(node[index], `${path}[${index}]`, stack) : \"null\");\n      }\n      return `[${items.join(\",\")}]`;\n    }\n    const record = node as Record<string, unknown>;\n    const members: string[] = [];\n    for (const key of Object.keys(record).sort()) {\n      const member = record[key];\n      if (member === undefined) continue;\n      members.push(`${JSON.stringify(key)}:${serialize(member, `${path}.${key}`, stack)}`);\n    }\n    return `{${members.join(\",\")}}`;\n  } finally {\n    stack.delete(node);\n  }\n}\n\nconst sha256Of = (input: string | Uint8Array): Uint8Array =>\n  sha256(typeof input === \"string\" ? new TextEncoder().encode(input) : input);\n\n/** SHA-256 of a UTF-8 string or raw bytes, lowercase hex. */\nexport const sha256Hex = (input: string | Uint8Array): string => bytesToHex(sha256Of(input));\n\n/** SHA-256 of a UTF-8 string or raw bytes, standard padded base64. */\nexport const sha256Base64 = (input: string | Uint8Array): string => base64.encode(sha256Of(input));\n\nexport const hashCanonicalJsonSha256Hex = (value: unknown): string =>\n  sha256Hex(stringifyCanonicalJson(value));\n\nexport const hashCanonicalJsonSha256Base64 = (value: unknown): string =>\n  sha256Base64(stringifyCanonicalJson(value));\n\n/** Standard (RFC 4648 §4, padded) base64; works in browsers, Workers, Node and Hermes. */\nexport const bytesToBase64 = (bytes: Uint8Array): string => base64.encode(bytes);\n\nexport const base64ToBytes = (encoded: string): Uint8Array => base64.decode(encoded);\n\n/**\n * A signing challenge: a domain tag + version namespace the signature, and the fields are encoded\n * as canonical JSON so boundaries and key order are unambiguous.\n */\nexport interface ICanonicalChallenge {\n  readonly domainTag: string;\n  readonly version: number;\n  readonly fields: Readonly<Record<string, TCanonicalJsonValue>>;\n}\n\n/**\n * The exact string a {@link ICanonicalChallenge} signs:\n * `stringifyCanonicalJson({ domainTag, version, fields })`. Stricter than the serializer: any\n * value that is not a strict {@link TCanonicalJsonValue} (undefined entries, sparse arrays,\n * non-plain objects, non-finite numbers) is rejected instead of normalised.\n */\nexport function buildCanonicalChallenge(challenge: ICanonicalChallenge): string {\n  const { domainTag, version, fields } = challenge;\n  if (typeof domainTag !== \"string\" || domainTag === \"\") {\n    throw new Error(\"canonical challenge: domainTag must be a non-empty string\");\n  }\n  if (typeof version !== \"number\" || !Number.isSafeInteger(version) || version < 1) {\n    throw new Error(\"canonical challenge: version must be a positive safe integer\");\n  }\n  if (!isPlainObject(fields)) throw new Error(\"canonical challenge: fields must be a plain object\");\n  for (const key of Object.keys(fields)) requireStrictJson(fields[key], `fields.${key}`);\n  return stringifyCanonicalJson({ domainTag, version, fields });\n}\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n  if (value === null || typeof value !== \"object\") return false;\n  const prototype = Object.getPrototypeOf(value);\n  return prototype === null || prototype === Object.prototype;\n}\n\nfunction requireStrictJson(value: unknown, path: string): void {\n  if (value === null || typeof value === \"string\" || typeof value === \"boolean\") return;\n  if (typeof value === \"number\") {\n    if (Number.isFinite(value)) return;\n    throw new Error(`canonical challenge: non-finite number at ${path}`);\n  }\n  if (Array.isArray(value)) {\n    for (let index = 0; index < value.length; index++) {\n      if (!(index in value))\n        throw new Error(`canonical challenge: sparse hole at ${path}[${index}]`);\n      requireStrictJson(value[index], `${path}[${index}]`);\n    }\n    return;\n  }\n  if (isPlainObject(value)) {\n    for (const key of Object.keys(value)) {\n      if (value[key] === undefined) {\n        throw new Error(`canonical challenge: undefined entry at ${path}.${key}`);\n      }\n      requireStrictJson(value[key], `${path}.${key}`);\n    }\n    return;\n  }\n  throw new Error(`canonical challenge: unsupported value at ${path} (strict JSON only)`);\n}\n","import type {\n  IActionPayload_Request_JsonObject,\n  IActionPayload_Result_JsonObject,\n} from \"@meteorwallet/connect-core/action\";\nimport {\n  isActionPayload_Request_JsonObject,\n  isActionPayload_Result_JsonObject,\n} from \"@meteorwallet/connect-core/action\";\nimport * as v from \"valibot\";\nimport { hashCanonicalJsonSha256Base64 } from \"../../../../utils/serialization/canonical_json\";\nimport { vBase64HashSha256 } from \"../../../core/core_valibot_schemas\";\nimport { vDurableObjectId } from \"../../../core/meteor_core.schema\";\nimport type { EWalletProtocolCapability } from \"../../../core/wallet_protocol.schema\";\n\n/**\n * Shared contracts for the session-only bridge protocol.\n *\n * Every schema at a durable or client boundary is `v.strictObject` (D20/§8.1): unknown persisted or\n * wire fields fail closed instead of being silently stripped or carried.\n */\n\nexport enum EBridgeInteractionMode {\n  /** One claimed bridge carrying a bounded sequence of action turns. */\n  session_v1 = \"session_v1\",\n}\n\nexport const vBridgeInteractionMode = v.enum(EBridgeInteractionMode);\n\nexport enum ESessionPhase {\n  /** Private allocation: initial action validated but not yet bridge-bound/staged; unclaimable. */\n  initializing = \"initializing\",\n  waiting_for_wallet = \"waiting_for_wallet\",\n  wallet_verification = \"wallet_verification\",\n  wallet_confirmation = \"wallet_confirmation\",\n  wallet_action = \"wallet_action\",\n  result_ready = \"result_ready\",\n  ready = \"ready\",\n  external_work = \"external_work\",\n  closed = \"closed\",\n  failed = \"failed\",\n}\n\nexport const vSessionPhase = v.enum(ESessionPhase);\n\n/** The partner's claim-time authorization policy, bound by the creation proof. */\nexport enum ESessionAuthorizationMode {\n  /** First contact requires wallet consent; an exact live link skips repeated consent. */\n  partner_link = \"partner_link\",\n  /** Always run a new PIN ceremony, even when this wallet/partner pair is already trusted. */\n  fresh_pin = \"fresh_pin\",\n}\n\nexport const vSessionAuthorizationMode = v.enum(ESessionAuthorizationMode);\n\n/**\n * Authorization is selected once at claim and never stepped up in-session (amended D4). A fresh\n * PIN is stronger than a trusted link; a trusted-link session therefore rejects any later turn\n * whose server-owned action policy requires `fresh_pin`.\n */\nexport enum ESessionAuthorizationLevel {\n  trusted_link = \"trusted_link\",\n  fresh_pin = \"fresh_pin\",\n}\n\nexport const vSessionAuthorizationLevel = v.enum(ESessionAuthorizationLevel);\n\n/** Immutable server-approved authority/resource envelopes (D35). */\nexport enum ESessionResourceProfile {\n  single_turn_v1 = \"single_turn_v1\",\n  interactive_v1 = \"interactive_v1\",\n  external_work_v1 = \"external_work_v1\",\n}\n\nexport const vSessionResourceProfile = v.enum(ESessionResourceProfile);\n\n// ---------------------------------------------------------------------------\n// Frozen V1 operational constants (Phase 0 decision record; protocol doc §1).\n// Per D10 these may be REDUCED by qualification evidence without a protocol-version review;\n// increasing any of them requires one.\n// ---------------------------------------------------------------------------\n\nexport const SESSION_MAX_TURNS = 8;\n\n/** Idle/progress window: extended only by successful state-changing transitions (plan §7.2). */\nexport const SESSION_IDLE_WINDOW_MILLIS = 300_000;\n\n/** Non-renewable absolute session lifetime; embedded in the routing lease (D11/D18). */\nexport const SESSION_MAX_ABSOLUTE_LIFETIME_MILLIS = 1_800_000;\n\n/** Largest immutable reconnect budget exposed by any V1 resource profile. */\nexport const SESSION_MAX_REDIAL_ATTEMPTS = 64;\n\nexport interface ISessionResourceProfilePolicy {\n  maxTurns: number;\n  idleWindowMillis: number;\n  absoluteLifetimeMillis: number;\n  maxRedialAttempts: number;\n  externalWorkHoldAllowed: boolean;\n}\n\n/**\n * Frozen D35 profile limits. Increasing any value is a protocol/authority review; deployment\n * bindings independently cap the idle and absolute dimensions.\n */\nexport const SESSION_RESOURCE_PROFILE_POLICIES = {\n  [ESessionResourceProfile.single_turn_v1]: {\n    maxTurns: 1,\n    idleWindowMillis: 300_000,\n    absoluteLifetimeMillis: 300_000,\n    maxRedialAttempts: 24,\n    externalWorkHoldAllowed: false,\n  },\n  [ESessionResourceProfile.interactive_v1]: {\n    maxTurns: 8,\n    idleWindowMillis: 300_000,\n    absoluteLifetimeMillis: 600_000,\n    maxRedialAttempts: 32,\n    externalWorkHoldAllowed: false,\n  },\n  [ESessionResourceProfile.external_work_v1]: {\n    maxTurns: 8,\n    idleWindowMillis: 300_000,\n    absoluteLifetimeMillis: 1_800_000,\n    maxRedialAttempts: 64,\n    externalWorkHoldAllowed: true,\n  },\n} as const satisfies Record<ESessionResourceProfile, ISessionResourceProfilePolicy>;\n\nexport const getSessionResourceProfilePolicy = (\n  profile: ESessionResourceProfile,\n): ISessionResourceProfilePolicy => SESSION_RESOURCE_PROFILE_POLICIES[profile];\n\n/** Canonical-JSON cap for a wallet action result — the result-side sibling of the request cap. */\nexport const MAX_SESSION_RESULT_CANONICAL_JSON_LENGTH = 400_000;\n\n/**\n * Serialized operation frames above this must use the authenticated HTTP bridge lane; the inbound\n * WebSocket frame cap is 131,072 bytes and the margin covers envelope/framing overhead.\n */\nexport const MAX_SESSION_WS_OPERATION_BYTES = 100_000;\n\n/** Signature freshness for a NEW operation's `issuedAt` (mirrors the creation-proof policy). */\nexport const SESSION_OPERATION_MAX_AGE_MILLIS = 120_000;\nexport const SESSION_OPERATION_MAX_FUTURE_SKEW_MILLIS = 30_000;\n\n// ---------------------------------------------------------------------------\n// Bounded identity/ordering primitives\n// ---------------------------------------------------------------------------\n\nexport const vSessionTurnSequence = v.pipe(\n  v.number(),\n  v.safeInteger(),\n  v.minValue(1),\n  v.maxValue(SESSION_MAX_TURNS),\n);\n\n/**\n * Unpredictable opaque identifiers (turn/operation/notification): bounded, non-empty, URL-safe.\n * UUIDs satisfy this; the schema deliberately does not require UUID shape so clients may use any\n * equivalently unpredictable generator.\n */\nconst vBoundedOpaqueId = v.pipe(\n  v.string(),\n  v.minLength(16),\n  v.maxLength(64),\n  v.regex(/^[A-Za-z0-9_-]+$/u, \"Invalid opaque identifier encoding\"),\n);\n\nexport const vSessionTurnId = vBoundedOpaqueId;\nexport const vSessionOperationId = vBoundedOpaqueId;\nexport const vSessionNotificationId = vBoundedOpaqueId;\n\nexport const vSessionIssuedAt = v.pipe(v.number(), v.safeInteger(), v.minValue(1));\n\n/**\n * Bounded monotonic commit counter for the session record (§9.1). Not an analytics dimension and\n * never caller-controlled; projected to the realm as a synchronization fence.\n */\nexport const vSessionStateRevision = v.pipe(v.number(), v.safeInteger(), v.minValue(0));\n\nexport const vSessionRequestPayload = v.custom<IActionPayload_Request_JsonObject>(\n  isActionPayload_Request_JsonObject,\n);\n\nexport const vSessionResultPayload = v.custom<IActionPayload_Result_JsonObject>(\n  isActionPayload_Result_JsonObject,\n);\n\n// ---------------------------------------------------------------------------\n// Turn envelopes (§5.4/§5.5; challenge construction in session_challenges.ts)\n// ---------------------------------------------------------------------------\n\nexport const SESSION_ENVELOPE_FORMAT_VERSION = 1;\n\n/**\n * Purpose tag prepended to the plaintext before the DO encrypts a sensitive turn's complete signed\n * envelope to the claiming wallet (the multi sibling of `ACTION_REQUEST_ENVELOPE_PURPOSE_TAG` —\n * same derived AES key family, so the tag pins which ciphertext this is). The tagged plaintext is\n * `JSON.stringify({ envelope, partnerTurnSignatureBase64 })`.\n */\nexport const SESSION_TURN_ENVELOPE_PURPOSE_TAG = \"session_turn::\";\n\n/**\n * The partner-authored request envelope for one turn. `requestHash` is the canonical hash of the\n * backend-validated request (normalization-stability contract, §5.4), computed with\n * `nice-code/util`'s serializer — never the unsupported one (§8.4). `priorResultHash` binds the\n * acknowledged previous result for sequence ≥ 2 and is explicitly `null` at sequence 1 (D6).\n */\nexport const vSessionRequestEnvelopeV1 = v.strictObject({\n  formatVersion: v.literal(SESSION_ENVELOPE_FORMAT_VERSION),\n  bridgeId: vDurableObjectId,\n  interactionMode: v.literal(EBridgeInteractionMode.session_v1),\n  sequence: vSessionTurnSequence,\n  turnId: vSessionTurnId,\n  operationId: vSessionOperationId,\n  issuedAt: vSessionIssuedAt,\n  recoveryContractHash: vBase64HashSha256,\n  requestHash: vBase64HashSha256,\n  priorResultHash: v.nullable(vBase64HashSha256),\n  actionRequest: vSessionRequestPayload,\n});\n\nexport type TSessionRequestEnvelopeV1 = v.InferOutput<typeof vSessionRequestEnvelopeV1>;\n\n/**\n * The wallet-authored result envelope for one turn: signed as plaintext with the fixed wallet\n * identity, then encrypted for the fixed partner link (§5.5). The bridge never sees this plaintext.\n */\nexport const vSessionResultEnvelopeV1 = v.strictObject({\n  formatVersion: v.literal(SESSION_ENVELOPE_FORMAT_VERSION),\n  bridgeId: vDurableObjectId,\n  interactionMode: v.literal(EBridgeInteractionMode.session_v1),\n  sequence: vSessionTurnSequence,\n  turnId: vSessionTurnId,\n  requestHash: vBase64HashSha256,\n  resultHash: vBase64HashSha256,\n  actionResult: vSessionResultPayload,\n});\n\nexport type TSessionResultEnvelopeV1 = v.InferOutput<typeof vSessionResultEnvelopeV1>;\n\n// ---------------------------------------------------------------------------\n// Session policy (§5.4 creation binding)\n// ---------------------------------------------------------------------------\n\n/**\n * The session policy the session creation proof binds through `sessionPolicyHash`: the frozen\n * operational limits plus the partner's wallet requirements. Built only through\n * {@link buildSessionPolicyV1} so the capability list is canonically ordered and the\n * limits can never drift from the frozen constants; hashed with the library serializer (§8.4 —\n * every `session_v1` hash uses `nice-code/util`, never the unsupported serializer).\n */\nexport interface ISessionPolicyV1 {\n  formatVersion: 1;\n  interactionMode: EBridgeInteractionMode.session_v1;\n  authorizationMode: ESessionAuthorizationMode;\n  resourceProfile: ESessionResourceProfile;\n  maxTurns: number;\n  maxRedialAttempts: number;\n  idleWindowMillis: number;\n  absoluteLifetimeMillis: number;\n  requiredWalletProtocolVersion: number;\n  requiredWalletCapabilities: string[];\n}\n\nexport const buildSessionPolicyV1 = (requirements: {\n  authorizationMode: ESessionAuthorizationMode;\n  resourceProfile: ESessionResourceProfile;\n  requiredWalletProtocolVersion: number;\n  requiredWalletCapabilities: readonly EWalletProtocolCapability[];\n}): ISessionPolicyV1 => {\n  const profile = getSessionResourceProfilePolicy(requirements.resourceProfile);\n  return {\n    formatVersion: 1,\n    interactionMode: EBridgeInteractionMode.session_v1,\n    authorizationMode: requirements.authorizationMode,\n    resourceProfile: requirements.resourceProfile,\n    maxTurns: profile.maxTurns,\n    maxRedialAttempts: profile.maxRedialAttempts,\n    idleWindowMillis: profile.idleWindowMillis,\n    absoluteLifetimeMillis: profile.absoluteLifetimeMillis,\n    requiredWalletProtocolVersion: requirements.requiredWalletProtocolVersion,\n    // Canonical order: UTF-16 code-unit sort, so semantically equal requirement sets hash equally.\n    requiredWalletCapabilities: [...requirements.requiredWalletCapabilities].sort(),\n  };\n};\n\nexport const hashSessionPolicyV1 = (policy: ISessionPolicyV1): string =>\n  hashCanonicalJsonSha256Base64({ ...policy });\n","import { base64urlnopad, hex } from \"@scure/base\";\nimport { CANONICAL_DURABLE_OBJECT_ID_PATTERN } from \"./bridge.schema\";\n\n/**\n * Wire layout of a `v2` bridge lease — the ENCODING only. Signing, verification, and the keyring\n * live in the backend (`config/bridge_lease.ts`) and nothing key-bearing belongs in this file.\n *\n * It is shared because the wallet has to read the bridge id back out of a lease it cannot verify:\n * the `s2` session link stopped carrying a second copy of the id (feedback L2), so the routing id\n * is recovered from the lease body here. That is a CLAIM, never authorization — the id selects a\n * Durable Object stub before any validation runs, and the DO then checks the signed `b` against\n * its own identity. Decoding one of these says a string is shaped like a lease, not that it is a\n * lease anyone issued.\n *\n * ```text\n * byte  0      header — version; the remaining bits are reserved and MUST be zero\n * bytes 1..32  bridge id, the 32 raw bytes behind its 64 hex characters\n * bytes 33..36 absolute expiry, epoch SECONDS, big-endian uint32\n * bytes 37..52 HMAC-SHA256 tag, truncated to 16 bytes (RFC 2104 §5)\n *              53 bytes → 71 base64url characters, unpadded, no separators\n * ```\n *\n * Canonicality is STRUCTURAL: a fixed-width 53-byte buffer has exactly one encoding, so the\n * re-serialise-and-string-compare check the JSON layout needed (and had to keep in sync with the\n * payload shape by hand) is gone. Every decode still re-encodes to prove the base64url itself was\n * canonical — that is the one degree of freedom the transport keeps.\n */\n\n/** Header byte of a `v2` lease. Reserved bits are zero; a future key index (M3) would live here. */\nexport const BRIDGE_LEASE_V2_HEADER_BYTE = 0x02;\n/** Bytes covered by the HMAC: header ‖ bridge id ‖ expiry. */\nexport const BRIDGE_LEASE_V2_SIGNED_BYTES = 37;\n/** Truncated tag length. RFC 2104 §5 sanctions ≥ half the output and ≥ 80 bits; 128 clears both. */\nexport const BRIDGE_LEASE_V2_TAG_BYTES = 16;\n/** Whole lease, before base64url. */\nexport const BRIDGE_LEASE_V2_TOTAL_BYTES = BRIDGE_LEASE_V2_SIGNED_BYTES + BRIDGE_LEASE_V2_TAG_BYTES;\n/** Exact character length of an encoded `v2` lease. Length is fixed, so parsers check it exactly. */\nexport const BRIDGE_LEASE_V2_LENGTH = 71;\n\nconst EXPIRY_OFFSET = 33;\nconst MAX_EPOCH_SECONDS = 0xff_ff_ff_ff;\nconst BASE64URL_PATTERN = /^[A-Za-z0-9_-]+$/u;\n\nexport interface IBridgeLeaseV2Claims {\n  /** Canonical (lower-case 64 hex) Durable Object id. */\n  bridgeId: string;\n  /** Absolute expiry in epoch MILLISECONDS, as every caller in the protocol expresses time. */\n  expiresAt: number;\n}\n\nexport interface IDecodedBridgeLeaseV2 extends IBridgeLeaseV2Claims {\n  /** The 37 bytes the tag is computed over. */\n  signedBytes: Uint8Array;\n  /** The 16-byte truncated tag as presented. */\n  tag: Uint8Array;\n}\n\n/**\n * Build the signed prefix of a `v2` lease.\n *\n * The expiry is rounded DOWN to the second, so a re-encoded lease can never outlive the deadline it\n * was issued for. Four bytes of epoch seconds is good to 2106; the 13-digit millisecond value buys\n * nothing on a capability whose absolute lifetime is 30 minutes.\n */\nexport const encodeBridgeLeaseV2SignedBytes = ({\n  bridgeId,\n  expiresAt,\n}: IBridgeLeaseV2Claims): Uint8Array => {\n  if (!CANONICAL_DURABLE_OBJECT_ID_PATTERN.test(bridgeId)) {\n    throw new Error(\"Cannot encode a bridge lease for a non-canonical Durable Object id\");\n  }\n  if (!Number.isSafeInteger(expiresAt) || expiresAt <= 0) {\n    throw new Error(\"Cannot encode a bridge lease for an invalid expiry\");\n  }\n  const expiresAtSeconds = Math.floor(expiresAt / 1000);\n  if (expiresAtSeconds <= 0 || expiresAtSeconds > MAX_EPOCH_SECONDS) {\n    throw new Error(\"Cannot encode a bridge lease whose expiry is outside the 32-bit second range\");\n  }\n\n  const signedBytes = new Uint8Array(BRIDGE_LEASE_V2_SIGNED_BYTES);\n  signedBytes[0] = BRIDGE_LEASE_V2_HEADER_BYTE;\n  signedBytes.set(hex.decode(bridgeId), 1);\n  new DataView(signedBytes.buffer).setUint32(EXPIRY_OFFSET, expiresAtSeconds, false);\n  return signedBytes;\n};\n\n/** Join a signed prefix and its truncated tag into the encoded lease. */\nexport const encodeBridgeLeaseV2 = ({\n  signedBytes,\n  tag,\n}: {\n  signedBytes: Uint8Array;\n  tag: Uint8Array;\n}): string => {\n  if (signedBytes.byteLength !== BRIDGE_LEASE_V2_SIGNED_BYTES) {\n    throw new Error(\"Cannot encode a bridge lease from a wrongly sized signed prefix\");\n  }\n  if (tag.byteLength !== BRIDGE_LEASE_V2_TAG_BYTES) {\n    throw new Error(\"Cannot encode a bridge lease from a wrongly sized tag\");\n  }\n  const lease = new Uint8Array(BRIDGE_LEASE_V2_TOTAL_BYTES);\n  lease.set(signedBytes, 0);\n  lease.set(tag, BRIDGE_LEASE_V2_SIGNED_BYTES);\n  return base64urlnopad.encode(lease);\n};\n\n/**\n * Decode a `v2` lease's structure, or `null`. Fail-closed on every degree of freedom the transport\n * has: wrong length, non-base64url characters, a non-canonical base64url encoding, an unknown\n * header byte (which is also how a `v1` lease is refused here), or a zero expiry.\n *\n * Says nothing about authenticity — the tag comes back untouched for the backend to verify.\n */\nexport const decodeBridgeLeaseV2 = (lease: string): IDecodedBridgeLeaseV2 | null => {\n  if (\n    typeof lease !== \"string\" ||\n    lease.length !== BRIDGE_LEASE_V2_LENGTH ||\n    !BASE64URL_PATTERN.test(lease)\n  ) {\n    return null;\n  }\n  let decoded: Uint8Array;\n  try {\n    decoded = base64urlnopad.decode(lease);\n  } catch {\n    return null;\n  }\n  if (\n    decoded.byteLength !== BRIDGE_LEASE_V2_TOTAL_BYTES ||\n    base64urlnopad.encode(decoded) !== lease ||\n    decoded[0] !== BRIDGE_LEASE_V2_HEADER_BYTE\n  ) {\n    return null;\n  }\n\n  const signedBytes = decoded.slice(0, BRIDGE_LEASE_V2_SIGNED_BYTES);\n  const tag = decoded.slice(BRIDGE_LEASE_V2_SIGNED_BYTES);\n  const bridgeId = hex.encode(decoded.slice(1, EXPIRY_OFFSET));\n  const expiresAtSeconds = new DataView(\n    decoded.buffer,\n    decoded.byteOffset,\n    decoded.byteLength,\n  ).getUint32(EXPIRY_OFFSET, false);\n  if (expiresAtSeconds <= 0) return null;\n\n  return { bridgeId, expiresAt: expiresAtSeconds * 1000, signedBytes, tag };\n};\n\n/**\n * The bridge id a lease claims to route to, or `null` when the string is not a decodable `v2`\n * lease. This is what the `s2` link parser uses in place of the query parameter L2 removed.\n */\nexport const readBridgeLeaseV2BridgeId = (lease: string): string | null =>\n  decodeBridgeLeaseV2(lease)?.bridgeId ?? null;\n","import * as v from \"valibot\";\nimport { vBase64HashSha256 } from \"../../../core/core_valibot_schemas\";\nimport { vDurableObjectId } from \"../../../core/meteor_core.schema\";\nimport { vWalletProtocolVersion } from \"../../../core/wallet_protocol.schema\";\nimport { vEncryptedAesGcmPayload } from \"../../../crypto/crypto.schema\";\nimport { vBridgeLease } from \"../bridge.schema\";\nimport { readBridgeLeaseV2BridgeId } from \"../bridge_lease_codec\";\nimport {\n  EBridgeInteractionMode,\n  vSessionNotificationId,\n  vSessionTurnId,\n  vSessionTurnSequence,\n} from \"./session.schema\";\n\n/**\n * Versioned link/push payload contracts for `session_v1` (plan §8.1): the QR/app-link query,\n * the initial claim push payload, and the D24 per-turn wake payload. In every case the carried\n * mode/format is ADVISORY routing data, never authorization — the wallet claims over the HTTP lane\n * first and trusts only the authenticated response's mode confirmation (§9.4); a mode mismatch\n * between link and backend fails closed.\n */\n\n/**\n * Link format markers.\n *\n * `s2` is the only format the backend BUILDS. It exists because `s1` was 409 characters — a 93×93\n * QR grid that users could not scan at arm's length — and `s2` is 147: no second copy of the bridge\n * id (it is an authenticated claim inside the lease), no advisory `interactionMode`, no inert\n * `protocolVersion`, single-character parameter names, and a 71-character `v2` lease.\n *\n * `s1` is still PARSED, and only that. A link minted seconds before the backend deploys has to stay\n * claimable by the wallet that scans it a minute later; nothing builds one. See\n * `PLAN-session-link-length.md` §6 for when this branch goes.\n *\n * Both markers are strict literals in strict objects, so an unknown marker — an `s3` from a newer\n * backend, or a mangled QR — returns `null` from {@link parseSessionLinkQuery} rather than\n * half-parsing into something a caller might act on.\n */\nexport const SESSION_LINK_FORMAT_V1 = \"s1\";\nexport const SESSION_LINK_FORMAT_V2 = \"s2\";\n\n/**\n * Wire keys. Readability lives in the parser and its types, not on the wire — every character here\n * is a QR module, and the `s2` link sits 7 bytes under QR version 7's level-L capacity (154 bytes),\n * so anything added back to it costs the user a 49×49 grid.\n */\nexport const SESSION_LINK_QUERY_KEY_FORMAT_V2 = \"f\";\nexport const SESSION_LINK_QUERY_KEY_LEASE_V2 = \"l\";\n/** Fragment key carrying the partner secret. Fragments never reach a server; that is why it is one. */\nexport const SESSION_LINK_FRAGMENT_KEY_SECRET_V2 = \"s\";\nexport const SESSION_LINK_FRAGMENT_KEY_SECRET_V1 = \"partnerSecret\";\n\n/** `data.type` marker routing a push into the session claim path. */\nexport const PUSH_TYPE_SESSION_CLAIM = \"bridge_session_claim\";\n\n/** `data.type` marker for the D24 per-turn wake/re-entry handoff. */\nexport const PUSH_TYPE_SESSION_TURN_WAKE = \"bridge_session_turn_wake\";\n\n/** Legacy `s1` payload. Parsed, never built. */\nexport const vSessionLinkPayloadV1 = v.strictObject({\n  linkFormat: v.literal(SESSION_LINK_FORMAT_V1),\n  interactionMode: v.literal(EBridgeInteractionMode.session_v1),\n  bridgeId: vDurableObjectId,\n  bridgeLease: vBridgeLease,\n  protocolVersion: vWalletProtocolVersion,\n});\n\n/**\n * The `s2` payload: a format marker and a lease, and that is the whole link.\n *\n * `bridgeId` is not absent from the protocol, only from the wire — it is recovered from the signed\n * lease body by {@link readBridgeLeaseV2BridgeId} and validated here exactly as the query copy used\n * to be. That is why removing the copy is a simplification rather than a weakening: the route\n * segment was never authorization (it selects a stub before any validation runs, and the DO checks\n * the signed id against its own identity), so a second, unsigned copy could only ever disagree with\n * the signed one. `validateBridgeLease`'s `wrong_bridge` check is untouched, and the push payloads\n * below still carry `bridgeId` alongside the lease because that path still needs it.\n *\n * `interactionMode` and `protocolVersion` are gone. The mode was advisory by construction — the\n * wallet claims over the HTTP lane and trusts only the authenticated response's mode confirmation\n * (§9.4) — and `s2` pins it one-to-one anyway. `protocolVersion` was written into every link and\n * read by nothing; the compatibility gate that actually runs is `isWalletProtocolCompatible`\n * against `session.requiredWalletProtocolVersion`, on the authenticated claim.\n */\nexport const vSessionLinkPayloadV2 = v.strictObject({\n  linkFormat: v.literal(SESSION_LINK_FORMAT_V2),\n  bridgeId: vDurableObjectId,\n  bridgeLease: vBridgeLease,\n});\n\nexport type TSessionLinkPayloadV1 = v.InferOutput<typeof vSessionLinkPayloadV1>;\nexport type TSessionLinkPayloadV2 = v.InferOutput<typeof vSessionLinkPayloadV2>;\n/** What {@link parseSessionLinkQuery} returns: discriminated on `linkFormat`. */\nexport type TSessionLinkPayload = TSessionLinkPayloadV1 | TSessionLinkPayloadV2;\n\n/**\n * Build the query-string half of a session wallet link. The host/scheme selection stays with the\n * backend link builder; the partner secret rides the URL fragment appended client-side.\n *\n * Written by hand rather than through `URLSearchParams` for two reasons: the parameter order is\n * part of the length budget and must be deterministic, and base64url needs no percent-encoding, so\n * there is nothing for an encoder to do except risk doing it differently one day.\n */\nexport const buildSessionLinkQuery = (payload: { bridgeLease: string }): string =>\n  `${SESSION_LINK_QUERY_KEY_FORMAT_V2}=${SESSION_LINK_FORMAT_V2}` +\n  `&${SESSION_LINK_QUERY_KEY_LEASE_V2}=${payload.bridgeLease}`;\n\n/**\n * Build a legacy `s1` query. Nothing in production calls this — it exists so the compatibility\n * branch of {@link parseSessionLinkQuery} can be exercised by tests until §6 removes both.\n *\n * @deprecated `s1` is parse-only; build `s2` with {@link buildSessionLinkQuery}.\n */\nexport const buildSessionLinkQueryV1 = (payload: {\n  bridgeId: string;\n  bridgeLease: string;\n  protocolVersion: number;\n}): string =>\n  new URLSearchParams({\n    linkFormat: SESSION_LINK_FORMAT_V1,\n    interactionMode: EBridgeInteractionMode.session_v1,\n    bridgeId: payload.bridgeId,\n    bridgeLease: payload.bridgeLease,\n    protocolVersion: String(payload.protocolVersion),\n  }).toString();\n\n/**\n * Parse a supported link query. Missing, unknown, or invalid format data returns `null` and must be\n * rejected by the caller — including a lease whose body will not decode, which fails here rather\n * than surviving into a claim that cannot work.\n */\nexport const parseSessionLinkQuery = (query: string): TSessionLinkPayload | null => {\n  const params = new URLSearchParams(query.startsWith(\"?\") ? query.slice(1) : query);\n\n  const formatV2 = params.get(SESSION_LINK_QUERY_KEY_FORMAT_V2);\n  if (formatV2 != null) {\n    const bridgeLease = params.get(SESSION_LINK_QUERY_KEY_LEASE_V2);\n    const parsed = v.safeParse(vSessionLinkPayloadV2, {\n      linkFormat: formatV2,\n      bridgeId: bridgeLease == null ? null : readBridgeLeaseV2BridgeId(bridgeLease),\n      bridgeLease,\n    });\n    return parsed.success ? parsed.output : null;\n  }\n\n  if (params.get(\"linkFormat\") == null) {\n    return null;\n  }\n  const candidate = {\n    linkFormat: params.get(\"linkFormat\"),\n    interactionMode: params.get(\"interactionMode\"),\n    bridgeId: params.get(\"bridgeId\"),\n    bridgeLease: params.get(\"bridgeLease\"),\n    protocolVersion: Number(params.get(\"protocolVersion\")),\n  };\n  const parsed = v.safeParse(vSessionLinkPayloadV1, candidate);\n  return parsed.success ? parsed.output : null;\n};\n\n/**\n * The FCM `data` payload for initial claim delivery (`notify_wallet_session`). All values are\n * strings on the wire (FCM constraint); `sealedSecret` travels JSON-encoded like the unsupported push.\n */\nexport const vSessionClaimPushPayload = v.strictObject({\n  type: v.literal(PUSH_TYPE_SESSION_CLAIM),\n  notificationId: vSessionNotificationId,\n  interactionMode: v.literal(EBridgeInteractionMode.session_v1),\n  bridgeId: vDurableObjectId,\n  bridgeLease: vBridgeLease,\n  partnerId: vDurableObjectId,\n  sealedSecret: vEncryptedAesGcmPayload,\n});\n\nexport type TSessionClaimPushPayload = v.InferOutput<typeof vSessionClaimPushPayload>;\n\n/**\n * The FCM `data` payload for the D24 per-turn wake. Carries NO action plaintext — only the exact\n * turn identity for authoritative correlation after re-claim, plus the sealed session re-entry\n * material. Processing it never extends any deadline; the wallet independently rejects delivery\n * at/after the authenticated idle deadline (§7.4).\n */\nexport const vSessionTurnWakePushPayload = v.strictObject({\n  type: v.literal(PUSH_TYPE_SESSION_TURN_WAKE),\n  notificationId: vSessionNotificationId,\n  interactionMode: v.literal(EBridgeInteractionMode.session_v1),\n  bridgeId: vDurableObjectId,\n  bridgeLease: vBridgeLease,\n  /** Advisory lookup key for the wallet's locally persisted partner public keys. */\n  partnerId: vDurableObjectId,\n  sequence: vSessionTurnSequence,\n  turnId: vSessionTurnId,\n  requestHash: vBase64HashSha256,\n  sealedReentry: vEncryptedAesGcmPayload,\n});\n\nexport type TSessionTurnWakePushPayload = v.InferOutput<typeof vSessionTurnWakePushPayload>;\n\n/** What {@link classifySessionPushPayload} made of an untrusted FCM `data` payload. */\nexport type TSessionPushClassification =\n  | { kind: \"session_claim\"; payload: TSessionClaimPushPayload }\n  | { kind: \"session_turn_wake\"; payload: TSessionTurnWakePushPayload }\n  /** Not a Meteor Connect session push, or not a well-formed one. Ignore it. */\n  | { kind: \"unrecognized\" };\n\n/**\n * Transport-shaped push schemas: FCM `data` values are ALWAYS strings on the wire, and the DO\n * sends exactly that (`sequence: String(...)`, sealed members `JSON.stringify(...)`-encoded). The\n * typed payload schemas above describe the DECODED shape; these describe what actually arrives.\n * The bound on the sealed members rejects oversized garbage before any JSON parse.\n */\nexport const MAX_SESSION_PUSH_SEALED_JSON_LENGTH = 4_096;\n\nconst vSessionClaimPushTransportStrings = v.object({\n  type: v.literal(PUSH_TYPE_SESSION_CLAIM),\n  notificationId: vSessionNotificationId,\n  interactionMode: v.literal(EBridgeInteractionMode.session_v1),\n  bridgeId: vDurableObjectId,\n  bridgeLease: vBridgeLease,\n  partnerId: vDurableObjectId,\n  sealedSecret: v.pipe(v.string(), v.maxLength(MAX_SESSION_PUSH_SEALED_JSON_LENGTH)),\n});\n\nconst vSessionTurnWakePushTransportStrings = v.object({\n  type: v.literal(PUSH_TYPE_SESSION_TURN_WAKE),\n  notificationId: vSessionNotificationId,\n  interactionMode: v.literal(EBridgeInteractionMode.session_v1),\n  bridgeId: vDurableObjectId,\n  bridgeLease: vBridgeLease,\n  partnerId: vDurableObjectId,\n  sequence: v.pipe(v.string(), v.regex(/^[1-8]$/)),\n  turnId: vSessionTurnId,\n  requestHash: vBase64HashSha256,\n  sealedReentry: v.pipe(v.string(), v.maxLength(MAX_SESSION_PUSH_SEALED_JSON_LENGTH)),\n});\n\nconst parseSealedPushMember = (serialized: string): unknown | null => {\n  let decoded: unknown;\n  try {\n    decoded = JSON.parse(serialized);\n  } catch {\n    return null;\n  }\n  const parsed = v.safeParse(vEncryptedAesGcmPayload, decoded);\n  return parsed.success ? parsed.output : null;\n};\n\n/**\n * Decode a transport-shaped (string-valued) claim push into the typed payload, or `null`. Also\n * accepts an already-decoded payload so hosts that persisted one keep working.\n */\nexport const decodeSessionClaimPushData = (data: unknown): TSessionClaimPushPayload | null => {\n  const typed = v.safeParse(vSessionClaimPushPayload, data);\n  if (typed.success) return typed.output;\n\n  const strings = v.safeParse(vSessionClaimPushTransportStrings, data);\n  if (!strings.success) return null;\n  const sealedSecret = parseSealedPushMember(strings.output.sealedSecret);\n  if (sealedSecret == null) return null;\n  const parsed = v.safeParse(vSessionClaimPushPayload, { ...strings.output, sealedSecret });\n  return parsed.success ? parsed.output : null;\n};\n\n/**\n * Decode a transport-shaped (string-valued) D24 turn wake into the typed payload, or `null`. Also\n * accepts an already-decoded payload.\n */\nexport const decodeSessionTurnWakePushData = (\n  data: unknown,\n): TSessionTurnWakePushPayload | null => {\n  const typed = v.safeParse(vSessionTurnWakePushPayload, data);\n  if (typed.success) return typed.output;\n\n  const strings = v.safeParse(vSessionTurnWakePushTransportStrings, data);\n  if (!strings.success) return null;\n  const sealedReentry = parseSealedPushMember(strings.output.sealedReentry);\n  if (sealedReentry == null) return null;\n  const sequence = Number(strings.output.sequence);\n  if (!v.safeParse(vSessionTurnSequence, sequence).success) return null;\n  const parsed = v.safeParse(vSessionTurnWakePushPayload, {\n    ...strings.output,\n    sequence,\n    sealedReentry,\n  });\n  return parsed.success ? parsed.output : null;\n};\n\n/**\n * Classify an untrusted FCM `data` payload into one of the two session pushes a wallet acts on.\n *\n * A wallet receives every push its app is registered for, from a transport it cannot authenticate,\n * and has to decide which of `claimInitialPush` / `claimTurnWake` to route it to. Doing that by\n * hand means re-deriving the discriminator and the field shapes in every host — and a host that\n * gets it slightly wrong either drops real sessions or feeds malformed input to a claim.\n *\n * Accepts BOTH the raw transport shape (every value a string, sealed members JSON-encoded — what\n * FCM actually delivers) and the decoded typed shape, converging on the typed payload\n * (stabilization XR-1: the original classifier validated only the typed shape, so every real\n * device push classified as `unrecognized` and was silently dropped).\n *\n * Fail-closed by construction: anything that matches neither shape comes back as `unrecognized`.\n * It validates shape only — the payload stays unauthenticated until the SDK claims against it,\n * which is where the sealed material is actually verified.\n */\nexport const classifySessionPushPayload = (data: unknown): TSessionPushClassification => {\n  const claim = decodeSessionClaimPushData(data);\n  if (claim != null) return { kind: \"session_claim\", payload: claim };\n\n  const turnWake = decodeSessionTurnWakePushData(data);\n  if (turnWake != null) return { kind: \"session_turn_wake\", payload: turnWake };\n\n  return { kind: \"unrecognized\" };\n};\n","import { createActionRootDomain } from \"@meteorwallet/connect-core/action\";\n\nexport const act_root_meteor_connect = createActionRootDomain({\n  domain: \"meteor_connect\",\n});\n","import { actionSchema } from \"@meteorwallet/connect-core/action\";\nimport { err } from \"@meteorwallet/connect-core/error\";\nimport * as v from \"valibot\";\nimport { merr_meteor_connect } from \"../../../error/merr_meteor_connect\";\nimport { act_root_meteor_connect } from \"../act_root_meteor_connect\";\n\nconst vDemoScenarioId = v.pipe(\n  v.string(),\n  v.minLength(8),\n  v.maxLength(64),\n  v.regex(/^[A-Za-z0-9_-]+$/u, \"Invalid demo scenario id\"),\n);\nconst vDemoTurn = v.pipe(v.number(), v.integer(), v.minValue(1), v.maxValue(3));\nconst vDemoMessage = v.pipe(v.string(), v.minLength(1), v.maxLength(256));\n\nexport const vSessionDemoReviewInput = v.strictObject({\n  scenarioId: vDemoScenarioId,\n  turn: vDemoTurn,\n  message: vDemoMessage,\n});\n\nexport const vSessionDemoReviewOutput = v.strictObject({\n  scenarioId: vDemoScenarioId,\n  turn: vDemoTurn,\n  acknowledgedMessage: vDemoMessage,\n  approved: v.literal(true),\n});\n\n/**\n * Strictly test-harness action domain. The server policy also requires the test-only\n * `session_demo_review_v1` wallet capability, so no production wallet can be targeted by it.\n */\nexport const act_impl_meteor_connect_demo = act_root_meteor_connect.createChildDomain({\n  domain: \"meteor_connect_demo\",\n  actions: {\n    review_session_message: actionSchema()\n      .input({ schema: vSessionDemoReviewInput })\n      .output({ schema: vSessionDemoReviewOutput }),\n  },\n});\n\n/**\n * The demo wallets' typed decline for `review_session_message`; the partner renders the serialized\n * error ids. Lives here (not in the demo apps) so the demos need no direct error-library import.\n */\nexport const merr_demo_wallet_review = merr_meteor_connect.createChildDomain({\n  domain: \"demo_wallet_review\",\n  schema: {\n    wallet_declined: err({ message: \"The wallet declined the review message\" }),\n  },\n});\n","import { vEncryptedAesGcmPayload } from \"@meteorwallet/connect-core/util\";\nimport { base58 } from \"@scure/base\";\nimport * as v from \"valibot\";\nimport { base64ToBytes, stringifyCanonicalJson } from \"../../../utils/serialization/canonical_json\";\n\n/**\n * Transfer-accounts v1 wire protocol — versioned and bounded BEFORE first ship, so the limits are\n * part of the compatibility contract (capability `transfer_accounts_v1` means exactly this shape).\n *\n * Every numeric bound is an exported named constant: the partner wrapper, the backend's\n * first-party request validation, and the wallet's post-decrypt validation all consume these same\n * values — no magic numbers, no drift.\n *\n * Size-cap derivation (re-verify the whole chain before ever raising the ciphertext cap):\n * ~1 MiB Workers RPC serialization on `create_session` → 2 MB per-value SQLite-backed DO storage\n * (the whole bridge state persists as ONE value, and D8 stores a second wallet-encrypted envelope\n * of the same request) → 1 MiB realm WebSocket message. 350,000 base64 chars (≈256 KiB plaintext)\n * keeps ≥2× margin at every hop.\n */\nexport const TRANSFER_ACCOUNTS_FORMAT_VERSION = 1;\nexport const TRANSFER_ACCOUNTS_MIN_ACCOUNTS = 1;\nexport const TRANSFER_ACCOUNTS_MAX_ACCOUNTS = 50;\nexport const TRANSFER_ACCOUNTS_MIN_SECRETS_PER_ACCOUNT = 1;\nexport const TRANSFER_ACCOUNTS_MAX_SECRETS_PER_ACCOUNT = 10;\nexport const TRANSFER_ACCOUNTS_MIN_ACCOUNT_ID_LENGTH = 2;\nexport const TRANSFER_ACCOUNTS_MAX_ACCOUNT_ID_LENGTH = 64;\n/** NEAR's account-id grammar. See the note on `vAccountBasicData.accountId`. */\nexport const TRANSFER_ACCOUNTS_ACCOUNT_ID_PATTERN = /^[a-z0-9._-]+$/;\nexport const TRANSFER_ACCOUNTS_MAX_DERIVATION_PATH_LENGTH = 128;\nexport const TRANSFER_ACCOUNTS_MAX_SECRET_DATA_LENGTH = 16_384;\nexport const TRANSFER_ACCOUNTS_MAX_CIPHERTEXT_BASE64_LENGTH = 350_000;\nexport const TRANSFER_ACCOUNTS_NONCE_BYTE_LENGTH = 12;\n\nexport const vBlockchainId = v.picklist([\"near\"]);\n\nexport const vCryptoGenericNetworkId = v.picklist([\"mainnet\", \"testnet\"]);\n\nexport const vAccountSecretType = v.picklist([\"mnemonic\", \"private_key\"]);\n\n/**\n * `prefixedBase64DataString` format: `\"<encoding>::<standard base64>\"`. The embedded prefix must\n * match the entry's declared `encoding`, and the base64 part must decode, be non-empty, and stay\n * within {@link TRANSFER_ACCOUNTS_MAX_SECRET_DATA_LENGTH} — an empty or arbitrary string is not an\n * importable secret.\n */\nconst isValidPrefixedSecretData = (encoding: string, value: string): boolean => {\n  const requiredPrefix = `${encoding}::`;\n  if (!value.startsWith(requiredPrefix)) {\n    return false;\n  }\n  const dataPart = value.slice(requiredPrefix.length);\n  if (dataPart.length === 0 || dataPart.length > TRANSFER_ACCOUNTS_MAX_SECRET_DATA_LENGTH) {\n    return false;\n  }\n  try {\n    return base64ToBytes(dataPart).length > 0;\n  } catch {\n    return false;\n  }\n};\n\nexport const vAccountSecretMnemonic = v.object({\n  type: v.literal(\"mnemonic\"),\n  encoding: v.literal(\"utf8_base64\"),\n  derivationPath: v.pipe(\n    v.string(),\n    v.minLength(1),\n    v.maxLength(TRANSFER_ACCOUNTS_MAX_DERIVATION_PATH_LENGTH),\n  ),\n  prefixedBase64DataString: v.pipe(\n    v.string(),\n    v.check(\n      (value) => isValidPrefixedSecretData(\"utf8_base64\", value),\n      \"Mnemonic secret data must be 'utf8_base64::<base64>' with non-empty, bounded, decodable data\",\n    ),\n  ),\n});\n\nexport const vAccountSecretPrivateKey = v.object({\n  type: v.literal(\"private_key\"),\n  encoding: v.literal(\"near_prefixed_utf8_base64\"),\n  keyAlgorithm: v.literal(\"ed25519\"),\n  prefixedBase64DataString: v.pipe(\n    v.string(),\n    v.check(\n      (value) => isValidPrefixedSecretData(\"near_prefixed_utf8_base64\", value),\n      \"Private-key secret data must be 'near_prefixed_utf8_base64::<base64>' with non-empty, bounded, decodable data\",\n    ),\n  ),\n});\n\nexport const vAccountSecretData = v.variant(\"type\", [\n  vAccountSecretMnemonic,\n  vAccountSecretPrivateKey,\n]);\n\n/**\n * The only free-form account identity field (`blockchainId`/`networkId` are closed picklists), and\n * it is rendered verbatim in approval UIs. The grammar prevents homoglyph/bidi/zero-width labels.\n */\nexport const vNearAccountId = v.pipe(\n  v.string(),\n  v.minLength(TRANSFER_ACCOUNTS_MIN_ACCOUNT_ID_LENGTH),\n  v.maxLength(TRANSFER_ACCOUNTS_MAX_ACCOUNT_ID_LENGTH),\n  v.regex(TRANSFER_ACCOUNTS_ACCOUNT_ID_PATTERN),\n);\n\nexport const vAccountBasicData = v.object({\n  blockchainId: vBlockchainId,\n  networkId: vCryptoGenericNetworkId,\n  accountId: vNearAccountId,\n});\n\nconst basicAccountKey = (account: {\n  blockchainId: string;\n  networkId: string;\n  accountId: string;\n}): string => `${account.blockchainId}::${account.networkId}::${account.accountId}`;\n\nconst hasNoDuplicateAccounts = (\n  accounts: readonly { blockchainId: string; networkId: string; accountId: string }[],\n): boolean => new Set(accounts.map(basicAccountKey)).size === accounts.length;\n\nconst hasNoDuplicateSecrets = (secrets: readonly unknown[]): boolean =>\n  new Set(secrets.map((secret) => stringifyCanonicalJson(secret))).size === secrets.length;\n\nexport const vAccountTransferDataDecrypted = v.object({\n  ...vAccountBasicData.entries,\n  secret: v.pipe(\n    v.array(vAccountSecretData),\n    v.minLength(TRANSFER_ACCOUNTS_MIN_SECRETS_PER_ACCOUNT),\n    v.maxLength(TRANSFER_ACCOUNTS_MAX_SECRETS_PER_ACCOUNT),\n    v.check(\n      (secrets) => hasNoDuplicateSecrets(secrets),\n      \"Duplicate secret entries for the same account are not allowed\",\n    ),\n  ),\n});\n\nexport const vAllAccountsTransferDataDecrypted = v.object({\n  formatVersion: v.literal(TRANSFER_ACCOUNTS_FORMAT_VERSION),\n  accounts: v.pipe(\n    v.array(vAccountTransferDataDecrypted),\n    v.minLength(TRANSFER_ACCOUNTS_MIN_ACCOUNTS),\n    v.maxLength(TRANSFER_ACCOUNTS_MAX_ACCOUNTS),\n    v.check(\n      (accounts) => hasNoDuplicateAccounts(accounts),\n      \"Duplicate (blockchainId, networkId, accountId) accounts are not allowed\",\n    ),\n  ),\n});\n\nexport const vTransferAccountsCiphertext = v.pipe(\n  vEncryptedAesGcmPayload,\n  v.check(\n    (payload) => payload.ciphertext.length <= TRANSFER_ACCOUNTS_MAX_CIPHERTEXT_BASE64_LENGTH,\n    \"Transfer ciphertext exceeds the v1 size cap\",\n  ),\n  v.check((payload) => {\n    try {\n      return base64ToBytes(payload.nonce).length === TRANSFER_ACCOUNTS_NONCE_BYTE_LENGTH;\n    } catch {\n      return false;\n    }\n  }, \"Transfer ciphertext nonce must decode to exactly 12 bytes\"),\n);\n\nexport const TRANSFER_ACCOUNTS_ID_RANDOM_BYTE_LENGTH = 16;\nexport const TRANSFER_ACCOUNTS_MIN_ID_LENGTH = 22;\nexport const TRANSFER_ACCOUNTS_MAX_ID_LENGTH = 128;\nexport const TRANSFER_ACCOUNTS_ID_PATTERN = /^[A-Za-z0-9_-]+$/;\n\n/** Stable source-generated identity used by the wallet's transactional import receipt. */\nexport const vAccountTransferOpaqueId = v.pipe(\n  v.string(),\n  v.minLength(TRANSFER_ACCOUNTS_MIN_ID_LENGTH),\n  v.maxLength(TRANSFER_ACCOUNTS_MAX_ID_LENGTH),\n  v.regex(TRANSFER_ACCOUNTS_ID_PATTERN),\n);\n\nexport const vAllAccountsTransferDataEncrypted = v.object({\n  formatVersion: v.literal(TRANSFER_ACCOUNTS_FORMAT_VERSION),\n  clientTransferId: vAccountTransferOpaqueId,\n  allAccountsBasicInfo: v.pipe(\n    v.array(vAccountBasicData),\n    v.minLength(TRANSFER_ACCOUNTS_MIN_ACCOUNTS),\n    v.maxLength(TRANSFER_ACCOUNTS_MAX_ACCOUNTS),\n    v.check(\n      (accounts) => hasNoDuplicateAccounts(accounts),\n      \"Duplicate (blockchainId, networkId, accountId) accounts are not allowed\",\n    ),\n  ),\n  encryptedData: vTransferAccountsCiphertext,\n});\n\nexport type TBlockchainId = v.InferOutput<typeof vBlockchainId>;\nexport type TCryptoGenericNetworkId = v.InferOutput<typeof vCryptoGenericNetworkId>;\nexport type TAccountSecretData = v.InferOutput<typeof vAccountSecretData>;\nexport type TAccountBasicData = v.InferOutput<typeof vAccountBasicData>;\nexport type TAccountTransferDataDecrypted = v.InferOutput<typeof vAccountTransferDataDecrypted>;\nexport type TAllAccountsTransferDataDecrypted = v.InferOutput<\n  typeof vAllAccountsTransferDataDecrypted\n>;\nexport type TAllAccountsTransferDataEncrypted = v.InferOutput<\n  typeof vAllAccountsTransferDataEncrypted\n>;\n\n// --- NEW-KEY ACCOUNT TRANSFER V1 --------------------------------------------\n\nexport const NEW_KEY_ACCOUNT_TRANSFER_FORMAT_VERSION = 1;\nexport const NEW_KEY_ACCOUNT_TRANSFER_MIN_ACCOUNTS = 1;\nexport const NEW_KEY_ACCOUNT_TRANSFER_MAX_ACCOUNTS = 50;\nexport const NEW_KEY_ACCOUNT_TRANSFER_ID_RANDOM_BYTE_LENGTH = 16;\nexport const NEW_KEY_ACCOUNT_TRANSFER_MIN_ID_LENGTH = 22;\nexport const NEW_KEY_ACCOUNT_TRANSFER_MAX_ID_LENGTH = 128;\nexport const NEW_KEY_ACCOUNT_TRANSFER_MAX_PUBLIC_KEY_LENGTH = 64;\nexport const NEW_KEY_ACCOUNT_TRANSFER_MAX_TRANSACTION_HASH_LENGTH = 64;\nexport const NEW_KEY_ACCOUNT_TRANSFER_KEY_BYTE_LENGTH = 32;\nexport const NEW_KEY_ACCOUNT_TRANSFER_ID_PATTERN = /^[A-Za-z0-9_-]+$/;\n\nconst NEAR_ED25519_PUBLIC_KEY_PREFIX = \"ed25519:\";\n\nconst decodesBase58ToExactBytes = (value: string, byteLength: number): boolean => {\n  try {\n    return base58.decode(value).length === byteLength;\n  } catch {\n    return false;\n  }\n};\n\nexport const vNewKeyTransferOpaqueId = v.pipe(\n  v.string(),\n  v.minLength(NEW_KEY_ACCOUNT_TRANSFER_MIN_ID_LENGTH),\n  v.maxLength(NEW_KEY_ACCOUNT_TRANSFER_MAX_ID_LENGTH),\n  v.regex(NEW_KEY_ACCOUNT_TRANSFER_ID_PATTERN),\n);\n\nexport const vNearEd25519PublicKey = v.pipe(\n  v.string(),\n  v.maxLength(NEW_KEY_ACCOUNT_TRANSFER_MAX_PUBLIC_KEY_LENGTH),\n  v.check((value) => {\n    if (!value.startsWith(NEAR_ED25519_PUBLIC_KEY_PREFIX)) {\n      return false;\n    }\n    return decodesBase58ToExactBytes(\n      value.slice(NEAR_ED25519_PUBLIC_KEY_PREFIX.length),\n      NEW_KEY_ACCOUNT_TRANSFER_KEY_BYTE_LENGTH,\n    );\n  }, \"NEAR public key must be ed25519 and decode to exactly 32 bytes\"),\n);\n\nexport const vNearTransactionHash = v.pipe(\n  v.string(),\n  v.maxLength(NEW_KEY_ACCOUNT_TRANSFER_MAX_TRANSACTION_HASH_LENGTH),\n  v.check(\n    (value) => decodesBase58ToExactBytes(value, NEW_KEY_ACCOUNT_TRANSFER_KEY_BYTE_LENGTH),\n    \"NEAR transaction hash must decode to exactly 32 bytes\",\n  ),\n);\n\nexport const NEW_KEY_TRANSFER_START_ISSUES = [\n  \"account_not_found\",\n  \"source_key_not_found\",\n  \"source_key_not_full_access\",\n  \"rpc_lookup_failed\",\n  \"pending_transfer_conflict\",\n  \"key_generation_failed\",\n  \"secure_storage_failed\",\n] as const;\n\nexport const NEW_KEY_TRANSFER_VERIFY_ACTIVE_ISSUES = [\n  \"session_not_found\",\n  \"account_not_in_session\",\n  \"activation_not_found\",\n  \"activation_not_full_access\",\n  \"invalid_add_key_transaction\",\n  \"source_signer_mismatch\",\n  \"rpc_lookup_failed\",\n] as const;\n\nexport const vNewKeyTransferStartIssueV1 = v.picklist(NEW_KEY_TRANSFER_START_ISSUES);\nexport const vNewKeyTransferVerifyActiveIssueV1 = v.picklist(NEW_KEY_TRANSFER_VERIFY_ACTIVE_ISSUES);\nexport const vNewKeyTransferDestinationSignerTypeV1 = v.picklist([\"seed_phrase\", \"ledger\"]);\n\nexport const vNewKeyTransferStartInputAccountV1 = v.object({\n  ...vAccountBasicData.entries,\n  sourcePublicKey: vNearEd25519PublicKey,\n});\n\nconst vNewKeyTransferStartOutputReadyAccountV1 = v.object({\n  ...vAccountBasicData.entries,\n  ok: v.literal(true),\n  destinationSignerType: vNewKeyTransferDestinationSignerTypeV1,\n  destinationPublicKey: vNearEd25519PublicKey,\n});\n\nconst vNewKeyTransferStartOutputFailedAccountV1 = v.object({\n  ...vAccountBasicData.entries,\n  ok: v.literal(false),\n  issue: vNewKeyTransferStartIssueV1,\n});\n\nexport const vNewKeyTransferStartOutputAccountV1 = v.union([\n  vNewKeyTransferStartOutputReadyAccountV1,\n  vNewKeyTransferStartOutputFailedAccountV1,\n]);\n\nexport const vNewKeyTransferVerifyActiveInputAccountV1 = v.object({\n  ...vAccountBasicData.entries,\n  addKeyTransactionHash: vNearTransactionHash,\n});\n\n/**\n * Stabilization SD4 verify-output states.\n *\n * `secured` means the wallet proved the finalized AddKey AND durably imported the destination\n * signer + account into its real inventory (SD3) — under the SD1/SD5 ordering the recovery phrase\n * was already confirmed in full before the key was ever published, so `secured` is the partner's\n * only \"done\" signal (SD6). `verified_pending_completion` means chain proof passed but a wallet\n * completion fact is still outstanding; the bounded `pendingFact` says which one, and a re-entrant\n * verify later resolves it to `secured`. `not_verified` remains the proof-failure arm.\n *\n * The optional `liveness` fact on `secured` rows reports the SD13 1-yocto activation self-test:\n * `confirmed` (test transaction executed, hash journaled wallet-side) or `skipped` (policy off,\n * balance below the gas floor, or RPC-uncertain after bounded retries). A *definitive*\n * signing/execution failure of the self-test is never reported as `secured` — it surfaces as\n * `verified_pending_completion` with `pendingFact: \"liveness_check_failed\"`.\n */\nexport const NEW_KEY_TRANSFER_PENDING_FACTS = [\n  \"import_incomplete\",\n  \"liveness_check_failed\",\n] as const;\n\nexport const NEW_KEY_TRANSFER_LIVENESS_FACTS = [\"confirmed\", \"skipped\"] as const;\n\nexport const vNewKeyTransferPendingFactV1 = v.picklist(NEW_KEY_TRANSFER_PENDING_FACTS);\nexport const vNewKeyTransferLivenessFactV1 = v.picklist(NEW_KEY_TRANSFER_LIVENESS_FACTS);\n\nconst vNewKeyTransferVerifyActiveOutputSecuredAccountV1 = v.object({\n  ...vAccountBasicData.entries,\n  activation: v.literal(\"secured\"),\n  liveness: v.optional(vNewKeyTransferLivenessFactV1),\n});\n\nconst vNewKeyTransferVerifyActiveOutputPendingAccountV1 = v.object({\n  ...vAccountBasicData.entries,\n  activation: v.literal(\"verified_pending_completion\"),\n  pendingFact: vNewKeyTransferPendingFactV1,\n});\n\nconst vNewKeyTransferVerifyActiveOutputNotVerifiedAccountV1 = v.object({\n  ...vAccountBasicData.entries,\n  activation: v.literal(\"not_verified\"),\n  issue: vNewKeyTransferVerifyActiveIssueV1,\n});\n\nexport const vNewKeyTransferVerifyActiveOutputAccountV1 = v.union([\n  vNewKeyTransferVerifyActiveOutputSecuredAccountV1,\n  vNewKeyTransferVerifyActiveOutputPendingAccountV1,\n  vNewKeyTransferVerifyActiveOutputNotVerifiedAccountV1,\n]);\n\nexport const vNewKeyTransferStartInputV1 = v.object({\n  formatVersion: v.literal(NEW_KEY_ACCOUNT_TRANSFER_FORMAT_VERSION),\n  clientTransferId: vNewKeyTransferOpaqueId,\n  accounts: v.pipe(\n    v.array(vNewKeyTransferStartInputAccountV1),\n    v.minLength(NEW_KEY_ACCOUNT_TRANSFER_MIN_ACCOUNTS),\n    v.maxLength(NEW_KEY_ACCOUNT_TRANSFER_MAX_ACCOUNTS),\n    v.check(\n      (accounts) => hasNoDuplicateAccounts(accounts),\n      \"Duplicate (blockchainId, networkId, accountId) accounts are not allowed\",\n    ),\n  ),\n});\n\nexport const vNewKeyTransferStartOutputV1 = v.object({\n  formatVersion: v.literal(NEW_KEY_ACCOUNT_TRANSFER_FORMAT_VERSION),\n  clientTransferId: vNewKeyTransferOpaqueId,\n  transferSessionId: vNewKeyTransferOpaqueId,\n  accounts: v.pipe(\n    v.array(vNewKeyTransferStartOutputAccountV1),\n    v.minLength(NEW_KEY_ACCOUNT_TRANSFER_MIN_ACCOUNTS),\n    v.maxLength(NEW_KEY_ACCOUNT_TRANSFER_MAX_ACCOUNTS),\n    v.check(\n      (accounts) => hasNoDuplicateAccounts(accounts),\n      \"Duplicate (blockchainId, networkId, accountId) accounts are not allowed\",\n    ),\n  ),\n});\n\nexport const vNewKeyTransferVerifyActiveInputV1 = v.object({\n  formatVersion: v.literal(NEW_KEY_ACCOUNT_TRANSFER_FORMAT_VERSION),\n  transferSessionId: vNewKeyTransferOpaqueId,\n  activations: v.pipe(\n    v.array(vNewKeyTransferVerifyActiveInputAccountV1),\n    v.minLength(NEW_KEY_ACCOUNT_TRANSFER_MIN_ACCOUNTS),\n    v.maxLength(NEW_KEY_ACCOUNT_TRANSFER_MAX_ACCOUNTS),\n    v.check(\n      (accounts) => hasNoDuplicateAccounts(accounts),\n      \"Duplicate (blockchainId, networkId, accountId) accounts are not allowed\",\n    ),\n  ),\n});\n\nexport const vNewKeyTransferVerifyActiveOutputV1 = v.object({\n  formatVersion: v.literal(NEW_KEY_ACCOUNT_TRANSFER_FORMAT_VERSION),\n  transferSessionId: vNewKeyTransferOpaqueId,\n  accounts: v.pipe(\n    v.array(vNewKeyTransferVerifyActiveOutputAccountV1),\n    v.minLength(NEW_KEY_ACCOUNT_TRANSFER_MIN_ACCOUNTS),\n    v.maxLength(NEW_KEY_ACCOUNT_TRANSFER_MAX_ACCOUNTS),\n    v.check(\n      (accounts) => hasNoDuplicateAccounts(accounts),\n      \"Duplicate (blockchainId, networkId, accountId) accounts are not allowed\",\n    ),\n  ),\n});\n\nexport type TNewKeyTransferStartIssueV1 = v.InferOutput<typeof vNewKeyTransferStartIssueV1>;\nexport type TNewKeyTransferVerifyActiveIssueV1 = v.InferOutput<\n  typeof vNewKeyTransferVerifyActiveIssueV1\n>;\nexport type TNewKeyTransferDestinationSignerTypeV1 = v.InferOutput<\n  typeof vNewKeyTransferDestinationSignerTypeV1\n>;\nexport type TNewKeyTransferPendingFactV1 = v.InferOutput<typeof vNewKeyTransferPendingFactV1>;\nexport type TNewKeyTransferLivenessFactV1 = v.InferOutput<typeof vNewKeyTransferLivenessFactV1>;\nexport type TNewKeyTransferStartInputAccountV1 = v.InferOutput<\n  typeof vNewKeyTransferStartInputAccountV1\n>;\nexport type TNewKeyTransferStartOutputAccountV1 = v.InferOutput<\n  typeof vNewKeyTransferStartOutputAccountV1\n>;\nexport type TNewKeyTransferVerifyActiveInputAccountV1 = v.InferOutput<\n  typeof vNewKeyTransferVerifyActiveInputAccountV1\n>;\nexport type TNewKeyTransferVerifyActiveOutputAccountV1 = v.InferOutput<\n  typeof vNewKeyTransferVerifyActiveOutputAccountV1\n>;\nexport type TNewKeyTransferStartInputV1 = v.InferOutput<typeof vNewKeyTransferStartInputV1>;\nexport type TNewKeyTransferStartOutputV1 = v.InferOutput<typeof vNewKeyTransferStartOutputV1>;\nexport type TNewKeyTransferVerifyActiveInputV1 = v.InferOutput<\n  typeof vNewKeyTransferVerifyActiveInputV1\n>;\nexport type TNewKeyTransferVerifyActiveOutputV1 = v.InferOutput<\n  typeof vNewKeyTransferVerifyActiveOutputV1\n>;\n","import { actionSchema } from \"@meteorwallet/connect-core/action\";\nimport * as v from \"valibot\";\nimport {\n  EErr_NewKeyAccountTransfer,\n  merr_new_key_account_transfer,\n} from \"../../../error/merr_new_key_account_transfer\";\nimport { act_root_meteor_connect } from \"../act_root_meteor_connect\";\nimport {\n  vAllAccountsTransferDataEncrypted,\n  vNewKeyTransferStartInputV1,\n  vNewKeyTransferStartOutputV1,\n  vNewKeyTransferVerifyActiveInputV1,\n  vNewKeyTransferVerifyActiveOutputV1,\n} from \"./act_impl_meteor_wallet_core.schemas\";\n\nexport const act_impl_meteor_wallet_core = act_root_meteor_connect.createChildDomain({\n  domain: \"meteor_wallet_core\",\n  actions: {\n    /**\n     * ⚠ **A decline is a SUCCESS result on this action, not an error.**\n     *\n     * This action's entire output is one boolean, and it declares no `.throws(...)` arm — so a user\n     * refusing the transfer is `successResult({ success: false })`, which reaches the partner as\n     * `waitForValidatedResult`'s `\"ok\"` arm. Its two siblings\n     * (`new_key_account_transfer_start`, `_verify_active`) DO declare typed error arms, so the same\n     * `waitForValidatedResult` call means different things per action id, and the difference is\n     * invisible at the call site. Code that reads `status === \"ok\"` as \"the user approved\" is wrong\n     * here; read `output.success`.\n     *\n     * The output is also the entire report: per-account detail (imported / already present /\n     * failed) stays local to the wallet by design, and the signed result is all-or-nothing.\n     *\n     * Why this is a doc and not a `.throws` arm: every wallet in the field — both demos and the\n     * shipped Meteor wallet — sends `{ success: false }` today. Adding the arm would create a\n     * SECOND decline representation without retiring the first, so `status === \"ok\"` still would\n     * not mean \"approved\" until every deployed wallet had been updated. Making the arm worth having\n     * therefore needs a coordinated migration: add the arm, update every wallet, then narrow this\n     * output to `{ success: true }` so the old representation cannot be sent. Until that lands,\n     * this comment is the honest mitigation.\n     */\n    transfer_accounts: actionSchema()\n      .input({\n        schema: vAllAccountsTransferDataEncrypted,\n      })\n      .output({\n        schema: v.object({\n          success: v.boolean(),\n          /**\n           * What actually happened to the destination wallet, when `success` alone would mislead.\n           *\n           * `success: false` used to mean only \"the wallet did not sign off\", which a partner has\n           * no choice but to render as a clean decline — even when the wallet already holds some\n           * of the transferred accounts (REVIEW-consumer-implementation B-02/H-02). A wallet that\n           * stops after its inventory write landed MUST send `partially_imported` so the partner\n           * never tells the user their accounts are untouched.\n           *\n           * Optional for compatibility: an older wallet omits it, and `success` keeps its meaning.\n           * A partner that does not understand it is no worse off than before.\n           */\n          outcome: v.optional(v.picklist([\"imported\", \"declined\", \"partially_imported\"])),\n        }),\n      }),\n\n    new_key_account_transfer_start: actionSchema()\n      .input({ schema: vNewKeyTransferStartInputV1 })\n      .output({ schema: vNewKeyTransferStartOutputV1 })\n      .throws(merr_new_key_account_transfer, [\n        EErr_NewKeyAccountTransfer.wallet_declined,\n        EErr_NewKeyAccountTransfer.client_transfer_id_conflict,\n      ]),\n\n    new_key_account_transfer_verify_active: actionSchema()\n      .input({ schema: vNewKeyTransferVerifyActiveInputV1 })\n      .output({ schema: vNewKeyTransferVerifyActiveOutputV1 })\n      .throws(merr_new_key_account_transfer, [EErr_NewKeyAccountTransfer.wallet_declined]),\n  },\n});\n","import * as v from \"valibot\";\n\n/**\n * JSON-safe mirrors of the public `@hot-labs/near-connect` wallet contract.\n *\n * Rich values are converted only where JSON requires it:\n * - message nonces (`Uint8Array`) become base64 strings;\n * - near-api action instances become the connector's `{ type, params }` action format;\n * - final execution outcomes remain complete JSON objects so a dApp receives the same result it\n *   would receive from a directly connected wallet.\n */\n\nexport const vNearNetwork = v.picklist([\"mainnet\", \"testnet\"]);\n\nexport const vNearAccount = v.object({\n  accountId: v.string(),\n  publicKey: v.optional(v.string()),\n});\n\n// --- SIGN IN -----------------------------------------------------------------\n\nconst vNearAllowAnyMethod = v.object({\n  anyMethod: v.literal(true),\n});\n\nconst vNearAllowSelectedMethods = v.object({\n  anyMethod: v.literal(false),\n  methodNames: v.array(v.string()),\n});\n\nconst vNearUnlimitedGasAllowance = v.object({\n  kind: v.literal(\"unlimited\"),\n});\n\nconst vNearLimitedGasAllowance = v.object({\n  kind: v.literal(\"limited\"),\n  amount: v.string(),\n});\n\nexport const vNearAddFunctionCallKey = v.object({\n  contractId: v.string(),\n  publicKey: v.string(),\n  allowMethods: v.union([vNearAllowAnyMethod, vNearAllowSelectedMethods]),\n  gasAllowance: v.optional(v.union([vNearUnlimitedGasAllowance, vNearLimitedGasAllowance])),\n});\n\nexport const vNearSignInInput = v.object({\n  network: v.optional(vNearNetwork),\n  addFunctionCallKey: v.optional(vNearAddFunctionCallKey),\n});\n\n// --- SIGN MESSAGE ------------------------------------------------------------\n\n/** JSON wire form of `SignMessageParams`; `nonce` is base64 instead of `Uint8Array`. */\nexport const vNearSignMessageParams = v.object({\n  message: v.string(),\n  recipient: v.string(),\n  nonceBase64: v.string(),\n  network: v.optional(vNearNetwork),\n  signerId: v.string(),\n});\n\n/** Sign-in message params deliberately exclude `network` and `signerId`. */\nexport const vNearSignMessageDuringSignInParams = v.object({\n  message: v.string(),\n  recipient: v.string(),\n  nonceBase64: v.string(),\n});\n\nexport const vNearSignedMessage = v.object({\n  accountId: v.string(),\n  publicKey: v.string(),\n  signature: v.string(),\n});\n\nexport const vNearAccountWithSignedMessage = v.object({\n  ...vNearAccount.entries,\n  signedMessage: vNearSignedMessage,\n});\n\n// --- TRANSACTIONS / DELEGATE ACTIONS -----------------------------------------\n\n/**\n * The connector supports both near-api Action instances and this JSON connector-action format.\n * Bridge requests always use the latter because class instances cannot cross the wire.\n */\nexport const vNearConnectorAction = v.object({\n  type: v.string(),\n  params: v.record(v.string(), v.unknown()),\n});\n\nexport const vNearTransaction = v.object({\n  receiverId: v.string(),\n  actions: v.array(vNearConnectorAction),\n});\n\nexport const vNearSignTransactionInput = v.object({\n  network: v.optional(vNearNetwork),\n  signerId: v.string(),\n  ...vNearTransaction.entries,\n});\n\nexport const vNearSignTransactionsInput = v.object({\n  network: v.optional(vNearNetwork),\n  signerId: v.string(),\n  transactions: v.array(vNearTransaction),\n});\n\nexport const vNearSignDelegateActionsInput = v.object({\n  network: v.optional(vNearNetwork),\n  signerId: v.string(),\n  delegateActions: v.array(vNearTransaction),\n});\n\n/** A complete JSON-serialized NEAR `FinalExecutionOutcome`. */\nexport const vNearFinalExecutionOutcome = v.record(v.string(), v.unknown());\n\nexport const vNearSignedDelegateActions = v.object({\n  signedDelegateActions: v.array(v.string()),\n});\n\n// --- METEOR VERIFY-OWNER EXTENSION -------------------------------------------\n\n/**\n * `verifyOwner` is not in the current NearWalletBase interface, but the Meteor adapter still\n * exposes it. Keep it as an explicit extension while the production wallet supports the flow.\n */\nexport const vNearVerifyOwnerInput = v.object({\n  network: v.optional(vNearNetwork),\n  accountId: v.string(),\n  message: v.string(),\n});\n\nexport const vNearVerifyOwnerOutput = v.object({\n  accountId: v.string(),\n  message: v.string(),\n  blockId: v.string(),\n  publicKey: v.string(),\n  signature: v.string(),\n});\n","import { actionSchema } from \"@meteorwallet/connect-core/action\";\nimport * as v from \"valibot\";\nimport { act_root_meteor_connect } from \"../act_root_meteor_connect\";\nimport {\n  vNearAccount,\n  vNearAccountWithSignedMessage,\n  vNearFinalExecutionOutcome,\n  vNearNetwork,\n  vNearSignDelegateActionsInput,\n  vNearSignedDelegateActions,\n  vNearSignedMessage,\n  vNearSignInInput,\n  vNearSignMessageDuringSignInParams,\n  vNearSignMessageParams,\n  vNearSignTransactionInput,\n  vNearSignTransactionsInput,\n  vNearVerifyOwnerInput,\n  vNearVerifyOwnerOutput,\n} from \"./act_impl_near.schemas\";\n\n/**\n * NiceCode action domain for the public NEAR Connect wallet interface. Requests and results match\n * `NearWalletBase`; the only wire adaptation is replacing non-JSON runtime values with the forms\n * documented in `act_impl_near.schemas.ts`.\n */\nexport const act_impl_near = act_root_meteor_connect.createChildDomain({\n  domain: \"near\",\n  actions: {\n    sign_in: actionSchema()\n      .input({ schema: vNearSignInInput })\n      .output({ schema: v.array(vNearAccount) }),\n\n    sign_in_and_sign_message: actionSchema()\n      .input({\n        schema: v.object({\n          ...vNearSignInInput.entries,\n          messageParams: vNearSignMessageDuringSignInParams,\n        }),\n      })\n      .output({ schema: v.array(vNearAccountWithSignedMessage) }),\n\n    sign_out: actionSchema()\n      .input({ schema: v.object({ accountId: v.string(), network: v.optional(vNearNetwork) }) })\n      .output({ schema: v.object({ accountId: v.string() }) }),\n\n    sign_message: actionSchema()\n      .input({ schema: vNearSignMessageParams })\n      .output({ schema: vNearSignedMessage }),\n\n    sign_and_send_transaction: actionSchema()\n      .input({ schema: vNearSignTransactionInput })\n      .output({ schema: vNearFinalExecutionOutcome }),\n\n    sign_and_send_transactions: actionSchema()\n      .input({ schema: vNearSignTransactionsInput })\n      .output({ schema: v.array(vNearFinalExecutionOutcome) }),\n\n    sign_delegate_actions: actionSchema()\n      .input({ schema: vNearSignDelegateActionsInput })\n      .output({ schema: vNearSignedDelegateActions }),\n\n    verify_owner: actionSchema()\n      .input({ schema: vNearVerifyOwnerInput })\n      .output({ schema: vNearVerifyOwnerOutput }),\n  },\n});\n","import type { IActionPayload_Request_JsonObject } from \"@meteorwallet/connect-core/action\";\nimport { EWalletProtocolCapability } from \"../model/core/wallet_protocol.schema\";\nimport { ESessionResourceProfile } from \"../model/durable_object/bridge/session/session.schema\";\nimport { stringifyCanonicalJson } from \"../utils/serialization/canonical_json\";\nimport { act_impl_meteor_connect_demo } from \"./actions/impl/act_impl_meteor_connect_demo\";\nimport { act_impl_meteor_wallet_core } from \"./actions/impl/act_impl_meteor_wallet_core\";\nimport { act_impl_near } from \"./actions/impl/act_impl_near\";\n\n/**\n * Server-authoritative per-action security policy. The bridge Durable Object — not the partner —\n * consults this registry at bridge creation, claim, notify, and realm projection. Partner-supplied\n * requirements can only ADD strictness on top of what is declared here.\n *\n * Every action of a first-party domain must make an explicit policy choice — the `satisfies\n * Record<keyof …, TActionPolicy>` maps below turn a missing entry into a compile error.\n */\n\nexport type TActionDeliveryMode = \"claim_response\" | \"post_pin_wallet_encrypted\";\nexport type TActionMinimumSessionAuthorization = \"trusted_link\" | \"fresh_pin\";\nexport type TActionResourceProfile = `${ESessionResourceProfile}`;\n\n/**\n * Prepended to the plaintext before the DO encrypts a `post_pin_wallet_encrypted` action request\n * to the claiming wallet, and verified/stripped by the wallet client on decrypt. Cheap context\n * binding: the envelope shares its derived AES key with the other bridge-link ciphertexts\n * (`pinCodeEncrypted`, `bridgeSaltEncrypted`, …), so the tag pins what this one is.\n */\nexport const ACTION_REQUEST_ENVELOPE_PURPOSE_TAG = \"action_request::\";\n\ninterface IActionPolicyShared {\n  requiredWalletCapabilities: readonly EWalletProtocolCapability[];\n  allowedResourceProfiles: readonly TActionResourceProfile[];\n}\n\n/**\n * Delivery mode and minimum session authorization are COUPLED, not independent knobs.\n * `post_pin_wallet_encrypted` means \"the DO hands this to the wallet only after a PIN verified on\n * this bridge\", so a policy asking for the encrypted envelope while allowing the trusted PIN-skip\n * fast path would be self-contradictory — and worse, that fast path returns the PLAINTEXT action.\n *\n * Encoding it as a discriminated union makes the bad combination a compile error under the\n * `satisfies Record<…>` maps below, instead of an invariant every future action has to remember.\n */\nexport type TActionPolicy =\n  | (IActionPolicyShared & {\n      delivery: \"claim_response\";\n      minimumSessionAuthorization: TActionMinimumSessionAuthorization;\n    })\n  | (IActionPolicyShared & {\n      delivery: \"post_pin_wallet_encrypted\";\n      minimumSessionAuthorization: \"fresh_pin\";\n    });\n\nconst STANDARD_ACTION_POLICY: TActionPolicy = {\n  minimumSessionAuthorization: \"trusted_link\",\n  requiredWalletCapabilities: [],\n  allowedResourceProfiles: [\n    ESessionResourceProfile.single_turn_v1,\n    ESessionResourceProfile.interactive_v1,\n  ],\n  delivery: \"claim_response\",\n};\n\n/**\n * Recognized first-party domain but unknown action id. Creation-time rejection lives in\n * {@link validateKnownFirstPartyActionRequest}; this policy only defends claim/notify re-checks\n * over persisted state — and it fails closed.\n */\nconst FAIL_CLOSED_ACTION_POLICY: TActionPolicy = {\n  minimumSessionAuthorization: \"fresh_pin\",\n  requiredWalletCapabilities: [],\n  allowedResourceProfiles: [],\n  delivery: \"post_pin_wallet_encrypted\",\n};\n\nconst nearActionPolicies = {\n  sign_in: STANDARD_ACTION_POLICY,\n  sign_in_and_sign_message: STANDARD_ACTION_POLICY,\n  sign_out: STANDARD_ACTION_POLICY,\n  sign_message: STANDARD_ACTION_POLICY,\n  sign_and_send_transaction: STANDARD_ACTION_POLICY,\n  sign_and_send_transactions: STANDARD_ACTION_POLICY,\n  sign_delegate_actions: STANDARD_ACTION_POLICY,\n  verify_owner: STANDARD_ACTION_POLICY,\n} satisfies Record<keyof (typeof act_impl_near)[\"actionSchema\"], TActionPolicy>;\n\nconst meteorWalletCoreActionPolicies = {\n  transfer_accounts: {\n    minimumSessionAuthorization: \"fresh_pin\",\n    requiredWalletCapabilities: [EWalletProtocolCapability.transfer_accounts_v1],\n    allowedResourceProfiles: [ESessionResourceProfile.single_turn_v1],\n    delivery: \"post_pin_wallet_encrypted\",\n  },\n  new_key_account_transfer_start: {\n    // Unlike `transfer_accounts`, no signing secret ever crosses this bridge — the wallet mints\n    // keys locally and returns only their PUBLIC halves — so it carries the same trusted-link\n    // policy as the standard actions and its own verify turn: the PIN ceremony runs only when\n    // no live trusted link exists between this partner and the claiming wallet.\n    minimumSessionAuthorization: \"trusted_link\",\n    requiredWalletCapabilities: [EWalletProtocolCapability.new_key_account_transfer_v1],\n    allowedResourceProfiles: [ESessionResourceProfile.external_work_v1],\n    delivery: \"claim_response\",\n  },\n  new_key_account_transfer_verify_active: {\n    minimumSessionAuthorization: \"trusted_link\",\n    requiredWalletCapabilities: [EWalletProtocolCapability.new_key_account_transfer_v1],\n    allowedResourceProfiles: [\n      ESessionResourceProfile.single_turn_v1,\n      ESessionResourceProfile.external_work_v1,\n    ],\n    delivery: \"claim_response\",\n  },\n} satisfies Record<keyof (typeof act_impl_meteor_wallet_core)[\"actionSchema\"], TActionPolicy>;\n\nconst meteorConnectDemoActionPolicies = {\n  review_session_message: {\n    minimumSessionAuthorization: \"trusted_link\",\n    requiredWalletCapabilities: [EWalletProtocolCapability.session_demo_review_v1],\n    allowedResourceProfiles: [\n      ESessionResourceProfile.single_turn_v1,\n      ESessionResourceProfile.interactive_v1,\n    ],\n    delivery: \"claim_response\",\n  },\n} satisfies Record<keyof (typeof act_impl_meteor_connect_demo)[\"actionSchema\"], TActionPolicy>;\n\n/**\n * The per-domain tables are object LITERALS so `satisfies Record<keyof actionSchema, …>` can\n * compile-enforce exhaustiveness — but they must never be looked up by bracket index. Ids like\n * `__proto__`, `constructor` or `toString` resolve to inherited members that are non-null, which\n * sails past a `policy == null` fail-closed branch and yields an object whose\n * `minimumSessionAuthorization` is `undefined` and whose `delivery` is not\n * `post_pin_wallet_encrypted` — the most permissive policy possible, from the very lookup whose job\n * is to fail closed.\n *\n * `Object.entries` copies own enumerable keys only, and `Map.get` has no prototype chain, so\n * converting here removes the whole bug class rather than guarding against it. The outer domain\n * lookup was already a Map and was never affected.\n */\nconst toPolicyLookup = (\n  policies: Record<string, TActionPolicy>,\n): ReadonlyMap<string, TActionPolicy> => new Map(Object.entries(policies));\n\nconst firstPartyDomainPolicies: ReadonlyMap<string, ReadonlyMap<string, TActionPolicy>> = new Map<\n  string,\n  ReadonlyMap<string, TActionPolicy>\n>([\n  [act_impl_near.domain, toPolicyLookup(nearActionPolicies)],\n  [act_impl_meteor_wallet_core.domain, toPolicyLookup(meteorWalletCoreActionPolicies)],\n  [act_impl_meteor_connect_demo.domain, toPolicyLookup(meteorConnectDemoActionPolicies)],\n]);\n\n/**\n * Last line of defence on a resolved registry entry: only a structurally complete policy is\n * honoured, so anything unexpected degrades to {@link FAIL_CLOSED_ACTION_POLICY} rather than to a\n * partially-`undefined` object whose falsy fields read as \"no PIN needed, plaintext delivery\".\n */\nconst isWellFormedActionPolicy = (policy: unknown): policy is TActionPolicy => {\n  if (policy == null || typeof policy !== \"object\") {\n    return false;\n  }\n  const candidate: {\n    minimumSessionAuthorization?: unknown;\n    requiredWalletCapabilities?: unknown;\n    allowedResourceProfiles?: unknown;\n    delivery?: unknown;\n  } = policy;\n  return (\n    (candidate.minimumSessionAuthorization === \"trusted_link\" ||\n      candidate.minimumSessionAuthorization === \"fresh_pin\") &&\n    Array.isArray(candidate.requiredWalletCapabilities) &&\n    Array.isArray(candidate.allowedResourceProfiles) &&\n    candidate.allowedResourceProfiles.every(\n      (profile) =>\n        profile === ESessionResourceProfile.single_turn_v1 ||\n        profile === ESessionResourceProfile.interactive_v1 ||\n        profile === ESessionResourceProfile.external_work_v1,\n    ) &&\n    (candidate.delivery === \"claim_response\" ||\n      (candidate.delivery === \"post_pin_wallet_encrypted\" &&\n        candidate.minimumSessionAuthorization === \"fresh_pin\"))\n  );\n};\n\n/**\n * Unrecognized (third-party) domains and nullish input use the generic action policy; a recognized\n * first-party domain with an unknown id fails closed instead.\n */\nexport const getActionPolicy = (\n  action: { domain?: string; id?: string } | null | undefined,\n): TActionPolicy => {\n  if (action == null || action.domain == null || action.id == null) {\n    return STANDARD_ACTION_POLICY;\n  }\n\n  const domainPolicies = firstPartyDomainPolicies.get(action.domain);\n  if (domainPolicies == null) {\n    return STANDARD_ACTION_POLICY;\n  }\n\n  // Map lookup (see `toPolicyLookup`): prototype-key ids resolve to `undefined` here, not to an\n  // inherited member. The shape check then makes anything unexpected degrade to fail-closed rather\n  // than to a partially-`undefined` object whose falsy fields read as \"no PIN, plaintext delivery\".\n  const policy = domainPolicies.get(action.id);\n  if (!isWellFormedActionPolicy(policy)) {\n    return FAIL_CLOSED_ACTION_POLICY;\n  }\n\n  return policy;\n};\n\n/** Server-owned D35 gate; partner profile selection may only reduce to an allowed profile. */\nexport const isActionResourceProfileAllowed = (\n  action: { domain?: string; id?: string } | null | undefined,\n  profile: ESessionResourceProfile,\n): boolean => getActionPolicy(action).allowedResourceProfiles.includes(profile);\n\nexport const actionRequiresFreshPin = (\n  action: { domain?: string; id?: string } | null | undefined,\n): boolean => getActionPolicy(action).minimumSessionAuthorization === \"fresh_pin\";\n\nexport const getActionMinimumSessionAuthorization = (\n  action: { domain?: string; id?: string } | null | undefined,\n): TActionMinimumSessionAuthorization => getActionPolicy(action).minimumSessionAuthorization;\n\nexport const getActionAllowedResourceProfiles = (\n  action: { domain?: string; id?: string } | null | undefined,\n): readonly TActionResourceProfile[] => getActionPolicy(action).allowedResourceProfiles;\n\nexport const getServerRequiredWalletCapabilities = (\n  action: { domain?: string; id?: string } | null | undefined,\n): readonly EWalletProtocolCapability[] => getActionPolicy(action).requiredWalletCapabilities;\n\nexport const actionRequiresWalletEncryptedDelivery = (\n  action: { domain?: string; id?: string } | null | undefined,\n): boolean => getActionPolicy(action).delivery === \"post_pin_wallet_encrypted\";\n\n/**\n * Domain-agnostic serialized-size cap applied to EVERY incoming `actionRequest` at bridge\n * creation, unknown domains included — first-party payload bounds must not be dodgeable by\n * relabeling the domain. Sized against the transport chain documented in\n * `act_impl_meteor_wallet_core.schemas.ts`.\n */\nexport const MAX_ACTION_REQUEST_CANONICAL_JSON_LENGTH = 400_000;\n\nexport type TActionRequestValidationResult =\n  | {\n      ok: true;\n      /**\n       * The request to STORE, with a recognized first-party `input` replaced by the valibot-validated\n       * output. Callers should persist this rather than the raw wire object, so what gets stored,\n       * relayed and encrypted to the wallet is the value that was actually checked.\n       *\n       * Identical to the input for unrecognized domains (nothing to validate against) — the\n       * domain-agnostic size cap still applied.\n       */\n      validatedRequest: IActionPayload_Request_JsonObject;\n    }\n  | { ok: false; reason: \"request_too_large\" | \"invalid_first_party_request\" };\n\n// The action library does not expose an erased wire-payload overload for this registry boundary.\n// Resolve its runtime methods reflectively, validate their shape, then immediately pass the\n// hydrated value through the concrete action schema. This keeps the boundary honest without\n// pretending a generic wire request is a domain-specific type via `as never`.\nconst buildFirstPartyRequestValidator = (domainImpl: object & { domain: string }) => {\n  const hydrateRequestPayload = Reflect.get(domainImpl, \"hydrateRequestPayload\");\n  const actionForId = Reflect.get(domainImpl, \"actionForId\");\n  if (typeof hydrateRequestPayload !== \"function\" || typeof actionForId !== \"function\") {\n    throw new Error(`First-party action domain ${domainImpl.domain} lacks its runtime validators`);\n  }\n  return (request: IActionPayload_Request_JsonObject): unknown => {\n    const hydrated: unknown = Reflect.apply(hydrateRequestPayload, domainImpl, [request]);\n    if (hydrated == null || typeof hydrated !== \"object\") {\n      throw new Error(`First-party action domain ${domainImpl.domain} returned no hydrated input`);\n    }\n    const action: unknown = Reflect.apply(actionForId, domainImpl, [request.id]);\n    if (action == null || typeof action !== \"object\") {\n      throw new Error(`First-party action domain ${domainImpl.domain} returned no action schema`);\n    }\n    const validateInput = Reflect.get(action, \"validateInput\");\n    if (typeof validateInput !== \"function\") {\n      throw new Error(`First-party action domain ${domainImpl.domain} action lacks validation`);\n    }\n    // `validateInput` returns the parsed/stripped value — previously discarded, so the object that\n    // got persisted was the raw partner-supplied one (schemas are `v.object`, not `v.strictObject`,\n    // so unknown keys survived). Returning it lets the caller store what it checked.\n    return Reflect.apply(validateInput, action, [Reflect.get(hydrated, \"input\")]);\n  };\n};\n\nconst firstPartyRequestValidators: ReadonlyMap<\n  string,\n  (request: IActionPayload_Request_JsonObject) => unknown\n> = new Map([\n  [act_impl_near.domain, buildFirstPartyRequestValidator(act_impl_near)],\n  [\n    act_impl_meteor_connect_demo.domain,\n    buildFirstPartyRequestValidator(act_impl_meteor_connect_demo),\n  ],\n  [\n    act_impl_meteor_wallet_core.domain,\n    buildFirstPartyRequestValidator(act_impl_meteor_wallet_core),\n  ],\n]);\n\n/**\n * Bridge-creation gate: enforces the domain-agnostic size cap on every request, then — for\n * recognized first-party domains — hydrates the request through its real action domain and\n * validates the input against the action's schema, so a handcrafted partner payload cannot bypass\n * the versioned/bounded transfer schemas. Unknown domains keep generic-envelope validation only.\n *\n * On success it returns `validatedRequest`: the request with a first-party `input` replaced by the\n * schema's own output. Callers must persist THAT, not the object they passed in — the schemas are\n * `v.object` rather than `v.strictObject`, so unknown keys on the raw wire object survive\n * validation and would otherwise be stored, relayed, and encrypted to the wallet unchecked.\n *\n * Deliberately not `v.strictObject`: generic action payloads may carry extension fields that the\n * current first-party schema does not retain. Named fields are bounded; unknown keys are counted\n * against the size cap and then dropped before storage or relay.\n */\nexport const validateKnownFirstPartyActionRequest = (\n  actionRequest: IActionPayload_Request_JsonObject,\n): TActionRequestValidationResult => {\n  const serializedBytes = new TextEncoder().encode(\n    stringifyCanonicalJson(actionRequest),\n  ).byteLength;\n  if (serializedBytes > MAX_ACTION_REQUEST_CANONICAL_JSON_LENGTH) {\n    return { ok: false, reason: \"request_too_large\" };\n  }\n\n  const validator = firstPartyRequestValidators.get(actionRequest.domain);\n  if (validator == null) {\n    return { ok: true, validatedRequest: actionRequest };\n  }\n\n  let validatedInput: unknown;\n  try {\n    validatedInput = validator(actionRequest);\n  } catch {\n    return { ok: false, reason: \"invalid_first_party_request\" };\n  }\n\n  return { ok: true, validatedRequest: { ...actionRequest, input: validatedInput } };\n};\n","import * as v from \"valibot\";\nimport {\n  hashCanonicalJsonSha256Base64,\n  stringifyCanonicalJson,\n} from \"../../../utils/serialization/canonical_json\";\nimport {\n  type TAccountTransferDataDecrypted,\n  vAccountTransferDataDecrypted,\n} from \"./act_impl_meteor_wallet_core.schemas\";\n\nexport const ACCOUNT_IMPORT_RECORD_FORMAT_VERSION = 3;\n\n/**\n * How many receipts keep their full per-account evidence.\n *\n * This is a WORKING SET, not a lifetime ceiling. Format v2 kept every completed receipt forever in\n * one bounded array of 64 and refused the 65th transfer permanently — correct about never making an\n * old `clientTransferId` replayable, wrong about what that requires\n * (REVIEW-consumer-implementation B-03). Detailed rows are only needed while a transfer is live or\n * freshly completed; replay safety only needs the id and the account-set hash.\n */\nexport const ACCOUNT_IMPORT_MAX_ACTIVE_RECEIPTS = 64;\n\n/**\n * How many archived replay fences are retained. Each is ~80 bytes against a full receipt's ~1 KB,\n * so the whole archive stays inside a single storage slot while covering orders of magnitude more\n * transfers than any real wallet profile performs. Exhausting it fails closed as\n * `archive_capacity_exceeded` — an old transfer id is never silently made valid again.\n */\nexport const ACCOUNT_IMPORT_MAX_ARCHIVED_RECEIPTS = 4_096;\n\n/** @deprecated Format v2's single combined bound. Use {@link ACCOUNT_IMPORT_MAX_ACTIVE_RECEIPTS}. */\nexport const ACCOUNT_IMPORT_MAX_RECEIPTS = ACCOUNT_IMPORT_MAX_ACTIVE_RECEIPTS;\n\nconst vReceiptId = v.pipe(v.string(), v.minLength(22), v.maxLength(128));\nconst vHash = v.pipe(v.string(), v.regex(/^[A-Za-z0-9+/]{43}=$/u));\n\nconst vAccountImportReceiptRow = v.strictObject({\n  accountKey: v.pipe(v.string(), v.minLength(1), v.maxLength(256)),\n  accountDataHash: vHash,\n  outcome: v.picklist([\"imported\", \"replaced\", \"already_present\"]),\n});\n\nexport const vAccountImportReceipt = v.strictObject({\n  clientTransferId: vReceiptId,\n  canonicalAccountSetHash: vHash,\n  status: v.picklist([\"prepared\", \"completed\"]),\n  rows: v.pipe(v.array(vAccountImportReceiptRow), v.minLength(1), v.maxLength(50)),\n});\n\n/**\n * A completed receipt reduced to its replay identity. Keeping the account-set hash is what lets a\n * conflicting reuse of an archived id still be caught as `transfer_id_conflict` rather than\n * degrading into a generic \"already done\".\n */\nexport const vArchivedAccountImportReceipt = v.strictObject({\n  clientTransferId: vReceiptId,\n  canonicalAccountSetHash: vHash,\n});\n\nexport const vAccountImportRecord = v.strictObject({\n  formatVersion: v.literal(ACCOUNT_IMPORT_RECORD_FORMAT_VERSION),\n  accounts: v.pipe(v.array(vAccountTransferDataDecrypted), v.maxLength(500)),\n  receipts: v.pipe(v.array(vAccountImportReceipt), v.maxLength(ACCOUNT_IMPORT_MAX_ACTIVE_RECEIPTS)),\n  archivedReceipts: v.pipe(\n    v.array(vArchivedAccountImportReceipt),\n    v.maxLength(ACCOUNT_IMPORT_MAX_ARCHIVED_RECEIPTS),\n  ),\n});\n\n/** The format v2 record shape, accepted only by {@link migrateAccountImportRecord}. */\nconst vAccountImportRecordV2 = v.strictObject({\n  formatVersion: v.literal(2),\n  accounts: v.pipe(v.array(vAccountTransferDataDecrypted), v.maxLength(500)),\n  receipts: v.pipe(v.array(vAccountImportReceipt), v.maxLength(64)),\n});\n\nexport type TAccountImportReceipt = v.InferOutput<typeof vAccountImportReceipt>;\nexport type TArchivedAccountImportReceipt = v.InferOutput<typeof vArchivedAccountImportReceipt>;\nexport type TAccountImportRecord = v.InferOutput<typeof vAccountImportRecord>;\n\nexport const emptyAccountImportRecord = (): TAccountImportRecord => ({\n  formatVersion: ACCOUNT_IMPORT_RECORD_FORMAT_VERSION,\n  accounts: [],\n  receipts: [],\n  archivedReceipts: [],\n});\n\nconst archiveOf = (receipt: TAccountImportReceipt): TArchivedAccountImportReceipt => ({\n  clientTransferId: receipt.clientTransferId,\n  canonicalAccountSetHash: receipt.canonicalAccountSetHash,\n});\n\n/**\n * Make room for one more receipt by archiving the OLDEST completed ones.\n *\n * Only `completed` receipts may be archived: a `prepared` receipt is live recovery state whose rows\n * a commit still has to match. Insertion order is the archive order, so the receipts a host is most\n * likely to replay stay whole.\n *\n * Returns `null` when no room can be made — either every retained receipt is still `prepared`\n * (`receipt_capacity_exceeded`) or the archive itself is full (`archive_capacity_exceeded`).\n */\nconst withRoomForOneMoreReceipt = (\n  record: TAccountImportRecord,\n): { record: TAccountImportRecord } | { reason: TAccountImportCapacityReason } => {\n  if (record.receipts.length < ACCOUNT_IMPORT_MAX_ACTIVE_RECEIPTS) return { record };\n\n  const needed = record.receipts.length - ACCOUNT_IMPORT_MAX_ACTIVE_RECEIPTS + 1;\n  const archivable: TAccountImportReceipt[] = [];\n  for (const receipt of record.receipts) {\n    if (archivable.length === needed) break;\n    if (receipt.status === \"completed\") archivable.push(receipt);\n  }\n  if (archivable.length < needed) return { reason: \"receipt_capacity_exceeded\" };\n\n  if (record.archivedReceipts.length + archivable.length > ACCOUNT_IMPORT_MAX_ARCHIVED_RECEIPTS) {\n    return { reason: \"archive_capacity_exceeded\" };\n  }\n\n  const archivedIds = new Set(archivable.map((receipt) => receipt.clientTransferId));\n  return {\n    record: {\n      ...record,\n      receipts: record.receipts.filter((receipt) => !archivedIds.has(receipt.clientTransferId)),\n      archivedReceipts: [...record.archivedReceipts, ...archivable.map(archiveOf)],\n    },\n  };\n};\n\nexport type TAccountImportCapacityReason =\n  /** Every retained receipt is still `prepared`; nothing may be archived out from under a commit. */\n  | \"receipt_capacity_exceeded\"\n  /** The compact replay-fence archive is full. Never resolved by dropping a fence. */\n  | \"archive_capacity_exceeded\";\n\n/**\n * Upgrade a stored record to the current format, or return `null` if it is not a record at all.\n *\n * v2 → v3 keeps every receipt exactly as it was and adds an empty archive: a profile that never\n * reached the old ceiling is unchanged, and one that did now has somewhere for its completed\n * receipts to go on the next import. Call this on load, before any prepare/commit; the record\n * schemas deliberately refuse an unmigrated version rather than coercing it.\n */\nexport const migrateAccountImportRecord = (stored: unknown): TAccountImportRecord | null => {\n  const current = v.safeParse(vAccountImportRecord, stored);\n  if (current.success) return current.output;\n  const legacy = v.safeParse(vAccountImportRecordV2, stored);\n  if (!legacy.success) return null;\n  return {\n    formatVersion: ACCOUNT_IMPORT_RECORD_FORMAT_VERSION,\n    accounts: legacy.output.accounts,\n    receipts: legacy.output.receipts,\n    archivedReceipts: [],\n  };\n};\n\n/** An archived receipt for this id, if the detailed one has already been retired. */\nconst findArchivedReceipt = (\n  record: TAccountImportRecord,\n  clientTransferId: string,\n): TArchivedAccountImportReceipt | undefined =>\n  record.archivedReceipts.find((receipt) => receipt.clientTransferId === clientTransferId);\n\nexport const accountImportKey = (account: {\n  blockchainId: string;\n  networkId: string;\n  accountId: string;\n}): string => `${account.blockchainId}::${account.networkId}::${account.accountId}`;\n\nconst compareUtf16 = (left: string, right: string): number =>\n  left < right ? -1 : left > right ? 1 : 0;\n\nconst canonicalAccount = (account: TAccountTransferDataDecrypted) => ({\n  blockchainId: account.blockchainId,\n  networkId: account.networkId,\n  accountId: account.accountId,\n  secret: [...account.secret].sort((left, right) =>\n    compareUtf16(stringifyCanonicalJson(left), stringifyCanonicalJson(right)),\n  ),\n});\n\nconst canonicalAccounts = (\n  accounts: readonly TAccountTransferDataDecrypted[],\n): TAccountTransferDataDecrypted[] =>\n  accounts\n    .map((account) => v.parse(vAccountTransferDataDecrypted, account))\n    .sort((left, right) => compareUtf16(accountImportKey(left), accountImportKey(right)))\n    .map(canonicalAccount);\n\nexport const hashAccountImportSet = (accounts: readonly TAccountTransferDataDecrypted[]): string =>\n  hashCanonicalJsonSha256Base64(canonicalAccounts(accounts));\n\nconst accountDataHash = (account: TAccountTransferDataDecrypted): string =>\n  hashCanonicalJsonSha256Base64(canonicalAccount(account));\n\nconst findReceipt = (\n  record: TAccountImportRecord,\n  clientTransferId: string,\n): TAccountImportReceipt | undefined =>\n  record.receipts.find((receipt) => receipt.clientTransferId === clientTransferId);\n\nconst receiptMatchesAuthoritativeAccounts = (\n  record: TAccountImportRecord,\n  receipt: TAccountImportReceipt,\n): boolean => {\n  const stored = new Map(record.accounts.map((account) => [accountImportKey(account), account]));\n  return receipt.rows.every((row) => {\n    const account = stored.get(row.accountKey);\n    return account != null && accountDataHash(account) === row.accountDataHash;\n  });\n};\n\nexport type TPrepareAccountImportResult =\n  | {\n      ok: true;\n      record: TAccountImportRecord;\n      receipt: TAccountImportReceipt;\n      disposition: \"prepared\" | \"already_prepared\" | \"already_completed\";\n    }\n  | {\n      ok: false;\n      reason:\n        | \"transfer_id_conflict\"\n        | \"completed_receipt_drift\"\n        /**\n         * This exact transfer completed, but its detailed receipt has been archived down to a\n         * replay fence. Treat it as done: do NOT import again. The per-account outcome rows are no\n         * longer retained, which is why this is not an `ok` disposition.\n         */\n        | \"already_completed_archived\"\n        | TAccountImportCapacityReason;\n    };\n\n/**\n * Prepare the durable intent before mutating account inventory. Persist the returned record before\n * calling {@link commitPreparedAccountImport}; a crash after this step is provably not-started.\n */\nexport const prepareAccountImport = (input: {\n  record: TAccountImportRecord;\n  clientTransferId: string;\n  accounts: readonly TAccountTransferDataDecrypted[];\n}): TPrepareAccountImportResult => {\n  const record = v.parse(vAccountImportRecord, input.record);\n  const accounts = canonicalAccounts(input.accounts);\n  const canonicalAccountSetHash = hashAccountImportSet(accounts);\n  const archived = findArchivedReceipt(record, input.clientTransferId);\n  if (archived != null) {\n    // The fence outlives the evidence. A different account set under a retired id is still a\n    // conflict — that is exactly what keeping the hash in the archive buys.\n    return {\n      ok: false,\n      reason:\n        archived.canonicalAccountSetHash === canonicalAccountSetHash\n          ? \"already_completed_archived\"\n          : \"transfer_id_conflict\",\n    };\n  }\n  const existing = findReceipt(record, input.clientTransferId);\n  if (existing != null) {\n    if (existing.canonicalAccountSetHash !== canonicalAccountSetHash) {\n      return { ok: false, reason: \"transfer_id_conflict\" };\n    }\n    if (existing.status === \"completed\" && !receiptMatchesAuthoritativeAccounts(record, existing)) {\n      return { ok: false, reason: \"completed_receipt_drift\" };\n    }\n    return {\n      ok: true,\n      record,\n      receipt: existing,\n      disposition: existing.status === \"completed\" ? \"already_completed\" : \"already_prepared\",\n    };\n  }\n\n  // Completed receipts are the durable replay fence: dropping one would make its\n  // clientTransferId valid again. Archiving is not dropping — the id and the account-set hash are\n  // retained, only the per-account rows are retired — so the working set can roll forward without\n  // ever weakening replay or conflict detection.\n  const roomed = withRoomForOneMoreReceipt(record);\n  if (!(\"record\" in roomed)) return { ok: false, reason: roomed.reason };\n  const rolled = roomed.record;\n\n  const currentAccounts = new Map(\n    rolled.accounts.map((account) => [accountImportKey(account), account]),\n  );\n  const receipt: TAccountImportReceipt = {\n    clientTransferId: input.clientTransferId,\n    canonicalAccountSetHash,\n    status: \"prepared\",\n    rows: accounts.map((account) => {\n      const current = currentAccounts.get(accountImportKey(account));\n      return {\n        accountKey: accountImportKey(account),\n        accountDataHash: accountDataHash(account),\n        outcome:\n          current == null\n            ? \"imported\"\n            : accountDataHash(current) === accountDataHash(account)\n              ? \"already_present\"\n              : \"replaced\",\n      };\n    }),\n  };\n  return {\n    ok: true,\n    disposition: \"prepared\",\n    receipt,\n    record: {\n      ...rolled,\n      receipts: [...rolled.receipts, receipt],\n    },\n  };\n};\n\nexport type TCommitAccountImportResult =\n  | {\n      ok: true;\n      record: TAccountImportRecord;\n      receipt: TAccountImportReceipt;\n      disposition: \"completed\" | \"already_completed\";\n    }\n  | {\n      ok: false;\n      reason:\n        | \"receipt_missing\"\n        | \"transfer_id_conflict\"\n        | \"completed_receipt_drift\"\n        | \"prepared_receipt_mismatch\"\n        /** Completed earlier and archived down to a replay fence; nothing left to commit. */\n        | \"already_completed_archived\";\n    };\n\n/** Atomically materialize account inventory and the completed receipt in one persisted record. */\nexport const commitPreparedAccountImport = (input: {\n  record: TAccountImportRecord;\n  clientTransferId: string;\n  accounts: readonly TAccountTransferDataDecrypted[];\n}): TCommitAccountImportResult => {\n  const record = v.parse(vAccountImportRecord, input.record);\n  const accounts = canonicalAccounts(input.accounts);\n  const canonicalAccountSetHash = hashAccountImportSet(accounts);\n  const receipt = findReceipt(record, input.clientTransferId);\n  if (receipt == null) {\n    const archived = findArchivedReceipt(record, input.clientTransferId);\n    if (archived == null) return { ok: false, reason: \"receipt_missing\" };\n    return {\n      ok: false,\n      reason:\n        archived.canonicalAccountSetHash === canonicalAccountSetHash\n          ? \"already_completed_archived\"\n          : \"transfer_id_conflict\",\n    };\n  }\n  if (receipt.canonicalAccountSetHash !== canonicalAccountSetHash) {\n    return { ok: false, reason: \"transfer_id_conflict\" };\n  }\n  if (receipt.status === \"completed\") {\n    return receiptMatchesAuthoritativeAccounts(record, receipt)\n      ? { ok: true, record, receipt, disposition: \"already_completed\" }\n      : { ok: false, reason: \"completed_receipt_drift\" };\n  }\n\n  const expectedRows = new Map(receipt.rows.map((row) => [row.accountKey, row.accountDataHash]));\n  if (\n    accounts.length !== expectedRows.size ||\n    accounts.some(\n      (account) => expectedRows.get(accountImportKey(account)) !== accountDataHash(account),\n    )\n  ) {\n    return { ok: false, reason: \"prepared_receipt_mismatch\" };\n  }\n\n  const incomingKeys = new Set(accounts.map(accountImportKey));\n  const completedReceipt: TAccountImportReceipt = { ...receipt, status: \"completed\" };\n  return {\n    ok: true,\n    disposition: \"completed\",\n    receipt: completedReceipt,\n    record: {\n      ...record,\n      accounts: [\n        ...record.accounts.filter((account) => !incomingKeys.has(accountImportKey(account))),\n        ...accounts,\n      ],\n      receipts: record.receipts.map((entry) =>\n        entry.clientTransferId === input.clientTransferId ? completedReceipt : entry,\n      ),\n    },\n  };\n};\n","import {\n  decryptJsonWithKeyString,\n  encryptJsonWithGeneratedKey,\n  type TKeyEncryptedDecryptResult,\n} from \"@meteorwallet/connect-core/util\";\nimport { hashes as ed25519Hashes, getPublicKey } from \"@noble/ed25519\";\nimport { hmac } from \"@noble/hashes/hmac.js\";\nimport { pbkdf2 } from \"@noble/hashes/pbkdf2.js\";\nimport { sha512 } from \"@noble/hashes/sha2.js\";\nimport { concatBytes } from \"@noble/hashes/utils.js\";\nimport { base58, base64urlnopad } from \"@scure/base\";\nimport * as v from \"valibot\";\nimport { vDurableObjectId } from \"../../../model/core/meteor_core.schema\";\nimport { vSerializedCryptoKeyDataEd25519_Raw } from \"../../../model/crypto/crypto.schema\";\nimport {\n  base64ToBytes,\n  bytesToBase64,\n  hashCanonicalJsonSha256Base64,\n  stringifyCanonicalJson,\n} from \"../../../utils/serialization/canonical_json\";\nimport {\n  NEW_KEY_ACCOUNT_TRANSFER_ID_RANDOM_BYTE_LENGTH,\n  type TAccountBasicData,\n  type TAccountSecretData,\n  type TAllAccountsTransferDataDecrypted,\n  type TAllAccountsTransferDataEncrypted,\n  type TNewKeyTransferStartInputV1,\n  type TNewKeyTransferStartOutputV1,\n  type TNewKeyTransferVerifyActiveInputV1,\n  type TNewKeyTransferVerifyActiveOutputV1,\n  TRANSFER_ACCOUNTS_FORMAT_VERSION,\n  TRANSFER_ACCOUNTS_ID_RANDOM_BYTE_LENGTH,\n  vAccountSecretData,\n  vAllAccountsTransferDataDecrypted,\n  vAllAccountsTransferDataEncrypted,\n  vNearEd25519PublicKey,\n  vNearTransactionHash,\n  vNewKeyTransferOpaqueId,\n  vNewKeyTransferStartInputV1,\n  vNewKeyTransferStartOutputV1,\n  vNewKeyTransferVerifyActiveInputV1,\n  vNewKeyTransferVerifyActiveOutputV1,\n} from \"./act_impl_meteor_wallet_core.schemas\";\n\nexport const METEOR_CONNECT_KEY_PREFIX = \"mck1\";\n\n/** NEAR's standard mnemonic derivation path — the default for mnemonic secrets built here. */\nexport const NEAR_DEFAULT_DERIVATION_PATH = \"m/44'/397'/0'\";\n\nconst NEAR_ED25519_PRIVATE_KEY_PREFIX = \"ed25519:\";\n\nconst textToBase64 = (text: string): string => bytesToBase64(new TextEncoder().encode(text));\n\nexport type TBuildAccountSecretDataResult =\n  | { ok: true; secret: TAccountSecretData }\n  | { ok: false; reason: \"empty_secret_input\" }\n  | { ok: false; reason: \"invalid_private_key\" }\n  | { ok: false; reason: \"invalid_mnemonic_word_count\"; wordCount: number }\n  | { ok: false; reason: \"invalid_secret_data\"; issueMessage: string };\n\nexport type TDeriveNearSigningKeyFromSecretResult =\n  | { ok: true; publicKey: string; privateKey: `ed25519:${string}` }\n  | {\n      ok: false;\n      reason: \"invalid_secret_encoding\" | \"invalid_derivation_path\" | \"invalid_private_key\";\n    };\n\n/**\n * The one shared raw-secret encoder: turns user-pasted input into a schema-valid\n * {@link TAccountSecretData} entry for `buildAccountsTransferRequestData`. Partner UIs and SDKs\n * must use this rather than mirroring the encoding rules locally.\n *\n * Auto-detects the secret kind: `ed25519:…` → private key, otherwise a mnemonic phrase (12 or 24\n * words, whitespace-normalized and lowercased). `derivationPath` applies to mnemonics only and\n * defaults to {@link NEAR_DEFAULT_DERIVATION_PATH}.\n *\n * Failures are typed reason codes (not display strings) so each consumer writes its own copy;\n * `invalid_secret_data` is the schema backstop (e.g. an over-length secret or derivation path).\n */\nexport const buildAccountSecretData = (input: {\n  secretInput: string;\n  derivationPath?: string;\n}): TBuildAccountSecretDataResult => {\n  const cleanSecret = input.secretInput.trim().replace(/\\s+/g, \" \");\n  if (cleanSecret.length === 0) {\n    return { ok: false, reason: \"empty_secret_input\" };\n  }\n\n  let candidate: TAccountSecretData;\n  if (cleanSecret.startsWith(NEAR_ED25519_PRIVATE_KEY_PREFIX)) {\n    if (cleanSecret.includes(\" \") || cleanSecret.length <= NEAR_ED25519_PRIVATE_KEY_PREFIX.length) {\n      return { ok: false, reason: \"invalid_private_key\" };\n    }\n    candidate = {\n      type: \"private_key\",\n      encoding: \"near_prefixed_utf8_base64\",\n      keyAlgorithm: \"ed25519\",\n      prefixedBase64DataString: `near_prefixed_utf8_base64::${textToBase64(cleanSecret)}`,\n    };\n  } else {\n    const wordCount = cleanSecret.split(\" \").length;\n    if (wordCount !== 12 && wordCount !== 24) {\n      return { ok: false, reason: \"invalid_mnemonic_word_count\", wordCount };\n    }\n    candidate = {\n      type: \"mnemonic\",\n      encoding: \"utf8_base64\",\n      derivationPath: input.derivationPath ?? NEAR_DEFAULT_DERIVATION_PATH,\n      prefixedBase64DataString: `utf8_base64::${textToBase64(cleanSecret.toLowerCase())}`,\n    };\n  }\n\n  const parsed = v.safeParse(vAccountSecretData, candidate);\n  if (!parsed.success) {\n    return {\n      ok: false,\n      reason: \"invalid_secret_data\",\n      issueMessage: parsed.issues[0].message,\n    };\n  }\n\n  return { ok: true, secret: parsed.output };\n};\n\nexport type TMeteorConnectKeyString = `mck1.${string}.${string}`;\n\n/** Generate the stable receipt identity for one existing-secret transfer attempt. */\nexport const createAccountTransferOpaqueId = (): string =>\n  base64urlnopad.encode(\n    crypto.getRandomValues(new Uint8Array(TRANSFER_ACCOUNTS_ID_RANDOM_BYTE_LENGTH)),\n  );\n\nconst isMeteorConnectKeyString = (value: string): value is TMeteorConnectKeyString =>\n  value.startsWith(`${METEOR_CONNECT_KEY_PREFIX}.`) && value.split(\".\").length === 3;\n\n/**\n * Canonical comparison key over exactly the three allowlisted preview fields. Both the derived\n * preview and the tamper-evidence check use this — never object spread, so a future secret-bearing\n * field can never leak into the plaintext preview.\n */\nconst basicInfoCanonicalKey = (info: {\n  blockchainId: TAccountBasicData[\"blockchainId\"];\n  networkId: TAccountBasicData[\"networkId\"];\n  accountId: string;\n}): string =>\n  stringifyCanonicalJson({\n    blockchainId: info.blockchainId,\n    networkId: info.networkId,\n    accountId: info.accountId,\n  });\n\n/**\n * Partner side: validates and bounds the v1 payload, encrypts it under a freshly generated\n * `mck1.*` key, and derives the plaintext preview by explicit allowlist mapping.\n *\n * `transferKeyString` must NEVER be put on the bridge — hold it in partner-local component state\n * only and hand it to the user via QR / copy after fresh PIN verification.\n */\nexport const buildAccountsTransferRequestData = async (input: {\n  decrypted: TAllAccountsTransferDataDecrypted;\n}): Promise<{\n  transferKeyString: TMeteorConnectKeyString;\n  actionInput: TAllAccountsTransferDataEncrypted;\n}> => {\n  const validatedDecrypted = v.parse(vAllAccountsTransferDataDecrypted, input.decrypted);\n\n  const encrypted = await encryptJsonWithGeneratedKey({\n    data: validatedDecrypted,\n    keyPrefix: METEOR_CONNECT_KEY_PREFIX,\n  });\n\n  if (!isMeteorConnectKeyString(encrypted.keyString)) {\n    throw new Error(\"Generated transfer key string is not in the mck1 format\");\n  }\n\n  const allAccountsBasicInfo: TAccountBasicData[] = validatedDecrypted.accounts.map((account) => ({\n    blockchainId: account.blockchainId,\n    networkId: account.networkId,\n    accountId: account.accountId,\n  }));\n\n  const actionInput = v.parse(vAllAccountsTransferDataEncrypted, {\n    formatVersion: TRANSFER_ACCOUNTS_FORMAT_VERSION,\n    clientTransferId: createAccountTransferOpaqueId(),\n    allAccountsBasicInfo,\n    encryptedData: encrypted.encryptedData,\n  });\n\n  return { transferKeyString: encrypted.keyString, actionInput };\n};\n\nexport type TAccountsTransferDecryptResult =\n  | { ok: true; data: TAllAccountsTransferDataDecrypted }\n  | {\n      ok: false;\n      reason: \"bad_key_string\" | \"decrypt_failed\" | \"invalid_payload\" | \"preview_mismatch\";\n    };\n\n/**\n * Wallet side: decrypts with the user-entered key, validates the plaintext against the v1 schema,\n * then compares the unauthenticated plaintext preview to the authenticated decrypted account list:\n * set equality over canonical JSON of the three allowlisted fields, PLUS a length check, so array\n * order differences are not a mismatch but multiplicity still is.\n *\n * The length check is load-bearing and cannot be dropped in favour of \"D7 rejects duplicates\":\n * that rule lives in `vAllAccountsTransferDataEncrypted`, which is applied at bridge creation to\n * the request as a whole — this function never applies it to `input.actionInput`. Without the\n * length comparison, a relay could duplicate a preview row (`[alice, bob]` → `[alice, bob, bob]`)\n * and the sets would still match.\n *\n * `preview_mismatch` is tamper-evidence, defense in depth: the approval gate is always the\n * decrypted data. UIs must block approval on mismatch rather than silently preferring either list.\n */\nexport const decryptAccountsTransferRequestData = async (input: {\n  transferKeyString: string;\n  actionInput: TAllAccountsTransferDataEncrypted;\n}): Promise<TAccountsTransferDecryptResult> => {\n  const result: TKeyEncryptedDecryptResult<TAllAccountsTransferDataDecrypted> =\n    await decryptJsonWithKeyString({\n      keyString: input.transferKeyString,\n      expectedKeyPrefix: METEOR_CONNECT_KEY_PREFIX,\n      encryptedData: input.actionInput.encryptedData,\n      schema: vAllAccountsTransferDataDecrypted,\n    });\n\n  if (!result.ok) {\n    return result;\n  }\n\n  const previewKeys = new Set(input.actionInput.allAccountsBasicInfo.map(basicInfoCanonicalKey));\n  const decryptedKeys = new Set(result.data.accounts.map(basicInfoCanonicalKey));\n\n  const previewMatchesDecrypted =\n    input.actionInput.allAccountsBasicInfo.length === result.data.accounts.length &&\n    previewKeys.size === decryptedKeys.size &&\n    [...previewKeys].every((key) => decryptedKeys.has(key));\n\n  if (!previewMatchesDecrypted) {\n    return { ok: false, reason: \"preview_mismatch\" };\n  }\n\n  return result;\n};\n\n// --- NEW-KEY ACCOUNT TRANSFER V1 --------------------------------------------\n\ntype TNewKeyTransferAccountIdentity = {\n  blockchainId: string;\n  networkId: string;\n  accountId: string;\n};\n\nexport const newKeyTransferAccountIdentityKey = (account: TNewKeyTransferAccountIdentity): string =>\n  `${account.blockchainId}::${account.networkId}::${account.accountId}`;\n\nconst compareNewKeyTransferAccounts = (\n  left: TNewKeyTransferAccountIdentity,\n  right: TNewKeyTransferAccountIdentity,\n): number => {\n  const leftKey = newKeyTransferAccountIdentityKey(left);\n  const rightKey = newKeyTransferAccountIdentityKey(right);\n  return leftKey < rightKey ? -1 : leftKey > rightKey ? 1 : 0;\n};\n\nconst hasSameNewKeyTransferAccountSet = (\n  expected: readonly TNewKeyTransferAccountIdentity[],\n  received: readonly TNewKeyTransferAccountIdentity[],\n): boolean => {\n  if (expected.length !== received.length) {\n    return false;\n  }\n  const expectedKeys = new Set(expected.map(newKeyTransferAccountIdentityKey));\n  const receivedKeys = new Set(received.map(newKeyTransferAccountIdentityKey));\n  return (\n    expectedKeys.size === expected.length &&\n    receivedKeys.size === received.length &&\n    [...expectedKeys].every((key) => receivedKeys.has(key))\n  );\n};\n\n/** Generate an opaque v1 transfer id from 128 CSPRNG bits in unpadded base64url form. */\nexport const createNewKeyTransferOpaqueId = (): string => {\n  const randomBytes = crypto.getRandomValues(\n    new Uint8Array(NEW_KEY_ACCOUNT_TRANSFER_ID_RANDOM_BYTE_LENGTH),\n  );\n  return base64urlnopad.encode(randomBytes);\n};\n\n/** Format raw 32-byte Ed25519 material as NEAR's canonical public-key string. */\nexport const formatNearEd25519PublicKey = (publicKeyBytes: Uint8Array): string => {\n  if (publicKeyBytes.length !== 32) {\n    throw new Error(\"NEAR Ed25519 public keys must contain exactly 32 bytes\");\n  }\n  return `ed25519:${base58.encode(publicKeyBytes)}`;\n};\n\n/** Format raw 32-byte NEAR transaction-hash material as canonical base58. */\nexport const formatNearTransactionHash = (transactionHashBytes: Uint8Array): string => {\n  if (transactionHashBytes.length !== 32) {\n    throw new Error(\"NEAR transaction hashes must contain exactly 32 bytes\");\n  }\n  return base58.encode(transactionHashBytes);\n};\n\nexport type TDeriveNearPublicKeyFromSecretResult =\n  | { ok: true; publicKey: string }\n  | {\n      ok: false;\n      reason: \"invalid_secret_encoding\" | \"invalid_private_key\" | \"invalid_derivation_path\";\n    };\n\nconst decodePrefixedSecretText = (input: {\n  value: string;\n  prefix: \"utf8_base64::\" | \"near_prefixed_utf8_base64::\";\n}): string | null => {\n  if (!input.value.startsWith(input.prefix)) return null;\n  try {\n    return new TextDecoder(\"utf-8\", { fatal: true }).decode(\n      base64ToBytes(input.value.slice(input.prefix.length)),\n    );\n  } catch {\n    return null;\n  }\n};\n\nconst getEd25519PublicKey = (privateSeed: Uint8Array): Uint8Array => {\n  // Noble deliberately requires callers of the synchronous API to select the SHA-512\n  // implementation. The assignment is idempotent and the implementation is immutable.\n  ed25519Hashes.sha512 ??= sha512;\n  return getPublicKey(privateSeed);\n};\n\nconst deriveSlip10Ed25519PrivateSeed = (\n  mnemonic: string,\n  derivationPath: string,\n): Uint8Array | null => {\n  const pathSegments = derivationPath.split(\"/\");\n  if (pathSegments[0] !== \"m\" || pathSegments.length < 2) return null;\n\n  const childIndexes: number[] = [];\n  for (const segment of pathSegments.slice(1)) {\n    const match = /^(0|[1-9][0-9]*)'$/.exec(segment);\n    if (match == null) return null;\n    const index = Number(match[1]);\n    if (!Number.isSafeInteger(index) || index > 0x7fffffff) return null;\n    childIndexes.push(index);\n  }\n\n  const normalizedMnemonic = mnemonic.trim().replace(/\\s+/g, \" \").normalize(\"NFKD\");\n  if (normalizedMnemonic.length === 0) return null;\n\n  const mnemonicSeed = pbkdf2(\n    sha512,\n    new TextEncoder().encode(normalizedMnemonic),\n    new TextEncoder().encode(\"mnemonic\"),\n    { c: 2048, dkLen: 64 },\n  );\n  let derived = hmac(sha512, new TextEncoder().encode(\"ed25519 seed\"), mnemonicSeed);\n  mnemonicSeed.fill(0);\n\n  let privateSeed = derived.slice(0, 32);\n  let chainCode = derived.slice(32);\n  derived.fill(0);\n\n  for (const childIndex of childIndexes) {\n    const serializedIndex = new Uint8Array(4);\n    new DataView(serializedIndex.buffer).setUint32(0, childIndex + 0x80000000, false);\n    const childData = concatBytes(Uint8Array.of(0), privateSeed, serializedIndex);\n    derived = hmac(sha512, chainCode, childData);\n    privateSeed.fill(0);\n    chainCode.fill(0);\n    childData.fill(0);\n    privateSeed = derived.slice(0, 32);\n    chainCode = derived.slice(32);\n    derived.fill(0);\n  }\n\n  chainCode.fill(0);\n  return privateSeed;\n};\n\n/**\n * Derive canonical NEAR signing material from one stored Ed25519 account secret. This is intended\n * for a local signer boundary only: callers must never serialize, persist, or log the private key.\n *\n * Mnemonics use BIP-39's empty-passphrase seed derivation followed by hardened SLIP-0010 Ed25519\n * derivation at the stored path. Private-key entries must contain NEAR's canonical 64-byte\n * seed-plus-public-key representation; their embedded public half is checked against the seed.\n */\nexport const deriveNearSigningKeyFromAccountSecret = (\n  secret: TAccountSecretData,\n): TDeriveNearSigningKeyFromSecretResult => {\n  if (secret.type === \"mnemonic\") {\n    const mnemonic = decodePrefixedSecretText({\n      value: secret.prefixedBase64DataString,\n      prefix: \"utf8_base64::\",\n    });\n    if (mnemonic == null) return { ok: false, reason: \"invalid_secret_encoding\" };\n    const privateSeed = deriveSlip10Ed25519PrivateSeed(mnemonic, secret.derivationPath);\n    if (privateSeed == null) return { ok: false, reason: \"invalid_derivation_path\" };\n    try {\n      const publicKeyBytes = getEd25519PublicKey(privateSeed);\n      const privateKeyBytes = concatBytes(privateSeed, publicKeyBytes);\n      try {\n        return {\n          ok: true,\n          publicKey: formatNearEd25519PublicKey(publicKeyBytes),\n          privateKey: `${NEAR_ED25519_PRIVATE_KEY_PREFIX}${base58.encode(privateKeyBytes)}`,\n        };\n      } finally {\n        privateKeyBytes.fill(0);\n      }\n    } finally {\n      privateSeed.fill(0);\n    }\n  }\n\n  const privateKey = decodePrefixedSecretText({\n    value: secret.prefixedBase64DataString,\n    prefix: \"near_prefixed_utf8_base64::\",\n  });\n  if (privateKey == null) return { ok: false, reason: \"invalid_secret_encoding\" };\n  if (!privateKey.startsWith(NEAR_ED25519_PRIVATE_KEY_PREFIX)) {\n    return { ok: false, reason: \"invalid_private_key\" };\n  }\n\n  try {\n    const privateKeyBytes = base58.decode(privateKey.slice(NEAR_ED25519_PRIVATE_KEY_PREFIX.length));\n    if (privateKeyBytes.length !== 64) {\n      privateKeyBytes.fill(0);\n      return { ok: false, reason: \"invalid_private_key\" };\n    }\n    const privateSeed = privateKeyBytes.slice(0, 32);\n    const embeddedPublicKey = privateKeyBytes.slice(32);\n    try {\n      const derivedPublicKey = getEd25519PublicKey(privateSeed);\n      if (!embeddedPublicKey.every((byte, index) => byte === derivedPublicKey[index])) {\n        return { ok: false, reason: \"invalid_private_key\" };\n      }\n      return {\n        ok: true,\n        publicKey: formatNearEd25519PublicKey(derivedPublicKey),\n        privateKey: `${NEAR_ED25519_PRIVATE_KEY_PREFIX}${base58.encode(privateKeyBytes)}`,\n      };\n    } finally {\n      privateKeyBytes.fill(0);\n      privateSeed.fill(0);\n      embeddedPublicKey.fill(0);\n    }\n  } catch {\n    return { ok: false, reason: \"invalid_private_key\" };\n  }\n};\n\n/**\n * Derive the public half of one stored NEAR Ed25519 account secret. This deliberately drops the\n * private half returned by {@link deriveNearSigningKeyFromAccountSecret}; use the signing helper\n * only in a local signer boundary and never serialize or log its result.\n */\nexport const deriveNearPublicKeyFromAccountSecret = (\n  secret: TAccountSecretData,\n): TDeriveNearPublicKeyFromSecretResult => {\n  const result = deriveNearSigningKeyFromAccountSecret(secret);\n  return result.ok ? { ok: true, publicKey: result.publicKey } : result;\n};\n\n/**\n * Validate and canonicalize a start request for the wallet's idempotency binding. Array order is\n * presentation-only, so complete rows are sorted by the protocol account tuple before hashing.\n */\nexport const canonicalizeNewKeyTransferStartInput = (\n  input: TNewKeyTransferStartInputV1,\n): TNewKeyTransferStartInputV1 => {\n  const validated = v.parse(vNewKeyTransferStartInputV1, input);\n  return {\n    formatVersion: validated.formatVersion,\n    clientTransferId: validated.clientTransferId,\n    accounts: [...validated.accounts].sort(compareNewKeyTransferAccounts),\n  };\n};\n\nexport const hashNewKeyTransferStartInput = (input: TNewKeyTransferStartInputV1): string =>\n  hashCanonicalJsonSha256Base64(canonicalizeNewKeyTransferStartInput(input));\n\n/** Fail-closed primitives for validating durable wallet/host journal fields without Valibot. */\nexport const isValidNewKeyTransferOpaqueId = (value: unknown): value is string =>\n  v.safeParse(vNewKeyTransferOpaqueId, value).success;\n\nexport const isValidNearEd25519PublicKey = (value: unknown): value is string =>\n  v.safeParse(vNearEd25519PublicKey, value).success;\n\nexport const isValidNearTransactionHash = (value: unknown): value is string =>\n  v.safeParse(vNearTransactionHash, value).success;\n\nexport const isValidMeteorConnectVerifyPublicKey = (value: unknown): value is string =>\n  v.safeParse(vSerializedCryptoKeyDataEd25519_Raw, value).success;\n\nexport const isValidMeteorConnectDurableObjectId = (value: unknown): value is string =>\n  v.safeParse(vDurableObjectId, value).success;\n\n/** Parse a stored standalone output when the original request is not available at load time. */\nexport const parseNewKeyTransferStartOutputV1 = (output: unknown): TNewKeyTransferStartOutputV1 =>\n  v.parse(vNewKeyTransferStartOutputV1, output);\n\n/**\n * SDK receive-boundary validation. Authorship/hash checks happen before this helper; this proves\n * the signed value also conforms to the action schema and describes exactly the requested rows.\n */\nexport const validateNewKeyTransferStartOutputForInput = (input: {\n  request: TNewKeyTransferStartInputV1;\n  output: unknown;\n}): TNewKeyTransferStartOutputV1 => {\n  const request = v.parse(vNewKeyTransferStartInputV1, input.request);\n  const output = v.parse(vNewKeyTransferStartOutputV1, input.output);\n  if (output.clientTransferId !== request.clientTransferId) {\n    throw new Error(\"New-key transfer start output clientTransferId mismatch\");\n  }\n  if (!hasSameNewKeyTransferAccountSet(request.accounts, output.accounts)) {\n    throw new Error(\"New-key transfer start output account set mismatch\");\n  }\n  return output;\n};\n\nexport const validateNewKeyTransferVerifyActiveOutputForInput = (input: {\n  request: TNewKeyTransferVerifyActiveInputV1;\n  output: unknown;\n}): TNewKeyTransferVerifyActiveOutputV1 => {\n  const request = v.parse(vNewKeyTransferVerifyActiveInputV1, input.request);\n  const output = v.parse(vNewKeyTransferVerifyActiveOutputV1, input.output);\n  if (output.transferSessionId !== request.transferSessionId) {\n    throw new Error(\"New-key transfer verify output transferSessionId mismatch\");\n  }\n  if (!hasSameNewKeyTransferAccountSet(request.activations, output.accounts)) {\n    throw new Error(\"New-key transfer verify output account set mismatch\");\n  }\n  return output;\n};\n","import * as v from \"valibot\";\nimport {\n  type TNewKeyTransferVerifyActiveIssueV1,\n  vCryptoGenericNetworkId,\n  vNearAccountId,\n  vNearEd25519PublicKey,\n  vNearTransactionHash,\n} from \"./act_impl_meteor_wallet_core.schemas\";\n\nexport const vNewKeyTransferNormalizedAddKeyAction = v.object({\n  type: v.literal(\"add_key\"),\n  publicKey: vNearEd25519PublicKey,\n  permission: v.picklist([\"full_access\", \"function_call\"]),\n});\n\nexport const vNewKeyTransferNormalizedOtherAction = v.object({\n  type: v.literal(\"other\"),\n  actionType: v.pipe(v.string(), v.minLength(1), v.maxLength(64)),\n});\n\nexport const vNewKeyTransferNormalizedTransactionAction = v.union([\n  vNewKeyTransferNormalizedAddKeyAction,\n  vNewKeyTransferNormalizedOtherAction,\n]);\n\nexport const vNewKeyTransferNormalizedDestinationAccess = v.union([\n  v.object({ exists: v.literal(false) }),\n  v.object({\n    exists: v.literal(true),\n    permission: v.picklist([\"full_access\", \"function_call\"]),\n  }),\n]);\n\n/**\n * Wallet-specific RPC adapters normalize provider/library response variants into this shape. The\n * authorization decision below is then identical in V1, V2, and the demos.\n */\nexport const vNewKeyTransferNormalizedAddKeyProof = v.object({\n  networkId: vCryptoGenericNetworkId,\n  finalExecutionStatus: v.picklist([\"final\", \"not_final\"]),\n  executionSucceeded: v.boolean(),\n  transactionHash: vNearTransactionHash,\n  signerId: vNearAccountId,\n  receiverId: vNearAccountId,\n  signerPublicKey: vNearEd25519PublicKey,\n  actions: v.pipe(\n    v.array(vNewKeyTransferNormalizedTransactionAction),\n    v.minLength(1),\n    v.maxLength(16),\n  ),\n  destinationAccess: vNewKeyTransferNormalizedDestinationAccess,\n});\n\nexport type TNewKeyTransferNormalizedAddKeyProof = v.InferOutput<\n  typeof vNewKeyTransferNormalizedAddKeyProof\n>;\n\nexport type TNewKeyTransferAddKeyProofResult =\n  | { verified: true }\n  | {\n      verified: false;\n      issue: Extract<\n        TNewKeyTransferVerifyActiveIssueV1,\n        | \"activation_not_found\"\n        | \"activation_not_full_access\"\n        | \"invalid_add_key_transaction\"\n        | \"source_signer_mismatch\"\n      >;\n    };\n\n/**\n * What the caller asserts the AddKey transaction must prove. `networkId` is load-bearing: it is the\n * check that stops a testnet transaction from authorizing a mainnet account, so a proof that omits\n * it can never verify.\n */\nexport interface INewKeyTransferAddKeyProofExpectation {\n  networkId: \"mainnet\" | \"testnet\";\n  accountId: string;\n  sourcePublicKey: string;\n  destinationPublicKey: string;\n  addKeyTransactionHash: string;\n}\n\n/**\n * Verify a normalized AddKey proof against what the transfer expects.\n *\n * `proof` is typed rather than `unknown` on purpose. This function's runtime parse is strict, so a\n * proof missing a field it has since gained fails as `invalid_add_key_transaction` — for every\n * account, permanently, with nothing to distinguish it from a genuinely bad transaction. When the\n * parameter was `unknown`, a host that hand-rolled its proof object got no compiler signal when the\n * schema grew `networkId`, and the break was invisible until it reached users. Build the proof with\n * {@link normalizeNearAddKeyProof} so the type tracks the schema, and the compiler tells you.\n *\n * The runtime parse still runs — the static type is a guard-rail, never the guarantee. For input\n * whose shape genuinely is not known at build time (a stored journal row, a value off the wire),\n * use {@link verifyNewKeyTransferAddKeyProofFromUnknown}, which is the same check with the\n * parameter widened and the risk stated at the call site.\n */\nexport const verifyNewKeyTransferAddKeyProof = (input: {\n  expected: INewKeyTransferAddKeyProofExpectation;\n  proof: TNewKeyTransferNormalizedAddKeyProof;\n}): TNewKeyTransferAddKeyProofResult => verifyNewKeyTransferAddKeyProofFromUnknown(input);\n\n/**\n * {@link verifyNewKeyTransferAddKeyProof} for a proof whose shape is not known at build time.\n * Identical checks; the only difference is that the caller has said so explicitly.\n */\nexport const verifyNewKeyTransferAddKeyProofFromUnknown = (input: {\n  expected: INewKeyTransferAddKeyProofExpectation;\n  proof: unknown;\n}): TNewKeyTransferAddKeyProofResult => {\n  const parsed = v.safeParse(vNewKeyTransferNormalizedAddKeyProof, input.proof);\n  if (!parsed.success) {\n    return { verified: false, issue: \"invalid_add_key_transaction\" };\n  }\n\n  const proof = parsed.output;\n  if (\n    proof.networkId !== input.expected.networkId ||\n    proof.finalExecutionStatus !== \"final\" ||\n    !proof.executionSucceeded ||\n    proof.transactionHash !== input.expected.addKeyTransactionHash ||\n    proof.signerId !== input.expected.accountId ||\n    proof.receiverId !== input.expected.accountId ||\n    proof.actions.length !== 1\n  ) {\n    return { verified: false, issue: \"invalid_add_key_transaction\" };\n  }\n\n  if (proof.signerPublicKey !== input.expected.sourcePublicKey) {\n    return { verified: false, issue: \"source_signer_mismatch\" };\n  }\n\n  const action = proof.actions[0];\n  if (action.type !== \"add_key\" || action.publicKey !== input.expected.destinationPublicKey) {\n    return { verified: false, issue: \"invalid_add_key_transaction\" };\n  }\n  if (action.permission !== \"full_access\") {\n    return { verified: false, issue: \"activation_not_full_access\" };\n  }\n  if (!proof.destinationAccess.exists) {\n    return { verified: false, issue: \"activation_not_found\" };\n  }\n  if (proof.destinationAccess.permission !== \"full_access\") {\n    return { verified: false, issue: \"activation_not_full_access\" };\n  }\n\n  return { verified: true };\n};\n","import * as v from \"valibot\";\nimport {\n  type TNewKeyTransferNormalizedAddKeyProof,\n  vNewKeyTransferNormalizedAddKeyProof,\n} from \"./new_key_account_transfer_proof\";\n\n/**\n * One shared normalizer from raw NEAR RPC shapes to the proof input that\n * `verifyNewKeyTransferAddKeyProof` consumes (A7). Both transfer roles need it: the source host\n * proves its own broadcast/reconciled AddKey reached exact finality, and the destination wallet\n * builds the same proof from its independent RPC lookup. Centralizing the mapping keeps the\n * exact-key/finality decision in ONE place — the verifier — instead of two hand-rolled raw-shape\n * assertions.\n *\n * Inputs are the raw JSON results of the NEAR RPC calls (`EXPERIMENTAL_tx_status`/`send_tx` with\n * FINAL wait, and `view_access_key_list` at final finality). The mapping is fail-closed: a result\n * that cannot be normalized is reported as such, never silently narrowed into a passing proof.\n */\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n  typeof value === \"object\" && value != null && !Array.isArray(value);\n\nconst vRawNearTransaction = v.object({\n  hash: v.string(),\n  signer_id: v.string(),\n  receiver_id: v.string(),\n  public_key: v.string(),\n  actions: v.array(v.unknown()),\n});\n\nconst vRawNearTransactionStatus = v.object({\n  final_execution_status: v.unknown(),\n  transaction: vRawNearTransaction,\n});\n\nconst vRawNearAccessKeyEntry = v.object({\n  public_key: v.string(),\n  access_key: v.object({ permission: v.unknown() }),\n});\n\nconst vRawNearAccessKeyList = v.object({ keys: v.array(v.unknown()) });\n\nexport type TNormalizeNearAddKeyProofFailure =\n  | \"malformed_transaction_status\"\n  | \"malformed_access_key_list\"\n  | \"proof_shape_invalid\";\n\nexport type TNormalizeNearAddKeyProofResult =\n  | { ok: true; proof: TNewKeyTransferNormalizedAddKeyProof }\n  | { ok: false; reason: TNormalizeNearAddKeyProofFailure };\n\nconst normalizeAction = (\n  action: unknown,\n): TNewKeyTransferNormalizedAddKeyProof[\"actions\"][number] | null => {\n  if (isRecord(action) && isRecord(action[\"AddKey\"])) {\n    const addKey = action[\"AddKey\"];\n    const publicKey = addKey[\"public_key\"];\n    if (typeof publicKey !== \"string\") return null;\n    const accessKey = addKey[\"access_key\"];\n    const permission = isRecord(accessKey) ? accessKey[\"permission\"] : undefined;\n    return {\n      type: \"add_key\",\n      publicKey,\n      permission: permission === \"FullAccess\" ? \"full_access\" : \"function_call\",\n    };\n  }\n  if (typeof action === \"string\") return { type: \"other\", actionType: action };\n  if (isRecord(action)) {\n    const [firstKey] = Object.keys(action);\n    return { type: \"other\", actionType: firstKey ?? \"Unknown\" };\n  }\n  return null;\n};\n\n/**\n * Normalize a raw NEAR transaction-status outcome plus the account's current access-key list into\n * the shared AddKey proof shape. The result is meant to feed `verifyNewKeyTransferAddKeyProof`,\n * which owns EVERY authorization decision (exact hash/signer/receiver, exactly-one-AddKey,\n * full-access destination, finality, execution success, destination-key liveness).\n */\nexport const normalizeNearAddKeyProof = (input: {\n  networkId: \"mainnet\" | \"testnet\";\n  destinationPublicKey: string;\n  /** Raw NEAR RPC transaction-status result (`send_tx` / `EXPERIMENTAL_tx_status`, FINAL wait). */\n  outcome: unknown;\n  /**\n   * Raw NEAR RPC `view_access_key_list` result for the account, at final finality: every page of\n   * it merged into one `{ keys }` object, or a `{ keys }` holding just the destination key's own\n   * entry (`view_access_key`) — only that key is read here.\n   */\n  accessKeys: unknown;\n}): TNormalizeNearAddKeyProofResult => {\n  const outcome = v.safeParse(vRawNearTransactionStatus, input.outcome);\n  if (!outcome.success) return { ok: false, reason: \"malformed_transaction_status\" };\n  const accessKeyList = v.safeParse(vRawNearAccessKeyList, input.accessKeys);\n  if (!accessKeyList.success) return { ok: false, reason: \"malformed_access_key_list\" };\n\n  const status = isRecord(input.outcome) ? input.outcome[\"status\"] : undefined;\n  const actions: TNewKeyTransferNormalizedAddKeyProof[\"actions\"] = [];\n  for (const rawAction of outcome.output.transaction.actions) {\n    const normalized = normalizeAction(rawAction);\n    if (normalized == null) return { ok: false, reason: \"malformed_transaction_status\" };\n    actions.push(normalized);\n  }\n\n  let destinationAccess: TNewKeyTransferNormalizedAddKeyProof[\"destinationAccess\"] = {\n    exists: false,\n  };\n  for (const rawEntry of accessKeyList.output.keys) {\n    const entry = v.safeParse(vRawNearAccessKeyEntry, rawEntry);\n    if (!entry.success || entry.output.public_key !== input.destinationPublicKey) continue;\n    destinationAccess = {\n      exists: true,\n      permission:\n        entry.output.access_key.permission === \"FullAccess\" ? \"full_access\" : \"function_call\",\n    };\n    break;\n  }\n\n  const candidate = {\n    networkId: input.networkId,\n    finalExecutionStatus:\n      outcome.output.final_execution_status === \"FINAL\"\n        ? (\"final\" as const)\n        : (\"not_final\" as const),\n    executionSucceeded: isRecord(status) && \"SuccessValue\" in status,\n    transactionHash: outcome.output.transaction.hash,\n    signerId: outcome.output.transaction.signer_id,\n    receiverId: outcome.output.transaction.receiver_id,\n    signerPublicKey: outcome.output.transaction.public_key,\n    actions,\n    destinationAccess,\n  };\n  const proof = v.safeParse(vNewKeyTransferNormalizedAddKeyProof, candidate);\n  if (!proof.success) return { ok: false, reason: \"proof_shape_invalid\" };\n  return { ok: true, proof: proof.output };\n};\n","/**\n * Durable state machines for the new-key account transfer (stabilization SD5 ordering).\n *\n * Meteor side — the load-bearing change from the pre-stabilization machine: the seed-phrase\n * backup states sit BEFORE `public_key_published`, so no destination public key is ever released\n * to the partner (and therefore no key ever reaches the chain) whose recovery phrase the user has\n * not confirmed in full (SD1/SD2). Import follows verification directly (SD3); the signed\n * `secured` result is produced only at/after `signer_imported`.\n *\n * Two deliberate branch edges:\n * - `key_stored -> public_key_published` is the Ledger path (backup-exempt per D9; the wallet\n *   must hold on-device confirmation evidence instead — SD2).\n * - `public_key_published -> signer_imported` is the SD9 guarded import: AddKey landed on-chain\n *   but `verify_active` never arrived and the partner is gone. The wallet may import after a live\n *   destination-FAK chain check, recording `provenance: \"unproven\"` in its journal beside the\n *   state; such accounts never qualify for source-key DeleteKey (no proven source key exists).\n *\n * MNW side — `verify_requested` resolves to `destination_secured` (row came back `secured`) or\n * `wallet_completion_pending` (row came back `verified_pending_completion`; re-verify later).\n * Source-cleanup remains separate facts per D12: `source_key_absent` is entered only from\n * on-chain observation at finality, never from a wallet claim.\n */\nexport const NEW_KEY_TRANSFER_METEOR_ACCOUNT_STATES = [\n  \"key_stored\",\n  \"backup_required\",\n  \"backed_up\",\n  \"public_key_published\",\n  \"activation_verified\",\n  \"signer_imported\",\n  \"removal_awaiting_consent\",\n  \"removal_submitted\",\n  \"source_key_absent\",\n] as const;\n\nexport type TNewKeyTransferMeteorAccountState =\n  (typeof NEW_KEY_TRANSFER_METEOR_ACCOUNT_STATES)[number];\n\nexport const NEW_KEY_TRANSFER_MNW_SESSION_STATES = [\n  \"created\",\n  \"start_requested\",\n  \"start_result_committed\",\n] as const;\n\nexport type TNewKeyTransferMnwSessionState = (typeof NEW_KEY_TRANSFER_MNW_SESSION_STATES)[number];\n\nexport const NEW_KEY_TRANSFER_MNW_ACCOUNT_STATES = [\n  \"add_key_intent\",\n  \"add_key_submitted\",\n  \"add_key_finalized\",\n  \"verify_requested\",\n  \"wallet_completion_pending\",\n  \"destination_secured\",\n  \"source_key_absent\",\n  \"local_source_cleaned\",\n] as const;\n\nexport type TNewKeyTransferMnwAccountState = (typeof NEW_KEY_TRANSFER_MNW_ACCOUNT_STATES)[number];\n\nconst meteorForwardTransitions: Record<\n  TNewKeyTransferMeteorAccountState,\n  readonly TNewKeyTransferMeteorAccountState[]\n> = {\n  key_stored: [\"backup_required\", \"public_key_published\"],\n  backup_required: [\"backed_up\"],\n  backed_up: [\"public_key_published\"],\n  public_key_published: [\"activation_verified\", \"signer_imported\"],\n  activation_verified: [\"signer_imported\"],\n  signer_imported: [\"removal_awaiting_consent\"],\n  removal_awaiting_consent: [\"removal_submitted\"],\n  removal_submitted: [\"source_key_absent\"],\n  source_key_absent: [],\n};\n\nconst mnwSessionForwardTransitions: Record<\n  TNewKeyTransferMnwSessionState,\n  readonly TNewKeyTransferMnwSessionState[]\n> = {\n  created: [\"start_requested\"],\n  start_requested: [\"start_result_committed\"],\n  start_result_committed: [],\n};\n\nconst mnwAccountForwardTransitions: Record<\n  TNewKeyTransferMnwAccountState,\n  readonly TNewKeyTransferMnwAccountState[]\n> = {\n  add_key_intent: [\"add_key_submitted\"],\n  add_key_submitted: [\"add_key_finalized\"],\n  add_key_finalized: [\"verify_requested\"],\n  verify_requested: [\"wallet_completion_pending\", \"destination_secured\"],\n  wallet_completion_pending: [\"destination_secured\"],\n  destination_secured: [\"source_key_absent\"],\n  source_key_absent: [\"local_source_cleaned\"],\n  local_source_cleaned: [],\n};\n\nexport const canAdvanceNewKeyTransferMeteorAccountState = (\n  from: TNewKeyTransferMeteorAccountState,\n  to: TNewKeyTransferMeteorAccountState,\n): boolean => meteorForwardTransitions[from].includes(to);\n\nexport const canAdvanceNewKeyTransferMnwSessionState = (\n  from: TNewKeyTransferMnwSessionState,\n  to: TNewKeyTransferMnwSessionState,\n): boolean => mnwSessionForwardTransitions[from].includes(to);\n\nexport const canAdvanceNewKeyTransferMnwAccountState = (\n  from: TNewKeyTransferMnwAccountState,\n  to: TNewKeyTransferMnwAccountState,\n): boolean => mnwAccountForwardTransitions[from].includes(to);\n","import { sha256 } from \"@noble/hashes/sha2.js\";\nimport { base32 } from \"@scure/base\";\nimport type { IAddKeyJournalJob, TAddKeyJournalEntry } from \"./new_key_transfer_add_key_journal\";\n\n/**\n * The public reconciliation contract for a FENCED new-key transfer (D33 / A7).\n *\n * A journaled `transaction_signed` AddKey whose start-result record is missing or damaged is\n * correctly fail-closed: the exact bytes may still land on-chain, so nothing new may be started\n * and the row must not be generically cleared. Before this module the only thing a host could see\n * was a single `orphanedSignedAddKey: boolean`, which is enough to refuse work and not enough to\n * do anything about it — every affected browser profile was permanently stranded\n * (REVIEW-consumer-implementation B-04).\n *\n * This module turns that fence into a state a host can actually resolve. It exposes:\n *\n * - {@link INewKeyTransferFencedOperation} — the non-secret evidence for one fenced operation.\n *   Deliberately NOT the signed transaction bytes: a host needs to know they exist and are\n *   replayable, never to handle them.\n * - {@link INewKeyTransferReconciliationReport} — what is fenced, why, and a stable support\n *   reference the user can quote.\n * - {@link TNewKeyTransferReconcileStatus} — the states the chain-backed state machine in\n *   `createAddKeyJournalRunner().reconcileFencedOperation()` can reach.\n *\n * The state machine itself lives with the runner because only the runner holds the chain seam.\n */\n\n/** Why the transfer surface is fenced. Both states refuse new work; only one carries evidence. */\nexport type TNewKeyTransferFenceReason =\n  /** One or more signed AddKey rows exist with no start-result record to bind them. */\n  | \"orphaned_signed_add_key\"\n  /**\n   * The journal could not be parsed. Evidence is unavailable, so no operation can be listed and\n   * the fence cannot be resolved automatically — this is the state that needs a support path.\n   */\n  | \"journal_unreadable\";\n\n/**\n * One fenced AddKey operation, in non-secret terms only.\n *\n * Every field here is already known to the wallet and the chain: account, the source key that\n * signed, the destination key that was granted, and the transaction hash. The signed bytes stay\n * inside the journal — `hasReplayableSignedTransaction` reports only that a rebroadcast is\n * possible.\n */\nexport interface INewKeyTransferFencedOperation {\n  transferSessionId: string;\n  blockchainId: \"near\";\n  networkId: \"mainnet\" | \"testnet\";\n  accountId: string;\n  sourcePublicKey: string;\n  destinationPublicKey: string;\n  /** `transaction_signed` may still land on-chain; `finalized` already did. */\n  phase: \"transaction_signed\" | \"finalized\";\n  transactionHash: string;\n  /** True while the exact signed bytes are retained and could be rebroadcast unchanged. */\n  hasReplayableSignedTransaction: boolean;\n}\n\nexport interface INewKeyTransferReconciliationReport {\n  /** True while this host must refuse to start or clear a transfer. */\n  fenced: boolean;\n  reason: TNewKeyTransferFenceReason | null;\n  /** Empty when `reason` is `journal_unreadable` — there is nothing safe to read. */\n  operations: readonly INewKeyTransferFencedOperation[];\n  /**\n   * A stable, non-secret reference for support. Derived from the fenced identities, so the same\n   * damaged profile always quotes the same string and two different profiles never collide.\n   * `null` when nothing is fenced.\n   */\n  supportReference: string | null;\n}\n\n/** What one pass of the chain-backed reconciliation state machine established. */\nexport type TNewKeyTransferReconcileStatus =\n  /** Proven exact and final on-chain. The row is now `finalized`; resume verification. */\n  | \"finalized\"\n  /**\n   * The transaction never took effect AND the destination key is absent at final finality.\n   * `archiveReconciledOperation` may now retire the row.\n   */\n  | \"destination_key_absent\"\n  /**\n   * The destination key IS on the account but no proof binds it to this transfer. It must be\n   * removed with the source signer, then proven absent, before the row can be retired.\n   */\n  | \"destination_key_present_unproven\"\n  /** Chain state could not be established this pass. Nothing changed; retry later. */\n  | \"ambiguous\"\n  /** No journal row matches this operation identity — it was already reconciled. */\n  | \"not_found\";\n\nexport interface INewKeyTransferReconcileResult {\n  status: TNewKeyTransferReconcileStatus;\n  operation: INewKeyTransferFencedOperation;\n  /** Present for `finalized`; the exact hash proven on-chain. */\n  transactionHash?: string;\n  /** Machine-readable detail for `ambiguous` / `destination_key_present_unproven`. */\n  detail?: string;\n}\n\nconst isProtectedEntry = (\n  entry: TAddKeyJournalEntry,\n): entry is Extract<TAddKeyJournalEntry, { phase: \"transaction_signed\" | \"finalized\" }> =>\n  entry.phase === \"transaction_signed\" || entry.phase === \"finalized\";\n\nconst toFencedOperation = (\n  entry: Extract<TAddKeyJournalEntry, { phase: \"transaction_signed\" | \"finalized\" }>,\n): INewKeyTransferFencedOperation => ({\n  transferSessionId: entry.transferSessionId,\n  blockchainId: entry.blockchainId,\n  networkId: entry.networkId,\n  accountId: entry.accountId,\n  sourcePublicKey: entry.sourcePublicKey,\n  destinationPublicKey: entry.destinationPublicKey,\n  phase: entry.phase,\n  transactionHash: entry.transactionHash,\n  hasReplayableSignedTransaction: entry.phase === \"transaction_signed\",\n});\n\n/**\n * Every protected (signed or finalized) operation in the journal, optionally narrowed to one\n * transfer session and/or a set of accounts.\n *\n * Unlike {@link buildNewKeyTransferReconciliationReport} this does not care whether the rows are\n * orphaned: a host revoking destination keys for a transfer that still HAS its start result needs\n * the same evidence, and needs the same on-chain absence proof before the rows can be retired.\n */\nexport const newKeyTransferProtectedOperations = (\n  entries: readonly TAddKeyJournalEntry[],\n  filter: { transferSessionId?: string; accountIds?: readonly string[] } = {},\n): INewKeyTransferFencedOperation[] => {\n  const accountIds = filter.accountIds == null ? null : new Set(filter.accountIds);\n  return entries\n    .filter(isProtectedEntry)\n    .filter(\n      (entry) =>\n        (filter.transferSessionId == null ||\n          entry.transferSessionId === filter.transferSessionId) &&\n        (accountIds == null || accountIds.has(entry.accountId)),\n    )\n    .map(toFencedOperation);\n};\n\n/** The job identity the chain seam expects, rebuilt from a fenced operation. */\nexport const fencedOperationToJob = (\n  operation: INewKeyTransferFencedOperation,\n): IAddKeyJournalJob => ({\n  transferSessionId: operation.transferSessionId,\n  blockchainId: operation.blockchainId,\n  networkId: operation.networkId,\n  accountId: operation.accountId,\n  sourcePublicKey: operation.sourcePublicKey,\n  destinationPublicKey: operation.destinationPublicKey,\n});\n\n/**\n * A short, stable, non-secret support reference.\n *\n * Hashed rather than assembled from the raw identities: the reference is meant to be pasted into a\n * support ticket, and a truncated digest correlates a damaged profile without republishing account\n * ids or public keys through a channel that was never scoped for them. Base32 (no padding,\n * unambiguous when read aloud or retyped), 16 characters, grouped for legibility.\n */\nexport const newKeyTransferSupportReference = (input: {\n  reason: TNewKeyTransferFenceReason;\n  operations: readonly INewKeyTransferFencedOperation[];\n}): string => {\n  const material = [\n    input.reason,\n    ...input.operations\n      .map((op) => `${op.transferSessionId}::${op.accountId}::${op.transactionHash}`)\n      .sort(),\n  ].join(\"\\n\");\n  const digest = base32.encode(sha256(new TextEncoder().encode(material))).replace(/=+$/, \"\");\n  return `MCNKT-${digest.slice(0, 4)}-${digest.slice(4, 8)}-${digest.slice(8, 12)}-${digest.slice(12, 16)}`;\n};\n\n/**\n * Read the fence and everything safe to say about it, without mutating a byte.\n *\n * A transfer is fenced when signed AddKey rows exist that no start-result record binds — either\n * because there is no start result at all, or because the one on file belongs to a different\n * transfer session. `finalized` rows for the same orphaned session are reported too: they are part\n * of the same stranded operation set and a host reconciling one needs to see all of them.\n */\nexport const buildNewKeyTransferReconciliationReport = (input: {\n  /**\n   * Parsed journal rows, or `null` when the journal could not be parsed at all. Taking rows rather\n   * than raw storage keeps this module free of any runtime dependency on the journal module, so\n   * the journal and the runner can both import it without a cycle.\n   */\n  entries: readonly TAddKeyJournalEntry[] | null;\n  /** The transfer session the stored start result binds, or `null` when there is none. */\n  boundTransferSessionId: string | null;\n}): INewKeyTransferReconciliationReport => {\n  const entries = input.entries;\n  if (entries == null) {\n    // Matches `addKeyJournalHasOrphanedSignedRecovery`: unreadable storage fences exactly as a\n    // real signed row does. There is nothing safe to enumerate, so the report carries only the\n    // reason and a reference.\n    return {\n      fenced: true,\n      reason: \"journal_unreadable\",\n      operations: [],\n      supportReference: newKeyTransferSupportReference({\n        reason: \"journal_unreadable\",\n        operations: [],\n      }),\n    };\n  }\n\n  const boundTransferSessionId = input.boundTransferSessionId;\n  const orphanedSessionIds = new Set(\n    entries\n      .filter((entry) => entry.phase === \"transaction_signed\")\n      .filter((entry) => entry.transferSessionId !== boundTransferSessionId)\n      .map((entry) => entry.transferSessionId),\n  );\n\n  if (orphanedSessionIds.size === 0) {\n    return { fenced: false, reason: null, operations: [], supportReference: null };\n  }\n\n  const operations = entries\n    .filter(isProtectedEntry)\n    .filter((entry) => orphanedSessionIds.has(entry.transferSessionId))\n    .map(toFencedOperation);\n\n  return {\n    fenced: true,\n    reason: \"orphaned_signed_add_key\",\n    operations,\n    supportReference: newKeyTransferSupportReference({\n      reason: \"orphaned_signed_add_key\",\n      operations,\n    }),\n  };\n};\n","import type { IActionPayload_Result_JsonObject } from \"@meteorwallet/connect-core/action\";\nimport * as v from \"valibot\";\nimport { vBase64HashSha256 } from \"../../../model/core/core_valibot_schemas\";\nimport { base64ToBytes } from \"../../../utils/serialization/canonical_json\";\nimport {\n  type TNewKeyTransferStartInputV1,\n  type TNewKeyTransferStartOutputV1,\n  type TNewKeyTransferVerifyActiveInputV1,\n  vCryptoGenericNetworkId,\n  vNearAccountId,\n  vNearEd25519PublicKey,\n  vNearTransactionHash,\n  vNewKeyTransferOpaqueId,\n  vNewKeyTransferStartOutputV1,\n  vNewKeyTransferVerifyActiveInputV1,\n} from \"./act_impl_meteor_wallet_core.schemas\";\nimport { validateNewKeyTransferStartOutputForInput } from \"./act_impl_meteor_wallet_core.utils\";\nimport {\n  buildNewKeyTransferReconciliationReport,\n  type INewKeyTransferReconciliationReport,\n} from \"./new_key_transfer_reconciliation\";\n\n/**\n * Generic D33 AddKey journal machinery for the SOURCE host of a new-key account transfer (A7).\n *\n * This module owns the crash-safe three-phase AddKey journal (`intent_recorded` →\n * `transaction_signed` → `finalized`) plus the two secret-free companion records every source host\n * must keep across process loss:\n *\n * - the **start-result journal** — the wallet's exact signed start output, durable BEFORE the host\n *   acknowledges it into the external-work hold, so a crashed host can resume AddKey without\n *   asking the wallet to mint a different destination key;\n * - the **pending-verify record** — the complete secret-free verification request, durable AFTER\n *   every AddKey finalized and BEFORE the start-result journal is released.\n *\n * Everything here is host-neutral: no chain client, no storage technology, no UI copy. Failures\n * are typed {@link AddKeyJournalError}s so hosts can keep their own recovery copy while the\n * invariants stay centralized. Hosts with synchronous storage (web `localStorage`) bind through\n * {@link createAddKeyJournalStore}; the full submission driver (which adds the chain seam) lives\n * in `createAddKeyJournalRunner`.\n */\n\nexport const ADD_KEY_JOURNAL_FORMAT_VERSION = 2;\nexport const MAX_SIGNED_ADD_KEY_TRANSACTION_BYTES = 4_096;\nexport const MAX_ADD_KEY_JOURNAL_ENTRIES = 1_000;\n\n/** The three storage slots the AddKey journal machinery persists, overridable per host. */\nexport interface IAddKeyJournalStorageKeys {\n  journal: string;\n  startResult: string;\n  pendingVerify: string;\n}\n\nexport const DEFAULT_ADD_KEY_JOURNAL_STORAGE_KEYS: IAddKeyJournalStorageKeys = {\n  journal: \"new_key_transfer::add_key_journal_v1\",\n  startResult: \"new_key_transfer::start_result_journal_v1\",\n  pendingVerify: \"new_key_transfer::pending_verify_v1\",\n};\n\nexport type TAddKeyJournalErrorCode =\n  | \"journal_unreadable\"\n  | \"journal_unsupported_shape\"\n  | \"journal_duplicate_operations\"\n  | \"journal_operation_conflict\"\n  | \"journal_record_mismatch\"\n  | \"journal_persist_failed\"\n  | \"access_keys_malformed\"\n  | \"destination_key_unproven\"\n  | \"source_key_missing\"\n  | \"source_key_not_full_access\"\n  | \"signed_transaction_invalid\"\n  | \"broadcast_ambiguous\"\n  | \"finalized_proof_invalid\"\n  | \"start_result_conflict\"\n  | \"start_result_corrupt\"\n  | \"start_result_persist_failed\"\n  | \"start_result_clear_failed\"\n  | \"pending_verify_conflict\"\n  | \"pending_verify_corrupt\"\n  | \"pending_verify_persist_failed\";\n\n/**\n * Typed failure for every AddKey journal invariant. The default messages are safe host-neutral\n * copy; hosts that want their own recovery wording switch on {@link AddKeyJournalError.code}.\n */\nexport class AddKeyJournalError extends Error {\n  readonly code: TAddKeyJournalErrorCode;\n\n  constructor(code: TAddKeyJournalErrorCode, message: string, options?: { cause?: unknown }) {\n    super(message, options);\n    this.name = \"AddKeyJournalError\";\n    this.code = code;\n  }\n}\n\nconst vSignedAddKeyTransactionBase64 = v.pipe(\n  v.string(),\n  v.maxLength(Math.ceil((MAX_SIGNED_ADD_KEY_TRANSACTION_BYTES * 4) / 3) + 4),\n  v.check((value) => {\n    try {\n      const bytes = base64ToBytes(value);\n      return bytes.length > 0 && bytes.length <= MAX_SIGNED_ADD_KEY_TRANSACTION_BYTES;\n    } catch {\n      return false;\n    }\n  }, \"Signed AddKey transaction must be bounded canonical base64\"),\n);\n\nconst vAddKeyJournalIdentity = {\n  operationVersion: v.literal(1),\n  transferSessionId: vNewKeyTransferOpaqueId,\n  blockchainId: v.literal(\"near\"),\n  networkId: vCryptoGenericNetworkId,\n  accountId: vNearAccountId,\n  sourcePublicKey: vNearEd25519PublicKey,\n  destinationPublicKey: vNearEd25519PublicKey,\n};\n\nexport const vAddKeyIntentJournalEntry = v.strictObject({\n  ...vAddKeyJournalIdentity,\n  phase: v.literal(\"intent_recorded\"),\n});\n\nexport const vAddKeySignedJournalEntry = v.strictObject({\n  ...vAddKeyJournalIdentity,\n  phase: v.literal(\"transaction_signed\"),\n  transactionHash: vNearTransactionHash,\n  signedTransactionBase64: vSignedAddKeyTransactionBase64,\n});\n\nexport const vAddKeyFinalizedJournalEntry = v.strictObject({\n  ...vAddKeyJournalIdentity,\n  phase: v.literal(\"finalized\"),\n  transactionHash: vNearTransactionHash,\n});\n\nexport const vAddKeyJournalEntry = v.union([\n  vAddKeyIntentJournalEntry,\n  vAddKeySignedJournalEntry,\n  vAddKeyFinalizedJournalEntry,\n]);\n\nexport const vAddKeyJournal = v.strictObject({\n  formatVersion: v.literal(ADD_KEY_JOURNAL_FORMAT_VERSION),\n  entries: v.pipe(v.array(vAddKeyJournalEntry), v.maxLength(MAX_ADD_KEY_JOURNAL_ENTRIES)),\n});\n\nexport type TAddKeyJournalEntry = v.InferOutput<typeof vAddKeyJournalEntry>;\nexport type TAddKeyIntentJournalEntry = v.InferOutput<typeof vAddKeyIntentJournalEntry>;\nexport type TAddKeySignedJournalEntry = v.InferOutput<typeof vAddKeySignedJournalEntry>;\nexport type TAddKeyFinalizedJournalEntry = v.InferOutput<typeof vAddKeyFinalizedJournalEntry>;\n\n/** One AddKey operation's full identity — the exact keys the journal converges on. */\nexport interface IAddKeyJournalJob {\n  transferSessionId: string;\n  blockchainId: \"near\";\n  networkId: \"mainnet\" | \"testnet\";\n  accountId: string;\n  sourcePublicKey: string;\n  destinationPublicKey: string;\n}\n\nconst journalOperationId = (entry: { transferSessionId: string; accountId: string }): string =>\n  `${entry.transferSessionId}::${entry.accountId}`;\n\nconst assertNoDuplicateJournalOperations = (entries: readonly TAddKeyJournalEntry[]): void => {\n  const seen = new Set<string>();\n  for (const entry of entries) {\n    const operationId = journalOperationId(entry);\n    if (seen.has(operationId)) {\n      throw new AddKeyJournalError(\n        \"journal_duplicate_operations\",\n        \"The local AddKey recovery journal contains duplicate operation records. No transaction was submitted; preserve the stored journal data for reconciliation.\",\n      );\n    }\n    seen.add(operationId);\n  }\n};\n\n/**\n * Parse the serialized mutation journal without narrowing or dropping malformed rows. Returning an\n * empty journal for damaged storage could cause a second AddKey, so corruption is deliberately a\n * hard stop.\n */\nexport const parseAddKeyJournalEntries = (\n  serialized: string | null | undefined,\n): TAddKeyJournalEntry[] => {\n  if (serialized == null) return [];\n\n  let parsed: unknown;\n  try {\n    parsed = JSON.parse(serialized);\n  } catch {\n    throw new AddKeyJournalError(\n      \"journal_unreadable\",\n      \"The local AddKey recovery journal is unreadable. No transaction was submitted; preserve the stored journal data for reconciliation.\",\n    );\n  }\n\n  const current = v.safeParse(vAddKeyJournal, parsed);\n  if (current.success) {\n    assertNoDuplicateJournalOperations(current.output.entries);\n    return [...current.output.entries];\n  }\n\n  throw new AddKeyJournalError(\n    \"journal_unsupported_shape\",\n    \"The local AddKey recovery journal has an unsupported shape. No transaction was submitted; preserve the stored journal data for reconciliation.\",\n  );\n};\n\n/** Validate and serialize the journal for persistence; duplicate operations fail closed. */\nexport const serializeAddKeyJournalEntries = (entries: readonly TAddKeyJournalEntry[]): string => {\n  const journal = v.parse(vAddKeyJournal, {\n    formatVersion: ADD_KEY_JOURNAL_FORMAT_VERSION,\n    entries,\n  });\n  assertNoDuplicateJournalOperations(journal.entries);\n  return JSON.stringify(journal);\n};\n\n/**\n * Replace (or insert) one operation's journal entry. An existing record for the same operation id\n * with DIFFERENT key material is a conflicting concurrent transfer and fails closed.\n */\nexport const replaceAddKeyJournalEntry = (\n  entries: readonly TAddKeyJournalEntry[],\n  entry: TAddKeyJournalEntry,\n): TAddKeyJournalEntry[] => {\n  const operationId = journalOperationId(entry);\n  const current = entries.find((candidate) => journalOperationId(candidate) === operationId);\n  if (\n    current != null &&\n    (current.destinationPublicKey !== entry.destinationPublicKey ||\n      current.sourcePublicKey !== entry.sourcePublicKey)\n  ) {\n    throw new AddKeyJournalError(\n      \"journal_operation_conflict\",\n      `${entry.accountId} already has a different AddKey operation under this transfer session. No transaction was submitted.`,\n    );\n  }\n  return [...entries.filter((candidate) => journalOperationId(candidate) !== operationId), entry];\n};\n\n/**\n * Find the journal entry for one job, requiring the stored record to match the job's EXACT key\n * material — a partial match is a different transfer and fails closed.\n */\nexport const findAddKeyJournalEntry = (\n  entries: readonly TAddKeyJournalEntry[],\n  job: IAddKeyJournalJob,\n): TAddKeyJournalEntry | null => {\n  const entry = entries.find(\n    (candidate) =>\n      candidate.transferSessionId === job.transferSessionId &&\n      candidate.accountId === job.accountId,\n  );\n  if (entry == null) return null;\n  if (\n    entry.blockchainId !== job.blockchainId ||\n    entry.networkId !== job.networkId ||\n    entry.destinationPublicKey !== job.destinationPublicKey ||\n    entry.sourcePublicKey !== job.sourcePublicKey\n  ) {\n    throw new AddKeyJournalError(\n      \"journal_record_mismatch\",\n      `${job.accountId}'s AddKey recovery record does not match this exact transfer request. No transaction was submitted.`,\n    );\n  }\n  return entry;\n};\n\n/**\n * Signed/finalized operations cannot be abandoned by a generic \"start fresh\" reset. A malformed\n * journal must fence reset just as it fences submission, so corruption reports `true`.\n */\nexport const addKeyJournalHasProtectedRecovery = (\n  serialized: string | null | undefined,\n  transferSessionId: string,\n): boolean => {\n  try {\n    return parseAddKeyJournalEntries(serialized).some(\n      (entry) =>\n        entry.transferSessionId === transferSessionId &&\n        (entry.phase === \"transaction_signed\" || entry.phase === \"finalized\"),\n    );\n  } catch {\n    return true;\n  }\n};\n\n/** Global fence for a replayable artifact whose start-result record was lost or damaged. */\nexport const addKeyJournalHasOrphanedSignedRecovery = (\n  serialized: string | null | undefined,\n): boolean => {\n  try {\n    return parseAddKeyJournalEntries(serialized).some(\n      (entry) => entry.phase === \"transaction_signed\",\n    );\n  } catch {\n    return true;\n  }\n};\n\n/**\n *\n *  [ START-RESULT JOURNAL ]\n *\n */\n\nexport interface IJournaledNewKeyStartResult {\n  formatVersion: 1;\n  resultHash: string;\n  output: TNewKeyTransferStartOutputV1;\n}\n\nconst vJournaledNewKeyStartResult = v.strictObject({\n  formatVersion: v.literal(1),\n  resultHash: vBase64HashSha256,\n  output: vNewKeyTransferStartOutputV1,\n});\n\nexport type TReceivedNewKeyStartResult =\n  | { accepted: true; journal: IJournaledNewKeyStartResult }\n  | { accepted: false; reason: string };\n\nexport const parseJournaledNewKeyStartResult = (\n  serialized: string | null | undefined,\n): IJournaledNewKeyStartResult | null => {\n  if (serialized == null) return null;\n  try {\n    return v.parse(vJournaledNewKeyStartResult, JSON.parse(serialized));\n  } catch (error) {\n    throw new AddKeyJournalError(\n      \"start_result_corrupt\",\n      \"The saved new-key start-result journal is corrupt. Preserve the stored journal data and reconcile it before continuing.\",\n      { cause: error },\n    );\n  }\n};\n\n/**\n * Validate one start result into its durable journal form, refusing to displace a DIFFERENT\n * remembered transfer (only an exact re-remember of the same session + result hash converges).\n */\nexport const buildJournaledNewKeyStartResult = (input: {\n  existingSerialized: string | null | undefined;\n  resultHash: string;\n  output: TNewKeyTransferStartOutputV1;\n}): { journal: IJournaledNewKeyStartResult; serialized: string } => {\n  const journal = v.parse(vJournaledNewKeyStartResult, {\n    formatVersion: 1,\n    resultHash: input.resultHash,\n    output: input.output,\n  });\n  const existing = parseJournaledNewKeyStartResult(input.existingSerialized);\n  if (\n    existing != null &&\n    (existing.output.transferSessionId !== journal.output.transferSessionId ||\n      existing.resultHash !== journal.resultHash)\n  ) {\n    throw new AddKeyJournalError(\n      \"start_result_conflict\",\n      \"A different new-key start result is already journaled. Resume or explicitly discard that transfer before recording another.\",\n    );\n  }\n  return { journal, serialized: JSON.stringify(journal) };\n};\n\n/**\n * Consume a signed start result against the exact remembered request. A validation failure is a\n * transport RECEIPT, never an acceptance: nothing durable may be touched, and the caller still\n * acknowledges receipt so the session is not parked in `result_ready`.\n */\nexport const consumeSignedNewKeyStartResult = (input: {\n  request: TNewKeyTransferStartInputV1;\n  resultHash: string;\n  actionResult: IActionPayload_Result_JsonObject;\n  existingSerialized: string | null | undefined;\n}):\n  | { accepted: true; journal: IJournaledNewKeyStartResult; serialized: string }\n  | { accepted: false; reason: string } => {\n  const payload = input.actionResult;\n  if (\n    payload.domain !== \"meteor_wallet_core\" ||\n    payload.id !== \"new_key_account_transfer_start\" ||\n    !payload.result.ok\n  ) {\n    return {\n      accepted: false,\n      reason: \"The signed wallet result did not belong to this new-key start request.\",\n    };\n  }\n  let output: TNewKeyTransferStartOutputV1;\n  try {\n    output = validateNewKeyTransferStartOutputForInput({\n      request: input.request,\n      output: payload.result.output,\n    });\n  } catch {\n    return {\n      accepted: false,\n      reason: \"The signed start result did not match the exact requested account set.\",\n    };\n  }\n  const built = buildJournaledNewKeyStartResult({\n    existingSerialized: input.existingSerialized,\n    resultHash: input.resultHash,\n    output,\n  });\n  return { accepted: true, journal: built.journal, serialized: built.serialized };\n};\n\n/**\n *\n *  [ PENDING-VERIFY RECORD ]\n *\n */\n\nconst hasExactKeys = (value: object, expected: readonly string[]): boolean => {\n  const actual = Object.keys(value).sort();\n  const sortedExpected = [...expected].sort();\n  return (\n    actual.length === sortedExpected.length &&\n    actual.every((key, index) => key === sortedExpected[index])\n  );\n};\n\nconst isExactPendingVerifyShape = (value: unknown): boolean => {\n  if (typeof value !== \"object\" || value == null || Array.isArray(value)) return false;\n  if (!hasExactKeys(value, [\"activations\", \"formatVersion\", \"transferSessionId\"])) return false;\n  const activations = Reflect.get(value, \"activations\");\n  return (\n    Array.isArray(activations) &&\n    activations.every(\n      (activation) =>\n        typeof activation === \"object\" &&\n        activation != null &&\n        !Array.isArray(activation) &&\n        hasExactKeys(activation, [\n          \"accountId\",\n          \"addKeyTransactionHash\",\n          \"blockchainId\",\n          \"networkId\",\n        ]),\n    )\n  );\n};\n\n/**\n * Parse the complete, secret-free verification request recorded after every AddKey finalized.\n * Exact-key validation prevents a malformed or future storage shape from being silently narrowed\n * into a request the user did not save.\n */\nexport const parsePendingNewKeyVerification = (\n  serialized: string | null | undefined,\n): TNewKeyTransferVerifyActiveInputV1 | null => {\n  if (serialized == null) return null;\n  try {\n    const parsed: unknown = JSON.parse(serialized);\n    if (!isExactPendingVerifyShape(parsed)) throw new Error(\"unexpected persisted fields\");\n    return v.parse(vNewKeyTransferVerifyActiveInputV1, parsed);\n  } catch (error) {\n    throw new AddKeyJournalError(\n      \"pending_verify_corrupt\",\n      \"The saved new-key verification proof is corrupt. Preserve the stored journal data and reconcile it before continuing.\",\n      { cause: error },\n    );\n  }\n};\n\n/**\n * Validate one verification request into its durable form, refusing to displace a DIFFERENT\n * pending proof (only a byte-identical re-remember converges).\n */\nexport const buildPendingNewKeyVerification = (input: {\n  existingSerialized: string | null | undefined;\n  verifyInput: TNewKeyTransferVerifyActiveInputV1;\n}): { parsed: TNewKeyTransferVerifyActiveInputV1; serialized: string } => {\n  const parsed = v.parse(vNewKeyTransferVerifyActiveInputV1, input.verifyInput);\n  const existing = parsePendingNewKeyVerification(input.existingSerialized);\n  if (\n    existing != null &&\n    (existing.transferSessionId !== parsed.transferSessionId ||\n      JSON.stringify(existing) !== JSON.stringify(parsed))\n  ) {\n    throw new AddKeyJournalError(\n      \"pending_verify_conflict\",\n      \"A different verification proof is already saved. Resume or explicitly discard it before recording another transfer.\",\n    );\n  }\n  return { parsed, serialized: JSON.stringify(parsed) };\n};\n\n/**\n *\n *  [ SYNCHRONOUS STORE BINDING ]\n *\n */\n\n/** Minimal synchronous storage; web `localStorage` satisfies it directly. */\nexport interface IAddKeyJournalSyncStorage {\n  getItem(key: string): string | null;\n  setItem(key: string, value: string): void;\n  removeItem(key: string): void;\n}\n\n/**\n * The record/guard surface of the AddKey journal machinery. The synchronous binding exists for\n * hosts whose storage is synchronous (web `localStorage`) and whose UIs read journal state during\n * render; `createAddKeyJournalRunner` exposes the same surface asynchronously plus the chain\n * driver.\n */\nexport interface IAddKeyJournalStore {\n  loadJournalEntries(): TAddKeyJournalEntry[];\n  hasProtectedRecovery(transferSessionId: string): boolean;\n  hasOrphanedSignedRecovery(): boolean;\n  /**\n   * The non-secret evidence behind the fence, for a host that needs to show a user what is stuck\n   * (B-04). Record-only: resolving the fence needs chain calls and lives on the runner.\n   */\n  buildReconciliationReport(): INewKeyTransferReconciliationReport;\n  rememberStartResult(input: {\n    resultHash: string;\n    output: TNewKeyTransferStartOutputV1;\n  }): IJournaledNewKeyStartResult;\n  receiveSignedStartResult(input: {\n    request: TNewKeyTransferStartInputV1;\n    resultHash: string;\n    actionResult: IActionPayload_Result_JsonObject;\n  }): TReceivedNewKeyStartResult;\n  loadStartResult(): IJournaledNewKeyStartResult | null;\n  discardStartResult(): boolean;\n  loadPendingVerification(): TNewKeyTransferVerifyActiveInputV1 | null;\n  rememberPendingVerification(\n    verifyInput: TNewKeyTransferVerifyActiveInputV1,\n  ): TNewKeyTransferVerifyActiveInputV1;\n  clearPendingVerification(transferSessionId: string): boolean;\n  discardPendingVerification(): boolean;\n  commitVerificationIntent(\n    verifyInput: TNewKeyTransferVerifyActiveInputV1,\n  ): TNewKeyTransferVerifyActiveInputV1;\n}\n\nexport const createAddKeyJournalStore = (input: {\n  storage: IAddKeyJournalSyncStorage;\n  storageKeys?: Partial<IAddKeyJournalStorageKeys>;\n}): IAddKeyJournalStore => {\n  const keys: IAddKeyJournalStorageKeys = {\n    ...DEFAULT_ADD_KEY_JOURNAL_STORAGE_KEYS,\n    ...input.storageKeys,\n  };\n  const storage = input.storage;\n\n  const loadJournalEntries = (): TAddKeyJournalEntry[] =>\n    parseAddKeyJournalEntries(storage.getItem(keys.journal));\n\n  const writeJournalEntries = (entries: readonly TAddKeyJournalEntry[]): void => {\n    const serialized = serializeAddKeyJournalEntries(entries);\n    try {\n      storage.setItem(keys.journal, serialized);\n    } catch {\n      throw new AddKeyJournalError(\n        \"journal_persist_failed\",\n        \"This host could not persist the AddKey recovery checkpoint. The previous checkpoint was retained; keep this process alive, resume this exact transfer, and do not start a replacement transaction.\",\n      );\n    }\n  };\n\n  const loadStartResult = (): IJournaledNewKeyStartResult | null =>\n    parseJournaledNewKeyStartResult(storage.getItem(keys.startResult));\n\n  const persistStartResult = (serialized: string): void => {\n    try {\n      storage.setItem(keys.startResult, serialized);\n    } catch {\n      throw new AddKeyJournalError(\n        \"start_result_persist_failed\",\n        \"The wallet returned destination keys, but the start-result recovery journal could not be persisted. Keep this session open and retry; do not submit AddKey yet.\",\n      );\n    }\n  };\n\n  const removeStartResult = (): boolean => {\n    try {\n      storage.removeItem(keys.startResult);\n      return true;\n    } catch {\n      return false;\n    }\n  };\n\n  const loadPendingVerification = (): TNewKeyTransferVerifyActiveInputV1 | null =>\n    parsePendingNewKeyVerification(storage.getItem(keys.pendingVerify));\n\n  const rememberPendingVerification = (\n    verifyInput: TNewKeyTransferVerifyActiveInputV1,\n  ): TNewKeyTransferVerifyActiveInputV1 => {\n    const built = buildPendingNewKeyVerification({\n      existingSerialized: storage.getItem(keys.pendingVerify),\n      verifyInput,\n    });\n    try {\n      storage.setItem(keys.pendingVerify, built.serialized);\n    } catch {\n      throw new AddKeyJournalError(\n        \"pending_verify_persist_failed\",\n        \"Every AddKey finalized, but the secret-free verification proof could not be persisted. Keep this session open and retry; do not reset this transfer.\",\n      );\n    }\n    return built.parsed;\n  };\n\n  return {\n    loadJournalEntries,\n\n    hasProtectedRecovery: (transferSessionId) =>\n      addKeyJournalHasProtectedRecovery(storage.getItem(keys.journal), transferSessionId),\n\n    hasOrphanedSignedRecovery: () =>\n      addKeyJournalHasOrphanedSignedRecovery(storage.getItem(keys.journal)),\n\n    buildReconciliationReport: () => {\n      let entries: TAddKeyJournalEntry[] | null;\n      try {\n        entries = loadJournalEntries();\n      } catch {\n        entries = null;\n      }\n      return buildNewKeyTransferReconciliationReport({\n        entries,\n        boundTransferSessionId: loadStartResult()?.output.transferSessionId ?? null,\n      });\n    },\n\n    rememberStartResult: ({ resultHash, output }) => {\n      const built = buildJournaledNewKeyStartResult({\n        existingSerialized: storage.getItem(keys.startResult),\n        resultHash,\n        output,\n      });\n      persistStartResult(built.serialized);\n      return built.journal;\n    },\n\n    receiveSignedStartResult: ({ request, resultHash, actionResult }) => {\n      const consumed = consumeSignedNewKeyStartResult({\n        request,\n        resultHash,\n        actionResult,\n        existingSerialized: storage.getItem(keys.startResult),\n      });\n      if (!consumed.accepted) return consumed;\n      persistStartResult(consumed.serialized);\n      return { accepted: true, journal: consumed.journal };\n    },\n\n    loadStartResult,\n\n    /**\n     * Discard the remembered start result AND its intent-only journal rows — but never across the\n     * protected signed/finalized boundary, and never when the journal cannot be read.\n     */\n    discardStartResult: () => {\n      const journaledStart = loadStartResult();\n      if (\n        journaledStart != null &&\n        addKeyJournalHasProtectedRecovery(\n          storage.getItem(keys.journal),\n          journaledStart.output.transferSessionId,\n        )\n      ) {\n        return false;\n      }\n      if (journaledStart != null) {\n        try {\n          const entries = loadJournalEntries();\n          const retainedEntries = entries.filter(\n            (entry) =>\n              entry.transferSessionId !== journaledStart.output.transferSessionId ||\n              entry.phase !== \"intent_recorded\",\n          );\n          if (retainedEntries.length !== entries.length) writeJournalEntries(retainedEntries);\n        } catch {\n          return false;\n        }\n      }\n      return removeStartResult();\n    },\n\n    loadPendingVerification,\n    rememberPendingVerification,\n\n    /**\n     * Clear only the pending proof for the expected session; a stale completion cannot erase a\n     * newer one, and a replayable signed transaction or unfinished intent is never pruned here.\n     */\n    clearPendingVerification: (transferSessionId) => {\n      const pending = loadPendingVerification();\n      if (pending?.transferSessionId !== transferSessionId) return true;\n      try {\n        const entries = loadJournalEntries();\n        const transferEntries = entries.filter(\n          (entry) => entry.transferSessionId === transferSessionId,\n        );\n        if (transferEntries.some((entry) => entry.phase !== \"finalized\")) {\n          return false;\n        }\n        if (transferEntries.length > 0) {\n          writeJournalEntries(\n            entries.filter((entry) => entry.transferSessionId !== transferSessionId),\n          );\n        }\n        storage.removeItem(keys.pendingVerify);\n        return true;\n      } catch {\n        // Keeping an already verified, secret-free proof is safe; a later load may retry.\n        return false;\n      }\n    },\n\n    /** Explicit host reset: discard the saved pending proof regardless of its session contents. */\n    discardPendingVerification: () => {\n      try {\n        storage.removeItem(keys.pendingVerify);\n        return true;\n      } catch {\n        return false;\n      }\n    },\n\n    /**\n     * The durable completion ordering: persist the COMPLETE verification intent first; only then\n     * may the earlier start-result journal be released.\n     */\n    commitVerificationIntent: (verifyInput) => {\n      const remembered = rememberPendingVerification(verifyInput);\n      if (!removeStartResult()) {\n        throw new AddKeyJournalError(\n          \"start_result_clear_failed\",\n          \"Verification proof is safely saved, but the older start-result journal could not be cleared. Resume verification; do not submit AddKey again.\",\n        );\n      }\n      return remembered;\n    },\n  };\n};\n","import type { IActionPayload_Result_JsonObject } from \"@meteorwallet/connect-core/action\";\nimport * as v from \"valibot\";\nimport type {\n  TNewKeyTransferStartInputV1,\n  TNewKeyTransferStartOutputV1,\n  TNewKeyTransferVerifyActiveInputV1,\n} from \"./act_impl_meteor_wallet_core.schemas\";\nimport { verifyNewKeyTransferAddKeyProof } from \"./new_key_account_transfer_proof\";\nimport { normalizeNearAddKeyProof } from \"./new_key_account_transfer_proof_normalize\";\nimport {\n  AddKeyJournalError,\n  addKeyJournalHasOrphanedSignedRecovery,\n  addKeyJournalHasProtectedRecovery,\n  buildJournaledNewKeyStartResult,\n  buildPendingNewKeyVerification,\n  consumeSignedNewKeyStartResult,\n  DEFAULT_ADD_KEY_JOURNAL_STORAGE_KEYS,\n  findAddKeyJournalEntry,\n  type IAddKeyJournalJob,\n  type IAddKeyJournalStorageKeys,\n  type IJournaledNewKeyStartResult,\n  parseAddKeyJournalEntries,\n  parseJournaledNewKeyStartResult,\n  parsePendingNewKeyVerification,\n  replaceAddKeyJournalEntry,\n  serializeAddKeyJournalEntries,\n  type TAddKeyFinalizedJournalEntry,\n  type TAddKeyIntentJournalEntry,\n  type TAddKeyJournalEntry,\n  type TAddKeySignedJournalEntry,\n  type TReceivedNewKeyStartResult,\n  vAddKeySignedJournalEntry,\n} from \"./new_key_transfer_add_key_journal\";\nimport {\n  buildNewKeyTransferReconciliationReport,\n  fencedOperationToJob,\n  type INewKeyTransferFencedOperation,\n  type INewKeyTransferReconcileResult,\n  type INewKeyTransferReconciliationReport,\n} from \"./new_key_transfer_reconciliation\";\n\n/**\n * The crash-safe AddKey submission engine (A7): the full D33 journal driver over two seams —\n * a minimal storage-methods interface (sync or async; NO storage technology baked in) and a chain\n * interface carrying the NEAR RPC calls. It owns every invariant a source host would otherwise\n * have to re-prove:\n *\n * - **journal-before-everything**: the journal is read (and fails closed on ANY corruption)\n *   before the first chain call;\n * - **durable intent before signing**; **durable exact signed bytes/hash before broadcast**;\n * - **same-byte-only rebroadcast**: an ambiguous broadcast never builds a replacement transaction —\n *   it reconciles the precomputed hash, and a retry rebroadcasts only the identical journaled\n *   bytes;\n * - **finality verified through the shared proof verifier** (exact hash/signer/receiver,\n *   exactly-one-AddKey, full-access destination, execution success, destination-key liveness)\n *   before the replayable bytes are replaced by the finalized checkpoint;\n * - **fail-closed convergence**: duplicate operation records, mismatched recovery records, and a\n *   destination key present without journaled proof all refuse submission.\n */\n\nexport interface IAddKeyJournalStorageMethods {\n  getItem(key: string): string | null | undefined | Promise<string | null | undefined>;\n  setItem(key: string, value: string): void | Promise<void>;\n  removeItem(key: string): void | Promise<void>;\n}\n\n/**\n * The `getString`/`setString` vocabulary `StorageAdapter` speaks (`nice-code/util`, re-exported by\n * `@meteorwallet/connect`). Accepted directly so a host that already built a storage adapter for the\n * client does not have to hand-write an adapter-of-an-adapter just to reach the journal runner.\n */\nexport interface IAddKeyJournalStorageStringMethods {\n  getString(key: string): string | null | undefined | Promise<string | null | undefined>;\n  setString(key: string, value: string): void | Promise<void>;\n  removeItem(key: string): void | Promise<void>;\n}\n\n/** Either storage vocabulary; {@link createAddKeyJournalRunner} normalizes them. */\nexport type TAddKeyJournalStorage =\n  | IAddKeyJournalStorageMethods\n  | IAddKeyJournalStorageStringMethods;\n\nconst normalizeJournalStorage = (storage: TAddKeyJournalStorage): IAddKeyJournalStorageMethods =>\n  \"getItem\" in storage\n    ? storage\n    : {\n        getItem: (key) => storage.getString(key),\n        setItem: (key, value) => storage.setString(key, value),\n        removeItem: (key) => storage.removeItem(key),\n      };\n\nexport interface IAddKeySignedTransaction {\n  transactionHash: string;\n  signedTransactionBase64: string;\n}\n\n/**\n * The chain seam. Every method receives the full job identity; implementations close over their\n * chain client and signing material (signing keys NEVER reach this module).\n */\nexport interface IAddKeyJournalChain {\n  /**\n   * Raw NEAR RPC `view_access_key_list` result for the job's account, at final finality — the\n   * COMPLETE list. Nodes refuse the unpaginated request for an account with more than 100 keys\n   * (`TOO_MANY_ACCESS_KEYS`), so read it page by page (`limit`/`after_key`, later pages pinned to\n   * the first page's `block_id`) and answer with every page's `keys` in one `{ keys }` object.\n   */\n  getAccessKeys(job: IAddKeyJournalJob): Promise<unknown>;\n  /** Build and sign the exact AddKey transaction. MUST NOT broadcast anything. */\n  signAddKeyTransaction(job: IAddKeyJournalJob): Promise<IAddKeySignedTransaction>;\n  /**\n   * Broadcast the exact signed bytes with FINAL wait; returns the raw transaction-status outcome.\n   * A thrown error is treated as AMBIGUOUS (the transaction may still land) and reconciled.\n   */\n  broadcastSignedTransaction(\n    job: IAddKeyJournalJob,\n    signed: IAddKeySignedTransaction,\n  ): Promise<unknown>;\n  /** Raw transaction-status for a precomputed hash, with FINAL wait. */\n  getFinalTransactionStatus(job: IAddKeyJournalJob, transactionHash: string): Promise<unknown>;\n  /**\n   * Whether these exact signed bytes can NEVER be accepted by the chain any more.\n   *\n   * Used only by the reconciliation state machine, and only to separate \"has not landed yet\" from\n   * \"can no longer land\". Absence of the destination key is not by itself evidence that a signed\n   * transaction is dead — it may simply be in flight — so without a definitive answer here\n   * reconciliation stays `ambiguous` rather than retiring a row that could still take effect.\n   *\n   * A NEAR host can implement this by rebroadcasting the exact bytes and mapping\n   * `InvalidTxError::Expired` (the transaction's block hash has fallen outside the validity\n   * window) to `true`. Returning `false` when unsure is correct; throwing is treated as unknown.\n   *\n   * Optional: a host that cannot determine expiry never reaches `destination_key_absent`\n   * automatically and reconciles through explicit revocation instead.\n   */\n  isSignedTransactionExpired?(\n    job: IAddKeyJournalJob,\n    signed: IAddKeySignedTransaction,\n  ): Promise<boolean>;\n}\n\nexport interface IAddKeyJournalRunnerConfig {\n  storage: TAddKeyJournalStorage;\n  chain: IAddKeyJournalChain;\n  storageKeys?: Partial<IAddKeyJournalStorageKeys>;\n  /**\n   * Serializes whole submissions across every tab/process sharing this storage (e.g. a Web Lock on\n   * multi-tab web). Defaults to per-runner serialization, which is only sufficient when this\n   * process is the storage's sole writer.\n   */\n  withMutationLock?: <T>(operation: () => Promise<T>) => Promise<T>;\n}\n\n/** Async record/guard surface plus the submission driver. */\nexport interface IAddKeyJournalRunner {\n  /**\n   * Submit one account's AddKey through the crash-safe journal; returns the finalized transaction\n   * hash. Idempotent per journal state: finalized entries reconcile, signed entries rebroadcast\n   * the identical bytes, and fresh jobs record intent before signing.\n   */\n  submitAddKey(job: IAddKeyJournalJob): Promise<string>;\n  loadJournalEntries(): Promise<TAddKeyJournalEntry[]>;\n  hasProtectedRecovery(transferSessionId: string): Promise<boolean>;\n  hasOrphanedSignedRecovery(): Promise<boolean>;\n  rememberStartResult(input: {\n    resultHash: string;\n    output: TNewKeyTransferStartOutputV1;\n  }): Promise<IJournaledNewKeyStartResult>;\n  receiveSignedStartResult(input: {\n    request: TNewKeyTransferStartInputV1;\n    resultHash: string;\n    actionResult: IActionPayload_Result_JsonObject;\n  }): Promise<TReceivedNewKeyStartResult>;\n  loadStartResult(): Promise<IJournaledNewKeyStartResult | null>;\n  discardStartResult(): Promise<boolean>;\n  loadPendingVerification(): Promise<TNewKeyTransferVerifyActiveInputV1 | null>;\n  rememberPendingVerification(\n    verifyInput: TNewKeyTransferVerifyActiveInputV1,\n  ): Promise<TNewKeyTransferVerifyActiveInputV1>;\n  clearPendingVerification(transferSessionId: string): Promise<boolean>;\n  discardPendingVerification(): Promise<boolean>;\n  commitVerificationIntent(\n    verifyInput: TNewKeyTransferVerifyActiveInputV1,\n  ): Promise<TNewKeyTransferVerifyActiveInputV1>;\n  /**\n   * Non-secret evidence for whatever is fencing this host, without mutating anything. Empty\n   * `operations` with reason `journal_unreadable` means the fence cannot be resolved from stored\n   * data — that is the case that needs the support reference.\n   */\n  buildReconciliationReport(): Promise<INewKeyTransferReconciliationReport>;\n  /**\n   * Advance ONE fenced operation as far as the chain allows. Never destructive: the only mutation\n   * it can make is promoting a proven `transaction_signed` row to `finalized`.\n   */\n  reconcileFencedOperation(\n    operation: INewKeyTransferFencedOperation,\n  ): Promise<INewKeyTransferReconcileResult>;\n  /**\n   * Retire a fenced row once its destination key is proven ABSENT on-chain at final finality —\n   * either because the transaction can never land (`destination_key_absent`) or because the host\n   * removed the key with the source signer and waited for finality. Re-proves absence itself; a\n   * caller's assurance is never taken at face value. Returns `false` when it refused.\n   */\n  archiveReconciledOperation(operation: INewKeyTransferFencedOperation): Promise<boolean>;\n}\n\nconst vRawNearAccessKeyEntry = v.object({\n  public_key: v.string(),\n  access_key: v.object({ permission: v.unknown() }),\n});\n\nconst vRawNearAccessKeyList = v.object({ keys: v.array(v.unknown()) });\n\ninterface IRawAccessKeySummary {\n  publicKey: string;\n  fullAccess: boolean;\n}\n\nconst readAccessKeySummaries = (raw: unknown, accountId: string): IRawAccessKeySummary[] => {\n  const list = v.safeParse(vRawNearAccessKeyList, raw);\n  if (!list.success) {\n    throw new AddKeyJournalError(\n      \"access_keys_malformed\",\n      `${accountId}'s current access keys could not be read from the chain adapter. No transaction was submitted.`,\n    );\n  }\n  const summaries: IRawAccessKeySummary[] = [];\n  for (const rawEntry of list.output.keys) {\n    const entry = v.safeParse(vRawNearAccessKeyEntry, rawEntry);\n    if (!entry.success) continue;\n    summaries.push({\n      publicKey: entry.output.public_key,\n      fullAccess: entry.output.access_key.permission === \"FullAccess\",\n    });\n  }\n  return summaries;\n};\n\nconst finalizedEntryFromSigned = (\n  signed: TAddKeySignedJournalEntry,\n): TAddKeyFinalizedJournalEntry => ({\n  operationVersion: 1,\n  transferSessionId: signed.transferSessionId,\n  blockchainId: signed.blockchainId,\n  networkId: signed.networkId,\n  accountId: signed.accountId,\n  sourcePublicKey: signed.sourcePublicKey,\n  destinationPublicKey: signed.destinationPublicKey,\n  phase: \"finalized\",\n  transactionHash: signed.transactionHash,\n});\n\nconst defaultMutationLock = (): (<T>(operation: () => Promise<T>) => Promise<T>) => {\n  let chain: Promise<void> = Promise.resolve();\n  return <T>(operation: () => Promise<T>): Promise<T> => {\n    const pending = chain.then(operation, operation);\n    chain = pending.then(\n      () => undefined,\n      () => undefined,\n    );\n    return pending;\n  };\n};\n\nexport const createAddKeyJournalRunner = (\n  config: IAddKeyJournalRunnerConfig,\n): IAddKeyJournalRunner => {\n  const keys: IAddKeyJournalStorageKeys = {\n    ...DEFAULT_ADD_KEY_JOURNAL_STORAGE_KEYS,\n    ...config.storageKeys,\n  };\n  const storage = normalizeJournalStorage(config.storage);\n  const { chain } = config;\n  const withMutationLock = config.withMutationLock ?? defaultMutationLock();\n\n  const loadJournalEntries = async (): Promise<TAddKeyJournalEntry[]> =>\n    parseAddKeyJournalEntries(await storage.getItem(keys.journal));\n\n  const writeJournalEntries = async (entries: readonly TAddKeyJournalEntry[]): Promise<void> => {\n    const serialized = serializeAddKeyJournalEntries(entries);\n    try {\n      await storage.setItem(keys.journal, serialized);\n    } catch {\n      throw new AddKeyJournalError(\n        \"journal_persist_failed\",\n        \"This host could not persist the AddKey recovery checkpoint. The previous checkpoint was retained; keep this process alive, resume this exact transfer, and do not start a replacement transaction.\",\n      );\n    }\n  };\n\n  const replaceJournalEntry = async (entry: TAddKeyJournalEntry): Promise<void> => {\n    const entries = await loadJournalEntries();\n    await writeJournalEntries(replaceAddKeyJournalEntry(entries, entry));\n  };\n\n  /**\n   * Prove the precomputed transaction reached exact finality through the shared normalizer +\n   * verifier, then (optionally) replace the replayable signed bytes with the finalized checkpoint.\n   * The status lookup runs FIRST so an unknown transaction fails fast without touching access keys.\n   */\n  const reconcileFinalizedTransaction = async (input: {\n    job: IAddKeyJournalJob;\n    transactionHash: string;\n    finalizedEntry?: TAddKeyFinalizedJournalEntry;\n  }): Promise<string> => {\n    const outcome = await chain.getFinalTransactionStatus(input.job, input.transactionHash);\n    await assertOutcomeProvenFinal(input.job, input.transactionHash, outcome);\n    if (input.finalizedEntry != null) await replaceJournalEntry(input.finalizedEntry);\n    return input.transactionHash;\n  };\n\n  const assertOutcomeProvenFinal = async (\n    job: IAddKeyJournalJob,\n    transactionHash: string,\n    outcome: unknown,\n  ): Promise<void> => {\n    const accessKeys = await chain.getAccessKeys(job);\n    const normalized = normalizeNearAddKeyProof({\n      networkId: job.networkId,\n      destinationPublicKey: job.destinationPublicKey,\n      outcome,\n      accessKeys,\n    });\n    if (!normalized.ok) {\n      throw new AddKeyJournalError(\n        \"finalized_proof_invalid\",\n        `${job.accountId}'s AddKey transaction could not be proven exact and final (${normalized.reason}). The recovery record was retained.`,\n      );\n    }\n    const verified = verifyNewKeyTransferAddKeyProof({\n      expected: {\n        networkId: job.networkId,\n        accountId: job.accountId,\n        sourcePublicKey: job.sourcePublicKey,\n        destinationPublicKey: job.destinationPublicKey,\n        addKeyTransactionHash: transactionHash,\n      },\n      proof: normalized.proof,\n    });\n    if (!verified.verified) {\n      throw new AddKeyJournalError(\n        \"finalized_proof_invalid\",\n        `${job.accountId}'s AddKey transaction could not be proven exact and final (${verified.issue}). The recovery record was retained.`,\n      );\n    }\n  };\n\n  const broadcastSignedTransaction = async (input: {\n    job: IAddKeyJournalJob;\n    signed: TAddKeySignedJournalEntry;\n  }): Promise<string> => {\n    let outcome: unknown;\n    try {\n      outcome = await chain.broadcastSignedTransaction(input.job, {\n        transactionHash: input.signed.transactionHash,\n        signedTransactionBase64: input.signed.signedTransactionBase64,\n      });\n    } catch (broadcastError: unknown) {\n      // A timeout, lost response, or already-consumed nonce is ambiguous. Query the exact\n      // precomputed hash before surfacing the error; never build a replacement transaction here.\n      try {\n        return await reconcileFinalizedTransaction({\n          job: input.job,\n          transactionHash: input.signed.transactionHash,\n          finalizedEntry: finalizedEntryFromSigned(input.signed),\n        });\n      } catch {\n        throw new AddKeyJournalError(\n          \"broadcast_ambiguous\",\n          `${input.job.accountId}'s exact signed AddKey transaction is saved as ${input.signed.transactionHash}, but broadcast/finality is still ambiguous. Resume this transfer to rebroadcast the same bytes; do not start a replacement transfer.`,\n          { cause: broadcastError },\n        );\n      }\n    }\n\n    await assertOutcomeProvenFinal(input.job, input.signed.transactionHash, outcome);\n    await replaceJournalEntry(finalizedEntryFromSigned(input.signed));\n    return input.signed.transactionHash;\n  };\n\n  const submitAddKeyUnlocked = async (job: IAddKeyJournalJob): Promise<string> => {\n    // Journal first: any corruption fails closed BEFORE the first chain call.\n    const journalEntry = findAddKeyJournalEntry(await loadJournalEntries(), job);\n    const accessKeys = readAccessKeySummaries(await chain.getAccessKeys(job), job.accountId);\n    const destinationAccess = accessKeys.find((key) => key.publicKey === job.destinationPublicKey);\n\n    if (journalEntry?.phase === \"finalized\") {\n      return await reconcileFinalizedTransaction({\n        job,\n        transactionHash: journalEntry.transactionHash,\n      });\n    }\n\n    if (journalEntry?.phase === \"transaction_signed\") {\n      if (destinationAccess != null) {\n        return await reconcileFinalizedTransaction({\n          job,\n          transactionHash: journalEntry.transactionHash,\n          finalizedEntry: finalizedEntryFromSigned(journalEntry),\n        });\n      }\n      return await broadcastSignedTransaction({ job, signed: journalEntry });\n    }\n\n    if (destinationAccess != null) {\n      throw new AddKeyJournalError(\n        \"destination_key_unproven\",\n        `${job.accountId} already has this destination key on ${job.networkId}, but no signed transaction hash is journaled for it. Preserve the journal and reconcile or revoke that exact key; key presence alone is not authorization proof.`,\n      );\n    }\n\n    const sourceAccess = accessKeys.find((key) => key.publicKey === job.sourcePublicKey);\n    if (sourceAccess == null) {\n      throw new AddKeyJournalError(\n        \"source_key_missing\",\n        `${job.accountId} does not have the stored source key on ${job.networkId}. Add the account with its current full-access signing key.`,\n      );\n    }\n    if (!sourceAccess.fullAccess) {\n      throw new AddKeyJournalError(\n        \"source_key_not_full_access\",\n        `${job.accountId}'s stored source key is not a full-access key.`,\n      );\n    }\n\n    const intent: TAddKeyIntentJournalEntry = {\n      operationVersion: 1,\n      transferSessionId: job.transferSessionId,\n      blockchainId: job.blockchainId,\n      networkId: job.networkId,\n      accountId: job.accountId,\n      sourcePublicKey: job.sourcePublicKey,\n      destinationPublicKey: job.destinationPublicKey,\n      phase: \"intent_recorded\",\n    };\n    if (journalEntry == null) await replaceJournalEntry(intent);\n\n    const signedTransaction = await chain.signAddKeyTransaction(job);\n    const signedParse = v.safeParse(vAddKeySignedJournalEntry, {\n      ...intent,\n      phase: \"transaction_signed\",\n      transactionHash: signedTransaction.transactionHash,\n      signedTransactionBase64: signedTransaction.signedTransactionBase64,\n    });\n    if (!signedParse.success) {\n      throw new AddKeyJournalError(\n        \"signed_transaction_invalid\",\n        `${job.accountId}'s AddKey transaction was not signed into a bounded canonical form.`,\n      );\n    }\n    await replaceJournalEntry(signedParse.output);\n    return await broadcastSignedTransaction({ job, signed: signedParse.output });\n  };\n\n  /**\n   * Read the destination key's presence on the account at final finality. Returns `null` when the\n   * chain could not be read at all — absence must never be inferred from a failed lookup.\n   */\n  const readDestinationKeyPresence = async (job: IAddKeyJournalJob): Promise<boolean | null> => {\n    try {\n      const summaries = readAccessKeySummaries(await chain.getAccessKeys(job), job.accountId);\n      return summaries.some((key) => key.publicKey === job.destinationPublicKey);\n    } catch {\n      return null;\n    }\n  };\n\n  /**\n   * One pass of the fenced-operation state machine (B-04). Ordered so the cheapest definitive\n   * answer comes first and nothing destructive can happen:\n   *\n   *   1. transaction proven exact and final  → promote the row to `finalized`, resume verification\n   *   2. destination key present on-chain    → the host must revoke it with the source signer\n   *   3. key absent AND bytes provably dead  → safe to archive\n   *   4. anything else                        → ambiguous; nothing changed\n   */\n  const reconcileFencedOperation = async (\n    operation: INewKeyTransferFencedOperation,\n  ): Promise<INewKeyTransferReconcileResult> => {\n    const job = fencedOperationToJob(operation);\n    const entry = findAddKeyJournalEntry(await loadJournalEntries(), job);\n    if (entry == null || entry.phase === \"intent_recorded\") {\n      return { status: \"not_found\", operation };\n    }\n\n    // 1. Already on-chain? Promote and hand the transfer back to normal verification.\n    try {\n      const transactionHash = await reconcileFinalizedTransaction({\n        job,\n        transactionHash: entry.transactionHash,\n        finalizedEntry:\n          entry.phase === \"transaction_signed\" ? finalizedEntryFromSigned(entry) : undefined,\n      });\n      return { status: \"finalized\", operation, transactionHash };\n    } catch {\n      // Not provably final. Fall through — this is the expected path for a transfer that never\n      // landed, and is never on its own evidence that the bytes are dead.\n    }\n\n    const destinationPresent = await readDestinationKeyPresence(job);\n    if (destinationPresent == null) {\n      return { status: \"ambiguous\", operation, detail: \"access_keys_unreadable\" };\n    }\n    if (destinationPresent) {\n      // 2. The key is granted but nothing proves this transfer granted it. Key presence alone is\n      // not authorization proof, so it must be removed with the source signer before the row can\n      // be retired.\n      return { status: \"destination_key_present_unproven\", operation };\n    }\n\n    // 3. The key is absent — but absence today does not mean the signed bytes cannot land\n    // tomorrow. Only a definitive expiry answer closes that gap.\n    if (entry.phase === \"finalized\") {\n      // A finalized row whose key is absent means the grant was already reverted; nothing can\n      // replay it because no signed bytes are retained.\n      return { status: \"destination_key_absent\", operation };\n    }\n    if (chain.isSignedTransactionExpired == null) {\n      return { status: \"ambiguous\", operation, detail: \"transaction_expiry_unknown\" };\n    }\n    let expired: boolean;\n    try {\n      expired = await chain.isSignedTransactionExpired(job, {\n        transactionHash: entry.transactionHash,\n        signedTransactionBase64: entry.signedTransactionBase64,\n      });\n    } catch {\n      return { status: \"ambiguous\", operation, detail: \"transaction_expiry_unknown\" };\n    }\n    return expired\n      ? { status: \"destination_key_absent\", operation }\n      : { status: \"ambiguous\", operation, detail: \"signed_transaction_may_still_land\" };\n  };\n\n  /**\n   * Retire a fenced row. Re-proves on-chain absence of the exact destination key first — the whole\n   * point of the fence is that a caller's word is not evidence.\n   */\n  const archiveReconciledOperation = async (\n    operation: INewKeyTransferFencedOperation,\n  ): Promise<boolean> => {\n    const job = fencedOperationToJob(operation);\n    const entries = await loadJournalEntries();\n    const entry = findAddKeyJournalEntry(entries, job);\n    if (entry == null) return true; // Already gone; archiving is idempotent.\n\n    const destinationPresent = await readDestinationKeyPresence(job);\n    if (destinationPresent !== false) return false;\n\n    try {\n      await writeJournalEntries(\n        entries.filter(\n          (candidate) =>\n            candidate.transferSessionId !== operation.transferSessionId ||\n            candidate.accountId !== operation.accountId,\n        ),\n      );\n    } catch {\n      return false;\n    }\n    return true;\n  };\n\n  const loadStartResult = async (): Promise<IJournaledNewKeyStartResult | null> =>\n    parseJournaledNewKeyStartResult(await storage.getItem(keys.startResult));\n\n  const persistStartResult = async (serialized: string): Promise<void> => {\n    try {\n      await storage.setItem(keys.startResult, serialized);\n    } catch {\n      throw new AddKeyJournalError(\n        \"start_result_persist_failed\",\n        \"The wallet returned destination keys, but the start-result recovery journal could not be persisted. Keep this session open and retry; do not submit AddKey yet.\",\n      );\n    }\n  };\n\n  const removeStartResult = async (): Promise<boolean> => {\n    try {\n      await storage.removeItem(keys.startResult);\n      return true;\n    } catch {\n      return false;\n    }\n  };\n\n  const loadPendingVerification = async (): Promise<TNewKeyTransferVerifyActiveInputV1 | null> =>\n    parsePendingNewKeyVerification(await storage.getItem(keys.pendingVerify));\n\n  const rememberPendingVerification = async (\n    verifyInput: TNewKeyTransferVerifyActiveInputV1,\n  ): Promise<TNewKeyTransferVerifyActiveInputV1> => {\n    const built = buildPendingNewKeyVerification({\n      existingSerialized: await storage.getItem(keys.pendingVerify),\n      verifyInput,\n    });\n    try {\n      await storage.setItem(keys.pendingVerify, built.serialized);\n    } catch {\n      throw new AddKeyJournalError(\n        \"pending_verify_persist_failed\",\n        \"Every AddKey finalized, but the secret-free verification proof could not be persisted. Keep this session open and retry; do not reset this transfer.\",\n      );\n    }\n    return built.parsed;\n  };\n\n  return {\n    submitAddKey: async (job) =>\n      await withMutationLock(async () => await submitAddKeyUnlocked(job)),\n\n    loadJournalEntries,\n\n    hasProtectedRecovery: async (transferSessionId) =>\n      addKeyJournalHasProtectedRecovery(await storage.getItem(keys.journal), transferSessionId),\n\n    hasOrphanedSignedRecovery: async () =>\n      addKeyJournalHasOrphanedSignedRecovery(await storage.getItem(keys.journal)),\n\n    buildReconciliationReport: async () => {\n      let entries: TAddKeyJournalEntry[] | null;\n      try {\n        entries = await loadJournalEntries();\n      } catch {\n        entries = null;\n      }\n      return buildNewKeyTransferReconciliationReport({\n        entries,\n        boundTransferSessionId: (await loadStartResult())?.output.transferSessionId ?? null,\n      });\n    },\n\n    reconcileFencedOperation: async (operation) =>\n      await withMutationLock(async () => await reconcileFencedOperation(operation)),\n\n    archiveReconciledOperation: async (operation) =>\n      await withMutationLock(async () => await archiveReconciledOperation(operation)),\n\n    rememberStartResult: async ({ resultHash, output }) => {\n      const built = buildJournaledNewKeyStartResult({\n        existingSerialized: await storage.getItem(keys.startResult),\n        resultHash,\n        output,\n      });\n      await persistStartResult(built.serialized);\n      return built.journal;\n    },\n\n    receiveSignedStartResult: async ({ request, resultHash, actionResult }) => {\n      const consumed = consumeSignedNewKeyStartResult({\n        request,\n        resultHash,\n        actionResult,\n        existingSerialized: await storage.getItem(keys.startResult),\n      });\n      if (!consumed.accepted) return consumed;\n      await persistStartResult(consumed.serialized);\n      return { accepted: true, journal: consumed.journal };\n    },\n\n    loadStartResult,\n\n    discardStartResult: async () => {\n      const journaledStart = await loadStartResult();\n      if (\n        journaledStart != null &&\n        addKeyJournalHasProtectedRecovery(\n          await storage.getItem(keys.journal),\n          journaledStart.output.transferSessionId,\n        )\n      ) {\n        return false;\n      }\n      if (journaledStart != null) {\n        try {\n          const entries = await loadJournalEntries();\n          const retainedEntries = entries.filter(\n            (entry) =>\n              entry.transferSessionId !== journaledStart.output.transferSessionId ||\n              entry.phase !== \"intent_recorded\",\n          );\n          if (retainedEntries.length !== entries.length) await writeJournalEntries(retainedEntries);\n        } catch {\n          return false;\n        }\n      }\n      return await removeStartResult();\n    },\n\n    loadPendingVerification,\n    rememberPendingVerification,\n\n    clearPendingVerification: async (transferSessionId) => {\n      const pending = await loadPendingVerification();\n      if (pending?.transferSessionId !== transferSessionId) return true;\n      try {\n        const entries = await loadJournalEntries();\n        const transferEntries = entries.filter(\n          (entry) => entry.transferSessionId === transferSessionId,\n        );\n        if (transferEntries.some((entry) => entry.phase !== \"finalized\")) {\n          return false;\n        }\n        if (transferEntries.length > 0) {\n          await writeJournalEntries(\n            entries.filter((entry) => entry.transferSessionId !== transferSessionId),\n          );\n        }\n        await storage.removeItem(keys.pendingVerify);\n        return true;\n      } catch {\n        return false;\n      }\n    },\n\n    discardPendingVerification: async () => {\n      try {\n        await storage.removeItem(keys.pendingVerify);\n        return true;\n      } catch {\n        return false;\n      }\n    },\n\n    commitVerificationIntent: async (verifyInput) => {\n      const remembered = await rememberPendingVerification(verifyInput);\n      if (!(await removeStartResult())) {\n        throw new AddKeyJournalError(\n          \"start_result_clear_failed\",\n          \"Verification proof is safely saved, but the older start-result journal could not be cleared. Resume verification; do not submit AddKey again.\",\n        );\n      }\n      return remembered;\n    },\n  };\n};\n","import * as v from \"valibot\";\nimport {\n  hashCanonicalJsonSha256Base64,\n  type ICanonicalChallenge,\n} from \"../../../../utils/serialization/canonical_json\";\nimport { vBase64HashSha256, vBase64SignatureEd25519 } from \"../../../core/core_valibot_schemas\";\nimport { vDurableObjectId, vIncarnationId } from \"../../../core/meteor_core.schema\";\nimport {\n  vSerializedCryptoKeyDataEd25519_Raw,\n  vSerializedCryptoKeyDataX25519_Raw,\n} from \"../../../crypto/crypto.schema\";\nimport { vPartnerMetadata } from \"../../client/partner/partner_client.schema\";\nimport { vBridgeLease } from \"../bridge.schema\";\nimport { vSessionIssuedAt, vSessionOperationId } from \"./session.schema\";\n\n/** Frozen, wallet-only pending consent. No action payload or user secrets belong here. */\nexport const vSessionLinkConfirmation = v.strictObject({\n  version: v.literal(1),\n  bridgeId: vDurableObjectId,\n  bridgeLease: vBridgeLease,\n  walletPerId: vDurableObjectId,\n  accountIncarnation: vIncarnationId,\n  walletVerifyPublicKey: vSerializedCryptoKeyDataEd25519_Raw,\n  walletExchangePublicKey: vSerializedCryptoKeyDataX25519_Raw,\n  partnerId: vDurableObjectId,\n  partnerVerifyPublicKey: vSerializedCryptoKeyDataEd25519_Raw,\n  partnerExchangePublicKey: vSerializedCryptoKeyDataX25519_Raw,\n  partnerMetadata: vPartnerMetadata,\n  requestHash: vBase64HashSha256,\n  authorizationMode: v.literal(\"partner_link\"),\n  rememberPartner: v.literal(true),\n  operationId: vSessionOperationId,\n  issuedAt: vSessionIssuedAt,\n  expiresAt: vSessionIssuedAt,\n});\nexport type TSessionLinkConfirmation = v.InferOutput<typeof vSessionLinkConfirmation>;\n\n/** The lease binds the backend trust domain; the hash covers every displayed/identity field. */\nexport const buildSessionLinkConfirmationChallenge = (\n  confirmation: TSessionLinkConfirmation,\n): ICanonicalChallenge => ({\n  domainTag: \"meteor-connect-session-link-confirmation-v1\",\n  version: 1,\n  fields: { confirmationHash: hashCanonicalJsonSha256Base64(confirmation) },\n});\n\nexport const vSessionLinkConfirmationReceipt = v.strictObject({\n  confirmation: vSessionLinkConfirmation,\n  signatureBase64: vBase64SignatureEd25519,\n});\nexport type TSessionLinkConfirmationReceipt = v.InferOutput<typeof vSessionLinkConfirmationReceipt>;\n","import { defineRealm, type TInferRealmState, t } from \"@meteorwallet/connect-core/realm\";\nimport * as v from \"valibot\";\nimport { vBase64HashSha256, vBase64SignatureEd25519 } from \"../model/core/core_valibot_schemas\";\nimport { vIncarnationId } from \"../model/core/meteor_core.schema\";\nimport { vEncryptedAesGcmPayload } from \"../model/crypto/crypto.schema\";\nimport { vActionPayloadJsonObject } from \"../model/durable_object/bridge/bridge.schema\";\nimport {\n  EBridgeInteractionMode,\n  ESessionAuthorizationLevel,\n  ESessionAuthorizationMode,\n  ESessionPhase,\n  ESessionResourceProfile,\n  getSessionResourceProfilePolicy,\n  SESSION_MAX_REDIAL_ATTEMPTS,\n  SESSION_MAX_TURNS,\n  vSessionIssuedAt,\n  vSessionOperationId,\n  vSessionTurnId,\n  vSessionTurnSequence,\n} from \"../model/durable_object/bridge/session/session.schema\";\nimport { vSessionLinkConfirmationReceipt } from \"../model/durable_object/bridge/session/session_link_confirmation\";\nimport { vWalletClientConnectionInfo } from \"../model/durable_object/client/partner/partner_client.schema\";\n\n/**\n * `bridge_session_realm` — the view-sliced projection of a `session_v1` session (plan §9.4). A\n * It is hosted in the session bridge DO; a wallet attaching with an unknown or stale definition\n * gets the typed `realm_unknown`/`schema_mismatch` refusal.\n *\n * Contract posture (0.79.0 surface, §8.4 N5/N6):\n * - every `t.schema` leaf carries a `hashTag` from birth — bump the tag on ANY leaf-contract\n *   change so stale clients fail at attach instead of only failing CI fixtures;\n * - everything else uses bounded primitives (`t.number({min,max,integer})`,\n *   `t.string({maxLength})`), enforced state-aware against the candidate next state of every\n *   commit INCLUDING server `update()` output — an over-bound projection fails the realm commit\n *   and takes the D21 projection-repair path, never a broadcast;\n * - all paths are `r.serverOnly` (clients only observe);\n * - realm state is a disposable materialized view — `stateRevision` is projected as the bounded\n *   synchronization fence, and every leaf derives from the committed session/turn snapshot.\n *\n * View slicing is role separation, not an authorization boundary: the E2E\n * envelopes, salt-hash gate, and handler signature checks carry authorization. No secret (PIN,\n * salts, keys, plaintext results) ever enters this realm.\n */\nexport enum ESessionRealmAvatar {\n  wallet = \"wallet\",\n  partner = \"partner\",\n}\n\n/** Partner-facing E2E result relay for the CURRENT turn, bound to its exact identity. */\nexport const vSessionRealmTurnResult = v.strictObject({\n  sequence: vSessionTurnSequence,\n  turnId: vSessionTurnId,\n  requestHash: vBase64HashSha256,\n  resultHash: vBase64HashSha256,\n  resultEnvelopeEncrypted: vEncryptedAesGcmPayload,\n  walletResultEnvelopeSignatureBase64: vBase64SignatureEd25519,\n});\n\n/**\n * Wallet-facing signed plaintext turn delivery (non-sensitive actions, post-authorization). Carries\n * the COMPLETE signed envelope fields so the wallet can rebuild the exact stage/submit canonical\n * challenge and verify `partnerTurnSignatureBase64` independently (§5.4).\n */\nexport const vSessionRealmTurnRequest = v.strictObject({\n  sequence: vSessionTurnSequence,\n  turnId: vSessionTurnId,\n  operationId: vSessionOperationId,\n  issuedAt: vSessionIssuedAt,\n  recoveryContractHash: vBase64HashSha256,\n  requestHash: vBase64HashSha256,\n  priorResultHash: v.nullable(vBase64HashSha256),\n  actionRequest: vActionPayloadJsonObject,\n  partnerTurnSignatureBase64: vBase64SignatureEd25519,\n});\n\nexport const vSessionRealmFailureCode = v.picklist([\n  \"wallet_update_required\",\n  \"pin_attempts_exceeded\",\n  \"trusted_link_revoked\",\n  \"bridge_failed\",\n  \"bridge_expired\",\n  \"session_closed\",\n]);\n\nexport type TSessionRealmFailureCode = v.InferOutput<typeof vSessionRealmFailureCode>;\n\nconst MAX_EPOCH_MILLIS = 4_102_444_800_000; // 2100-01-01; generous bounded ceiling for deadlines.\n\nexport const bridge_session_realm = defineRealm({\n  id: \"bridge_session_realm\",\n  security: \"encrypted\",\n  avatars: {\n    [ESessionRealmAvatar.wallet]: { persistentId: t.string({ maxLength: 128 }) },\n    [ESessionRealmAvatar.partner]: { persistentId: t.string({ maxLength: 128 }) },\n  },\n  state: {\n    // Both roles: session phase, bounded revision fence, current sequence, both deadlines.\n    interactionMode: t.schema(v.literal(EBridgeInteractionMode.session_v1), {\n      hashTag: \"interaction-mode-v1\",\n    }),\n    phase: t.schema(v.enum(ESessionPhase), { hashTag: \"phase-v2-confirmation\" }),\n    resourceProfile: t.schema(v.enum(ESessionResourceProfile), {\n      hashTag: \"resource-profile-v1\",\n    }),\n    maxTurns: t.number({ min: 1, max: SESSION_MAX_TURNS, integer: true }),\n    maxRedialAttempts: t.number({\n      min: 1,\n      max: SESSION_MAX_REDIAL_ATTEMPTS,\n      integer: true,\n    }),\n    authorizationMode: t.schema(v.enum(ESessionAuthorizationMode), {\n      hashTag: \"authorization-mode-v2-confirmation\",\n    }),\n    authorizationLevel: t.optional(\n      t.schema(v.enum(ESessionAuthorizationLevel), {\n        hashTag: \"authorization-level-v1\",\n      }),\n    ),\n    authorizationLinkIncarnation: t.optional(\n      t.schema(vIncarnationId, {\n        hashTag: \"authorization-link-incarnation-v1\",\n      }),\n    ),\n    stateRevision: t.number({ min: 0, max: Number.MAX_SAFE_INTEGER, integer: true }),\n    sequence: t.optional(t.number({ min: 1, max: SESSION_MAX_TURNS, integer: true })),\n    turnId: t.optional(t.string({ maxLength: 64 })),\n    requestHash: t.optional(t.string({ maxLength: 64 })),\n    idleExpiresAt: t.number({ min: 0, max: MAX_EPOCH_MILLIS, integer: true }),\n    absoluteExpiresAt: t.number({ min: 0, max: MAX_EPOCH_MILLIS, integer: true }),\n    closeAfterTurn: t.boolean(),\n    closeAfterResultAck: t.boolean(),\n    externalWorkHoldConsumed: t.boolean(),\n    // Partner-facing safe machine code only.\n    failureCode: t.optional(t.schema(vSessionRealmFailureCode, { hashTag: \"failure-code-v2\" })),\n    // Wallet-facing: the current turn as signed plaintext (delivery mode `plaintext_post_authorization`).\n    turnRequest: t.optional(t.schema(vSessionRealmTurnRequest, { hashTag: \"turn-request-v3\" })),\n    // Wallet-facing, sensitive delivery: the complete signed turn envelope encrypted to the\n    // claiming wallet. The plaintext leaf is never assigned for these turns.\n    turnRequestEncrypted: t.optional(\n      t.schema(vEncryptedAesGcmPayload, { hashTag: \"turn-request-encrypted-v1\" }),\n    ),\n    // Partner-facing: the claimed wallet's connection details (partner derives the E2E key).\n    clientConnection: t.optional(\n      t.schema(\n        v.object({\n          ...vWalletClientConnectionInfo.entries,\n          linkConfirmationReceipt: v.optional(vSessionLinkConfirmationReceipt),\n        }),\n        { hashTag: \"client-connection-v2-confirmation\" },\n      ),\n    ),\n    // Partner-facing: the retained result relay for the current turn (until exact acknowledgement).\n    turnResult: t.optional(t.schema(vSessionRealmTurnResult, { hashTag: \"turn-result-v3\" })),\n  },\n  rules: (r) => [\n    r.path(\"interactionMode\").view(r.everyone).alter(r.serverOnly),\n    r.path(\"phase\").view(r.everyone).alter(r.serverOnly),\n    r.path(\"resourceProfile\").view(r.everyone).alter(r.serverOnly),\n    r.path(\"maxTurns\").view(r.everyone).alter(r.serverOnly),\n    r.path(\"maxRedialAttempts\").view(r.everyone).alter(r.serverOnly),\n    r.path(\"authorizationMode\").view(r.everyone).alter(r.serverOnly),\n    r.path(\"authorizationLevel\").view(r.everyone).alter(r.serverOnly),\n    r.path(\"authorizationLinkIncarnation\").view(r.everyone).alter(r.serverOnly),\n    r.path(\"stateRevision\").view(r.everyone).alter(r.serverOnly),\n    r.path(\"sequence\").view(r.everyone).alter(r.serverOnly),\n    r.path(\"turnId\").view(r.everyone).alter(r.serverOnly),\n    r.path(\"requestHash\").view(r.everyone).alter(r.serverOnly),\n    r.path(\"idleExpiresAt\").view(r.everyone).alter(r.serverOnly),\n    r.path(\"absoluteExpiresAt\").view(r.everyone).alter(r.serverOnly),\n    r.path(\"closeAfterTurn\").view(r.everyone).alter(r.serverOnly),\n    r.path(\"closeAfterResultAck\").view(r.everyone).alter(r.serverOnly),\n    r.path(\"externalWorkHoldConsumed\").view(r.everyone).alter(r.serverOnly),\n    r.path(\"failureCode\").view(r.avatarTypes(ESessionRealmAvatar.partner)).alter(r.serverOnly),\n    r.path(\"turnRequest\").view(r.avatarTypes(ESessionRealmAvatar.wallet)).alter(r.serverOnly),\n    r\n      .path(\"turnRequestEncrypted\")\n      .view(r.avatarTypes(ESessionRealmAvatar.wallet))\n      .alter(r.serverOnly),\n    r.path(\"clientConnection\").view(r.avatarTypes(ESessionRealmAvatar.partner)).alter(r.serverOnly),\n    r.path(\"turnResult\").view(r.avatarTypes(ESessionRealmAvatar.partner)).alter(r.serverOnly),\n  ],\n});\n\nexport type TSessionRealmState = TInferRealmState<typeof bridge_session_realm>;\n\n/** Genesis projection for a freshly allocated (still private, unclaimable) session. */\nexport const sessionRealmGenesisState = (facts: {\n  idleExpiresAt: number;\n  absoluteExpiresAt: number;\n  resourceProfile?: ESessionResourceProfile;\n  authorizationMode?: ESessionAuthorizationMode;\n}) =>\n  (() => {\n    const resourceProfile = facts.resourceProfile ?? ESessionResourceProfile.single_turn_v1;\n    return {\n      interactionMode: EBridgeInteractionMode.session_v1,\n      phase: ESessionPhase.initializing,\n      resourceProfile,\n      maxTurns: getSessionResourceProfilePolicy(resourceProfile).maxTurns,\n      maxRedialAttempts: getSessionResourceProfilePolicy(resourceProfile).maxRedialAttempts,\n      authorizationMode: facts.authorizationMode ?? ESessionAuthorizationMode.fresh_pin,\n      stateRevision: 0,\n      idleExpiresAt: facts.idleExpiresAt,\n      absoluteExpiresAt: facts.absoluteExpiresAt,\n      closeAfterTurn: false,\n      closeAfterResultAck: false,\n      externalWorkHoldConsumed: false,\n    } as const;\n  })();\n","import { sha256 } from \"@noble/hashes/sha2.js\";\nimport { base64 } from \"@scure/base\";\n\nexport const hashTextSha256ToBase64 = (text: string): string => {\n  const hashedTextBytes = sha256(new TextEncoder().encode(text));\n  return base64.encode(hashedTextBytes);\n};\n","import {\n  importEd25519Key,\n  importX25519Key,\n  serializeEd25519Key_Jwk,\n  serializeEd25519Key_Raw,\n  serializeX25519Key_Jwk,\n  serializeX25519Key_Raw,\n} from \"../../crypto\";\nimport type {\n  IClientKeys_Deserialized,\n  IClientKeys_Serialized,\n} from \"./ClientKeySerialization.types\";\n\nexport const ClientKeySerialization = {\n  /**\n   * Serializes IBridgeKeysInput into the standard persisted format for Third Party clients.\n   */\n  async serializeClientKeys(keys: IClientKeys_Deserialized): Promise<IClientKeys_Serialized> {\n    const signingPrivate = await serializeEd25519Key_Jwk(keys.signingKeyPair.privateKey);\n    const signingPublic = await serializeEd25519Key_Raw(keys.signingKeyPair.publicKey);\n    const exchangePrivate = await serializeX25519Key_Jwk(keys.exchangeKeyPair.privateKey);\n    const exchangePublic = await serializeX25519Key_Raw(keys.exchangeKeyPair.publicKey);\n\n    return {\n      signingKeyPairSerialized: {\n        private: signingPrivate.prefixed,\n        public: signingPublic.prefixed,\n      },\n      exchangeKeyPairSerialized: {\n        private: exchangePrivate.prefixed,\n        public: exchangePublic.prefixed,\n      },\n    };\n  },\n\n  /**\n   * Deserializes the persisted format back into IBridgeKeysInput for Third Party clients.\n   */\n  async deserializeClientKeys(\n    serialized: IClientKeys_Serialized,\n  ): Promise<IClientKeys_Deserialized> {\n    const signingKeyPair: CryptoKeyPair = {\n      privateKey: await importEd25519Key.private.fromFormattedString.extractable(\n        serialized.signingKeyPairSerialized.private,\n      ),\n      publicKey: await importEd25519Key.public.fromFormattedString.extractable(\n        serialized.signingKeyPairSerialized.public,\n      ),\n    };\n\n    const exchangeKeyPair: CryptoKeyPair = {\n      privateKey: await importX25519Key.private.fromFormattedString.extractable(\n        serialized.exchangeKeyPairSerialized.private,\n      ),\n      publicKey: await importX25519Key.public.fromFormattedString.extractable(\n        serialized.exchangeKeyPairSerialized.public,\n      ),\n    };\n\n    return {\n      signingKeyPair,\n      exchangeKeyPair,\n    };\n  },\n};\n"],"mappings":";;;;;;;;;;;;;;;;AAGA,IAAY,qBAAL,yBAAA,oBAAA;CACL,mBAAA,+BAAA;CACA,mBAAA,kCAAA;CACA,mBAAA,uBAAA;;AACF,EAAA,CAAA,CAAA;AAEA,MAAa,sBAAsBA,uBAAAA,gBAAgB;CACjD,QAAQ;CACR,uBAAuBC,kBAAAA,YAAY;CACnC,QAAQ;GAC0CC,8BAAAA,uBAAAA,IAAI,EAClD,SAAS,sCACX,CAAC;GACkDA,iCAAAA,uBAAAA,IAAI,EACrD,SAAS,yC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