@polyester/sdk 0.25.1 → 0.26.1

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.
Files changed (38) hide show
  1. package/CHANGELOG.md +34 -0
  2. package/dist/index.d.ts +3 -2
  3. package/dist/index.js +2 -2
  4. package/dist/server-client.d.ts +12 -1
  5. package/dist/server-client.d.ts.map +1 -1
  6. package/dist/server-client.js +8 -3
  7. package/dist/server-client.js.map +1 -1
  8. package/dist/server-session.d.ts +3 -2
  9. package/dist/server-session.js +2 -1
  10. package/dist/services/auth/account-signer-auth.d.ts.map +1 -1
  11. package/dist/services/auth/account-signer-auth.js +78 -44
  12. package/dist/services/auth/account-signer-auth.js.map +1 -1
  13. package/dist/services/auth/cookie-constants.d.ts +14 -1
  14. package/dist/services/auth/cookie-constants.d.ts.map +1 -1
  15. package/dist/services/auth/cookie-constants.js +13 -1
  16. package/dist/services/auth/cookie-constants.js.map +1 -1
  17. package/dist/services/auth/session.d.ts +10 -2
  18. package/dist/services/auth/session.d.ts.map +1 -1
  19. package/dist/services/auth/session.js +9 -11
  20. package/dist/services/auth/session.js.map +1 -1
  21. package/dist/services/auth/token-storage.js +5 -5
  22. package/dist/services/auth/token-storage.js.map +1 -1
  23. package/dist/services/candles/candles.schemas.d.ts +10 -10
  24. package/dist/services/heatmap/heatmap.schemas.d.ts +13 -13
  25. package/dist/services/market-overview/market-overview.schemas.d.ts +3 -3
  26. package/dist/services/orderbook/orderbook.schemas.d.ts +1 -1
  27. package/dist/services/orders/orders-output.schemas.d.ts +6 -6
  28. package/dist/services/subaccounts/subaccounts.schemas.d.ts +5 -5
  29. package/dist/services/trades/trades.schemas.d.ts +1 -1
  30. package/dist/services/triggers/trigger-input.schemas.d.ts +2 -2
  31. package/dist/services/triggers/triggers-output.schemas.d.ts +18 -18
  32. package/dist/smart-account/index.d.ts +2 -2
  33. package/dist/smart-account/index.js +2 -2
  34. package/dist/smart-account/smart-account.d.ts +3095 -7
  35. package/dist/smart-account/smart-account.d.ts.map +1 -1
  36. package/dist/smart-account/smart-account.js +169 -45
  37. package/dist/smart-account/smart-account.js.map +1 -1
  38. package/package.json +1 -1
package/CHANGELOG.md CHANGED
@@ -1,5 +1,39 @@
1
1
  # @polyester/sdk
2
2
 
