@open-pencil/cloud 0.17.0-beta.5 → 0.17.0-beta.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/client.d.ts +560 -93
- package/dist/client.d.ts.map +1 -1
- package/dist/client.js +1101 -186
- package/dist/client.js.map +1 -1
- package/dist/contract.d.ts +2 -2
- package/dist/contract.js +2 -2
- package/dist/contract2.js +390 -44
- package/dist/contract2.js.map +1 -1
- package/dist/email.d.ts +366 -3
- package/dist/email.d.ts.map +1 -1
- package/dist/email.js +1403 -556
- package/dist/email.js.map +1 -1
- package/dist/errors.js +16 -3
- package/dist/errors.js.map +1 -1
- package/dist/index.d.ts +878 -37
- package/dist/index.d.ts.map +1 -1
- package/dist/index2.d.ts +12 -2
- package/dist/index2.d.ts.map +1 -1
- package/dist/listen.mjs +589 -128
- package/dist/listen.mjs.map +1 -1
- package/dist/runtime-cloudflare.d.ts +4 -0
- package/dist/runtime-cloudflare.d.ts.map +1 -1
- package/dist/runtime-cloudflare.js +8689 -6324
- package/dist/runtime-cloudflare.js.map +1 -1
- package/dist/runtime-node.d.mts +10098 -5401
- package/dist/runtime-node.d.mts.map +1 -1
- package/dist/server.d.ts +14078 -7909
- package/dist/server.d.ts.map +1 -1
- package/dist/server.js +11723 -9412
- package/dist/server.js.map +1 -1
- package/dist/server.mjs +10658 -8649
- package/dist/server.mjs.map +1 -1
- package/dist/server2.mjs +79 -57
- package/dist/server2.mjs.map +1 -1
- package/package.json +13 -4
- package/src/admin/api/routes.ts +263 -190
- package/src/admin/audit/service.ts +9 -1
- package/src/admin/bootstrap.ts +86 -0
- package/src/admin/documents/service.ts +119 -4
- package/src/admin/email/service.ts +2 -1
- package/src/admin/enrollment/email.ts +17 -3
- package/src/admin/enrollment/service.ts +71 -10
- package/src/admin/errors.ts +5 -0
- package/src/admin/index.ts +1 -0
- package/src/admin/reports/service.ts +9 -3
- package/src/admin/schema.ts +6 -5
- package/src/admin/users/service.ts +173 -16
- package/src/client/api.ts +29 -2
- package/src/client/comments.ts +205 -0
- package/src/client/device-authorization.ts +4 -20
- package/src/client/discovery.ts +4 -2
- package/src/client/files/archive.ts +60 -0
- package/src/client/files/checksum.ts +7 -0
- package/src/client/files/download.ts +122 -0
- package/src/client/files/images.ts +89 -0
- package/src/client/files/index.ts +15 -0
- package/src/client/files/objects.ts +173 -0
- package/src/client/files/save.ts +79 -0
- package/src/client/index.ts +3 -6
- package/src/client/portal/account.ts +20 -2
- package/src/client/portal/administration.ts +52 -5
- package/src/client/portal/request.ts +4 -2
- package/src/client/tour.ts +44 -0
- package/src/client/versions.ts +7 -1
- package/src/contract/account.ts +61 -11
- package/src/contract/admin/index.ts +48 -3
- package/src/contract/billing.ts +73 -4
- package/src/contract/comments.ts +223 -0
- package/src/contract/discovery.ts +47 -19
- package/src/contract/index.ts +10 -0
- package/src/contract/links.ts +5 -0
- package/src/contract/relay.ts +3 -1
- package/src/contract/services.ts +44 -4
- package/src/contract/workspaces.ts +5 -0
- package/src/email/locales/ar.json +28 -0
- package/src/email/locales/de.json +28 -0
- package/src/email/locales/es.json +28 -0
- package/src/email/locales/fr.json +28 -0
- package/src/email/locales/it.json +28 -0
- package/src/email/locales/ja.json +28 -0
- package/src/email/locales/pl.json +28 -0
- package/src/email/locales/pt-br.json +28 -0
- package/src/email/locales/ru.json +28 -0
- package/src/email/locales/zh-cn.json +28 -0
- package/src/email/messages.ts +35 -0
- package/src/email/render.ts +18 -0
- package/src/email/samples.ts +28 -1
- package/src/email/schema.ts +29 -3
- package/src/email/templates/BrandEmail.vue +3 -1
- package/src/email/templates/CommentNotification.vue +39 -0
- package/src/email/templates/EnrollmentInvitation.vue +53 -0
- package/src/email/templates/TwoStepChanged.vue +17 -2
- package/src/email/templates/brand.ts +6 -0
- package/src/errors/posthog.ts +28 -4
- package/src/runtime/cloudflare/email.ts +2 -0
- package/src/runtime/cloudflare/relay/index.ts +21 -6
- package/src/runtime/cloudflare/worker.ts +6 -0
- package/src/runtime/cloudflare/xml.ts +12 -0
- package/src/runtime/node/admin.ts +51 -47
- package/src/runtime/node/email/runtime.ts +1 -0
- package/src/runtime/node/email/transport.ts +1 -0
- package/src/runtime/node/server.ts +8 -2
- package/src/runtime/posthog/errors.ts +3 -1
- package/src/server/account/actions.ts +3 -1
- package/src/server/account/deletion.ts +38 -4
- package/src/server/account/routes.ts +67 -46
- package/src/server/account/tokens.ts +3 -3
- package/src/server/api/router.ts +22 -7
- package/src/server/app/checks.ts +6 -1
- package/src/server/app/cors.ts +44 -0
- package/src/server/app/index.ts +76 -76
- package/src/server/app/routes.ts +14 -5
- package/src/server/app/services.ts +49 -15
- package/src/server/auth/access-control.ts +13 -8
- package/src/server/auth/account.ts +13 -12
- package/src/server/auth/activity.ts +7 -2
- package/src/server/auth/adapter.ts +16 -3
- package/src/server/auth/email.ts +29 -17
- package/src/server/auth/endpoints.ts +4 -0
- package/src/server/auth/factory.ts +83 -64
- package/src/server/auth/index.ts +1 -1
- package/src/server/auth/methods.ts +162 -0
- package/src/server/auth/mfa-assurance.ts +147 -10
- package/src/server/auth/rate-limit.ts +31 -0
- package/src/server/auth/runtime.ts +19 -5
- package/src/server/auth/social-providers.ts +70 -24
- package/src/server/billing/index.ts +2 -0
- package/src/server/billing/notify.ts +55 -0
- package/src/server/billing/seats.ts +17 -0
- package/src/server/billing/tokens.ts +1 -1
- package/src/server/cleanup/documents.ts +5 -2
- package/src/server/cleanup/revisions.ts +6 -3
- package/src/server/cleanup/uploads.ts +2 -1
- package/src/server/collaboration/relay/connection.ts +7 -2
- package/src/server/collaboration/relay/hub.ts +55 -24
- package/src/server/collaboration/routes.ts +8 -5
- package/src/server/comments/index.ts +9 -0
- package/src/server/comments/notify.ts +277 -0
- package/src/server/comments/routes.ts +352 -0
- package/src/server/comments/rows.ts +249 -0
- package/src/server/comments/service.ts +570 -0
- package/src/server/community/routes.ts +6 -6
- package/src/server/config/deployment.ts +19 -6
- package/src/server/config/index.ts +1 -1
- package/src/server/config/public.ts +19 -6
- package/src/server/config/schema.ts +14 -2
- package/src/server/config/toml/schema.ts +27 -4
- package/src/server/db/index.ts +2 -1
- package/src/server/db/migrate.ts +21 -1
- package/src/server/db/migrations/015_comments.ts +57 -0
- package/src/server/db/migrations/016_comment_notifications.ts +76 -0
- package/src/server/db/migrations/017_invitation_emails.ts +19 -0
- package/src/server/db/migrations/018_enrollment_source.ts +17 -0
- package/src/server/db/tables.ts +92 -2
- package/src/server/documents/access.ts +17 -0
- package/src/server/documents/images.ts +6 -1
- package/src/server/documents/routes.ts +12 -12
- package/src/server/documents/service.ts +19 -5
- package/src/server/documents/summary.ts +15 -0
- package/src/server/documents/versions/routes.ts +7 -8
- package/src/server/documents/versions/service.ts +5 -2
- package/src/server/email/service.ts +8 -2
- package/src/server/email/types.ts +1 -0
- package/src/server/errors/index.ts +48 -3
- package/src/server/index.ts +15 -1
- package/src/server/internal/routes.ts +8 -2
- package/src/server/internal/service.ts +10 -0
- package/src/server/invitations/budget.ts +3 -1
- package/src/server/invitations/index.ts +1 -0
- package/src/server/invitations/links.ts +6 -0
- package/src/server/pictures/service.ts +3 -1
- package/src/server/policy/workspace.ts +5 -2
- package/src/server/reports/routes.ts +2 -2
- package/src/server/reports/service.ts +3 -1
- package/src/server/services/routes.ts +2 -2
- package/src/server/sharing/capabilities/service.ts +1 -1
- package/src/server/sharing/document-routes.ts +3 -3
- package/src/server/sharing/invitations/service.ts +3 -4
- package/src/server/sharing/routes.ts +15 -15
- package/src/server/validation.ts +33 -25
- package/src/server/workspaces/members.ts +50 -12
- package/src/server/workspaces/repository.ts +23 -12
- package/src/server/workspaces/routes.ts +8 -8
- package/src/services/app.ts +30 -19
- package/src/services/config.ts +47 -8
- package/src/services/metering.ts +15 -27
- package/src/client/billing.ts +0 -80
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { normalizeEnrollmentEmail } from '#cloud/admin/enrollment/service'
|
|
1
2
|
import { AdminDomainError } from '#cloud/admin/errors'
|
|
2
3
|
import {
|
|
3
4
|
containsPattern,
|
|
@@ -11,24 +12,40 @@ import {
|
|
|
11
12
|
cloudAdminUserFilterSchema,
|
|
12
13
|
type CloudAdminUser,
|
|
13
14
|
type CloudAdminUserDetail,
|
|
14
|
-
type CloudAdminUserFilter
|
|
15
|
+
type CloudAdminUserFilter,
|
|
16
|
+
type CloudAdminUserMethod
|
|
15
17
|
} from '#cloud/contract'
|
|
18
|
+
import { createAccountDeletionService } from '#cloud/server/account/deletion'
|
|
16
19
|
import {
|
|
17
20
|
createSignInActivity,
|
|
18
21
|
type AuthenticationEmailService,
|
|
19
22
|
type CloudAuthAdapter
|
|
20
23
|
} from '#cloud/server/auth'
|
|
24
|
+
import { canRemoveSignInMethod, removeSignInMethod } from '#cloud/server/auth/methods'
|
|
21
25
|
import type { CloudDatabase } from '#cloud/server/db'
|
|
22
26
|
import type { UserPictureService } from '#cloud/server/pictures'
|
|
23
27
|
import { dateString } from '#cloud/server/sharing/contracts'
|
|
24
|
-
import {
|
|
25
|
-
import
|
|
28
|
+
import { APIError } from 'better-auth'
|
|
29
|
+
import { countBy, groupBy, keyBy } from 'es-toolkit'
|
|
30
|
+
import { NoResultError, type ExpressionBuilder, type Kysely } from 'kysely'
|
|
26
31
|
|
|
27
32
|
/** The sign-ins a person's page lists. */
|
|
28
33
|
const DETAIL_SIGN_INS = 20
|
|
29
34
|
|
|
30
35
|
type UserExpression = ExpressionBuilder<CloudDatabase, 'user'>
|
|
31
36
|
|
|
37
|
+
/** The accounts that sign in with a provider: `credential` is a password. */
|
|
38
|
+
function signsInWith(provider: string) {
|
|
39
|
+
return (expression: UserExpression) =>
|
|
40
|
+
expression.exists(
|
|
41
|
+
expression
|
|
42
|
+
.selectFrom('account')
|
|
43
|
+
.select('account.id')
|
|
44
|
+
.whereRef('account.userId', '=', 'user.id')
|
|
45
|
+
.where('account.providerId', '=', provider)
|
|
46
|
+
)
|
|
47
|
+
}
|
|
48
|
+
|
|
32
49
|
/** A search for part of a name or email, matched literally and without case. */
|
|
33
50
|
function searchCondition(search: string) {
|
|
34
51
|
const pattern = containsPattern(search)
|
|
@@ -58,7 +75,13 @@ const FILTERS: ListFilters<CloudAdminUserFilter, 'user'> = {
|
|
|
58
75
|
])
|
|
59
76
|
}
|
|
60
77
|
|
|
61
|
-
|
|
78
|
+
/** The provider a sign-in method a list is narrowed to is stored as: a password is `credential`. */
|
|
79
|
+
const methodProvider = (method: CloudAdminUserMethod) =>
|
|
80
|
+
method === 'password' ? 'credential' : method
|
|
81
|
+
|
|
82
|
+
export type AdminUserQuery = AdminListQuery<CloudAdminUserFilter> & {
|
|
83
|
+
method?: CloudAdminUserMethod
|
|
84
|
+
}
|
|
62
85
|
|
|
63
86
|
type UserRow = {
|
|
64
87
|
id: string
|
|
@@ -80,6 +103,10 @@ export function createAdminUserService(
|
|
|
80
103
|
notify?: AuthenticationEmailService
|
|
81
104
|
/** Takes down a person's picture; without it, `removePicture` refuses. */
|
|
82
105
|
pictures?: UserPictureService
|
|
106
|
+
/** People join only once approved, so the list says where each account's request stands. */
|
|
107
|
+
approval?: boolean
|
|
108
|
+
/** The providers the server signs in with now; without it, every linked method is a way in. */
|
|
109
|
+
signInProviders?: ReadonlySet<string>
|
|
83
110
|
} = {}
|
|
84
111
|
) {
|
|
85
112
|
const activity = createSignInActivity(database)
|
|
@@ -103,6 +130,8 @@ export function createAdminUserService(
|
|
|
103
130
|
.execute()
|
|
104
131
|
}
|
|
105
132
|
|
|
133
|
+
const deletion = createAccountDeletionService(database)
|
|
134
|
+
|
|
106
135
|
function refuseSelf(actorId: string, userId: string, action: string): void {
|
|
107
136
|
if (actorId === userId) {
|
|
108
137
|
throw new AdminDomainError(
|
|
@@ -144,8 +173,14 @@ export function createAdminUserService(
|
|
|
144
173
|
async function accountSummaries(rows: UserRow[]): Promise<CloudAdminUser[]> {
|
|
145
174
|
const ids = rows.map((row) => row.id)
|
|
146
175
|
if (ids.length === 0) return []
|
|
147
|
-
const [passkeys, sessions, memberships] = await Promise.all([
|
|
176
|
+
const [passkeys, accounts, sessions, memberships, requests] = await Promise.all([
|
|
148
177
|
database.selectFrom('passkey').select('userId').where('userId', 'in', ids).execute(),
|
|
178
|
+
database
|
|
179
|
+
.selectFrom('account')
|
|
180
|
+
.select(['userId', 'providerId'])
|
|
181
|
+
.where('userId', 'in', ids)
|
|
182
|
+
.orderBy('createdAt')
|
|
183
|
+
.execute(),
|
|
149
184
|
database
|
|
150
185
|
.selectFrom('session')
|
|
151
186
|
.select(({ fn }) => ['session.userId', fn.max('session.updatedAt').as('lastActiveAt')])
|
|
@@ -153,11 +188,24 @@ export function createAdminUserService(
|
|
|
153
188
|
.where('session.expiresAt', '>', new Date())
|
|
154
189
|
.groupBy('session.userId')
|
|
155
190
|
.execute(),
|
|
156
|
-
database.selectFrom('workspaceMember').select('userId').where('userId', 'in', ids).execute()
|
|
191
|
+
database.selectFrom('workspaceMember').select('userId').where('userId', 'in', ids).execute(),
|
|
192
|
+
options.approval
|
|
193
|
+
? database
|
|
194
|
+
.selectFrom('enrollment')
|
|
195
|
+
.select(['emailNormalized', 'status'])
|
|
196
|
+
.where(
|
|
197
|
+
'emailNormalized',
|
|
198
|
+
'in',
|
|
199
|
+
rows.map((row) => normalizeEnrollmentEmail(row.email))
|
|
200
|
+
)
|
|
201
|
+
.execute()
|
|
202
|
+
: []
|
|
157
203
|
])
|
|
204
|
+
const requestStatus = keyBy(requests, (request) => request.emailNormalized)
|
|
158
205
|
const withPasskeys = new Set(passkeys.map((passkey) => passkey.userId))
|
|
159
206
|
const lastActive = keyBy(sessions, (session) => session.userId)
|
|
160
207
|
const workspaceCounts = countBy(memberships, (membership) => membership.userId)
|
|
208
|
+
const methods = groupBy(accounts, (account) => account.userId)
|
|
161
209
|
return rows.map((row) => ({
|
|
162
210
|
id: row.id,
|
|
163
211
|
name: row.name,
|
|
@@ -169,7 +217,11 @@ export function createAdminUserService(
|
|
|
169
217
|
createdAt: dateString(row.createdAt) ?? '',
|
|
170
218
|
twoStep: row.twoFactorEnabled === true || withPasskeys.has(row.id),
|
|
171
219
|
lastActiveAt: dateString(lastActive[row.id]?.lastActiveAt ?? null),
|
|
172
|
-
workspaceCount: workspaceCounts[row.id] ?? 0
|
|
220
|
+
workspaceCount: workspaceCounts[row.id] ?? 0,
|
|
221
|
+
methods: (methods[row.id] ?? []).map((account) => account.providerId),
|
|
222
|
+
...(options.approval && {
|
|
223
|
+
request: requestStatus[normalizeEnrollmentEmail(row.email)]?.status ?? null
|
|
224
|
+
})
|
|
173
225
|
}))
|
|
174
226
|
}
|
|
175
227
|
|
|
@@ -194,6 +246,7 @@ export function createAdminUserService(
|
|
|
194
246
|
const { limit, offset } = listWindow(query)
|
|
195
247
|
let searched = database.selectFrom('user')
|
|
196
248
|
if (search) searched = searched.where(searchCondition(search))
|
|
249
|
+
if (query.method) searched = searched.where(signsInWith(methodProvider(query.method)))
|
|
197
250
|
const counts = await countEachFilter(searched, cloudAdminUserFilterSchema.options, FILTERS)
|
|
198
251
|
const rows = await searched
|
|
199
252
|
.where(FILTERS[filter])
|
|
@@ -218,7 +271,7 @@ export function createAdminUserService(
|
|
|
218
271
|
accountSummaries([row]),
|
|
219
272
|
database
|
|
220
273
|
.selectFrom('account')
|
|
221
|
-
.select(['providerId', 'createdAt'])
|
|
274
|
+
.select(['id', 'providerId', 'createdAt'])
|
|
222
275
|
.where('userId', '=', userId)
|
|
223
276
|
.orderBy('createdAt')
|
|
224
277
|
.execute(),
|
|
@@ -251,8 +304,10 @@ export function createAdminUserService(
|
|
|
251
304
|
return {
|
|
252
305
|
user: { ...summary, emailVerified: row.emailVerified },
|
|
253
306
|
methods: methods.map((method) => ({
|
|
307
|
+
id: method.id,
|
|
254
308
|
provider: method.providerId,
|
|
255
|
-
createdAt: dateString(method.createdAt) ?? ''
|
|
309
|
+
createdAt: dateString(method.createdAt) ?? '',
|
|
310
|
+
canRemove: canRemoveSignInMethod(method, methods, options.signInProviders)
|
|
256
311
|
})),
|
|
257
312
|
authenticator: row.twoFactorEnabled === true,
|
|
258
313
|
passkeyCount: Number(passkeys.count),
|
|
@@ -316,7 +371,7 @@ export function createAdminUserService(
|
|
|
316
371
|
*/
|
|
317
372
|
async resetTwoStep(actorId: string, userId: string): Promise<void> {
|
|
318
373
|
refuseSelf(actorId, userId, 'reset two-step sign-in for')
|
|
319
|
-
|
|
374
|
+
await database.transaction().execute(async (transaction) => {
|
|
320
375
|
const target = await transaction
|
|
321
376
|
.selectFrom('user')
|
|
322
377
|
.select(['id', 'email', 'name'])
|
|
@@ -342,16 +397,118 @@ export function createAdminUserService(
|
|
|
342
397
|
metadata: {}
|
|
343
398
|
})
|
|
344
399
|
.execute()
|
|
345
|
-
|
|
400
|
+
await options.notify?.sendTwoStepChanged(
|
|
401
|
+
{ email: target.email, name: target.name, userId, change: 'reset-by-administrator' },
|
|
402
|
+
transaction
|
|
403
|
+
)
|
|
346
404
|
})
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
405
|
+
},
|
|
406
|
+
|
|
407
|
+
/**
|
|
408
|
+
* Removes one way an account signs in, such as a Google account its owner lost control of.
|
|
409
|
+
* The account keeps at least one; sessions already signed in stay until revoked.
|
|
410
|
+
*/
|
|
411
|
+
async removeSignInMethod(actorId: string, userId: string, methodId: string): Promise<void> {
|
|
412
|
+
refuseSelf(actorId, userId, 'remove a sign-in method from')
|
|
413
|
+
await removeSignInMethod(database, {
|
|
414
|
+
userId,
|
|
415
|
+
methodId,
|
|
416
|
+
providers: options.signInProviders,
|
|
417
|
+
block: true,
|
|
418
|
+
// The audit entry and the notice commit with the removal, or not at all.
|
|
419
|
+
async also(transaction, removed) {
|
|
420
|
+
await transaction
|
|
421
|
+
.insertInto('adminAuditEvent')
|
|
422
|
+
.values({
|
|
423
|
+
id: crypto.randomUUID(),
|
|
424
|
+
actorUserId: actorId,
|
|
425
|
+
action: 'user.sign-in-method-removed',
|
|
426
|
+
subjectType: 'user',
|
|
427
|
+
subjectId: userId,
|
|
428
|
+
metadata: { provider: removed }
|
|
429
|
+
})
|
|
430
|
+
.execute()
|
|
431
|
+
const user = await transaction
|
|
432
|
+
.selectFrom('user')
|
|
433
|
+
.select(['email', 'name'])
|
|
434
|
+
.where('id', '=', userId)
|
|
435
|
+
.executeTakeFirstOrThrow()
|
|
436
|
+
await options.notify?.sendTwoStepChanged(
|
|
437
|
+
{ ...user, userId, change: 'sign-in-method-removed', method: removed },
|
|
438
|
+
transaction
|
|
439
|
+
)
|
|
440
|
+
}
|
|
441
|
+
}).catch((error: unknown) => {
|
|
442
|
+
if (!(error instanceof APIError)) throw error
|
|
443
|
+
if (error.body?.code === 'FAILED_TO_UNLINK_LAST_ACCOUNT') {
|
|
444
|
+
throw new AdminDomainError(
|
|
445
|
+
'last_authentication_method',
|
|
446
|
+
'Cannot remove an account’s last sign-in method'
|
|
447
|
+
)
|
|
448
|
+
}
|
|
449
|
+
// A method of another account, or none, names nothing here, as an unknown person does.
|
|
450
|
+
throw new NoResultError(database.selectFrom('account').toOperationNode())
|
|
352
451
|
})
|
|
353
452
|
},
|
|
354
453
|
|
|
454
|
+
/**
|
|
455
|
+
* Deletes an account that never got in: its request to join is still waiting or was declined,
|
|
456
|
+
* as with someone who signed up again behind Apple's hidden email. It goes as its owner's own
|
|
457
|
+
* deletion does, sessions and sign-in methods with it; the audit entry keeps who it was. An
|
|
458
|
+
* account that was approved, or an administrator, is refused: those leave by their own hand.
|
|
459
|
+
*/
|
|
460
|
+
async deleteUnapproved(actorId: string, userId: string): Promise<void> {
|
|
461
|
+
refuseSelf(actorId, userId, 'delete')
|
|
462
|
+
await deletion.remove(
|
|
463
|
+
{ id: userId },
|
|
464
|
+
{
|
|
465
|
+
// Under the account's and the request's locks, with the account as locked, so neither a
|
|
466
|
+
// promotion, an address change, nor an approval can land between the check and the delete.
|
|
467
|
+
async before(transaction, user) {
|
|
468
|
+
const request = await transaction
|
|
469
|
+
.selectFrom('enrollment')
|
|
470
|
+
.select(['id', 'status', 'approvedUserId'])
|
|
471
|
+
.where('emailNormalized', '=', normalizeEnrollmentEmail(user.email))
|
|
472
|
+
.forUpdate()
|
|
473
|
+
.executeTakeFirst()
|
|
474
|
+
// A request that is waiting again may have been approved before and removed: that account
|
|
475
|
+
// got in, and leaves only by its owner's hand.
|
|
476
|
+
const approvedBefore =
|
|
477
|
+
request !== undefined &&
|
|
478
|
+
(request.approvedUserId !== null ||
|
|
479
|
+
(await transaction
|
|
480
|
+
.selectFrom('adminAuditEvent')
|
|
481
|
+
.select('id')
|
|
482
|
+
.where('action', '=', 'enrollment.approved')
|
|
483
|
+
.where('subjectType', '=', 'enrollment')
|
|
484
|
+
.where('subjectId', '=', request.id)
|
|
485
|
+
.executeTakeFirst()) !== undefined)
|
|
486
|
+
if (
|
|
487
|
+
user.role === 'admin' ||
|
|
488
|
+
approvedBefore ||
|
|
489
|
+
(request?.status !== 'pending' && request?.status !== 'rejected')
|
|
490
|
+
) {
|
|
491
|
+
throw new AdminDomainError(
|
|
492
|
+
'account_approved',
|
|
493
|
+
'Only an account whose request was never approved can be deleted'
|
|
494
|
+
)
|
|
495
|
+
}
|
|
496
|
+
await transaction
|
|
497
|
+
.insertInto('adminAuditEvent')
|
|
498
|
+
.values({
|
|
499
|
+
id: crypto.randomUUID(),
|
|
500
|
+
actorUserId: actorId,
|
|
501
|
+
action: 'user.deleted',
|
|
502
|
+
subjectType: 'user',
|
|
503
|
+
subjectId: userId,
|
|
504
|
+
metadata: { name: user.name, email: user.email }
|
|
505
|
+
})
|
|
506
|
+
.execute()
|
|
507
|
+
}
|
|
508
|
+
}
|
|
509
|
+
)
|
|
510
|
+
},
|
|
511
|
+
|
|
355
512
|
/** Takes down a person's picture, such as one that should not be shown; initials replace it. */
|
|
356
513
|
async removePicture(actorId: string, userId: string): Promise<void> {
|
|
357
514
|
if (!options.pictures) throw new Error('Pictures are not available')
|
package/src/client/api.ts
CHANGED
|
@@ -4,6 +4,7 @@ import {
|
|
|
4
4
|
servicesTokenSchema,
|
|
5
5
|
billingTokenSchema,
|
|
6
6
|
cloudSessionSchema,
|
|
7
|
+
sendsTokenSafely,
|
|
7
8
|
type AccountEntitlements,
|
|
8
9
|
type ServicesToken,
|
|
9
10
|
type BillingToken,
|
|
@@ -13,6 +14,9 @@ import type { CloudAPI, PublicCloudAPI } from '#cloud/server/api'
|
|
|
13
14
|
import { hc } from 'hono/client'
|
|
14
15
|
import * as v from 'valibot'
|
|
15
16
|
|
|
17
|
+
import { anySignal, DEADLINE_MS } from '@open-pencil/std/timing'
|
|
18
|
+
|
|
19
|
+
import { createCommentRequests, createSharedCommentRequests } from './comments'
|
|
16
20
|
import { createCommunityRequests } from './community'
|
|
17
21
|
import { createDocumentRequests } from './documents'
|
|
18
22
|
import { createImageRequests } from './images'
|
|
@@ -42,17 +46,38 @@ function apiURL(baseURL: string): string {
|
|
|
42
46
|
return url.href
|
|
43
47
|
}
|
|
44
48
|
|
|
49
|
+
/**
|
|
50
|
+
* How long one Cloud API request may take. Some do real work on the server, such as saving a
|
|
51
|
+
* revision or deleting an account, and bytes go to storage directly, so a JSON call past this has
|
|
52
|
+
* hung rather than run slowly.
|
|
53
|
+
*/
|
|
54
|
+
const API_DEADLINE_MS = DEADLINE_MS.slowRequest
|
|
55
|
+
|
|
56
|
+
/** `fetch`, with each request bounded by its own deadline as well as the caller's signal. */
|
|
57
|
+
function boundedFetch(fetch: CloudFetch = globalThis.fetch): CloudFetch {
|
|
58
|
+
return (input, init) =>
|
|
59
|
+
fetch(input, {
|
|
60
|
+
...init,
|
|
61
|
+
signal: anySignal([init?.signal, AbortSignal.timeout(API_DEADLINE_MS)])
|
|
62
|
+
})
|
|
63
|
+
}
|
|
64
|
+
|
|
45
65
|
export function createCloudAPIClient(baseURL: string, options: CloudRequestOptions = {}) {
|
|
66
|
+
// An access token goes only where nobody between can read it, as services tokens do.
|
|
67
|
+
if (options.accessToken && !sendsTokenSafely(apiURL(baseURL))) {
|
|
68
|
+
throw new CloudAPIError('OpenPencil Cloud takes an access token only over HTTPS', 0)
|
|
69
|
+
}
|
|
46
70
|
const headers = {
|
|
47
71
|
'Content-Type': 'application/json',
|
|
48
72
|
...(options.accessToken ? { Authorization: `Bearer ${options.accessToken}` } : {})
|
|
49
73
|
}
|
|
74
|
+
const fetch = boundedFetch(options.fetch)
|
|
50
75
|
const client = hc<CloudAPI>(apiURL(baseURL), {
|
|
51
|
-
fetch
|
|
76
|
+
fetch,
|
|
52
77
|
init: { credentials: 'include', signal: options.signal, headers }
|
|
53
78
|
})
|
|
54
79
|
const publicClient = hc<PublicCloudAPI>(apiURL(baseURL), {
|
|
55
|
-
fetch
|
|
80
|
+
fetch,
|
|
56
81
|
init: { credentials: 'include', signal: options.signal, headers }
|
|
57
82
|
})
|
|
58
83
|
|
|
@@ -87,6 +112,8 @@ export function createCloudAPIClient(baseURL: string, options: CloudRequestOptio
|
|
|
87
112
|
...createImageRequests(client, publicClient, options.onDiagnostic),
|
|
88
113
|
...createDocumentRequests(client, options.onDiagnostic),
|
|
89
114
|
...createVersionRequests(client, options.onDiagnostic),
|
|
115
|
+
...createCommentRequests(client, options.onDiagnostic),
|
|
116
|
+
...createSharedCommentRequests(publicClient, options.onDiagnostic),
|
|
90
117
|
...createSharingRequests(client, publicClient, options.onDiagnostic),
|
|
91
118
|
...createCommunityRequests(publicClient, options.onDiagnostic)
|
|
92
119
|
}
|
|
@@ -0,0 +1,205 @@
|
|
|
1
|
+
import {
|
|
2
|
+
commentPeopleSchema,
|
|
3
|
+
commentThreadResponseSchema,
|
|
4
|
+
notificationSettingsSchema,
|
|
5
|
+
commentThreadsSchema,
|
|
6
|
+
type CloudCommentThread,
|
|
7
|
+
type CommentPerson,
|
|
8
|
+
type NotificationSettings,
|
|
9
|
+
type CommentThreads,
|
|
10
|
+
type CreateCommentInput,
|
|
11
|
+
type CreateCommentThreadInput,
|
|
12
|
+
type ImportCommentThreadsInput,
|
|
13
|
+
type UpdateCommentInput,
|
|
14
|
+
type UpdateCommentThreadInput
|
|
15
|
+
} from '#cloud/contract'
|
|
16
|
+
import type { CloudAPI, PublicCloudAPI } from '#cloud/server/api'
|
|
17
|
+
import type { hc } from 'hono/client'
|
|
18
|
+
import * as v from 'valibot'
|
|
19
|
+
|
|
20
|
+
import { parseResponse, type CloudClientDiagnostic, type CloudResponse } from './response'
|
|
21
|
+
|
|
22
|
+
/** A thread after deleting one of its comments; null once the thread went with its first. */
|
|
23
|
+
const threadOrGoneSchema = v.nullable(commentThreadResponseSchema)
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* What every way of reaching a document's comments does, through membership or a link: the app
|
|
27
|
+
* talks to one without asking which it is.
|
|
28
|
+
*/
|
|
29
|
+
export type CloudCommentRequests = {
|
|
30
|
+
list(): Promise<CommentThreads>
|
|
31
|
+
get(threadId: string): Promise<CloudCommentThread>
|
|
32
|
+
createThread(input: CreateCommentThreadInput): Promise<CloudCommentThread>
|
|
33
|
+
updateThread(threadId: string, input: UpdateCommentThreadInput): Promise<CloudCommentThread>
|
|
34
|
+
deleteThread(threadId: string): Promise<void>
|
|
35
|
+
reply(threadId: string, input: CreateCommentInput): Promise<CloudCommentThread>
|
|
36
|
+
updateComment(
|
|
37
|
+
threadId: string,
|
|
38
|
+
commentId: string,
|
|
39
|
+
input: UpdateCommentInput
|
|
40
|
+
): Promise<CloudCommentThread>
|
|
41
|
+
deleteComment(threadId: string, commentId: string): Promise<CloudCommentThread | null>
|
|
42
|
+
/** Records that the signed-in account read the thread as it is now. */
|
|
43
|
+
markRead(threadId: string): Promise<void>
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
async function thread(request: Promise<CloudResponse>, onDiagnostic?: CloudClientDiagnostic) {
|
|
47
|
+
return (await parseResponse(request, commentThreadResponseSchema, onDiagnostic)).thread
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
async function threadOrGone(request: Promise<CloudResponse>, onDiagnostic?: CloudClientDiagnostic) {
|
|
51
|
+
return (await parseResponse(request, threadOrGoneSchema, onDiagnostic))?.thread ?? null
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** Comment requests for documents people reach through membership or a direct grant. */
|
|
55
|
+
export function createCommentRequests(
|
|
56
|
+
client: ReturnType<typeof hc<CloudAPI>>,
|
|
57
|
+
onDiagnostic?: CloudClientDiagnostic
|
|
58
|
+
) {
|
|
59
|
+
return {
|
|
60
|
+
/** The comments of a document the signed-in account can open. */
|
|
61
|
+
documentComments(documentId: string): CloudCommentRequests {
|
|
62
|
+
const threads = client.documents[':documentId'].threads
|
|
63
|
+
const one = threads[':threadId']
|
|
64
|
+
const comment = one.comments[':commentId']
|
|
65
|
+
return {
|
|
66
|
+
list: () =>
|
|
67
|
+
parseResponse(
|
|
68
|
+
threads.$get({ param: { documentId } }),
|
|
69
|
+
commentThreadsSchema,
|
|
70
|
+
onDiagnostic
|
|
71
|
+
),
|
|
72
|
+
get: (threadId) => thread(one.$get({ param: { documentId, threadId } }), onDiagnostic),
|
|
73
|
+
createThread: (json) =>
|
|
74
|
+
thread(threads.$post({ param: { documentId }, json }), onDiagnostic),
|
|
75
|
+
updateThread: (threadId, json) =>
|
|
76
|
+
thread(one.$patch({ param: { documentId, threadId }, json }), onDiagnostic),
|
|
77
|
+
deleteThread: async (threadId) => {
|
|
78
|
+
await parseResponse(
|
|
79
|
+
one.$delete({ param: { documentId, threadId } }),
|
|
80
|
+
v.null(),
|
|
81
|
+
onDiagnostic
|
|
82
|
+
)
|
|
83
|
+
},
|
|
84
|
+
reply: (threadId, json) =>
|
|
85
|
+
thread(one.comments.$post({ param: { documentId, threadId }, json }), onDiagnostic),
|
|
86
|
+
updateComment: (threadId, commentId, json) =>
|
|
87
|
+
thread(
|
|
88
|
+
comment.$patch({ param: { documentId, threadId, commentId }, json }),
|
|
89
|
+
onDiagnostic
|
|
90
|
+
),
|
|
91
|
+
deleteComment: (threadId, commentId) =>
|
|
92
|
+
threadOrGone(
|
|
93
|
+
comment.$delete({ param: { documentId, threadId, commentId } }),
|
|
94
|
+
onDiagnostic
|
|
95
|
+
),
|
|
96
|
+
markRead: async (threadId) => {
|
|
97
|
+
await parseResponse(
|
|
98
|
+
one.read.$post({ param: { documentId, threadId } }),
|
|
99
|
+
v.null(),
|
|
100
|
+
onDiagnostic
|
|
101
|
+
)
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
},
|
|
105
|
+
|
|
106
|
+
/** Whom the signed-in account may name in a document's comments. */
|
|
107
|
+
async commentPeople(documentId: string): Promise<CommentPerson[]> {
|
|
108
|
+
const response = await parseResponse(
|
|
109
|
+
client.documents[':documentId'].threads.people.$get({ param: { documentId } }),
|
|
110
|
+
commentPeopleSchema,
|
|
111
|
+
onDiagnostic
|
|
112
|
+
)
|
|
113
|
+
return response.people
|
|
114
|
+
},
|
|
115
|
+
|
|
116
|
+
/** Which comments the signed-in account hears about by email. */
|
|
117
|
+
notificationSettings(): Promise<NotificationSettings> {
|
|
118
|
+
return parseResponse(
|
|
119
|
+
client.account.notifications.$get(),
|
|
120
|
+
notificationSettingsSchema,
|
|
121
|
+
onDiagnostic
|
|
122
|
+
)
|
|
123
|
+
},
|
|
124
|
+
setNotificationSettings(json: NotificationSettings): Promise<NotificationSettings> {
|
|
125
|
+
return parseResponse(
|
|
126
|
+
client.account.notifications.$put({ json }),
|
|
127
|
+
notificationSettingsSchema,
|
|
128
|
+
onDiagnostic
|
|
129
|
+
)
|
|
130
|
+
},
|
|
131
|
+
|
|
132
|
+
/** Brings a file's threads into a document that just moved to Cloud. */
|
|
133
|
+
async importCommentThreads(
|
|
134
|
+
documentId: string,
|
|
135
|
+
json: ImportCommentThreadsInput
|
|
136
|
+
): Promise<CommentThreads> {
|
|
137
|
+
return parseResponse(
|
|
138
|
+
client.documents[':documentId'].threads.import.$post({ param: { documentId }, json }),
|
|
139
|
+
commentThreadsSchema,
|
|
140
|
+
onDiagnostic
|
|
141
|
+
)
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
/** Comment requests through a share link, whose secret every request carries in its body. */
|
|
147
|
+
export function createSharedCommentRequests(
|
|
148
|
+
publicClient: ReturnType<typeof hc<PublicCloudAPI>>,
|
|
149
|
+
onDiagnostic?: CloudClientDiagnostic
|
|
150
|
+
) {
|
|
151
|
+
return {
|
|
152
|
+
sharedComments(shareId: string, secret: string): CloudCommentRequests {
|
|
153
|
+
const share = { secret }
|
|
154
|
+
const threads = publicClient.shares[':shareId'].threads
|
|
155
|
+
const one = threads[':threadId']
|
|
156
|
+
const comment = one.comments[':commentId']
|
|
157
|
+
return {
|
|
158
|
+
list: () =>
|
|
159
|
+
parseResponse(
|
|
160
|
+
threads.list.$post({ param: { shareId }, json: { share } }),
|
|
161
|
+
commentThreadsSchema,
|
|
162
|
+
onDiagnostic
|
|
163
|
+
),
|
|
164
|
+
get: (threadId) =>
|
|
165
|
+
thread(one.get.$post({ param: { shareId, threadId }, json: { share } }), onDiagnostic),
|
|
166
|
+
createThread: (input) =>
|
|
167
|
+
thread(threads.$post({ param: { shareId }, json: { share, ...input } }), onDiagnostic),
|
|
168
|
+
updateThread: (threadId, input) =>
|
|
169
|
+
thread(
|
|
170
|
+
one.$patch({ param: { shareId, threadId }, json: { share, ...input } }),
|
|
171
|
+
onDiagnostic
|
|
172
|
+
),
|
|
173
|
+
deleteThread: async (threadId) => {
|
|
174
|
+
await parseResponse(
|
|
175
|
+
one.$delete({ param: { shareId, threadId }, json: { share } }),
|
|
176
|
+
v.null(),
|
|
177
|
+
onDiagnostic
|
|
178
|
+
)
|
|
179
|
+
},
|
|
180
|
+
reply: (threadId, input) =>
|
|
181
|
+
thread(
|
|
182
|
+
one.comments.$post({ param: { shareId, threadId }, json: { share, ...input } }),
|
|
183
|
+
onDiagnostic
|
|
184
|
+
),
|
|
185
|
+
updateComment: (threadId, commentId, input) =>
|
|
186
|
+
thread(
|
|
187
|
+
comment.$patch({ param: { shareId, threadId, commentId }, json: { share, ...input } }),
|
|
188
|
+
onDiagnostic
|
|
189
|
+
),
|
|
190
|
+
deleteComment: (threadId, commentId) =>
|
|
191
|
+
threadOrGone(
|
|
192
|
+
comment.$delete({ param: { shareId, threadId, commentId }, json: { share } }),
|
|
193
|
+
onDiagnostic
|
|
194
|
+
),
|
|
195
|
+
markRead: async (threadId) => {
|
|
196
|
+
await parseResponse(
|
|
197
|
+
one.read.$post({ param: { shareId, threadId }, json: { share } }),
|
|
198
|
+
v.null(),
|
|
199
|
+
onDiagnostic
|
|
200
|
+
)
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
}
|
|
@@ -2,6 +2,8 @@ import type { CloudDiscovery } from '#cloud/contract'
|
|
|
2
2
|
import { joinURL } from 'ufo'
|
|
3
3
|
import * as v from 'valibot'
|
|
4
4
|
|
|
5
|
+
import { sleep } from '@open-pencil/std/timing'
|
|
6
|
+
|
|
5
7
|
import type { CloudFetch } from './discovery'
|
|
6
8
|
|
|
7
9
|
const deviceCodeSchema = v.object({
|
|
@@ -41,24 +43,6 @@ export type CloudDevicePollingOptions = {
|
|
|
41
43
|
sleep?: (milliseconds: number, signal?: AbortSignal) => Promise<void>
|
|
42
44
|
}
|
|
43
45
|
|
|
44
|
-
function abortableSleep(milliseconds: number, signal?: AbortSignal): Promise<void> {
|
|
45
|
-
return new Promise<void>((resolve, reject) => {
|
|
46
|
-
const timeout = setTimeout(resolve, milliseconds)
|
|
47
|
-
signal?.addEventListener(
|
|
48
|
-
'abort',
|
|
49
|
-
() => {
|
|
50
|
-
clearTimeout(timeout)
|
|
51
|
-
reject(
|
|
52
|
-
signal.reason instanceof Error
|
|
53
|
-
? signal.reason
|
|
54
|
-
: new DOMException('Authorization cancelled', 'AbortError')
|
|
55
|
-
)
|
|
56
|
-
},
|
|
57
|
-
{ once: true }
|
|
58
|
-
)
|
|
59
|
-
})
|
|
60
|
-
}
|
|
61
|
-
|
|
62
46
|
function authEndpoint(discovery: CloudDiscovery, path: string): string {
|
|
63
47
|
return joinURL(discovery.authURL, path)
|
|
64
48
|
}
|
|
@@ -93,12 +77,12 @@ export async function pollCloudDeviceToken(
|
|
|
93
77
|
): Promise<CloudDeviceToken> {
|
|
94
78
|
const request = options.fetch ?? globalThis.fetch
|
|
95
79
|
const now = options.now ?? Date.now
|
|
96
|
-
const
|
|
80
|
+
const wait = options.sleep ?? sleep
|
|
97
81
|
const expiresAt = now() + authorization.expires_in * 1000
|
|
98
82
|
let interval = authorization.interval * 1000
|
|
99
83
|
while (now() < expiresAt) {
|
|
100
84
|
options.signal?.throwIfAborted()
|
|
101
|
-
await
|
|
85
|
+
await wait(interval, options.signal)
|
|
102
86
|
if (now() >= expiresAt) break
|
|
103
87
|
const response = await request(authEndpoint(discovery, 'device/token'), {
|
|
104
88
|
method: 'POST',
|
package/src/client/discovery.ts
CHANGED
|
@@ -7,7 +7,9 @@ import {
|
|
|
7
7
|
} from '#cloud/contract'
|
|
8
8
|
import * as v from 'valibot'
|
|
9
9
|
|
|
10
|
-
|
|
10
|
+
import { anySignal, DEADLINE_MS } from '@open-pencil/std/timing'
|
|
11
|
+
|
|
12
|
+
const DISCOVERY_TIMEOUT_MS = DEADLINE_MS.request
|
|
11
13
|
|
|
12
14
|
export type CloudFetch = (input: RequestInfo | URL, init?: RequestInit) => Promise<Response>
|
|
13
15
|
|
|
@@ -105,7 +107,7 @@ export async function discoverCloud(
|
|
|
105
107
|
): Promise<CloudDiscovery> {
|
|
106
108
|
const fetchImplementation = options.fetch ?? globalThis.fetch
|
|
107
109
|
const timeoutSignal = AbortSignal.timeout(DISCOVERY_TIMEOUT_MS)
|
|
108
|
-
const signal =
|
|
110
|
+
const signal = anySignal([options.signal, timeoutSignal])
|
|
109
111
|
|
|
110
112
|
try {
|
|
111
113
|
const response = await fetchImplementation(discoveryURL(serverURL), {
|