-
Notifications
You must be signed in to change notification settings - Fork 386
/
api.ts
746 lines (715 loc) · 23.2 KB
/
api.ts
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
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
// Copyright (C) 2021 Storj Labs, Inc.
// See LICENSE for copying information.
/*
* This is the Admin API client exposing the API operations using the
* interfaces, types and classes of the `ui-generator.ts` for allowing the
* `UIGenerator.svelte` component to dynamically render their Web UI interface.
*/
import type { Operation } from '$lib/ui-generator';
import { InputText, Select } from '$lib/ui-generator';
// API must be implemented by any class which expose the access to a specific
// API.
export interface API {
operations: {
[key: string]: Operation[];
};
}
export class Admin {
readonly operations = {
APIKeys: [
{
name: 'get',
desc: 'Get information on the specific API key',
params: [['API key', new InputText('text', true)]],
func: async (apiKey: string): Promise<Record<string, unknown>> => {
return this.fetch('GET', `apikeys/${apiKey}`);
}
},
{
name: 'delete key',
desc: 'Delete an API key',
params: [['API key', new InputText('text', true)]],
func: async (apiKey: string): Promise<null> => {
return this.fetch('DELETE', `apikeys/${apiKey}`) as Promise<null>;
}
}
],
bucket: [
{
name: 'get',
desc: 'Get the information of the specified bucket',
params: [
['Project ID', new InputText('text', true)],
['Bucket name', new InputText('text', true)]
],
func: async (projectId: string, bucketName: string): Promise<Record<string, unknown>> => {
return this.fetch('GET', `projects/${projectId}/buckets/${bucketName}`);
},
deprecated: true
},
{
name: 'delete geofencing',
desc: 'Delete the geofencing configuration of the specified bucket. The bucket MUST be empty',
params: [
['Project ID', new InputText('text', true)],
['Bucket name', new InputText('text', true)]
],
func: async (projectId: string, bucketName: string): Promise<null> => {
return this.fetch(
'DELETE',
`projects/${projectId}/buckets/${bucketName}/geofence`
) as Promise<null>;
},
deprecated: true
},
{
name: 'set geofencing',
desc: 'Set the geofencing configuration of the specified bucket. The bucket MUST be empty',
params: [
['Project ID', new InputText('text', true)],
['Bucket name', new InputText('text', true)],
[
'Region',
new Select(false, true, [
{ text: 'European Union', value: 'EU' },
{ text: 'European Economic Area', value: 'EEA' },
{ text: 'United States', value: 'US' },
{ text: 'Germany', value: 'DE' },
{ text: 'No Russia and/or other sanctioned country', value: 'NR' }
])
]
],
func: async (projectId: string, bucketName: string, region: string): Promise<null> => {
const query = this.urlQueryFromObject({ region });
if (query === '') {
throw new APIError('region cannot be empty');
}
return this.fetch(
'POST',
`projects/${projectId}/buckets/${bucketName}/geofence`,
query
) as Promise<null>;
},
deprecated: true
}
],
oauth_clients: [
{
name: 'create',
desc: 'Add a new oauth client',
params: [
['Client ID', new InputText('text', true)],
['Client Secret', new InputText('text', true)],
['Owner ID (userID)', new InputText('text', true)],
['Redirect URL', new InputText('text', true)],
['Application Name', new InputText('text', true)],
['Application Logo URL', new InputText('text', false)]
],
func: async (
id: string,
secret: string,
ownerID: string,
redirectURL: string,
appName: string,
appLogoURL: string
): Promise<null> => {
return this.fetch('POST', `oauth/clients`, null, {
id,
secret,
userID: ownerID,
redirectURL,
appName,
appLogoURL
}) as Promise<null>;
}
},
{
name: 'update',
desc: 'Update an existing oauth client',
params: [
['Client ID', new InputText('text', true)],
['Redirect URL', new InputText('text', false)],
['Application Name', new InputText('text', false)],
['Application Logo URL', new InputText('text', false)]
],
func: async (
id: string,
redirectURL: string,
appName: string,
appLogoURL: string
): Promise<null> => {
return this.fetch('PUT', `oauth/clients/${id}`, null, {
id,
redirectURL,
appName,
appLogoURL
}) as Promise<null>;
}
},
{
name: 'delete',
desc: 'Remove an oauth client',
params: [['Client ID', new InputText('text', true)]],
func: async (clientID: string): Promise<null> => {
return this.fetch('DELETE', `oauth/clients/${clientID}`, null) as Promise<null>;
}
}
],
project: [
{
name: 'create',
desc: 'Add a new project to a specific user',
params: [
['Owner ID (user ID)', new InputText('text', true)],
['Project Name', new InputText('text', true)]
],
func: async (ownerId: string, projectName: string): Promise<Record<string, unknown>> => {
return this.fetch('POST', 'projects', null, { ownerId, projectName });
}
},
{
name: 'delete',
desc: 'Delete a specific project',
params: [['Project ID', new InputText('text', true)]],
func: async (projectId: string): Promise<null> => {
return this.fetch('DELETE', `projects/${projectId}`) as Promise<null>;
}
},
{
name: 'get',
desc: 'Get the information of a specific project',
params: [['Project ID', new InputText('text', true)]],
func: async (projectId: string): Promise<Record<string, unknown>> => {
return this.fetch('GET', `projects/${projectId}`);
},
deprecated: true
},
{
name: 'update',
desc: 'Update the information of a specific project',
params: [
['Project ID', new InputText('text', true)],
['Project Name', new InputText('text', true)],
['Description', new InputText('text', false)]
],
func: async (
projectId: string,
projectName: string,
description: string
): Promise<null> => {
return this.fetch('PUT', `projects/${projectId}`, null, {
projectName,
description
}) as Promise<null>;
},
deprecated: true
},
{
name: 'update user agent',
desc: 'Update projects user agent',
params: [
['Project ID', new InputText('text', true)],
['User Agent', new InputText('text', true)]
],
func: async (projectId: string, userAgent: string): Promise<null> => {
return this.fetch('PATCH', `projects/${projectId}/useragent`, null, {
userAgent
}) as Promise<null>;
},
deprecated: true
},
{
name: 'create API key',
desc: 'Create a new API key for a specific project',
params: [
['Project ID', new InputText('text', true)],
['API key name', new InputText('text', true)]
],
func: async (projectId: string, name: string): Promise<Record<string, unknown>> => {
return this.fetch('POST', `projects/${projectId}/apikeys`, null, {
name
});
}
},
{
name: 'delete API key',
desc: 'Delete a API key of a specific project',
params: [
['Project ID', new InputText('text', true)],
['API Key name', new InputText('text', true)]
],
func: async (projectId: string, apiKeyName: string): Promise<null> => {
const query = this.urlQueryFromObject({
name: apiKeyName
});
return this.fetch('DELETE', `projects/${projectId}/apikeys`, query) as Promise<null>;
}
},
{
name: 'get API keys',
desc: 'Get the API keys of a specific project',
params: [['Project ID', new InputText('text', true)]],
func: async (projectId: string): Promise<Record<string, unknown>> => {
return this.fetch('GET', `projects/${projectId}/apikeys`);
}
},
{
name: 'get project usage',
desc: 'Get the current usage of a specific project',
params: [['Project ID', new InputText('text', true)]],
func: async (projectId: string): Promise<Record<string, unknown>> => {
return this.fetch('GET', `projects/${projectId}/usage`);
}
},
{
name: 'get project limits',
desc: 'Get the current limits of a specific project. NULL values means that the satellite applies the configured defaults',
params: [['Project ID', new InputText('text', true)]],
func: async (projectId: string): Promise<Record<string, unknown>> => {
return this.fetch('GET', `projects/${projectId}/limit`);
},
deprecated: true
},
{
name: 'update project limits',
desc: 'Update the limits of a specific project. Only the no blank fields are updated. Fields with the 0 value are set to 0, which is not the default value. The fields that accept -1 set the value to null, which is the value that indicate the satellite to apply the configured defaults',
params: [
['Project ID', new InputText('text', true)],
['Storage (in bytes or notations like 1GB, 2tb)', new InputText('text', false)],
['Bandwidth (in bytes or notations like 1GB, 2tb)', new InputText('text', false)],
['Rate: requests per second (accepts -1)', new InputText('number', false)],
['Buckets: maximum number (accepts -1)', new InputText('number', false)],
['Burst: max concurrent requests (accepts -1)', new InputText('number', false)],
['Segments (maximum number)', new InputText('number', false)]
],
func: async (
projectId: string,
usage: string,
bandwidth: string,
rate: number,
buckets: number,
burst: number,
segments: number
): Promise<null> => {
usage = this.emptyToUndefined(usage);
bandwidth = this.emptyToUndefined(bandwidth);
rate = this.nullToUndefined(rate);
buckets = this.nullToUndefined(buckets);
burst = this.nullToUndefined(burst);
segments = this.nullToUndefined(segments);
const query = this.urlQueryFromObject({
usage,
bandwidth,
rate,
buckets,
burst,
segments
});
if (query === '') {
throw new APIError('nothing to update, at least one limit must be set');
}
return this.fetch('PUT', `projects/${projectId}/limit`, query) as Promise<null>;
},
deprecated: true
}
],
user: [
{
name: 'create',
desc: 'Create a new user account',
params: [
['email', new InputText('email', true)],
['full name', new InputText('text', false)],
['password', new InputText('password', true)]
],
func: async (
email: string,
fullName: string,
password: string
): Promise<Record<string, unknown>> => {
return this.fetch('POST', 'users', null, {
email,
fullName,
password
});
}
},
{
name: 'delete',
desc: "Delete a user's account",
params: [['email', new InputText('email', true)]],
func: async (email: string): Promise<null> => {
return this.fetch('DELETE', `users/${email}`) as Promise<null>;
}
},
{
name: 'get',
desc: "Get the information of a user's account",
params: [['email', new InputText('email', true)]],
func: async (email: string): Promise<Record<string, unknown>> => {
return this.fetch('GET', `users/${email}`);
},
deprecated: true
},
{
name: 'get users pending deletion',
desc: 'Get the information of a users pending deletion and have no unpaid invoices',
params: [
['Limit', new InputText('number', true)],
['Page', new InputText('number', true)]
],
func: async (limit: number, page: number): Promise<Record<string, unknown>> => {
return this.fetch('GET', `users-pending-deletion?limit=${limit}&page=${page}`);
}
},
{
name: 'get user limits',
desc: 'Get the current limits for a user',
params: [['email', new InputText('email', true)]],
func: async (email: string): Promise<Record<string, unknown>> => {
return this.fetch('GET', `users/${email}/limits`);
},
deprecated: true
},
{
name: 'update',
desc: `Update the information of a user's account.
Blank fields will not be updated.`,
params: [
["current user's email", new InputText('email', true)],
['new email', new InputText('email', false)],
['full name', new InputText('text', false)],
['short name', new InputText('text', false)],
['password hash', new InputText('text', false)],
['project limit (max number)', new InputText('number', false)],
['project storage limit (in bytes)', new InputText('number', false)],
['project bandwidth limit (in bytes)', new InputText('number', false)],
['project segment limit (max number)', new InputText('number', false)],
[
'paid tier',
new Select(false, false, [
{ text: '', value: '' },
{ text: 'true', value: 'true' },
{ text: 'false', value: 'false' }
])
]
],
func: async (
currentEmail: string,
email?: string,
fullName?: string,
shortName?: string,
passwordHash?: string,
projectLimit?: number,
projectStorageLimit?: number,
projectBandwidthLimit?: number,
projectSegmentLimit?: number,
paidTierStr?: boolean
): Promise<null> => {
return this.fetch('PUT', `users/${currentEmail}`, null, {
email,
fullName,
shortName,
passwordHash,
projectLimit,
projectStorageLimit,
projectBandwidthLimit,
projectSegmentLimit,
paidTierStr
}) as Promise<null>;
},
deprecated: true
},
{
name: "update user's project limits",
desc: `Update limits for all of user's existing and future projects.
Blank fields will not be updated.`,
params: [
["current user's email", new InputText('email', true)],
[
'project storage limit (in bytes or notations like 1GB, 2tb)',
new InputText('text', false)
],
[
'project bandwidth limit (in bytes or notations like 1GB, 2tb)',
new InputText('text', false)
],
['project segment limit (max number)', new InputText('number', false)]
],
func: async (
currentEmail: string,
storage?: number,
bandwidth?: number,
segment?: number
): Promise<null> => {
return this.fetch('PUT', `users/${currentEmail}/limits`, null, {
storage,
bandwidth,
segment
}) as Promise<null>;
}
},
{
name: 'update user agent',
desc: `Update user's user agent.`,
params: [
["current user's email", new InputText('email', true)],
['user agent', new InputText('text', true)]
],
func: async (currentEmail: string, userAgent: string): Promise<null> => {
return this.fetch('PATCH', `users/${currentEmail}/useragent`, null, {
userAgent
}) as Promise<null>;
},
deprecated: true
},
{
name: 'activate account/disable bot restriction',
desc: 'Disables account bot restrictions by activating the account and restoring its limit values. This is used only for accounts with the PendingBotVerification status.',
params: [['email', new InputText('email', true)]],
func: async (email: string): Promise<null> => {
return this.fetch(
'PATCH',
`users/${email}/activate-account/disable-bot-restriction`
) as Promise<null>;
}
},
{
name: 'disable MFA',
desc: "Disable user's mulifactor authentication",
params: [['email', new InputText('email', true)]],
func: async (email: string): Promise<null> => {
return this.fetch('DELETE', `users/${email}/mfa`) as Promise<null>;
}
},
{
name: 'billing freeze user',
desc: "insert user into account_freeze_events and set user's limits to zero",
params: [['email', new InputText('email', true)]],
func: async (email: string): Promise<null> => {
return this.fetch('PUT', `users/${email}/billing-freeze`) as Promise<null>;
}
},
{
name: 'billing unfreeze user',
desc: "remove user from account_freeze_events and reset user's limits to what is stored in account_freeze_events",
params: [['email', new InputText('email', true)]],
func: async (email: string): Promise<null> => {
return this.fetch('DELETE', `users/${email}/billing-freeze`) as Promise<null>;
}
},
{
name: 'violation freeze user',
desc: 'freeze a user for ToS violation, set limits to zero and status to pending deletion',
params: [['email', new InputText('email', true)]],
func: async (email: string): Promise<null> => {
return this.fetch('PUT', `users/${email}/violation-freeze`) as Promise<null>;
}
},
{
name: 'violation unfreeze user',
desc: "remove a user's violation freeze, reinstating their limits and status (Active)",
params: [['email', new InputText('email', true)]],
func: async (email: string): Promise<null> => {
return this.fetch('DELETE', `users/${email}/violation-freeze`) as Promise<null>;
}
},
{
name: 'legal freeze user',
desc: 'freeze a user for legal review, set limits to zero and status to legal hold',
params: [['email', new InputText('email', true)]],
func: async (email: string): Promise<null> => {
return this.fetch('PUT', `users/${email}/legal-freeze`) as Promise<null>;
}
},
{
name: 'legal unfreeze user',
desc: "remove a user's legal freeze, reinstating their limits and status (Active)",
params: [['email', new InputText('email', true)]],
func: async (email: string): Promise<null> => {
return this.fetch('DELETE', `users/${email}/legal-freeze`) as Promise<null>;
}
},
{
name: 'trial expiration freeze user',
desc: 'freeze a user for trial expiration, setting limits to zero',
params: [['email', new InputText('email', true)]],
func: async (email: string): Promise<null> => {
return this.fetch('PUT', `users/${email}/trial-expiration-freeze`) as Promise<null>;
}
},
{
name: 'trial expiration unfreeze user',
desc: "remove a user's trial expiration freeze, reinstating their limits",
params: [['email', new InputText('email', true)]],
func: async (email: string): Promise<null> => {
return this.fetch('DELETE', `users/${email}/trial-expiration-freeze`) as Promise<null>;
}
},
{
name: 'remove billing warning',
desc: "Remove the billing warning status from a user's account",
params: [['email', new InputText('email', true)]],
func: async (email: string): Promise<null> => {
return this.fetch('DELETE', `users/${email}/billing-warning`) as Promise<null>;
}
},
{
name: 'set geofencing',
desc: 'Set account level geofence for a user',
params: [
['email', new InputText('email', true)],
[
'Region',
new Select(false, true, [
{ text: 'European Union', value: 'EU' },
{ text: 'European Economic Area', value: 'EEA' },
{ text: 'United States', value: 'US' },
{ text: 'Germany', value: 'DE' },
{ text: 'No Russia and/or other sanctioned country', value: 'NR' }
])
]
],
func: async (email: string, region: string): Promise<null> => {
return this.fetch('PATCH', `users/${email}/geofence`, null, {
region
}) as Promise<null>;
},
deprecated: true
},
{
name: 'delete geofencing',
desc: 'Delete account level geofence for a user',
params: [['email', new InputText('email', true)]],
func: async (email: string): Promise<null> => {
return this.fetch('DELETE', `users/${email}/geofence`) as Promise<null>;
},
deprecated: true
},
{
name: 'update free trial expiration',
desc: `Update a date when user's free trial will end.`,
params: [
["current user's email", new InputText('email', true)],
[
'trial expiration date (date string i.e. YYYY/MM/DD or null)',
new InputText('text', true)
]
],
func: async (currentEmail: string, date: string): Promise<null> => {
return this.fetch('PATCH', `users/${currentEmail}/trial-expiration`, null, {
trialExpiration: date === 'null' ? null : this.toISOStringWithLocalTimezone(date)
}) as Promise<null>;
}
}
],
rest_api_keys: [
{
name: 'create',
desc: 'Create a REST key. The expiration format must be accepted by https://pkg.go.dev/time#ParseDuration (e.g 20d4h20s) and if it is blank the default applies',
params: [
["user's email", new InputText('text', true)],
['expiration', new InputText('text', false)]
],
func: async (useremail: string, expiration?: string): Promise<Record<string, unknown>> => {
return this.fetch('POST', `restkeys/${useremail}`, null, {
expiration
});
}
},
{
name: 'revoke',
desc: 'Revoke a REST key',
params: [['api key', new InputText('text', true)]],
func: async (apikey: string): Promise<Record<string, unknown>> => {
return this.fetch('PUT', `restkeys/${apikey}/revoke`);
}
}
]
};
private readonly baseURL: string;
constructor(baseURL: string, private readonly authToken: string = '') {
this.baseURL = baseURL.endsWith('/') ? baseURL.substring(0, baseURL.length - 1) : baseURL;
}
protected async fetch(
method: 'DELETE' | 'GET' | 'POST' | 'PUT' | 'PATCH',
path: string,
query?: string,
data?: Record<string, unknown>
): Promise<Record<string, unknown> | null> {
const url = this.apiURL(path, query);
const headers = new window.Headers();
if (this.authToken) {
headers.set('Authorization', this.authToken);
}
let body: string;
if (data) {
headers.set('Content-Type', 'application/json');
body = JSON.stringify(data);
}
const resp = await window.fetch(url, { method, headers, body });
if (!resp.ok) {
let body: Record<string, unknown>;
if (resp.headers.get('Content-Type') === 'application/json') {
body = await resp.json();
}
throw new APIError('server response error', resp.status, body);
}
if (resp.headers.get('Content-Type') === 'application/json') {
return resp.json();
}
return null;
}
protected toISOStringWithLocalTimezone(dateInput: string): string {
const date = new Date(dateInput);
// getTimezoneOffset() returns the difference in minutes between local time and UTC,
// where local time is ahead of UTC (e.g., UTC+2) it returns a negative value,
// and where local time is behind UTC (e.g., UTC-5) it returns a positive value.
const timezoneOffset = date.getTimezoneOffset() * 60000; // convert offset to milliseconds
// Adjusting the date by its own timezone offset ensures the date part remains unchanged
// when converting to the ISO string, regardless of the local timezone.
const adjustedDate = new Date(date.getTime() - timezoneOffset);
return adjustedDate.toISOString();
}
protected apiURL(path: string, query?: string): string {
path = path.startsWith('/') ? path.substring(1) : path;
if (!query) {
query = '';
} else {
query = '?' + query;
}
return `${this.baseURL}/${path}${query}`;
}
protected urlQueryFromObject(values: Record<string, boolean | number | string>): string {
const queryParts = [];
for (const name of Object.keys(values)) {
const val = values[name];
if (val === undefined) {
continue;
}
queryParts.push(`${name}=${encodeURIComponent(val)}`);
}
return queryParts.join('&');
}
protected nullToUndefined<Type>(val: Type): Type {
if (val === null) {
return undefined;
}
return val;
}
protected emptyToUndefined(s: string): string {
if (s === '') {
return undefined;
}
return s;
}
}
class APIError extends Error {
constructor(
public readonly msg: string,
public readonly responseStatusCode?: number,
public readonly responseBody?: Record<string, unknown> | string
) {
super(msg);
}
}