@thirdweb-dev/service-utils 0.5.0-nightly-6cf298a29-20240308012322 → 0.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/dist/cjs/cf-worker/index.js +164 -0
- package/dist/cjs/cf-worker/index.js.map +1 -0
- package/dist/cjs/cf-worker/usage.js +55 -0
- package/dist/cjs/cf-worker/usage.js.map +1 -0
- package/dist/cjs/core/api.js +42 -0
- package/dist/cjs/core/api.js.map +1 -0
- package/dist/cjs/core/authorize/client.js +98 -0
- package/dist/cjs/core/authorize/client.js.map +1 -0
- package/dist/cjs/core/authorize/index.js +109 -0
- package/dist/cjs/core/authorize/index.js.map +1 -0
- package/dist/cjs/core/authorize/service.js +50 -0
- package/dist/cjs/core/authorize/service.js.map +1 -0
- package/dist/cjs/core/authorize/types.js +3 -0
- package/dist/cjs/core/authorize/types.js.map +1 -0
- package/dist/cjs/core/rateLimit/index.js +60 -0
- package/dist/cjs/core/rateLimit/index.js.map +1 -0
- package/dist/cjs/core/rateLimit/types.js +3 -0
- package/dist/cjs/core/rateLimit/types.js.map +1 -0
- package/dist/cjs/core/services.js +85 -0
- package/dist/cjs/core/services.js.map +1 -0
- package/dist/cjs/core/types.js +3 -0
- package/dist/cjs/core/types.js.map +1 -0
- package/dist/cjs/core/usage.js +85 -0
- package/dist/cjs/core/usage.js.map +1 -0
- package/dist/cjs/index.js +13 -0
- package/dist/cjs/index.js.map +1 -0
- package/dist/cjs/mocks.js +60 -0
- package/dist/cjs/mocks.js.map +1 -0
- package/dist/cjs/node/index.js +182 -0
- package/dist/cjs/node/index.js.map +1 -0
- package/dist/cjs/package.json +1 -0
- package/dist/esm/cf-worker/index.js +156 -0
- package/dist/esm/cf-worker/index.js.map +1 -0
- package/dist/esm/cf-worker/usage.js +53 -0
- package/dist/esm/cf-worker/usage.js.map +1 -0
- package/dist/esm/core/api.js +38 -0
- package/dist/esm/core/api.js.map +1 -0
- package/dist/esm/core/authorize/client.js +93 -0
- package/dist/esm/core/authorize/client.js.map +1 -0
- package/dist/esm/core/authorize/index.js +106 -0
- package/dist/esm/core/authorize/index.js.map +1 -0
- package/dist/esm/core/authorize/service.js +47 -0
- package/dist/esm/core/authorize/service.js.map +1 -0
- package/dist/esm/core/authorize/types.js +2 -0
- package/dist/esm/core/authorize/types.js.map +1 -0
- package/dist/esm/core/rateLimit/index.js +57 -0
- package/dist/esm/core/rateLimit/index.js.map +1 -0
- package/dist/esm/core/rateLimit/types.js +2 -0
- package/dist/esm/core/rateLimit/types.js.map +1 -0
- package/dist/esm/core/services.js +81 -0
- package/dist/esm/core/services.js.map +1 -0
- package/dist/esm/core/types.js +2 -0
- package/dist/esm/core/types.js.map +1 -0
- package/dist/esm/core/usage.js +82 -0
- package/dist/esm/core/usage.js.map +1 -0
- package/dist/esm/index.js +5 -0
- package/dist/esm/index.js.map +1 -0
- package/dist/esm/mocks.js +57 -0
- package/dist/esm/mocks.js.map +1 -0
- package/dist/esm/node/index.js +174 -0
- package/dist/esm/node/index.js.map +1 -0
- package/dist/esm/package.json +1 -0
- package/dist/{declarations/src → types}/cf-worker/index.d.ts +8 -9
- package/dist/types/cf-worker/index.d.ts.map +1 -0
- package/dist/types/cf-worker/usage.d.ts +24 -0
- package/dist/types/cf-worker/usage.d.ts.map +1 -0
- package/dist/types/core/api.d.ts +121 -0
- package/dist/types/core/api.d.ts.map +1 -0
- package/dist/types/core/authorize/client.d.ts +17 -0
- package/dist/types/core/authorize/client.d.ts.map +1 -0
- package/dist/{declarations/src → types}/core/authorize/index.d.ts +6 -5
- package/dist/types/core/authorize/index.d.ts.map +1 -0
- package/dist/types/core/authorize/service.d.ts +4 -0
- package/dist/types/core/authorize/service.d.ts.map +1 -0
- package/dist/types/core/authorize/types.d.ts +10 -0
- package/dist/types/core/authorize/types.d.ts.map +1 -0
- package/dist/{declarations/src → types}/core/rateLimit/index.d.ts +4 -4
- package/dist/types/core/rateLimit/index.d.ts.map +1 -0
- package/dist/types/core/rateLimit/types.d.ts.map +1 -0
- package/dist/{declarations/src → types}/core/services.d.ts +55 -23
- package/dist/types/core/services.d.ts.map +1 -0
- package/dist/types/core/types.d.ts.map +1 -0
- package/dist/{declarations/src/cf-worker → types/core}/usage.d.ts +84 -30
- package/dist/types/core/usage.d.ts.map +1 -0
- package/dist/types/index.d.ts +5 -0
- package/dist/types/index.d.ts.map +1 -0
- package/dist/types/mocks.d.ts +7 -0
- package/dist/types/mocks.d.ts.map +1 -0
- package/dist/{declarations/src → types}/node/index.d.ts +10 -12
- package/dist/types/node/index.d.ts.map +1 -0
- package/package.json +42 -45
- package/cf-worker/dist/thirdweb-dev-service-utils-cf-worker.cjs.d.ts +0 -2
- package/cf-worker/dist/thirdweb-dev-service-utils-cf-worker.cjs.d.ts.map +0 -1
- package/cf-worker/dist/thirdweb-dev-service-utils-cf-worker.cjs.dev.js +0 -272
- package/cf-worker/dist/thirdweb-dev-service-utils-cf-worker.cjs.js +0 -7
- package/cf-worker/dist/thirdweb-dev-service-utils-cf-worker.cjs.prod.js +0 -272
- package/cf-worker/dist/thirdweb-dev-service-utils-cf-worker.esm.js +0 -258
- package/cf-worker/package.json +0 -4
- package/dist/declarations/src/cf-worker/index.d.ts.map +0 -1
- package/dist/declarations/src/cf-worker/usage.d.ts.map +0 -1
- package/dist/declarations/src/core/api.d.ts +0 -84
- package/dist/declarations/src/core/api.d.ts.map +0 -1
- package/dist/declarations/src/core/authorize/client.d.ts +0 -9
- package/dist/declarations/src/core/authorize/client.d.ts.map +0 -1
- package/dist/declarations/src/core/authorize/index.d.ts.map +0 -1
- package/dist/declarations/src/core/authorize/service.d.ts +0 -7
- package/dist/declarations/src/core/authorize/service.d.ts.map +0 -1
- package/dist/declarations/src/core/authorize/types.d.ts +0 -12
- package/dist/declarations/src/core/authorize/types.d.ts.map +0 -1
- package/dist/declarations/src/core/rateLimit/index.d.ts.map +0 -1
- package/dist/declarations/src/core/rateLimit/types.d.ts.map +0 -1
- package/dist/declarations/src/core/services.d.ts.map +0 -1
- package/dist/declarations/src/core/types.d.ts.map +0 -1
- package/dist/declarations/src/core/usageLimit/index.d.ts +0 -5
- package/dist/declarations/src/core/usageLimit/index.d.ts.map +0 -1
- package/dist/declarations/src/core/usageLimit/types.d.ts +0 -9
- package/dist/declarations/src/core/usageLimit/types.d.ts.map +0 -1
- package/dist/declarations/src/index.d.ts +0 -2
- package/dist/declarations/src/index.d.ts.map +0 -1
- package/dist/declarations/src/node/index.d.ts.map +0 -1
- package/dist/index-3b9a0743.esm.js +0 -572
- package/dist/index-62b88cac.cjs.dev.js +0 -576
- package/dist/index-aa324361.cjs.prod.js +0 -576
- package/dist/services-2aecbda8.esm.js +0 -65
- package/dist/services-508322f3.cjs.dev.js +0 -70
- package/dist/services-5c4d6977.cjs.prod.js +0 -70
- package/dist/thirdweb-dev-service-utils.cjs.d.ts +0 -2
- package/dist/thirdweb-dev-service-utils.cjs.d.ts.map +0 -1
- package/dist/thirdweb-dev-service-utils.cjs.dev.js +0 -12
- package/dist/thirdweb-dev-service-utils.cjs.js +0 -7
- package/dist/thirdweb-dev-service-utils.cjs.prod.js +0 -12
- package/dist/thirdweb-dev-service-utils.esm.js +0 -1
- package/node/dist/thirdweb-dev-service-utils-node.cjs.d.ts +0 -2
- package/node/dist/thirdweb-dev-service-utils-node.cjs.d.ts.map +0 -1
- package/node/dist/thirdweb-dev-service-utils-node.cjs.dev.js +0 -193
- package/node/dist/thirdweb-dev-service-utils-node.cjs.js +0 -7
- package/node/dist/thirdweb-dev-service-utils-node.cjs.prod.js +0 -193
- package/node/dist/thirdweb-dev-service-utils-node.esm.js +0 -180
- package/node/package.json +0 -4
- /package/dist/{declarations/src → types}/core/rateLimit/types.d.ts +0 -0
- /package/dist/{declarations/src → types}/core/types.d.ts +0 -0
@@ -1,572 +0,0 @@
|
|
1
|
-
async function fetchKeyMetadataFromApi(clientId, config) {
|
2
|
-
const {
|
3
|
-
apiUrl,
|
4
|
-
serviceScope,
|
5
|
-
serviceApiKey,
|
6
|
-
checkPolicy,
|
7
|
-
policyMetadata
|
8
|
-
} = config;
|
9
|
-
const policyQuery = checkPolicy && policyMetadata ? `&checkPolicy=true&policyMetadata=${encodeURIComponent(JSON.stringify(policyMetadata))}` : "";
|
10
|
-
const url = `${apiUrl}/v1/keys/use?clientId=${clientId}&scope=${serviceScope}&includeUsage=true${policyQuery}`;
|
11
|
-
const response = await fetch(url, {
|
12
|
-
method: "GET",
|
13
|
-
headers: {
|
14
|
-
"x-service-api-key": serviceApiKey,
|
15
|
-
"content-type": "application/json"
|
16
|
-
}
|
17
|
-
});
|
18
|
-
let text = "";
|
19
|
-
try {
|
20
|
-
text = await response.text();
|
21
|
-
return JSON.parse(text);
|
22
|
-
} catch (e) {
|
23
|
-
throw new Error(`Error fetching key metadata from API: ${response.status} - ${text}`);
|
24
|
-
}
|
25
|
-
}
|
26
|
-
async function fetchAccountFromApi(jwt, config, useWalletAuth) {
|
27
|
-
const {
|
28
|
-
apiUrl,
|
29
|
-
serviceApiKey
|
30
|
-
} = config;
|
31
|
-
const url = useWalletAuth ? `${apiUrl}/v1/wallet/me?includeUsage=true` : `${apiUrl}/v1/account/me?includeUsage=true`;
|
32
|
-
const response = await fetch(url, {
|
33
|
-
method: "GET",
|
34
|
-
headers: {
|
35
|
-
"x-service-api-key": serviceApiKey,
|
36
|
-
"content-type": "application/json",
|
37
|
-
authorization: `Bearer ${jwt}`
|
38
|
-
}
|
39
|
-
});
|
40
|
-
let text = "";
|
41
|
-
try {
|
42
|
-
text = await response.text();
|
43
|
-
return JSON.parse(text);
|
44
|
-
} catch (e) {
|
45
|
-
throw new Error(`Error fetching account from API: ${response.status} - ${text}`);
|
46
|
-
}
|
47
|
-
}
|
48
|
-
async function updateRateLimitedAt(apiKeyId, config) {
|
49
|
-
const {
|
50
|
-
apiUrl,
|
51
|
-
serviceScope: scope,
|
52
|
-
serviceApiKey
|
53
|
-
} = config;
|
54
|
-
const url = `${apiUrl}/usage/rateLimit`;
|
55
|
-
await fetch(url, {
|
56
|
-
method: "PUT",
|
57
|
-
headers: {
|
58
|
-
"x-service-api-key": serviceApiKey,
|
59
|
-
"content-type": "application/json"
|
60
|
-
},
|
61
|
-
body: JSON.stringify({
|
62
|
-
apiKeyId,
|
63
|
-
scope
|
64
|
-
})
|
65
|
-
});
|
66
|
-
}
|
67
|
-
|
68
|
-
function authorizeClient(authOptions, apiKeyMeta) {
|
69
|
-
const {
|
70
|
-
origin,
|
71
|
-
bundleId,
|
72
|
-
secretKeyHash: providedSecretHash
|
73
|
-
} = authOptions;
|
74
|
-
const {
|
75
|
-
domains,
|
76
|
-
bundleIds,
|
77
|
-
secretHash
|
78
|
-
} = apiKeyMeta;
|
79
|
-
const authResult = {
|
80
|
-
authorized: true,
|
81
|
-
apiKeyMeta,
|
82
|
-
accountMeta: {
|
83
|
-
id: apiKeyMeta.accountId,
|
84
|
-
// TODO update this later
|
85
|
-
name: "",
|
86
|
-
creatorWalletAddress: apiKeyMeta.creatorWalletAddress,
|
87
|
-
limits: apiKeyMeta.limits,
|
88
|
-
rateLimits: apiKeyMeta.rateLimits,
|
89
|
-
usage: apiKeyMeta.usage
|
90
|
-
}
|
91
|
-
};
|
92
|
-
|
93
|
-
// check for public restrictions
|
94
|
-
if (domains.includes("*")) {
|
95
|
-
return authResult;
|
96
|
-
}
|
97
|
-
|
98
|
-
// check for secretHash
|
99
|
-
if (providedSecretHash) {
|
100
|
-
if (secretHash !== providedSecretHash) {
|
101
|
-
return {
|
102
|
-
authorized: false,
|
103
|
-
errorMessage: "Incorrect key provided. You can view your active API keys at https://thirdweb.com/dashboard/settings",
|
104
|
-
errorCode: "SECRET_INVALID",
|
105
|
-
status: 401
|
106
|
-
};
|
107
|
-
}
|
108
|
-
return authResult;
|
109
|
-
}
|
110
|
-
|
111
|
-
// validate domains
|
112
|
-
if (origin) {
|
113
|
-
if (
|
114
|
-
// find matching domain, or if all domains allowed
|
115
|
-
domains.find(d => {
|
116
|
-
// if any domain is allowed, we'll return true
|
117
|
-
if (d === "*") {
|
118
|
-
return true;
|
119
|
-
}
|
120
|
-
|
121
|
-
// special rule for `localhost`
|
122
|
-
// if the domain is localhost, we'll allow any origin that starts with localhost
|
123
|
-
if (d === "localhost" && origin.startsWith("localhost")) {
|
124
|
-
return true;
|
125
|
-
}
|
126
|
-
|
127
|
-
// If the allowedDomain has a wildcard,
|
128
|
-
// we'll check that the ending of our domain matches the wildcard
|
129
|
-
if (d.startsWith("*.")) {
|
130
|
-
// get rid of the * and check if it ends with the `.<domain>.<tld>`
|
131
|
-
const domainRoot = d.slice(1);
|
132
|
-
return origin.endsWith(domainRoot);
|
133
|
-
}
|
134
|
-
|
135
|
-
// If there's no wildcard, we'll check for an exact match
|
136
|
-
return d === origin;
|
137
|
-
})) {
|
138
|
-
return authResult;
|
139
|
-
}
|
140
|
-
return {
|
141
|
-
authorized: false,
|
142
|
-
errorMessage: `Invalid request: Unauthorized domain: ${origin}. You can view the restrictions on this API key at https://thirdweb.com/create-api-key`,
|
143
|
-
errorCode: "ORIGIN_UNAUTHORIZED",
|
144
|
-
status: 401
|
145
|
-
};
|
146
|
-
}
|
147
|
-
|
148
|
-
// validate bundleId
|
149
|
-
if (bundleId) {
|
150
|
-
if (
|
151
|
-
// find matching bundle id, or if all bundles allowed
|
152
|
-
bundleIds.find(b => {
|
153
|
-
if (b === "*") {
|
154
|
-
return true;
|
155
|
-
}
|
156
|
-
return b === bundleId;
|
157
|
-
})) {
|
158
|
-
return authResult;
|
159
|
-
}
|
160
|
-
return {
|
161
|
-
authorized: false,
|
162
|
-
errorMessage: `Invalid request: Unauthorized Bundle ID: ${bundleId}. You can view the restrictions on this API key at https://thirdweb.com/create-api-key`,
|
163
|
-
errorCode: "BUNDLE_UNAUTHORIZED",
|
164
|
-
status: 401
|
165
|
-
};
|
166
|
-
}
|
167
|
-
return {
|
168
|
-
authorized: false,
|
169
|
-
errorMessage: "The keys are invalid. Please check the secret-key/clientId and try again.",
|
170
|
-
errorCode: "UNAUTHORIZED",
|
171
|
-
status: 401
|
172
|
-
};
|
173
|
-
}
|
174
|
-
|
175
|
-
function authorizeService(apiKeyMetadata, serviceConfig, authorizationPayload) {
|
176
|
-
const {
|
177
|
-
services
|
178
|
-
} = apiKeyMetadata;
|
179
|
-
// validate services
|
180
|
-
const service = services.find(srv => srv.name === serviceConfig.serviceScope);
|
181
|
-
if (!service) {
|
182
|
-
return {
|
183
|
-
authorized: false,
|
184
|
-
errorMessage: `Invalid request: Unauthorized service: ${serviceConfig.serviceScope}. You can view the restrictions on this API key in your dashboard: https://thirdweb.com/create-api-key`,
|
185
|
-
errorCode: "SERVICE_UNAUTHORIZED",
|
186
|
-
status: 403
|
187
|
-
};
|
188
|
-
}
|
189
|
-
|
190
|
-
// validate service actions
|
191
|
-
if (serviceConfig.serviceAction) {
|
192
|
-
const isActionAllowed = service.actions.includes(serviceConfig.serviceAction);
|
193
|
-
if (!isActionAllowed) {
|
194
|
-
return {
|
195
|
-
authorized: false,
|
196
|
-
errorMessage: `Invalid request: Unauthorized action: ${serviceConfig.serviceScope} ${serviceConfig.serviceAction}. You can view the restrictions on this API key in your dashboard: https://thirdweb.com/create-api-key`,
|
197
|
-
errorCode: "SERVICE_ACTION_UNAUTHORIZED",
|
198
|
-
status: 403
|
199
|
-
};
|
200
|
-
}
|
201
|
-
}
|
202
|
-
|
203
|
-
// validate service target addresses
|
204
|
-
// the service has to pass in the target address for this to be validated
|
205
|
-
if (authorizationPayload?.targetAddress) {
|
206
|
-
const checkedAddresses = Array.isArray(authorizationPayload.targetAddress) ? authorizationPayload.targetAddress : [authorizationPayload.targetAddress];
|
207
|
-
const allAllowed = service.targetAddresses.includes("*");
|
208
|
-
if (!allAllowed && checkedAddresses.some(ta => !service.targetAddresses.includes(ta))) {
|
209
|
-
return {
|
210
|
-
authorized: false,
|
211
|
-
errorMessage: `Invalid request: Unauthorized address: ${serviceConfig.serviceScope} ${checkedAddresses}. You can view the restrictions on this API key in your dashboard: https://thirdweb.com/create-api-key`,
|
212
|
-
errorCode: "SERVICE_TARGET_ADDRESS_UNAUTHORIZED",
|
213
|
-
status: 403
|
214
|
-
};
|
215
|
-
}
|
216
|
-
}
|
217
|
-
return {
|
218
|
-
authorized: true,
|
219
|
-
apiKeyMeta: apiKeyMetadata,
|
220
|
-
accountMeta: {
|
221
|
-
id: apiKeyMetadata.accountId,
|
222
|
-
name: "",
|
223
|
-
creatorWalletAddress: apiKeyMetadata.creatorWalletAddress,
|
224
|
-
limits: apiKeyMetadata.limits,
|
225
|
-
rateLimits: apiKeyMetadata.rateLimits,
|
226
|
-
usage: apiKeyMetadata.usage
|
227
|
-
}
|
228
|
-
};
|
229
|
-
}
|
230
|
-
|
231
|
-
async function authorize(authData, serviceConfig, cacheOptions) {
|
232
|
-
const {
|
233
|
-
clientId,
|
234
|
-
targetAddress,
|
235
|
-
secretKeyHash,
|
236
|
-
jwt,
|
237
|
-
hashedJWT,
|
238
|
-
useWalletAuth
|
239
|
-
} = authData;
|
240
|
-
const {
|
241
|
-
enforceAuth
|
242
|
-
} = serviceConfig;
|
243
|
-
|
244
|
-
// BACKWARDS COMPAT: if auth not enforced and we don't have auth credentials bypass
|
245
|
-
if (!enforceAuth && !clientId && !secretKeyHash) {
|
246
|
-
return {
|
247
|
-
authorized: true,
|
248
|
-
apiKeyMeta: null,
|
249
|
-
accountMeta: null
|
250
|
-
};
|
251
|
-
}
|
252
|
-
// if we come in with a JWT then we only check the account is valid
|
253
|
-
if (jwt && hashedJWT) {
|
254
|
-
let accountMeta = null;
|
255
|
-
if (cacheOptions) {
|
256
|
-
try {
|
257
|
-
const cachedAccountInfo = await cacheOptions.get(hashedJWT);
|
258
|
-
if (cachedAccountInfo) {
|
259
|
-
const parsed = JSON.parse(cachedAccountInfo);
|
260
|
-
if ("updatedAt" in parsed) {
|
261
|
-
// we want to compare the updatedAt time to the current time
|
262
|
-
// if the difference is greater than the cacheTtl we want to ignore the cached data
|
263
|
-
const now = Date.now();
|
264
|
-
const diff = now - parsed.updatedAt;
|
265
|
-
const cacheTtlMs = cacheOptions.cacheTtlSeconds * 1000;
|
266
|
-
// only if the diff is less than the cacheTtl do we want to use the cached key
|
267
|
-
if (diff < cacheTtlMs) {
|
268
|
-
accountMeta = parsed.apiKeyMeta;
|
269
|
-
}
|
270
|
-
} else {
|
271
|
-
accountMeta = parsed;
|
272
|
-
}
|
273
|
-
}
|
274
|
-
} catch (err) {
|
275
|
-
// ignore errors, proceed as if not in cache
|
276
|
-
}
|
277
|
-
}
|
278
|
-
if (!accountMeta) {
|
279
|
-
try {
|
280
|
-
const {
|
281
|
-
data,
|
282
|
-
error
|
283
|
-
} = await fetchAccountFromApi(jwt, serviceConfig, useWalletAuth?.toLowerCase() === "true");
|
284
|
-
if (error) {
|
285
|
-
return {
|
286
|
-
authorized: false,
|
287
|
-
errorCode: error.code,
|
288
|
-
errorMessage: error.message,
|
289
|
-
status: error.statusCode
|
290
|
-
};
|
291
|
-
} else if (!data) {
|
292
|
-
return {
|
293
|
-
authorized: false,
|
294
|
-
errorCode: "NO_ACCOUNT",
|
295
|
-
errorMessage: "No error but also no account returned.",
|
296
|
-
status: 500
|
297
|
-
};
|
298
|
-
}
|
299
|
-
accountMeta = data;
|
300
|
-
if (cacheOptions) {
|
301
|
-
await cacheOptions.put(hashedJWT, accountMeta);
|
302
|
-
}
|
303
|
-
} catch (err) {
|
304
|
-
console.warn("failed to fetch account from api", err);
|
305
|
-
return {
|
306
|
-
authorized: false,
|
307
|
-
status: 500,
|
308
|
-
errorMessage: "Failed to get account information.",
|
309
|
-
errorCode: "FAILED_TO_LOAD_ACCOUNT"
|
310
|
-
};
|
311
|
-
}
|
312
|
-
}
|
313
|
-
// if we still don't have an accountMeta at this point we can't authorize
|
314
|
-
if (!accountMeta) {
|
315
|
-
return {
|
316
|
-
authorized: false,
|
317
|
-
status: 401,
|
318
|
-
errorMessage: "Missing account information.",
|
319
|
-
errorCode: "MISSING_ACCOUNT"
|
320
|
-
};
|
321
|
-
}
|
322
|
-
// otherwise we want to return early with the accountMeta
|
323
|
-
return {
|
324
|
-
authorized: true,
|
325
|
-
apiKeyMeta: null,
|
326
|
-
accountMeta
|
327
|
-
};
|
328
|
-
}
|
329
|
-
|
330
|
-
// if we don't have a client id at this point we can't authorize
|
331
|
-
if (!clientId) {
|
332
|
-
return {
|
333
|
-
authorized: false,
|
334
|
-
status: 401,
|
335
|
-
errorMessage: "Missing clientId or secretKey.",
|
336
|
-
errorCode: "MISSING_KEY"
|
337
|
-
};
|
338
|
-
}
|
339
|
-
let apiKeyMeta = null;
|
340
|
-
// if we have cache options we want to check the cache first
|
341
|
-
if (cacheOptions) {
|
342
|
-
try {
|
343
|
-
const cachedKey = await cacheOptions.get(clientId);
|
344
|
-
if (cachedKey) {
|
345
|
-
const parsed = JSON.parse(cachedKey);
|
346
|
-
if ("updatedAt" in parsed) {
|
347
|
-
// we want to compare the updatedAt time to the current time
|
348
|
-
// if the difference is greater than the cacheTtl we want to ignore the cached data
|
349
|
-
const now = Date.now();
|
350
|
-
const diff = now - parsed.updatedAt;
|
351
|
-
const cacheTtlMs = cacheOptions.cacheTtlSeconds * 1000;
|
352
|
-
// only if the diff is less than the cacheTtl do we want to use the cached key
|
353
|
-
if (diff < cacheTtlMs) {
|
354
|
-
apiKeyMeta = parsed.apiKeyMeta;
|
355
|
-
}
|
356
|
-
} else {
|
357
|
-
apiKeyMeta = parsed;
|
358
|
-
}
|
359
|
-
}
|
360
|
-
} catch (err) {
|
361
|
-
// ignore errors, proceed as if not in cache
|
362
|
-
}
|
363
|
-
}
|
364
|
-
|
365
|
-
// if we don't have a cached key, fetch from the API
|
366
|
-
if (!apiKeyMeta) {
|
367
|
-
try {
|
368
|
-
const {
|
369
|
-
data,
|
370
|
-
error
|
371
|
-
} = await fetchKeyMetadataFromApi(clientId, serviceConfig);
|
372
|
-
if (error) {
|
373
|
-
return {
|
374
|
-
authorized: false,
|
375
|
-
errorCode: error.code,
|
376
|
-
errorMessage: error.message,
|
377
|
-
status: error.statusCode
|
378
|
-
};
|
379
|
-
} else if (!data) {
|
380
|
-
return {
|
381
|
-
authorized: false,
|
382
|
-
errorCode: "NO_KEY",
|
383
|
-
errorMessage: "No error but also no key returned.",
|
384
|
-
status: 500
|
385
|
-
};
|
386
|
-
}
|
387
|
-
// if we have a key for sure then assign it
|
388
|
-
apiKeyMeta = data;
|
389
|
-
|
390
|
-
// cache the retrieved key if we have cache options
|
391
|
-
if (cacheOptions) {
|
392
|
-
// we await this always because it can be a promise or not
|
393
|
-
await cacheOptions.put(clientId, data);
|
394
|
-
}
|
395
|
-
} catch (err) {
|
396
|
-
console.warn("failed to fetch key metadata from api", err);
|
397
|
-
return {
|
398
|
-
authorized: false,
|
399
|
-
status: 500,
|
400
|
-
errorMessage: "Failed to fetch key metadata. Please check your secret-key/clientId.",
|
401
|
-
errorCode: "FAILED_TO_FETCH_KEY"
|
402
|
-
};
|
403
|
-
}
|
404
|
-
}
|
405
|
-
if (!apiKeyMeta) {
|
406
|
-
return {
|
407
|
-
authorized: false,
|
408
|
-
status: 401,
|
409
|
-
errorMessage: "Key is invalid. Please check your secret-key/clientId.",
|
410
|
-
errorCode: "INVALID_KEY"
|
411
|
-
};
|
412
|
-
}
|
413
|
-
// now we can validate the key itself
|
414
|
-
const clientAuth = authorizeClient(authData, apiKeyMeta);
|
415
|
-
if (!clientAuth.authorized) {
|
416
|
-
return {
|
417
|
-
errorCode: clientAuth.errorCode,
|
418
|
-
authorized: false,
|
419
|
-
status: 401,
|
420
|
-
errorMessage: clientAuth.errorMessage
|
421
|
-
};
|
422
|
-
}
|
423
|
-
|
424
|
-
// if we've made it this far we need to check service specific authorization
|
425
|
-
const serviceAuth = authorizeService(apiKeyMeta, serviceConfig, {
|
426
|
-
targetAddress
|
427
|
-
});
|
428
|
-
if (!serviceAuth.authorized) {
|
429
|
-
return {
|
430
|
-
errorCode: serviceAuth.errorCode,
|
431
|
-
authorized: false,
|
432
|
-
status: 403,
|
433
|
-
errorMessage: serviceAuth.errorMessage
|
434
|
-
};
|
435
|
-
}
|
436
|
-
|
437
|
-
// if we reach this point we are authorized!
|
438
|
-
return {
|
439
|
-
authorized: true,
|
440
|
-
apiKeyMeta,
|
441
|
-
accountMeta: {
|
442
|
-
id: apiKeyMeta.accountId,
|
443
|
-
// TODO update this later
|
444
|
-
name: "",
|
445
|
-
limits: apiKeyMeta.limits,
|
446
|
-
rateLimits: apiKeyMeta.rateLimits,
|
447
|
-
usage: apiKeyMeta.usage,
|
448
|
-
creatorWalletAddress: apiKeyMeta.creatorWalletAddress
|
449
|
-
}
|
450
|
-
};
|
451
|
-
}
|
452
|
-
|
453
|
-
const RATE_LIMIT_WINDOW_SECONDS = 10;
|
454
|
-
|
455
|
-
// Redis interface compatible with ioredis (Node) and upstash (Cloudflare Workers).
|
456
|
-
|
457
|
-
async function rateLimit(args) {
|
458
|
-
const {
|
459
|
-
authzResult,
|
460
|
-
serviceConfig,
|
461
|
-
redis,
|
462
|
-
sampleRate = 1.0
|
463
|
-
} = args;
|
464
|
-
const shouldSampleRequest = Math.random() < sampleRate;
|
465
|
-
if (!shouldSampleRequest || !authzResult.authorized) {
|
466
|
-
return {
|
467
|
-
rateLimited: false,
|
468
|
-
requestCount: 0,
|
469
|
-
rateLimit: 0
|
470
|
-
};
|
471
|
-
}
|
472
|
-
const {
|
473
|
-
apiKeyMeta,
|
474
|
-
accountMeta
|
475
|
-
} = authzResult;
|
476
|
-
const accountId = apiKeyMeta?.accountId || accountMeta?.id;
|
477
|
-
const {
|
478
|
-
serviceScope
|
479
|
-
} = serviceConfig;
|
480
|
-
const limitPerSecond = apiKeyMeta?.rateLimits?.[serviceScope] ?? accountMeta?.rateLimits?.[serviceScope];
|
481
|
-
if (!limitPerSecond) {
|
482
|
-
// No rate limit is provided. Assume the request is not rate limited.
|
483
|
-
return {
|
484
|
-
rateLimited: false,
|
485
|
-
requestCount: 0,
|
486
|
-
rateLimit: 0
|
487
|
-
};
|
488
|
-
}
|
489
|
-
|
490
|
-
// Gets the 10-second window for the current timestamp.
|
491
|
-
const timestampWindow = Math.floor(Date.now() / (1000 * RATE_LIMIT_WINDOW_SECONDS)) * RATE_LIMIT_WINDOW_SECONDS;
|
492
|
-
const key = `rate-limit:${serviceScope}:${accountId}:${timestampWindow}`;
|
493
|
-
|
494
|
-
// Increment and get the current request count in this window.
|
495
|
-
const requestCount = await redis.incr(key);
|
496
|
-
if (requestCount === 1) {
|
497
|
-
// For the first increment, set an expiration to clean up this key.
|
498
|
-
await redis.expire(key, RATE_LIMIT_WINDOW_SECONDS);
|
499
|
-
}
|
500
|
-
|
501
|
-
// Get the limit for this window accounting for the sample rate.
|
502
|
-
const limitPerWindow = limitPerSecond * sampleRate * RATE_LIMIT_WINDOW_SECONDS;
|
503
|
-
if (requestCount > limitPerWindow) {
|
504
|
-
// Report rate limit hits.
|
505
|
-
if (apiKeyMeta?.id) {
|
506
|
-
await updateRateLimitedAt(apiKeyMeta.id, serviceConfig);
|
507
|
-
}
|
508
|
-
|
509
|
-
// Reject requests when they've exceeded 2x the rate limit.
|
510
|
-
if (requestCount > 2 * limitPerWindow) {
|
511
|
-
return {
|
512
|
-
rateLimited: true,
|
513
|
-
requestCount,
|
514
|
-
rateLimit: limitPerWindow,
|
515
|
-
status: 429,
|
516
|
-
errorMessage: `You've exceeded your ${serviceScope} rate limit at ${limitPerSecond} reqs/sec. To get higher rate limits, contact us at https://thirdweb.com/contact-us.`,
|
517
|
-
errorCode: "RATE_LIMIT_EXCEEDED"
|
518
|
-
};
|
519
|
-
}
|
520
|
-
}
|
521
|
-
return {
|
522
|
-
rateLimited: false,
|
523
|
-
requestCount,
|
524
|
-
rateLimit: limitPerWindow
|
525
|
-
};
|
526
|
-
}
|
527
|
-
|
528
|
-
async function usageLimit(authzResult, serviceConfig) {
|
529
|
-
if (!authzResult.authorized) {
|
530
|
-
return {
|
531
|
-
usageLimited: false
|
532
|
-
};
|
533
|
-
}
|
534
|
-
const {
|
535
|
-
apiKeyMeta,
|
536
|
-
accountMeta
|
537
|
-
} = authzResult;
|
538
|
-
const {
|
539
|
-
limits,
|
540
|
-
usage
|
541
|
-
} = apiKeyMeta || accountMeta || {};
|
542
|
-
const {
|
543
|
-
serviceScope
|
544
|
-
} = serviceConfig;
|
545
|
-
if (!usage || !(serviceScope in usage) || !limits || !(serviceScope in limits)) {
|
546
|
-
// No usage limit is provided. Assume the request is not limited.
|
547
|
-
return {
|
548
|
-
usageLimited: false
|
549
|
-
};
|
550
|
-
}
|
551
|
-
if (serviceScope === "storage" && (usage.storage?.sumFileSizeBytes ?? 0) > (limits.storage ?? 0)) {
|
552
|
-
return {
|
553
|
-
usageLimited: true,
|
554
|
-
status: 403,
|
555
|
-
errorMessage: `You've used all of your total usage credits for Storage Pinning. Please add your payment method at https://thirdweb.com/dashboard/settings/billing.`,
|
556
|
-
errorCode: "PAYMENT_METHOD_REQUIRED"
|
557
|
-
};
|
558
|
-
}
|
559
|
-
if (serviceScope === "embeddedWallets" && (usage.embeddedWallets?.countWalletAddresses ?? 0) > (limits.embeddedWallets ?? 0)) {
|
560
|
-
return {
|
561
|
-
usageLimited: true,
|
562
|
-
status: 403,
|
563
|
-
errorMessage: `You've used all of your total usage credits for Embedded Wallets. Please add your payment method at https://thirdweb.com/dashboard/settings/billing.`,
|
564
|
-
errorCode: "PAYMENT_METHOD_REQUIRED"
|
565
|
-
};
|
566
|
-
}
|
567
|
-
return {
|
568
|
-
usageLimited: false
|
569
|
-
};
|
570
|
-
}
|
571
|
-
|
572
|
-
export { authorize as a, rateLimit as r, usageLimit as u };
|