@pairdraw/cloud 0.18.0 → 0.19.0
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 +5 -10
- package/dist/client.d.ts.map +1 -1
- package/dist/client.js +0 -7
- package/dist/client.js.map +1 -1
- package/dist/contract.d.ts +2 -2
- package/dist/contract.js +2 -2
- package/dist/contract2.js +8 -5
- package/dist/contract2.js.map +1 -1
- package/dist/email.js.map +1 -1
- package/dist/index.d.ts +9 -7
- package/dist/index.d.ts.map +1 -1
- package/dist/listen.mjs +202 -110
- package/dist/listen.mjs.map +1 -1
- package/dist/runtime-node.d.mts +2299 -661
- package/dist/runtime-node.d.mts.map +1 -1
- package/dist/server.d.ts +3319 -985
- package/dist/server.d.ts.map +1 -1
- package/dist/server.js +415 -190
- package/dist/server.js.map +1 -1
- package/dist/server.mjs +243 -79
- package/dist/server.mjs.map +1 -1
- package/package.json +2 -2
- package/src/client/api.ts +0 -15
- package/src/contract/documents.ts +8 -0
- package/src/contract/index.ts +1 -3
- package/src/contract/sharing.ts +0 -9
- package/src/runtime/cloudflare/relay.ts +5 -1
- package/src/runtime/cloudflare/worker.ts +4 -1
- package/src/runtime/node/bootstrap.ts +13 -3
- package/src/runtime/node/cleanup.ts +5 -1
- package/src/runtime/node/migrate.ts +5 -1
- package/src/runtime/node/server.ts +12 -2
- package/src/runtime/postgres/database.ts +20 -1
- package/src/runtime/site/server.ts +19 -2
- package/src/server/api/router.ts +16 -8
- package/src/server/api/types.ts +7 -0
- package/src/server/app.ts +9 -0
- package/src/server/auth/factory.ts +3 -0
- package/src/server/collaboration/relay/hub.ts +42 -3
- package/src/server/collaboration/routes.ts +21 -14
- package/src/server/config/schema.ts +3 -0
- package/src/server/db/expressions.ts +13 -1
- package/src/server/db/migrate.ts +3 -1
- package/src/server/db/migrations/028_invitation_sends.ts +31 -0
- package/src/server/db/tables.ts +9 -0
- package/src/server/documents/access.ts +4 -2
- package/src/server/documents/routes.ts +81 -57
- package/src/server/documents/versions/routes.ts +27 -16
- package/src/server/index.ts +2 -0
- package/src/server/invitations/budget.ts +66 -0
- package/src/server/invitations/index.ts +1 -0
- package/src/server/profiles/routes.ts +16 -12
- 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 +98 -11
- package/src/server/sharing/capabilities/service.ts +27 -2
- package/src/server/sharing/document-routes.ts +30 -22
- package/src/server/sharing/grants/service.ts +13 -7
- package/src/server/sharing/http.ts +4 -0
- package/src/server/sharing/invitations/service.ts +2 -0
- package/src/server/sharing/routes.ts +79 -64
- package/src/server/sharing/service.ts +1 -17
- package/src/server/validation.ts +76 -0
- package/src/server/workspaces/members.ts +2 -0
- package/src/server/workspaces/routes.ts +56 -35
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@pairdraw/cloud",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.19.0",
|
|
4
4
|
"license": "Apache-2.0 AND MIT",
|
|
5
5
|
"files": [
|
|
6
6
|
"dist",
|
|
@@ -23,7 +23,7 @@
|
|
|
23
23
|
"@internationalized/date": "^3.12.3",
|
|
24
24
|
"@noble/hashes": "^2.4.0",
|
|
25
25
|
"@openfeature/server-sdk": "^1.23.0",
|
|
26
|
-
"@pairdraw/scene-graph": "^0.
|
|
26
|
+
"@pairdraw/scene-graph": "^0.19.0",
|
|
27
27
|
"@vue-email/components": "^0.0.21",
|
|
28
28
|
"@vue-email/render": "^0.0.9",
|
|
29
29
|
"better-auth": "1.7.7",
|
package/src/client/api.ts
CHANGED
|
@@ -47,7 +47,6 @@ import {
|
|
|
47
47
|
type UpdateDocumentVersionInput,
|
|
48
48
|
type SharedDocument,
|
|
49
49
|
type InvitationPreview,
|
|
50
|
-
type LookupCloudUserInput,
|
|
51
50
|
type PutDocumentGrantInput,
|
|
52
51
|
type ResolveDocumentShareInput,
|
|
53
52
|
type UpdateDocumentShareInput,
|
|
@@ -146,20 +145,6 @@ export function createCloudAPIClient(baseURL: string, options: CloudRequestOptio
|
|
|
146
145
|
options.onDiagnostic
|
|
147
146
|
)
|
|
148
147
|
},
|
|
149
|
-
async lookupUser(
|
|
150
|
-
documentId: string,
|
|
151
|
-
input: LookupCloudUserInput
|
|
152
|
-
): Promise<CloudUserProfile | null> {
|
|
153
|
-
const response = await parseResponse(
|
|
154
|
-
client.documents[':documentId'].users.lookup.$post({
|
|
155
|
-
param: { documentId },
|
|
156
|
-
json: input
|
|
157
|
-
}),
|
|
158
|
-
userLookupResponseSchema,
|
|
159
|
-
options.onDiagnostic
|
|
160
|
-
)
|
|
161
|
-
return response.user
|
|
162
|
-
},
|
|
163
148
|
async getUserProfile(documentId: string, userId: string): Promise<CloudUserProfile | null> {
|
|
164
149
|
const response = await parseResponse(
|
|
165
150
|
client.documents[':documentId'].users[':userId'].$get({
|
|
@@ -12,6 +12,14 @@ export function isCloudChecksum(value: string): boolean {
|
|
|
12
12
|
/** The most images one revision, or one request for image uploads, may name. */
|
|
13
13
|
export const CLOUD_MAX_DOCUMENT_IMAGES = 10_000
|
|
14
14
|
|
|
15
|
+
/**
|
|
16
|
+
* The most a Cloud API request body may hold; a server refuses anything past it before reading
|
|
17
|
+
* it. Files go to the object store, never through the API, so only lists grow large: a save's
|
|
18
|
+
* images fit with room to spare, and a client commits image uploads, whose part lists can run
|
|
19
|
+
* long, in batches under half of it.
|
|
20
|
+
*/
|
|
21
|
+
export const CLOUD_API_MAX_BODY_BYTES = 8 * 1024 * 1024
|
|
22
|
+
|
|
15
23
|
/**
|
|
16
24
|
* An image's name inside a `.fig` file that Cloud stores apart from it: the SHA-1 Figma names it
|
|
17
25
|
* by, or an older plain name. A client leaves images under other names inside the file.
|
package/src/contract/index.ts
CHANGED
|
@@ -66,6 +66,7 @@ export {
|
|
|
66
66
|
type CloudListing
|
|
67
67
|
} from './discovery'
|
|
68
68
|
export {
|
|
69
|
+
CLOUD_API_MAX_BODY_BYTES,
|
|
69
70
|
CLOUD_DOCUMENT_NAME_MAX_LENGTH,
|
|
70
71
|
CLOUD_IMAGE_NAME_PATTERN,
|
|
71
72
|
CLOUD_MAX_DOCUMENT_IMAGES,
|
|
@@ -130,12 +131,10 @@ export {
|
|
|
130
131
|
documentShareSchema,
|
|
131
132
|
invitationContinuationSchema,
|
|
132
133
|
invitationPreviewSchema,
|
|
133
|
-
lookupCloudUserSchema,
|
|
134
134
|
parseAcceptDocumentInvitation,
|
|
135
135
|
parseCreateInvitationContinuation,
|
|
136
136
|
parseCreateDocumentInvitation,
|
|
137
137
|
parseCreateDocumentShare,
|
|
138
|
-
parseLookupCloudUser,
|
|
139
138
|
parsePutDocumentGrant,
|
|
140
139
|
parseRequestSharedImageLinks,
|
|
141
140
|
parseResolveDocumentShare,
|
|
@@ -157,7 +156,6 @@ export {
|
|
|
157
156
|
type DocumentShare,
|
|
158
157
|
type InvitationContinuation,
|
|
159
158
|
type InvitationPreview,
|
|
160
|
-
type LookupCloudUserInput,
|
|
161
159
|
type PutDocumentGrantInput,
|
|
162
160
|
type RequestSharedImageLinksInput,
|
|
163
161
|
type ResolveDocumentShareInput,
|
package/src/contract/sharing.ts
CHANGED
|
@@ -113,11 +113,6 @@ export const acceptedInvitationSchema = v.variant('kind', [
|
|
|
113
113
|
])
|
|
114
114
|
export type AcceptedInvitation = v.InferOutput<typeof acceptedInvitationSchema>
|
|
115
115
|
|
|
116
|
-
export const lookupCloudUserSchema = v.object({
|
|
117
|
-
email: v.pipe(v.string(), v.trim(), v.toLowerCase(), v.email())
|
|
118
|
-
})
|
|
119
|
-
export type LookupCloudUserInput = v.InferOutput<typeof lookupCloudUserSchema>
|
|
120
|
-
|
|
121
116
|
export const putDocumentGrantSchema = v.object({ permission: documentPermissionSchema })
|
|
122
117
|
export type PutDocumentGrantInput = v.InferOutput<typeof putDocumentGrantSchema>
|
|
123
118
|
|
|
@@ -186,10 +181,6 @@ export function parseCreateInvitationContinuation(
|
|
|
186
181
|
return v.parse(createInvitationContinuationSchema, input)
|
|
187
182
|
}
|
|
188
183
|
|
|
189
|
-
export function parseLookupCloudUser(input: unknown): LookupCloudUserInput {
|
|
190
|
-
return v.parse(lookupCloudUserSchema, input)
|
|
191
|
-
}
|
|
192
|
-
|
|
193
184
|
export function parseCreateDocumentShare(input: unknown): CreateDocumentShareInput {
|
|
194
185
|
return v.parse(createDocumentShareSchema, input)
|
|
195
186
|
}
|
|
@@ -97,7 +97,11 @@ export function createCloudflareRelayObject(
|
|
|
97
97
|
|
|
98
98
|
#open(documentId: string) {
|
|
99
99
|
this.#relay ??= prepare(this.env).then(({ config }) => {
|
|
100
|
-
|
|
100
|
+
// Hyperdrive keeps no session settings and ends queries past its own limit.
|
|
101
|
+
const database = createPostgresCloudDatabase({
|
|
102
|
+
connectionString: config.databaseURL,
|
|
103
|
+
statementTimeoutMs: null
|
|
104
|
+
})
|
|
101
105
|
this.#opened = createCollaborationRelay({
|
|
102
106
|
authSecret: config.authSecret,
|
|
103
107
|
documentId,
|
|
@@ -40,7 +40,10 @@ function cloudServices(
|
|
|
40
40
|
context: Pick<ExecutionContext, 'waitUntil'>
|
|
41
41
|
) {
|
|
42
42
|
const { config } = prepared
|
|
43
|
-
const database = createPostgresCloudDatabase({
|
|
43
|
+
const database = createPostgresCloudDatabase({
|
|
44
|
+
connectionString: config.databaseURL,
|
|
45
|
+
statementTimeoutMs: null
|
|
46
|
+
})
|
|
44
47
|
const objects = createS3ObjectStore(config)
|
|
45
48
|
const transport = emailTransport(prepared, env)
|
|
46
49
|
const queued = createTransactionalEmailService(database, {
|
|
@@ -15,8 +15,18 @@ export async function createMigratedNodeCloudDatabase(
|
|
|
15
15
|
auth: ReturnType<typeof createBetterAuthAdapter>
|
|
16
16
|
}> {
|
|
17
17
|
const config = await loadNodeCloudServerConfig(environment)
|
|
18
|
+
// Migrations run on a connection of their own without the statement timeout, since one may
|
|
19
|
+
// rewrite a large table.
|
|
20
|
+
const migrating = createPostgresCloudDatabase({
|
|
21
|
+
connectionString: config.databaseURL,
|
|
22
|
+
statementTimeoutMs: null
|
|
23
|
+
})
|
|
24
|
+
try {
|
|
25
|
+
const auth = createBetterAuthAdapter(config, migrating)
|
|
26
|
+
await migrateCloudDatabase(migrating, { run: auth.migrate, schemaVersion: auth.schemaVersion })
|
|
27
|
+
} finally {
|
|
28
|
+
await migrating.destroy()
|
|
29
|
+
}
|
|
18
30
|
const database = createPostgresCloudDatabase({ connectionString: config.databaseURL })
|
|
19
|
-
|
|
20
|
-
await migrateCloudDatabase(database, { run: auth.migrate, schemaVersion: auth.schemaVersion })
|
|
21
|
-
return { config, database, auth }
|
|
31
|
+
return { config, database, auth: createBetterAuthAdapter(config, database) }
|
|
22
32
|
}
|
|
@@ -10,7 +10,11 @@ import {
|
|
|
10
10
|
import { loadNodeCloudServerConfig } from './config'
|
|
11
11
|
|
|
12
12
|
const config = await loadNodeCloudServerConfig(process.env)
|
|
13
|
-
|
|
13
|
+
// A sweep may take longer than a request should.
|
|
14
|
+
const database = createPostgresCloudDatabase({
|
|
15
|
+
connectionString: config.databaseURL,
|
|
16
|
+
statementTimeoutMs: null
|
|
17
|
+
})
|
|
14
18
|
const objects = createS3ObjectStore(config)
|
|
15
19
|
try {
|
|
16
20
|
const policy = createConfiguredCloudPolicy(config, database)
|
|
@@ -4,7 +4,11 @@ import { createBetterAuthAdapter, migrateCloudDatabase } from '#cloud/server'
|
|
|
4
4
|
import { loadNodeCloudServerConfig } from './config'
|
|
5
5
|
|
|
6
6
|
const config = await loadNodeCloudServerConfig(process.env)
|
|
7
|
-
|
|
7
|
+
// A migration may rewrite a large table, which takes as long as it takes.
|
|
8
|
+
const database = createPostgresCloudDatabase({
|
|
9
|
+
connectionString: config.databaseURL,
|
|
10
|
+
statementTimeoutMs: null
|
|
11
|
+
})
|
|
8
12
|
try {
|
|
9
13
|
const auth = createBetterAuthAdapter(config, database)
|
|
10
14
|
await migrateCloudDatabase(database, { run: auth.migrate, schemaVersion: auth.schemaVersion })
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { defaultRelayURL } from '#cloud/contract'
|
|
2
|
+
import { createPostgresCloudDatabase } from '#cloud/runtime/postgres/database'
|
|
2
3
|
import { createS3ObjectStore } from '#cloud/runtime/s3/objects'
|
|
3
4
|
import { createCloudServer, type SiteFiles } from '#cloud/runtime/site/server'
|
|
4
5
|
import {
|
|
@@ -54,8 +55,16 @@ export async function startNodeCloudServer(options: NodeCloudServerOptions = {})
|
|
|
54
55
|
} = createNodeTransactionalEmailRuntime(config, database)
|
|
55
56
|
const { auth, enrollment } = createCloudAuthenticationRuntime(config, database, email)
|
|
56
57
|
const policy = createConfiguredCloudPolicy(config, database)
|
|
57
|
-
|
|
58
|
-
|
|
58
|
+
// Cleanup sweeps may run longer than a request should, so they have a connection of their own
|
|
59
|
+
// without the statement timeout.
|
|
60
|
+
const cleanupDatabase = config.cleanupEnabled
|
|
61
|
+
? createPostgresCloudDatabase({
|
|
62
|
+
connectionString: config.databaseURL,
|
|
63
|
+
statementTimeoutMs: null
|
|
64
|
+
})
|
|
65
|
+
: undefined
|
|
66
|
+
const cleanup = cleanupDatabase
|
|
67
|
+
? startCleanupWorker(createCleanupServices(config, cleanupDatabase, objects, policy), {
|
|
59
68
|
...cleanupPassOptions(config),
|
|
60
69
|
intervalMs: config.cleanupIntervalMs,
|
|
61
70
|
onError: (error) => console.error('[Cloud] Cleanup worker failed:', error)
|
|
@@ -112,6 +121,7 @@ export async function startNodeCloudServer(options: NodeCloudServerOptions = {})
|
|
|
112
121
|
await relayListener.close()
|
|
113
122
|
await server.close()
|
|
114
123
|
await cleanup?.stop()
|
|
124
|
+
await cleanupDatabase?.destroy()
|
|
115
125
|
await emailWorker?.stop()
|
|
116
126
|
await database.destroy()
|
|
117
127
|
}
|
|
@@ -2,16 +2,35 @@ import { createCloudDatabase } from '#cloud/server'
|
|
|
2
2
|
import { PostgresDialect } from 'kysely'
|
|
3
3
|
import { Pool, type PoolConfig } from 'pg'
|
|
4
4
|
|
|
5
|
+
/**
|
|
6
|
+
* How long a query serving a request may run before PostgreSQL cancels it. Rate limits and
|
|
7
|
+
* sessions live in PostgreSQL, so one stuck query would otherwise hold its connection, and every
|
|
8
|
+
* request waiting for one, indefinitely.
|
|
9
|
+
*/
|
|
10
|
+
export const POSTGRES_STATEMENT_TIMEOUT_MS = 30_000
|
|
11
|
+
|
|
5
12
|
export type PostgresCloudDatabaseOptions = {
|
|
6
13
|
connectionString: string
|
|
7
|
-
pool?: Omit<PoolConfig, 'connectionString'>
|
|
14
|
+
pool?: Omit<PoolConfig, 'connectionString' | 'statement_timeout' | 'query_timeout'>
|
|
15
|
+
/**
|
|
16
|
+
* How long one statement may run, `POSTGRES_STATEMENT_TIMEOUT_MS` unless set; null for no limit
|
|
17
|
+
* of this server's own, as migrations need and as Hyperdrive takes, which keeps no session
|
|
18
|
+
* settings and ends queries past its own limit. PostgreSQL cancels a statement past it, so its
|
|
19
|
+
* connection is free again for the next query.
|
|
20
|
+
*/
|
|
21
|
+
statementTimeoutMs?: number | null
|
|
8
22
|
}
|
|
9
23
|
|
|
10
24
|
export function createPostgresCloudDatabase(options: PostgresCloudDatabaseOptions) {
|
|
25
|
+
const statementTimeoutMs =
|
|
26
|
+
options.statementTimeoutMs === undefined
|
|
27
|
+
? POSTGRES_STATEMENT_TIMEOUT_MS
|
|
28
|
+
: options.statementTimeoutMs
|
|
11
29
|
return createCloudDatabase({
|
|
12
30
|
dialect: new PostgresDialect({
|
|
13
31
|
pool: new Pool({
|
|
14
32
|
...options.pool,
|
|
33
|
+
...(statementTimeoutMs === null ? {} : { statement_timeout: statementTimeoutMs }),
|
|
15
34
|
connectionString: options.connectionString
|
|
16
35
|
})
|
|
17
36
|
})
|
|
@@ -16,11 +16,28 @@ export type SiteFiles = (path: string, request: Request) => Promise<SiteFile | n
|
|
|
16
16
|
const PORTAL_PAGE = '/cloud.html'
|
|
17
17
|
const EDITOR_PAGE = '/index.html'
|
|
18
18
|
|
|
19
|
+
/**
|
|
20
|
+
* What the site's pages may run: only the site's own scripts and Turnstile's on the portal, so an
|
|
21
|
+
* injected script tag or one from another host never runs. The pages carry no inline script (the
|
|
22
|
+
* boot splash loads its own file). The editor compiles design JSX and code-tool snippets with
|
|
23
|
+
* `Function` and runs WebAssembly and workers from blobs, which the policy keeps; plugins and AI
|
|
24
|
+
* providers reach other hosts through `fetch`, which it leaves be. Desktop sign-in approval and
|
|
25
|
+
* the editor must never be framed by another site.
|
|
26
|
+
*/
|
|
27
|
+
export const SITE_CONTENT_SECURITY_POLICY = [
|
|
28
|
+
"script-src 'self' 'unsafe-eval' 'wasm-unsafe-eval' blob: https://challenges.cloudflare.com",
|
|
29
|
+
"worker-src 'self' blob:",
|
|
30
|
+
"object-src 'none'",
|
|
31
|
+
"base-uri 'self'",
|
|
32
|
+
"frame-ancestors 'none'"
|
|
33
|
+
].join('; ')
|
|
34
|
+
|
|
19
35
|
const PAGE_HEADERS = {
|
|
20
36
|
'Content-Type': 'text/html; charset=utf-8',
|
|
21
37
|
'Cache-Control': 'no-cache',
|
|
22
|
-
|
|
23
|
-
|
|
38
|
+
'Content-Security-Policy': SITE_CONTENT_SECURITY_POLICY,
|
|
39
|
+
// Browsers take this only over HTTPS; a deployment on plain HTTP is unaffected.
|
|
40
|
+
'Strict-Transport-Security': 'max-age=31536000',
|
|
24
41
|
'Referrer-Policy': 'no-referrer',
|
|
25
42
|
'X-Content-Type-Options': 'nosniff'
|
|
26
43
|
}
|
package/src/server/api/router.ts
CHANGED
|
@@ -8,7 +8,7 @@ import {
|
|
|
8
8
|
} from '#cloud/server/collaboration'
|
|
9
9
|
import type { CloudDatabase } from '#cloud/server/db'
|
|
10
10
|
import type { DocumentService } from '#cloud/server/documents'
|
|
11
|
-
import { createDocumentRoutes } from '#cloud/server/documents'
|
|
11
|
+
import { createDocumentRoutes, DocumentNotFoundError } from '#cloud/server/documents'
|
|
12
12
|
import {
|
|
13
13
|
createDocumentVersionRoutes,
|
|
14
14
|
type DocumentVersionService
|
|
@@ -25,6 +25,7 @@ import {
|
|
|
25
25
|
createPublicDocumentRoutes,
|
|
26
26
|
createPublicSharingRoutes
|
|
27
27
|
} from '#cloud/server/sharing'
|
|
28
|
+
import { workspaceParams } from '#cloud/server/validation'
|
|
28
29
|
import type { WorkspaceMemberService, WorkspaceService } from '#cloud/server/workspaces'
|
|
29
30
|
import { createWorkspaceRoutes } from '#cloud/server/workspaces'
|
|
30
31
|
import { Hono } from 'hono'
|
|
@@ -65,15 +66,22 @@ export function createCloudAPIRouter(services: CloudAPIServices) {
|
|
|
65
66
|
return new Hono<CloudAPIEnvironment>()
|
|
66
67
|
.route('/', createPublicProfileSettingsRoutes(services.profiles))
|
|
67
68
|
.route('/public', createPublicCloudAPIRouter(services))
|
|
68
|
-
.get('/workspaces/:workspaceId/entitlements', async (context) => {
|
|
69
|
+
.get('/workspaces/:workspaceId/entitlements', workspaceParams, async (context) => {
|
|
69
70
|
if (!services.entitlements)
|
|
70
71
|
return context.json({ error: { code: 'not_found' as const } }, 404)
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
72
|
+
try {
|
|
73
|
+
return context.json({
|
|
74
|
+
entitlements: await services.entitlements.workspace(
|
|
75
|
+
context.get('actor').userId,
|
|
76
|
+
context.req.valid('param').workspaceId
|
|
77
|
+
)
|
|
78
|
+
})
|
|
79
|
+
} catch (error) {
|
|
80
|
+
// A workspace the account left, or one that has gone, since the editor listed it.
|
|
81
|
+
if (error instanceof DocumentNotFoundError)
|
|
82
|
+
return context.json({ error: { code: 'not_found' as const } }, 404)
|
|
83
|
+
throw error
|
|
84
|
+
}
|
|
77
85
|
})
|
|
78
86
|
.get('/session', (context) => context.json({ user: context.get('actor') }))
|
|
79
87
|
.route(
|
package/src/server/api/types.ts
CHANGED
|
@@ -1,7 +1,14 @@
|
|
|
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 `hono-rate-limiter` for the last budget it counted. */
|
|
10
|
+
rateLimit?: RateLimitUse
|
|
11
|
+
/** A resource budget's use, kept before the actor-wide budget records its own. */
|
|
12
|
+
resourceRateLimit?: RateLimitUse
|
|
6
13
|
}
|
|
7
14
|
}
|
package/src/server/app.ts
CHANGED
|
@@ -9,6 +9,7 @@ import {
|
|
|
9
9
|
} from '#cloud/admin'
|
|
10
10
|
import {
|
|
11
11
|
CLOUD_AI_JWKS_PATH,
|
|
12
|
+
CLOUD_API_MAX_BODY_BYTES,
|
|
12
13
|
CLOUD_DISCOVERY_PATH,
|
|
13
14
|
CLOUD_PROTOCOL_VERSION,
|
|
14
15
|
type CloudDiscovery
|
|
@@ -61,6 +62,7 @@ import {
|
|
|
61
62
|
import { createDocumentSharingService } from '#cloud/server/sharing'
|
|
62
63
|
import { createWorkspaceMemberService, createWorkspaceService } from '#cloud/server/workspaces'
|
|
63
64
|
import { Hono, type Context } from 'hono'
|
|
65
|
+
import { bodyLimit } from 'hono/body-limit'
|
|
64
66
|
import { cors } from 'hono/cors'
|
|
65
67
|
import type { Kysely } from 'kysely'
|
|
66
68
|
|
|
@@ -322,6 +324,13 @@ export function createCloudApp(services: CloudServices) {
|
|
|
322
324
|
return new Hono<CloudEnvironment>()
|
|
323
325
|
.use(CLOUD_DISCOVERY_PATH, cloudCORS)
|
|
324
326
|
.use('/api/*', cloudCORS)
|
|
327
|
+
.use(
|
|
328
|
+
'/api/*',
|
|
329
|
+
bodyLimit({
|
|
330
|
+
maxSize: CLOUD_API_MAX_BODY_BYTES,
|
|
331
|
+
onError: (context) => context.json({ error: { code: 'invalid_request' as const } }, 413)
|
|
332
|
+
})
|
|
333
|
+
)
|
|
325
334
|
.use('*', async (context, next) => {
|
|
326
335
|
await next()
|
|
327
336
|
if (shouldPreventIndexing(context.req.path, services.config.indexingPolicy)) {
|
|
@@ -156,6 +156,9 @@ export function createBetterAuthAdapter(
|
|
|
156
156
|
customRules: {
|
|
157
157
|
[devices.endpoints.deviceCode.path]: { window: 60, max: 10 },
|
|
158
158
|
[devices.endpoints.deviceToken.path]: { window: 60, max: 60 },
|
|
159
|
+
// The plugin's own budget is 5 lookups per code lifetime (30 minutes), so reopening the
|
|
160
|
+
// sign-in page a few times turned away every new code for half an hour.
|
|
161
|
+
[devices.endpoints.deviceVerify.path]: { window: 60, max: 20 },
|
|
159
162
|
[devices.endpoints.deviceApprove.path]: { window: 60, max: 10 },
|
|
160
163
|
[devices.endpoints.deviceDeny.path]: { window: 60, max: 10 },
|
|
161
164
|
[CORE_AUTH_PATHS.signInEmail]: { window: 10, max: 3 },
|
|
@@ -26,6 +26,18 @@ export type RelaySocket = {
|
|
|
26
26
|
close(code: number, reason: string): void
|
|
27
27
|
}
|
|
28
28
|
|
|
29
|
+
/** Whether `update` adds nothing and deletes only content `document` already holds. */
|
|
30
|
+
function deletesOnlyKnown(document: Y.Doc, update: Uint8Array): boolean {
|
|
31
|
+
const { from, to } = Y.parseUpdateMetaV2(update)
|
|
32
|
+
if (![...to].every(([client, clock]) => from.get(client) === clock)) return false
|
|
33
|
+
const { ds } = Y.decodeUpdateV2(update)
|
|
34
|
+
for (const [client, deletions] of ds.clients) {
|
|
35
|
+
const held = Y.getState(document.store, client)
|
|
36
|
+
if (deletions.some((deletion) => deletion.clock + deletion.len > held)) return false
|
|
37
|
+
}
|
|
38
|
+
return true
|
|
39
|
+
}
|
|
40
|
+
|
|
29
41
|
/** What the adapter reports back about that socket. */
|
|
30
42
|
export type RelayConnection = {
|
|
31
43
|
receive(data: Uint8Array): void
|
|
@@ -45,6 +57,11 @@ export type CollaborationRelayOptions = {
|
|
|
45
57
|
* up to `MAX_COLLAB_MESSAGE_BYTES`; anyone else's frame must fit in one message.
|
|
46
58
|
*/
|
|
47
59
|
maximumMessageBytes: number
|
|
60
|
+
/**
|
|
61
|
+
* The most a room's document may hold: `MAX_COLLAB_MESSAGE_BYTES` unless the runtime holds
|
|
62
|
+
* rooms in less memory.
|
|
63
|
+
*/
|
|
64
|
+
maximumRoomBytes?: number
|
|
48
65
|
maximumConnectionsPerRoom: number
|
|
49
66
|
/** The participant limit policy sets for a document, or null for none. */
|
|
50
67
|
maximumParticipants?: (documentId: string) => Promise<number | null>
|
|
@@ -86,6 +103,9 @@ type Room = {
|
|
|
86
103
|
document: Y.Doc
|
|
87
104
|
peers: Map<string, Peer>
|
|
88
105
|
persistTimer: ReturnType<typeof setTimeout> | null
|
|
106
|
+
/** The document's encoded size, measured again after a delete once it may be over the limit. */
|
|
107
|
+
bytes: number
|
|
108
|
+
deletedSinceMeasure: boolean
|
|
89
109
|
}
|
|
90
110
|
|
|
91
111
|
export type CollaborationRelay = ReturnType<typeof createCollaborationRelay>
|
|
@@ -103,6 +123,7 @@ export function createCollaborationRelay(options: CollaborationRelayOptions) {
|
|
|
103
123
|
/** Set by `close()`: a failed save then drops the room instead of retrying. */
|
|
104
124
|
let shuttingDown = false
|
|
105
125
|
const persistDelayMs = options.persistDelayMs ?? 2_000
|
|
126
|
+
const maximumRoomBytes = options.maximumRoomBytes ?? MAX_COLLAB_MESSAGE_BYTES
|
|
106
127
|
const persistRetryMs = options.persistRetryMs ?? 30_000
|
|
107
128
|
const authTimeoutMs = options.authTimeoutMs ?? 10_000
|
|
108
129
|
const report = options.onError ?? ((message, error) => console.error(`[Cloud] ${message}`, error))
|
|
@@ -136,8 +157,14 @@ export function createCollaborationRelay(options: CollaborationRelayOptions) {
|
|
|
136
157
|
identity,
|
|
137
158
|
document,
|
|
138
159
|
peers: new Map(),
|
|
139
|
-
persistTimer: null
|
|
160
|
+
persistTimer: null,
|
|
161
|
+
bytes: state?.byteLength ?? 0,
|
|
162
|
+
deletedSinceMeasure: false
|
|
140
163
|
}
|
|
164
|
+
// A delete can shrink what is encoded; the size is measured again when the room is full.
|
|
165
|
+
document.on('afterTransaction', (transaction) => {
|
|
166
|
+
if (transaction.deleteSet.clients.size > 0) room.deletedSinceMeasure = true
|
|
167
|
+
})
|
|
141
168
|
document.on('update', () => schedulePersist(room))
|
|
142
169
|
rooms.set(room.id, room)
|
|
143
170
|
return room
|
|
@@ -167,6 +194,17 @@ export function createCollaborationRelay(options: CollaborationRelayOptions) {
|
|
|
167
194
|
room.persistTimer ??= setTimeout(() => void persist(room), persistDelayMs)
|
|
168
195
|
}
|
|
169
196
|
|
|
197
|
+
/** Whether the update keeps the room within its size, measuring again after a delete. */
|
|
198
|
+
function fits(room: Room, update: Uint8Array): boolean {
|
|
199
|
+
// Deleting takes no room, whatever is left, so a full room can be cleaned up.
|
|
200
|
+
if (deletesOnlyKnown(room.document, update)) return true
|
|
201
|
+
if (room.bytes + update.byteLength <= maximumRoomBytes) return true
|
|
202
|
+
if (!room.deletedSinceMeasure) return false
|
|
203
|
+
room.bytes = Y.encodeStateAsUpdateV2(room.document).byteLength
|
|
204
|
+
room.deletedSinceMeasure = false
|
|
205
|
+
return room.bytes + update.byteLength <= maximumRoomBytes
|
|
206
|
+
}
|
|
207
|
+
|
|
170
208
|
/**
|
|
171
209
|
* Applies a peer's V2 update to the room, inflated first for a sync reply. Rooms are saved as
|
|
172
210
|
* V1 updates; only what peers exchange is V2.
|
|
@@ -174,14 +212,15 @@ export function createCollaborationRelay(options: CollaborationRelayOptions) {
|
|
|
174
212
|
function applyToRoom(room: Room, peer: Peer, namespace: string, payload: Uint8Array): boolean {
|
|
175
213
|
try {
|
|
176
214
|
const update = decodeRoomUpdate(payload, {
|
|
177
|
-
limit:
|
|
215
|
+
limit: maximumRoomBytes,
|
|
178
216
|
compressed: namespace === COLLAB_ACTIONS.syncReply
|
|
179
217
|
})
|
|
180
|
-
if (!update) {
|
|
218
|
+
if (!update || !fits(room, update)) {
|
|
181
219
|
peer.socket.close(RELAY_CLOSE.messageTooLarge, 'Collaboration update is too large')
|
|
182
220
|
return false
|
|
183
221
|
}
|
|
184
222
|
Y.applyUpdateV2(room.document, update, peer.id)
|
|
223
|
+
room.bytes += update.byteLength
|
|
185
224
|
return true
|
|
186
225
|
} catch {
|
|
187
226
|
peer.socket.close(RELAY_CLOSE.protocol, 'Malformed document update')
|
|
@@ -3,9 +3,9 @@ import type { CloudActor, CloudSessionResolver } from '#cloud/server/auth'
|
|
|
3
3
|
import type { CollaborationTicketService } from '#cloud/server/collaboration/service'
|
|
4
4
|
import type { CloudDatabase } from '#cloud/server/db'
|
|
5
5
|
import { DocumentNotFoundError } from '#cloud/server/documents'
|
|
6
|
-
import { CLOUD_RATE_LIMITS,
|
|
6
|
+
import { CLOUD_RATE_LIMITS, createResourceRateLimiter } from '#cloud/server/rate-limit'
|
|
7
7
|
import { DocumentShareInvalidError, DocumentShareSignInRequiredError } from '#cloud/server/sharing'
|
|
8
|
-
import { validatedJSON } from '#cloud/server/validation'
|
|
8
|
+
import { documentParams, shareParams, validatedJSON } from '#cloud/server/validation'
|
|
9
9
|
import { Hono, type Context } from 'hono'
|
|
10
10
|
import type { Kysely } from 'kysely'
|
|
11
11
|
|
|
@@ -29,26 +29,32 @@ export function createCollaborationRoutes(
|
|
|
29
29
|
if (rateLimit) {
|
|
30
30
|
router.use(
|
|
31
31
|
'/documents/:documentId/collaboration-ticket',
|
|
32
|
-
|
|
32
|
+
createResourceRateLimiter(
|
|
33
33
|
rateLimit.database,
|
|
34
34
|
rateLimit.secret,
|
|
35
35
|
CLOUD_RATE_LIMITS.collaborationTicket,
|
|
36
|
-
undefined,
|
|
37
36
|
(context) => context.req.param('documentId') ?? 'unknown-document'
|
|
38
37
|
)
|
|
39
38
|
)
|
|
40
39
|
}
|
|
41
|
-
return router.post(
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
40
|
+
return router.post(
|
|
41
|
+
'/documents/:documentId/collaboration-ticket',
|
|
42
|
+
documentParams,
|
|
43
|
+
async (context) => {
|
|
44
|
+
try {
|
|
45
|
+
return context.json({
|
|
46
|
+
ticket: await service.issueUserTicket(
|
|
47
|
+
context.get('actor'),
|
|
48
|
+
context.req.param('documentId')
|
|
49
|
+
)
|
|
50
|
+
})
|
|
51
|
+
} catch (error) {
|
|
52
|
+
const response = notFound(context, error)
|
|
53
|
+
if (response) return response
|
|
54
|
+
throw error
|
|
55
|
+
}
|
|
50
56
|
}
|
|
51
|
-
|
|
57
|
+
)
|
|
52
58
|
}
|
|
53
59
|
|
|
54
60
|
export function createPublicCollaborationRoutes(
|
|
@@ -57,6 +63,7 @@ export function createPublicCollaborationRoutes(
|
|
|
57
63
|
) {
|
|
58
64
|
return new Hono().post(
|
|
59
65
|
'/shares/:shareId/collaboration-ticket',
|
|
66
|
+
shareParams,
|
|
60
67
|
validatedJSON(parseResolveDocumentShare),
|
|
61
68
|
async (context) => {
|
|
62
69
|
try {
|
|
@@ -181,6 +181,9 @@ function validateAuthenticationConfig(config: CloudServerConfig): void {
|
|
|
181
181
|
if (config.deploymentAdminMFARequired && !config.totpEnabled && !config.passkeysEnabled) {
|
|
182
182
|
throw new CloudConfigError('Deployment administrator MFA requires TOTP or passkeys')
|
|
183
183
|
}
|
|
184
|
+
if (config.deployment === 'official' && !config.deploymentAdminMFARequired) {
|
|
185
|
+
throw new CloudConfigError('An official deployment requires MFA for deployment administrators')
|
|
186
|
+
}
|
|
184
187
|
if (config.recoveryCodesEnabled && !config.totpEnabled) {
|
|
185
188
|
throw new CloudConfigError('MFA recovery codes require TOTP')
|
|
186
189
|
}
|
|
@@ -1,8 +1,20 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import type { CloudDatabase } from '#cloud/server/db'
|
|
2
|
+
import { sql, type Expression, type Transaction } from 'kysely'
|
|
2
3
|
|
|
3
4
|
export const CURRENT_TIMESTAMP = sql<Date>`current_timestamp`
|
|
4
5
|
export const EMPTY_JSON_OBJECT = sql`'{}'::jsonb`
|
|
5
6
|
|
|
7
|
+
/**
|
|
8
|
+
* Holds a transaction-scoped advisory lock on `key` until the transaction ends, so two
|
|
9
|
+
* transactions that claim the same thing wait for each other instead of both reading it free.
|
|
10
|
+
*/
|
|
11
|
+
export async function lockForTransaction(
|
|
12
|
+
transaction: Transaction<CloudDatabase>,
|
|
13
|
+
key: string
|
|
14
|
+
): Promise<void> {
|
|
15
|
+
await sql`select pg_advisory_xact_lock(hashtextextended(${key}, 0))`.execute(transaction)
|
|
16
|
+
}
|
|
17
|
+
|
|
6
18
|
const CHECK_VALUE_PATTERN = /^[a-z][a-z0-9-]*$/
|
|
7
19
|
|
|
8
20
|
export function checkColumnIn(column: string, values: readonly string[]): Expression<boolean> {
|
package/src/server/db/migrate.ts
CHANGED
|
@@ -28,6 +28,7 @@ import * as accountActivity from './migrations/024_account_activity'
|
|
|
28
28
|
import * as tableNames from './migrations/025_table_names'
|
|
29
29
|
import * as userPicture from './migrations/026_user_picture'
|
|
30
30
|
import * as sharingCommentsSnapshotsProfiles from './migrations/027_sharing_comments_snapshots_profiles'
|
|
31
|
+
import * as invitationSends from './migrations/028_invitation_sends'
|
|
31
32
|
import type { CloudDatabase } from './tables'
|
|
32
33
|
|
|
33
34
|
const migrations: Record<string, Migration> = {
|
|
@@ -57,7 +58,8 @@ const migrations: Record<string, Migration> = {
|
|
|
57
58
|
'024_account_activity': accountActivity,
|
|
58
59
|
'025_table_names': tableNames,
|
|
59
60
|
'026_user_picture': userPicture,
|
|
60
|
-
'027_sharing_comments_snapshots_profiles': sharingCommentsSnapshotsProfiles
|
|
61
|
+
'027_sharing_comments_snapshots_profiles': sharingCommentsSnapshotsProfiles,
|
|
62
|
+
'028_invitation_sends': invitationSends
|
|
61
63
|
}
|
|
62
64
|
|
|
63
65
|
class CloudMigrationProvider implements MigrationProvider {
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import { CURRENT_TIMESTAMP } from '#cloud/server/db/expressions'
|
|
2
|
+
import type { Kysely } from 'kysely'
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Each invitation sent, by sender and recipient, for the daily invitation budget. It is kept apart
|
|
6
|
+
* from the invitations themselves, which go with their workspace or document, so deleting one
|
|
7
|
+
* never gives the budget back; rows older than a day are swept with the rate limits.
|
|
8
|
+
*/
|
|
9
|
+
export async function up(database: Kysely<unknown>): Promise<void> {
|
|
10
|
+
await database.schema
|
|
11
|
+
.createTable('invitation_send')
|
|
12
|
+
.addColumn('id', 'uuid', (column) => column.primaryKey())
|
|
13
|
+
.addColumn('sender_id', 'text', (column) => column.notNull())
|
|
14
|
+
.addColumn('email_normalized', 'text', (column) => column.notNull())
|
|
15
|
+
.addColumn('sent_at', 'timestamptz', (column) => column.notNull().defaultTo(CURRENT_TIMESTAMP))
|
|
16
|
+
.execute()
|
|
17
|
+
await database.schema
|
|
18
|
+
.createIndex('invitation_send_sender_index')
|
|
19
|
+
.on('invitation_send')
|
|
20
|
+
.columns(['sender_id', 'sent_at'])
|
|
21
|
+
.execute()
|
|
22
|
+
await database.schema
|
|
23
|
+
.createIndex('invitation_send_recipient_index')
|
|
24
|
+
.on('invitation_send')
|
|
25
|
+
.columns(['email_normalized', 'sent_at'])
|
|
26
|
+
.execute()
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export async function down(database: Kysely<unknown>): Promise<void> {
|
|
30
|
+
await database.schema.dropTable('invitation_send').execute()
|
|
31
|
+
}
|