@assetpay/steam-mobile 1.0.1 → 1.0.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +34 -0
- package/dist/index.d.mts +10 -2
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +80 -30
- package/dist/index.mjs.map +1 -1
- package/package.json +7 -7
package/dist/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","names":["Buffer","headerValue","RsaReqSchema","RsaResSchema","BeginReqSchema","BeginResSchema","PollReqSchema","PollResSchema","GuardReqSchema","GuardResSchema","GetSessReqSchema","GetSessResSchema","RevokeReqSchema","RevokeResSchema","toUint8","Buffer","Buffer","Buffer","BROWSER_ACCEPT","steamTotpTime","SteamTotp.getDeviceID","SteamTotp.time","SteamTotp.getConfirmationKey","time","Buffer","Buffer","RequestSchema","ResponseSchema","fetchTradeStatus","fetchTradeHistory","fetchTradeOffersSummary"],"sources":["../src/core/constants.ts","../src/core/enums.ts","../src/core/eresults.ts","../src/core/errors.ts","../src/protobufs/steammessages_auth_pb.ts","../src/session/protoTransport.ts","../src/auth/AuthClient.ts","../src/crypto/rsa.ts","../src/crypto/steamTotp.ts","../src/auth/deviceDetails.ts","../src/auth/CredentialSession.ts","../src/core/mobileProfile.ts","../src/http/HttpClient.ts","../src/auth/loginWithCredentials.ts","../src/core/paginate.ts","../src/core/parseStrError.ts","../src/core/rateLimits.ts","../src/http/checkers.ts","../src/http/tradePageError.ts","../src/models/EconItem.ts","../src/community/openid.ts","../src/community/tradeProtection.ts","../src/community/CommunityNamespace.ts","../src/http/queryTime.ts","../src/community/confirmations.ts","../src/core/offerState.ts","../src/core/target.ts","../src/http/webApi.ts","../src/keyApi/SteamWebApi.ts","../src/protobufs/csgo_econ_preview_pb.ts","../src/models/inspect.ts","../src/session/tokens.ts","../src/session/SessionManager.ts","../src/community/userDetails.ts","../src/trade/exchange.ts","../src/trade/polling.ts","../src/trade/TradeOffer.ts","../src/trade/TradeNamespace.ts","../src/SteamMobile.ts"],"sourcesContent":["export const LANG = { l: \"english\", language: \"en\" } as const;\n\nexport const URLS = {\n community: \"https://steamcommunity.com\",\n store: \"https://store.steampowered.com\",\n help: \"https://help.steampowered.com\",\n api: \"https://api.steampowered.com\",\n} as const;\n\nexport const DEFAULT_CONTEXTID = \"2\";\n\nexport const ACCESS_TOKEN_RENEW_THRESHOLD_SECONDS = 300;\n// When the refresh token is within this window of expiry, mint with renew=true to rotate it\n// (the MobileApp self-renew path) so an active client's credential never lapses.\nexport const REFRESH_TOKEN_RENEW_THRESHOLD_SECONDS = 30 * 86_400;\n","export enum ETradeOfferState {\n Invalid = 1,\n Active = 2,\n Accepted = 3,\n Countered = 4,\n Expired = 5,\n Canceled = 6,\n Declined = 7,\n InvalidItems = 8,\n CreatedNeedsConfirmation = 9,\n CanceledBySecondFactor = 10,\n InEscrow = 11,\n /** Trade was reverted by the user (Trade protection update 2025) */\n Reverted = 12,\n}\n\nexport enum ETradeStatus {\n Init = 0,\n PreCommitted = 1,\n Committed = 2,\n Complete = 3,\n Failed = 4,\n PartialSupportRollback = 5,\n FullSupportRollback = 6,\n SupportRollback_Selective = 7,\n RollbackFailed = 8,\n RollbackAbandoned = 9,\n InEscrow = 10,\n EscrowRollback = 11,\n /** Trade was reverted by the user (Trade protection update 2025) */\n Reverted = 12,\n}\n\nexport enum EConfirmationMethod {\n None = 0,\n Email = 1,\n MobileApp = 2,\n}\n\nexport enum EConfirmationType {\n Invalid = 0,\n Generic = 1,\n Trade = 2,\n MarketListing = 3,\n FeatureOptOut = 4,\n PhoneNumberChange = 5,\n AccountRecovery = 6,\n}\n\nexport enum EOfferFilter {\n ActiveOnly = 1,\n HistoricalOnly = 2,\n All = 3,\n}\n\n// IAuthenticationService enums — clean public-API aliases of the generated wire enums (same values).\nexport enum EAuthTokenPlatformType {\n Unknown = 0,\n SteamClient = 1,\n WebBrowser = 2,\n MobileApp = 3,\n}\n\nexport enum ESessionPersistence {\n Invalid = -1,\n Ephemeral = 0,\n Persistent = 1,\n}\n\nexport enum EAuthSessionGuardType {\n Unknown = 0,\n None = 1,\n EmailCode = 2,\n DeviceCode = 3,\n DeviceConfirmation = 4,\n EmailConfirmation = 5,\n MachineToken = 6,\n LegacyMachineAuth = 7,\n}\n\nexport enum EAuthTokenRevokeAction {\n Logout = 0,\n Permanent = 1,\n Replaced = 2,\n Support = 3,\n Consume = 4,\n NonRememberedLogout = 5,\n NonRememberedPermanent = 6,\n Automatic = 7,\n}\n\nexport enum ETokenRenewalType {\n None = 0,\n Allow = 1,\n}\n\nexport enum EResult {\n Invalid = 0,\n OK = 1,\n Fail = 2,\n NoConnection = 3,\n InvalidPassword = 5,\n LoggedInElsewhere = 6,\n InvalidProtocolVer = 7,\n InvalidParam = 8,\n FileNotFound = 9,\n Busy = 10,\n InvalidState = 11,\n InvalidName = 12,\n InvalidEmail = 13,\n DuplicateName = 14,\n AccessDenied = 15,\n Timeout = 16,\n Banned = 17,\n AccountNotFound = 18,\n InvalidSteamID = 19,\n ServiceUnavailable = 20,\n NotLoggedOn = 21,\n Pending = 22,\n EncryptionFailure = 23,\n InsufficientPrivilege = 24,\n LimitExceeded = 25,\n Revoked = 26,\n Expired = 27,\n AlreadyRedeemed = 28,\n DuplicateRequest = 29,\n AlreadyOwned = 30,\n IPNotFound = 31,\n PersistFailed = 32,\n LockingFailed = 33,\n LogonSessionReplaced = 34,\n ConnectFailed = 35,\n HandshakeFailed = 36,\n IOFailure = 37,\n RemoteDisconnect = 38,\n ShoppingCartNotFound = 39,\n Blocked = 40,\n Ignored = 41,\n NoMatch = 42,\n AccountDisabled = 43,\n ServiceReadOnly = 44,\n AccountNotFeatured = 45,\n AdministratorOK = 46,\n ContentVersion = 47,\n TryAnotherCM = 48,\n PasswordRequiredToKickSession = 49,\n AlreadyLoggedInElsewhere = 50,\n Suspended = 51,\n Cancelled = 52,\n DataCorruption = 53,\n DiskFull = 54,\n RemoteCallFailed = 55,\n PasswordUnset = 56,\n ExternalAccountUnlinked = 57,\n PSNTicketInvalid = 58,\n ExternalAccountAlreadyLinked = 59,\n RemoteFileConflict = 60,\n IllegalPassword = 61,\n SameAsPreviousValue = 62,\n AccountLogonDenied = 63,\n CannotUseOldPassword = 64,\n InvalidLoginAuthCode = 65,\n AccountLogonDeniedNoMail = 66,\n HardwareNotCapableOfIPT = 67,\n IPTInitError = 68,\n ParentalControlRestricted = 69,\n FacebookQueryError = 70,\n ExpiredLoginAuthCode = 71,\n IPLoginRestrictionFailed = 72,\n AccountLockedDown = 73,\n AccountLogonDeniedVerifiedEmailRequired = 74,\n NoMatchingURL = 75,\n BadResponse = 76,\n RequirePasswordReEntry = 77,\n ValueOutOfRange = 78,\n UnexpectedError = 79,\n Disabled = 80,\n InvalidCEGSubmission = 81,\n RestrictedDevice = 82,\n RegionLocked = 83,\n RateLimitExceeded = 84,\n AccountLoginDeniedNeedTwoFactor = 85,\n ItemDeleted = 86,\n AccountLoginDeniedThrottle = 87,\n TwoFactorCodeMismatch = 88,\n TwoFactorActivationCodeMismatch = 89,\n AccountAssociatedToMultiplePartners = 90,\n NotModified = 91,\n NoMobileDevice = 92,\n TimeNotSynced = 93,\n SMSCodeFailed = 94,\n AccountLimitExceeded = 95,\n AccountActivityLimitExceeded = 96,\n PhoneActivityLimitExceeded = 97,\n RefundToWallet = 98,\n EmailSendFailure = 99,\n NotSettled = 100,\n NeedCaptcha = 101,\n GSLTDenied = 102,\n GSOwnerDenied = 103,\n InvalidItemType = 104,\n IPBanned = 105,\n GSLTExpired = 106,\n InsufficientFunds = 107,\n TooManyPending = 108,\n NoSiteLicensesFound = 109,\n WGNetworkSendExceeded = 110,\n AccountNotFriends = 111,\n LimitedUserAccount = 112,\n}\n","import { EResult } from \"./enums.js\";\n\nexport const TRANSIENT_ERESULTS: ReadonlySet<number> = new Set([\n EResult.ServiceUnavailable,\n EResult.Busy,\n EResult.Timeout,\n EResult.TryAnotherCM,\n EResult.RemoteCallFailed,\n]);\n\nexport function isTransientEResult(eresult: number | undefined): boolean {\n return eresult !== undefined && TRANSIENT_ERESULTS.has(eresult);\n}\n\n// Confirmed-dead-token eresults; anything else is treated as transient so a blip never re-bootstraps.\nexport const TERMINAL_AUTH_ERESULTS: ReadonlySet<number> = new Set([\n EResult.InvalidPassword,\n EResult.AccessDenied,\n EResult.Revoked,\n EResult.Expired,\n]);\n\nexport function isTerminalAuthEResult(eresult: number | undefined): boolean {\n return eresult !== undefined && TERMINAL_AUTH_ERESULTS.has(eresult);\n}\n","import { isTransientEResult } from \"./eresults.js\";\n\n// Fallback so every RateLimitError has a concrete unlockAt (Steam never sends Retry-After).\nexport const DEFAULT_RATE_LIMIT_RETRY_MS = 60_000;\n\nexport class SteamError extends Error {\n readonly eresult?: number;\n readonly body?: unknown;\n\n constructor(message: string, options?: { eresult?: number; body?: unknown; cause?: unknown }) {\n super(message, options?.cause !== undefined ? { cause: options.cause } : undefined);\n this.name = \"SteamError\";\n if (options?.eresult !== undefined) this.eresult = options.eresult;\n if (options?.body !== undefined) this.body = options.body;\n }\n}\n\nexport class ProxyError extends SteamError {\n constructor(message: string, options?: { cause?: unknown }) {\n super(message, options);\n this.name = \"ProxyError\";\n }\n}\n\nexport class HttpStatusError extends SteamError {\n readonly statusCode: number;\n\n constructor(statusCode: number, message?: string, body?: unknown) {\n super(message ?? `HTTP error ${statusCode}`, { body });\n this.name = \"HttpStatusError\";\n this.statusCode = statusCode;\n }\n}\n\nexport class SteamSessionExpiredError extends SteamError {\n constructor(message = \"Not Logged In\") {\n super(message);\n this.name = \"SteamSessionExpiredError\";\n }\n}\n\n// Steam OpenID relying-party login failed (no interstitial form, missing assertion redirect, etc.).\nexport class OpenIdError extends SteamError {\n constructor(message: string) {\n super(message);\n this.name = \"OpenIdError\";\n }\n}\n\nexport class RateLimitError extends SteamError {\n readonly statusCode: number | undefined;\n readonly retryAfterMs: number;\n readonly unlockAt: number;\n\n constructor(\n options: {\n message?: string;\n body?: unknown;\n retryAfterMs?: number;\n eresult?: number;\n statusCode?: number;\n } = {},\n ) {\n super(options.message ?? \"Rate limit exceeded\", {\n ...(options.eresult !== undefined ? { eresult: options.eresult } : {}),\n body: options.body,\n });\n this.name = \"RateLimitError\";\n this.statusCode = options.statusCode;\n this.retryAfterMs = options.retryAfterMs ?? DEFAULT_RATE_LIMIT_RETRY_MS;\n this.unlockAt = Date.now() + this.retryAfterMs;\n }\n}\n\nexport class EscrowError extends SteamError {\n readonly escrowDays: number;\n\n constructor(escrowDays: number, message?: string) {\n super(message ?? `Trade would be held in escrow for ${escrowDays} days`);\n this.name = \"EscrowError\";\n this.escrowDays = escrowDays;\n }\n}\n\nexport class TradeBanError extends SteamError {\n constructor(message = \"Trade ban\") {\n super(message);\n this.name = \"TradeBanError\";\n }\n}\n\nexport class OfferLimitError extends SteamError {\n constructor(message = \"Sent too many trade offers\") {\n super(message, { eresult: 25 });\n this.name = \"OfferLimitError\";\n }\n}\n\n// Steam blocks the action because we logged in from a new device recently.\nexport class NewDeviceError extends SteamError {\n constructor(message = \"You have logged in from a new device\", options?: { eresult?: number }) {\n super(message, options);\n this.name = \"NewDeviceError\";\n }\n}\n\n// Target account is not in a state where it can complete trades (limited, escrow-only, etc.).\nexport class TargetCannotTradeError extends SteamError {\n constructor(message = \"This user is not available to trade\", options?: { eresult?: number }) {\n super(message, options);\n this.name = \"TargetCannotTradeError\";\n }\n}\n\n// The game's item server (its Game Coordinator) is unreachable — transient, per-app, retry later.\nexport class ItemServerUnavailableError extends SteamError {\n constructor(\n message = \"Steam is currently unable to contact the game's item server\",\n options?: { eresult?: number },\n ) {\n super(message, { eresult: options?.eresult ?? 102 });\n this.name = \"ItemServerUnavailableError\";\n }\n}\n\nexport class ConfirmationError extends SteamError {\n constructor(message: string) {\n super(message);\n this.name = \"ConfirmationError\";\n }\n}\n\nexport class FamilyViewError extends SteamError {\n constructor(message = \"Family View Restricted\") {\n super(message);\n this.name = \"FamilyViewError\";\n }\n}\n\n// Partner/profile inventory is private (or friends-only and we're not friends).\n// A trade URL/token does NOT bypass inventory privacy — only inventory privacy does.\nexport class PrivateInventoryError extends SteamError {\n constructor(message = \"This profile's inventory is private.\") {\n super(message);\n this.name = \"PrivateInventoryError\";\n }\n}\n\n// Credential-login failures; carries Steam's extended_error_message when present.\nexport class LoginError extends SteamError {\n readonly extendedErrorMessage: string | undefined;\n readonly isTransient: boolean;\n\n constructor(\n message: string,\n options?: { eresult?: number; body?: unknown; extendedErrorMessage?: string },\n ) {\n super(message, options);\n this.name = \"LoginError\";\n this.extendedErrorMessage = options?.extendedErrorMessage;\n this.isTransient = isTransientEResult(options?.eresult);\n }\n}\n\n// sharedSecret was supplied but the account has no mobile authenticator attached, so TOTP can't\n// answer the guard challenge. Use steamGuardCode / onSteamGuardRequired with an email code instead.\nexport class NoMobileAuthenticatorError extends LoginError {\n constructor(\n message = \"account has no mobile authenticator attached; sharedSecret cannot be used (account uses email Steam Guard)\",\n ) {\n super(message);\n this.name = \"NoMobileAuthenticatorError\";\n }\n}\n","// @generated by protoc-gen-es v2.12.1 with parameter \"target=ts,import_extension=js\"\n// @generated from file steammessages_auth.proto (syntax proto2)\n/* eslint-disable */\n\nimport type { GenEnum, GenFile, GenMessage } from \"@bufbuild/protobuf/codegenv2\";\nimport { enumDesc, fileDesc, messageDesc } from \"@bufbuild/protobuf/codegenv2\";\nimport type { Message } from \"@bufbuild/protobuf\";\n\n/**\n * Describes the file steammessages_auth.proto.\n */\nexport const file_steammessages_auth: GenFile = /*@__PURE__*/\n fileDesc(\"ChhzdGVhbW1lc3NhZ2VzX2F1dGgucHJvdG8iRwovQ0F1dGhlbnRpY2F0aW9uX0dldFBhc3N3b3JkUlNBUHVibGljS2V5X1JlcXVlc3QSFAoMYWNjb3VudF9uYW1lGAEgASgJInMKMENBdXRoZW50aWNhdGlvbl9HZXRQYXNzd29yZFJTQVB1YmxpY0tleV9SZXNwb25zZRIVCg1wdWJsaWNrZXlfbW9kGAEgASgJEhUKDXB1YmxpY2t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wZV9MZWdhY3lNYWNoaW5lQXV0aBAHKlAKEUVUb2tlblJlbmV3YWxUeXBlEhwKGGtfRVRva2VuUmVuZXdhbFR5cGVfTm9uZRAAEh0KGWtfRVRva2VuUmVuZXdhbFR5cGVfQWxsb3cQASqvAgoWRUF1dGhUb2tlblJldm9rZUFjdGlvbhIcChhrX0VBdXRoVG9rZW5SZXZva2VMb2dvdXQQABIfChtrX0VBdXRoVG9rZW5SZXZva2VQZXJtYW5lbnQQARIeChprX0VBdXRoVG9rZW5SZXZva2VSZXBsYWNlZBACEh0KGWtfRUF1dGhUb2tlblJldm9rZVN1cHBvcnQQAxIdChlrX0VBdXRoVG9rZW5SZXZva2VDb25zdW1lEAQSKQola19FQXV0aFRva2VuUmV2b2tlTm9uUmVtZW1iZXJlZExvZ291dBAFEiwKKGtfRUF1dGhUb2tlblJldm9rZU5vblJlbWVtYmVyZWRQZXJtYW5lbnQQBhIfChtrX0VBdXRoVG9rZW5SZXZva2VBdXRvbWF0aWMQByqMAQoTRVNlc3Npb25QZXJzaXN0ZW5jZRIqCh1rX0VTZXNzaW9uUGVyc2lzdGVuY2VfSW52YWxpZBD///////////8BEiMKH2tfRVNlc3Npb25QZXJzaXN0ZW5jZV9FcGhlbWVyYWwQABIkCiBrX0VTZXNzaW9uUGVyc2lzdGVuY2VfUGVyc2lzdGVudBAB\");\n\n/**\n * @generated from message CAuthentication_GetPasswordRSAPublicKey_Request\n */\nexport type CAuthentication_GetPasswordRSAPublicKey_Request = Message<\"CAuthentication_GetPasswordRSAPublicKey_Request\"> & {\n /**\n * @generated from field: optional string account_name = 1;\n */\n accountName: string;\n};\n\n/**\n * Describes the message CAuthentication_GetPasswordRSAPublicKey_Request.\n * Use `create(CAuthentication_GetPasswordRSAPublicKey_RequestSchema)` to create a new message.\n */\nexport const CAuthentication_GetPasswordRSAPublicKey_RequestSchema: GenMessage<CAuthentication_GetPasswordRSAPublicKey_Request> = /*@__PURE__*/\n messageDesc(file_steammessages_auth, 0);\n\n/**\n * @generated from message CAuthentication_GetPasswordRSAPublicKey_Response\n */\nexport type CAuthentication_GetPasswordRSAPublicKey_Response = Message<\"CAuthentication_GetPasswordRSAPublicKey_Response\"> & {\n /**\n * @generated from field: optional string publickey_mod = 1;\n */\n publickeyMod: string;\n\n /**\n * @generated from field: optional string publickey_exp = 2;\n */\n publickeyExp: string;\n\n /**\n * @generated from field: optional uint64 timestamp = 3;\n */\n timestamp: bigint;\n};\n\n/**\n * Describes the message CAuthentication_GetPasswordRSAPublicKey_Response.\n * Use `create(CAuthentication_GetPasswordRSAPublicKey_ResponseSchema)` to create a new message.\n */\nexport const CAuthentication_GetPasswordRSAPublicKey_ResponseSchema: GenMessage<CAuthentication_GetPasswordRSAPublicKey_Response> = /*@__PURE__*/\n messageDesc(file_steammessages_auth, 1);\n\n/**\n * @generated from message CAuthentication_DeviceDetails\n */\nexport type CAuthentication_DeviceDetails = Message<\"CAuthentication_DeviceDetails\"> & {\n /**\n * @generated from field: optional string device_friendly_name = 1;\n */\n deviceFriendlyName: string;\n\n /**\n * @generated from field: optional EAuthTokenPlatformType platform_type = 2 [default = k_EAuthTokenPlatformType_Unknown];\n */\n platformType: EAuthTokenPlatformType;\n\n /**\n * @generated from field: optional int32 os_type = 3;\n */\n osType: number;\n\n /**\n * @generated from field: optional uint32 gaming_device_type = 4;\n */\n gamingDeviceType: number;\n\n /**\n * @generated from field: optional uint32 client_count = 5;\n */\n clientCount: number;\n\n /**\n * @generated from field: optional bytes machine_id = 6;\n */\n machineId: Uint8Array;\n\n /**\n * @generated from field: optional EAuthTokenAppType app_type = 7 [default = k_EAuthTokenAppType_Unknown];\n */\n appType: EAuthTokenAppType;\n};\n\n/**\n * Describes the message CAuthentication_DeviceDetails.\n * Use `create(CAuthentication_DeviceDetailsSchema)` to create a new message.\n */\nexport const CAuthentication_DeviceDetailsSchema: GenMessage<CAuthentication_DeviceDetails> = /*@__PURE__*/\n messageDesc(file_steammessages_auth, 2);\n\n/**\n * @generated from message CAuthentication_AllowedConfirmation\n */\nexport type CAuthentication_AllowedConfirmation = Message<\"CAuthentication_AllowedConfirmation\"> & {\n /**\n * @generated from field: optional EAuthSessionGuardType confirmation_type = 1 [default = k_EAuthSessionGuardType_Unknown];\n */\n confirmationType: EAuthSessionGuardType;\n\n /**\n * @generated from field: optional string associated_message = 2;\n */\n associatedMessage: string;\n};\n\n/**\n * Describes the message CAuthentication_AllowedConfirmation.\n * Use `create(CAuthentication_AllowedConfirmationSchema)` to create a new message.\n */\nexport const CAuthentication_AllowedConfirmationSchema: GenMessage<CAuthentication_AllowedConfirmation> = /*@__PURE__*/\n messageDesc(file_steammessages_auth, 3);\n\n/**\n * @generated from message CAuthentication_BeginAuthSessionViaCredentials_Request\n */\nexport type CAuthentication_BeginAuthSessionViaCredentials_Request = Message<\"CAuthentication_BeginAuthSessionViaCredentials_Request\"> & {\n /**\n * @generated from field: optional string device_friendly_name = 1;\n */\n deviceFriendlyName: string;\n\n /**\n * @generated from field: optional string account_name = 2;\n */\n accountName: string;\n\n /**\n * @generated from field: optional string encrypted_password = 3;\n */\n encryptedPassword: string;\n\n /**\n * @generated from field: optional uint64 encryption_timestamp = 4;\n */\n encryptionTimestamp: bigint;\n\n /**\n * @generated from field: optional bool remember_login = 5;\n */\n rememberLogin: boolean;\n\n /**\n * @generated from field: optional EAuthTokenPlatformType platform_type = 6 [default = k_EAuthTokenPlatformType_Unknown];\n */\n platformType: EAuthTokenPlatformType;\n\n /**\n * @generated from field: optional ESessionPersistence persistence = 7 [default = k_ESessionPersistence_Persistent];\n */\n persistence: ESessionPersistence;\n\n /**\n * @generated from field: optional string website_id = 8 [default = \"Unknown\"];\n */\n websiteId: string;\n\n /**\n * @generated from field: optional CAuthentication_DeviceDetails device_details = 9;\n */\n deviceDetails?: CAuthentication_DeviceDetails | undefined;\n\n /**\n * @generated from field: optional string guard_data = 10;\n */\n guardData: string;\n\n /**\n * @generated from field: optional uint32 language = 11;\n */\n language: number;\n\n /**\n * @generated from field: optional int32 qos_level = 12 [default = 2];\n */\n qosLevel: number;\n};\n\n/**\n * Describes the message CAuthentication_BeginAuthSessionViaCredentials_Request.\n * Use `create(CAuthentication_BeginAuthSessionViaCredentials_RequestSchema)` to create a new message.\n */\nexport const CAuthentication_BeginAuthSessionViaCredentials_RequestSchema: GenMessage<CAuthentication_BeginAuthSessionViaCredentials_Request> = /*@__PURE__*/\n messageDesc(file_steammessages_auth, 4);\n\n/**\n * @generated from message CAuthentication_BeginAuthSessionViaCredentials_Response\n */\nexport type CAuthentication_BeginAuthSessionViaCredentials_Response = Message<\"CAuthentication_BeginAuthSessionViaCredentials_Response\"> & {\n /**\n * @generated from field: optional uint64 client_id = 1;\n */\n clientId: bigint;\n\n /**\n * @generated from field: optional bytes request_id = 2;\n */\n requestId: Uint8Array;\n\n /**\n * @generated from field: optional float interval = 3;\n */\n interval: number;\n\n /**\n * @generated from field: repeated CAuthentication_AllowedConfirmation allowed_confirmations = 4;\n */\n allowedConfirmations: CAuthentication_AllowedConfirmation[];\n\n /**\n * @generated from field: optional uint64 steamid = 5;\n */\n steamid: bigint;\n\n /**\n * @generated from field: optional string weak_token = 6;\n */\n weakToken: string;\n\n /**\n * @generated from field: optional string agreement_session_url = 7;\n */\n agreementSessionUrl: string;\n\n /**\n * @generated from field: optional string extended_error_message = 8;\n */\n extendedErrorMessage: string;\n};\n\n/**\n * Describes the message CAuthentication_BeginAuthSessionViaCredentials_Response.\n * Use `create(CAuthentication_BeginAuthSessionViaCredentials_ResponseSchema)` to create a new message.\n */\nexport const CAuthentication_BeginAuthSessionViaCredentials_ResponseSchema: GenMessage<CAuthentication_BeginAuthSessionViaCredentials_Response> = /*@__PURE__*/\n messageDesc(file_steammessages_auth, 5);\n\n/**\n * @generated from message CAuthentication_PollAuthSessionStatus_Request\n */\nexport type CAuthentication_PollAuthSessionStatus_Request = Message<\"CAuthentication_PollAuthSessionStatus_Request\"> & {\n /**\n * @generated from field: optional uint64 client_id = 1;\n */\n clientId: bigint;\n\n /**\n * @generated from field: optional bytes request_id = 2;\n */\n requestId: Uint8Array;\n\n /**\n * @generated from field: optional fixed64 token_to_revoke = 3;\n */\n tokenToRevoke: bigint;\n};\n\n/**\n * Describes the message CAuthentication_PollAuthSessionStatus_Request.\n * Use `create(CAuthentication_PollAuthSessionStatus_RequestSchema)` to create a new message.\n */\nexport const CAuthentication_PollAuthSessionStatus_RequestSchema: GenMessage<CAuthentication_PollAuthSessionStatus_Request> = /*@__PURE__*/\n messageDesc(file_steammessages_auth, 6);\n\n/**\n * @generated from message CAuthentication_PollAuthSessionStatus_Response\n */\nexport type CAuthentication_PollAuthSessionStatus_Response = Message<\"CAuthentication_PollAuthSessionStatus_Response\"> & {\n /**\n * @generated from field: optional uint64 new_client_id = 1;\n */\n newClientId: bigint;\n\n /**\n * @generated from field: optional string new_challenge_url = 2;\n */\n newChallengeUrl: string;\n\n /**\n * @generated from field: optional string refresh_token = 3;\n */\n refreshToken: string;\n\n /**\n * @generated from field: optional string access_token = 4;\n */\n accessToken: string;\n\n /**\n * @generated from field: optional bool had_remote_interaction = 5;\n */\n hadRemoteInteraction: boolean;\n\n /**\n * @generated from field: optional string account_name = 6;\n */\n accountName: string;\n\n /**\n * @generated from field: optional string new_guard_data = 7;\n */\n newGuardData: string;\n\n /**\n * @generated from field: optional string agreement_session_url = 8;\n */\n agreementSessionUrl: string;\n};\n\n/**\n * Describes the message CAuthentication_PollAuthSessionStatus_Response.\n * Use `create(CAuthentication_PollAuthSessionStatus_ResponseSchema)` to create a new message.\n */\nexport const CAuthentication_PollAuthSessionStatus_ResponseSchema: GenMessage<CAuthentication_PollAuthSessionStatus_Response> = /*@__PURE__*/\n messageDesc(file_steammessages_auth, 7);\n\n/**\n * @generated from message CAuthentication_UpdateAuthSessionWithSteamGuardCode_Request\n */\nexport type CAuthentication_UpdateAuthSessionWithSteamGuardCode_Request = Message<\"CAuthentication_UpdateAuthSessionWithSteamGuardCode_Request\"> & {\n /**\n * @generated from field: optional uint64 client_id = 1;\n */\n clientId: bigint;\n\n /**\n * @generated from field: optional fixed64 steamid = 2;\n */\n steamid: bigint;\n\n /**\n * @generated from field: optional string code = 3;\n */\n code: string;\n\n /**\n * @generated from field: optional EAuthSessionGuardType code_type = 4 [default = k_EAuthSessionGuardType_Unknown];\n */\n codeType: EAuthSessionGuardType;\n};\n\n/**\n * Describes the message CAuthentication_UpdateAuthSessionWithSteamGuardCode_Request.\n * Use `create(CAuthentication_UpdateAuthSessionWithSteamGuardCode_RequestSchema)` to create a new message.\n */\nexport const CAuthentication_UpdateAuthSessionWithSteamGuardCode_RequestSchema: GenMessage<CAuthentication_UpdateAuthSessionWithSteamGuardCode_Request> = /*@__PURE__*/\n messageDesc(file_steammessages_auth, 8);\n\n/**\n * @generated from message CAuthentication_UpdateAuthSessionWithSteamGuardCode_Response\n */\nexport type CAuthentication_UpdateAuthSessionWithSteamGuardCode_Response = Message<\"CAuthentication_UpdateAuthSessionWithSteamGuardCode_Response\"> & {\n /**\n * @generated from field: optional string agreement_session_url = 7;\n */\n agreementSessionUrl: string;\n};\n\n/**\n * Describes the message CAuthentication_UpdateAuthSessionWithSteamGuardCode_Response.\n * Use `create(CAuthentication_UpdateAuthSessionWithSteamGuardCode_ResponseSchema)` to create a new message.\n */\nexport const CAuthentication_UpdateAuthSessionWithSteamGuardCode_ResponseSchema: GenMessage<CAuthentication_UpdateAuthSessionWithSteamGuardCode_Response> = /*@__PURE__*/\n messageDesc(file_steammessages_auth, 9);\n\n/**\n * @generated from message CAuthentication_AccessToken_GenerateForApp_Request\n */\nexport type CAuthentication_AccessToken_GenerateForApp_Request = Message<\"CAuthentication_AccessToken_GenerateForApp_Request\"> & {\n /**\n * @generated from field: optional string refresh_token = 1;\n */\n refreshToken: string;\n\n /**\n * @generated from field: optional fixed64 steamid = 2;\n */\n steamid: bigint;\n\n /**\n * @generated from field: optional ETokenRenewalType renewal_type = 3 [default = k_ETokenRenewalType_None];\n */\n renewalType: ETokenRenewalType;\n};\n\n/**\n * Describes the message CAuthentication_AccessToken_GenerateForApp_Request.\n * Use `create(CAuthentication_AccessToken_GenerateForApp_RequestSchema)` to create a new message.\n */\nexport const CAuthentication_AccessToken_GenerateForApp_RequestSchema: GenMessage<CAuthentication_AccessToken_GenerateForApp_Request> = /*@__PURE__*/\n messageDesc(file_steammessages_auth, 10);\n\n/**\n * @generated from message CAuthentication_AccessToken_GenerateForApp_Response\n */\nexport type CAuthentication_AccessToken_GenerateForApp_Response = Message<\"CAuthentication_AccessToken_GenerateForApp_Response\"> & {\n /**\n * @generated from field: optional string access_token = 1;\n */\n accessToken: string;\n\n /**\n * @generated from field: optional string refresh_token = 2;\n */\n refreshToken: string;\n};\n\n/**\n * Describes the message CAuthentication_AccessToken_GenerateForApp_Response.\n * Use `create(CAuthentication_AccessToken_GenerateForApp_ResponseSchema)` to create a new message.\n */\nexport const CAuthentication_AccessToken_GenerateForApp_ResponseSchema: GenMessage<CAuthentication_AccessToken_GenerateForApp_Response> = /*@__PURE__*/\n messageDesc(file_steammessages_auth, 11);\n\n/**\n * @generated from message CAuthentication_GetAuthSessionsForAccount_Request\n */\nexport type CAuthentication_GetAuthSessionsForAccount_Request = Message<\"CAuthentication_GetAuthSessionsForAccount_Request\"> & {\n};\n\n/**\n * Describes the message CAuthentication_GetAuthSessionsForAccount_Request.\n * Use `create(CAuthentication_GetAuthSessionsForAccount_RequestSchema)` to create a new message.\n */\nexport const CAuthentication_GetAuthSessionsForAccount_RequestSchema: GenMessage<CAuthentication_GetAuthSessionsForAccount_Request> = /*@__PURE__*/\n messageDesc(file_steammessages_auth, 12);\n\n/**\n * @generated from message CAuthentication_GetAuthSessionsForAccount_Response\n */\nexport type CAuthentication_GetAuthSessionsForAccount_Response = Message<\"CAuthentication_GetAuthSessionsForAccount_Response\"> & {\n /**\n * @generated from field: repeated uint64 client_ids = 1;\n */\n clientIds: bigint[];\n};\n\n/**\n * Describes the message CAuthentication_GetAuthSessionsForAccount_Response.\n * Use `create(CAuthentication_GetAuthSessionsForAccount_ResponseSchema)` to create a new message.\n */\nexport const CAuthentication_GetAuthSessionsForAccount_ResponseSchema: GenMessage<CAuthentication_GetAuthSessionsForAccount_Response> = /*@__PURE__*/\n messageDesc(file_steammessages_auth, 13);\n\n/**\n * @generated from message CAuthentication_RefreshToken_Revoke_Request\n */\nexport type CAuthentication_RefreshToken_Revoke_Request = Message<\"CAuthentication_RefreshToken_Revoke_Request\"> & {\n /**\n * @generated from field: optional fixed64 token_id = 1;\n */\n tokenId: bigint;\n\n /**\n * @generated from field: optional fixed64 steamid = 2;\n */\n steamid: bigint;\n\n /**\n * @generated from field: optional EAuthTokenRevokeAction revoke_action = 3 [default = k_EAuthTokenRevokePermanent];\n */\n revokeAction: EAuthTokenRevokeAction;\n\n /**\n * @generated from field: optional bytes signature = 4;\n */\n signature: Uint8Array;\n};\n\n/**\n * Describes the message CAuthentication_RefreshToken_Revoke_Request.\n * Use `create(CAuthentication_RefreshToken_Revoke_RequestSchema)` to create a new message.\n */\nexport const CAuthentication_RefreshToken_Revoke_RequestSchema: GenMessage<CAuthentication_RefreshToken_Revoke_Request> = /*@__PURE__*/\n messageDesc(file_steammessages_auth, 14);\n\n/**\n * @generated from message CAuthentication_RefreshToken_Revoke_Response\n */\nexport type CAuthentication_RefreshToken_Revoke_Response = Message<\"CAuthentication_RefreshToken_Revoke_Response\"> & {\n};\n\n/**\n * Describes the message CAuthentication_RefreshToken_Revoke_Response.\n * Use `create(CAuthentication_RefreshToken_Revoke_ResponseSchema)` to create a new message.\n */\nexport const CAuthentication_RefreshToken_Revoke_ResponseSchema: GenMessage<CAuthentication_RefreshToken_Revoke_Response> = /*@__PURE__*/\n messageDesc(file_steammessages_auth, 15);\n\n/**\n * @generated from enum EAuthTokenPlatformType\n */\nexport enum EAuthTokenPlatformType {\n /**\n * @generated from enum value: k_EAuthTokenPlatformType_Unknown = 0;\n */\n k_EAuthTokenPlatformType_Unknown = 0,\n\n /**\n * @generated from enum value: k_EAuthTokenPlatformType_SteamClient = 1;\n */\n k_EAuthTokenPlatformType_SteamClient = 1,\n\n /**\n * @generated from enum value: k_EAuthTokenPlatformType_WebBrowser = 2;\n */\n k_EAuthTokenPlatformType_WebBrowser = 2,\n\n /**\n * @generated from enum value: k_EAuthTokenPlatformType_MobileApp = 3;\n */\n k_EAuthTokenPlatformType_MobileApp = 3,\n}\n\n/**\n * Describes the enum EAuthTokenPlatformType.\n */\nexport const EAuthTokenPlatformTypeSchema: GenEnum<EAuthTokenPlatformType> = /*@__PURE__*/\n enumDesc(file_steammessages_auth, 0);\n\n/**\n * @generated from enum EAuthTokenAppType\n */\nexport enum EAuthTokenAppType {\n /**\n * @generated from enum value: k_EAuthTokenAppType_Unknown = 0;\n */\n k_EAuthTokenAppType_Unknown = 0,\n\n /**\n * @generated from enum value: k_EAuthTokenAppType_Mobile_SteamApp = 1;\n */\n k_EAuthTokenAppType_Mobile_SteamApp = 1,\n\n /**\n * @generated from enum value: k_EAuthTokenAppType_Mobile_ChatApp = 2;\n */\n k_EAuthTokenAppType_Mobile_ChatApp = 2,\n}\n\n/**\n * Describes the enum EAuthTokenAppType.\n */\nexport const EAuthTokenAppTypeSchema: GenEnum<EAuthTokenAppType> = /*@__PURE__*/\n enumDesc(file_steammessages_auth, 1);\n\n/**\n * @generated from enum EAuthSessionGuardType\n */\nexport enum EAuthSessionGuardType {\n /**\n * @generated from enum value: k_EAuthSessionGuardType_Unknown = 0;\n */\n k_EAuthSessionGuardType_Unknown = 0,\n\n /**\n * @generated from enum value: k_EAuthSessionGuardType_None = 1;\n */\n k_EAuthSessionGuardType_None = 1,\n\n /**\n * @generated from enum value: k_EAuthSessionGuardType_EmailCode = 2;\n */\n k_EAuthSessionGuardType_EmailCode = 2,\n\n /**\n * @generated from enum value: k_EAuthSessionGuardType_DeviceCode = 3;\n */\n k_EAuthSessionGuardType_DeviceCode = 3,\n\n /**\n * @generated from enum value: k_EAuthSessionGuardType_DeviceConfirmation = 4;\n */\n k_EAuthSessionGuardType_DeviceConfirmation = 4,\n\n /**\n * @generated from enum value: k_EAuthSessionGuardType_EmailConfirmation = 5;\n */\n k_EAuthSessionGuardType_EmailConfirmation = 5,\n\n /**\n * @generated from enum value: k_EAuthSessionGuardType_MachineToken = 6;\n */\n k_EAuthSessionGuardType_MachineToken = 6,\n\n /**\n * @generated from enum value: k_EAuthSessionGuardType_LegacyMachineAuth = 7;\n */\n k_EAuthSessionGuardType_LegacyMachineAuth = 7,\n}\n\n/**\n * Describes the enum EAuthSessionGuardType.\n */\nexport const EAuthSessionGuardTypeSchema: GenEnum<EAuthSessionGuardType> = /*@__PURE__*/\n enumDesc(file_steammessages_auth, 2);\n\n/**\n * @generated from enum ETokenRenewalType\n */\nexport enum ETokenRenewalType {\n /**\n * @generated from enum value: k_ETokenRenewalType_None = 0;\n */\n k_ETokenRenewalType_None = 0,\n\n /**\n * @generated from enum value: k_ETokenRenewalType_Allow = 1;\n */\n k_ETokenRenewalType_Allow = 1,\n}\n\n/**\n * Describes the enum ETokenRenewalType.\n */\nexport const ETokenRenewalTypeSchema: GenEnum<ETokenRenewalType> = /*@__PURE__*/\n enumDesc(file_steammessages_auth, 3);\n\n/**\n * @generated from enum EAuthTokenRevokeAction\n */\nexport enum EAuthTokenRevokeAction {\n /**\n * @generated from enum value: k_EAuthTokenRevokeLogout = 0;\n */\n k_EAuthTokenRevokeLogout = 0,\n\n /**\n * @generated from enum value: k_EAuthTokenRevokePermanent = 1;\n */\n k_EAuthTokenRevokePermanent = 1,\n\n /**\n * @generated from enum value: k_EAuthTokenRevokeReplaced = 2;\n */\n k_EAuthTokenRevokeReplaced = 2,\n\n /**\n * @generated from enum value: k_EAuthTokenRevokeSupport = 3;\n */\n k_EAuthTokenRevokeSupport = 3,\n\n /**\n * @generated from enum value: k_EAuthTokenRevokeConsume = 4;\n */\n k_EAuthTokenRevokeConsume = 4,\n\n /**\n * @generated from enum value: k_EAuthTokenRevokeNonRememberedLogout = 5;\n */\n k_EAuthTokenRevokeNonRememberedLogout = 5,\n\n /**\n * @generated from enum value: k_EAuthTokenRevokeNonRememberedPermanent = 6;\n */\n k_EAuthTokenRevokeNonRememberedPermanent = 6,\n\n /**\n * @generated from enum value: k_EAuthTokenRevokeAutomatic = 7;\n */\n k_EAuthTokenRevokeAutomatic = 7,\n}\n\n/**\n * Describes the enum EAuthTokenRevokeAction.\n */\nexport const EAuthTokenRevokeActionSchema: GenEnum<EAuthTokenRevokeAction> = /*@__PURE__*/\n enumDesc(file_steammessages_auth, 4);\n\n/**\n * @generated from enum ESessionPersistence\n */\nexport enum ESessionPersistence {\n /**\n * @generated from enum value: k_ESessionPersistence_Invalid = -1;\n */\n k_ESessionPersistence_Invalid = -1,\n\n /**\n * @generated from enum value: k_ESessionPersistence_Ephemeral = 0;\n */\n k_ESessionPersistence_Ephemeral = 0,\n\n /**\n * @generated from enum value: k_ESessionPersistence_Persistent = 1;\n */\n k_ESessionPersistence_Persistent = 1,\n}\n\n/**\n * Describes the enum ESessionPersistence.\n */\nexport const ESessionPersistenceSchema: GenEnum<ESessionPersistence> = /*@__PURE__*/\n enumDesc(file_steammessages_auth, 5);\n\n","import { Buffer } from \"node:buffer\";\nimport type { HttpClient, HttpResponse } from \"../http/HttpClient.js\";\n\nexport interface ProtoResult {\n status: number;\n eresult: string | null;\n errorMessage: string | null;\n body: Buffer | Uint8Array;\n}\n\nexport interface ProtoRequest {\n url: string;\n method: \"GET\" | \"POST\";\n body?: Uint8Array;\n accessToken?: string;\n multipart?: boolean;\n origin?: boolean;\n spoofSteamid?: string;\n}\n\nexport type ProtoTransport = (req: ProtoRequest) => Promise<ProtoResult>;\n\nexport type ProtoPost = (\n url: string,\n base64Body: string,\n accessToken?: string,\n) => Promise<ProtoResult>;\n\nexport function createProtoTransport(http: HttpClient): ProtoTransport {\n return async (req) => {\n const base64 = req.body && req.body.length > 0 ? Buffer.from(req.body).toString(\"base64\") : \"\";\n const searchParams: Record<string, string> = {};\n if (req.accessToken) {\n searchParams.access_token = req.accessToken;\n searchParams.spoof_steamid = req.spoofSteamid ?? \"\";\n }\n if (req.origin) searchParams.origin = \"SteamMobile\";\n\n let res: HttpResponse<Buffer | Uint8Array>;\n if (req.method === \"GET\") {\n // Must be present even when empty, or Steam replies in JSON instead of protobuf.\n searchParams.input_protobuf_encoded = base64;\n res = await http.get<Buffer | Uint8Array>(req.url, { responseType: \"buffer\", searchParams });\n } else {\n const bodyOpt = req.multipart\n ? { multipart: [{ name: \"input_protobuf_encoded\", value: base64 }] }\n : { form: { input_protobuf_encoded: base64 } };\n res = await http.post<Buffer | Uint8Array>(req.url, {\n responseType: \"buffer\",\n ...(Object.keys(searchParams).length > 0 ? { searchParams } : {}),\n ...bodyOpt,\n });\n }\n\n return {\n status: res.statusCode,\n eresult: headerValue(res.headers[\"x-eresult\"]) ?? null,\n errorMessage: headerValue(res.headers[\"x-error_message\"]) ?? null,\n body: res.body,\n };\n };\n}\n\n// The mint keeps its urlencoded-form POST shape.\nexport function createProtoPost(http: HttpClient): ProtoPost {\n const transport = createProtoTransport(http);\n return (url, base64Body, accessToken) =>\n transport({\n url,\n method: \"POST\",\n body: Buffer.from(base64Body, \"base64\"),\n ...(accessToken ? { accessToken } : {}),\n });\n}\n\nfunction headerValue(v: string | string[] | undefined): string | undefined {\n return Array.isArray(v) ? v[0] : v;\n}\n","import { Buffer } from \"node:buffer\";\nimport {\n create,\n fromBinary,\n type MessageInitShape,\n type MessageShape,\n toBinary,\n} from \"@bufbuild/protobuf\";\nimport { URLS } from \"../core/constants.js\";\nimport { EResult } from \"../core/enums.js\";\nimport { LoginError, RateLimitError } from \"../core/errors.js\";\nimport type { HttpClient } from \"../http/HttpClient.js\";\nimport {\n CAuthentication_BeginAuthSessionViaCredentials_RequestSchema as BeginReqSchema,\n CAuthentication_BeginAuthSessionViaCredentials_ResponseSchema as BeginResSchema,\n type CAuthentication_BeginAuthSessionViaCredentials_RequestSchema,\n type EAuthSessionGuardType,\n type EAuthTokenRevokeAction,\n CAuthentication_GetAuthSessionsForAccount_RequestSchema as GetSessReqSchema,\n CAuthentication_GetAuthSessionsForAccount_ResponseSchema as GetSessResSchema,\n CAuthentication_UpdateAuthSessionWithSteamGuardCode_RequestSchema as GuardReqSchema,\n CAuthentication_UpdateAuthSessionWithSteamGuardCode_ResponseSchema as GuardResSchema,\n CAuthentication_PollAuthSessionStatus_RequestSchema as PollReqSchema,\n CAuthentication_PollAuthSessionStatus_ResponseSchema as PollResSchema,\n CAuthentication_RefreshToken_Revoke_RequestSchema as RevokeReqSchema,\n CAuthentication_RefreshToken_Revoke_ResponseSchema as RevokeResSchema,\n CAuthentication_GetPasswordRSAPublicKey_RequestSchema as RsaReqSchema,\n CAuthentication_GetPasswordRSAPublicKey_ResponseSchema as RsaResSchema,\n} from \"../protobufs/steammessages_auth_pb.js\";\nimport {\n createProtoTransport,\n type ProtoResult,\n type ProtoTransport,\n} from \"../session/protoTransport.js\";\n\ntype BeginRequest = MessageInitShape<\n typeof CAuthentication_BeginAuthSessionViaCredentials_RequestSchema\n>;\n\ninterface SendOptions {\n apiMethod: string;\n method: \"GET\" | \"POST\";\n body?: Uint8Array;\n accessToken?: string;\n origin?: boolean;\n multipart?: boolean;\n}\n\n// Stateless 1:1 wrappers over the IAuthenticationService protobuf RPCs (the mint lives in tokens.ts).\nexport class AuthClient {\n private readonly transport: ProtoTransport;\n\n constructor(http: HttpClient) {\n this.transport = createProtoTransport(http);\n }\n\n async getPasswordRSAPublicKey(accountName: string): Promise<MessageShape<typeof RsaResSchema>> {\n const body = toBinary(RsaReqSchema, create(RsaReqSchema, { accountName }));\n const out = await this.send({\n apiMethod: \"GetPasswordRSAPublicKey\",\n method: \"GET\",\n body,\n origin: true,\n });\n return fromBinary(RsaResSchema, out);\n }\n\n async beginAuthSessionViaCredentials(\n req: BeginRequest,\n ): Promise<MessageShape<typeof BeginResSchema>> {\n const body = toBinary(BeginReqSchema, create(BeginReqSchema, req));\n const out = await this.send({\n apiMethod: \"BeginAuthSessionViaCredentials\",\n method: \"POST\",\n body,\n multipart: true,\n });\n return fromBinary(BeginResSchema, out);\n }\n\n async pollAuthSessionStatus(\n clientId: bigint,\n requestId: Uint8Array,\n ): Promise<MessageShape<typeof PollResSchema>> {\n const body = toBinary(PollReqSchema, create(PollReqSchema, { clientId, requestId }));\n const out = await this.send({\n apiMethod: \"PollAuthSessionStatus\",\n method: \"POST\",\n body,\n multipart: true,\n });\n return fromBinary(PollResSchema, out);\n }\n\n async updateAuthSessionWithSteamGuardCode(\n clientId: bigint,\n steamid: bigint,\n code: string,\n codeType: number,\n ): Promise<MessageShape<typeof GuardResSchema>> {\n const body = toBinary(\n GuardReqSchema,\n create(GuardReqSchema, {\n clientId,\n steamid,\n code,\n codeType: codeType as EAuthSessionGuardType,\n }),\n );\n const out = await this.send({\n apiMethod: \"UpdateAuthSessionWithSteamGuardCode\",\n method: \"POST\",\n body,\n multipart: true,\n });\n return fromBinary(GuardResSchema, out);\n }\n\n // In-progress auth sessions (login-approval flows), not a device list. GET-only (POST → 405).\n async getAuthSessionsForAccount(\n accessToken: string,\n ): Promise<MessageShape<typeof GetSessResSchema>> {\n const body = toBinary(GetSessReqSchema, create(GetSessReqSchema, {}));\n const out = await this.send({\n apiMethod: \"GetAuthSessionsForAccount\",\n method: \"GET\",\n body,\n accessToken,\n origin: true,\n });\n return fromBinary(GetSessResSchema, out);\n }\n\n // Self-revoke (logout): the query access_token identifies the token; no signature needed.\n async revokeRefreshToken(\n accessToken: string,\n revokeAction: number,\n ): Promise<MessageShape<typeof RevokeResSchema>> {\n const body = toBinary(\n RevokeReqSchema,\n create(RevokeReqSchema, { revokeAction: revokeAction as EAuthTokenRevokeAction }),\n );\n const out = await this.send({\n apiMethod: \"RevokeRefreshToken\",\n method: \"POST\",\n body,\n accessToken,\n multipart: true,\n });\n return fromBinary(RevokeResSchema, out);\n }\n\n private async send(opts: SendOptions): Promise<Uint8Array> {\n const url = `${URLS.api}/IAuthenticationService/${opts.apiMethod}/v1`;\n const res = await this.transport({\n url,\n method: opts.method,\n ...(opts.body ? { body: opts.body } : {}),\n ...(opts.accessToken ? { accessToken: opts.accessToken } : {}),\n ...(opts.origin ? { origin: true } : {}),\n ...(opts.multipart ? { multipart: true } : {}),\n });\n ensureOk(res, opts.apiMethod);\n return toUint8(res.body);\n }\n}\n\nfunction ensureOk(res: ProtoResult, apiMethod: string): void {\n if (res.status === 429) {\n throw new RateLimitError({\n message: `IAuthenticationService/${apiMethod} HTTP 429`,\n ...(res.eresult ? { eresult: Number(res.eresult) } : {}),\n });\n }\n if (res.status < 200 || res.status >= 300) {\n throw new LoginError(`IAuthenticationService/${apiMethod} HTTP ${res.status}`, {\n ...(res.eresult ? { eresult: Number(res.eresult) } : {}),\n ...(res.errorMessage ? { extendedErrorMessage: res.errorMessage } : {}),\n });\n }\n const er = res.eresult;\n if (er && er !== \"1\") {\n const code = Number(er);\n // Steam sometimes returns Fail(2) alongside a valid body; treat as success (matches webApi.ts).\n if (code === EResult.Fail && res.body.length > 0) return;\n const name = EResult[code] ?? \"EResult\";\n const msg = `${apiMethod}: ${name} (${er})${res.errorMessage ? ` ${res.errorMessage}` : \"\"}`;\n if (code === EResult.RateLimitExceeded)\n throw new RateLimitError({ message: msg, eresult: code });\n throw new LoginError(msg, {\n eresult: code,\n ...(res.errorMessage ? { extendedErrorMessage: res.errorMessage } : {}),\n });\n }\n}\n\nfunction toUint8(input: Buffer | Uint8Array): Uint8Array {\n return input instanceof Uint8Array && !Buffer.isBuffer(input) ? input : new Uint8Array(input);\n}\n","import { Buffer } from \"node:buffer\";\nimport { constants, createPublicKey, publicEncrypt } from \"node:crypto\";\n\n// Encrypt the password with Steam's RSA public key (hex modulus/exponent → JWK), PKCS#1 v1.5 → base64.\nexport function encryptPassword(password: string, modHex: string, expHex: string): string {\n const n = Buffer.from(modHex, \"hex\").toString(\"base64url\");\n const e = Buffer.from(expHex, \"hex\").toString(\"base64url\");\n const key = createPublicKey({ key: { kty: \"RSA\", n, e }, format: \"jwk\" });\n // publicEncrypt defaults to OAEP; Steam needs PKCS#1 v1.5.\n return publicEncrypt(\n { key, padding: constants.RSA_PKCS1_PADDING },\n Buffer.from(password, \"utf8\"),\n ).toString(\"base64\");\n}\n","import { Buffer } from \"node:buffer\";\nimport { createHash, createHmac } from \"node:crypto\";\n\n// Ported from DoctorMcKay's steam-totp (the few functions we use), so it isn't a runtime dependency.\n// The QueryTime server-time call lives in ConfirmationManager so it rides HttpClient (proxy).\nconst CODE_CHARS = \"23456789BCDFGHJKMNPQRTVWXY\";\n\nexport function time(timeOffset = 0): number {\n return Math.floor(Date.now() / 1000) + timeOffset;\n}\n\n// Steam-style TOTP code from a base64/hex/Buffer shared_secret.\nexport function getAuthCode(secret: Buffer | string, timeOffset = 0): string {\n const key = bufferizeSecret(secret);\n const buffer = Buffer.allocUnsafe(8);\n buffer.writeUInt32BE(0, 0);\n buffer.writeUInt32BE(Math.floor(time(timeOffset) / 30), 4);\n\n const hmac = createHmac(\"sha1\", key).update(buffer).digest();\n const start = (hmac[19] ?? 0) & 0x0f;\n let fullcode = hmac.subarray(start, start + 4).readUInt32BE(0) & 0x7fffffff;\n\n let code = \"\";\n for (let i = 0; i < 5; i++) {\n code += CODE_CHARS.charAt(fullcode % CODE_CHARS.length);\n fullcode /= CODE_CHARS.length;\n }\n return code;\n}\n\n// Single-use base64 confirmation key for mobileconf (tag: \"conf\"/\"list\"/\"allow\"/\"cancel\"/…).\nexport function getConfirmationKey(\n identitySecret: Buffer | string,\n t: number,\n tag: string,\n): string {\n const key = bufferizeSecret(identitySecret);\n const dataLen = 8 + (tag ? Math.min(tag.length, 32) : 0);\n const buffer = Buffer.allocUnsafe(dataLen);\n buffer.writeBigUInt64BE(BigInt(t), 0);\n if (tag) buffer.write(tag, 8);\n return createHmac(\"sha1\", key).update(buffer).digest(\"base64\");\n}\n\n// Stable mobileconf device id derived from the steamID (android: + UUID-formatted SHA1).\nexport function getDeviceID(steamID: string): string {\n const salt = process.env.STEAM_TOTP_SALT ?? \"\";\n const hash = createHash(\"sha1\")\n .update(steamID + salt)\n .digest(\"hex\")\n .replace(\n /^([0-9a-f]{8})([0-9a-f]{4})([0-9a-f]{4})([0-9a-f]{4})([0-9a-f]{12}).*$/,\n \"$1-$2-$3-$4-$5\",\n );\n return `android:${hash}`;\n}\n\nfunction bufferizeSecret(secret: Buffer | string): Buffer {\n if (typeof secret !== \"string\") return secret;\n return /[0-9a-f]{40}/i.test(secret) ? Buffer.from(secret, \"hex\") : Buffer.from(secret, \"base64\");\n}\n","import { create } from \"@bufbuild/protobuf\";\nimport type { MobileProfile } from \"../core/mobileProfile.js\";\nimport {\n type CAuthentication_DeviceDetails,\n CAuthentication_DeviceDetailsSchema,\n type EAuthTokenAppType,\n EAuthTokenPlatformType,\n} from \"../protobufs/steammessages_auth_pb.js\";\n\n// device_details for the login (shows in Steam's authorized-devices list). Always MobileApp.\nexport function buildDeviceDetails(profile: MobileProfile): CAuthentication_DeviceDetails {\n return create(CAuthentication_DeviceDetailsSchema, {\n deviceFriendlyName: profile.deviceFriendlyName,\n platformType: EAuthTokenPlatformType.k_EAuthTokenPlatformType_MobileApp,\n osType: profile.osType,\n gamingDeviceType: profile.gamingDeviceType,\n ...(profile.appType !== undefined ? { appType: profile.appType as EAuthTokenAppType } : {}),\n });\n}\n","import { EventEmitter } from \"node:events\";\nimport SteamID from \"steamid\";\nimport { EAuthSessionGuardType } from \"../core/enums.js\";\nimport { LoginError, NoMobileAuthenticatorError } from \"../core/errors.js\";\nimport type { MobileProfile } from \"../core/mobileProfile.js\";\nimport { encryptPassword } from \"../crypto/rsa.js\";\nimport { getAuthCode } from \"../crypto/steamTotp.js\";\nimport type { HttpClient } from \"../http/HttpClient.js\";\nimport { ESessionPersistence } from \"../protobufs/steammessages_auth_pb.js\";\nimport { AuthClient } from \"./AuthClient.js\";\nimport { buildDeviceDetails } from \"./deviceDetails.js\";\n\nexport interface CredentialSessionEvents {\n debug: [message: string];\n authenticated: [];\n timeout: [];\n error: [error: Error];\n // No code could be supplied automatically; caller must submitSteamGuardCode().\n steamGuardRequired: [info: { type: EAuthSessionGuardType; message: string }];\n remoteInteraction: [];\n}\n\nexport interface CredentialStartOptions {\n username: string;\n password: string;\n sharedSecret?: string; // answers DeviceCode automatically via TOTP\n steamGuardCode?: string;\n}\n\nconst DEFAULT_POLL_TIMEOUT_MS = 180_000;\nconst DEFAULT_POLL_INTERVAL_MS = 5_000;\n\n// Drives one credential login (rsaKey -> encrypt -> begin -> answer guard -> poll) to a refresh token.\nexport class CredentialSession extends EventEmitter<CredentialSessionEvents> {\n private readonly auth: AuthClient;\n private clientId = 0n;\n private requestId: Uint8Array = new Uint8Array();\n private pollIntervalMs = DEFAULT_POLL_INTERVAL_MS;\n private allowedConfirmations: EAuthSessionGuardType[] = [];\n private deadline = 0;\n private pollTimer: NodeJS.Timeout | undefined;\n private settled = false;\n private remoteInteractionEmitted = false;\n\n steamID: SteamID | undefined;\n username = \"\";\n accessToken: string | undefined;\n refreshToken: string | undefined;\n\n constructor(\n http: HttpClient,\n private readonly profile: MobileProfile,\n private readonly pollTimeoutMs = DEFAULT_POLL_TIMEOUT_MS,\n ) {\n super();\n this.auth = new AuthClient(http);\n }\n\n async start(opts: CredentialStartOptions): Promise<void> {\n this.username = opts.username;\n const rsa = await this.auth.getPasswordRSAPublicKey(opts.username);\n const encryptedPassword = encryptPassword(opts.password, rsa.publickeyMod, rsa.publickeyExp);\n\n // device_friendly_name and platform_type go only inside device_details, matching the iOS app.\n const begin = await this.auth.beginAuthSessionViaCredentials({\n accountName: opts.username,\n encryptedPassword,\n encryptionTimestamp: rsa.timestamp,\n rememberLogin: true,\n persistence: ESessionPersistence.k_ESessionPersistence_Persistent,\n websiteId: \"Mobile\",\n deviceDetails: buildDeviceDetails(this.profile),\n language: 0,\n });\n\n // A successful begin always returns a request_id; its absence (not clientId, which can be 0n)\n // means Steam rejected the login.\n if (begin.requestId.length === 0) {\n throw new LoginError(begin.extendedErrorMessage || \"login was rejected by Steam\", {\n ...(begin.extendedErrorMessage ? { extendedErrorMessage: begin.extendedErrorMessage } : {}),\n });\n }\n\n this.clientId = begin.clientId;\n this.requestId = begin.requestId;\n if (begin.steamid) this.steamID = new SteamID(begin.steamid.toString());\n if (begin.interval > 0) this.pollIntervalMs = Math.round(begin.interval * 1000);\n this.allowedConfirmations = begin.allowedConfirmations.map((c) => Number(c.confirmationType));\n this.emit(\"debug\", `begin OK: confirmations=[${this.allowedConfirmations.join(\",\")}]`);\n\n await this.answerConfirmations(opts);\n\n this.deadline = Date.now() + this.pollTimeoutMs;\n this.schedulePoll();\n }\n\n async submitSteamGuardCode(code: string): Promise<void> {\n const trimmed = code?.trim();\n if (!trimmed) throw new LoginError(\"a Steam Guard code is required\");\n const codeType = this.allowedConfirmations.includes(EAuthSessionGuardType.DeviceCode)\n ? EAuthSessionGuardType.DeviceCode\n : EAuthSessionGuardType.EmailCode;\n await this.submitCode(trimmed, codeType);\n }\n\n stop(): void {\n this.settled = true;\n if (this.pollTimer) clearTimeout(this.pollTimer);\n this.pollTimer = undefined;\n }\n\n private async answerConfirmations(opts: CredentialStartOptions): Promise<void> {\n const allowed = this.allowedConfirmations;\n\n if (allowed.includes(EAuthSessionGuardType.DeviceCode) && opts.sharedSecret) {\n const code = getAuthCode(opts.sharedSecret);\n this.emit(\"debug\", \"answering DeviceCode with generated TOTP\");\n await this.submitCode(code, EAuthSessionGuardType.DeviceCode);\n return;\n }\n\n // sharedSecret was supplied but the account isn't TOTP-protected — fail loud rather than fall through\n // to an \"email code required\" prompt the caller can't satisfy with what they provided.\n if (opts.sharedSecret && !allowed.includes(EAuthSessionGuardType.DeviceCode)) {\n throw new NoMobileAuthenticatorError();\n }\n\n if (opts.steamGuardCode) {\n const codeType = allowed.includes(EAuthSessionGuardType.DeviceCode)\n ? EAuthSessionGuardType.DeviceCode\n : EAuthSessionGuardType.EmailCode;\n await this.submitCode(opts.steamGuardCode, codeType);\n return;\n }\n\n if (\n allowed.includes(EAuthSessionGuardType.DeviceConfirmation) ||\n allowed.includes(EAuthSessionGuardType.EmailConfirmation)\n ) {\n this.emitRemoteInteraction();\n return;\n }\n\n const codeGuard = allowed.find(\n (t) => t === EAuthSessionGuardType.EmailCode || t === EAuthSessionGuardType.DeviceCode,\n );\n if (codeGuard !== undefined) {\n this.emit(\"steamGuardRequired\", {\n type: codeGuard,\n message:\n codeGuard === EAuthSessionGuardType.EmailCode\n ? \"an email Steam Guard code is required\"\n : \"a device (TOTP) Steam Guard code is required\",\n });\n }\n // else (None, or only confirmations): fall through to polling.\n }\n\n private async submitCode(code: string, codeType: EAuthSessionGuardType): Promise<void> {\n if (!this.steamID) throw new LoginError(\"cannot submit Steam Guard code before begin\");\n await this.auth.updateAuthSessionWithSteamGuardCode(\n this.clientId,\n BigInt(this.steamID.getSteamID64()),\n code,\n codeType,\n );\n }\n\n private schedulePoll(): void {\n if (this.settled) return;\n this.pollTimer = setTimeout(() => {\n this.poll().catch((err) => this.fail(err instanceof Error ? err : new Error(String(err))));\n }, this.pollIntervalMs);\n }\n\n private async poll(): Promise<void> {\n if (this.settled) return;\n\n let res: Awaited<ReturnType<typeof this.auth.pollAuthSessionStatus>>;\n try {\n res = await this.auth.pollAuthSessionStatus(this.clientId, this.requestId);\n } catch (err) {\n if (Date.now() >= this.deadline) {\n this.stop();\n this.emit(\"timeout\");\n return;\n }\n this.emit(\"debug\", `poll error, retrying: ${(err as Error).message}`);\n this.schedulePoll();\n return;\n }\n\n if (res.hadRemoteInteraction) this.emitRemoteInteraction();\n if (res.newClientId) this.clientId = res.newClientId;\n if (res.accessToken) this.accessToken = res.accessToken;\n\n if (res.refreshToken) {\n this.refreshToken = res.refreshToken;\n if (res.accountName) this.username = res.accountName;\n this.stop();\n this.emit(\"authenticated\");\n return;\n }\n\n if (Date.now() >= this.deadline) {\n this.stop();\n this.emit(\"timeout\");\n return;\n }\n this.schedulePoll();\n }\n\n private emitRemoteInteraction(): void {\n if (this.remoteInteractionEmitted) return;\n this.remoteInteractionEmitted = true;\n this.emit(\"remoteInteraction\");\n }\n\n private fail(error: Error): void {\n if (this.settled) return;\n this.stop();\n this.emit(\"error\", error);\n }\n}\n","// How we present as the Steam mobile app on the wire (per-host UA + cookies) plus the login-time\n// device_details. Steam doesn't strictly require any of it, but we match the app consistently.\nexport type MobilePlatform = \"ios\" | \"android\";\n\nexport interface MobileProfile {\n mobileClient: MobilePlatform; // mobileClient cookie value\n mobileClientVersion: string; // its presence is Steam's trigger for mobile treatment\n apiUserAgent: string; // UA for api.steampowered.com\n webUserAgent: string; // UA for steamcommunity/store/help\n // device_details (BeginAuthSessionViaCredentials):\n deviceFriendlyName: string; // iOS sends the model id, e.g. \"iPhone18,3\"\n osType: number; // EOSType, signed: iOS -600, Android -500\n gamingDeviceType: number;\n appType?: number; // EAuthTokenAppType (iOS 1); omitted for Android\n}\n\n// Captured from a real iOS Steam app (Charles).\nexport const IOS_PROFILE: MobileProfile = {\n mobileClient: \"ios\",\n mobileClientVersion: \"777777 3.10.9\",\n apiUserAgent: \"Steam%20Mobile/10472498 CFNetwork/3860.600.12 Darwin/25.5.0\",\n webUserAgent:\n \"Mozilla/5.0 (iPhone; CPU iPhone OS 18_7 like Mac OS X; Valve Steam App Version/3) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148\",\n deviceFriendlyName: \"iPhone18,3\",\n osType: -600,\n gamingDeviceType: 528,\n appType: 1,\n};\n\n// Matches the Android Steam app (okhttp UA) and our android: confirmation device-ids.\nexport const ANDROID_PROFILE: MobileProfile = {\n mobileClient: \"android\",\n mobileClientVersion: \"777777 3.10.3\",\n apiUserAgent: \"okhttp/4.9.2\",\n webUserAgent:\n \"Mozilla/5.0 (Linux; Android 14; SM-S921B) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Mobile Safari/537.36\",\n deviceFriendlyName: \"Galaxy S25\",\n osType: -500,\n gamingDeviceType: 528,\n};\n\nconst PRESETS: Record<MobilePlatform, MobileProfile> = {\n ios: IOS_PROFILE,\n android: ANDROID_PROFILE,\n};\n\n// Default to iOS; a string picks a preset; an object overrides fields on the implied preset.\nexport function resolveMobileProfile(\n input?: MobilePlatform | Partial<MobileProfile>,\n): MobileProfile {\n if (input === undefined) return { ...IOS_PROFILE };\n if (typeof input === \"string\") return { ...PRESETS[input] };\n const base = input.mobileClient === \"android\" ? ANDROID_PROFILE : IOS_PROFILE;\n return { ...base, ...input };\n}\n","import { type Browser, Impit } from \"impit\";\nimport { type Cookie, CookieJar } from \"tough-cookie\";\nimport { URLS } from \"../core/constants.js\";\nimport { ProxyError } from \"../core/errors.js\";\nimport type { MobilePlatform, MobileProfile } from \"../core/mobileProfile.js\";\n\n// Hosts that share our session cookies. api is included because the mobile app sends them to the WebAPI host too.\nconst COOKIE_HOSTS = [URLS.community, URLS.store, URLS.help, URLS.api];\n\n// TLS fingerprint per request kind. iOS runs webview + API on one Apple stack, so ios18 serves both.\n// Android splits: community pages use the Chrome WebView, native api/mobileconf uses okhttp — and Steam's\n// WAF 429s an okhttp fingerprint on the community host, so web pages must look like Chrome.\nconst IMPIT_BROWSER: Record<MobilePlatform, { web: Browser; native: Browser }> = {\n ios: { web: \"ios18\", native: \"ios18\" },\n android: { web: \"chrome\", native: \"okhttp5\" },\n};\n\n// Document Accept for webview page loads; a browser always sends one and its absence is a WAF bot tell.\n// (JSON XHRs send application/json instead — see perform().)\nconst BROWSER_ACCEPT = \"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8\";\n\ntype Method = \"GET\" | \"POST\";\ntype ResponseType = \"text\" | \"json\" | \"buffer\";\ntype Scalar = string | number | boolean;\n\nexport interface HttpResponse<T = string> {\n statusCode: number;\n headers: Record<string, string | string[] | undefined>;\n body: T;\n}\n\n// Ordered multipart fields; repeated names (e.g. cid[]/ck[]) are allowed and order-significant.\nexport interface MultipartField {\n name: string;\n value: string;\n}\n\nexport interface RequestOptions {\n searchParams?: Record<string, Scalar | undefined>;\n // Request body: pass exactly one of form / multipart / json / body.\n form?: Record<string, Scalar | undefined>;\n multipart?: MultipartField[];\n json?: unknown;\n body?: string | Buffer;\n headers?: Record<string, string>;\n responseType?: ResponseType;\n referer?: string;\n signal?: AbortSignal; // abort the request\n timeoutMs?: number; // per-request timeout override (default 50000)\n}\n\nfunction clean(input?: Record<string, Scalar | undefined>): Record<string, string> | undefined {\n if (!input) return undefined;\n const out: Record<string, string> = {};\n for (const [k, v] of Object.entries(input)) {\n if (v !== undefined) out[k] = String(v);\n }\n return out;\n}\n\n// Hand-built to match the Steam mobile app's mobileconf POSTs.\nfunction buildMultipart(fields: MultipartField[], boundary: string): string {\n let out = \"\";\n for (const { name, value } of fields) {\n out += `--${boundary}\\r\\ncontent-disposition: form-data; name=\"${name}\"\\r\\n\\r\\n${value}\\r\\n`;\n }\n return `${out}--${boundary}--\\r\\n`;\n}\n\nexport class HttpClient {\n readonly jar: CookieJar;\n private readonly webClient: Impit;\n private readonly nativeClient: Impit;\n private readonly browserClient: Impit;\n private readonly profile: MobileProfile;\n private readonly proxy: string | undefined;\n\n constructor(opts: { proxy?: string; profile: MobileProfile }) {\n this.jar = new CookieJar();\n this.profile = opts.profile;\n this.proxy = opts.proxy;\n\n const makeClient = (browser: Browser): Impit =>\n new Impit({\n browser,\n cookieJar: this.jar,\n followRedirects: false,\n timeout: 50000,\n ...(opts.proxy ? { proxyUrl: opts.proxy } : {}),\n });\n const fp = IMPIT_BROWSER[this.profile.mobileClient];\n this.webClient = makeClient(fp.web);\n // iOS uses the same fingerprint for both, so reuse the one instance.\n this.nativeClient = fp.native === fp.web ? this.webClient : makeClient(fp.native);\n // Third-party hosts (e.g. an OpenID relying party behind Cloudflare) get a real Chrome hello:\n // impit's ios18 ClientHello trips Cloudflare's strict TLS parser (decode_error). Steam hosts, which\n // are lenient, keep the app-accurate fingerprint.\n this.browserClient = fp.web === \"chrome\" ? this.webClient : makeClient(\"chrome\");\n\n // Cookies that mark every request as coming from the Steam mobile app.\n for (const raw of [\n `mobileClient=${this.profile.mobileClient}`,\n `mobileClientVersion=${this.profile.mobileClientVersion}`,\n \"Steam_Language=english\",\n ]) {\n for (const host of COOKIE_HOSTS) this.jar.setCookieSync(raw, host);\n }\n }\n\n async request<T = string>(\n method: Method,\n url: string,\n opts: RequestOptions = {},\n ): Promise<HttpResponse<T>> {\n const res = await this.perform<T>(method, url, opts);\n // Steam gates trade/market pages behind a one-time eligibility check (302 → /market/\n // eligibilitycheck/ → back). We don't auto-follow redirects, so visit it once to prime the\n // session, then retry. A genuinely limited account keeps redirecting and the retry surfaces it.\n const location = firstHeader(res.headers.location);\n if (\n res.statusCode >= 300 &&\n res.statusCode < 400 &&\n location?.includes(\"/market/eligibilitycheck\")\n ) {\n await this.perform(\"GET\", location, opts.signal ? { signal: opts.signal } : {});\n return this.perform<T>(method, url, opts);\n }\n return res;\n }\n\n private async perform<T = string>(\n method: Method,\n url: string,\n opts: RequestOptions = {},\n ): Promise<HttpResponse<T>> {\n // Native app calls (WebAPI + mobileconf) carry the native UA; webview pages carry the web UA (per iOS-app captures).\n const isNative = url.startsWith(URLS.api) || url.includes(\"/mobileconf/\");\n const headers: Record<string, string> = {\n \"User-Agent\": isNative ? this.profile.apiUserAgent : this.profile.webUserAgent,\n \"Accept-Language\": \"en-US,en;q=0.9\",\n };\n if (isNative) {\n // Native app transport: JSON accept, no browser Origin/Sec-Fetch headers.\n headers.Accept = \"application/json, text/plain, */*\";\n } else {\n headers.Accept =\n opts.responseType === \"json\" ? \"application/json, text/plain, */*\" : BROWSER_ACCEPT;\n if (method !== \"GET\") {\n headers.Origin = URLS.community;\n if (opts.referer) headers.Referer = opts.referer;\n }\n }\n\n // Body: exactly one of multipart / form / json / body. impit auto-sets Content-Type for URLSearchParams;\n // for the hand-built multipart and json strings we set it explicitly so impit doesn't override.\n let body: string | Buffer | URLSearchParams | undefined;\n if (opts.multipart) {\n const boundary = `----steamMobile${randomSessionId()}`;\n body = buildMultipart(opts.multipart, boundary);\n headers[\"Content-Type\"] = `multipart/form-data; boundary=${boundary}`;\n } else if (opts.form) {\n body = new URLSearchParams(clean(opts.form));\n } else if (opts.json !== undefined) {\n body = JSON.stringify(opts.json);\n headers[\"Content-Type\"] = \"application/json\";\n } else if (opts.body !== undefined) {\n body = opts.body;\n }\n Object.assign(headers, opts.headers); // explicit caller headers win\n\n // impit's fetch takes a full URL (no searchParams option) — fold them into the query string.\n const target = new URL(url);\n const sp = clean(opts.searchParams);\n if (sp) for (const [k, v] of Object.entries(sp)) target.searchParams.set(k, v);\n\n try {\n const client = isNative\n ? this.nativeClient\n : isSteamHost(target.hostname)\n ? this.webClient\n : this.browserClient;\n const res = await client.fetch(target.toString(), {\n method,\n headers,\n ...(body !== undefined ? { body } : {}),\n ...(opts.signal ? { signal: opts.signal } : {}),\n ...(opts.timeoutMs !== undefined ? { timeout: opts.timeoutMs } : {}),\n });\n\n const responseType: ResponseType = opts.responseType ?? \"text\";\n let parsed: unknown;\n if (responseType === \"buffer\") {\n parsed = Buffer.from(await res.bytes());\n } else if (responseType === \"json\") {\n // Empty/invalid JSON → undefined body, never throw; callers branch on status, not parse errors.\n const text = await res.text();\n parsed = text ? safeJsonParse(text) : undefined;\n } else {\n parsed = await res.text();\n }\n\n return {\n statusCode: res.status,\n headers: headersToRecord(res.headers),\n body: parsed as T,\n };\n } catch (err) {\n throw this.wrapTransportError(err);\n }\n }\n\n // impit only throws on transport failures inside perform() (HTTP statuses don't throw); aborts surface as\n // a DOMException (not an Error subclass), so instanceof Error && !abort isolates a genuine transport failure.\n private wrapTransportError(err: unknown): unknown {\n if (this.proxy && err instanceof Error && !isAbortError(err)) {\n return new ProxyError(`proxy request failed: ${err.message}`, { cause: err });\n }\n return err;\n }\n\n get<T = string>(url: string, opts?: RequestOptions): Promise<HttpResponse<T>> {\n return this.request<T>(\"GET\", url, opts);\n }\n\n post<T = string>(url: string, opts?: RequestOptions): Promise<HttpResponse<T>> {\n return this.request<T>(\"POST\", url, opts);\n }\n\n async setCookie(rawCookie: string): Promise<void> {\n for (const host of COOKIE_HOSTS) {\n await this.jar.setCookie(rawCookie, host);\n }\n }\n\n // Read a cookie value from the jar (includes HttpOnly cookies). undefined if not set.\n async getCookie(key: string, url: string = URLS.community): Promise<string | undefined> {\n const cookies = await this.jar.getCookies(url);\n return cookies.find((c: Cookie) => c.key === key)?.value;\n }\n\n async getSessionId(): Promise<string> {\n const cookies = await this.jar.getCookies(URLS.community);\n const existing = cookies.find((c: Cookie) => c.key === \"sessionid\");\n if (existing) return existing.value;\n const sessionId = randomSessionId();\n await this.setCookie(`sessionid=${sessionId}`);\n return sessionId;\n }\n}\n\nfunction randomSessionId(): string {\n const bytes = new Uint8Array(12);\n globalThis.crypto.getRandomValues(bytes);\n return Array.from(bytes, (b) => b.toString(16).padStart(2, \"0\")).join(\"\");\n}\n\nfunction firstHeader(v: string | string[] | undefined): string | undefined {\n return Array.isArray(v) ? v[0] : v;\n}\n\nconst STEAM_HOSTS = [\"steamcommunity.com\", \"steampowered.com\"] as const;\n\n// Steam's own hosts (community/store/help/api); everything else is treated as a third-party site.\nfunction isSteamHost(host: string): boolean {\n const h = host.toLowerCase();\n return STEAM_HOSTS.some((d) => h === d || h.endsWith(`.${d}`));\n}\n\n// WHATWG Headers → lowercased plain record (consumers read location / x-eresult / x-error_message).\nfunction headersToRecord(h: Headers): Record<string, string> {\n const out: Record<string, string> = {};\n h.forEach((value, key) => {\n out[key] = value;\n });\n return out;\n}\n\nfunction safeJsonParse(text: string): unknown {\n try {\n return JSON.parse(text);\n } catch {\n return undefined;\n }\n}\n\nfunction isAbortError(err: unknown): boolean {\n if (typeof err !== \"object\" || err === null) return false;\n const e = err as { name?: unknown; code?: unknown };\n return e.name === \"AbortError\" || e.code === \"ERR_ABORTED\";\n}\n","import { LoginError } from \"../core/errors.js\";\nimport {\n type MobilePlatform,\n type MobileProfile,\n resolveMobileProfile,\n} from \"../core/mobileProfile.js\";\nimport { HttpClient } from \"../http/HttpClient.js\";\nimport { CredentialSession } from \"./CredentialSession.js\";\n\nexport interface LoginWithCredentialsOptions {\n username: string;\n password: string;\n sharedSecret?: string; // answers DeviceCode automatically via TOTP\n steamGuardCode?: string;\n proxy?: string;\n mobileProfile?: MobilePlatform | Partial<MobileProfile>;\n // Aborts the flow: stops polling and rejects with a LoginError.\n signal?: AbortSignal;\n // Called when a code is required and none was supplied; resolve to the code to continue.\n onSteamGuardRequired?: (info: { type: number; message: string }) => Promise<string> | string;\n}\n\nexport interface LoginResult {\n refreshToken: string;\n accessToken: string | undefined;\n steamId: string;\n username: string;\n}\n\n// One-shot credential login → MobileApp refresh token. Feed into `new SteamMobile({ refreshToken })`.\nexport function loginWithCredentials(opts: LoginWithCredentialsOptions): Promise<LoginResult> {\n const profile = resolveMobileProfile(opts.mobileProfile);\n const http = new HttpClient({ ...(opts.proxy ? { proxy: opts.proxy } : {}), profile });\n const session = new CredentialSession(http, profile);\n\n return new Promise<LoginResult>((resolve, reject) => {\n const { signal } = opts;\n const onAbort = (): void => {\n session.stop();\n reject(new LoginError(\"login aborted\"));\n };\n const cleanup = (): void => signal?.removeEventListener(\"abort\", onAbort);\n const fail = (err: Error): void => {\n session.stop();\n cleanup();\n reject(err);\n };\n\n if (signal?.aborted) {\n reject(new LoginError(\"login aborted\"));\n return;\n }\n signal?.addEventListener(\"abort\", onAbort, { once: true });\n\n session.on(\"error\", fail);\n session.on(\"timeout\", () => fail(new LoginError(\"login timed out waiting for confirmation\")));\n session.on(\"authenticated\", () => {\n cleanup();\n if (!session.refreshToken || !session.steamID) {\n reject(new LoginError(\"login completed without a refresh token\"));\n return;\n }\n resolve({\n refreshToken: session.refreshToken,\n accessToken: session.accessToken,\n steamId: session.steamID.getSteamID64(),\n username: session.username,\n });\n });\n\n session.on(\"steamGuardRequired\", (info) => {\n const handler = opts.onSteamGuardRequired;\n if (!handler) {\n fail(\n new LoginError(\n `${info.message}; pass sharedSecret, steamGuardCode, or onSteamGuardRequired`,\n ),\n );\n return;\n }\n Promise.resolve(handler(info))\n .then((code) => session.submitSteamGuardCode(code))\n .catch((err) => fail(err instanceof Error ? err : new Error(String(err))));\n });\n\n session.start(opts).catch((err) => fail(err instanceof Error ? err : new Error(String(err))));\n });\n}\n","export interface Page<T, C> {\n items: T[];\n next: C | undefined;\n}\n\nexport async function paginate<T, C>(\n fetchPage: (cursor: C | undefined) => Promise<Page<T, C>>,\n): Promise<T[]> {\n const all: T[] = [];\n let cursor: C | undefined;\n do {\n const { items, next } = await fetchPage(cursor);\n all.push(...items);\n cursor = next;\n } while (cursor !== undefined);\n return all;\n}\n","import { EResult } from \"./enums.js\";\nimport {\n ItemServerUnavailableError,\n NewDeviceError,\n OfferLimitError,\n PrivateInventoryError,\n SteamError,\n TargetCannotTradeError,\n TradeBanError,\n} from \"./errors.js\";\n\n// Classify a Steam-supplied error string (sendOffer `strError`, accept-offer body, or scraped trade-page\n// <div id=\"error_msg\">) into the right typed error. Mirrors steam-tradeoffer-manager's makeAnError\n// taxonomy plus the inventory-privacy case Steam shows on the trade page.\nexport function parseStrError(message: string): SteamError {\n const match = message.match(/\\((\\d+)\\)$/);\n const eresult = match?.[1] !== undefined ? Number(match[1]) : undefined;\n const opts = eresult !== undefined ? { eresult } : undefined;\n\n if (/You cannot trade with .* because they have a trade ban\\./.test(message)) {\n return new TradeBanError(message);\n }\n if (/sent too many trade offers/.test(message)) {\n return new OfferLimitError(message);\n }\n if (/You have logged in from a new device/.test(message)) {\n return new NewDeviceError(message, opts);\n }\n if (/is not available to trade\\. More information will be shown to/.test(message)) {\n return new TargetCannotTradeError(message, opts);\n }\n if (/unable to contact the game's item server/.test(message)) {\n return new ItemServerUnavailableError(message, {\n eresult: eresult ?? EResult.ServiceUnavailable,\n });\n }\n if (\n /inventory privacy is set to|inventory is (?:currently )?private|profile's inventory is private/i.test(\n message,\n )\n ) {\n return new PrivateInventoryError(message);\n }\n return new SteamError(message, opts);\n}\n","// Per-endpoint rate-limit config, from live profiling (Steam doesn't send Retry-After). null = not measured yet.\n// window — `max` calls per `windowMs`. bucket — `capacity` burst, 1 token refills every `refillMs`.\nexport type RateLimit =\n | { type: \"window\"; windowMs: number; max: number }\n | { type: \"bucket\"; capacity: number; refillMs: number };\n\nexport const RATE_LIMITS = {\n partnerInventory: { type: \"window\", windowMs: 120_000, max: 30 },\n inventory: null,\n GetTradeHistory: { type: \"bucket\", capacity: 25, refillMs: 15_000 },\n GetTradeHoldDurations: { type: \"bucket\", capacity: 3750, refillMs: 5 },\n GetTradeOffer: { type: \"bucket\", capacity: 3750, refillMs: 5 },\n GetTradeOffers: { type: \"bucket\", capacity: 85, refillMs: 125 },\n GetTradeOffersSummary: { type: \"bucket\", capacity: 85, refillMs: 125 },\n GetTradeStatus: { type: \"bucket\", capacity: 25, refillMs: 2000 },\n} as const satisfies Record<string, RateLimit | null>;\n\nexport type RateLimitedEndpoint = keyof typeof RATE_LIMITS;\n\nfunction retryAfterMs(limit: RateLimit | null): number | null {\n if (!limit) return null;\n return limit.type === \"bucket\" ? limit.refillMs : limit.windowMs;\n}\n\n// Retry-after hint (ms) per endpoint: one token for a bucket, the full window otherwise.\nexport const RETRY_AFTER = Object.fromEntries(\n Object.entries(RATE_LIMITS).map(([key, limit]) => [key, retryAfterMs(limit)]),\n) as Record<RateLimitedEndpoint, number | null>;\n","import {\n FamilyViewError,\n HttpStatusError,\n RateLimitError,\n SteamError,\n SteamSessionExpiredError,\n} from \"../core/errors.js\";\nimport type { HttpResponse } from \"./HttpClient.js\";\n\nfunction locationHeader(res: HttpResponse<unknown>): string {\n const loc = res.headers.location;\n return Array.isArray(loc) ? (loc[0] ?? \"\") : (loc ?? \"\");\n}\n\nexport function httpError(\n res: HttpResponse<unknown>,\n rateLimitWindowMs?: number | null,\n): SteamError {\n if (res.statusCode === 429) {\n return new RateLimitError({\n statusCode: 429,\n body: res.body,\n ...(typeof rateLimitWindowMs === \"number\" ? { retryAfterMs: rateLimitWindowMs } : {}),\n });\n }\n if (res.statusCode === 401) return new SteamSessionExpiredError();\n if (res.statusCode >= 300 && res.statusCode <= 399) {\n const loc = locationHeader(res);\n if (loc.includes(\"/login\")) return new SteamSessionExpiredError();\n if (loc.includes(\"eligibilitycheck\")) {\n return new SteamError(\n \"Steam redirected to the market eligibility check — this account is limited / not trade-eligible\",\n );\n }\n }\n return new HttpStatusError(res.statusCode, undefined, res.body);\n}\n\nexport function checkHttpError(res: HttpResponse<unknown>): void {\n const { statusCode } = res;\n\n if (statusCode >= 300 && statusCode <= 399 && locationHeader(res).includes(\"/login\")) {\n throw new SteamSessionExpiredError();\n }\n\n if (\n statusCode === 403 &&\n typeof res.body === \"string\" &&\n /<div id=\"parental_notice_instructions\">/.test(res.body)\n ) {\n throw new FamilyViewError();\n }\n\n if (statusCode >= 400) {\n throw new HttpStatusError(statusCode, undefined, res.body);\n }\n}\n\nexport function checkCommunityError(html: unknown): void {\n if (typeof html !== \"string\") return;\n\n const sorry = html.match(/<h1>Sorry!<\\/h1>/);\n if (sorry) {\n const match = html.match(/<h3>(.+)<\\/h3>/);\n throw new SteamError(match?.[1] ?? \"Unknown error occurred\");\n }\n\n if (html.includes(\"g_steamID = false;\") && html.includes(\"<title>Sign In</title>\")) {\n throw new SteamSessionExpiredError();\n }\n}\n\nexport function checkTradeError(html: unknown): void {\n if (typeof html !== \"string\") return;\n const match = html.match(/<div id=\"error_msg\">\\s*([^<]+)\\s*<\\/div>/);\n if (match?.[1]) throw new SteamError(match[1].trim());\n}\n","import SteamID from \"steamid\";\nimport { URLS } from \"../core/constants.js\";\nimport type { SteamError } from \"../core/errors.js\";\nimport { parseStrError } from \"../core/parseStrError.js\";\nimport type { HttpClient } from \"./HttpClient.js\";\n\n// Scrape <div id=\"error_msg\">…</div> from the trade page — the richer \"their inventory is private\",\n// \"trade-banned\", \"limited account\" etc. message Steam shows the user. Regex matches McKay's\n// `[^<]+` — text-only, no nested markup.\nexport async function fetchTradePageErrorMessage(\n http: HttpClient,\n steamId: string,\n token?: string | undefined,\n): Promise<string | undefined> {\n const accountId = new SteamID(steamId).accountid;\n const url = `${URLS.community}/tradeoffer/new/?partner=${accountId}${token ? `&token=${token}` : \"\"}`;\n const res = await http.get<string>(url, {\n responseType: \"text\",\n headers: { Referer: `${URLS.community}/profiles/${steamId}` },\n });\n if (res.statusCode !== 200) return undefined;\n const match = res.body.match(/<div id=\"error_msg\">\\s*([^<]+)\\s*<\\/div>/);\n return match?.[1]?.replace(/\\s+/g, \" \").trim() || undefined;\n}\n\n// Resolve the best error to throw when an inventory endpoint reports a failure. Loads the trade page\n// for the richer Steam-rendered message, then classifies (private / trade-ban / new device / etc.).\n// Falls back to the JSON body's error string if the page has nothing useful.\nexport async function inventoryFailureError(\n http: HttpClient,\n steamId: string,\n token: string | undefined,\n bodyMessage: string | undefined,\n): Promise<SteamError> {\n const scraped = await fetchTradePageErrorMessage(http, steamId, token).catch(() => undefined);\n const message = scraped ?? bodyMessage ?? \"Failed to load inventory\";\n return parseStrError(message);\n}\n","export interface SteamTag {\n category: string;\n internal_name: string;\n localized_category_name?: string;\n category_name?: string;\n localized_tag_name?: string;\n name?: string;\n color?: string;\n}\n\nexport interface SteamDescriptionLine {\n type: string;\n value: string;\n color?: string;\n name?: string;\n}\n\nexport interface SteamAction {\n link: string;\n name: string;\n type?: string;\n}\n\nexport interface AssetProperty {\n propertyid: number;\n int_value?: string;\n float_value?: string;\n string_value?: string;\n}\n\nexport interface RawInventoryAsset {\n appid?: number | string;\n contextid?: string;\n assetid?: string;\n id?: string;\n classid: string;\n instanceid?: string;\n amount: string;\n currencyid?: string;\n pos?: number;\n [key: string]: unknown;\n}\n\nexport interface RawDescription {\n appid?: number | string;\n classid: string;\n instanceid?: string;\n icon_url?: string;\n name?: string;\n type?: string;\n market_name?: string;\n market_hash_name?: string;\n tradable?: number | boolean;\n marketable?: number | boolean;\n commodity?: number | boolean;\n market_tradable_restriction?: number | string;\n market_marketable_restriction?: number | string;\n descriptions?: SteamDescriptionLine[];\n owner_descriptions?: SteamDescriptionLine[];\n actions?: SteamAction[];\n market_actions?: SteamAction[];\n fraudwarnings?: string[];\n tags?: SteamTag[];\n [key: string]: unknown;\n}\n\nexport interface RawAssetPropertyEntry {\n appid: number;\n contextid: string;\n assetid: string;\n asset_properties: AssetProperty[];\n}\n\nexport interface RawInventoryResponse {\n assets?: RawInventoryAsset[];\n descriptions?: RawDescription[];\n asset_properties?: RawAssetPropertyEntry[];\n more_items?: number;\n last_assetid?: string;\n total_inventory_count?: number;\n success?: number;\n error?: string;\n Error?: string;\n}\n\nexport interface RawPartnerInventoryResponse {\n success?: boolean;\n error?: string;\n Error?: string;\n rgInventory?: Record<string, RawInventoryAsset> | unknown[];\n rgDescriptions?: Record<string, RawDescription> | unknown[];\n rgAssetProperties?: Record<string, AssetProperty[]> | unknown[];\n more?: boolean;\n more_start?: number | boolean;\n}\n\nexport interface EconItem {\n appid: number;\n contextid: string;\n assetid: string;\n classid: string;\n instanceid: string;\n amount: number;\n currencyid?: string;\n\n name: string;\n market_name: string;\n market_hash_name: string;\n type: string;\n name_color?: string;\n background_color?: string;\n icon_url: string;\n icon_url_large?: string;\n\n tradable: boolean;\n marketable: boolean;\n commodity: boolean;\n market_tradable_restriction: number;\n market_marketable_restriction: number;\n\n descriptions: SteamDescriptionLine[];\n owner_descriptions: SteamDescriptionLine[];\n actions: SteamAction[];\n market_actions: SteamAction[];\n fraudwarnings: string[];\n tags: SteamTag[];\n asset_properties: AssetProperty[];\n\n [key: string]: unknown;\n}\n\nfunction toBool(value: number | boolean | undefined): boolean {\n return typeof value === \"boolean\" ? value : Number(value ?? 0) !== 0;\n}\n\nfunction toInt(value: number | string | undefined): number {\n return value ? Number.parseInt(String(value), 10) : 0;\n}\n\nfunction asRecord<T>(value: Record<string, T> | unknown[] | undefined): Record<string, T> {\n return value && !Array.isArray(value) ? value : {};\n}\n\n// Key by appid_classid_instanceid: trade offers span multiple apps, so appid must be in the key (unlike single-app inventory).\nexport function buildDescriptionMap(\n descriptions: RawDescription[] | undefined,\n): Map<string, RawDescription> {\n const map = new Map<string, RawDescription>();\n for (const d of descriptions ?? []) {\n map.set(`${d.appid}_${d.classid}_${d.instanceid ?? \"0\"}`, d);\n }\n return map;\n}\n\nexport function buildItem(\n asset: RawInventoryAsset,\n description: RawDescription | undefined,\n properties: AssetProperty[],\n fallbackContextId: string,\n): EconItem {\n return {\n ...asset,\n ...description,\n appid: Number(asset.appid ?? description?.appid ?? 0),\n contextid: (asset.contextid ?? fallbackContextId).toString(),\n assetid: (asset.assetid ?? asset.id ?? \"\").toString(),\n classid: asset.classid.toString(),\n instanceid: (asset.instanceid ?? \"0\").toString(),\n amount: toInt(asset.amount),\n ...(asset.currencyid ? { currencyid: asset.currencyid } : {}),\n name: description?.name ?? \"\",\n market_name: description?.market_name ?? \"\",\n market_hash_name: description?.market_hash_name ?? \"\",\n type: description?.type ?? \"\",\n icon_url: description?.icon_url ?? \"\",\n tradable: toBool(description?.tradable),\n marketable: toBool(description?.marketable),\n commodity: toBool(description?.commodity),\n market_tradable_restriction: toInt(description?.market_tradable_restriction),\n market_marketable_restriction: toInt(description?.market_marketable_restriction),\n descriptions: description?.descriptions ?? [],\n owner_descriptions: description?.owner_descriptions ?? [],\n actions: description?.actions ?? [],\n market_actions: description?.market_actions ?? [],\n fraudwarnings: description?.fraudwarnings ?? [],\n tags: description?.tags ?? [],\n asset_properties: properties,\n };\n}\n\nexport function parseInventory(\n body: RawInventoryResponse,\n contextid: string,\n tradableOnly = false,\n): EconItem[] {\n const descriptions = new Map<string, RawDescription>();\n for (const d of body.descriptions ?? []) {\n descriptions.set(`${d.classid}_${d.instanceid ?? \"0\"}`, d);\n }\n\n const properties = new Map<string, AssetProperty[]>();\n for (const p of body.asset_properties ?? []) {\n properties.set(p.assetid, p.asset_properties);\n }\n\n const items: EconItem[] = [];\n for (const asset of body.assets ?? []) {\n const assetid = (asset.assetid ?? asset.id ?? \"\").toString();\n const description = descriptions.get(`${asset.classid}_${asset.instanceid ?? \"0\"}`);\n if (tradableOnly && !toBool(description?.tradable)) continue;\n items.push(buildItem(asset, description, properties.get(assetid) ?? [], contextid));\n }\n return items;\n}\n\nexport function parsePartnerInventory(\n body: RawPartnerInventoryResponse,\n contextid: string,\n tradableOnly = false,\n): EconItem[] {\n const inventory = asRecord<RawInventoryAsset>(body.rgInventory);\n const descriptions = asRecord<RawDescription>(body.rgDescriptions);\n const properties = asRecord<AssetProperty[]>(body.rgAssetProperties);\n\n const assets = Object.values(inventory).sort((a, b) => Number(a.pos ?? 0) - Number(b.pos ?? 0));\n const items: EconItem[] = [];\n for (const asset of assets) {\n const description = descriptions[`${asset.classid}_${asset.instanceid ?? \"0\"}`];\n if (tradableOnly && !toBool(description?.tradable)) continue;\n const assetid = (asset.assetid ?? asset.id ?? \"\").toString();\n items.push(buildItem(asset, description, properties[assetid] ?? [], contextid));\n }\n return items;\n}\n","import type { Cookie } from \"tough-cookie\";\nimport { URLS } from \"../core/constants.js\";\nimport { OpenIdError } from \"../core/errors.js\";\nimport type { HttpClient, HttpResponse, MultipartField } from \"../http/HttpClient.js\";\n\nconst STEAM_OPENID_URL = `${URLS.community}/openid/login`;\nconst DEFAULT_MAX_REDIRECTS = 10;\n// got sends no Accept on web requests; a browser does, and a relying party's /login may negotiate on it.\nconst BROWSER_ACCEPT = \"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8\";\n\nexport interface OpenidConfirmation {\n // The signed assertion redirect Steam issues back to the relying party (carries the openid.* id_res params).\n location: string;\n params: Record<string, string>;\n steamId: string;\n}\n\nexport interface OpenidCookie {\n name: string;\n value: string;\n}\n\nexport interface OpenidLoginResult {\n steamId: string;\n // Where the relying party left us once it consumed the assertion.\n finalUrl: string;\n // Cookies the relying party set, scoped to its host - carry these into your own HTTP client.\n cookies: OpenidCookie[];\n}\n\nexport interface OpenidLoginOptions {\n // The relying party's \"Sign in through Steam\" entry URL (a plain GET that 302-chains to Steam).\n initiateUrl: string;\n // Host whose cookies to return; defaults to the host we land on.\n cookieHost?: string;\n maxRedirects?: number;\n}\n\nfunction locationOf(res: HttpResponse<string>): string | undefined {\n const loc = res.headers.location;\n return (Array.isArray(loc) ? loc[0] : loc) || undefined;\n}\n\nfunction isRedirect(res: HttpResponse<string>): boolean {\n return res.statusCode >= 300 && res.statusCode < 400 && locationOf(res) !== undefined;\n}\n\nfunction queryParams(url: string): Record<string, string> {\n const out: Record<string, string> = {};\n for (const [k, v] of new URL(url).searchParams) out[k] = v;\n return out;\n}\n\n// Decode the HTML entities that occur in form attribute values (& last, so &quot; survives).\nfunction decodeEntities(s: string): string {\n return s\n .replace(/"/g, '\"')\n .replace(/�?39;/g, \"'\")\n .replace(/'/g, \"'\")\n .replace(/</g, \"<\")\n .replace(/>/g, \">\")\n .replace(/&/g, \"&\");\n}\n\n// Steam's /openid/login interstitial submits multipart/form-data (urlencoded -> \"Invalid Params\").\nexport function parseOpenidForm(html: string): { action: string; fields: MultipartField[] } | null {\n const form = [...html.matchAll(/<form\\b([^>]*?)>([\\s\\S]*?)<\\/form>/gi)].find((m) =>\n /openid\\/login/i.test(m[1] ?? \"\"),\n );\n const action = form?.[1]?.match(/\\baction=[\"']([^\"']+)[\"']/i)?.[1];\n if (!form || !action) return null;\n const fields: MultipartField[] = [];\n for (const tag of (form[2] ?? \"\").match(/<input\\b[^>]*>/gi) ?? []) {\n const name = tag.match(/\\bname=[\"']([^\"']*)[\"']/i)?.[1];\n if (!name) continue;\n const value = decodeEntities(tag.match(/\\bvalue=[\"']([^\"']*)[\"']/i)?.[1] ?? \"\");\n fields.push({ name, value });\n }\n return { action: new URL(decodeEntities(action), STEAM_OPENID_URL).toString(), fields };\n}\n\n// Confirm a Steam OpenID assertion from an interstitial page you've already loaded (the session must be\n// authenticated) and return the signed redirect Steam issues to the relying party. This is the\n// protocol-universal leg; consuming `location` (the relying party's own callback) is the caller's concern.\nexport async function confirmOpenid(\n http: HttpClient,\n interstitialHtml: string,\n referer?: string,\n): Promise<OpenidConfirmation> {\n const form = parseOpenidForm(interstitialHtml);\n if (!form) {\n throw new OpenIdError(\"no Steam OpenID form in the page; the web session is not authenticated\");\n }\n const res = await http.post<string>(form.action, {\n multipart: form.fields,\n headers: { Accept: BROWSER_ACCEPT },\n ...(referer ? { referer } : {}),\n });\n const location = isRedirect(res) ? locationOf(res) : undefined;\n if (!location) {\n throw new OpenIdError(`Steam returned no OpenID assertion redirect (HTTP ${res.statusCode})`);\n }\n const params = queryParams(location);\n const claimed = params[\"openid.claimed_id\"] ?? params[\"openid.identity\"] ?? \"\";\n const steamId = claimed.match(/\\/id\\/(\\d{17})/)?.[1];\n if (!steamId) throw new OpenIdError(\"OpenID assertion carried no steamid\");\n return { location, params, steamId };\n}\n\n// Log into a third-party relying party that offers \"Sign in through Steam\", spending the live web\n// session in `http`'s jar. Drives entry -> Steam confirm -> relying-party callback, then returns the\n// cookies the site set. Site-specific gates (Cloudflare, device headers, etc.) are the caller's job.\nexport async function steamOpenidLogin(\n http: HttpClient,\n options: OpenidLoginOptions,\n): Promise<OpenidLoginResult> {\n const maxRedirects = options.maxRedirects ?? DEFAULT_MAX_REDIRECTS;\n await http.getSessionId(); // a sessionid cookie must accompany steamLoginSecure on the handshake\n const get = (u: string) => http.get<string>(u, { headers: { Accept: BROWSER_ACCEPT } });\n\n let url = options.initiateUrl;\n let res = await get(url);\n for (let i = 0; i < maxRedirects && isRedirect(res); i++) {\n url = new URL(locationOf(res) as string, url).toString();\n res = await get(url);\n }\n\n const confirmation = await confirmOpenid(http, res.body, url);\n\n url = confirmation.location;\n res = await get(url);\n for (let i = 0; i < maxRedirects && isRedirect(res); i++) {\n url = new URL(locationOf(res) as string, url).toString();\n res = await get(url);\n }\n\n const cookieHost = options.cookieHost ? `https://${options.cookieHost}` : new URL(url).origin;\n const cookies = (await http.jar.getCookies(cookieHost)).map((c: Cookie) => ({\n name: c.key,\n value: c.value,\n }));\n return { steamId: confirmation.steamId, finalUrl: url, cookies };\n}\n","import { URLS } from \"../core/constants.js\";\nimport { httpError } from \"../http/checkers.js\";\nimport type { HttpClient } from \"../http/HttpClient.js\";\n\n// 2025 trade-protection notice; Steam blocks send() until it's acknowledged once. Plain community POST\n// — no mobileconf, no identitySecret. Idempotent on the server side.\nexport async function acknowledgeTradeProtection(http: HttpClient): Promise<void> {\n const sessionid = await http.getSessionId();\n const res = await http.post<unknown>(`${URLS.community}/trade/new/acknowledge`, {\n form: { sessionid, message: 1 },\n });\n if (res.statusCode !== 200) throw httpError(res);\n}\n","import { DEFAULT_CONTEXTID, LANG, URLS } from \"../core/constants.js\";\nimport { SteamError } from \"../core/errors.js\";\nimport { type Page, paginate } from \"../core/paginate.js\";\nimport { parseStrError } from \"../core/parseStrError.js\";\nimport { RETRY_AFTER } from \"../core/rateLimits.js\";\nimport type { WebTradeEligibility } from \"../core/types.js\";\nimport { checkCommunityError, httpError } from \"../http/checkers.js\";\nimport type { HttpClient } from \"../http/HttpClient.js\";\nimport { inventoryFailureError } from \"../http/tradePageError.js\";\nimport type { WebApiClient } from \"../http/webApi.js\";\nimport {\n type EconItem,\n parseInventory,\n parsePartnerInventory,\n type RawInventoryResponse,\n type RawPartnerInventoryResponse,\n} from \"../models/EconItem.js\";\nimport type { SessionManager } from \"../session/SessionManager.js\";\nimport type { ConfirmationManager } from \"./confirmations.js\";\nimport { type OpenidLoginOptions, type OpenidLoginResult, steamOpenidLogin } from \"./openid.js\";\nimport { acknowledgeTradeProtection } from \"./tradeProtection.js\";\n\nconst INVENTORY_PAGE_SIZE = 2000;\n\nexport interface GetInventoryOptions {\n steamId?: string;\n tradableOnly?: boolean;\n}\n\nexport interface SteamProfile {\n steamId: string;\n personaName: string;\n avatar: string;\n accountCreated: Date | null;\n tradeBanState: string;\n isLimited: boolean;\n vacBanned: boolean;\n privacyState: string;\n}\n\nexport class CommunityNamespace {\n constructor(\n private readonly http: HttpClient,\n private readonly session: SessionManager,\n private readonly confirmations: ConfirmationManager,\n private readonly api: WebApiClient,\n ) {}\n\n acknowledgeTradeProtection(): Promise<void> {\n return acknowledgeTradeProtection(this.http);\n }\n\n // Our trade URL, scraped from /profiles/<id>/tradeoffers/privacy directly (we know our steamid; skip upstream's /my redirect).\n async getTradeURL(): Promise<{ url: string; token: string }> {\n await this.session.getAccessToken();\n const steamId = this.session.steamID.getSteamID64();\n const res = await this.http.get<string>(\n `${URLS.community}/profiles/${steamId}/tradeoffers/privacy`,\n { responseType: \"text\", headers: { Referer: `${URLS.community}/profiles/${steamId}` } },\n );\n if (res.statusCode !== 200) throw httpError(res);\n const html = res.body;\n checkCommunityError(html);\n\n const match = html.match(\n /https?:\\/\\/(?:www\\.)?steamcommunity\\.com\\/tradeoffer\\/new\\/\\?partner=\\d+(?:&|&)token=([a-zA-Z0-9\\-_]+)/,\n );\n if (!match?.[1]) throw new SteamError(\"Failed to parse trade URL from the privacy page\");\n return { url: match[0].replace(/&/g, \"&\"), token: match[1] };\n }\n\n // Regenerate our trade URL/token (invalidates the old one).\n async changeTradeURL(): Promise<{ url: string; token: string }> {\n await this.session.getAccessToken();\n const steamId = this.session.steamID.getSteamID64();\n const sessionid = await this.http.getSessionId();\n const res = await this.http.post<unknown>(\n `${URLS.community}/profiles/${steamId}/tradeoffers/newtradeurl`,\n { responseType: \"json\", form: { sessionid } },\n );\n if (res.statusCode !== 200) throw httpError(res);\n // Steam returns either a bare JSON string token or { token }.\n const body = res.body;\n const token =\n typeof body === \"string\" ? body : String((body as { token?: string })?.token ?? \"\");\n if (!token) throw new SteamError(\"Failed to parse the new trade token\");\n const accountId = this.session.steamID.accountid;\n return { url: `${URLS.community}/tradeoffer/new/?partner=${accountId}&token=${token}`, token };\n }\n\n // Profile summary from the community XML (one request). Steam level isn't here — use getSteamLevel().\n async getProfile(steamId?: string): Promise<SteamProfile> {\n await this.session.getAccessToken();\n const id = steamId ?? this.session.steamID.getSteamID64();\n const res = await this.http.get<string>(`${URLS.community}/profiles/${id}?xml=1`, {\n responseType: \"text\",\n });\n if (res.statusCode !== 200) throw httpError(res);\n const xml = res.body;\n checkCommunityError(xml);\n if (!xml.includes(\"<steamID64>\")) throw new SteamError(\"Failed to load the profile XML\");\n\n const memberSince = xmlValue(xml, \"memberSince\");\n const created = memberSince ? new Date(memberSince) : null;\n\n return {\n steamId: id,\n personaName: xmlValue(xml, \"steamID\") ?? \"\",\n avatar: xmlValue(xml, \"avatarFull\") ?? \"\",\n accountCreated: created && !Number.isNaN(created.getTime()) ? created : null,\n tradeBanState: xmlValue(xml, \"tradeBanState\") ?? \"None\",\n isLimited: xmlValue(xml, \"isLimitedAccount\") === \"1\",\n vacBanned: xmlValue(xml, \"vacBanned\") === \"1\",\n privacyState: xmlValue(xml, \"privacyState\") ?? \"\",\n };\n }\n\n // Run Steam's web-trade eligibility check. The endpoint 302s back (we don't follow), priming the\n // session and leaving a `webTradeEligibility` cookie that carries the verdict — whether trades are\n // allowed plus the active Steam Guard / new-device holds gating them. We decode and return it 1:1.\n async getWebTradeEligibility(): Promise<WebTradeEligibility> {\n await this.session.getAccessToken();\n const res = await this.http.get<string>(`${URLS.community}/market/eligibilitycheck/`, {\n responseType: \"text\",\n headers: { Referer: `${URLS.community}/` },\n });\n if (res.statusCode >= 400) throw httpError(res);\n const raw = await this.http.getCookie(\"webTradeEligibility\");\n if (!raw) throw new SteamError(\"Steam did not return a webTradeEligibility cookie\");\n try {\n return JSON.parse(decodeURIComponent(raw)) as WebTradeEligibility;\n } catch {\n throw new SteamError(\"Failed to parse the webTradeEligibility cookie\");\n }\n }\n\n // Log into a third-party site that offers \"Sign in through Steam\" (OpenID 2.0), spending this live\n // web session. Returns the cookies the site set - carry them into your own HTTP client for its API.\n async openidLogin(options: OpenidLoginOptions): Promise<OpenidLoginResult> {\n await this.session.getAccessToken();\n return steamOpenidLogin(this.http, options);\n }\n\n // Steam level via IPlayerService (accepts the access token — no API key needed).\n async getSteamLevel(steamId?: string): Promise<number> {\n const id = steamId ?? this.session.steamID.getSteamID64();\n const res = await this.api.call<{ response?: { player_level?: number } }>({\n httpMethod: \"GET\",\n iface: \"IPlayerService\",\n method: \"GetSteamLevel\",\n input: { steamid: id },\n });\n return res.response?.player_level ?? 0;\n }\n\n // Existing Web API key, else register one (auto-confirms via identitySecret). null if ineligible.\n async ensureApiKey(domain = \"assetpay.gg\"): Promise<string | null> {\n await this.session.getAccessToken();\n const res = await this.http.get<string>(`${URLS.community}/dev/apikey?l=english`, {\n responseType: \"text\",\n });\n if (res.statusCode !== 200) throw httpError(res);\n const body = res.body;\n const key = body.match(/<p>Key:\\s*([0-9A-F]+)<\\/p>/i)?.[1];\n if (key) return key;\n if (\n /validated email address|Steam Guard Mobile Authenticator|<h2>Access Denied<\\/h2>/i.test(body)\n ) {\n return null;\n }\n return this.requestApiKey(domain);\n }\n\n private async requestApiKey(domain: string, requestId = \"0\"): Promise<string | null> {\n const sessionid = await this.http.getSessionId();\n const res = await this.http.post<{ api_key?: string; request_id?: string }>(\n `${URLS.community}/dev/requestkey`,\n {\n responseType: \"json\",\n form: { domain, request_id: requestId, sessionid, agreeToTerms: \"true\" },\n },\n );\n if (res.statusCode !== 200) throw httpError(res);\n const body = res.body ?? {};\n if (body.api_key) return body.api_key;\n // Pending: Steam wants a mobile confirmation. Auto-accept it (needs identitySecret), then retry.\n if (body.request_id) {\n try {\n await this.confirmations.acceptConfirmationForObject(body.request_id);\n } catch {\n return null;\n }\n return this.requestApiKey(domain, body.request_id);\n }\n return null;\n }\n\n async getInventory(\n appid: number,\n contextid: string = DEFAULT_CONTEXTID,\n options: GetInventoryOptions = {},\n ): Promise<EconItem[]> {\n await this.session.getAccessToken();\n const ownId = this.session.steamID.getSteamID64();\n const steamId = options.steamId ?? ownId;\n const tradableOnly = options.tradableOnly ?? false;\n return steamId === ownId\n ? this.getOwnInventoryItems(steamId, appid, contextid, tradableOnly)\n : this.getTheirInventory(steamId, appid, contextid, tradableOnly);\n }\n\n // Own inventory uses the legacy /inventory/json/ endpoint: near-nonexistent rate limits, surfaces\n // trade-protected items, and the rg* response shape matches /partnerinventory/. The modern\n // IEconService/GetInventoryItemsWithDescriptions endpoint trips Steam's silent throttle (returns\n // {response:{}}) on ≥2 calls/sec, which makes it unfit for repeated use.\n // trading=1 is Steam's server-side tradable filter; legacy endpoint has no other knob for it.\n private getOwnInventoryItems(\n steamId: string,\n appid: number,\n contextid: string,\n tradableOnly: boolean,\n ): Promise<EconItem[]> {\n const url = `${URLS.community}/profiles/${steamId}/inventory/json/${appid}/${contextid}`;\n return paginate<EconItem, number>(async (start): Promise<Page<EconItem, number>> => {\n const res = await this.http.get<RawPartnerInventoryResponse>(url, {\n responseType: \"json\",\n searchParams: {\n trading: tradableOnly ? 1 : 0,\n preserve_bbcode: 1,\n l: LANG.l,\n ...(start !== undefined ? { start } : {}),\n },\n headers: { Referer: `${URLS.community}/profiles/${steamId}/inventory` },\n });\n if (res.statusCode !== 200) throw httpError(res, RETRY_AFTER.inventory);\n const body = res.body;\n if (!body?.success) {\n throw new SteamError(body?.error ?? body?.Error ?? \"Malformed inventory response\");\n }\n\n const next =\n body.more && typeof body.more_start === \"number\" && body.more_start > (start ?? 0)\n ? body.more_start\n : undefined;\n return { items: parsePartnerInventory(body, contextid, tradableOnly), next };\n });\n }\n\n // Their inventory uses the new /inventory/ endpoint (the legacy one only serves the logged-in user).\n private getTheirInventory(\n steamId: string,\n appid: number,\n contextid: string,\n tradableOnly: boolean,\n ): Promise<EconItem[]> {\n const url = `${URLS.community}/inventory/${steamId}/${appid}/${contextid}`;\n return paginate<EconItem, string>(async (startAssetId): Promise<Page<EconItem, string>> => {\n const res = await this.http.get<RawInventoryResponse>(url, {\n responseType: \"json\",\n searchParams: {\n l: LANG.l,\n count: INVENTORY_PAGE_SIZE,\n raw_asset_properties: 1,\n preserve_bbcode: 1,\n start_assetid: startAssetId,\n },\n headers: { Referer: `${URLS.community}/profiles/${steamId}/inventory` },\n });\n const body = res.body;\n\n if (res.statusCode === 403 && !body) {\n throw await inventoryFailureError(\n this.http,\n steamId,\n undefined,\n \"This profile is private.\",\n );\n }\n if (res.statusCode === 500 && body?.error) throw parseStrError(body.error);\n if (res.statusCode !== 200) throw httpError(res, RETRY_AFTER.inventory);\n\n if (!body?.success) {\n throw await inventoryFailureError(\n this.http,\n steamId,\n undefined,\n body?.error ?? body?.Error,\n );\n }\n // Empty inventory: Steam returns success with no assets.\n if (!body.assets) return { items: [], next: undefined };\n\n return {\n items: parseInventory(body, contextid, tradableOnly),\n next: body.more_items && body.last_assetid ? body.last_assetid : undefined,\n };\n });\n }\n}\n\n// Read a profile-XML element's text, tolerating optional CDATA wrapping.\nfunction xmlValue(xml: string, tag: string): string | undefined {\n const m = xml.match(new RegExp(`<${tag}>(?:<!\\\\[CDATA\\\\[)?([\\\\s\\\\S]*?)(?:\\\\]\\\\]>)?</${tag}>`));\n return m?.[1]?.trim() || undefined;\n}\n","import { URLS } from \"../core/constants.js\";\nimport { SteamError } from \"../core/errors.js\";\nimport { time as steamTotpTime } from \"../crypto/steamTotp.js\";\nimport { httpError } from \"./checkers.js\";\nimport type { HttpClient } from \"./HttpClient.js\";\n\n// Steam server-time offset via ITwoFactorService/QueryTime — used by mobileconf to sign requests\n// with Steam's clock instead of the local one (Windows hosts drift; the 30s TOTP/conf window is\n// unforgiving). Goes through HttpClient so it inherits the proxy + mobile headers.\nexport async function queryServerTimeOffset(http: HttpClient): Promise<number> {\n const res = await http.post<{ response?: { server_time?: string | number } }>(\n `${URLS.api}/ITwoFactorService/QueryTime/v1/`,\n { responseType: \"json\" },\n );\n if (res.statusCode !== 200) throw httpError(res);\n const serverTime = Number(res.body?.response?.server_time);\n if (!serverTime) throw new SteamError(\"Failed to query Steam server time\");\n return serverTime - steamTotpTime();\n}\n","import type SteamID from \"steamid\";\nimport { URLS } from \"../core/constants.js\";\nimport { EConfirmationType } from \"../core/enums.js\";\nimport { ConfirmationError, SteamSessionExpiredError } from \"../core/errors.js\";\nimport type { MobileProfile } from \"../core/mobileProfile.js\";\nimport * as SteamTotp from \"../crypto/steamTotp.js\";\nimport { httpError } from \"../http/checkers.js\";\nimport type { HttpClient } from \"../http/HttpClient.js\";\nimport { queryServerTimeOffset } from \"../http/queryTime.js\";\n\nexport interface Confirmation {\n id: string;\n type: number;\n creator: string;\n key: string;\n title: string;\n receiving: string;\n sending: string;\n time: string;\n timestamp: Date;\n icon: string;\n}\n\ninterface RawConfirmation {\n id: string | number;\n type: number;\n creator_id: string | number;\n nonce: string;\n type_name?: string;\n headline?: string;\n summary?: string[];\n creation_time: number;\n icon?: string;\n}\n\ninterface RawConfListResponse {\n success?: boolean;\n conf?: RawConfirmation[];\n needauth?: boolean;\n message?: string;\n detail?: string;\n}\n\ninterface RawConfActionResponse {\n success?: boolean;\n message?: string;\n}\n\ntype ConfKey = string | { tag: string; key: string };\n\nconst TIME_OFFSET_TTL_MS = 12 * 60 * 60 * 1000;\n\nexport class ConfirmationManager {\n private timeOffset: number | undefined;\n private timeOffsetAt = 0;\n private readonly usedConfTimes: number[] = [];\n\n constructor(\n private readonly http: HttpClient,\n private readonly steamID: SteamID,\n private readonly identitySecret: string | undefined,\n private readonly profile: MobileProfile,\n ) {}\n\n get hasIdentitySecret(): boolean {\n return Boolean(this.identitySecret);\n }\n\n // The mobileconf `p` device id: iOS sends a bare uppercase UUID, Android the `android:`-prefixed one. Stable id only, not part of the `k` HMAC.\n private deviceId(): string {\n const android = SteamTotp.getDeviceID(this.steamID.getSteamID64());\n return this.profile.mobileClient === \"ios\"\n ? android.replace(/^android:/, \"\").toUpperCase()\n : android;\n }\n\n async getConfirmations(time: number, key: ConfKey): Promise<Confirmation[]> {\n const { tag, k } = splitKey(key, \"conf\");\n const body = await this.getlist(k, time, tag);\n if (!body?.success) {\n if (body?.needauth) throw new SteamSessionExpiredError();\n throw new ConfirmationError(\n String(body?.message ?? body?.detail ?? \"Failed to get confirmation list\"),\n );\n }\n return (body.conf ?? []).map((c) => ({\n id: String(c.id),\n type: Number(c.type),\n creator: String(c.creator_id),\n key: String(c.nonce),\n title: `${c.type_name ?? \"Confirm\"} - ${c.headline ?? \"\"}`,\n receiving: Number(c.type) === EConfirmationType.Trade ? String(c.summary?.[1] ?? \"\") : \"\",\n sending: String(c.summary?.[0] ?? \"\"),\n time: new Date(Number(c.creation_time) * 1000).toISOString(),\n timestamp: new Date(Number(c.creation_time) * 1000),\n icon: String(c.icon ?? \"\"),\n }));\n }\n\n async respondToConfirmation(\n confID: string,\n confKey: string,\n time: number,\n key: ConfKey,\n accept: boolean,\n ): Promise<void> {\n const { tag, k } = splitKey(key, accept ? \"allow\" : \"cancel\");\n const op = accept ? \"allow\" : \"cancel\";\n // multiajaxop: ids go in the multipart body (cid[]/ck[]), op/signature stay in the query string.\n const res = await this.http.post<RawConfActionResponse>(\n `${URLS.community}/mobileconf/multiajaxop`,\n {\n responseType: \"json\",\n searchParams: { ...this.confParams(k, time, tag), op },\n multipart: [\n { name: \"cid[]\", value: confID },\n { name: \"ck[]\", value: confKey },\n ],\n },\n );\n if (res.statusCode !== 200) throw httpError(res);\n if (res.body?.success) return;\n throw new ConfirmationError(String(res.body?.message ?? \"Could not act on confirmation\"));\n }\n\n // All pending confirmations, with the list HMAC derived for you (needs identitySecret).\n async getPending(): Promise<Confirmation[]> {\n const secret = this.requireSecret();\n const offset = await this.getTimeOffset();\n const listTime = SteamTotp.time(offset);\n const listKey = SteamTotp.getConfirmationKey(secret, listTime, \"list\");\n return this.getConfirmations(listTime, { tag: \"list\", key: listKey });\n }\n\n // Accept a single confirmation by id + nonce (its `key`).\n acceptConfirmation(confID: string, nonce: string): Promise<void> {\n return this.actOnConfirmation(confID, nonce, true);\n }\n\n // Reject (cancel) a single confirmation by id + nonce.\n rejectConfirmation(confID: string, nonce: string): Promise<void> {\n return this.actOnConfirmation(confID, nonce, false);\n }\n\n // Accept every pending confirmation; returns the ones acted on. Fails fast on the first error.\n async acceptAll(): Promise<Confirmation[]> {\n const pending = await this.getPending();\n for (const c of pending) await this.acceptConfirmation(c.id, c.key);\n return pending;\n }\n\n async acceptConfirmationForObject(objectID: string): Promise<void> {\n const conf = (await this.getPending()).find((c) => c.creator === String(objectID));\n if (!conf) throw new ConfirmationError(`Could not find confirmation for object ${objectID}`);\n await this.acceptConfirmation(conf.id, conf.key);\n }\n\n private async actOnConfirmation(confID: string, nonce: string, accept: boolean): Promise<void> {\n const secret = this.requireSecret();\n const offset = await this.getTimeOffset();\n const time = this.nextConfTime(offset);\n const tag = accept ? \"accept\" : \"cancel\";\n const key = SteamTotp.getConfirmationKey(secret, time, tag);\n await this.respondToConfirmation(confID, nonce, time, { tag, key }, accept);\n }\n\n private requireSecret(): string {\n if (!this.identitySecret) {\n throw new ConfirmationError(\"identitySecret is required to respond to confirmations\");\n }\n return this.identitySecret;\n }\n\n // A distinct single-use timestamp per HMAC; bump locally past any we've already signed with.\n private nextConfTime(offset: number): number {\n let time = SteamTotp.time(offset);\n let localOffset = 0;\n while (this.usedConfTimes.includes(time)) time = SteamTotp.time(offset) + ++localOffset;\n this.usedConfTimes.push(time);\n if (this.usedConfTimes.length > 60) {\n this.usedConfTimes.splice(0, this.usedConfTimes.length - 60);\n }\n return time;\n }\n\n private async getTimeOffset(): Promise<number> {\n if (this.timeOffset !== undefined && Date.now() - this.timeOffsetAt < TIME_OFFSET_TTL_MS) {\n return this.timeOffset;\n }\n const offset = await queryServerTimeOffset(this.http);\n this.timeOffset = offset;\n this.timeOffsetAt = Date.now();\n return offset;\n }\n\n // Common mobileconf query params; the `k` HMAC authorizes the request.\n private confParams(key: string, time: number, tag: string): Record<string, string | number> {\n return {\n p: this.deviceId(),\n a: this.steamID.getSteamID64(),\n k: key,\n t: time,\n m: \"react\",\n tag,\n };\n }\n\n private async getlist(key: string, time: number, tag: string): Promise<RawConfListResponse> {\n const res = await this.http.get<RawConfListResponse>(`${URLS.community}/mobileconf/getlist`, {\n responseType: \"json\",\n searchParams: this.confParams(key, time, tag),\n });\n if (res.statusCode !== 200) throw httpError(res);\n return res.body;\n }\n}\n\nfunction splitKey(key: ConfKey, fallbackTag: string): { tag: string; k: string } {\n return typeof key === \"object\" ? { tag: key.tag, k: key.key } : { tag: fallbackTag, k: key };\n}\n","import { ETradeOfferState } from \"./enums.js\";\n\n// States where the offer can still change (pruning must not drop these).\nconst NON_TERMINAL: ReadonlySet<ETradeOfferState> = new Set([\n ETradeOfferState.Active,\n ETradeOfferState.CreatedNeedsConfirmation,\n ETradeOfferState.InEscrow,\n]);\n\nexport function isTerminalState(state: ETradeOfferState): boolean {\n return !NON_TERMINAL.has(state);\n}\n","import SteamID from \"steamid\";\nimport { SteamError } from \"./errors.js\";\nimport type { OfferTarget } from \"./types.js\";\n\nexport interface ResolvedTarget {\n steamId: string;\n token: string | undefined;\n}\n\nexport function resolveTarget(target: OfferTarget): ResolvedTarget {\n if (\"tradeUrl\" in target && target.tradeUrl) {\n const params = new URL(target.tradeUrl).searchParams;\n const partner = params.get(\"partner\");\n if (!partner) throw new SteamError(\"invalid trade URL: missing partner\");\n const accountId = Number(partner);\n if (!Number.isInteger(accountId) || accountId <= 0) {\n throw new SteamError(`invalid trade URL: non-numeric partner '${partner}'`);\n }\n return {\n steamId: SteamID.fromIndividualAccountID(accountId).getSteamID64(),\n token: params.get(\"token\") ?? undefined,\n };\n }\n if (\"steamId\" in target && target.steamId) {\n return { steamId: target.steamId, token: target.token };\n }\n throw new SteamError(\"invalid target: provide tradeUrl or steamId\");\n}\n","import { URLS } from \"../core/constants.js\";\nimport { EResult } from \"../core/enums.js\";\nimport { RateLimitError, SteamError, SteamSessionExpiredError } from \"../core/errors.js\";\nimport { httpError } from \"./checkers.js\";\nimport type { HttpClient } from \"./HttpClient.js\";\n\ntype Scalar = string | number | boolean;\n\nexport interface ApiCallParams {\n httpMethod: \"GET\" | \"POST\";\n iface: string;\n method: string;\n version?: number;\n input?: Record<string, Scalar | undefined>;\n retryAfterMs?: number | null;\n}\n\ntype ApiBody = { response?: Record<string, unknown> } & Record<string, unknown>;\n\nexport class WebApiClient {\n constructor(\n private readonly http: HttpClient,\n private readonly getAccessToken: () => Promise<string>,\n ) {}\n\n async call<T = ApiBody>(params: ApiCallParams): Promise<T> {\n const { httpMethod, iface, method, version = 1, input = {}, retryAfterMs = null } = params;\n const accessToken = await this.getAccessToken();\n const url = `${URLS.api}/${iface}/${method}/v${version}/`;\n // origin=SteamMobile keeps us identified as the mobile app on every WebAPI call (matches\n // protoTransport's behavior on IAuthenticationService reads).\n const payload = { origin: \"SteamMobile\", ...input, access_token: accessToken };\n\n if (process.env.DEBUG_HTTP === \"1\") {\n const qs = new URLSearchParams(\n Object.entries(payload)\n .filter(([, v]) => v !== undefined)\n .map(([k, v]): [string, string] => [k, String(v)]),\n );\n console.log(`[http] ${httpMethod} ${url}?${qs.toString()}`);\n }\n\n const res = await this.http.request<ApiBody>(httpMethod, url, {\n responseType: \"json\",\n ...(httpMethod === \"GET\" ? { searchParams: payload } : { form: payload }),\n });\n\n if (res.statusCode !== 200) {\n throw httpError(res, retryAfterMs);\n }\n\n const header = res.headers[\"x-eresult\"];\n let eresult = Array.isArray(header) ? header[0] : header;\n const errorMessage = headerValue(res.headers[\"x-error_message\"]);\n const body = res.body;\n\n const responseObj =\n body && typeof body === \"object\"\n ? (body.response as Record<string, unknown> | undefined)\n : undefined;\n if (\n eresult === \"2\" &&\n body &&\n (Object.keys(body).length > 1 || (responseObj && Object.keys(responseObj).length > 0))\n ) {\n eresult = \"1\";\n }\n\n if (eresult !== undefined && eresult !== \"1\") {\n const code = Number(eresult);\n const name = EResult[code] ?? \"EResult\";\n const msg = `${name} (${eresult})${errorMessage ? `: ${errorMessage}` : \"\"}`;\n if (code === EResult.NotLoggedOn) throw new SteamSessionExpiredError(msg);\n if (code === EResult.RateLimitExceeded) {\n throw new RateLimitError({\n message: msg,\n body,\n eresult: 84,\n ...(typeof retryAfterMs === \"number\" ? { retryAfterMs } : {}),\n });\n }\n throw new SteamError(msg, { eresult: code, body });\n }\n\n if (!body || typeof body !== \"object\") {\n throw new SteamError(\"Invalid API response\", { body });\n }\n\n return body as T;\n }\n}\n\nfunction headerValue(v: string | string[] | undefined): string | undefined {\n return Array.isArray(v) ? v[0] : v;\n}\n","import { URLS } from \"../core/constants.js\";\nimport { SteamError } from \"../core/errors.js\";\nimport { resolveMobileProfile } from \"../core/mobileProfile.js\";\nimport { httpError } from \"../http/checkers.js\";\nimport { HttpClient } from \"../http/HttpClient.js\";\n\n// Steam's documented caps on these endpoints.\nconst GET_PLAYER_BANS_BATCH = 100;\nconst GET_PLAYER_SUMMARIES_BATCH = 100;\n\nexport interface SteamWebApiOptions {\n apiKey: string;\n proxy?: string;\n http?: HttpClient;\n}\n\n// ISteamUser/GetPlayerBans/v1.\nexport interface PlayerBans {\n SteamId: string;\n CommunityBanned: boolean;\n VACBanned: boolean;\n NumberOfVACBans: number;\n DaysSinceLastBan: number;\n NumberOfGameBans: number;\n EconomyBan: string;\n [key: string]: unknown;\n}\n\n// ISteamUser/GetPlayerSummaries/v2.\nexport interface PlayerSummary {\n steamid: string;\n personaname: string;\n profileurl: string;\n avatar: string;\n avatarmedium: string;\n avatarfull: string;\n avatarhash: string;\n personastate: number;\n communityvisibilitystate: number;\n profilestate?: number;\n lastlogoff?: number;\n commentpermission?: number;\n realname?: string;\n primaryclanid?: string;\n timecreated?: number;\n personastateflags?: number;\n gameid?: string;\n gameserverip?: string;\n gameextrainfo?: string;\n loccountrycode?: string;\n locstatecode?: string;\n loccityid?: number;\n [key: string]: unknown;\n}\n\n// IPlayerService/GetBadges/v1.\nexport interface Badge {\n badgeid: number;\n level: number;\n completion_time: number;\n xp: number;\n scarcity: number;\n appid?: number;\n communityitemid?: string;\n border_color?: number;\n [key: string]: unknown;\n}\n\nexport interface PlayerBadges {\n badges: Badge[];\n player_xp: number;\n player_level: number;\n player_xp_needed_to_level_up: number;\n player_xp_needed_current_level: number;\n [key: string]: unknown;\n}\n\n// Standalone Web-API client authenticated by developer key (no SteamMobile, no login, no session).\nexport class SteamWebApi {\n private readonly http: HttpClient;\n private readonly apiKey: string;\n\n constructor(options: SteamWebApiOptions) {\n this.apiKey = options.apiKey;\n this.http =\n options.http ??\n new HttpClient({\n ...(options.proxy ? { proxy: options.proxy } : {}),\n profile: resolveMobileProfile(),\n });\n }\n\n // Auto-batches into 100-id requests; preserves caller order across batches.\n async getPlayerBans(steamIds: readonly string[]): Promise<PlayerBans[]> {\n if (steamIds.length === 0) return [];\n const out: PlayerBans[] = [];\n for (let i = 0; i < steamIds.length; i += GET_PLAYER_BANS_BATCH) {\n const chunk = steamIds.slice(i, i + GET_PLAYER_BANS_BATCH);\n const res = await this.http.get<{ players?: PlayerBans[] }>(\n `${URLS.api}/ISteamUser/GetPlayerBans/v1/`,\n {\n responseType: \"json\",\n searchParams: { key: this.apiKey, steamids: chunk.join(\",\") },\n },\n );\n if (res.statusCode !== 200) throw httpError(res);\n const players = res.body?.players;\n if (!Array.isArray(players)) {\n throw new SteamError(\"Invalid GetPlayerBans response\", { body: res.body });\n }\n out.push(...players);\n }\n return out;\n }\n\n // Auto-batches into 100-id requests; preserves caller order across batches.\n async getPlayerSummaries(steamIds: readonly string[]): Promise<PlayerSummary[]> {\n if (steamIds.length === 0) return [];\n const out: PlayerSummary[] = [];\n for (let i = 0; i < steamIds.length; i += GET_PLAYER_SUMMARIES_BATCH) {\n const chunk = steamIds.slice(i, i + GET_PLAYER_SUMMARIES_BATCH);\n const res = await this.http.get<{ response?: { players?: PlayerSummary[] } }>(\n `${URLS.api}/ISteamUser/GetPlayerSummaries/v2/`,\n {\n responseType: \"json\",\n searchParams: { key: this.apiKey, steamids: chunk.join(\",\") },\n },\n );\n if (res.statusCode !== 200) throw httpError(res);\n const players = res.body?.response?.players;\n if (!Array.isArray(players)) {\n throw new SteamError(\"Invalid GetPlayerSummaries response\", { body: res.body });\n }\n out.push(...players);\n }\n return out;\n }\n\n async getBadges(steamId: string): Promise<PlayerBadges> {\n const res = await this.http.get<{ response?: PlayerBadges }>(\n `${URLS.api}/IPlayerService/GetBadges/v1/`,\n {\n responseType: \"json\",\n searchParams: { key: this.apiKey, steamid: steamId },\n },\n );\n if (res.statusCode !== 200) throw httpError(res);\n const response = res.body?.response;\n if (!response || !Array.isArray(response.badges)) {\n throw new SteamError(\"Invalid GetBadges response\", { body: res.body });\n }\n return response;\n }\n}\n","// @generated by protoc-gen-es v2.12.1 with parameter \"target=ts,import_extension=js\"\n// @generated from file csgo_econ_preview.proto (syntax proto3)\n/* eslint-disable */\n\nimport type { GenFile, GenMessage } from \"@bufbuild/protobuf/codegenv2\";\nimport { fileDesc, messageDesc } from \"@bufbuild/protobuf/codegenv2\";\nimport type { Message } from \"@bufbuild/protobuf\";\n\n/**\n * Describes the file csgo_econ_preview.proto.\n */\nexport const file_csgo_econ_preview: GenFile = /*@__PURE__*/\n fileDesc(\"Chdjc2dvX2Vjb25fcHJldmlldy5wcm90byK0CQoZQ0Vjb25JdGVtUHJldmlld0RhdGFCbG9jaxIWCglhY2NvdW50aWQYASABKA1IAIgBARITCgZpdGVtaWQYAiABKARIAYgBARIVCghkZWZpbmRleBgDIAEoDUgCiAEBEhcKCnBhaW50aW5kZXgYBCABKA1IA4gBARITCgZyYXJpdHkYBSABKA1IBIgBARIUCgdxdWFsaXR5GAYgASgNSAWIAQESFgoJcGFpbnR3ZWFyGAcgASgNSAaIAQESFgoJcGFpbnRzZWVkGAggASgNSAeIAQESHwoSa2lsbGVhdGVyc2NvcmV0eXBlGAkgASgNSAiIAQESGwoOa2lsbGVhdGVydmFsdWUYCiABKA1ICYgBARIXCgpjdXN0b21uYW1lGAsgASgJSAqIAQESNAoIc3RpY2tlcnMYDCADKAsyIi5DRWNvbkl0ZW1QcmV2aWV3RGF0YUJsb2NrLlN0aWNrZXISFgoJaW52ZW50b3J5GA0gASgNSAuIAQESEwoGb3JpZ2luGA4gASgNSAyIAQESFAoHcXVlc3RpZBgPIAEoDUgNiAEBEhcKCmRyb3ByZWFzb24YECABKA1IDogBARIXCgptdXNpY2luZGV4GBEgASgNSA+IAQESFQoIZW50aW5kZXgYEiABKAVIEIgBARIVCghwZXRpbmRleBgTIAEoDUgRiAEBEjUKCWtleWNoYWlucxgUIAMoCzIiLkNFY29uSXRlbVByZXZpZXdEYXRhQmxvY2suU3RpY2tlchISCgVzdHlsZRgVIAEoDUgSiAEBGtsCCgdTdGlja2VyEhEKBHNsb3QYASABKA1IAIgBARIXCgpzdGlja2VyX2lkGAIgASgNSAGIAQESEQoEd2VhchgDIAEoAkgCiAEBEhIKBXNjYWxlGAQgASgCSAOIAQESFQoIcm90YXRpb24YBSABKAJIBIgBARIUCgd0aW50X2lkGAYgASgNSAWIAQESFQoIb2Zmc2V0X3gYByABKAJIBogBARIVCghvZmZzZXRfeRgIIAEoAkgHiAEBEhUKCG9mZnNldF96GAkgASgCSAiIAQESFAoHcGF0dGVybhgKIAEoDUgJiAEBQgcKBV9zbG90Qg0KC19zdGlja2VyX2lkQgcKBV93ZWFyQggKBl9zY2FsZUILCglfcm90YXRpb25CCgoIX3RpbnRfaWRCCwoJX29mZnNldF94QgsKCV9vZmZzZXRfeUILCglfb2Zmc2V0X3pCCgoIX3BhdHRlcm5CDAoKX2FjY291bnRpZEIJCgdfaXRlbWlkQgsKCV9kZWZpbmRleEINCgtfcGFpbnRpbmRleEIJCgdfcmFyaXR5QgoKCF9xdWFsaXR5QgwKCl9wYWludHdlYXJCDAoKX3BhaW50c2VlZEIVChNfa2lsbGVhdGVyc2NvcmV0eXBlQhEKD19raWxsZWF0ZXJ2YWx1ZUINCgtfY3VzdG9tbmFtZUIMCgpfaW52ZW50b3J5QgkKB19vcmlnaW5CCgoIX3F1ZXN0aWRCDQoLX2Ryb3ByZWFzb25CDQoLX211c2ljaW5kZXhCCwoJX2VudGluZGV4QgsKCV9wZXRpbmRleEIICgZfc3R5bGViBnByb3RvMw\");\n\n/**\n * @generated from message CEconItemPreviewDataBlock\n */\nexport type CEconItemPreviewDataBlock = Message<\"CEconItemPreviewDataBlock\"> & {\n /**\n * @generated from field: optional uint32 accountid = 1;\n */\n accountid?: number | undefined;\n\n /**\n * @generated from field: optional uint64 itemid = 2;\n */\n itemid?: bigint | undefined;\n\n /**\n * @generated from field: optional uint32 defindex = 3;\n */\n defindex?: number | undefined;\n\n /**\n * @generated from field: optional uint32 paintindex = 4;\n */\n paintindex?: number | undefined;\n\n /**\n * @generated from field: optional uint32 rarity = 5;\n */\n rarity?: number | undefined;\n\n /**\n * @generated from field: optional uint32 quality = 6;\n */\n quality?: number | undefined;\n\n /**\n * @generated from field: optional uint32 paintwear = 7;\n */\n paintwear?: number | undefined;\n\n /**\n * @generated from field: optional uint32 paintseed = 8;\n */\n paintseed?: number | undefined;\n\n /**\n * @generated from field: optional uint32 killeaterscoretype = 9;\n */\n killeaterscoretype?: number | undefined;\n\n /**\n * @generated from field: optional uint32 killeatervalue = 10;\n */\n killeatervalue?: number | undefined;\n\n /**\n * @generated from field: optional string customname = 11;\n */\n customname?: string | undefined;\n\n /**\n * @generated from field: repeated CEconItemPreviewDataBlock.Sticker stickers = 12;\n */\n stickers: CEconItemPreviewDataBlock_Sticker[];\n\n /**\n * @generated from field: optional uint32 inventory = 13;\n */\n inventory?: number | undefined;\n\n /**\n * @generated from field: optional uint32 origin = 14;\n */\n origin?: number | undefined;\n\n /**\n * @generated from field: optional uint32 questid = 15;\n */\n questid?: number | undefined;\n\n /**\n * @generated from field: optional uint32 dropreason = 16;\n */\n dropreason?: number | undefined;\n\n /**\n * @generated from field: optional uint32 musicindex = 17;\n */\n musicindex?: number | undefined;\n\n /**\n * @generated from field: optional int32 entindex = 18;\n */\n entindex?: number | undefined;\n\n /**\n * @generated from field: optional uint32 petindex = 19;\n */\n petindex?: number | undefined;\n\n /**\n * @generated from field: repeated CEconItemPreviewDataBlock.Sticker keychains = 20;\n */\n keychains: CEconItemPreviewDataBlock_Sticker[];\n\n /**\n * @generated from field: optional uint32 style = 21;\n */\n style?: number | undefined;\n};\n\n/**\n * Describes the message CEconItemPreviewDataBlock.\n * Use `create(CEconItemPreviewDataBlockSchema)` to create a new message.\n */\nexport const CEconItemPreviewDataBlockSchema: GenMessage<CEconItemPreviewDataBlock> = /*@__PURE__*/\n messageDesc(file_csgo_econ_preview, 0);\n\n/**\n * @generated from message CEconItemPreviewDataBlock.Sticker\n */\nexport type CEconItemPreviewDataBlock_Sticker = Message<\"CEconItemPreviewDataBlock.Sticker\"> & {\n /**\n * @generated from field: optional uint32 slot = 1;\n */\n slot?: number | undefined;\n\n /**\n * @generated from field: optional uint32 sticker_id = 2;\n */\n stickerId?: number | undefined;\n\n /**\n * @generated from field: optional float wear = 3;\n */\n wear?: number | undefined;\n\n /**\n * @generated from field: optional float scale = 4;\n */\n scale?: number | undefined;\n\n /**\n * @generated from field: optional float rotation = 5;\n */\n rotation?: number | undefined;\n\n /**\n * @generated from field: optional uint32 tint_id = 6;\n */\n tintId?: number | undefined;\n\n /**\n * @generated from field: optional float offset_x = 7;\n */\n offsetX?: number | undefined;\n\n /**\n * @generated from field: optional float offset_y = 8;\n */\n offsetY?: number | undefined;\n\n /**\n * @generated from field: optional float offset_z = 9;\n */\n offsetZ?: number | undefined;\n\n /**\n * @generated from field: optional uint32 pattern = 10;\n */\n pattern?: number | undefined;\n};\n\n/**\n * Describes the message CEconItemPreviewDataBlock.Sticker.\n * Use `create(CEconItemPreviewDataBlock_StickerSchema)` to create a new message.\n */\nexport const CEconItemPreviewDataBlock_StickerSchema: GenMessage<CEconItemPreviewDataBlock_Sticker> = /*@__PURE__*/\n messageDesc(file_csgo_econ_preview, 0, 0);\n\n","import { Buffer } from \"node:buffer\";\nimport { fromBinary, toJson } from \"@bufbuild/protobuf\";\nimport { CEconItemPreviewDataBlockSchema } from \"../protobufs/csgo_econ_preview_pb.js\";\n\nconst HEX_RE = /^[0-9a-fA-F]+$/;\nconst wearView = new DataView(new ArrayBuffer(4));\n\n/**\n * Decode a CS2 masked preview token — the asset_properties propertyid-6\n * \"certificate\" hex — into a plain JSON object (uint64 ids as strings, camelCase\n * fields, only set fields present). Layout is `[xorKey][protobuf][crc32]`: every\n * byte after the key is XOR'd with it and the trailing 4-byte crc32 dropped.\n * `paintwear` is returned as the float wear (0..1), not its raw uint32 bits.\n * Returns `null` for non-hex input.\n */\nexport function decodePreviewToken(hex: string | null | undefined): Record<string, unknown> | null {\n if (!hex || hex.length % 2 !== 0 || hex.length < 12 || !HEX_RE.test(hex)) return null;\n try {\n const bytes = Buffer.from(hex, \"hex\");\n const xorKey = bytes[0] as number;\n for (let i = 1; i < bytes.length; i++) bytes[i] = (bytes[i] as number) ^ xorKey;\n const message = fromBinary(\n CEconItemPreviewDataBlockSchema,\n bytes.subarray(1, bytes.length - 4),\n );\n const json = toJson(CEconItemPreviewDataBlockSchema, message) as Record<string, unknown>;\n if (typeof json.paintwear === \"number\") {\n wearView.setUint32(0, json.paintwear >>> 0, true);\n json.paintwear = wearView.getFloat32(0, true);\n }\n return json;\n } catch {\n return null;\n }\n}\n","import { Buffer } from \"node:buffer\";\nimport { create, fromBinary, toBinary } from \"@bufbuild/protobuf\";\nimport {\n CAuthentication_AccessToken_GenerateForApp_RequestSchema as RequestSchema,\n CAuthentication_AccessToken_GenerateForApp_ResponseSchema as ResponseSchema,\n} from \"../protobufs/steammessages_auth_pb.js\";\nimport type { ProtoPost } from \"./protoTransport.js\";\n\nexport type { ProtoPost } from \"./protoTransport.js\";\n\nexport const GENERATE_TOKEN_URL =\n \"https://api.steampowered.com/IAuthenticationService/GenerateAccessTokenForApp/v1\";\n\nexport interface JwtPayload {\n iss?: string;\n sub?: string;\n aud?: string[];\n exp?: number;\n iat?: number;\n [k: string]: unknown;\n}\n\nexport interface MintResult {\n accessToken: string;\n refreshToken?: string;\n}\n\nexport class AccessTokenError extends Error {\n constructor(\n message: string,\n readonly eresult?: number,\n ) {\n super(message);\n this.name = \"AccessTokenError\";\n }\n}\n\nexport function decodeJwt(token: string): JwtPayload | null {\n try {\n const payload = token.split(\".\")[1];\n if (!payload) return null;\n const json = Buffer.from(payload.replace(/-/g, \"+\").replace(/_/g, \"/\"), \"base64\").toString(\n \"utf8\",\n );\n return JSON.parse(json) as JwtPayload;\n } catch {\n return null;\n }\n}\n\nexport function secondsUntilExpiry(token: string): number {\n const exp = decodeJwt(token)?.exp;\n return typeof exp === \"number\" ? exp - Math.floor(Date.now() / 1000) : Number.NaN;\n}\n\n// GenerateAccessTokenForApp_Request: refresh_token=1 string, steamid=2 fixed64, renewal_type=3.\n// renewal_type is set explicitly (even to 0) so it's always on the wire, as the iOS app sends it.\nexport function encodeGenerateForAppRequest(refreshToken: string, renew = false): Buffer {\n const sub = decodeJwt(refreshToken)?.sub;\n if (!sub) throw new AccessTokenError(\"invalid refresh token: no steamid (sub) in payload\");\n let steamId: bigint;\n try {\n steamId = BigInt(sub);\n } catch {\n throw new AccessTokenError(`invalid refresh token: non-numeric steamid '${sub}'`);\n }\n const msg = create(RequestSchema, {\n refreshToken,\n steamid: steamId,\n renewalType: renew ? 1 : 0,\n });\n return Buffer.from(toBinary(RequestSchema, msg));\n}\n\n// GenerateAccessTokenForApp_Response: access_token=1 string, refresh_token=2 string.\nexport function decodeGenerateForAppResponse(input: Buffer | Uint8Array): MintResult {\n let accessToken: string;\n let refreshToken: string;\n try {\n const msg = fromBinary(ResponseSchema, toUint8(input));\n accessToken = msg.accessToken;\n refreshToken = msg.refreshToken;\n } catch {\n throw new AccessTokenError(\"malformed GenerateAccessTokenForApp response\");\n }\n if (!accessToken) throw new AccessTokenError(\"response had no access_token field\");\n return refreshToken ? { accessToken, refreshToken } : { accessToken };\n}\n\nfunction toUint8(input: Buffer | Uint8Array): Uint8Array {\n return input instanceof Uint8Array && !Buffer.isBuffer(input) ? input : new Uint8Array(input);\n}\n\nconst ERESULT_OK = \"1\";\n\nexport async function mintAccessToken(\n refreshToken: string,\n renew: boolean,\n post: ProtoPost,\n): Promise<MintResult> {\n const req = encodeGenerateForAppRequest(refreshToken, renew);\n const { status, eresult, errorMessage, body } = await post(\n GENERATE_TOKEN_URL,\n req.toString(\"base64\"),\n );\n\n if (status < 200 || status >= 300) {\n throw new AccessTokenError(\n `GenerateAccessTokenForApp HTTP ${status} (eresult=${eresult ?? \"?\"}${errorMessage ? `, ${errorMessage}` : \"\"})`,\n eresult ? Number(eresult) : undefined,\n );\n }\n if (eresult && eresult !== ERESULT_OK) {\n throw new AccessTokenError(\n `GenerateAccessTokenForApp failed: eresult=${eresult}${errorMessage ? ` (${errorMessage})` : \"\"}`,\n Number(eresult),\n );\n }\n if (!body.length) {\n throw new AccessTokenError(\n `GenerateAccessTokenForApp empty response (eresult=${eresult ?? \"?\"})`,\n );\n }\n return decodeGenerateForAppResponse(body);\n}\n","import { EventEmitter } from \"node:events\";\nimport SteamID from \"steamid\";\nimport { AuthClient } from \"../auth/AuthClient.js\";\nimport {\n ACCESS_TOKEN_RENEW_THRESHOLD_SECONDS,\n REFRESH_TOKEN_RENEW_THRESHOLD_SECONDS,\n} from \"../core/constants.js\";\nimport { EAuthTokenRevokeAction } from \"../core/enums.js\";\nimport { isTerminalAuthEResult } from \"../core/eresults.js\";\nimport { SteamError, SteamSessionExpiredError } from \"../core/errors.js\";\nimport type { HttpClient } from \"../http/HttpClient.js\";\nimport { createProtoPost, type ProtoPost } from \"./protoTransport.js\";\nimport {\n AccessTokenError,\n decodeJwt,\n type MintResult,\n mintAccessToken,\n secondsUntilExpiry,\n} from \"./tokens.js\";\n\nexport interface SessionManagerEvents {\n refreshToken: [token: string];\n sessionExpired: [error: Error];\n debug: [message: string];\n}\n\nexport class SessionManager extends EventEmitter<SessionManagerEvents> {\n refreshToken: string;\n accessToken: string | undefined;\n readonly steamID: SteamID;\n private readonly http: HttpClient;\n private readonly protoPost: ProtoPost;\n private minting: Promise<string> | undefined;\n private revoked = false;\n\n constructor(http: HttpClient, refreshToken: string) {\n super();\n const sub = decodeJwt(refreshToken)?.sub;\n if (!sub)\n throw new SteamSessionExpiredError(\"invalid refresh token: no steamid (sub) in payload\");\n this.http = http;\n this.protoPost = createProtoPost(http);\n this.refreshToken = refreshToken;\n this.steamID = new SteamID(sub);\n }\n\n async getAccessToken(): Promise<string> {\n if (this.revoked) throw new SteamSessionExpiredError(\"session has been revoked (logged out)\");\n if (\n this.accessToken &&\n secondsUntilExpiry(this.accessToken) > ACCESS_TOKEN_RENEW_THRESHOLD_SECONDS\n ) {\n return this.accessToken;\n }\n if (!this.minting) {\n this.minting = this.mint().finally(() => {\n this.minting = undefined;\n });\n }\n return this.minting;\n }\n\n // Client ids of in-progress auth sessions (login-approval flows), not a device list.\n async listSessions(): Promise<bigint[]> {\n const accessToken = await this.getAccessToken();\n const res = await new AuthClient(this.http).getAuthSessionsForAccount(accessToken);\n return res.clientIds;\n }\n\n // Revoke this refresh token; the session is dead afterward and further calls throw.\n async logout(action: EAuthTokenRevokeAction = EAuthTokenRevokeAction.Logout): Promise<void> {\n const accessToken = await this.getAccessToken();\n await new AuthClient(this.http).revokeRefreshToken(accessToken, action);\n this.revoked = true;\n this.accessToken = undefined;\n this.emit(\"debug\", \"refresh token revoked (logout)\");\n }\n\n async setRefreshToken(refreshToken: string): Promise<void> {\n const sub = decodeJwt(refreshToken)?.sub;\n if (!sub) {\n throw new SteamSessionExpiredError(\"invalid refresh token: no steamid (sub) in payload\");\n }\n if (sub !== this.steamID.getSteamID64()) {\n throw new SteamError(\n `refresh token is for a different account (${sub} != ${this.steamID.getSteamID64()})`,\n );\n }\n this.refreshToken = refreshToken;\n this.revoked = false;\n this.accessToken = undefined;\n this.emit(\"refreshToken\", refreshToken);\n await this.getAccessToken();\n }\n\n private async mint(): Promise<string> {\n const refreshExpiresIn = secondsUntilExpiry(this.refreshToken);\n if (refreshExpiresIn <= 0) {\n throw this.expire(\"refresh token has expired — re-authentication required\");\n }\n\n const renew = refreshExpiresIn < REFRESH_TOKEN_RENEW_THRESHOLD_SECONDS;\n let result: MintResult;\n try {\n result = await mintAccessToken(this.refreshToken, renew, this.protoPost);\n } catch (err) {\n if (err instanceof AccessTokenError && isTerminalAuthFailure(err)) {\n throw this.expire(`refresh token rejected by Steam: ${err.message}`);\n }\n throw err;\n }\n\n this.accessToken = result.accessToken;\n if (result.refreshToken && result.refreshToken !== this.refreshToken) {\n this.refreshToken = result.refreshToken;\n this.emit(\"refreshToken\", result.refreshToken);\n }\n await this.applyLoginCookie();\n this.emit(\n \"debug\",\n `minted access token${renew ? \" + renewed refresh token\" : \"\"}, expires in ` +\n `${Math.round(secondsUntilExpiry(result.accessToken))}s`,\n );\n return result.accessToken;\n }\n\n // Emit sessionExpired so a global handler can trigger re-auth.\n private expire(message: string): SteamSessionExpiredError {\n const err = new SteamSessionExpiredError(message);\n this.emit(\"sessionExpired\", err);\n return err;\n }\n\n private async applyLoginCookie(): Promise<void> {\n const value = encodeURIComponent(`${this.steamID.getSteamID64()}||${this.accessToken}`);\n await this.http.setCookie(`steamLoginSecure=${value}`);\n }\n}\n\nfunction isTerminalAuthFailure(err: AccessTokenError): boolean {\n return isTerminalAuthEResult(err.eresult);\n}\n","import { URLS } from \"../core/constants.js\";\nimport { SteamError } from \"../core/errors.js\";\nimport { checkCommunityError, httpError } from \"../http/checkers.js\";\nimport type { HttpClient } from \"../http/HttpClient.js\";\n\nexport interface UserSideDetails {\n personaName: string;\n contexts: Record<string, unknown> | null;\n escrowDays: number;\n avatarIcon: string | undefined;\n avatarMedium: string | undefined;\n avatarFull: string | undefined;\n}\n\nexport interface UserPartnerDetails extends UserSideDetails {\n probation: boolean;\n}\n\nexport interface UserDetails {\n me: UserSideDetails;\n them: UserPartnerDetails;\n}\n\n// Fetch + parse the trade page for both sides of a trade. URL is either /tradeoffer/new/?partner=…\n// (unsent offer) or /tradeoffer/<id>/ (existing offer); both pages share the same JS vars + avatar\n// markup so the parser doesn't care which.\nexport async function fetchUserDetails(\n http: HttpClient,\n url: string,\n referer: string,\n myAccountId: number,\n partnerAccountId: number,\n): Promise<UserDetails> {\n const res = await http.get<string>(url, { responseType: \"text\", headers: { Referer: referer } });\n if (res.statusCode !== 200) throw httpError(res);\n const html = res.body;\n checkCommunityError(html);\n if (!html.includes(\"g_rgAppContextData\")) {\n throw new SteamError(\"Failed to load the trade page for this user\");\n }\n return parseUserDetails(html, myAccountId, partnerAccountId);\n}\n\nexport function buildPartnerTradePageUrl(partnerAccountId: number, token?: string): string {\n return `${URLS.community}/tradeoffer/new/?partner=${partnerAccountId}${token ? `&token=${token}` : \"\"}`;\n}\n\nexport function parseUserDetails(\n html: string,\n myAccountId: number,\n partnerAccountId: number,\n): UserDetails {\n const myEscrowDays = matchInt(html, /var g_daysMyEscrow = (\\d+);/);\n const theirEscrowDays = matchInt(html, /var g_daysTheirEscrow = (\\d+);/);\n // Fail loud rather than report a misleading 0 — callers trust 0 to mean \"no hold\".\n if (myEscrowDays === null || theirEscrowDays === null) {\n throw new SteamError(\"Failed to parse escrow durations from the trade page\");\n }\n\n return {\n me: {\n personaName: matchJsString(html, \"g_strYourPersonaName\") ?? \"\",\n contexts: matchJson(html, /g_rgAppContextData\\s*=\\s*(\\{.*?\\});/),\n escrowDays: myEscrowDays,\n ...matchAvatars(html, myAccountId),\n },\n them: {\n personaName: matchJsString(html, \"g_strTradePartnerPersonaName\") ?? \"\",\n contexts: matchJson(html, /g_rgPartnerAppContextData\\s*=\\s*(\\{.*?\\});/),\n escrowDays: theirEscrowDays,\n probation: /g_bTradePartnerProbation\\s*=\\s*(?:true|1)\\b/.test(html),\n ...matchAvatars(html, partnerAccountId),\n },\n };\n}\n\nfunction matchInt(html: string, re: RegExp): number | null {\n const m = html.match(re);\n return m?.[1] !== undefined ? Number.parseInt(m[1], 10) : null;\n}\n\nfunction matchJson(html: string, re: RegExp): Record<string, unknown> | null {\n const m = html.match(re);\n if (!m?.[1]) return null;\n try {\n return JSON.parse(m[1]) as Record<string, unknown>;\n } catch {\n return null;\n }\n}\n\n// Decode a `var X = \"...\";` JS string literal. JS escapes that aren't valid JSON (\\x, octal) are rare\n// in Steam's persona names, so JSON.parse covers the common cases (\\n, \\t, \\\", \\\\, \\uXXXX).\nfunction matchJsString(html: string, varName: string): string | undefined {\n const re = new RegExp(`var ${varName}\\\\s*=\\\\s*(\"(?:\\\\\\\\.|[^\"\\\\\\\\])*\");`);\n const m = html.match(re);\n if (!m?.[1]) return undefined;\n try {\n return JSON.parse(m[1]) as string;\n } catch {\n return m[1].slice(1, -1);\n }\n}\n\ninterface AvatarUrls {\n avatarIcon: string | undefined;\n avatarMedium: string | undefined;\n avatarFull: string | undefined;\n}\n\n// `<img src=\"...\" [alt=\"...\"] data-miniprofile=\"<accountid>\">`. Steam serves <icon>.jpg; size variants\n// are <icon>_medium.jpg / <icon>_full.jpg (mirrors steamcommunity's getUserDetails).\nfunction matchAvatars(html: string, accountId: number): AvatarUrls {\n const re = new RegExp(`<img src=\"([^\"]+)\"(?: alt=\"[^\"]*\")? data-miniprofile=\"${accountId}\">`);\n const m = html.match(re);\n if (!m?.[1]) return { avatarIcon: undefined, avatarMedium: undefined, avatarFull: undefined };\n const icon = m[1];\n return {\n avatarIcon: icon,\n avatarMedium: icon.replace(/\\.jpg$/, \"_medium.jpg\"),\n avatarFull: icon.replace(/\\.jpg$/, \"_full.jpg\"),\n };\n}\n","import { LANG } from \"../core/constants.js\";\nimport type { ETradeStatus } from \"../core/enums.js\";\nimport { SteamError } from \"../core/errors.js\";\nimport { RETRY_AFTER } from \"../core/rateLimits.js\";\nimport type { RawExchangeAsset, RawTradeStatus } from \"../core/types.js\";\nimport type { WebApiClient } from \"../http/webApi.js\";\nimport {\n buildDescriptionMap,\n buildItem,\n type EconItem,\n type RawDescription,\n} from \"../models/EconItem.js\";\n\n// EconItem + where it landed after settlement. new_assetid/new_contextid: Rust populates, CS2 omits.\nexport interface ExchangeItem extends EconItem {\n new_assetid?: string;\n new_contextid?: string;\n rollback_new_assetid?: string;\n rollback_new_contextid?: string;\n}\n\nexport interface ExchangeDetails {\n status: ETradeStatus;\n tradeInitTime: Date;\n settlementTime: Date | null;\n receivedItems: ExchangeItem[];\n sentItems: ExchangeItem[];\n usedInventoryFallback: boolean; // always false; inventory-diff reconcile is the server's job\n}\n\nexport interface TradeHistoryEntry extends ExchangeDetails {\n tradeId: string;\n partnerSteamId: string | undefined;\n}\n\nexport interface TradeHistory {\n trades: TradeHistoryEntry[];\n more: boolean;\n totalTrades: number | undefined;\n}\n\nexport interface TradeHistoryOptions {\n maxTrades?: number;\n startAfterTime?: number;\n startAfterTradeId?: string;\n navigatingBack?: boolean;\n includeFailed?: boolean;\n includeTotal?: boolean;\n}\n\nexport interface TradeOffersSummary {\n pending_received_count: number;\n new_received_count: number;\n updated_received_count: number;\n historical_received_count: number;\n pending_sent_count: number;\n newly_accepted_sent_count: number;\n updated_sent_count: number;\n historical_sent_count: number;\n escrow_received_count: number;\n escrow_sent_count: number;\n}\n\nfunction parseTrade(\n trade: RawTradeStatus,\n descriptions: Map<string, RawDescription>,\n): ExchangeDetails {\n const toItem = (a: RawExchangeAsset): ExchangeItem =>\n buildItem(\n a,\n descriptions.get(`${a.appid}_${a.classid}_${a.instanceid ?? \"0\"}`),\n [],\n a.contextid,\n ) as ExchangeItem;\n return {\n status: trade.status,\n tradeInitTime: new Date(trade.time_init * 1000),\n settlementTime: trade.time_settlement ? new Date(trade.time_settlement * 1000) : null,\n receivedItems: (trade.assets_received ?? []).map(toItem),\n sentItems: (trade.assets_given ?? []).map(toItem),\n usedInventoryFallback: false,\n };\n}\n\n// Needs the tradeID (set on offer accept), not the offer id.\nexport async function getTradeStatus(api: WebApiClient, tradeId: string): Promise<ExchangeDetails> {\n const body = await api.call<{\n response?: { trades?: RawTradeStatus[]; descriptions?: RawDescription[] };\n }>({\n httpMethod: \"GET\",\n iface: \"IEconService\",\n method: \"GetTradeStatus\",\n retryAfterMs: RETRY_AFTER.GetTradeStatus,\n input: { tradeid: tradeId, get_descriptions: 1, ...LANG },\n });\n\n const trades = body.response?.trades ?? [];\n // ?? the lone trade on an id-format mismatch; never guess from a multi-trade response.\n const trade =\n trades.find((t) => t.tradeid === tradeId) ?? (trades.length === 1 ? trades[0] : undefined);\n if (!trade) throw new SteamError(`Trade ${tradeId} not found in GetTradeStatus response`);\n return parseTrade(trade, buildDescriptionMap(body.response?.descriptions));\n}\n\n// Past trades, newest first. Cursor-paginate via startAfterTime + startAfterTradeId while `more`.\nexport async function getTradeHistory(\n api: WebApiClient,\n opts: TradeHistoryOptions = {},\n): Promise<TradeHistory> {\n const body = await api.call<{\n response?: {\n more?: boolean;\n total_trades?: number;\n trades?: RawTradeStatus[];\n descriptions?: RawDescription[];\n };\n }>({\n httpMethod: \"GET\",\n iface: \"IEconService\",\n method: \"GetTradeHistory\",\n retryAfterMs: RETRY_AFTER.GetTradeHistory,\n input: {\n max_trades: opts.maxTrades ?? 100,\n get_descriptions: 1,\n include_failed: opts.includeFailed ? 1 : 0,\n include_total: opts.includeTotal ? 1 : 0,\n ...(opts.startAfterTime !== undefined ? { start_after_time: opts.startAfterTime } : {}),\n ...(opts.startAfterTradeId !== undefined\n ? { start_after_tradeid: opts.startAfterTradeId }\n : {}),\n ...(opts.navigatingBack ? { navigating_back: 1 } : {}),\n ...LANG,\n },\n });\n\n const resp = body.response ?? {};\n const descriptions = buildDescriptionMap(resp.descriptions);\n const trades = (resp.trades ?? []).map((t) => ({\n ...parseTrade(t, descriptions),\n tradeId: t.tradeid,\n partnerSteamId: t.steamid_other,\n }));\n return { trades, more: resp.more ?? false, totalTrades: resp.total_trades };\n}\n\nexport async function getTradeOffersSummary(api: WebApiClient): Promise<TradeOffersSummary> {\n const body = await api.call<{ response?: Partial<TradeOffersSummary> }>({\n httpMethod: \"GET\",\n iface: \"IEconService\",\n method: \"GetTradeOffersSummary\",\n retryAfterMs: RETRY_AFTER.GetTradeOffersSummary,\n input: { time_last_visit: 0 },\n });\n const r = body.response ?? {};\n return {\n pending_received_count: r.pending_received_count ?? 0,\n new_received_count: r.new_received_count ?? 0,\n updated_received_count: r.updated_received_count ?? 0,\n historical_received_count: r.historical_received_count ?? 0,\n pending_sent_count: r.pending_sent_count ?? 0,\n newly_accepted_sent_count: r.newly_accepted_sent_count ?? 0,\n updated_sent_count: r.updated_sent_count ?? 0,\n historical_sent_count: r.historical_sent_count ?? 0,\n escrow_received_count: r.escrow_received_count ?? 0,\n escrow_sent_count: r.escrow_sent_count ?? 0,\n };\n}\n","import { EOfferFilter, ETradeOfferState } from \"../core/enums.js\";\nimport { RateLimitError } from \"../core/errors.js\";\nimport { isTerminalState } from \"../core/offerState.js\";\nimport type { PollChange, PollData, PollDataStore, PollOptions, TradeEvents } from \"./pollTypes.js\";\nimport type { TradeOffer } from \"./TradeOffer.js\";\n\nexport const DEFAULT_POLL_INTERVAL = 10_000;\nexport const DEFAULT_POLL_FULL_UPDATE_INTERVAL = 300_000;\nexport const DEFAULT_POLL_MAX_AGE_MS = 2_592_000_000; // 30 days\n// Steam backdates offer update times; re-ask 30 min before our last-seen mark so we don't miss one.\nconst POLL_BACKDATING_BUFFER = 1800;\nconst MINIMUM_POLL_INTERVAL = 1000;\n// Offers expire ~14d after creation; this margin makes prune-by-creation safe against sweep resurrection.\nconst OFFER_MAX_LIFETIME_MS = 1_209_600_000;\n\nexport interface PollSource {\n getTradeOffers(\n filter: EOfferFilter,\n historicalCutoff: Date,\n ): Promise<{ sent: TradeOffer[]; received: TradeOffer[] }>;\n emit<K extends keyof TradeEvents>(event: K, ...args: TradeEvents[K]): void;\n}\n\nfunction emptyPollData(): PollData {\n return { offersSince: 0, sent: {}, received: {}, timestamps: {} };\n}\n\nexport class Poller {\n pollData: PollData;\n private readonly pollInterval: number;\n private readonly fullInterval: number;\n private readonly maxAgeMs: number;\n private readonly cancelTime: number | undefined;\n private readonly store: PollDataStore | undefined;\n private timer: ReturnType<typeof setTimeout> | undefined;\n private running = false;\n private stopped = true;\n private loaded = false;\n\n constructor(\n private readonly source: PollSource,\n options: PollOptions = {},\n ) {\n this.pollInterval = Math.max(\n options.pollInterval ?? DEFAULT_POLL_INTERVAL,\n MINIMUM_POLL_INTERVAL,\n );\n this.fullInterval = options.pollFullUpdateInterval ?? DEFAULT_POLL_FULL_UPDATE_INTERVAL;\n this.maxAgeMs = options.maxAgeMs ?? DEFAULT_POLL_MAX_AGE_MS;\n this.cancelTime = options.cancelTime;\n this.store = options.store;\n this.pollData = options.pollData ?? emptyPollData();\n }\n\n start(): void {\n this.stopped = false;\n this.schedule(0); // immediate first tick; also a full sweep since lastFullUpdate is 0\n }\n\n stop(): void {\n this.stopped = true;\n if (this.timer) clearTimeout(this.timer);\n this.timer = undefined;\n }\n\n // Timer cycle. Never throws; returns the delay (ms) until the next poll. Loads the store once on start.\n async poll(forceFull = false): Promise<number> {\n if (this.running) return this.pollInterval;\n this.running = true;\n try {\n if (this.store && !this.loaded) await this.loadFromStore();\n let result: { changes: PollChange[]; changed: boolean };\n try {\n result = await this.runCycle(forceFull);\n } catch (err) {\n const error = err as Error;\n this.source.emit(\"debug\", `Trade offer poll failed: ${error.message}`);\n this.source.emit(\"pollFailure\", error);\n return this.backoffDelay(error);\n }\n if (this.store && result.changed) await this.persist();\n return this.pollInterval;\n } finally {\n this.running = false;\n }\n }\n\n // Timer-less single cycle for an external scheduler; throws on fetch error (unlike the timer loop).\n async pollOnce(forceFull = false): Promise<{ changes: PollChange[]; pollData: PollData }> {\n if (this.store) await this.loadFromStore();\n const { changes, changed } = await this.runCycle(forceFull);\n if (this.store && changed) await this.persist();\n return { changes, pollData: this.pollData };\n }\n\n private async loadFromStore(): Promise<void> {\n const loaded = await this.store?.load();\n if (loaded) this.pollData = loaded;\n this.loaded = true;\n }\n\n private async persist(): Promise<void> {\n try {\n await this.store?.save(this.pollData);\n } catch (err) {\n this.source.emit(\"debug\", `pollData store save failed: ${(err as Error).message}`);\n }\n }\n\n private schedule(ms: number): void {\n if (this.stopped) return;\n if (this.timer) clearTimeout(this.timer);\n this.timer = setTimeout(\n () => {\n void this.poll().then((delay) => this.schedule(delay));\n },\n Math.max(0, ms),\n );\n }\n\n // On a rate limit, wait until the bucket unlocks (if longer than our interval) to self-tune instead of hammering.\n private backoffDelay(err: Error): number {\n if (err instanceof RateLimitError) {\n const wait = err.unlockAt - Date.now();\n if (wait > this.pollInterval) return Math.max(wait, MINIMUM_POLL_INTERVAL);\n }\n return this.pollInterval;\n }\n\n private async runCycle(forceFull: boolean): Promise<{ changes: PollChange[]; changed: boolean }> {\n // Capture before touching lastFullUpdate so an offer-less full sweep still persists the advanced cadence.\n const before = JSON.stringify(this.pollData);\n const sinceBase = this.pollData.offersSince\n ? this.pollData.offersSince - POLL_BACKDATING_BUFFER\n : 0;\n let fullUpdate = forceFull;\n let cutoff = sinceBase;\n if (forceFull || Date.now() - (this.pollData.lastFullUpdate ?? 0) >= this.fullInterval) {\n fullUpdate = true;\n this.pollData.lastFullUpdate = Date.now();\n cutoff = this.sweepCutoffSeconds();\n }\n this.source.emit(\n \"debug\",\n `Polling trade offers since ${cutoff}${fullUpdate ? \" (full update)\" : \"\"}`,\n );\n\n const result = await this.source.getTradeOffers(\n fullUpdate ? EOfferFilter.All : EOfferFilter.ActiveOnly,\n new Date(cutoff * 1000),\n );\n const changes = this.process(result.sent, result.received, fullUpdate);\n if (this.cancelTime !== undefined) this.autoCancel(result.sent, this.cancelTime);\n this.prune(seenIds(result.sent, result.received));\n const changed = JSON.stringify(this.pollData) !== before;\n\n this.source.emit(\"pollSuccess\");\n if (changed) this.source.emit(\"pollData\", this.pollData);\n return { changes, changed };\n }\n\n // Auto-cancel sent offers still Active past cancelTime since their last update (McKay's cancelTime).\n // Fire-and-forget like the upstream; the resulting state change surfaces on a later poll.\n private autoCancel(sentList: TradeOffer[], cancelTime: number): void {\n const now = Date.now();\n for (const offer of sentList) {\n if (offer.state !== ETradeOfferState.Active || !offer.updated) continue;\n if (now - offer.updated.getTime() < cancelTime) continue;\n void offer.cancel().then(\n () => this.source.emit(\"sentOfferCanceled\", offer, \"cancelTime\"),\n (err: Error) =>\n this.source.emit(\"debug\", `Can't auto-cancel offer #${offer.id}: ${err.message}`),\n );\n }\n }\n\n // Bound the full sweep to the retention window so it stays cheap and can't return already-pruned offers.\n private sweepCutoffSeconds(): number {\n return Math.max(1, Math.floor((Date.now() - this.maxAgeMs) / 1000));\n }\n\n private process(\n sentList: TradeOffer[],\n receivedList: TradeOffer[],\n fullUpdate: boolean,\n ): PollChange[] {\n const changes: PollChange[] = [];\n const { sent, received, timestamps } = this.pollData;\n let hasGlitched = false;\n\n for (const offer of sentList) {\n if (!offer.id) continue;\n const known = sent[offer.id];\n if (known === undefined) {\n // Unknown sent offer: record + announce regardless of glitch (matches steam-tradeoffer-manager).\n // Skipping these strands the cutoff at 0 and re-announces them on every poll.\n this.record(changes, { type: \"unknownOfferSent\", offer });\n } else if (offer.state !== known) {\n if (offer.glitched) {\n // Defer a glitched state change so it's re-polled with full item data; blocks cutoff advance.\n hasGlitched = true;\n continue;\n }\n this.record(changes, { type: \"sentOfferChanged\", offer, oldState: known });\n }\n sent[offer.id] = offer.state;\n this.stamp(timestamps, offer);\n }\n\n for (const offer of receivedList) {\n if (!offer.id) continue;\n if (offer.glitched) {\n hasGlitched = true;\n continue;\n }\n const known = received[offer.id];\n if (known === undefined && offer.state === ETradeOfferState.Active) {\n this.record(changes, { type: \"newOffer\", offer });\n } else if (known !== undefined && offer.state !== known) {\n this.record(changes, { type: \"receivedOfferChanged\", offer, oldState: known });\n }\n received[offer.id] = offer.state;\n this.stamp(timestamps, offer);\n }\n\n // Advance the cutoff only when nothing was glitched, so incomplete offers get re-polled.\n if (!hasGlitched) {\n let latest = this.pollData.offersSince;\n for (const offer of [...sentList, ...receivedList]) {\n const updated = offer.updated ? Math.floor(offer.updated.getTime() / 1000) : 0;\n if (updated > latest) latest = updated;\n }\n // A full sweep observes all state up to now, so floor offersSince to now even when no offers\n // come back. Otherwise it stays 0 and active polls send time_historical_cutoff=0, which Steam\n // answers erratically (misses declines, resurfaces old offers as \"new\"). Our sweep is bounded\n // to maxAgeMs, so unlike McKay's epoch sweep it can legitimately return nothing.\n if (fullUpdate) latest = Math.max(latest, Math.floor(Date.now() / 1000));\n this.pollData.offersSince = latest;\n }\n return changes;\n }\n\n // Record a change and emit it as both its specific named event and the unified offerUpdate event.\n private record(changes: PollChange[], change: PollChange): void {\n changes.push(change);\n switch (change.type) {\n case \"newOffer\":\n this.source.emit(\"newOffer\", change.offer);\n break;\n case \"unknownOfferSent\":\n this.source.emit(\"unknownOfferSent\", change.offer);\n break;\n case \"sentOfferChanged\":\n this.source.emit(\"sentOfferChanged\", change.offer, change.oldState);\n break;\n case \"receivedOfferChanged\":\n this.source.emit(\"receivedOfferChanged\", change.offer, change.oldState);\n break;\n }\n const previousState = \"oldState\" in change ? change.oldState : undefined;\n this.source.emit(\"offerUpdate\", {\n offer: change.offer,\n ...(previousState !== undefined ? { previousState } : {}),\n });\n }\n\n // Drop terminal offers older than the retention window; never prune one seen this cycle.\n private prune(seen: Set<string>): void {\n const cutoff = Math.floor((Date.now() - this.maxAgeMs - OFFER_MAX_LIFETIME_MS) / 1000);\n this.pruneMap(this.pollData.sent, seen, cutoff);\n this.pruneMap(this.pollData.received, seen, cutoff);\n }\n\n private pruneMap(map: Record<string, ETradeOfferState>, seen: Set<string>, cutoff: number): void {\n for (const id of Object.keys(map)) {\n const state = map[id];\n const created = this.pollData.timestamps[id];\n if (\n !seen.has(id) &&\n state !== undefined &&\n isTerminalState(state) &&\n created !== undefined &&\n created > 0 &&\n created < cutoff\n ) {\n delete map[id];\n delete this.pollData.timestamps[id];\n }\n }\n }\n\n private stamp(timestamps: Record<string, number>, offer: TradeOffer): void {\n if (offer.id && offer.created)\n timestamps[offer.id] = Math.floor(offer.created.getTime() / 1000);\n }\n}\n\nfunction seenIds(sent: TradeOffer[], received: TradeOffer[]): Set<string> {\n const ids = new Set<string>();\n for (const offer of [...sent, ...received]) if (offer.id) ids.add(offer.id);\n return ids;\n}\n","import SteamID from \"steamid\";\nimport type { ConfirmationManager } from \"../community/confirmations.js\";\nimport { acknowledgeTradeProtection } from \"../community/tradeProtection.js\";\nimport {\n buildPartnerTradePageUrl,\n fetchUserDetails,\n type UserDetails,\n} from \"../community/userDetails.js\";\nimport { URLS } from \"../core/constants.js\";\nimport { EConfirmationMethod, ETradeOfferState } from \"../core/enums.js\";\nimport { ConfirmationError, SteamError, SteamSessionExpiredError } from \"../core/errors.js\";\nimport { isTerminalState } from \"../core/offerState.js\";\nimport { parseStrError } from \"../core/parseStrError.js\";\nimport type { OfferTarget, RawAsset, RawCEconTradeOffer, TradeItem } from \"../core/types.js\";\nimport { httpError } from \"../http/checkers.js\";\nimport type { HttpClient } from \"../http/HttpClient.js\";\nimport { buildItem, type EconItem, type RawDescription } from \"../models/EconItem.js\";\nimport type { SessionManager } from \"../session/SessionManager.js\";\nimport type { ExchangeDetails } from \"./exchange.js\";\nimport type { TradeNamespace } from \"./TradeNamespace.js\";\n\nexport type SendResult = \"sent\" | \"needs_confirmation\";\nexport type AcceptResult = \"accepted\" | \"escrow\" | \"needs_confirmation\";\n\nconst TWO_WEEKS_MS = 1_209_600_000;\n\nexport interface TradeOfferDeps {\n http: HttpClient;\n session: SessionManager;\n confirmations: ConfirmationManager;\n trade: TradeNamespace;\n}\n\ninterface RawSendResponse {\n tradeofferid?: string;\n needs_mobile_confirmation?: boolean;\n needs_email_confirmation?: boolean;\n strError?: string;\n}\n\ninterface RawAcceptResponse {\n tradeid?: string;\n needs_mobile_confirmation?: boolean;\n needs_email_confirmation?: boolean;\n strError?: string;\n}\n\ninterface RawCancelResponse {\n tradeofferid?: string;\n strError?: string;\n}\n\nexport class TradeOffer {\n id: string | undefined;\n readonly partner: SteamID;\n token: string | undefined;\n message = \"\";\n state: ETradeOfferState = ETradeOfferState.Invalid;\n itemsToGive: TradeItem[] = [];\n itemsToReceive: TradeItem[] = [];\n isOurOffer = true;\n tradeID: string | undefined;\n confirmationMethod: EConfirmationMethod = EConfirmationMethod.None;\n escrowEnds: Date | undefined;\n // 2025 trade-protection hold end (== trade time_settlement); set once Accepted. Distinct from escrowEnds.\n settlementDate: Date | undefined;\n delaySettlement = false;\n created: Date | undefined;\n updated: Date | undefined;\n expires: Date | undefined;\n fromRealTimeTrade = false;\n // Offer with missing item names (descriptions not ready) or no items; polling must not advance its cutoff past it.\n glitched = false;\n private countering: string | undefined;\n\n constructor(\n private readonly deps: TradeOfferDeps,\n init: { partner: SteamID; token?: string; id?: string },\n ) {\n this.partner = init.partner;\n this.token = init.token;\n this.id = init.id;\n }\n\n // `descriptions` (from get_descriptions=1) enriches each item into a full EconItem; glitch detection needs the names.\n static fromData(\n deps: TradeOfferDeps,\n raw: RawCEconTradeOffer,\n descriptions?: Map<string, RawDescription>,\n ): TradeOffer {\n if (!raw.accountid_other) {\n throw new SteamError(`Trade offer ${raw.tradeofferid} is missing a partner accountid`);\n }\n const partner = SteamID.fromIndividualAccountID(raw.accountid_other);\n const offer = new TradeOffer(deps, { partner, id: raw.tradeofferid });\n offer.message = raw.message ?? \"\";\n offer.state = raw.trade_offer_state;\n offer.isOurOffer = raw.is_our_offer;\n offer.fromRealTimeTrade = raw.from_real_time_trade ?? false;\n const mapItem = (a: RawAsset): TradeItem =>\n descriptions\n ? buildItem(a, descriptions.get(`${a.appid}_${a.classid}_${a.instanceid}`), [], a.contextid)\n : toTradeItem(a);\n offer.itemsToGive = (raw.items_to_give ?? []).map(mapItem);\n offer.itemsToReceive = (raw.items_to_receive ?? []).map(mapItem);\n offer.confirmationMethod = raw.confirmation_method ?? EConfirmationMethod.None;\n if (raw.tradeid) offer.tradeID = raw.tradeid;\n if (raw.escrow_end_date) offer.escrowEnds = new Date(raw.escrow_end_date * 1000);\n if (raw.settlement_date) offer.settlementDate = new Date(raw.settlement_date * 1000);\n offer.delaySettlement = raw.delay_settlement ?? false;\n if (raw.time_created) offer.created = new Date(raw.time_created * 1000);\n if (raw.time_updated) offer.updated = new Date(raw.time_updated * 1000);\n if (raw.expiration_time) offer.expires = new Date(raw.expiration_time * 1000);\n\n const allItems = [...offer.itemsToGive, ...offer.itemsToReceive];\n offer.glitched =\n !isTerminalState(offer.state) &&\n (allItems.length === 0 ||\n (descriptions !== undefined && allItems.some((i) => !(i as EconItem).name)));\n return offer;\n }\n\n // Faithful to upstream itemEquals: same appid + contextid + assetid.\n containsItem(item: { appid: number; contextid: string; assetid: string }): boolean {\n return [...this.itemsToGive, ...this.itemsToReceive].some(\n (i) => i.appid === item.appid && i.contextid === item.contextid && i.assetid === item.assetid,\n );\n }\n\n give(items: TradeItem[]): this {\n this.itemsToGive.push(...items);\n return this;\n }\n\n receive(items: TradeItem[]): this {\n this.itemsToReceive.push(...items);\n return this;\n }\n\n setMessage(message: string): this {\n if (this.id) throw new SteamError(\"Cannot set a message on an already-sent offer\");\n this.message = message.slice(0, 128);\n return this;\n }\n\n async send(): Promise<SendResult> {\n if (this.id) throw new SteamError(\"This offer has already been sent\");\n if (this.itemsToGive.length + this.itemsToReceive.length === 0) {\n throw new SteamError(\"Cannot send an empty trade offer\");\n }\n\n await this.deps.session.getAccessToken();\n const sessionid = await this.deps.http.getSessionId();\n // Acknowledge the 2025 trade-protection notice so send isn't blocked; tolerate ack failures but not an expired session.\n await acknowledgeTradeProtection(this.deps.http).catch((err) => {\n if (err instanceof SteamSessionExpiredError) throw err;\n });\n\n const offerdata = {\n newversion: true,\n version: this.itemsToGive.length + this.itemsToReceive.length + 1,\n me: { assets: this.itemsToGive.map(toAsset), currency: [], ready: false },\n them: { assets: this.itemsToReceive.map(toAsset), currency: [], ready: false },\n };\n const createParams: Record<string, string> = {};\n if (this.token) createParams.trade_offer_access_token = this.token;\n\n const res = await this.deps.http.post<RawSendResponse>(\n `${URLS.community}/tradeoffer/new/send`,\n {\n responseType: \"json\",\n referer: this.newOfferReferer(),\n form: {\n sessionid,\n serverid: 1,\n partner: this.partner.getSteamID64(),\n tradeoffermessage: this.message,\n json_tradeoffer: JSON.stringify(offerdata),\n captcha: \"\",\n trade_offer_create_params: JSON.stringify(createParams),\n ...(this.countering ? { tradeofferid_countered: this.countering } : {}),\n },\n },\n );\n\n if (res.statusCode === 401) throw new SteamSessionExpiredError();\n const body = res.body;\n // Steam often returns strError on a non-200; surface the typed error first.\n if (body?.strError) throw parseStrError(body.strError);\n if (res.statusCode !== 200) throw httpError(res);\n if (!body) throw new SteamError(\"Malformed JSON response\");\n\n if (body.tradeofferid) {\n this.id = body.tradeofferid;\n this.state = ETradeOfferState.Active;\n this.created = new Date();\n this.updated = new Date();\n this.expires = new Date(Date.now() + TWO_WEEKS_MS);\n }\n this.confirmationMethod = EConfirmationMethod.None;\n if (body.needs_email_confirmation) {\n this.state = ETradeOfferState.CreatedNeedsConfirmation;\n this.confirmationMethod = EConfirmationMethod.Email;\n }\n if (body.needs_mobile_confirmation) {\n this.state = ETradeOfferState.CreatedNeedsConfirmation;\n this.confirmationMethod = EConfirmationMethod.MobileApp;\n }\n\n if (this.state === ETradeOfferState.CreatedNeedsConfirmation) return \"needs_confirmation\";\n if (body.tradeofferid) return \"sent\";\n throw new SteamError(\"Unknown response sending trade offer\");\n }\n\n async accept(): Promise<AcceptResult> {\n if (!this.id) throw new SteamError(\"Cannot accept an unsent offer\");\n if (this.state !== ETradeOfferState.Active) {\n throw new SteamError(`Offer #${this.id} is not active, so it may not be accepted`);\n }\n if (this.isOurOffer) throw new SteamError(`Cannot accept our own offer #${this.id}`);\n\n await this.deps.session.getAccessToken();\n const sessionid = await this.deps.http.getSessionId();\n const res = await this.deps.http.post<RawAcceptResponse>(\n `${URLS.community}/tradeoffer/${this.id}/accept`,\n {\n responseType: \"json\",\n referer: `${URLS.community}/tradeoffer/${this.id}/`,\n form: {\n sessionid,\n serverid: 1,\n tradeofferid: this.id,\n partner: this.partner.getSteamID64(),\n captcha: \"\",\n },\n },\n );\n\n if (res.statusCode === 403) throw new SteamSessionExpiredError();\n const body = res.body;\n if (body?.strError) throw parseStrError(body.strError);\n if (res.statusCode !== 200) throw httpError(res);\n if (!body) throw new SteamError(\"Malformed JSON response\");\n\n if (body.tradeid) this.tradeID = body.tradeid;\n if (body.needs_mobile_confirmation || body.needs_email_confirmation) {\n this.confirmationMethod = body.needs_mobile_confirmation\n ? EConfirmationMethod.MobileApp\n : EConfirmationMethod.Email;\n return \"needs_confirmation\";\n }\n\n // The accept response doesn't flag escrow; re-read to distinguish a held trade from a settled one.\n this.state = ETradeOfferState.Accepted;\n try {\n const refreshed = await this.deps.trade.getTradeOffer(this.id);\n this.state = refreshed.state;\n this.escrowEnds = refreshed.escrowEnds;\n } catch {\n // keep optimistic Accepted; caller can reconcile via getTradeOffer\n }\n return this.state === ETradeOfferState.InEscrow ? \"escrow\" : \"accepted\";\n }\n\n async cancel(): Promise<void> {\n if (!this.id) throw new SteamError(\"Cannot cancel or decline an unsent offer\");\n if (\n this.state !== ETradeOfferState.Active &&\n this.state !== ETradeOfferState.CreatedNeedsConfirmation\n ) {\n throw new SteamError(\n `Offer #${this.id} is not active, so it may not be cancelled or declined`,\n );\n }\n\n await this.deps.session.getAccessToken();\n const sessionid = await this.deps.http.getSessionId();\n const action = this.isOurOffer ? \"cancel\" : \"decline\";\n const res = await this.deps.http.post<RawCancelResponse>(\n `${URLS.community}/tradeoffer/${this.id}/${action}`,\n {\n responseType: \"json\",\n referer: this.offerReferer(),\n form: { sessionid },\n },\n );\n\n if (res.statusCode === 401) throw new SteamSessionExpiredError();\n const body = res.body;\n if (body?.strError) throw parseStrError(body.strError);\n if (res.statusCode !== 200) throw httpError(res);\n if (!body) throw new SteamError(\"Malformed JSON response\");\n if (body.tradeofferid !== this.id) throw new SteamError(\"Wrong response cancelling offer\");\n\n this.state = this.isOurOffer ? ETradeOfferState.Canceled : ETradeOfferState.Declined;\n this.updated = new Date();\n }\n\n decline(): Promise<void> {\n return this.cancel();\n }\n\n async confirm(): Promise<void> {\n if (!this.id) throw new ConfirmationError(\"Cannot confirm an unsent offer\");\n if (!this.deps.confirmations.hasIdentitySecret) {\n throw new ConfirmationError(\n \"identitySecret is required to confirm trade offers — construct SteamMobile with { identitySecret }\",\n );\n }\n await this.deps.confirmations.acceptConfirmationForObject(this.id);\n }\n\n counter(): TradeOffer {\n if (!this.id) throw new SteamError(\"Cannot counter an unsent offer\");\n if (this.state !== ETradeOfferState.Active) {\n throw new SteamError(`Offer #${this.id} is not active, so it may not be countered`);\n }\n const next = new TradeOffer(this.deps, {\n partner: this.partner,\n ...(this.token ? { token: this.token } : {}),\n });\n next.countering = this.id;\n next.isOurOffer = true;\n // Deep-copy items so editing the counter doesn't mutate the original offer.\n next.itemsToGive = this.itemsToGive.map((i) => ({ ...i }));\n next.itemsToReceive = this.itemsToReceive.map((i) => ({ ...i }));\n next.message = this.message;\n return next;\n }\n\n // Settlement details once accepted (needs tradeID, set on accept / on a fetched accepted offer).\n getTradeStatus(): Promise<ExchangeDetails> {\n if (!this.tradeID) {\n throw new SteamError(\"No trade ID — getTradeStatus needs an accepted offer\");\n }\n return this.deps.trade.getTradeStatus({ tradeId: this.tradeID });\n }\n\n getPartnerInventory(\n appid: number,\n contextid?: string,\n tradableOnly?: boolean,\n ): Promise<EconItem[]> {\n const target = this.partnerTarget();\n return this.deps.trade.getInventory(\n target,\n appid,\n contextid,\n tradableOnly !== undefined ? { tradableOnly } : {},\n );\n }\n\n // Persona, contexts, avatars, escrow, partner probation — McKay-parity getUserDetails. Allowed for:\n // - offers we created and haven't sent yet (need friendship or the token)\n // - offers they created and sent to us, while still Active\n async getUserDetails(): Promise<UserDetails> {\n if (this.id && this.isOurOffer) {\n throw new SteamError(\"Cannot get user details for an offer that we sent\");\n }\n if (this.id && this.state !== ETradeOfferState.Active) {\n throw new SteamError(\"Cannot get user details for an offer that is sent and not Active\");\n }\n await this.deps.session.getAccessToken();\n const url = this.id\n ? `${URLS.community}/tradeoffer/${this.id}/`\n : buildPartnerTradePageUrl(this.partner.accountid, this.token);\n const referer = `${URLS.community}/profiles/${this.partner.getSteamID64()}`;\n return fetchUserDetails(\n this.deps.http,\n url,\n referer,\n this.deps.session.steamID.accountid,\n this.partner.accountid,\n );\n }\n\n private partnerTarget(): OfferTarget {\n const steamId = this.partner.getSteamID64();\n return this.token ? { steamId, token: this.token } : { steamId };\n }\n\n private newOfferReferer(): string {\n const token = this.token ? `&token=${this.token}` : \"\";\n return `${URLS.community}/tradeoffer/${this.id ?? \"new\"}/?partner=${this.partner.accountid}${token}`;\n }\n\n private offerReferer(): string {\n const token = this.token ? `&token=${this.token}` : \"\";\n return `${URLS.community}/tradeoffer/${this.id}/?partner=${this.partner.accountid}${token}`;\n }\n}\n\nfunction toAsset(item: TradeItem): {\n appid: number;\n contextid: string;\n amount: number;\n assetid: string;\n} {\n return {\n appid: item.appid,\n contextid: item.contextid,\n amount: item.amount && item.amount > 0 ? item.amount : 1,\n assetid: item.assetid,\n };\n}\n\nfunction toTradeItem(raw: RawAsset): TradeItem {\n return {\n appid: raw.appid,\n contextid: raw.contextid,\n assetid: raw.assetid,\n amount: Number(raw.amount) || 1,\n };\n}\n","import { EventEmitter } from \"node:events\";\nimport SteamID from \"steamid\";\nimport type { ConfirmationManager } from \"../community/confirmations.js\";\nimport {\n buildPartnerTradePageUrl,\n fetchUserDetails,\n type UserDetails,\n} from \"../community/userDetails.js\";\nimport { DEFAULT_CONTEXTID, LANG, URLS } from \"../core/constants.js\";\nimport { EOfferFilter } from \"../core/enums.js\";\nimport { SteamError } from \"../core/errors.js\";\nimport { type Page, paginate } from \"../core/paginate.js\";\nimport { parseStrError } from \"../core/parseStrError.js\";\nimport { RETRY_AFTER } from \"../core/rateLimits.js\";\nimport { resolveTarget } from \"../core/target.js\";\nimport type { OfferTarget, RawAsset, RawCEconTradeOffer } from \"../core/types.js\";\nimport { httpError } from \"../http/checkers.js\";\nimport type { HttpClient } from \"../http/HttpClient.js\";\nimport { inventoryFailureError } from \"../http/tradePageError.js\";\nimport type { WebApiClient } from \"../http/webApi.js\";\nimport {\n buildDescriptionMap,\n type EconItem,\n parsePartnerInventory,\n type RawPartnerInventoryResponse,\n} from \"../models/EconItem.js\";\nimport type { SessionManager } from \"../session/SessionManager.js\";\nimport {\n type ExchangeDetails,\n getTradeHistory as fetchTradeHistory,\n getTradeOffersSummary as fetchTradeOffersSummary,\n getTradeStatus as fetchTradeStatus,\n type TradeHistory,\n type TradeHistoryOptions,\n type TradeOffersSummary,\n} from \"./exchange.js\";\nimport { Poller } from \"./polling.js\";\nimport type { PollChange, PollData, PollOptions, TradeEvents } from \"./pollTypes.js\";\nimport { TradeOffer, type TradeOfferDeps } from \"./TradeOffer.js\";\n\nconst FUTURE_CUTOFF_MS = 31_536_000_000; // 1 year ahead = \"no historical offers\"\n\nexport interface EscrowSide {\n escrow_end_duration_seconds: number;\n}\n\nexport interface EscrowHold {\n me: EscrowSide;\n them: EscrowSide;\n both: EscrowSide;\n}\n\ninterface RawEscrowResponse {\n my_escrow?: EscrowSide;\n their_escrow?: EscrowSide;\n both_escrow?: EscrowSide;\n}\n\nexport class TradeNamespace extends EventEmitter<TradeEvents> {\n private poller: Poller | undefined;\n\n constructor(\n private readonly api: WebApiClient,\n private readonly http: HttpClient,\n private readonly session: SessionManager,\n private readonly confirmations: ConfirmationManager,\n ) {\n super();\n }\n\n private offerDeps(): TradeOfferDeps {\n return {\n http: this.http,\n session: this.session,\n confirmations: this.confirmations,\n trade: this,\n };\n }\n\n // Local only — no network until send().\n createOffer(target: OfferTarget): TradeOffer {\n const { steamId, token } = resolveTarget(target);\n return new TradeOffer(this.offerDeps(), {\n partner: new SteamID(steamId),\n ...(token ? { token } : {}),\n });\n }\n\n async getTradeOffer(id: string): Promise<TradeOffer> {\n const body = await this.api.call<{\n response?: {\n offer?: RawCEconTradeOffer;\n descriptions?: Parameters<typeof buildDescriptionMap>[0];\n };\n }>({\n httpMethod: \"GET\",\n iface: \"IEconService\",\n method: \"GetTradeOffer\",\n retryAfterMs: RETRY_AFTER.GetTradeOffer,\n input: { tradeofferid: id, get_descriptions: 1, ...LANG },\n });\n const raw = body.response?.offer;\n if (!raw) throw new SteamError(`Trade offer ${id} not found`);\n return TradeOffer.fromData(\n this.offerDeps(),\n raw,\n buildDescriptionMap(body.response?.descriptions),\n );\n }\n\n // Cursor-paginates all pages; rejects the wholly-malformed \"data temporarily unavailable\" glitch.\n async getTradeOffers(\n filter: EOfferFilter = EOfferFilter.ActiveOnly,\n historicalCutoff?: Date,\n ): Promise<{ sent: TradeOffer[]; received: TradeOffer[] }> {\n const cutoff = historicalCutoff ?? new Date(Date.now() + FUTURE_CUTOFF_MS);\n\n const sentRaw: RawCEconTradeOffer[] = [];\n const receivedRaw: RawCEconTradeOffer[] = [];\n const descriptions: NonNullable<Parameters<typeof buildDescriptionMap>[0]> = [];\n let cursor = 0;\n\n do {\n const body = await this.api.call<{\n response?: {\n trade_offers_sent?: RawCEconTradeOffer[];\n trade_offers_received?: RawCEconTradeOffer[];\n descriptions?: NonNullable<Parameters<typeof buildDescriptionMap>[0]>;\n next_cursor?: number;\n };\n }>({\n httpMethod: \"GET\",\n iface: \"IEconService\",\n method: \"GetTradeOffers\",\n retryAfterMs: RETRY_AFTER.GetTradeOffers,\n input: {\n get_sent_offers: 1,\n get_received_offers: 1,\n get_descriptions: 1,\n active_only: filter === EOfferFilter.ActiveOnly ? 1 : 0,\n historical_only: filter === EOfferFilter.HistoricalOnly ? 1 : 0,\n time_historical_cutoff: Math.floor(cutoff.getTime() / 1000),\n cursor,\n ...LANG,\n },\n });\n const response = body.response ?? {};\n sentRaw.push(...(response.trade_offers_sent ?? []));\n receivedRaw.push(...(response.trade_offers_received ?? []));\n descriptions.push(...(response.descriptions ?? []));\n const next = response.next_cursor ?? 0;\n if (next !== 0 && next === cursor) break; // cursor not advancing — stop rather than loop forever\n cursor = next;\n if (cursor) this.emit(\"debug\", `GetTradeOffers with cursor ${cursor}`);\n } while (cursor);\n\n const all = [...sentRaw, ...receivedRaw];\n if (all.length > 0 && (all.every(offerMalformed) || all.some(offerSuperMalformed))) {\n throw new SteamError(\"Data temporarily unavailable\");\n }\n\n const descMap = buildDescriptionMap(descriptions);\n const build = (raw: RawCEconTradeOffer): TradeOffer =>\n TradeOffer.fromData(this.offerDeps(), sanitizeRawOffer(raw), descMap);\n return { sent: sentRaw.map(build), received: receivedRaw.map(build) };\n }\n\n // Settlement details for a completed/escrowed trade (tradeID, not offer id).\n getTradeStatus(opts: { tradeId: string }): Promise<ExchangeDetails> {\n return fetchTradeStatus(this.api, opts.tradeId);\n }\n\n // Persona, contexts, escrow days, avatars, and partner probation for both sides — same trade-page\n // scrape as offer.getUserDetails(), but addressed by target instead of by an existing offer.\n async getUserDetails(target: OfferTarget): Promise<UserDetails> {\n await this.session.getAccessToken();\n const { steamId, token } = resolveTarget(target);\n const partnerAccountId = new SteamID(steamId).accountid;\n return fetchUserDetails(\n this.http,\n buildPartnerTradePageUrl(partnerAccountId, token),\n `${URLS.community}/profiles/${steamId}`,\n this.session.steamID.accountid,\n partnerAccountId,\n );\n }\n\n // Escrow hold (seconds) via IEconService/GetTradeHoldDurations — escrow-only, lightweight. For\n // everything together (escrow + persona + avatars + contexts), use offer.getUserDetails() instead.\n async getEscrow(target: OfferTarget): Promise<EscrowHold> {\n const { steamId, token } = resolveTarget(target);\n const body = await this.api.call<{ response?: RawEscrowResponse }>({\n httpMethod: \"GET\",\n iface: \"IEconService\",\n method: \"GetTradeHoldDurations\",\n retryAfterMs: RETRY_AFTER.GetTradeHoldDurations,\n input: {\n steamid_target: steamId,\n ...(token ? { trade_offer_access_token: token } : {}),\n },\n });\n const r = body.response ?? {};\n const zero: EscrowSide = { escrow_end_duration_seconds: 0 };\n return {\n me: r.my_escrow ?? zero,\n them: r.their_escrow ?? zero,\n both: r.both_escrow ?? zero,\n };\n }\n\n // Past trades (newest first); cursor-paginate with startAfterTime/startAfterTradeId while `more`.\n getTradeHistory(opts?: TradeHistoryOptions): Promise<TradeHistory> {\n return fetchTradeHistory(this.api, opts);\n }\n\n // Counts of pending/new/historical sent & received offers.\n getTradeOffersSummary(): Promise<TradeOffersSummary> {\n return fetchTradeOffersSummary(this.api);\n }\n\n // Re-read known offers by id; missing/errored ids are skipped so one can't fail the batch.\n async reconcile(ids: string[]): Promise<Map<string, TradeOffer>> {\n const results = await Promise.allSettled(ids.map((id) => this.getTradeOffer(id)));\n const map = new Map<string, TradeOffer>();\n results.forEach((res, i) => {\n const id = ids[i];\n if (id !== undefined && res.status === \"fulfilled\") map.set(id, res.value);\n });\n return map;\n }\n\n async getOffersContainingItems(\n items: { appid: number; contextid: string; assetid: string }[],\n includeInactive = false,\n ): Promise<TradeOffer[]> {\n const { sent, received } = await this.getTradeOffers(\n includeInactive ? EOfferFilter.All : EOfferFilter.ActiveOnly,\n );\n return [...sent, ...received].filter((offer) =>\n items.every((item) => offer.containsItem(item)),\n );\n }\n\n startPolling(options: PollOptions = {}): void {\n this.poller?.stop();\n this.poller = new Poller(this, options);\n this.poller.start();\n }\n\n stopPolling(): void {\n this.poller?.stop();\n this.poller = undefined;\n }\n\n async pollOnce(\n options: PollOptions & { forceFull?: boolean } = {},\n ): Promise<{ changes: PollChange[]; pollData: PollData }> {\n const { forceFull, ...pollOptions } = options;\n if (!this.poller) this.poller = new Poller(this, pollOptions);\n return this.poller.pollOnce(forceFull ?? false);\n }\n\n get pollData(): PollData | undefined {\n return this.poller?.pollData;\n }\n\n async getInventory(\n target: OfferTarget,\n appid: number,\n contextid: string = DEFAULT_CONTEXTID,\n options: { tradableOnly?: boolean } = {},\n ): Promise<EconItem[]> {\n const tradableOnly = options.tradableOnly ?? false;\n await this.session.getAccessToken();\n const { steamId, token } = resolveTarget(target);\n const sessionid = await this.http.getSessionId();\n const accountId = new SteamID(steamId).accountid;\n const referer = `${URLS.community}/tradeoffer/new/?partner=${accountId}${token ? `&token=${token}` : \"\"}`;\n\n return paginate<EconItem, number>(async (start): Promise<Page<EconItem, number>> => {\n const res = await this.http.get<RawPartnerInventoryResponse>(\n `${URLS.community}/tradeoffer/new/partnerinventory/`,\n {\n responseType: \"json\",\n searchParams: {\n sessionid,\n partner: steamId,\n appid,\n contextid,\n ...(token ? { token } : {}),\n ...(start !== undefined ? { start } : {}),\n l: LANG.l,\n },\n headers: { Referer: referer },\n },\n );\n\n const body = res.body;\n if (res.statusCode === 500 && body?.error) throw parseStrError(body.error);\n if (res.statusCode !== 200) throw httpError(res, RETRY_AFTER.partnerInventory);\n if (!body?.success) {\n throw await inventoryFailureError(this.http, steamId, token, body?.error ?? body?.Error);\n }\n\n // Continue only when more_start actually advances, else a stuck cursor loops forever.\n const next =\n body.more && typeof body.more_start === \"number\" && body.more_start > (start ?? 0)\n ? body.more_start\n : undefined;\n return { items: parsePartnerInventory(body, contextid, tradableOnly), next };\n });\n }\n}\n\nfunction itemMalformed(item: RawAsset): boolean {\n return !item.appid || !item.contextid || !item.assetid;\n}\n\nfunction offerSuperMalformed(offer: RawCEconTradeOffer): boolean {\n return !offer.accountid_other;\n}\n\nfunction offerMalformed(offer: RawCEconTradeOffer): boolean {\n return (\n offerSuperMalformed(offer) ||\n ((offer.items_to_give ?? []).length === 0 && (offer.items_to_receive ?? []).length === 0) ||\n (offer.items_to_give ?? []).some(itemMalformed) ||\n (offer.items_to_receive ?? []).some(itemMalformed)\n );\n}\n\nfunction sanitizeRawOffer(offer: RawCEconTradeOffer): RawCEconTradeOffer {\n return {\n ...offer,\n ...(offer.items_to_give\n ? { items_to_give: offer.items_to_give.filter((i) => !itemMalformed(i)) }\n : {}),\n ...(offer.items_to_receive\n ? { items_to_receive: offer.items_to_receive.filter((i) => !itemMalformed(i)) }\n : {}),\n };\n}\n","import { EventEmitter } from \"node:events\";\nimport type SteamID from \"steamid\";\nimport {\n type LoginWithCredentialsOptions,\n loginWithCredentials,\n} from \"./auth/loginWithCredentials.js\";\nimport { CommunityNamespace } from \"./community/CommunityNamespace.js\";\nimport { ConfirmationManager } from \"./community/confirmations.js\";\nimport type { OpenidLoginOptions, OpenidLoginResult } from \"./community/openid.js\";\nimport {\n type MobilePlatform,\n type MobileProfile,\n resolveMobileProfile,\n} from \"./core/mobileProfile.js\";\nimport { HttpClient, type HttpResponse, type RequestOptions } from \"./http/HttpClient.js\";\nimport { WebApiClient } from \"./http/webApi.js\";\nimport { SessionManager } from \"./session/SessionManager.js\";\nimport type { PollOptions, TradeEvents } from \"./trade/pollTypes.js\";\nimport { TradeNamespace } from \"./trade/TradeNamespace.js\";\n\n// Root surface: session lifecycle events + all trade events re-emitted (so consumers can listen on\n// `bot` or `bot.trade`). `debug` comes from TradeEvents.\nexport interface SteamMobileEvents extends TradeEvents {\n refreshToken: [token: string];\n sessionExpired: [error: Error];\n}\n\nexport interface SteamMobileOptions {\n refreshToken: string;\n identitySecret?: string;\n proxy?: string;\n // Wire impersonation: a string picks a preset (\"ios\" default, \"android\"); an object overrides individual fields.\n mobileProfile?: MobilePlatform | Partial<MobileProfile>;\n // Start polling after login. `true` uses defaults; pass PollOptions to tune cadence or resume from saved pollData.\n polling?: boolean | PollOptions;\n}\n\nexport type ReauthenticateOptions = Omit<LoginWithCredentialsOptions, \"proxy\" | \"mobileProfile\">;\n\nexport class SteamMobile extends EventEmitter<SteamMobileEvents> {\n readonly http: HttpClient;\n readonly session: SessionManager;\n readonly api: WebApiClient;\n readonly confirmations: ConfirmationManager;\n readonly trade: TradeNamespace;\n readonly community: CommunityNamespace;\n readonly identitySecret: string | undefined;\n private readonly polling: boolean | PollOptions | undefined;\n private readonly proxy: string | undefined;\n private readonly profile: MobileProfile;\n\n constructor(options: SteamMobileOptions) {\n super();\n const profile = resolveMobileProfile(options.mobileProfile);\n this.profile = profile;\n this.proxy = options.proxy;\n this.http = new HttpClient({\n ...(options.proxy ? { proxy: options.proxy } : {}),\n profile,\n });\n this.session = new SessionManager(this.http, options.refreshToken);\n this.identitySecret = options.identitySecret;\n this.polling = options.polling;\n this.api = new WebApiClient(this.http, () => this.session.getAccessToken());\n this.confirmations = new ConfirmationManager(\n this.http,\n this.session.steamID,\n options.identitySecret,\n profile,\n );\n this.trade = new TradeNamespace(this.api, this.http, this.session, this.confirmations);\n this.community = new CommunityNamespace(this.http, this.session, this.confirmations, this.api);\n\n this.session.on(\"refreshToken\", (token) => this.emit(\"refreshToken\", token));\n this.session.on(\"sessionExpired\", (error) => this.emit(\"sessionExpired\", error));\n this.session.on(\"debug\", (message) => this.emit(\"debug\", message));\n this.trade.on(\"debug\", (message) => this.emit(\"debug\", message));\n this.trade.on(\"newOffer\", (o) => this.emit(\"newOffer\", o));\n this.trade.on(\"sentOfferChanged\", (o, s) => this.emit(\"sentOfferChanged\", o, s));\n this.trade.on(\"receivedOfferChanged\", (o, s) => this.emit(\"receivedOfferChanged\", o, s));\n this.trade.on(\"unknownOfferSent\", (o) => this.emit(\"unknownOfferSent\", o));\n this.trade.on(\"sentOfferCanceled\", (o, r) => this.emit(\"sentOfferCanceled\", o, r));\n this.trade.on(\"offerUpdate\", (u) => this.emit(\"offerUpdate\", u));\n this.trade.on(\"pollData\", (d) => this.emit(\"pollData\", d));\n this.trade.on(\"pollSuccess\", () => this.emit(\"pollSuccess\"));\n this.trade.on(\"pollFailure\", (e) => this.emit(\"pollFailure\", e));\n }\n\n async login(): Promise<this> {\n await this.session.getAccessToken();\n if (this.polling) {\n this.trade.startPolling(this.polling === true ? {} : this.polling);\n }\n return this;\n }\n\n async reauthenticate(credentials: ReauthenticateOptions): Promise<void> {\n const result = await loginWithCredentials({\n ...credentials,\n ...(this.proxy ? { proxy: this.proxy } : {}),\n mobileProfile: this.profile,\n });\n await this.session.setRefreshToken(result.refreshToken);\n }\n\n // Existing Web API key, or register one; null if the account is ineligible.\n ensureApiKey(domain?: string): Promise<string | null> {\n return this.community.ensureApiKey(domain);\n }\n\n // Log into a third-party site via \"Sign in through Steam\" (OpenID 2.0), spending this session.\n openidLogin(options: OpenidLoginOptions): Promise<OpenidLoginResult> {\n return this.community.openidLogin(options);\n }\n\n // Authenticated escape-hatch HTTP: ensures the session is live, then delegates to http.\n async request<T = string>(\n method: \"GET\" | \"POST\",\n url: string,\n opts?: RequestOptions,\n ): Promise<HttpResponse<T>> {\n await this.session.getAccessToken();\n return this.http.request<T>(method, url, opts);\n }\n\n get<T = string>(url: string, opts?: RequestOptions): Promise<HttpResponse<T>> {\n return this.request<T>(\"GET\", url, opts);\n }\n\n post<T = string>(url: string, opts?: RequestOptions): Promise<HttpResponse<T>> {\n return this.request<T>(\"POST\", url, opts);\n }\n\n get steamID(): SteamID {\n return this.session.steamID;\n }\n\n get accessToken(): string | undefined {\n return this.session.accessToken;\n }\n\n get refreshToken(): string {\n return this.session.refreshToken;\n }\n\n async shutdown(): Promise<void> {\n this.trade.stopPolling();\n this.trade.removeAllListeners();\n this.removeAllListeners();\n }\n}\n"],"mappings":";;;;;;;;;AAAA,MAAa,OAAO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AK,mBAAmB;CAC1B;AACF"}
|
|
1
|
+
{"version":3,"file":"index.mjs","names":["Buffer","headerValue","RsaReqSchema","RsaResSchema","BeginReqSchema","BeginResSchema","PollReqSchema","PollResSchema","GuardReqSchema","GuardResSchema","GetSessReqSchema","GetSessResSchema","RevokeReqSchema","RevokeResSchema","toUint8","Buffer","Buffer","Buffer","BROWSER_ACCEPT","steamTotpTime","SteamTotp.getDeviceID","SteamTotp.time","SteamTotp.getConfirmationKey","time","Buffer","Buffer","RequestSchema","ResponseSchema","fetchTradeStatus","fetchTradeHistory","fetchTradeOffersSummary"],"sources":["../src/core/constants.ts","../src/core/enums.ts","../src/core/eresults.ts","../src/core/errors.ts","../src/protobufs/steammessages_auth_pb.ts","../src/session/protoTransport.ts","../src/auth/AuthClient.ts","../src/crypto/rsa.ts","../src/crypto/steamTotp.ts","../src/auth/deviceDetails.ts","../src/auth/CredentialSession.ts","../src/core/mobileProfile.ts","../src/http/HttpClient.ts","../src/auth/loginWithCredentials.ts","../src/core/paginate.ts","../src/core/parseStrError.ts","../src/core/rateLimits.ts","../src/http/checkers.ts","../src/http/tradePageError.ts","../src/models/EconItem.ts","../src/community/openid.ts","../src/community/tradeProtection.ts","../src/community/CommunityNamespace.ts","../src/http/queryTime.ts","../src/community/confirmations.ts","../src/core/offerState.ts","../src/core/target.ts","../src/http/webApi.ts","../src/keyApi/SteamWebApi.ts","../src/protobufs/csgo_econ_preview_pb.ts","../src/models/inspect.ts","../src/session/tokens.ts","../src/session/SessionManager.ts","../src/community/userDetails.ts","../src/trade/exchange.ts","../src/trade/polling.ts","../src/trade/TradeOffer.ts","../src/trade/TradeNamespace.ts","../src/SteamMobile.ts"],"sourcesContent":["export const LANG = { l: \"english\", language: \"en\" } as const;\n\nexport const URLS = {\n community: \"https://steamcommunity.com\",\n store: \"https://store.steampowered.com\",\n help: \"https://help.steampowered.com\",\n api: \"https://api.steampowered.com\",\n} as const;\n\nexport const DEFAULT_CONTEXTID = \"2\";\n\nexport const ACCESS_TOKEN_RENEW_THRESHOLD_SECONDS = 300;\n// When the refresh token is within this window of expiry, mint with renew=true to rotate it\n// (the MobileApp self-renew path) so an active client's credential never lapses.\nexport const REFRESH_TOKEN_RENEW_THRESHOLD_SECONDS = 30 * 86_400;\n","export enum ETradeOfferState {\n Invalid = 1,\n Active = 2,\n Accepted = 3,\n Countered = 4,\n Expired = 5,\n Canceled = 6,\n Declined = 7,\n InvalidItems = 8,\n CreatedNeedsConfirmation = 9,\n CanceledBySecondFactor = 10,\n InEscrow = 11,\n /** Trade was reverted by the user (Trade protection update 2025) */\n Reverted = 12,\n}\n\nexport enum ETradeStatus {\n Init = 0,\n PreCommitted = 1,\n Committed = 2,\n Complete = 3,\n Failed = 4,\n PartialSupportRollback = 5,\n FullSupportRollback = 6,\n SupportRollback_Selective = 7,\n RollbackFailed = 8,\n RollbackAbandoned = 9,\n InEscrow = 10,\n EscrowRollback = 11,\n /** Trade was reverted by the user (Trade protection update 2025) */\n Reverted = 12,\n}\n\nexport enum EConfirmationMethod {\n None = 0,\n Email = 1,\n MobileApp = 2,\n}\n\nexport enum EConfirmationType {\n Invalid = 0,\n Generic = 1,\n Trade = 2,\n MarketListing = 3,\n FeatureOptOut = 4,\n PhoneNumberChange = 5,\n AccountRecovery = 6,\n}\n\nexport enum EOfferFilter {\n ActiveOnly = 1,\n HistoricalOnly = 2,\n All = 3,\n}\n\n// IAuthenticationService enums — clean public-API aliases of the generated wire enums (same values).\nexport enum EAuthTokenPlatformType {\n Unknown = 0,\n SteamClient = 1,\n WebBrowser = 2,\n MobileApp = 3,\n}\n\nexport enum ESessionPersistence {\n Invalid = -1,\n Ephemeral = 0,\n Persistent = 1,\n}\n\nexport enum EAuthSessionGuardType {\n Unknown = 0,\n None = 1,\n EmailCode = 2,\n DeviceCode = 3,\n DeviceConfirmation = 4,\n EmailConfirmation = 5,\n MachineToken = 6,\n LegacyMachineAuth = 7,\n}\n\nexport enum EAuthTokenRevokeAction {\n Logout = 0,\n Permanent = 1,\n Replaced = 2,\n Support = 3,\n Consume = 4,\n NonRememberedLogout = 5,\n NonRememberedPermanent = 6,\n Automatic = 7,\n}\n\nexport enum ETokenRenewalType {\n None = 0,\n Allow = 1,\n}\n\nexport enum EResult {\n Invalid = 0,\n OK = 1,\n Fail = 2,\n NoConnection = 3,\n InvalidPassword = 5,\n LoggedInElsewhere = 6,\n InvalidProtocolVer = 7,\n InvalidParam = 8,\n FileNotFound = 9,\n Busy = 10,\n InvalidState = 11,\n InvalidName = 12,\n InvalidEmail = 13,\n DuplicateName = 14,\n AccessDenied = 15,\n Timeout = 16,\n Banned = 17,\n AccountNotFound = 18,\n InvalidSteamID = 19,\n ServiceUnavailable = 20,\n NotLoggedOn = 21,\n Pending = 22,\n EncryptionFailure = 23,\n InsufficientPrivilege = 24,\n LimitExceeded = 25,\n Revoked = 26,\n Expired = 27,\n AlreadyRedeemed = 28,\n DuplicateRequest = 29,\n AlreadyOwned = 30,\n IPNotFound = 31,\n PersistFailed = 32,\n LockingFailed = 33,\n LogonSessionReplaced = 34,\n ConnectFailed = 35,\n HandshakeFailed = 36,\n IOFailure = 37,\n RemoteDisconnect = 38,\n ShoppingCartNotFound = 39,\n Blocked = 40,\n Ignored = 41,\n NoMatch = 42,\n AccountDisabled = 43,\n ServiceReadOnly = 44,\n AccountNotFeatured = 45,\n AdministratorOK = 46,\n ContentVersion = 47,\n TryAnotherCM = 48,\n PasswordRequiredToKickSession = 49,\n AlreadyLoggedInElsewhere = 50,\n Suspended = 51,\n Cancelled = 52,\n DataCorruption = 53,\n DiskFull = 54,\n RemoteCallFailed = 55,\n PasswordUnset = 56,\n ExternalAccountUnlinked = 57,\n PSNTicketInvalid = 58,\n ExternalAccountAlreadyLinked = 59,\n RemoteFileConflict = 60,\n IllegalPassword = 61,\n SameAsPreviousValue = 62,\n AccountLogonDenied = 63,\n CannotUseOldPassword = 64,\n InvalidLoginAuthCode = 65,\n AccountLogonDeniedNoMail = 66,\n HardwareNotCapableOfIPT = 67,\n IPTInitError = 68,\n ParentalControlRestricted = 69,\n FacebookQueryError = 70,\n ExpiredLoginAuthCode = 71,\n IPLoginRestrictionFailed = 72,\n AccountLockedDown = 73,\n AccountLogonDeniedVerifiedEmailRequired = 74,\n NoMatchingURL = 75,\n BadResponse = 76,\n RequirePasswordReEntry = 77,\n ValueOutOfRange = 78,\n UnexpectedError = 79,\n Disabled = 80,\n InvalidCEGSubmission = 81,\n RestrictedDevice = 82,\n RegionLocked = 83,\n RateLimitExceeded = 84,\n AccountLoginDeniedNeedTwoFactor = 85,\n ItemDeleted = 86,\n AccountLoginDeniedThrottle = 87,\n TwoFactorCodeMismatch = 88,\n TwoFactorActivationCodeMismatch = 89,\n AccountAssociatedToMultiplePartners = 90,\n NotModified = 91,\n NoMobileDevice = 92,\n TimeNotSynced = 93,\n SMSCodeFailed = 94,\n AccountLimitExceeded = 95,\n AccountActivityLimitExceeded = 96,\n PhoneActivityLimitExceeded = 97,\n RefundToWallet = 98,\n EmailSendFailure = 99,\n NotSettled = 100,\n NeedCaptcha = 101,\n GSLTDenied = 102,\n GSOwnerDenied = 103,\n InvalidItemType = 104,\n IPBanned = 105,\n GSLTExpired = 106,\n InsufficientFunds = 107,\n TooManyPending = 108,\n NoSiteLicensesFound = 109,\n WGNetworkSendExceeded = 110,\n AccountNotFriends = 111,\n LimitedUserAccount = 112,\n}\n","import { EResult } from \"./enums.js\";\n\nexport const TRANSIENT_ERESULTS: ReadonlySet<number> = new Set([\n EResult.ServiceUnavailable,\n EResult.Busy,\n EResult.Timeout,\n EResult.TryAnotherCM,\n EResult.RemoteCallFailed,\n]);\n\nexport function isTransientEResult(eresult: number | undefined): boolean {\n return eresult !== undefined && TRANSIENT_ERESULTS.has(eresult);\n}\n\n// Confirmed-dead-token eresults; anything else is treated as transient so a blip never re-bootstraps.\nexport const TERMINAL_AUTH_ERESULTS: ReadonlySet<number> = new Set([\n EResult.InvalidPassword,\n EResult.AccessDenied,\n EResult.Revoked,\n EResult.Expired,\n]);\n\nexport function isTerminalAuthEResult(eresult: number | undefined): boolean {\n return eresult !== undefined && TERMINAL_AUTH_ERESULTS.has(eresult);\n}\n","import { isTransientEResult } from \"./eresults.js\";\n\n// Fallback so every RateLimitError has a concrete unlockAt (Steam never sends Retry-After).\nexport const DEFAULT_RATE_LIMIT_RETRY_MS = 60_000;\n\nexport class SteamError extends Error {\n readonly eresult?: number;\n readonly body?: unknown;\n\n constructor(message: string, options?: { eresult?: number; body?: unknown; cause?: unknown }) {\n super(message, options?.cause !== undefined ? { cause: options.cause } : undefined);\n this.name = \"SteamError\";\n if (options?.eresult !== undefined) this.eresult = options.eresult;\n if (options?.body !== undefined) this.body = options.body;\n }\n}\n\nexport class ProxyError extends SteamError {\n constructor(message: string, options?: { cause?: unknown }) {\n super(message, options);\n this.name = \"ProxyError\";\n }\n}\n\nexport class HttpStatusError extends SteamError {\n readonly statusCode: number;\n\n constructor(statusCode: number, message?: string, body?: unknown) {\n super(message ?? `HTTP error ${statusCode}`, { body });\n this.name = \"HttpStatusError\";\n this.statusCode = statusCode;\n }\n}\n\nexport class SteamSessionExpiredError extends SteamError {\n constructor(message = \"Not Logged In\") {\n super(message);\n this.name = \"SteamSessionExpiredError\";\n }\n}\n\n// Steam OpenID relying-party login failed (no interstitial form, missing assertion redirect, etc.).\nexport class OpenIdError extends SteamError {\n constructor(message: string) {\n super(message);\n this.name = \"OpenIdError\";\n }\n}\n\nexport class RateLimitError extends SteamError {\n readonly statusCode: number | undefined;\n readonly retryAfterMs: number;\n readonly unlockAt: number;\n\n constructor(\n options: {\n message?: string;\n body?: unknown;\n retryAfterMs?: number;\n eresult?: number;\n statusCode?: number;\n } = {},\n ) {\n super(options.message ?? \"Rate limit exceeded\", {\n ...(options.eresult !== undefined ? { eresult: options.eresult } : {}),\n body: options.body,\n });\n this.name = \"RateLimitError\";\n this.statusCode = options.statusCode;\n this.retryAfterMs = options.retryAfterMs ?? DEFAULT_RATE_LIMIT_RETRY_MS;\n this.unlockAt = Date.now() + this.retryAfterMs;\n }\n}\n\nexport class EscrowError extends SteamError {\n readonly escrowDays: number;\n\n constructor(escrowDays: number, message?: string) {\n super(message ?? `Trade would be held in escrow for ${escrowDays} days`);\n this.name = \"EscrowError\";\n this.escrowDays = escrowDays;\n }\n}\n\nexport class TradeBanError extends SteamError {\n constructor(message = \"Trade ban\") {\n super(message);\n this.name = \"TradeBanError\";\n }\n}\n\nexport class OfferLimitError extends SteamError {\n constructor(message = \"Sent too many trade offers\") {\n super(message, { eresult: 25 });\n this.name = \"OfferLimitError\";\n }\n}\n\n// Steam blocks the action because we logged in from a new device recently.\nexport class NewDeviceError extends SteamError {\n constructor(message = \"You have logged in from a new device\", options?: { eresult?: number }) {\n super(message, options);\n this.name = \"NewDeviceError\";\n }\n}\n\n// Target account is not in a state where it can complete trades (limited, escrow-only, etc.).\nexport class TargetCannotTradeError extends SteamError {\n constructor(message = \"This user is not available to trade\", options?: { eresult?: number }) {\n super(message, options);\n this.name = \"TargetCannotTradeError\";\n }\n}\n\n// The game's item server (its Game Coordinator) is unreachable — transient, per-app, retry later.\nexport class ItemServerUnavailableError extends SteamError {\n constructor(\n message = \"Steam is currently unable to contact the game's item server\",\n options?: { eresult?: number },\n ) {\n super(message, { eresult: options?.eresult ?? 102 });\n this.name = \"ItemServerUnavailableError\";\n }\n}\n\nexport class ConfirmationError extends SteamError {\n constructor(message: string) {\n super(message);\n this.name = \"ConfirmationError\";\n }\n}\n\nexport class FamilyViewError extends SteamError {\n constructor(message = \"Family View Restricted\") {\n super(message);\n this.name = \"FamilyViewError\";\n }\n}\n\n// Partner/profile inventory is private (or friends-only and we're not friends).\n// A trade URL/token does NOT bypass inventory privacy — only inventory privacy does.\nexport class PrivateInventoryError extends SteamError {\n constructor(message = \"This profile's inventory is private.\") {\n super(message);\n this.name = \"PrivateInventoryError\";\n }\n}\n\n// Credential-login failures; carries Steam's extended_error_message when present.\nexport class LoginError extends SteamError {\n readonly extendedErrorMessage: string | undefined;\n readonly isTransient: boolean;\n\n constructor(\n message: string,\n options?: { eresult?: number; body?: unknown; extendedErrorMessage?: string },\n ) {\n super(message, options);\n this.name = \"LoginError\";\n this.extendedErrorMessage = options?.extendedErrorMessage;\n this.isTransient = isTransientEResult(options?.eresult);\n }\n}\n\n// sharedSecret was supplied but the account has no mobile authenticator attached, so TOTP can't\n// answer the guard challenge. Use steamGuardCode / onSteamGuardRequired with an email code instead.\nexport class NoMobileAuthenticatorError extends LoginError {\n constructor(\n message = \"account has no mobile authenticator attached; sharedSecret cannot be used (account uses email Steam Guard)\",\n ) {\n super(message);\n this.name = \"NoMobileAuthenticatorError\";\n }\n}\n","// @generated by protoc-gen-es v2.12.1 with parameter \"target=ts,import_extension=js\"\n// @generated from file steammessages_auth.proto (syntax proto2)\n/* eslint-disable */\n\nimport type { GenEnum, GenFile, GenMessage } from \"@bufbuild/protobuf/codegenv2\";\nimport { enumDesc, fileDesc, messageDesc } from \"@bufbuild/protobuf/codegenv2\";\nimport type { Message } from \"@bufbuild/protobuf\";\n\n/**\n * Describes the file steammessages_auth.proto.\n */\nexport const file_steammessages_auth: GenFile = /*@__PURE__*/\n fileDesc(\"ChhzdGVhbW1lc3NhZ2VzX2F1dGgucHJvdG8iRwovQ0F1dGhlbnRpY2F0aW9uX0dldFBhc3N3b3JkUlNBUHVibGljS2V5X1JlcXVlc3QSFAoMYWNjb3VudF9uYW1lGAEgASgJInMKMENBdXRoZW50aWNhdGlvbl9HZXRQYXNzd29yZFJTQVB1YmxpY0tleV9SZXNwb25zZRIVCg1wdWJsaWNrZXlfbW9kGAEgASgJEhUKDXB1YmxpY2tleV9leHAYAiABKAkSEQoJdGltZXN0YW1wGAMgASgEIqkCCh1DQXV0aGVudGljYXRpb25fRGV2aWNlRGV0YWlscxIcChRkZXZpY2VfZnJpZW5kbHlfbmFtZRgBIAEoCRJQCg1wbGF0Zm9ybV90eXBlGAIgASgOMhcuRUF1dGhUb2tlblBsYXRmb3JtVHlwZToga19FQXV0aFRva2VuUGxhdGZvcm1UeX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fChtrX0VBdXRoVG9rZW5SZXZva2VQZXJtYW5lbnQQARIeChprX0VBdXRoVG9rZW5SZXZva2VSZXBsYWNlZBACEh0KGWtfRUF1dGhUb2tlblJldm9rZVN1cHBvcnQQAxIdChlrX0VBdXRoVG9rZW5SZXZva2VDb25zdW1lEAQSKQola19FQXV0aFRva2VuUmV2b2tlTm9uUmVtZW1iZXJlZExvZ291dBAFEiwKKGtfRUF1dGhUb2tlblJldm9rZU5vblJlbWVtYmVyZWRQZXJtYW5lbnQQBhIfChtrX0VBdXRoVG9rZW5SZXZva2VBdXRvbWF0aWMQByqMAQoTRVNlc3Npb25QZXJzaXN0ZW5jZRIqCh1rX0VTZXNzaW9uUGVyc2lzdGVuY2VfSW52YWxpZBD///////////8BEiMKH2tfRVNlc3Npb25QZXJzaXN0ZW5jZV9FcGhlbWVyYWwQABIkCiBrX0VTZXNzaW9uUGVyc2lzdGVuY2VfUGVyc2lzdGVudBAB\");\n\n/**\n * @generated from message CAuthentication_GetPasswordRSAPublicKey_Request\n */\nexport type CAuthentication_GetPasswordRSAPublicKey_Request = Message<\"CAuthentication_GetPasswordRSAPublicKey_Request\"> & {\n /**\n * @generated from field: optional string account_name = 1;\n */\n accountName: string;\n};\n\n/**\n * Describes the message CAuthentication_GetPasswordRSAPublicKey_Request.\n * Use `create(CAuthentication_GetPasswordRSAPublicKey_RequestSchema)` to create a new message.\n */\nexport const CAuthentication_GetPasswordRSAPublicKey_RequestSchema: GenMessage<CAuthentication_GetPasswordRSAPublicKey_Request> = /*@__PURE__*/\n messageDesc(file_steammessages_auth, 0);\n\n/**\n * @generated from message CAuthentication_GetPasswordRSAPublicKey_Response\n */\nexport type CAuthentication_GetPasswordRSAPublicKey_Response = Message<\"CAuthentication_GetPasswordRSAPublicKey_Response\"> & {\n /**\n * @generated from field: optional string publickey_mod = 1;\n */\n publickeyMod: string;\n\n /**\n * @generated from field: optional string publickey_exp = 2;\n */\n publickeyExp: string;\n\n /**\n * @generated from field: optional uint64 timestamp = 3;\n */\n timestamp: bigint;\n};\n\n/**\n * Describes the message CAuthentication_GetPasswordRSAPublicKey_Response.\n * Use `create(CAuthentication_GetPasswordRSAPublicKey_ResponseSchema)` to create a new message.\n */\nexport const CAuthentication_GetPasswordRSAPublicKey_ResponseSchema: GenMessage<CAuthentication_GetPasswordRSAPublicKey_Response> = /*@__PURE__*/\n messageDesc(file_steammessages_auth, 1);\n\n/**\n * @generated from message CAuthentication_DeviceDetails\n */\nexport type CAuthentication_DeviceDetails = Message<\"CAuthentication_DeviceDetails\"> & {\n /**\n * @generated from field: optional string device_friendly_name = 1;\n */\n deviceFriendlyName: string;\n\n /**\n * @generated from field: optional EAuthTokenPlatformType platform_type = 2 [default = k_EAuthTokenPlatformType_Unknown];\n */\n platformType: EAuthTokenPlatformType;\n\n /**\n * @generated from field: optional int32 os_type = 3;\n */\n osType: number;\n\n /**\n * @generated from field: optional uint32 gaming_device_type = 4;\n */\n gamingDeviceType: number;\n\n /**\n * @generated from field: optional uint32 client_count = 5;\n */\n clientCount: number;\n\n /**\n * @generated from field: optional bytes machine_id = 6;\n */\n machineId: Uint8Array;\n\n /**\n * @generated from field: optional EAuthTokenAppType app_type = 7 [default = k_EAuthTokenAppType_Unknown];\n */\n appType: EAuthTokenAppType;\n};\n\n/**\n * Describes the message CAuthentication_DeviceDetails.\n * Use `create(CAuthentication_DeviceDetailsSchema)` to create a new message.\n */\nexport const CAuthentication_DeviceDetailsSchema: GenMessage<CAuthentication_DeviceDetails> = /*@__PURE__*/\n messageDesc(file_steammessages_auth, 2);\n\n/**\n * @generated from message CAuthentication_AllowedConfirmation\n */\nexport type CAuthentication_AllowedConfirmation = Message<\"CAuthentication_AllowedConfirmation\"> & {\n /**\n * @generated from field: optional EAuthSessionGuardType confirmation_type = 1 [default = k_EAuthSessionGuardType_Unknown];\n */\n confirmationType: EAuthSessionGuardType;\n\n /**\n * @generated from field: optional string associated_message = 2;\n */\n associatedMessage: string;\n};\n\n/**\n * Describes the message CAuthentication_AllowedConfirmation.\n * Use `create(CAuthentication_AllowedConfirmationSchema)` to create a new message.\n */\nexport const CAuthentication_AllowedConfirmationSchema: GenMessage<CAuthentication_AllowedConfirmation> = /*@__PURE__*/\n messageDesc(file_steammessages_auth, 3);\n\n/**\n * @generated from message CAuthentication_BeginAuthSessionViaCredentials_Request\n */\nexport type CAuthentication_BeginAuthSessionViaCredentials_Request = Message<\"CAuthentication_BeginAuthSessionViaCredentials_Request\"> & {\n /**\n * @generated from field: optional string device_friendly_name = 1;\n */\n deviceFriendlyName: string;\n\n /**\n * @generated from field: optional string account_name = 2;\n */\n accountName: string;\n\n /**\n * @generated from field: optional string encrypted_password = 3;\n */\n encryptedPassword: string;\n\n /**\n * @generated from field: optional uint64 encryption_timestamp = 4;\n */\n encryptionTimestamp: bigint;\n\n /**\n * @generated from field: optional bool remember_login = 5;\n */\n rememberLogin: boolean;\n\n /**\n * @generated from field: optional EAuthTokenPlatformType platform_type = 6 [default = k_EAuthTokenPlatformType_Unknown];\n */\n platformType: EAuthTokenPlatformType;\n\n /**\n * @generated from field: optional ESessionPersistence persistence = 7 [default = k_ESessionPersistence_Persistent];\n */\n persistence: ESessionPersistence;\n\n /**\n * @generated from field: optional string website_id = 8 [default = \"Unknown\"];\n */\n websiteId: string;\n\n /**\n * @generated from field: optional CAuthentication_DeviceDetails device_details = 9;\n */\n deviceDetails?: CAuthentication_DeviceDetails | undefined;\n\n /**\n * @generated from field: optional string guard_data = 10;\n */\n guardData: string;\n\n /**\n * @generated from field: optional uint32 language = 11;\n */\n language: number;\n\n /**\n * @generated from field: optional int32 qos_level = 12 [default = 2];\n */\n qosLevel: number;\n};\n\n/**\n * Describes the message CAuthentication_BeginAuthSessionViaCredentials_Request.\n * Use `create(CAuthentication_BeginAuthSessionViaCredentials_RequestSchema)` to create a new message.\n */\nexport const CAuthentication_BeginAuthSessionViaCredentials_RequestSchema: GenMessage<CAuthentication_BeginAuthSessionViaCredentials_Request> = /*@__PURE__*/\n messageDesc(file_steammessages_auth, 4);\n\n/**\n * @generated from message CAuthentication_BeginAuthSessionViaCredentials_Response\n */\nexport type CAuthentication_BeginAuthSessionViaCredentials_Response = Message<\"CAuthentication_BeginAuthSessionViaCredentials_Response\"> & {\n /**\n * @generated from field: optional uint64 client_id = 1;\n */\n clientId: bigint;\n\n /**\n * @generated from field: optional bytes request_id = 2;\n */\n requestId: Uint8Array;\n\n /**\n * @generated from field: optional float interval = 3;\n */\n interval: number;\n\n /**\n * @generated from field: repeated CAuthentication_AllowedConfirmation allowed_confirmations = 4;\n */\n allowedConfirmations: CAuthentication_AllowedConfirmation[];\n\n /**\n * @generated from field: optional uint64 steamid = 5;\n */\n steamid: bigint;\n\n /**\n * @generated from field: optional string weak_token = 6;\n */\n weakToken: string;\n\n /**\n * @generated from field: optional string agreement_session_url = 7;\n */\n agreementSessionUrl: string;\n\n /**\n * @generated from field: optional string extended_error_message = 8;\n */\n extendedErrorMessage: string;\n};\n\n/**\n * Describes the message CAuthentication_BeginAuthSessionViaCredentials_Response.\n * Use `create(CAuthentication_BeginAuthSessionViaCredentials_ResponseSchema)` to create a new message.\n */\nexport const CAuthentication_BeginAuthSessionViaCredentials_ResponseSchema: GenMessage<CAuthentication_BeginAuthSessionViaCredentials_Response> = /*@__PURE__*/\n messageDesc(file_steammessages_auth, 5);\n\n/**\n * @generated from message CAuthentication_PollAuthSessionStatus_Request\n */\nexport type CAuthentication_PollAuthSessionStatus_Request = Message<\"CAuthentication_PollAuthSessionStatus_Request\"> & {\n /**\n * @generated from field: optional uint64 client_id = 1;\n */\n clientId: bigint;\n\n /**\n * @generated from field: optional bytes request_id = 2;\n */\n requestId: Uint8Array;\n\n /**\n * @generated from field: optional fixed64 token_to_revoke = 3;\n */\n tokenToRevoke: bigint;\n};\n\n/**\n * Describes the message CAuthentication_PollAuthSessionStatus_Request.\n * Use `create(CAuthentication_PollAuthSessionStatus_RequestSchema)` to create a new message.\n */\nexport const CAuthentication_PollAuthSessionStatus_RequestSchema: GenMessage<CAuthentication_PollAuthSessionStatus_Request> = /*@__PURE__*/\n messageDesc(file_steammessages_auth, 6);\n\n/**\n * @generated from message CAuthentication_PollAuthSessionStatus_Response\n */\nexport type CAuthentication_PollAuthSessionStatus_Response = Message<\"CAuthentication_PollAuthSessionStatus_Response\"> & {\n /**\n * @generated from field: optional uint64 new_client_id = 1;\n */\n newClientId: bigint;\n\n /**\n * @generated from field: optional string new_challenge_url = 2;\n */\n newChallengeUrl: string;\n\n /**\n * @generated from field: optional string refresh_token = 3;\n */\n refreshToken: string;\n\n /**\n * @generated from field: optional string access_token = 4;\n */\n accessToken: string;\n\n /**\n * @generated from field: optional bool had_remote_interaction = 5;\n */\n hadRemoteInteraction: boolean;\n\n /**\n * @generated from field: optional string account_name = 6;\n */\n accountName: string;\n\n /**\n * @generated from field: optional string new_guard_data = 7;\n */\n newGuardData: string;\n\n /**\n * @generated from field: optional string agreement_session_url = 8;\n */\n agreementSessionUrl: string;\n};\n\n/**\n * Describes the message CAuthentication_PollAuthSessionStatus_Response.\n * Use `create(CAuthentication_PollAuthSessionStatus_ResponseSchema)` to create a new message.\n */\nexport const CAuthentication_PollAuthSessionStatus_ResponseSchema: GenMessage<CAuthentication_PollAuthSessionStatus_Response> = /*@__PURE__*/\n messageDesc(file_steammessages_auth, 7);\n\n/**\n * @generated from message CAuthentication_UpdateAuthSessionWithSteamGuardCode_Request\n */\nexport type CAuthentication_UpdateAuthSessionWithSteamGuardCode_Request = Message<\"CAuthentication_UpdateAuthSessionWithSteamGuardCode_Request\"> & {\n /**\n * @generated from field: optional uint64 client_id = 1;\n */\n clientId: bigint;\n\n /**\n * @generated from field: optional fixed64 steamid = 2;\n */\n steamid: bigint;\n\n /**\n * @generated from field: optional string code = 3;\n */\n code: string;\n\n /**\n * @generated from field: optional EAuthSessionGuardType code_type = 4 [default = k_EAuthSessionGuardType_Unknown];\n */\n codeType: EAuthSessionGuardType;\n};\n\n/**\n * Describes the message CAuthentication_UpdateAuthSessionWithSteamGuardCode_Request.\n * Use `create(CAuthentication_UpdateAuthSessionWithSteamGuardCode_RequestSchema)` to create a new message.\n */\nexport const CAuthentication_UpdateAuthSessionWithSteamGuardCode_RequestSchema: GenMessage<CAuthentication_UpdateAuthSessionWithSteamGuardCode_Request> = /*@__PURE__*/\n messageDesc(file_steammessages_auth, 8);\n\n/**\n * @generated from message CAuthentication_UpdateAuthSessionWithSteamGuardCode_Response\n */\nexport type CAuthentication_UpdateAuthSessionWithSteamGuardCode_Response = Message<\"CAuthentication_UpdateAuthSessionWithSteamGuardCode_Response\"> & {\n /**\n * @generated from field: optional string agreement_session_url = 7;\n */\n agreementSessionUrl: string;\n};\n\n/**\n * Describes the message CAuthentication_UpdateAuthSessionWithSteamGuardCode_Response.\n * Use `create(CAuthentication_UpdateAuthSessionWithSteamGuardCode_ResponseSchema)` to create a new message.\n */\nexport const CAuthentication_UpdateAuthSessionWithSteamGuardCode_ResponseSchema: GenMessage<CAuthentication_UpdateAuthSessionWithSteamGuardCode_Response> = /*@__PURE__*/\n messageDesc(file_steammessages_auth, 9);\n\n/**\n * @generated from message CAuthentication_AccessToken_GenerateForApp_Request\n */\nexport type CAuthentication_AccessToken_GenerateForApp_Request = Message<\"CAuthentication_AccessToken_GenerateForApp_Request\"> & {\n /**\n * @generated from field: optional string refresh_token = 1;\n */\n refreshToken: string;\n\n /**\n * @generated from field: optional fixed64 steamid = 2;\n */\n steamid: bigint;\n\n /**\n * @generated from field: optional ETokenRenewalType renewal_type = 3 [default = k_ETokenRenewalType_None];\n */\n renewalType: ETokenRenewalType;\n};\n\n/**\n * Describes the message CAuthentication_AccessToken_GenerateForApp_Request.\n * Use `create(CAuthentication_AccessToken_GenerateForApp_RequestSchema)` to create a new message.\n */\nexport const CAuthentication_AccessToken_GenerateForApp_RequestSchema: GenMessage<CAuthentication_AccessToken_GenerateForApp_Request> = /*@__PURE__*/\n messageDesc(file_steammessages_auth, 10);\n\n/**\n * @generated from message CAuthentication_AccessToken_GenerateForApp_Response\n */\nexport type CAuthentication_AccessToken_GenerateForApp_Response = Message<\"CAuthentication_AccessToken_GenerateForApp_Response\"> & {\n /**\n * @generated from field: optional string access_token = 1;\n */\n accessToken: string;\n\n /**\n * @generated from field: optional string refresh_token = 2;\n */\n refreshToken: string;\n};\n\n/**\n * Describes the message CAuthentication_AccessToken_GenerateForApp_Response.\n * Use `create(CAuthentication_AccessToken_GenerateForApp_ResponseSchema)` to create a new message.\n */\nexport const CAuthentication_AccessToken_GenerateForApp_ResponseSchema: GenMessage<CAuthentication_AccessToken_GenerateForApp_Response> = /*@__PURE__*/\n messageDesc(file_steammessages_auth, 11);\n\n/**\n * @generated from message CAuthentication_GetAuthSessionsForAccount_Request\n */\nexport type CAuthentication_GetAuthSessionsForAccount_Request = Message<\"CAuthentication_GetAuthSessionsForAccount_Request\"> & {\n};\n\n/**\n * Describes the message CAuthentication_GetAuthSessionsForAccount_Request.\n * Use `create(CAuthentication_GetAuthSessionsForAccount_RequestSchema)` to create a new message.\n */\nexport const CAuthentication_GetAuthSessionsForAccount_RequestSchema: GenMessage<CAuthentication_GetAuthSessionsForAccount_Request> = /*@__PURE__*/\n messageDesc(file_steammessages_auth, 12);\n\n/**\n * @generated from message CAuthentication_GetAuthSessionsForAccount_Response\n */\nexport type CAuthentication_GetAuthSessionsForAccount_Response = Message<\"CAuthentication_GetAuthSessionsForAccount_Response\"> & {\n /**\n * @generated from field: repeated uint64 client_ids = 1;\n */\n clientIds: bigint[];\n};\n\n/**\n * Describes the message CAuthentication_GetAuthSessionsForAccount_Response.\n * Use `create(CAuthentication_GetAuthSessionsForAccount_ResponseSchema)` to create a new message.\n */\nexport const CAuthentication_GetAuthSessionsForAccount_ResponseSchema: GenMessage<CAuthentication_GetAuthSessionsForAccount_Response> = /*@__PURE__*/\n messageDesc(file_steammessages_auth, 13);\n\n/**\n * @generated from message CAuthentication_RefreshToken_Revoke_Request\n */\nexport type CAuthentication_RefreshToken_Revoke_Request = Message<\"CAuthentication_RefreshToken_Revoke_Request\"> & {\n /**\n * @generated from field: optional fixed64 token_id = 1;\n */\n tokenId: bigint;\n\n /**\n * @generated from field: optional fixed64 steamid = 2;\n */\n steamid: bigint;\n\n /**\n * @generated from field: optional EAuthTokenRevokeAction revoke_action = 3 [default = k_EAuthTokenRevokePermanent];\n */\n revokeAction: EAuthTokenRevokeAction;\n\n /**\n * @generated from field: optional bytes signature = 4;\n */\n signature: Uint8Array;\n};\n\n/**\n * Describes the message CAuthentication_RefreshToken_Revoke_Request.\n * Use `create(CAuthentication_RefreshToken_Revoke_RequestSchema)` to create a new message.\n */\nexport const CAuthentication_RefreshToken_Revoke_RequestSchema: GenMessage<CAuthentication_RefreshToken_Revoke_Request> = /*@__PURE__*/\n messageDesc(file_steammessages_auth, 14);\n\n/**\n * @generated from message CAuthentication_RefreshToken_Revoke_Response\n */\nexport type CAuthentication_RefreshToken_Revoke_Response = Message<\"CAuthentication_RefreshToken_Revoke_Response\"> & {\n};\n\n/**\n * Describes the message CAuthentication_RefreshToken_Revoke_Response.\n * Use `create(CAuthentication_RefreshToken_Revoke_ResponseSchema)` to create a new message.\n */\nexport const CAuthentication_RefreshToken_Revoke_ResponseSchema: GenMessage<CAuthentication_RefreshToken_Revoke_Response> = /*@__PURE__*/\n messageDesc(file_steammessages_auth, 15);\n\n/**\n * @generated from enum EAuthTokenPlatformType\n */\nexport enum EAuthTokenPlatformType {\n /**\n * @generated from enum value: k_EAuthTokenPlatformType_Unknown = 0;\n */\n k_EAuthTokenPlatformType_Unknown = 0,\n\n /**\n * @generated from enum value: k_EAuthTokenPlatformType_SteamClient = 1;\n */\n k_EAuthTokenPlatformType_SteamClient = 1,\n\n /**\n * @generated from enum value: k_EAuthTokenPlatformType_WebBrowser = 2;\n */\n k_EAuthTokenPlatformType_WebBrowser = 2,\n\n /**\n * @generated from enum value: k_EAuthTokenPlatformType_MobileApp = 3;\n */\n k_EAuthTokenPlatformType_MobileApp = 3,\n}\n\n/**\n * Describes the enum EAuthTokenPlatformType.\n */\nexport const EAuthTokenPlatformTypeSchema: GenEnum<EAuthTokenPlatformType> = /*@__PURE__*/\n enumDesc(file_steammessages_auth, 0);\n\n/**\n * @generated from enum EAuthTokenAppType\n */\nexport enum EAuthTokenAppType {\n /**\n * @generated from enum value: k_EAuthTokenAppType_Unknown = 0;\n */\n k_EAuthTokenAppType_Unknown = 0,\n\n /**\n * @generated from enum value: k_EAuthTokenAppType_Mobile_SteamApp = 1;\n */\n k_EAuthTokenAppType_Mobile_SteamApp = 1,\n\n /**\n * @generated from enum value: k_EAuthTokenAppType_Mobile_ChatApp = 2;\n */\n k_EAuthTokenAppType_Mobile_ChatApp = 2,\n}\n\n/**\n * Describes the enum EAuthTokenAppType.\n */\nexport const EAuthTokenAppTypeSchema: GenEnum<EAuthTokenAppType> = /*@__PURE__*/\n enumDesc(file_steammessages_auth, 1);\n\n/**\n * @generated from enum EAuthSessionGuardType\n */\nexport enum EAuthSessionGuardType {\n /**\n * @generated from enum value: k_EAuthSessionGuardType_Unknown = 0;\n */\n k_EAuthSessionGuardType_Unknown = 0,\n\n /**\n * @generated from enum value: k_EAuthSessionGuardType_None = 1;\n */\n k_EAuthSessionGuardType_None = 1,\n\n /**\n * @generated from enum value: k_EAuthSessionGuardType_EmailCode = 2;\n */\n k_EAuthSessionGuardType_EmailCode = 2,\n\n /**\n * @generated from enum value: k_EAuthSessionGuardType_DeviceCode = 3;\n */\n k_EAuthSessionGuardType_DeviceCode = 3,\n\n /**\n * @generated from enum value: k_EAuthSessionGuardType_DeviceConfirmation = 4;\n */\n k_EAuthSessionGuardType_DeviceConfirmation = 4,\n\n /**\n * @generated from enum value: k_EAuthSessionGuardType_EmailConfirmation = 5;\n */\n k_EAuthSessionGuardType_EmailConfirmation = 5,\n\n /**\n * @generated from enum value: k_EAuthSessionGuardType_MachineToken = 6;\n */\n k_EAuthSessionGuardType_MachineToken = 6,\n\n /**\n * @generated from enum value: k_EAuthSessionGuardType_LegacyMachineAuth = 7;\n */\n k_EAuthSessionGuardType_LegacyMachineAuth = 7,\n}\n\n/**\n * Describes the enum EAuthSessionGuardType.\n */\nexport const EAuthSessionGuardTypeSchema: GenEnum<EAuthSessionGuardType> = /*@__PURE__*/\n enumDesc(file_steammessages_auth, 2);\n\n/**\n * @generated from enum ETokenRenewalType\n */\nexport enum ETokenRenewalType {\n /**\n * @generated from enum value: k_ETokenRenewalType_None = 0;\n */\n k_ETokenRenewalType_None = 0,\n\n /**\n * @generated from enum value: k_ETokenRenewalType_Allow = 1;\n */\n k_ETokenRenewalType_Allow = 1,\n}\n\n/**\n * Describes the enum ETokenRenewalType.\n */\nexport const ETokenRenewalTypeSchema: GenEnum<ETokenRenewalType> = /*@__PURE__*/\n enumDesc(file_steammessages_auth, 3);\n\n/**\n * @generated from enum EAuthTokenRevokeAction\n */\nexport enum EAuthTokenRevokeAction {\n /**\n * @generated from enum value: k_EAuthTokenRevokeLogout = 0;\n */\n k_EAuthTokenRevokeLogout = 0,\n\n /**\n * @generated from enum value: k_EAuthTokenRevokePermanent = 1;\n */\n k_EAuthTokenRevokePermanent = 1,\n\n /**\n * @generated from enum value: k_EAuthTokenRevokeReplaced = 2;\n */\n k_EAuthTokenRevokeReplaced = 2,\n\n /**\n * @generated from enum value: k_EAuthTokenRevokeSupport = 3;\n */\n k_EAuthTokenRevokeSupport = 3,\n\n /**\n * @generated from enum value: k_EAuthTokenRevokeConsume = 4;\n */\n k_EAuthTokenRevokeConsume = 4,\n\n /**\n * @generated from enum value: k_EAuthTokenRevokeNonRememberedLogout = 5;\n */\n k_EAuthTokenRevokeNonRememberedLogout = 5,\n\n /**\n * @generated from enum value: k_EAuthTokenRevokeNonRememberedPermanent = 6;\n */\n k_EAuthTokenRevokeNonRememberedPermanent = 6,\n\n /**\n * @generated from enum value: k_EAuthTokenRevokeAutomatic = 7;\n */\n k_EAuthTokenRevokeAutomatic = 7,\n}\n\n/**\n * Describes the enum EAuthTokenRevokeAction.\n */\nexport const EAuthTokenRevokeActionSchema: GenEnum<EAuthTokenRevokeAction> = /*@__PURE__*/\n enumDesc(file_steammessages_auth, 4);\n\n/**\n * @generated from enum ESessionPersistence\n */\nexport enum ESessionPersistence {\n /**\n * @generated from enum value: k_ESessionPersistence_Invalid = -1;\n */\n k_ESessionPersistence_Invalid = -1,\n\n /**\n * @generated from enum value: k_ESessionPersistence_Ephemeral = 0;\n */\n k_ESessionPersistence_Ephemeral = 0,\n\n /**\n * @generated from enum value: k_ESessionPersistence_Persistent = 1;\n */\n k_ESessionPersistence_Persistent = 1,\n}\n\n/**\n * Describes the enum ESessionPersistence.\n */\nexport const ESessionPersistenceSchema: GenEnum<ESessionPersistence> = /*@__PURE__*/\n enumDesc(file_steammessages_auth, 5);\n\n","import { Buffer } from \"node:buffer\";\nimport type { HttpClient, HttpResponse } from \"../http/HttpClient.js\";\n\nexport interface ProtoResult {\n status: number;\n eresult: string | null;\n errorMessage: string | null;\n body: Buffer | Uint8Array;\n}\n\nexport interface ProtoRequest {\n url: string;\n method: \"GET\" | \"POST\";\n body?: Uint8Array;\n accessToken?: string;\n multipart?: boolean;\n origin?: boolean;\n spoofSteamid?: string;\n}\n\nexport type ProtoTransport = (req: ProtoRequest) => Promise<ProtoResult>;\n\nexport type ProtoPost = (\n url: string,\n base64Body: string,\n accessToken?: string,\n) => Promise<ProtoResult>;\n\nexport function createProtoTransport(http: HttpClient): ProtoTransport {\n return async (req) => {\n const base64 = req.body && req.body.length > 0 ? Buffer.from(req.body).toString(\"base64\") : \"\";\n const searchParams: Record<string, string> = {};\n if (req.accessToken) {\n searchParams.access_token = req.accessToken;\n searchParams.spoof_steamid = req.spoofSteamid ?? \"\";\n }\n if (req.origin) searchParams.origin = \"SteamMobile\";\n\n let res: HttpResponse<Buffer | Uint8Array>;\n if (req.method === \"GET\") {\n // Must be present even when empty, or Steam replies in JSON instead of protobuf.\n searchParams.input_protobuf_encoded = base64;\n res = await http.get<Buffer | Uint8Array>(req.url, { responseType: \"buffer\", searchParams });\n } else {\n const bodyOpt = req.multipart\n ? { multipart: [{ name: \"input_protobuf_encoded\", value: base64 }] }\n : { form: { input_protobuf_encoded: base64 } };\n res = await http.post<Buffer | Uint8Array>(req.url, {\n responseType: \"buffer\",\n ...(Object.keys(searchParams).length > 0 ? { searchParams } : {}),\n ...bodyOpt,\n });\n }\n\n return {\n status: res.statusCode,\n eresult: headerValue(res.headers[\"x-eresult\"]) ?? null,\n errorMessage: headerValue(res.headers[\"x-error_message\"]) ?? null,\n body: res.body,\n };\n };\n}\n\n// The mint keeps its urlencoded-form POST shape.\nexport function createProtoPost(http: HttpClient): ProtoPost {\n const transport = createProtoTransport(http);\n return (url, base64Body, accessToken) =>\n transport({\n url,\n method: \"POST\",\n body: Buffer.from(base64Body, \"base64\"),\n ...(accessToken ? { accessToken } : {}),\n });\n}\n\nfunction headerValue(v: string | string[] | undefined): string | undefined {\n return Array.isArray(v) ? v[0] : v;\n}\n","import { Buffer } from \"node:buffer\";\nimport {\n create,\n fromBinary,\n type MessageInitShape,\n type MessageShape,\n toBinary,\n} from \"@bufbuild/protobuf\";\nimport { URLS } from \"../core/constants.js\";\nimport { EResult } from \"../core/enums.js\";\nimport { LoginError, RateLimitError } from \"../core/errors.js\";\nimport type { HttpClient } from \"../http/HttpClient.js\";\nimport {\n CAuthentication_BeginAuthSessionViaCredentials_RequestSchema as BeginReqSchema,\n CAuthentication_BeginAuthSessionViaCredentials_ResponseSchema as BeginResSchema,\n type CAuthentication_BeginAuthSessionViaCredentials_RequestSchema,\n type EAuthSessionGuardType,\n type EAuthTokenRevokeAction,\n CAuthentication_GetAuthSessionsForAccount_RequestSchema as GetSessReqSchema,\n CAuthentication_GetAuthSessionsForAccount_ResponseSchema as GetSessResSchema,\n CAuthentication_UpdateAuthSessionWithSteamGuardCode_RequestSchema as GuardReqSchema,\n CAuthentication_UpdateAuthSessionWithSteamGuardCode_ResponseSchema as GuardResSchema,\n CAuthentication_PollAuthSessionStatus_RequestSchema as PollReqSchema,\n CAuthentication_PollAuthSessionStatus_ResponseSchema as PollResSchema,\n CAuthentication_RefreshToken_Revoke_RequestSchema as RevokeReqSchema,\n CAuthentication_RefreshToken_Revoke_ResponseSchema as RevokeResSchema,\n CAuthentication_GetPasswordRSAPublicKey_RequestSchema as RsaReqSchema,\n CAuthentication_GetPasswordRSAPublicKey_ResponseSchema as RsaResSchema,\n} from \"../protobufs/steammessages_auth_pb.js\";\nimport {\n createProtoTransport,\n type ProtoResult,\n type ProtoTransport,\n} from \"../session/protoTransport.js\";\n\ntype BeginRequest = MessageInitShape<\n typeof CAuthentication_BeginAuthSessionViaCredentials_RequestSchema\n>;\n\ninterface SendOptions {\n apiMethod: string;\n method: \"GET\" | \"POST\";\n body?: Uint8Array;\n accessToken?: string;\n origin?: boolean;\n multipart?: boolean;\n}\n\n// Stateless 1:1 wrappers over the IAuthenticationService protobuf RPCs (the mint lives in tokens.ts).\nexport class AuthClient {\n private readonly transport: ProtoTransport;\n\n constructor(http: HttpClient) {\n this.transport = createProtoTransport(http);\n }\n\n async getPasswordRSAPublicKey(accountName: string): Promise<MessageShape<typeof RsaResSchema>> {\n const body = toBinary(RsaReqSchema, create(RsaReqSchema, { accountName }));\n const out = await this.send({\n apiMethod: \"GetPasswordRSAPublicKey\",\n method: \"GET\",\n body,\n origin: true,\n });\n return fromBinary(RsaResSchema, out);\n }\n\n async beginAuthSessionViaCredentials(\n req: BeginRequest,\n ): Promise<MessageShape<typeof BeginResSchema>> {\n const body = toBinary(BeginReqSchema, create(BeginReqSchema, req));\n const out = await this.send({\n apiMethod: \"BeginAuthSessionViaCredentials\",\n method: \"POST\",\n body,\n multipart: true,\n });\n return fromBinary(BeginResSchema, out);\n }\n\n async pollAuthSessionStatus(\n clientId: bigint,\n requestId: Uint8Array,\n ): Promise<MessageShape<typeof PollResSchema>> {\n const body = toBinary(PollReqSchema, create(PollReqSchema, { clientId, requestId }));\n const out = await this.send({\n apiMethod: \"PollAuthSessionStatus\",\n method: \"POST\",\n body,\n multipart: true,\n });\n return fromBinary(PollResSchema, out);\n }\n\n async updateAuthSessionWithSteamGuardCode(\n clientId: bigint,\n steamid: bigint,\n code: string,\n codeType: number,\n ): Promise<MessageShape<typeof GuardResSchema>> {\n const body = toBinary(\n GuardReqSchema,\n create(GuardReqSchema, {\n clientId,\n steamid,\n code,\n codeType: codeType as EAuthSessionGuardType,\n }),\n );\n const out = await this.send({\n apiMethod: \"UpdateAuthSessionWithSteamGuardCode\",\n method: \"POST\",\n body,\n multipart: true,\n });\n return fromBinary(GuardResSchema, out);\n }\n\n // In-progress auth sessions (login-approval flows), not a device list. GET-only (POST → 405).\n async getAuthSessionsForAccount(\n accessToken: string,\n ): Promise<MessageShape<typeof GetSessResSchema>> {\n const body = toBinary(GetSessReqSchema, create(GetSessReqSchema, {}));\n const out = await this.send({\n apiMethod: \"GetAuthSessionsForAccount\",\n method: \"GET\",\n body,\n accessToken,\n origin: true,\n });\n return fromBinary(GetSessResSchema, out);\n }\n\n // Self-revoke (logout): the query access_token identifies the token; no signature needed.\n async revokeRefreshToken(\n accessToken: string,\n revokeAction: number,\n ): Promise<MessageShape<typeof RevokeResSchema>> {\n const body = toBinary(\n RevokeReqSchema,\n create(RevokeReqSchema, { revokeAction: revokeAction as EAuthTokenRevokeAction }),\n );\n const out = await this.send({\n apiMethod: \"RevokeRefreshToken\",\n method: \"POST\",\n body,\n accessToken,\n multipart: true,\n });\n return fromBinary(RevokeResSchema, out);\n }\n\n private async send(opts: SendOptions): Promise<Uint8Array> {\n const url = `${URLS.api}/IAuthenticationService/${opts.apiMethod}/v1`;\n const res = await this.transport({\n url,\n method: opts.method,\n ...(opts.body ? { body: opts.body } : {}),\n ...(opts.accessToken ? { accessToken: opts.accessToken } : {}),\n ...(opts.origin ? { origin: true } : {}),\n ...(opts.multipart ? { multipart: true } : {}),\n });\n ensureOk(res, opts.apiMethod);\n return toUint8(res.body);\n }\n}\n\nfunction ensureOk(res: ProtoResult, apiMethod: string): void {\n if (res.status === 429) {\n throw new RateLimitError({\n message: `IAuthenticationService/${apiMethod} HTTP 429`,\n ...(res.eresult ? { eresult: Number(res.eresult) } : {}),\n });\n }\n if (res.status < 200 || res.status >= 300) {\n throw new LoginError(`IAuthenticationService/${apiMethod} HTTP ${res.status}`, {\n ...(res.eresult ? { eresult: Number(res.eresult) } : {}),\n ...(res.errorMessage ? { extendedErrorMessage: res.errorMessage } : {}),\n });\n }\n const er = res.eresult;\n if (er && er !== \"1\") {\n const code = Number(er);\n // Steam sometimes returns Fail(2) alongside a valid body; treat as success (matches webApi.ts).\n if (code === EResult.Fail && res.body.length > 0) return;\n const name = EResult[code] ?? \"EResult\";\n const msg = `${apiMethod}: ${name} (${er})${res.errorMessage ? ` ${res.errorMessage}` : \"\"}`;\n if (code === EResult.RateLimitExceeded)\n throw new RateLimitError({ message: msg, eresult: code });\n throw new LoginError(msg, {\n eresult: code,\n ...(res.errorMessage ? { extendedErrorMessage: res.errorMessage } : {}),\n });\n }\n}\n\nfunction toUint8(input: Buffer | Uint8Array): Uint8Array {\n return input instanceof Uint8Array && !Buffer.isBuffer(input) ? input : new Uint8Array(input);\n}\n","import { Buffer } from \"node:buffer\";\nimport { constants, createPublicKey, publicEncrypt } from \"node:crypto\";\n\n// Encrypt the password with Steam's RSA public key (hex modulus/exponent → JWK), PKCS#1 v1.5 → base64.\nexport function encryptPassword(password: string, modHex: string, expHex: string): string {\n const n = Buffer.from(modHex, \"hex\").toString(\"base64url\");\n const e = Buffer.from(expHex, \"hex\").toString(\"base64url\");\n const key = createPublicKey({ key: { kty: \"RSA\", n, e }, format: \"jwk\" });\n // publicEncrypt defaults to OAEP; Steam needs PKCS#1 v1.5.\n return publicEncrypt(\n { key, padding: constants.RSA_PKCS1_PADDING },\n Buffer.from(password, \"utf8\"),\n ).toString(\"base64\");\n}\n","import { Buffer } from \"node:buffer\";\nimport { createHash, createHmac } from \"node:crypto\";\n\n// Ported from DoctorMcKay's steam-totp (the few functions we use), so it isn't a runtime dependency.\n// The QueryTime server-time call lives in ConfirmationManager so it rides HttpClient (proxy).\nconst CODE_CHARS = \"23456789BCDFGHJKMNPQRTVWXY\";\n\nexport function time(timeOffset = 0): number {\n return Math.floor(Date.now() / 1000) + timeOffset;\n}\n\n// Steam-style TOTP code from a base64/hex/Buffer shared_secret.\nexport function getAuthCode(secret: Buffer | string, timeOffset = 0): string {\n const key = bufferizeSecret(secret);\n const buffer = Buffer.allocUnsafe(8);\n buffer.writeUInt32BE(0, 0);\n buffer.writeUInt32BE(Math.floor(time(timeOffset) / 30), 4);\n\n const hmac = createHmac(\"sha1\", key).update(buffer).digest();\n const start = (hmac[19] ?? 0) & 0x0f;\n let fullcode = hmac.subarray(start, start + 4).readUInt32BE(0) & 0x7fffffff;\n\n let code = \"\";\n for (let i = 0; i < 5; i++) {\n code += CODE_CHARS.charAt(fullcode % CODE_CHARS.length);\n fullcode /= CODE_CHARS.length;\n }\n return code;\n}\n\n// Single-use base64 confirmation key for mobileconf (tag: \"conf\"/\"list\"/\"allow\"/\"cancel\"/…).\nexport function getConfirmationKey(\n identitySecret: Buffer | string,\n t: number,\n tag: string,\n): string {\n const key = bufferizeSecret(identitySecret);\n const dataLen = 8 + (tag ? Math.min(tag.length, 32) : 0);\n const buffer = Buffer.allocUnsafe(dataLen);\n buffer.writeBigUInt64BE(BigInt(t), 0);\n if (tag) buffer.write(tag, 8);\n return createHmac(\"sha1\", key).update(buffer).digest(\"base64\");\n}\n\n// Stable mobileconf device id derived from the steamID (android: + UUID-formatted SHA1).\nexport function getDeviceID(steamID: string): string {\n const salt = process.env.STEAM_TOTP_SALT ?? \"\";\n const hash = createHash(\"sha1\")\n .update(steamID + salt)\n .digest(\"hex\")\n .replace(\n /^([0-9a-f]{8})([0-9a-f]{4})([0-9a-f]{4})([0-9a-f]{4})([0-9a-f]{12}).*$/,\n \"$1-$2-$3-$4-$5\",\n );\n return `android:${hash}`;\n}\n\nfunction bufferizeSecret(secret: Buffer | string): Buffer {\n if (typeof secret !== \"string\") return secret;\n return /[0-9a-f]{40}/i.test(secret) ? Buffer.from(secret, \"hex\") : Buffer.from(secret, \"base64\");\n}\n","import { create } from \"@bufbuild/protobuf\";\nimport type { MobileProfile } from \"../core/mobileProfile.js\";\nimport {\n type CAuthentication_DeviceDetails,\n CAuthentication_DeviceDetailsSchema,\n type EAuthTokenAppType,\n EAuthTokenPlatformType,\n} from \"../protobufs/steammessages_auth_pb.js\";\n\n// device_details for the login (shows in Steam's authorized-devices list). Always MobileApp.\nexport function buildDeviceDetails(profile: MobileProfile): CAuthentication_DeviceDetails {\n return create(CAuthentication_DeviceDetailsSchema, {\n deviceFriendlyName: profile.deviceFriendlyName,\n platformType: EAuthTokenPlatformType.k_EAuthTokenPlatformType_MobileApp,\n osType: profile.osType,\n gamingDeviceType: profile.gamingDeviceType,\n ...(profile.appType !== undefined ? { appType: profile.appType as EAuthTokenAppType } : {}),\n });\n}\n","import { EventEmitter } from \"node:events\";\nimport SteamID from \"steamid\";\nimport { EAuthSessionGuardType } from \"../core/enums.js\";\nimport { LoginError, NoMobileAuthenticatorError } from \"../core/errors.js\";\nimport type { MobileProfile } from \"../core/mobileProfile.js\";\nimport { encryptPassword } from \"../crypto/rsa.js\";\nimport { getAuthCode } from \"../crypto/steamTotp.js\";\nimport type { HttpClient } from \"../http/HttpClient.js\";\nimport { ESessionPersistence } from \"../protobufs/steammessages_auth_pb.js\";\nimport { AuthClient } from \"./AuthClient.js\";\nimport { buildDeviceDetails } from \"./deviceDetails.js\";\n\nexport interface CredentialSessionEvents {\n debug: [message: string];\n authenticated: [];\n timeout: [];\n error: [error: Error];\n // No code could be supplied automatically; caller must submitSteamGuardCode().\n steamGuardRequired: [info: { type: EAuthSessionGuardType; message: string }];\n remoteInteraction: [];\n}\n\nexport interface CredentialStartOptions {\n username: string;\n password: string;\n sharedSecret?: string; // answers DeviceCode automatically via TOTP\n steamGuardCode?: string;\n}\n\nconst DEFAULT_POLL_TIMEOUT_MS = 180_000;\nconst DEFAULT_POLL_INTERVAL_MS = 5_000;\n\n// Drives one credential login (rsaKey -> encrypt -> begin -> answer guard -> poll) to a refresh token.\nexport class CredentialSession extends EventEmitter<CredentialSessionEvents> {\n private readonly auth: AuthClient;\n private clientId = 0n;\n private requestId: Uint8Array = new Uint8Array();\n private pollIntervalMs = DEFAULT_POLL_INTERVAL_MS;\n private allowedConfirmations: EAuthSessionGuardType[] = [];\n private deadline = 0;\n private pollTimer: NodeJS.Timeout | undefined;\n private settled = false;\n private remoteInteractionEmitted = false;\n\n steamID: SteamID | undefined;\n username = \"\";\n accessToken: string | undefined;\n refreshToken: string | undefined;\n\n constructor(\n http: HttpClient,\n private readonly profile: MobileProfile,\n private readonly pollTimeoutMs = DEFAULT_POLL_TIMEOUT_MS,\n ) {\n super();\n this.auth = new AuthClient(http);\n }\n\n async start(opts: CredentialStartOptions): Promise<void> {\n this.username = opts.username;\n const rsa = await this.auth.getPasswordRSAPublicKey(opts.username);\n const encryptedPassword = encryptPassword(opts.password, rsa.publickeyMod, rsa.publickeyExp);\n\n // device_friendly_name and platform_type go only inside device_details, matching the iOS app.\n const begin = await this.auth.beginAuthSessionViaCredentials({\n accountName: opts.username,\n encryptedPassword,\n encryptionTimestamp: rsa.timestamp,\n rememberLogin: true,\n persistence: ESessionPersistence.k_ESessionPersistence_Persistent,\n websiteId: \"Mobile\",\n deviceDetails: buildDeviceDetails(this.profile),\n language: 0,\n });\n\n // A successful begin always returns a request_id; its absence (not clientId, which can be 0n)\n // means Steam rejected the login.\n if (begin.requestId.length === 0) {\n throw new LoginError(begin.extendedErrorMessage || \"login was rejected by Steam\", {\n ...(begin.extendedErrorMessage ? { extendedErrorMessage: begin.extendedErrorMessage } : {}),\n });\n }\n\n this.clientId = begin.clientId;\n this.requestId = begin.requestId;\n if (begin.steamid) this.steamID = new SteamID(begin.steamid.toString());\n if (begin.interval > 0) this.pollIntervalMs = Math.round(begin.interval * 1000);\n this.allowedConfirmations = begin.allowedConfirmations.map((c) => Number(c.confirmationType));\n this.emit(\"debug\", `begin OK: confirmations=[${this.allowedConfirmations.join(\",\")}]`);\n\n await this.answerConfirmations(opts);\n\n this.deadline = Date.now() + this.pollTimeoutMs;\n this.schedulePoll();\n }\n\n async submitSteamGuardCode(code: string): Promise<void> {\n const trimmed = code?.trim();\n if (!trimmed) throw new LoginError(\"a Steam Guard code is required\");\n const codeType = this.allowedConfirmations.includes(EAuthSessionGuardType.DeviceCode)\n ? EAuthSessionGuardType.DeviceCode\n : EAuthSessionGuardType.EmailCode;\n await this.submitCode(trimmed, codeType);\n }\n\n stop(): void {\n this.settled = true;\n if (this.pollTimer) clearTimeout(this.pollTimer);\n this.pollTimer = undefined;\n }\n\n private async answerConfirmations(opts: CredentialStartOptions): Promise<void> {\n const allowed = this.allowedConfirmations;\n\n if (allowed.includes(EAuthSessionGuardType.DeviceCode) && opts.sharedSecret) {\n const code = getAuthCode(opts.sharedSecret);\n this.emit(\"debug\", \"answering DeviceCode with generated TOTP\");\n await this.submitCode(code, EAuthSessionGuardType.DeviceCode);\n return;\n }\n\n // sharedSecret was supplied but the account isn't TOTP-protected — fail loud rather than fall through\n // to an \"email code required\" prompt the caller can't satisfy with what they provided.\n if (opts.sharedSecret && !allowed.includes(EAuthSessionGuardType.DeviceCode)) {\n throw new NoMobileAuthenticatorError();\n }\n\n if (opts.steamGuardCode) {\n const codeType = allowed.includes(EAuthSessionGuardType.DeviceCode)\n ? EAuthSessionGuardType.DeviceCode\n : EAuthSessionGuardType.EmailCode;\n await this.submitCode(opts.steamGuardCode, codeType);\n return;\n }\n\n if (\n allowed.includes(EAuthSessionGuardType.DeviceConfirmation) ||\n allowed.includes(EAuthSessionGuardType.EmailConfirmation)\n ) {\n this.emitRemoteInteraction();\n return;\n }\n\n const codeGuard = allowed.find(\n (t) => t === EAuthSessionGuardType.EmailCode || t === EAuthSessionGuardType.DeviceCode,\n );\n if (codeGuard !== undefined) {\n this.emit(\"steamGuardRequired\", {\n type: codeGuard,\n message:\n codeGuard === EAuthSessionGuardType.EmailCode\n ? \"an email Steam Guard code is required\"\n : \"a device (TOTP) Steam Guard code is required\",\n });\n }\n // else (None, or only confirmations): fall through to polling.\n }\n\n private async submitCode(code: string, codeType: EAuthSessionGuardType): Promise<void> {\n if (!this.steamID) throw new LoginError(\"cannot submit Steam Guard code before begin\");\n await this.auth.updateAuthSessionWithSteamGuardCode(\n this.clientId,\n BigInt(this.steamID.getSteamID64()),\n code,\n codeType,\n );\n }\n\n private schedulePoll(): void {\n if (this.settled) return;\n this.pollTimer = setTimeout(() => {\n this.poll().catch((err) => this.fail(err instanceof Error ? err : new Error(String(err))));\n }, this.pollIntervalMs);\n }\n\n private async poll(): Promise<void> {\n if (this.settled) return;\n\n let res: Awaited<ReturnType<typeof this.auth.pollAuthSessionStatus>>;\n try {\n res = await this.auth.pollAuthSessionStatus(this.clientId, this.requestId);\n } catch (err) {\n if (Date.now() >= this.deadline) {\n this.stop();\n this.emit(\"timeout\");\n return;\n }\n this.emit(\"debug\", `poll error, retrying: ${(err as Error).message}`);\n this.schedulePoll();\n return;\n }\n\n if (res.hadRemoteInteraction) this.emitRemoteInteraction();\n if (res.newClientId) this.clientId = res.newClientId;\n if (res.accessToken) this.accessToken = res.accessToken;\n\n if (res.refreshToken) {\n this.refreshToken = res.refreshToken;\n if (res.accountName) this.username = res.accountName;\n this.stop();\n this.emit(\"authenticated\");\n return;\n }\n\n if (Date.now() >= this.deadline) {\n this.stop();\n this.emit(\"timeout\");\n return;\n }\n this.schedulePoll();\n }\n\n private emitRemoteInteraction(): void {\n if (this.remoteInteractionEmitted) return;\n this.remoteInteractionEmitted = true;\n this.emit(\"remoteInteraction\");\n }\n\n private fail(error: Error): void {\n if (this.settled) return;\n this.stop();\n this.emit(\"error\", error);\n }\n}\n","// How we present as the Steam mobile app on the wire (per-host UA + cookies) plus the login-time\n// device_details. Steam doesn't strictly require any of it, but we match the app consistently.\nexport type MobilePlatform = \"ios\" | \"android\";\n\nexport interface MobileProfile {\n mobileClient: MobilePlatform; // mobileClient cookie value\n mobileClientVersion: string; // its presence is Steam's trigger for mobile treatment\n apiUserAgent: string; // UA for api.steampowered.com\n webUserAgent: string; // UA for steamcommunity/store/help\n // device_details (BeginAuthSessionViaCredentials):\n deviceFriendlyName: string; // iOS sends the model id, e.g. \"iPhone18,3\"\n osType: number; // EOSType, signed: iOS -600, Android -500\n gamingDeviceType: number;\n appType?: number; // EAuthTokenAppType (iOS 1); omitted for Android\n}\n\n// Captured from a real iOS Steam app (Charles).\nexport const IOS_PROFILE: MobileProfile = {\n mobileClient: \"ios\",\n mobileClientVersion: \"777777 3.10.9\",\n apiUserAgent: \"Steam%20Mobile/10472498 CFNetwork/3860.600.12 Darwin/25.5.0\",\n webUserAgent:\n \"Mozilla/5.0 (iPhone; CPU iPhone OS 18_7 like Mac OS X; Valve Steam App Version/3) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148\",\n deviceFriendlyName: \"iPhone18,3\",\n osType: -600,\n gamingDeviceType: 528,\n appType: 1,\n};\n\n// Matches the Android Steam app (okhttp UA) and our android: confirmation device-ids.\nexport const ANDROID_PROFILE: MobileProfile = {\n mobileClient: \"android\",\n mobileClientVersion: \"777777 3.10.3\",\n apiUserAgent: \"okhttp/4.9.2\",\n webUserAgent:\n \"Mozilla/5.0 (Linux; Android 14; SM-S921B) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Mobile Safari/537.36\",\n deviceFriendlyName: \"Galaxy S25\",\n osType: -500,\n gamingDeviceType: 528,\n};\n\nconst PRESETS: Record<MobilePlatform, MobileProfile> = {\n ios: IOS_PROFILE,\n android: ANDROID_PROFILE,\n};\n\n// Default to iOS; a string picks a preset; an object overrides fields on the implied preset.\nexport function resolveMobileProfile(\n input?: MobilePlatform | Partial<MobileProfile>,\n): MobileProfile {\n if (input === undefined) return { ...IOS_PROFILE };\n if (typeof input === \"string\") return { ...PRESETS[input] };\n const base = input.mobileClient === \"android\" ? ANDROID_PROFILE : IOS_PROFILE;\n return { ...base, ...input };\n}\n","import { type Browser, Impit } from \"impit\";\nimport { type Cookie, CookieJar } from \"tough-cookie\";\nimport { URLS } from \"../core/constants.js\";\nimport { ProxyError } from \"../core/errors.js\";\nimport type { MobilePlatform, MobileProfile } from \"../core/mobileProfile.js\";\n\n// Hosts that share our session cookies. api is included because the mobile app sends them to the WebAPI host too.\nconst COOKIE_HOSTS = [URLS.community, URLS.store, URLS.help, URLS.api];\n\n// TLS fingerprint per request kind. iOS runs webview + API on one Apple stack, so ios18 serves both.\n// Android splits: community pages use the Chrome WebView, native api/mobileconf uses okhttp — and Steam's\n// WAF 429s an okhttp fingerprint on the community host, so web pages must look like Chrome.\nconst IMPIT_BROWSER: Record<MobilePlatform, { web: Browser; native: Browser }> = {\n ios: { web: \"ios18\", native: \"ios18\" },\n android: { web: \"chrome\", native: \"okhttp5\" },\n};\n\n// Document Accept for webview page loads; a browser always sends one and its absence is a WAF bot tell.\n// (JSON XHRs send application/json instead — see perform().)\nconst BROWSER_ACCEPT = \"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8\";\n\ntype Method = \"GET\" | \"POST\";\ntype ResponseType = \"text\" | \"json\" | \"buffer\";\ntype Scalar = string | number | boolean;\n\nexport interface HttpResponse<T = string> {\n statusCode: number;\n headers: Record<string, string | string[] | undefined>;\n body: T;\n}\n\n// Ordered multipart fields; repeated names (e.g. cid[]/ck[]) are allowed and order-significant.\nexport interface MultipartField {\n name: string;\n value: string;\n}\n\nexport interface RequestOptions {\n searchParams?: Record<string, Scalar | undefined>;\n // Request body: pass exactly one of form / multipart / json / body.\n form?: Record<string, Scalar | undefined>;\n multipart?: MultipartField[];\n json?: unknown;\n body?: string | Buffer;\n headers?: Record<string, string>;\n responseType?: ResponseType;\n referer?: string;\n signal?: AbortSignal; // abort the request\n timeoutMs?: number; // per-request timeout override (default 50000)\n}\n\nfunction clean(input?: Record<string, Scalar | undefined>): Record<string, string> | undefined {\n if (!input) return undefined;\n const out: Record<string, string> = {};\n for (const [k, v] of Object.entries(input)) {\n if (v !== undefined) out[k] = String(v);\n }\n return out;\n}\n\n// Hand-built to match the Steam mobile app's mobileconf POSTs.\nfunction buildMultipart(fields: MultipartField[], boundary: string): string {\n let out = \"\";\n for (const { name, value } of fields) {\n out += `--${boundary}\\r\\ncontent-disposition: form-data; name=\"${name}\"\\r\\n\\r\\n${value}\\r\\n`;\n }\n return `${out}--${boundary}--\\r\\n`;\n}\n\nexport class HttpClient {\n readonly jar: CookieJar;\n private readonly webClient: Impit;\n private readonly nativeClient: Impit;\n private readonly browserClient: Impit;\n private readonly profile: MobileProfile;\n private readonly proxy: string | undefined;\n\n constructor(opts: { proxy?: string; profile: MobileProfile }) {\n this.jar = new CookieJar();\n this.profile = opts.profile;\n this.proxy = opts.proxy;\n\n const makeClient = (browser: Browser): Impit =>\n new Impit({\n browser,\n cookieJar: this.jar,\n followRedirects: false,\n timeout: 50000,\n ...(opts.proxy ? { proxyUrl: opts.proxy } : {}),\n });\n const fp = IMPIT_BROWSER[this.profile.mobileClient];\n this.webClient = makeClient(fp.web);\n // iOS uses the same fingerprint for both, so reuse the one instance.\n this.nativeClient = fp.native === fp.web ? this.webClient : makeClient(fp.native);\n // Third-party hosts (e.g. an OpenID relying party behind Cloudflare) get a real Chrome hello:\n // impit's ios18 ClientHello trips Cloudflare's strict TLS parser (decode_error). Steam hosts, which\n // are lenient, keep the app-accurate fingerprint.\n this.browserClient = fp.web === \"chrome\" ? this.webClient : makeClient(\"chrome\");\n\n // Cookies that mark every request as coming from the Steam mobile app.\n for (const raw of [\n `mobileClient=${this.profile.mobileClient}`,\n `mobileClientVersion=${this.profile.mobileClientVersion}`,\n \"Steam_Language=english\",\n ]) {\n for (const host of COOKIE_HOSTS) this.jar.setCookieSync(raw, host);\n }\n }\n\n async request<T = string>(\n method: Method,\n url: string,\n opts: RequestOptions = {},\n ): Promise<HttpResponse<T>> {\n const res = await this.perform<T>(method, url, opts);\n // Steam gates trade/market pages behind a one-time eligibility check (302 → /market/\n // eligibilitycheck/ → back). We don't auto-follow redirects, so visit it once to prime the\n // session, then retry. A genuinely limited account keeps redirecting and the retry surfaces it.\n const location = firstHeader(res.headers.location);\n if (\n res.statusCode >= 300 &&\n res.statusCode < 400 &&\n location?.includes(\"/market/eligibilitycheck\")\n ) {\n await this.perform(\"GET\", location, opts.signal ? { signal: opts.signal } : {});\n return this.perform<T>(method, url, opts);\n }\n return res;\n }\n\n private async perform<T = string>(\n method: Method,\n url: string,\n opts: RequestOptions = {},\n ): Promise<HttpResponse<T>> {\n // Native app calls (WebAPI + mobileconf) carry the native UA; webview pages carry the web UA (per iOS-app captures).\n const isNative = url.startsWith(URLS.api) || url.includes(\"/mobileconf/\");\n const headers: Record<string, string> = {\n \"User-Agent\": isNative ? this.profile.apiUserAgent : this.profile.webUserAgent,\n \"Accept-Language\": \"en-US,en;q=0.9\",\n };\n if (isNative) {\n // Native app transport: JSON accept, no browser Origin/Sec-Fetch headers.\n headers.Accept = \"application/json, text/plain, */*\";\n } else {\n headers.Accept =\n opts.responseType === \"json\" ? \"application/json, text/plain, */*\" : BROWSER_ACCEPT;\n if (method !== \"GET\") {\n headers.Origin = URLS.community;\n if (opts.referer) headers.Referer = opts.referer;\n }\n }\n\n // Body: exactly one of multipart / form / json / body. impit auto-sets Content-Type for URLSearchParams;\n // for the hand-built multipart and json strings we set it explicitly so impit doesn't override.\n let body: string | Buffer | URLSearchParams | undefined;\n if (opts.multipart) {\n const boundary = `----steamMobile${randomSessionId()}`;\n body = buildMultipart(opts.multipart, boundary);\n headers[\"Content-Type\"] = `multipart/form-data; boundary=${boundary}`;\n } else if (opts.form) {\n body = new URLSearchParams(clean(opts.form));\n } else if (opts.json !== undefined) {\n body = JSON.stringify(opts.json);\n headers[\"Content-Type\"] = \"application/json\";\n } else if (opts.body !== undefined) {\n body = opts.body;\n }\n Object.assign(headers, opts.headers); // explicit caller headers win\n\n // impit's fetch takes a full URL (no searchParams option) — fold them into the query string.\n const target = new URL(url);\n const sp = clean(opts.searchParams);\n if (sp) for (const [k, v] of Object.entries(sp)) target.searchParams.set(k, v);\n\n try {\n const client = isNative\n ? this.nativeClient\n : isSteamHost(target.hostname)\n ? this.webClient\n : this.browserClient;\n const res = await client.fetch(target.toString(), {\n method,\n headers,\n ...(body !== undefined ? { body } : {}),\n ...(opts.signal ? { signal: opts.signal } : {}),\n ...(opts.timeoutMs !== undefined ? { timeout: opts.timeoutMs } : {}),\n });\n\n const responseType: ResponseType = opts.responseType ?? \"text\";\n let parsed: unknown;\n if (responseType === \"buffer\") {\n parsed = Buffer.from(await res.bytes());\n } else if (responseType === \"json\") {\n // Empty/invalid JSON → undefined body, never throw; callers branch on status, not parse errors.\n const text = await res.text();\n parsed = text ? safeJsonParse(text) : undefined;\n } else {\n parsed = await res.text();\n }\n\n return {\n statusCode: res.status,\n headers: headersToRecord(res.headers),\n body: parsed as T,\n };\n } catch (err) {\n throw this.wrapTransportError(err);\n }\n }\n\n // impit only throws on transport failures inside perform() (HTTP statuses don't throw); aborts surface as\n // a DOMException (not an Error subclass), so instanceof Error && !abort isolates a genuine transport failure.\n private wrapTransportError(err: unknown): unknown {\n if (this.proxy && err instanceof Error && !isAbortError(err)) {\n return new ProxyError(`proxy request failed: ${err.message}`, { cause: err });\n }\n return err;\n }\n\n get<T = string>(url: string, opts?: RequestOptions): Promise<HttpResponse<T>> {\n return this.request<T>(\"GET\", url, opts);\n }\n\n post<T = string>(url: string, opts?: RequestOptions): Promise<HttpResponse<T>> {\n return this.request<T>(\"POST\", url, opts);\n }\n\n async setCookie(rawCookie: string): Promise<void> {\n for (const host of COOKIE_HOSTS) {\n await this.jar.setCookie(rawCookie, host);\n }\n }\n\n // Read a cookie value from the jar (includes HttpOnly cookies). undefined if not set.\n async getCookie(key: string, url: string = URLS.community): Promise<string | undefined> {\n const cookies = await this.jar.getCookies(url);\n return cookies.find((c: Cookie) => c.key === key)?.value;\n }\n\n async getSessionId(): Promise<string> {\n const cookies = await this.jar.getCookies(URLS.community);\n const existing = cookies.find((c: Cookie) => c.key === \"sessionid\");\n if (existing) return existing.value;\n const sessionId = randomSessionId();\n await this.setCookie(`sessionid=${sessionId}`);\n return sessionId;\n }\n}\n\nfunction randomSessionId(): string {\n const bytes = new Uint8Array(12);\n globalThis.crypto.getRandomValues(bytes);\n return Array.from(bytes, (b) => b.toString(16).padStart(2, \"0\")).join(\"\");\n}\n\nfunction firstHeader(v: string | string[] | undefined): string | undefined {\n return Array.isArray(v) ? v[0] : v;\n}\n\nconst STEAM_HOSTS = [\"steamcommunity.com\", \"steampowered.com\"] as const;\n\n// Steam's own hosts (community/store/help/api); everything else is treated as a third-party site.\nfunction isSteamHost(host: string): boolean {\n const h = host.toLowerCase();\n return STEAM_HOSTS.some((d) => h === d || h.endsWith(`.${d}`));\n}\n\n// WHATWG Headers → lowercased plain record (consumers read location / x-eresult / x-error_message).\nfunction headersToRecord(h: Headers): Record<string, string> {\n const out: Record<string, string> = {};\n h.forEach((value, key) => {\n out[key] = value;\n });\n return out;\n}\n\nfunction safeJsonParse(text: string): unknown {\n try {\n return JSON.parse(text);\n } catch {\n return undefined;\n }\n}\n\nfunction isAbortError(err: unknown): boolean {\n if (typeof err !== \"object\" || err === null) return false;\n const e = err as { name?: unknown; code?: unknown };\n return e.name === \"AbortError\" || e.code === \"ERR_ABORTED\";\n}\n","import { LoginError } from \"../core/errors.js\";\nimport {\n type MobilePlatform,\n type MobileProfile,\n resolveMobileProfile,\n} from \"../core/mobileProfile.js\";\nimport { HttpClient } from \"../http/HttpClient.js\";\nimport { CredentialSession } from \"./CredentialSession.js\";\n\nexport interface LoginWithCredentialsOptions {\n username: string;\n password: string;\n sharedSecret?: string; // answers DeviceCode automatically via TOTP\n steamGuardCode?: string;\n proxy?: string;\n mobileProfile?: MobilePlatform | Partial<MobileProfile>;\n // Aborts the flow: stops polling and rejects with a LoginError.\n signal?: AbortSignal;\n // Called when a code is required and none was supplied; resolve to the code to continue.\n onSteamGuardRequired?: (info: { type: number; message: string }) => Promise<string> | string;\n}\n\nexport interface LoginResult {\n refreshToken: string;\n accessToken: string | undefined;\n steamId: string;\n username: string;\n}\n\n// One-shot credential login → MobileApp refresh token. Feed into `new SteamMobile({ refreshToken })`.\nexport function loginWithCredentials(opts: LoginWithCredentialsOptions): Promise<LoginResult> {\n const profile = resolveMobileProfile(opts.mobileProfile);\n const http = new HttpClient({ ...(opts.proxy ? { proxy: opts.proxy } : {}), profile });\n const session = new CredentialSession(http, profile);\n\n return new Promise<LoginResult>((resolve, reject) => {\n const { signal } = opts;\n const onAbort = (): void => {\n session.stop();\n reject(new LoginError(\"login aborted\"));\n };\n const cleanup = (): void => signal?.removeEventListener(\"abort\", onAbort);\n const fail = (err: Error): void => {\n session.stop();\n cleanup();\n reject(err);\n };\n\n if (signal?.aborted) {\n reject(new LoginError(\"login aborted\"));\n return;\n }\n signal?.addEventListener(\"abort\", onAbort, { once: true });\n\n session.on(\"error\", fail);\n session.on(\"timeout\", () => fail(new LoginError(\"login timed out waiting for confirmation\")));\n session.on(\"authenticated\", () => {\n cleanup();\n if (!session.refreshToken || !session.steamID) {\n reject(new LoginError(\"login completed without a refresh token\"));\n return;\n }\n resolve({\n refreshToken: session.refreshToken,\n accessToken: session.accessToken,\n steamId: session.steamID.getSteamID64(),\n username: session.username,\n });\n });\n\n session.on(\"steamGuardRequired\", (info) => {\n const handler = opts.onSteamGuardRequired;\n if (!handler) {\n fail(\n new LoginError(\n `${info.message}; pass sharedSecret, steamGuardCode, or onSteamGuardRequired`,\n ),\n );\n return;\n }\n Promise.resolve(handler(info))\n .then((code) => session.submitSteamGuardCode(code))\n .catch((err) => fail(err instanceof Error ? err : new Error(String(err))));\n });\n\n session.start(opts).catch((err) => fail(err instanceof Error ? err : new Error(String(err))));\n });\n}\n","export interface Page<T, C> {\n items: T[];\n next: C | undefined;\n}\n\nexport async function paginate<T, C>(\n fetchPage: (cursor: C | undefined) => Promise<Page<T, C>>,\n): Promise<T[]> {\n const all: T[] = [];\n let cursor: C | undefined;\n do {\n const { items, next } = await fetchPage(cursor);\n all.push(...items);\n cursor = next;\n } while (cursor !== undefined);\n return all;\n}\n","import { EResult } from \"./enums.js\";\nimport {\n ItemServerUnavailableError,\n NewDeviceError,\n OfferLimitError,\n PrivateInventoryError,\n SteamError,\n TargetCannotTradeError,\n TradeBanError,\n} from \"./errors.js\";\n\n// Classify a Steam-supplied error string (sendOffer `strError`, accept-offer body, or scraped trade-page\n// <div id=\"error_msg\">) into the right typed error. Mirrors steam-tradeoffer-manager's makeAnError\n// taxonomy plus the inventory-privacy case Steam shows on the trade page.\nexport function parseStrError(message: string): SteamError {\n const match = message.match(/\\((\\d+)\\)$/);\n const eresult = match?.[1] !== undefined ? Number(match[1]) : undefined;\n const opts = eresult !== undefined ? { eresult } : undefined;\n\n if (/You cannot trade with .* because they have a trade ban\\./.test(message)) {\n return new TradeBanError(message);\n }\n if (/sent too many trade offers/.test(message)) {\n return new OfferLimitError(message);\n }\n if (/You have logged in from a new device/.test(message)) {\n return new NewDeviceError(message, opts);\n }\n if (/is not available to trade\\. More information will be shown to/.test(message)) {\n return new TargetCannotTradeError(message, opts);\n }\n if (/unable to contact the game's item server/.test(message)) {\n return new ItemServerUnavailableError(message, {\n eresult: eresult ?? EResult.ServiceUnavailable,\n });\n }\n if (\n /inventory privacy is set to|inventory is (?:currently )?private|profile's inventory is private/i.test(\n message,\n )\n ) {\n return new PrivateInventoryError(message);\n }\n return new SteamError(message, opts);\n}\n","// Per-endpoint rate-limit config, from live profiling (Steam doesn't send Retry-After). null = not measured yet.\n// window — `max` calls per `windowMs`. bucket — `capacity` burst, 1 token refills every `refillMs`.\nexport type RateLimit =\n | { type: \"window\"; windowMs: number; max: number }\n | { type: \"bucket\"; capacity: number; refillMs: number };\n\nexport const RATE_LIMITS = {\n partnerInventory: { type: \"window\", windowMs: 120_000, max: 30 },\n inventory: null,\n GetTradeHistory: { type: \"bucket\", capacity: 25, refillMs: 15_000 },\n GetTradeHoldDurations: { type: \"bucket\", capacity: 3750, refillMs: 5 },\n GetTradeOffer: { type: \"bucket\", capacity: 3750, refillMs: 5 },\n GetTradeOffers: { type: \"bucket\", capacity: 85, refillMs: 125 },\n GetTradeOffersSummary: { type: \"bucket\", capacity: 85, refillMs: 125 },\n GetTradeStatus: { type: \"bucket\", capacity: 25, refillMs: 2000 },\n} as const satisfies Record<string, RateLimit | null>;\n\nexport type RateLimitedEndpoint = keyof typeof RATE_LIMITS;\n\nfunction retryAfterMs(limit: RateLimit | null): number | null {\n if (!limit) return null;\n return limit.type === \"bucket\" ? limit.refillMs : limit.windowMs;\n}\n\n// Retry-after hint (ms) per endpoint: one token for a bucket, the full window otherwise.\nexport const RETRY_AFTER = Object.fromEntries(\n Object.entries(RATE_LIMITS).map(([key, limit]) => [key, retryAfterMs(limit)]),\n) as Record<RateLimitedEndpoint, number | null>;\n","import {\n FamilyViewError,\n HttpStatusError,\n RateLimitError,\n SteamError,\n SteamSessionExpiredError,\n} from \"../core/errors.js\";\nimport type { HttpResponse } from \"./HttpClient.js\";\n\nfunction locationHeader(res: HttpResponse<unknown>): string {\n const loc = res.headers.location;\n return Array.isArray(loc) ? (loc[0] ?? \"\") : (loc ?? \"\");\n}\n\nexport function httpError(\n res: HttpResponse<unknown>,\n rateLimitWindowMs?: number | null,\n): SteamError {\n if (res.statusCode === 429) {\n return new RateLimitError({\n statusCode: 429,\n body: res.body,\n ...(typeof rateLimitWindowMs === \"number\" ? { retryAfterMs: rateLimitWindowMs } : {}),\n });\n }\n if (res.statusCode === 401) return new SteamSessionExpiredError();\n if (res.statusCode >= 300 && res.statusCode <= 399) {\n const loc = locationHeader(res);\n if (loc.includes(\"/login\")) return new SteamSessionExpiredError();\n if (loc.includes(\"eligibilitycheck\")) {\n return new SteamError(\n \"Steam redirected to the market eligibility check — this account is limited / not trade-eligible\",\n );\n }\n }\n return new HttpStatusError(res.statusCode, undefined, res.body);\n}\n\nexport function checkHttpError(res: HttpResponse<unknown>): void {\n const { statusCode } = res;\n\n if (statusCode >= 300 && statusCode <= 399 && locationHeader(res).includes(\"/login\")) {\n throw new SteamSessionExpiredError();\n }\n\n if (\n statusCode === 403 &&\n typeof res.body === \"string\" &&\n /<div id=\"parental_notice_instructions\">/.test(res.body)\n ) {\n throw new FamilyViewError();\n }\n\n if (statusCode >= 400) {\n throw new HttpStatusError(statusCode, undefined, res.body);\n }\n}\n\nexport function checkCommunityError(html: unknown): void {\n if (typeof html !== \"string\") return;\n\n const sorry = html.match(/<h1>Sorry!<\\/h1>/);\n if (sorry) {\n const match = html.match(/<h3>(.+)<\\/h3>/);\n throw new SteamError(match?.[1] ?? \"Unknown error occurred\");\n }\n\n if (html.includes(\"g_steamID = false;\") && html.includes(\"<title>Sign In</title>\")) {\n throw new SteamSessionExpiredError();\n }\n}\n\nexport function checkTradeError(html: unknown): void {\n if (typeof html !== \"string\") return;\n const match = html.match(/<div id=\"error_msg\">\\s*([^<]+)\\s*<\\/div>/);\n if (match?.[1]) throw new SteamError(match[1].trim());\n}\n","import SteamID from \"steamid\";\nimport { URLS } from \"../core/constants.js\";\nimport type { SteamError } from \"../core/errors.js\";\nimport { parseStrError } from \"../core/parseStrError.js\";\nimport type { HttpClient } from \"./HttpClient.js\";\n\n// Scrape <div id=\"error_msg\">…</div> from the trade page — the richer \"their inventory is private\",\n// \"trade-banned\", \"limited account\" etc. message Steam shows the user. Regex matches McKay's\n// `[^<]+` — text-only, no nested markup.\nexport async function fetchTradePageErrorMessage(\n http: HttpClient,\n steamId: string,\n token?: string | undefined,\n): Promise<string | undefined> {\n const accountId = new SteamID(steamId).accountid;\n const url = `${URLS.community}/tradeoffer/new/?partner=${accountId}${token ? `&token=${token}` : \"\"}`;\n const res = await http.get<string>(url, {\n responseType: \"text\",\n headers: { Referer: `${URLS.community}/profiles/${steamId}` },\n });\n if (res.statusCode !== 200) return undefined;\n const match = res.body.match(/<div id=\"error_msg\">\\s*([^<]+)\\s*<\\/div>/);\n return match?.[1]?.replace(/\\s+/g, \" \").trim() || undefined;\n}\n\n// Resolve the best error to throw when an inventory endpoint reports a failure. Loads the trade page\n// for the richer Steam-rendered message, then classifies (private / trade-ban / new device / etc.).\n// Falls back to the JSON body's error string if the page has nothing useful.\nexport async function inventoryFailureError(\n http: HttpClient,\n steamId: string,\n token: string | undefined,\n bodyMessage: string | undefined,\n): Promise<SteamError> {\n const scraped = await fetchTradePageErrorMessage(http, steamId, token).catch(() => undefined);\n const message = scraped ?? bodyMessage ?? \"Failed to load inventory\";\n return parseStrError(message);\n}\n","export interface SteamTag {\n category: string;\n internal_name: string;\n localized_category_name?: string;\n category_name?: string;\n localized_tag_name?: string;\n name?: string;\n color?: string;\n}\n\nexport interface SteamDescriptionLine {\n type: string;\n value: string;\n color?: string;\n name?: string;\n}\n\nexport interface SteamAction {\n link: string;\n name: string;\n type?: string;\n}\n\nexport interface AssetProperty {\n propertyid: number;\n int_value?: string;\n float_value?: string;\n string_value?: string;\n}\n\nexport interface RawInventoryAsset {\n appid?: number | string;\n contextid?: string;\n assetid?: string;\n id?: string;\n classid: string;\n instanceid?: string;\n amount: string;\n currencyid?: string;\n pos?: number;\n [key: string]: unknown;\n}\n\nexport interface RawDescription {\n appid?: number | string;\n classid: string;\n instanceid?: string;\n icon_url?: string;\n name?: string;\n type?: string;\n market_name?: string;\n market_hash_name?: string;\n tradable?: number | boolean;\n marketable?: number | boolean;\n commodity?: number | boolean;\n market_tradable_restriction?: number | string;\n market_marketable_restriction?: number | string;\n descriptions?: SteamDescriptionLine[];\n owner_descriptions?: SteamDescriptionLine[];\n actions?: SteamAction[];\n market_actions?: SteamAction[];\n fraudwarnings?: string[];\n tags?: SteamTag[];\n [key: string]: unknown;\n}\n\nexport interface RawAssetPropertyEntry {\n appid: number;\n contextid: string;\n assetid: string;\n asset_properties: AssetProperty[];\n}\n\nexport interface RawInventoryResponse {\n assets?: RawInventoryAsset[];\n descriptions?: RawDescription[];\n asset_properties?: RawAssetPropertyEntry[];\n more_items?: number;\n last_assetid?: string;\n total_inventory_count?: number;\n success?: number;\n error?: string;\n Error?: string;\n}\n\nexport interface RawPartnerInventoryResponse {\n success?: boolean;\n error?: string;\n Error?: string;\n rgInventory?: Record<string, RawInventoryAsset> | unknown[];\n rgDescriptions?: Record<string, RawDescription> | unknown[];\n rgAssetProperties?: Record<string, AssetProperty[]> | unknown[];\n more?: boolean;\n more_start?: number | boolean;\n}\n\nexport interface EconItem {\n appid: number;\n contextid: string;\n assetid: string;\n classid: string;\n instanceid: string;\n amount: number;\n currencyid?: string;\n\n name: string;\n market_name: string;\n market_hash_name: string;\n type: string;\n name_color?: string;\n background_color?: string;\n icon_url: string;\n icon_url_large?: string;\n\n tradable: boolean;\n marketable: boolean;\n commodity: boolean;\n market_tradable_restriction: number;\n market_marketable_restriction: number;\n\n descriptions: SteamDescriptionLine[];\n owner_descriptions: SteamDescriptionLine[];\n actions: SteamAction[];\n market_actions: SteamAction[];\n fraudwarnings: string[];\n tags: SteamTag[];\n asset_properties: AssetProperty[];\n\n [key: string]: unknown;\n}\n\nfunction toBool(value: number | boolean | undefined): boolean {\n return typeof value === \"boolean\" ? value : Number(value ?? 0) !== 0;\n}\n\nfunction toInt(value: number | string | undefined): number {\n return value ? Number.parseInt(String(value), 10) : 0;\n}\n\nfunction asRecord<T>(value: Record<string, T> | unknown[] | undefined): Record<string, T> {\n return value && !Array.isArray(value) ? value : {};\n}\n\n// Key by appid_classid_instanceid: trade offers span multiple apps, so appid must be in the key (unlike single-app inventory).\nexport function buildDescriptionMap(\n descriptions: RawDescription[] | undefined,\n): Map<string, RawDescription> {\n const map = new Map<string, RawDescription>();\n for (const d of descriptions ?? []) {\n map.set(`${d.appid}_${d.classid}_${d.instanceid ?? \"0\"}`, d);\n }\n return map;\n}\n\nexport function buildItem(\n asset: RawInventoryAsset,\n description: RawDescription | undefined,\n properties: AssetProperty[],\n fallbackContextId: string,\n): EconItem {\n return {\n ...asset,\n ...description,\n appid: Number(asset.appid ?? description?.appid ?? 0),\n contextid: (asset.contextid ?? fallbackContextId).toString(),\n assetid: (asset.assetid ?? asset.id ?? \"\").toString(),\n classid: asset.classid.toString(),\n instanceid: (asset.instanceid ?? \"0\").toString(),\n amount: toInt(asset.amount),\n ...(asset.currencyid ? { currencyid: asset.currencyid } : {}),\n name: description?.name ?? \"\",\n market_name: description?.market_name ?? \"\",\n market_hash_name: description?.market_hash_name ?? \"\",\n type: description?.type ?? \"\",\n icon_url: description?.icon_url ?? \"\",\n tradable: toBool(description?.tradable),\n marketable: toBool(description?.marketable),\n commodity: toBool(description?.commodity),\n market_tradable_restriction: toInt(description?.market_tradable_restriction),\n market_marketable_restriction: toInt(description?.market_marketable_restriction),\n descriptions: description?.descriptions ?? [],\n owner_descriptions: description?.owner_descriptions ?? [],\n actions: description?.actions ?? [],\n market_actions: description?.market_actions ?? [],\n fraudwarnings: description?.fraudwarnings ?? [],\n tags: description?.tags ?? [],\n asset_properties: properties,\n };\n}\n\nexport function parseInventory(\n body: RawInventoryResponse,\n contextid: string,\n tradableOnly = false,\n): EconItem[] {\n const descriptions = new Map<string, RawDescription>();\n for (const d of body.descriptions ?? []) {\n descriptions.set(`${d.classid}_${d.instanceid ?? \"0\"}`, d);\n }\n\n const properties = new Map<string, AssetProperty[]>();\n for (const p of body.asset_properties ?? []) {\n properties.set(p.assetid, p.asset_properties);\n }\n\n const items: EconItem[] = [];\n for (const asset of body.assets ?? []) {\n const assetid = (asset.assetid ?? asset.id ?? \"\").toString();\n const description = descriptions.get(`${asset.classid}_${asset.instanceid ?? \"0\"}`);\n if (tradableOnly && !toBool(description?.tradable)) continue;\n items.push(buildItem(asset, description, properties.get(assetid) ?? [], contextid));\n }\n return items;\n}\n\nexport function parsePartnerInventory(\n body: RawPartnerInventoryResponse,\n contextid: string,\n tradableOnly = false,\n): EconItem[] {\n const inventory = asRecord<RawInventoryAsset>(body.rgInventory);\n const descriptions = asRecord<RawDescription>(body.rgDescriptions);\n const properties = asRecord<AssetProperty[]>(body.rgAssetProperties);\n\n const assets = Object.values(inventory).sort((a, b) => Number(a.pos ?? 0) - Number(b.pos ?? 0));\n const items: EconItem[] = [];\n for (const asset of assets) {\n const description = descriptions[`${asset.classid}_${asset.instanceid ?? \"0\"}`];\n if (tradableOnly && !toBool(description?.tradable)) continue;\n const assetid = (asset.assetid ?? asset.id ?? \"\").toString();\n items.push(buildItem(asset, description, properties[assetid] ?? [], contextid));\n }\n return items;\n}\n","import type { Cookie } from \"tough-cookie\";\nimport { URLS } from \"../core/constants.js\";\nimport { OpenIdError } from \"../core/errors.js\";\nimport type { HttpClient, HttpResponse, MultipartField } from \"../http/HttpClient.js\";\n\nconst STEAM_OPENID_URL = `${URLS.community}/openid/login`;\nconst DEFAULT_MAX_REDIRECTS = 10;\n// got sends no Accept on web requests; a browser does, and a relying party's /login may negotiate on it.\nconst BROWSER_ACCEPT = \"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8\";\n\nexport interface OpenidConfirmation {\n // The signed assertion redirect Steam issues back to the relying party (carries the openid.* id_res params).\n location: string;\n params: Record<string, string>;\n steamId: string;\n}\n\nexport interface OpenidCookie {\n name: string;\n value: string;\n}\n\nexport interface OpenidLoginResult {\n steamId: string;\n // Where the relying party left us once it consumed the assertion.\n finalUrl: string;\n // Cookies the relying party set, scoped to its host - carry these into your own HTTP client.\n cookies: OpenidCookie[];\n}\n\nexport interface OpenidLoginOptions {\n // The relying party's \"Sign in through Steam\" entry URL (a plain GET that 302-chains to Steam).\n initiateUrl: string;\n // Host whose cookies to return; defaults to the host we land on.\n cookieHost?: string;\n maxRedirects?: number;\n}\n\nfunction locationOf(res: HttpResponse<string>): string | undefined {\n const loc = res.headers.location;\n return (Array.isArray(loc) ? loc[0] : loc) || undefined;\n}\n\nfunction isRedirect(res: HttpResponse<string>): boolean {\n return res.statusCode >= 300 && res.statusCode < 400 && locationOf(res) !== undefined;\n}\n\nfunction queryParams(url: string): Record<string, string> {\n const out: Record<string, string> = {};\n for (const [k, v] of new URL(url).searchParams) out[k] = v;\n return out;\n}\n\n// Decode the HTML entities that occur in form attribute values (& last, so &quot; survives).\nfunction decodeEntities(s: string): string {\n return s\n .replace(/"/g, '\"')\n .replace(/�?39;/g, \"'\")\n .replace(/'/g, \"'\")\n .replace(/</g, \"<\")\n .replace(/>/g, \">\")\n .replace(/&/g, \"&\");\n}\n\n// Steam's /openid/login interstitial submits multipart/form-data (urlencoded -> \"Invalid Params\").\nexport function parseOpenidForm(html: string): { action: string; fields: MultipartField[] } | null {\n const form = [...html.matchAll(/<form\\b([^>]*?)>([\\s\\S]*?)<\\/form>/gi)].find((m) =>\n /openid\\/login/i.test(m[1] ?? \"\"),\n );\n const action = form?.[1]?.match(/\\baction=[\"']([^\"']+)[\"']/i)?.[1];\n if (!form || !action) return null;\n const fields: MultipartField[] = [];\n for (const tag of (form[2] ?? \"\").match(/<input\\b[^>]*>/gi) ?? []) {\n const name = tag.match(/\\bname=[\"']([^\"']*)[\"']/i)?.[1];\n if (!name) continue;\n const value = decodeEntities(tag.match(/\\bvalue=[\"']([^\"']*)[\"']/i)?.[1] ?? \"\");\n fields.push({ name, value });\n }\n return { action: new URL(decodeEntities(action), STEAM_OPENID_URL).toString(), fields };\n}\n\n// Confirm a Steam OpenID assertion from an interstitial page you've already loaded (the session must be\n// authenticated) and return the signed redirect Steam issues to the relying party. This is the\n// protocol-universal leg; consuming `location` (the relying party's own callback) is the caller's concern.\nexport async function confirmOpenid(\n http: HttpClient,\n interstitialHtml: string,\n referer?: string,\n): Promise<OpenidConfirmation> {\n const form = parseOpenidForm(interstitialHtml);\n if (!form) {\n throw new OpenIdError(\"no Steam OpenID form in the page; the web session is not authenticated\");\n }\n const res = await http.post<string>(form.action, {\n multipart: form.fields,\n headers: { Accept: BROWSER_ACCEPT },\n ...(referer ? { referer } : {}),\n });\n const location = isRedirect(res) ? locationOf(res) : undefined;\n if (!location) {\n throw new OpenIdError(`Steam returned no OpenID assertion redirect (HTTP ${res.statusCode})`);\n }\n const params = queryParams(location);\n const claimed = params[\"openid.claimed_id\"] ?? params[\"openid.identity\"] ?? \"\";\n const steamId = claimed.match(/\\/id\\/(\\d{17})/)?.[1];\n if (!steamId) throw new OpenIdError(\"OpenID assertion carried no steamid\");\n return { location, params, steamId };\n}\n\n// Log into a third-party relying party that offers \"Sign in through Steam\", spending the live web\n// session in `http`'s jar. Drives entry -> Steam confirm -> relying-party callback, then returns the\n// cookies the site set. Site-specific gates (Cloudflare, device headers, etc.) are the caller's job.\nexport async function steamOpenidLogin(\n http: HttpClient,\n options: OpenidLoginOptions,\n): Promise<OpenidLoginResult> {\n const maxRedirects = options.maxRedirects ?? DEFAULT_MAX_REDIRECTS;\n await http.getSessionId(); // a sessionid cookie must accompany steamLoginSecure on the handshake\n const get = (u: string) => http.get<string>(u, { headers: { Accept: BROWSER_ACCEPT } });\n\n let url = options.initiateUrl;\n let res = await get(url);\n for (let i = 0; i < maxRedirects && isRedirect(res); i++) {\n url = new URL(locationOf(res) as string, url).toString();\n res = await get(url);\n }\n\n const confirmation = await confirmOpenid(http, res.body, url);\n\n url = confirmation.location;\n res = await get(url);\n for (let i = 0; i < maxRedirects && isRedirect(res); i++) {\n url = new URL(locationOf(res) as string, url).toString();\n res = await get(url);\n }\n\n const cookieHost = options.cookieHost ? `https://${options.cookieHost}` : new URL(url).origin;\n const cookies = (await http.jar.getCookies(cookieHost)).map((c: Cookie) => ({\n name: c.key,\n value: c.value,\n }));\n return { steamId: confirmation.steamId, finalUrl: url, cookies };\n}\n","import { URLS } from \"../core/constants.js\";\nimport { httpError } from \"../http/checkers.js\";\nimport type { HttpClient } from \"../http/HttpClient.js\";\n\n// 2025 trade-protection notice; Steam blocks send() until it's acknowledged once. Plain community POST\n// — no mobileconf, no identitySecret. Idempotent on the server side.\nexport async function acknowledgeTradeProtection(http: HttpClient): Promise<void> {\n const sessionid = await http.getSessionId();\n const res = await http.post<unknown>(`${URLS.community}/trade/new/acknowledge`, {\n form: { sessionid, message: 1 },\n });\n if (res.statusCode !== 200) throw httpError(res);\n}\n","import { DEFAULT_CONTEXTID, LANG, URLS } from \"../core/constants.js\";\nimport { SteamError } from \"../core/errors.js\";\nimport { type Page, paginate } from \"../core/paginate.js\";\nimport { parseStrError } from \"../core/parseStrError.js\";\nimport { RETRY_AFTER } from \"../core/rateLimits.js\";\nimport type { WebTradeEligibility } from \"../core/types.js\";\nimport { checkCommunityError, httpError } from \"../http/checkers.js\";\nimport type { HttpClient } from \"../http/HttpClient.js\";\nimport { inventoryFailureError } from \"../http/tradePageError.js\";\nimport type { WebApiClient } from \"../http/webApi.js\";\nimport {\n type EconItem,\n parseInventory,\n parsePartnerInventory,\n type RawInventoryResponse,\n type RawPartnerInventoryResponse,\n} from \"../models/EconItem.js\";\nimport type { SessionManager } from \"../session/SessionManager.js\";\nimport type { ConfirmationManager } from \"./confirmations.js\";\nimport { type OpenidLoginOptions, type OpenidLoginResult, steamOpenidLogin } from \"./openid.js\";\nimport { acknowledgeTradeProtection } from \"./tradeProtection.js\";\n\nconst INVENTORY_PAGE_SIZE = 2000;\n\nexport interface GetInventoryOptions {\n steamId?: string;\n tradableOnly?: boolean;\n}\n\nexport interface SteamProfile {\n steamId: string;\n personaName: string;\n avatar: string;\n accountCreated: Date | null;\n tradeBanState: string;\n isLimited: boolean;\n vacBanned: boolean;\n privacyState: string;\n}\n\nexport class CommunityNamespace {\n constructor(\n private readonly http: HttpClient,\n private readonly session: SessionManager,\n private readonly confirmations: ConfirmationManager,\n private readonly api: WebApiClient,\n ) {}\n\n acknowledgeTradeProtection(): Promise<void> {\n return acknowledgeTradeProtection(this.http);\n }\n\n // Our trade URL, scraped from /profiles/<id>/tradeoffers/privacy directly (we know our steamid; skip upstream's /my redirect).\n async getTradeURL(): Promise<{ url: string; token: string }> {\n await this.session.getAccessToken();\n const steamId = this.session.steamID.getSteamID64();\n const res = await this.http.get<string>(\n `${URLS.community}/profiles/${steamId}/tradeoffers/privacy`,\n { responseType: \"text\", headers: { Referer: `${URLS.community}/profiles/${steamId}` } },\n );\n if (res.statusCode !== 200) throw httpError(res);\n const html = res.body;\n checkCommunityError(html);\n\n const match = html.match(\n /https?:\\/\\/(?:www\\.)?steamcommunity\\.com\\/tradeoffer\\/new\\/\\?partner=\\d+(?:&|&)token=([a-zA-Z0-9\\-_]+)/,\n );\n if (!match?.[1]) throw new SteamError(\"Failed to parse trade URL from the privacy page\");\n return { url: match[0].replace(/&/g, \"&\"), token: match[1] };\n }\n\n // Regenerate our trade URL/token (invalidates the old one).\n async changeTradeURL(): Promise<{ url: string; token: string }> {\n await this.session.getAccessToken();\n const steamId = this.session.steamID.getSteamID64();\n const sessionid = await this.http.getSessionId();\n const res = await this.http.post<unknown>(\n `${URLS.community}/profiles/${steamId}/tradeoffers/newtradeurl`,\n { responseType: \"json\", form: { sessionid } },\n );\n if (res.statusCode !== 200) throw httpError(res);\n // Steam returns either a bare JSON string token or { token }.\n const body = res.body;\n const token =\n typeof body === \"string\" ? body : String((body as { token?: string })?.token ?? \"\");\n if (!token) throw new SteamError(\"Failed to parse the new trade token\");\n const accountId = this.session.steamID.accountid;\n return { url: `${URLS.community}/tradeoffer/new/?partner=${accountId}&token=${token}`, token };\n }\n\n // Profile summary from the community XML (one request). Steam level isn't here — use getSteamLevel().\n async getProfile(steamId?: string): Promise<SteamProfile> {\n await this.session.getAccessToken();\n const id = steamId ?? this.session.steamID.getSteamID64();\n const res = await this.http.get<string>(`${URLS.community}/profiles/${id}?xml=1`, {\n responseType: \"text\",\n });\n if (res.statusCode !== 200) throw httpError(res);\n const xml = res.body;\n checkCommunityError(xml);\n if (!xml.includes(\"<steamID64>\")) throw new SteamError(\"Failed to load the profile XML\");\n\n const memberSince = xmlValue(xml, \"memberSince\");\n const created = memberSince ? new Date(memberSince) : null;\n\n return {\n steamId: id,\n personaName: xmlValue(xml, \"steamID\") ?? \"\",\n avatar: xmlValue(xml, \"avatarFull\") ?? \"\",\n accountCreated: created && !Number.isNaN(created.getTime()) ? created : null,\n tradeBanState: xmlValue(xml, \"tradeBanState\") ?? \"None\",\n isLimited: xmlValue(xml, \"isLimitedAccount\") === \"1\",\n vacBanned: xmlValue(xml, \"vacBanned\") === \"1\",\n privacyState: xmlValue(xml, \"privacyState\") ?? \"\",\n };\n }\n\n // Run Steam's web-trade eligibility check. The endpoint 302s back (we don't follow), priming the\n // session and leaving a `webTradeEligibility` cookie that carries the verdict — whether trades are\n // allowed plus the active Steam Guard / new-device holds gating them. We decode and return it 1:1.\n async getWebTradeEligibility(): Promise<WebTradeEligibility> {\n await this.session.getAccessToken();\n const res = await this.http.get<string>(`${URLS.community}/market/eligibilitycheck/`, {\n responseType: \"text\",\n headers: { Referer: `${URLS.community}/` },\n });\n if (res.statusCode >= 400) throw httpError(res);\n const raw = await this.http.getCookie(\"webTradeEligibility\");\n if (!raw) throw new SteamError(\"Steam did not return a webTradeEligibility cookie\");\n try {\n return JSON.parse(decodeURIComponent(raw)) as WebTradeEligibility;\n } catch {\n throw new SteamError(\"Failed to parse the webTradeEligibility cookie\");\n }\n }\n\n // Log into a third-party site that offers \"Sign in through Steam\" (OpenID 2.0), spending this live\n // web session. Returns the cookies the site set - carry them into your own HTTP client for its API.\n async openidLogin(options: OpenidLoginOptions): Promise<OpenidLoginResult> {\n await this.session.getAccessToken();\n return steamOpenidLogin(this.http, options);\n }\n\n // Steam level via IPlayerService (accepts the access token — no API key needed).\n async getSteamLevel(steamId?: string): Promise<number> {\n const id = steamId ?? this.session.steamID.getSteamID64();\n const res = await this.api.call<{ response?: { player_level?: number } }>({\n httpMethod: \"GET\",\n iface: \"IPlayerService\",\n method: \"GetSteamLevel\",\n input: { steamid: id },\n });\n return res.response?.player_level ?? 0;\n }\n\n // Existing Web API key, else register one (auto-confirms via identitySecret). null if ineligible.\n async ensureApiKey(domain = \"assetpay.gg\"): Promise<string | null> {\n await this.session.getAccessToken();\n const res = await this.http.get<string>(`${URLS.community}/dev/apikey?l=english`, {\n responseType: \"text\",\n });\n if (res.statusCode !== 200) throw httpError(res);\n const body = res.body;\n const key = body.match(/<p>Key:\\s*([0-9A-F]+)<\\/p>/i)?.[1];\n if (key) return key;\n if (\n /validated email address|Steam Guard Mobile Authenticator|<h2>Access Denied<\\/h2>/i.test(body)\n ) {\n return null;\n }\n return this.requestApiKey(domain);\n }\n\n private async requestApiKey(domain: string, requestId = \"0\"): Promise<string | null> {\n const sessionid = await this.http.getSessionId();\n const res = await this.http.post<{ api_key?: string; request_id?: string }>(\n `${URLS.community}/dev/requestkey`,\n {\n responseType: \"json\",\n form: { domain, request_id: requestId, sessionid, agreeToTerms: \"true\" },\n },\n );\n if (res.statusCode !== 200) throw httpError(res);\n const body = res.body ?? {};\n if (body.api_key) return body.api_key;\n // Pending: Steam wants a mobile confirmation. Auto-accept it (needs identitySecret), then retry.\n if (body.request_id) {\n try {\n await this.confirmations.acceptConfirmationForObject(body.request_id);\n } catch {\n return null;\n }\n return this.requestApiKey(domain, body.request_id);\n }\n return null;\n }\n\n async getInventory(\n appid: number,\n contextid: string = DEFAULT_CONTEXTID,\n options: GetInventoryOptions = {},\n ): Promise<EconItem[]> {\n await this.session.getAccessToken();\n const ownId = this.session.steamID.getSteamID64();\n const steamId = options.steamId ?? ownId;\n const tradableOnly = options.tradableOnly ?? false;\n return steamId === ownId\n ? this.getOwnInventoryItems(steamId, appid, contextid, tradableOnly)\n : this.getTheirInventory(steamId, appid, contextid, tradableOnly);\n }\n\n // Own inventory uses the legacy /inventory/json/ endpoint: near-nonexistent rate limits, surfaces\n // trade-protected items, and the rg* response shape matches /partnerinventory/. The modern\n // IEconService/GetInventoryItemsWithDescriptions endpoint trips Steam's silent throttle (returns\n // {response:{}}) on ≥2 calls/sec, which makes it unfit for repeated use.\n // trading=1 is Steam's server-side tradable filter; legacy endpoint has no other knob for it.\n private getOwnInventoryItems(\n steamId: string,\n appid: number,\n contextid: string,\n tradableOnly: boolean,\n ): Promise<EconItem[]> {\n const url = `${URLS.community}/profiles/${steamId}/inventory/json/${appid}/${contextid}`;\n return paginate<EconItem, number>(async (start): Promise<Page<EconItem, number>> => {\n const res = await this.http.get<RawPartnerInventoryResponse>(url, {\n responseType: \"json\",\n searchParams: {\n trading: tradableOnly ? 1 : 0,\n preserve_bbcode: 1,\n l: LANG.l,\n ...(start !== undefined ? { start } : {}),\n },\n headers: { Referer: `${URLS.community}/profiles/${steamId}/inventory` },\n });\n if (res.statusCode !== 200) throw httpError(res, RETRY_AFTER.inventory);\n const body = res.body;\n if (!body?.success) {\n throw new SteamError(body?.error ?? body?.Error ?? \"Malformed inventory response\");\n }\n\n const next =\n body.more && typeof body.more_start === \"number\" && body.more_start > (start ?? 0)\n ? body.more_start\n : undefined;\n return { items: parsePartnerInventory(body, contextid, tradableOnly), next };\n });\n }\n\n // Their inventory uses the new /inventory/ endpoint (the legacy one only serves the logged-in user).\n private getTheirInventory(\n steamId: string,\n appid: number,\n contextid: string,\n tradableOnly: boolean,\n ): Promise<EconItem[]> {\n const url = `${URLS.community}/inventory/${steamId}/${appid}/${contextid}`;\n return paginate<EconItem, string>(async (startAssetId): Promise<Page<EconItem, string>> => {\n const res = await this.http.get<RawInventoryResponse>(url, {\n responseType: \"json\",\n searchParams: {\n l: LANG.l,\n count: INVENTORY_PAGE_SIZE,\n raw_asset_properties: 1,\n preserve_bbcode: 1,\n start_assetid: startAssetId,\n },\n headers: { Referer: `${URLS.community}/profiles/${steamId}/inventory` },\n });\n const body = res.body;\n\n if (res.statusCode === 403 && !body) {\n throw await inventoryFailureError(\n this.http,\n steamId,\n undefined,\n \"This profile is private.\",\n );\n }\n if (res.statusCode === 500 && body?.error) throw parseStrError(body.error);\n if (res.statusCode !== 200) throw httpError(res, RETRY_AFTER.inventory);\n\n if (!body?.success) {\n throw await inventoryFailureError(\n this.http,\n steamId,\n undefined,\n body?.error ?? body?.Error,\n );\n }\n // Empty inventory: Steam returns success with no assets.\n if (!body.assets) return { items: [], next: undefined };\n\n return {\n items: parseInventory(body, contextid, tradableOnly),\n next: body.more_items && body.last_assetid ? body.last_assetid : undefined,\n };\n });\n }\n}\n\n// Read a profile-XML element's text, tolerating optional CDATA wrapping.\nfunction xmlValue(xml: string, tag: string): string | undefined {\n const m = xml.match(new RegExp(`<${tag}>(?:<!\\\\[CDATA\\\\[)?([\\\\s\\\\S]*?)(?:\\\\]\\\\]>)?</${tag}>`));\n return m?.[1]?.trim() || undefined;\n}\n","import { URLS } from \"../core/constants.js\";\nimport { SteamError } from \"../core/errors.js\";\nimport { time as steamTotpTime } from \"../crypto/steamTotp.js\";\nimport { httpError } from \"./checkers.js\";\nimport type { HttpClient } from \"./HttpClient.js\";\n\n// Steam server-time offset via ITwoFactorService/QueryTime — used by mobileconf to sign requests\n// with Steam's clock instead of the local one (Windows hosts drift; the 30s TOTP/conf window is\n// unforgiving). Goes through HttpClient so it inherits the proxy + mobile headers.\nexport async function queryServerTimeOffset(http: HttpClient): Promise<number> {\n const res = await http.post<{ response?: { server_time?: string | number } }>(\n `${URLS.api}/ITwoFactorService/QueryTime/v1/`,\n { responseType: \"json\" },\n );\n if (res.statusCode !== 200) throw httpError(res);\n const serverTime = Number(res.body?.response?.server_time);\n if (!serverTime) throw new SteamError(\"Failed to query Steam server time\");\n return serverTime - steamTotpTime();\n}\n","import type SteamID from \"steamid\";\nimport { URLS } from \"../core/constants.js\";\nimport { EConfirmationType } from \"../core/enums.js\";\nimport { ConfirmationError, SteamSessionExpiredError } from \"../core/errors.js\";\nimport type { MobileProfile } from \"../core/mobileProfile.js\";\nimport * as SteamTotp from \"../crypto/steamTotp.js\";\nimport { httpError } from \"../http/checkers.js\";\nimport type { HttpClient } from \"../http/HttpClient.js\";\nimport { queryServerTimeOffset } from \"../http/queryTime.js\";\n\nexport interface Confirmation {\n id: string;\n type: number;\n creator: string;\n key: string;\n title: string;\n receiving: string;\n sending: string;\n time: string;\n timestamp: Date;\n icon: string;\n}\n\ninterface RawConfirmation {\n id: string | number;\n type: number;\n creator_id: string | number;\n nonce: string;\n type_name?: string;\n headline?: string;\n summary?: string[];\n creation_time: number;\n icon?: string;\n}\n\ninterface RawConfListResponse {\n success?: boolean;\n conf?: RawConfirmation[];\n needauth?: boolean;\n message?: string;\n detail?: string;\n}\n\ninterface RawConfActionResponse {\n success?: boolean;\n message?: string;\n}\n\ntype ConfKey = string | { tag: string; key: string };\n\nconst TIME_OFFSET_TTL_MS = 12 * 60 * 60 * 1000;\n\nexport class ConfirmationManager {\n private timeOffset: number | undefined;\n private timeOffsetAt = 0;\n private readonly usedConfTimes: number[] = [];\n\n constructor(\n private readonly http: HttpClient,\n private readonly steamID: SteamID,\n private readonly identitySecret: string | undefined,\n private readonly profile: MobileProfile,\n ) {}\n\n get hasIdentitySecret(): boolean {\n return Boolean(this.identitySecret);\n }\n\n // The mobileconf `p` device id: iOS sends a bare uppercase UUID, Android the `android:`-prefixed one. Stable id only, not part of the `k` HMAC.\n private deviceId(): string {\n const android = SteamTotp.getDeviceID(this.steamID.getSteamID64());\n return this.profile.mobileClient === \"ios\"\n ? android.replace(/^android:/, \"\").toUpperCase()\n : android;\n }\n\n async getConfirmations(time: number, key: ConfKey): Promise<Confirmation[]> {\n const { tag, k } = splitKey(key, \"conf\");\n const body = await this.getlist(k, time, tag);\n if (!body?.success) {\n if (body?.needauth) throw new SteamSessionExpiredError();\n throw new ConfirmationError(\n String(body?.message ?? body?.detail ?? \"Failed to get confirmation list\"),\n );\n }\n return (body.conf ?? []).map((c) => ({\n id: String(c.id),\n type: Number(c.type),\n creator: String(c.creator_id),\n key: String(c.nonce),\n title: `${c.type_name ?? \"Confirm\"} - ${c.headline ?? \"\"}`,\n receiving: Number(c.type) === EConfirmationType.Trade ? String(c.summary?.[1] ?? \"\") : \"\",\n sending: String(c.summary?.[0] ?? \"\"),\n time: new Date(Number(c.creation_time) * 1000).toISOString(),\n timestamp: new Date(Number(c.creation_time) * 1000),\n icon: String(c.icon ?? \"\"),\n }));\n }\n\n async respondToConfirmation(\n confID: string,\n confKey: string,\n time: number,\n key: ConfKey,\n accept: boolean,\n ): Promise<void> {\n const { tag, k } = splitKey(key, accept ? \"allow\" : \"cancel\");\n const op = accept ? \"allow\" : \"cancel\";\n // multiajaxop: ids go in the multipart body (cid[]/ck[]), op/signature stay in the query string.\n const res = await this.http.post<RawConfActionResponse>(\n `${URLS.community}/mobileconf/multiajaxop`,\n {\n responseType: \"json\",\n searchParams: { ...this.confParams(k, time, tag), op },\n multipart: [\n { name: \"cid[]\", value: confID },\n { name: \"ck[]\", value: confKey },\n ],\n },\n );\n if (res.statusCode !== 200) throw httpError(res);\n if (res.body?.success) return;\n throw new ConfirmationError(String(res.body?.message ?? \"Could not act on confirmation\"));\n }\n\n // All pending confirmations, with the list HMAC derived for you (needs identitySecret).\n async getPending(): Promise<Confirmation[]> {\n const secret = this.requireSecret();\n const offset = await this.getTimeOffset();\n const listTime = SteamTotp.time(offset);\n const listKey = SteamTotp.getConfirmationKey(secret, listTime, \"list\");\n return this.getConfirmations(listTime, { tag: \"list\", key: listKey });\n }\n\n // Accept a single confirmation by id + nonce (its `key`).\n acceptConfirmation(confID: string, nonce: string): Promise<void> {\n return this.actOnConfirmation(confID, nonce, true);\n }\n\n // Reject (cancel) a single confirmation by id + nonce.\n rejectConfirmation(confID: string, nonce: string): Promise<void> {\n return this.actOnConfirmation(confID, nonce, false);\n }\n\n // Accept every pending confirmation; returns the ones acted on. Fails fast on the first error.\n async acceptAll(): Promise<Confirmation[]> {\n const pending = await this.getPending();\n for (const c of pending) await this.acceptConfirmation(c.id, c.key);\n return pending;\n }\n\n async acceptConfirmationForObject(objectID: string): Promise<void> {\n const conf = (await this.getPending()).find((c) => c.creator === String(objectID));\n if (!conf) throw new ConfirmationError(`Could not find confirmation for object ${objectID}`);\n await this.acceptConfirmation(conf.id, conf.key);\n }\n\n private async actOnConfirmation(confID: string, nonce: string, accept: boolean): Promise<void> {\n const secret = this.requireSecret();\n const offset = await this.getTimeOffset();\n const time = this.nextConfTime(offset);\n const tag = accept ? \"accept\" : \"cancel\";\n const key = SteamTotp.getConfirmationKey(secret, time, tag);\n await this.respondToConfirmation(confID, nonce, time, { tag, key }, accept);\n }\n\n private requireSecret(): string {\n if (!this.identitySecret) {\n throw new ConfirmationError(\"identitySecret is required to respond to confirmations\");\n }\n return this.identitySecret;\n }\n\n // A distinct single-use timestamp per HMAC; bump locally past any we've already signed with.\n private nextConfTime(offset: number): number {\n let time = SteamTotp.time(offset);\n let localOffset = 0;\n while (this.usedConfTimes.includes(time)) time = SteamTotp.time(offset) + ++localOffset;\n this.usedConfTimes.push(time);\n if (this.usedConfTimes.length > 60) {\n this.usedConfTimes.splice(0, this.usedConfTimes.length - 60);\n }\n return time;\n }\n\n private async getTimeOffset(): Promise<number> {\n if (this.timeOffset !== undefined && Date.now() - this.timeOffsetAt < TIME_OFFSET_TTL_MS) {\n return this.timeOffset;\n }\n const offset = await queryServerTimeOffset(this.http);\n this.timeOffset = offset;\n this.timeOffsetAt = Date.now();\n return offset;\n }\n\n // Common mobileconf query params; the `k` HMAC authorizes the request.\n private confParams(key: string, time: number, tag: string): Record<string, string | number> {\n return {\n p: this.deviceId(),\n a: this.steamID.getSteamID64(),\n k: key,\n t: time,\n m: \"react\",\n tag,\n };\n }\n\n private async getlist(key: string, time: number, tag: string): Promise<RawConfListResponse> {\n const res = await this.http.get<RawConfListResponse>(`${URLS.community}/mobileconf/getlist`, {\n responseType: \"json\",\n searchParams: this.confParams(key, time, tag),\n });\n if (res.statusCode !== 200) throw httpError(res);\n return res.body;\n }\n}\n\nfunction splitKey(key: ConfKey, fallbackTag: string): { tag: string; k: string } {\n return typeof key === \"object\" ? { tag: key.tag, k: key.key } : { tag: fallbackTag, k: key };\n}\n","import { ETradeOfferState } from \"./enums.js\";\n\n// States where the offer can still change (pruning must not drop these).\nconst NON_TERMINAL: ReadonlySet<ETradeOfferState> = new Set([\n ETradeOfferState.Active,\n ETradeOfferState.CreatedNeedsConfirmation,\n ETradeOfferState.InEscrow,\n]);\n\nexport function isTerminalState(state: ETradeOfferState): boolean {\n return !NON_TERMINAL.has(state);\n}\n","import SteamID from \"steamid\";\nimport { SteamError } from \"./errors.js\";\nimport type { OfferTarget } from \"./types.js\";\n\nexport interface ResolvedTarget {\n steamId: string;\n token: string | undefined;\n}\n\nexport function resolveTarget(target: OfferTarget): ResolvedTarget {\n if (\"tradeUrl\" in target && target.tradeUrl) {\n const params = new URL(target.tradeUrl).searchParams;\n const partner = params.get(\"partner\");\n if (!partner) throw new SteamError(\"invalid trade URL: missing partner\");\n const accountId = Number(partner);\n if (!Number.isInteger(accountId) || accountId <= 0) {\n throw new SteamError(`invalid trade URL: non-numeric partner '${partner}'`);\n }\n return {\n steamId: SteamID.fromIndividualAccountID(accountId).getSteamID64(),\n token: params.get(\"token\") ?? undefined,\n };\n }\n if (\"steamId\" in target && target.steamId) {\n return { steamId: target.steamId, token: target.token };\n }\n throw new SteamError(\"invalid target: provide tradeUrl or steamId\");\n}\n","import { URLS } from \"../core/constants.js\";\nimport { EResult } from \"../core/enums.js\";\nimport { RateLimitError, SteamError, SteamSessionExpiredError } from \"../core/errors.js\";\nimport { httpError } from \"./checkers.js\";\nimport type { HttpClient } from \"./HttpClient.js\";\n\ntype Scalar = string | number | boolean;\n\nexport interface ApiCallParams {\n httpMethod: \"GET\" | \"POST\";\n iface: string;\n method: string;\n version?: number;\n input?: Record<string, Scalar | undefined>;\n retryAfterMs?: number | null;\n}\n\ntype ApiBody = { response?: Record<string, unknown> } & Record<string, unknown>;\n\nexport class WebApiClient {\n constructor(\n private readonly http: HttpClient,\n private readonly getAccessToken: () => Promise<string>,\n ) {}\n\n async call<T = ApiBody>(params: ApiCallParams): Promise<T> {\n const { httpMethod, iface, method, version = 1, input = {}, retryAfterMs = null } = params;\n const accessToken = await this.getAccessToken();\n const url = `${URLS.api}/${iface}/${method}/v${version}/`;\n // origin=SteamMobile keeps us identified as the mobile app on every WebAPI call (matches\n // protoTransport's behavior on IAuthenticationService reads).\n const payload = { origin: \"SteamMobile\", ...input, access_token: accessToken };\n\n if (process.env.DEBUG_HTTP === \"1\") {\n const qs = new URLSearchParams(\n Object.entries(payload)\n .filter(([, v]) => v !== undefined)\n .map(([k, v]): [string, string] => [k, String(v)]),\n );\n console.log(`[http] ${httpMethod} ${url}?${qs.toString()}`);\n }\n\n const res = await this.http.request<ApiBody>(httpMethod, url, {\n responseType: \"json\",\n ...(httpMethod === \"GET\" ? { searchParams: payload } : { form: payload }),\n });\n\n if (res.statusCode !== 200) {\n throw httpError(res, retryAfterMs);\n }\n\n const header = res.headers[\"x-eresult\"];\n let eresult = Array.isArray(header) ? header[0] : header;\n const errorMessage = headerValue(res.headers[\"x-error_message\"]);\n const body = res.body;\n\n const responseObj =\n body && typeof body === \"object\"\n ? (body.response as Record<string, unknown> | undefined)\n : undefined;\n if (\n eresult === \"2\" &&\n body &&\n (Object.keys(body).length > 1 || (responseObj && Object.keys(responseObj).length > 0))\n ) {\n eresult = \"1\";\n }\n\n if (eresult !== undefined && eresult !== \"1\") {\n const code = Number(eresult);\n const name = EResult[code] ?? \"EResult\";\n const msg = `${name} (${eresult})${errorMessage ? `: ${errorMessage}` : \"\"}`;\n if (code === EResult.NotLoggedOn) throw new SteamSessionExpiredError(msg);\n if (code === EResult.RateLimitExceeded) {\n throw new RateLimitError({\n message: msg,\n body,\n eresult: 84,\n ...(typeof retryAfterMs === \"number\" ? { retryAfterMs } : {}),\n });\n }\n throw new SteamError(msg, { eresult: code, body });\n }\n\n if (!body || typeof body !== \"object\") {\n throw new SteamError(\"Invalid API response\", { body });\n }\n\n return body as T;\n }\n}\n\nfunction headerValue(v: string | string[] | undefined): string | undefined {\n return Array.isArray(v) ? v[0] : v;\n}\n","import { URLS } from \"../core/constants.js\";\nimport { SteamError } from \"../core/errors.js\";\nimport { resolveMobileProfile } from \"../core/mobileProfile.js\";\nimport { httpError } from \"../http/checkers.js\";\nimport { HttpClient } from \"../http/HttpClient.js\";\n\n// Steam's documented caps on these endpoints.\nconst GET_PLAYER_BANS_BATCH = 100;\nconst GET_PLAYER_SUMMARIES_BATCH = 100;\n\nexport interface SteamWebApiOptions {\n apiKey: string;\n proxy?: string;\n http?: HttpClient;\n}\n\n// ISteamUser/GetPlayerBans/v1.\nexport interface PlayerBans {\n SteamId: string;\n CommunityBanned: boolean;\n VACBanned: boolean;\n NumberOfVACBans: number;\n DaysSinceLastBan: number;\n NumberOfGameBans: number;\n EconomyBan: string;\n [key: string]: unknown;\n}\n\n// ISteamUser/GetPlayerSummaries/v2.\nexport interface PlayerSummary {\n steamid: string;\n personaname: string;\n profileurl: string;\n avatar: string;\n avatarmedium: string;\n avatarfull: string;\n avatarhash: string;\n personastate: number;\n communityvisibilitystate: number;\n profilestate?: number;\n lastlogoff?: number;\n commentpermission?: number;\n realname?: string;\n primaryclanid?: string;\n timecreated?: number;\n personastateflags?: number;\n gameid?: string;\n gameserverip?: string;\n gameextrainfo?: string;\n loccountrycode?: string;\n locstatecode?: string;\n loccityid?: number;\n [key: string]: unknown;\n}\n\n// IPlayerService/GetBadges/v1.\nexport interface Badge {\n badgeid: number;\n level: number;\n completion_time: number;\n xp: number;\n scarcity: number;\n appid?: number;\n communityitemid?: string;\n border_color?: number;\n [key: string]: unknown;\n}\n\nexport interface PlayerBadges {\n badges: Badge[];\n player_xp: number;\n player_level: number;\n player_xp_needed_to_level_up: number;\n player_xp_needed_current_level: number;\n [key: string]: unknown;\n}\n\n// Standalone Web-API client authenticated by developer key (no SteamMobile, no login, no session).\nexport class SteamWebApi {\n private readonly http: HttpClient;\n private readonly apiKey: string;\n\n constructor(options: SteamWebApiOptions) {\n this.apiKey = options.apiKey;\n this.http =\n options.http ??\n new HttpClient({\n ...(options.proxy ? { proxy: options.proxy } : {}),\n profile: resolveMobileProfile(),\n });\n }\n\n // Auto-batches into 100-id requests; preserves caller order across batches.\n async getPlayerBans(steamIds: readonly string[]): Promise<PlayerBans[]> {\n if (steamIds.length === 0) return [];\n const out: PlayerBans[] = [];\n for (let i = 0; i < steamIds.length; i += GET_PLAYER_BANS_BATCH) {\n const chunk = steamIds.slice(i, i + GET_PLAYER_BANS_BATCH);\n const res = await this.http.get<{ players?: PlayerBans[] }>(\n `${URLS.api}/ISteamUser/GetPlayerBans/v1/`,\n {\n responseType: \"json\",\n searchParams: { key: this.apiKey, steamids: chunk.join(\",\") },\n },\n );\n if (res.statusCode !== 200) throw httpError(res);\n const players = res.body?.players;\n if (!Array.isArray(players)) {\n throw new SteamError(\"Invalid GetPlayerBans response\", { body: res.body });\n }\n out.push(...players);\n }\n return out;\n }\n\n // Auto-batches into 100-id requests; preserves caller order across batches.\n async getPlayerSummaries(steamIds: readonly string[]): Promise<PlayerSummary[]> {\n if (steamIds.length === 0) return [];\n const out: PlayerSummary[] = [];\n for (let i = 0; i < steamIds.length; i += GET_PLAYER_SUMMARIES_BATCH) {\n const chunk = steamIds.slice(i, i + GET_PLAYER_SUMMARIES_BATCH);\n const res = await this.http.get<{ response?: { players?: PlayerSummary[] } }>(\n `${URLS.api}/ISteamUser/GetPlayerSummaries/v2/`,\n {\n responseType: \"json\",\n searchParams: { key: this.apiKey, steamids: chunk.join(\",\") },\n },\n );\n if (res.statusCode !== 200) throw httpError(res);\n const players = res.body?.response?.players;\n if (!Array.isArray(players)) {\n throw new SteamError(\"Invalid GetPlayerSummaries response\", { body: res.body });\n }\n out.push(...players);\n }\n return out;\n }\n\n async getBadges(steamId: string): Promise<PlayerBadges> {\n const res = await this.http.get<{ response?: PlayerBadges }>(\n `${URLS.api}/IPlayerService/GetBadges/v1/`,\n {\n responseType: \"json\",\n searchParams: { key: this.apiKey, steamid: steamId },\n },\n );\n if (res.statusCode !== 200) throw httpError(res);\n const response = res.body?.response;\n if (!response || !Array.isArray(response.badges)) {\n throw new SteamError(\"Invalid GetBadges response\", { body: res.body });\n }\n return response;\n }\n}\n","// @generated by protoc-gen-es v2.12.1 with parameter \"target=ts,import_extension=js\"\n// @generated from file csgo_econ_preview.proto (syntax proto3)\n/* eslint-disable */\n\nimport type { GenFile, GenMessage } from \"@bufbuild/protobuf/codegenv2\";\nimport { fileDesc, messageDesc } from \"@bufbuild/protobuf/codegenv2\";\nimport type { Message } from \"@bufbuild/protobuf\";\n\n/**\n * Describes the file csgo_econ_preview.proto.\n */\nexport const file_csgo_econ_preview: GenFile = /*@__PURE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iIAQESFAoHcGF0dGVybhgKIAEoDUgJiAEBQgcKBV9zbG90Qg0KC19zdGlja2VyX2lkQgcKBV93ZWFyQggKBl9zY2FsZUILCglfcm90YXRpb25CCgoIX3RpbnRfaWRCCwoJX29mZnNldF94QgsKCV9vZmZzZXRfeUILCglfb2Zmc2V0X3pCCgoIX3BhdHRlcm5CDAoKX2FjY291bnRpZEIJCgdfaXRlbWlkQgsKCV9kZWZpbmRleEINCgtfcGFpbnRpbmRleEIJCgdfcmFyaXR5QgoKCF9xdWFsaXR5QgwKCl9wYWludHdlYXJCDAoKX3BhaW50c2VlZEIVChNfa2lsbGVhdGVyc2NvcmV0eXBlQhEKD19raWxsZWF0ZXJ2YWx1ZUINCgtfY3VzdG9tbmFtZUIMCgpfaW52ZW50b3J5QgkKB19vcmlnaW5CCgoIX3F1ZXN0aWRCDQoLX2Ryb3ByZWFzb25CDQoLX211c2ljaW5kZXhCCwoJX2VudGluZGV4QgsKCV9wZXRpbmRleEIICgZfc3R5bGViBnByb3RvMw\");\n\n/**\n * @generated from message CEconItemPreviewDataBlock\n */\nexport type CEconItemPreviewDataBlock = Message<\"CEconItemPreviewDataBlock\"> & {\n /**\n * @generated from field: optional uint32 accountid = 1;\n */\n accountid?: number | undefined;\n\n /**\n * @generated from field: optional uint64 itemid = 2;\n */\n itemid?: bigint | undefined;\n\n /**\n * @generated from field: optional uint32 defindex = 3;\n */\n defindex?: number | undefined;\n\n /**\n * @generated from field: optional uint32 paintindex = 4;\n */\n paintindex?: number | undefined;\n\n /**\n * @generated from field: optional uint32 rarity = 5;\n */\n rarity?: number | undefined;\n\n /**\n * @generated from field: optional uint32 quality = 6;\n */\n quality?: number | undefined;\n\n /**\n * @generated from field: optional uint32 paintwear = 7;\n */\n paintwear?: number | undefined;\n\n /**\n * @generated from field: optional uint32 paintseed = 8;\n */\n paintseed?: number | undefined;\n\n /**\n * @generated from field: optional uint32 killeaterscoretype = 9;\n */\n killeaterscoretype?: number | undefined;\n\n /**\n * @generated from field: optional uint32 killeatervalue = 10;\n */\n killeatervalue?: number | undefined;\n\n /**\n * @generated from field: optional string customname = 11;\n */\n customname?: string | undefined;\n\n /**\n * @generated from field: repeated CEconItemPreviewDataBlock.Sticker stickers = 12;\n */\n stickers: CEconItemPreviewDataBlock_Sticker[];\n\n /**\n * @generated from field: optional uint32 inventory = 13;\n */\n inventory?: number | undefined;\n\n /**\n * @generated from field: optional uint32 origin = 14;\n */\n origin?: number | undefined;\n\n /**\n * @generated from field: optional uint32 questid = 15;\n */\n questid?: number | undefined;\n\n /**\n * @generated from field: optional uint32 dropreason = 16;\n */\n dropreason?: number | undefined;\n\n /**\n * @generated from field: optional uint32 musicindex = 17;\n */\n musicindex?: number | undefined;\n\n /**\n * @generated from field: optional int32 entindex = 18;\n */\n entindex?: number | undefined;\n\n /**\n * @generated from field: optional uint32 petindex = 19;\n */\n petindex?: number | undefined;\n\n /**\n * @generated from field: repeated CEconItemPreviewDataBlock.Sticker keychains = 20;\n */\n keychains: CEconItemPreviewDataBlock_Sticker[];\n\n /**\n * @generated from field: optional uint32 style = 21;\n */\n style?: number | undefined;\n};\n\n/**\n * Describes the message CEconItemPreviewDataBlock.\n * Use `create(CEconItemPreviewDataBlockSchema)` to create a new message.\n */\nexport const CEconItemPreviewDataBlockSchema: GenMessage<CEconItemPreviewDataBlock> = /*@__PURE__*/\n messageDesc(file_csgo_econ_preview, 0);\n\n/**\n * @generated from message CEconItemPreviewDataBlock.Sticker\n */\nexport type CEconItemPreviewDataBlock_Sticker = Message<\"CEconItemPreviewDataBlock.Sticker\"> & {\n /**\n * @generated from field: optional uint32 slot = 1;\n */\n slot?: number | undefined;\n\n /**\n * @generated from field: optional uint32 sticker_id = 2;\n */\n stickerId?: number | undefined;\n\n /**\n * @generated from field: optional float wear = 3;\n */\n wear?: number | undefined;\n\n /**\n * @generated from field: optional float scale = 4;\n */\n scale?: number | undefined;\n\n /**\n * @generated from field: optional float rotation = 5;\n */\n rotation?: number | undefined;\n\n /**\n * @generated from field: optional uint32 tint_id = 6;\n */\n tintId?: number | undefined;\n\n /**\n * @generated from field: optional float offset_x = 7;\n */\n offsetX?: number | undefined;\n\n /**\n * @generated from field: optional float offset_y = 8;\n */\n offsetY?: number | undefined;\n\n /**\n * @generated from field: optional float offset_z = 9;\n */\n offsetZ?: number | undefined;\n\n /**\n * @generated from field: optional uint32 pattern = 10;\n */\n pattern?: number | undefined;\n};\n\n/**\n * Describes the message CEconItemPreviewDataBlock.Sticker.\n * Use `create(CEconItemPreviewDataBlock_StickerSchema)` to create a new message.\n */\nexport const CEconItemPreviewDataBlock_StickerSchema: GenMessage<CEconItemPreviewDataBlock_Sticker> = /*@__PURE__*/\n messageDesc(file_csgo_econ_preview, 0, 0);\n\n","import { Buffer } from \"node:buffer\";\nimport { fromBinary, fromJson, type JsonObject, toBinary, toJson } from \"@bufbuild/protobuf\";\nimport { CEconItemPreviewDataBlockSchema } from \"../protobufs/csgo_econ_preview_pb.js\";\n\nconst HEX_RE = /^[0-9a-fA-F]+$/;\nconst wearView = new DataView(new ArrayBuffer(4));\n\nconst CRC32_TABLE = new Uint32Array(256);\nfor (let i = 0; i < 256; i++) {\n let c = i;\n for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1;\n CRC32_TABLE[i] = c >>> 0;\n}\n\n/** Trailing checksum: crc32 over `[xorKey, ...protobuf]` folded with the protobuf length. */\nfunction previewChecksum(keyed: Uint8Array, protoLength: number): number {\n let crc = 0xffffffff;\n for (const byte of keyed) crc = (CRC32_TABLE[(crc ^ byte) & 0xff] as number) ^ (crc >>> 8);\n crc = (crc ^ 0xffffffff) >>> 0;\n return ((crc & 0xffff) ^ (protoLength * crc)) >>> 0;\n}\n\n/**\n * Decode a CS2 masked preview token — the asset_properties propertyid-6\n * \"certificate\" hex — into a plain JSON object (uint64 ids as strings, camelCase\n * fields, only set fields present). Layout is `[xorKey][protobuf][crc32]`: every\n * byte after the key is XOR'd with it and the trailing 4-byte crc32 dropped.\n * `paintwear` is returned as the float wear (0..1), not its raw uint32 bits.\n * Returns `null` for non-hex input.\n */\nexport function decodePreviewToken(hex: string | null | undefined): Record<string, unknown> | null {\n if (!hex || hex.length % 2 !== 0 || hex.length < 12 || !HEX_RE.test(hex)) return null;\n try {\n const bytes = Buffer.from(hex, \"hex\");\n const xorKey = bytes[0] as number;\n for (let i = 1; i < bytes.length; i++) bytes[i] = (bytes[i] as number) ^ xorKey;\n const message = fromBinary(\n CEconItemPreviewDataBlockSchema,\n bytes.subarray(1, bytes.length - 4),\n );\n const json = toJson(CEconItemPreviewDataBlockSchema, message) as Record<string, unknown>;\n if (typeof json.paintwear === \"number\") {\n wearView.setUint32(0, json.paintwear >>> 0, true);\n json.paintwear = wearView.getFloat32(0, true);\n }\n return json;\n } catch {\n return null;\n }\n}\n\n/**\n * Encode JSON back into a masked preview token — the inverse of\n * {@link decodePreviewToken}, accepting the same shape it returns. `paintwear` is read as\n * the float wear (0..1) and re-packed into its uint32 bits. `xorKey` 0 leaves the payload\n * readable; any other byte masks it the way CS2's own links do. The checksum is unkeyed\n * crc32, so this is an integrity code and not a signature. Returns `null` if the input is\n * not a valid CEconItemPreviewDataBlock.\n */\nexport function encodePreviewToken(data: Record<string, unknown>, xorKey = 0): string | null {\n if (!Number.isInteger(xorKey) || xorKey < 0 || xorKey > 0xff) return null;\n try {\n const json = { ...data };\n if (typeof json.paintwear === \"number\") {\n wearView.setFloat32(0, json.paintwear, true);\n json.paintwear = wearView.getUint32(0, true);\n }\n const proto = toBinary(\n CEconItemPreviewDataBlockSchema,\n fromJson(CEconItemPreviewDataBlockSchema, json as JsonObject),\n );\n const bytes = Buffer.alloc(proto.length + 5);\n bytes[0] = xorKey;\n bytes.set(proto, 1);\n bytes.writeUInt32BE(\n previewChecksum(bytes.subarray(0, proto.length + 1), proto.length),\n proto.length + 1,\n );\n for (let i = 1; i < bytes.length; i++) bytes[i] = (bytes[i] as number) ^ xorKey;\n return bytes.toString(\"hex\").toUpperCase();\n } catch {\n return null;\n }\n}\n","import { Buffer } from \"node:buffer\";\nimport { create, fromBinary, toBinary } from \"@bufbuild/protobuf\";\nimport {\n CAuthentication_AccessToken_GenerateForApp_RequestSchema as RequestSchema,\n CAuthentication_AccessToken_GenerateForApp_ResponseSchema as ResponseSchema,\n} from \"../protobufs/steammessages_auth_pb.js\";\nimport type { ProtoPost } from \"./protoTransport.js\";\n\nexport type { ProtoPost } from \"./protoTransport.js\";\n\nexport const GENERATE_TOKEN_URL =\n \"https://api.steampowered.com/IAuthenticationService/GenerateAccessTokenForApp/v1\";\n\nexport interface JwtPayload {\n iss?: string;\n sub?: string;\n aud?: string[];\n exp?: number;\n iat?: number;\n [k: string]: unknown;\n}\n\nexport interface MintResult {\n accessToken: string;\n refreshToken?: string;\n}\n\nexport class AccessTokenError extends Error {\n constructor(\n message: string,\n readonly eresult?: number,\n ) {\n super(message);\n this.name = \"AccessTokenError\";\n }\n}\n\nexport function decodeJwt(token: string): JwtPayload | null {\n try {\n const payload = token.split(\".\")[1];\n if (!payload) return null;\n const json = Buffer.from(payload.replace(/-/g, \"+\").replace(/_/g, \"/\"), \"base64\").toString(\n \"utf8\",\n );\n return JSON.parse(json) as JwtPayload;\n } catch {\n return null;\n }\n}\n\nexport function secondsUntilExpiry(token: string): number {\n const exp = decodeJwt(token)?.exp;\n return typeof exp === \"number\" ? exp - Math.floor(Date.now() / 1000) : Number.NaN;\n}\n\n// GenerateAccessTokenForApp_Request: refresh_token=1 string, steamid=2 fixed64, renewal_type=3.\n// renewal_type is set explicitly (even to 0) so it's always on the wire, as the iOS app sends it.\nexport function encodeGenerateForAppRequest(refreshToken: string, renew = false): Buffer {\n const sub = decodeJwt(refreshToken)?.sub;\n if (!sub) throw new AccessTokenError(\"invalid refresh token: no steamid (sub) in payload\");\n let steamId: bigint;\n try {\n steamId = BigInt(sub);\n } catch {\n throw new AccessTokenError(`invalid refresh token: non-numeric steamid '${sub}'`);\n }\n const msg = create(RequestSchema, {\n refreshToken,\n steamid: steamId,\n renewalType: renew ? 1 : 0,\n });\n return Buffer.from(toBinary(RequestSchema, msg));\n}\n\n// GenerateAccessTokenForApp_Response: access_token=1 string, refresh_token=2 string.\nexport function decodeGenerateForAppResponse(input: Buffer | Uint8Array): MintResult {\n let accessToken: string;\n let refreshToken: string;\n try {\n const msg = fromBinary(ResponseSchema, toUint8(input));\n accessToken = msg.accessToken;\n refreshToken = msg.refreshToken;\n } catch {\n throw new AccessTokenError(\"malformed GenerateAccessTokenForApp response\");\n }\n if (!accessToken) throw new AccessTokenError(\"response had no access_token field\");\n return refreshToken ? { accessToken, refreshToken } : { accessToken };\n}\n\nfunction toUint8(input: Buffer | Uint8Array): Uint8Array {\n return input instanceof Uint8Array && !Buffer.isBuffer(input) ? input : new Uint8Array(input);\n}\n\nconst ERESULT_OK = \"1\";\n\nexport async function mintAccessToken(\n refreshToken: string,\n renew: boolean,\n post: ProtoPost,\n): Promise<MintResult> {\n const req = encodeGenerateForAppRequest(refreshToken, renew);\n const { status, eresult, errorMessage, body } = await post(\n GENERATE_TOKEN_URL,\n req.toString(\"base64\"),\n );\n\n if (status < 200 || status >= 300) {\n throw new AccessTokenError(\n `GenerateAccessTokenForApp HTTP ${status} (eresult=${eresult ?? \"?\"}${errorMessage ? `, ${errorMessage}` : \"\"})`,\n eresult ? Number(eresult) : undefined,\n );\n }\n if (eresult && eresult !== ERESULT_OK) {\n throw new AccessTokenError(\n `GenerateAccessTokenForApp failed: eresult=${eresult}${errorMessage ? ` (${errorMessage})` : \"\"}`,\n Number(eresult),\n );\n }\n if (!body.length) {\n throw new AccessTokenError(\n `GenerateAccessTokenForApp empty response (eresult=${eresult ?? \"?\"})`,\n );\n }\n return decodeGenerateForAppResponse(body);\n}\n","import { EventEmitter } from \"node:events\";\nimport SteamID from \"steamid\";\nimport { AuthClient } from \"../auth/AuthClient.js\";\nimport {\n ACCESS_TOKEN_RENEW_THRESHOLD_SECONDS,\n REFRESH_TOKEN_RENEW_THRESHOLD_SECONDS,\n} from \"../core/constants.js\";\nimport { EAuthTokenRevokeAction } from \"../core/enums.js\";\nimport { isTerminalAuthEResult } from \"../core/eresults.js\";\nimport { SteamError, SteamSessionExpiredError } from \"../core/errors.js\";\nimport type { HttpClient } from \"../http/HttpClient.js\";\nimport { createProtoPost, type ProtoPost } from \"./protoTransport.js\";\nimport {\n AccessTokenError,\n decodeJwt,\n type MintResult,\n mintAccessToken,\n secondsUntilExpiry,\n} from \"./tokens.js\";\n\nexport interface SessionManagerEvents {\n refreshToken: [token: string];\n sessionExpired: [error: Error];\n debug: [message: string];\n}\n\nexport class SessionManager extends EventEmitter<SessionManagerEvents> {\n refreshToken: string;\n accessToken: string | undefined;\n readonly steamID: SteamID;\n private readonly http: HttpClient;\n private readonly protoPost: ProtoPost;\n private minting: Promise<string> | undefined;\n private revoked = false;\n\n constructor(http: HttpClient, refreshToken: string) {\n super();\n const sub = decodeJwt(refreshToken)?.sub;\n if (!sub)\n throw new SteamSessionExpiredError(\"invalid refresh token: no steamid (sub) in payload\");\n this.http = http;\n this.protoPost = createProtoPost(http);\n this.refreshToken = refreshToken;\n this.steamID = new SteamID(sub);\n }\n\n async getAccessToken(): Promise<string> {\n if (this.revoked) throw new SteamSessionExpiredError(\"session has been revoked (logged out)\");\n if (\n this.accessToken &&\n secondsUntilExpiry(this.accessToken) > ACCESS_TOKEN_RENEW_THRESHOLD_SECONDS\n ) {\n return this.accessToken;\n }\n if (!this.minting) {\n this.minting = this.mint().finally(() => {\n this.minting = undefined;\n });\n }\n return this.minting;\n }\n\n // Client ids of in-progress auth sessions (login-approval flows), not a device list.\n async listSessions(): Promise<bigint[]> {\n const accessToken = await this.getAccessToken();\n const res = await new AuthClient(this.http).getAuthSessionsForAccount(accessToken);\n return res.clientIds;\n }\n\n // Revoke this refresh token; the session is dead afterward and further calls throw.\n async logout(action: EAuthTokenRevokeAction = EAuthTokenRevokeAction.Logout): Promise<void> {\n const accessToken = await this.getAccessToken();\n await new AuthClient(this.http).revokeRefreshToken(accessToken, action);\n this.revoked = true;\n this.accessToken = undefined;\n this.emit(\"debug\", \"refresh token revoked (logout)\");\n }\n\n async setRefreshToken(refreshToken: string): Promise<void> {\n const sub = decodeJwt(refreshToken)?.sub;\n if (!sub) {\n throw new SteamSessionExpiredError(\"invalid refresh token: no steamid (sub) in payload\");\n }\n if (sub !== this.steamID.getSteamID64()) {\n throw new SteamError(\n `refresh token is for a different account (${sub} != ${this.steamID.getSteamID64()})`,\n );\n }\n this.refreshToken = refreshToken;\n this.revoked = false;\n this.accessToken = undefined;\n this.emit(\"refreshToken\", refreshToken);\n await this.getAccessToken();\n }\n\n private async mint(): Promise<string> {\n const refreshExpiresIn = secondsUntilExpiry(this.refreshToken);\n if (refreshExpiresIn <= 0) {\n throw this.expire(\"refresh token has expired — re-authentication required\");\n }\n\n const renew = refreshExpiresIn < REFRESH_TOKEN_RENEW_THRESHOLD_SECONDS;\n let result: MintResult;\n try {\n result = await mintAccessToken(this.refreshToken, renew, this.protoPost);\n } catch (err) {\n if (err instanceof AccessTokenError && isTerminalAuthFailure(err)) {\n throw this.expire(`refresh token rejected by Steam: ${err.message}`);\n }\n throw err;\n }\n\n this.accessToken = result.accessToken;\n if (result.refreshToken && result.refreshToken !== this.refreshToken) {\n this.refreshToken = result.refreshToken;\n this.emit(\"refreshToken\", result.refreshToken);\n }\n await this.applyLoginCookie();\n this.emit(\n \"debug\",\n `minted access token${renew ? \" + renewed refresh token\" : \"\"}, expires in ` +\n `${Math.round(secondsUntilExpiry(result.accessToken))}s`,\n );\n return result.accessToken;\n }\n\n // Emit sessionExpired so a global handler can trigger re-auth.\n private expire(message: string): SteamSessionExpiredError {\n const err = new SteamSessionExpiredError(message);\n this.emit(\"sessionExpired\", err);\n return err;\n }\n\n private async applyLoginCookie(): Promise<void> {\n const value = encodeURIComponent(`${this.steamID.getSteamID64()}||${this.accessToken}`);\n await this.http.setCookie(`steamLoginSecure=${value}`);\n }\n}\n\nfunction isTerminalAuthFailure(err: AccessTokenError): boolean {\n return isTerminalAuthEResult(err.eresult);\n}\n","import { URLS } from \"../core/constants.js\";\nimport { SteamError } from \"../core/errors.js\";\nimport { checkCommunityError, httpError } from \"../http/checkers.js\";\nimport type { HttpClient } from \"../http/HttpClient.js\";\n\nexport interface UserSideDetails {\n personaName: string;\n contexts: Record<string, unknown> | null;\n escrowDays: number;\n avatarIcon: string | undefined;\n avatarMedium: string | undefined;\n avatarFull: string | undefined;\n}\n\nexport interface UserPartnerDetails extends UserSideDetails {\n probation: boolean;\n}\n\nexport interface UserDetails {\n me: UserSideDetails;\n them: UserPartnerDetails;\n}\n\n// Fetch + parse the trade page for both sides of a trade. URL is either /tradeoffer/new/?partner=…\n// (unsent offer) or /tradeoffer/<id>/ (existing offer); both pages share the same JS vars + avatar\n// markup so the parser doesn't care which.\nexport async function fetchUserDetails(\n http: HttpClient,\n url: string,\n referer: string,\n myAccountId: number,\n partnerAccountId: number,\n): Promise<UserDetails> {\n const res = await http.get<string>(url, { responseType: \"text\", headers: { Referer: referer } });\n if (res.statusCode !== 200) throw httpError(res);\n const html = res.body;\n checkCommunityError(html);\n if (!html.includes(\"g_rgAppContextData\")) {\n throw new SteamError(\"Failed to load the trade page for this user\");\n }\n return parseUserDetails(html, myAccountId, partnerAccountId);\n}\n\nexport function buildPartnerTradePageUrl(partnerAccountId: number, token?: string): string {\n return `${URLS.community}/tradeoffer/new/?partner=${partnerAccountId}${token ? `&token=${token}` : \"\"}`;\n}\n\nexport function parseUserDetails(\n html: string,\n myAccountId: number,\n partnerAccountId: number,\n): UserDetails {\n const myEscrowDays = matchInt(html, /var g_daysMyEscrow = (\\d+);/);\n const theirEscrowDays = matchInt(html, /var g_daysTheirEscrow = (\\d+);/);\n // Fail loud rather than report a misleading 0 — callers trust 0 to mean \"no hold\".\n if (myEscrowDays === null || theirEscrowDays === null) {\n throw new SteamError(\"Failed to parse escrow durations from the trade page\");\n }\n\n return {\n me: {\n personaName: matchJsString(html, \"g_strYourPersonaName\") ?? \"\",\n contexts: matchJson(html, /g_rgAppContextData\\s*=\\s*(\\{.*?\\});/),\n escrowDays: myEscrowDays,\n ...matchAvatars(html, myAccountId),\n },\n them: {\n personaName: matchJsString(html, \"g_strTradePartnerPersonaName\") ?? \"\",\n contexts: matchJson(html, /g_rgPartnerAppContextData\\s*=\\s*(\\{.*?\\});/),\n escrowDays: theirEscrowDays,\n probation: /g_bTradePartnerProbation\\s*=\\s*(?:true|1)\\b/.test(html),\n ...matchAvatars(html, partnerAccountId),\n },\n };\n}\n\nfunction matchInt(html: string, re: RegExp): number | null {\n const m = html.match(re);\n return m?.[1] !== undefined ? Number.parseInt(m[1], 10) : null;\n}\n\nfunction matchJson(html: string, re: RegExp): Record<string, unknown> | null {\n const m = html.match(re);\n if (!m?.[1]) return null;\n try {\n return JSON.parse(m[1]) as Record<string, unknown>;\n } catch {\n return null;\n }\n}\n\n// Decode a `var X = \"...\";` JS string literal. JS escapes that aren't valid JSON (\\x, octal) are rare\n// in Steam's persona names, so JSON.parse covers the common cases (\\n, \\t, \\\", \\\\, \\uXXXX).\nfunction matchJsString(html: string, varName: string): string | undefined {\n const re = new RegExp(`var ${varName}\\\\s*=\\\\s*(\"(?:\\\\\\\\.|[^\"\\\\\\\\])*\");`);\n const m = html.match(re);\n if (!m?.[1]) return undefined;\n try {\n return JSON.parse(m[1]) as string;\n } catch {\n return m[1].slice(1, -1);\n }\n}\n\ninterface AvatarUrls {\n avatarIcon: string | undefined;\n avatarMedium: string | undefined;\n avatarFull: string | undefined;\n}\n\n// `<img src=\"...\" [alt=\"...\"] data-miniprofile=\"<accountid>\">`. Steam serves <icon>.jpg; size variants\n// are <icon>_medium.jpg / <icon>_full.jpg (mirrors steamcommunity's getUserDetails).\nfunction matchAvatars(html: string, accountId: number): AvatarUrls {\n const re = new RegExp(`<img src=\"([^\"]+)\"(?: alt=\"[^\"]*\")? data-miniprofile=\"${accountId}\">`);\n const m = html.match(re);\n if (!m?.[1]) return { avatarIcon: undefined, avatarMedium: undefined, avatarFull: undefined };\n const icon = m[1];\n return {\n avatarIcon: icon,\n avatarMedium: icon.replace(/\\.jpg$/, \"_medium.jpg\"),\n avatarFull: icon.replace(/\\.jpg$/, \"_full.jpg\"),\n };\n}\n","import { LANG } from \"../core/constants.js\";\nimport type { ETradeStatus } from \"../core/enums.js\";\nimport { SteamError } from \"../core/errors.js\";\nimport { RETRY_AFTER } from \"../core/rateLimits.js\";\nimport type { RawExchangeAsset, RawTradeStatus } from \"../core/types.js\";\nimport type { WebApiClient } from \"../http/webApi.js\";\nimport {\n buildDescriptionMap,\n buildItem,\n type EconItem,\n type RawDescription,\n} from \"../models/EconItem.js\";\n\n// EconItem + where it landed after settlement. new_assetid/new_contextid: Rust populates, CS2 omits.\nexport interface ExchangeItem extends EconItem {\n new_assetid?: string;\n new_contextid?: string;\n rollback_new_assetid?: string;\n rollback_new_contextid?: string;\n}\n\nexport interface ExchangeDetails {\n status: ETradeStatus;\n tradeInitTime: Date;\n settlementTime: Date | null;\n receivedItems: ExchangeItem[];\n sentItems: ExchangeItem[];\n usedInventoryFallback: boolean; // always false; inventory-diff reconcile is the server's job\n}\n\nexport interface TradeHistoryEntry extends ExchangeDetails {\n tradeId: string;\n partnerSteamId: string | undefined;\n}\n\nexport interface TradeHistory {\n trades: TradeHistoryEntry[];\n more: boolean;\n totalTrades: number | undefined;\n}\n\nexport interface TradeHistoryOptions {\n maxTrades?: number;\n startAfterTime?: number;\n startAfterTradeId?: string;\n navigatingBack?: boolean;\n includeFailed?: boolean;\n includeTotal?: boolean;\n}\n\nexport interface TradeOffersSummary {\n pending_received_count: number;\n new_received_count: number;\n updated_received_count: number;\n historical_received_count: number;\n pending_sent_count: number;\n newly_accepted_sent_count: number;\n updated_sent_count: number;\n historical_sent_count: number;\n escrow_received_count: number;\n escrow_sent_count: number;\n}\n\nfunction parseTrade(\n trade: RawTradeStatus,\n descriptions: Map<string, RawDescription>,\n): ExchangeDetails {\n const toItem = (a: RawExchangeAsset): ExchangeItem =>\n buildItem(\n a,\n descriptions.get(`${a.appid}_${a.classid}_${a.instanceid ?? \"0\"}`),\n [],\n a.contextid,\n ) as ExchangeItem;\n return {\n status: trade.status,\n tradeInitTime: new Date(trade.time_init * 1000),\n settlementTime: trade.time_settlement ? new Date(trade.time_settlement * 1000) : null,\n receivedItems: (trade.assets_received ?? []).map(toItem),\n sentItems: (trade.assets_given ?? []).map(toItem),\n usedInventoryFallback: false,\n };\n}\n\n// Needs the tradeID (set on offer accept), not the offer id.\nexport async function getTradeStatus(api: WebApiClient, tradeId: string): Promise<ExchangeDetails> {\n const body = await api.call<{\n response?: { trades?: RawTradeStatus[]; descriptions?: RawDescription[] };\n }>({\n httpMethod: \"GET\",\n iface: \"IEconService\",\n method: \"GetTradeStatus\",\n retryAfterMs: RETRY_AFTER.GetTradeStatus,\n input: { tradeid: tradeId, get_descriptions: 1, ...LANG },\n });\n\n const trades = body.response?.trades ?? [];\n // ?? the lone trade on an id-format mismatch; never guess from a multi-trade response.\n const trade =\n trades.find((t) => t.tradeid === tradeId) ?? (trades.length === 1 ? trades[0] : undefined);\n if (!trade) throw new SteamError(`Trade ${tradeId} not found in GetTradeStatus response`);\n return parseTrade(trade, buildDescriptionMap(body.response?.descriptions));\n}\n\n// Past trades, newest first. Cursor-paginate via startAfterTime + startAfterTradeId while `more`.\nexport async function getTradeHistory(\n api: WebApiClient,\n opts: TradeHistoryOptions = {},\n): Promise<TradeHistory> {\n const body = await api.call<{\n response?: {\n more?: boolean;\n total_trades?: number;\n trades?: RawTradeStatus[];\n descriptions?: RawDescription[];\n };\n }>({\n httpMethod: \"GET\",\n iface: \"IEconService\",\n method: \"GetTradeHistory\",\n retryAfterMs: RETRY_AFTER.GetTradeHistory,\n input: {\n max_trades: opts.maxTrades ?? 100,\n get_descriptions: 1,\n include_failed: opts.includeFailed ? 1 : 0,\n include_total: opts.includeTotal ? 1 : 0,\n ...(opts.startAfterTime !== undefined ? { start_after_time: opts.startAfterTime } : {}),\n ...(opts.startAfterTradeId !== undefined\n ? { start_after_tradeid: opts.startAfterTradeId }\n : {}),\n ...(opts.navigatingBack ? { navigating_back: 1 } : {}),\n ...LANG,\n },\n });\n\n const resp = body.response ?? {};\n const descriptions = buildDescriptionMap(resp.descriptions);\n const trades = (resp.trades ?? []).map((t) => ({\n ...parseTrade(t, descriptions),\n tradeId: t.tradeid,\n partnerSteamId: t.steamid_other,\n }));\n return { trades, more: resp.more ?? false, totalTrades: resp.total_trades };\n}\n\nexport async function getTradeOffersSummary(api: WebApiClient): Promise<TradeOffersSummary> {\n const body = await api.call<{ response?: Partial<TradeOffersSummary> }>({\n httpMethod: \"GET\",\n iface: \"IEconService\",\n method: \"GetTradeOffersSummary\",\n retryAfterMs: RETRY_AFTER.GetTradeOffersSummary,\n input: { time_last_visit: 0 },\n });\n const r = body.response ?? {};\n return {\n pending_received_count: r.pending_received_count ?? 0,\n new_received_count: r.new_received_count ?? 0,\n updated_received_count: r.updated_received_count ?? 0,\n historical_received_count: r.historical_received_count ?? 0,\n pending_sent_count: r.pending_sent_count ?? 0,\n newly_accepted_sent_count: r.newly_accepted_sent_count ?? 0,\n updated_sent_count: r.updated_sent_count ?? 0,\n historical_sent_count: r.historical_sent_count ?? 0,\n escrow_received_count: r.escrow_received_count ?? 0,\n escrow_sent_count: r.escrow_sent_count ?? 0,\n };\n}\n","import { EOfferFilter, ETradeOfferState } from \"../core/enums.js\";\nimport { RateLimitError } from \"../core/errors.js\";\nimport { isTerminalState } from \"../core/offerState.js\";\nimport type { PollChange, PollData, PollDataStore, PollOptions, TradeEvents } from \"./pollTypes.js\";\nimport type { TradeOffer } from \"./TradeOffer.js\";\n\nexport const DEFAULT_POLL_INTERVAL = 10_000;\nexport const DEFAULT_POLL_FULL_UPDATE_INTERVAL = 300_000;\nexport const DEFAULT_POLL_MAX_AGE_MS = 2_592_000_000; // 30 days\n// Steam backdates offer update times; re-ask 30 min before our last-seen mark so we don't miss one.\nconst POLL_BACKDATING_BUFFER = 1800;\nconst MINIMUM_POLL_INTERVAL = 1000;\n// Offers expire ~14d after creation; this margin makes prune-by-creation safe against sweep resurrection.\nconst OFFER_MAX_LIFETIME_MS = 1_209_600_000;\n\nexport interface PollSource {\n getTradeOffers(\n filter: EOfferFilter,\n historicalCutoff: Date,\n ): Promise<{ sent: TradeOffer[]; received: TradeOffer[] }>;\n emit<K extends keyof TradeEvents>(event: K, ...args: TradeEvents[K]): void;\n}\n\nfunction emptyPollData(): PollData {\n return { offersSince: 0, sent: {}, received: {}, timestamps: {} };\n}\n\nexport class Poller {\n pollData: PollData;\n private readonly pollInterval: number;\n private readonly fullInterval: number;\n private readonly maxAgeMs: number;\n private readonly cancelTime: number | undefined;\n private readonly store: PollDataStore | undefined;\n private timer: ReturnType<typeof setTimeout> | undefined;\n private running = false;\n private stopped = true;\n private loaded = false;\n\n constructor(\n private readonly source: PollSource,\n options: PollOptions = {},\n ) {\n this.pollInterval = Math.max(\n options.pollInterval ?? DEFAULT_POLL_INTERVAL,\n MINIMUM_POLL_INTERVAL,\n );\n this.fullInterval = options.pollFullUpdateInterval ?? DEFAULT_POLL_FULL_UPDATE_INTERVAL;\n this.maxAgeMs = options.maxAgeMs ?? DEFAULT_POLL_MAX_AGE_MS;\n this.cancelTime = options.cancelTime;\n this.store = options.store;\n this.pollData = options.pollData ?? emptyPollData();\n }\n\n start(): void {\n this.stopped = false;\n this.schedule(0); // immediate first tick; also a full sweep since lastFullUpdate is 0\n }\n\n stop(): void {\n this.stopped = true;\n if (this.timer) clearTimeout(this.timer);\n this.timer = undefined;\n }\n\n // Timer cycle. Never throws; returns the delay (ms) until the next poll. Loads the store once on start.\n async poll(forceFull = false): Promise<number> {\n if (this.running) return this.pollInterval;\n this.running = true;\n try {\n if (this.store && !this.loaded) await this.loadFromStore();\n let result: { changes: PollChange[]; changed: boolean };\n try {\n result = await this.runCycle(forceFull);\n } catch (err) {\n const error = err as Error;\n this.source.emit(\"debug\", `Trade offer poll failed: ${error.message}`);\n this.source.emit(\"pollFailure\", error);\n return this.backoffDelay(error);\n }\n if (this.store && result.changed) await this.persist();\n return this.pollInterval;\n } finally {\n this.running = false;\n }\n }\n\n // Timer-less single cycle for an external scheduler; throws on fetch error (unlike the timer loop).\n async pollOnce(forceFull = false): Promise<{ changes: PollChange[]; pollData: PollData }> {\n if (this.store) await this.loadFromStore();\n const { changes, changed } = await this.runCycle(forceFull);\n if (this.store && changed) await this.persist();\n return { changes, pollData: this.pollData };\n }\n\n private async loadFromStore(): Promise<void> {\n const loaded = await this.store?.load();\n if (loaded) this.pollData = loaded;\n this.loaded = true;\n }\n\n private async persist(): Promise<void> {\n try {\n await this.store?.save(this.pollData);\n } catch (err) {\n this.source.emit(\"debug\", `pollData store save failed: ${(err as Error).message}`);\n }\n }\n\n private schedule(ms: number): void {\n if (this.stopped) return;\n if (this.timer) clearTimeout(this.timer);\n this.timer = setTimeout(\n () => {\n void this.poll().then((delay) => this.schedule(delay));\n },\n Math.max(0, ms),\n );\n }\n\n // On a rate limit, wait until the bucket unlocks (if longer than our interval) to self-tune instead of hammering.\n private backoffDelay(err: Error): number {\n if (err instanceof RateLimitError) {\n const wait = err.unlockAt - Date.now();\n if (wait > this.pollInterval) return Math.max(wait, MINIMUM_POLL_INTERVAL);\n }\n return this.pollInterval;\n }\n\n private async runCycle(forceFull: boolean): Promise<{ changes: PollChange[]; changed: boolean }> {\n // Capture before touching lastFullUpdate so an offer-less full sweep still persists the advanced cadence.\n const before = JSON.stringify(this.pollData);\n const sinceBase = this.pollData.offersSince\n ? this.pollData.offersSince - POLL_BACKDATING_BUFFER\n : 0;\n let fullUpdate = forceFull;\n let cutoff = sinceBase;\n if (forceFull || Date.now() - (this.pollData.lastFullUpdate ?? 0) >= this.fullInterval) {\n fullUpdate = true;\n this.pollData.lastFullUpdate = Date.now();\n cutoff = this.sweepCutoffSeconds();\n }\n this.source.emit(\n \"debug\",\n `Polling trade offers since ${cutoff}${fullUpdate ? \" (full update)\" : \"\"}`,\n );\n\n const result = await this.source.getTradeOffers(\n fullUpdate ? EOfferFilter.All : EOfferFilter.ActiveOnly,\n new Date(cutoff * 1000),\n );\n const changes = this.process(result.sent, result.received, fullUpdate);\n if (this.cancelTime !== undefined) this.autoCancel(result.sent, this.cancelTime);\n this.prune(seenIds(result.sent, result.received));\n const changed = JSON.stringify(this.pollData) !== before;\n\n this.source.emit(\"pollSuccess\");\n if (changed) this.source.emit(\"pollData\", this.pollData);\n return { changes, changed };\n }\n\n // Auto-cancel sent offers still Active past cancelTime since their last update (McKay's cancelTime).\n // Fire-and-forget like the upstream; the resulting state change surfaces on a later poll.\n private autoCancel(sentList: TradeOffer[], cancelTime: number): void {\n const now = Date.now();\n for (const offer of sentList) {\n if (offer.state !== ETradeOfferState.Active || !offer.updated) continue;\n if (now - offer.updated.getTime() < cancelTime) continue;\n void offer.cancel().then(\n () => this.source.emit(\"sentOfferCanceled\", offer, \"cancelTime\"),\n (err: Error) =>\n this.source.emit(\"debug\", `Can't auto-cancel offer #${offer.id}: ${err.message}`),\n );\n }\n }\n\n // Bound the full sweep to the retention window so it stays cheap and can't return already-pruned offers.\n private sweepCutoffSeconds(): number {\n return Math.max(1, Math.floor((Date.now() - this.maxAgeMs) / 1000));\n }\n\n private process(\n sentList: TradeOffer[],\n receivedList: TradeOffer[],\n fullUpdate: boolean,\n ): PollChange[] {\n const changes: PollChange[] = [];\n const { sent, received, timestamps } = this.pollData;\n let hasGlitched = false;\n\n for (const offer of sentList) {\n if (!offer.id) continue;\n const known = sent[offer.id];\n if (known === undefined) {\n // Unknown sent offer: record + announce regardless of glitch (matches steam-tradeoffer-manager).\n // Skipping these strands the cutoff at 0 and re-announces them on every poll.\n this.record(changes, { type: \"unknownOfferSent\", offer });\n } else if (offer.state !== known) {\n if (offer.glitched) {\n // Defer a glitched state change so it's re-polled with full item data; blocks cutoff advance.\n hasGlitched = true;\n continue;\n }\n this.record(changes, { type: \"sentOfferChanged\", offer, oldState: known });\n }\n sent[offer.id] = offer.state;\n this.stamp(timestamps, offer);\n }\n\n for (const offer of receivedList) {\n if (!offer.id) continue;\n if (offer.glitched) {\n hasGlitched = true;\n continue;\n }\n const known = received[offer.id];\n if (known === undefined && offer.state === ETradeOfferState.Active) {\n this.record(changes, { type: \"newOffer\", offer });\n } else if (known !== undefined && offer.state !== known) {\n this.record(changes, { type: \"receivedOfferChanged\", offer, oldState: known });\n }\n received[offer.id] = offer.state;\n this.stamp(timestamps, offer);\n }\n\n // Advance the cutoff only when nothing was glitched, so incomplete offers get re-polled.\n if (!hasGlitched) {\n let latest = this.pollData.offersSince;\n for (const offer of [...sentList, ...receivedList]) {\n const updated = offer.updated ? Math.floor(offer.updated.getTime() / 1000) : 0;\n if (updated > latest) latest = updated;\n }\n // A full sweep observes all state up to now, so floor offersSince to now even when no offers\n // come back. Otherwise it stays 0 and active polls send time_historical_cutoff=0, which Steam\n // answers erratically (misses declines, resurfaces old offers as \"new\"). Our sweep is bounded\n // to maxAgeMs, so unlike McKay's epoch sweep it can legitimately return nothing.\n if (fullUpdate) latest = Math.max(latest, Math.floor(Date.now() / 1000));\n this.pollData.offersSince = latest;\n }\n return changes;\n }\n\n // Record a change and emit it as both its specific named event and the unified offerUpdate event.\n private record(changes: PollChange[], change: PollChange): void {\n changes.push(change);\n switch (change.type) {\n case \"newOffer\":\n this.source.emit(\"newOffer\", change.offer);\n break;\n case \"unknownOfferSent\":\n this.source.emit(\"unknownOfferSent\", change.offer);\n break;\n case \"sentOfferChanged\":\n this.source.emit(\"sentOfferChanged\", change.offer, change.oldState);\n break;\n case \"receivedOfferChanged\":\n this.source.emit(\"receivedOfferChanged\", change.offer, change.oldState);\n break;\n }\n const previousState = \"oldState\" in change ? change.oldState : undefined;\n this.source.emit(\"offerUpdate\", {\n offer: change.offer,\n ...(previousState !== undefined ? { previousState } : {}),\n });\n }\n\n // Drop terminal offers older than the retention window; never prune one seen this cycle.\n private prune(seen: Set<string>): void {\n const cutoff = Math.floor((Date.now() - this.maxAgeMs - OFFER_MAX_LIFETIME_MS) / 1000);\n this.pruneMap(this.pollData.sent, seen, cutoff);\n this.pruneMap(this.pollData.received, seen, cutoff);\n }\n\n private pruneMap(map: Record<string, ETradeOfferState>, seen: Set<string>, cutoff: number): void {\n for (const id of Object.keys(map)) {\n const state = map[id];\n const created = this.pollData.timestamps[id];\n if (\n !seen.has(id) &&\n state !== undefined &&\n isTerminalState(state) &&\n created !== undefined &&\n created > 0 &&\n created < cutoff\n ) {\n delete map[id];\n delete this.pollData.timestamps[id];\n }\n }\n }\n\n private stamp(timestamps: Record<string, number>, offer: TradeOffer): void {\n if (offer.id && offer.created)\n timestamps[offer.id] = Math.floor(offer.created.getTime() / 1000);\n }\n}\n\nfunction seenIds(sent: TradeOffer[], received: TradeOffer[]): Set<string> {\n const ids = new Set<string>();\n for (const offer of [...sent, ...received]) if (offer.id) ids.add(offer.id);\n return ids;\n}\n","import SteamID from \"steamid\";\nimport type { ConfirmationManager } from \"../community/confirmations.js\";\nimport { acknowledgeTradeProtection } from \"../community/tradeProtection.js\";\nimport {\n buildPartnerTradePageUrl,\n fetchUserDetails,\n type UserDetails,\n} from \"../community/userDetails.js\";\nimport { URLS } from \"../core/constants.js\";\nimport { EConfirmationMethod, ETradeOfferState } from \"../core/enums.js\";\nimport { ConfirmationError, SteamError, SteamSessionExpiredError } from \"../core/errors.js\";\nimport { isTerminalState } from \"../core/offerState.js\";\nimport { parseStrError } from \"../core/parseStrError.js\";\nimport type { OfferTarget, RawAsset, RawCEconTradeOffer, TradeItem } from \"../core/types.js\";\nimport { httpError } from \"../http/checkers.js\";\nimport type { HttpClient } from \"../http/HttpClient.js\";\nimport { buildItem, type EconItem, type RawDescription } from \"../models/EconItem.js\";\nimport type { SessionManager } from \"../session/SessionManager.js\";\nimport type { ExchangeDetails } from \"./exchange.js\";\nimport type { TradeNamespace } from \"./TradeNamespace.js\";\n\nexport type SendResult = \"sent\" | \"needs_confirmation\";\nexport type AcceptResult = \"accepted\" | \"escrow\" | \"needs_confirmation\";\n\nconst TWO_WEEKS_MS = 1_209_600_000;\n\nexport interface TradeOfferDeps {\n http: HttpClient;\n session: SessionManager;\n confirmations: ConfirmationManager;\n trade: TradeNamespace;\n}\n\ninterface RawSendResponse {\n tradeofferid?: string;\n needs_mobile_confirmation?: boolean;\n needs_email_confirmation?: boolean;\n strError?: string;\n}\n\ninterface RawAcceptResponse {\n tradeid?: string;\n needs_mobile_confirmation?: boolean;\n needs_email_confirmation?: boolean;\n strError?: string;\n}\n\ninterface RawCancelResponse {\n tradeofferid?: string;\n strError?: string;\n}\n\nexport class TradeOffer {\n id: string | undefined;\n readonly partner: SteamID;\n token: string | undefined;\n message = \"\";\n state: ETradeOfferState = ETradeOfferState.Invalid;\n itemsToGive: TradeItem[] = [];\n itemsToReceive: TradeItem[] = [];\n isOurOffer = true;\n tradeID: string | undefined;\n confirmationMethod: EConfirmationMethod = EConfirmationMethod.None;\n escrowEnds: Date | undefined;\n // 2025 trade-protection hold end (== trade time_settlement); set once Accepted. Distinct from escrowEnds.\n settlementDate: Date | undefined;\n delaySettlement = false;\n created: Date | undefined;\n updated: Date | undefined;\n expires: Date | undefined;\n fromRealTimeTrade = false;\n // Offer with missing item names (descriptions not ready) or no items; polling must not advance its cutoff past it.\n glitched = false;\n private countering: string | undefined;\n\n constructor(\n private readonly deps: TradeOfferDeps,\n init: { partner: SteamID; token?: string; id?: string },\n ) {\n this.partner = init.partner;\n this.token = init.token;\n this.id = init.id;\n }\n\n // `descriptions` (from get_descriptions=1) enriches each item into a full EconItem; glitch detection needs the names.\n static fromData(\n deps: TradeOfferDeps,\n raw: RawCEconTradeOffer,\n descriptions?: Map<string, RawDescription>,\n ): TradeOffer {\n if (!raw.accountid_other) {\n throw new SteamError(`Trade offer ${raw.tradeofferid} is missing a partner accountid`);\n }\n const partner = SteamID.fromIndividualAccountID(raw.accountid_other);\n const offer = new TradeOffer(deps, { partner, id: raw.tradeofferid });\n offer.message = raw.message ?? \"\";\n offer.state = raw.trade_offer_state;\n offer.isOurOffer = raw.is_our_offer;\n offer.fromRealTimeTrade = raw.from_real_time_trade ?? false;\n const mapItem = (a: RawAsset): TradeItem =>\n descriptions\n ? buildItem(a, descriptions.get(`${a.appid}_${a.classid}_${a.instanceid}`), [], a.contextid)\n : toTradeItem(a);\n offer.itemsToGive = (raw.items_to_give ?? []).map(mapItem);\n offer.itemsToReceive = (raw.items_to_receive ?? []).map(mapItem);\n offer.confirmationMethod = raw.confirmation_method ?? EConfirmationMethod.None;\n if (raw.tradeid) offer.tradeID = raw.tradeid;\n if (raw.escrow_end_date) offer.escrowEnds = new Date(raw.escrow_end_date * 1000);\n if (raw.settlement_date) offer.settlementDate = new Date(raw.settlement_date * 1000);\n offer.delaySettlement = raw.delay_settlement ?? false;\n if (raw.time_created) offer.created = new Date(raw.time_created * 1000);\n if (raw.time_updated) offer.updated = new Date(raw.time_updated * 1000);\n if (raw.expiration_time) offer.expires = new Date(raw.expiration_time * 1000);\n\n const allItems = [...offer.itemsToGive, ...offer.itemsToReceive];\n offer.glitched =\n !isTerminalState(offer.state) &&\n (allItems.length === 0 ||\n (descriptions !== undefined && allItems.some((i) => !(i as EconItem).name)));\n return offer;\n }\n\n // Faithful to upstream itemEquals: same appid + contextid + assetid.\n containsItem(item: { appid: number; contextid: string; assetid: string }): boolean {\n return [...this.itemsToGive, ...this.itemsToReceive].some(\n (i) => i.appid === item.appid && i.contextid === item.contextid && i.assetid === item.assetid,\n );\n }\n\n give(items: TradeItem[]): this {\n this.itemsToGive.push(...items);\n return this;\n }\n\n receive(items: TradeItem[]): this {\n this.itemsToReceive.push(...items);\n return this;\n }\n\n setMessage(message: string): this {\n if (this.id) throw new SteamError(\"Cannot set a message on an already-sent offer\");\n this.message = message.slice(0, 128);\n return this;\n }\n\n async send(): Promise<SendResult> {\n if (this.id) throw new SteamError(\"This offer has already been sent\");\n if (this.itemsToGive.length + this.itemsToReceive.length === 0) {\n throw new SteamError(\"Cannot send an empty trade offer\");\n }\n\n await this.deps.session.getAccessToken();\n const sessionid = await this.deps.http.getSessionId();\n // Acknowledge the 2025 trade-protection notice so send isn't blocked; tolerate ack failures but not an expired session.\n await acknowledgeTradeProtection(this.deps.http).catch((err) => {\n if (err instanceof SteamSessionExpiredError) throw err;\n });\n\n const offerdata = {\n newversion: true,\n version: this.itemsToGive.length + this.itemsToReceive.length + 1,\n me: { assets: this.itemsToGive.map(toAsset), currency: [], ready: false },\n them: { assets: this.itemsToReceive.map(toAsset), currency: [], ready: false },\n };\n const createParams: Record<string, string> = {};\n if (this.token) createParams.trade_offer_access_token = this.token;\n\n const res = await this.deps.http.post<RawSendResponse>(\n `${URLS.community}/tradeoffer/new/send`,\n {\n responseType: \"json\",\n referer: this.newOfferReferer(),\n form: {\n sessionid,\n serverid: 1,\n partner: this.partner.getSteamID64(),\n tradeoffermessage: this.message,\n json_tradeoffer: JSON.stringify(offerdata),\n captcha: \"\",\n trade_offer_create_params: JSON.stringify(createParams),\n ...(this.countering ? { tradeofferid_countered: this.countering } : {}),\n },\n },\n );\n\n if (res.statusCode === 401) throw new SteamSessionExpiredError();\n const body = res.body;\n // Steam often returns strError on a non-200; surface the typed error first.\n if (body?.strError) throw parseStrError(body.strError);\n if (res.statusCode !== 200) throw httpError(res);\n if (!body) throw new SteamError(\"Malformed JSON response\");\n\n if (body.tradeofferid) {\n this.id = body.tradeofferid;\n this.state = ETradeOfferState.Active;\n this.created = new Date();\n this.updated = new Date();\n this.expires = new Date(Date.now() + TWO_WEEKS_MS);\n }\n this.confirmationMethod = EConfirmationMethod.None;\n if (body.needs_email_confirmation) {\n this.state = ETradeOfferState.CreatedNeedsConfirmation;\n this.confirmationMethod = EConfirmationMethod.Email;\n }\n if (body.needs_mobile_confirmation) {\n this.state = ETradeOfferState.CreatedNeedsConfirmation;\n this.confirmationMethod = EConfirmationMethod.MobileApp;\n }\n\n if (this.state === ETradeOfferState.CreatedNeedsConfirmation) return \"needs_confirmation\";\n if (body.tradeofferid) return \"sent\";\n throw new SteamError(\"Unknown response sending trade offer\");\n }\n\n async accept(): Promise<AcceptResult> {\n if (!this.id) throw new SteamError(\"Cannot accept an unsent offer\");\n if (this.state !== ETradeOfferState.Active) {\n throw new SteamError(`Offer #${this.id} is not active, so it may not be accepted`);\n }\n if (this.isOurOffer) throw new SteamError(`Cannot accept our own offer #${this.id}`);\n\n await this.deps.session.getAccessToken();\n const sessionid = await this.deps.http.getSessionId();\n const res = await this.deps.http.post<RawAcceptResponse>(\n `${URLS.community}/tradeoffer/${this.id}/accept`,\n {\n responseType: \"json\",\n referer: `${URLS.community}/tradeoffer/${this.id}/`,\n form: {\n sessionid,\n serverid: 1,\n tradeofferid: this.id,\n partner: this.partner.getSteamID64(),\n captcha: \"\",\n },\n },\n );\n\n if (res.statusCode === 403) throw new SteamSessionExpiredError();\n const body = res.body;\n if (body?.strError) throw parseStrError(body.strError);\n if (res.statusCode !== 200) throw httpError(res);\n if (!body) throw new SteamError(\"Malformed JSON response\");\n\n if (body.tradeid) this.tradeID = body.tradeid;\n if (body.needs_mobile_confirmation || body.needs_email_confirmation) {\n this.confirmationMethod = body.needs_mobile_confirmation\n ? EConfirmationMethod.MobileApp\n : EConfirmationMethod.Email;\n return \"needs_confirmation\";\n }\n\n // The accept response doesn't flag escrow; re-read to distinguish a held trade from a settled one.\n this.state = ETradeOfferState.Accepted;\n try {\n const refreshed = await this.deps.trade.getTradeOffer(this.id);\n this.state = refreshed.state;\n this.escrowEnds = refreshed.escrowEnds;\n } catch {\n // keep optimistic Accepted; caller can reconcile via getTradeOffer\n }\n return this.state === ETradeOfferState.InEscrow ? \"escrow\" : \"accepted\";\n }\n\n async cancel(): Promise<void> {\n if (!this.id) throw new SteamError(\"Cannot cancel or decline an unsent offer\");\n if (\n this.state !== ETradeOfferState.Active &&\n this.state !== ETradeOfferState.CreatedNeedsConfirmation\n ) {\n throw new SteamError(\n `Offer #${this.id} is not active, so it may not be cancelled or declined`,\n );\n }\n\n await this.deps.session.getAccessToken();\n const sessionid = await this.deps.http.getSessionId();\n const action = this.isOurOffer ? \"cancel\" : \"decline\";\n const res = await this.deps.http.post<RawCancelResponse>(\n `${URLS.community}/tradeoffer/${this.id}/${action}`,\n {\n responseType: \"json\",\n referer: this.offerReferer(),\n form: { sessionid },\n },\n );\n\n if (res.statusCode === 401) throw new SteamSessionExpiredError();\n const body = res.body;\n if (body?.strError) throw parseStrError(body.strError);\n if (res.statusCode !== 200) throw httpError(res);\n if (!body) throw new SteamError(\"Malformed JSON response\");\n if (body.tradeofferid !== this.id) throw new SteamError(\"Wrong response cancelling offer\");\n\n this.state = this.isOurOffer ? ETradeOfferState.Canceled : ETradeOfferState.Declined;\n this.updated = new Date();\n }\n\n decline(): Promise<void> {\n return this.cancel();\n }\n\n async confirm(): Promise<void> {\n if (!this.id) throw new ConfirmationError(\"Cannot confirm an unsent offer\");\n if (!this.deps.confirmations.hasIdentitySecret) {\n throw new ConfirmationError(\n \"identitySecret is required to confirm trade offers — construct SteamMobile with { identitySecret }\",\n );\n }\n await this.deps.confirmations.acceptConfirmationForObject(this.id);\n }\n\n counter(): TradeOffer {\n if (!this.id) throw new SteamError(\"Cannot counter an unsent offer\");\n if (this.state !== ETradeOfferState.Active) {\n throw new SteamError(`Offer #${this.id} is not active, so it may not be countered`);\n }\n const next = new TradeOffer(this.deps, {\n partner: this.partner,\n ...(this.token ? { token: this.token } : {}),\n });\n next.countering = this.id;\n next.isOurOffer = true;\n // Deep-copy items so editing the counter doesn't mutate the original offer.\n next.itemsToGive = this.itemsToGive.map((i) => ({ ...i }));\n next.itemsToReceive = this.itemsToReceive.map((i) => ({ ...i }));\n next.message = this.message;\n return next;\n }\n\n // Settlement details once accepted (needs tradeID, set on accept / on a fetched accepted offer).\n getTradeStatus(): Promise<ExchangeDetails> {\n if (!this.tradeID) {\n throw new SteamError(\"No trade ID — getTradeStatus needs an accepted offer\");\n }\n return this.deps.trade.getTradeStatus({ tradeId: this.tradeID });\n }\n\n getPartnerInventory(\n appid: number,\n contextid?: string,\n tradableOnly?: boolean,\n ): Promise<EconItem[]> {\n const target = this.partnerTarget();\n return this.deps.trade.getInventory(\n target,\n appid,\n contextid,\n tradableOnly !== undefined ? { tradableOnly } : {},\n );\n }\n\n // Persona, contexts, avatars, escrow, partner probation — McKay-parity getUserDetails. Allowed for:\n // - offers we created and haven't sent yet (need friendship or the token)\n // - offers they created and sent to us, while still Active\n async getUserDetails(): Promise<UserDetails> {\n if (this.id && this.isOurOffer) {\n throw new SteamError(\"Cannot get user details for an offer that we sent\");\n }\n if (this.id && this.state !== ETradeOfferState.Active) {\n throw new SteamError(\"Cannot get user details for an offer that is sent and not Active\");\n }\n await this.deps.session.getAccessToken();\n const url = this.id\n ? `${URLS.community}/tradeoffer/${this.id}/`\n : buildPartnerTradePageUrl(this.partner.accountid, this.token);\n const referer = `${URLS.community}/profiles/${this.partner.getSteamID64()}`;\n return fetchUserDetails(\n this.deps.http,\n url,\n referer,\n this.deps.session.steamID.accountid,\n this.partner.accountid,\n );\n }\n\n private partnerTarget(): OfferTarget {\n const steamId = this.partner.getSteamID64();\n return this.token ? { steamId, token: this.token } : { steamId };\n }\n\n private newOfferReferer(): string {\n const token = this.token ? `&token=${this.token}` : \"\";\n return `${URLS.community}/tradeoffer/${this.id ?? \"new\"}/?partner=${this.partner.accountid}${token}`;\n }\n\n private offerReferer(): string {\n const token = this.token ? `&token=${this.token}` : \"\";\n return `${URLS.community}/tradeoffer/${this.id}/?partner=${this.partner.accountid}${token}`;\n }\n}\n\nfunction toAsset(item: TradeItem): {\n appid: number;\n contextid: string;\n amount: number;\n assetid: string;\n} {\n return {\n appid: item.appid,\n contextid: item.contextid,\n amount: item.amount && item.amount > 0 ? item.amount : 1,\n assetid: item.assetid,\n };\n}\n\nfunction toTradeItem(raw: RawAsset): TradeItem {\n return {\n appid: raw.appid,\n contextid: raw.contextid,\n assetid: raw.assetid,\n amount: Number(raw.amount) || 1,\n };\n}\n","import { EventEmitter } from \"node:events\";\nimport SteamID from \"steamid\";\nimport type { ConfirmationManager } from \"../community/confirmations.js\";\nimport {\n buildPartnerTradePageUrl,\n fetchUserDetails,\n type UserDetails,\n} from \"../community/userDetails.js\";\nimport { DEFAULT_CONTEXTID, LANG, URLS } from \"../core/constants.js\";\nimport { EOfferFilter } from \"../core/enums.js\";\nimport { SteamError } from \"../core/errors.js\";\nimport { type Page, paginate } from \"../core/paginate.js\";\nimport { parseStrError } from \"../core/parseStrError.js\";\nimport { RETRY_AFTER } from \"../core/rateLimits.js\";\nimport { resolveTarget } from \"../core/target.js\";\nimport type { OfferTarget, RawAsset, RawCEconTradeOffer } from \"../core/types.js\";\nimport { httpError } from \"../http/checkers.js\";\nimport type { HttpClient } from \"../http/HttpClient.js\";\nimport { inventoryFailureError } from \"../http/tradePageError.js\";\nimport type { WebApiClient } from \"../http/webApi.js\";\nimport {\n buildDescriptionMap,\n type EconItem,\n parsePartnerInventory,\n type RawPartnerInventoryResponse,\n} from \"../models/EconItem.js\";\nimport type { SessionManager } from \"../session/SessionManager.js\";\nimport {\n type ExchangeDetails,\n getTradeHistory as fetchTradeHistory,\n getTradeOffersSummary as fetchTradeOffersSummary,\n getTradeStatus as fetchTradeStatus,\n type TradeHistory,\n type TradeHistoryOptions,\n type TradeOffersSummary,\n} from \"./exchange.js\";\nimport { Poller } from \"./polling.js\";\nimport type { PollChange, PollData, PollOptions, TradeEvents } from \"./pollTypes.js\";\nimport { TradeOffer, type TradeOfferDeps } from \"./TradeOffer.js\";\n\nconst FUTURE_CUTOFF_MS = 31_536_000_000; // 1 year ahead = \"no historical offers\"\n\nexport interface EscrowSide {\n escrow_end_duration_seconds: number;\n}\n\nexport interface EscrowHold {\n me: EscrowSide;\n them: EscrowSide;\n both: EscrowSide;\n}\n\ninterface RawEscrowResponse {\n my_escrow?: EscrowSide;\n their_escrow?: EscrowSide;\n both_escrow?: EscrowSide;\n}\n\nexport class TradeNamespace extends EventEmitter<TradeEvents> {\n private poller: Poller | undefined;\n\n constructor(\n private readonly api: WebApiClient,\n private readonly http: HttpClient,\n private readonly session: SessionManager,\n private readonly confirmations: ConfirmationManager,\n ) {\n super();\n }\n\n private offerDeps(): TradeOfferDeps {\n return {\n http: this.http,\n session: this.session,\n confirmations: this.confirmations,\n trade: this,\n };\n }\n\n // Local only — no network until send().\n createOffer(target: OfferTarget): TradeOffer {\n const { steamId, token } = resolveTarget(target);\n return new TradeOffer(this.offerDeps(), {\n partner: new SteamID(steamId),\n ...(token ? { token } : {}),\n });\n }\n\n async getTradeOffer(id: string): Promise<TradeOffer> {\n const body = await this.api.call<{\n response?: {\n offer?: RawCEconTradeOffer;\n descriptions?: Parameters<typeof buildDescriptionMap>[0];\n };\n }>({\n httpMethod: \"GET\",\n iface: \"IEconService\",\n method: \"GetTradeOffer\",\n retryAfterMs: RETRY_AFTER.GetTradeOffer,\n input: { tradeofferid: id, get_descriptions: 1, ...LANG },\n });\n const raw = body.response?.offer;\n if (!raw) throw new SteamError(`Trade offer ${id} not found`);\n return TradeOffer.fromData(\n this.offerDeps(),\n raw,\n buildDescriptionMap(body.response?.descriptions),\n );\n }\n\n // Cursor-paginates all pages; rejects the wholly-malformed \"data temporarily unavailable\" glitch.\n async getTradeOffers(\n filter: EOfferFilter = EOfferFilter.ActiveOnly,\n historicalCutoff?: Date,\n ): Promise<{ sent: TradeOffer[]; received: TradeOffer[] }> {\n const cutoff = historicalCutoff ?? new Date(Date.now() + FUTURE_CUTOFF_MS);\n\n const sentRaw: RawCEconTradeOffer[] = [];\n const receivedRaw: RawCEconTradeOffer[] = [];\n const descriptions: NonNullable<Parameters<typeof buildDescriptionMap>[0]> = [];\n let cursor = 0;\n\n do {\n const body = await this.api.call<{\n response?: {\n trade_offers_sent?: RawCEconTradeOffer[];\n trade_offers_received?: RawCEconTradeOffer[];\n descriptions?: NonNullable<Parameters<typeof buildDescriptionMap>[0]>;\n next_cursor?: number;\n };\n }>({\n httpMethod: \"GET\",\n iface: \"IEconService\",\n method: \"GetTradeOffers\",\n retryAfterMs: RETRY_AFTER.GetTradeOffers,\n input: {\n get_sent_offers: 1,\n get_received_offers: 1,\n get_descriptions: 1,\n active_only: filter === EOfferFilter.ActiveOnly ? 1 : 0,\n historical_only: filter === EOfferFilter.HistoricalOnly ? 1 : 0,\n time_historical_cutoff: Math.floor(cutoff.getTime() / 1000),\n cursor,\n ...LANG,\n },\n });\n const response = body.response ?? {};\n sentRaw.push(...(response.trade_offers_sent ?? []));\n receivedRaw.push(...(response.trade_offers_received ?? []));\n descriptions.push(...(response.descriptions ?? []));\n const next = response.next_cursor ?? 0;\n if (next !== 0 && next === cursor) break; // cursor not advancing — stop rather than loop forever\n cursor = next;\n if (cursor) this.emit(\"debug\", `GetTradeOffers with cursor ${cursor}`);\n } while (cursor);\n\n const all = [...sentRaw, ...receivedRaw];\n if (all.length > 0 && (all.every(offerMalformed) || all.some(offerSuperMalformed))) {\n throw new SteamError(\"Data temporarily unavailable\");\n }\n\n const descMap = buildDescriptionMap(descriptions);\n const build = (raw: RawCEconTradeOffer): TradeOffer =>\n TradeOffer.fromData(this.offerDeps(), sanitizeRawOffer(raw), descMap);\n return { sent: sentRaw.map(build), received: receivedRaw.map(build) };\n }\n\n // Settlement details for a completed/escrowed trade (tradeID, not offer id).\n getTradeStatus(opts: { tradeId: string }): Promise<ExchangeDetails> {\n return fetchTradeStatus(this.api, opts.tradeId);\n }\n\n // Persona, contexts, escrow days, avatars, and partner probation for both sides — same trade-page\n // scrape as offer.getUserDetails(), but addressed by target instead of by an existing offer.\n async getUserDetails(target: OfferTarget): Promise<UserDetails> {\n await this.session.getAccessToken();\n const { steamId, token } = resolveTarget(target);\n const partnerAccountId = new SteamID(steamId).accountid;\n return fetchUserDetails(\n this.http,\n buildPartnerTradePageUrl(partnerAccountId, token),\n `${URLS.community}/profiles/${steamId}`,\n this.session.steamID.accountid,\n partnerAccountId,\n );\n }\n\n // Escrow hold (seconds) via IEconService/GetTradeHoldDurations — escrow-only, lightweight. For\n // everything together (escrow + persona + avatars + contexts), use offer.getUserDetails() instead.\n async getEscrow(target: OfferTarget): Promise<EscrowHold> {\n const { steamId, token } = resolveTarget(target);\n const body = await this.api.call<{ response?: RawEscrowResponse }>({\n httpMethod: \"GET\",\n iface: \"IEconService\",\n method: \"GetTradeHoldDurations\",\n retryAfterMs: RETRY_AFTER.GetTradeHoldDurations,\n input: {\n steamid_target: steamId,\n ...(token ? { trade_offer_access_token: token } : {}),\n },\n });\n const r = body.response ?? {};\n const zero: EscrowSide = { escrow_end_duration_seconds: 0 };\n return {\n me: r.my_escrow ?? zero,\n them: r.their_escrow ?? zero,\n both: r.both_escrow ?? zero,\n };\n }\n\n // Past trades (newest first); cursor-paginate with startAfterTime/startAfterTradeId while `more`.\n getTradeHistory(opts?: TradeHistoryOptions): Promise<TradeHistory> {\n return fetchTradeHistory(this.api, opts);\n }\n\n // Counts of pending/new/historical sent & received offers.\n getTradeOffersSummary(): Promise<TradeOffersSummary> {\n return fetchTradeOffersSummary(this.api);\n }\n\n // Re-read known offers by id; missing/errored ids are skipped so one can't fail the batch.\n async reconcile(ids: string[]): Promise<Map<string, TradeOffer>> {\n const results = await Promise.allSettled(ids.map((id) => this.getTradeOffer(id)));\n const map = new Map<string, TradeOffer>();\n results.forEach((res, i) => {\n const id = ids[i];\n if (id !== undefined && res.status === \"fulfilled\") map.set(id, res.value);\n });\n return map;\n }\n\n async getOffersContainingItems(\n items: { appid: number; contextid: string; assetid: string }[],\n includeInactive = false,\n ): Promise<TradeOffer[]> {\n const { sent, received } = await this.getTradeOffers(\n includeInactive ? EOfferFilter.All : EOfferFilter.ActiveOnly,\n );\n return [...sent, ...received].filter((offer) =>\n items.every((item) => offer.containsItem(item)),\n );\n }\n\n startPolling(options: PollOptions = {}): void {\n this.poller?.stop();\n this.poller = new Poller(this, options);\n this.poller.start();\n }\n\n stopPolling(): void {\n this.poller?.stop();\n this.poller = undefined;\n }\n\n async pollOnce(\n options: PollOptions & { forceFull?: boolean } = {},\n ): Promise<{ changes: PollChange[]; pollData: PollData }> {\n const { forceFull, ...pollOptions } = options;\n if (!this.poller) this.poller = new Poller(this, pollOptions);\n return this.poller.pollOnce(forceFull ?? false);\n }\n\n get pollData(): PollData | undefined {\n return this.poller?.pollData;\n }\n\n async getInventory(\n target: OfferTarget,\n appid: number,\n contextid: string = DEFAULT_CONTEXTID,\n options: { tradableOnly?: boolean } = {},\n ): Promise<EconItem[]> {\n const tradableOnly = options.tradableOnly ?? false;\n await this.session.getAccessToken();\n const { steamId, token } = resolveTarget(target);\n const sessionid = await this.http.getSessionId();\n const accountId = new SteamID(steamId).accountid;\n const referer = `${URLS.community}/tradeoffer/new/?partner=${accountId}${token ? `&token=${token}` : \"\"}`;\n\n return paginate<EconItem, number>(async (start): Promise<Page<EconItem, number>> => {\n const res = await this.http.get<RawPartnerInventoryResponse>(\n `${URLS.community}/tradeoffer/new/partnerinventory/`,\n {\n responseType: \"json\",\n searchParams: {\n sessionid,\n partner: steamId,\n appid,\n contextid,\n ...(token ? { token } : {}),\n ...(start !== undefined ? { start } : {}),\n l: LANG.l,\n },\n headers: { Referer: referer },\n },\n );\n\n const body = res.body;\n if (res.statusCode === 500 && body?.error) throw parseStrError(body.error);\n if (res.statusCode !== 200) throw httpError(res, RETRY_AFTER.partnerInventory);\n if (!body?.success) {\n throw await inventoryFailureError(this.http, steamId, token, body?.error ?? body?.Error);\n }\n\n // Continue only when more_start actually advances, else a stuck cursor loops forever.\n const next =\n body.more && typeof body.more_start === \"number\" && body.more_start > (start ?? 0)\n ? body.more_start\n : undefined;\n return { items: parsePartnerInventory(body, contextid, tradableOnly), next };\n });\n }\n}\n\nfunction itemMalformed(item: RawAsset): boolean {\n return !item.appid || !item.contextid || !item.assetid;\n}\n\nfunction offerSuperMalformed(offer: RawCEconTradeOffer): boolean {\n return !offer.accountid_other;\n}\n\nfunction offerMalformed(offer: RawCEconTradeOffer): boolean {\n return (\n offerSuperMalformed(offer) ||\n ((offer.items_to_give ?? []).length === 0 && (offer.items_to_receive ?? []).length === 0) ||\n (offer.items_to_give ?? []).some(itemMalformed) ||\n (offer.items_to_receive ?? []).some(itemMalformed)\n );\n}\n\nfunction sanitizeRawOffer(offer: RawCEconTradeOffer): RawCEconTradeOffer {\n return {\n ...offer,\n ...(offer.items_to_give\n ? { items_to_give: offer.items_to_give.filter((i) => !itemMalformed(i)) }\n : {}),\n ...(offer.items_to_receive\n ? { items_to_receive: offer.items_to_receive.filter((i) => !itemMalformed(i)) }\n : {}),\n };\n}\n","import { EventEmitter } from \"node:events\";\nimport type SteamID from \"steamid\";\nimport {\n type LoginWithCredentialsOptions,\n loginWithCredentials,\n} from \"./auth/loginWithCredentials.js\";\nimport { CommunityNamespace } from \"./community/CommunityNamespace.js\";\nimport { ConfirmationManager } from \"./community/confirmations.js\";\nimport type { OpenidLoginOptions, OpenidLoginResult } from \"./community/openid.js\";\nimport {\n type MobilePlatform,\n type MobileProfile,\n resolveMobileProfile,\n} from \"./core/mobileProfile.js\";\nimport { HttpClient, type HttpResponse, type RequestOptions } from \"./http/HttpClient.js\";\nimport { WebApiClient } from \"./http/webApi.js\";\nimport { SessionManager } from \"./session/SessionManager.js\";\nimport type { PollOptions, TradeEvents } from \"./trade/pollTypes.js\";\nimport { TradeNamespace } from \"./trade/TradeNamespace.js\";\n\n// Root surface: session lifecycle events + all trade events re-emitted (so consumers can listen on\n// `bot` or `bot.trade`). `debug` comes from TradeEvents.\nexport interface SteamMobileEvents extends TradeEvents {\n refreshToken: [token: string];\n sessionExpired: [error: Error];\n}\n\nexport interface SteamMobileOptions {\n refreshToken: string;\n identitySecret?: string;\n proxy?: string;\n // Wire impersonation: a string picks a preset (\"ios\" default, \"android\"); an object overrides individual fields.\n mobileProfile?: MobilePlatform | Partial<MobileProfile>;\n // Start polling after login. `true` uses defaults; pass PollOptions to tune cadence or resume from saved pollData.\n polling?: boolean | PollOptions;\n}\n\nexport type ReauthenticateOptions = Omit<LoginWithCredentialsOptions, \"proxy\" | \"mobileProfile\">;\n\nexport class SteamMobile extends EventEmitter<SteamMobileEvents> {\n readonly http: HttpClient;\n readonly session: SessionManager;\n readonly api: WebApiClient;\n readonly confirmations: ConfirmationManager;\n readonly trade: TradeNamespace;\n readonly community: CommunityNamespace;\n readonly identitySecret: string | undefined;\n private readonly polling: boolean | PollOptions | undefined;\n private readonly proxy: string | undefined;\n private readonly profile: MobileProfile;\n\n constructor(options: SteamMobileOptions) {\n super();\n const profile = resolveMobileProfile(options.mobileProfile);\n this.profile = profile;\n this.proxy = options.proxy;\n this.http = new HttpClient({\n ...(options.proxy ? { proxy: options.proxy } : {}),\n profile,\n });\n this.session = new SessionManager(this.http, options.refreshToken);\n this.identitySecret = options.identitySecret;\n this.polling = options.polling;\n this.api = new WebApiClient(this.http, () => this.session.getAccessToken());\n this.confirmations = new ConfirmationManager(\n this.http,\n this.session.steamID,\n options.identitySecret,\n profile,\n );\n this.trade = new TradeNamespace(this.api, this.http, this.session, this.confirmations);\n this.community = new CommunityNamespace(this.http, this.session, this.confirmations, this.api);\n\n this.session.on(\"refreshToken\", (token) => this.emit(\"refreshToken\", token));\n this.session.on(\"sessionExpired\", (error) => this.emit(\"sessionExpired\", error));\n this.session.on(\"debug\", (message) => this.emit(\"debug\", message));\n this.trade.on(\"debug\", (message) => this.emit(\"debug\", message));\n this.trade.on(\"newOffer\", (o) => this.emit(\"newOffer\", o));\n this.trade.on(\"sentOfferChanged\", (o, s) => this.emit(\"sentOfferChanged\", o, s));\n this.trade.on(\"receivedOfferChanged\", (o, s) => this.emit(\"receivedOfferChanged\", o, s));\n this.trade.on(\"unknownOfferSent\", (o) => this.emit(\"unknownOfferSent\", o));\n this.trade.on(\"sentOfferCanceled\", (o, r) => this.emit(\"sentOfferCanceled\", o, r));\n this.trade.on(\"offerUpdate\", (u) => this.emit(\"offerUpdate\", u));\n this.trade.on(\"pollData\", (d) => this.emit(\"pollData\", d));\n this.trade.on(\"pollSuccess\", () => this.emit(\"pollSuccess\"));\n this.trade.on(\"pollFailure\", (e) => this.emit(\"pollFailure\", e));\n }\n\n async login(): Promise<this> {\n await this.session.getAccessToken();\n if (this.polling) {\n this.trade.startPolling(this.polling === true ? {} : this.polling);\n }\n return this;\n }\n\n async reauthenticate(credentials: ReauthenticateOptions): Promise<void> {\n const result = await loginWithCredentials({\n ...credentials,\n ...(this.proxy ? { proxy: this.proxy } : {}),\n mobileProfile: this.profile,\n });\n await this.session.setRefreshToken(result.refreshToken);\n }\n\n // Existing Web API key, or register one; null if the account is ineligible.\n ensureApiKey(domain?: string): Promise<string | null> {\n return this.community.ensureApiKey(domain);\n }\n\n // Log into a third-party site via \"Sign in through Steam\" (OpenID 2.0), spending this session.\n openidLogin(options: OpenidLoginOptions): Promise<OpenidLoginResult> {\n return this.community.openidLogin(options);\n }\n\n // Authenticated escape-hatch HTTP: ensures the session is live, then delegates to http.\n async request<T = string>(\n method: \"GET\" | \"POST\",\n url: string,\n opts?: RequestOptions,\n ): Promise<HttpResponse<T>> {\n await this.session.getAccessToken();\n return this.http.request<T>(method, url, opts);\n }\n\n get<T = string>(url: string, opts?: RequestOptions): Promise<HttpResponse<T>> {\n return this.request<T>(\"GET\", url, opts);\n }\n\n post<T = string>(url: string, opts?: RequestOptions): Promise<HttpResponse<T>> {\n return this.request<T>(\"POST\", url, opts);\n }\n\n get steamID(): SteamID {\n return this.session.steamID;\n }\n\n get accessToken(): string | undefined {\n return this.session.accessToken;\n }\n\n get refreshToken(): string {\n return this.session.refreshToken;\n }\n\n async shutdown(): Promise<void> {\n this.trade.stopPolling();\n this.trade.removeAllListeners();\n this.removeAllListeners();\n }\n}\n"],"mappings":";;;;;;;;;AAAA,MAAa,OAAO;CAAE,GAAG;CAAW,UAAU;AAAK;AAEnD,MAAa,OAAO;CAClB,WAAW;CACX,OAAO;CACP,MAAM;CACN,KAAK;AACP;AAEA,MAAa,oBAAoB;AAKjC,MAAa,wCAAwC;;;ACdrD,IAAY,mBAAL,yBAAA,kBAAA;CACL,iBAAA,iBAAA,aAAA,KAAA;CACA,iBAAA,iBAAA,YAAA,KAAA;CACA,iBAAA,iBAAA,cAAA,KAAA;CACA,iBAAA,iBAAA,eAAA,KAAA;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