@sogni-ai/sogni-client 1.0.1 → 1.1.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.
- package/CHANGELOG.md +15 -0
- package/README.md +126 -0
- package/dist/Account/CurrentAccount.d.ts +4 -5
- package/dist/Account/CurrentAccount.js +9 -29
- package/dist/Account/CurrentAccount.js.map +1 -1
- package/dist/Account/index.d.ts +5 -3
- package/dist/Account/index.js +20 -9
- package/dist/Account/index.js.map +1 -1
- package/dist/Account/types.d.ts +2 -0
- package/dist/ApiClient/WebSocketClient/index.d.ts +4 -4
- package/dist/ApiClient/WebSocketClient/index.js +33 -49
- package/dist/ApiClient/WebSocketClient/index.js.map +1 -1
- package/dist/ApiClient/WebSocketClient/messages.d.ts +7 -0
- package/dist/ApiClient/index.d.ts +4 -10
- package/dist/ApiClient/index.js +26 -17
- package/dist/ApiClient/index.js.map +1 -1
- package/dist/Projects/Project.d.ts +4 -0
- package/dist/Projects/Project.js +8 -0
- package/dist/Projects/Project.js.map +1 -1
- package/dist/Projects/createJobRequestMessage.js +12 -1
- package/dist/Projects/createJobRequestMessage.js.map +1 -1
- package/dist/Projects/index.d.ts +40 -2
- package/dist/Projects/index.js +146 -14
- package/dist/Projects/index.js.map +1 -1
- package/dist/Projects/types/index.d.ts +40 -0
- package/dist/lib/AuthManager.d.ts +51 -0
- package/dist/lib/AuthManager.js +157 -0
- package/dist/lib/AuthManager.js.map +1 -0
- package/dist/lib/Cache.d.ts +9 -0
- package/dist/lib/Cache.js +30 -0
- package/dist/lib/Cache.js.map +1 -0
- package/dist/lib/RestClient.d.ts +4 -7
- package/dist/lib/RestClient.js +7 -7
- package/dist/lib/RestClient.js.map +1 -1
- package/dist/lib/utils.d.ts +8 -0
- package/dist/lib/utils.js +20 -0
- package/dist/lib/utils.js.map +1 -0
- package/dist/version.d.ts +1 -1
- package/dist/version.js +1 -1
- package/dist/version.js.map +1 -1
- package/package.json +1 -2
- package/src/Account/CurrentAccount.ts +12 -33
- package/src/Account/index.ts +18 -8
- package/src/Account/types.ts +2 -0
- package/src/ApiClient/WebSocketClient/index.ts +16 -25
- package/src/ApiClient/WebSocketClient/messages.ts +8 -0
- package/src/ApiClient/index.ts +19 -27
- package/src/Projects/Project.ts +7 -0
- package/src/Projects/createJobRequestMessage.ts +14 -1
- package/src/Projects/index.ts +150 -8
- package/src/Projects/types/index.ts +42 -0
- package/src/lib/AuthManager.ts +172 -0
- package/src/lib/Cache.ts +36 -0
- package/src/lib/RestClient.ts +8 -13
- package/src/lib/utils.ts +17 -0
- package/src/version.ts +1 -1
- package/dist/Projects/models.json +0 -8906
- package/src/Projects/models.json +0 -8906
|
@@ -0,0 +1,172 @@
|
|
|
1
|
+
import { decodeToken, decodeRefreshToken } from './utils';
|
|
2
|
+
import { ApiError, ApiErrorResponse } from '../ApiClient';
|
|
3
|
+
import { Logger } from './DefaultLogger';
|
|
4
|
+
import isNodejs from './isNodejs';
|
|
5
|
+
import Cookie from 'js-cookie';
|
|
6
|
+
import TypedEventEmitter from './TypedEventEmitter';
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* Tokens object, containing the token and refresh token
|
|
10
|
+
* @typedef {Object} Tokens
|
|
11
|
+
* @property {string} [token] - The JWT token. Optonal, if missing it will be retrieved from the server
|
|
12
|
+
* @property {string} refreshToken - The refresh token
|
|
13
|
+
*/
|
|
14
|
+
export interface Tokens {
|
|
15
|
+
token?: string;
|
|
16
|
+
refreshToken: string;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export type AuthUpdatedEvent =
|
|
20
|
+
| { token: string; refreshToken: string; walletAddress: string }
|
|
21
|
+
| { token: null; refreshToken: null; walletAddress: null };
|
|
22
|
+
|
|
23
|
+
interface AuthManagerEvents {
|
|
24
|
+
updated: AuthUpdatedEvent;
|
|
25
|
+
refreshFailed: ApiErrorResponse;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
class AuthManager extends TypedEventEmitter<AuthManagerEvents> {
|
|
29
|
+
private _token?: string;
|
|
30
|
+
private _tokenExpiresAt: Date = new Date(0);
|
|
31
|
+
private _refreshToken?: string;
|
|
32
|
+
private _refreshTokenExpiresAt: Date = new Date(0);
|
|
33
|
+
private _logger: Logger;
|
|
34
|
+
private _baseUrl: string;
|
|
35
|
+
private _walletAddress?: string;
|
|
36
|
+
private _renewTokenPromise?: Promise<string>;
|
|
37
|
+
|
|
38
|
+
constructor(baseUrl: string, logger: Logger) {
|
|
39
|
+
super();
|
|
40
|
+
this._logger = logger;
|
|
41
|
+
this._baseUrl = baseUrl;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
get refreshToken() {
|
|
45
|
+
return this._refreshToken;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
get walletAddress() {
|
|
49
|
+
return this._walletAddress;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
get isAuthenticated() {
|
|
53
|
+
return !!this._refreshToken && this._refreshTokenExpiresAt > new Date();
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
private _updateCookies() {
|
|
57
|
+
if (isNodejs) {
|
|
58
|
+
return;
|
|
59
|
+
}
|
|
60
|
+
const token = this._token;
|
|
61
|
+
if (token) {
|
|
62
|
+
Cookie.set('authorization', token, {
|
|
63
|
+
domain: '.sogni.ai',
|
|
64
|
+
expires: 1
|
|
65
|
+
});
|
|
66
|
+
} else {
|
|
67
|
+
Cookie.remove('authorization', {
|
|
68
|
+
domain: '.sogni.ai'
|
|
69
|
+
});
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
async setTokens({ refreshToken, token }: { refreshToken: string; token?: string }) {
|
|
74
|
+
if (token) {
|
|
75
|
+
this._updateTokens({ token, refreshToken });
|
|
76
|
+
return;
|
|
77
|
+
}
|
|
78
|
+
this._refreshToken = refreshToken;
|
|
79
|
+
const { expiresAt: refreshExpiresAt } = decodeRefreshToken(refreshToken);
|
|
80
|
+
this._refreshTokenExpiresAt = refreshExpiresAt;
|
|
81
|
+
await this.renewToken();
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
async getToken(): Promise<string | undefined> {
|
|
85
|
+
//If there is a token, and it is not expired, return it
|
|
86
|
+
if (this._token && this._tokenExpiresAt > new Date()) {
|
|
87
|
+
return this._token;
|
|
88
|
+
}
|
|
89
|
+
//If there is no refresh token, return undefined, to make unauthorized requests
|
|
90
|
+
if (!this._refreshToken) {
|
|
91
|
+
return;
|
|
92
|
+
}
|
|
93
|
+
//If there is a refresh token, try to renew the token
|
|
94
|
+
return this.renewToken();
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
async renewToken(): Promise<string> {
|
|
98
|
+
if (this._renewTokenPromise) {
|
|
99
|
+
return this._renewTokenPromise;
|
|
100
|
+
}
|
|
101
|
+
this._renewTokenPromise = this._renewToken();
|
|
102
|
+
this._renewTokenPromise.finally(() => {
|
|
103
|
+
this._renewTokenPromise = undefined;
|
|
104
|
+
});
|
|
105
|
+
return this._renewTokenPromise;
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
clear() {
|
|
109
|
+
// Prevent duplicate events
|
|
110
|
+
if (!this._token && !this._refreshToken) {
|
|
111
|
+
return;
|
|
112
|
+
}
|
|
113
|
+
this._refreshToken = undefined;
|
|
114
|
+
this._refreshTokenExpiresAt = new Date(0);
|
|
115
|
+
this._token = undefined;
|
|
116
|
+
this._tokenExpiresAt = new Date(0);
|
|
117
|
+
this._walletAddress = undefined;
|
|
118
|
+
this.emit('updated', { token: null, refreshToken: null, walletAddress: null });
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
private _updateTokens({ token, refreshToken }: { token: string; refreshToken: string }) {
|
|
122
|
+
// Prevent duplicate events
|
|
123
|
+
if (this._token === token && this._refreshToken === refreshToken) {
|
|
124
|
+
return;
|
|
125
|
+
}
|
|
126
|
+
this._token = token;
|
|
127
|
+
const { expiresAt, walletAddress } = decodeToken(token);
|
|
128
|
+
this._walletAddress = walletAddress;
|
|
129
|
+
this._tokenExpiresAt = expiresAt;
|
|
130
|
+
this._refreshToken = refreshToken;
|
|
131
|
+
const { expiresAt: refreshExpiresAt } = decodeRefreshToken(refreshToken);
|
|
132
|
+
this._refreshTokenExpiresAt = refreshExpiresAt;
|
|
133
|
+
this._updateCookies();
|
|
134
|
+
this.emit('updated', { token, refreshToken, walletAddress });
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
private async _renewToken(): Promise<string> {
|
|
138
|
+
if (this._refreshTokenExpiresAt < new Date()) {
|
|
139
|
+
throw new Error('Refresh token expired');
|
|
140
|
+
}
|
|
141
|
+
const url = new URL('/v1/account/refresh-token', this._baseUrl).toString();
|
|
142
|
+
const response = await fetch(url, {
|
|
143
|
+
method: 'POST',
|
|
144
|
+
headers: {
|
|
145
|
+
'Content-Type': 'application/json'
|
|
146
|
+
},
|
|
147
|
+
body: JSON.stringify({ refreshToken: this._refreshToken })
|
|
148
|
+
});
|
|
149
|
+
let responseData: any;
|
|
150
|
+
try {
|
|
151
|
+
responseData = await response.json();
|
|
152
|
+
} catch (e) {
|
|
153
|
+
this.emit('refreshFailed', {
|
|
154
|
+
status: 'error',
|
|
155
|
+
errorCode: 0,
|
|
156
|
+
message: 'Failed to parse response'
|
|
157
|
+
});
|
|
158
|
+
this._logger.error('Failed to parse response:', e);
|
|
159
|
+
throw new Error('Failed to parse response');
|
|
160
|
+
}
|
|
161
|
+
if (!response.ok) {
|
|
162
|
+
this.emit('refreshFailed', responseData);
|
|
163
|
+
this.clear();
|
|
164
|
+
throw new ApiError(response.status, responseData as ApiErrorResponse);
|
|
165
|
+
}
|
|
166
|
+
const { token, refreshToken } = responseData.data;
|
|
167
|
+
this._updateTokens({ token, refreshToken });
|
|
168
|
+
return this._token!;
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
export default AuthManager;
|
package/src/lib/Cache.ts
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
interface CacheRecord<V = any> {
|
|
2
|
+
exp: number;
|
|
3
|
+
value: V;
|
|
4
|
+
}
|
|
5
|
+
|
|
6
|
+
/** A simple memory cache implementation. */
|
|
7
|
+
export default class Cache<V = any> {
|
|
8
|
+
readonly ttl: number;
|
|
9
|
+
private data: Map<string, CacheRecord<V>> = new Map();
|
|
10
|
+
|
|
11
|
+
constructor(defaultTTL: number) {
|
|
12
|
+
this.ttl = defaultTTL;
|
|
13
|
+
setInterval(() => this.cleanup(), 10000);
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
write(key: string, value: V, ttl?: number) {
|
|
17
|
+
this.data.set(key, {
|
|
18
|
+
exp: Date.now() + (ttl || this.ttl),
|
|
19
|
+
value
|
|
20
|
+
});
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
read(key: string): V | undefined {
|
|
24
|
+
const record = this.data.get(key);
|
|
25
|
+
return record && record.exp > Date.now() ? record.value : undefined;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
private cleanup() {
|
|
29
|
+
const now = Date.now();
|
|
30
|
+
this.data.forEach((record, key) => {
|
|
31
|
+
if (record.exp < now) {
|
|
32
|
+
this.data.delete(key);
|
|
33
|
+
}
|
|
34
|
+
});
|
|
35
|
+
}
|
|
36
|
+
}
|
package/src/lib/RestClient.ts
CHANGED
|
@@ -2,30 +2,24 @@ import { ApiError, ApiErrorResponse } from '../ApiClient';
|
|
|
2
2
|
import TypedEventEmitter, { EventMap } from './TypedEventEmitter';
|
|
3
3
|
import { JSONValue } from '../types/json';
|
|
4
4
|
import { Logger } from './DefaultLogger';
|
|
5
|
-
|
|
6
|
-
export interface AuthData {
|
|
7
|
-
token: string;
|
|
8
|
-
}
|
|
5
|
+
import AuthManager from './AuthManager';
|
|
9
6
|
|
|
10
7
|
class RestClient<E extends EventMap = never> extends TypedEventEmitter<E> {
|
|
11
8
|
readonly baseUrl: string;
|
|
12
|
-
protected _auth:
|
|
9
|
+
protected _auth: AuthManager;
|
|
13
10
|
protected _logger: Logger;
|
|
14
11
|
|
|
15
|
-
constructor(baseUrl: string, logger: Logger) {
|
|
12
|
+
constructor(baseUrl: string, auth: AuthManager, logger: Logger) {
|
|
16
13
|
super();
|
|
17
14
|
this.baseUrl = baseUrl;
|
|
15
|
+
this._auth = auth;
|
|
18
16
|
this._logger = logger;
|
|
19
17
|
}
|
|
20
18
|
|
|
21
|
-
get auth():
|
|
19
|
+
get auth(): AuthManager {
|
|
22
20
|
return this._auth;
|
|
23
21
|
}
|
|
24
22
|
|
|
25
|
-
set auth(auth: AuthData | null) {
|
|
26
|
-
this._auth = auth;
|
|
27
|
-
}
|
|
28
|
-
|
|
29
23
|
private formatUrl(relativeUrl: string, query: Record<string, string> = {}): string {
|
|
30
24
|
const url = new URL(relativeUrl, this.baseUrl);
|
|
31
25
|
Object.keys(query).forEach((key) => {
|
|
@@ -34,12 +28,13 @@ class RestClient<E extends EventMap = never> extends TypedEventEmitter<E> {
|
|
|
34
28
|
return url.toString();
|
|
35
29
|
}
|
|
36
30
|
|
|
37
|
-
private request<T = JSONValue>(url: string, options: RequestInit = {}): Promise<T> {
|
|
31
|
+
private async request<T = JSONValue>(url: string, options: RequestInit = {}): Promise<T> {
|
|
32
|
+
const token = await this.auth.getToken();
|
|
38
33
|
return fetch(url, {
|
|
39
34
|
...options,
|
|
40
35
|
headers: {
|
|
41
36
|
...(options.headers || {}),
|
|
42
|
-
...(
|
|
37
|
+
...(token ? { Authorization: token } : {})
|
|
43
38
|
}
|
|
44
39
|
}).then((r) => this.processResponse(r) as T);
|
|
45
40
|
}
|
package/src/lib/utils.ts
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import { jwtDecode } from 'jwt-decode';
|
|
2
|
+
|
|
3
|
+
export function decodeToken(token: string) {
|
|
4
|
+
const data = jwtDecode<{ addr: string; env: string; iat: number; exp: number }>(token);
|
|
5
|
+
return {
|
|
6
|
+
walletAddress: data.addr,
|
|
7
|
+
expiresAt: new Date(data.exp * 1000)
|
|
8
|
+
};
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
export function decodeRefreshToken(token: string) {
|
|
12
|
+
const data = jwtDecode<{ type: string; env: string; iat: number; exp: number }>(token);
|
|
13
|
+
return {
|
|
14
|
+
env: data.env,
|
|
15
|
+
expiresAt: new Date(data.exp * 1000)
|
|
16
|
+
};
|
|
17
|
+
}
|
package/src/version.ts
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export const LIB_VERSION = "1.0.
|
|
1
|
+
export const LIB_VERSION = "1.0.0-alpha.4";
|