@misofm/sdk 0.2.1 → 0.4.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 (87) hide show
  1. package/README.md +68 -5
  2. package/dist/auth.d.ts +73 -0
  3. package/dist/auth.d.ts.map +1 -0
  4. package/dist/auth.js +193 -0
  5. package/dist/auth.js.map +1 -0
  6. package/dist/contracts/miso_drop/drop.d.ts +550 -0
  7. package/dist/contracts/miso_drop/drop.d.ts.map +1 -0
  8. package/dist/contracts/miso_drop/drop.js +523 -0
  9. package/dist/contracts/miso_drop/drop.js.map +1 -0
  10. package/dist/contracts.d.ts +1 -0
  11. package/dist/contracts.d.ts.map +1 -1
  12. package/dist/contracts.js +3 -0
  13. package/dist/contracts.js.map +1 -1
  14. package/dist/drop.d.ts +120 -0
  15. package/dist/drop.d.ts.map +1 -0
  16. package/dist/drop.js +152 -0
  17. package/dist/drop.js.map +1 -0
  18. package/dist/index.d.ts +1 -0
  19. package/dist/index.d.ts.map +1 -1
  20. package/dist/index.js +4 -0
  21. package/dist/index.js.map +1 -1
  22. package/dist/read/artist.d.ts +24 -0
  23. package/dist/read/artist.d.ts.map +1 -0
  24. package/dist/read/artist.js +114 -0
  25. package/dist/read/artist.js.map +1 -0
  26. package/dist/read/catalog.d.ts +63 -0
  27. package/dist/read/catalog.d.ts.map +1 -0
  28. package/dist/read/catalog.js +252 -0
  29. package/dist/read/catalog.js.map +1 -0
  30. package/dist/read/client.d.ts +36 -0
  31. package/dist/read/client.d.ts.map +1 -0
  32. package/dist/read/client.js +46 -0
  33. package/dist/read/client.js.map +1 -0
  34. package/dist/read/config.d.ts +83 -0
  35. package/dist/read/config.d.ts.map +1 -0
  36. package/dist/read/config.js +76 -0
  37. package/dist/read/config.js.map +1 -0
  38. package/dist/read/genres.d.ts +7 -0
  39. package/dist/read/genres.d.ts.map +1 -0
  40. package/dist/read/genres.js +38 -0
  41. package/dist/read/genres.js.map +1 -0
  42. package/dist/read/index.d.ts +12 -0
  43. package/dist/read/index.d.ts.map +1 -0
  44. package/dist/read/index.js +23 -0
  45. package/dist/read/index.js.map +1 -0
  46. package/dist/read/internal/scalars.d.ts +23 -0
  47. package/dist/read/internal/scalars.d.ts.map +1 -0
  48. package/dist/read/internal/scalars.js +56 -0
  49. package/dist/read/internal/scalars.js.map +1 -0
  50. package/dist/read/internal/walrus.d.ts +4 -0
  51. package/dist/read/internal/walrus.d.ts.map +1 -0
  52. package/dist/read/internal/walrus.js +23 -0
  53. package/dist/read/internal/walrus.js.map +1 -0
  54. package/dist/read/receipts.d.ts +22 -0
  55. package/dist/read/receipts.d.ts.map +1 -0
  56. package/dist/read/receipts.js +233 -0
  57. package/dist/read/receipts.js.map +1 -0
  58. package/dist/read/types.d.ts +279 -0
  59. package/dist/read/types.d.ts.map +1 -0
  60. package/dist/read/types.js +21 -0
  61. package/dist/read/types.js.map +1 -0
  62. package/dist/read/wallet.d.ts +58 -0
  63. package/dist/read/wallet.d.ts.map +1 -0
  64. package/dist/read/wallet.js +325 -0
  65. package/dist/read/wallet.js.map +1 -0
  66. package/dist/read/works.d.ts +31 -0
  67. package/dist/read/works.d.ts.map +1 -0
  68. package/dist/read/works.js +106 -0
  69. package/dist/read/works.js.map +1 -0
  70. package/package.json +19 -2
  71. package/src/auth.ts +275 -0
  72. package/src/contracts/miso_drop/drop.ts +798 -0
  73. package/src/contracts.ts +4 -0
  74. package/src/drop.ts +266 -0
  75. package/src/index.ts +5 -0
  76. package/src/read/artist.ts +136 -0
  77. package/src/read/catalog.ts +293 -0
  78. package/src/read/client.ts +79 -0
  79. package/src/read/config.ts +164 -0
  80. package/src/read/genres.ts +37 -0
  81. package/src/read/index.ts +53 -0
  82. package/src/read/internal/scalars.ts +57 -0
  83. package/src/read/internal/walrus.ts +32 -0
  84. package/src/read/receipts.ts +266 -0
  85. package/src/read/types.ts +361 -0
  86. package/src/read/wallet.ts +360 -0
  87. package/src/read/works.ts +164 -0
