@open-pencil/cloud 0.17.0-beta.1 → 0.17.0-beta.4
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/README.md +1 -1
- package/dist/bin/{ai-relay.mjs → services.mjs} +8 -8
- package/dist/bin/services.mjs.map +1 -0
- package/dist/client.d.ts +236 -46
- package/dist/client.d.ts.map +1 -1
- package/dist/client.js +649 -400
- package/dist/client.js.map +1 -1
- package/dist/contract.d.ts +2 -2
- package/dist/contract.js +2 -2
- package/dist/contract2.js +680 -443
- package/dist/contract2.js.map +1 -1
- package/dist/email.d.ts +9 -1
- package/dist/email.d.ts.map +1 -1
- package/dist/email.js +99 -58
- package/dist/email.js.map +1 -1
- package/dist/index.d.ts +468 -64
- package/dist/index.d.ts.map +1 -1
- package/dist/listen.mjs +575 -738
- package/dist/listen.mjs.map +1 -1
- package/dist/runtime-node.d.mts +6564 -2934
- package/dist/runtime-node.d.mts.map +1 -1
- package/dist/runtime-node.mjs +6 -5
- package/dist/runtime-node.mjs.map +1 -1
- package/dist/server.d.ts +8931 -4198
- package/dist/server.d.ts.map +1 -1
- package/dist/server.js +5260 -3859
- package/dist/server.js.map +1 -1
- package/dist/server.mjs +5686 -3736
- package/dist/server.mjs.map +1 -1
- package/dist/server2.mjs +101 -79
- package/dist/server2.mjs.map +1 -1
- package/package.json +9 -6
- package/src/admin/api/routes.ts +103 -33
- package/src/admin/audit/service.ts +25 -6
- package/src/admin/documents/service.ts +361 -0
- package/src/admin/errors.ts +9 -1
- package/src/admin/index.ts +6 -0
- package/src/admin/operations/service.ts +7 -0
- package/src/admin/reports/service.ts +147 -0
- package/src/admin/schema.ts +6 -0
- package/src/client/api.ts +36 -21
- package/src/client/auth/navigation.ts +6 -5
- package/src/client/index.ts +7 -7
- package/src/client/portal/account.ts +25 -0
- package/src/client/portal/administration.ts +56 -0
- package/src/client/{ai.ts → services.ts} +44 -27
- package/src/contract/account.ts +58 -2
- package/src/contract/admin/index.ts +67 -3
- package/src/contract/collaboration.ts +6 -1
- package/src/contract/discovery.ts +22 -4
- package/src/contract/documents.ts +27 -0
- package/src/contract/entitlements.ts +2 -2
- package/src/contract/index.ts +63 -37
- package/src/contract/relay.ts +6 -0
- package/src/contract/reports.ts +42 -0
- package/src/contract/services.ts +233 -0
- package/src/contract/sharing.ts +3 -9
- package/src/email/render.ts +26 -0
- package/src/email/schema.ts +11 -1
- package/src/email/templates/brand.ts +1 -1
- package/src/runtime/cloudflare/environment.ts +31 -6
- package/src/runtime/cloudflare/index.ts +1 -1
- package/src/runtime/cloudflare/logging.ts +15 -0
- package/src/runtime/cloudflare/maintenance.ts +31 -0
- package/src/runtime/cloudflare/relay/index.ts +176 -0
- package/src/runtime/cloudflare/relay/sockets.ts +112 -0
- package/src/runtime/cloudflare/worker.ts +89 -26
- package/src/runtime/node/application.ts +5 -3
- package/src/runtime/node/bootstrap.ts +20 -4
- package/src/runtime/node/cleanup.ts +16 -3
- package/src/runtime/node/entitlements/main.ts +14 -11
- package/src/runtime/node/index.ts +1 -1
- package/src/runtime/node/migrate.ts +5 -1
- package/src/runtime/node/relay.ts +8 -2
- package/src/runtime/node/request-id.ts +13 -0
- package/src/runtime/node/server.ts +71 -15
- package/src/runtime/node/{ai-relay → services}/main.ts +6 -6
- package/src/runtime/node/{ai-relay → services}/server.ts +18 -18
- package/src/runtime/postgres/database.ts +20 -1
- package/src/runtime/posthog/errors.ts +32 -0
- package/src/runtime/s3/objects.ts +50 -1
- package/src/runtime/site/server.ts +33 -4
- package/src/server/account/actions.ts +5 -0
- package/src/server/account/deletion.ts +302 -0
- package/src/server/account/routes.ts +47 -3
- package/src/server/account/terms.ts +42 -0
- package/src/server/api/router.ts +12 -7
- package/src/server/api/types.ts +9 -0
- package/src/server/app.ts +93 -15
- package/src/server/auth/access-control.ts +63 -0
- package/src/server/auth/adapter.ts +11 -0
- package/src/server/auth/endpoints.ts +5 -1
- package/src/server/auth/factory.ts +30 -3
- package/src/server/auth/index.ts +10 -1
- package/src/server/cleanup/configured.ts +12 -5
- package/src/server/cleanup/documents.ts +165 -71
- package/src/server/cleanup/objects.ts +10 -2
- package/src/server/cleanup/revisions.ts +24 -7
- package/src/server/cleanup/uploads.ts +8 -2
- package/src/server/cleanup/worker.ts +5 -2
- package/src/server/collaboration/index.ts +3 -0
- package/src/server/collaboration/relay/connection.ts +196 -0
- package/src/server/collaboration/relay/documents.ts +13 -10
- package/src/server/collaboration/relay/hub.ts +279 -195
- package/src/server/collaboration/relay/index.ts +3 -1
- package/src/server/collaboration/relay/log.ts +79 -0
- package/src/server/collaboration/relay/persistence.ts +147 -22
- package/src/server/collaboration/relay/resume.ts +28 -0
- package/src/server/collaboration/routes.ts +27 -16
- package/src/server/collaboration/service.ts +27 -31
- package/src/server/config/deployment.ts +35 -4
- package/src/server/config/public.ts +5 -4
- package/src/server/config/schema.ts +104 -16
- package/src/server/db/expressions.ts +15 -1
- package/src/server/db/migrate.ts +34 -114
- package/src/server/db/migrations/001_accounts.ts +79 -0
- package/src/server/db/migrations/002_workspaces.ts +48 -0
- package/src/server/db/migrations/003_storage.ts +44 -0
- package/src/server/db/migrations/004_documents.ts +193 -0
- package/src/server/db/migrations/005_sharing.ts +95 -0
- package/src/server/db/migrations/006_operations.ts +110 -0
- package/src/server/db/migrations/007_trash.ts +33 -0
- package/src/server/db/migrations/008_terms.ts +18 -0
- package/src/server/db/migrations/schema.ts +71 -0
- package/src/server/db/tables.ts +70 -7
- package/src/server/documents/access.ts +66 -55
- package/src/server/documents/errors.ts +7 -0
- package/src/server/documents/images.ts +2 -1
- package/src/server/documents/limits.ts +9 -9
- package/src/server/documents/purge.ts +75 -0
- package/src/server/documents/repository.ts +2 -0
- package/src/server/documents/routes.ts +132 -80
- package/src/server/documents/service.ts +18 -4
- package/src/server/documents/summary.ts +1 -0
- package/src/server/documents/trash.ts +203 -0
- package/src/server/documents/versions/checkpoint.ts +2 -1
- package/src/server/documents/versions/history.ts +11 -7
- package/src/server/documents/versions/routes.ts +36 -25
- package/src/server/documents/versions/service.ts +22 -4
- package/src/server/errors/index.ts +99 -0
- package/src/server/errors/posthog.ts +80 -0
- package/src/server/index.ts +56 -16
- package/src/server/internal/index.ts +3 -3
- package/src/server/internal/routes.ts +7 -15
- package/src/server/internal/schema.ts +1 -1
- package/src/server/internal/service.ts +17 -23
- package/src/server/invitations/budget.ts +66 -0
- package/src/server/invitations/index.ts +1 -0
- package/src/server/logging.ts +76 -0
- package/src/server/objects/types.ts +12 -0
- package/src/server/pictures/routes.ts +4 -2
- package/src/server/pictures/service.ts +2 -1
- package/src/server/policy/database.ts +39 -25
- package/src/server/policy/index.ts +2 -1
- package/src/server/policy/keys.ts +5 -2
- package/src/server/policy/policy.ts +1 -0
- package/src/server/policy/schema.ts +2 -2
- package/src/server/policy/service.ts +12 -9
- package/src/server/policy/static.ts +5 -5
- package/src/server/policy/workspace.ts +41 -0
- package/src/server/quota/reconcile.ts +2 -0
- package/src/server/quota/storage.ts +69 -31
- package/src/server/rate-limit/cleanup.ts +17 -5
- package/src/server/rate-limit/index.ts +4 -1
- package/src/server/rate-limit/middleware.ts +100 -12
- package/src/server/reports/index.ts +8 -0
- package/src/server/reports/routes.ts +37 -0
- package/src/server/reports/service.ts +123 -0
- package/src/server/services/errors.ts +7 -0
- package/src/server/services/index.ts +8 -0
- package/src/server/{ai → services}/keys.ts +11 -11
- package/src/server/services/routes.ts +47 -0
- package/src/server/{ai/service.ts → services/tokens.ts} +23 -20
- package/src/server/sharing/capabilities/service.ts +68 -22
- package/src/server/sharing/document-routes.ts +30 -22
- package/src/server/sharing/grants/service.ts +11 -18
- package/src/server/sharing/http.ts +4 -0
- package/src/server/sharing/invitations/service.ts +21 -11
- package/src/server/sharing/policy.ts +9 -14
- package/src/server/sharing/routes.ts +108 -85
- package/src/server/sharing/service.ts +1 -17
- package/src/server/validation.ts +59 -2
- package/src/server/workspaces/index.ts +1 -0
- package/src/server/workspaces/members.ts +89 -38
- package/src/server/workspaces/repository.ts +2 -1
- package/src/server/workspaces/routes.ts +67 -45
- package/src/{ai-relay → services}/app.ts +48 -44
- package/src/{ai-relay → services}/config.ts +25 -19
- package/src/services/db/index.ts +10 -0
- package/src/services/db/migrate.ts +37 -0
- package/src/{ai-relay/db/migrations/001_usage.ts → services/db/migrations/001_baseline.ts} +18 -7
- package/src/services/db/schema.ts +22 -0
- package/src/services/index.ts +18 -0
- package/src/{ai-relay → services}/metering.ts +2 -2
- package/src/{ai-relay → services}/usage.ts +43 -19
- package/dist/bin/ai-relay.mjs.map +0 -1
- package/src/ai-relay/db/index.ts +0 -10
- package/src/ai-relay/db/migrate.ts +0 -32
- package/src/ai-relay/db/schema.ts +0 -20
- package/src/ai-relay/index.ts +0 -18
- package/src/contract/ai.ts +0 -150
- package/src/runtime/cloudflare/relay.ts +0 -136
- package/src/server/ai/errors.ts +0 -7
- package/src/server/ai/index.ts +0 -4
- package/src/server/ai/routes.ts +0 -43
- package/src/server/auth/workspace-access.ts +0 -23
- package/src/server/db/migrations/001_foundation.ts +0 -164
- package/src/server/db/migrations/002_upload_cleanup_claims.ts +0 -34
- package/src/server/db/migrations/003_document_cleanup_claims.ts +0 -23
- package/src/server/db/migrations/004_document_sharing.ts +0 -82
- package/src/server/db/migrations/005_document_collaboration_epoch.ts +0 -13
- package/src/server/db/migrations/006_invitation_continuation.ts +0 -27
- package/src/server/db/migrations/007_collaboration_state.ts +0 -25
- package/src/server/db/migrations/008_storage_reservations.ts +0 -37
- package/src/server/db/migrations/009_workspace_entitlements.ts +0 -22
- package/src/server/db/migrations/010_upload_finalization.ts +0 -22
- package/src/server/db/migrations/011_upload_finalization_lease.ts +0 -12
- package/src/server/db/migrations/012_transactional_email.ts +0 -48
- package/src/server/db/migrations/013_admin_enrollment.ts +0 -54
- package/src/server/db/migrations/014_enrollment_email_kinds.ts +0 -30
- package/src/server/db/migrations/015_cloud_rate_limit.ts +0 -22
- package/src/server/db/migrations/016_auth_schema.ts +0 -16
- package/src/server/db/migrations/017_authentication_email_kinds.ts +0 -32
- package/src/server/db/migrations/018_authentication_mfa.ts +0 -78
- package/src/server/db/migrations/019_better_auth_account_issuer.ts +0 -42
- package/src/server/db/migrations/020_workspace_invitations.ts +0 -57
- package/src/server/db/migrations/021_document_versions.ts +0 -66
- package/src/server/db/migrations/022_entitlement_external_version.ts +0 -17
- package/src/server/db/migrations/023_document_images.ts +0 -61
- package/src/server/db/migrations/024_account_activity.ts +0 -66
- package/src/server/db/migrations/025_table_names.ts +0 -58
- package/src/server/db/migrations/026_user_picture.ts +0 -30
- package/src/server/db/migrations/027_document_kind.ts +0 -19
- package/src/server/db/migrations/helpers.ts +0 -78
- /package/dist/bin/{ai-relay.d.mts → services.d.mts} +0 -0
|
@@ -0,0 +1,302 @@
|
|
|
1
|
+
import { normalizeEnrollmentEmail } from '#cloud/admin/enrollment/service'
|
|
2
|
+
import type { CloudAccountDeletion } from '#cloud/contract'
|
|
3
|
+
import type { CloudDatabase } from '#cloud/server/db'
|
|
4
|
+
import { markPurged } from '#cloud/server/documents/purge'
|
|
5
|
+
import { handOverOwnership } from '#cloud/server/workspaces'
|
|
6
|
+
import { APIError } from 'better-auth'
|
|
7
|
+
import type { Kysely, Transaction } from 'kysely'
|
|
8
|
+
|
|
9
|
+
/** Workspaces the account alone administers while others belong to them, which it must hand on. */
|
|
10
|
+
export class AccountDeletionBlockedError extends Error {
|
|
11
|
+
constructor(readonly workspaces: CloudAccountDeletion['blockedBy']) {
|
|
12
|
+
super('The account is the only administrator of workspaces with other members')
|
|
13
|
+
this.name = 'AccountDeletionBlockedError'
|
|
14
|
+
}
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
/** The account is the deployment's last administrator, so deleting it would lock the console. */
|
|
18
|
+
export class AccountLastAdministratorError extends Error {
|
|
19
|
+
constructor() {
|
|
20
|
+
super('Cannot delete the last deployment administrator')
|
|
21
|
+
this.name = 'AccountLastAdministratorError'
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* Whether the account is an administrator of the deployment with no other active one, the
|
|
27
|
+
* check the console makes before banning or demoting one (`src/admin/users/service.ts`).
|
|
28
|
+
* Inside a transaction it locks the administrators' rows, so two of them can't both go at once.
|
|
29
|
+
*/
|
|
30
|
+
async function lastAdministrator(
|
|
31
|
+
database: Kysely<CloudDatabase> | Transaction<CloudDatabase>,
|
|
32
|
+
userId: string,
|
|
33
|
+
lock: boolean
|
|
34
|
+
): Promise<boolean> {
|
|
35
|
+
let query = database
|
|
36
|
+
.selectFrom('user')
|
|
37
|
+
.select(['id', 'banned'])
|
|
38
|
+
.where('role', '=', 'admin')
|
|
39
|
+
.orderBy('id')
|
|
40
|
+
if (lock) query = query.forUpdate()
|
|
41
|
+
const administrators = await query.execute()
|
|
42
|
+
if (!administrators.some((row) => row.id === userId)) return false
|
|
43
|
+
return !administrators.some((row) => row.id !== userId && row.banned !== true)
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
type Membership = {
|
|
47
|
+
workspaceId: string
|
|
48
|
+
name: string
|
|
49
|
+
role: string
|
|
50
|
+
members: number
|
|
51
|
+
admins: number
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** What happens to each workspace the account belongs to when it goes. */
|
|
55
|
+
function classify(memberships: Membership[]) {
|
|
56
|
+
const deletes: Membership[] = []
|
|
57
|
+
const blockedBy: Membership[] = []
|
|
58
|
+
const leaves: Membership[] = []
|
|
59
|
+
for (const membership of memberships) {
|
|
60
|
+
if (membership.members === 1) deletes.push(membership)
|
|
61
|
+
else if (membership.role === 'admin' && membership.admins === 1) blockedBy.push(membership)
|
|
62
|
+
else leaves.push(membership)
|
|
63
|
+
}
|
|
64
|
+
return { deletes, blockedBy, leaves }
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
async function memberships(
|
|
68
|
+
database: Kysely<CloudDatabase> | Transaction<CloudDatabase>,
|
|
69
|
+
userId: string
|
|
70
|
+
): Promise<Membership[]> {
|
|
71
|
+
return database
|
|
72
|
+
.selectFrom('workspaceMember as own')
|
|
73
|
+
.innerJoin('workspace', 'workspace.id', 'own.workspaceId')
|
|
74
|
+
.innerJoin('workspaceMember as everyone', 'everyone.workspaceId', 'own.workspaceId')
|
|
75
|
+
.select((expression) => [
|
|
76
|
+
'own.workspaceId',
|
|
77
|
+
'workspace.name',
|
|
78
|
+
'own.role',
|
|
79
|
+
expression.fn.count<number>('everyone.userId').as('members'),
|
|
80
|
+
expression.fn
|
|
81
|
+
.count<number>('everyone.userId')
|
|
82
|
+
.filterWhere('everyone.role', '=', 'admin')
|
|
83
|
+
.as('admins')
|
|
84
|
+
])
|
|
85
|
+
.where('own.userId', '=', userId)
|
|
86
|
+
.groupBy(['own.workspaceId', 'workspace.name', 'own.role'])
|
|
87
|
+
.orderBy('workspace.name')
|
|
88
|
+
.orderBy('own.workspaceId')
|
|
89
|
+
.execute()
|
|
90
|
+
.then((rows) =>
|
|
91
|
+
rows.map((row) => ({ ...row, members: Number(row.members), admins: Number(row.admins) }))
|
|
92
|
+
)
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
const workspaceSummary = (membership: Membership) => ({
|
|
96
|
+
id: membership.workspaceId,
|
|
97
|
+
name: membership.name
|
|
98
|
+
})
|
|
99
|
+
|
|
100
|
+
/**
|
|
101
|
+
* Deleting an account: what it takes, and the Cloud side of taking it. Better Auth removes the
|
|
102
|
+
* user with their sessions, sign-in methods, passkeys, and two-step secrets; this removes what
|
|
103
|
+
* Cloud keeps about them. Workspaces only they belong to go with their documents, deleted
|
|
104
|
+
* forever, which cleanup destroys once the deployment's grace passes; in workspaces others keep
|
|
105
|
+
* they drop out, handing ownership, and so the plan the workspace draws on, to the
|
|
106
|
+
* longest-standing other admin.
|
|
107
|
+
*/
|
|
108
|
+
export function createAccountDeletionService(database: Kysely<CloudDatabase>) {
|
|
109
|
+
return {
|
|
110
|
+
async plan(userId: string): Promise<CloudAccountDeletion> {
|
|
111
|
+
const { deletes, blockedBy, leaves } = classify(await memberships(database, userId))
|
|
112
|
+
const deleted = deletes.map((membership) => membership.workspaceId)
|
|
113
|
+
const left = leaves.map((membership) => membership.workspaceId)
|
|
114
|
+
const blocked = blockedBy.map((membership) => membership.workspaceId)
|
|
115
|
+
// What the account can still download: everything in workspaces that go with it, and what
|
|
116
|
+
// it created in workspaces it leaves, keeps an admin role in, or reaches only by a grant.
|
|
117
|
+
const documents = await database
|
|
118
|
+
.selectFrom('document')
|
|
119
|
+
.innerJoin('workspace', 'workspace.id', 'document.workspaceId')
|
|
120
|
+
.select(['document.id', 'document.name', 'workspace.name as workspaceName'])
|
|
121
|
+
.where('document.deletedAt', 'is', null)
|
|
122
|
+
.where('document.disabledAt', 'is', null)
|
|
123
|
+
.where((expression) =>
|
|
124
|
+
expression.or([
|
|
125
|
+
...(deleted.length > 0 ? [expression('document.workspaceId', 'in', deleted)] : []),
|
|
126
|
+
expression.and([
|
|
127
|
+
expression('document.createdBy', '=', userId),
|
|
128
|
+
expression.or([
|
|
129
|
+
...(left.length > 0 ? [expression('document.workspaceId', 'in', left)] : []),
|
|
130
|
+
...(blocked.length > 0 ? [expression('document.workspaceId', 'in', blocked)] : []),
|
|
131
|
+
expression(
|
|
132
|
+
'document.id',
|
|
133
|
+
'in',
|
|
134
|
+
expression
|
|
135
|
+
.selectFrom('documentGrant')
|
|
136
|
+
.select('documentGrant.documentId')
|
|
137
|
+
.where('documentGrant.userId', '=', userId)
|
|
138
|
+
.where('documentGrant.revokedAt', 'is', null)
|
|
139
|
+
)
|
|
140
|
+
])
|
|
141
|
+
])
|
|
142
|
+
])
|
|
143
|
+
)
|
|
144
|
+
.orderBy('workspace.name')
|
|
145
|
+
.orderBy('document.name')
|
|
146
|
+
.orderBy('document.id')
|
|
147
|
+
.execute()
|
|
148
|
+
return {
|
|
149
|
+
lastAdministrator: await lastAdministrator(database, userId, false),
|
|
150
|
+
blockedBy: blockedBy.map(workspaceSummary),
|
|
151
|
+
deletes: deletes.map(workspaceSummary),
|
|
152
|
+
leaves: leaves.map(workspaceSummary),
|
|
153
|
+
documents
|
|
154
|
+
}
|
|
155
|
+
},
|
|
156
|
+
|
|
157
|
+
/**
|
|
158
|
+
* Removes everything Cloud keeps about the account, in one transaction, or refuses with
|
|
159
|
+
* `AccountDeletionBlockedError` and changes nothing. Its workspaces are locked first, so nobody
|
|
160
|
+
* joins one, changes a role in one, or adds a document to one while it decides.
|
|
161
|
+
*/
|
|
162
|
+
async remove(user: { id: string; email: string }): Promise<void> {
|
|
163
|
+
await database.transaction().execute(async (transaction) => {
|
|
164
|
+
if (await lastAdministrator(transaction, user.id, true)) {
|
|
165
|
+
throw new AccountLastAdministratorError()
|
|
166
|
+
}
|
|
167
|
+
const workspaceIds = await transaction
|
|
168
|
+
.selectFrom('workspaceMember')
|
|
169
|
+
.select('workspaceId')
|
|
170
|
+
.where('userId', '=', user.id)
|
|
171
|
+
.orderBy('workspaceId')
|
|
172
|
+
.execute()
|
|
173
|
+
for (const { workspaceId } of workspaceIds) {
|
|
174
|
+
await transaction
|
|
175
|
+
.selectFrom('workspace')
|
|
176
|
+
.select('id')
|
|
177
|
+
.where('id', '=', workspaceId)
|
|
178
|
+
.forUpdate()
|
|
179
|
+
.execute()
|
|
180
|
+
}
|
|
181
|
+
const { deletes, blockedBy, leaves } = classify(await memberships(transaction, user.id))
|
|
182
|
+
if (blockedBy.length > 0) {
|
|
183
|
+
throw new AccountDeletionBlockedError(blockedBy.map(workspaceSummary))
|
|
184
|
+
}
|
|
185
|
+
const now = new Date()
|
|
186
|
+
for (const { workspaceId } of deletes) {
|
|
187
|
+
await transaction
|
|
188
|
+
.updateTable('document')
|
|
189
|
+
.set({ deletedAt: now })
|
|
190
|
+
.where('workspaceId', '=', workspaceId)
|
|
191
|
+
.where('deletedAt', 'is', null)
|
|
192
|
+
.execute()
|
|
193
|
+
// Nobody is left to restore them, so they are deleted forever, Trash included: out of
|
|
194
|
+
// sight now, and destroyed by cleanup once the deployment's grace passes.
|
|
195
|
+
const documents = await transaction
|
|
196
|
+
.selectFrom('document')
|
|
197
|
+
.select('id')
|
|
198
|
+
.where('workspaceId', '=', workspaceId)
|
|
199
|
+
.where('purgedAt', 'is', null)
|
|
200
|
+
.execute()
|
|
201
|
+
await markPurged(
|
|
202
|
+
transaction,
|
|
203
|
+
documents.map((document) => document.id),
|
|
204
|
+
null,
|
|
205
|
+
now
|
|
206
|
+
)
|
|
207
|
+
await transaction
|
|
208
|
+
.updateTable('workspaceInvitation')
|
|
209
|
+
.set({ revokedAt: now })
|
|
210
|
+
.where('workspaceId', '=', workspaceId)
|
|
211
|
+
.where('acceptedAt', 'is', null)
|
|
212
|
+
.where('revokedAt', 'is', null)
|
|
213
|
+
.execute()
|
|
214
|
+
await transaction
|
|
215
|
+
.deleteFrom('workspaceMember')
|
|
216
|
+
.where('workspaceId', '=', workspaceId)
|
|
217
|
+
.where('userId', '=', user.id)
|
|
218
|
+
.execute()
|
|
219
|
+
// One with documents stays, member-less, until cleanup purges the last of them.
|
|
220
|
+
await transaction
|
|
221
|
+
.deleteFrom('workspace')
|
|
222
|
+
.where('id', '=', workspaceId)
|
|
223
|
+
.where((expression) =>
|
|
224
|
+
expression.not(
|
|
225
|
+
expression.exists(
|
|
226
|
+
expression
|
|
227
|
+
.selectFrom('document')
|
|
228
|
+
.select('document.id')
|
|
229
|
+
.whereRef('document.workspaceId', '=', 'workspace.id')
|
|
230
|
+
)
|
|
231
|
+
)
|
|
232
|
+
)
|
|
233
|
+
.execute()
|
|
234
|
+
}
|
|
235
|
+
for (const { workspaceId } of leaves) {
|
|
236
|
+
await transaction
|
|
237
|
+
.deleteFrom('workspaceMember')
|
|
238
|
+
.where('workspaceId', '=', workspaceId)
|
|
239
|
+
.where('userId', '=', user.id)
|
|
240
|
+
.execute()
|
|
241
|
+
await handOverOwnership(transaction, workspaceId, user.id)
|
|
242
|
+
}
|
|
243
|
+
await transaction.deleteFrom('documentGrant').where('userId', '=', user.id).execute()
|
|
244
|
+
for (const table of ['documentInvitation', 'workspaceInvitation'] as const) {
|
|
245
|
+
await transaction
|
|
246
|
+
.updateTable(table)
|
|
247
|
+
.set({ revokedAt: now })
|
|
248
|
+
.where('invitedBy', '=', user.id)
|
|
249
|
+
.where('acceptedAt', 'is', null)
|
|
250
|
+
.where('revokedAt', 'is', null)
|
|
251
|
+
.execute()
|
|
252
|
+
}
|
|
253
|
+
await transaction.deleteFrom('invitationSend').where('senderId', '=', user.id).execute()
|
|
254
|
+
for (const table of [
|
|
255
|
+
'accountEntitlement',
|
|
256
|
+
'termsAcceptance',
|
|
257
|
+
'userPicture',
|
|
258
|
+
'signIn',
|
|
259
|
+
'mfaAssurance'
|
|
260
|
+
] as const) {
|
|
261
|
+
await transaction.deleteFrom(table).where('userId', '=', user.id).execute()
|
|
262
|
+
}
|
|
263
|
+
await transaction
|
|
264
|
+
.deleteFrom('enrollment')
|
|
265
|
+
.where('emailNormalized', '=', normalizeEnrollmentEmail(user.email))
|
|
266
|
+
.execute()
|
|
267
|
+
// The user row goes in the same transaction, with the sessions, sign-in methods, passkeys
|
|
268
|
+
// and two-step secrets its keys cascade to, so a failure leaves the account whole and
|
|
269
|
+
// signed in to try again. Better Auth's own deletes that follow then find nothing.
|
|
270
|
+
await transaction.deleteFrom('user').where('id', '=', user.id).execute()
|
|
271
|
+
})
|
|
272
|
+
}
|
|
273
|
+
}
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
export type AccountDeletionService = ReturnType<typeof createAccountDeletionService>
|
|
277
|
+
|
|
278
|
+
/**
|
|
279
|
+
* Better Auth's `user.deleteUser` options: it checks the password, or that the session is fresh,
|
|
280
|
+
* then runs `beforeDelete` outside any transaction of its own, so Cloud's may query. That
|
|
281
|
+
* transaction deletes the user too; a refusal reaches the client as `account_sole_admin` or
|
|
282
|
+
* `last_admin_required`.
|
|
283
|
+
*/
|
|
284
|
+
export function accountDeletionOptions(database: Kysely<CloudDatabase>) {
|
|
285
|
+
const deletion = createAccountDeletionService(database)
|
|
286
|
+
return {
|
|
287
|
+
enabled: true,
|
|
288
|
+
async beforeDelete(user: { id: string; email: string }) {
|
|
289
|
+
try {
|
|
290
|
+
await deletion.remove(user)
|
|
291
|
+
} catch (error) {
|
|
292
|
+
if (error instanceof AccountDeletionBlockedError) {
|
|
293
|
+
throw APIError.from('CONFLICT', { code: 'ACCOUNT_SOLE_ADMIN', message: error.message })
|
|
294
|
+
}
|
|
295
|
+
if (error instanceof AccountLastAdministratorError) {
|
|
296
|
+
throw APIError.from('CONFLICT', { code: 'LAST_ADMIN_REQUIRED', message: error.message })
|
|
297
|
+
}
|
|
298
|
+
throw error
|
|
299
|
+
}
|
|
300
|
+
}
|
|
301
|
+
}
|
|
302
|
+
}
|
|
@@ -10,7 +10,10 @@ import {
|
|
|
10
10
|
parseCloudProfileUpdate,
|
|
11
11
|
parseCloudPictureUpload,
|
|
12
12
|
CLOUD_PICTURE_MAX_BYTES,
|
|
13
|
-
parseCloudSessionRevoke
|
|
13
|
+
parseCloudSessionRevoke,
|
|
14
|
+
parseCloudAccountDelete,
|
|
15
|
+
parseCloudTermsAcceptance,
|
|
16
|
+
type CloudAccountStatus
|
|
14
17
|
} from '#cloud/contract'
|
|
15
18
|
import type { CloudAPIEnvironment } from '#cloud/server/api'
|
|
16
19
|
import {
|
|
@@ -28,6 +31,8 @@ import { bodyLimit } from 'hono/body-limit'
|
|
|
28
31
|
import { toUint8Array } from 'js-base64'
|
|
29
32
|
|
|
30
33
|
import { createAccountActions } from './actions'
|
|
34
|
+
import type { AccountDeletionService } from './deletion'
|
|
35
|
+
import type { TermsService } from './terms'
|
|
31
36
|
|
|
32
37
|
/** Room for a Base64 picture and the JSON around it. */
|
|
33
38
|
const PICTURE_BODY_BYTES = Math.ceil(CLOUD_PICTURE_MAX_BYTES / 3) * 4 + 1024
|
|
@@ -38,9 +43,13 @@ export type AccountRouteDependencies = {
|
|
|
38
43
|
pictures: UserPictureService
|
|
39
44
|
enrollment: EnrollmentService
|
|
40
45
|
workspaces: WorkspaceService
|
|
46
|
+
deletion: AccountDeletionService
|
|
47
|
+
terms: TermsService
|
|
41
48
|
resolveIdentity: CloudIdentityResolver
|
|
42
49
|
resolveSession: CloudSessionResolver
|
|
43
50
|
requireActiveSession: MiddlewareHandler<CloudAPIEnvironment>
|
|
51
|
+
/** Lets an account with terms to accept reach what leaving needs; see `resolveAccountSession`. */
|
|
52
|
+
requireAccountSession: MiddlewareHandler<CloudAPIEnvironment>
|
|
44
53
|
authenticatedMutationLimiter: MiddlewareHandler<CloudAPIEnvironment>
|
|
45
54
|
}
|
|
46
55
|
|
|
@@ -65,13 +74,29 @@ export function createAccountRoutes(services: AccountRouteDependencies) {
|
|
|
65
74
|
await enrollment.request({ email: identity.email, name: identity.name })
|
|
66
75
|
enrollmentStatus = 'pending'
|
|
67
76
|
}
|
|
68
|
-
|
|
77
|
+
// Waiting or declined, from enrollment; null once the account may use the server.
|
|
78
|
+
const enrollmentState =
|
|
69
79
|
services.config.enrollmentMode !== 'approval' || enrollmentStatus === 'approved'
|
|
70
|
-
?
|
|
80
|
+
? null
|
|
71
81
|
: (enrollmentStatus ?? 'pending')
|
|
82
|
+
// Terms come after approval: an account still waiting has nothing to accept yet.
|
|
83
|
+
let state: CloudAccountStatus['state'] = enrollmentState ?? 'active'
|
|
84
|
+
if (!enrollmentState && !(await services.terms.hasAccepted(identity.userId))) state = 'terms'
|
|
72
85
|
if (state === 'active') await workspaces.ensurePersonal(identity)
|
|
73
86
|
return context.json({ user: identity, state })
|
|
74
87
|
})
|
|
88
|
+
.post('/api/account/terms', validatedJSON(parseCloudTermsAcceptance), async (context) => {
|
|
89
|
+
const identity = await resolveIdentity(context.req.raw)
|
|
90
|
+
if (!identity) return context.json({ error: { code: 'unauthorized' as const } }, 401)
|
|
91
|
+
if (!services.terms.requiredVersion) {
|
|
92
|
+
return context.json({ error: { code: 'not_found' as const } }, 404)
|
|
93
|
+
}
|
|
94
|
+
// Accepting is for the version shown; one that changed meanwhile is read again first.
|
|
95
|
+
if (!(await services.terms.accept(identity.userId, context.req.valid('json').version))) {
|
|
96
|
+
return context.json({ error: { code: 'terms_changed' as const } }, 409)
|
|
97
|
+
}
|
|
98
|
+
return context.json({ ok: true as const })
|
|
99
|
+
})
|
|
75
100
|
.get('/api/account/mfa', async (context) => {
|
|
76
101
|
const actor = await resolveSession(context.req.raw)
|
|
77
102
|
if (!actor) return context.json({ error: { code: 'unauthorized' as const } }, 401)
|
|
@@ -205,6 +230,9 @@ export function createAccountRoutes(services: AccountRouteDependencies) {
|
|
|
205
230
|
.use('/api/account/sessions', requireActiveSession)
|
|
206
231
|
.use('/api/account/sessions/*', requireActiveSession)
|
|
207
232
|
.use('/api/account/sign-ins', requireActiveSession)
|
|
233
|
+
.use('/api/account/deletion', services.requireAccountSession)
|
|
234
|
+
.use('/api/account/delete', services.requireAccountSession)
|
|
235
|
+
.use('/api/account/delete', authenticatedMutationLimiter)
|
|
208
236
|
.use('/api/account/profile', authenticatedMutationLimiter)
|
|
209
237
|
.use('/api/account/profile/*', authenticatedMutationLimiter)
|
|
210
238
|
.use('/api/account/sessions/*', authenticatedMutationLimiter)
|
|
@@ -287,6 +315,22 @@ export function createAccountRoutes(services: AccountRouteDependencies) {
|
|
|
287
315
|
if (!signIns) return context.json({ error: { code: 'unauthorized' as const } }, 401)
|
|
288
316
|
return context.json({ signIns })
|
|
289
317
|
})
|
|
318
|
+
.get('/api/account/deletion', async (context) => {
|
|
319
|
+
return context.json({ deletion: await services.deletion.plan(context.get('actor').userId) })
|
|
320
|
+
})
|
|
321
|
+
.post('/api/account/delete', validatedJSON(parseCloudAccountDelete), async (context) => {
|
|
322
|
+
const result = await accountAction(
|
|
323
|
+
() =>
|
|
324
|
+
services.auth.deleteAccount(context.req.raw.headers, context.req.valid('json').password),
|
|
325
|
+
context
|
|
326
|
+
)
|
|
327
|
+
if (result instanceof Response) return result
|
|
328
|
+
// The session is gone with the account; the cookie that named it goes too.
|
|
329
|
+
for (const cookie of result.getSetCookie()) {
|
|
330
|
+
context.header('Set-Cookie', cookie, { append: true })
|
|
331
|
+
}
|
|
332
|
+
return context.json({ ok: true as const })
|
|
333
|
+
})
|
|
290
334
|
.get('/api/account/authentication', async (context) => {
|
|
291
335
|
const result = await accountAction(
|
|
292
336
|
() => accountAuthentication.methods(context.req.raw.headers),
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import type { CloudServerConfig } from '#cloud/server/config'
|
|
2
|
+
import type { CloudDatabase } from '#cloud/server/db'
|
|
3
|
+
import type { Kysely } from 'kysely'
|
|
4
|
+
|
|
5
|
+
/** Whether an account accepted the deployment's current terms, and recording that it did. */
|
|
6
|
+
export type TermsService = {
|
|
7
|
+
/** The version accounts accept, when the deployment requires acceptance. */
|
|
8
|
+
readonly requiredVersion: string | undefined
|
|
9
|
+
/** True when nothing is required, or the account accepted the current version. */
|
|
10
|
+
hasAccepted(userId: string): Promise<boolean>
|
|
11
|
+
/** Records acceptance of the current version; false when `version` is not the current one. */
|
|
12
|
+
accept(userId: string, version: string): Promise<boolean>
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
export function createTermsService(
|
|
16
|
+
database: Kysely<CloudDatabase>,
|
|
17
|
+
config: CloudServerConfig
|
|
18
|
+
): TermsService {
|
|
19
|
+
const requiredVersion = config.legal?.requireAcceptance ? config.legal.termsVersion : undefined
|
|
20
|
+
return {
|
|
21
|
+
requiredVersion,
|
|
22
|
+
async hasAccepted(userId) {
|
|
23
|
+
if (!requiredVersion) return true
|
|
24
|
+
const row = await database
|
|
25
|
+
.selectFrom('termsAcceptance')
|
|
26
|
+
.select('userId')
|
|
27
|
+
.where('userId', '=', userId)
|
|
28
|
+
.where('version', '=', requiredVersion)
|
|
29
|
+
.executeTakeFirst()
|
|
30
|
+
return row !== undefined
|
|
31
|
+
},
|
|
32
|
+
async accept(userId, version) {
|
|
33
|
+
if (!requiredVersion || version !== requiredVersion) return false
|
|
34
|
+
await database
|
|
35
|
+
.insertInto('termsAcceptance')
|
|
36
|
+
.values({ userId, version, acceptedAt: new Date() })
|
|
37
|
+
.onConflict((conflict) => conflict.columns(['userId', 'version']).doNothing())
|
|
38
|
+
.execute()
|
|
39
|
+
return true
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
}
|
package/src/server/api/router.ts
CHANGED
|
@@ -1,4 +1,3 @@
|
|
|
1
|
-
import { createAIRoutes, type AITokenService } from '#cloud/server/ai'
|
|
2
1
|
import type { CloudAPIEnvironment } from '#cloud/server/api/types'
|
|
3
2
|
import type { CloudSessionResolver } from '#cloud/server/auth'
|
|
4
3
|
import type { CollaborationTicketService } from '#cloud/server/collaboration'
|
|
@@ -14,12 +13,15 @@ import {
|
|
|
14
13
|
type DocumentVersionService
|
|
15
14
|
} from '#cloud/server/documents/versions'
|
|
16
15
|
import type { EntitlementService } from '#cloud/server/policy'
|
|
16
|
+
import { createPublicReportRoutes, type DocumentReportService } from '#cloud/server/reports'
|
|
17
|
+
import { createServicesRoutes, type ServicesTokenService } from '#cloud/server/services'
|
|
17
18
|
import type { DocumentSharingService } from '#cloud/server/sharing'
|
|
18
19
|
import {
|
|
19
20
|
createDocumentSharingRoutes,
|
|
20
21
|
createPublicDocumentRoutes,
|
|
21
22
|
createPublicSharingRoutes
|
|
22
23
|
} from '#cloud/server/sharing'
|
|
24
|
+
import { workspaceParams } from '#cloud/server/validation'
|
|
23
25
|
import type { WorkspaceMemberService, WorkspaceService } from '#cloud/server/workspaces'
|
|
24
26
|
import { createWorkspaceRoutes } from '#cloud/server/workspaces'
|
|
25
27
|
import { Hono } from 'hono'
|
|
@@ -32,16 +34,19 @@ export type CloudAPIServices = {
|
|
|
32
34
|
documents: DocumentService
|
|
33
35
|
versions: DocumentVersionService
|
|
34
36
|
sharing: DocumentSharingService
|
|
37
|
+
/** Reports about documents shared by link. */
|
|
38
|
+
reports: DocumentReportService
|
|
35
39
|
resolveSession?: CloudSessionResolver
|
|
36
40
|
entitlements?: EntitlementService
|
|
37
|
-
/** Signs
|
|
38
|
-
|
|
41
|
+
/** Signs service tokens; without it the deployment offers no services. */
|
|
42
|
+
servicesTokens?: ServicesTokenService
|
|
39
43
|
workspaces: WorkspaceService
|
|
40
44
|
workspaceMembers: WorkspaceMemberService
|
|
41
45
|
}
|
|
42
46
|
|
|
43
47
|
export function createPublicCloudAPIRouter(services: CloudAPIServices) {
|
|
44
48
|
return new Hono<CloudAPIEnvironment>()
|
|
49
|
+
.route('/', createPublicReportRoutes(services.reports, services.resolveSession))
|
|
45
50
|
.route('/', createPublicSharingRoutes(services.sharing, services.resolveSession))
|
|
46
51
|
.route(
|
|
47
52
|
'/',
|
|
@@ -53,21 +58,21 @@ export function createPublicCloudAPIRouter(services: CloudAPIServices) {
|
|
|
53
58
|
export function createCloudAPIRouter(services: CloudAPIServices) {
|
|
54
59
|
return new Hono<CloudAPIEnvironment>()
|
|
55
60
|
.route('/public', createPublicCloudAPIRouter(services))
|
|
56
|
-
.get('/workspaces/:workspaceId/entitlements', async (context) => {
|
|
61
|
+
.get('/workspaces/:workspaceId/entitlements', workspaceParams, async (context) => {
|
|
57
62
|
if (!services.entitlements)
|
|
58
63
|
return context.json({ error: { code: 'not_found' as const } }, 404)
|
|
59
64
|
return context.json({
|
|
60
65
|
entitlements: await services.entitlements.workspace(
|
|
61
66
|
context.get('actor').userId,
|
|
62
|
-
context.req.
|
|
67
|
+
context.req.valid('param').workspaceId
|
|
63
68
|
)
|
|
64
69
|
})
|
|
65
70
|
})
|
|
66
71
|
.get('/session', (context) => context.json({ user: context.get('actor') }))
|
|
67
72
|
.route(
|
|
68
73
|
'/',
|
|
69
|
-
|
|
70
|
-
services.
|
|
74
|
+
createServicesRoutes(
|
|
75
|
+
services.servicesTokens,
|
|
71
76
|
services.database && services.rateLimitSecret
|
|
72
77
|
? { database: services.database, secret: services.rateLimitSecret }
|
|
73
78
|
: undefined
|
package/src/server/api/types.ts
CHANGED
|
@@ -1,7 +1,16 @@
|
|
|
1
1
|
import type { CloudActor } from '#cloud/server/auth'
|
|
2
2
|
|
|
3
|
+
/** What a rate limiter records on the request about the budget it just counted. */
|
|
4
|
+
export type RateLimitUse = { limit: number; remaining: number; resetTime?: Date }
|
|
5
|
+
|
|
3
6
|
export type CloudAPIEnvironment = {
|
|
4
7
|
Variables: {
|
|
5
8
|
actor: CloudActor
|
|
9
|
+
/** Set by `cloudRequestId`: what logs and error reports name the request by. */
|
|
10
|
+
requestId: string
|
|
11
|
+
/** Set by `hono-rate-limiter` for the last budget it counted. */
|
|
12
|
+
rateLimit?: RateLimitUse
|
|
13
|
+
/** A resource budget's use, kept before the actor-wide budget records its own. */
|
|
14
|
+
resourceRateLimit?: RateLimitUse
|
|
6
15
|
}
|
|
7
16
|
}
|