@pairdraw/cloud 0.18.0 → 0.19.0-beta.1
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 +8 -6
- 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 +3298 -964
- 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/dist/server.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { CLOUD_AI_JWKS_PATH, CLOUD_AI_TOKEN_AUDIENCE, CLOUD_DISCOVERY_PATH, CLOUD_PICTURE_MAX_BYTES, CLOUD_PROTOCOL_MAX_UPLOAD_BYTES, COLLAB_ACTIONS, MAX_COLLAB_MESSAGE_BYTES, RELAY_CLOSE, RELAY_DOCUMENT_PARAM, RELAY_MINIMUM_MESSAGE_BYTES, RELAY_SERVER_PEER, ROOM_COMMENT_THREADS, cloudAdminAuditFilterSchema, cloudAdminEmailFilterSchema, cloudAdminUserFilterSchema, cloudEditorVersionSchema, cloudInvitationURL, collaborationPrincipalSchema, createRelayClientAssembler, decodeCommentRelayMessage, decodeRelayClientFrame, decodeRoomUpdate, documentPermissionSchema, encodeSyncReply, enrollmentStatusSchema as enrollmentStatusSchema$1, isPublicProfileHandle, parseAcceptDocumentInvitation, parseCloudDiscovery, parseCloudEmailChange, parseCloudMFAEnable, parseCloudMFAVerify, parseCloudPasskeyDelete, parseCloudPasswordChange, parseCloudPictureUpload, parseCloudProfileUpdate, parseCloudSessionRevoke, parseCloudSocialLink, parseCloudUnlinkAuthenticationMethod, parseCommitImageUploads, parseCommitUpload, parseCreateAIToken, parseCreateDocument, parseCreateDocumentInvitation, parseCreateDocumentShare, parseCreateInvitationContinuation, parseCreateUpload, parseCreateWorkspace, parseCreateWorkspaceInvitation, parseDuplicateDocumentVersion,
|
|
1
|
+
import { CLOUD_AI_JWKS_PATH, CLOUD_AI_TOKEN_AUDIENCE, CLOUD_API_MAX_BODY_BYTES, CLOUD_DISCOVERY_PATH, CLOUD_PICTURE_MAX_BYTES, CLOUD_PROTOCOL_MAX_UPLOAD_BYTES, COLLAB_ACTIONS, MAX_COLLAB_MESSAGE_BYTES, RELAY_CLOSE, RELAY_DOCUMENT_PARAM, RELAY_MINIMUM_MESSAGE_BYTES, RELAY_SERVER_PEER, ROOM_COMMENT_THREADS, cloudAdminAuditFilterSchema, cloudAdminEmailFilterSchema, cloudAdminUserFilterSchema, cloudEditorVersionSchema, cloudInvitationURL, collaborationPrincipalSchema, createRelayClientAssembler, decodeCommentRelayMessage, decodeRelayClientFrame, decodeRoomUpdate, documentPermissionSchema, encodeSyncReply, enrollmentStatusSchema as enrollmentStatusSchema$1, isPublicProfileHandle, parseAcceptDocumentInvitation, parseCloudDiscovery, parseCloudEmailChange, parseCloudMFAEnable, parseCloudMFAVerify, parseCloudPasskeyDelete, parseCloudPasswordChange, parseCloudPictureUpload, parseCloudProfileUpdate, parseCloudSessionRevoke, parseCloudSocialLink, parseCloudUnlinkAuthenticationMethod, parseCommitImageUploads, parseCommitUpload, parseCreateAIToken, parseCreateDocument, parseCreateDocumentInvitation, parseCreateDocumentShare, parseCreateInvitationContinuation, parseCreateUpload, parseCreateWorkspace, parseCreateWorkspaceInvitation, parseDuplicateDocumentVersion, parsePublishWorkspace, parsePutDocumentGrant, parseRequestImageLinks, parseRequestImageUploads, parseRequestSharedImageLinks, parseResolveDocumentShare, parseSaveDocumentVersion, parseUpdateDocumentShare, parseUpdateDocumentVersion, parseUpdatePublicProfile, parseUpdateWorkspace, parseUpdateWorkspaceMember, presenceName, readRoomCommentThread, relayServerMessages, workspaceRoleSchema, writeRoomCommentThread } from "./contract2.js";
|
|
2
2
|
import { toUint8Array } from "js-base64";
|
|
3
3
|
import * as v from "valibot";
|
|
4
4
|
import { ValiError } from "valibot";
|
|
@@ -7,13 +7,14 @@ import * as decoding from "lib0/decoding";
|
|
|
7
7
|
import * as encoding from "lib0/encoding";
|
|
8
8
|
import * as Y from "yjs";
|
|
9
9
|
import { withQuery, withoutTrailingSlash } from "ufo";
|
|
10
|
+
import { CamelCasePlugin, Kysely, NoResultError, sql } from "kysely";
|
|
10
11
|
import { rateLimiter } from "hono-rate-limiter";
|
|
12
|
+
import { every } from "hono/combine";
|
|
11
13
|
import { matchedRoutes } from "hono/route";
|
|
12
14
|
import { sha256 } from "@noble/hashes/sha2.js";
|
|
13
15
|
import { bytesToHex, hexToBytes, utf8ToBytes } from "@noble/hashes/utils.js";
|
|
14
16
|
import { validator } from "hono/validator";
|
|
15
17
|
import { Hono } from "hono";
|
|
16
|
-
import { CamelCasePlugin, Kysely, NoResultError, sql } from "kysely";
|
|
17
18
|
import { pickBy } from "es-toolkit/object";
|
|
18
19
|
import { isNotNil } from "es-toolkit/predicate";
|
|
19
20
|
import { parse } from "smol-toml";
|
|
@@ -99,11 +100,71 @@ const parseEnrollmentReview = (input) => v.parse(enrollmentReviewSchema, input);
|
|
|
99
100
|
const parseUserMutation = (input) => v.parse(userMutationSchema, input);
|
|
100
101
|
const parseUserRoleMutation = (input) => v.parse(userRoleMutationSchema, input);
|
|
101
102
|
//#endregion
|
|
103
|
+
//#region src/server/db/expressions.ts
|
|
104
|
+
const CURRENT_TIMESTAMP = sql`current_timestamp`;
|
|
105
|
+
const EMPTY_JSON_OBJECT = sql`'{}'::jsonb`;
|
|
106
|
+
/**
|
|
107
|
+
* Holds a transaction-scoped advisory lock on `key` until the transaction ends, so two
|
|
108
|
+
* transactions that claim the same thing wait for each other instead of both reading it free.
|
|
109
|
+
*/
|
|
110
|
+
async function lockForTransaction(transaction, key) {
|
|
111
|
+
await sql`select pg_advisory_xact_lock(hashtextextended(${key}, 0))`.execute(transaction);
|
|
112
|
+
}
|
|
113
|
+
const CHECK_VALUE_PATTERN = /^[a-z][a-z0-9-]*$/;
|
|
114
|
+
function checkColumnIn(column, values) {
|
|
115
|
+
if (values.length === 0 || values.some((value) => !CHECK_VALUE_PATTERN.test(value))) throw new Error("Check constraint values must be non-empty lowercase identifiers");
|
|
116
|
+
return sql`${sql.ref(column)} in (${sql.join(values.map((value) => sql.lit(value)))})`;
|
|
117
|
+
}
|
|
118
|
+
//#endregion
|
|
119
|
+
//#region src/server/invitations/budget.ts
|
|
120
|
+
/**
|
|
121
|
+
* How many invitations, to documents and workspaces alike, one person may send in a day, and how
|
|
122
|
+
* many one address may receive from everyone. Each sends an email naming the inviter and the file,
|
|
123
|
+
* both of which the sender chooses, so without a daily budget invitations are a way to send spam.
|
|
124
|
+
*/
|
|
125
|
+
const INVITATION_BUDGET = {
|
|
126
|
+
windowMs: 864e5,
|
|
127
|
+
perSender: 100,
|
|
128
|
+
perRecipient: 5
|
|
129
|
+
};
|
|
130
|
+
/** An invitation past the sender's or the recipient's daily budget. */
|
|
131
|
+
var InvitationLimitError = class extends Error {
|
|
132
|
+
name = "InvitationLimitError";
|
|
133
|
+
};
|
|
134
|
+
async function sentSince(transaction, column, value, since) {
|
|
135
|
+
const row = await transaction.selectFrom("invitationSend").select((expression) => expression.fn.countAll().as("count")).where(column, "=", value).where("sentAt", ">", since).executeTakeFirstOrThrow();
|
|
136
|
+
return Number(row.count);
|
|
137
|
+
}
|
|
138
|
+
/**
|
|
139
|
+
* Counts an invitation from `senderId` to `email` against both daily budgets, in the transaction
|
|
140
|
+
* that creates it, or refuses it once either budget is used. Sends are logged apart from the
|
|
141
|
+
* invitations, so deleting a workspace or document gives nothing back, and the check holds locks
|
|
142
|
+
* on the sender and the recipient, so two invitations at once cannot both take the last one.
|
|
143
|
+
*/
|
|
144
|
+
async function spendInvitationBudget(transaction, invitation, now = /* @__PURE__ */ new Date()) {
|
|
145
|
+
const email = invitation.email.trim().toLowerCase();
|
|
146
|
+
await lockForTransaction(transaction, `invitation-sender:${invitation.senderId}`);
|
|
147
|
+
await lockForTransaction(transaction, `invitation-recipient:${email}`);
|
|
148
|
+
const since = new Date(now.getTime() - INVITATION_BUDGET.windowMs);
|
|
149
|
+
const bySender = await sentSince(transaction, "senderId", invitation.senderId, since);
|
|
150
|
+
const byRecipient = await sentSince(transaction, "emailNormalized", email, since);
|
|
151
|
+
if (bySender >= INVITATION_BUDGET.perSender || byRecipient >= INVITATION_BUDGET.perRecipient) throw new InvitationLimitError();
|
|
152
|
+
await transaction.insertInto("invitationSend").values({
|
|
153
|
+
id: crypto.randomUUID(),
|
|
154
|
+
senderId: invitation.senderId,
|
|
155
|
+
emailNormalized: email,
|
|
156
|
+
sentAt: now
|
|
157
|
+
}).execute();
|
|
158
|
+
}
|
|
159
|
+
//#endregion
|
|
160
|
+
//#region src/server/invitations/types.ts
|
|
161
|
+
const noOpInvitationDelivery = { async sendDocumentInvitation() {} };
|
|
162
|
+
//#endregion
|
|
102
163
|
//#region src/server/rate-limit/cleanup.ts
|
|
103
164
|
function createRateLimitCleanupService(database) {
|
|
104
165
|
return { async cleanupExpired(before) {
|
|
105
|
-
const
|
|
106
|
-
return Number(
|
|
166
|
+
const [limits, invitations] = await Promise.all([database.deleteFrom("apiRateLimit").where("windowStartedAt", "<", before).executeTakeFirst(), database.deleteFrom("invitationSend").where("sentAt", "<", new Date(Math.min(before.getTime(), Date.now() - INVITATION_BUDGET.windowMs))).executeTakeFirst()]);
|
|
167
|
+
return Number(limits.numDeletedRows) + Number(invitations.numDeletedRows);
|
|
107
168
|
} };
|
|
108
169
|
}
|
|
109
170
|
//#endregion
|
|
@@ -190,12 +251,14 @@ const CLOUD_RATE_LIMITS = {
|
|
|
190
251
|
collaborationTicket: {
|
|
191
252
|
namespace: "collaboration-ticket",
|
|
192
253
|
windowMs: 6e4,
|
|
193
|
-
limit: 60
|
|
254
|
+
limit: 60,
|
|
255
|
+
actorLimit: 300
|
|
194
256
|
},
|
|
195
257
|
invitationMutation: {
|
|
196
258
|
namespace: "invitation-mutation",
|
|
197
259
|
windowMs: 6e4,
|
|
198
|
-
limit: 30
|
|
260
|
+
limit: 30,
|
|
261
|
+
actorLimit: 60
|
|
199
262
|
},
|
|
200
263
|
workspaceCreation: {
|
|
201
264
|
namespace: "workspace-creation",
|
|
@@ -205,12 +268,14 @@ const CLOUD_RATE_LIMITS = {
|
|
|
205
268
|
documentCreation: {
|
|
206
269
|
namespace: "document-creation",
|
|
207
270
|
windowMs: 6e4,
|
|
208
|
-
limit: 60
|
|
271
|
+
limit: 60,
|
|
272
|
+
actorLimit: 120
|
|
209
273
|
},
|
|
210
274
|
uploadCreation: {
|
|
211
275
|
namespace: "upload-creation",
|
|
212
276
|
windowMs: 6e4,
|
|
213
|
-
limit: 120
|
|
277
|
+
limit: 120,
|
|
278
|
+
actorLimit: 600
|
|
214
279
|
},
|
|
215
280
|
authenticatedMutation: {
|
|
216
281
|
namespace: "authenticated-mutation",
|
|
@@ -282,11 +347,50 @@ function createActorRateLimiter(database, secret, policy, skip, resource) {
|
|
|
282
347
|
});
|
|
283
348
|
}
|
|
284
349
|
/**
|
|
285
|
-
* A limiter a route mounts for its own budget, such as
|
|
350
|
+
* A limiter a route mounts for its own budget, such as workspace creation; general limiters leave
|
|
286
351
|
* the requests it counts to it.
|
|
287
352
|
*/
|
|
288
|
-
function createRouteRateLimiter(database, secret, policy, skip
|
|
289
|
-
return ownBudget(createActorRateLimiter(database, secret, policy, skip
|
|
353
|
+
function createRouteRateLimiter(database, secret, policy, skip) {
|
|
354
|
+
return ownBudget(createActorRateLimiter(database, secret, policy, skip), skip);
|
|
355
|
+
}
|
|
356
|
+
/**
|
|
357
|
+
* A route's own budget counted per resource, such as uploads per document, and capped per actor
|
|
358
|
+
* across resources by `actorLimit`; general limiters leave the requests it counts to it.
|
|
359
|
+
*/
|
|
360
|
+
function createResourceRateLimiter(database, secret, policy, resource, skip) {
|
|
361
|
+
const perResource = createActorRateLimiter(database, secret, policy, skip, resource);
|
|
362
|
+
const perActor = createActorRateLimiter(database, secret, {
|
|
363
|
+
namespace: `${policy.namespace}-actor`,
|
|
364
|
+
windowMs: policy.windowMs,
|
|
365
|
+
limit: policy.actorLimit
|
|
366
|
+
}, skip);
|
|
367
|
+
return ownBudget(every(perResource, keepResourceUse, perActor, reportTighterBudget(policy.windowMs)), skip);
|
|
368
|
+
}
|
|
369
|
+
/** Keeps the resource budget's use, which the actor-wide limiter would record over. */
|
|
370
|
+
const keepResourceUse = async (context, next) => {
|
|
371
|
+
context.set("resourceRateLimit", context.get("rateLimit"));
|
|
372
|
+
await next();
|
|
373
|
+
};
|
|
374
|
+
/**
|
|
375
|
+
* Reports whichever budget has fewer requests left in the `RateLimit` headers, as both limiters
|
|
376
|
+
* write them and the last would otherwise win. A refused request keeps the headers of the budget
|
|
377
|
+
* that refused it.
|
|
378
|
+
*/
|
|
379
|
+
function reportTighterBudget(windowMs) {
|
|
380
|
+
return async (context, next) => {
|
|
381
|
+
const resource = context.get("resourceRateLimit");
|
|
382
|
+
const actor = context.get("rateLimit");
|
|
383
|
+
const tighter = resource && actor && resource.remaining < actor.remaining ? resource : actor;
|
|
384
|
+
if (tighter) setBudgetHeaders(context, tighter, windowMs);
|
|
385
|
+
await next();
|
|
386
|
+
};
|
|
387
|
+
}
|
|
388
|
+
/** The draft-7 `RateLimit` headers `hono-rate-limiter` writes, for one budget's use. */
|
|
389
|
+
function setBudgetHeaders(context, use, windowMs) {
|
|
390
|
+
const windowSeconds = Math.ceil(windowMs / 1e3);
|
|
391
|
+
const reset = use.resetTime ? Math.max(0, Math.ceil((use.resetTime.getTime() - Date.now()) / 1e3)) : windowSeconds;
|
|
392
|
+
context.header("RateLimit-Policy", `${use.limit};w=${windowSeconds}`);
|
|
393
|
+
context.header("RateLimit", `limit=${use.limit}, remaining=${use.remaining}, reset=${reset}`);
|
|
290
394
|
}
|
|
291
395
|
//#endregion
|
|
292
396
|
//#region src/server/validation.ts
|
|
@@ -306,6 +410,63 @@ function validatedJSON(parse) {
|
|
|
306
410
|
function validatedQuery(parse) {
|
|
307
411
|
return validator("query", (value, context) => parseOrReject(parse, value, context));
|
|
308
412
|
}
|
|
413
|
+
/**
|
|
414
|
+
* Route parameters, so a malformed id names nothing and never reaches the database: it answers
|
|
415
|
+
* 404 like a row that has gone, as upstream does.
|
|
416
|
+
*/
|
|
417
|
+
function validatedParams(parse) {
|
|
418
|
+
return validator("param", (value, context) => {
|
|
419
|
+
try {
|
|
420
|
+
return parse(value);
|
|
421
|
+
} catch (error) {
|
|
422
|
+
if (error instanceof ValiError) return context.json({ error: { code: "not_found" } }, 404);
|
|
423
|
+
throw error;
|
|
424
|
+
}
|
|
425
|
+
});
|
|
426
|
+
}
|
|
427
|
+
const uuidParamSchema = v.pipe(v.string(), v.uuid());
|
|
428
|
+
const workspaceParamsSchema = v.object({ workspaceId: uuidParamSchema });
|
|
429
|
+
const textParamSchema = v.pipe(v.string(), v.minLength(1));
|
|
430
|
+
const workspaceMemberParamsSchema = v.object({
|
|
431
|
+
workspaceId: uuidParamSchema,
|
|
432
|
+
userId: textParamSchema
|
|
433
|
+
});
|
|
434
|
+
const workspaceInvitationParamsSchema = v.object({
|
|
435
|
+
workspaceId: uuidParamSchema,
|
|
436
|
+
invitationId: uuidParamSchema
|
|
437
|
+
});
|
|
438
|
+
const documentParamsSchema = v.object({ documentId: uuidParamSchema });
|
|
439
|
+
const documentVersionParamsSchema = v.object({
|
|
440
|
+
documentId: uuidParamSchema,
|
|
441
|
+
versionId: uuidParamSchema
|
|
442
|
+
});
|
|
443
|
+
const documentShareParamsSchema = v.object({
|
|
444
|
+
documentId: uuidParamSchema,
|
|
445
|
+
shareId: uuidParamSchema
|
|
446
|
+
});
|
|
447
|
+
const documentUserParamsSchema = v.object({
|
|
448
|
+
documentId: uuidParamSchema,
|
|
449
|
+
userId: textParamSchema
|
|
450
|
+
});
|
|
451
|
+
const documentInvitationParamsSchema = v.object({
|
|
452
|
+
documentId: uuidParamSchema,
|
|
453
|
+
invitationId: uuidParamSchema
|
|
454
|
+
});
|
|
455
|
+
/** A share or invitation named on its own, as a public link or an emailed link does. */
|
|
456
|
+
const shareParamsSchema = v.object({ shareId: uuidParamSchema });
|
|
457
|
+
const invitationParamsSchema = v.object({ invitationId: uuidParamSchema });
|
|
458
|
+
const uploadParamsSchema = v.object({ uploadId: uuidParamSchema });
|
|
459
|
+
const workspaceParams = validatedParams((input) => v.parse(workspaceParamsSchema, input));
|
|
460
|
+
const workspaceMemberParams = validatedParams((input) => v.parse(workspaceMemberParamsSchema, input));
|
|
461
|
+
const workspaceInvitationParams = validatedParams((input) => v.parse(workspaceInvitationParamsSchema, input));
|
|
462
|
+
const documentParams = validatedParams((input) => v.parse(documentParamsSchema, input));
|
|
463
|
+
const documentVersionParams = validatedParams((input) => v.parse(documentVersionParamsSchema, input));
|
|
464
|
+
const documentShareParams = validatedParams((input) => v.parse(documentShareParamsSchema, input));
|
|
465
|
+
const documentUserParams = validatedParams((input) => v.parse(documentUserParamsSchema, input));
|
|
466
|
+
const documentInvitationParams = validatedParams((input) => v.parse(documentInvitationParamsSchema, input));
|
|
467
|
+
const shareParams = validatedParams((input) => v.parse(shareParamsSchema, input));
|
|
468
|
+
const invitationParams = validatedParams((input) => v.parse(invitationParamsSchema, input));
|
|
469
|
+
const uploadParams = validatedParams((input) => v.parse(uploadParamsSchema, input));
|
|
309
470
|
//#endregion
|
|
310
471
|
//#region src/admin/api/routes.ts
|
|
311
472
|
/**
|
|
@@ -328,10 +489,10 @@ const parseUserQuery = listQuery(cloudAdminUserFilterSchema);
|
|
|
328
489
|
const parseEmailQuery = listQuery(cloudAdminEmailFilterSchema);
|
|
329
490
|
const parseAuditQuery = listQuery(cloudAdminAuditFilterSchema);
|
|
330
491
|
/** Accounts are named by UUID; anything else names no one, rather than failing the query. */
|
|
331
|
-
const accountIdSchema = v.pipe(v.string(), v.uuid());
|
|
492
|
+
const accountIdSchema$1 = v.pipe(v.string(), v.uuid());
|
|
332
493
|
/** Does what an administrator asked to another account; one that is not an account is not found. */
|
|
333
494
|
async function accountMutation(context, userId, mutate) {
|
|
334
|
-
if (!v.is(accountIdSchema, userId)) return context.json({ error: { code: "not_found" } }, 404);
|
|
495
|
+
if (!v.is(accountIdSchema$1, userId)) return context.json({ error: { code: "not_found" } }, 404);
|
|
335
496
|
await mutate(context.get("actor").userId, userId);
|
|
336
497
|
return context.json({ ok: true });
|
|
337
498
|
}
|
|
@@ -351,7 +512,7 @@ function createCloudAdminRoutes(services, trustedOrigins, security) {
|
|
|
351
512
|
throw error;
|
|
352
513
|
}).get("/enrollments", validatedQuery(parseEnrollmentQuery), async (context) => context.json(await services.enrollment.list(context.req.valid("query")))).post("/enrollments/:id/approve", validatedJSON(parseEnrollmentReview), async (context) => context.json({ enrollment: await services.enrollment.review(context.get("actor").userId, context.req.param("id"), "approved", context.req.valid("json")) })).post("/enrollments/:id/reject", validatedJSON(parseEnrollmentReview), async (context) => context.json({ enrollment: await services.enrollment.review(context.get("actor").userId, context.req.param("id"), "rejected", context.req.valid("json")) })).post("/enrollments/:id/revoke", validatedJSON(parseEnrollmentReview), async (context) => context.json({ enrollment: await services.enrollment.review(context.get("actor").userId, context.req.param("id"), "revoked", context.req.valid("json")) })).get("/users", validatedQuery(parseUserQuery), async (context) => context.json(await services.users.list(context.req.valid("query")))).get("/users/:id", async (context) => {
|
|
353
514
|
const id = context.req.param("id");
|
|
354
|
-
const detail = v.is(accountIdSchema, id) ? await services.users.detail(id) : null;
|
|
515
|
+
const detail = v.is(accountIdSchema$1, id) ? await services.users.detail(id) : null;
|
|
355
516
|
if (!detail) return context.json({ error: { code: "not_found" } }, 404);
|
|
356
517
|
return context.json(detail);
|
|
357
518
|
}).post("/users/reset-two-step", validatedJSON(parseUserMutation), (context) => accountMutation(context, context.req.valid("json").userId, (actorId, userId) => services.users.resetTwoStep(actorId, userId))).post("/users/remove-picture", validatedJSON(parseUserMutation), (context) => accountMutation(context, context.req.valid("json").userId, (actorId, userId) => services.users.removePicture(actorId, userId))).post("/users/ban", validatedJSON(parseUserMutation), async (context) => {
|
|
@@ -1003,6 +1164,7 @@ function validateAuthenticationConfig(config) {
|
|
|
1003
1164
|
if (config.emailPasswordMinimumLength > config.emailPasswordMaximumLength) throw new CloudConfigError("Minimum password length cannot exceed maximum password length");
|
|
1004
1165
|
if (config.emailPasswordEnabled && config.emailTransport === "none") throw new CloudConfigError("Email and password authentication requires transactional email delivery");
|
|
1005
1166
|
if (config.deploymentAdminMFARequired && !config.totpEnabled && !config.passkeysEnabled) throw new CloudConfigError("Deployment administrator MFA requires TOTP or passkeys");
|
|
1167
|
+
if (config.deployment === "official" && !config.deploymentAdminMFARequired) throw new CloudConfigError("An official deployment requires MFA for deployment administrators");
|
|
1006
1168
|
if (config.recoveryCodesEnabled && !config.totpEnabled) throw new CloudConfigError("MFA recovery codes require TOTP");
|
|
1007
1169
|
requireTogether(config, "CAPTCHA", [
|
|
1008
1170
|
"captchaProvider",
|
|
@@ -2182,6 +2344,10 @@ function createBetterAuthAdapter(config, database, enrollment = createEnrollment
|
|
|
2182
2344
|
window: 60,
|
|
2183
2345
|
max: 60
|
|
2184
2346
|
},
|
|
2347
|
+
[devices.endpoints.deviceVerify.path]: {
|
|
2348
|
+
window: 60,
|
|
2349
|
+
max: 20
|
|
2350
|
+
},
|
|
2185
2351
|
[devices.endpoints.deviceApprove.path]: {
|
|
2186
2352
|
window: 60,
|
|
2187
2353
|
max: 10
|
|
@@ -2931,7 +3097,7 @@ async function resolveDocumentAccess(database, userId, documentId) {
|
|
|
2931
3097
|
if (!document) return void 0;
|
|
2932
3098
|
const sources = [];
|
|
2933
3099
|
const candidates = [];
|
|
2934
|
-
const owner = document.createdBy === userId;
|
|
3100
|
+
const owner = document.createdBy === userId && document.workspaceRole !== null;
|
|
2935
3101
|
if (owner) {
|
|
2936
3102
|
sources.push("owner");
|
|
2937
3103
|
candidates.push("edit");
|
|
@@ -2963,7 +3129,7 @@ function canEditDocument(access) {
|
|
|
2963
3129
|
async function canDeleteDocument(database, userId, documentId) {
|
|
2964
3130
|
const document = await database.selectFrom("document").leftJoin("workspaceMember", (join) => join.onRef("workspaceMember.workspaceId", "=", "document.workspaceId").on("workspaceMember.userId", "=", userId)).select(["document.createdBy", "workspaceMember.role as workspaceRole"]).where("document.id", "=", documentId).where("document.deletedAt", "is", null).executeTakeFirst();
|
|
2965
3131
|
if (!document) return false;
|
|
2966
|
-
return document.createdBy === userId || document.workspaceRole === "admin" || document.workspaceRole === "editor";
|
|
3132
|
+
return document.createdBy === userId && document.workspaceRole !== null || document.workspaceRole === "admin" || document.workspaceRole === "editor";
|
|
2967
3133
|
}
|
|
2968
3134
|
//#endregion
|
|
2969
3135
|
//#region src/server/documents/errors.ts
|
|
@@ -3106,15 +3272,15 @@ async function documentResponse(context, respond) {
|
|
|
3106
3272
|
function createDocumentRoutes(service, rateLimit) {
|
|
3107
3273
|
const router = new Hono();
|
|
3108
3274
|
if (rateLimit) {
|
|
3109
|
-
router.use("/workspaces/:workspaceId/documents",
|
|
3110
|
-
router.use("/documents/:documentId/images",
|
|
3111
|
-
router.use("/documents/:documentId/uploads",
|
|
3275
|
+
router.use("/workspaces/:workspaceId/documents", createResourceRateLimiter(rateLimit.database, rateLimit.secret, CLOUD_RATE_LIMITS.documentCreation, (context) => context.req.param("workspaceId") ?? "unknown", (context) => context.req.method !== "POST"));
|
|
3276
|
+
router.use("/documents/:documentId/images", createResourceRateLimiter(rateLimit.database, rateLimit.secret, CLOUD_RATE_LIMITS.uploadCreation, (context) => context.req.param("documentId") ?? "unknown", (context) => context.req.method !== "POST"));
|
|
3277
|
+
router.use("/documents/:documentId/uploads", createResourceRateLimiter(rateLimit.database, rateLimit.secret, CLOUD_RATE_LIMITS.uploadCreation, (context) => context.req.param("documentId") ?? "unknown", (context) => context.req.method !== "POST"));
|
|
3112
3278
|
}
|
|
3113
|
-
return router.get("/shared-documents", async (context) => context.json({ documents: await service.listShared(context.get("actor").userId) })).get("/workspaces/:workspaceId/documents", async (context) => {
|
|
3279
|
+
return router.get("/shared-documents", async (context) => context.json({ documents: await service.listShared(context.get("actor").userId) })).get("/workspaces/:workspaceId/documents", workspaceParams, async (context) => {
|
|
3114
3280
|
const documents = await service.list(context.get("actor").userId, context.req.param("workspaceId"));
|
|
3115
3281
|
if (!documents) return context.json({ error: { code: "not_found" } }, 404);
|
|
3116
3282
|
return context.json({ documents });
|
|
3117
|
-
}).get("/workspaces/:workspaceId/usage", async (context) => {
|
|
3283
|
+
}).get("/workspaces/:workspaceId/usage", workspaceParams, async (context) => {
|
|
3118
3284
|
try {
|
|
3119
3285
|
return context.json({ usage: await service.usage(context.get("actor").userId, context.req.param("workspaceId")) });
|
|
3120
3286
|
} catch (error) {
|
|
@@ -3122,7 +3288,7 @@ function createDocumentRoutes(service, rateLimit) {
|
|
|
3122
3288
|
if (response) return response;
|
|
3123
3289
|
throw error;
|
|
3124
3290
|
}
|
|
3125
|
-
}).post("/workspaces/:workspaceId/documents", validatedJSON(parseCreateDocument), async (context) => {
|
|
3291
|
+
}).post("/workspaces/:workspaceId/documents", workspaceParams, validatedJSON(parseCreateDocument), async (context) => {
|
|
3126
3292
|
try {
|
|
3127
3293
|
const document = await service.create(context.get("actor").userId, context.req.param("workspaceId"), context.req.valid("json"));
|
|
3128
3294
|
return context.json({ document }, 201);
|
|
@@ -3131,7 +3297,7 @@ function createDocumentRoutes(service, rateLimit) {
|
|
|
3131
3297
|
if (response) return response;
|
|
3132
3298
|
throw error;
|
|
3133
3299
|
}
|
|
3134
|
-
}).delete("/documents/:documentId", async (context) => {
|
|
3300
|
+
}).delete("/documents/:documentId", documentParams, async (context) => {
|
|
3135
3301
|
try {
|
|
3136
3302
|
await service.remove(context.get("actor").userId, context.req.param("documentId"));
|
|
3137
3303
|
return context.body(null, 204);
|
|
@@ -3140,7 +3306,7 @@ function createDocumentRoutes(service, rateLimit) {
|
|
|
3140
3306
|
if (response) return response;
|
|
3141
3307
|
throw error;
|
|
3142
3308
|
}
|
|
3143
|
-
}).get("/documents/:documentId/access", async (context) => {
|
|
3309
|
+
}).get("/documents/:documentId/access", documentParams, async (context) => {
|
|
3144
3310
|
try {
|
|
3145
3311
|
return context.json({ access: await service.access(context.get("actor").userId, context.req.param("documentId")) });
|
|
3146
3312
|
} catch (error) {
|
|
@@ -3148,7 +3314,7 @@ function createDocumentRoutes(service, rateLimit) {
|
|
|
3148
3314
|
if (response) return response;
|
|
3149
3315
|
throw error;
|
|
3150
3316
|
}
|
|
3151
|
-
}).get("/documents/:documentId", async (context) => {
|
|
3317
|
+
}).get("/documents/:documentId", documentParams, async (context) => {
|
|
3152
3318
|
try {
|
|
3153
3319
|
return context.json({ document: await service.download(context.get("actor").userId, context.req.param("documentId")) });
|
|
3154
3320
|
} catch (error) {
|
|
@@ -3156,10 +3322,10 @@ function createDocumentRoutes(service, rateLimit) {
|
|
|
3156
3322
|
if (response) return response;
|
|
3157
3323
|
throw error;
|
|
3158
3324
|
}
|
|
3159
|
-
}).post("/documents/:documentId/uploads", validatedJSON(parseCreateUpload), (context) => documentResponse(context, async () => context.json(await service.createUpload(context.get("actor").userId, context.req.param("documentId"), context.req.valid("json")), 201))).post("/documents/:documentId/images/commit", validatedJSON(parseCommitImageUploads), (context) => documentResponse(context, async () => {
|
|
3325
|
+
}).post("/documents/:documentId/uploads", documentParams, validatedJSON(parseCreateUpload), (context) => documentResponse(context, async () => context.json(await service.createUpload(context.get("actor").userId, context.req.param("documentId"), context.req.valid("json")), 201))).post("/documents/:documentId/images/commit", documentParams, validatedJSON(parseCommitImageUploads), (context) => documentResponse(context, async () => {
|
|
3160
3326
|
await service.commitImageUploads(context.get("actor").userId, context.req.param("documentId"), context.req.valid("json").uploads);
|
|
3161
3327
|
return context.body(null, 204);
|
|
3162
|
-
})).post("/documents/:documentId/images/links", validatedJSON(parseRequestImageLinks), (context) => documentResponse(context, async () => context.json(await service.imageLinks(context.get("actor").userId, context.req.param("documentId"), context.req.valid("json").checksums)))).post("/documents/:documentId/images", validatedJSON(parseRequestImageUploads), (context) => documentResponse(context, async () => context.json(await service.requestImageUploads(context.get("actor").userId, context.req.param("documentId"), context.req.valid("json")), 201))).post("/uploads/:uploadId/commit", validatedJSON(parseCommitUpload), async (context) => {
|
|
3328
|
+
})).post("/documents/:documentId/images/links", documentParams, validatedJSON(parseRequestImageLinks), (context) => documentResponse(context, async () => context.json(await service.imageLinks(context.get("actor").userId, context.req.param("documentId"), context.req.valid("json").checksums)))).post("/documents/:documentId/images", documentParams, validatedJSON(parseRequestImageUploads), (context) => documentResponse(context, async () => context.json(await service.requestImageUploads(context.get("actor").userId, context.req.param("documentId"), context.req.valid("json")), 201))).post("/uploads/:uploadId/commit", uploadParams, validatedJSON(parseCommitUpload), async (context) => {
|
|
3163
3329
|
try {
|
|
3164
3330
|
const document = await service.commitUpload(context.get("actor").userId, context.req.param("uploadId"), context.req.valid("json"));
|
|
3165
3331
|
return context.json({ document });
|
|
@@ -4747,6 +4913,18 @@ function createSharingPolicy(database, options) {
|
|
|
4747
4913
|
//#endregion
|
|
4748
4914
|
//#region src/server/sharing/capabilities/service.ts
|
|
4749
4915
|
const SHARE_SECRET_BYTES = 24;
|
|
4916
|
+
/** An account ID as the user table keys it; other IDs in `createdBy` name no account. */
|
|
4917
|
+
const accountIdSchema = v.pipe(v.string(), v.uuid());
|
|
4918
|
+
/**
|
|
4919
|
+
* Whether any of these people is banned, for a ban that has not run out. A link stops working
|
|
4920
|
+
* while whoever made it, or made its document, is banned, so what a banned person put up is no
|
|
4921
|
+
* longer public. The IDs are matched as the user table keys them, so the lookup uses its index.
|
|
4922
|
+
*/
|
|
4923
|
+
async function anyBanned(database, userIds) {
|
|
4924
|
+
const accounts = userIds.filter((id) => v.is(accountIdSchema, id));
|
|
4925
|
+
if (accounts.length === 0) return false;
|
|
4926
|
+
return await database.selectFrom("user").select("id").where("id", "in", accounts).where("banned", "=", true).where((user) => user.or([user("banExpires", "is", null), user("banExpires", ">", /* @__PURE__ */ new Date())])).executeTakeFirst() !== void 0;
|
|
4927
|
+
}
|
|
4750
4928
|
/**
|
|
4751
4929
|
* The revision a snapshot pins: the document's current one, or one of its own revisions. Anything
|
|
4752
4930
|
* else, as a document with no revision yet, cannot be shared as a snapshot.
|
|
@@ -4857,9 +5035,11 @@ function createCapabilityService(database, options) {
|
|
|
4857
5035
|
"documentShare.secretHash",
|
|
4858
5036
|
"documentShare.roomEpoch",
|
|
4859
5037
|
"documentShare.expiresAt",
|
|
4860
|
-
"documentShare.revisionId"
|
|
5038
|
+
"documentShare.revisionId",
|
|
5039
|
+
"documentShare.createdBy as linkMaker",
|
|
5040
|
+
"document.createdBy as documentMaker"
|
|
4861
5041
|
]).where("documentShare.id", "=", shareId).where("documentShare.revokedAt", "is", null).where("document.deletedAt", "is", null).executeTakeFirst();
|
|
4862
|
-
if (!row || !capabilityHashMatches(row.secretHash, input.secret) || row.expiresAt && new Date(row.expiresAt).getTime() <= Date.now()) throw new DocumentShareInvalidError();
|
|
5042
|
+
if (!row || !capabilityHashMatches(row.secretHash, input.secret) || row.expiresAt && new Date(row.expiresAt).getTime() <= Date.now() || await anyBanned(database, [row.linkMaker, row.documentMaker])) throw new DocumentShareInvalidError();
|
|
4863
5043
|
if (!actor && options.policy) {
|
|
4864
5044
|
const document = await database.selectFrom("document").select("workspaceId").where("id", "=", row.documentId).executeTakeFirstOrThrow();
|
|
4865
5045
|
const featureKey = row.permission === "edit" ? CLOUD_FEATURE_KEYS.guestEdit : CLOUD_FEATURE_KEYS.guestView;
|
|
@@ -4908,7 +5088,7 @@ function createGrantService(database) {
|
|
|
4908
5088
|
},
|
|
4909
5089
|
async putGrant(userId, documentId, targetUserId, input) {
|
|
4910
5090
|
await requireSharingAccess(database, userId, documentId);
|
|
4911
|
-
|
|
5091
|
+
const row = await database.insertInto("documentGrant").values({
|
|
4912
5092
|
id: crypto.randomUUID(),
|
|
4913
5093
|
documentId,
|
|
4914
5094
|
userId: targetUserId,
|
|
@@ -4918,9 +5098,8 @@ function createGrantService(database) {
|
|
|
4918
5098
|
}).onConflict((conflict) => conflict.columns(["documentId", "userId"]).doUpdateSet({
|
|
4919
5099
|
permission: input.permission,
|
|
4920
5100
|
createdBy: userId,
|
|
4921
|
-
revokedAt: null,
|
|
4922
5101
|
updatedAt: /* @__PURE__ */ new Date()
|
|
4923
|
-
})).returning([
|
|
5102
|
+
}).where("documentGrant.revokedAt", "is", null)).returning([
|
|
4924
5103
|
"id",
|
|
4925
5104
|
"documentId",
|
|
4926
5105
|
"userId",
|
|
@@ -4928,7 +5107,9 @@ function createGrantService(database) {
|
|
|
4928
5107
|
"createdBy",
|
|
4929
5108
|
"createdAt",
|
|
4930
5109
|
"updatedAt"
|
|
4931
|
-
]).
|
|
5110
|
+
]).executeTakeFirst();
|
|
5111
|
+
if (!row) throw new DocumentNotFoundError();
|
|
5112
|
+
return grantContract(row);
|
|
4932
5113
|
},
|
|
4933
5114
|
/** Revoking access advances the collaboration epoch, so tickets and room keys issued before stop working. */
|
|
4934
5115
|
async revokeGrant(userId, documentId, targetUserId) {
|
|
@@ -5146,6 +5327,10 @@ function createWorkspaceMemberService(database, options) {
|
|
|
5146
5327
|
return {
|
|
5147
5328
|
invitation: invitationContract({
|
|
5148
5329
|
...await database.transaction().execute(async (transaction) => {
|
|
5330
|
+
await spendInvitationBudget(transaction, {
|
|
5331
|
+
senderId: userId,
|
|
5332
|
+
email: input.email
|
|
5333
|
+
});
|
|
5149
5334
|
await transaction.updateTable("workspaceInvitation").set({ revokedAt: /* @__PURE__ */ new Date() }).where("workspaceId", "=", workspaceId).where("emailNormalized", "=", input.email).where("acceptedAt", "is", null).where("revokedAt", "is", null).execute();
|
|
5150
5335
|
const inserted = await transaction.insertInto("workspaceInvitation").values({
|
|
5151
5336
|
id,
|
|
@@ -5332,6 +5517,7 @@ function sharingDomainError(context, error) {
|
|
|
5332
5517
|
if (error instanceof DocumentShareKindError) return context.json({ error: { code: "invalid_request" } }, 400);
|
|
5333
5518
|
if (error instanceof DocumentShareSignInRequiredError) return context.json({ error: { code: "unauthorized" } }, 401);
|
|
5334
5519
|
if (error instanceof InvitationDeliveryError) return context.json({ error: { code: "invitation_delivery_failed" } }, 502);
|
|
5520
|
+
if (error instanceof InvitationLimitError) return context.json({ error: { code: "rate_limited" } }, 429);
|
|
5335
5521
|
if (error instanceof DocumentForbiddenError) return context.json({ error: { code: "forbidden" } }, 403);
|
|
5336
5522
|
return null;
|
|
5337
5523
|
}
|
|
@@ -5356,13 +5542,13 @@ async function shareActor(request, resolveSession) {
|
|
|
5356
5542
|
//#endregion
|
|
5357
5543
|
//#region src/server/sharing/document-routes.ts
|
|
5358
5544
|
function createPublicDocumentRoutes(sharing, documents, resolveSession) {
|
|
5359
|
-
return new Hono().post("/shares/:shareId/document", validatedJSON(parseResolveDocumentShare), (context) => sharingRoute(context, async () => {
|
|
5545
|
+
return new Hono().post("/shares/:shareId/document", shareParams, validatedJSON(parseResolveDocumentShare), (context) => sharingRoute(context, async () => {
|
|
5360
5546
|
const resolution = await sharing.resolveShare(context.req.param("shareId"), context.req.valid("json"), await shareActor(context.req.raw, resolveSession));
|
|
5361
5547
|
return context.json({
|
|
5362
5548
|
resolution,
|
|
5363
5549
|
document: await documents.downloadShared(resolution.documentId, resolution.revisionId)
|
|
5364
5550
|
});
|
|
5365
|
-
})).post("/shares/:shareId/images", validatedJSON(parseRequestSharedImageLinks), (context) => sharingRoute(context, async () => {
|
|
5551
|
+
})).post("/shares/:shareId/images", shareParams, validatedJSON(parseRequestSharedImageLinks), (context) => sharingRoute(context, async () => {
|
|
5366
5552
|
const { checksums, ...share } = context.req.valid("json");
|
|
5367
5553
|
const resolution = await sharing.resolveShare(context.req.param("shareId"), share, await shareActor(context.req.raw, resolveSession));
|
|
5368
5554
|
return context.json(await documents.imageLinksShared(resolution.documentId, checksums));
|
|
@@ -5427,6 +5613,10 @@ function createInvitationService(database, options) {
|
|
|
5427
5613
|
acceptanceURL
|
|
5428
5614
|
} : null;
|
|
5429
5615
|
const invitation = invitationContract$1(await database.transaction().execute(async (transaction) => {
|
|
5616
|
+
await spendInvitationBudget(transaction, {
|
|
5617
|
+
senderId: userId,
|
|
5618
|
+
email: input.email
|
|
5619
|
+
});
|
|
5430
5620
|
const inserted = await transaction.insertInto("documentInvitation").values({
|
|
5431
5621
|
id,
|
|
5432
5622
|
documentId,
|
|
@@ -5531,20 +5721,20 @@ function createInvitationService(database, options) {
|
|
|
5531
5721
|
//#region src/server/sharing/routes.ts
|
|
5532
5722
|
function createDocumentSharingRoutes(service, rateLimit) {
|
|
5533
5723
|
const router = new Hono();
|
|
5534
|
-
if (rateLimit) router.use("/documents/:documentId/invitations",
|
|
5535
|
-
return router.
|
|
5724
|
+
if (rateLimit) router.use("/documents/:documentId/invitations", createResourceRateLimiter(rateLimit.database, rateLimit.secret, CLOUD_RATE_LIMITS.invitationMutation, (context) => context.req.param("documentId") ?? "unknown", (context) => context.req.method !== "POST"));
|
|
5725
|
+
return router.get("/documents/:documentId/users/:userId", documentUserParams, (context) => sharingRoute(context, async () => context.json({ user: await service.userProfile(context.get("actor").userId, context.req.param("documentId"), context.req.param("userId")) }))).get("/documents/:documentId/shares", documentParams, (context) => sharingRoute(context, async () => context.json({ shares: await service.listShares(context.get("actor").userId, context.req.param("documentId")) }))).post("/documents/:documentId/shares", documentParams, validatedJSON(parseCreateDocumentShare), (context) => sharingRoute(context, async () => context.json(await service.createShare(context.get("actor").userId, context.req.param("documentId"), context.req.valid("json")), 201))).patch("/documents/:documentId/shares/:shareId", documentShareParams, validatedJSON(parseUpdateDocumentShare), (context) => sharingRoute(context, async () => context.json({ share: await service.updateShare(context.get("actor").userId, context.req.param("documentId"), context.req.param("shareId"), context.req.valid("json")) }))).post("/documents/:documentId/shares/:shareId/rotate", documentShareParams, (context) => sharingRoute(context, async () => context.json(await service.rotateShare(context.get("actor").userId, context.req.param("documentId"), context.req.param("shareId"))))).delete("/documents/:documentId/shares/:shareId", documentShareParams, (context) => sharingRoute(context, async () => {
|
|
5536
5726
|
await service.revokeShare(context.get("actor").userId, context.req.param("documentId"), context.req.param("shareId"));
|
|
5537
5727
|
return context.body(null, 204);
|
|
5538
|
-
})).get("/documents/:documentId/grants", (context) => sharingRoute(context, async () => context.json({ grants: await service.listGrants(context.get("actor").userId, context.req.param("documentId")) }))).put("/documents/:documentId/grants/:userId", validatedJSON(parsePutDocumentGrant), (context) => sharingRoute(context, async () => context.json({ grant: await service.putGrant(context.get("actor").userId, context.req.param("documentId"), context.req.param("userId"), context.req.valid("json")) }))).delete("/documents/:documentId/grants/:userId", (context) => sharingRoute(context, async () => {
|
|
5728
|
+
})).get("/documents/:documentId/grants", documentParams, (context) => sharingRoute(context, async () => context.json({ grants: await service.listGrants(context.get("actor").userId, context.req.param("documentId")) }))).put("/documents/:documentId/grants/:userId", documentUserParams, validatedJSON(parsePutDocumentGrant), (context) => sharingRoute(context, async () => context.json({ grant: await service.putGrant(context.get("actor").userId, context.req.param("documentId"), context.req.param("userId"), context.req.valid("json")) }))).delete("/documents/:documentId/grants/:userId", documentUserParams, (context) => sharingRoute(context, async () => {
|
|
5539
5729
|
await service.revokeGrant(context.get("actor").userId, context.req.param("documentId"), context.req.param("userId"));
|
|
5540
5730
|
return context.body(null, 204);
|
|
5541
|
-
})).get("/documents/:documentId/invitations", (context) => sharingRoute(context, async () => context.json({ invitations: await service.listInvitations(context.get("actor").userId, context.req.param("documentId")) }))).post("/documents/:documentId/invitations", validatedJSON(parseCreateDocumentInvitation), (context) => sharingRoute(context, async () => context.json(await service.createInvitation(context.get("actor").userId, context.req.param("documentId"), context.req.valid("json")), 201))).post("/invitations/:invitationId/accept", validatedJSON(parseAcceptDocumentInvitation), (context) => sharingRoute(context, async () => context.json({ accepted: await service.acceptInvitation(context.get("actor"), context.req.param("invitationId"), context.req.valid("json")) }))).delete("/documents/:documentId/invitations/:invitationId", (context) => sharingRoute(context, async () => {
|
|
5731
|
+
})).get("/documents/:documentId/invitations", documentParams, (context) => sharingRoute(context, async () => context.json({ invitations: await service.listInvitations(context.get("actor").userId, context.req.param("documentId")) }))).post("/documents/:documentId/invitations", documentParams, validatedJSON(parseCreateDocumentInvitation), (context) => sharingRoute(context, async () => context.json(await service.createInvitation(context.get("actor").userId, context.req.param("documentId"), context.req.valid("json")), 201))).post("/invitations/:invitationId/accept", invitationParams, validatedJSON(parseAcceptDocumentInvitation), (context) => sharingRoute(context, async () => context.json({ accepted: await service.acceptInvitation(context.get("actor"), context.req.param("invitationId"), context.req.valid("json")) }))).delete("/documents/:documentId/invitations/:invitationId", documentInvitationParams, (context) => sharingRoute(context, async () => {
|
|
5542
5732
|
await service.revokeInvitation(context.get("actor").userId, context.req.param("documentId"), context.req.param("invitationId"));
|
|
5543
5733
|
return context.body(null, 204);
|
|
5544
5734
|
}));
|
|
5545
5735
|
}
|
|
5546
5736
|
function createPublicSharingRoutes(service, resolveSession) {
|
|
5547
|
-
return new Hono().post("/invitations/continuations", validatedJSON(parseCreateInvitationContinuation), (context) => sharingRoute(context, async () => context.json(await service.createInvitationContinuation(context.req.valid("json")), 201))).post("/invitations/continuations/:continuationId/consume", (context) => sharingRoute(context, async () => context.json(await service.consumeInvitationContinuation(context.req.param("continuationId"))))).post("/invitations/:invitationId/preview", validatedJSON(parseAcceptDocumentInvitation), (context) => sharingRoute(context, async () => context.json({ invitation: await service.previewInvitation(context.req.param("invitationId"), context.req.valid("json")) }))).post("/shares/:shareId/resolve", validatedJSON(parseResolveDocumentShare), (context) => sharingRoute(context, async () => context.json({ resolution: await service.resolveShare(context.req.param("shareId"), context.req.valid("json"), await shareActor(context.req.raw, resolveSession)) })));
|
|
5737
|
+
return new Hono().post("/invitations/continuations", validatedJSON(parseCreateInvitationContinuation), (context) => sharingRoute(context, async () => context.json(await service.createInvitationContinuation(context.req.valid("json")), 201))).post("/invitations/continuations/:continuationId/consume", (context) => sharingRoute(context, async () => context.json(await service.consumeInvitationContinuation(context.req.param("continuationId"))))).post("/invitations/:invitationId/preview", invitationParams, validatedJSON(parseAcceptDocumentInvitation), (context) => sharingRoute(context, async () => context.json({ invitation: await service.previewInvitation(context.req.param("invitationId"), context.req.valid("json")) }))).post("/shares/:shareId/resolve", shareParams, validatedJSON(parseResolveDocumentShare), (context) => sharingRoute(context, async () => context.json({ resolution: await service.resolveShare(context.req.param("shareId"), context.req.valid("json"), await shareActor(context.req.raw, resolveSession)) })));
|
|
5548
5738
|
}
|
|
5549
5739
|
//#endregion
|
|
5550
5740
|
//#region src/server/sharing/service.ts
|
|
@@ -5553,15 +5743,6 @@ function createDocumentSharingService(database, options = {}) {
|
|
|
5553
5743
|
const grants = createGrantService(database);
|
|
5554
5744
|
const invitations = createInvitationService(database, options);
|
|
5555
5745
|
return {
|
|
5556
|
-
async lookupUser(userId, documentId, input) {
|
|
5557
|
-
await requireSharingAccess(database, userId, documentId);
|
|
5558
|
-
return await database.selectFrom("user").select([
|
|
5559
|
-
"id",
|
|
5560
|
-
"name",
|
|
5561
|
-
"email",
|
|
5562
|
-
"image"
|
|
5563
|
-
]).where((expression) => expression(expression.fn("lower", [expression.ref("email")]), "=", input.email)).executeTakeFirst() ?? null;
|
|
5564
|
-
},
|
|
5565
5746
|
async userProfile(userId, documentId, profileUserId) {
|
|
5566
5747
|
await requireSharingAccess(database, userId, documentId);
|
|
5567
5748
|
if (!await database.selectFrom("document").select("document.id").where("document.id", "=", documentId).where((expression) => expression.or([
|
|
@@ -5591,8 +5772,8 @@ function notFound(context, error) {
|
|
|
5591
5772
|
}
|
|
5592
5773
|
function createCollaborationRoutes(service, rateLimit) {
|
|
5593
5774
|
const router = new Hono();
|
|
5594
|
-
if (rateLimit) router.use("/documents/:documentId/collaboration-ticket",
|
|
5595
|
-
return router.post("/documents/:documentId/collaboration-ticket", async (context) => {
|
|
5775
|
+
if (rateLimit) router.use("/documents/:documentId/collaboration-ticket", createResourceRateLimiter(rateLimit.database, rateLimit.secret, CLOUD_RATE_LIMITS.collaborationTicket, (context) => context.req.param("documentId") ?? "unknown-document"));
|
|
5776
|
+
return router.post("/documents/:documentId/collaboration-ticket", documentParams, async (context) => {
|
|
5596
5777
|
try {
|
|
5597
5778
|
return context.json({ ticket: await service.issueUserTicket(context.get("actor"), context.req.param("documentId")) });
|
|
5598
5779
|
} catch (error) {
|
|
@@ -5603,7 +5784,7 @@ function createCollaborationRoutes(service, rateLimit) {
|
|
|
5603
5784
|
});
|
|
5604
5785
|
}
|
|
5605
5786
|
function createPublicCollaborationRoutes(service, resolveSession) {
|
|
5606
|
-
return new Hono().post("/shares/:shareId/collaboration-ticket", validatedJSON(parseResolveDocumentShare), async (context) => {
|
|
5787
|
+
return new Hono().post("/shares/:shareId/collaboration-ticket", shareParams, validatedJSON(parseResolveDocumentShare), async (context) => {
|
|
5607
5788
|
try {
|
|
5608
5789
|
return context.json({ ticket: await service.issueShareTicket(context.req.param("shareId"), context.req.valid("json"), resolveSession ? await resolveSession(context.req.raw) ?? void 0 : void 0) });
|
|
5609
5790
|
} catch (error) {
|
|
@@ -5903,6 +6084,17 @@ function commenterThreadWrites(threads, incoming, author, now = (/* @__PURE__ */
|
|
|
5903
6084
|
}
|
|
5904
6085
|
//#endregion
|
|
5905
6086
|
//#region src/server/collaboration/relay/hub.ts
|
|
6087
|
+
/** Whether `update` adds nothing and deletes only content `document` already holds. */
|
|
6088
|
+
function deletesOnlyKnown(document, update) {
|
|
6089
|
+
const { from, to } = Y.parseUpdateMetaV2(update);
|
|
6090
|
+
if (![...to].every(([client, clock]) => from.get(client) === clock)) return false;
|
|
6091
|
+
const { ds } = Y.decodeUpdateV2(update);
|
|
6092
|
+
for (const [client, deletions] of ds.clients) {
|
|
6093
|
+
const held = Y.getState(document.store, client);
|
|
6094
|
+
if (deletions.some((deletion) => deletion.clock + deletion.len > held)) return false;
|
|
6095
|
+
}
|
|
6096
|
+
return true;
|
|
6097
|
+
}
|
|
5906
6098
|
/** Messages a viewer may send; their document writes never leave the relay. */
|
|
5907
6099
|
const VIEWER_ACTIONS = /* @__PURE__ */ new Set([COLLAB_ACTIONS.syncStep1, COLLAB_ACTIONS.awareness]);
|
|
5908
6100
|
/** A commenter may also send its comment threads, which the relay writes into the room itself. */
|
|
@@ -5924,6 +6116,7 @@ function createCollaborationRelay(options) {
|
|
|
5924
6116
|
/** Set by `close()`: a failed save then drops the room instead of retrying. */
|
|
5925
6117
|
let shuttingDown = false;
|
|
5926
6118
|
const persistDelayMs = options.persistDelayMs ?? 2e3;
|
|
6119
|
+
const maximumRoomBytes = options.maximumRoomBytes ?? 268435456;
|
|
5927
6120
|
const persistRetryMs = options.persistRetryMs ?? 3e4;
|
|
5928
6121
|
const authTimeoutMs = options.authTimeoutMs ?? 1e4;
|
|
5929
6122
|
const report = options.onError ?? ((message, error) => console.error(`[Cloud] ${message}`, error));
|
|
@@ -5955,8 +6148,13 @@ function createCollaborationRelay(options) {
|
|
|
5955
6148
|
identity,
|
|
5956
6149
|
document,
|
|
5957
6150
|
peers: /* @__PURE__ */ new Map(),
|
|
5958
|
-
persistTimer: null
|
|
6151
|
+
persistTimer: null,
|
|
6152
|
+
bytes: state?.byteLength ?? 0,
|
|
6153
|
+
deletedSinceMeasure: false
|
|
5959
6154
|
};
|
|
6155
|
+
document.on("afterTransaction", (transaction) => {
|
|
6156
|
+
if (transaction.deleteSet.clients.size > 0) room.deletedSinceMeasure = true;
|
|
6157
|
+
});
|
|
5960
6158
|
document.on("update", () => schedulePersist(room));
|
|
5961
6159
|
rooms.set(room.id, room);
|
|
5962
6160
|
return room;
|
|
@@ -5983,6 +6181,15 @@ function createCollaborationRelay(options) {
|
|
|
5983
6181
|
function schedulePersist(room) {
|
|
5984
6182
|
room.persistTimer ??= setTimeout(() => void persist(room), persistDelayMs);
|
|
5985
6183
|
}
|
|
6184
|
+
/** Whether the update keeps the room within its size, measuring again after a delete. */
|
|
6185
|
+
function fits(room, update) {
|
|
6186
|
+
if (deletesOnlyKnown(room.document, update)) return true;
|
|
6187
|
+
if (room.bytes + update.byteLength <= maximumRoomBytes) return true;
|
|
6188
|
+
if (!room.deletedSinceMeasure) return false;
|
|
6189
|
+
room.bytes = Y.encodeStateAsUpdateV2(room.document).byteLength;
|
|
6190
|
+
room.deletedSinceMeasure = false;
|
|
6191
|
+
return room.bytes + update.byteLength <= maximumRoomBytes;
|
|
6192
|
+
}
|
|
5986
6193
|
/**
|
|
5987
6194
|
* Applies a peer's V2 update to the room, inflated first for a sync reply. Rooms are saved as
|
|
5988
6195
|
* V1 updates; only what peers exchange is V2.
|
|
@@ -5990,14 +6197,15 @@ function createCollaborationRelay(options) {
|
|
|
5990
6197
|
function applyToRoom(room, peer, namespace, payload) {
|
|
5991
6198
|
try {
|
|
5992
6199
|
const update = decodeRoomUpdate(payload, {
|
|
5993
|
-
limit:
|
|
6200
|
+
limit: maximumRoomBytes,
|
|
5994
6201
|
compressed: namespace === COLLAB_ACTIONS.syncReply
|
|
5995
6202
|
});
|
|
5996
|
-
if (!update) {
|
|
6203
|
+
if (!update || !fits(room, update)) {
|
|
5997
6204
|
peer.socket.close(RELAY_CLOSE.messageTooLarge, "Collaboration update is too large");
|
|
5998
6205
|
return false;
|
|
5999
6206
|
}
|
|
6000
6207
|
Y.applyUpdateV2(room.document, update, peer.id);
|
|
6208
|
+
room.bytes += update.byteLength;
|
|
6001
6209
|
return true;
|
|
6002
6210
|
} catch {
|
|
6003
6211
|
peer.socket.close(RELAY_CLOSE.protocol, "Malformed document update");
|
|
@@ -6341,7 +6549,7 @@ async function answer(context, run) {
|
|
|
6341
6549
|
}
|
|
6342
6550
|
/** A document's version history: listing, naming, opening, restoring, and duplicating versions. */
|
|
6343
6551
|
function createDocumentVersionRoutes(service) {
|
|
6344
|
-
return new Hono().get("/documents/:documentId/versions", validatedQuery(parsePage), (context) => answer(context, async () => context.json(await service.list(context.get("actor").userId, context.req.param("documentId"), context.req.valid("query"))))).post("/documents/:documentId/versions", validatedJSON(parseSaveDocumentVersion), (context) => answer(context, async () => context.json({ version: await service.save(context.get("actor").userId, context.req.param("documentId"), context.req.valid("json")) }, 201))).patch("/documents/:documentId/versions/:versionId", validatedJSON(parseUpdateDocumentVersion), (context) => answer(context, async () => context.json({ version: await service.update(context.get("actor").userId, context.req.param("documentId"), context.req.param("versionId"), context.req.valid("json")) }))).get("/documents/:documentId/versions/:versionId", (context) => answer(context, async () => context.json(await service.download(context.get("actor").userId, context.req.param("documentId"), context.req.param("versionId"))))).post("/documents/:documentId/versions/:versionId/restore", (context) => answer(context, async () => context.json(await service.restore(context.get("actor").userId, context.req.param("documentId"), context.req.param("versionId"))))).post("/documents/:documentId/versions/:versionId/duplicate", validatedJSON(parseDuplicateDocumentVersion), (context) => answer(context, async () => context.json({ document: await service.duplicate(context.get("actor").userId, context.req.param("documentId"), context.req.param("versionId"), context.req.valid("json")) }, 201)));
|
|
6552
|
+
return new Hono().get("/documents/:documentId/versions", documentParams, validatedQuery(parsePage), (context) => answer(context, async () => context.json(await service.list(context.get("actor").userId, context.req.param("documentId"), context.req.valid("query"))))).post("/documents/:documentId/versions", documentParams, validatedJSON(parseSaveDocumentVersion), (context) => answer(context, async () => context.json({ version: await service.save(context.get("actor").userId, context.req.param("documentId"), context.req.valid("json")) }, 201))).patch("/documents/:documentId/versions/:versionId", documentVersionParams, validatedJSON(parseUpdateDocumentVersion), (context) => answer(context, async () => context.json({ version: await service.update(context.get("actor").userId, context.req.param("documentId"), context.req.param("versionId"), context.req.valid("json")) }))).get("/documents/:documentId/versions/:versionId", documentVersionParams, (context) => answer(context, async () => context.json(await service.download(context.get("actor").userId, context.req.param("documentId"), context.req.param("versionId"))))).post("/documents/:documentId/versions/:versionId/restore", documentVersionParams, (context) => answer(context, async () => context.json(await service.restore(context.get("actor").userId, context.req.param("documentId"), context.req.param("versionId"))))).post("/documents/:documentId/versions/:versionId/duplicate", documentVersionParams, validatedJSON(parseDuplicateDocumentVersion), (context) => answer(context, async () => context.json({ document: await service.duplicate(context.get("actor").userId, context.req.param("documentId"), context.req.param("versionId"), context.req.valid("json")) }, 201)));
|
|
6345
6553
|
}
|
|
6346
6554
|
//#endregion
|
|
6347
6555
|
//#region src/server/documents/versions/service.ts
|
|
@@ -6766,7 +6974,7 @@ function required(service) {
|
|
|
6766
6974
|
* service every route answers 404.
|
|
6767
6975
|
*/
|
|
6768
6976
|
function createPublicProfileSettingsRoutes(service) {
|
|
6769
|
-
return new Hono().get("/profile", (context) => profileRoute(context, async () => context.json({ profile: await required(service).settings(context.get("actor").userId) }))).put("/profile", validatedJSON(parseUpdatePublicProfile), (context) => profileRoute(context, async () => context.json({ profile: await required(service).update(context.get("actor").userId, context.req.valid("json")) }))).put("/workspaces/:workspaceId/public", validatedJSON(parsePublishWorkspace), (context) => profileRoute(context, async () => context.json({ profile: await required(service).publishWorkspace(context.get("actor").userId, context.req.param("workspaceId"), context.req.valid("json").public) })));
|
|
6977
|
+
return new Hono().get("/profile", (context) => profileRoute(context, async () => context.json({ profile: await required(service).settings(context.get("actor").userId) }))).put("/profile", validatedJSON(parseUpdatePublicProfile), (context) => profileRoute(context, async () => context.json({ profile: await required(service).update(context.get("actor").userId, context.req.valid("json")) }))).put("/workspaces/:workspaceId/public", workspaceParams, validatedJSON(parsePublishWorkspace), (context) => profileRoute(context, async () => context.json({ profile: await required(service).publishWorkspace(context.get("actor").userId, context.req.param("workspaceId"), context.req.valid("json").public) })));
|
|
6770
6978
|
}
|
|
6771
6979
|
/** What anyone may read without signing in: profiles and the documents they list. */
|
|
6772
6980
|
function createPublicProfileRoutes(service, documents) {
|
|
@@ -6775,7 +6983,7 @@ function createPublicProfileRoutes(service, documents) {
|
|
|
6775
6983
|
const profile = isPublicProfileHandle(handle) ? await required(service).publicProfile(handle) : null;
|
|
6776
6984
|
if (!profile) throw new DocumentNotFoundError();
|
|
6777
6985
|
return context.json({ profile });
|
|
6778
|
-
})).post("/documents/:documentId/document", (context) => profileRoute(context, async () => {
|
|
6986
|
+
})).post("/documents/:documentId/document", documentParams, (context) => profileRoute(context, async () => {
|
|
6779
6987
|
const documentId = context.req.param("documentId");
|
|
6780
6988
|
await required(service).requirePublicDocument(documentId);
|
|
6781
6989
|
return context.json({ document: await documents.downloadShared(documentId) });
|
|
@@ -6857,6 +7065,7 @@ async function memberRoute(context, action) {
|
|
|
6857
7065
|
return context.json({ error: { code } }, 409);
|
|
6858
7066
|
}
|
|
6859
7067
|
if (error instanceof WorkspaceAlreadyMemberError) return context.json({ error: { code: "already_member" } }, 409);
|
|
7068
|
+
if (error instanceof InvitationLimitError) return context.json({ error: { code: "rate_limited" } }, 429);
|
|
6860
7069
|
throw error;
|
|
6861
7070
|
}
|
|
6862
7071
|
}
|
|
@@ -6864,8 +7073,8 @@ function createWorkspaceRoutes(service, members, rateLimit) {
|
|
|
6864
7073
|
const router = new Hono();
|
|
6865
7074
|
if (rateLimit) {
|
|
6866
7075
|
router.use("/", createRouteRateLimiter(rateLimit.database, rateLimit.secret, CLOUD_RATE_LIMITS.workspaceCreation, (context) => context.req.method !== "POST"));
|
|
6867
|
-
router.use("/:workspaceId/invitations/:invitationId/resend",
|
|
6868
|
-
router.use("/:workspaceId/invitations",
|
|
7076
|
+
router.use("/:workspaceId/invitations/:invitationId/resend", createResourceRateLimiter(rateLimit.database, rateLimit.secret, CLOUD_RATE_LIMITS.invitationMutation, (context) => context.req.param("workspaceId") ?? "unknown", () => false));
|
|
7077
|
+
router.use("/:workspaceId/invitations", createResourceRateLimiter(rateLimit.database, rateLimit.secret, CLOUD_RATE_LIMITS.invitationMutation, (context) => context.req.param("workspaceId") ?? "unknown", (context) => context.req.method !== "POST"));
|
|
6869
7078
|
}
|
|
6870
7079
|
return router.get("/", async (context) => {
|
|
6871
7080
|
const workspaces = await service.list(context.get("actor").userId);
|
|
@@ -6878,20 +7087,20 @@ function createWorkspaceRoutes(service, members, rateLimit) {
|
|
|
6878
7087
|
if (error instanceof WorkspaceSlugConflictError) return context.json({ error: { code: "slug_conflict" } }, 409);
|
|
6879
7088
|
throw error;
|
|
6880
7089
|
}
|
|
6881
|
-
}).get("/:workspaceId", async (context) => {
|
|
7090
|
+
}).get("/:workspaceId", workspaceParams, async (context) => {
|
|
6882
7091
|
const workspace = await service.get(context.get("actor").userId, context.req.param("workspaceId"));
|
|
6883
7092
|
if (!workspace) return context.json({ error: { code: "not_found" } }, 404);
|
|
6884
7093
|
return context.json({ workspace });
|
|
6885
|
-
}).patch("/:workspaceId", validatedJSON(parseUpdateWorkspace), (context) => memberRoute(context, async () => context.json({ workspace: await members.rename(context.get("actor").userId, context.req.param("workspaceId"), context.req.valid("json").name) }))).delete("/:workspaceId", (context) => memberRoute(context, async () => {
|
|
7094
|
+
}).patch("/:workspaceId", workspaceParams, validatedJSON(parseUpdateWorkspace), (context) => memberRoute(context, async () => context.json({ workspace: await members.rename(context.get("actor").userId, context.req.param("workspaceId"), context.req.valid("json").name) }))).delete("/:workspaceId", workspaceParams, (context) => memberRoute(context, async () => {
|
|
6886
7095
|
await members.delete(context.get("actor").userId, context.req.param("workspaceId"));
|
|
6887
7096
|
return context.body(null, 204);
|
|
6888
|
-
})).get("/:workspaceId/members", (context) => memberRoute(context, async () => context.json(await members.list(context.get("actor").userId, context.req.param("workspaceId"))))).post("/:workspaceId/invitations", validatedJSON(parseCreateWorkspaceInvitation), (context) => memberRoute(context, async () => context.json(await members.invite(context.get("actor").userId, context.req.param("workspaceId"), context.req.valid("json")), 201))).post("/:workspaceId/invitations/:invitationId/resend", (context) => memberRoute(context, async () => context.json(await members.resendInvitation(context.get("actor").userId, context.req.param("workspaceId"), context.req.param("invitationId"))))).delete("/:workspaceId/invitations/:invitationId", (context) => memberRoute(context, async () => {
|
|
7097
|
+
})).get("/:workspaceId/members", workspaceParams, (context) => memberRoute(context, async () => context.json(await members.list(context.get("actor").userId, context.req.param("workspaceId"))))).post("/:workspaceId/invitations", workspaceParams, validatedJSON(parseCreateWorkspaceInvitation), (context) => memberRoute(context, async () => context.json(await members.invite(context.get("actor").userId, context.req.param("workspaceId"), context.req.valid("json")), 201))).post("/:workspaceId/invitations/:invitationId/resend", workspaceInvitationParams, (context) => memberRoute(context, async () => context.json(await members.resendInvitation(context.get("actor").userId, context.req.param("workspaceId"), context.req.param("invitationId"))))).delete("/:workspaceId/invitations/:invitationId", workspaceInvitationParams, (context) => memberRoute(context, async () => {
|
|
6889
7098
|
await members.revokeInvitation(context.get("actor").userId, context.req.param("workspaceId"), context.req.param("invitationId"));
|
|
6890
7099
|
return context.body(null, 204);
|
|
6891
|
-
})).patch("/:workspaceId/members/:userId", validatedJSON(parseUpdateWorkspaceMember), (context) => memberRoute(context, async () => {
|
|
7100
|
+
})).patch("/:workspaceId/members/:userId", workspaceMemberParams, validatedJSON(parseUpdateWorkspaceMember), (context) => memberRoute(context, async () => {
|
|
6892
7101
|
await members.updateRole(context.get("actor").userId, context.req.param("workspaceId"), context.req.param("userId"), context.req.valid("json").role);
|
|
6893
7102
|
return context.body(null, 204);
|
|
6894
|
-
})).delete("/:workspaceId/members/:userId", (context) => memberRoute(context, async () => {
|
|
7103
|
+
})).delete("/:workspaceId/members/:userId", workspaceMemberParams, (context) => memberRoute(context, async () => {
|
|
6895
7104
|
await members.remove(context.get("actor").userId, context.req.param("workspaceId"), context.req.param("userId"));
|
|
6896
7105
|
return context.body(null, 204);
|
|
6897
7106
|
}));
|
|
@@ -6902,9 +7111,14 @@ function createPublicCloudAPIRouter(services) {
|
|
|
6902
7111
|
return new Hono().route("/public", createPublicProfileRoutes(services.profiles, services.documents)).route("/", createPublicSharingRoutes(services.sharing, services.resolveSession)).route("/", createPublicDocumentRoutes(services.sharing, services.documents, services.resolveSession)).route("/", createPublicCollaborationRoutes(services.collaboration, services.resolveSession));
|
|
6903
7112
|
}
|
|
6904
7113
|
function createCloudAPIRouter(services) {
|
|
6905
|
-
return new Hono().route("/", createPublicProfileSettingsRoutes(services.profiles)).route("/public", createPublicCloudAPIRouter(services)).get("/workspaces/:workspaceId/entitlements", async (context) => {
|
|
7114
|
+
return new Hono().route("/", createPublicProfileSettingsRoutes(services.profiles)).route("/public", createPublicCloudAPIRouter(services)).get("/workspaces/:workspaceId/entitlements", workspaceParams, async (context) => {
|
|
6906
7115
|
if (!services.entitlements) return context.json({ error: { code: "not_found" } }, 404);
|
|
6907
|
-
|
|
7116
|
+
try {
|
|
7117
|
+
return context.json({ entitlements: await services.entitlements.workspace(context.get("actor").userId, context.req.valid("param").workspaceId) });
|
|
7118
|
+
} catch (error) {
|
|
7119
|
+
if (error instanceof DocumentNotFoundError) return context.json({ error: { code: "not_found" } }, 404);
|
|
7120
|
+
throw error;
|
|
7121
|
+
}
|
|
6908
7122
|
}).get("/session", (context) => context.json({ user: context.get("actor") })).route("/", createAIRoutes(services.aiTokens, services.database && services.rateLimitSecret ? {
|
|
6909
7123
|
database: services.database,
|
|
6910
7124
|
secret: services.rateLimitSecret
|
|
@@ -7295,7 +7509,10 @@ function createCloudApp(services) {
|
|
|
7295
7509
|
resolveSession
|
|
7296
7510
|
});
|
|
7297
7511
|
const internalAPI = services.config.internalServiceToken ? createInternalRoutes(createInternalService(services.database), services.config.internalServiceToken) : new Hono();
|
|
7298
|
-
return new Hono().use(CLOUD_DISCOVERY_PATH, cloudCORS).use("/api/*", cloudCORS).use("
|
|
7512
|
+
return new Hono().use(CLOUD_DISCOVERY_PATH, cloudCORS).use("/api/*", cloudCORS).use("/api/*", bodyLimit({
|
|
7513
|
+
maxSize: CLOUD_API_MAX_BODY_BYTES,
|
|
7514
|
+
onError: (context) => context.json({ error: { code: "invalid_request" } }, 413)
|
|
7515
|
+
})).use("*", async (context, next) => {
|
|
7299
7516
|
await next();
|
|
7300
7517
|
if (shouldPreventIndexing(context.req.path, services.config.indexingPolicy)) context.header("X-Robots-Tag", "noindex, nofollow, noarchive");
|
|
7301
7518
|
}).get("/robots.txt", (context) => {
|
|
@@ -7333,15 +7550,6 @@ function createCloudDatabase(options) {
|
|
|
7333
7550
|
});
|
|
7334
7551
|
}
|
|
7335
7552
|
//#endregion
|
|
7336
|
-
//#region src/server/db/expressions.ts
|
|
7337
|
-
const CURRENT_TIMESTAMP = sql`current_timestamp`;
|
|
7338
|
-
const EMPTY_JSON_OBJECT = sql`'{}'::jsonb`;
|
|
7339
|
-
const CHECK_VALUE_PATTERN = /^[a-z][a-z0-9-]*$/;
|
|
7340
|
-
function checkColumnIn(column, values) {
|
|
7341
|
-
if (values.length === 0 || values.some((value) => !CHECK_VALUE_PATTERN.test(value))) throw new Error("Check constraint values must be non-empty lowercase identifiers");
|
|
7342
|
-
return sql`${sql.ref(column)} in (${sql.join(values.map((value) => sql.lit(value)))})`;
|
|
7343
|
-
}
|
|
7344
|
-
//#endregion
|
|
7345
7553
|
//#region src/server/db/migrations/helpers.ts
|
|
7346
7554
|
async function addCheckConstraint(database, table, constraint, column, values) {
|
|
7347
7555
|
await database.schema.alterTable(table).addCheckConstraint(constraint, checkColumnIn(column, values)).execute();
|
|
@@ -7363,11 +7571,11 @@ function addInvitationColumns(table, access) {
|
|
|
7363
7571
|
//#endregion
|
|
7364
7572
|
//#region src/server/db/migrations/001_foundation.ts
|
|
7365
7573
|
var _001_foundation_exports = /* @__PURE__ */ __exportAll({
|
|
7366
|
-
down: () => down$
|
|
7367
|
-
up: () => up$
|
|
7574
|
+
down: () => down$27,
|
|
7575
|
+
up: () => up$27
|
|
7368
7576
|
});
|
|
7369
7577
|
const UPDATED_AT_TRIGGER = "pairdraw_set_updated_at";
|
|
7370
|
-
async function up$
|
|
7578
|
+
async function up$27(database) {
|
|
7371
7579
|
await database.schema.createTable("workspace").addColumn("id", "uuid", (column) => column.primaryKey()).addColumn("name", "text", (column) => column.notNull()).addColumn("slug", "text", (column) => column.notNull().unique()).addColumn("created_by", "text", (column) => column.notNull()).execute();
|
|
7372
7580
|
await addCurrentTimestampColumns(database, "workspace", ["created_at", "updated_at"]);
|
|
7373
7581
|
await database.schema.createTable("workspace_member").addColumn("workspace_id", "uuid", (column) => column.references("workspace.id").onDelete("cascade").notNull()).addColumn("user_id", "text", (column) => column.notNull()).addColumn("role", "text", (column) => column.notNull()).addPrimaryKeyConstraint("workspace_member_primary", ["workspace_id", "user_id"]).addCheckConstraint("workspace_member_role_check", checkColumnIn("role", [
|
|
@@ -7404,7 +7612,7 @@ async function up$26(database) {
|
|
|
7404
7612
|
for each row execute function ${sql.id(UPDATED_AT_TRIGGER)}()
|
|
7405
7613
|
`.execute(database);
|
|
7406
7614
|
}
|
|
7407
|
-
async function down$
|
|
7615
|
+
async function down$27(database) {
|
|
7408
7616
|
await database.schema.dropTable("upload").ifExists().execute();
|
|
7409
7617
|
await database.schema.alterTable("document").dropConstraint("document_current_revision_foreign").execute();
|
|
7410
7618
|
await database.schema.dropTable("document_revision").ifExists().execute();
|
|
@@ -7417,10 +7625,10 @@ async function down$26(database) {
|
|
|
7417
7625
|
//#endregion
|
|
7418
7626
|
//#region src/server/db/migrations/002_upload_cleanup_claims.ts
|
|
7419
7627
|
var _002_upload_cleanup_claims_exports = /* @__PURE__ */ __exportAll({
|
|
7420
|
-
down: () => down$
|
|
7421
|
-
up: () => up$
|
|
7628
|
+
down: () => down$26,
|
|
7629
|
+
up: () => up$26
|
|
7422
7630
|
});
|
|
7423
|
-
async function up$
|
|
7631
|
+
async function up$26(database) {
|
|
7424
7632
|
await database.schema.alterTable("upload").addColumn("cleanup_claim_id", "uuid").addColumn("cleanup_claimed_at", "timestamptz").execute();
|
|
7425
7633
|
await database.schema.alterTable("upload").dropConstraint("upload_status_check").execute();
|
|
7426
7634
|
await database.schema.alterTable("upload").addCheckConstraint("upload_status_check", checkColumnIn("status", [
|
|
@@ -7430,7 +7638,7 @@ async function up$25(database) {
|
|
|
7430
7638
|
"abandoned"
|
|
7431
7639
|
])).execute();
|
|
7432
7640
|
}
|
|
7433
|
-
async function down$
|
|
7641
|
+
async function down$26(database) {
|
|
7434
7642
|
await database.schema.alterTable("upload").dropConstraint("upload_status_check").execute();
|
|
7435
7643
|
await database.schema.alterTable("upload").addCheckConstraint("upload_status_check", checkColumnIn("status", [
|
|
7436
7644
|
"pending",
|
|
@@ -7442,24 +7650,24 @@ async function down$25(database) {
|
|
|
7442
7650
|
//#endregion
|
|
7443
7651
|
//#region src/server/db/migrations/003_document_cleanup_claims.ts
|
|
7444
7652
|
var _003_document_cleanup_claims_exports = /* @__PURE__ */ __exportAll({
|
|
7445
|
-
down: () => down$
|
|
7446
|
-
up: () => up$
|
|
7653
|
+
down: () => down$25,
|
|
7654
|
+
up: () => up$25
|
|
7447
7655
|
});
|
|
7448
|
-
async function up$
|
|
7656
|
+
async function up$25(database) {
|
|
7449
7657
|
await database.schema.alterTable("document").addColumn("cleanup_claim_id", "uuid").addColumn("cleanup_claimed_at", "timestamptz").execute();
|
|
7450
7658
|
await database.schema.createIndex("document_cleanup_index").on("document").columns(["deleted_at", "cleanup_claimed_at"]).execute();
|
|
7451
7659
|
}
|
|
7452
|
-
async function down$
|
|
7660
|
+
async function down$25(database) {
|
|
7453
7661
|
await database.schema.dropIndex("document_cleanup_index").ifExists().execute();
|
|
7454
7662
|
await database.schema.alterTable("document").dropColumn("cleanup_claimed_at").dropColumn("cleanup_claim_id").execute();
|
|
7455
7663
|
}
|
|
7456
7664
|
//#endregion
|
|
7457
7665
|
//#region src/server/db/migrations/004_document_sharing.ts
|
|
7458
7666
|
var _004_document_sharing_exports = /* @__PURE__ */ __exportAll({
|
|
7459
|
-
down: () => down$
|
|
7460
|
-
up: () => up$
|
|
7667
|
+
down: () => down$24,
|
|
7668
|
+
up: () => up$24
|
|
7461
7669
|
});
|
|
7462
|
-
async function up$
|
|
7670
|
+
async function up$24(database) {
|
|
7463
7671
|
await database.schema.createTable("document_share").addColumn("id", "uuid", (column) => column.primaryKey()).addColumn("document_id", "uuid", (column) => column.references("document.id").onDelete("cascade").notNull()).addColumn("permission", "text", (column) => column.notNull()).addColumn("secret_hash", "text", (column) => column.notNull()).addColumn("room_epoch", "integer", (column) => column.notNull().defaultTo(0)).addColumn("created_by", "text", (column) => column.notNull()).addColumn("expires_at", "timestamptz").addColumn("revoked_at", "timestamptz").addColumn("last_used_at", "timestamptz").addCheckConstraint("document_share_permission_check", checkColumnIn("permission", ["view", "edit"])).execute();
|
|
7464
7672
|
await addCurrentTimestampColumns(database, "document_share", ["created_at", "updated_at"]);
|
|
7465
7673
|
await database.schema.createTable("document_grant").addColumn("id", "uuid", (column) => column.primaryKey()).addColumn("document_id", "uuid", (column) => column.references("document.id").onDelete("cascade").notNull()).addColumn("user_id", "text", (column) => column.notNull()).addColumn("permission", "text", (column) => column.notNull()).addColumn("created_by", "text", (column) => column.notNull()).addColumn("revoked_at", "timestamptz").addUniqueConstraint("document_grant_document_user_unique", ["document_id", "user_id"]).addCheckConstraint("document_grant_permission_check", checkColumnIn("permission", ["view", "edit"])).execute();
|
|
@@ -7470,7 +7678,7 @@ async function up$23(database) {
|
|
|
7470
7678
|
await database.schema.createIndex("document_grant_user_index").on("document_grant").columns(["user_id", "document_id"]).execute();
|
|
7471
7679
|
await database.schema.createIndex("document_invitation_document_index").on("document_invitation").columns(["document_id", "revoked_at"]).execute();
|
|
7472
7680
|
}
|
|
7473
|
-
async function down$
|
|
7681
|
+
async function down$24(database) {
|
|
7474
7682
|
await database.schema.dropTable("document_invitation").ifExists().execute();
|
|
7475
7683
|
await database.schema.dropTable("document_grant").ifExists().execute();
|
|
7476
7684
|
await database.schema.dropTable("document_share").ifExists().execute();
|
|
@@ -7478,73 +7686,73 @@ async function down$23(database) {
|
|
|
7478
7686
|
//#endregion
|
|
7479
7687
|
//#region src/server/db/migrations/005_document_collaboration_epoch.ts
|
|
7480
7688
|
var _005_document_collaboration_epoch_exports = /* @__PURE__ */ __exportAll({
|
|
7481
|
-
down: () => down$
|
|
7482
|
-
up: () => up$
|
|
7689
|
+
down: () => down$23,
|
|
7690
|
+
up: () => up$23
|
|
7483
7691
|
});
|
|
7484
|
-
async function up$
|
|
7692
|
+
async function up$23(database) {
|
|
7485
7693
|
await database.schema.alterTable("document").addColumn("collaborationEpoch", "integer", (column) => column.notNull().defaultTo(0)).execute();
|
|
7486
7694
|
}
|
|
7487
|
-
async function down$
|
|
7695
|
+
async function down$23(database) {
|
|
7488
7696
|
await database.schema.alterTable("document").dropColumn("collaborationEpoch").execute();
|
|
7489
7697
|
}
|
|
7490
7698
|
//#endregion
|
|
7491
7699
|
//#region src/server/db/migrations/006_invitation_continuation.ts
|
|
7492
7700
|
var _006_invitation_continuation_exports = /* @__PURE__ */ __exportAll({
|
|
7493
|
-
down: () => down$
|
|
7494
|
-
up: () => up$
|
|
7701
|
+
down: () => down$22,
|
|
7702
|
+
up: () => up$22
|
|
7495
7703
|
});
|
|
7496
|
-
async function up$
|
|
7704
|
+
async function up$22(database) {
|
|
7497
7705
|
await database.schema.createTable("invitationContinuation").addColumn("id", "text", (column) => column.primaryKey()).addColumn("invitationId", "uuid", (column) => column.notNull().references("documentInvitation.id").onDelete("cascade")).addColumn("tokenEncrypted", "text", (column) => column.notNull()).addColumn("expiresAt", "timestamptz", (column) => column.notNull()).addColumn("consumedAt", "timestamptz").addColumn("createdAt", "timestamptz", (column) => column.notNull().defaultTo(database.fn("now"))).execute();
|
|
7498
7706
|
await database.schema.createIndex("invitationContinuationExpiryIndex").on("invitationContinuation").column("expiresAt").execute();
|
|
7499
7707
|
}
|
|
7500
|
-
async function down$
|
|
7708
|
+
async function down$22(database) {
|
|
7501
7709
|
await database.schema.dropTable("invitationContinuation").execute();
|
|
7502
7710
|
}
|
|
7503
7711
|
//#endregion
|
|
7504
7712
|
//#region src/server/db/migrations/007_collaboration_state.ts
|
|
7505
7713
|
var _007_collaboration_state_exports = /* @__PURE__ */ __exportAll({
|
|
7506
|
-
down: () => down$
|
|
7507
|
-
up: () => up$
|
|
7714
|
+
down: () => down$21,
|
|
7715
|
+
up: () => up$21
|
|
7508
7716
|
});
|
|
7509
|
-
async function up$
|
|
7717
|
+
async function up$21(database) {
|
|
7510
7718
|
await database.schema.createTable("documentCollaborationState").addColumn("documentId", "uuid", (column) => column.notNull().references("document.id").onDelete("cascade")).addColumn("roomEpoch", "integer", (column) => column.notNull()).addColumn("state", "bytea", (column) => column.notNull()).addColumn("version", "integer", (column) => column.notNull().defaultTo(1)).addColumn("createdAt", "timestamptz", (column) => column.notNull().defaultTo(database.fn("now"))).addColumn("updatedAt", "timestamptz", (column) => column.notNull().defaultTo(database.fn("now"))).addPrimaryKeyConstraint("documentCollaborationStatePrimary", ["documentId", "roomEpoch"]).execute();
|
|
7511
7719
|
}
|
|
7512
|
-
async function down$
|
|
7720
|
+
async function down$21(database) {
|
|
7513
7721
|
await database.schema.dropTable("documentCollaborationState").execute();
|
|
7514
7722
|
}
|
|
7515
7723
|
//#endregion
|
|
7516
7724
|
//#region src/server/db/migrations/008_storage_reservations.ts
|
|
7517
7725
|
var _008_storage_reservations_exports = /* @__PURE__ */ __exportAll({
|
|
7518
|
-
down: () => down$
|
|
7519
|
-
up: () => up$
|
|
7726
|
+
down: () => down$20,
|
|
7727
|
+
up: () => up$20
|
|
7520
7728
|
});
|
|
7521
|
-
async function up$
|
|
7729
|
+
async function up$20(database) {
|
|
7522
7730
|
await database.schema.createTable("workspaceStorageUsage").addColumn("workspaceId", "uuid", (column) => column.primaryKey().references("workspace.id").onDelete("cascade")).addColumn("committedBytes", "bigint", (column) => column.notNull().defaultTo(0)).addColumn("updatedAt", "timestamptz", (column) => column.notNull().defaultTo(database.fn("now"))).execute();
|
|
7523
7731
|
await database.schema.createTable("uploadStorageReservation").addColumn("id", "uuid", (column) => column.primaryKey()).addColumn("workspaceId", "uuid", (column) => column.notNull().references("workspace.id").onDelete("cascade")).addColumn("uploadId", "uuid", (column) => column.notNull().unique().references("upload.id").onDelete("cascade")).addColumn("bytes", "bigint", (column) => column.notNull()).addColumn("expiresAt", "timestamptz", (column) => column.notNull()).addColumn("committedAt", "timestamptz").addColumn("releasedAt", "timestamptz").addColumn("createdAt", "timestamptz", (column) => column.notNull().defaultTo(database.fn("now"))).execute();
|
|
7524
7732
|
}
|
|
7525
|
-
async function down$
|
|
7733
|
+
async function down$20(database) {
|
|
7526
7734
|
await database.schema.dropTable("uploadStorageReservation").execute();
|
|
7527
7735
|
await database.schema.dropTable("workspaceStorageUsage").execute();
|
|
7528
7736
|
}
|
|
7529
7737
|
//#endregion
|
|
7530
7738
|
//#region src/server/db/migrations/009_workspace_entitlements.ts
|
|
7531
7739
|
var _009_workspace_entitlements_exports = /* @__PURE__ */ __exportAll({
|
|
7532
|
-
down: () => down$
|
|
7533
|
-
up: () => up$
|
|
7740
|
+
down: () => down$19,
|
|
7741
|
+
up: () => up$19
|
|
7534
7742
|
});
|
|
7535
|
-
async function up$
|
|
7743
|
+
async function up$19(database) {
|
|
7536
7744
|
await database.schema.createTable("workspaceEntitlement").addColumn("workspaceId", "uuid", (column) => column.primaryKey().references("workspace.id").onDelete("cascade")).addColumn("values", "jsonb", (column) => column.notNull()).addColumn("source", "text", (column) => column.notNull()).addColumn("revision", "integer", (column) => column.notNull().defaultTo(1)).addColumn("updatedAt", "timestamptz", (column) => column.notNull().defaultTo(CURRENT_TIMESTAMP)).execute();
|
|
7537
7745
|
}
|
|
7538
|
-
async function down$
|
|
7746
|
+
async function down$19(database) {
|
|
7539
7747
|
await database.schema.dropTable("workspaceEntitlement").execute();
|
|
7540
7748
|
}
|
|
7541
7749
|
//#endregion
|
|
7542
7750
|
//#region src/server/db/migrations/010_upload_finalization.ts
|
|
7543
7751
|
var _010_upload_finalization_exports = /* @__PURE__ */ __exportAll({
|
|
7544
|
-
down: () => down$
|
|
7545
|
-
up: () => up$
|
|
7752
|
+
down: () => down$18,
|
|
7753
|
+
up: () => up$18
|
|
7546
7754
|
});
|
|
7547
|
-
async function up$
|
|
7755
|
+
async function up$18(database) {
|
|
7548
7756
|
await replaceCheckConstraint(database, "upload", "upload_status_check", "status", [
|
|
7549
7757
|
"pending",
|
|
7550
7758
|
"finalizing",
|
|
@@ -7553,7 +7761,7 @@ async function up$17(database) {
|
|
|
7553
7761
|
"abandoned"
|
|
7554
7762
|
]);
|
|
7555
7763
|
}
|
|
7556
|
-
async function down$
|
|
7764
|
+
async function down$18(database) {
|
|
7557
7765
|
await replaceCheckConstraint(database, "upload", "upload_status_check", "status", [
|
|
7558
7766
|
"pending",
|
|
7559
7767
|
"cleaning",
|
|
@@ -7564,22 +7772,22 @@ async function down$17(database) {
|
|
|
7564
7772
|
//#endregion
|
|
7565
7773
|
//#region src/server/db/migrations/011_upload_finalization_lease.ts
|
|
7566
7774
|
var _011_upload_finalization_lease_exports = /* @__PURE__ */ __exportAll({
|
|
7567
|
-
down: () => down$
|
|
7568
|
-
up: () => up$
|
|
7775
|
+
down: () => down$17,
|
|
7776
|
+
up: () => up$17
|
|
7569
7777
|
});
|
|
7570
|
-
async function up$
|
|
7778
|
+
async function up$17(database) {
|
|
7571
7779
|
await database.schema.alterTable("upload").addColumn("finalization_started_at", "timestamptz").execute();
|
|
7572
7780
|
}
|
|
7573
|
-
async function down$
|
|
7781
|
+
async function down$17(database) {
|
|
7574
7782
|
await database.schema.alterTable("upload").dropColumn("finalization_started_at").execute();
|
|
7575
7783
|
}
|
|
7576
7784
|
//#endregion
|
|
7577
7785
|
//#region src/server/db/migrations/012_transactional_email.ts
|
|
7578
7786
|
var _012_transactional_email_exports = /* @__PURE__ */ __exportAll({
|
|
7579
|
-
down: () => down$
|
|
7580
|
-
up: () => up$
|
|
7787
|
+
down: () => down$16,
|
|
7788
|
+
up: () => up$16
|
|
7581
7789
|
});
|
|
7582
|
-
async function up$
|
|
7790
|
+
async function up$16(database) {
|
|
7583
7791
|
await database.schema.createTable("transactional_email").addColumn("id", "uuid", (column) => column.primaryKey()).addColumn("idempotency_key", "text", (column) => column.notNull().unique()).addColumn("kind", "text", (column) => column.notNull()).addColumn("recipient_email_normalized", "text", (column) => column.notNull()).addColumn("payload_encrypted", "text").addColumn("status", "text", (column) => column.notNull().defaultTo("pending")).addColumn("attempt_count", "integer", (column) => column.notNull().defaultTo(0)).addColumn("next_attempt_at", "timestamptz", (column) => column.notNull().defaultTo(CURRENT_TIMESTAMP)).addColumn("claim_id", "uuid").addColumn("claimed_at", "timestamptz").addColumn("transport", "text").addColumn("transport_message_id", "text").addColumn("last_error_code", "text").addColumn("created_at", "timestamptz", (column) => column.notNull().defaultTo(CURRENT_TIMESTAMP)).addColumn("updated_at", "timestamptz", (column) => column.notNull().defaultTo(CURRENT_TIMESTAMP)).addColumn("accepted_at", "timestamptz").addCheckConstraint("transactional_email_kind_check", checkColumnIn("kind", ["document-invitation"])).addCheckConstraint("transactional_email_status_check", checkColumnIn("status", [
|
|
7584
7792
|
"pending",
|
|
7585
7793
|
"sending",
|
|
@@ -7589,16 +7797,16 @@ async function up$15(database) {
|
|
|
7589
7797
|
])).execute();
|
|
7590
7798
|
await database.schema.createIndex("transactional_email_delivery_index").on("transactional_email").columns(["status", "next_attempt_at"]).execute();
|
|
7591
7799
|
}
|
|
7592
|
-
async function down$
|
|
7800
|
+
async function down$16(database) {
|
|
7593
7801
|
await database.schema.dropTable("transactional_email").ifExists().execute();
|
|
7594
7802
|
}
|
|
7595
7803
|
//#endregion
|
|
7596
7804
|
//#region src/server/db/migrations/013_admin_enrollment.ts
|
|
7597
7805
|
var _013_admin_enrollment_exports = /* @__PURE__ */ __exportAll({
|
|
7598
|
-
down: () => down$
|
|
7599
|
-
up: () => up$
|
|
7806
|
+
down: () => down$15,
|
|
7807
|
+
up: () => up$15
|
|
7600
7808
|
});
|
|
7601
|
-
async function up$
|
|
7809
|
+
async function up$15(database) {
|
|
7602
7810
|
await database.schema.createTable("cloud_enrollment").addColumn("id", "uuid", (column) => column.primaryKey()).addColumn("email_normalized", "text", (column) => column.notNull().unique()).addColumn("name", "text").addColumn("reason", "text").addColumn("status", "text", (column) => column.notNull().defaultTo("pending")).addColumn("requested_at", "timestamptz", (column) => column.notNull().defaultTo(CURRENT_TIMESTAMP)).addColumn("reviewed_at", "timestamptz").addColumn("reviewed_by", "text").addColumn("review_note", "text").addColumn("approved_user_id", "text").addCheckConstraint("cloud_enrollment_status_check", checkColumnIn("status", [
|
|
7603
7811
|
"pending",
|
|
7604
7812
|
"approved",
|
|
@@ -7609,17 +7817,17 @@ async function up$14(database) {
|
|
|
7609
7817
|
await database.schema.createTable("cloud_admin_audit_event").addColumn("id", "uuid", (column) => column.primaryKey()).addColumn("actor_user_id", "text", (column) => column.notNull()).addColumn("action", "text", (column) => column.notNull()).addColumn("subject_type", "text", (column) => column.notNull()).addColumn("subject_id", "text", (column) => column.notNull()).addColumn("metadata", "jsonb", (column) => column.notNull().defaultTo(EMPTY_JSON_OBJECT)).addColumn("created_at", "timestamptz", (column) => column.notNull().defaultTo(CURRENT_TIMESTAMP)).execute();
|
|
7610
7818
|
await database.schema.createIndex("cloud_admin_audit_created_index").on("cloud_admin_audit_event").column("created_at").execute();
|
|
7611
7819
|
}
|
|
7612
|
-
async function down$
|
|
7820
|
+
async function down$15(database) {
|
|
7613
7821
|
await database.schema.dropTable("cloud_admin_audit_event").ifExists().execute();
|
|
7614
7822
|
await database.schema.dropTable("cloud_enrollment").ifExists().execute();
|
|
7615
7823
|
}
|
|
7616
7824
|
//#endregion
|
|
7617
7825
|
//#region src/server/db/migrations/014_enrollment_email_kinds.ts
|
|
7618
7826
|
var _014_enrollment_email_kinds_exports = /* @__PURE__ */ __exportAll({
|
|
7619
|
-
down: () => down$
|
|
7620
|
-
up: () => up$
|
|
7827
|
+
down: () => down$14,
|
|
7828
|
+
up: () => up$14
|
|
7621
7829
|
});
|
|
7622
|
-
async function up$
|
|
7830
|
+
async function up$14(database) {
|
|
7623
7831
|
await replaceCheckConstraint(database, "transactional_email", "transactional_email_kind_check", "kind", [
|
|
7624
7832
|
"document-invitation",
|
|
7625
7833
|
"enrollment-requested",
|
|
@@ -7629,42 +7837,42 @@ async function up$13(database) {
|
|
|
7629
7837
|
"enrollment-revoked"
|
|
7630
7838
|
]);
|
|
7631
7839
|
}
|
|
7632
|
-
async function down$
|
|
7840
|
+
async function down$14(database) {
|
|
7633
7841
|
await replaceCheckConstraint(database, "transactional_email", "transactional_email_kind_check", "kind", ["document-invitation"]);
|
|
7634
7842
|
}
|
|
7635
7843
|
//#endregion
|
|
7636
7844
|
//#region src/server/db/migrations/015_cloud_rate_limit.ts
|
|
7637
7845
|
var _015_cloud_rate_limit_exports = /* @__PURE__ */ __exportAll({
|
|
7638
|
-
down: () => down$
|
|
7639
|
-
up: () => up$
|
|
7846
|
+
down: () => down$13,
|
|
7847
|
+
up: () => up$13
|
|
7640
7848
|
});
|
|
7641
|
-
async function up$
|
|
7849
|
+
async function up$13(database) {
|
|
7642
7850
|
await database.schema.alterTable("cloud_enrollment").addColumn("request_revision", "integer", (column) => column.notNull().defaultTo(1)).execute();
|
|
7643
7851
|
await database.schema.createTable("cloud_rate_limit").addColumn("key_hash", "text", (column) => column.primaryKey()).addColumn("window_started_at", "timestamptz", (column) => column.notNull()).addColumn("request_count", "integer", (column) => column.notNull().defaultTo(1)).execute();
|
|
7644
7852
|
await addCurrentTimestampColumns(database, "cloud_rate_limit", ["updated_at"]);
|
|
7645
7853
|
}
|
|
7646
|
-
async function down$
|
|
7854
|
+
async function down$13(database) {
|
|
7647
7855
|
await database.schema.dropTable("cloud_rate_limit").ifExists().execute();
|
|
7648
7856
|
await database.schema.alterTable("cloud_enrollment").dropColumn("request_revision").execute();
|
|
7649
7857
|
}
|
|
7650
7858
|
//#endregion
|
|
7651
7859
|
//#region src/server/db/migrations/016_auth_schema.ts
|
|
7652
7860
|
var _016_auth_schema_exports = /* @__PURE__ */ __exportAll({
|
|
7653
|
-
down: () => down$
|
|
7654
|
-
up: () => up$
|
|
7861
|
+
down: () => down$12,
|
|
7862
|
+
up: () => up$12
|
|
7655
7863
|
});
|
|
7656
|
-
async function up$
|
|
7864
|
+
async function up$12(database) {
|
|
7657
7865
|
await database.schema.createTable("cloud_auth_schema").addColumn("id", "text", (column) => column.primaryKey()).addColumn("version", "text", (column) => column.notNull()).execute();
|
|
7658
7866
|
await addCurrentTimestampColumns(database, "cloud_auth_schema", ["updated_at"]);
|
|
7659
7867
|
}
|
|
7660
|
-
async function down$
|
|
7868
|
+
async function down$12(database) {
|
|
7661
7869
|
await database.schema.dropTable("cloud_auth_schema").ifExists().execute();
|
|
7662
7870
|
}
|
|
7663
7871
|
//#endregion
|
|
7664
7872
|
//#region src/server/db/migrations/017_authentication_email_kinds.ts
|
|
7665
7873
|
var _017_authentication_email_kinds_exports = /* @__PURE__ */ __exportAll({
|
|
7666
|
-
down: () => down$
|
|
7667
|
-
up: () => up$
|
|
7874
|
+
down: () => down$11,
|
|
7875
|
+
up: () => up$11
|
|
7668
7876
|
});
|
|
7669
7877
|
const kinds = [
|
|
7670
7878
|
"document-invitation",
|
|
@@ -7674,7 +7882,7 @@ const kinds = [
|
|
|
7674
7882
|
"enrollment-rejected",
|
|
7675
7883
|
"enrollment-revoked"
|
|
7676
7884
|
];
|
|
7677
|
-
async function up$
|
|
7885
|
+
async function up$11(database) {
|
|
7678
7886
|
await replaceCheckConstraint(database, "transactional_email", "transactional_email_kind_check", "kind", [
|
|
7679
7887
|
...kinds,
|
|
7680
7888
|
"email-verification",
|
|
@@ -7682,19 +7890,19 @@ async function up$10(database) {
|
|
|
7682
7890
|
"password-changed"
|
|
7683
7891
|
]);
|
|
7684
7892
|
}
|
|
7685
|
-
async function down$
|
|
7893
|
+
async function down$11(database) {
|
|
7686
7894
|
await replaceCheckConstraint(database, "transactional_email", "transactional_email_kind_check", "kind", kinds);
|
|
7687
7895
|
}
|
|
7688
7896
|
//#endregion
|
|
7689
7897
|
//#region src/server/db/migrations/018_authentication_mfa.ts
|
|
7690
7898
|
var _018_authentication_mfa_exports = /* @__PURE__ */ __exportAll({
|
|
7691
|
-
down: () => down$
|
|
7692
|
-
up: () => up$
|
|
7899
|
+
down: () => down$10,
|
|
7900
|
+
up: () => up$10
|
|
7693
7901
|
});
|
|
7694
7902
|
async function tableNames(database) {
|
|
7695
7903
|
return new Set((await database.introspection.getTables()).map((table) => table.name));
|
|
7696
7904
|
}
|
|
7697
|
-
async function up$
|
|
7905
|
+
async function up$10(database) {
|
|
7698
7906
|
const cloud = database;
|
|
7699
7907
|
const tables = await tableNames(database);
|
|
7700
7908
|
await database.schema.createTable("cloud_mfa_assurance").addColumn("session_id", "uuid", (column) => column.primaryKey()).addColumn("user_id", "uuid", (column) => column.notNull()).addColumn("method", "text", (column) => column.notNull()).addColumn("verified_at", "timestamptz", (column) => column.notNull()).execute();
|
|
@@ -7709,7 +7917,7 @@ async function up$9(database) {
|
|
|
7709
7917
|
updatedAt: /* @__PURE__ */ new Date()
|
|
7710
7918
|
}).where("id", "=", "better-auth").where("version", "=", "1.7.2").execute();
|
|
7711
7919
|
}
|
|
7712
|
-
async function down$
|
|
7920
|
+
async function down$10(database) {
|
|
7713
7921
|
await database.schema.dropTable("cloud_mfa_assurance").ifExists().execute();
|
|
7714
7922
|
await database.schema.dropTable("passkey").ifExists().execute();
|
|
7715
7923
|
await database.schema.dropTable("two_factor").ifExists().execute();
|
|
@@ -7718,8 +7926,8 @@ async function down$9(database) {
|
|
|
7718
7926
|
//#endregion
|
|
7719
7927
|
//#region src/server/db/migrations/019_better_auth_account_issuer.ts
|
|
7720
7928
|
var _019_better_auth_account_issuer_exports = /* @__PURE__ */ __exportAll({
|
|
7721
|
-
down: () => down$
|
|
7722
|
-
up: () => up$
|
|
7929
|
+
down: () => down$9,
|
|
7930
|
+
up: () => up$9
|
|
7723
7931
|
});
|
|
7724
7932
|
/** The unique index Better Auth 1.7.0 through 1.7.2 created on `account (issuer, accountId)`. */
|
|
7725
7933
|
const ISSUER_INDEX = "account_issuer_accountId_uidx";
|
|
@@ -7729,7 +7937,7 @@ const ISSUER_INDEX = "account_issuer_accountId_uidx";
|
|
|
7729
7937
|
* Better Auth's 1.7 upgrade guide, the column becomes optional and its unique index goes; the
|
|
7730
7938
|
* column itself is left for a later cleanup.
|
|
7731
7939
|
*/
|
|
7732
|
-
async function up$
|
|
7940
|
+
async function up$9(database) {
|
|
7733
7941
|
const cloud = database;
|
|
7734
7942
|
if ((await database.introspection.getTables()).find((table) => table.name === "account")?.columns.some((column) => column.name === "issuer")) {
|
|
7735
7943
|
await database.schema.dropIndex(ISSUER_INDEX).ifExists().execute();
|
|
@@ -7740,7 +7948,7 @@ async function up$8(database) {
|
|
|
7740
7948
|
updatedAt: /* @__PURE__ */ new Date()
|
|
7741
7949
|
}).where("id", "=", "better-auth").where("version", "=", "1.7.2+mfa.1").execute();
|
|
7742
7950
|
}
|
|
7743
|
-
async function down$
|
|
7951
|
+
async function down$9(database) {
|
|
7744
7952
|
await database.updateTable("cloudAuthSchema").set({
|
|
7745
7953
|
version: "1.7.2+mfa.1",
|
|
7746
7954
|
updatedAt: /* @__PURE__ */ new Date()
|
|
@@ -7749,8 +7957,8 @@ async function down$8(database) {
|
|
|
7749
7957
|
//#endregion
|
|
7750
7958
|
//#region src/server/db/migrations/020_workspace_invitations.ts
|
|
7751
7959
|
var _020_workspace_invitations_exports = /* @__PURE__ */ __exportAll({
|
|
7752
|
-
down: () => down$
|
|
7753
|
-
up: () => up$
|
|
7960
|
+
down: () => down$8,
|
|
7961
|
+
up: () => up$8
|
|
7754
7962
|
});
|
|
7755
7963
|
const emailKinds$1 = [
|
|
7756
7964
|
"document-invitation",
|
|
@@ -7763,7 +7971,7 @@ const emailKinds$1 = [
|
|
|
7763
7971
|
"password-reset",
|
|
7764
7972
|
"password-changed"
|
|
7765
7973
|
];
|
|
7766
|
-
async function up$
|
|
7974
|
+
async function up$8(database) {
|
|
7767
7975
|
await addInvitationColumns(database.schema.createTable("workspace_invitation").addColumn("id", "uuid", (column) => column.primaryKey()).addColumn("workspace_id", "uuid", (column) => column.references("workspace.id").onDelete("cascade").notNull()), "role").addCheckConstraint("workspace_invitation_role_check", checkColumnIn("role", [
|
|
7768
7976
|
"admin",
|
|
7769
7977
|
"editor",
|
|
@@ -7773,22 +7981,22 @@ async function up$7(database) {
|
|
|
7773
7981
|
await database.schema.createIndex("workspace_invitation_workspace_index").on("workspace_invitation").columns(["workspace_id", "revoked_at"]).execute();
|
|
7774
7982
|
await replaceCheckConstraint(database, "transactional_email", "transactional_email_kind_check", "kind", [...emailKinds$1, "workspace-invitation"]);
|
|
7775
7983
|
}
|
|
7776
|
-
async function down$
|
|
7984
|
+
async function down$8(database) {
|
|
7777
7985
|
await replaceCheckConstraint(database, "transactional_email", "transactional_email_kind_check", "kind", emailKinds$1);
|
|
7778
7986
|
await database.schema.dropTable("workspace_invitation").execute();
|
|
7779
7987
|
}
|
|
7780
7988
|
//#endregion
|
|
7781
7989
|
//#region src/server/db/migrations/021_document_versions.ts
|
|
7782
7990
|
var _021_document_versions_exports = /* @__PURE__ */ __exportAll({
|
|
7783
|
-
down: () => down$
|
|
7991
|
+
down: () => down$7,
|
|
7784
7992
|
keepCurrentRevisions: () => keepCurrentRevisions,
|
|
7785
|
-
up: () => up$
|
|
7993
|
+
up: () => up$7
|
|
7786
7994
|
});
|
|
7787
7995
|
/**
|
|
7788
7996
|
* A document's version history: the revisions kept as checkpoints or named versions. Saves in
|
|
7789
7997
|
* between are compacted away, so a version is what keeps a revision and its stored file.
|
|
7790
7998
|
*/
|
|
7791
|
-
async function up$
|
|
7999
|
+
async function up$7(database) {
|
|
7792
8000
|
await database.schema.createTable("document_version").addColumn("id", "uuid", (column) => column.primaryKey()).addColumn("document_id", "uuid", (column) => column.references("document.id").onDelete("cascade").notNull()).addColumn("revision_id", "uuid", (column) => column.references("document_revision.id").onDelete("cascade").notNull().unique()).addColumn("kind", "text", (column) => column.notNull()).addColumn("name", "text").addColumn("description", "text").addColumn("created_by", "text", (column) => column.notNull()).addColumn("restored_from_version_id", "uuid", (column) => column.references("document_version.id").onDelete("set null")).addCheckConstraint("document_version_kind_check", checkColumnIn("kind", ["checkpoint", "named"])).execute();
|
|
7793
8001
|
await addCurrentTimestampColumns(database, "document_version", ["created_at"]);
|
|
7794
8002
|
await database.schema.createIndex("document_version_document_index").on("document_version").columns([
|
|
@@ -7798,7 +8006,7 @@ async function up$6(database) {
|
|
|
7798
8006
|
]).execute();
|
|
7799
8007
|
await keepCurrentRevisions(database);
|
|
7800
8008
|
}
|
|
7801
|
-
async function down$
|
|
8009
|
+
async function down$7(database) {
|
|
7802
8010
|
await database.schema.dropTable("document_version").execute();
|
|
7803
8011
|
}
|
|
7804
8012
|
/** Keeps each document's current revision as the first checkpoint of its history. */
|
|
@@ -7822,24 +8030,24 @@ async function keepCurrentRevisions(database) {
|
|
|
7822
8030
|
//#endregion
|
|
7823
8031
|
//#region src/server/db/migrations/022_entitlement_external_version.ts
|
|
7824
8032
|
var _022_entitlement_external_version_exports = /* @__PURE__ */ __exportAll({
|
|
7825
|
-
down: () => down$
|
|
7826
|
-
up: () => up$
|
|
8033
|
+
down: () => down$6,
|
|
8034
|
+
up: () => up$6
|
|
7827
8035
|
});
|
|
7828
8036
|
/**
|
|
7829
8037
|
* The version an external writer, such as a billing service, attached to a workspace's
|
|
7830
8038
|
* entitlements. Writers deliver out of order, so a write older than the stored one is refused.
|
|
7831
8039
|
*/
|
|
7832
|
-
async function up$
|
|
8040
|
+
async function up$6(database) {
|
|
7833
8041
|
await database.schema.alterTable("workspaceEntitlement").addColumn("externalVersion", "bigint").execute();
|
|
7834
8042
|
}
|
|
7835
|
-
async function down$
|
|
8043
|
+
async function down$6(database) {
|
|
7836
8044
|
await database.schema.alterTable("workspaceEntitlement").dropColumn("externalVersion").execute();
|
|
7837
8045
|
}
|
|
7838
8046
|
//#endregion
|
|
7839
8047
|
//#region src/server/db/migrations/023_document_images.ts
|
|
7840
8048
|
var _023_document_images_exports = /* @__PURE__ */ __exportAll({
|
|
7841
|
-
down: () => down$
|
|
7842
|
-
up: () => up$
|
|
8049
|
+
down: () => down$5,
|
|
8050
|
+
up: () => up$5
|
|
7843
8051
|
});
|
|
7844
8052
|
/**
|
|
7845
8053
|
* Images live once per workspace, keyed by the SHA-256 the object store verifies, each a stored
|
|
@@ -7847,7 +8055,7 @@ var _023_document_images_exports = /* @__PURE__ */ __exportAll({
|
|
|
7847
8055
|
* the images it uses under the names its file gives them. An image upload is an upload of its own
|
|
7848
8056
|
* kind, so reservations, commits, and expired-upload cleanup cover it.
|
|
7849
8057
|
*/
|
|
7850
|
-
async function up$
|
|
8058
|
+
async function up$5(database) {
|
|
7851
8059
|
await database.schema.alterTable("upload").addColumn("kind", "text", (column) => column.notNull().defaultTo("revision")).execute();
|
|
7852
8060
|
await addCheckConstraint(database, "upload", "upload_kind_check", "kind", ["revision", "image"]);
|
|
7853
8061
|
await database.schema.createTable("workspace_image").addColumn("workspace_id", "uuid", (column) => column.references("workspace.id").onDelete("cascade").notNull()).addColumn("checksum", "text", (column) => column.notNull()).addColumn("storage_object_id", "uuid", (column) => column.references("storage_object.id").notNull().unique()).addPrimaryKeyConstraint("workspace_image_pkey", ["workspace_id", "checksum"]).execute();
|
|
@@ -7855,7 +8063,7 @@ async function up$4(database) {
|
|
|
7855
8063
|
await database.schema.createTable("revision_image").addColumn("revision_id", "uuid", (column) => column.references("document_revision.id").onDelete("cascade").notNull()).addColumn("name", "text", (column) => column.notNull()).addColumn("workspace_id", "uuid", (column) => column.notNull()).addColumn("checksum", "text", (column) => column.notNull()).addPrimaryKeyConstraint("revision_image_pkey", ["revision_id", "name"]).addForeignKeyConstraint("revision_image_image_fkey", ["workspace_id", "checksum"], "workspace_image", ["workspace_id", "checksum"]).execute();
|
|
7856
8064
|
await database.schema.createIndex("revision_image_image_index").on("revision_image").columns(["workspace_id", "checksum"]).execute();
|
|
7857
8065
|
}
|
|
7858
|
-
async function down$
|
|
8066
|
+
async function down$5(database) {
|
|
7859
8067
|
await database.schema.dropTable("revision_image").execute();
|
|
7860
8068
|
await database.schema.dropTable("workspace_image").execute();
|
|
7861
8069
|
await database.schema.alterTable("upload").dropConstraint("upload_kind_check").execute();
|
|
@@ -7864,8 +8072,8 @@ async function down$4(database) {
|
|
|
7864
8072
|
//#endregion
|
|
7865
8073
|
//#region src/server/db/migrations/024_account_activity.ts
|
|
7866
8074
|
var _024_account_activity_exports = /* @__PURE__ */ __exportAll({
|
|
7867
|
-
down: () => down$
|
|
7868
|
-
up: () => up$
|
|
8075
|
+
down: () => down$4,
|
|
8076
|
+
up: () => up$4
|
|
7869
8077
|
});
|
|
7870
8078
|
const emailKinds = [
|
|
7871
8079
|
"document-invitation",
|
|
@@ -7884,7 +8092,7 @@ const emailKinds = [
|
|
|
7884
8092
|
* an address it never signed in from; a session keeps the row of the sign-in that made it, which
|
|
7885
8093
|
* names how it was made. The security notices that follow get their own email kinds.
|
|
7886
8094
|
*/
|
|
7887
|
-
async function up$
|
|
8095
|
+
async function up$4(database) {
|
|
7888
8096
|
await database.schema.createTable("sign_in").addColumn("id", "uuid", (column) => column.primaryKey()).addColumn("user_id", "uuid", (column) => column.notNull()).addColumn("session_id", "uuid").addColumn("method", "text", (column) => column.notNull()).addColumn("ip_address", "text").addColumn("user_agent", "text").addColumn("created_at", "timestamptz", (column) => column.notNull().defaultTo(CURRENT_TIMESTAMP)).execute();
|
|
7889
8097
|
await database.schema.createIndex("sign_in_user_index").on("sign_in").columns(["user_id", "created_at"]).execute();
|
|
7890
8098
|
await database.schema.createIndex("sign_in_session_index").on("sign_in").column("session_id").execute();
|
|
@@ -7895,15 +8103,15 @@ async function up$3(database) {
|
|
|
7895
8103
|
"two-step-changed"
|
|
7896
8104
|
]);
|
|
7897
8105
|
}
|
|
7898
|
-
async function down$
|
|
8106
|
+
async function down$4(database) {
|
|
7899
8107
|
await replaceCheckConstraint(database, "transactional_email", "transactional_email_kind_check", "kind", emailKinds);
|
|
7900
8108
|
await database.schema.dropTable("sign_in").execute();
|
|
7901
8109
|
}
|
|
7902
8110
|
//#endregion
|
|
7903
8111
|
//#region src/server/db/migrations/025_table_names.ts
|
|
7904
8112
|
var _025_table_names_exports = /* @__PURE__ */ __exportAll({
|
|
7905
|
-
down: () => down$
|
|
7906
|
-
up: () => up$
|
|
8113
|
+
down: () => down$3,
|
|
8114
|
+
up: () => up$3
|
|
7907
8115
|
});
|
|
7908
8116
|
/**
|
|
7909
8117
|
* Pairdraw's tables beside Better Auth's lose the `cloud_` prefix the rest never had; only the
|
|
@@ -7965,33 +8173,33 @@ async function rename(database, direction) {
|
|
|
7965
8173
|
}
|
|
7966
8174
|
if (!forward) for (const [from, to] of TABLES) await database.schema.alterTable(to).renameTo(from).execute();
|
|
7967
8175
|
}
|
|
7968
|
-
async function up$
|
|
8176
|
+
async function up$3(database) {
|
|
7969
8177
|
await rename(database, "up");
|
|
7970
8178
|
}
|
|
7971
|
-
async function down$
|
|
8179
|
+
async function down$3(database) {
|
|
7972
8180
|
await rename(database, "down");
|
|
7973
8181
|
}
|
|
7974
8182
|
//#endregion
|
|
7975
8183
|
//#region src/server/db/migrations/026_user_picture.ts
|
|
7976
8184
|
var _026_user_picture_exports = /* @__PURE__ */ __exportAll({
|
|
7977
|
-
down: () => down$
|
|
7978
|
-
up: () => up$
|
|
8185
|
+
down: () => down$2,
|
|
8186
|
+
up: () => up$2
|
|
7979
8187
|
});
|
|
7980
8188
|
/**
|
|
7981
8189
|
* The picture each account shows, kept by the server so pages never load one from another
|
|
7982
8190
|
* service: one uploaded by its owner, or the one a linked Google account gave it, copied at sign-in.
|
|
7983
8191
|
*/
|
|
7984
|
-
async function up$
|
|
8192
|
+
async function up$2(database) {
|
|
7985
8193
|
await database.schema.createTable("user_picture").addColumn("user_id", "uuid", (column) => column.primaryKey()).addColumn("bytes", "bytea", (column) => column.notNull()).addColumn("format", "text", (column) => column.notNull()).addColumn("checksum", "text", (column) => column.notNull()).addColumn("source", "text", (column) => column.notNull()).addColumn("created_at", "timestamptz", (column) => column.notNull().defaultTo(CURRENT_TIMESTAMP)).addCheckConstraint("user_picture_format_check", checkColumnIn("format", ["png", "jpeg"])).addCheckConstraint("user_picture_source_check", checkColumnIn("source", ["upload", "provider"])).execute();
|
|
7986
8194
|
}
|
|
7987
|
-
async function down$
|
|
8195
|
+
async function down$2(database) {
|
|
7988
8196
|
await database.schema.dropTable("user_picture").execute();
|
|
7989
8197
|
}
|
|
7990
8198
|
//#endregion
|
|
7991
8199
|
//#region src/server/db/migrations/027_sharing_comments_snapshots_profiles.ts
|
|
7992
8200
|
var _027_sharing_comments_snapshots_profiles_exports = /* @__PURE__ */ __exportAll({
|
|
7993
|
-
down: () => down,
|
|
7994
|
-
up: () => up
|
|
8201
|
+
down: () => down$1,
|
|
8202
|
+
up: () => up$1
|
|
7995
8203
|
});
|
|
7996
8204
|
const PERMISSION_TABLES = [
|
|
7997
8205
|
"document_share",
|
|
@@ -8003,7 +8211,7 @@ const PERMISSION_TABLES = [
|
|
|
8003
8211
|
* invitations; snapshot links that show one revision as it was shared; and public profiles that
|
|
8004
8212
|
* list the workspaces their owner made public.
|
|
8005
8213
|
*/
|
|
8006
|
-
async function up(database) {
|
|
8214
|
+
async function up$1(database) {
|
|
8007
8215
|
for (const table of PERMISSION_TABLES) await replaceCheckConstraint(database, table, `${table}_permission_check`, "permission", [
|
|
8008
8216
|
"view",
|
|
8009
8217
|
"comment",
|
|
@@ -8015,7 +8223,7 @@ async function up(database) {
|
|
|
8015
8223
|
await database.schema.createTable("public_profile").addColumn("user_id", "uuid", (column) => column.primaryKey()).addColumn("handle", "text", (column) => column.notNull().unique()).addColumn("bio", "text").execute();
|
|
8016
8224
|
await addCurrentTimestampColumns(database, "public_profile", ["created_at", "updated_at"]);
|
|
8017
8225
|
}
|
|
8018
|
-
async function down(database) {
|
|
8226
|
+
async function down$1(database) {
|
|
8019
8227
|
await database.schema.dropTable("public_profile").ifExists().execute();
|
|
8020
8228
|
await database.schema.alterTable("workspace").dropColumn("public_by").dropColumn("public_at").execute();
|
|
8021
8229
|
await database.schema.dropIndex("document_share_revision_index").ifExists().execute();
|
|
@@ -8026,6 +8234,25 @@ async function down(database) {
|
|
|
8026
8234
|
}
|
|
8027
8235
|
}
|
|
8028
8236
|
//#endregion
|
|
8237
|
+
//#region src/server/db/migrations/028_invitation_sends.ts
|
|
8238
|
+
var _028_invitation_sends_exports = /* @__PURE__ */ __exportAll({
|
|
8239
|
+
down: () => down,
|
|
8240
|
+
up: () => up
|
|
8241
|
+
});
|
|
8242
|
+
/**
|
|
8243
|
+
* Each invitation sent, by sender and recipient, for the daily invitation budget. It is kept apart
|
|
8244
|
+
* from the invitations themselves, which go with their workspace or document, so deleting one
|
|
8245
|
+
* never gives the budget back; rows older than a day are swept with the rate limits.
|
|
8246
|
+
*/
|
|
8247
|
+
async function up(database) {
|
|
8248
|
+
await database.schema.createTable("invitation_send").addColumn("id", "uuid", (column) => column.primaryKey()).addColumn("sender_id", "text", (column) => column.notNull()).addColumn("email_normalized", "text", (column) => column.notNull()).addColumn("sent_at", "timestamptz", (column) => column.notNull().defaultTo(CURRENT_TIMESTAMP)).execute();
|
|
8249
|
+
await database.schema.createIndex("invitation_send_sender_index").on("invitation_send").columns(["sender_id", "sent_at"]).execute();
|
|
8250
|
+
await database.schema.createIndex("invitation_send_recipient_index").on("invitation_send").columns(["email_normalized", "sent_at"]).execute();
|
|
8251
|
+
}
|
|
8252
|
+
async function down(database) {
|
|
8253
|
+
await database.schema.dropTable("invitation_send").execute();
|
|
8254
|
+
}
|
|
8255
|
+
//#endregion
|
|
8029
8256
|
//#region src/server/db/migrate.ts
|
|
8030
8257
|
const migrations = {
|
|
8031
8258
|
"001_foundation": _001_foundation_exports,
|
|
@@ -8054,7 +8281,8 @@ const migrations = {
|
|
|
8054
8281
|
"024_account_activity": _024_account_activity_exports,
|
|
8055
8282
|
"025_table_names": _025_table_names_exports,
|
|
8056
8283
|
"026_user_picture": _026_user_picture_exports,
|
|
8057
|
-
"027_sharing_comments_snapshots_profiles": _027_sharing_comments_snapshots_profiles_exports
|
|
8284
|
+
"027_sharing_comments_snapshots_profiles": _027_sharing_comments_snapshots_profiles_exports,
|
|
8285
|
+
"028_invitation_sends": _028_invitation_sends_exports
|
|
8058
8286
|
};
|
|
8059
8287
|
var CloudMigrationProvider = class {
|
|
8060
8288
|
async getMigrations() {
|
|
@@ -8848,9 +9076,6 @@ function startTransactionalEmailWorker(email, options) {
|
|
|
8848
9076
|
});
|
|
8849
9077
|
}
|
|
8850
9078
|
//#endregion
|
|
8851
|
-
|
|
8852
|
-
const noOpInvitationDelivery = { async sendDocumentInvitation() {} };
|
|
8853
|
-
//#endregion
|
|
8854
|
-
export { AINotEntitledError, AdminDomainError, CHECKPOINT_INTERVAL_MS, CLOUD_DEFAULT_MAX_COLLABORATION_MESSAGE_BYTES, CLOUD_DEFAULT_MAX_CONNECTIONS_PER_ROOM, CLOUD_FEATURE_KEYS, CLOUD_RATE_LIMITS, CloudConfigError, CloudPolicy, DatabaseEntitlementSource, DocumentConflictError, DocumentForbiddenError, DocumentNotFoundError, DocumentShareInvalidError, DocumentShareKindError, DocumentShareSignInRequiredError, EntitlementOpenFeatureProvider, LIMITED_HISTORY_DAYS, PostgresRateLimitStore, PublicProfileForbiddenError, PublicProfileHandleTakenError, REVISION_COMPACTION_GRACE_MS, StaticEntitlementSource, StorageQuotaExceededError, TransactionalEmailTransportError, UploadInvalidError, WorkspaceSlugConflictError, adminErrorStatus, authorizeRelayTicket, canEditDocument, capabilityHashMatches, cleanupPassOptions, cloudDeploymentConfigSchema, cloudDiscoveryFromConfig, configuredSocialProviders, createAIRoutes, createAITokenService, createAccountAuthenticationService, createActorRateLimiter, createAdminAuditService, createAdminEmailService, createAdminOperationsService, createAdminUserService, createAuthenticationEmailService, createBetterAuthAdapter, createCleanupServices, createCloudAPIRouter, createCloudAdminRoutes, createCloudApp, createCloudAuthenticationRuntime, createCloudDatabase, createCloudIdentityResolver, createCloudRateLimiter, createCloudSessionResolver, createCollaborationRelay, createCollaborationRoutes, createCollaborationStateStore, createCollaborationTicketService, createConfiguredCloudPolicy, createDefaultCloudPolicy, createDocumentCleanupService, createDocumentRoutes, createDocumentService, createDocumentSharingRoutes, createDocumentSharingService, createDocumentVersionRoutes, createDocumentVersionService, createEnrollmentService, createEntitlementService, createInternalRoutes, createInternalService, createInvitationOutbox, createPublicCloudAPIRouter, createPublicCollaborationRoutes, createPublicDocumentRoutes, createPublicProfileRoutes, createPublicProfileService, createPublicProfileSettingsRoutes, createPublicSharingRoutes, createRateLimitCleanupService, createRevisionCompactionService, createStorageQuotaService, createStorageReconciliationService, createTransactionalEmailService, createTrustedIPRateLimiter, createUploadCleanupService, createWorkspaceEntitlementRepository, createWorkspaceRoutes, createWorkspaceService, decryptContinuationToken, decryptTransactionalEmailPayload, encryptContinuationToken, encryptTransactionalEmailPayload, hashCapability, importAISigningKey, loadAISigningKey, migrateCloudDatabase, noOpInvitationDelivery, normalizeEnrollmentEmail, parseCloudDeploymentConfig, parseCloudDeploymentSource, parseCloudDeploymentTOML, parseCloudServerConfig, parseSetWorkspaceEntitlements, parseStaticEntitlementsTOML, rateLimitKey, relayDocumentLookups, resolveDocumentAccess, runCleanup, setWorkspaceEntitlementsSchema, shouldPreventIndexing, signCollaborationTicket, stampAwareness, startCleanupWorker, startTransactionalEmailWorker, staticEntitlementValues, staticEntitlementsSchema, trustedClientIP, withIndexingPolicy, workspaceAccessControl, workspaceRoles, workspaceStatements };
|
|
9079
|
+
export { AINotEntitledError, AdminDomainError, CHECKPOINT_INTERVAL_MS, CLOUD_DEFAULT_MAX_COLLABORATION_MESSAGE_BYTES, CLOUD_DEFAULT_MAX_CONNECTIONS_PER_ROOM, CLOUD_FEATURE_KEYS, CLOUD_RATE_LIMITS, CloudConfigError, CloudPolicy, DatabaseEntitlementSource, DocumentConflictError, DocumentForbiddenError, DocumentNotFoundError, DocumentShareInvalidError, DocumentShareKindError, DocumentShareSignInRequiredError, EntitlementOpenFeatureProvider, INVITATION_BUDGET, InvitationLimitError, LIMITED_HISTORY_DAYS, PostgresRateLimitStore, PublicProfileForbiddenError, PublicProfileHandleTakenError, REVISION_COMPACTION_GRACE_MS, StaticEntitlementSource, StorageQuotaExceededError, TransactionalEmailTransportError, UploadInvalidError, WorkspaceSlugConflictError, adminErrorStatus, authorizeRelayTicket, canEditDocument, capabilityHashMatches, cleanupPassOptions, cloudDeploymentConfigSchema, cloudDiscoveryFromConfig, configuredSocialProviders, createAIRoutes, createAITokenService, createAccountAuthenticationService, createActorRateLimiter, createAdminAuditService, createAdminEmailService, createAdminOperationsService, createAdminUserService, createAuthenticationEmailService, createBetterAuthAdapter, createCleanupServices, createCloudAPIRouter, createCloudAdminRoutes, createCloudApp, createCloudAuthenticationRuntime, createCloudDatabase, createCloudIdentityResolver, createCloudRateLimiter, createCloudSessionResolver, createCollaborationRelay, createCollaborationRoutes, createCollaborationStateStore, createCollaborationTicketService, createConfiguredCloudPolicy, createDefaultCloudPolicy, createDocumentCleanupService, createDocumentRoutes, createDocumentService, createDocumentSharingRoutes, createDocumentSharingService, createDocumentVersionRoutes, createDocumentVersionService, createEnrollmentService, createEntitlementService, createInternalRoutes, createInternalService, createInvitationOutbox, createPublicCloudAPIRouter, createPublicCollaborationRoutes, createPublicDocumentRoutes, createPublicProfileRoutes, createPublicProfileService, createPublicProfileSettingsRoutes, createPublicSharingRoutes, createRateLimitCleanupService, createRevisionCompactionService, createStorageQuotaService, createStorageReconciliationService, createTransactionalEmailService, createTrustedIPRateLimiter, createUploadCleanupService, createWorkspaceEntitlementRepository, createWorkspaceRoutes, createWorkspaceService, decryptContinuationToken, decryptTransactionalEmailPayload, encryptContinuationToken, encryptTransactionalEmailPayload, hashCapability, importAISigningKey, loadAISigningKey, migrateCloudDatabase, noOpInvitationDelivery, normalizeEnrollmentEmail, parseCloudDeploymentConfig, parseCloudDeploymentSource, parseCloudDeploymentTOML, parseCloudServerConfig, parseSetWorkspaceEntitlements, parseStaticEntitlementsTOML, rateLimitKey, relayDocumentLookups, resolveDocumentAccess, runCleanup, setWorkspaceEntitlementsSchema, shouldPreventIndexing, signCollaborationTicket, stampAwareness, startCleanupWorker, startTransactionalEmailWorker, staticEntitlementValues, staticEntitlementsSchema, trustedClientIP, withIndexingPolicy, workspaceAccessControl, workspaceRoles, workspaceStatements };
|
|
8855
9080
|
|
|
8856
9081
|
//# sourceMappingURL=server.js.map
|