@thirdweb-dev/service-utils 0.5.0-nightly-6cf298a29-20240308012322 → 0.5.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 (142) hide show
  1. package/dist/cjs/cf-worker/index.js +152 -0
  2. package/dist/cjs/cf-worker/index.js.map +1 -0
  3. package/dist/cjs/cf-worker/usage.js +55 -0
  4. package/dist/cjs/cf-worker/usage.js.map +1 -0
  5. package/dist/cjs/core/api.js +42 -0
  6. package/dist/cjs/core/api.js.map +1 -0
  7. package/dist/cjs/core/authorize/client.js +104 -0
  8. package/dist/cjs/core/authorize/client.js.map +1 -0
  9. package/dist/cjs/core/authorize/index.js +110 -0
  10. package/dist/cjs/core/authorize/index.js.map +1 -0
  11. package/dist/cjs/core/authorize/service.js +60 -0
  12. package/dist/cjs/core/authorize/service.js.map +1 -0
  13. package/dist/cjs/core/authorize/types.js +3 -0
  14. package/dist/cjs/core/authorize/types.js.map +1 -0
  15. package/dist/cjs/core/rateLimit/index.js +60 -0
  16. package/dist/cjs/core/rateLimit/index.js.map +1 -0
  17. package/dist/cjs/core/rateLimit/types.js +3 -0
  18. package/dist/cjs/core/rateLimit/types.js.map +1 -0
  19. package/dist/cjs/core/services.js +85 -0
  20. package/dist/cjs/core/services.js.map +1 -0
  21. package/dist/cjs/core/types.js +3 -0
  22. package/dist/cjs/core/types.js.map +1 -0
  23. package/dist/cjs/core/usage.js +85 -0
  24. package/dist/cjs/core/usage.js.map +1 -0
  25. package/dist/cjs/index.js +13 -0
  26. package/dist/cjs/index.js.map +1 -0
  27. package/dist/cjs/mocks.js +61 -0
  28. package/dist/cjs/mocks.js.map +1 -0
  29. package/dist/cjs/node/index.js +156 -0
  30. package/dist/cjs/node/index.js.map +1 -0
  31. package/dist/cjs/package.json +1 -0
  32. package/dist/esm/cf-worker/index.js +145 -0
  33. package/dist/esm/cf-worker/index.js.map +1 -0
  34. package/dist/esm/cf-worker/usage.js +53 -0
  35. package/dist/esm/cf-worker/usage.js.map +1 -0
  36. package/dist/esm/core/api.js +38 -0
  37. package/dist/esm/core/api.js.map +1 -0
  38. package/dist/esm/core/authorize/client.js +99 -0
  39. package/dist/esm/core/authorize/client.js.map +1 -0
  40. package/dist/esm/core/authorize/index.js +107 -0
  41. package/dist/esm/core/authorize/index.js.map +1 -0
  42. package/dist/esm/core/authorize/service.js +57 -0
  43. package/dist/esm/core/authorize/service.js.map +1 -0
  44. package/dist/esm/core/authorize/types.js +2 -0
  45. package/dist/esm/core/authorize/types.js.map +1 -0
  46. package/dist/esm/core/rateLimit/index.js +57 -0
  47. package/dist/esm/core/rateLimit/index.js.map +1 -0
  48. package/dist/esm/core/rateLimit/types.js +2 -0
  49. package/dist/esm/core/rateLimit/types.js.map +1 -0
  50. package/dist/esm/core/services.js +81 -0
  51. package/dist/esm/core/services.js.map +1 -0
  52. package/dist/esm/core/types.js +2 -0
  53. package/dist/esm/core/types.js.map +1 -0
  54. package/dist/esm/core/usage.js +82 -0
  55. package/dist/esm/core/usage.js.map +1 -0
  56. package/dist/esm/index.js +5 -0
  57. package/dist/esm/index.js.map +1 -0
  58. package/dist/esm/mocks.js +58 -0
  59. package/dist/esm/mocks.js.map +1 -0
  60. package/dist/esm/node/index.js +149 -0
  61. package/dist/esm/node/index.js.map +1 -0
  62. package/dist/esm/package.json +1 -0
  63. package/dist/{declarations/src → types}/cf-worker/index.d.ts +8 -10
  64. package/dist/types/cf-worker/index.d.ts.map +1 -0
  65. package/dist/types/cf-worker/usage.d.ts +24 -0
  66. package/dist/types/cf-worker/usage.d.ts.map +1 -0
  67. package/dist/types/core/api.d.ts +121 -0
  68. package/dist/types/core/api.d.ts.map +1 -0
  69. package/dist/types/core/authorize/client.d.ts +17 -0
  70. package/dist/types/core/authorize/client.d.ts.map +1 -0
  71. package/dist/{declarations/src → types}/core/authorize/index.d.ts +6 -5
  72. package/dist/types/core/authorize/index.d.ts.map +1 -0
  73. package/dist/types/core/authorize/service.d.ts +4 -0
  74. package/dist/types/core/authorize/service.d.ts.map +1 -0
  75. package/dist/types/core/authorize/types.d.ts +10 -0
  76. package/dist/types/core/authorize/types.d.ts.map +1 -0
  77. package/dist/{declarations/src → types}/core/rateLimit/index.d.ts +4 -4
  78. package/dist/types/core/rateLimit/index.d.ts.map +1 -0
  79. package/dist/types/core/rateLimit/types.d.ts.map +1 -0
  80. package/dist/{declarations/src → types}/core/services.d.ts +55 -23
  81. package/dist/types/core/services.d.ts.map +1 -0
  82. package/dist/types/core/types.d.ts.map +1 -0
  83. package/dist/{declarations/src/cf-worker → types/core}/usage.d.ts +84 -30
  84. package/dist/types/core/usage.d.ts.map +1 -0
  85. package/dist/types/index.d.ts +5 -0
  86. package/dist/types/index.d.ts.map +1 -0
  87. package/dist/types/mocks.d.ts +7 -0
  88. package/dist/types/mocks.d.ts.map +1 -0
  89. package/dist/types/node/index.d.ts +23 -0
  90. package/dist/types/node/index.d.ts.map +1 -0
  91. package/package.json +42 -45
  92. package/cf-worker/dist/thirdweb-dev-service-utils-cf-worker.cjs.d.ts +0 -2
  93. package/cf-worker/dist/thirdweb-dev-service-utils-cf-worker.cjs.d.ts.map +0 -1
  94. package/cf-worker/dist/thirdweb-dev-service-utils-cf-worker.cjs.dev.js +0 -272
  95. package/cf-worker/dist/thirdweb-dev-service-utils-cf-worker.cjs.js +0 -7
  96. package/cf-worker/dist/thirdweb-dev-service-utils-cf-worker.cjs.prod.js +0 -272
  97. package/cf-worker/dist/thirdweb-dev-service-utils-cf-worker.esm.js +0 -258
  98. package/cf-worker/package.json +0 -4
  99. package/dist/declarations/src/cf-worker/index.d.ts.map +0 -1
  100. package/dist/declarations/src/cf-worker/usage.d.ts.map +0 -1
  101. package/dist/declarations/src/core/api.d.ts +0 -84
  102. package/dist/declarations/src/core/api.d.ts.map +0 -1
  103. package/dist/declarations/src/core/authorize/client.d.ts +0 -9
  104. package/dist/declarations/src/core/authorize/client.d.ts.map +0 -1
  105. package/dist/declarations/src/core/authorize/index.d.ts.map +0 -1
  106. package/dist/declarations/src/core/authorize/service.d.ts +0 -7
  107. package/dist/declarations/src/core/authorize/service.d.ts.map +0 -1
  108. package/dist/declarations/src/core/authorize/types.d.ts +0 -12
  109. package/dist/declarations/src/core/authorize/types.d.ts.map +0 -1
  110. package/dist/declarations/src/core/rateLimit/index.d.ts.map +0 -1
  111. package/dist/declarations/src/core/rateLimit/types.d.ts.map +0 -1
  112. package/dist/declarations/src/core/services.d.ts.map +0 -1
  113. package/dist/declarations/src/core/types.d.ts.map +0 -1
  114. package/dist/declarations/src/core/usageLimit/index.d.ts +0 -5
  115. package/dist/declarations/src/core/usageLimit/index.d.ts.map +0 -1
  116. package/dist/declarations/src/core/usageLimit/types.d.ts +0 -9
  117. package/dist/declarations/src/core/usageLimit/types.d.ts.map +0 -1
  118. package/dist/declarations/src/index.d.ts +0 -2
  119. package/dist/declarations/src/index.d.ts.map +0 -1
  120. package/dist/declarations/src/node/index.d.ts +0 -43
  121. package/dist/declarations/src/node/index.d.ts.map +0 -1
  122. package/dist/index-3b9a0743.esm.js +0 -572
  123. package/dist/index-62b88cac.cjs.dev.js +0 -576
  124. package/dist/index-aa324361.cjs.prod.js +0 -576
  125. package/dist/services-2aecbda8.esm.js +0 -65
  126. package/dist/services-508322f3.cjs.dev.js +0 -70
  127. package/dist/services-5c4d6977.cjs.prod.js +0 -70
  128. package/dist/thirdweb-dev-service-utils.cjs.d.ts +0 -2
  129. package/dist/thirdweb-dev-service-utils.cjs.d.ts.map +0 -1
  130. package/dist/thirdweb-dev-service-utils.cjs.dev.js +0 -12
  131. package/dist/thirdweb-dev-service-utils.cjs.js +0 -7
  132. package/dist/thirdweb-dev-service-utils.cjs.prod.js +0 -12
  133. package/dist/thirdweb-dev-service-utils.esm.js +0 -1
  134. package/node/dist/thirdweb-dev-service-utils-node.cjs.d.ts +0 -2
  135. package/node/dist/thirdweb-dev-service-utils-node.cjs.d.ts.map +0 -1
  136. package/node/dist/thirdweb-dev-service-utils-node.cjs.dev.js +0 -193
  137. package/node/dist/thirdweb-dev-service-utils-node.cjs.js +0 -7
  138. package/node/dist/thirdweb-dev-service-utils-node.cjs.prod.js +0 -193
  139. package/node/dist/thirdweb-dev-service-utils-node.esm.js +0 -180
  140. package/node/package.json +0 -4
  141. /package/dist/{declarations/src → types}/core/rateLimit/types.d.ts +0 -0
  142. /package/dist/{declarations/src → types}/core/types.d.ts +0 -0
