/
store.ts
249 lines (196 loc) · 6.81 KB
/
store.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
import * as fs from 'fs';
import * as path from 'path';
import { home } from 'osenv';
import { read, getGalleryAPI, getSecurityRolesAPI, log } from './util';
import { validatePublisher } from './validation';
import { readManifest } from './package';
export interface IPublisher {
readonly name: string;
readonly pat: string;
}
export interface IStore extends Iterable<IPublisher> {
readonly size: number;
get(name: string): IPublisher | undefined;
add(publisher: IPublisher): Promise<void>;
delete(name: string): Promise<void>;
}
export class FileStore implements IStore {
private static readonly DefaultPath = path.join(home(), '.vsce');
static async open(path: string = FileStore.DefaultPath): Promise<FileStore> {
try {
const rawStore = await fs.promises.readFile(path, 'utf8');
return new FileStore(path, JSON.parse(rawStore).publishers);
} catch (err) {
if (err.code === 'ENOENT') {
return new FileStore(path, []);
} else if (/SyntaxError/.test(err)) {
throw new Error(`Error parsing file store: ${path}`);
}
throw err;
}
}
get size(): number {
return this.publishers.length;
}
private constructor(readonly path: string, private publishers: IPublisher[]) {}
private async save(): Promise<void> {
await fs.promises.writeFile(this.path, JSON.stringify({ publishers: this.publishers }), { mode: '0600' });
}
async deleteStore(): Promise<void> {
try {
await fs.promises.unlink(this.path);
} catch {
// noop
}
}
get(name: string): IPublisher | undefined {
return this.publishers.filter(p => p.name === name)[0];
}
async add(publisher: IPublisher): Promise<void> {
this.publishers = [...this.publishers.filter(p => p.name !== publisher.name), publisher];
await this.save();
}
async delete(name: string): Promise<void> {
this.publishers = this.publishers.filter(p => p.name !== name);
await this.save();
}
[Symbol.iterator]() {
return this.publishers[Symbol.iterator]();
}
}
export class KeytarStore implements IStore {
static async open(serviceName = 'vscode-vsce'): Promise<KeytarStore> {
const keytar = await import('keytar');
const creds = await keytar.findCredentials(serviceName);
return new KeytarStore(
keytar,
serviceName,
creds.map(({ account, password }) => ({ name: account, pat: password }))
);
}
get size(): number {
return this.publishers.length;
}
private constructor(
private readonly keytar: typeof import('keytar'),
private readonly serviceName: string,
private publishers: IPublisher[]
) {}
get(name: string): IPublisher {
return this.publishers.filter(p => p.name === name)[0];
}
async add(publisher: IPublisher): Promise<void> {
this.publishers = [...this.publishers.filter(p => p.name !== publisher.name), publisher];
await this.keytar.setPassword(this.serviceName, publisher.name, publisher.pat);
}
async delete(name: string): Promise<void> {
this.publishers = this.publishers.filter(p => p.name !== name);
await this.keytar.deletePassword(this.serviceName, name);
}
[Symbol.iterator](): Iterator<IPublisher, any, undefined> {
return this.publishers[Symbol.iterator]();
}
}
export async function verifyPat(pat: string, publisherName?: string): Promise<void> {
if (!pat) {
throw new Error('The Personal Access Token is mandatory.');
}
if (!publisherName) {
try {
publisherName = (await readManifest()).publisher;
} catch (error) {
throw new Error(
`Can not read the publisher's name. Either supply it as an argument or run vsce from the extension folder. Additional information:\n\n${error}`
);
}
}
try {
// If the caller of the `getRoleAssignments` API has any of the roles
// (Creator, Owner, Contributor, Reader) on the publisher, we get a 200,
// otherwise we get a 403.
const api = await getSecurityRolesAPI(pat);
await api.getRoleAssignments('gallery.publisher', publisherName);
} catch (error) {
throw new Error('The Personal Access Token verification has failed. Additional information:\n\n' + error);
}
console.log(`The Personal Access Token verification succeeded for the publisher '${publisherName}'.`);
}
async function requestPAT(publisherName: string): Promise<string> {
console.log('https://marketplace.visualstudio.com/manage/publishers/');
const pat = await read(`Personal Access Token for publisher '${publisherName}':`, { silent: true, replace: '*' });
await verifyPat(pat, publisherName);
return pat;
}
async function openDefaultStore(): Promise<IStore> {
if (/^file$/i.test(process.env['VSCE_STORE'] ?? '')) {
return await FileStore.open();
}
const keytarStore = await KeytarStore.open();
const fileStore = await FileStore.open();
// migrate from file store
if (fileStore.size) {
for (const publisher of fileStore) {
await keytarStore.add(publisher);
}
await fileStore.deleteStore();
log.info(
`Migrated ${fileStore.size} publishers to system credential manager. Deleted local store '${fileStore.path}'.`
);
}
return keytarStore;
}
export async function getPublisher(publisherName: string): Promise<IPublisher> {
validatePublisher(publisherName);
const store = await openDefaultStore();
let publisher = store.get(publisherName);
if (publisher) {
return publisher;
}
const pat = await requestPAT(publisherName);
publisher = { name: publisherName, pat };
await store.add(publisher);
return publisher;
}
export async function loginPublisher(publisherName: string): Promise<IPublisher> {
validatePublisher(publisherName);
const store = await openDefaultStore();
let publisher = store.get(publisherName);
if (publisher) {
console.log(`Publisher '${publisherName}' is already known`);
const answer = await read('Do you want to overwrite its PAT? [y/N] ');
if (!/^y$/i.test(answer)) {
throw new Error('Aborted');
}
}
const pat = await requestPAT(publisherName);
publisher = { name: publisherName, pat };
await store.add(publisher);
return publisher;
}
export async function logoutPublisher(publisherName: string): Promise<void> {
validatePublisher(publisherName);
const store = await openDefaultStore();
const publisher = store.get(publisherName);
if (!publisher) {
throw new Error(`Unknown publisher '${publisherName}'`);
}
await store.delete(publisherName);
}
export async function deletePublisher(publisherName: string): Promise<void> {
const publisher = await getPublisher(publisherName);
const answer = await read(`This will FOREVER delete '${publisherName}'! Are you sure? [y/N] `);
if (!/^y$/i.test(answer)) {
throw new Error('Aborted');
}
const api = await getGalleryAPI(publisher.pat);
await api.deletePublisher(publisherName);
const store = await openDefaultStore();
await store.delete(publisherName);
log.done(`Deleted publisher '${publisherName}'.`);
}
export async function listPublishers(): Promise<void> {
const store = await openDefaultStore();
for (const publisher of store) {
console.log(publisher.name);
}
}