-
Notifications
You must be signed in to change notification settings - Fork 7
/
space.js
414 lines (362 loc) Β· 11.3 KB
/
space.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
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
404
405
406
407
408
409
410
411
412
413
414
import * as W3Space from '@web3-storage/w3up-client/space'
import * as W3Account from '@web3-storage/w3up-client/account'
import { getClient } from './lib.js'
import process from 'node:process'
import * as DIDMailto from '@web3-storage/did-mailto'
import * as Account from './account.js'
import { SpaceDID } from '@web3-storage/capabilities/utils'
import ora from 'ora'
import { select, input } from '@inquirer/prompts'
import { mnemonic } from './dialog.js'
import { API } from '@ucanto/core'
import * as Result from '@web3-storage/w3up-client/result'
/**
* @typedef {object} CreateOptions
* @property {false} [recovery]
* @property {false} [caution]
* @property {DIDMailto.EmailAddress|false} [customer]
* @property {string|false} [account]
*
* @param {string|undefined} name
* @param {CreateOptions} options
*/
export const create = async (name, options) => {
const client = await getClient()
const spaces = client.spaces()
const space = await client.createSpace(await chooseName(name ?? '', spaces))
// Unless use opted-out from paper key recovery, we go through the flow
if (options.recovery !== false) {
const recovery = await setupRecovery(space, options)
if (recovery == null) {
console.log(
'β οΈ Aborting, if you want to create space without recovery option pass --no-recovery flag'
)
process.exit(1)
}
}
if (options.customer !== false) {
console.log('ποΈ To serve this space we need to set a billing account')
const setup = await setupBilling(client, {
customer: options.customer,
space: space.did(),
message: 'π Setting a billing account',
})
if (setup.error) {
if (setup.error.reason === 'abort') {
console.log(
'βοΈ Skipped billing setup. You can do it later using `w3 space provision`'
)
} else {
console.error(
'β οΈ Failed to to set billing account. You can retry using `w3 space provision`'
)
console.error(setup.error.cause.message)
}
} else {
console.log(`β¨ Billing account is set`)
}
}
// Authorize this client to allow them to use this space.
// β οΈ This is a temporary solution until we solve the account sync problem
// after which we will simply delegate to the account.
const authorization = await space.createAuthorization(client)
await client.addSpace(authorization)
// set this space as the current default space
await client.setCurrentSpace(space.did())
// Unless user opted-out we go through an account authorization flow
if (options.account !== false) {
console.log(
`βοΈ To manage space across devices we need to authorize an account`
)
const account = options.account
? await useAccount(client, { email: options.account })
: await selectAccount(client)
if (account) {
const spinner = ora(`π© Authorizing ${account.toEmail()}`).start()
const recovery = await space.createRecovery(account.did())
const result = await client.capability.access.delegate({
space: space.did(),
delegations: [recovery],
})
spinner.stop()
if (result.ok) {
console.log(`β¨ Account is authorized`)
} else {
console.error(
`β οΈ Failed to authorize account. You can still manage space using "paper key"`
)
console.error(result.error)
}
} else {
console.log(
`βοΈ Skip account authorization. You can still can manage space using "paper key"`
)
}
}
console.log(`β Space created: ${space.did()}`)
return space
}
/**
* @param {import('@web3-storage/w3up-client').Client} client
* @param {object} options
* @param {import('@web3-storage/w3up-client/types').SpaceDID} options.space
* @param {DIDMailto.EmailAddress} [options.customer]
* @param {string} [options.message]
* @param {string} [options.waitMessage]
* @returns {Promise<API.Result<{}, {reason:'abort'}|{reason: 'error', cause: Error}>>}
*/
const setupBilling = async (
client,
{
customer,
space,
message = 'Setting up a billing account',
waitMessage = 'Waiting for payment plan to be selected',
}
) => {
const account = customer
? await useAccount(client, { email: customer })
: await selectAccount(client)
if (account) {
const spinner = ora(waitMessage).start()
let plan = null
while (!plan) {
const result = await account.plan.get()
if (result.ok) {
plan = result.ok
} else {
await new Promise((resolve) => setTimeout(resolve, 1000))
}
}
spinner.text = message
const result = await account.provision(space)
spinner.stop()
if (result.error) {
return { error: { reason: 'error', cause: result.error } }
} else {
return { ok: {} }
}
} else {
return { error: { reason: 'abort' } }
}
}
/**
* @typedef {object} ProvisionOptions
* @property {DIDMailto.EmailAddress} [customer]
* @property {string} [coupon]
* @property {string} [provider]
* @property {string} [password]
*
* @param {string} name
* @param {ProvisionOptions} options
*/
export const provision = async (name = '', options = {}) => {
const client = await getClient()
const space = chooseSpace(client, { name })
if (!space) {
console.log(
`You do not appear to have a space, you can create one by running "w3 space create"`
)
process.exit(1)
}
if (options.coupon) {
const { ok: bytes, error: fetchError } = await fetch(options.coupon)
.then((response) => response.arrayBuffer())
.then((buffer) => Result.ok(new Uint8Array(buffer)))
.catch((error) => Result.error(/** @type {Error} */ (error)))
if (fetchError) {
console.error(`Failed to fetch coupon from ${options.coupon}`)
process.exit(1)
}
const { ok: access, error: couponError } = await client.coupon
.redeem(bytes, options)
.then(Result.ok, Result.error)
if (!access) {
console.error(`Failed to redeem coupon: ${couponError.message}}`)
process.exit(1)
}
const result = await W3Space.provision(
{ did: () => space },
{
proofs: access.proofs,
agent: client.agent,
}
)
if (result.error) {
console.log(`Failed to provision space: ${result.error.message}`)
process.exit(1)
}
} else {
const result = await setupBilling(client, {
customer: options.customer,
space,
})
if (result.error) {
console.error(
`β οΈ Failed to set up billing account,\n ${
Object(result.error).message ?? ''
}`
)
process.exit(1)
}
}
console.log(`β¨ Billing account is set`)
}
/**
* @typedef {import('@web3-storage/w3up-client/types').SpaceDID} SpaceDID
*
* @param {import('@web3-storage/w3up-client').Client} client
* @param {object} options
* @param {string} options.name
* @returns {SpaceDID|undefined}
*/
const chooseSpace = (client, { name }) => {
if (name) {
const result = SpaceDID.read(name)
if (result.ok) {
return result.ok
}
const space = client.spaces().find((space) => space.name === name)
if (space) {
return /** @type {SpaceDID} */ (space.did())
}
}
return /** @type {SpaceDID|undefined} */ (client.currentSpace()?.did())
}
/**
*
* @param {W3Space.Model} space
* @param {CreateOptions} options
*/
export const setupEmailRecovery = async (space, options = {}) => {}
/**
* @param {string} email
* @returns {{ok: DIDMailto.EmailAddress, error?:void}|{ok?:void, error: Error}}
*/
const parseEmail = (email) => {
try {
return { ok: DIDMailto.email(email) }
} catch (cause) {
return { error: /** @type {Error} */ (cause) }
}
}
/**
* @param {W3Space.OwnedSpace} space
* @param {CreateOptions} options
*/
export const setupRecovery = async (space, options = {}) => {
const recoveryKey = W3Space.toMnemonic(space)
if (options.caution === false) {
console.log(formatRecoveryInstruction(recoveryKey))
return space
} else {
const verified = await mnemonic({
secret: recoveryKey.split(/\s+/g),
message:
'You need to save the following secret recovery key somewhere safe! For example write it down on a piece of paper and put it inside your favorite book.',
revealMessage:
'π€« Make sure no one is eavesdropping and hit enter to reveal the key',
submitMessage: 'π Once you have saved the key hit enter to continue',
validateMessage:
'π Please type or paste your recovery key to make sure it is correct',
exitMessage: 'π Secret recovery key is correct!',
}).catch(() => null)
return verified ? space : null
}
}
/**
* @param {string} key
*/
const formatRecoveryInstruction = (key) =>
`π You need to save following secret recovery key somewhere safe! For example write it down on a piece of paper and put it inside your favorite book.
${key}
`
/**
* @param {string} name
* @param {{name:string}[]} spaces
* @returns {Promise<string>}
*/
const chooseName = async (name, spaces) => {
const space = spaces.find((space) => String(space.name) === name)
const message =
name === ''
? 'What would you like to call this space?'
: space
? `Name "${space.name}" is already taken, please choose a different one`
: null
if (message == null) {
return name
} else {
return await input({
message,
})
}
}
/**
* @param {import('@web3-storage/w3up-client').Client} client
* @param {{email?:string}} options
*/
export const pickAccount = async (client, { email }) =>
email ? await useAccount(client, { email }) : await selectAccount(client)
/**
* @param {import('@web3-storage/w3up-client').Client} client
* @param {{email?:string}} options
*/
export const useAccount = (client, { email }) => {
const accounts = Object.values(W3Account.list(client))
const account = accounts.find((account) => account.toEmail() === email)
if (!account) {
console.error(
`Agent is not authorized by ${email}, please login with it first`
)
return null
}
return account
}
/**
* @param {import('@web3-storage/w3up-client').Client} client
*/
export const selectAccount = async (client) => {
const accounts = Object.values(W3Account.list(client))
// If we do not have any accounts yet we take user through setup flow
if (accounts.length === 0) {
return setupAccount(client)
}
// If we have only one account we use it
else if (accounts.length === 1) {
return accounts[0]
}
// Otherwise we ask user to choose one
else {
return chooseAccount(accounts)
}
}
/**
* @param {import('@web3-storage/w3up-client').Client} client
*/
export const setupAccount = async (client) => {
const email = await input({
message: `π§ Please enter an email address to setup an account`,
validate: (input) => parseEmail(input).ok != null,
}).catch(() => null)
return email
? await Account.loginWithClient(
/** @type {DIDMailto.EmailAddress} */ (email),
client
)
: null
}
/**
* @param {Account.View[]} accounts
* @returns {Promise<Account.View|null>}
*/
export const chooseAccount = async (accounts) => {
const account = await select({
message: 'Please choose an account you would like to use',
choices: accounts.map((account) => ({
name: account.toEmail(),
value: account,
})),
}).catch(() => null)
return account
}