@opensea/sdk 11.4.8 → 11.5.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.
package/src/auth/index.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import { createSiwxMessage, parseSiwxMessage } from "./siwx"
1
2
  import type {
2
3
  AuthenticateOptions,
3
4
  AuthNonceResponse,
@@ -30,16 +31,33 @@ export type {
30
31
  OpenSeaAuthConfig,
31
32
  }
32
33
 
33
- const DEFAULT_AUTH_BASE_URL = "https://auth.opensea.io"
34
-
35
- /** Buffer (in ms) before expiry at which auto-refresh triggers. */
34
+ const DEFAULT_API_BASE_URL = "https://api.opensea.io"
35
+ const DEFAULT_TOKEN_TTL_SECONDS = 3600
36
+ const SCOPED_TOKEN_CLEANUP_ATTEMPTS = 2
36
37
  const REFRESH_BUFFER_MS = 60_000
38
+ const SIWE_STATEMENT =
39
+ "Click to sign in and accept the OpenSea Terms of Service (https://opensea.io/tos) and Privacy Policy (https://opensea.io/privacy)."
40
+ const SESSION_COOKIE_NAMES = ["access_token", "refresh_token"]
41
+
42
+ interface ScopedTokenCreatedResponse {
43
+ id: string
44
+ token: string
45
+ scopes: string[]
46
+ }
47
+
48
+ interface ScopedTokenExchangeResponse {
49
+ accessToken: string
50
+ expiresIn?: number
51
+ tokenScopes?: string[]
52
+ }
37
53
 
38
54
  /**
39
55
  * SIWE-based authentication helper for OpenSea.
40
56
  *
41
- * Handles the full sign-in flow: nonce request, EIP-4361 message generation,
42
- * signature exchange, token caching, and automatic refresh.
57
+ * Establishes a browser-style wallet session, creates a one-day scoped token,
58
+ * and exchanges that token for the short-lived JWT used by REST and MCP. Token
59
+ * management remains bound to the wallet session, while automatic JWT refresh
60
+ * uses the scoped token.
43
61
  *
44
62
  * @example
45
63
  * ```ts
@@ -49,62 +67,58 @@ const REFRESH_BUFFER_MS = 60_000
49
67
  * const token = await auth.authenticate(signer, {
50
68
  * scopes: ["read:eligibility", "write:orders"],
51
69
  * })
52
- *
53
- * // Auto-refresh before expiry
54
70
  * const freshToken = await auth.getValidToken()
55
- *
56
- * // Revoke
57
- * await auth.revoke(token.accessToken)
71
+ * await auth.revoke(freshToken.accessToken)
58
72
  * ```
59
73
  *
60
74
  * @category Authentication
61
75
  */
62
76
  export class OpenSeaAuth {
63
- private readonly authBaseUrl: string
77
+ private readonly apiBaseUrl: string
64
78
  private cachedToken: AuthToken | undefined
79
+ private scopedTokenId: string | undefined
80
+ private sessionCookies: string | undefined
65
81
 
66
82
  constructor(config: OpenSeaAuthConfig = {}) {
67
- this.authBaseUrl = (config.authBaseUrl ?? DEFAULT_AUTH_BASE_URL).replace(
68
- /\/$/,
69
- "",
70
- )
83
+ this.apiBaseUrl = (
84
+ config.apiBaseUrl ??
85
+ config.authBaseUrl ??
86
+ DEFAULT_API_BASE_URL
87
+ ).replace(/\/$/, "")
71
88
  }
72
89
 
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
- */
90
+ /** Run the current SIWE, scoped-token creation, and token-exchange flow. */
83
91
  async authenticate(
84
92
  signer: AuthSigner,
85
93
  options: AuthenticateOptions = {},
86
94
  ): Promise<AuthToken> {
95
+ const scopes = options.scopes ?? []
87
96
  const address = await signer.getAddress()
88
97
  const { nonce } = await this.requestNonce()
89
- const message = generateSiweMessage(
90
- address,
91
- options.scopes ?? [],
92
- nonce,
93
- this.authBaseUrl,
94
- )
98
+ // Webauth uses SIWE only to establish the wallet session. Including PAT
99
+ // scopes here does not round-trip through its signature reconstruction;
100
+ // scope entitlement is enforced by the session-authorized token request.
101
+ const message = generateSiweMessage(address, [], nonce, this.apiBaseUrl)
95
102
  const signature = await signer.signMessage(message)
96
- const tokenResponse = await this.exchangeSignature(message, signature)
97
- const token = toAuthToken(tokenResponse)
103
+ const cookie = await this.verifySignature(message, signature)
104
+ const scopedToken = await this.createScopedToken(cookie, scopes)
105
+
106
+ let exchange: ScopedTokenExchangeResponse
107
+ try {
108
+ exchange = await this.exchangeScopedToken(scopedToken.token)
109
+ } catch (error) {
110
+ await this.cleanupScopedToken(cookie, scopedToken.id)
111
+ throw error
112
+ }
113
+
114
+ const token = toAuthToken(exchange, scopedToken)
98
115
  this.cachedToken = token
116
+ this.scopedTokenId = scopedToken.id
117
+ this.sessionCookies = cookie
99
118
  return token
100
119
  }
101
120
 
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
- */
121
+ /** Return a valid JWT, exchanging the stored scoped token when needed. */
108
122
  async getValidToken(): Promise<AuthToken> {
109
123
  if (!this.cachedToken) {
110
124
  throw new Error(
@@ -113,132 +127,213 @@ export class OpenSeaAuth {
113
127
  }
114
128
 
115
129
  if (this.cachedToken.expiresAt.getTime() - Date.now() < REFRESH_BUFFER_MS) {
116
- const tokenResponse = await this.refreshToken(
130
+ const exchange = await this.exchangeScopedToken(
117
131
  this.cachedToken.refreshToken,
118
132
  )
119
- this.cachedToken = toAuthToken(tokenResponse)
133
+ this.cachedToken = toAuthToken(exchange, {
134
+ id: this.scopedTokenId ?? "",
135
+ token: this.cachedToken.refreshToken,
136
+ scopes: this.cachedToken.scopes,
137
+ })
120
138
  }
121
139
 
122
140
  return this.cachedToken
123
141
  }
124
142
 
125
- /**
126
- * Revoke an access token.
127
- */
143
+ /** Revoke the scoped token backing the current JWT. */
128
144
  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) {
145
+ if (
146
+ !this.cachedToken ||
147
+ !this.scopedTokenId ||
148
+ !this.sessionCookies ||
149
+ this.cachedToken.accessToken !== accessToken
150
+ ) {
135
151
  throw new Error(
136
- `Auth server error (${response.status}): ${response.statusText}`,
152
+ "The access token is not managed by this OpenSeaAuth instance",
137
153
  )
138
154
  }
139
- if (this.cachedToken?.accessToken === accessToken) {
140
- this.cachedToken = undefined
141
- }
155
+
156
+ const refreshedCookies = await this.refreshSession(this.sessionCookies)
157
+ // The refresh token rotates, so retain the replacement if DELETE needs a
158
+ // retry after a transient failure.
159
+ this.sessionCookies = refreshedCookies
160
+ const response = await fetch(
161
+ `${this.apiBaseUrl}/api/v2/auth/tokens/${this.scopedTokenId}`,
162
+ { method: "DELETE", headers: { Cookie: refreshedCookies } },
163
+ )
164
+ await requireOk(response, "Scoped token revocation")
165
+ this.cachedToken = undefined
166
+ this.scopedTokenId = undefined
167
+ this.sessionCookies = undefined
142
168
  }
143
169
 
144
- /** Request a nonce from the auth server. */
170
+ /** Request a single-use SIWE nonce. */
145
171
  async requestNonce(): Promise<AuthNonceResponse> {
146
- const response = await fetch(`${this.authBaseUrl}/api/nonce`, {
147
- method: "GET",
172
+ const response = await fetch(`${this.apiBaseUrl}/api/v2/auth/siwe/nonce`, {
173
+ method: "POST",
148
174
  headers: { Accept: "application/json" },
149
175
  })
150
- if (!response.ok) {
151
- throw new Error(
152
- `Auth server error (${response.status}): ${response.statusText}`,
153
- )
154
- }
176
+ await requireOk(response, "Nonce request")
155
177
  return response.json() as Promise<AuthNonceResponse>
156
178
  }
157
179
 
158
- /** Exchange a signed SIWE message for a JWT token. */
159
- private async exchangeSignature(
180
+ private async verifySignature(
160
181
  message: string,
161
182
  signature: string,
162
- ): Promise<AuthTokenResponse> {
163
- const response = await fetch(`${this.authBaseUrl}/api/token`, {
183
+ ): Promise<string> {
184
+ const response = await fetch(`${this.apiBaseUrl}/api/v2/auth/siwe/verify`, {
164
185
  method: "POST",
165
186
  headers: { "Content-Type": "application/json" },
166
- body: JSON.stringify({ message, signature }),
187
+ body: JSON.stringify({
188
+ message: parseSiwxMessage(message),
189
+ signature,
190
+ chainArch: "EVM",
191
+ }),
167
192
  })
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>
193
+ await requireOk(response, "SIWE verification")
194
+ return extractSessionCookies(response.headers)
174
195
  }
175
196
 
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`, {
197
+ private async createScopedToken(
198
+ cookie: string,
199
+ scopes: string[],
200
+ ): Promise<ScopedTokenCreatedResponse> {
201
+ const response = await fetch(`${this.apiBaseUrl}/api/v2/auth/tokens`, {
181
202
  method: "POST",
182
- headers: { "Content-Type": "application/json" },
183
- body: JSON.stringify({ refresh_token: refreshTokenValue }),
203
+ headers: { "Content-Type": "application/json", Cookie: cookie },
204
+ body: JSON.stringify({
205
+ label: `opensea-sdk-${Date.now()}`,
206
+ scopes,
207
+ expiresInDays: 1,
208
+ }),
184
209
  })
185
- if (!response.ok) {
186
- throw new Error(
187
- `Auth server error (${response.status}): ${response.statusText}`,
188
- )
210
+ await requireOk(response, "Scoped token creation")
211
+ return response.json() as Promise<ScopedTokenCreatedResponse>
212
+ }
213
+
214
+ private async exchangeScopedToken(
215
+ scopedToken: string,
216
+ ): Promise<ScopedTokenExchangeResponse> {
217
+ const response = await fetch(
218
+ `${this.apiBaseUrl}/api/v2/auth/tokens/exchange`,
219
+ {
220
+ method: "POST",
221
+ headers: { "Content-Type": "application/json" },
222
+ body: JSON.stringify({
223
+ subjectToken: scopedToken,
224
+ subjectTokenType: "ACCESS_TOKEN",
225
+ }),
226
+ },
227
+ )
228
+ await requireOk(response, "Token exchange")
229
+ return response.json() as Promise<ScopedTokenExchangeResponse>
230
+ }
231
+
232
+ private async cleanupScopedToken(cookie: string, id: string): Promise<void> {
233
+ for (let attempt = 0; attempt < SCOPED_TOKEN_CLEANUP_ATTEMPTS; attempt++) {
234
+ try {
235
+ const response = await fetch(
236
+ `${this.apiBaseUrl}/api/v2/auth/tokens/${id}`,
237
+ { method: "DELETE", headers: { Cookie: cookie } },
238
+ )
239
+ if (response.ok || response.status === 404) return
240
+ } catch {
241
+ // Retry once, then preserve the original exchange failure.
242
+ }
189
243
  }
190
- return response.json() as Promise<AuthTokenResponse>
191
244
  }
192
- }
193
245
 
194
- /** Validity window (in ms) for a generated SIWE message. */
195
- const SIWE_MESSAGE_VALIDITY_MS = 10 * 60_000
246
+ private async refreshSession(cookie: string): Promise<string> {
247
+ const response = await fetch(
248
+ `${this.apiBaseUrl}/api/v2/auth/session/refresh`,
249
+ { method: "POST", headers: { Cookie: cookie } },
250
+ )
251
+ await requireOk(response, "Session refresh")
252
+ return extractSessionCookies(response.headers)
253
+ }
254
+ }
196
255
 
197
256
  /**
198
- * Build an EIP-4361 (SIWE) message for OpenSea authentication.
199
- *
200
- * @see https://eips.ethereum.org/EIPS/eip-4361
257
+ * Build the SIWE message accepted by the current OpenSea wallet-auth API.
258
+ * The scopes argument remains for compatibility; webauth authorizes PAT scopes
259
+ * on token creation and does not accept them in this session proof.
201
260
  */
202
261
  export function generateSiweMessage(
203
262
  address: string,
204
- scopes: string[],
263
+ _scopes: string[],
205
264
  nonce: string,
206
- authBaseUrl: string,
265
+ _apiBaseUrl: string,
207
266
  chainId = 1,
208
267
  ): 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:`,
268
+ return createSiwxMessage({
222
269
  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")
270
+ chainArch: "EVM",
271
+ chainId,
272
+ nonce,
273
+ statement: SIWE_STATEMENT,
274
+ issuedAt: new Date(),
275
+ })
276
+ }
277
+
278
+ async function requireOk(response: Response, operation: string): Promise<void> {
279
+ if (response.ok) return
280
+ const body = await response.text().catch(() => "")
281
+ throw new Error(`${operation} failed (${response.status}): ${body}`)
282
+ }
283
+
284
+ function splitSetCookieHeader(header: string): string[] {
285
+ const segments = header.split(", ")
286
+ const cookies: string[] = []
287
+ let current = ""
288
+ for (const segment of segments) {
289
+ const trimmed = segment.trim()
290
+ const equals = trimmed.indexOf("=")
291
+ const name = equals > 0 ? trimmed.slice(0, equals).trim() : ""
292
+ if (SESSION_COOKIE_NAMES.includes(name) && current) {
293
+ cookies.push(current)
294
+ current = trimmed
295
+ } else if (SESSION_COOKIE_NAMES.includes(name)) {
296
+ current = trimmed
297
+ } else {
298
+ current = current ? `${current}, ${trimmed}` : trimmed
299
+ }
300
+ }
301
+ if (current) cookies.push(current)
302
+ return cookies
303
+ }
304
+
305
+ function extractSessionCookies(headers: Headers): string {
306
+ const getSetCookie = (headers as Headers & { getSetCookie?: () => string[] })
307
+ .getSetCookie
308
+ const raw =
309
+ getSetCookie?.call(headers) ??
310
+ splitSetCookieHeader(headers.get("set-cookie") ?? "")
311
+ const cookies = new Map<string, string>()
312
+ for (const cookie of raw) {
313
+ const pair = cookie.split(";")[0]
314
+ const equals = pair.indexOf("=")
315
+ if (equals < 0) continue
316
+ const name = pair.slice(0, equals).trim()
317
+ if (SESSION_COOKIE_NAMES.includes(name)) {
318
+ cookies.set(name, pair.slice(equals + 1).trim())
319
+ }
320
+ }
321
+ if (!cookies.has("access_token") || !cookies.has("refresh_token")) {
322
+ throw new Error("SIWE verification did not create a session")
323
+ }
324
+ return [...cookies].map(([name, value]) => `${name}=${value}`).join("; ")
234
325
  }
235
326
 
236
- /** Convert a raw auth server response to a typed AuthToken. */
237
- function toAuthToken(response: AuthTokenResponse): AuthToken {
327
+ function toAuthToken(
328
+ exchange: ScopedTokenExchangeResponse,
329
+ scopedToken: ScopedTokenCreatedResponse,
330
+ ): AuthToken {
238
331
  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,
332
+ accessToken: exchange.accessToken,
333
+ refreshToken: scopedToken.token,
334
+ expiresAt: new Date(
335
+ Date.now() + (exchange.expiresIn ?? DEFAULT_TOKEN_TTL_SECONDS) * 1000,
336
+ ),
337
+ scopes: exchange.tokenScopes ?? scopedToken.scopes,
243
338
  }
244
339
  }
package/src/auth/types.ts CHANGED
@@ -4,7 +4,7 @@
4
4
  export interface AuthToken {
5
5
  /** JWT access token */
6
6
  accessToken: string
7
- /** Refresh token for obtaining a new access token */
7
+ /** Scoped token (PAT) used to exchange for a new access token */
8
8
  refreshToken: string
9
9
  /** When the access token expires */
10
10
  expiresAt: Date
@@ -24,7 +24,9 @@ export interface AuthenticateOptions {
24
24
  * Configuration for the {@link OpenSeaAuth} class.
25
25
  */
26
26
  export interface OpenSeaAuthConfig {
27
- /** Auth server base URL. Defaults to `https://auth.opensea.io`. */
27
+ /** OpenSea API base URL. Defaults to `https://api.opensea.io`. */
28
+ apiBaseUrl?: string
29
+ /** @deprecated Use `apiBaseUrl`. */
28
30
  authBaseUrl?: string
29
31
  }
30
32
 
@@ -38,7 +40,8 @@ export interface AuthSigner {
38
40
  }
39
41
 
40
42
  /**
41
- * Raw token response from the auth server `/api/token` and `/api/refresh` endpoints.
43
+ * Legacy auth response shape retained for source compatibility.
44
+ * @deprecated The public wallet-auth API now returns scoped-token and exchange responses.
42
45
  */
43
46
  export interface AuthTokenResponse {
44
47
  access_token: string
@@ -48,7 +51,7 @@ export interface AuthTokenResponse {
48
51
  }
49
52
 
50
53
  /**
51
- * Nonce response from the auth server `/api/nonce` endpoint.
54
+ * Response from the SIWE nonce endpoint.
52
55
  */
53
56
  export interface AuthNonceResponse {
54
57
  nonce: string
package/src/scopes.ts CHANGED
@@ -13,8 +13,10 @@ export const OPENSEA_SCOPES = {
13
13
  READ_ELIGIBILITY: "read:eligibility",
14
14
  READ_FAVORITES: "read:favorites",
15
15
  READ_SOCIAL: "read:social",
16
+ READ_TOOLS: "read:tools",
16
17
  WRITE_FAVORITES: "write:favorites",
17
18
  WRITE_SOCIAL: "write:social",
19
+ WRITE_TOOLS: "write:tools",
18
20
  WRITE_ORDERS: "write:orders",
19
21
  WRITE_DROPS: "write:drops",
20
22
  WRITE_COLLECTIONS: "write:collections",