@opensea/sdk 11.1.1 → 11.3.0

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 (68) hide show
  1. package/lib/api/accounts.d.ts +13 -1
  2. package/lib/api/accounts.js +18 -0
  3. package/lib/api/accounts.js.map +1 -1
  4. package/lib/api/api.d.ts +14 -1
  5. package/lib/api/api.js +22 -0
  6. package/lib/api/api.js.map +1 -1
  7. package/lib/api/apiPaths.d.ts +3 -0
  8. package/lib/api/apiPaths.js +13 -1
  9. package/lib/api/apiPaths.js.map +1 -1
  10. package/lib/api/types.d.ts +31 -1
  11. package/lib/auth/index.d.ts +67 -0
  12. package/lib/auth/index.js +174 -0
  13. package/lib/auth/index.js.map +1 -0
  14. package/lib/auth/oauth-types.d.ts +69 -0
  15. package/lib/auth/oauth-types.js +3 -0
  16. package/lib/auth/oauth-types.js.map +1 -0
  17. package/lib/auth/oauth.d.ts +109 -0
  18. package/lib/auth/oauth.js +342 -0
  19. package/lib/auth/oauth.js.map +1 -0
  20. package/lib/auth/siwx.d.ts +63 -0
  21. package/lib/auth/siwx.js +276 -0
  22. package/lib/auth/siwx.js.map +1 -0
  23. package/lib/auth/types.d.ts +50 -0
  24. package/lib/auth/types.js +3 -0
  25. package/lib/auth/types.js.map +1 -0
  26. package/lib/index.d.ts +7 -1
  27. package/lib/index.js +9 -1
  28. package/lib/index.js.map +1 -1
  29. package/lib/scopes.d.ts +29 -0
  30. package/lib/scopes.js +27 -0
  31. package/lib/scopes.js.map +1 -0
  32. package/lib/sdk/base.d.ts +1 -0
  33. package/lib/sdk/base.js +6 -3
  34. package/lib/sdk/base.js.map +1 -1
  35. package/lib/sdk/cancellation.js +33 -23
  36. package/lib/sdk/cancellation.js.map +1 -1
  37. package/lib/types.d.ts +5 -1
  38. package/lib/types.js +1 -0
  39. package/lib/types.js.map +1 -1
  40. package/lib/utils/chain.d.ts +1 -1
  41. package/lib/utils/chain.js +30 -5
  42. package/lib/utils/chain.js.map +1 -1
  43. package/lib/utils/chainIds.generated.js +1 -0
  44. package/lib/utils/chainIds.generated.js.map +1 -1
  45. package/lib/utils/units.js +9 -5
  46. package/lib/utils/units.js.map +1 -1
  47. package/lib/viem.d.ts +1 -0
  48. package/lib/viem.js +1 -0
  49. package/lib/viem.js.map +1 -1
  50. package/package.json +7 -7
  51. package/src/api/accounts.ts +41 -0
  52. package/src/api/api.ts +36 -0
  53. package/src/api/apiPaths.ts +12 -0
  54. package/src/api/types.ts +36 -0
  55. package/src/auth/index.ts +244 -0
  56. package/src/auth/oauth-types.ts +73 -0
  57. package/src/auth/oauth.ts +428 -0
  58. package/src/auth/siwx.ts +400 -0
  59. package/src/auth/types.ts +55 -0
  60. package/src/index.ts +10 -0
  61. package/src/scopes.ts +39 -0
  62. package/src/sdk/base.ts +6 -4
  63. package/src/sdk/cancellation.ts +39 -25
  64. package/src/types.ts +4 -0
  65. package/src/utils/chain.ts +37 -5
  66. package/src/utils/chainIds.generated.ts +1 -0
  67. package/src/utils/units.ts +9 -5
  68. package/src/viem.ts +1 -0