3
+ ## 0.26.1
4
+
5
+ ### Patch Changes
6
+
7
+ - Fix UserOperations accepted then rejected by the bundler by using per-operation paymaster stubs and `pm_getPaymasterData`. ([#160](https://github.com/Fabric-Labs/polyester-sdk-typescript/pull/160))
8
+
9
+ - Restore paymaster gas estimate buffering (+20%, 50k floor), while preserving stub-provided limits during preparation. ([#160](https://github.com/Fabric-Labs/polyester-sdk-typescript/pull/160))
10
+
11
+ ## 0.26.0
12
+
13
+ ### Minor Changes
14
+
15
+ - Memoize `createPolyesterSmartAccountClient` per account, environment and options so the gas price cache and warmed connections survive across submissions. ([#157](https://github.com/Fabric-Labs/polyester-sdk-typescript/pull/157))
16
+
17
+ - Add `waitForPolyesterUserOperationReceipt`, which polls `pimlico_getUserOperationStatus` at a 250ms default interval, fetches the receipt only once included, fails fast on `rejected` or `failed`, and keeps checking the chain for operations the bundler reports as `not_found`. The client default `pollingInterval` is now 250ms, so viem's built-in `waitForUserOperationReceipt` also polls four times as often. ([#157](https://github.com/Fabric-Labs/polyester-sdk-typescript/pull/157))
18
+
19
+ - Sponsor smart-account UserOperations with `pm_sponsorUserOperation` instead of `pm_getPaymasterData`, signing over client-buffered account gas limits, and cache the paymaster stub so warm-up removes one round trip per submission. The stub is fetched once with a synthetic operation and reused, which relies on the Polyester paymaster returning constant stub data regardless of the operation or context. ([#157](https://github.com/Fabric-Labs/polyester-sdk-typescript/pull/157))
20
+
21
+ - Add an `onPhase` timing hook to `sendPolyesterUserOperation` and `waitForPolyesterUserOperationReceipt` reporting `prepare`, `sign`, `send`, and `receipt` durations. Observer errors never affect the result. ([#157](https://github.com/Fabric-Labs/polyester-sdk-typescript/pull/157))
22
+
23
+ ### Patch Changes
24
+
25
+ - Raise the smart-account gas price cache TTL from 10s to 60s. `sendPolyesterUserOperation` clears the cache when submission fails after signing, and `waitForPolyesterUserOperationReceipt` clears it on a bundler `rejected` status. ([#157](https://github.com/Fabric-Labs/polyester-sdk-typescript/pull/157))
26
+
27
+ - Return zero from `getSessionTimeToExpiry()` for malformed JWTs even when their payload contains a future expiration. ([#159](https://github.com/Fabric-Labs/polyester-sdk-typescript/pull/159))
28
+
29
+ - Scope local bearer and display-session cookies by port across browser storage and server parsing, including default ports and custom bearer-cookie names. Framework cookie stores must provide `cookieLocation`; local sessions do not fall back to shared legacy cookies. ([#159](https://github.com/Fabric-Labs/polyester-sdk-typescript/pull/159))
30
+
31
+ - Retain foreign environment fingerprints during display-session reads so the next bearer-token read can reject and clear the mismatched session. ([#159](https://github.com/Fabric-Labs/polyester-sdk-typescript/pull/159))
32
+
33
+ - Prevent superseded restoration, login, and refresh operations from clearing or overwriting a newer session. Superseded restores return `null`, and superseded logins reject with `AbortError`. ([#159](https://github.com/Fabric-Labs/polyester-sdk-typescript/pull/159))
34
+
35
+ - Preserve authentication when session restoration fails because of a transient request or signer initialization error. Propagate these failures for retry while continuing to clear expired or backend-rejected sessions. ([#159](https://github.com/Fabric-Labs/polyester-sdk-typescript/pull/159))
36
+
3
37
  ## 0.25.1
4
38
 
5
39
  ### Patch Changes
package/dist/index.d.ts CHANGED
@@ -63,11 +63,12 @@ import { GetSpotFeeRatesInput, SpotFeeRate } from "./services/fees/fees.schemas.
63
63
  import { TradingRateLimitClass } from "./services/rate-limits/rate-limits.codecs.js";
64
64
  import { RateLimitConfig, TradingRateLimitRule, TradingRateLimits } from "./services/rate-limits/rate-limits.schemas.js";
65
65
  import { PolyesterClient, PolyesterClientBaseConfig, PolyesterClientConfig, PolyesterRealtimeAuthConfig } from "./core-client.js";
66
+ import { AuthCookieLocation, POLYESTER_AUTH_TOKEN_COOKIE_NAME, POLYESTER_SESSION_COOKIE_NAME, resolveAuthCookieName } from "./services/auth/cookie-constants.js";
66
67
  import { AuthTokenStorage, AuthTokenStorageSetOptions, CookieAuthTokenStorageOptions, createCookieAuthTokenStorage, createMemoryAuthTokenStorage } from "./services/auth/token-storage.js";
67
68
  import { ActiveAccountInfo, AuthHydrationData, AuthLoginMethod, AuthState, ServerSessionSnapshot, SessionData } from "./services/auth/session.types.js";
69
+ import { ServerSessionCookieOptions } from "./services/auth/session.js";
68
70
  import { AccountSignerAuthEvents, CreateSubaccountParams, CreateSubaccountResult, LoginOptions, LoginResult } from "./services/auth/account-signer-auth.js";
69
71
  import { PolyesterBrowserClient, PolyesterBrowserClientConfig } from "./browser-client.js";
70
- import { POLYESTER_AUTH_TOKEN_COOKIE_NAME, POLYESTER_SESSION_COOKIE_NAME } from "./services/auth/cookie-constants.js";
71
72
  import { CreateServerClientFromCookiesParams, CreateServerClientFromRequestParams, PolyesterServerClient, PolyesterServerClientConfig, createPolyesterServerClientFromCookies, createPolyesterServerClientFromRequest } from "./server-client.js";
72
73
  import { connectErrorToPolyesterError, createErrorMappingInterceptor, toPolyesterError } from "./shared/connect-error-mapping.js";
73
74
  import { isFreshStepUpRequiredError, isMfaEnrollmentRequiredError, isMfaLastFactorRequiredError, isSessionElevationRequiredError } from "./utils/connect-mfa-errors.js";
@@ -109,4 +110,4 @@ import "./services/triggers/triggers.types.js";
109
110
  import "./services/vip/vip.types.js";
110
111
  import "./services/whiteboard/whiteboard.types.js";
111
112
  import "./services/zipper/zipper.types.js";
112
- export { type AccountCodeValue, type AccountIdentity, type AccountScope, type AccountScopedInput, type AccountSigner, type AccountSignerAuthEvents, type AccountSignerConfig, type CreateSubaccountResult as AccountSignerCreateSubaccountResult, type AccountSignerFactory, type ActiveAccountInfo, type AddressBook, type AddressBookEntries, type AddressBookEntriesView, type AddressBookEntry, type AddressBookRecentDestinationsView, type AddressBookTag, type AddressBookTagSummary, type AddressBookView, type AddressBookViewInvalidated, AlreadyExistsError, type ApiKey, type ApiKeyEd25519AuthProvider, type ApiKeyIdInput, type ApiKeyPolicy, type ApiKeyPolicyApplyInput, type ApiKeyPolicyCreateInput, type ApiKeyPolicyUpdateInput, type ApiKeyStatus, type ApiKeysCreateInput, type ApiKeysListInput, type ApiKeysUpdateInput, type ArchiveWhiteboardBoardInput, type ArchiveWhiteboardBoardResult, type AssetConfig, type AuthHydrationData, type AuthLoginMethod, type AuthState, type AuthTokenStorage, type AuthTokenStorageSetOptions, AuthenticationError, type BalanceHistoryInput, type BalanceHistoryResponse, type BalanceRange, type BatchCancelOrderInput, type BatchCancelOrderResult, type BatchCancelOrdersInput, type BatchCancelOrdersResult, type BatchCreateOrderResult, type BatchCreateOrdersInput, type BatchCreateOrdersResult, type BatchGuardApprovals, type BatchReplaceAdmissionItem, type BatchReplaceOrdersInput, type BatchReplaceOrdersResult, type BatchSignProtectedActionInput, type BeginMfaChallengeInput, type BeginMfaChallengeResult, type BeginPasskeyEnrollmentInput, type BeginPasskeyEnrollmentResult, type BeginTotpEnrollmentInput, type BeginTotpEnrollmentResult, type CancelAllAfterInput, type CancelAllAfterResult, type CancelAllOrdersInput, type CancelAllOrdersResponse, type CancelOrderInput, type CancelOrderResult, type CancelTriggerInput, type CancelTriggerResult, type Candle, type CandleColumnar, type CandleColumnarInt, type CandleInt, type ChainAnalyticsRange, type ClaimCampaign, type ClaimDailyRewardResult, type ClaimFreshStepUpInput, type ClaimFreshStepUpResult, type ClaimGeneratedUsernameInput, type ClaimPolicy, type ColumnarTimeWindow, type CompleteMfaChallengeResult, ConfigurationError, type ConnectChannelParams, type ConsumeFreshStepUpInput, type CookieAuthTokenStorageOptions, type CopyAddressBookEntryInput, type CreateAddressBookEntryInput, type CreateAddressBookTagInput, type CreateDepositAddressInput, type CreateGuardSignerWalletResult, type CreateInternalTransferInput, type CreateInternalTransferResult, type CreateOrderResult, type CreateOrderbookSubscriptionInput, type CreatePolyesterAccountSignerParams, type CreatePolyesterEnvironmentParams, type CreateServerClientFromCookiesParams, type CreateServerClientFromRequestParams, type CreateSubaccountInput, type CreateSubaccountParams, type CreateSubaccountResult$1 as CreateSubaccountResult, type CreateSubaccountResult$1 as CreateSubaccountServiceResult, type CreateTradingWithdrawResult, type CreateTradingWithdrawToExternalChainInput, type CreateTradingWithdrawToExternalChainServiceInput, type CreateTradingWithdrawToFundingInput, type CreateTradingWithdrawToFundingServiceInput, type CreateTriggerInput, type CreateTriggerResult, type CreateWalletChallengeInput, type CreateWhiteboardBoardInput, type CreateWhiteboardBoardResult, type CurrencyConversionConfig, type CurrencyConversionRates, type CurrencyMetadata, type DailyClaimReward, type DailyClaimState, type DailyClaimStatus, type DailyClaimTransfer, type DeleteAddressBookEntryInput, type DeleteAddressBookTagInput, type DeleteMfaFactorInput, type DepositAddress, type DepositWithdrawConfig, type EffectiveSubaccountPermissions, type EquityGroupBy, type EquityHistoryInput, type EquityHistoryResponse, type EquitySeries, type EquitySeriesGrouping, type EvmHex, type ExportGuardSignerWalletResult, type FiatConversionRate, type FiatConversionSnapshot, type FinishPasskeyChallengeInput, type FinishPasskeyEnrollmentInput, type FinishPasskeyEnrollmentResult, type FinishTotpEnrollmentInput, type FinishTotpEnrollmentResult, type GeneratedUsernameOffer, type GetAddressBookViewInput, type GetBatchReplaceStatusInput, type GetBatchReplaceStatusResult, type GetCandlesColumnsInput, type GetCandlesInput, type GetLifecycleFlowInput, type GetLifecycleFlowOutput, type GetMarketTradesInput, type GetOrderDetailsInput, type GetOrderbookHeatmapInput, type GetOrderbookInput, type GetSpotFeeRatesInput, type GetTriggerInput, type GetUnifiedAssetBalancesInput, type GetUserTradesInput, type GetVerificationResponse, type GetWhiteboardBoardInput, type GetWhiteboardBoardResult, type GetZippedAssetSupplyGroupInput, type GetZippedAssetSupplyInput, type GuardApproval, type GuardSignerScopedInput, type GuardSignerStatus, type HeatmapDepthValue, type HeatmapIntervalValue, type HeatmapQuantityModeValue, type HexAddress, InternalServerError, type InternalTransferDestination, type InternalTransferWhitelistEntries, type InternalTransferWhitelistEntry, type InviteSubaccountMemberInput, type JwtAuthProvider, type LadderDetailsOutput, type LedgerBalance, type LedgerTransfer, type LedgerTransferSide, type LifecycleAssetIds, type LifecycleFlowDetail, type LifecycleFlowState, type LifecycleFlowStep, type LifecycleFlowStepActivity, type LifecycleFlowSummary, type LifecycleFlowSummaryProgress, type LifecycleFlowTimelineItem, type LifecycleFlowTxMatch, type LifecycleListOrderBy, type LifecycleListScope, type LifecycleReason, type LifecycleRequestFee, type LifecycleRequestFeeStatus, type LifecycleSort, type LifecycleTxLookupKind, type LifecycleZipperReason, type ListAddressBookEntriesInput, type ListApiKeyPoliciesResponse, type ListDepositAddressesInput, type ListInternalTransferWhitelistEntriesInput, type ListLifecycleFlowsByTxInput, type ListLifecycleFlowsByTxOutput, type ListLifecycleFlowsInput, type ListLifecycleFlowsOutput, type ListMarketOverviewInput, type ListMfaFactorsResult, type ListSubaccountInvitesInput, type ListTransferCounterpartiesInput, type ListTransferDestinationsInput, type ListTransfersInput, type ListTriggerEventsInput, type ListTriggerEventsResult, type ListTriggersInput, type ListTriggersResult, type ListWhiteboardBoardsInput, type ListWhiteboardBoardsResult, type LoginOptions, type LoginResult, type LoginWithWalletInput, type LoginWithWalletResponse, type MarketOverview, type MarketOverviewOrderBy, type MarketOverviewSort, type MarketOverviewSparkline, type MarketTrade, type Me, MfaEnrollmentRequiredError, type MfaFactor, MfaLastFactorRequiredError, MfaRequiredError, type MfaSessionInfo, MfaVerificationError, type MfaVerificationFailureReason, type MintWhiteboardJoinTokenInput, type MirroredWithdrawWhitelistEntry, type ModifyOrderInput, type ModifyOrderResult, type ModifyTriggerInput, type ModifyTriggerResult, NetworkError, type NewOrderInput, type NextVipTierThresholds, type OpenOrdersInput, type Order, type OrderDetails, type OrderErrorCode, type OrderErrorDetail, type OrderHistoryInput, type OrderIntentInput, type OrderLineage, type OrderTransfer, type OrderbookData, type OrderbookHeatmapDeltaBucket, type OrderbookHeatmapDeltaChain, type OrderbookHeatmapDeltaLevels, type OrderbookHeatmapKeyframe, type OrderbookHeatmapLevels, type OrderbookHeatmapLiveBucket, type OrderbookHeatmapResponse, type OrderbookLevel, type OrderbookStreamHandlers, type OrderbookSubscription, POLYESTER_AUTH_TOKEN_COOKIE_NAME, POLYESTER_DEVNET_ENVIRONMENT, POLYESTER_SESSION_COOKIE_NAME, POLYESTER_TESTNET_ENVIRONMENT, type PairConfig, type PairStatus, type PauseTriggerInput, type PauseTriggerResult, PermissionError, type PolicyAction, PolicyInUseError, PolicyLockedError, type PolicyMarketScope, PolicyScopeMismatchError, type PolyesterAccountAbstractionEnvironment, PolyesterBrowserClient, type PolyesterBrowserClientConfig, PolyesterClient, type PolyesterClientBaseConfig, type PolyesterClientConfig, type PolyesterContractsEnvironment, type PolyesterEntryPointConfig, type PolyesterEnvironment, PolyesterError, type PolyesterErrorCode, type PolyesterErrorDetail, type PolyesterErrorOptions, type PolyesterMutationOptions, type PolyesterRealtime, type PolyesterRealtimeAuthConfig, type PolyesterRequestOptions, type PolyesterSafeDeploymentConfig, PolyesterServerClient, type PolyesterServerClientConfig, type PortfolioEquityHistoryInput, type PortfolioEquityHistoryResponse, type PortfolioEquitySeries, type PortfolioEquitySeriesGrouping, type PortfolioEquitySnapshotResponse, PreconditionFailedError, type PreparedTradingWithdraw, type PreviewOrderResult, type Profile, type RateLimitConfig, type RateLimitDetail, RateLimitError, type RateLimitErrorOptions, type RateLimitFailureReason, type RateLimitPolicyClass, type RateLimitRefillModel, type RateLimitScope, type RegenerateRecoveryCodesInput, type RegenerateRecoveryCodesResult, type ReleaseFreshStepUpInput, type RemoveSubaccountMemberInput, RequestError, type ResolveAccountInput, type ResolvedAccount, type ResolvedInternalTransferDestination, ResourceNotFoundError, type RespondSubaccountInviteInput, type ResumeTriggerInput, type ResumeTriggerResult, RevisionConflictError, type RiskPolicyInput, type RotateGuardSignerWalletResult, type SdkSubscriptionErrorContext, type ServerSessionSnapshot, ServiceUnavailableError, type SessionData, SessionElevationRequiredError, type SetSubaccountMemberMfaRequirementInput, type SignProtectedActionInput, type SocialProvider, type SocialProviderInput, type SocialVerification, type SocialVerificationMethod, type SocialVerificationStatus, type SparklineIntervalName, type SpotConfig, type SpotFeeRate, type SpotPairVolumeSeries, type SpotVolumeHistoryInput, type SpotVolumeHistoryResponse, type StablecoinConversionRate, StaleQuoteError, type StartVerificationInput, type StartVerificationResponse, StepUpRequiredError, type StopDetailsOutput, type StopLossInput, type Subaccount, type SubaccountActivityInput, type SubaccountEvent, type SubaccountIdInput, type SubaccountInvite, type SubaccountInviteStatus, type SubaccountMember, type SubaccountPermission, type SubaccountPermissionDefinition, type SubaccountPolicy, type SubaccountPolicyApplyInput, type SubaccountPolicyCreateInput, type SubaccountPolicyUpdateInput, type SubaccountRole, type SubaccountRoleCatalog, type SubaccountRoleDefinition, type SubaccountScopedInput, type SubaccountStatus, type SubscribeHandlers, type SubscribeZippedAssetSupplyInput, type TakeProfitInput, type Timeframe, TimeoutError, type Trade, type TradingRateLimitClass, type TradingRateLimitRule, type TradingRateLimits, type TradingWithdrawSigningConfig, type TradingWithdrawWalletSigner, type TrailingDetailsOutput, type TrailingStopInput, type TransferCodeValue, type TransferCounterparties, type TransferCounterparty, type TransferDestination, type TransferDestinations, type TransferSideKind, TransientError, type Transports, type Trigger, type TriggerDetailsOutput, type TriggerEvent, type TwapDetailsOutput, type UnifiedAssetBalancesResponse, type UpdateAddressBookEntryInput, type UpdateAddressBookTagInput, type UpdateMfaFactorInput, type UpdateMfaFactorResult, type UpdateProfileInput, type UpdateSubaccountInput, type UpdateSubaccountMemberRoleInput, type UpdateWhiteboardBoardAclInput, type UpdateWhiteboardBoardAclResult, type UpdateWhiteboardBoardInput, type UpdateWhiteboardBoardResult, type UsernameHistoryEntry, type ValidateWithdrawDestinationInput, type ValidateWithdrawDestinationResult, ValidationError, type VerificationReadyResponse, type VerifyRecoveryCodeChallengeInput, type VerifyTotpChallengeInput, type VipStatus, type VipTier, type VipTierCatalog, type WalletChallenge, type WalletChallengePurpose, type WhiteboardAccess, type WhiteboardAclEntry, type WhiteboardAclEntryInput, type WhiteboardAclSubjectType, type WhiteboardAudience, type WhiteboardBoard, type WhiteboardBoardDetails, type WhiteboardBoardListItem, type WhiteboardJoinTokenResult, type WhiteboardPermissions, type WhiteboardPresencePayload, type WhiteboardResolvedRole, type WhiteboardSnapshot, type WhiteboardWritableRole, type WithdrawWhitelistView, type ZippedAssetSupplyBatch, type ZippedAssetSupplyGroupResponse, type ZippedAssetSupplyResponse, type ZippedAssetSupplySeries, type ZippedAssetSupplyUpdate, type ZipperAssetChainVariant, type ZipperAssetConfig, type ZipperChainConfig, type ZipperChainContractConfig, checksumEvmAddress, columnarTimestampSecAt, compareUnsignedIntegerStrings, connectErrorToPolyesterError, createCookieAuthTokenStorage, createErrorMappingInterceptor, createMemoryAuthTokenStorage, createPolyesterEnvironment, createPolyesterServerClientFromCookies, createPolyesterServerClientFromRequest, errorFromHttpStatus, evmHexToBytes, evmUtf8ToBytes, evmUtf8ToHex, expandColumnarTimestampsSec, formatConnectError, formatUserFacingError, isAbortError, isEvmAddress, isEvmAddressStrict, isFreshStepUpRequiredError, isMfaEnrollmentRequiredError, isMfaLastFactorRequiredError, isPolicyInUseError, isPolicyLockedError, isPolicyScopeMismatchError, isResourceNotFoundError, isRetryableError, isRevisionConflictError, isSessionElevationRequiredError, keccak256Hex, mergeLedgerBalances, normalizeErrorMessage, shouldApplyReconciliationUpdate, tsObjToNsString as timestampToNanoseconds, toPolyesterError, validateCreateAddressBookEntryInput };
113
+ export { type AccountCodeValue, type AccountIdentity, type AccountScope, type AccountScopedInput, type AccountSigner, type AccountSignerAuthEvents, type AccountSignerConfig, type CreateSubaccountResult as AccountSignerCreateSubaccountResult, type AccountSignerFactory, type ActiveAccountInfo, type AddressBook, type AddressBookEntries, type AddressBookEntriesView, type AddressBookEntry, type AddressBookRecentDestinationsView, type AddressBookTag, type AddressBookTagSummary, type AddressBookView, type AddressBookViewInvalidated, AlreadyExistsError, type ApiKey, type ApiKeyEd25519AuthProvider, type ApiKeyIdInput, type ApiKeyPolicy, type ApiKeyPolicyApplyInput, type ApiKeyPolicyCreateInput, type ApiKeyPolicyUpdateInput, type ApiKeyStatus, type ApiKeysCreateInput, type ApiKeysListInput, type ApiKeysUpdateInput, type ArchiveWhiteboardBoardInput, type ArchiveWhiteboardBoardResult, type AssetConfig, type AuthCookieLocation, type AuthHydrationData, type AuthLoginMethod, type AuthState, type AuthTokenStorage, type AuthTokenStorageSetOptions, AuthenticationError, type BalanceHistoryInput, type BalanceHistoryResponse, type BalanceRange, type BatchCancelOrderInput, type BatchCancelOrderResult, type BatchCancelOrdersInput, type BatchCancelOrdersResult, type BatchCreateOrderResult, type BatchCreateOrdersInput, type BatchCreateOrdersResult, type BatchGuardApprovals, type BatchReplaceAdmissionItem, type BatchReplaceOrdersInput, type BatchReplaceOrdersResult, type BatchSignProtectedActionInput, type BeginMfaChallengeInput, type BeginMfaChallengeResult, type BeginPasskeyEnrollmentInput, type BeginPasskeyEnrollmentResult, type BeginTotpEnrollmentInput, type BeginTotpEnrollmentResult, type CancelAllAfterInput, type CancelAllAfterResult, type CancelAllOrdersInput, type CancelAllOrdersResponse, type CancelOrderInput, type CancelOrderResult, type CancelTriggerInput, type CancelTriggerResult, type Candle, type CandleColumnar, type CandleColumnarInt, type CandleInt, type ChainAnalyticsRange, type ClaimCampaign, type ClaimDailyRewardResult, type ClaimFreshStepUpInput, type ClaimFreshStepUpResult, type ClaimGeneratedUsernameInput, type ClaimPolicy, type ColumnarTimeWindow, type CompleteMfaChallengeResult, ConfigurationError, type ConnectChannelParams, type ConsumeFreshStepUpInput, type CookieAuthTokenStorageOptions, type CopyAddressBookEntryInput, type CreateAddressBookEntryInput, type CreateAddressBookTagInput, type CreateDepositAddressInput, type CreateGuardSignerWalletResult, type CreateInternalTransferInput, type CreateInternalTransferResult, type CreateOrderResult, type CreateOrderbookSubscriptionInput, type CreatePolyesterAccountSignerParams, type CreatePolyesterEnvironmentParams, type CreateServerClientFromCookiesParams, type CreateServerClientFromRequestParams, type CreateSubaccountInput, type CreateSubaccountParams, type CreateSubaccountResult$1 as CreateSubaccountResult, type CreateSubaccountResult$1 as CreateSubaccountServiceResult, type CreateTradingWithdrawResult, type CreateTradingWithdrawToExternalChainInput, type CreateTradingWithdrawToExternalChainServiceInput, type CreateTradingWithdrawToFundingInput, type CreateTradingWithdrawToFundingServiceInput, type CreateTriggerInput, type CreateTriggerResult, type CreateWalletChallengeInput, type CreateWhiteboardBoardInput, type CreateWhiteboardBoardResult, type CurrencyConversionConfig, type CurrencyConversionRates, type CurrencyMetadata, type DailyClaimReward, type DailyClaimState, type DailyClaimStatus, type DailyClaimTransfer, type DeleteAddressBookEntryInput, type DeleteAddressBookTagInput, type DeleteMfaFactorInput, type DepositAddress, type DepositWithdrawConfig, type EffectiveSubaccountPermissions, type EquityGroupBy, type EquityHistoryInput, type EquityHistoryResponse, type EquitySeries, type EquitySeriesGrouping, type EvmHex, type ExportGuardSignerWalletResult, type FiatConversionRate, type FiatConversionSnapshot, type FinishPasskeyChallengeInput, type FinishPasskeyEnrollmentInput, type FinishPasskeyEnrollmentResult, type FinishTotpEnrollmentInput, type FinishTotpEnrollmentResult, type GeneratedUsernameOffer, type GetAddressBookViewInput, type GetBatchReplaceStatusInput, type GetBatchReplaceStatusResult, type GetCandlesColumnsInput, type GetCandlesInput, type GetLifecycleFlowInput, type GetLifecycleFlowOutput, type GetMarketTradesInput, type GetOrderDetailsInput, type GetOrderbookHeatmapInput, type GetOrderbookInput, type GetSpotFeeRatesInput, type GetTriggerInput, type GetUnifiedAssetBalancesInput, type GetUserTradesInput, type GetVerificationResponse, type GetWhiteboardBoardInput, type GetWhiteboardBoardResult, type GetZippedAssetSupplyGroupInput, type GetZippedAssetSupplyInput, type GuardApproval, type GuardSignerScopedInput, type GuardSignerStatus, type HeatmapDepthValue, type HeatmapIntervalValue, type HeatmapQuantityModeValue, type HexAddress, InternalServerError, type InternalTransferDestination, type InternalTransferWhitelistEntries, type InternalTransferWhitelistEntry, type InviteSubaccountMemberInput, type JwtAuthProvider, type LadderDetailsOutput, type LedgerBalance, type LedgerTransfer, type LedgerTransferSide, type LifecycleAssetIds, type LifecycleFlowDetail, type LifecycleFlowState, type LifecycleFlowStep, type LifecycleFlowStepActivity, type LifecycleFlowSummary, type LifecycleFlowSummaryProgress, type LifecycleFlowTimelineItem, type LifecycleFlowTxMatch, type LifecycleListOrderBy, type LifecycleListScope, type LifecycleReason, type LifecycleRequestFee, type LifecycleRequestFeeStatus, type LifecycleSort, type LifecycleTxLookupKind, type LifecycleZipperReason, type ListAddressBookEntriesInput, type ListApiKeyPoliciesResponse, type ListDepositAddressesInput, type ListInternalTransferWhitelistEntriesInput, type ListLifecycleFlowsByTxInput, type ListLifecycleFlowsByTxOutput, type ListLifecycleFlowsInput, type ListLifecycleFlowsOutput, type ListMarketOverviewInput, type ListMfaFactorsResult, type ListSubaccountInvitesInput, type ListTransferCounterpartiesInput, type ListTransferDestinationsInput, type ListTransfersInput, type ListTriggerEventsInput, type ListTriggerEventsResult, type ListTriggersInput, type ListTriggersResult, type ListWhiteboardBoardsInput, type ListWhiteboardBoardsResult, type LoginOptions, type LoginResult, type LoginWithWalletInput, type LoginWithWalletResponse, type MarketOverview, type MarketOverviewOrderBy, type MarketOverviewSort, type MarketOverviewSparkline, type MarketTrade, type Me, MfaEnrollmentRequiredError, type MfaFactor, MfaLastFactorRequiredError, MfaRequiredError, type MfaSessionInfo, MfaVerificationError, type MfaVerificationFailureReason, type MintWhiteboardJoinTokenInput, type MirroredWithdrawWhitelistEntry, type ModifyOrderInput, type ModifyOrderResult, type ModifyTriggerInput, type ModifyTriggerResult, NetworkError, type NewOrderInput, type NextVipTierThresholds, type OpenOrdersInput, type Order, type OrderDetails, type OrderErrorCode, type OrderErrorDetail, type OrderHistoryInput, type OrderIntentInput, type OrderLineage, type OrderTransfer, type OrderbookData, type OrderbookHeatmapDeltaBucket, type OrderbookHeatmapDeltaChain, type OrderbookHeatmapDeltaLevels, type OrderbookHeatmapKeyframe, type OrderbookHeatmapLevels, type OrderbookHeatmapLiveBucket, type OrderbookHeatmapResponse, type OrderbookLevel, type OrderbookStreamHandlers, type OrderbookSubscription, POLYESTER_AUTH_TOKEN_COOKIE_NAME, POLYESTER_DEVNET_ENVIRONMENT, POLYESTER_SESSION_COOKIE_NAME, POLYESTER_TESTNET_ENVIRONMENT, type PairConfig, type PairStatus, type PauseTriggerInput, type PauseTriggerResult, PermissionError, type PolicyAction, PolicyInUseError, PolicyLockedError, type PolicyMarketScope, PolicyScopeMismatchError, type PolyesterAccountAbstractionEnvironment, PolyesterBrowserClient, type PolyesterBrowserClientConfig, PolyesterClient, type PolyesterClientBaseConfig, type PolyesterClientConfig, type PolyesterContractsEnvironment, type PolyesterEntryPointConfig, type PolyesterEnvironment, PolyesterError, type PolyesterErrorCode, type PolyesterErrorDetail, type PolyesterErrorOptions, type PolyesterMutationOptions, type PolyesterRealtime, type PolyesterRealtimeAuthConfig, type PolyesterRequestOptions, type PolyesterSafeDeploymentConfig, PolyesterServerClient, type PolyesterServerClientConfig, type PortfolioEquityHistoryInput, type PortfolioEquityHistoryResponse, type PortfolioEquitySeries, type PortfolioEquitySeriesGrouping, type PortfolioEquitySnapshotResponse, PreconditionFailedError, type PreparedTradingWithdraw, type PreviewOrderResult, type Profile, type RateLimitConfig, type RateLimitDetail, RateLimitError, type RateLimitErrorOptions, type RateLimitFailureReason, type RateLimitPolicyClass, type RateLimitRefillModel, type RateLimitScope, type RegenerateRecoveryCodesInput, type RegenerateRecoveryCodesResult, type ReleaseFreshStepUpInput, type RemoveSubaccountMemberInput, RequestError, type ResolveAccountInput, type ResolvedAccount, type ResolvedInternalTransferDestination, ResourceNotFoundError, type RespondSubaccountInviteInput, type ResumeTriggerInput, type ResumeTriggerResult, RevisionConflictError, type RiskPolicyInput, type RotateGuardSignerWalletResult, type SdkSubscriptionErrorContext, type ServerSessionCookieOptions, type ServerSessionSnapshot, ServiceUnavailableError, type SessionData, SessionElevationRequiredError, type SetSubaccountMemberMfaRequirementInput, type SignProtectedActionInput, type SocialProvider, type SocialProviderInput, type SocialVerification, type SocialVerificationMethod, type SocialVerificationStatus, type SparklineIntervalName, type SpotConfig, type SpotFeeRate, type SpotPairVolumeSeries, type SpotVolumeHistoryInput, type SpotVolumeHistoryResponse, type StablecoinConversionRate, StaleQuoteError, type StartVerificationInput, type StartVerificationResponse, StepUpRequiredError, type StopDetailsOutput, type StopLossInput, type Subaccount, type SubaccountActivityInput, type SubaccountEvent, type SubaccountIdInput, type SubaccountInvite, type SubaccountInviteStatus, type SubaccountMember, type SubaccountPermission, type SubaccountPermissionDefinition, type SubaccountPolicy, type SubaccountPolicyApplyInput, type SubaccountPolicyCreateInput, type SubaccountPolicyUpdateInput, type SubaccountRole, type SubaccountRoleCatalog, type SubaccountRoleDefinition, type SubaccountScopedInput, type SubaccountStatus, type SubscribeHandlers, type SubscribeZippedAssetSupplyInput, type TakeProfitInput, type Timeframe, TimeoutError, type Trade, type TradingRateLimitClass, type TradingRateLimitRule, type TradingRateLimits, type TradingWithdrawSigningConfig, type TradingWithdrawWalletSigner, type TrailingDetailsOutput, type TrailingStopInput, type TransferCodeValue, type TransferCounterparties, type TransferCounterparty, type TransferDestination, type TransferDestinations, type TransferSideKind, TransientError, type Transports, type Trigger, type TriggerDetailsOutput, type TriggerEvent, type TwapDetailsOutput, type UnifiedAssetBalancesResponse, type UpdateAddressBookEntryInput, type UpdateAddressBookTagInput, type UpdateMfaFactorInput, type UpdateMfaFactorResult, type UpdateProfileInput, type UpdateSubaccountInput, type UpdateSubaccountMemberRoleInput, type UpdateWhiteboardBoardAclInput, type UpdateWhiteboardBoardAclResult, type UpdateWhiteboardBoardInput, type UpdateWhiteboardBoardResult, type UsernameHistoryEntry, type ValidateWithdrawDestinationInput, type ValidateWithdrawDestinationResult, ValidationError, type VerificationReadyResponse, type VerifyRecoveryCodeChallengeInput, type VerifyTotpChallengeInput, type VipStatus, type VipTier, type VipTierCatalog, type WalletChallenge, type WalletChallengePurpose, type WhiteboardAccess, type WhiteboardAclEntry, type WhiteboardAclEntryInput, type WhiteboardAclSubjectType, type WhiteboardAudience, type WhiteboardBoard, type WhiteboardBoardDetails, type WhiteboardBoardListItem, type WhiteboardJoinTokenResult, type WhiteboardPermissions, type WhiteboardPresencePayload, type WhiteboardResolvedRole, type WhiteboardSnapshot, type WhiteboardWritableRole, type WithdrawWhitelistView, type ZippedAssetSupplyBatch, type ZippedAssetSupplyGroupResponse, type ZippedAssetSupplyResponse, type ZippedAssetSupplySeries, type ZippedAssetSupplyUpdate, type ZipperAssetChainVariant, type ZipperAssetConfig, type ZipperChainConfig, type ZipperChainContractConfig, checksumEvmAddress, columnarTimestampSecAt, compareUnsignedIntegerStrings, connectErrorToPolyesterError, createCookieAuthTokenStorage, createErrorMappingInterceptor, createMemoryAuthTokenStorage, createPolyesterEnvironment, createPolyesterServerClientFromCookies, createPolyesterServerClientFromRequest, errorFromHttpStatus, evmHexToBytes, evmUtf8ToBytes, evmUtf8ToHex, expandColumnarTimestampsSec, formatConnectError, formatUserFacingError, isAbortError, isEvmAddress, isEvmAddressStrict, isFreshStepUpRequiredError, isMfaEnrollmentRequiredError, isMfaLastFactorRequiredError, isPolicyInUseError, isPolicyLockedError, isPolicyScopeMismatchError, isResourceNotFoundError, isRetryableError, isRevisionConflictError, isSessionElevationRequiredError, keccak256Hex, mergeLedgerBalances, normalizeErrorMessage, resolveAuthCookieName, shouldApplyReconciliationUpdate, tsObjToNsString as timestampToNanoseconds, toPolyesterError, validateCreateAddressBookEntryInput };
package/dist/index.js CHANGED
@@ -8,10 +8,10 @@ import { compareUnsignedIntegerStrings, shouldApplyReconciliationUpdate } from "
8
8
  import { mergeLedgerBalances } from "./services/balances/balances.merge.js";
9
9
  import { validateCreateAddressBookEntryInput } from "./services/address-book/address-book.schemas.js";
10
10
  import { PolyesterClient } from "./core-client.js";
11
- import { POLYESTER_AUTH_TOKEN_COOKIE_NAME, POLYESTER_SESSION_COOKIE_NAME } from "./services/auth/cookie-constants.js";
11
+ import { POLYESTER_AUTH_TOKEN_COOKIE_NAME, POLYESTER_SESSION_COOKIE_NAME, resolveAuthCookieName } from "./services/auth/cookie-constants.js";
12
12
  import { createCookieAuthTokenStorage, createMemoryAuthTokenStorage } from "./services/auth/token-storage.js";
13
13
  import { PolyesterBrowserClient } from "./browser-client.js";
14
14
  import { PolyesterServerClient, createPolyesterServerClientFromCookies, createPolyesterServerClientFromRequest } from "./server-client.js";
15
15
  import { isFreshStepUpRequiredError, isMfaEnrollmentRequiredError, isMfaLastFactorRequiredError, isSessionElevationRequiredError } from "./utils/connect-mfa-errors.js";
16
16
  import { columnarTimestampSecAt, expandColumnarTimestampsSec } from "./utils/columnar-time.js";
17
- export { AlreadyExistsError, AuthenticationError, ConfigurationError, InternalServerError, MfaEnrollmentRequiredError, MfaLastFactorRequiredError, MfaRequiredError, MfaVerificationError, NetworkError, POLYESTER_AUTH_TOKEN_COOKIE_NAME, POLYESTER_DEVNET_ENVIRONMENT, POLYESTER_SESSION_COOKIE_NAME, POLYESTER_TESTNET_ENVIRONMENT, PermissionError, PolicyInUseError, PolicyLockedError, PolicyScopeMismatchError, PolyesterBrowserClient, PolyesterClient, PolyesterError, PolyesterServerClient, PreconditionFailedError, RateLimitError, RequestError, ResourceNotFoundError, RevisionConflictError, ServiceUnavailableError, SessionElevationRequiredError, StaleQuoteError, StepUpRequiredError, TimeoutError, TransientError, ValidationError, checksumEvmAddress, columnarTimestampSecAt, compareUnsignedIntegerStrings, connectErrorToPolyesterError, createCookieAuthTokenStorage, createErrorMappingInterceptor, createMemoryAuthTokenStorage, createPolyesterEnvironment, createPolyesterServerClientFromCookies, createPolyesterServerClientFromRequest, errorFromHttpStatus, evmHexToBytes, evmUtf8ToBytes, evmUtf8ToHex, expandColumnarTimestampsSec, formatConnectError, formatUserFacingError, isAbortError, isEvmAddress, isEvmAddressStrict, isFreshStepUpRequiredError, isMfaEnrollmentRequiredError, isMfaLastFactorRequiredError, isPolicyInUseError, isPolicyLockedError, isPolicyScopeMismatchError, isResourceNotFoundError, isRetryableError, isRevisionConflictError, isSessionElevationRequiredError, keccak256Hex, mergeLedgerBalances, normalizeErrorMessage, shouldApplyReconciliationUpdate, tsObjToNsString as timestampToNanoseconds, toPolyesterError, validateCreateAddressBookEntryInput };
17
+ export { AlreadyExistsError, AuthenticationError, ConfigurationError, InternalServerError, MfaEnrollmentRequiredError, MfaLastFactorRequiredError, MfaRequiredError, MfaVerificationError, NetworkError, POLYESTER_AUTH_TOKEN_COOKIE_NAME, POLYESTER_DEVNET_ENVIRONMENT, POLYESTER_SESSION_COOKIE_NAME, POLYESTER_TESTNET_ENVIRONMENT, PermissionError, PolicyInUseError, PolicyLockedError, PolicyScopeMismatchError, PolyesterBrowserClient, PolyesterClient, PolyesterError, PolyesterServerClient, PreconditionFailedError, RateLimitError, RequestError, ResourceNotFoundError, RevisionConflictError, ServiceUnavailableError, SessionElevationRequiredError, StaleQuoteError, StepUpRequiredError, TimeoutError, TransientError, ValidationError, checksumEvmAddress, columnarTimestampSecAt, compareUnsignedIntegerStrings, connectErrorToPolyesterError, createCookieAuthTokenStorage, createErrorMappingInterceptor, createMemoryAuthTokenStorage, createPolyesterEnvironment, createPolyesterServerClientFromCookies, createPolyesterServerClientFromRequest, errorFromHttpStatus, evmHexToBytes, evmUtf8ToBytes, evmUtf8ToHex, expandColumnarTimestampsSec, formatConnectError, formatUserFacingError, isAbortError, isEvmAddress, isEvmAddressStrict, isFreshStepUpRequiredError, isMfaEnrollmentRequiredError, isMfaLastFactorRequiredError, isPolicyInUseError, isPolicyLockedError, isPolicyScopeMismatchError, isResourceNotFoundError, isRetryableError, isRevisionConflictError, isSessionElevationRequiredError, keccak256Hex, mergeLedgerBalances, normalizeErrorMessage, resolveAuthCookieName, shouldApplyReconciliationUpdate, tsObjToNsString as timestampToNanoseconds, toPolyesterError, validateCreateAddressBookEntryInput };
@@ -4,8 +4,9 @@ import { SubaccountResolver } from "./services/subaccount-resolver.js";
4
4
  import { Me } from "./services/auth/auth.js";
5
5
  import { PolyesterClient, PolyesterClientBaseConfig } from "./core-client.js";
6
6
  import { CookieGetter } from "./utils/cookies.js";
7
+ import { AuthCookieLocation, POLYESTER_AUTH_TOKEN_COOKIE_NAME, POLYESTER_SESSION_COOKIE_NAME } from "./services/auth/cookie-constants.js";
7
8
  import { ServerSessionSnapshot } from "./services/auth/session.types.js";
8
- import { POLYESTER_AUTH_TOKEN_COOKIE_NAME, POLYESTER_SESSION_COOKIE_NAME } from "./services/auth/cookie-constants.js";
9
+ import "./services/auth/session.js";
9
10
  //#region src/server-client.d.ts
10
11
  /** Configuration for the server Polyester client. */
11
12
  type PolyesterServerClientConfig = PolyesterClientBaseConfig & {
@@ -54,6 +55,14 @@ type CreateServerClientFromCookiesParams = ServerClientFactoryBaseConfig<Polyest
54
55
  * Await asynchronous framework cookie helpers before passing their result.
55
56
  */
56
57
  cookies: CookieGetter;
58
+ /**
59
+ * The page or request location that supplied `cookies`. Required for
60
+ * local framework cookie stores so their port-scoped auth cookies can
61
+ * be parsed; a `Request` source derives this from `request.url`.
62
+ */
63
+ cookieLocation?: AuthCookieLocation;
64
+ /** Base name configured for the browser bearer-token cookie. */
65
+ tokenCookieName?: string;
57
66
  /**
58
67
  * Use unsigned display-session `activeAccount` as the default subaccount for
59
68
  * calls that omit `subaccountId`. This is caller intent from UI hydration,
@@ -64,6 +73,8 @@ type CreateServerClientFromCookiesParams = ServerClientFactoryBaseConfig<Polyest
64
73
  /** Parameters for creating a server client from a request. */
65
74
  type CreateServerClientFromRequestParams = ServerClientFactoryBaseConfig<PolyesterClientBaseConfig> & {
66
75
  request: Request;
76
+ /** Base name configured for the browser bearer-token cookie. */
77
+ tokenCookieName?: string;
67
78
  /**
68
79
  * Use unsigned display-session `activeAccount` as the default subaccount for
69
80
  * calls that omit `subaccountId`. This is caller intent from UI hydration,
@@ -1 +1 @@
1
- {"version":3,"file":"server-client.d.ts","names":[],"sources":["../src/server-client.ts"],"mappings":";;;;;;;;;;KAkCY,8BAA8B;;EAEtC,OAAO,kBAAkB;;EAEzB,UAAU;;;;;;;EAOV;;;;;cAMS,8BAA8B;;EAK3B,YAAA,QAAQ;;;;;;YAyBD,4BAA4B;MAc3C;MAIA;MAIA;MAIA;MAIA,WAAW;;;;;;EAST,iBAAiB,QAAQ;;KAa9B,8BAA8B,WAAW,gBAAgB,4BACxD,KACI;;KAcE,sCACR,8BAA8B;;;;;;EAM1B,SAAS;;;;;;EAMT;;;KAII,sCACR,8BAA8B;EAC1B,SAAS;;;;;;EAMT;;;;;iBAMQ,uCACZ,QAAQ,sCACT;;;;iBA0Ba,uCACZ,QAAQ,sCACT"}
1
+ {"version":3,"file":"server-client.d.ts","names":[],"sources":["../src/server-client.ts"],"mappings":";;;;;;;;;;;KAwCY,8BAA8B;;EAEtC,OAAO,kBAAkB;;EAEzB,UAAU;;;;;;;EAOV;;;;;cAMS,8BAA8B;;EAK3B,YAAA,QAAQ;;;;;;YAyBD,4BAA4B;MAc3C;MAIA;MAIA;MAIA;MAIA,WAAW;;;;;;EAST,iBAAiB,QAAQ;;KAa9B,8BAA8B,WAAW,gBAAgB,4BACxD,KACI;;KAcE,sCACR,8BAA8B;;;;;;EAM1B,SAAS;;;;;;EAMT,iBAAiB;;EAEjB;;;;;;EAMA;;;KAII,sCACR,8BAA8B;EAC1B,SAAS;;EAET;;;;;;EAMA;;;;;iBAMQ,uCACZ,QAAQ,sCACT;;;;iBA6Ba,uCACZ,QAAQ,sCACT"}
@@ -8,8 +8,8 @@ import { isJwtValid } from "./utils/jwt.js";
8
8
  /**
9
9
  * Parses a serialized session cookie into SDK session data.
10
10
  */
11
- function parseSessionCookie(cookies, environment) {
12
- return parseServerSessionSnapshot(cookies, environment);
11
+ function parseSessionCookie(cookies, environment, options) {
12
+ return parseServerSessionSnapshot(cookies, environment, options);
13
13
  }
14
14
  /**
15
15
  * Server-side SDK client that can parse display-session cookies and verify bearer-token sessions with the backend.
@@ -87,7 +87,10 @@ var PolyesterServerClient = class extends PolyesterClient {
87
87
  * Creates a server SDK client from a Request, cookie record, or synchronous cookie store.
88
88
  */
89
89
  function createPolyesterServerClientFromCookies(params) {
90
- const session = parseSessionCookie(params.cookies, params.environment);
90
+ const session = parseSessionCookie(params.cookies, params.environment, {
91
+ cookieLocation: params.cookieLocation,
92
+ tokenCookieName: params.tokenCookieName
93
+ });
91
94
  const auth = isJwtValid(session.bearerToken) ? {
92
95
  kind: "jwt",
93
96
  getToken: () => session.bearerToken
@@ -112,6 +115,8 @@ function createPolyesterServerClientFromRequest(params) {
112
115
  if (!(params?.request instanceof Request)) throw new ConfigurationError("request is required and must be a Request.");
113
116
  return createPolyesterServerClientFromCookies({
114
117
  cookies: params.request,
118
+ cookieLocation: new URL(params.request.url),
119
+ tokenCookieName: params.tokenCookieName,
115
120
  environment: params.environment,
116
121
  interceptors: params.interceptors,
117
122
  wireFormat: params.wireFormat,
@@ -1 +1 @@
1
- {"version":3,"file":"server-client.js","names":["#hasAuthProvider","#session","#useDisplaySessionActiveAccountAsDefault"],"sources":["../src/server-client.ts"],"sourcesContent":["import {\n parsePolyesterClientConfig,\n pickPolyesterCatalogConfig,\n PolyesterClient,\n type PolyesterClientBaseConfig,\n} from \"./core-client.js\";\nimport {\n POLYESTER_AUTH_TOKEN_COOKIE_NAME,\n POLYESTER_SESSION_COOKIE_NAME,\n} from \"./services/auth/cookie-constants.js\";\nimport type { ServerSessionSnapshot } from \"./services/auth/session.types.js\";\nimport { emptyServerSessionSnapshot, parseServerSessionSnapshot } from \"./services/auth/session.js\";\nimport type { CookieGetter } from \"./utils/cookies.js\";\nimport type { JwtAuthProvider, ApiKeyEd25519AuthProvider } from \"./shared/transports.js\";\nimport type { SubaccountResolver } from \"./services/subaccount-resolver.js\";\nimport { isJwtValid } from \"./utils/jwt.js\";\nimport type { Me } from \"./services/auth/auth.js\";\nimport type { PolyesterEnvironment } from \"./environment.js\";\nimport { AuthenticationError, ConfigurationError } from \"./shared/errors.js\";\nimport { toPolyesterError } from \"./shared/connect-error-mapping.js\";\n\nexport type { ServerSessionSnapshot };\n\n/**\n * Parses a serialized session cookie into SDK session data.\n */\nexport function parseSessionCookie(\n cookies: CookieGetter,\n environment: PolyesterEnvironment,\n): ServerSessionSnapshot {\n return parseServerSessionSnapshot(cookies, environment);\n}\n\n/** Configuration for the server Polyester client. */\nexport type PolyesterServerClientConfig = PolyesterClientBaseConfig & {\n /** Auth provider config for HTTP/Connect endpoints. */\n auth?: JwtAuthProvider | ApiKeyEd25519AuthProvider;\n /** Bearer authentication and display-only session data parsed from cookies. */\n session?: ServerSessionSnapshot;\n /**\n * Use unsigned display-session `activeAccount` as the default subaccount for\n * calls that omit `subaccountId`. This preserves account-switcher intent for\n * apps that explicitly opt in; backend authorization must still decide what\n * the authenticated user can access.\n */\n useDisplaySessionActiveAccountAsDefault?: boolean;\n};\n\n/**\n * Server-side SDK client that can parse display-session cookies and verify bearer-token sessions with the backend.\n */\nexport class PolyesterServerClient extends PolyesterClient {\n #hasAuthProvider: boolean;\n #session: ServerSessionSnapshot;\n #useDisplaySessionActiveAccountAsDefault: boolean;\n\n constructor(config: PolyesterServerClientConfig) {\n config = parsePolyesterClientConfig(config);\n const auth = config.auth ?? undefined;\n\n super({\n environment: config.environment,\n interceptors: config.interceptors,\n auth,\n wireFormat: config.wireFormat,\n realtime: config.realtime,\n ...pickPolyesterCatalogConfig(config),\n transports: config.transports,\n realtimeClient: config.realtimeClient,\n });\n this.#hasAuthProvider = !!auth;\n this.#session = config.session ?? emptyServerSessionSnapshot();\n this.#useDisplaySessionActiveAccountAsDefault =\n config.useDisplaySessionActiveAccountAsDefault ?? false;\n }\n\n /**\n * Creates a resolver for server-side subaccount defaults. Display-session\n * `activeAccount` is only used as caller intent when explicitly enabled;\n * backend auth remains authoritative.\n */\n protected override createSubaccountResolver(): SubaccountResolver {\n return {\n getDefaultSubaccountId: () => {\n if (!this.#useDisplaySessionActiveAccountAsDefault) return null;\n\n const activeAccount = this.#session.activeAccount;\n if (activeAccount && !activeAccount.isMain) return activeAccount.accountId;\n return null;\n },\n getActiveAccountId: () => this.#session.activeAccount?.accountId ?? null,\n getMainAccountId: () => this.#session.activeAccount?.mainAccountId ?? null,\n };\n }\n\n get hasAuthProvider(): boolean {\n return this.#hasAuthProvider;\n }\n\n get hasBearerToken(): boolean {\n return !!this.#session.bearerToken;\n }\n\n get hasUsableBearerToken(): boolean {\n return isJwtValid(this.#session.bearerToken);\n }\n\n get hasDisplaySession(): boolean {\n return this.#session.hasDisplaySession;\n }\n\n get session(): ServerSessionSnapshot {\n return this.#session;\n }\n\n /**\n * Verifies the current server session. Returns null only when credentials\n * are absent or rejected as unauthenticated. Transport, configuration, and\n * other backend failures are rethrown so callers do not treat outages as logout.\n */\n async verifySession(): Promise<Me | null> {\n if (!this.#hasAuthProvider) return null;\n\n try {\n return await this.auth.me();\n } catch (error) {\n const mappedError = toPolyesterError(error);\n if (mappedError instanceof AuthenticationError) return null;\n throw mappedError;\n }\n }\n}\n\ntype ServerClientFactoryBaseConfig<TConfig> = TConfig extends PolyesterClientBaseConfig\n ? Pick<\n TConfig,\n | \"environment\"\n | \"interceptors\"\n | \"realtime\"\n | \"wireFormat\"\n | \"catalog\"\n | \"catalogSnapshot\"\n | \"catalogCell\"\n | \"transports\"\n | \"realtimeClient\"\n >\n : never;\n\n/** Parameters for creating a server client from cookies. */\nexport type CreateServerClientFromCookiesParams =\n ServerClientFactoryBaseConfig<PolyesterClientBaseConfig> & {\n /**\n * A Request, name-value record, or synchronous cookie store whose `get`\n * method returns either a string or an object with a string `value`.\n * Await asynchronous framework cookie helpers before passing their result.\n */\n cookies: CookieGetter;\n /**\n * Use unsigned display-session `activeAccount` as the default subaccount for\n * calls that omit `subaccountId`. This is caller intent from UI hydration,\n * not proof of authority; backend authorization remains authoritative.\n */\n useDisplaySessionActiveAccountAsDefault?: boolean;\n };\n\n/** Parameters for creating a server client from a request. */\nexport type CreateServerClientFromRequestParams =\n ServerClientFactoryBaseConfig<PolyesterClientBaseConfig> & {\n request: Request;\n /**\n * Use unsigned display-session `activeAccount` as the default subaccount for\n * calls that omit `subaccountId`. This is caller intent from UI hydration,\n * not proof of authority; backend authorization remains authoritative.\n */\n useDisplaySessionActiveAccountAsDefault?: boolean;\n };\n\n/**\n * Creates a server SDK client from a Request, cookie record, or synchronous cookie store.\n */\nexport function createPolyesterServerClientFromCookies(\n params: CreateServerClientFromCookiesParams,\n): PolyesterServerClient {\n const session = parseSessionCookie(params.cookies, params.environment);\n const auth = isJwtValid(session.bearerToken)\n ? ({\n kind: \"jwt\",\n getToken: () => session.bearerToken,\n } satisfies JwtAuthProvider)\n : undefined;\n\n return new PolyesterServerClient({\n environment: params.environment,\n interceptors: params.interceptors,\n session,\n wireFormat: params.wireFormat,\n realtime: params.realtime,\n ...pickPolyesterCatalogConfig(params),\n transports: params.transports,\n realtimeClient: params.realtimeClient,\n auth,\n useDisplaySessionActiveAccountAsDefault: params.useDisplaySessionActiveAccountAsDefault,\n });\n}\n\n/**\n * Creates a server SDK client from a Request object.\n */\nexport function createPolyesterServerClientFromRequest(\n params: CreateServerClientFromRequestParams,\n): PolyesterServerClient {\n if (!(params?.request instanceof Request)) {\n throw new ConfigurationError(\"request is required and must be a Request.\");\n }\n return createPolyesterServerClientFromCookies({\n cookies: params.request,\n environment: params.environment,\n interceptors: params.interceptors,\n wireFormat: params.wireFormat,\n realtime: params.realtime,\n ...pickPolyesterCatalogConfig(params),\n transports: params.transports,\n realtimeClient: params.realtimeClient,\n useDisplaySessionActiveAccountAsDefault: params.useDisplaySessionActiveAccountAsDefault,\n });\n}\n\n/**\n * Reads a bearer token from supported auth cookies.\n */\nexport function getBearerTokenFromCookies(\n cookies: CookieGetter,\n environment: PolyesterEnvironment,\n): string | null {\n return parseSessionCookie(cookies, environment).bearerToken;\n}\n\nexport { POLYESTER_AUTH_TOKEN_COOKIE_NAME, POLYESTER_SESSION_COOKIE_NAME };\n"],"mappings":";;;;;;;;;;AA0BA,SAAgB,mBACZ,SACA,aACqB;CACrB,OAAO,2BAA2B,SAAS,WAAW;AAC1D;;;;AAoBA,IAAa,wBAAb,cAA2C,gBAAgB;CACvD;CACA;CACA;CAEA,YAAY,QAAqC;EAC7C,SAAS,2BAA2B,MAAM;EAC1C,MAAM,OAAO,OAAO,QAAQ,KAAA;EAE5B,MAAM;GACF,aAAa,OAAO;GACpB,cAAc,OAAO;GACrB;GACA,YAAY,OAAO;GACnB,UAAU,OAAO;GACjB,GAAG,2BAA2B,MAAM;GACpC,YAAY,OAAO;GACnB,gBAAgB,OAAO;EAC3B,CAAC;EACD,KAAKA,mBAAmB,CAAC,CAAC;EAC1B,KAAKC,WAAW,OAAO,WAAW,2BAA2B;EAC7D,KAAKC,2CACD,OAAO,2CAA2C;CAC1D;;;;;;CAOA,2BAAkE;EAC9D,OAAO;GACH,8BAA8B;IAC1B,IAAI,CAAC,KAAKA,0CAA0C,OAAO;IAE3D,MAAM,gBAAgB,KAAKD,SAAS;IACpC,IAAI,iBAAiB,CAAC,cAAc,QAAQ,OAAO,cAAc;IACjE,OAAO;GACX;GACA,0BAA0B,KAAKA,SAAS,eAAe,aAAa;GACpE,wBAAwB,KAAKA,SAAS,eAAe,iBAAiB;EAC1E;CACJ;CAEA,IAAI,kBAA2B;EAC3B,OAAO,KAAKD;CAChB;CAEA,IAAI,iBAA0B;EAC1B,OAAO,CAAC,CAAC,KAAKC,SAAS;CAC3B;CAEA,IAAI,uBAAgC;EAChC,OAAO,WAAW,KAAKA,SAAS,WAAW;CAC/C;CAEA,IAAI,oBAA6B;EAC7B,OAAO,KAAKA,SAAS;CACzB;CAEA,IAAI,UAAiC;EACjC,OAAO,KAAKA;CAChB;;;;;;CAOA,MAAM,gBAAoC;EACtC,IAAI,CAAC,KAAKD,kBAAkB,OAAO;EAEnC,IAAI;GACA,OAAO,MAAM,KAAK,KAAK,GAAG;EAC9B,SAAS,OAAO;GACZ,MAAM,cAAc,iBAAiB,KAAK;GAC1C,IAAI,uBAAuB,qBAAqB,OAAO;GACvD,MAAM;EACV;CACJ;AACJ;;;;AAiDA,SAAgB,uCACZ,QACqB;CACrB,MAAM,UAAU,mBAAmB,OAAO,SAAS,OAAO,WAAW;CACrE,MAAM,OAAO,WAAW,QAAQ,WAAW,IACpC;EACG,MAAM;EACN,gBAAgB,QAAQ;CAC5B,IACA,KAAA;CAEN,OAAO,IAAI,sBAAsB;EAC7B,aAAa,OAAO;EACpB,cAAc,OAAO;EACrB;EACA,YAAY,OAAO;EACnB,UAAU,OAAO;EACjB,GAAG,2BAA2B,MAAM;EACpC,YAAY,OAAO;EACnB,gBAAgB,OAAO;EACvB;EACA,yCAAyC,OAAO;CACpD,CAAC;AACL;;;;AAKA,SAAgB,uCACZ,QACqB;CACrB,IAAI,EAAE,QAAQ,mBAAmB,UAC7B,MAAM,IAAI,mBAAmB,4CAA4C;CAE7E,OAAO,uCAAuC;EAC1C,SAAS,OAAO;EAChB,aAAa,OAAO;EACpB,cAAc,OAAO;EACrB,YAAY,OAAO;EACnB,UAAU,OAAO;EACjB,GAAG,2BAA2B,MAAM;EACpC,YAAY,OAAO;EACnB,gBAAgB,OAAO;EACvB,yCAAyC,OAAO;CACpD,CAAC;AACL"}
1
+ {"version":3,"file":"server-client.js","names":["#hasAuthProvider","#session","#useDisplaySessionActiveAccountAsDefault"],"sources":["../src/server-client.ts"],"sourcesContent":["import {\n parsePolyesterClientConfig,\n pickPolyesterCatalogConfig,\n PolyesterClient,\n type PolyesterClientBaseConfig,\n} from \"./core-client.js\";\nimport {\n POLYESTER_AUTH_TOKEN_COOKIE_NAME,\n POLYESTER_SESSION_COOKIE_NAME,\n type AuthCookieLocation,\n} from \"./services/auth/cookie-constants.js\";\nimport type { ServerSessionSnapshot } from \"./services/auth/session.types.js\";\nimport {\n emptyServerSessionSnapshot,\n parseServerSessionSnapshot,\n type ServerSessionCookieOptions,\n} from \"./services/auth/session.js\";\nimport type { CookieGetter } from \"./utils/cookies.js\";\nimport type { JwtAuthProvider, ApiKeyEd25519AuthProvider } from \"./shared/transports.js\";\nimport type { SubaccountResolver } from \"./services/subaccount-resolver.js\";\nimport { isJwtValid } from \"./utils/jwt.js\";\nimport type { Me } from \"./services/auth/auth.js\";\nimport type { PolyesterEnvironment } from \"./environment.js\";\nimport { AuthenticationError, ConfigurationError } from \"./shared/errors.js\";\nimport { toPolyesterError } from \"./shared/connect-error-mapping.js\";\n\nexport type { ServerSessionSnapshot };\n\n/**\n * Parses a serialized session cookie into SDK session data.\n */\nexport function parseSessionCookie(\n cookies: CookieGetter,\n environment: PolyesterEnvironment,\n options?: ServerSessionCookieOptions,\n): ServerSessionSnapshot {\n return parseServerSessionSnapshot(cookies, environment, options);\n}\n\n/** Configuration for the server Polyester client. */\nexport type PolyesterServerClientConfig = PolyesterClientBaseConfig & {\n /** Auth provider config for HTTP/Connect endpoints. */\n auth?: JwtAuthProvider | ApiKeyEd25519AuthProvider;\n /** Bearer authentication and display-only session data parsed from cookies. */\n session?: ServerSessionSnapshot;\n /**\n * Use unsigned display-session `activeAccount` as the default subaccount for\n * calls that omit `subaccountId`. This preserves account-switcher intent for\n * apps that explicitly opt in; backend authorization must still decide what\n * the authenticated user can access.\n */\n useDisplaySessionActiveAccountAsDefault?: boolean;\n};\n\n/**\n * Server-side SDK client that can parse display-session cookies and verify bearer-token sessions with the backend.\n */\nexport class PolyesterServerClient extends PolyesterClient {\n #hasAuthProvider: boolean;\n #session: ServerSessionSnapshot;\n #useDisplaySessionActiveAccountAsDefault: boolean;\n\n constructor(config: PolyesterServerClientConfig) {\n config = parsePolyesterClientConfig(config);\n const auth = config.auth ?? undefined;\n\n super({\n environment: config.environment,\n interceptors: config.interceptors,\n auth,\n wireFormat: config.wireFormat,\n realtime: config.realtime,\n ...pickPolyesterCatalogConfig(config),\n transports: config.transports,\n realtimeClient: config.realtimeClient,\n });\n this.#hasAuthProvider = !!auth;\n this.#session = config.session ?? emptyServerSessionSnapshot();\n this.#useDisplaySessionActiveAccountAsDefault =\n config.useDisplaySessionActiveAccountAsDefault ?? false;\n }\n\n /**\n * Creates a resolver for server-side subaccount defaults. Display-session\n * `activeAccount` is only used as caller intent when explicitly enabled;\n * backend auth remains authoritative.\n */\n protected override createSubaccountResolver(): SubaccountResolver {\n return {\n getDefaultSubaccountId: () => {\n if (!this.#useDisplaySessionActiveAccountAsDefault) return null;\n\n const activeAccount = this.#session.activeAccount;\n if (activeAccount && !activeAccount.isMain) return activeAccount.accountId;\n return null;\n },\n getActiveAccountId: () => this.#session.activeAccount?.accountId ?? null,\n getMainAccountId: () => this.#session.activeAccount?.mainAccountId ?? null,\n };\n }\n\n get hasAuthProvider(): boolean {\n return this.#hasAuthProvider;\n }\n\n get hasBearerToken(): boolean {\n return !!this.#session.bearerToken;\n }\n\n get hasUsableBearerToken(): boolean {\n return isJwtValid(this.#session.bearerToken);\n }\n\n get hasDisplaySession(): boolean {\n return this.#session.hasDisplaySession;\n }\n\n get session(): ServerSessionSnapshot {\n return this.#session;\n }\n\n /**\n * Verifies the current server session. Returns null only when credentials\n * are absent or rejected as unauthenticated. Transport, configuration, and\n * other backend failures are rethrown so callers do not treat outages as logout.\n */\n async verifySession(): Promise<Me | null> {\n if (!this.#hasAuthProvider) return null;\n\n try {\n return await this.auth.me();\n } catch (error) {\n const mappedError = toPolyesterError(error);\n if (mappedError instanceof AuthenticationError) return null;\n throw mappedError;\n }\n }\n}\n\ntype ServerClientFactoryBaseConfig<TConfig> = TConfig extends PolyesterClientBaseConfig\n ? Pick<\n TConfig,\n | \"environment\"\n | \"interceptors\"\n | \"realtime\"\n | \"wireFormat\"\n | \"catalog\"\n | \"catalogSnapshot\"\n | \"catalogCell\"\n | \"transports\"\n | \"realtimeClient\"\n >\n : never;\n\n/** Parameters for creating a server client from cookies. */\nexport type CreateServerClientFromCookiesParams =\n ServerClientFactoryBaseConfig<PolyesterClientBaseConfig> & {\n /**\n * A Request, name-value record, or synchronous cookie store whose `get`\n * method returns either a string or an object with a string `value`.\n * Await asynchronous framework cookie helpers before passing their result.\n */\n cookies: CookieGetter;\n /**\n * The page or request location that supplied `cookies`. Required for\n * local framework cookie stores so their port-scoped auth cookies can\n * be parsed; a `Request` source derives this from `request.url`.\n */\n cookieLocation?: AuthCookieLocation;\n /** Base name configured for the browser bearer-token cookie. */\n tokenCookieName?: string;\n /**\n * Use unsigned display-session `activeAccount` as the default subaccount for\n * calls that omit `subaccountId`. This is caller intent from UI hydration,\n * not proof of authority; backend authorization remains authoritative.\n */\n useDisplaySessionActiveAccountAsDefault?: boolean;\n };\n\n/** Parameters for creating a server client from a request. */\nexport type CreateServerClientFromRequestParams =\n ServerClientFactoryBaseConfig<PolyesterClientBaseConfig> & {\n request: Request;\n /** Base name configured for the browser bearer-token cookie. */\n tokenCookieName?: string;\n /**\n * Use unsigned display-session `activeAccount` as the default subaccount for\n * calls that omit `subaccountId`. This is caller intent from UI hydration,\n * not proof of authority; backend authorization remains authoritative.\n */\n useDisplaySessionActiveAccountAsDefault?: boolean;\n };\n\n/**\n * Creates a server SDK client from a Request, cookie record, or synchronous cookie store.\n */\nexport function createPolyesterServerClientFromCookies(\n params: CreateServerClientFromCookiesParams,\n): PolyesterServerClient {\n const session = parseSessionCookie(params.cookies, params.environment, {\n cookieLocation: params.cookieLocation,\n tokenCookieName: params.tokenCookieName,\n });\n const auth = isJwtValid(session.bearerToken)\n ? ({\n kind: \"jwt\",\n getToken: () => session.bearerToken,\n } satisfies JwtAuthProvider)\n : undefined;\n\n return new PolyesterServerClient({\n environment: params.environment,\n interceptors: params.interceptors,\n session,\n wireFormat: params.wireFormat,\n realtime: params.realtime,\n ...pickPolyesterCatalogConfig(params),\n transports: params.transports,\n realtimeClient: params.realtimeClient,\n auth,\n useDisplaySessionActiveAccountAsDefault: params.useDisplaySessionActiveAccountAsDefault,\n });\n}\n\n/**\n * Creates a server SDK client from a Request object.\n */\nexport function createPolyesterServerClientFromRequest(\n params: CreateServerClientFromRequestParams,\n): PolyesterServerClient {\n if (!(params?.request instanceof Request)) {\n throw new ConfigurationError(\"request is required and must be a Request.\");\n }\n return createPolyesterServerClientFromCookies({\n cookies: params.request,\n cookieLocation: new URL(params.request.url),\n tokenCookieName: params.tokenCookieName,\n environment: params.environment,\n interceptors: params.interceptors,\n wireFormat: params.wireFormat,\n realtime: params.realtime,\n ...pickPolyesterCatalogConfig(params),\n transports: params.transports,\n realtimeClient: params.realtimeClient,\n useDisplaySessionActiveAccountAsDefault: params.useDisplaySessionActiveAccountAsDefault,\n });\n}\n\n/**\n * Reads a bearer token from supported auth cookies.\n */\nexport function getBearerTokenFromCookies(\n cookies: CookieGetter,\n environment: PolyesterEnvironment,\n options?: ServerSessionCookieOptions,\n): string | null {\n return parseSessionCookie(cookies, environment, options).bearerToken;\n}\n\nexport { POLYESTER_AUTH_TOKEN_COOKIE_NAME, POLYESTER_SESSION_COOKIE_NAME };\n"],"mappings":";;;;;;;;;;AA+BA,SAAgB,mBACZ,SACA,aACA,SACqB;CACrB,OAAO,2BAA2B,SAAS,aAAa,OAAO;AACnE;;;;AAoBA,IAAa,wBAAb,cAA2C,gBAAgB;CACvD;CACA;CACA;CAEA,YAAY,QAAqC;EAC7C,SAAS,2BAA2B,MAAM;EAC1C,MAAM,OAAO,OAAO,QAAQ,KAAA;EAE5B,MAAM;GACF,aAAa,OAAO;GACpB,cAAc,OAAO;GACrB;GACA,YAAY,OAAO;GACnB,UAAU,OAAO;GACjB,GAAG,2BAA2B,MAAM;GACpC,YAAY,OAAO;GACnB,gBAAgB,OAAO;EAC3B,CAAC;EACD,KAAKA,mBAAmB,CAAC,CAAC;EAC1B,KAAKC,WAAW,OAAO,WAAW,2BAA2B;EAC7D,KAAKC,2CACD,OAAO,2CAA2C;CAC1D;;;;;;CAOA,2BAAkE;EAC9D,OAAO;GACH,8BAA8B;IAC1B,IAAI,CAAC,KAAKA,0CAA0C,OAAO;IAE3D,MAAM,gBAAgB,KAAKD,SAAS;IACpC,IAAI,iBAAiB,CAAC,cAAc,QAAQ,OAAO,cAAc;IACjE,OAAO;GACX;GACA,0BAA0B,KAAKA,SAAS,eAAe,aAAa;GACpE,wBAAwB,KAAKA,SAAS,eAAe,iBAAiB;EAC1E;CACJ;CAEA,IAAI,kBAA2B;EAC3B,OAAO,KAAKD;CAChB;CAEA,IAAI,iBAA0B;EAC1B,OAAO,CAAC,CAAC,KAAKC,SAAS;CAC3B;CAEA,IAAI,uBAAgC;EAChC,OAAO,WAAW,KAAKA,SAAS,WAAW;CAC/C;CAEA,IAAI,oBAA6B;EAC7B,OAAO,KAAKA,SAAS;CACzB;CAEA,IAAI,UAAiC;EACjC,OAAO,KAAKA;CAChB;;;;;;CAOA,MAAM,gBAAoC;EACtC,IAAI,CAAC,KAAKD,kBAAkB,OAAO;EAEnC,IAAI;GACA,OAAO,MAAM,KAAK,KAAK,GAAG;EAC9B,SAAS,OAAO;GACZ,MAAM,cAAc,iBAAiB,KAAK;GAC1C,IAAI,uBAAuB,qBAAqB,OAAO;GACvD,MAAM;EACV;CACJ;AACJ;;;;AA2DA,SAAgB,uCACZ,QACqB;CACrB,MAAM,UAAU,mBAAmB,OAAO,SAAS,OAAO,aAAa;EACnE,gBAAgB,OAAO;EACvB,iBAAiB,OAAO;CAC5B,CAAC;CACD,MAAM,OAAO,WAAW,QAAQ,WAAW,IACpC;EACG,MAAM;EACN,gBAAgB,QAAQ;CAC5B,IACA,KAAA;CAEN,OAAO,IAAI,sBAAsB;EAC7B,aAAa,OAAO;EACpB,cAAc,OAAO;EACrB;EACA,YAAY,OAAO;EACnB,UAAU,OAAO;EACjB,GAAG,2BAA2B,MAAM;EACpC,YAAY,OAAO;EACnB,gBAAgB,OAAO;EACvB;EACA,yCAAyC,OAAO;CACpD,CAAC;AACL;;;;AAKA,SAAgB,uCACZ,QACqB;CACrB,IAAI,EAAE,QAAQ,mBAAmB,UAC7B,MAAM,IAAI,mBAAmB,4CAA4C;CAE7E,OAAO,uCAAuC;EAC1C,SAAS,OAAO;EAChB,gBAAgB,IAAI,IAAI,OAAO,QAAQ,GAAG;EAC1C,iBAAiB,OAAO;EACxB,aAAa,OAAO;EACpB,cAAc,OAAO;EACrB,YAAY,OAAO;EACnB,UAAU,OAAO;EACjB,GAAG,2BAA2B,MAAM;EACpC,YAAY,OAAO;EACnB,gBAAgB,OAAO;EACvB,yCAAyC,OAAO;CACpD,CAAC;AACL"}
@@ -1,4 +1,5 @@
1
+ import { AuthCookieLocation, resolveAuthCookieName } from "./services/auth/cookie-constants.js";
1
2
  import { ServerSessionSnapshot } from "./services/auth/session.types.js";
2
- import { emptyServerSessionSnapshot, parseServerSessionSnapshot } from "./services/auth/session.js";
3
+ import { ServerSessionCookieOptions, emptyServerSessionSnapshot, parseServerSessionSnapshot } from "./services/auth/session.js";
3
4
  import { isJwtValid } from "./utils/jwt.js";
4
- export { type ServerSessionSnapshot, emptyServerSessionSnapshot, isJwtValid, parseServerSessionSnapshot as parseSessionCookie };
5
+ export { type AuthCookieLocation, type ServerSessionCookieOptions, type ServerSessionSnapshot, emptyServerSessionSnapshot, isJwtValid, parseServerSessionSnapshot as parseSessionCookie, resolveAuthCookieName };
@@ -1,3 +1,4 @@
1
+ import { resolveAuthCookieName } from "./services/auth/cookie-constants.js";
1
2
  import { emptyServerSessionSnapshot, parseServerSessionSnapshot } from "./services/auth/session.js";
2
3
  import { isJwtValid } from "./utils/jwt.js";
3
- export { emptyServerSessionSnapshot, isJwtValid, parseServerSessionSnapshot as parseSessionCookie };
4
+ export { emptyServerSessionSnapshot, isJwtValid, parseServerSessionSnapshot as parseSessionCookie, resolveAuthCookieName };
@@ -1 +1 @@
1
- {"version":3,"file":"account-signer-auth.d.ts","names":[],"sources":["../../../src/services/auth/account-signer-auth.ts"],"mappings":";;;;;;;;;;;;;UAwBiB;EACb;IAAiB;IAAmB;;EACpC;EACA;IAAS;IAAc;;EACvB;EACA,aAAa;;UAGA;EACb;EACA;EACA,WAAW;;UAGE;;;;EAIb;;EAEA;EACA,cAAc;;UAGD;;EAEb,eAAe;;EAEf;;EAEA;;UAGa;EACb;EACA;EACA;;;;;cAWS,iCAAiC;;WACjC,QAAM,aAAA;EAiBH,cACR,YACA,qBACA,aACA,aACA,UACA,cACA;IAEA,YAAY;IACZ,sBAAsB;IACtB,aAAa;IACb,aAAa;IACb,UAAU;IACV,cAAc;IACd,eAAe;;;;;EAmBnB,sBAAsB,aAAa;;;;EAOnC,iBAAiB,eAAe;;;;EAUhC,oBAAoB;;;;EAOd,MAAM,SAAS,eAAe,QAAQ;;;;EA+F5C,iBAAiB,OAAO;;;;EAwBlB,kBAAkB;IAAU;IAAmB;;;;;EA6D/C,UAAU;;;;EAoChB;;;;EASM,eAAe;;IAEjB;IACA;IACA,cAAc;MACd,QAAQ;;;;EAmBZ,cACI,mBACA;IAAY;IAA8B;;IACzC;IAAmB;;;EAuBxB,oBAAoB;;;;EASd,iBAAiB,QAAQ,yBAAyB,QAAQ;;;;EAuChE,YAAY"}
1
+ {"version":3,"file":"account-signer-auth.d.ts","names":[],"sources":["../../../src/services/auth/account-signer-auth.ts"],"mappings":";;;;;;;;;;;;;UAyBiB;EACb;IAAiB;IAAmB;;EACpC;EACA;IAAS;IAAc;;EACvB;EACA,aAAa;;UAGA;EACb;EACA;EACA,WAAW;;UAGE;;;;EAIb;;EAEA;EACA,cAAc;;UAGD;;EAEb,eAAe;;EAEf;;EAEA;;UAGa;EACb;EACA;EACA;;;;;cAWS,iCAAiC;;WACjC,QAAM,aAAA;EAoBH,cACR,YACA,qBACA,aACA,aACA,UACA,cACA;IAEA,YAAY;IACZ,sBAAsB;IACtB,aAAa;IACb,aAAa;IACb,UAAU;IACV,cAAc;IACd,eAAe;;;;;EAmBnB,sBAAsB,aAAa;;;;EAOnC,iBAAiB,eAAe;;;;EAWhC,oBAAoB;;;;EAOd,MAAM,SAAS,eAAe,QAAQ;;;;EA0F5C,iBAAiB,OAAO;;;;EAyBlB,kBAAkB;IAAU;IAAmB;;;;;EA0E/C,UAAU;;;;EAqChB;;;;EASM,eAAe;;IAEjB;IACA;IACA,cAAc;MACd,QAAQ;;;;EAmBZ,cACI,mBACA;IAAY;IAA8B;;IACzC;IAAmB;;;EAuBxB,oBAAoB;;;;EASd,iBAAiB,QAAQ,yBAAyB,QAAQ;;;;EAuChE,YAAY"}
@@ -1,4 +1,5 @@
1
1
  import { AuthenticationError, ConfigurationError } from "../../shared/errors.js";
2
+ import { toPolyesterError } from "../../shared/connect-error-mapping.js";
2
3
  import { AuthService } from "./auth.js";
3
4
  import { AuthSessionStore } from "./session.js";
4
5
  import { assertAccountSigner, resolveAccountSigner } from "../../account-signer/types.js";
@@ -25,6 +26,7 @@ var AccountSignerAuthService = class extends AuthService {
25
26
  #tokenStorage;
26
27
  #sessionStore;
27
28
  #realtime;
29
+ #authOperationGeneration = 0;
28
30
  constructor({ transports, accountSignerConfig, environment, subaccounts, realtime, tokenStorage, sessionStore }) {
29
31
  super(transports, realtime);
30
32
  this.#accountSignerConfig = accountSignerConfig;
@@ -45,6 +47,7 @@ var AccountSignerAuthService = class extends AuthService {
45
47
  */
46
48
  setAccountSigner(accountSigner) {
47
49
  if (accountSigner) this.#assertAccountSignerEnvironment(accountSigner);
50
+ this.#beginAuthOperation();
48
51
  this.#accountSigner = accountSigner;
49
52
  this.#accountIdentity = accountSigner ? this.#identityFromSigner(accountSigner) : null;
50
53
  this.#notifyStateChange();
@@ -62,6 +65,8 @@ var AccountSignerAuthService = class extends AuthService {
62
65
  return this.#login(options);
63
66
  }
64
67
  async #login(options, previousActiveAccount) {
68
+ const generation = this.#beginAuthOperation();
69
+ const startingToken = this.#tokenStorage.get();
65
70
  const { provider, loginMethod } = options;
66
71
  const accountSigner = await this.#resolveAccountSigner();
67
72
  if (!accountSigner) throw new ConfigurationError("No account signer configured. Call setAccountSigner() or pass accountSigner in config.");
@@ -81,6 +86,7 @@ var AccountSignerAuthService = class extends AuthService {
81
86
  signature,
82
87
  walletProvider: provider
83
88
  });
89
+ if (!this.#isCurrentAuthOperation(generation, startingToken)) throw new DOMException("Authentication operation superseded", "AbortError");
84
90
  const environmentSession = this.#getEnvironmentSession();
85
91
  const resolvedLoginMethod = loginMethod ?? this.#loginMethod ?? environmentSession?.loginMethod ?? (provider === "metamask" ? "metamask" : null);
86
92
  const tokenOptions = createAuthTokenStorageSetOptions(response.accessToken);
@@ -102,23 +108,20 @@ var AccountSignerAuthService = class extends AuthService {
102
108
  this.#walletProvider = provider;
103
109
  this.#loginMethod = resolvedLoginMethod;
104
110
  this.#challengeUri = uri;
111
+ this.#accountSigner = accountSigner;
105
112
  this.#accountIdentity = this.#identityFromSigner(accountSigner);
106
113
  this.#notifyStateChange();
107
114
  this.events.emit("authenticated", {
108
115
  accountId: response.accountId,
109
116
  username: response.username
110
117
  });
111
- const expiresAt = response.expiresAt ? /* @__PURE__ */ new Date(Number(response.expiresAt.seconds) * 1e3 + (response.expiresAt.nanos ?? 0) / 1e6) : /* @__PURE__ */ new Date();
112
- return {
113
- accountId: response.accountId,
114
- username: response.username,
115
- expiresAt
116
- };
118
+ return this.#loginResult(response);
117
119
  }
118
120
  /**
119
121
  * Builds auth state from a session token and optional active account override.
120
122
  */
121
123
  hydrateAuthState(state) {
124
+ this.#beginAuthOperation();
122
125
  const existingToken = this.#getEnvironmentBoundToken();
123
126
  if (!existingToken || !isJwtValid(existingToken)) return;
124
127
  const existingSession = this.#getEnvironmentSession();
@@ -137,52 +140,72 @@ var AccountSignerAuthService = class extends AuthService {
137
140
  * Loads the stored token, validates that it still belongs to this environment, and restores auth state when possible.
138
141
  */
139
142
  async restoreSession() {
143
+ const generation = this.#beginAuthOperation();
140
144
  const existingToken = this.#getEnvironmentBoundToken();
141
145
  if (!existingToken || !isJwtValid(existingToken)) {
142
- this.#clearExpiredSessionState();
146
+ if (this.#isCurrentAuthOperation(generation)) this.#clearExpiredSessionState();
143
147
  return null;
144
148
  }
149
+ let me;
145
150
  try {
146
- const me = await this.me();
147
- this.#isAuthenticated = true;
148
- this.#mainAccountId = me.accountId;
149
- const existingSession = this.#getEnvironmentSession();
150
- this.#walletProvider = existingSession?.provider ?? this.#walletProvider;
151
- this.#loginMethod = existingSession?.loginMethod ?? this.#loginMethod;
152
- if (!this.#activeAccountId) this.#activeAccountId = existingSession?.activeAccount?.accountId ?? me.accountId;
153
- if (!this.#accountSigner) {
154
- this.#accountSigner = await resolveAccountSigner(this.#accountSignerConfig);
155
- if (this.#accountSigner) {
156
- this.#assertAccountSignerEnvironment(this.#accountSigner);
157
- this.#accountIdentity = this.#identityFromSigner(this.#accountSigner);
158
- }
151
+ me = await this.me();
152
+ } catch (error) {
153
+ if (!this.#isCurrentAuthOperation(generation, existingToken)) return null;
154
+ const mappedError = toPolyesterError(error);
155
+ if (mappedError instanceof AuthenticationError) {
156
+ this.#clearExpiredSessionState();
157
+ return null;
159
158
  }
160
- if (this.#accountSigner?.accountAddress) {
161
- const session = this.#sessionStore.ensureSession({
162
- provider: this.#walletProvider ? this.#walletProvider : "other",
163
- loginMethod: this.#loginMethod ?? (this.#walletProvider === "metamask" ? "metamask" : null),
164
- primaryWallet: this.#accountSigner.ownerAddress ?? this.#accountSigner.accountAddress,
165
- smartAccount: this.#accountSigner.accountAddress,
166
- accountId: me.accountId,
167
- username: me.username ?? void 0
168
- }, { maxAgeSeconds: this.#getCurrentTokenStorageOptions().maxAgeSeconds });
169
- this.#walletProvider = session.provider;
170
- this.#loginMethod = session.loginMethod ?? this.#loginMethod;
159
+ throw mappedError;
160
+ }
161
+ if (!this.#isCurrentAuthOperation(generation, existingToken)) return null;
162
+ let accountSigner = this.#accountSigner;
163
+ if (!accountSigner) {
164
+ try {
165
+ accountSigner = await resolveAccountSigner(this.#accountSignerConfig);
166
+ } catch (error) {
167
+ if (!this.#isCurrentAuthOperation(generation, existingToken)) return null;
168
+ throw error;
171
169
  }
172
- this.#notifyStateChange();
173
- return {
174
- accountId: me.accountId,
175
- username: me.username
176
- };
177
- } catch {
170
+ if (!this.#isCurrentAuthOperation(generation, existingToken)) return null;
171
+ if (accountSigner) this.#assertAccountSignerEnvironment(accountSigner);
172
+ }
173
+ if (!isJwtValid(existingToken) || this.#getEnvironmentBoundToken() !== existingToken) {
178
174
  this.#clearExpiredSessionState();
179
175
  return null;
180
176
  }
177
+ const existingSession = this.#getEnvironmentSession();
178
+ const walletProvider = existingSession?.provider ?? this.#walletProvider;
179
+ const loginMethod = existingSession?.loginMethod ?? this.#loginMethod;
180
+ const activeAccountId = this.#activeAccountId ?? existingSession?.activeAccount?.accountId ?? me.accountId;
181
+ if (accountSigner) {
182
+ this.#sessionStore.ensureSession({
183
+ provider: walletProvider ?? "other",
184
+ loginMethod: loginMethod ?? (walletProvider === "metamask" ? "metamask" : null),
185
+ primaryWallet: accountSigner.ownerAddress ?? accountSigner.accountAddress,
186
+ smartAccount: accountSigner.accountAddress,
187
+ accountId: me.accountId,
188
+ username: me.username ?? void 0
189
+ }, { maxAgeSeconds: this.#getCurrentTokenStorageOptions().maxAgeSeconds });
190
+ this.#accountSigner = accountSigner;
191
+ this.#accountIdentity = this.#identityFromSigner(accountSigner);
192
+ }
193
+ this.#isAuthenticated = true;
194
+ this.#mainAccountId = me.accountId;
195
+ this.#activeAccountId = activeAccountId;
196
+ this.#walletProvider = walletProvider ?? (accountSigner ? "other" : void 0);
197
+ this.#loginMethod = loginMethod;
198
+ this.#notifyStateChange();
199
+ return {
200
+ accountId: me.accountId,
201
+ username: me.username
202
+ };
181
203
  }
182
204
  /**
183
205
  * Clears stored auth state and removes the persisted auth token.
184
206
  */
185
207
  async logout() {
208
+ this.#beginAuthOperation();
186
209
  this.#realtime.disconnectPrivate();
187
210
  this.#tokenStorage.clear();
188
211
  this.#isAuthenticated = false;
@@ -214,7 +237,7 @@ var AccountSignerAuthService = class extends AuthService {
214
237
  */
215
238
  getSessionTimeToExpiry() {
216
239
  const token = this.#getEnvironmentBoundToken();
217
- if (!token) return 0;
240
+ if (!token || !isJwtValid(token)) return 0;
218
241
  return getJwtTimeToExpiry(token);
219
242
  }
220
243
  /**
@@ -303,16 +326,27 @@ var AccountSignerAuthService = class extends AuthService {
303
326
  return this.#accountSigner;
304
327
  }
305
328
  const resolved = await resolveAccountSigner(this.#accountSignerConfig);
306
- if (resolved) {
307
- this.#assertAccountSignerEnvironment(resolved);
308
- this.#accountSigner = resolved;
309
- this.#accountIdentity = this.#identityFromSigner(resolved);
310
- }
311
- return this.#accountSigner;
329
+ if (resolved) this.#assertAccountSignerEnvironment(resolved);
330
+ return resolved;
312
331
  }
313
332
  #notifyStateChange() {
314
333
  this.events.emit("stateChange", this.getState());
315
334
  }
335
+ #beginAuthOperation() {
336
+ this.#authOperationGeneration += 1;
337
+ return this.#authOperationGeneration;
338
+ }
339
+ #isCurrentAuthOperation(generation, token) {
340
+ return generation === this.#authOperationGeneration && (token === void 0 || this.#tokenStorage.get() === token);
341
+ }
342
+ #loginResult(response) {
343
+ const expiresAt = response.expiresAt ? /* @__PURE__ */ new Date(Number(response.expiresAt.seconds) * 1e3 + (response.expiresAt.nanos ?? 0) / 1e6) : /* @__PURE__ */ new Date();
344
+ return {
345
+ accountId: response.accountId,
346
+ username: response.username,
347
+ expiresAt
348
+ };
349
+ }
316
350
  #getEnvironmentBoundToken() {
317
351
  return this.#sessionStore.getEnvironmentBoundToken(this.#tokenStorage);
318
352
  }