-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.ts
More file actions
1492 lines (1379 loc) · 43.1 KB
/
server.ts
File metadata and controls
1492 lines (1379 loc) · 43.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import http, { type IncomingMessage } from "http";
import path from "node:path";
import { pathToFileURL } from "node:url";
import { config as loadEnv } from "dotenv";
import ShareDB from "sharedb";
import { WebSocketServer, WebSocket } from "ws";
import { createClient } from "redis";
// eslint-disable-next-line @typescript-eslint/no-require-imports
const WebSocketJSONStream = require("websocket-json-stream") as new (
ws: WebSocket,
) => unknown;
// eslint-disable-next-line @typescript-eslint/no-require-imports
const createShareDBRedisPubSub = require("sharedb-redis-pubsub") as (options: {
client: ReturnType<typeof createClient>;
observer?: ReturnType<typeof createClient>;
prefix?: string;
}) => unknown;
import { getFlags, isTrackingEnabledForSource } from "./lib/feature-flags";
import {
ensureDocumentAccess,
getDocumentOwnerOrganizationId,
} from "./lib/documents/repository";
import { verifyMcpShareDbAccessToken } from "./lib/sharedb/mcp-token";
import { verifyShareDbWsAccessToken } from "./lib/sharedb/ws-token";
import { resolveAuditHistoryAccess } from "./lib/operation-history/access";
import { generateInverseRawOp } from "./lib/operation-history/inverse-op";
import { createOperationHistory } from "./lib/operation-history/repository";
import type { OperationAttribution } from "./lib/operation-history/types";
// eslint-disable-next-line @typescript-eslint/no-require-imports
const createShareDBPostgres = require("sharedb-postgres") as (
options?: Record<string, unknown>,
) => unknown;
// eslint-disable-next-line @typescript-eslint/no-require-imports
const ShareDBError = require("sharedb/lib/error") as {
new (code: string, message?: string): Error & { code: string };
};
loadEnv({
path: path.resolve(process.cwd(), ".env.local"),
override: false,
quiet: true,
});
const sanitizeDatabaseUrl = (connectionString: string): string => {
try {
const parsed = new URL(connectionString);
parsed.searchParams.delete("sslmode");
parsed.searchParams.delete("sslrootcert");
parsed.searchParams.delete("uselibpqcompat");
return parsed.toString();
} catch {
return connectionString;
}
};
if (process.env.PGSSLROOTCERT?.trim().toLowerCase() === "system") {
// Some providers expose PGSSLROOTCERT=system, which breaks Node pg TLS.
delete process.env.PGSSLROOTCERT;
}
const shareDbDatabaseUrl =
process.env.SHAREDB_DATABASE_URL || process.env.DATABASE_URL;
if (!shareDbDatabaseUrl) {
throw new Error(
"Missing SHAREDB_DATABASE_URL/DATABASE_URL for ShareDB server.",
);
}
const SHAREDB_DATABASE_URL: string = sanitizeDatabaseUrl(shareDbDatabaseUrl);
const SHAREDB_REQUIRE_SSL = process.env.SHAREDB_REQUIRE_SSL !== "false";
const SHAREDB_SSL_REJECT_UNAUTHORIZED =
process.env.SHAREDB_SSL_REJECT_UNAUTHORIZED === "true";
const parsePositiveInt = (value: string | undefined, fallback: number) => {
if (!value) return fallback;
const parsed = Number.parseInt(value, 10);
return Number.isFinite(parsed) && parsed > 0 ? parsed : fallback;
};
const parseNonNegativeInt = (value: string | undefined, fallback: number) => {
if (!value) return fallback;
const parsed = Number.parseInt(value, 10);
return Number.isFinite(parsed) && parsed >= 0 ? parsed : fallback;
};
const parseBoolean = (value: string | undefined, fallback: boolean) => {
if (!value) return fallback;
const normalized = value.trim().toLowerCase();
if (normalized === "1" || normalized === "true") return true;
if (normalized === "0" || normalized === "false") return false;
return fallback;
};
const parseBoundedInt = (
value: string | undefined,
fallback: number,
min: number,
max: number,
) => {
if (!value) return fallback;
const parsed = Number.parseInt(value, 10);
if (!Number.isFinite(parsed)) return fallback;
if (parsed < min || parsed > max) return fallback;
return parsed;
};
const SHAREDB_PG_MAX_POOL_SIZE = parsePositiveInt(
process.env.SHAREDB_PG_MAX_POOL_SIZE,
10,
);
const SHAREDB_PG_CONNECTION_TIMEOUT_MS = parsePositiveInt(
process.env.SHAREDB_PG_CONNECTION_TIMEOUT_MS,
10000,
);
const SHAREDB_PG_IDLE_TIMEOUT_MS = parseNonNegativeInt(
process.env.SHAREDB_PG_IDLE_TIMEOUT_MS,
30000,
);
const SHAREDB_PG_MAX_LIFETIME_SECONDS = parseNonNegativeInt(
process.env.SHAREDB_PG_MAX_LIFETIME_SECONDS,
0,
);
const SHAREDB_PG_KEEP_ALIVE = parseBoolean(
process.env.SHAREDB_PG_KEEP_ALIVE,
true,
);
const SHAREDB_PG_KEEP_ALIVE_INITIAL_DELAY_MS = parseNonNegativeInt(
process.env.SHAREDB_PG_KEEP_ALIVE_INITIAL_DELAY_MS,
0,
);
const PORT = parseInt(
process.env.PORT || process.env.SHAREDB_PORT || "8080",
10,
);
const HOST = process.env.HOST || "0.0.0.0";
const SHAREDB_COLLECTION =
process.env.SHAREDB_COLLECTION?.trim() || "spreadsheets";
const SHAREDB_AUTH_DEBUG = process.env.SHAREDB_AUTH_DEBUG === "true";
const SHAREDB_REDIS_URL = process.env.SHAREDB_REDIS_URL?.trim() || null;
const SHAREDB_REDIS_PREFIX =
process.env.SHAREDB_REDIS_PREFIX?.trim() || "rnc:sharedb";
const SHAREDB_INSTANCE_ID =
process.env.SHAREDB_INSTANCE_ID?.trim() ||
process.env.RAILWAY_REPLICA_ID?.trim() ||
process.env.HOSTNAME?.trim() ||
"sharedb-instance";
const AUDIT_ACCESS_CACHE_TTL_MS = 5 * 60_000;
const DOC_ACCESS_CACHE_TTL_MS = parsePositiveInt(
process.env.SHAREDB_DOC_ACCESS_CACHE_TTL_MS,
45_000,
);
const POSTGRES_JSONB_MAX_BYTES = 268_435_455; // PostgreSQL hard limit for a single jsonb value
const DEFAULT_SHAREDB_DOC_MAX_BYTES = 300 * 1024 * 1024; // requested default
const SHAREDB_DOC_MAX_BYTES_REQUESTED = parseNonNegativeInt(
process.env.SHAREDB_DOC_MAX_BYTES,
DEFAULT_SHAREDB_DOC_MAX_BYTES,
);
const SHAREDB_DOC_JSONB_SAFETY_MARGIN_BYTES = parseNonNegativeInt(
process.env.SHAREDB_DOC_JSONB_SAFETY_MARGIN_BYTES,
8 * 1024 * 1024,
);
const SHAREDB_DOC_MAX_BYTES_CAP = Math.max(
1,
POSTGRES_JSONB_MAX_BYTES - SHAREDB_DOC_JSONB_SAFETY_MARGIN_BYTES,
);
const SHAREDB_DOC_MAX_BYTES = Math.min(
SHAREDB_DOC_MAX_BYTES_REQUESTED,
SHAREDB_DOC_MAX_BYTES_CAP,
);
const SHAREDB_OP_MAX_BYTES_REQUESTED = parseNonNegativeInt(
process.env.SHAREDB_OP_MAX_BYTES,
SHAREDB_DOC_MAX_BYTES_CAP,
);
const SHAREDB_OP_MAX_BYTES = Math.min(
SHAREDB_OP_MAX_BYTES_REQUESTED,
SHAREDB_DOC_MAX_BYTES_CAP,
);
const SHAREDB_WS_MAX_PAYLOAD_OVERHEAD_BYTES = parseNonNegativeInt(
process.env.SHAREDB_WS_MAX_PAYLOAD_OVERHEAD_BYTES,
1 * 1024 * 1024,
);
const SHAREDB_WS_MAX_PAYLOAD_CAP_BYTES =
SHAREDB_DOC_MAX_BYTES + SHAREDB_WS_MAX_PAYLOAD_OVERHEAD_BYTES;
const SHAREDB_WS_MAX_PAYLOAD_REQUESTED_BYTES = parseNonNegativeInt(
process.env.SHAREDB_WS_MAX_PAYLOAD_BYTES,
SHAREDB_WS_MAX_PAYLOAD_CAP_BYTES,
);
const SHAREDB_WS_MAX_PAYLOAD_BYTES = Math.min(
SHAREDB_WS_MAX_PAYLOAD_REQUESTED_BYTES,
SHAREDB_WS_MAX_PAYLOAD_CAP_BYTES,
);
const SHAREDB_WS_COMPRESSION_ENABLED = parseBoolean(
process.env.SHAREDB_WS_COMPRESSION_ENABLED,
true,
);
const SHAREDB_WS_COMPRESSION_THRESHOLD_BYTES = parseNonNegativeInt(
process.env.SHAREDB_WS_COMPRESSION_THRESHOLD_BYTES,
1024,
);
const SHAREDB_WS_COMPRESSION_CONCURRENCY_LIMIT = parsePositiveInt(
process.env.SHAREDB_WS_COMPRESSION_CONCURRENCY_LIMIT,
10,
);
const SHAREDB_WS_COMPRESSION_LEVEL = parseBoundedInt(
process.env.SHAREDB_WS_COMPRESSION_LEVEL,
3,
0,
9,
);
const SHAREDB_WS_COMPRESSION_NO_CONTEXT_TAKEOVER = parseBoolean(
process.env.SHAREDB_WS_COMPRESSION_NO_CONTEXT_TAKEOVER,
true,
);
const SHAREDB_WS_HEARTBEAT_INTERVAL_MS = parseNonNegativeInt(
process.env.SHAREDB_WS_HEARTBEAT_INTERVAL_MS,
30_000,
);
type AuthIdentity = {
userId: string;
email: string | null;
name: string | null;
};
type AuthFailureReason =
| "no_ws_token"
| "no_cookie"
| "invalid_token"
| "invalid_ws_token"
| "invalid_mcp_token"
| "timeout"
| "endpoint_failure";
type IdentityResolutionResult = {
identity: AuthIdentity | null;
failureReason: AuthFailureReason | null;
statusCode?: number;
};
type AgentAuditState = {
identity: AuthIdentity | null;
allowed: boolean;
isAdmin: boolean;
plan: "free" | "pro" | "max" | null;
};
type AgentAuthState = {
identity: AuthIdentity | null;
wsAccess: {
docId: string;
permission: DocumentPermission;
organizationId: string | null;
} | null;
mcpAccess: {
docId: string;
permission: DocumentPermission;
organizationId: string | null;
} | null;
failureReason: AuthFailureReason | null;
statusCode?: number;
resolvedAt: number;
};
type DocumentPermission = "view" | "edit";
type AgentDocAccessCacheEntry = {
canAccess: boolean;
permission: DocumentPermission;
expiresAt: number;
};
type ShareDBAuditSource = {
source?: unknown;
sourceType?: unknown;
actorType?: unknown;
actorId?: unknown;
userId?: unknown;
userName?: unknown;
userEmail?: unknown;
sessionId?: unknown;
threadId?: unknown;
runId?: unknown;
toolName?: unknown;
toolCallId?: unknown;
channel?: unknown;
origin?: unknown;
};
type ConnectContextLike = {
agent?: {
custom?: Record<string, unknown>;
};
req?: IncomingMessage;
};
type SubmitContextLike = {
agent?: {
custom?: Record<string, unknown>;
};
req?: IncomingMessage;
collection: string;
id: string;
op?: {
v?: unknown;
src?: unknown;
seq?: unknown;
op?: unknown;
};
snapshot?: {
v?: unknown;
data?: unknown;
} | null;
extra?: {
source?: unknown;
};
};
type ReadSnapshotLike = {
id?: unknown;
};
type HeartbeatWebSocket = WebSocket & {
isAlive?: boolean;
};
type ReadSnapshotsContextLike = {
agent?: {
custom?: Record<string, unknown>;
};
req?: IncomingMessage;
collection: string;
snapshots: ReadSnapshotLike[];
rejectSnapshotRead?: (snapshot: ReadSnapshotLike, error: Error) => void;
};
type QueryContextLike = {
agent?: {
custom?: Record<string, unknown>;
};
req?: IncomingMessage;
collection?: string;
index?: string;
query?: unknown;
};
const auditAccessCache = new Map<
string,
{ access: Omit<AgentAuditState, "identity">; expiresAt: number }
>();
const redactDatabaseUrl = (value: string) => {
try {
const parsed = new URL(value);
if (parsed.username) parsed.username = "***";
if (parsed.password) parsed.password = "***";
return parsed.toString();
} catch {
return value;
}
};
const redactRedisUrl = (value: string) => {
try {
const parsed = new URL(value);
if (parsed.username) parsed.username = "***";
if (parsed.password) parsed.password = "***";
return parsed.toString();
} catch {
return value;
}
};
const registerRedisLifecycleLogging = (
client: ReturnType<typeof createClient>,
role: "pub" | "sub",
) => {
const prefix = `[sharedb-redis][${SHAREDB_INSTANCE_ID}][${role}]`;
client.on("connect", () => {
console.log(`${prefix} connect`);
});
client.on("ready", () => {
console.log(`${prefix} ready`);
});
client.on("reconnecting", () => {
console.warn(`${prefix} reconnecting`);
});
client.on("end", () => {
console.warn(`${prefix} end`);
});
client.on("error", (error) => {
console.error(`${prefix} error`, error);
});
};
const getStringValue = (value: unknown): string | null => {
if (typeof value !== "string") {
return null;
}
const trimmed = value.trim();
return trimmed.length > 0 ? trimmed : null;
};
const getMcpTokenFromRequest = (req?: IncomingMessage): string | null => {
if (!req?.url) {
return null;
}
try {
const parsed = new URL(req.url, "http://localhost");
return getStringValue(parsed.searchParams.get("mcpToken"));
} catch {
return null;
}
};
const getWsTokenFromRequest = (req?: IncomingMessage): string | null => {
if (!req?.url) {
return null;
}
try {
const parsed = new URL(req.url, "http://localhost");
return getStringValue(parsed.searchParams.get("wsToken"));
} catch {
return null;
}
};
const logAuth = (
level: "debug" | "warn" | "error",
message: string,
payload?: Record<string, unknown>,
) => {
if (level === "debug" && !SHAREDB_AUTH_DEBUG) {
return;
}
const logger =
level === "warn"
? console.warn
: level === "error"
? console.error
: console.log;
logger("[sharedb-auth]", message, payload ?? {});
};
const resolveAuditAccessCached = async (
identity: AuthIdentity,
): Promise<Omit<AgentAuditState, "identity">> => {
const cacheKey = `${identity.userId}:${identity.email ?? ""}`;
const cached = auditAccessCache.get(cacheKey);
if (cached && cached.expiresAt >= Date.now()) {
return cached.access;
}
const access = await resolveAuditHistoryAccess({
userId: identity.userId,
email: identity.email,
});
const normalized = {
allowed: access.allowed,
isAdmin: access.isAdmin,
plan: access.plan,
};
auditAccessCache.set(cacheKey, {
access: normalized,
expiresAt: Date.now() + AUDIT_ACCESS_CACHE_TTL_MS,
});
return normalized;
};
const toNumber = (value: unknown): number | null => {
if (typeof value === "number" && Number.isFinite(value)) {
return value;
}
if (typeof value === "string" && value.trim() !== "") {
const parsed = Number(value);
if (Number.isFinite(parsed)) {
return parsed;
}
}
return null;
};
const toString = (value: unknown): string | null => {
if (typeof value !== "string") {
return null;
}
const trimmed = value.trim();
return trimmed.length > 0 ? trimmed : null;
};
const getAuditSourceType = (source: unknown): string | null => {
if (typeof source === "string") {
return source.trim().toLowerCase();
}
if (!source || typeof source !== "object") {
return null;
}
const metadata = source as ShareDBAuditSource;
const candidate = toString(metadata.sourceType) ?? toString(metadata.source);
return candidate ? candidate.toLowerCase() : null;
};
const isUserSource = (source: unknown): boolean => {
const normalized = getAuditSourceType(source);
if (!normalized) {
return true;
}
return normalized === "user";
};
const toSourceMetadata = (source: unknown): ShareDBAuditSource | null => {
if (!source || typeof source !== "object") {
return null;
}
return source as ShareDBAuditSource;
};
const getOrCreateAgentCustom = (
context:
| ConnectContextLike
| SubmitContextLike
| ReadSnapshotsContextLike
| QueryContextLike,
): Record<string, unknown> => {
if (!context.agent) {
return {};
}
if (!context.agent.custom) {
context.agent.custom = Object.create(null) as Record<string, unknown>;
}
return context.agent.custom;
};
const createUnauthorizedError = (message: string): Error => {
return new ShareDBError("ERR_UNAUTHORIZED", message);
};
const createForbiddenError = (message: string): Error => {
return new ShareDBError("ERR_FORBIDDEN", message);
};
const createDocumentSizeLimitError = (message: string): Error => {
return new ShareDBError("ERR_DOC_TOO_LARGE", message);
};
const createOperationSizeLimitError = (message: string): Error => {
return new ShareDBError("ERR_OP_TOO_LARGE", message);
};
const computeDocumentSizeBytes = (snapshotData: unknown): number | null => {
try {
return Buffer.byteLength(JSON.stringify(snapshotData ?? null), "utf8");
} catch {
return null;
}
};
const formatBytes = (value: number): string => {
if (!Number.isFinite(value) || value < 0) {
return "0 B";
}
const units = ["B", "KB", "MB", "GB"];
let size = value;
let unitIndex = 0;
while (size >= 1024 && unitIndex < units.length - 1) {
size /= 1024;
unitIndex += 1;
}
const precision = size >= 10 || unitIndex === 0 ? 0 : 1;
return `${size.toFixed(precision)} ${units[unitIndex]}`;
};
const toAgentAuthState = (
result: IdentityResolutionResult,
): AgentAuthState => ({
identity: result.identity,
wsAccess: null,
mcpAccess: null,
failureReason: result.failureReason,
statusCode: result.statusCode,
resolvedAt: Date.now(),
});
const ensureAgentAuthState = async (
context:
| ConnectContextLike
| SubmitContextLike
| ReadSnapshotsContextLike
| QueryContextLike,
): Promise<AgentAuthState> => {
const custom = getOrCreateAgentCustom(context);
const existing = (custom.__authState ?? null) as AgentAuthState | null;
if (existing) {
return existing;
}
const inFlight = (custom.__authStatePromise ??
null) as Promise<AgentAuthState> | null;
if (inFlight) {
return inFlight;
}
const promise = Promise.resolve()
.then(async () => {
const state = toAgentAuthState({
identity: null,
failureReason: "no_ws_token",
});
const wsToken = getWsTokenFromRequest(context.req);
if (wsToken) {
const access = await verifyShareDbWsAccessToken(wsToken);
if (access) {
const tokenOrgId = access.organizationId?.trim() || null;
if (tokenOrgId) {
const ownerOrgId = await getDocumentOwnerOrganizationId(
access.docId,
);
if (!ownerOrgId || ownerOrgId !== tokenOrgId) {
state.failureReason = "invalid_ws_token";
custom.__authState = state;
return state;
}
}
state.identity = {
userId: access.userId,
email: access.email ?? null,
name: access.name ?? null,
};
state.wsAccess = {
docId: access.docId,
permission: access.permission,
organizationId: tokenOrgId,
};
state.failureReason = null;
} else {
state.failureReason = "invalid_ws_token";
}
} else {
const mcpToken = getMcpTokenFromRequest(context.req);
if (mcpToken) {
const access = await verifyMcpShareDbAccessToken(mcpToken);
if (access) {
const tokenOrgId = access.organizationId?.trim() || null;
if (tokenOrgId) {
const ownerOrgId = await getDocumentOwnerOrganizationId(
access.docId,
);
if (!ownerOrgId || ownerOrgId !== tokenOrgId) {
state.failureReason = "invalid_mcp_token";
custom.__authState = state;
return state;
}
}
state.mcpAccess = {
docId: access.docId,
permission: access.permission,
organizationId: tokenOrgId,
};
state.failureReason = null;
} else {
state.failureReason = "invalid_mcp_token";
}
}
}
custom.__authState = state;
if (!state.identity && !state.mcpAccess) {
logAuth("warn", "identity_unresolved", {
reason: state.failureReason,
statusCode: state.statusCode,
});
} else if (state.wsAccess && state.identity) {
logAuth("debug", "ws_token_resolved", {
userId: state.identity.userId,
docId: state.wsAccess.docId,
permission: state.wsAccess.permission,
});
} else if (state.mcpAccess) {
logAuth("debug", "mcp_token_resolved", {
docId: state.mcpAccess.docId,
permission: state.mcpAccess.permission,
});
} else {
const identity = state.identity;
logAuth("debug", "identity_resolved", {
userId: identity?.userId ?? "unknown",
});
}
return state;
})
.finally(() => {
delete custom.__authStatePromise;
});
custom.__authStatePromise = promise;
return promise;
};
const getDocAccessCache = (
custom: Record<string, unknown>,
): Record<string, AgentDocAccessCacheEntry> => {
const existing = custom.__docAccessCache;
if (existing && typeof existing === "object") {
return existing as Record<string, AgentDocAccessCacheEntry>;
}
const created = Object.create(null) as Record<
string,
AgentDocAccessCacheEntry
>;
custom.__docAccessCache = created;
return created;
};
const getCachedDocumentAccess = (
custom: Record<string, unknown>,
docId: string,
): AgentDocAccessCacheEntry | null => {
const cache = getDocAccessCache(custom);
const entry = cache[docId];
if (!entry) {
return null;
}
if (entry.expiresAt < Date.now()) {
delete cache[docId];
return null;
}
return entry;
};
const setCachedDocumentAccess = (
custom: Record<string, unknown>,
docId: string,
entry: Omit<AgentDocAccessCacheEntry, "expiresAt">,
): AgentDocAccessCacheEntry => {
const cache = getDocAccessCache(custom);
const value: AgentDocAccessCacheEntry = {
...entry,
expiresAt: Date.now() + DOC_ACCESS_CACHE_TTL_MS,
};
cache[docId] = value;
return value;
};
const resolveDocumentAccessForAgent = async (
context:
| SubmitContextLike
| ReadSnapshotsContextLike
| QueryContextLike
| ConnectContextLike,
docId: string,
): Promise<{
authState: AgentAuthState;
access: AgentDocAccessCacheEntry | null;
}> => {
const authState = await ensureAgentAuthState(context);
if (authState.wsAccess) {
if (authState.wsAccess.docId !== docId) {
return { authState, access: null };
}
return {
authState,
access: {
canAccess: true,
permission: authState.wsAccess.permission,
expiresAt: Number.POSITIVE_INFINITY,
},
};
}
if (!authState.identity) {
return { authState, access: null };
}
const custom = getOrCreateAgentCustom(context);
const cached = getCachedDocumentAccess(custom, docId);
if (cached) {
return {
authState,
access: cached,
};
}
const accessResult = await ensureDocumentAccess({
docId,
userId: authState.identity.userId,
});
const access = setCachedDocumentAccess(custom, docId, {
canAccess: accessResult.canAccess,
permission: accessResult.permission as DocumentPermission,
});
return {
authState,
access,
};
};
const rejectSnapshotReadWithError = (
context: ReadSnapshotsContextLike,
snapshot: ReadSnapshotLike,
error: Error,
) => {
if (typeof context.rejectSnapshotRead === "function") {
context.rejectSnapshotRead(snapshot, error);
return;
}
throw error;
};
export const registerAuthAccessMiddleware = (backend: ShareDB) => {
backend.use("connect", (context: ConnectContextLike, callback) => {
void ensureAgentAuthState(context).catch((error) => {
logAuth("warn", "identity_resolution_failed", {
reason: "endpoint_failure",
error: error instanceof Error ? error.message : String(error),
});
});
callback();
});
backend.use(
"readSnapshots",
(context: ReadSnapshotsContextLike, callback: (error?: Error) => void) => {
void (async () => {
if (context.collection !== SHAREDB_COLLECTION) {
throw createForbiddenError("Collection access is forbidden.");
}
const authState = await ensureAgentAuthState(context);
if (!authState.identity && !authState.mcpAccess) {
const error = createUnauthorizedError(
"Authentication required to read this document.",
);
const deniedDocIds = context.snapshots
.map((snapshot) => toString(snapshot.id))
.filter((docId): docId is string => Boolean(docId));
for (const snapshot of context.snapshots) {
rejectSnapshotReadWithError(context, snapshot, error);
}
logAuth("warn", "read_denied", {
collection: context.collection,
docIds: deniedDocIds,
reason: authState.failureReason,
statusCode: authState.statusCode,
});
return;
}
for (const snapshot of context.snapshots) {
const docId = toString(snapshot.id);
if (!docId) {
rejectSnapshotReadWithError(
context,
snapshot,
createForbiddenError("Invalid document id."),
);
continue;
}
if (authState.wsAccess && authState.wsAccess.docId !== docId) {
const error = createForbiddenError(
"WS token is not valid for this document.",
);
rejectSnapshotReadWithError(context, snapshot, error);
logAuth("warn", "read_denied", {
collection: context.collection,
docId,
reason: "forbidden",
});
continue;
}
if (authState.mcpAccess) {
if (authState.mcpAccess.docId !== docId) {
const error = createForbiddenError(
"MCP token is not valid for this document.",
);
rejectSnapshotReadWithError(context, snapshot, error);
logAuth("warn", "read_denied", {
collection: context.collection,
docId,
reason: "forbidden",
});
continue;
}
logAuth("debug", "read_allowed", {
collection: context.collection,
docId,
permission: authState.mcpAccess.permission,
userId: "mcp-token",
});
continue;
}
const { access } = await resolveDocumentAccessForAgent(
context,
docId,
);
const authUserId = authState.identity?.userId ?? "unknown";
if (!access?.canAccess) {
const error = createForbiddenError(
"You do not have access to this document.",
);
rejectSnapshotReadWithError(context, snapshot, error);
logAuth("warn", "read_denied", {
collection: context.collection,
docId,
userId: authUserId,
reason: "forbidden",
});
} else {
logAuth("debug", "read_allowed", {
collection: context.collection,
docId,
permission: access.permission,
userId: authUserId,
});
}
}
})()
.then(() => callback())
.catch((error) => {
callback(
error instanceof Error
? error
: createForbiddenError("Unable to validate read access."),
);
});
},
);
backend.use(
"submit",
(context: SubmitContextLike, callback: (error?: Error) => void) => {
void (async () => {
if (context.collection !== SHAREDB_COLLECTION) {
throw createForbiddenError("Collection access is forbidden.");
}
const docId = toString(context.id);
if (!docId) {
throw createForbiddenError("Invalid document id.");
}
const { authState, access } = await resolveDocumentAccessForAgent(
context,
docId,
);
if (!authState.identity && !authState.mcpAccess) {
throw createUnauthorizedError(
"Authentication required to edit this document.",
);
}
if (authState.wsAccess) {
if (authState.wsAccess.docId !== docId) {
throw createForbiddenError(
"WS token is not valid for this document.",
);
}
if (authState.wsAccess.permission !== "edit") {
throw createForbiddenError("WS token does not allow edit access.");
}
}
if (authState.mcpAccess) {
if (authState.mcpAccess.docId !== docId) {
throw createForbiddenError(
"MCP token is not valid for this document.",
);
}
if (authState.mcpAccess.permission !== "edit") {
throw createForbiddenError("MCP token does not allow edit access.");
}
logAuth("debug", "submit_allowed", {
collection: context.collection,
docId,
userId: "mcp-token",
permission: authState.mcpAccess.permission,
});
return;
}
if (!access?.canAccess) {
throw createForbiddenError(
"You do not have access to this document.",
);
}
if (access.permission !== "edit") {
throw createForbiddenError(
"You do not have permission to edit this document.",
);
}
const authUserId = authState.identity?.userId ?? "unknown";
logAuth("debug", "submit_allowed", {
collection: context.collection,
docId,
userId: authUserId,
permission: access.permission,
});
})()
.then(() => callback())
.catch((error) => {
const authState = (getOrCreateAgentCustom(context).__authState ??