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