This repository has been archived by the owner on Nov 12, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathego-upload.ts
executable file
·403 lines (375 loc) · 11.5 KB
/
ego-upload.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
#!/usr/bin/env -S deno run --ext ts --allow-env=EGO_USERNAME,EGO_PASSWORD --allow-net=extensions.gnome.org
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
import { basename, extname } from "jsr:@std/path@1";
import { Confirm, Input, Secret } from "jsr:@cliffy/[email protected]";
import { Command } from "jsr:@cliffy/[email protected]";
import { CompletionsCommand } from "jsr:@cliffy/[email protected]/completions";
const VERSION = "1.2.1";
/**
* An error returned by the API.
*/
class APIStatusError extends Error {
constructor(
/**
* The status code returned in response to the API request.
*/
readonly status: number,
/**
* The detail string returned in the response body.
*/
readonly detail: APIDetailResponse,
options?: ErrorOptions,
) {
super(
`API request failed with status ${status}: ${detail.detail}`,
options,
);
}
}
/**
* Read data from an API response.
*
* This function does not validate the shape of response data.
*
* @param response The response to read data from
* @tparam T The type of response data
* @throws APIStatusError If `response` does not have an OK status code
* @returns The body of `response`, decoded from JSON and cast to `T`
*/
const readAPIResponse = async <T>(response: Response): Promise<T> => {
const data = await response.json();
if (!response.ok) {
throw new APIStatusError(response.status, data as APIDetailResponse);
} else {
return data as T;
}
};
/** User authentication for EGO. */
interface UserAuthentication {
readonly username: string;
readonly password: string;
}
interface APIDetailResponse {
readonly detail?: string;
}
interface APIToken {
readonly token: string;
}
interface APITokenResponse extends APIDetailResponse {
readonly token: APIToken;
}
/**
* Login with the given authentication data.
*
* @param auth The authentication to use
* @return The authentication token to use for further API requests
*/
const login = async (auth: UserAuthentication): Promise<string> => {
const response = await fetch(
"https://extensions.gnome.org/api/v1/accounts/login/",
{
method: "POST",
headers: {
"Content-Type": "application/json",
"Accept": "application/json",
},
body: JSON.stringify({
login: auth.username,
password: auth.password,
}),
},
);
try {
return (await readAPIResponse<APITokenResponse>(response)).token.token;
} catch (cause) {
throw new Error("Login failed", { cause });
}
};
const authorizationHeader = (token: string): Record<string, string> => ({
"Authorization": `Token ${token}`,
});
const logout = async (token: string): Promise<void> => {
const response = await fetch(
"https://extensions.gnome.org/api/v1/accounts/logout/",
{
method: "POST",
headers: {
"Content-Type": "application/json",
"Accept": "application/json",
...authorizationHeader(token),
},
body: JSON.stringify({
revoke_token: true,
}),
},
);
try {
return readAPIResponse<void>(response);
} catch (cause) {
throw new Error("Logout failed", { cause });
}
};
class InvalidUploadError extends Error {
constructor(readonly errors: readonly string[]) {
super(errors[0]);
}
}
interface UploadedExtension {
readonly extension: string;
readonly version: number;
}
const upload = async (
token: string,
path: string,
): Promise<UploadedExtension> => {
const body = new FormData();
body.append("shell_license_compliant", "true");
body.append("tos_compliant", "true");
const dataBlob = new Blob([await Deno.readFile(path)], {
type: "application/zip",
});
body.append("source", dataBlob, basename(path));
const response = await fetch(
"https://extensions.gnome.org/api/v1/extensions",
{
method: "POST",
headers: {
"Accept": "application/json",
...authorizationHeader(token),
},
body,
},
);
try {
return readAPIResponse<UploadedExtension>(response);
} catch (cause) {
throw new Error("Upload failed", { cause });
}
};
interface ExtensionMetadata {
readonly id: number;
readonly uuid: string;
}
const queryExtension = async (
token: string,
uuid: string,
): Promise<ExtensionMetadata> => {
const response = await fetch(
`https://extensions.gnome.org/api/v1/extensions/${uuid}/`,
{
headers: {
"Accept": "application/json",
...authorizationHeader(token),
},
},
);
try {
return readAPIResponse<ExtensionMetadata>(response);
} catch (cause) {
throw new Error("Failed to query extension metadata", { cause });
}
};
/**
* Prompts the user has to confirm in order to upload an extension.
*/
interface ConfirmationPrompts {
// deno-lint-ignore camelcase -- External entity with given names
readonly shell_license_compliant: string;
// deno-lint-ignore camelcase -- External entity with given names
readonly tos_compliant: string;
}
/**
* Fetch confirmation prompts.
*
* Fetch prompts the user has to confirm in order to upload an extension.
*
* @returns A map of field names to human-readable prompts to confirm.
*/
const fetchConfirmationPrompts = async (): Promise<ConfirmationPrompts> => {
// We can find the prompt texts as field titles in the API schema definition,
// so let's fetch the schema.
const response = await fetch("https://extensions.gnome.org/api/schema/", {
headers: {
"Accept": "application/json",
},
});
const data = await response.json();
const uploadComponent = data.components.schemas.ExtensionUpload;
const getPrompt = (field: keyof ConfirmationPrompts): string => {
const prompt = uploadComponent.properties[field].title;
if (typeof prompt !== "string") {
throw new Error(`Failed to find confirmation prompt for field ${field}`);
}
return prompt;
};
return {
shell_license_compliant: getPrompt("shell_license_compliant"),
tos_compliant: getPrompt("tos_compliant"),
};
};
/**
* Ask the user to confirm all prompts required to upload an extension.
*
* @param confirmationPrompts Prompts to confirm.
* @returns Whether all prompts where confirmed.
*/
const promptForConfirmation = async (
confirmationPrompts: ConfirmationPrompts,
): Promise<boolean> => {
const fields: (keyof ConfirmationPrompts)[] = [
"shell_license_compliant",
"tos_compliant",
];
for (const field of fields) {
// deno-lint-ignore no-await-in-loop -- We deliberately show one prompt after another
if (!await Confirm.prompt(confirmationPrompts[field])) {
return false;
}
}
return true;
};
/**
* Load confirmed prompts from a file.
*
* @param path The path with stored confirmations.
* @returns A record mapping field names to confirmed prompts
*/
const loadConfirmations = async (
path: string,
): Promise<Record<string, unknown>> => {
const permission = await Deno.permissions.request({ name: "read", path });
if (permission.state !== "granted") {
throw new Error(`Permission to read confirmations from ${path} denied`);
}
const contents = JSON.parse(
new TextDecoder().decode(await Deno.readFile(path)),
);
if (typeof contents === "object" && !Array.isArray(contents)) {
return contents;
} else {
console.warn("Ignoring unexpected confirmations:", contents);
return {};
}
};
/**
* Verify that the user has confirmed all required prompts to upload an extension.
*
* @param confirmedPrompts Pre-confirmed prompts if any
* @returns Whether the user has confirmed all required upload prompts, either directly or ahead of time.
*/
const verifyConfirmedPrompts = async (
confirmedPrompts: Record<string, unknown> | null,
): Promise<boolean> => {
const prompts = await fetchConfirmationPrompts();
if (confirmedPrompts === null) {
return await promptForConfirmation(prompts);
} else {
const fields: (keyof ConfirmationPrompts)[] = [
"shell_license_compliant",
"tos_compliant",
];
return fields.every((field) => confirmedPrompts[field] === prompts[field]);
}
};
/**
* Prompt for any missing part in the given authentication.
*
* @param auth Partial authentication information
* @returns Full authentication information with values supplied by the user as needed.
*/
const promptForMissingAuth = async (
auth: Partial<UserAuthentication>,
): Promise<UserAuthentication> => {
const username = auth.username ?? (await Input.prompt("Your e.g.o username"));
const password = auth.password ??
(await Secret.prompt(`e.g.o password for ${username}`));
return { username, password };
};
/**
* Main entry point
*/
const main = async () =>
await new Command()
.name("ego-upload")
.version(VERSION)
.description("Upload GNOME extensions to extensions.gnome.org")
.arguments("<zip-file:file>")
.env("EGO_USERNAME=<username:string>", "Your e.g.o username", {
prefix: "EGO_",
})
.env("EGO_PASSWORD=<password:string>", "Your e.g.o password", {
prefix: "EGO_",
})
.option("-u, --username <username:string>", "Your e.g.o username")
.option(
"-c, --confirmations <file:file>",
"A file with confirmations to the EGO upload prompts, as generated by 'confirm-upload'",
)
.action(async (options, zipPath) => {
if (extname(zipPath) !== ".zip") {
throw new Error(`${zipPath} does not appear to be a zip file`);
}
const readZipPermission = await Deno.permissions.request({
name: "read",
path: zipPath,
});
if (readZipPermission.state !== "granted") {
throw new Error(`Read permission to ${zipPath} denied`);
}
const preconfirmedPrompts = options.confirmations
? await loadConfirmations(options.confirmations)
: null;
if (!await verifyConfirmedPrompts(preconfirmedPrompts)) {
console.error(
"You must confirm the license terms and terms of service to upload an extension!",
);
Deno.exit(1);
}
const auth = await promptForMissingAuth({
username: options.username,
password: options.password,
});
const token = await login(auth);
try {
const { version, extension: uuid } = await upload(token, zipPath);
const { id } = await queryExtension(token, uuid);
const extensionUrl = `https://extensions.gnome.org/extension/${id}/`;
console.log(
`Successfully uploaded extension ${uuid} version ${version}, please find it at ${extensionUrl}`,
);
} catch (error) {
if (error instanceof InvalidUploadError) {
console.error("Upload failed; reasons:");
for (const msg of error.errors) {
console.error(` - ${msg}`);
}
} else {
throw error;
}
} finally {
await logout(token);
}
})
.command("completions", new CompletionsCommand())
.command("confirm-upload", "Confirm upload prompts ahead of time")
.arguments("<target-file:file>")
.action(async (_, targetFile) => {
const prompts = await fetchConfirmationPrompts();
if (await promptForConfirmation(prompts)) {
Deno.writeTextFile(
targetFile,
JSON.stringify(prompts, undefined, 2) + "\n",
);
} else {
console.error(
"You must accept the license terms and the terms of service",
);
Deno.exit(1);
}
})
.parse(Deno.args);
if (import.meta.main) {
main();
}