@pairdraw/cloud 0.18.0 → 0.19.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/client.d.ts +5 -10
- package/dist/client.d.ts.map +1 -1
- package/dist/client.js +0 -7
- package/dist/client.js.map +1 -1
- package/dist/contract.d.ts +2 -2
- package/dist/contract.js +2 -2
- package/dist/contract2.js +8 -5
- package/dist/contract2.js.map +1 -1
- package/dist/email.js.map +1 -1
- package/dist/index.d.ts +9 -7
- package/dist/index.d.ts.map +1 -1
- package/dist/listen.mjs +202 -110
- package/dist/listen.mjs.map +1 -1
- package/dist/runtime-node.d.mts +2299 -661
- package/dist/runtime-node.d.mts.map +1 -1
- package/dist/server.d.ts +3319 -985
- package/dist/server.d.ts.map +1 -1
- package/dist/server.js +415 -190
- package/dist/server.js.map +1 -1
- package/dist/server.mjs +243 -79
- package/dist/server.mjs.map +1 -1
- package/package.json +2 -2
- package/src/client/api.ts +0 -15
- package/src/contract/documents.ts +8 -0
- package/src/contract/index.ts +1 -3
- package/src/contract/sharing.ts +0 -9
- package/src/runtime/cloudflare/relay.ts +5 -1
- package/src/runtime/cloudflare/worker.ts +4 -1
- package/src/runtime/node/bootstrap.ts +13 -3
- package/src/runtime/node/cleanup.ts +5 -1
- package/src/runtime/node/migrate.ts +5 -1
- package/src/runtime/node/server.ts +12 -2
- package/src/runtime/postgres/database.ts +20 -1
- package/src/runtime/site/server.ts +19 -2
- package/src/server/api/router.ts +16 -8
- package/src/server/api/types.ts +7 -0
- package/src/server/app.ts +9 -0
- package/src/server/auth/factory.ts +3 -0
- package/src/server/collaboration/relay/hub.ts +42 -3
- package/src/server/collaboration/routes.ts +21 -14
- package/src/server/config/schema.ts +3 -0
- package/src/server/db/expressions.ts +13 -1
- package/src/server/db/migrate.ts +3 -1
- package/src/server/db/migrations/028_invitation_sends.ts +31 -0
- package/src/server/db/tables.ts +9 -0
- package/src/server/documents/access.ts +4 -2
- package/src/server/documents/routes.ts +81 -57
- package/src/server/documents/versions/routes.ts +27 -16
- package/src/server/index.ts +2 -0
- package/src/server/invitations/budget.ts +66 -0
- package/src/server/invitations/index.ts +1 -0
- package/src/server/profiles/routes.ts +16 -12
- package/src/server/rate-limit/cleanup.ts +17 -5
- package/src/server/rate-limit/index.ts +4 -1
- package/src/server/rate-limit/middleware.ts +98 -11
- package/src/server/sharing/capabilities/service.ts +27 -2
- package/src/server/sharing/document-routes.ts +30 -22
- package/src/server/sharing/grants/service.ts +13 -7
- package/src/server/sharing/http.ts +4 -0
- package/src/server/sharing/invitations/service.ts +2 -0
- package/src/server/sharing/routes.ts +79 -64
- package/src/server/sharing/service.ts +1 -17
- package/src/server/validation.ts +76 -0
- package/src/server/workspaces/members.ts +2 -0
- package/src/server/workspaces/routes.ts +56 -35
package/dist/server.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { CLOUD_AI_JWKS_PATH, CLOUD_AI_TOKEN_AUDIENCE, CLOUD_DISCOVERY_PATH, CLOUD_PROTOCOL_MAX_UPLOAD_BYTES, COLLAB_ACTIONS, CloudConfigError, MAX_COLLAB_MESSAGE_BYTES, RELAY_CLOSE, RELAY_DOCUMENT_PARAM, RELAY_MINIMUM_MESSAGE_BYTES, RELAY_SERVER_PEER, cloudDeploymentConfigSchema, createRelayClientAssembler, decodeRelayClientFrame, decodeRoomUpdate, defaultRelayURL, documentDownloadSchema, documentPermissionSchema, documentSummarySchema, encodeSyncReply, listen, migrateCloudDatabase, parseCloudDiscovery, parseCloudServerConfig, parseCommitImageUploads, parseCommitUpload, parseCreateAIToken, parseCreateDocument, parseCreateUpload, parseRequestImageLinks, parseRequestImageUploads, presenceName, relayServerMessages, requestImageLinksSchema, staticEntitlementsSchema, validatedJSON, validatedQuery } from "./listen.mjs";
|
|
1
|
+
import { CLOUD_AI_JWKS_PATH, CLOUD_AI_TOKEN_AUDIENCE, CLOUD_API_MAX_BODY_BYTES, CLOUD_DISCOVERY_PATH, CLOUD_PROTOCOL_MAX_UPLOAD_BYTES, COLLAB_ACTIONS, CloudConfigError, MAX_COLLAB_MESSAGE_BYTES, RELAY_CLOSE, RELAY_DOCUMENT_PARAM, RELAY_MINIMUM_MESSAGE_BYTES, RELAY_SERVER_PEER, cloudDeploymentConfigSchema, createRelayClientAssembler, decodeRelayClientFrame, decodeRoomUpdate, defaultRelayURL, documentDownloadSchema, documentInvitationParams, documentParams, documentPermissionSchema, documentShareParams, documentSummarySchema, documentUserParams, documentVersionParams, encodeSyncReply, invitationParams, listen, lockForTransaction, migrateCloudDatabase, parseCloudDiscovery, parseCloudServerConfig, parseCommitImageUploads, parseCommitUpload, parseCreateAIToken, parseCreateDocument, parseCreateUpload, parseRequestImageLinks, parseRequestImageUploads, presenceName, relayServerMessages, requestImageLinksSchema, shareParams, staticEntitlementsSchema, uploadParams, validatedJSON, validatedQuery, workspaceInvitationParams, workspaceMemberParams, workspaceParams } from "./listen.mjs";
|
|
2
2
|
import { readFile } from "node:fs/promises";
|
|
3
3
|
import { isValid, toUint8Array } from "js-base64";
|
|
4
4
|
import * as v from "valibot";
|
|
@@ -16,6 +16,7 @@ import { parse } from "smol-toml";
|
|
|
16
16
|
import { CamelCasePlugin, Kysely, NoResultError, PostgresDialect } from "kysely";
|
|
17
17
|
import { Pool } from "pg";
|
|
18
18
|
import { rateLimiter } from "hono-rate-limiter";
|
|
19
|
+
import { every } from "hono/combine";
|
|
19
20
|
import { matchedRoutes } from "hono/route";
|
|
20
21
|
import { sha256 } from "@noble/hashes/sha2.js";
|
|
21
22
|
import { bytesToHex, hexToBytes, utf8ToBytes } from "@noble/hashes/utils.js";
|
|
@@ -650,7 +651,6 @@ v.variant("kind", [v.object({
|
|
|
650
651
|
workspaceId: v.pipe(v.string(), v.uuid()),
|
|
651
652
|
role: workspaceRoleSchema
|
|
652
653
|
})]);
|
|
653
|
-
const lookupCloudUserSchema = v.object({ email: v.pipe(v.string(), v.trim(), v.toLowerCase(), v.email()) });
|
|
654
654
|
const putDocumentGrantSchema = v.object({ permission: documentPermissionSchema });
|
|
655
655
|
const createDocumentInvitationSchema = v.object({
|
|
656
656
|
email: v.pipe(v.string(), v.trim(), v.toLowerCase(), v.email()),
|
|
@@ -691,9 +691,6 @@ v.object({
|
|
|
691
691
|
function parseCreateInvitationContinuation(input) {
|
|
692
692
|
return v.parse(createInvitationContinuationSchema, input);
|
|
693
693
|
}
|
|
694
|
-
function parseLookupCloudUser(input) {
|
|
695
|
-
return v.parse(lookupCloudUserSchema, input);
|
|
696
|
-
}
|
|
697
694
|
function parseCreateDocumentShare(input) {
|
|
698
695
|
return v.parse(createDocumentShareSchema, input);
|
|
699
696
|
}
|
|
@@ -905,11 +902,52 @@ const parseEnrollmentReview = (input) => v.parse(enrollmentReviewSchema, input);
|
|
|
905
902
|
const parseUserMutation = (input) => v.parse(userMutationSchema, input);
|
|
906
903
|
const parseUserRoleMutation = (input) => v.parse(userRoleMutationSchema, input);
|
|
907
904
|
//#endregion
|
|
905
|
+
//#region src/server/invitations/budget.ts
|
|
906
|
+
/**
|
|
907
|
+
* How many invitations, to documents and workspaces alike, one person may send in a day, and how
|
|
908
|
+
* many one address may receive from everyone. Each sends an email naming the inviter and the file,
|
|
909
|
+
* both of which the sender chooses, so without a daily budget invitations are a way to send spam.
|
|
910
|
+
*/
|
|
911
|
+
const INVITATION_BUDGET = {
|
|
912
|
+
windowMs: 864e5,
|
|
913
|
+
perSender: 100,
|
|
914
|
+
perRecipient: 5
|
|
915
|
+
};
|
|
916
|
+
/** An invitation past the sender's or the recipient's daily budget. */
|
|
917
|
+
var InvitationLimitError = class extends Error {
|
|
918
|
+
name = "InvitationLimitError";
|
|
919
|
+
};
|
|
920
|
+
async function sentSince(transaction, column, value, since) {
|
|
921
|
+
const row = await transaction.selectFrom("invitationSend").select((expression) => expression.fn.countAll().as("count")).where(column, "=", value).where("sentAt", ">", since).executeTakeFirstOrThrow();
|
|
922
|
+
return Number(row.count);
|
|
923
|
+
}
|
|
924
|
+
/**
|
|
925
|
+
* Counts an invitation from `senderId` to `email` against both daily budgets, in the transaction
|
|
926
|
+
* that creates it, or refuses it once either budget is used. Sends are logged apart from the
|
|
927
|
+
* invitations, so deleting a workspace or document gives nothing back, and the check holds locks
|
|
928
|
+
* on the sender and the recipient, so two invitations at once cannot both take the last one.
|
|
929
|
+
*/
|
|
930
|
+
async function spendInvitationBudget(transaction, invitation, now = /* @__PURE__ */ new Date()) {
|
|
931
|
+
const email = invitation.email.trim().toLowerCase();
|
|
932
|
+
await lockForTransaction(transaction, `invitation-sender:${invitation.senderId}`);
|
|
933
|
+
await lockForTransaction(transaction, `invitation-recipient:${email}`);
|
|
934
|
+
const since = new Date(now.getTime() - INVITATION_BUDGET.windowMs);
|
|
935
|
+
const bySender = await sentSince(transaction, "senderId", invitation.senderId, since);
|
|
936
|
+
const byRecipient = await sentSince(transaction, "emailNormalized", email, since);
|
|
937
|
+
if (bySender >= INVITATION_BUDGET.perSender || byRecipient >= INVITATION_BUDGET.perRecipient) throw new InvitationLimitError();
|
|
938
|
+
await transaction.insertInto("invitationSend").values({
|
|
939
|
+
id: crypto.randomUUID(),
|
|
940
|
+
senderId: invitation.senderId,
|
|
941
|
+
emailNormalized: email,
|
|
942
|
+
sentAt: now
|
|
943
|
+
}).execute();
|
|
944
|
+
}
|
|
945
|
+
//#endregion
|
|
908
946
|
//#region src/server/rate-limit/cleanup.ts
|
|
909
947
|
function createRateLimitCleanupService(database) {
|
|
910
948
|
return { async cleanupExpired(before) {
|
|
911
|
-
const
|
|
912
|
-
return Number(
|
|
949
|
+
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()]);
|
|
950
|
+
return Number(limits.numDeletedRows) + Number(invitations.numDeletedRows);
|
|
913
951
|
} };
|
|
914
952
|
}
|
|
915
953
|
//#endregion
|
|
@@ -982,12 +1020,14 @@ const CLOUD_RATE_LIMITS = {
|
|
|
982
1020
|
collaborationTicket: {
|
|
983
1021
|
namespace: "collaboration-ticket",
|
|
984
1022
|
windowMs: 6e4,
|
|
985
|
-
limit: 60
|
|
1023
|
+
limit: 60,
|
|
1024
|
+
actorLimit: 300
|
|
986
1025
|
},
|
|
987
1026
|
invitationMutation: {
|
|
988
1027
|
namespace: "invitation-mutation",
|
|
989
1028
|
windowMs: 6e4,
|
|
990
|
-
limit: 30
|
|
1029
|
+
limit: 30,
|
|
1030
|
+
actorLimit: 60
|
|
991
1031
|
},
|
|
992
1032
|
workspaceCreation: {
|
|
993
1033
|
namespace: "workspace-creation",
|
|
@@ -997,12 +1037,14 @@ const CLOUD_RATE_LIMITS = {
|
|
|
997
1037
|
documentCreation: {
|
|
998
1038
|
namespace: "document-creation",
|
|
999
1039
|
windowMs: 6e4,
|
|
1000
|
-
limit: 60
|
|
1040
|
+
limit: 60,
|
|
1041
|
+
actorLimit: 120
|
|
1001
1042
|
},
|
|
1002
1043
|
uploadCreation: {
|
|
1003
1044
|
namespace: "upload-creation",
|
|
1004
1045
|
windowMs: 6e4,
|
|
1005
|
-
limit: 120
|
|
1046
|
+
limit: 120,
|
|
1047
|
+
actorLimit: 600
|
|
1006
1048
|
},
|
|
1007
1049
|
authenticatedMutation: {
|
|
1008
1050
|
namespace: "authenticated-mutation",
|
|
@@ -1074,11 +1116,50 @@ function createActorRateLimiter(database, secret, policy, skip, resource) {
|
|
|
1074
1116
|
});
|
|
1075
1117
|
}
|
|
1076
1118
|
/**
|
|
1077
|
-
* A limiter a route mounts for its own budget, such as
|
|
1119
|
+
* A limiter a route mounts for its own budget, such as workspace creation; general limiters leave
|
|
1078
1120
|
* the requests it counts to it.
|
|
1079
1121
|
*/
|
|
1080
|
-
function createRouteRateLimiter(database, secret, policy, skip
|
|
1081
|
-
return ownBudget(createActorRateLimiter(database, secret, policy, skip
|
|
1122
|
+
function createRouteRateLimiter(database, secret, policy, skip) {
|
|
1123
|
+
return ownBudget(createActorRateLimiter(database, secret, policy, skip), skip);
|
|
1124
|
+
}
|
|
1125
|
+
/**
|
|
1126
|
+
* A route's own budget counted per resource, such as uploads per document, and capped per actor
|
|
1127
|
+
* across resources by `actorLimit`; general limiters leave the requests it counts to it.
|
|
1128
|
+
*/
|
|
1129
|
+
function createResourceRateLimiter(database, secret, policy, resource, skip) {
|
|
1130
|
+
const perResource = createActorRateLimiter(database, secret, policy, skip, resource);
|
|
1131
|
+
const perActor = createActorRateLimiter(database, secret, {
|
|
1132
|
+
namespace: `${policy.namespace}-actor`,
|
|
1133
|
+
windowMs: policy.windowMs,
|
|
1134
|
+
limit: policy.actorLimit
|
|
1135
|
+
}, skip);
|
|
1136
|
+
return ownBudget(every(perResource, keepResourceUse, perActor, reportTighterBudget(policy.windowMs)), skip);
|
|
1137
|
+
}
|
|
1138
|
+
/** Keeps the resource budget's use, which the actor-wide limiter would record over. */
|
|
1139
|
+
const keepResourceUse = async (context, next) => {
|
|
1140
|
+
context.set("resourceRateLimit", context.get("rateLimit"));
|
|
1141
|
+
await next();
|
|
1142
|
+
};
|
|
1143
|
+
/**
|
|
1144
|
+
* Reports whichever budget has fewer requests left in the `RateLimit` headers, as both limiters
|
|
1145
|
+
* write them and the last would otherwise win. A refused request keeps the headers of the budget
|
|
1146
|
+
* that refused it.
|
|
1147
|
+
*/
|
|
1148
|
+
function reportTighterBudget(windowMs) {
|
|
1149
|
+
return async (context, next) => {
|
|
1150
|
+
const resource = context.get("resourceRateLimit");
|
|
1151
|
+
const actor = context.get("rateLimit");
|
|
1152
|
+
const tighter = resource && actor && resource.remaining < actor.remaining ? resource : actor;
|
|
1153
|
+
if (tighter) setBudgetHeaders(context, tighter, windowMs);
|
|
1154
|
+
await next();
|
|
1155
|
+
};
|
|
1156
|
+
}
|
|
1157
|
+
/** The draft-7 `RateLimit` headers `hono-rate-limiter` writes, for one budget's use. */
|
|
1158
|
+
function setBudgetHeaders(context, use, windowMs) {
|
|
1159
|
+
const windowSeconds = Math.ceil(windowMs / 1e3);
|
|
1160
|
+
const reset = use.resetTime ? Math.max(0, Math.ceil((use.resetTime.getTime() - Date.now()) / 1e3)) : windowSeconds;
|
|
1161
|
+
context.header("RateLimit-Policy", `${use.limit};w=${windowSeconds}`);
|
|
1162
|
+
context.header("RateLimit", `limit=${use.limit}, remaining=${use.remaining}, reset=${reset}`);
|
|
1082
1163
|
}
|
|
1083
1164
|
//#endregion
|
|
1084
1165
|
//#region src/admin/api/routes.ts
|
|
@@ -1102,10 +1183,10 @@ const parseUserQuery = listQuery(cloudAdminUserFilterSchema);
|
|
|
1102
1183
|
const parseEmailQuery = listQuery(cloudAdminEmailFilterSchema);
|
|
1103
1184
|
const parseAuditQuery = listQuery(cloudAdminAuditFilterSchema);
|
|
1104
1185
|
/** Accounts are named by UUID; anything else names no one, rather than failing the query. */
|
|
1105
|
-
const accountIdSchema = v.pipe(v.string(), v.uuid());
|
|
1186
|
+
const accountIdSchema$1 = v.pipe(v.string(), v.uuid());
|
|
1106
1187
|
/** Does what an administrator asked to another account; one that is not an account is not found. */
|
|
1107
1188
|
async function accountMutation(context, userId, mutate) {
|
|
1108
|
-
if (!v.is(accountIdSchema, userId)) return context.json({ error: { code: "not_found" } }, 404);
|
|
1189
|
+
if (!v.is(accountIdSchema$1, userId)) return context.json({ error: { code: "not_found" } }, 404);
|
|
1109
1190
|
await mutate(context.get("actor").userId, userId);
|
|
1110
1191
|
return context.json({ ok: true });
|
|
1111
1192
|
}
|
|
@@ -1125,7 +1206,7 @@ function createCloudAdminRoutes(services, trustedOrigins, security) {
|
|
|
1125
1206
|
throw error;
|
|
1126
1207
|
}).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) => {
|
|
1127
1208
|
const id = context.req.param("id");
|
|
1128
|
-
const detail = v.is(accountIdSchema, id) ? await services.users.detail(id) : null;
|
|
1209
|
+
const detail = v.is(accountIdSchema$1, id) ? await services.users.detail(id) : null;
|
|
1129
1210
|
if (!detail) return context.json({ error: { code: "not_found" } }, 404);
|
|
1130
1211
|
return context.json(detail);
|
|
1131
1212
|
}).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) => {
|
|
@@ -2552,6 +2633,10 @@ function createBetterAuthAdapter(config, database, enrollment = createEnrollment
|
|
|
2552
2633
|
window: 60,
|
|
2553
2634
|
max: 60
|
|
2554
2635
|
},
|
|
2636
|
+
[devices.endpoints.deviceVerify.path]: {
|
|
2637
|
+
window: 60,
|
|
2638
|
+
max: 20
|
|
2639
|
+
},
|
|
2555
2640
|
[devices.endpoints.deviceApprove.path]: {
|
|
2556
2641
|
window: 60,
|
|
2557
2642
|
max: 10
|
|
@@ -3251,7 +3336,7 @@ async function resolveDocumentAccess(database, userId, documentId) {
|
|
|
3251
3336
|
if (!document) return void 0;
|
|
3252
3337
|
const sources = [];
|
|
3253
3338
|
const candidates = [];
|
|
3254
|
-
const owner = document.createdBy === userId;
|
|
3339
|
+
const owner = document.createdBy === userId && document.workspaceRole !== null;
|
|
3255
3340
|
if (owner) {
|
|
3256
3341
|
sources.push("owner");
|
|
3257
3342
|
candidates.push("edit");
|
|
@@ -3283,7 +3368,7 @@ function canEditDocument(access) {
|
|
|
3283
3368
|
async function canDeleteDocument(database, userId, documentId) {
|
|
3284
3369
|
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();
|
|
3285
3370
|
if (!document) return false;
|
|
3286
|
-
return document.createdBy === userId || document.workspaceRole === "admin" || document.workspaceRole === "editor";
|
|
3371
|
+
return document.createdBy === userId && document.workspaceRole !== null || document.workspaceRole === "admin" || document.workspaceRole === "editor";
|
|
3287
3372
|
}
|
|
3288
3373
|
//#endregion
|
|
3289
3374
|
//#region src/server/documents/errors.ts
|
|
@@ -3398,15 +3483,15 @@ async function documentResponse(context, respond) {
|
|
|
3398
3483
|
function createDocumentRoutes(service, rateLimit) {
|
|
3399
3484
|
const router = new Hono();
|
|
3400
3485
|
if (rateLimit) {
|
|
3401
|
-
router.use("/workspaces/:workspaceId/documents",
|
|
3402
|
-
router.use("/documents/:documentId/images",
|
|
3403
|
-
router.use("/documents/:documentId/uploads",
|
|
3486
|
+
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"));
|
|
3487
|
+
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"));
|
|
3488
|
+
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"));
|
|
3404
3489
|
}
|
|
3405
|
-
return router.get("/shared-documents", async (context) => context.json({ documents: await service.listShared(context.get("actor").userId) })).get("/workspaces/:workspaceId/documents", async (context) => {
|
|
3490
|
+
return router.get("/shared-documents", async (context) => context.json({ documents: await service.listShared(context.get("actor").userId) })).get("/workspaces/:workspaceId/documents", workspaceParams, async (context) => {
|
|
3406
3491
|
const documents = await service.list(context.get("actor").userId, context.req.param("workspaceId"));
|
|
3407
3492
|
if (!documents) return context.json({ error: { code: "not_found" } }, 404);
|
|
3408
3493
|
return context.json({ documents });
|
|
3409
|
-
}).get("/workspaces/:workspaceId/usage", async (context) => {
|
|
3494
|
+
}).get("/workspaces/:workspaceId/usage", workspaceParams, async (context) => {
|
|
3410
3495
|
try {
|
|
3411
3496
|
return context.json({ usage: await service.usage(context.get("actor").userId, context.req.param("workspaceId")) });
|
|
3412
3497
|
} catch (error) {
|
|
@@ -3414,7 +3499,7 @@ function createDocumentRoutes(service, rateLimit) {
|
|
|
3414
3499
|
if (response) return response;
|
|
3415
3500
|
throw error;
|
|
3416
3501
|
}
|
|
3417
|
-
}).post("/workspaces/:workspaceId/documents", validatedJSON(parseCreateDocument), async (context) => {
|
|
3502
|
+
}).post("/workspaces/:workspaceId/documents", workspaceParams, validatedJSON(parseCreateDocument), async (context) => {
|
|
3418
3503
|
try {
|
|
3419
3504
|
const document = await service.create(context.get("actor").userId, context.req.param("workspaceId"), context.req.valid("json"));
|
|
3420
3505
|
return context.json({ document }, 201);
|
|
@@ -3423,7 +3508,7 @@ function createDocumentRoutes(service, rateLimit) {
|
|
|
3423
3508
|
if (response) return response;
|
|
3424
3509
|
throw error;
|
|
3425
3510
|
}
|
|
3426
|
-
}).delete("/documents/:documentId", async (context) => {
|
|
3511
|
+
}).delete("/documents/:documentId", documentParams, async (context) => {
|
|
3427
3512
|
try {
|
|
3428
3513
|
await service.remove(context.get("actor").userId, context.req.param("documentId"));
|
|
3429
3514
|
return context.body(null, 204);
|
|
@@ -3432,7 +3517,7 @@ function createDocumentRoutes(service, rateLimit) {
|
|
|
3432
3517
|
if (response) return response;
|
|
3433
3518
|
throw error;
|
|
3434
3519
|
}
|
|
3435
|
-
}).get("/documents/:documentId/access", async (context) => {
|
|
3520
|
+
}).get("/documents/:documentId/access", documentParams, async (context) => {
|
|
3436
3521
|
try {
|
|
3437
3522
|
return context.json({ access: await service.access(context.get("actor").userId, context.req.param("documentId")) });
|
|
3438
3523
|
} catch (error) {
|
|
@@ -3440,7 +3525,7 @@ function createDocumentRoutes(service, rateLimit) {
|
|
|
3440
3525
|
if (response) return response;
|
|
3441
3526
|
throw error;
|
|
3442
3527
|
}
|
|
3443
|
-
}).get("/documents/:documentId", async (context) => {
|
|
3528
|
+
}).get("/documents/:documentId", documentParams, async (context) => {
|
|
3444
3529
|
try {
|
|
3445
3530
|
return context.json({ document: await service.download(context.get("actor").userId, context.req.param("documentId")) });
|
|
3446
3531
|
} catch (error) {
|
|
@@ -3448,10 +3533,10 @@ function createDocumentRoutes(service, rateLimit) {
|
|
|
3448
3533
|
if (response) return response;
|
|
3449
3534
|
throw error;
|
|
3450
3535
|
}
|
|
3451
|
-
}).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 () => {
|
|
3536
|
+
}).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 () => {
|
|
3452
3537
|
await service.commitImageUploads(context.get("actor").userId, context.req.param("documentId"), context.req.valid("json").uploads);
|
|
3453
3538
|
return context.body(null, 204);
|
|
3454
|
-
})).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) => {
|
|
3539
|
+
})).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) => {
|
|
3455
3540
|
try {
|
|
3456
3541
|
const document = await service.commitUpload(context.get("actor").userId, context.req.param("uploadId"), context.req.valid("json"));
|
|
3457
3542
|
return context.json({ document });
|
|
@@ -5033,6 +5118,18 @@ function createSharingPolicy(database, options) {
|
|
|
5033
5118
|
//#endregion
|
|
5034
5119
|
//#region src/server/sharing/capabilities/service.ts
|
|
5035
5120
|
const SHARE_SECRET_BYTES = 24;
|
|
5121
|
+
/** An account ID as the user table keys it; other IDs in `createdBy` name no account. */
|
|
5122
|
+
const accountIdSchema = v.pipe(v.string(), v.uuid());
|
|
5123
|
+
/**
|
|
5124
|
+
* Whether any of these people is banned, for a ban that has not run out. A link stops working
|
|
5125
|
+
* while whoever made it, or made its document, is banned, so what a banned person put up is no
|
|
5126
|
+
* longer public. The IDs are matched as the user table keys them, so the lookup uses its index.
|
|
5127
|
+
*/
|
|
5128
|
+
async function anyBanned(database, userIds) {
|
|
5129
|
+
const accounts = userIds.filter((id) => v.is(accountIdSchema, id));
|
|
5130
|
+
if (accounts.length === 0) return false;
|
|
5131
|
+
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;
|
|
5132
|
+
}
|
|
5036
5133
|
/**
|
|
5037
5134
|
* The revision a snapshot pins: the document's current one, or one of its own revisions. Anything
|
|
5038
5135
|
* else, as a document with no revision yet, cannot be shared as a snapshot.
|
|
@@ -5143,9 +5240,11 @@ function createCapabilityService(database, options) {
|
|
|
5143
5240
|
"documentShare.secretHash",
|
|
5144
5241
|
"documentShare.roomEpoch",
|
|
5145
5242
|
"documentShare.expiresAt",
|
|
5146
|
-
"documentShare.revisionId"
|
|
5243
|
+
"documentShare.revisionId",
|
|
5244
|
+
"documentShare.createdBy as linkMaker",
|
|
5245
|
+
"document.createdBy as documentMaker"
|
|
5147
5246
|
]).where("documentShare.id", "=", shareId).where("documentShare.revokedAt", "is", null).where("document.deletedAt", "is", null).executeTakeFirst();
|
|
5148
|
-
if (!row || !capabilityHashMatches(row.secretHash, input.secret) || row.expiresAt && new Date(row.expiresAt).getTime() <= Date.now()) throw new DocumentShareInvalidError();
|
|
5247
|
+
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();
|
|
5149
5248
|
if (!actor && options.policy) {
|
|
5150
5249
|
const document = await database.selectFrom("document").select("workspaceId").where("id", "=", row.documentId).executeTakeFirstOrThrow();
|
|
5151
5250
|
const featureKey = row.permission === "edit" ? CLOUD_FEATURE_KEYS.guestEdit : CLOUD_FEATURE_KEYS.guestView;
|
|
@@ -5194,7 +5293,7 @@ function createGrantService(database) {
|
|
|
5194
5293
|
},
|
|
5195
5294
|
async putGrant(userId, documentId, targetUserId, input) {
|
|
5196
5295
|
await requireSharingAccess(database, userId, documentId);
|
|
5197
|
-
|
|
5296
|
+
const row = await database.insertInto("documentGrant").values({
|
|
5198
5297
|
id: crypto.randomUUID(),
|
|
5199
5298
|
documentId,
|
|
5200
5299
|
userId: targetUserId,
|
|
@@ -5204,9 +5303,8 @@ function createGrantService(database) {
|
|
|
5204
5303
|
}).onConflict((conflict) => conflict.columns(["documentId", "userId"]).doUpdateSet({
|
|
5205
5304
|
permission: input.permission,
|
|
5206
5305
|
createdBy: userId,
|
|
5207
|
-
revokedAt: null,
|
|
5208
5306
|
updatedAt: /* @__PURE__ */ new Date()
|
|
5209
|
-
})).returning([
|
|
5307
|
+
}).where("documentGrant.revokedAt", "is", null)).returning([
|
|
5210
5308
|
"id",
|
|
5211
5309
|
"documentId",
|
|
5212
5310
|
"userId",
|
|
@@ -5214,7 +5312,9 @@ function createGrantService(database) {
|
|
|
5214
5312
|
"createdBy",
|
|
5215
5313
|
"createdAt",
|
|
5216
5314
|
"updatedAt"
|
|
5217
|
-
]).
|
|
5315
|
+
]).executeTakeFirst();
|
|
5316
|
+
if (!row) throw new DocumentNotFoundError();
|
|
5317
|
+
return grantContract(row);
|
|
5218
5318
|
},
|
|
5219
5319
|
/** Revoking access advances the collaboration epoch, so tickets and room keys issued before stop working. */
|
|
5220
5320
|
async revokeGrant(userId, documentId, targetUserId) {
|
|
@@ -5432,6 +5532,10 @@ function createWorkspaceMemberService(database, options) {
|
|
|
5432
5532
|
return {
|
|
5433
5533
|
invitation: invitationContract({
|
|
5434
5534
|
...await database.transaction().execute(async (transaction) => {
|
|
5535
|
+
await spendInvitationBudget(transaction, {
|
|
5536
|
+
senderId: userId,
|
|
5537
|
+
email: input.email
|
|
5538
|
+
});
|
|
5435
5539
|
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();
|
|
5436
5540
|
const inserted = await transaction.insertInto("workspaceInvitation").values({
|
|
5437
5541
|
id,
|
|
@@ -5618,6 +5722,7 @@ function sharingDomainError(context, error) {
|
|
|
5618
5722
|
if (error instanceof DocumentShareKindError) return context.json({ error: { code: "invalid_request" } }, 400);
|
|
5619
5723
|
if (error instanceof DocumentShareSignInRequiredError) return context.json({ error: { code: "unauthorized" } }, 401);
|
|
5620
5724
|
if (error instanceof InvitationDeliveryError) return context.json({ error: { code: "invitation_delivery_failed" } }, 502);
|
|
5725
|
+
if (error instanceof InvitationLimitError) return context.json({ error: { code: "rate_limited" } }, 429);
|
|
5621
5726
|
if (error instanceof DocumentForbiddenError) return context.json({ error: { code: "forbidden" } }, 403);
|
|
5622
5727
|
return null;
|
|
5623
5728
|
}
|
|
@@ -5642,13 +5747,13 @@ async function shareActor(request, resolveSession) {
|
|
|
5642
5747
|
//#endregion
|
|
5643
5748
|
//#region src/server/sharing/document-routes.ts
|
|
5644
5749
|
function createPublicDocumentRoutes(sharing, documents, resolveSession) {
|
|
5645
|
-
return new Hono().post("/shares/:shareId/document", validatedJSON(parseResolveDocumentShare), (context) => sharingRoute(context, async () => {
|
|
5750
|
+
return new Hono().post("/shares/:shareId/document", shareParams, validatedJSON(parseResolveDocumentShare), (context) => sharingRoute(context, async () => {
|
|
5646
5751
|
const resolution = await sharing.resolveShare(context.req.param("shareId"), context.req.valid("json"), await shareActor(context.req.raw, resolveSession));
|
|
5647
5752
|
return context.json({
|
|
5648
5753
|
resolution,
|
|
5649
5754
|
document: await documents.downloadShared(resolution.documentId, resolution.revisionId)
|
|
5650
5755
|
});
|
|
5651
|
-
})).post("/shares/:shareId/images", validatedJSON(parseRequestSharedImageLinks), (context) => sharingRoute(context, async () => {
|
|
5756
|
+
})).post("/shares/:shareId/images", shareParams, validatedJSON(parseRequestSharedImageLinks), (context) => sharingRoute(context, async () => {
|
|
5652
5757
|
const { checksums, ...share } = context.req.valid("json");
|
|
5653
5758
|
const resolution = await sharing.resolveShare(context.req.param("shareId"), share, await shareActor(context.req.raw, resolveSession));
|
|
5654
5759
|
return context.json(await documents.imageLinksShared(resolution.documentId, checksums));
|
|
@@ -5713,6 +5818,10 @@ function createInvitationService(database, options) {
|
|
|
5713
5818
|
acceptanceURL
|
|
5714
5819
|
} : null;
|
|
5715
5820
|
const invitation = invitationContract$1(await database.transaction().execute(async (transaction) => {
|
|
5821
|
+
await spendInvitationBudget(transaction, {
|
|
5822
|
+
senderId: userId,
|
|
5823
|
+
email: input.email
|
|
5824
|
+
});
|
|
5716
5825
|
const inserted = await transaction.insertInto("documentInvitation").values({
|
|
5717
5826
|
id,
|
|
5718
5827
|
documentId,
|
|
@@ -5817,20 +5926,20 @@ function createInvitationService(database, options) {
|
|
|
5817
5926
|
//#region src/server/sharing/routes.ts
|
|
5818
5927
|
function createDocumentSharingRoutes(service, rateLimit) {
|
|
5819
5928
|
const router = new Hono();
|
|
5820
|
-
if (rateLimit) router.use("/documents/:documentId/invitations",
|
|
5821
|
-
return router.
|
|
5929
|
+
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"));
|
|
5930
|
+
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 () => {
|
|
5822
5931
|
await service.revokeShare(context.get("actor").userId, context.req.param("documentId"), context.req.param("shareId"));
|
|
5823
5932
|
return context.body(null, 204);
|
|
5824
|
-
})).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 () => {
|
|
5933
|
+
})).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 () => {
|
|
5825
5934
|
await service.revokeGrant(context.get("actor").userId, context.req.param("documentId"), context.req.param("userId"));
|
|
5826
5935
|
return context.body(null, 204);
|
|
5827
|
-
})).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 () => {
|
|
5936
|
+
})).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 () => {
|
|
5828
5937
|
await service.revokeInvitation(context.get("actor").userId, context.req.param("documentId"), context.req.param("invitationId"));
|
|
5829
5938
|
return context.body(null, 204);
|
|
5830
5939
|
}));
|
|
5831
5940
|
}
|
|
5832
5941
|
function createPublicSharingRoutes(service, resolveSession) {
|
|
5833
|
-
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)) })));
|
|
5942
|
+
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)) })));
|
|
5834
5943
|
}
|
|
5835
5944
|
//#endregion
|
|
5836
5945
|
//#region src/server/sharing/service.ts
|
|
@@ -5839,15 +5948,6 @@ function createDocumentSharingService(database, options = {}) {
|
|
|
5839
5948
|
const grants = createGrantService(database);
|
|
5840
5949
|
const invitations = createInvitationService(database, options);
|
|
5841
5950
|
return {
|
|
5842
|
-
async lookupUser(userId, documentId, input) {
|
|
5843
|
-
await requireSharingAccess(database, userId, documentId);
|
|
5844
|
-
return await database.selectFrom("user").select([
|
|
5845
|
-
"id",
|
|
5846
|
-
"name",
|
|
5847
|
-
"email",
|
|
5848
|
-
"image"
|
|
5849
|
-
]).where((expression) => expression(expression.fn("lower", [expression.ref("email")]), "=", input.email)).executeTakeFirst() ?? null;
|
|
5850
|
-
},
|
|
5851
5951
|
async userProfile(userId, documentId, profileUserId) {
|
|
5852
5952
|
await requireSharingAccess(database, userId, documentId);
|
|
5853
5953
|
if (!await database.selectFrom("document").select("document.id").where("document.id", "=", documentId).where((expression) => expression.or([
|
|
@@ -5877,8 +5977,8 @@ function notFound(context, error) {
|
|
|
5877
5977
|
}
|
|
5878
5978
|
function createCollaborationRoutes(service, rateLimit) {
|
|
5879
5979
|
const router = new Hono();
|
|
5880
|
-
if (rateLimit) router.use("/documents/:documentId/collaboration-ticket",
|
|
5881
|
-
return router.post("/documents/:documentId/collaboration-ticket", async (context) => {
|
|
5980
|
+
if (rateLimit) router.use("/documents/:documentId/collaboration-ticket", createResourceRateLimiter(rateLimit.database, rateLimit.secret, CLOUD_RATE_LIMITS.collaborationTicket, (context) => context.req.param("documentId") ?? "unknown-document"));
|
|
5981
|
+
return router.post("/documents/:documentId/collaboration-ticket", documentParams, async (context) => {
|
|
5882
5982
|
try {
|
|
5883
5983
|
return context.json({ ticket: await service.issueUserTicket(context.get("actor"), context.req.param("documentId")) });
|
|
5884
5984
|
} catch (error) {
|
|
@@ -5889,7 +5989,7 @@ function createCollaborationRoutes(service, rateLimit) {
|
|
|
5889
5989
|
});
|
|
5890
5990
|
}
|
|
5891
5991
|
function createPublicCollaborationRoutes(service, resolveSession) {
|
|
5892
|
-
return new Hono().post("/shares/:shareId/collaboration-ticket", validatedJSON(parseResolveDocumentShare), async (context) => {
|
|
5992
|
+
return new Hono().post("/shares/:shareId/collaboration-ticket", shareParams, validatedJSON(parseResolveDocumentShare), async (context) => {
|
|
5893
5993
|
try {
|
|
5894
5994
|
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) });
|
|
5895
5995
|
} catch (error) {
|
|
@@ -6189,6 +6289,17 @@ function commenterThreadWrites(threads, incoming, author, now = (/* @__PURE__ */
|
|
|
6189
6289
|
}
|
|
6190
6290
|
//#endregion
|
|
6191
6291
|
//#region src/server/collaboration/relay/hub.ts
|
|
6292
|
+
/** Whether `update` adds nothing and deletes only content `document` already holds. */
|
|
6293
|
+
function deletesOnlyKnown(document, update) {
|
|
6294
|
+
const { from, to } = Y.parseUpdateMetaV2(update);
|
|
6295
|
+
if (![...to].every(([client, clock]) => from.get(client) === clock)) return false;
|
|
6296
|
+
const { ds } = Y.decodeUpdateV2(update);
|
|
6297
|
+
for (const [client, deletions] of ds.clients) {
|
|
6298
|
+
const held = Y.getState(document.store, client);
|
|
6299
|
+
if (deletions.some((deletion) => deletion.clock + deletion.len > held)) return false;
|
|
6300
|
+
}
|
|
6301
|
+
return true;
|
|
6302
|
+
}
|
|
6192
6303
|
/** Messages a viewer may send; their document writes never leave the relay. */
|
|
6193
6304
|
const VIEWER_ACTIONS = /* @__PURE__ */ new Set([COLLAB_ACTIONS.syncStep1, COLLAB_ACTIONS.awareness]);
|
|
6194
6305
|
/** A commenter may also send its comment threads, which the relay writes into the room itself. */
|
|
@@ -6210,6 +6321,7 @@ function createCollaborationRelay(options) {
|
|
|
6210
6321
|
/** Set by `close()`: a failed save then drops the room instead of retrying. */
|
|
6211
6322
|
let shuttingDown = false;
|
|
6212
6323
|
const persistDelayMs = options.persistDelayMs ?? 2e3;
|
|
6324
|
+
const maximumRoomBytes = options.maximumRoomBytes ?? 268435456;
|
|
6213
6325
|
const persistRetryMs = options.persistRetryMs ?? 3e4;
|
|
6214
6326
|
const authTimeoutMs = options.authTimeoutMs ?? 1e4;
|
|
6215
6327
|
const report = options.onError ?? ((message, error) => console.error(`[Cloud] ${message}`, error));
|
|
@@ -6241,8 +6353,13 @@ function createCollaborationRelay(options) {
|
|
|
6241
6353
|
identity,
|
|
6242
6354
|
document,
|
|
6243
6355
|
peers: /* @__PURE__ */ new Map(),
|
|
6244
|
-
persistTimer: null
|
|
6356
|
+
persistTimer: null,
|
|
6357
|
+
bytes: state?.byteLength ?? 0,
|
|
6358
|
+
deletedSinceMeasure: false
|
|
6245
6359
|
};
|
|
6360
|
+
document.on("afterTransaction", (transaction) => {
|
|
6361
|
+
if (transaction.deleteSet.clients.size > 0) room.deletedSinceMeasure = true;
|
|
6362
|
+
});
|
|
6246
6363
|
document.on("update", () => schedulePersist(room));
|
|
6247
6364
|
rooms.set(room.id, room);
|
|
6248
6365
|
return room;
|
|
@@ -6269,6 +6386,15 @@ function createCollaborationRelay(options) {
|
|
|
6269
6386
|
function schedulePersist(room) {
|
|
6270
6387
|
room.persistTimer ??= setTimeout(() => void persist(room), persistDelayMs);
|
|
6271
6388
|
}
|
|
6389
|
+
/** Whether the update keeps the room within its size, measuring again after a delete. */
|
|
6390
|
+
function fits(room, update) {
|
|
6391
|
+
if (deletesOnlyKnown(room.document, update)) return true;
|
|
6392
|
+
if (room.bytes + update.byteLength <= maximumRoomBytes) return true;
|
|
6393
|
+
if (!room.deletedSinceMeasure) return false;
|
|
6394
|
+
room.bytes = Y.encodeStateAsUpdateV2(room.document).byteLength;
|
|
6395
|
+
room.deletedSinceMeasure = false;
|
|
6396
|
+
return room.bytes + update.byteLength <= maximumRoomBytes;
|
|
6397
|
+
}
|
|
6272
6398
|
/**
|
|
6273
6399
|
* Applies a peer's V2 update to the room, inflated first for a sync reply. Rooms are saved as
|
|
6274
6400
|
* V1 updates; only what peers exchange is V2.
|
|
@@ -6276,14 +6402,15 @@ function createCollaborationRelay(options) {
|
|
|
6276
6402
|
function applyToRoom(room, peer, namespace, payload) {
|
|
6277
6403
|
try {
|
|
6278
6404
|
const update = decodeRoomUpdate(payload, {
|
|
6279
|
-
limit:
|
|
6405
|
+
limit: maximumRoomBytes,
|
|
6280
6406
|
compressed: namespace === COLLAB_ACTIONS.syncReply
|
|
6281
6407
|
});
|
|
6282
|
-
if (!update) {
|
|
6408
|
+
if (!update || !fits(room, update)) {
|
|
6283
6409
|
peer.socket.close(RELAY_CLOSE.messageTooLarge, "Collaboration update is too large");
|
|
6284
6410
|
return false;
|
|
6285
6411
|
}
|
|
6286
6412
|
Y.applyUpdateV2(room.document, update, peer.id);
|
|
6413
|
+
room.bytes += update.byteLength;
|
|
6287
6414
|
return true;
|
|
6288
6415
|
} catch {
|
|
6289
6416
|
peer.socket.close(RELAY_CLOSE.protocol, "Malformed document update");
|
|
@@ -6627,7 +6754,7 @@ async function answer(context, run) {
|
|
|
6627
6754
|
}
|
|
6628
6755
|
/** A document's version history: listing, naming, opening, restoring, and duplicating versions. */
|
|
6629
6756
|
function createDocumentVersionRoutes(service) {
|
|
6630
|
-
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)));
|
|
6757
|
+
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)));
|
|
6631
6758
|
}
|
|
6632
6759
|
//#endregion
|
|
6633
6760
|
//#region src/server/documents/versions/service.ts
|
|
@@ -7052,7 +7179,7 @@ function required(service) {
|
|
|
7052
7179
|
* service every route answers 404.
|
|
7053
7180
|
*/
|
|
7054
7181
|
function createPublicProfileSettingsRoutes(service) {
|
|
7055
|
-
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) })));
|
|
7182
|
+
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) })));
|
|
7056
7183
|
}
|
|
7057
7184
|
/** What anyone may read without signing in: profiles and the documents they list. */
|
|
7058
7185
|
function createPublicProfileRoutes(service, documents) {
|
|
@@ -7061,7 +7188,7 @@ function createPublicProfileRoutes(service, documents) {
|
|
|
7061
7188
|
const profile = isPublicProfileHandle(handle) ? await required(service).publicProfile(handle) : null;
|
|
7062
7189
|
if (!profile) throw new DocumentNotFoundError();
|
|
7063
7190
|
return context.json({ profile });
|
|
7064
|
-
})).post("/documents/:documentId/document", (context) => profileRoute(context, async () => {
|
|
7191
|
+
})).post("/documents/:documentId/document", documentParams, (context) => profileRoute(context, async () => {
|
|
7065
7192
|
const documentId = context.req.param("documentId");
|
|
7066
7193
|
await required(service).requirePublicDocument(documentId);
|
|
7067
7194
|
return context.json({ document: await documents.downloadShared(documentId) });
|
|
@@ -7143,6 +7270,7 @@ async function memberRoute(context, action) {
|
|
|
7143
7270
|
return context.json({ error: { code } }, 409);
|
|
7144
7271
|
}
|
|
7145
7272
|
if (error instanceof WorkspaceAlreadyMemberError) return context.json({ error: { code: "already_member" } }, 409);
|
|
7273
|
+
if (error instanceof InvitationLimitError) return context.json({ error: { code: "rate_limited" } }, 429);
|
|
7146
7274
|
throw error;
|
|
7147
7275
|
}
|
|
7148
7276
|
}
|
|
@@ -7150,8 +7278,8 @@ function createWorkspaceRoutes(service, members, rateLimit) {
|
|
|
7150
7278
|
const router = new Hono();
|
|
7151
7279
|
if (rateLimit) {
|
|
7152
7280
|
router.use("/", createRouteRateLimiter(rateLimit.database, rateLimit.secret, CLOUD_RATE_LIMITS.workspaceCreation, (context) => context.req.method !== "POST"));
|
|
7153
|
-
router.use("/:workspaceId/invitations/:invitationId/resend",
|
|
7154
|
-
router.use("/:workspaceId/invitations",
|
|
7281
|
+
router.use("/:workspaceId/invitations/:invitationId/resend", createResourceRateLimiter(rateLimit.database, rateLimit.secret, CLOUD_RATE_LIMITS.invitationMutation, (context) => context.req.param("workspaceId") ?? "unknown", () => false));
|
|
7282
|
+
router.use("/:workspaceId/invitations", createResourceRateLimiter(rateLimit.database, rateLimit.secret, CLOUD_RATE_LIMITS.invitationMutation, (context) => context.req.param("workspaceId") ?? "unknown", (context) => context.req.method !== "POST"));
|
|
7155
7283
|
}
|
|
7156
7284
|
return router.get("/", async (context) => {
|
|
7157
7285
|
const workspaces = await service.list(context.get("actor").userId);
|
|
@@ -7164,20 +7292,20 @@ function createWorkspaceRoutes(service, members, rateLimit) {
|
|
|
7164
7292
|
if (error instanceof WorkspaceSlugConflictError) return context.json({ error: { code: "slug_conflict" } }, 409);
|
|
7165
7293
|
throw error;
|
|
7166
7294
|
}
|
|
7167
|
-
}).get("/:workspaceId", async (context) => {
|
|
7295
|
+
}).get("/:workspaceId", workspaceParams, async (context) => {
|
|
7168
7296
|
const workspace = await service.get(context.get("actor").userId, context.req.param("workspaceId"));
|
|
7169
7297
|
if (!workspace) return context.json({ error: { code: "not_found" } }, 404);
|
|
7170
7298
|
return context.json({ workspace });
|
|
7171
|
-
}).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 () => {
|
|
7299
|
+
}).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 () => {
|
|
7172
7300
|
await members.delete(context.get("actor").userId, context.req.param("workspaceId"));
|
|
7173
7301
|
return context.body(null, 204);
|
|
7174
|
-
})).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 () => {
|
|
7302
|
+
})).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 () => {
|
|
7175
7303
|
await members.revokeInvitation(context.get("actor").userId, context.req.param("workspaceId"), context.req.param("invitationId"));
|
|
7176
7304
|
return context.body(null, 204);
|
|
7177
|
-
})).patch("/:workspaceId/members/:userId", validatedJSON(parseUpdateWorkspaceMember), (context) => memberRoute(context, async () => {
|
|
7305
|
+
})).patch("/:workspaceId/members/:userId", workspaceMemberParams, validatedJSON(parseUpdateWorkspaceMember), (context) => memberRoute(context, async () => {
|
|
7178
7306
|
await members.updateRole(context.get("actor").userId, context.req.param("workspaceId"), context.req.param("userId"), context.req.valid("json").role);
|
|
7179
7307
|
return context.body(null, 204);
|
|
7180
|
-
})).delete("/:workspaceId/members/:userId", (context) => memberRoute(context, async () => {
|
|
7308
|
+
})).delete("/:workspaceId/members/:userId", workspaceMemberParams, (context) => memberRoute(context, async () => {
|
|
7181
7309
|
await members.remove(context.get("actor").userId, context.req.param("workspaceId"), context.req.param("userId"));
|
|
7182
7310
|
return context.body(null, 204);
|
|
7183
7311
|
}));
|
|
@@ -7188,9 +7316,14 @@ function createPublicCloudAPIRouter(services) {
|
|
|
7188
7316
|
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));
|
|
7189
7317
|
}
|
|
7190
7318
|
function createCloudAPIRouter(services) {
|
|
7191
|
-
return new Hono().route("/", createPublicProfileSettingsRoutes(services.profiles)).route("/public", createPublicCloudAPIRouter(services)).get("/workspaces/:workspaceId/entitlements", async (context) => {
|
|
7319
|
+
return new Hono().route("/", createPublicProfileSettingsRoutes(services.profiles)).route("/public", createPublicCloudAPIRouter(services)).get("/workspaces/:workspaceId/entitlements", workspaceParams, async (context) => {
|
|
7192
7320
|
if (!services.entitlements) return context.json({ error: { code: "not_found" } }, 404);
|
|
7193
|
-
|
|
7321
|
+
try {
|
|
7322
|
+
return context.json({ entitlements: await services.entitlements.workspace(context.get("actor").userId, context.req.valid("param").workspaceId) });
|
|
7323
|
+
} catch (error) {
|
|
7324
|
+
if (error instanceof DocumentNotFoundError) return context.json({ error: { code: "not_found" } }, 404);
|
|
7325
|
+
throw error;
|
|
7326
|
+
}
|
|
7194
7327
|
}).get("/session", (context) => context.json({ user: context.get("actor") })).route("/", createAIRoutes(services.aiTokens, services.database && services.rateLimitSecret ? {
|
|
7195
7328
|
database: services.database,
|
|
7196
7329
|
secret: services.rateLimitSecret
|
|
@@ -7581,7 +7714,10 @@ function createCloudApp(services) {
|
|
|
7581
7714
|
resolveSession
|
|
7582
7715
|
});
|
|
7583
7716
|
const internalAPI = services.config.internalServiceToken ? createInternalRoutes(createInternalService(services.database), services.config.internalServiceToken) : new Hono();
|
|
7584
|
-
return new Hono().use(CLOUD_DISCOVERY_PATH, cloudCORS).use("/api/*", cloudCORS).use("
|
|
7717
|
+
return new Hono().use(CLOUD_DISCOVERY_PATH, cloudCORS).use("/api/*", cloudCORS).use("/api/*", bodyLimit({
|
|
7718
|
+
maxSize: CLOUD_API_MAX_BODY_BYTES,
|
|
7719
|
+
onError: (context) => context.json({ error: { code: "invalid_request" } }, 413)
|
|
7720
|
+
})).use("*", async (context, next) => {
|
|
7585
7721
|
await next();
|
|
7586
7722
|
if (shouldPreventIndexing(context.req.path, services.config.indexingPolicy)) context.header("X-Robots-Tag", "noindex, nofollow, noarchive");
|
|
7587
7723
|
}).get("/robots.txt", (context) => {
|
|
@@ -8304,9 +8440,17 @@ function startTransactionalEmailWorker(email, options) {
|
|
|
8304
8440
|
}
|
|
8305
8441
|
//#endregion
|
|
8306
8442
|
//#region src/runtime/postgres/database.ts
|
|
8443
|
+
/**
|
|
8444
|
+
* How long a query serving a request may run before PostgreSQL cancels it. Rate limits and
|
|
8445
|
+
* sessions live in PostgreSQL, so one stuck query would otherwise hold its connection, and every
|
|
8446
|
+
* request waiting for one, indefinitely.
|
|
8447
|
+
*/
|
|
8448
|
+
const POSTGRES_STATEMENT_TIMEOUT_MS = 3e4;
|
|
8307
8449
|
function createPostgresCloudDatabase(options) {
|
|
8450
|
+
const statementTimeoutMs = options.statementTimeoutMs === void 0 ? POSTGRES_STATEMENT_TIMEOUT_MS : options.statementTimeoutMs;
|
|
8308
8451
|
return createCloudDatabase({ dialect: new PostgresDialect({ pool: new Pool({
|
|
8309
8452
|
...options.pool,
|
|
8453
|
+
...statementTimeoutMs === null ? {} : { statement_timeout: statementTimeoutMs },
|
|
8310
8454
|
connectionString: options.connectionString
|
|
8311
8455
|
}) }) });
|
|
8312
8456
|
}
|
|
@@ -8321,16 +8465,24 @@ async function loadNodeCloudServerConfig(environment) {
|
|
|
8321
8465
|
//#region src/runtime/node/bootstrap.ts
|
|
8322
8466
|
async function createMigratedNodeCloudDatabase(environment) {
|
|
8323
8467
|
const config = await loadNodeCloudServerConfig(environment);
|
|
8324
|
-
const
|
|
8325
|
-
|
|
8326
|
-
|
|
8327
|
-
run: auth.migrate,
|
|
8328
|
-
schemaVersion: auth.schemaVersion
|
|
8468
|
+
const migrating = createPostgresCloudDatabase({
|
|
8469
|
+
connectionString: config.databaseURL,
|
|
8470
|
+
statementTimeoutMs: null
|
|
8329
8471
|
});
|
|
8472
|
+
try {
|
|
8473
|
+
const auth = createBetterAuthAdapter(config, migrating);
|
|
8474
|
+
await migrateCloudDatabase(migrating, {
|
|
8475
|
+
run: auth.migrate,
|
|
8476
|
+
schemaVersion: auth.schemaVersion
|
|
8477
|
+
});
|
|
8478
|
+
} finally {
|
|
8479
|
+
await migrating.destroy();
|
|
8480
|
+
}
|
|
8481
|
+
const database = createPostgresCloudDatabase({ connectionString: config.databaseURL });
|
|
8330
8482
|
return {
|
|
8331
8483
|
config,
|
|
8332
8484
|
database,
|
|
8333
|
-
auth
|
|
8485
|
+
auth: createBetterAuthAdapter(config, database)
|
|
8334
8486
|
};
|
|
8335
8487
|
}
|
|
8336
8488
|
//#endregion
|
|
@@ -8657,7 +8809,14 @@ const EDITOR_PAGE = "/index.html";
|
|
|
8657
8809
|
const PAGE_HEADERS = {
|
|
8658
8810
|
"Content-Type": "text/html; charset=utf-8",
|
|
8659
8811
|
"Cache-Control": "no-cache",
|
|
8660
|
-
"Content-Security-Policy":
|
|
8812
|
+
"Content-Security-Policy": [
|
|
8813
|
+
"script-src 'self' 'unsafe-eval' 'wasm-unsafe-eval' blob: https://challenges.cloudflare.com",
|
|
8814
|
+
"worker-src 'self' blob:",
|
|
8815
|
+
"object-src 'none'",
|
|
8816
|
+
"base-uri 'self'",
|
|
8817
|
+
"frame-ancestors 'none'"
|
|
8818
|
+
].join("; "),
|
|
8819
|
+
"Strict-Transport-Security": "max-age=31536000",
|
|
8661
8820
|
"Referrer-Policy": "no-referrer",
|
|
8662
8821
|
"X-Content-Type-Options": "nosniff"
|
|
8663
8822
|
};
|
|
@@ -8779,7 +8938,11 @@ async function startNodeCloudServer(options = {}) {
|
|
|
8779
8938
|
const { email, invitationOutbox, transport: emailTransport } = createNodeTransactionalEmailRuntime(config, database);
|
|
8780
8939
|
const { auth, enrollment } = createCloudAuthenticationRuntime(config, database, email);
|
|
8781
8940
|
const policy = createConfiguredCloudPolicy(config, database);
|
|
8782
|
-
const
|
|
8941
|
+
const cleanupDatabase = config.cleanupEnabled ? createPostgresCloudDatabase({
|
|
8942
|
+
connectionString: config.databaseURL,
|
|
8943
|
+
statementTimeoutMs: null
|
|
8944
|
+
}) : void 0;
|
|
8945
|
+
const cleanup = cleanupDatabase ? startCleanupWorker(createCleanupServices(config, cleanupDatabase, objects, policy), {
|
|
8783
8946
|
...cleanupPassOptions(config),
|
|
8784
8947
|
intervalMs: config.cleanupIntervalMs,
|
|
8785
8948
|
onError: (error) => console.error("[Cloud] Cleanup worker failed:", error)
|
|
@@ -8825,6 +8988,7 @@ async function startNodeCloudServer(options = {}) {
|
|
|
8825
8988
|
await relayListener.close();
|
|
8826
8989
|
await server.close();
|
|
8827
8990
|
await cleanup?.stop();
|
|
8991
|
+
await cleanupDatabase?.destroy();
|
|
8828
8992
|
await emailWorker?.stop();
|
|
8829
8993
|
await database.destroy();
|
|
8830
8994
|
}
|