@@ -0,0 +1,244 @@
1
+ import type {
2
+ AuthenticateOptions,
3
+ AuthNonceResponse,
4
+ AuthSigner,
5
+ AuthToken,
6
+ AuthTokenResponse,
7
+ OpenSeaAuthConfig,
8
+ } from "./types"
9
+
10
+ export type {
11
+ AccountType,
12
+ ChainArch,
13
+ CreateSiwxMessageOptions,
14
+ LinkWalletWithSiwxOptions,
15
+ ParseSiwxMessageResult,
16
+ } from "./siwx"
17
+ export {
18
+ chainArchToAccountType,
19
+ createSiwxMessage,
20
+ linkWalletWithSiwx,
21
+ parseSiwxMessage,
22
+ requestSiwxNonce,
23
+ } from "./siwx"
24
+ export type {
25
+ AuthenticateOptions,
26
+ AuthNonceResponse,
27
+ AuthSigner,
28
+ AuthToken,
29
+ AuthTokenResponse,
30
+ OpenSeaAuthConfig,
31
+ }
32
+
33
+ const DEFAULT_AUTH_BASE_URL = "https://auth.opensea.io"
34
+
35
+ /** Buffer (in ms) before expiry at which auto-refresh triggers. */
36
+ const REFRESH_BUFFER_MS = 60_000
37
+
38
+ /**
39
+ * SIWE-based authentication helper for OpenSea.
40
+ *
41
+ * Handles the full sign-in flow: nonce request, EIP-4361 message generation,
42
+ * signature exchange, token caching, and automatic refresh.
43
+ *
44
+ * @example
45
+ * ```ts
46
+ * import { OpenSeaAuth } from "@opensea/sdk"
47
+ *
48
+ * const auth = new OpenSeaAuth()
49
+ * const token = await auth.authenticate(signer, {
50
+ * scopes: ["read:eligibility", "write:orders"],
51
+ * })
52
+ *
53
+ * // Auto-refresh before expiry
54
+ * const freshToken = await auth.getValidToken()
55
+ *
56
+ * // Revoke
57
+ * await auth.revoke(token.accessToken)
58
+ * ```
59
+ *
60
+ * @category Authentication
61
+ */
62
+ export class OpenSeaAuth {
63
+ private readonly authBaseUrl: string
64
+ private cachedToken: AuthToken | undefined
65
+
66
+ constructor(config: OpenSeaAuthConfig = {}) {
67
+ this.authBaseUrl = (config.authBaseUrl ?? DEFAULT_AUTH_BASE_URL).replace(
68
+ /\/$/,
69
+ "",
70
+ )
71
+ }
72
+
73
+ /**
74
+ * Run the full SIWE authentication flow:
75
+ * 1. Request a nonce from the auth server
76
+ * 2. Build an EIP-4361 SIWE message
77
+ * 3. Sign it with the provided signer
78
+ * 4. Exchange the signature for a scoped JWT token
79
+ *
80
+ * The returned token is cached in memory and will be auto-refreshed
81
+ * by {@link getValidToken}.
82
+ */
83
+ async authenticate(
84
+ signer: AuthSigner,
85
+ options: AuthenticateOptions = {},
86
+ ): Promise<AuthToken> {
87
+ const address = await signer.getAddress()
88
+ const { nonce } = await this.requestNonce()
89
+ const message = generateSiweMessage(
90
+ address,
91
+ options.scopes ?? [],
92
+ nonce,
93
+ this.authBaseUrl,
94
+ )
95
+ const signature = await signer.signMessage(message)
96
+ const tokenResponse = await this.exchangeSignature(message, signature)
97
+ const token = toAuthToken(tokenResponse)
98
+ this.cachedToken = token
99
+ return token
100
+ }
101
+
102
+ /**
103
+ * Return a valid access token, refreshing automatically if the cached
104
+ * token is expired or about to expire.
105
+ *
106
+ * @throws If no token has been obtained yet via {@link authenticate}.
107
+ */
108
+ async getValidToken(): Promise<AuthToken> {
109
+ if (!this.cachedToken) {
110
+ throw new Error(
111
+ "No auth token available. Call authenticate() with a signer first.",
112
+ )
113
+ }
114
+
115
+ if (this.cachedToken.expiresAt.getTime() - Date.now() < REFRESH_BUFFER_MS) {
116
+ const tokenResponse = await this.refreshToken(
117
+ this.cachedToken.refreshToken,
118
+ )
119
+ this.cachedToken = toAuthToken(tokenResponse)
120
+ }
121
+
122
+ return this.cachedToken
123
+ }
124
+
125
+ /**
126
+ * Revoke an access token.
127
+ */
128
+ async revoke(accessToken: string): Promise<void> {
129
+ const response = await fetch(`${this.authBaseUrl}/api/revoke`, {
130
+ method: "POST",
131
+ headers: { "Content-Type": "application/json" },
132
+ body: JSON.stringify({ token: accessToken }),
133
+ })
134
+ if (!response.ok) {
135
+ throw new Error(
136
+ `Auth server error (${response.status}): ${response.statusText}`,
137
+ )
138
+ }
139
+ if (this.cachedToken?.accessToken === accessToken) {
140
+ this.cachedToken = undefined
141
+ }
142
+ }
143
+
144
+ /** Request a nonce from the auth server. */
145
+ async requestNonce(): Promise<AuthNonceResponse> {
146
+ const response = await fetch(`${this.authBaseUrl}/api/nonce`, {
147
+ method: "GET",
148
+ headers: { Accept: "application/json" },
149
+ })
150
+ if (!response.ok) {
151
+ throw new Error(
152
+ `Auth server error (${response.status}): ${response.statusText}`,
153
+ )
154
+ }
155
+ return response.json() as Promise<AuthNonceResponse>
156
+ }
157
+
158
+ /** Exchange a signed SIWE message for a JWT token. */
159
+ private async exchangeSignature(
160
+ message: string,
161
+ signature: string,
162
+ ): Promise<AuthTokenResponse> {
163
+ const response = await fetch(`${this.authBaseUrl}/api/token`, {
164
+ method: "POST",
165
+ headers: { "Content-Type": "application/json" },
166
+ body: JSON.stringify({ message, signature }),
167
+ })
168
+ if (!response.ok) {
169
+ throw new Error(
170
+ `Auth server error (${response.status}): ${response.statusText}`,
171
+ )
172
+ }
173
+ return response.json() as Promise<AuthTokenResponse>
174
+ }
175
+
176
+ /** Refresh an access token using a refresh token. */
177
+ private async refreshToken(
178
+ refreshTokenValue: string,
179
+ ): Promise<AuthTokenResponse> {
180
+ const response = await fetch(`${this.authBaseUrl}/api/refresh`, {
181
+ method: "POST",
182
+ headers: { "Content-Type": "application/json" },
183
+ body: JSON.stringify({ refresh_token: refreshTokenValue }),
184
+ })
185
+ if (!response.ok) {
186
+ throw new Error(
187
+ `Auth server error (${response.status}): ${response.statusText}`,
188
+ )
189
+ }
190
+ return response.json() as Promise<AuthTokenResponse>
191
+ }
192
+ }
193
+
194
+ /** Validity window (in ms) for a generated SIWE message. */
195
+ const SIWE_MESSAGE_VALIDITY_MS = 10 * 60_000
196
+
197
+ /**
198
+ * Build an EIP-4361 (SIWE) message for OpenSea authentication.
199
+ *
200
+ * @see https://eips.ethereum.org/EIPS/eip-4361
201
+ */
202
+ export function generateSiweMessage(
203
+ address: string,
204
+ scopes: string[],
205
+ nonce: string,
206
+ authBaseUrl: string,
207
+ chainId = 1,
208
+ ): string {
209
+ const url = new URL(authBaseUrl)
210
+ const domain = url.host
211
+ const uri = `${authBaseUrl}/api/token`
212
+ const now = Date.now()
213
+ const issuedAt = new Date(now).toISOString()
214
+ const expirationTime = new Date(now + SIWE_MESSAGE_VALIDITY_MS).toISOString()
215
+ const resources =
216
+ scopes.length > 0
217
+ ? `\nResources:${scopes.map(s => `\n- ${s}`).join("")}`
218
+ : ""
219
+
220
+ return [
221
+ `${domain} wants you to sign in with your Ethereum account:`,
222
+ address,
223
+ "",
224
+ "Sign in to OpenSea",
225
+ "",
226
+ `URI: ${uri}`,
227
+ "Version: 1",
228
+ `Chain ID: ${chainId}`,
229
+ `Nonce: ${nonce}`,
230
+ `Issued At: ${issuedAt}`,
231
+ `Expiration Time: ${expirationTime}`,
232
+ ...(resources ? [resources] : []),
233
+ ].join("\n")
234
+ }
235
+
236
+ /** Convert a raw auth server response to a typed AuthToken. */
237
+ function toAuthToken(response: AuthTokenResponse): AuthToken {
238
+ return {
239
+ accessToken: response.access_token,
240
+ refreshToken: response.refresh_token,
241
+ expiresAt: new Date(Date.now() + response.expires_in * 1000),
242
+ scopes: response.scopes,
243
+ }
244
+ }
@@ -0,0 +1,73 @@
1
+ /**
2
+ * Configuration for the {@link OpenSeaOAuth} helper.
3
+ */
4
+ export interface OpenSeaOAuthConfig {
5
+ /**
6
+ * Public OAuth client id (Zitadel `auth_method: none` + PKCE client).
7
+ * Provisioned via opensea-infrastructure; required.
8
+ */
9
+ clientId: string
10
+ /** Authorization server issuer. Defaults to `https://auth.opensea.io`. */
11
+ issuer?: string
12
+ /**
13
+ * Per-request network timeout in milliseconds for calls to the
14
+ * authorization server. Defaults to 30000 (30s). Guards against a hung
15
+ * connection stalling `opensea login` (or an SDK consumer) indefinitely.
16
+ */
17
+ timeoutMs?: number
18
+ }
19
+
20
+ /**
21
+ * A token set returned by the OAuth 2.1 code/PKCE or device flow.
22
+ */
23
+ export interface OAuthToken {
24
+ /** JWT access token (bearer credential for the OpenSea API). */
25
+ accessToken: string
26
+ /** Refresh token for obtaining a new access token, if granted. */
27
+ refreshToken?: string
28
+ /** OIDC ID token, if `openid` scope was granted. */
29
+ idToken?: string
30
+ /** When the access token expires. */
31
+ expiresAt: Date
32
+ /** Scopes granted to this token. */
33
+ scopes: string[]
34
+ }
35
+
36
+ /**
37
+ * Subset of the OIDC discovery document (`/.well-known/openid-configuration`)
38
+ * this helper relies on.
39
+ */
40
+ export interface OAuthDiscoveryDocument {
41
+ issuer: string
42
+ authorization_endpoint: string
43
+ token_endpoint: string
44
+ device_authorization_endpoint?: string
45
+ revocation_endpoint?: string
46
+ registration_endpoint?: string
47
+ scopes_supported?: string[]
48
+ code_challenge_methods_supported?: string[]
49
+ }
50
+
51
+ /**
52
+ * Raw token response from the OAuth token endpoint.
53
+ */
54
+ export interface OAuthTokenResponse {
55
+ access_token: string
56
+ refresh_token?: string
57
+ id_token?: string
58
+ token_type: string
59
+ expires_in: number
60
+ scope?: string
61
+ }
62
+
63
+ /**
64
+ * Response from the device authorization endpoint (RFC 8628).
65
+ */
66
+ export interface DeviceAuthorizationResponse {
67
+ device_code: string
68
+ user_code: string
69
+ verification_uri: string
70
+ verification_uri_complete?: string
71
+ expires_in: number
72
+ interval?: number
73
+ }