-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathadmin-client.ts
More file actions
282 lines (245 loc) · 7.74 KB
/
admin-client.ts
File metadata and controls
282 lines (245 loc) · 7.74 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
import {
errInvalidAccessKey,
errNotFound,
errRateLimited,
errAdminAPI,
errNetwork,
errInvalidArgs,
} from "./errors.js";
import { timeout as globalTimeout } from "./output.js";
// ── Types ────────────────────────────────────────────────────────────
export interface ChainNetwork {
id: string;
name: string;
networkChainId: string | null;
isTestnet: boolean;
availability: "prerelease" | "public" | "deprecated";
docsUrl: string;
explorerUrl: string;
currency: string;
}
export interface AppChainNetwork {
name: string;
id: string;
networkChainId?: string | null;
rpcUrl: string;
wsUrl?: string;
grpcUrl?: string;
}
export interface AllowlistEntry {
name?: string;
value: string;
}
export interface App {
id: string;
name: string;
description?: string;
apiKey: string;
webhookApiKey: string;
chainNetworks: AppChainNetwork[];
products?: string[];
addressAllowlist?: AllowlistEntry[];
originAllowlist?: AllowlistEntry[];
ipAllowlist?: AllowlistEntry[];
createdAt: string;
}
interface ListAppsResponse {
apps: App[];
cursor?: string;
}
// ── Client ───────────────────────────────────────────────────────────
export class AdminClient {
private static readonly ADMIN_API_HOST = "admin-api.alchemy.com";
// Test/debug only: used by mock E2E to route admin requests locally.
private static readonly ADMIN_API_BASE_URL_ENV = "ALCHEMY_ADMIN_API_BASE_URL";
private accessKey: string;
constructor(accessKey: string) {
this.validateAccessKey(accessKey);
this.accessKey = accessKey;
}
protected baseURL(): string {
const override = this.baseURLOverride();
if (override) return override.toString().replace(/\/$/, "");
return "https://admin-api.alchemy.com";
}
protected allowedHosts(): Set<string> {
const hosts = new Set([AdminClient.ADMIN_API_HOST]);
const override = this.baseURLOverride();
if (override) hosts.add(override.hostname);
return hosts;
}
protected allowInsecureTransport(hostname: string): boolean {
return this.isLocalhost(hostname);
}
private isLocalhost(hostname: string): boolean {
return hostname === "localhost" || hostname === "127.0.0.1" || hostname === "::1";
}
private baseURLOverride(): URL | null {
const raw = process.env[AdminClient.ADMIN_API_BASE_URL_ENV];
if (!raw) return null;
let parsed: URL;
try {
parsed = new URL(raw);
} catch {
throw errInvalidArgs(`Invalid ${AdminClient.ADMIN_API_BASE_URL_ENV} value.`);
}
if (!this.isLocalhost(parsed.hostname)) {
throw errInvalidArgs(
`${AdminClient.ADMIN_API_BASE_URL_ENV} must target localhost or 127.0.0.1.`,
);
}
if (parsed.protocol !== "https:" && parsed.protocol !== "http:") {
throw errInvalidArgs(
`${AdminClient.ADMIN_API_BASE_URL_ENV} must use http:// or https://.`,
);
}
if (parsed.protocol === "http:" && !this.isLocalhost(parsed.hostname)) {
throw errInvalidArgs(
`${AdminClient.ADMIN_API_BASE_URL_ENV} can only use non-HTTPS for localhost targets.`,
);
}
return parsed;
}
private validateAccessKey(accessKey: string): void {
if (!accessKey.trim() || /\s/.test(accessKey)) {
throw errInvalidAccessKey();
}
}
private assertSafeRequestTarget(url: string): void {
let parsed: URL;
try {
parsed = new URL(url);
} catch {
throw errInvalidArgs("Invalid admin API URL.");
}
if (!this.allowedHosts().has(parsed.hostname)) {
throw errInvalidArgs(`Refusing to send credentials to unexpected host: ${parsed.hostname}`);
}
if (parsed.protocol !== "https:" && !this.allowInsecureTransport(parsed.hostname)) {
throw errInvalidArgs("Refusing to send credentials over non-HTTPS connection.");
}
}
private async request<T>(
method: string,
path: string,
body?: unknown,
): Promise<T> {
const url = `${this.baseURL()}${path}`;
this.assertSafeRequestTarget(url);
let resp: Response;
try {
resp = await fetch(url, {
method,
redirect: "error",
headers: {
Authorization: `Bearer ${this.accessKey}`,
"Content-Type": "application/json",
Accept: "application/json",
},
...(body !== undefined && { body: JSON.stringify(body) }),
...(globalTimeout && { signal: AbortSignal.timeout(globalTimeout) }),
});
} catch (err) {
if (err instanceof DOMException && err.name === "TimeoutError") {
throw errNetwork(`Request timed out after ${globalTimeout}ms`);
}
throw errNetwork((err as Error).message);
}
if (resp.status === 401 || resp.status === 403) throw errInvalidAccessKey();
if (resp.status === 404) {
const text = await resp.text().catch(() => "");
throw errNotFound(text || path);
}
if (resp.status === 429) throw errRateLimited();
if (!resp.ok) {
const text = await resp.text().catch(() => "");
throw errAdminAPI(resp.status, text);
}
return resp.json() as Promise<T>;
}
async listChains(): Promise<ChainNetwork[]> {
const result = await this.request<{ data: { networks: ChainNetwork[] } }>(
"GET",
"/v1/chains",
);
return result.data.networks;
}
async listApps(opts?: {
cursor?: string;
limit?: number;
}): Promise<ListAppsResponse> {
const params = new URLSearchParams();
if (opts?.cursor) params.set("cursor", opts.cursor);
if (opts?.limit) params.set("limit", String(opts.limit));
const qs = params.toString();
const resp = await this.request<{ data: ListAppsResponse }>(
"GET",
`/v1/apps${qs ? `?${qs}` : ""}`,
);
return resp.data;
}
async getApp(id: string): Promise<App> {
const resp = await this.request<{ data: App }>("GET", `/v1/apps/${id}`);
return resp.data;
}
async createApp(opts: {
name: string;
networks: string[];
description?: string;
products?: string[];
}): Promise<App> {
const resp = await this.request<{ data: App }>("POST", "/v1/apps", {
name: opts.name,
chainNetworks: opts.networks,
...(opts.description && { description: opts.description }),
...(opts.products && { products: opts.products }),
});
return resp.data;
}
async deleteApp(id: string): Promise<void> {
await this.request<unknown>("DELETE", `/v1/apps/${id}`);
}
async updateApp(
id: string,
opts: { name?: string; description?: string },
): Promise<App> {
const resp = await this.request<{ data: App }>("PATCH", `/v1/apps/${id}`, opts);
return resp.data;
}
async updateNetworkAllowlist(
id: string,
networks: string[],
): Promise<App> {
const resp = await this.request<{ data: App }>("PUT", `/v1/apps/${id}/networks`, {
chainNetworks: networks,
});
return resp.data;
}
async updateAddressAllowlist(
id: string,
addresses: AllowlistEntry[],
): Promise<App> {
const resp = await this.request<{ data: App }>("PUT", `/v1/apps/${id}/address-allowlist`, {
addressAllowlist: addresses,
});
return resp.data;
}
async updateOriginAllowlist(
id: string,
origins: AllowlistEntry[],
): Promise<App> {
const resp = await this.request<{ data: App }>("PUT", `/v1/apps/${id}/origin-allowlist`, {
originAllowlist: origins,
});
return resp.data;
}
async updateIpAllowlist(
id: string,
ips: AllowlistEntry[],
): Promise<App> {
const resp = await this.request<{ data: App }>("PUT", `/v1/apps/${id}/ip-allowlist`, {
ipAllowlist: ips,
});
return resp.data;
}
}