@super-protocol/sp-cli 0.0.2-alpha.1 → 0.0.2-beta.10

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 (51) hide show
  1. package/README.md +145 -260
  2. package/dist/commands/account/info.d.ts +21 -0
  3. package/dist/commands/account/info.js +43 -0
  4. package/dist/commands/auth/login.d.ts +2 -10
  5. package/dist/commands/auth/login.js +25 -75
  6. package/dist/commands/base.d.ts +2 -4
  7. package/dist/commands/base.js +8 -10
  8. package/dist/commands/config/add.js +9 -5
  9. package/dist/commands/config/base.d.ts +4 -3
  10. package/dist/commands/config/base.js +12 -14
  11. package/dist/commands/config/create.js +4 -4
  12. package/dist/commands/config/list.js +2 -2
  13. package/dist/commands/config/use.js +5 -3
  14. package/dist/commands/files/download.d.ts +15 -0
  15. package/dist/commands/files/download.js +53 -0
  16. package/dist/commands/files/upload.d.ts +18 -0
  17. package/dist/commands/files/upload.js +77 -0
  18. package/dist/commands/storage/base.d.ts +13 -0
  19. package/dist/commands/storage/base.js +123 -0
  20. package/dist/commands/storage/create.d.ts +11 -0
  21. package/dist/commands/storage/create.js +53 -0
  22. package/dist/commands/storage/select.d.ts +9 -0
  23. package/dist/commands/storage/select.js +46 -0
  24. package/dist/commands/storage/update.d.ts +14 -0
  25. package/dist/commands/storage/update.js +187 -0
  26. package/dist/config/config-file.schema.d.ts +4 -4
  27. package/dist/config/config-file.schema.js +1 -1
  28. package/dist/config/config.schema.d.ts +16 -15
  29. package/dist/config/config.schema.js +2 -10
  30. package/dist/config/resource.schema.d.ts +31 -0
  31. package/dist/config/resource.schema.js +14 -0
  32. package/dist/constants.d.ts +2 -0
  33. package/dist/constants.js +2 -0
  34. package/dist/errors.d.ts +2 -0
  35. package/dist/errors.js +2 -0
  36. package/dist/lib/container.d.ts +6 -7
  37. package/dist/lib/container.js +26 -26
  38. package/dist/managers/account-manager.js +13 -3
  39. package/dist/managers/config-file-manager.d.ts +1 -1
  40. package/dist/managers/config-file-manager.js +13 -8
  41. package/dist/middlewares/auth-middleware.js +5 -1
  42. package/dist/services/auth.service.d.ts +24 -0
  43. package/dist/services/auth.service.js +93 -0
  44. package/dist/services/storage.service.d.ts +71 -0
  45. package/dist/services/storage.service.js +308 -0
  46. package/dist/utils/helper.d.ts +5 -0
  47. package/dist/utils/helper.js +22 -0
  48. package/dist/utils/progress.d.ts +8 -0
  49. package/dist/utils/progress.js +27 -0
  50. package/oclif.manifest.json +368 -131
  51. package/package.json +12 -6
