-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathmember-api.js
290 lines (254 loc) · 8.77 KB
/
member-api.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
import * as crypto from 'node:crypto'
import { TypedEmitter } from 'tiny-typed-emitter'
import { InviteResponse_Decision } from './generated/rpc.js'
import {
assert,
noop,
ExhaustivenessError,
onceSatisfied,
projectKeyToId,
projectKeyToPublicId,
} from './utils.js'
import timingSafeEqual from './lib/timing-safe-equal.js'
import { ROLES, isRoleIdForNewInvite } from './roles.js'
const DEFAULT_INVITE_TIMEOUT = 5 * (1000 * 60)
/**
* @internal
* @typedef {import('./generated/rpc.js').Invite} Invite
*/
/**
* @internal
* @typedef {import('./generated/rpc.js').InviteResponse} InviteResponse
*/
/** @typedef {import('./datatype/index.js').DataType<import('./datastore/index.js').DataStore<'config'>, typeof import('./schema/project.js').deviceInfoTable, "deviceInfo", import('@mapeo/schema').DeviceInfo, import('@mapeo/schema').DeviceInfoValue>} DeviceInfoDataType */
/** @typedef {import('./datatype/index.js').DataType<import('./datastore/index.js').DataStore<'config'>, typeof import('./schema/client.js').projectSettingsTable, "projectSettings", import('@mapeo/schema').ProjectSettings, import('@mapeo/schema').ProjectSettingsValue>} ProjectDataType */
/** @typedef {{ deviceId: string, name?: import('@mapeo/schema').DeviceInfo['name'], role: import('./roles.js').Role }} MemberInfo */
export class MemberApi extends TypedEmitter {
#ownDeviceId
#roles
#coreOwnership
#encryptionKeys
#projectKey
#rpc
#dataTypes
/** @type {Set<string>} */
#deviceIdsWithPendingInvites = new Set()
/**
* @param {Object} opts
* @param {string} opts.deviceId public key of this device as hex string
* @param {import('./roles.js').Roles} opts.roles
* @param {import('./core-ownership.js').CoreOwnership} opts.coreOwnership
* @param {import('./generated/keys.js').EncryptionKeys} opts.encryptionKeys
* @param {Buffer} opts.projectKey
* @param {import('./local-peers.js').LocalPeers} opts.rpc
* @param {Object} opts.dataTypes
* @param {Pick<DeviceInfoDataType, 'getByDocId' | 'getMany'>} opts.dataTypes.deviceInfo
* @param {Pick<ProjectDataType, 'getByDocId'>} opts.dataTypes.project
*/
constructor({
deviceId,
roles,
coreOwnership,
encryptionKeys,
projectKey,
rpc,
dataTypes,
}) {
super()
this.#ownDeviceId = deviceId
this.#roles = roles
this.#coreOwnership = coreOwnership
this.#encryptionKeys = encryptionKeys
this.#projectKey = projectKey
this.#rpc = rpc
this.#dataTypes = dataTypes
}
/**
* @param {string} deviceId
* @param {Object} opts
* @param {import('./roles.js').RoleIdForNewInvite} opts.roleId
* @param {string} [opts.roleName]
* @param {string} [opts.roleDescription]
* @param {number} [opts.timeout]
* @returns {Promise<(
* typeof InviteResponse_Decision.ACCEPT |
* typeof InviteResponse_Decision.REJECT |
* typeof InviteResponse_Decision.ALREADY
* )>}
*/
async invite(
deviceId,
{
roleId,
roleName = ROLES[roleId]?.name,
roleDescription,
timeout = DEFAULT_INVITE_TIMEOUT,
}
) {
assert(isRoleIdForNewInvite(roleId), 'Invalid role ID for new invite')
assert(
!this.#deviceIdsWithPendingInvites.has(deviceId),
'Already inviting this device ID'
)
assert(timeout > 0, 'Timeout should be a positive number')
assert(timeout < 2 ** 32, 'Timeout is too large')
/**
* These cleanup functions should be synchronous so we don't have to
* `await` calls to `handleAborted`.
* @type {Array<() => void>}
*/
const cleanupFns = []
const cleanup = () => {
for (const fn of cleanupFns) {
try {
fn()
} catch (_err) {
console.error('Cleanup function failed')
}
}
}
try {
let handleAborted = noop
const timeoutId = setTimeout(() => {
handleAborted = () => {
throw new Error('Invite timed out')
}
}, timeout)
cleanupFns.push(() => {
clearTimeout(timeoutId)
})
this.#deviceIdsWithPendingInvites.add(deviceId)
cleanupFns.push(() => {
this.#deviceIdsWithPendingInvites.delete(deviceId)
})
const { name: invitorName } = await this.getById(this.#ownDeviceId)
// since we are always getting #ownDeviceId,
// this should never throw (see comment on getById), but it pleases ts
if (!invitorName)
throw new Error(
'Internal error trying to read own device name for this invite'
)
handleAborted()
const projectId = projectKeyToId(this.#projectKey)
const projectPublicId = projectKeyToPublicId(this.#projectKey)
const project = await this.#dataTypes.project.getByDocId(projectId)
const projectName = project.name
if (!projectName)
throw new Error('Project must have a name to invite people')
handleAborted()
const inviteId = crypto.randomBytes(32)
const receiveInviteAbortController = new AbortController()
cleanupFns.push(() => {
receiveInviteAbortController.abort()
})
const receiveInviteResponsePromise =
/** @type {typeof onceSatisfied<TypedEmitter<import('./local-peers.js').LocalPeersEvents>, 'invite-response'>} */ (
onceSatisfied
)(
this.#rpc,
'invite-response',
(peerId, inviteResponse) =>
timingSafeEqual(peerId, deviceId) &&
timingSafeEqual(inviteId, inviteResponse.inviteId),
{ signal: receiveInviteAbortController.signal }
).then((args) => args?.[1])
await this.#rpc.sendInvite(deviceId, {
inviteId,
projectPublicId,
projectName,
roleName,
roleDescription,
invitorName,
})
handleAborted()
const inviteResponse = await receiveInviteResponsePromise
assert(inviteResponse, 'Expected an invite response to be received')
handleAborted()
switch (inviteResponse.decision) {
case InviteResponse_Decision.ALREADY:
case InviteResponse_Decision.REJECT:
return inviteResponse.decision
case InviteResponse_Decision.UNRECOGNIZED:
return InviteResponse_Decision.REJECT
case InviteResponse_Decision.ACCEPT:
handleAborted()
// We should assign the role locally *before* sharing the project details
// so that they're part of the project even if they don't receive the
// project details message.
await this.#roles.assignRole(deviceId, roleId)
await this.#rpc.sendProjectJoinDetails(deviceId, {
inviteId,
projectKey: this.#projectKey,
encryptionKeys: this.#encryptionKeys,
})
return inviteResponse.decision
default:
throw new ExhaustivenessError(inviteResponse.decision)
}
} finally {
cleanup()
}
}
/**
* @param {string} deviceId
* @returns {Promise<MemberInfo>}
*/
async getById(deviceId) {
const role = await this.#roles.getRole(deviceId)
/** @type {MemberInfo} */
const result = { deviceId, role }
try {
const configCoreId = await this.#coreOwnership.getCoreId(
deviceId,
'config'
)
const deviceInfo = await this.#dataTypes.deviceInfo.getByDocId(
configCoreId
)
result.name = deviceInfo.name
} catch (err) {
// Attempting to get someone else may throw because sync hasn't occurred or completed
// Only throw if attempting to get themself since the relevant information should be available
if (deviceId === this.#ownDeviceId) throw err
}
return result
}
/**
* @returns {Promise<Array<MemberInfo>>}
*/
async getMany() {
const [allRoles, allDeviceInfo] = await Promise.all([
this.#roles.getAll(),
this.#dataTypes.deviceInfo.getMany(),
])
return Promise.all(
Object.entries(allRoles).map(async ([deviceId, role]) => {
/** @type {MemberInfo} */
const memberInfo = { deviceId, role }
try {
const configCoreId = await this.#coreOwnership.getCoreId(
deviceId,
'config'
)
const deviceInfo = allDeviceInfo.find(
({ docId }) => docId === configCoreId
)
memberInfo.name = deviceInfo?.name
} catch (err) {
// Attempting to get someone else may throw because sync hasn't occurred or completed
// Only throw if attempting to get themself since the relevant information should be available
if (deviceId === this.#ownDeviceId) throw err
}
return memberInfo
})
)
}
/**
* @param {string} deviceId
* @param {import('./roles.js').RoleIdAssignableToOthers} roleId
* @returns {Promise<void>}
*/
async assignRole(deviceId, roleId) {
return this.#roles.assignRole(deviceId, roleId)
}
}