package/src/auth.ts ADDED
@@ -0,0 +1,275 @@
1
+ // Copyright (c) Miso Labs, Inc.
2
+ // SPDX-License-Identifier: Apache-2.0
3
+
4
+ import { isValidSuiAddress, normalizeSuiAddress } from "@mysten/sui/utils";
5
+
6
+ export type AuthNetwork = "testnet" | "mainnet";
7
+
8
+ export interface ApiAuthorizationFields {
9
+ method: string;
10
+ path: string;
11
+ address: string;
12
+ network: AuthNetwork;
13
+ issuedAt: string;
14
+ }
15
+
16
+ export interface AuthorizationChallenge extends ApiAuthorizationFields {
17
+ payload: string;
18
+ expiresAt: string;
19
+ }
20
+
21
+ export interface PersonalMessageSigner {
22
+ signPersonalMessage(message: Uint8Array): Promise<{ signature: string; bytes?: string }>;
23
+ }
24
+
25
+ export const AUTHORIZATION_MAX_AGE_MS = 5 * 60 * 1_000;
26
+ export const AUTHORIZATION_FUTURE_SKEW_MS = 60 * 1_000;
27
+
28
+ export const MISO_AUTH_HEADERS = {
29
+ address: "X-Sui-Address",
30
+ signature: "X-Sui-Signature",
31
+ issuedAt: "X-Sui-Issued-At",
32
+ } as const;
33
+
34
+ export type MisoAuthErrorCode =
35
+ | "invalid_target"
36
+ | "challenge_rejected"
37
+ | "invalid_challenge"
38
+ | "signing_failed";
39
+
40
+ export class MisoAuthError extends Error {
41
+ readonly code: MisoAuthErrorCode;
42
+ readonly status?: number;
43
+
44
+ constructor(code: MisoAuthErrorCode, message: string, options: { status?: number; cause?: unknown } = {}) {
45
+ super(message, options.cause === undefined ? undefined : { cause: options.cause });
46
+ this.name = "MisoAuthError";
47
+ this.code = code;
48
+ this.status = options.status;
49
+ }
50
+ }
51
+
52
+ /** The byte-exact Sui personal message required for an authenticated API mutation. */
53
+ export function buildApiAuthorizationPayload(fields: ApiAuthorizationFields): string {
54
+ return [
55
+ "miso.fm API authorization v1",
56
+ "",
57
+ `Method: ${fields.method.toUpperCase()}`,
58
+ `Path: ${fields.path}`,
59
+ `Address: ${fields.address}`,
60
+ `Network: ${fields.network}`,
61
+ `Issued At: ${fields.issuedAt}`,
62
+ ].join("\n");
63
+ }
64
+
65
+ export function isValidAuthorizationTarget(method: string, path: string): boolean {
66
+ return (
67
+ ["POST", "PUT", "PATCH", "DELETE"].includes(method.toUpperCase()) &&
68
+ path.startsWith("/platform/") &&
69
+ path.length <= 2_048 &&
70
+ !/[\r\n?#]/.test(path)
71
+ );
72
+ }
73
+
74
+ /** Accept only fresh timestamps in one canonical spelling. */
75
+ export function parseFreshAuthorizationIssuedAt(input: unknown, nowMs: number = Date.now()): string | null {
76
+ if (typeof input !== "string") return null;
77
+ const issuedAtMs = Date.parse(input);
78
+ if (!Number.isFinite(issuedAtMs)) return null;
79
+ if (
80
+ issuedAtMs > nowMs + AUTHORIZATION_FUTURE_SKEW_MS ||
81
+ nowMs - issuedAtMs > AUTHORIZATION_MAX_AGE_MS
82
+ ) {
83
+ return null;
84
+ }
85
+ const canonical = new Date(issuedAtMs).toISOString();
86
+ return input === canonical ? canonical : null;
87
+ }
88
+
89
+ function target(method: string, path: string): { method: string; path: string } {
90
+ const normalized = { method: method.toUpperCase(), path };
91
+ if (!isValidAuthorizationTarget(normalized.method, normalized.path)) {
92
+ throw new MisoAuthError("invalid_target", "Authenticated requests require a mutation under /platform/.");
93
+ }
94
+ return normalized;
95
+ }
96
+
97
+ function parseChallenge(
98
+ input: unknown,
99
+ expected: { method: string; path: string; address: string; network?: AuthNetwork; nowMs?: number },
100
+ ): AuthorizationChallenge {
101
+ if (input === null || typeof input !== "object" || Array.isArray(input)) {
102
+ throw new MisoAuthError("invalid_challenge", "The API returned an invalid authorization challenge.");
103
+ }
104
+ const body = input as Partial<Record<keyof AuthorizationChallenge, unknown>>;
105
+ if (
106
+ typeof body.payload !== "string" ||
107
+ typeof body.method !== "string" ||
108
+ typeof body.path !== "string" ||
109
+ typeof body.address !== "string" ||
110
+ typeof body.network !== "string" ||
111
+ typeof body.issuedAt !== "string" ||
112
+ typeof body.expiresAt !== "string" ||
113
+ !isValidSuiAddress(body.address) ||
114
+ (body.network !== "testnet" && body.network !== "mainnet")
115
+ ) {
116
+ throw new MisoAuthError("invalid_challenge", "The API returned an invalid authorization challenge.");
117
+ }
118
+
119
+ const nowMs = expected.nowMs ?? Date.now();
120
+ const issuedAt = parseFreshAuthorizationIssuedAt(body.issuedAt, nowMs);
121
+ const expiresAtMs = Date.parse(body.expiresAt);
122
+ const canonicalAddress = normalizeSuiAddress(body.address);
123
+ const expectedAddress = normalizeSuiAddress(expected.address);
124
+ const challenge: AuthorizationChallenge = {
125
+ payload: body.payload,
126
+ method: body.method,
127
+ path: body.path,
128
+ address: canonicalAddress,
129
+ network: body.network,
130
+ issuedAt: body.issuedAt,
131
+ expiresAt: body.expiresAt,
132
+ };
133
+ const canonicalExpiresAt = Number.isFinite(expiresAtMs) ? new Date(expiresAtMs).toISOString() : "";
134
+
135
+ if (
136
+ !issuedAt ||
137
+ body.method !== expected.method ||
138
+ body.path !== expected.path ||
139
+ canonicalAddress !== expectedAddress ||
140
+ (expected.network !== undefined && body.network !== expected.network) ||
141
+ body.expiresAt !== canonicalExpiresAt ||
142
+ expiresAtMs <= nowMs ||
143
+ expiresAtMs > Date.parse(issuedAt) + AUTHORIZATION_MAX_AGE_MS ||
144
+ body.payload !== buildApiAuthorizationPayload(challenge)
145
+ ) {
146
+ throw new MisoAuthError("invalid_challenge", "The authorization challenge did not match this request.");
147
+ }
148
+ return challenge;
149
+ }
150
+
151
+ async function responseMessage(response: Response): Promise<string> {
152
+ const body = await response.clone().json().catch(() => null) as {
153
+ error?: { message?: unknown } | string;
154
+ message?: unknown;
155
+ } | null;
156
+ if (typeof body?.error === "object" && typeof body.error.message === "string") return body.error.message;
157
+ if (typeof body?.error === "string") return body.error;
158
+ if (typeof body?.message === "string") return body.message;
159
+ return `Authorization challenge failed (${response.status}).`;
160
+ }
161
+
162
+ export interface RequestAuthorizationChallengeOptions {
163
+ apiUrl: string | URL;
164
+ token: string;
165
+ address: string;
166
+ method: string;
167
+ path: string;
168
+ network?: AuthNetwork;
169
+ challengeUrl?: string | URL;
170
+ fetch?: typeof globalThis.fetch;
171
+ nowMs?: number;
172
+ }
173
+
174
+ /** Ask Miso to verify the Enoki account and issue the exact message to sign. */
175
+ export async function requestAuthorizationChallenge(
176
+ options: RequestAuthorizationChallengeOptions,
177
+ ): Promise<AuthorizationChallenge> {
178
+ const expected = target(options.method, options.path);
179
+ if (!options.token || !isValidSuiAddress(options.address)) {
180
+ throw new MisoAuthError("challenge_rejected", "A valid Enoki token and Sui address are required.");
181
+ }
182
+ const apiUrl = new URL(options.apiUrl);
183
+ const challengeUrl = options.challengeUrl === undefined
184
+ ? new URL("/platform/auth/challenge", apiUrl.origin)
185
+ : new URL(options.challengeUrl, apiUrl);
186
+ const fetcher = options.fetch ?? globalThis.fetch;
187
+ const response = await fetcher(challengeUrl, {
188
+ method: "POST",
189
+ headers: {
190
+ Authorization: `Bearer ${options.token}`,
191
+ [MISO_AUTH_HEADERS.address]: normalizeSuiAddress(options.address),
192
+ "Content-Type": "application/json",
193
+ },
194
+ body: JSON.stringify(expected),
195
+ });
196
+ if (!response.ok) {
197
+ throw new MisoAuthError("challenge_rejected", await responseMessage(response), { status: response.status });
198
+ }
199
+ const body = await response.json().catch(() => null);
200
+ return parseChallenge(body, {
201
+ ...expected,
202
+ address: options.address,
203
+ network: options.network,
204
+ nowMs: options.nowMs,
205
+ });
206
+ }
207
+
208
+ export interface CreateAuthorizationHeadersOptions extends RequestAuthorizationChallengeOptions {
209
+ signer: PersonalMessageSigner;
210
+ }
211
+
212
+ /** Verify the challenge locally, sign it as a Sui personal message, and produce API headers. */
213
+ export async function createAuthorizationHeaders(
214
+ options: CreateAuthorizationHeadersOptions,
215
+ ): Promise<{ challenge: AuthorizationChallenge; headers: Headers }> {
216
+ const challenge = await requestAuthorizationChallenge(options);
217
+ let signature: string;
218
+ try {
219
+ const signed = await options.signer.signPersonalMessage(new TextEncoder().encode(challenge.payload));
220
+ signature = signed.signature;
221
+ } catch (cause) {
222
+ throw new MisoAuthError("signing_failed", "The authorization request was not signed.", { cause });
223
+ }
224
+ if (!signature) {
225
+ throw new MisoAuthError("signing_failed", "The signer returned an empty authorization signature.");
226
+ }
227
+ return {
228
+ challenge,
229
+ headers: new Headers({
230
+ Authorization: `Bearer ${options.token}`,
231
+ [MISO_AUTH_HEADERS.address]: challenge.address,
232
+ [MISO_AUTH_HEADERS.signature]: signature,
233
+ [MISO_AUTH_HEADERS.issuedAt]: challenge.issuedAt,
234
+ }),
235
+ };
236
+ }
237
+
238
+ export interface AuthenticatedFetchOptions extends RequestInit {
239
+ auth: {
240
+ token: string;
241
+ address: string;
242
+ signer: PersonalMessageSigner;
243
+ network?: AuthNetwork;
244
+ };
245
+ challengeUrl?: string | URL;
246
+ fetch?: typeof globalThis.fetch;
247
+ }
248
+
249
+ /** Perform a protected Miso API mutation with a fresh Enoki-verified Sui signature. */
250
+ export async function authenticatedFetch(
251
+ input: string | URL,
252
+ options: AuthenticatedFetchOptions,
253
+ ): Promise<Response> {
254
+ const { auth, challengeUrl, fetch: fetchOption, ...init } = options;
255
+ const url = new URL(input);
256
+ const method = (init.method ?? "").toUpperCase();
257
+ if (url.search || url.hash) {
258
+ throw new MisoAuthError("invalid_target", "Authenticated request URLs cannot include a query or fragment.");
259
+ }
260
+ const fetcher = fetchOption ?? globalThis.fetch;
261
+ const authorization = await createAuthorizationHeaders({
262
+ apiUrl: url,
263
+ challengeUrl,
264
+ fetch: fetcher,
265
+ token: auth.token,
266
+ address: auth.address,
267
+ signer: auth.signer,
268
+ network: auth.network,
269
+ method,
270
+ path: url.pathname,
271
+ });
272
+ const headers = new Headers(init.headers);
273
+ authorization.headers.forEach((value, name) => headers.set(name, value));
274
+ return fetcher(url, { ...init, method, headers });
275
+ }