@@ -17,7 +17,6 @@ export class AppContainer {
17
17
  initQueue = new Map();
18
18
  logger;
19
19
  runtimeConfigFile;
20
- runtimeProviderUrl;
21
20
  constructor(cwdDir, oclifConfig) {
22
21
  this.cwdDir = cwdDir;
23
22
  this.oclifConfig = oclifConfig;
@@ -61,9 +60,10 @@ export class AppContainer {
61
60
  }
62
61
  async build() {
63
62
  await Promise.all(this.initPromises);
63
+ return this;
64
64
  }
65
- initAccountManager() {
66
- this.initConfigManager();
65
+ initAccountManager(rebuild = true) {
66
+ this.initConfigManager(rebuild);
67
67
  return this.queueInit('accountManager', async () => {
68
68
  await this.waitFor('configManager');
69
69
  if (this._accountManager) {
@@ -73,9 +73,9 @@ export class AppContainer {
73
73
  const accountManager = new AccountManager(this.configManager, this.logger);
74
74
  await accountManager.init();
75
75
  this._accountManager = accountManager;
76
- });
76
+ }, rebuild);
77
77
  }
78
- initConfigFileManager() {
78
+ initConfigFileManager(rebuild = false) {
79
79
  return this.queueInit('configFileManager', async () => {
80
80
  if (this._configFileManager) {
81
81
  return;
@@ -85,10 +85,10 @@ export class AppContainer {
85
85
  });
86
86
  await configFileManager.init();
87
87
  this._configFileManager = configFileManager;
88
- });
88
+ }, rebuild);
89
89
  }
90
- initConfigManager() {
91
- this.initConfigFileManager();
90
+ initConfigManager(rebuild = false) {
91
+ this.initConfigFileManager(rebuild);
92
92
  return this.queueInit('configManager', async () => {
93
93
  await this.waitFor('configFileManager');
94
94
  if (this._configManager) {
@@ -102,22 +102,32 @@ export class AppContainer {
102
102
  const configManager = new ConfigManager(configFilePath, this.logger);
103
103
  await configManager.init();
104
104
  this._configManager = configManager;
105
- });
105
+ }, rebuild);
106
106
  }
107
- initProviderClient({ enableAuth = true, enableCookies = true } = {}) {
107
+ initProviderClient({ enableAuth = true, enableCookies = true, rebuild = false } = {}) {
108
108
  this.initConfigManager();
109
109
  return this.queueInit('providerClient', async () => {
110
- if (this._providerClient) {
110
+ if (this._providerClient && !rebuild) {
111
111
  return;
112
112
  }
113
113
  await this.waitFor('configManager');
114
- const providerUrl = this.runtimeProviderUrl || await this.configManager.get('providerUrl') || PROVIDER_URL;
114
+ const providerUrl = await this.configManager.get('providerUrl') || PROVIDER_URL;
115
115
  this.logger.info('Initializing provider client');
116
116
  const providerClient = createProviderClient({
117
117
  baseUrl: providerUrl,
118
118
  logger: this.logger,
119
119
  middlewares: [requestIdMiddleware, loggerMiddleware],
120
120
  });
121
+ if (enableCookies) {
122
+ this.logger.info('Initializing cookie middleware');
123
+ const cookiesMiddleware = await createCookieMiddleware(this.configManager, this.logger, providerUrl);
124
+ providerClient.use(cookiesMiddleware);
125
+ }
126
+ if (enableAuth) {
127
+ this.logger.info('Initializing auth middleware');
128
+ const authMiddleware = await createAuthMiddleware(this.configManager, providerClient, this.logger);
129
+ providerClient.use(authMiddleware);
130
+ }
121
131
  providerClient.use({
122
132
  onRequest: async ({ request }) => {
123
133
  const req = request.clone();
@@ -128,28 +138,18 @@ export class AppContainer {
128
138
  }
129
139
  this.logger.debug({
130
140
  body,
141
+ token: req.headers.get('Authorization'),
131
142
  url: req.url,
132
143
  }, 'Requesting');
133
144
  },
134
145
  });
135
- if (enableCookies) {
136
- this.logger.info('Initializing cookie middleware');
137
- const cookiesMiddleware = await createCookieMiddleware(this.configManager, this.logger, providerUrl);
138
- providerClient.use(cookiesMiddleware);
139
- }
140
- if (enableAuth) {
141
- this.logger.info('Initializing auth middleware');
142
- const authMiddleware = await createAuthMiddleware(this.configManager, providerClient, this.logger);
143
- providerClient.use(authMiddleware);
144
- }
145
146
  this._providerClient = providerClient;
146
- });
147
+ }, rebuild);
147
148
  }
148
149
  setupRuntimeConfig(config) {
149
150
  if (this.initQueue.size > 0) {
150
151
  throw new Error('Cannot change runtime config after initialization has started');
151
152
  }
152
- this.runtimeProviderUrl = config.url;
153
153
  if (config.configFile) {
154
154
  this.runtimeConfigFile = path.isAbsolute(config.configFile)
155
155
  ? config.configFile
@@ -160,8 +160,8 @@ export class AppContainer {
160
160
  }
161
161
  return this;
162
162
  }
163
- queueInit(name, task) {
164
- if (!this.initQueue.has(name)) {
163
+ queueInit(name, task, force = false) {
164
+ if (!this.initQueue.has(name) || force) {
165
165
  const promise = task();
166
166
  this.initQueue.set(name, promise);
167
167
  this.initPromises.push(promise);
@@ -4,9 +4,9 @@ var __decorate = (this && this.__decorate) || function (decorators, target, key,
4
4
  else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
5
5
  return c > 3 && r && Object.defineProperty(target, key, r), r;
6
6
  };
7
- import { confirm, password } from '@inquirer/prompts';
7
+ import { confirm, isCancel, password } from '@clack/prompts';
8
8
  import { ux } from '@oclif/core';
9
- import { Value } from '@sinclair/typebox/value';
9
+ import { Value } from 'typebox/value';
10
10
  import { Retryable } from 'typescript-retry-decorator';
11
11
  import { generatePrivateKey, privateKeyToAccount } from 'viem/accounts';
12
12
  import { accountSchema } from '../config/config.schema.js';
@@ -69,6 +69,9 @@ export class AccountManager {
69
69
  const ask = await confirm({
70
70
  message: 'Do you want to create new one?',
71
71
  });
72
+ if (isCancel(ask)) {
73
+ ux.error('Operation cancelled.', { exit: 1 });
74
+ }
72
75
  if (ask) {
73
76
  await this.promptAccount();
74
77
  }
@@ -81,8 +84,15 @@ export class AccountManager {
81
84
  const askPrivateKey = await confirm({
82
85
  message: 'Do you want to input privateKey?',
83
86
  });
87
+ if (isCancel(askPrivateKey)) {
88
+ ux.error('Operation cancelled.', { exit: 1 });
89
+ }
84
90
  if (askPrivateKey) {
85
- const privateKey = await password({ message: 'Please input your privateKey for using in account' });
91
+ const privateKeyInput = await password({ message: 'Please input your privateKey for using in account' });
92
+ if (isCancel(privateKeyInput)) {
93
+ ux.error('Operation cancelled.', { exit: 1 });
94
+ }
95
+ const privateKey = privateKeyInput.trim();
86
96
  try {
87
97
  const account = await this.createFromKey(privateKey);
88
98
  ux.stdout('Your privateKey will be used in config. Keypair created');
@@ -1,4 +1,4 @@
1
- import { confirm, select } from '@inquirer/prompts';
1
+ import { confirm, select } from '@clack/prompts';
2
2
  import { ux } from '@oclif/core';
3
3
  import pino from 'pino';
4
4
  import { CliConfig } from '../config/config.schema.js';
@@ -1,8 +1,8 @@
1
- import { confirm, select } from '@inquirer/prompts';
1
+ import { confirm, isCancel, select } from '@clack/prompts';
2
2
  import { ux } from '@oclif/core';
3
- import { Value } from '@sinclair/typebox/value';
4
3
  import * as fs from 'node:fs';
5
4
  import path from 'node:path';
5
+ import { Value } from 'typebox/value';
6
6
  import { cliConfigSchema } from '../config/config.schema.js';
7
7
  import { DIR_ACCESS_PERMS, FILE_ACCESS_PERMS } from '../constants.js';
8
8
  import { getConfigName } from '../utils/helper.js';
@@ -78,22 +78,27 @@ export class ConfigFileManager {
78
78
  configToDelete = config.file;
79
79
  }
80
80
  else {
81
- configToDelete = await this.selectPrompt({
82
- choices: configs.map(config => ({
83
- name: config.name,
81
+ const selection = await this.selectPrompt({
82
+ message: 'Select configuration to delete:',
83
+ options: configs.map(config => ({
84
+ label: config.name,
84
85
  value: config.file,
85
86
  })),
86
- message: 'Select configuration to delete:',
87
87
  });
88
+ if (isCancel(selection)) {
89
+ this.ux.stdout('Deletion cancelled');
90
+ return;
91
+ }
92
+ configToDelete = selection;
88
93
  }
89
94
  const configToDeleteData = configs.find(c => c.file === configToDelete);
90
95
  const displayName = configToDeleteData?.name || configToDelete;
91
96
  if (!force) {
92
97
  const confirmed = await this.confirmPrompt({
93
- default: false,
98
+ initialValue: false,
94
99
  message: `Are you sure you want to delete configuration "${displayName}"?`,
95
100
  });
96
- if (!confirmed) {
101
+ if (isCancel(confirmed) || !confirmed) {
97
102
  this.ux.stdout('Deletion cancelled');
98
103
  return;
99
104
  }
@@ -1,4 +1,5 @@
1
1
  import { decode } from 'jsonwebtoken';
2
+ import { REFRESH_TOKEN_URI } from '../constants.js';
2
3
  import { AuthorizationRequiredError } from '../errors.js';
3
4
  function isAccessKeyExpired(accessKey) {
4
5
  try {
@@ -23,7 +24,7 @@ export async function createAuthMiddleware(configManager, providerClient, logger
23
24
  logger.info('Performed refresh token');
24
25
  let refreshResult;
25
26
  try {
26
- refreshResult = await providerClient.POST('/api/auth/refresh-access');
27
+ refreshResult = await providerClient.POST(REFRESH_TOKEN_URI);
27
28
  }
28
29
  catch (error) {
29
30
  logger.error({ err: error }, 'failure refresh token');
@@ -76,6 +77,9 @@ export async function createAuthMiddleware(configManager, providerClient, logger
76
77
  }
77
78
  const middleware = {
78
79
  async onRequest({ request }) {
80
+ if (request.url.endsWith(REFRESH_TOKEN_URI)) {
81
+ return request;
82
+ }
79
83
  const accessToken = await ensureAccessKey();
80
84
  if (accessToken) {
81
85
  request.headers.set('Authorization', `Bearer ${accessToken}`);
@@ -0,0 +1,24 @@
1
+ import { ProviderClient } from '@super-protocol/provider-client';
2
+ import pino from 'pino';
3
+ import { AccountManager } from '../managers/account-manager.js';
4
+ import { ConfigManager } from '../managers/config-manager.js';
5
+ export declare class AuthError extends Error {
6
+ }
7
+ export declare class AuthService {
8
+ private readonly accountManager;
9
+ private readonly configManager;
10
+ private readonly providerClient;
11
+ private readonly logger;
12
+ constructor(accountManager: AccountManager, configManager: ConfigManager, providerClient: ProviderClient, logger: pino.BaseLogger);
13
+ auth(): Promise<void>;
14
+ getTokens(nonce: string): Promise<void>;
15
+ getUserNonce(address: string): Promise<{
16
+ error: {
17
+ message: string;
18
+ statusCode: number;
19
+ } | undefined;
20
+ user: {
21
+ nonce?: string;
22
+ } | undefined;
23
+ }>;
24
+ }
@@ -0,0 +1,93 @@
1
+ export class AuthError extends Error {
2
+ }
3
+ export class AuthService {
4
+ accountManager;
5
+ configManager;
6
+ providerClient;
7
+ logger;
8
+ constructor(accountManager, configManager, providerClient, logger) {
9
+ this.accountManager = accountManager;
10
+ this.configManager = configManager;
11
+ this.providerClient = providerClient;
12
+ this.logger = logger;
13
+ }
14
+ async auth() {
15
+ const address = this.accountManager.getAddress();
16
+ const { error: nonceError, user } = await this.getUserNonce(address);
17
+ if (nonceError && nonceError.statusCode === 404) {
18
+ this.logger.debug('Nonce error call sign up');
19
+ const { data: nonceResponse, error: signUpError } = await this.providerClient.POST('/api/auth/sign-up', {
20
+ body: {
21
+ address,
22
+ },
23
+ });
24
+ if (signUpError && signUpError.statusCode === 409) {
25
+ this.logger.debug({ signUpError }, 'Error signing up');
26
+ const { error: nonceError, user } = await this.getUserNonce(address);
27
+ this.logger.debug({ nonceError, user }, 'Requesting nonce again');
28
+ if (user && user.nonce) {
29
+ await this.getTokens(user.nonce);
30
+ }
31
+ else {
32
+ throw new AuthError('User exists but nonce is unavailable. Please try again or contact support.');
33
+ }
34
+ }
35
+ else if (signUpError) {
36
+ this.logger.error({ signUpError }, 'Sign-up failed');
37
+ throw new AuthError('Sign-up failed. Please try again later.');
38
+ }
39
+ else {
40
+ const nonce = nonceResponse?.nonce;
41
+ if (!nonce) {
42
+ this.logger.error({ response: nonceResponse }, 'Unexpected sign-up response');
43
+ throw new AuthError('Provider did not return a nonce.');
44
+ }
45
+ await this.getTokens(nonce);
46
+ }
47
+ }
48
+ else if (user && user.nonce) {
49
+ this.logger.debug({ user }, 'Requesting for existed user');
50
+ await this.getTokens(user.nonce);
51
+ }
52
+ else {
53
+ throw new AuthError('Unable to retrieve authentication nonce. Please try again later or contact support if the issue persists.');
54
+ }
55
+ }
56
+ async getTokens(nonce) {
57
+ const signature = await this.accountManager.createSign(nonce);
58
+ const { data: tokenResponse, error, } = await this.providerClient.POST('/api/auth/token', {
59
+ body: {
60
+ address: this.accountManager.getAddress(),
61
+ provider: 'sp-cli',
62
+ signature,
63
+ },
64
+ });
65
+ if (error) {
66
+ this.logger.error({ err: error }, 'Token exchange failed');
67
+ throw new AuthError(error.message);
68
+ }
69
+ const { accessToken } = tokenResponse || {};
70
+ if (!accessToken) {
71
+ this.logger.error({ response: tokenResponse }, 'Unexpected token response');
72
+ throw new AuthError('Provider returned an unexpected token response.');
73
+ }
74
+ await this.configManager.setCredentials({ accessKey: accessToken });
75
+ }
76
+ async getUserNonce(address) {
77
+ try {
78
+ const { data, error } = await this.providerClient.GET('/api/users/nonce/{address}', {
79
+ params: {
80
+ path: {
81
+ address,
82
+ },
83
+ },
84
+ });
85
+ this.logger.debug({ data, error }, 'Getting user nonce');
86
+ return { error, user: data };
87
+ }
88
+ catch (error) {
89
+ this.logger.error({ err: error }, 'Error request nonce');
90
+ throw new AuthError('Connection failure, please try again later');
91
+ }
92
+ }
93
+ }
@@ -0,0 +1,71 @@
1
+ import { EncryptionWithIV, Resource, RuntimeInputInfo } from '@super-protocol/dto-js';
2
+ import { AddStorageDto, ProviderClient, StorageResponseDto, UpdateStorageDto } from '@super-protocol/provider-client';
3
+ import pino from 'pino';
4
+ export declare class StorageError extends Error {
5
+ }
6
+ export declare class StoragesUndefinedError extends StorageError {
7
+ }
8
+ export declare class StorageCreateError extends StorageError {
9
+ }
10
+ export declare class StorageUpdateError extends StorageError {
11
+ }
12
+ export declare class StorageGetError extends StorageError {
13
+ }
14
+ type IUploadParams = {
15
+ localPath: string;
16
+ maximumConcurrent?: number;
17
+ metadataPath?: string;
18
+ outputPath?: string;
19
+ remotePath?: string;
20
+ sync?: boolean;
21
+ withEncryption: boolean;
22
+ };
23
+ type IDownloadParams = {
24
+ downloadPath: string;
25
+ maximumConcurrent?: number;
26
+ resourcePath: string;
27
+ };
28
+ export type ResourceFile = Partial<Pick<RuntimeInputInfo, 'args' | 'hardwareContext' | 'hash' | 'signatureKeyHash'>> & {
29
+ encryption?: EncryptionWithIV;
30
+ resource: Resource;
31
+ };
32
+ type ProgressCb = (arg: {
33
+ current: number;
34
+ key: string;
35
+ total: number;
36
+ }) => void;
37
+ export declare const generateExternalId: () => string;
38
+ export declare class StorageService {
39
+ private readonly providerClient;
40
+ private readonly logger;
41
+ constructor(providerClient: ProviderClient, logger: pino.BaseLogger);
42
+ createStorage(storage: AddStorageDto): Promise<StorageResponseDto>;
43
+ download(params: IDownloadParams, progressCb: ProgressCb): Promise<void>;
44
+ getCentralizedStorage(): Promise<StorageResponseDto>;
45
+ getCurrentStorage(): Promise<StorageResponseDto>;
46
+ hasStorage(): Promise<boolean>;
47
+ initCentralizedStorage(): Promise<{
48
+ bucket: string;
49
+ createdAt: string;
50
+ id: string;
51
+ isCentralized: boolean;
52
+ prefix: string;
53
+ s3Credentials?: import("@super-protocol/provider-client").components["schemas"]["S3CredentialsResponseDto"];
54
+ storageType: import("@super-protocol/provider-client").components["schemas"]["StorageType"];
55
+ storjCredentials?: import("@super-protocol/provider-client").components["schemas"]["StorJCredentialsResponseDto"];
56
+ updatedAt: string;
57
+ userId: string;
58
+ }>;
59
+ requestStorages(): Promise<StorageResponseDto[]>;
60
+ saveStorage(selectedStorage: string): Promise<{
61
+ activeStorageId: string;
62
+ createdAt: string;
63
+ decentralizedStorageId?: string;
64
+ id: string;
65
+ updatedAt: string;
66
+ userId: string;
67
+ }>;
68
+ updateStorage(id: string, storage: UpdateStorageDto): Promise<StorageResponseDto>;
69
+ upload(params: IUploadParams, progressCb: ProgressCb): Promise<void>;
70
+ }
71
+ export {};