-
Notifications
You must be signed in to change notification settings - Fork 3
/
minisky.js
300 lines (232 loc) · 7.72 KB
/
minisky.js
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
/**
* Thrown when status code of an API response is not "success".
*/
class APIError extends Error {
/** @param {number} code, @param {json} json */
constructor(code, json) {
super("APIError status " + code + "\n\n" + JSON.stringify(json));
this.code = code;
this.json = json;
}
}
/**
* Thrown when authentication is needed, but access token is invalid or missing.
*/
class AuthError extends Error {}
/**
* Thrown when DID or DID document is invalid.
*/
class DIDError extends Error {}
/**
* Base API client for connecting to an ATProto XRPC API.
*/
class Minisky {
/** @param {string} did, @returns {Promise<string>} */
static async pdsEndpointForDid(did) {
let url;
if (did.startsWith('did:plc:')) {
url = new URL(`https://plc.directory/${did}`);
} else if (did.startsWith('did:web:')) {
let host = did.replace(/^did:web:/, '');
url = new URL(`https://${host}/.well-known/did.json`);
} else {
throw new DIDError("Unknown DID type: " + did);
}
let response = await fetch(url);
let text = await response.text();
let json = text.trim().length > 0 ? JSON.parse(text) : undefined;
if (response.status == 200) {
let service = (json.service || []).find(s => s.id == '#atproto_pds');
if (service) {
return service.serviceEndpoint.replace('https://', '');
} else {
throw new DIDError("Missing #atproto_pds service definition");
}
} else {
throw new APIError(response.status, json);
}
}
/**
* @typedef {object} MiniskyOptions
* @prop {boolean} [sendAuthHeaders]
* @prop {boolean} [autoManageTokens]
*
* @typedef {object} MiniskyConfig
* @prop {json | null | undefined} user
* @prop {() => void} save
*
* @param {string | undefined} host
* @param {MiniskyConfig | null | undefined} [config]
* @param {MiniskyOptions} [options]
*/
constructor(host, config, options) {
this.host = host;
this.config = config;
this.user = /** @type {json} */ (config?.user);
this.sendAuthHeaders = !!this.user;
this.autoManageTokens = !!this.user;
if (options) {
Object.assign(this, options);
}
}
/** @returns {string} */
get baseURL() {
if (this.host) {
let host = (this.host.includes('://')) ? this.host : `https://${this.host}`;
return host + '/xrpc';
} else {
throw new AuthError('Hostname not set');
}
}
/** @returns {boolean} */
get isLoggedIn() {
return !!(this.user && this.user.accessToken && this.user.refreshToken && this.user.did && this.user.pdsEndpoint);
}
/**
* @typedef {object} MiniskyRequestOptions
* @prop {string | boolean} [auth]
* @prop {Record<string, string>} [headers]
*
* @param {string} method, @param {json | null} [params], @param {MiniskyRequestOptions} [options]
* @returns {Promise<json>}
*/
async getRequest(method, params, options) {
let url = new URL(`${this.baseURL}/${method}`);
let auth = options && ('auth' in options) ? options.auth : this.sendAuthHeaders;
if (this.autoManageTokens && auth === true) {
await this.checkAccess();
}
if (params) {
for (let p in params) {
if (params[p] instanceof Array) {
params[p].forEach(x => url.searchParams.append(p, x));
} else {
url.searchParams.append(p, params[p]);
}
}
}
let headers = this.authHeaders(auth);
if (options && options.headers) {
Object.assign(headers, options.headers);
}
let response = await fetch(url, { headers: headers });
return await this.parseResponse(response);
}
/**
* @param {string} method, @param {json | null} [data], @param {MiniskyRequestOptions} [options]
* @returns Promise<json>
*/
async postRequest(method, data, options) {
let url = `${this.baseURL}/${method}`;
let auth = options && ('auth' in options) ? options.auth : this.sendAuthHeaders;
if (this.autoManageTokens && auth === true) {
await this.checkAccess();
}
let request = { method: 'POST', headers: this.authHeaders(auth) };
if (data) {
request.body = JSON.stringify(data);
request.headers['Content-Type'] = 'application/json';
}
if (options && options.headers) {
Object.assign(request.headers, options.headers);
}
let response = await fetch(url, request);
return await this.parseResponse(response);
}
/** @param {string | boolean} auth, @returns {Record<string, string>} */
authHeaders(auth) {
if (typeof auth == 'string') {
return { 'Authorization': `Bearer ${auth}` };
} else if (auth) {
if (this.user?.accessToken) {
return { 'Authorization': `Bearer ${this.user.accessToken}` };
} else {
throw new AuthError("Can't send auth headers, access token is missing");
}
} else {
return {};
}
}
/** @param {string} token, @returns {number} */
tokenExpirationTimestamp(token) {
let parts = token.split('.');
if (parts.length != 3) {
throw new AuthError("Invalid access token format");
}
let payload = JSON.parse(atob(parts[1]));
let exp = payload.exp;
if (!(exp && typeof exp == 'number' && exp > 0)) {
throw new AuthError("Invalid token expiry data");
}
return exp * 1000;
}
/** @param {Response} response, @param {json} json, @returns {boolean} */
isInvalidToken(response, json) {
return (response.status == 400) && !!json && ['InvalidToken', 'ExpiredToken'].includes(json.error);
}
/** @param {Response} response, @returns {Promise<json>} */
async parseResponse(response) {
let text = await response.text();
let json = text.trim().length > 0 ? JSON.parse(text) : undefined;
if (response.status == 200) {
return json;
} else {
throw new APIError(response.status, json);
}
}
/** @returns {Promise<void>} */
async checkAccess() {
if (!this.isLoggedIn) {
throw new AuthError("Not logged in");
}
let expirationTimestamp = this.tokenExpirationTimestamp(this.user.accessToken);
if (expirationTimestamp < new Date().getTime() + 60 * 1000) {
await this.performTokenRefresh();
}
}
/** @param {string} handle, @param {string} password, @returns {Promise<json>} */
async logIn(handle, password) {
if (!this.config || !this.config.user) {
throw new AuthError("Missing user configuration object");
}
let params = { identifier: handle, password: password };
let json = await this.postRequest('com.atproto.server.createSession', params, { auth: false });
this.saveTokens(json);
return json;
}
/** @returns {Promise<json>} */
async performTokenRefresh() {
if (!this.isLoggedIn) {
throw new AuthError("Not logged in");
}
console.log('Refreshing access token…');
let json = await this.postRequest('com.atproto.server.refreshSession', null, { auth: this.user.refreshToken });
this.saveTokens(json);
return json;
}
/** @param {json} json */
saveTokens(json) {
if (!this.config || !this.config.user) {
throw new AuthError("Missing user configuration object");
}
this.user.accessToken = json['accessJwt'];
this.user.refreshToken = json['refreshJwt'];
this.user.did = json['did'];
if (json.didDoc?.service) {
let service = json.didDoc.service.find(s => s.id == '#atproto_pds');
this.host = service.serviceEndpoint.replace('https://', '');
}
this.user.pdsEndpoint = this.host;
this.config.save();
}
resetTokens() {
if (!this.config || !this.config.user) {
throw new AuthError("Missing user configuration object");
}
delete this.user.accessToken;
delete this.user.refreshToken;
delete this.user.did;
delete this.user.pdsEndpoint;
this.config.save();
}
}