@@ -1,272 +0,0 @@
1
- 'use strict';
2
-
3
- Object.defineProperty(exports, '__esModule', { value: true });
4
-
5
- var index = require('../../dist/index-62b88cac.cjs.dev.js');
6
- var aws4fetch = require('aws4fetch');
7
- var zod = require('zod');
8
- var services = require('../../dist/services-508322f3.cjs.dev.js');
9
-
10
- // Initialize a singleton for aws usage.
11
- let _aws;
12
- function getAws(options) {
13
- if (!_aws) {
14
- _aws = new aws4fetch.AwsClient(options);
15
- }
16
- return _aws;
17
- }
18
-
19
- /**
20
- * Types
21
- */
22
- const usageEventSchema = zod.z.object({
23
- source: zod.z.enum(["embeddedWallets", "rpc", "storage", "bundler", "paymaster", "relayer", "connectWallet", "checkout", "engine"]),
24
- action: zod.z.string(),
25
- /**
26
- * The following fields are optional.
27
- */
28
-
29
- accountId: zod.z.string().optional(),
30
- isClientEvent: zod.z.boolean().optional(),
31
- apiKeyId: zod.z.string().optional(),
32
- creatorWalletAddress: zod.z.string().optional(),
33
- clientId: zod.z.string().optional(),
34
- walletAddress: zod.z.string().optional(),
35
- walletType: zod.z.string().optional(),
36
- chainId: zod.z.number().int().positive().optional(),
37
- provider: zod.z.string().optional(),
38
- mimeType: zod.z.string().optional(),
39
- fileSize: zod.z.number().int().nonnegative().optional(),
40
- fileCid: zod.z.string().optional(),
41
- evmMethod: zod.z.string().optional(),
42
- userOpHash: zod.z.string().optional(),
43
- gasLimit: zod.z.number().nonnegative().optional(),
44
- gasPricePerUnit: zod.z.string().optional(),
45
- transactionFeeUsd: zod.z.number().optional(),
46
- transactionHash: zod.z.string().optional(),
47
- sdkName: zod.z.string().optional(),
48
- sdkVersion: zod.z.string().optional(),
49
- sdkPlatform: zod.z.string().optional(),
50
- productName: zod.z.string().optional(),
51
- transactionValue: zod.z.string().optional(),
52
- pathname: zod.z.string().optional(),
53
- contractAddress: zod.z.string().optional(),
54
- errorCode: zod.z.string().optional(),
55
- httpStatusCode: zod.z.number().int().nonnegative().optional(),
56
- functionName: zod.z.string().optional(),
57
- extension: zod.z.string().optional(),
58
- retryCount: zod.z.number().int().nonnegative().optional(),
59
- policyId: zod.z.string().optional(),
60
- msSinceQueue: zod.z.number().nonnegative().optional(),
61
- msSinceSend: zod.z.number().nonnegative().optional(),
62
- msTotalDuration: zod.z.number().nonnegative().optional()
63
- });
64
- /**
65
- * Publish usage events. Provide the relevant fields for your application.
66
- *
67
- * Usage in Cloudflare Workers:
68
- * ctx.waitUntil(
69
- * publishUsageEvents(
70
- * [event1, event2],
71
- * { queueUrl, accessKeyId, secretAccessKey },
72
- * )
73
- * )
74
- *
75
- * @param usageEvents
76
- * @param config
77
- */
78
- async function publishUsageEvents(usageEvents, config) {
79
- const {
80
- queueUrl,
81
- accessKeyId,
82
- secretAccessKey,
83
- region = "us-west-2"
84
- } = config;
85
- const entries = usageEvents.map(event => {
86
- // Enforce schema of usage event.
87
- const parsed = usageEventSchema.parse(event);
88
- return {
89
- Id: crypto.randomUUID(),
90
- MessageBody: JSON.stringify(parsed)
91
- };
92
- });
93
- const aws = getAws({
94
- accessKeyId,
95
- secretAccessKey,
96
- region
97
- });
98
- await aws.fetch(`https://sqs.${region}.amazonaws.com`, {
99
- headers: {
100
- "X-Amz-Target": "AmazonSQS.SendMessageBatch",
101
- "X-Amz-Date": new Date().toISOString(),
102
- "Content-Type": "application/x-amz-json-1.0"
103
- },
104
- body: JSON.stringify({
105
- QueueUrl: queueUrl,
106
- Entries: entries
107
- })
108
- });
109
- }
110
-
111
- const DEFAULT_CACHE_TTL_SECONDS = 60;
112
- async function authorizeWorker(authInput, serviceConfig) {
113
- let authData;
114
- try {
115
- authData = await extractAuthorizationData(authInput);
116
- } catch (e) {
117
- if (e instanceof Error && e.message === "KEY_CONFLICT") {
118
- return {
119
- authorized: false,
120
- status: 400,
121
- errorMessage: "Please pass either a client id or a secret key.",
122
- errorCode: "KEY_CONFLICT"
123
- };
124
- }
125
- return {
126
- authorized: false,
127
- status: 500,
128
- errorMessage: "Internal Server Error",
129
- errorCode: "INTERNAL_SERVER_ERROR"
130
- };
131
- }
132
- return await index.authorize(authData, serviceConfig, {
133
- get: async clientId => serviceConfig.kvStore.get(clientId),
134
- put: (clientId, apiKeyMeta) => serviceConfig.ctx.waitUntil(serviceConfig.kvStore.put(clientId, JSON.stringify({
135
- updatedAt: Date.now(),
136
- apiKeyMeta
137
- }), {
138
- expirationTtl: serviceConfig.cacheTtlSeconds && serviceConfig.cacheTtlSeconds >= DEFAULT_CACHE_TTL_SECONDS ? serviceConfig.cacheTtlSeconds : DEFAULT_CACHE_TTL_SECONDS
139
- })),
140
- cacheTtlSeconds: serviceConfig.cacheTtlSeconds ?? DEFAULT_CACHE_TTL_SECONDS
141
- });
142
- }
143
- async function extractAuthorizationData(authInput) {
144
- const requestUrl = new URL(authInput.req.url);
145
- const headers = authInput.req.headers;
146
- const secretKey = headers.get("x-secret-key");
147
-
148
- // prefer clientId that is explicitly passed in
149
- let clientId = authInput.clientId ?? null;
150
- if (!clientId) {
151
- // next preference is clientId from header
152
- clientId = headers.get("x-client-id");
153
- }
154
-
155
- // next preference is search param
156
- if (!clientId) {
157
- clientId = requestUrl.searchParams.get("clientId");
158
- }
159
- // bundle id from header is first preference
160
- let bundleId = headers.get("x-bundle-id");
161
-
162
- // next preference is search param
163
- if (!bundleId) {
164
- bundleId = requestUrl.searchParams.get("bundleId");
165
- }
166
- let origin = headers.get("origin");
167
- // if origin header is not available we'll fall back to referrer;
168
- if (!origin) {
169
- origin = headers.get("referer");
170
- }
171
- // if we have an origin at this point, normalize it
172
- if (origin) {
173
- try {
174
- origin = new URL(origin).host;
175
- } catch (e) {
176
- console.warn("failed to parse origin", origin, e);
177
- }
178
- }
179
-
180
- // handle if we a secret key is passed in the headers
181
- let secretKeyHash = null;
182
- if (secretKey) {
183
- // hash the secret key
184
- secretKeyHash = await hashSecretKey(secretKey);
185
- // derive the client id from the secret key hash
186
- const derivedClientId = deriveClientIdFromSecretKeyHash(secretKeyHash);
187
- // if we already have a client id passed in we need to make sure they match
188
- if (clientId && clientId !== derivedClientId) {
189
- throw new Error("KEY_CONFLICT");
190
- }
191
- // otherwise set the client id to the derived client id (client id based off of secret key)
192
- clientId = derivedClientId;
193
- }
194
- let jwt = null;
195
- if (headers.has("authorization")) {
196
- const authHeader = headers.get("authorization");
197
- if (authHeader) {
198
- const [type, token] = authHeader.split(" ");
199
- if (type.toLowerCase() === "bearer" && !!token) {
200
- jwt = token;
201
- }
202
- }
203
- }
204
- return {
205
- jwt,
206
- hashedJWT: jwt ? await hashSecretKey(jwt) : null,
207
- secretKey,
208
- clientId,
209
- origin,
210
- bundleId,
211
- secretKeyHash,
212
- targetAddress: authInput.targetAddress
213
- };
214
- }
215
- async function hashSecretKey(secretKey) {
216
- return bufferToHex(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(secretKey)));
217
- }
218
- function deriveClientIdFromSecretKeyHash(secretKeyHash) {
219
- return secretKeyHash.slice(0, 32);
220
- }
221
- function bufferToHex(buffer) {
222
- return [...new Uint8Array(buffer)].map(x => x.toString(16).padStart(2, "0")).join("");
223
- }
224
- async function logHttpRequest(_ref) {
225
- let {
226
- source,
227
- clientId,
228
- req,
229
- res,
230
- isAuthed,
231
- statusMessage,
232
- latencyMs
233
- } = _ref;
234
- try {
235
- const authorizationData = await extractAuthorizationData({
236
- req,
237
- clientId
238
- });
239
- const headers = req.headers;
240
- console.log(JSON.stringify({
241
- source,
242
- pathname: req.url,
243
- hasSecretKey: !!authorizationData.secretKey,
244
- hasClientId: !!authorizationData.clientId,
245
- hasJwt: !!authorizationData.jwt,
246
- clientId: authorizationData.clientId,
247
- isAuthed: !!isAuthed ?? null,
248
- status: res.status,
249
- sdkName: headers.get("x-sdk-name") ?? "unknown",
250
- sdkVersion: headers.get("x-sdk-version") ?? "unknown",
251
- platform: headers.get("x-sdk-platform") ?? "unknown",
252
- os: headers.get("x-sdk-os") ?? "unknown",
253
- latencyMs: latencyMs ?? null
254
- }));
255
- console.log(`statusMessage=${statusMessage ?? res.statusText}`);
256
- } catch (err) {
257
- console.error("Failed to log HTTP request:", err);
258
- }
259
- }
260
-
261
- exports.rateLimit = index.rateLimit;
262
- exports.usageLimit = index.usageLimit;
263
- exports.SERVICES = services.SERVICES;
264
- exports.SERVICE_DEFINITIONS = services.SERVICE_DEFINITIONS;
265
- exports.SERVICE_NAMES = services.SERVICE_NAMES;
266
- exports.getServiceByName = services.getServiceByName;
267
- exports.authorizeWorker = authorizeWorker;
268
- exports.deriveClientIdFromSecretKeyHash = deriveClientIdFromSecretKeyHash;
269
- exports.extractAuthorizationData = extractAuthorizationData;
270
- exports.hashSecretKey = hashSecretKey;
271
- exports.logHttpRequest = logHttpRequest;
272
- exports.publishUsageEvents = publishUsageEvents;
@@ -1,7 +0,0 @@
1
- 'use strict';
2
-
3
- if (process.env.NODE_ENV === "production") {
4
- module.exports = require("./thirdweb-dev-service-utils-cf-worker.cjs.prod.js");
5
- } else {
6
- module.exports = require("./thirdweb-dev-service-utils-cf-worker.cjs.dev.js");
7
- }
@@ -1,272 +0,0 @@
1
- 'use strict';
2
-
3
- Object.defineProperty(exports, '__esModule', { value: true });
4
-
5
- var index = require('../../dist/index-aa324361.cjs.prod.js');
6
- var aws4fetch = require('aws4fetch');
7
- var zod = require('zod');
8
- var services = require('../../dist/services-5c4d6977.cjs.prod.js');
9
-
10
- // Initialize a singleton for aws usage.
11
- let _aws;
12
- function getAws(options) {
13
- if (!_aws) {
14
- _aws = new aws4fetch.AwsClient(options);
15
- }
16
- return _aws;
17
- }
18
-
19
- /**
20
- * Types
21
- */
22
- const usageEventSchema = zod.z.object({
23
- source: zod.z.enum(["embeddedWallets", "rpc", "storage", "bundler", "paymaster", "relayer", "connectWallet", "checkout", "engine"]),
24
- action: zod.z.string(),
25
- /**
26
- * The following fields are optional.
27
- */
28
-
29
- accountId: zod.z.string().optional(),
30
- isClientEvent: zod.z.boolean().optional(),
31
- apiKeyId: zod.z.string().optional(),
32
- creatorWalletAddress: zod.z.string().optional(),
33
- clientId: zod.z.string().optional(),
34
- walletAddress: zod.z.string().optional(),
35
- walletType: zod.z.string().optional(),
36
- chainId: zod.z.number().int().positive().optional(),
37
- provider: zod.z.string().optional(),
38
- mimeType: zod.z.string().optional(),
39
- fileSize: zod.z.number().int().nonnegative().optional(),
40
- fileCid: zod.z.string().optional(),
41
- evmMethod: zod.z.string().optional(),
42
- userOpHash: zod.z.string().optional(),
43
- gasLimit: zod.z.number().nonnegative().optional(),
44
- gasPricePerUnit: zod.z.string().optional(),
45
- transactionFeeUsd: zod.z.number().optional(),
46
- transactionHash: zod.z.string().optional(),
47
- sdkName: zod.z.string().optional(),
48
- sdkVersion: zod.z.string().optional(),
49
- sdkPlatform: zod.z.string().optional(),
50
- productName: zod.z.string().optional(),
51
- transactionValue: zod.z.string().optional(),
52
- pathname: zod.z.string().optional(),
53
- contractAddress: zod.z.string().optional(),
54
- errorCode: zod.z.string().optional(),
55
- httpStatusCode: zod.z.number().int().nonnegative().optional(),
56
- functionName: zod.z.string().optional(),
57
- extension: zod.z.string().optional(),
58
- retryCount: zod.z.number().int().nonnegative().optional(),
59
- policyId: zod.z.string().optional(),
60
- msSinceQueue: zod.z.number().nonnegative().optional(),
61
- msSinceSend: zod.z.number().nonnegative().optional(),
62
- msTotalDuration: zod.z.number().nonnegative().optional()
63
- });
64
- /**
65
- * Publish usage events. Provide the relevant fields for your application.
66
- *
67
- * Usage in Cloudflare Workers:
68
- * ctx.waitUntil(
69
- * publishUsageEvents(
70
- * [event1, event2],
71
- * { queueUrl, accessKeyId, secretAccessKey },
72
- * )
73
- * )
74
- *
75
- * @param usageEvents
76
- * @param config
77
- */
78
- async function publishUsageEvents(usageEvents, config) {
79
- const {
80
- queueUrl,
81
- accessKeyId,
82
- secretAccessKey,
83
- region = "us-west-2"
84
- } = config;
85
- const entries = usageEvents.map(event => {
86
- // Enforce schema of usage event.
87
- const parsed = usageEventSchema.parse(event);
88
- return {
89
- Id: crypto.randomUUID(),
90
- MessageBody: JSON.stringify(parsed)
91
- };
92
- });
93
- const aws = getAws({
94
- accessKeyId,
95
- secretAccessKey,
96
- region
97
- });
98
- await aws.fetch(`https://sqs.${region}.amazonaws.com`, {
99
- headers: {
100
- "X-Amz-Target": "AmazonSQS.SendMessageBatch",
101
- "X-Amz-Date": new Date().toISOString(),
102
- "Content-Type": "application/x-amz-json-1.0"
103
- },
104
- body: JSON.stringify({
105
- QueueUrl: queueUrl,
106
- Entries: entries
107
- })
108
- });
109
- }
110
-
111
- const DEFAULT_CACHE_TTL_SECONDS = 60;
112
- async function authorizeWorker(authInput, serviceConfig) {
113
- let authData;
114
- try {
115
- authData = await extractAuthorizationData(authInput);
116
- } catch (e) {
117
- if (e instanceof Error && e.message === "KEY_CONFLICT") {
118
- return {
119
- authorized: false,
120
- status: 400,
121
- errorMessage: "Please pass either a client id or a secret key.",
122
- errorCode: "KEY_CONFLICT"
123
- };
124
- }
125
- return {
126
- authorized: false,
127
- status: 500,
128
- errorMessage: "Internal Server Error",
129
- errorCode: "INTERNAL_SERVER_ERROR"
130
- };
131
- }
132
- return await index.authorize(authData, serviceConfig, {
133
- get: async clientId => serviceConfig.kvStore.get(clientId),
134
- put: (clientId, apiKeyMeta) => serviceConfig.ctx.waitUntil(serviceConfig.kvStore.put(clientId, JSON.stringify({
135
- updatedAt: Date.now(),
136
- apiKeyMeta
137
- }), {
138
- expirationTtl: serviceConfig.cacheTtlSeconds && serviceConfig.cacheTtlSeconds >= DEFAULT_CACHE_TTL_SECONDS ? serviceConfig.cacheTtlSeconds : DEFAULT_CACHE_TTL_SECONDS
139
- })),
140
- cacheTtlSeconds: serviceConfig.cacheTtlSeconds ?? DEFAULT_CACHE_TTL_SECONDS
141
- });
142
- }
143
- async function extractAuthorizationData(authInput) {
144
- const requestUrl = new URL(authInput.req.url);
145
- const headers = authInput.req.headers;
146
- const secretKey = headers.get("x-secret-key");
147
-
148
- // prefer clientId that is explicitly passed in
149
- let clientId = authInput.clientId ?? null;
150
- if (!clientId) {
151
- // next preference is clientId from header
152
- clientId = headers.get("x-client-id");
153
- }
154
-
155
- // next preference is search param
156
- if (!clientId) {
157
- clientId = requestUrl.searchParams.get("clientId");
158
- }
159
- // bundle id from header is first preference
160
- let bundleId = headers.get("x-bundle-id");
161
-
162
- // next preference is search param
163
- if (!bundleId) {
164
- bundleId = requestUrl.searchParams.get("bundleId");
165
- }
166
- let origin = headers.get("origin");
167
- // if origin header is not available we'll fall back to referrer;
168
- if (!origin) {
169
- origin = headers.get("referer");
170
- }
171
- // if we have an origin at this point, normalize it
172
- if (origin) {
173
- try {
174
- origin = new URL(origin).host;
175
- } catch (e) {
176
- console.warn("failed to parse origin", origin, e);
177
- }
178
- }
179
-
180
- // handle if we a secret key is passed in the headers
181
- let secretKeyHash = null;
182
- if (secretKey) {
183
- // hash the secret key
184
- secretKeyHash = await hashSecretKey(secretKey);
185
- // derive the client id from the secret key hash
186
- const derivedClientId = deriveClientIdFromSecretKeyHash(secretKeyHash);
187
- // if we already have a client id passed in we need to make sure they match
188
- if (clientId && clientId !== derivedClientId) {
189
- throw new Error("KEY_CONFLICT");
190
- }
191
- // otherwise set the client id to the derived client id (client id based off of secret key)
192
- clientId = derivedClientId;
193
- }
194
- let jwt = null;
195
- if (headers.has("authorization")) {
196
- const authHeader = headers.get("authorization");
197
- if (authHeader) {
198
- const [type, token] = authHeader.split(" ");
199
- if (type.toLowerCase() === "bearer" && !!token) {
200
- jwt = token;
201
- }
202
- }
203
- }
204
- return {
205
- jwt,
206
- hashedJWT: jwt ? await hashSecretKey(jwt) : null,
207
- secretKey,
208
- clientId,
209
- origin,
210
- bundleId,
211
- secretKeyHash,
212
- targetAddress: authInput.targetAddress
213
- };
214
- }
215
- async function hashSecretKey(secretKey) {
216
- return bufferToHex(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(secretKey)));
217
- }
218
- function deriveClientIdFromSecretKeyHash(secretKeyHash) {
219
- return secretKeyHash.slice(0, 32);
220
- }
221
- function bufferToHex(buffer) {
222
- return [...new Uint8Array(buffer)].map(x => x.toString(16).padStart(2, "0")).join("");
223
- }
224
- async function logHttpRequest(_ref) {
225
- let {
226
- source,
227
- clientId,
228
- req,
229
- res,
230
- isAuthed,
231
- statusMessage,
232
- latencyMs
233
- } = _ref;
234
- try {
235
- const authorizationData = await extractAuthorizationData({
236
- req,
237
- clientId
238
- });
239
- const headers = req.headers;
240
- console.log(JSON.stringify({
241
- source,
242
- pathname: req.url,
243
- hasSecretKey: !!authorizationData.secretKey,
244
- hasClientId: !!authorizationData.clientId,
245
- hasJwt: !!authorizationData.jwt,
246
- clientId: authorizationData.clientId,
247
- isAuthed: !!isAuthed ?? null,
248
- status: res.status,
249
- sdkName: headers.get("x-sdk-name") ?? "unknown",
250
- sdkVersion: headers.get("x-sdk-version") ?? "unknown",
251
- platform: headers.get("x-sdk-platform") ?? "unknown",
252
- os: headers.get("x-sdk-os") ?? "unknown",
253
- latencyMs: latencyMs ?? null
254
- }));
255
- console.log(`statusMessage=${statusMessage ?? res.statusText}`);
256
- } catch (err) {
257
- console.error("Failed to log HTTP request:", err);
258
- }
259
- }
260
-
261
- exports.rateLimit = index.rateLimit;
262
- exports.usageLimit = index.usageLimit;
263
- exports.SERVICES = services.SERVICES;
264
- exports.SERVICE_DEFINITIONS = services.SERVICE_DEFINITIONS;
265
- exports.SERVICE_NAMES = services.SERVICE_NAMES;
266
- exports.getServiceByName = services.getServiceByName;
267
- exports.authorizeWorker = authorizeWorker;
268
- exports.deriveClientIdFromSecretKeyHash = deriveClientIdFromSecretKeyHash;
269
- exports.extractAuthorizationData = extractAuthorizationData;
270
- exports.hashSecretKey = hashSecretKey;
271
- exports.logHttpRequest = logHttpRequest;
272
- exports.publishUsageEvents = publishUsageEvents;