Repository navigation
Expand file tree
/
Copy pathcreate-app.ts
More file actions
1650 lines (1648 loc) · 55.2 KB
/
Copy pathcreate-app.ts
File metadata and controls
1650 lines (1648 loc) · 55.2 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 { pluginServices } from "@core/shared/plugin-services.js";
import { registerGroups } from "../routes/groups.js";
import { createUserDirectory } from "@core/modules/discovery/users.js";
import { HOST_VERSION } from "./version.js";
import { defaultLocale, locales } from "@doca/i18n";
import { createHistoryWorker } from "../jobs/history-worker.js";
import { sessionDurations } from "./session-policy.js";
import {
desktopBearerToken,
desktopSessionUser,
isDesktopToken,
registerDesktopClient,
} from "./desktop-client.js";
import { imagePageAttemptLimit } from "../services/ai/image-attempt-policy.js";
import { pluginMobileActor } from "../plugins/mobile-session.js";
import { emitIntegrationEvent } from "@core/modules/automation/events.js";
import {
bearerSession,
mobileSession,
persistentAndroidExpiry,
registerMobileClient,
renewMobileSession,
sessionExpiresAt,
startMobilePush,
} from "./mobile-client.js";
import { registerRuntimeSettings } from "../routes/runtime-settings.js";
import { registerReleaseCheck } from "../routes/release-check.js";
import type { ReleaseCheckOptions } from "../services/release-check.js";
import { registerSiteBranding } from "../routes/site-branding.js";
import { readSiteLogo } from "../services/site-logo.js";
import type { registerAI } from "../routes/ai.js";
import { passwordIdentity } from "@core/modules/identity/accounts.js";
import { registrationProfile } from "@core/modules/identity/accounts.js";
import { profilePolicy } from "@core/modules/identity/naming.js";
import { requireSecurity } from "@core/modules/identity/security.js";
import {
adminUserDetails,
createAdminUser,
resetUserPassword,
} from "../routes/admin-users.js";
import { registerAccounts } from "../routes/accounts.js";
import { registerResourceHandover } from "../routes/resource-handover.js";
import { type MessagingRuntime } from "../adapters/messaging.js";
import {
passwordAllowed,
identityPolicy,
profileRequirements,
missingForcedLoginMethod,
} from "@core/modules/identity/accounts.js";
import { contactProofs } from "@core/modules/identity/verification.js";
import { accountBinding } from "./account-context.js";
import swagger from "@fastify/swagger";
import { Type, type TSchema } from "@sinclair/typebox";
import Fastify, { type FastifyRequest, type HTTPMethods } from "fastify";
import { sql } from "kysely";
import { randomBytes, randomUUID } from "node:crypto";
import { authorize } from "@core/modules/access/queries.js";
import {
createUser,
hashPassword,
publicUser,
recordLogin,
revokeDesktopSessions,
tokenHash,
verifyPassword,
type Actor,
} from "@core/modules/identity/passwords.js";
import {
notificationPage,
visibleUsers,
} from "@core/modules/interactions/community.js";
import { createVisitBuffer } from "@core/modules/interactions/visits.js";
import { AppError, fail, systemErrorText } from "@core/shared/errors.js";
import {
cursorFingerprint,
decodePageCursor,
encodePageCursor,
} from "@core/shared/cursor.js";
import { createContent } from "@core/workflows/resources.js";
import type { DB } from "@db/index.js";
import { transact } from "@db/transactions.js";
import type { IdentityRuntime } from "../adapters/identity-providers.js";
import { type StorageRuntime } from "../adapters/storage.js";
import { registerAssets } from "../routes/assets.js";
import { registerBrowserClipper } from "../routes/browser-clipper.js";
import { authenticateBrowserConnection } from "@core/modules/browser-clipper/access.js";
import { registerPageState } from "../routes/page-state.js";
import { registerDocumentPdf } from "../routes/document-pdf.js";
import { registerExperience } from "../routes/experience.js";
import { registerIdentity } from "../routes/identity.js";
import { registerRegistrationReviews } from "../routes/registration-reviews.js";
import type { SearchRuntime } from "../routes/search.js";
import { registerWorkspace } from "../routes/workspace.js";
import { registerWebhooks } from "../routes/webhooks.js";
import { dispatchWebhooks } from "../services/webhooks/dispatch.js";
import type { WebhookPost, WebhookResolve } from "../services/webhooks/http.js";
import { openWebhookDatabase, type WebhookDB } from "@db/webhook-database.js";
import { registerProfiles } from "../routes/profiles.js";
import { registerStaticRoutes } from "../routes/static.js";
import { registerTickets } from "../routes/tickets.js";
import { registerRealtime } from "../services/realtime/gateway.js";
import { createRealtimeCluster } from "../services/realtime/cluster.js";
import { composeServerPlugins } from "../plugins/composition.js";
import { MonitoringBuffer } from "../services/monitoring-buffer.js";
import { createHostMonitoring } from "../services/monitoring.js";
export interface CreateAppOptions {
origin: string;
staticDirectory?: string;
assetBase?: string;
logging?: boolean;
storage?: StorageRuntime;
search?: SearchRuntime;
identity?: IdentityRuntime;
messaging?: MessagingRuntime;
ai?: Parameters<typeof registerAI>[4];
pluginDirectory?: string;
plugins?: Readonly<Record<string, boolean | undefined>>;
redisUrl?: string;
redisPrefix?: string;
instanceId?: string;
trustProxy?: string[];
webhookDatabase?: WebhookDB;
webhookDispatch?: boolean;
webhookResolve?: WebhookResolve;
webhookPost?: WebhookPost;
releaseCheck?: ReleaseCheckOptions;
}
export async function createApp(db: DB, options: CreateAppOptions) {
imagePageAttemptLimit();
sessionDurations();
const origin = new URL(options.origin);
const monitoringBuffer = new MonitoringBuffer(options.instanceId ?? randomUUID());
const api = Fastify({
logger: options.logging
? {
stream: { write(chunk: string) { monitoringBuffer.hostLog(chunk); process.stdout.write(chunk); } },
serializers: {
req: (req: any) => ({
method: req.method,
url: String(req.url ?? "").split("?")[0],
hostname: req.hostname,
remoteAddress: req.ip,
}),
},
redact: [
"req.headers.cookie",
"req.headers.authorization",
"res.headers.set-cookie",
],
}
: false,
bodyLimit: 65536,
trustProxy: options.trustProxy?.length ? options.trustProxy : false,
ajv: { customOptions: { removeAdditional: false } },
});
const observedRequests = new WeakMap<FastifyRequest, { finish(status: number | null): void }>();
api.addHook("onRequest", async (request, reply) => {
// WebSocket messages and their connection lifetime have a separate presence source.
if (request.headers.upgrade?.toLowerCase() === "websocket") return;
const started = performance.now(); let finished = false;
monitoringBuffer.begin();
const finish = (status: number | null) => {
if (finished) return; finished = true;
request.raw.removeListener("aborted", aborted);
reply.raw.removeListener("close", closed);
const elapsed = performance.now() - started;
const route = request.routeOptions.url ?? "[unmatched]";
monitoringBuffer.request(request.method, route, status, elapsed);
if (status === null || status >= 400 || elapsed >= 2000) {
if (!monitoringBuffer.closed) monitoringBuffer.log(null, { level: status !== null && status >= 500 ? "error" : "warn", module: "http", message: status === null ? "HTTP request aborted" : "HTTP request completed", requestId: request.id, fields: { method: request.method, route, status, durationMs: elapsed } });
}
};
const aborted = () => finish(null), closed = () => { if (!reply.raw.writableFinished) finish(null); };
request.raw.once("aborted", aborted); reply.raw.once("close", closed);
observedRequests.set(request, { finish });
});
api.addHook("onResponse", async (request, reply) => { observedRequests.get(request)?.finish(reply.statusCode); });
await api.register(swagger, {
openapi: {
info: {
title: "Doca Cloud API",
version: HOST_VERSION,
description:
"No spaces or organizations. Browser writes require the configured Origin and a host-only session cookie. Mobile clients send Authorization: Bearer with the same session token. Rich text uses the authenticated /api/v1/ws Yjs channel.",
},
servers: [{ url: origin.origin }],
components: {
securitySchemes: {
session: { type: "apiKey", in: "cookie", name: "doca_session" },
bearer: { type: "http", scheme: "bearer" },
},
},
},
});
const realtimeCluster = await createRealtimeCluster({
redisUrl: options.redisUrl,
prefix: options.redisPrefix,
instanceId: monitoringBuffer.instanceId,
}).catch(error => { monitoringBuffer.close(); throw error; });
const monitoring = await createHostMonitoring(db, monitoringBuffer, realtimeCluster, { redisUrl: options.redisUrl, prefix: options.redisPrefix }).catch(async error => { monitoringBuffer.close(); await realtimeCluster.close(); throw error; });
api.addHook("onClose", async () => monitoring.close());
const actors = new WeakMap<FastifyRequest, Actor | null>(),
library = createContent(db);
const visits = createVisitBuffer((actor, id, stamp) =>
library.visit(actor, id, stamp),
);
api.addHook("preClose", async () => {
await visits.close();
});
api.addHook("preHandler", async (req) => {
const actor = actors.get(req);
if (req.method === "GET" && actor) await visits.flush(actor.id);
});
async function limit(key: string, max = 15) {
if (!(await realtimeCluster.consumeRateLimit(key, max, 600_000)))
fail(429, "请求过于频繁,请稍后再试");
}
function cookie(token: string, maxAge = sessionDurations().browserSeconds) {
return `doca_session=${token}; Path=/; HttpOnly; SameSite=Strict; Max-Age=${maxAge}${origin.protocol === "https:" ? "; Secure" : ""}`;
}
const scopedPlugins = new WeakMap<FastifyRequest,string>();
const sessionTokens = new WeakMap<FastifyRequest, string | null>();
function cookieToken(req: FastifyRequest) {
const token = req.headers.cookie
?.split(";")
.map((s) => s.trim())
.find((s) => s.startsWith("doca_session="))
?.slice(13);
return token && /^[a-f0-9]{64}$/.test(token) ? token : null;
}
async function sessionUser(token: string) {
if (isDesktopToken(token)) return desktopSessionUser(db, token);
return (
(await db
.selectFrom("sessions")
.innerJoin("users", "users.id", "sessions.user_id")
.select([
"users.id",
"users.public_id",
"users.display_name",
"users.admin",
])
.where("sessions.id", "=", tokenHash(token))
.where("sessions.expires_at", ">", new Date().toISOString())
.where("users.status", "=", "active")
.executeTakeFirst()) ?? null
);
}
function sessionToken(req: FastifyRequest) {
if (sessionTokens.has(req)) return sessionTokens.get(req) ?? null;
return cookieToken(req);
}
api.addHook("onRequest", async (req, reply) => {
if (req.url === "/api/v1/auth/logout") {
reply.header("Set-Cookie", cookie("", 0));
}
reply
.header("Cache-Control", "no-store")
.header("X-Content-Type-Options", "nosniff")
.header("Referrer-Policy", "no-referrer")
.header("X-Frame-Options", "DENY");
if (
req.raw.rawHeaders
.filter((_, i) => i % 2 === 0)
.filter((h) => h.toLowerCase() === "host").length !== 1 ||
req.headers.host?.toLowerCase() !== origin.host.toLowerCase()
)
fail(421, "访问地址与服务配置不符");
const presentedCookie = cookieToken(req);
const presentedBearer = bearerSession(req.headers.authorization);
const presentedDesktop = desktopBearerToken(req.headers.authorization);
const bearerUser = presentedBearer
? await sessionUser(presentedBearer)
: null;
const desktopUser = presentedDesktop
? await desktopSessionUser(db, presentedDesktop)
: null;
if (bearerUser && presentedBearer)
await renewMobileSession(db, presentedBearer);
const path = req.url.split("?")[0]!;
const browserClipper = !!(req.routeOptions.config as { docaBrowserClipper?: boolean }).docaBrowserClipper;
if (browserClipper && req.headers.origin && req.headers.origin !== origin.origin && !/^chrome-extension:\/\/[a-p]{32}$/.test(req.headers.origin))
fail(403, "clipper_invalid_origin");
if (path === "/api/v1/mcp" && req.headers.origin && req.headers.origin !== origin.origin)
fail(403, "Invalid MCP Origin");
const mobileCredential =
req.headers["x-doca-client"] === "mobile" &&
[
"/api/v1/auth/login",
"/api/v1/auth/register",
"/api/v1/auth/sms",
"/api/v1/auth/email",
"/api/v1/auth/sms/complete",
"/api/v1/auth/email/complete",
].includes(path);
const desktopHandoff = !req.headers.origin && [
"/api/v1/auth/desktop/start",
"/api/v1/auth/desktop/exchange",
].includes(path);
if (
!["GET", "HEAD", "OPTIONS"].includes(req.method) &&
!browserClipper &&
!(
req.url === "/api/v1/mcp" &&
/^Bearer doca_mcp_v1_[a-f0-9]{64}$/.test(req.headers.authorization ?? "")
) &&
!(req.routeOptions.config as { docaPluginExternal?: boolean })
.docaPluginExternal &&
!bearerUser &&
!desktopUser &&
!mobileCredential &&
!desktopHandoff &&
req.headers.origin !== origin.origin
)
fail(403, "来源校验失败");
const token = desktopUser ? presentedDesktop : bearerUser ? presentedBearer : presentedCookie;
const externalPlugin = (
req.routeOptions.config as { docaPluginExternal?: boolean }
).docaPluginExternal;
let user: Actor | null = externalPlugin
? null
: (desktopUser ?? bearerUser ?? (token ? await sessionUser(token) : null));
if (browserClipper) user = path === "/api/v1/browser-clipper/token" ? null : (await authenticateBrowserConnection(db, req.headers.authorization)).actor;
const scopedToken = /(?:^|;\s*)doca_plugin_session=([a-f0-9]{64})(?:;|$)/.exec(req.headers.cookie ?? "")?.[1];
if(scopedToken && path.startsWith("/api/") && path!=="/api/v1/plugins-mobile/redeem") {
const scoped=await pluginMobileActor(db,scopedToken,pluginComposition.plugins.map(p=>p.id));
if (!(req.method==="GET" && (path==="/api/v1/bootstrap" || path.startsWith(`/api/v1/plugin-assets/${scoped.plugin_id}/`))) && !path.startsWith(`/api/v1/plugins/${scoped.plugin_id}/`) && !(req.method === "POST" && path.startsWith(`/api/v1/plugin-platform/${scoped.plugin_id}/`))) fail(403,"Plugin session scope denied");
scopedPlugins.set(req,scoped.plugin_id);user={id:scoped.id,display_name:scoped.display_name,admin:scoped.admin,public_id:undefined};
}
sessionTokens.set(req, user && token ? token : null);
if (path.startsWith("/api/v1/plugin-platform/")) {
const pluginId = path.split("/")[4];
if (!pluginComposition.plugins.some(plugin => plugin.id === pluginId)) fail(404, "Plugin unavailable");
}
actors.set(req, user ?? null);
const accountPath = req.url.split("?")[0]!;
const forcedLoginMethod = user
? await missingForcedLoginMethod(db, user.id, await identityPolicy(db), {
phoneReady: runtime.messaging.phoneReady,
emailReady: runtime.messaging.emailReady,
providerReady: (ref) =>
Object.hasOwn(runtime.identity.credentials, ref) &&
typeof runtime.identity.credentials[ref] === "string" &&
!!runtime.identity.credentials[ref],
})
: null;
if (
user &&
accountPath.startsWith("/api/v1/") &&
((await profileRequirements(db, user.id)) || !!forcedLoginMethod) &&
!accountPath.startsWith("/api/v1/auth/") &&
![
"/api/v1/me",
"/api/v1/me/account",
"/api/v1/me/security",
"/api/v1/me/contacts",
"/api/v1/me/onboarding",
"/api/v1/me/profile",
"/api/v1/me/identities",
"/api/v1/bootstrap",
].includes(accountPath) &&
!accountPath.startsWith("/api/v1/me/identities/") &&
!(
user.admin &&
accountPath.startsWith("/api/v1/admin/") &&
!forcedLoginMethod
)
) {
reply.header("X-Doca-Profile-Required", "1");
fail(
403,
forcedLoginMethod
? "请先到账号资料页面补充指定登录方式"
: "请先到账号资料页面补全必填联系方式",
);
}
});
api.setErrorHandler((error, req, reply) => {
const conflict = [
"23505",
"40001",
"40P01",
"SQLITE_CONSTRAINT_UNIQUE",
"SQLITE_CONSTRAINT_PRIMARYKEY",
"SQLITE_BUSY",
"SQLITE_BUSY_SNAPSHOT",
].includes((error as { code?: string }).code ?? "");
const frameworkStatus =
error && typeof error === "object" && "statusCode" in error
? Number(error.statusCode)
: 0;
const status =
error instanceof AppError
? error.status
: error && typeof error === "object" && "validation" in error
? 400
: [400, 413, 415, 429].includes(frameworkStatus)
? frameworkStatus
: conflict
? 409
: 500;
if (status === 500) req.log.error({ err: error }, "Request failed");
reply.header("Cache-Control", "no-store").removeHeader("ETag").code(status).send({
message:
error instanceof AppError
? systemErrorText(error)
: status === 400
? "请求参数无效"
: status === 409
? "操作发生冲突,请刷新或更换用户名后重试"
: "服务暂时不可用",
requestId: req.id,
});
});
const actor = (req: FastifyRequest) => actors.get(req) ?? null;
const authenticated = (req: FastifyRequest) =>
actor(req) ?? fail(401, "请先登录");
const admin = (req: FastifyRequest) => {
const a = authenticated(req);
if (!a.admin) fail(403, "需要系统管理员权限");
return a;
};
const runtime = await registerRuntimeSettings(api, db, admin, options);
registerReleaseCheck(api, db, admin, options.releaseCheck);
const historyWorker = createHistoryWorker(db, runtime.storage);
let historyProcessing: Promise<unknown> | undefined;
let historyTimer: ReturnType<typeof setInterval> | undefined;
api.addHook("onReady", async () => {
historyTimer = setInterval(() => {
if (historyProcessing) return;
historyProcessing = historyWorker.pump()
.catch(error => api.log.error({ err: error }, "History storage maintenance failed"))
.finally(() => { historyProcessing = undefined; });
}, 1000);
historyTimer.unref();
});
api.addHook("preClose", async () => {
if (historyTimer) clearInterval(historyTimer);
await historyProcessing;
historyWorker.dispose();
});
registerRegistrationReviews(api, db, { admin });
registerTickets(api, db, {
origin,
actor,
authenticated,
admin,
sessionToken,
cookie,
limit,
});
registerAccounts(
api,
db,
{
origin,
actor,
authenticated,
admin,
sessionToken,
cookie,
limit,
providerReady: (ref) =>
Object.hasOwn(runtime.identity.credentials, ref) &&
typeof runtime.identity.credentials[ref] === "string" &&
!!runtime.identity.credentials[ref],
},
runtime.messaging,
);
const stopMobilePush = startMobilePush(db);
api.addHook("preClose", async () => {
await stopMobilePush();
});
registerMobileClient(api, db, authenticated, cookie, limit);
registerDesktopClient(api, db, { origin, limit, admin, sessionToken });
registerIdentity(
api,
db,
{
origin,
actor,
authenticated,
admin,
sessionToken,
cookie,
limit,
loginMethodRuntime: {
phoneReady: runtime.messaging.phoneReady,
emailReady: runtime.messaging.emailReady,
},
},
runtime.identity,
);
const realtime = await registerRealtime(
api,
db,
origin.origin,
async (req) => {
const token = sessionToken(req);
if (!token) return null;
const user = await sessionUser(token);
return user && !(await profileRequirements(db, user.id)) ? user : null;
},
realtimeCluster,
);
api.addHook("preClose", async () => realtimeCluster.close());
registerWorkspace(api, db, authenticated, admin, realtime.onlineUsers);
registerGroups(api, db, authenticated, admin, async userIds => {
await realtime.enforceAccess();
await Promise.all(userIds.map(id => realtime.notificationsChanged(id)));
});
registerResourceHandover(api, db, admin, async (userIds) => {
await realtime.enforceAccess();
await Promise.all(userIds.map((id) => realtime.notificationsChanged(id)));
});
const webhookDb =
options.webhookDatabase ??
(await openWebhookDatabase({ driver: "sqlite", path: ":memory:" }));
const ownsWebhookDatabase = !options.webhookDatabase;
registerWebhooks(api, db, webhookDb, admin, options.webhookResolve);
let webhookDispatching: Promise<unknown> | undefined;
const webhookTimer = options.webhookDispatch
? setInterval(() => {
if (webhookDispatching) return;
webhookDispatching = dispatchWebhooks(db, webhookDb, {
post: options.webhookPost,
resolve: options.webhookResolve,
})
.catch((error) => {
api.log.error({ err: error }, "Webhook dispatch failed");
})
.finally(() => {
webhookDispatching = undefined;
});
}, 1000)
: undefined;
api.addHook("preClose", async () => {
if (webhookTimer) clearInterval(webhookTimer);
await webhookDispatching;
if (ownsWebhookDatabase) await webhookDb.destroy();
});
registerPageState(api, db, authenticated);
registerDocumentPdf(api, db, actor);
const pluginComposition = await composeServerPlugins({
api,
db,
auth: authenticated,
admin,
origin,
runtime,
options,
realtime,
monitoring,
consumeRateLimit: (key, max, windowMs) =>
realtimeCluster.consumeRateLimit(key, max, windowMs),
}).catch(async (error) => {
// Failed composition must release already-created connections and workers.
try {
await api.close();
} finally {
throw error;
}
});
// Fastify routes are immutable after mounting, so the host is intentionally
// disposed only from application close (or startup rollback below).
api.addHook("preClose", async () => {
pluginServices(db).continuationsReady = false;
// Drain search work while its document/file sources are still registered.
await pluginComposition.search.stop();
await pluginComposition.host.dispose();
});
const search = pluginComposition.search;
registerProfiles(api, db, authenticated);
registerAssets(api, db, authenticated, actor, admin, runtime.storage, limit);
registerSiteBranding(api, db, admin);
registerBrowserClipper(api, db, authenticated, origin.origin, runtime.storage, realtime.documentChanged, limit);
const id = Type.String({ format: "uuid" }),
nullableId = Type.Union([id, Type.Null()]),
version = Type.Integer({ minimum: 1 }),
name = Type.String({ minLength: 1, maxLength: 160, pattern: "\\S" }),
password = Type.String({ minLength: 12, maxLength: 128 });
const object = (properties: Record<string, TSchema>) =>
Type.Object(properties, { additionalProperties: false });
const optional = <T extends TSchema>(schema: T) => Type.Optional(schema);
registerExperience(api, db, actor, authenticated);
const role = Type.Union(
["reader", "commenter", "editor", "manager"].map((x) => Type.Literal(x)),
);
function route<B = unknown>(
method: HTTPMethods,
path: string,
summary: string,
body: TSchema | undefined,
handler: (
req: FastifyRequest<{ Body: B; Params: Record<string, string> }>,
a: Actor,
) => Promise<unknown>,
) {
const params = Object.fromEntries(
[...path.matchAll(/:([a-zA-Z]+)/g)].map((m) => [m[1]!, id]),
);
api.route<{ Body: B; Params: Record<string, string> }>({
method,
url: "/api/v1" + path,
bodyLimit:
method === "POST" &&
[
"/resources",
"/resources/:id/import-initial",
"/resources/:id/import-markdown-initial",
].includes(path)
? 4 * 1024 * 1024
: 65536,
schema: {
summary,
tags: ["Content"],
security: [{ session: [] }],
...(body ? { body } : {}),
...(Object.keys(params).length ? { params: object(params) } : {}),
},
handler: (req) => handler(req, authenticated(req)),
});
}
api.get(
"/api/v1/bootstrap",
{ schema: { summary: "公开站点配置及当前会话", tags: ["Authentication"] } },
async (req) => {
const settings = await db
.selectFrom("settings")
.selectAll()
.where("id", "=", "system")
.executeTakeFirstOrThrow();
const initialized = !!(await db
.selectFrom("users")
.select("id")
.where("admin", "=", 1)
.executeTakeFirst());
const missingLoginMethod = actor(req)
? await missingForcedLoginMethod(
db,
actor(req)!.id,
await identityPolicy(db),
{
phoneReady: runtime.messaging.phoneReady,
emailReady: runtime.messaging.emailReady,
providerReady: (ref) =>
Object.hasOwn(runtime.identity.credentials, ref) &&
typeof runtime.identity.credentials[ref] === "string" &&
!!runtime.identity.credentials[ref],
},
)
: null;
return {
siteName: settings.site_name,
siteLogoUrl: (await readSiteLogo(settings.site_logo))?.url ?? null,
defaultLocale: settings.default_locale ?? defaultLocale,
defaultTimezone: settings.default_timezone ?? "Asia/Shanghai",
registrationEnabled: !!settings.registration,
authOptions: await identityPolicy(db),
needsProfile: actor(req)
? !!(
(await profileRequirements(db, actor(req)!.id)) ||
missingLoginMethod
)
: false,
forcedLoginMethod: missingLoginMethod,
initialized,
user: actor(req) ? publicUser(actor(req)!) : null,
capabilities: {
editing: true,
realtime: true,
oidcClient: true,
oidcProvider: false,
hooks: true,
integrationEventStream: true,
},
plugins: scopedPlugins.has(req) ? pluginComposition.plugins.filter(p=>p.id===scopedPlugins.get(req)) : pluginComposition.plugins,
};
},
);
api.post<{ Body: { login: string; password: string } }>(
"/api/v1/auth/login",
{
schema: {
summary: "账号密码登录",
tags: ["Authentication"],
body: object({
login: name,
password: Type.String({ minLength: 1, maxLength: 128 }),
}),
},
},
async (req, reply) => {
await limit(`login:${req.ip}`);
await passwordAllowed(db);
const identifier = await passwordIdentity(db, req.body.login);
const user = identifier
? await db
.selectFrom("users")
.selectAll()
.where("id", "=", identifier.user_id)
.executeTakeFirst()
: undefined;
if (
!(await verifyPassword(req.body.password, user?.password_hash ?? "")) ||
!user
)
fail(401, "账号或密码错误");
await passwordAllowed(db);
if (user.status === "pending") return { status: "pending" };
if (user.status !== "active") fail(401, "账号或密码错误");
const persistentAndroid =
req.headers["x-doca-client"] === "mobile" &&
req.headers["x-doca-client-platform"] === "android";
const token = randomBytes(32).toString("hex");
await transact(db, async (tx) => {
await passwordAllowed(tx);
if ((await passwordIdentity(tx, req.body.login))?.user_id !== user.id)
fail(401, "账号或密码错误");
const current = await tx
.selectFrom("users")
.select(["status", "password_hash"])
.where("id", "=", user.id)
.executeTakeFirstOrThrow();
if (
current.status !== "active" ||
current.password_hash !== user.password_hash
)
fail(401, "账号状态已变化,请重新登录");
await tx
.deleteFrom("sessions")
.where("expires_at", "<=", new Date().toISOString())
.execute();
await tx
.insertInto("sessions")
.values({
id: tokenHash(token),
user_id: user.id,
expires_at: persistentAndroid ? persistentAndroidExpiry : sessionExpiresAt(req),
})
.execute();
await recordLogin(tx, user.id);
});
if (!persistentAndroid) reply.header("Set-Cookie", cookie(token));
return mobileSession(req, token, { user: publicUser(user) });
},
);
api.post<{
Body: {
login: string;
password: string;
displayName?: string;
avatar?: string;
email?: string;
phone?: string;
publicId?: string;
proofs?: Partial<Record<"email" | "phone", string>>;
};
}>(
"/api/v1/auth/register",
{
schema: {
summary: "公开注册(需管理员开启)",
tags: ["Authentication"],
body: object({
login: name,
password,
displayName: optional(Type.String({ maxLength: 160 })),
avatar: optional(Type.String({ maxLength: 2048 })),
email: optional(Type.String({ maxLength: 254 })),
phone: optional(Type.String({ maxLength: 32 })),
publicId: optional(name),
proofs: optional(
object({ email: optional(name), phone: optional(name) }),
),
}),
},
},
async (req, reply) => {
await limit(`register:${req.ip}`, 5);
const result = await transact(db, async (tx) => {
const proofs = await contactProofs(
tx,
req.body.proofs,
accountBinding(req),
"profile",
);
const fields = await registrationProfile(
tx,
profilePolicy(),
{},
{},
{
...req.body,
username: req.body.publicId ?? req.body.login,
email: proofs.email ?? req.body.email,
phone: proofs.phone ?? req.body.phone,
},
proofs,
);
const u = await createUser(
tx,
{
...req.body,
login: fields.values.username!,
publicId: fields.values.username!,
displayName: fields.values.displayName ?? "",
},
{ registration: true, verifiedContacts: proofs },
);
if (fields.values.avatar)
await tx
.updateTable("users")
.set({
profile_metadata: JSON.stringify({
avatarUrl: fields.values.avatar,
}),
})
.where("id", "=", u.id)
.execute();
if (u.status === "active") {
const session = randomBytes(32).toString("hex");
await tx
.insertInto("sessions")
.values({
id: tokenHash(session),
user_id: u.id,
expires_at: sessionExpiresAt(req),
})
.execute();
await recordLogin(tx, u.id);
return { ...u, session };
}
return { ...u, session: undefined };
});
if (result.session) reply.header("Set-Cookie", cookie(result.session));
if (result.status === "pending") return { status: "pending" };
const { session, ...publicResult } = result;
return mobileSession(req, session, publicResult);
},
);
route("POST", "/auth/logout", "退出当前会话", undefined, async (req) => {
const token = sessionToken(req);
if (isDesktopToken(token))
await db.updateTable("desktop_sessions")
.set({ revoked_at: new Date().toISOString() })
.where("id", "=", tokenHash(token))
.where("revoked_at", "is", null)
.execute();
else if (token)
await db
.deleteFrom("sessions")
.where("id", "=", tokenHash(token))
.execute();
return { ok: true };
});
route<{ newPassword: string }>(
"POST",
"/auth/password",
"修改密码并撤销全部会话",
object({
newPassword: password,
}),
async (req, a) => {
await limit(`password:${a.id}`, 5);
await passwordAllowed(db);
const user = await db
.selectFrom("users")
.selectAll()
.where("id", "=", a.id)
.executeTakeFirstOrThrow();
await requireSecurity(db, a.id, tokenHash(sessionToken(req)!));
const hash = await hashPassword(req.body.newPassword);
await transact(db, async (tx) => {
await passwordAllowed(tx);
await requireSecurity(tx, a.id, tokenHash(sessionToken(req)!), true);
const changed = await tx
.updateTable("users")
.set({ password_hash: hash })
.where("id", "=", a.id)
.where("password_hash", "=", user.password_hash)
.executeTakeFirst();
if (!changed.numUpdatedRows) fail(409, "密码已变更,请重新登录");
await tx.deleteFrom("sessions").where("user_id", "=", a.id).execute();
await revokeDesktopSessions(tx, a.id);
});
return { ok: true };
},
);
const userDirectory = createUserDirectory(db);
api.get<{ Querystring: { query?: string; cursor?: string; limit?: number } }>(
"/api/v1/users/directory", {
schema: { querystring: object({ query: optional(Type.String({ maxLength: 160 })), cursor: optional(Type.String({ maxLength: 2048 })), limit: optional(Type.Integer({ minimum: 1, maximum: 100 })) }) },
}, async req => userDirectory.search(authenticated(req), { ...req.query, query: req.query.query ?? "" }),
);
for (const action of ["resolve", "validate"] as const)
api.post<{ Body: { ids: string[] } }>(`/api/v1/users/directory/${action}`, {
schema: { body: object({ ids: Type.Array(Type.String({ minLength: 1, maxLength: 200 }), { maxItems: 100 }) }) },
}, async req => {
const actor = authenticated(req);
if (action === "resolve") return { items: await userDirectory.resolve(actor, req.body) };
await userDirectory.validate(actor, req.body);
return { valid: true };
});
api.get<{ Querystring: { q: string } }>(
"/api/v1/users/lookup",
{
schema: {
summary: "协作者选择(按名称/精确账号搜索)",
tags: ["Users"],
querystring: object({
q: Type.String({ maxLength: 160 }),
}),
},
},
async (req) => {
return { items: await visibleUsers(db, authenticated(req), req.query.q) };
},
);
api.get<{
Querystring: {
cursor?: string;
q?: string;
status?: string;
};
}>(
"/api/v1/admin/users",
{
schema: {
summary: "分页用户管理",
tags: ["Administration"],
querystring: object({
cursor: optional(Type.String({ maxLength: 2048 })),
parentId: optional(id),
q: optional(name),
status: optional(
Type.Union([
Type.Literal("active"),
Type.Literal("pending"),
Type.Literal("disabled"),
]),
),
}),
},
},
async (req) => {
admin(req);
let query = db
.selectFrom("users")
.select([
"id",
"login",
"display_name",
"admin",
"status",
"created_at",
"last_login_at",
"public_id",
"directory_mode",
]);
if (req.query.status)
query = query.where("status", "=", req.query.status);
if (req.query.q)
query = query.where((eb) =>
eb.or([
eb("display_name", "like", `%${req.query.q}%`),
eb("login", "like", `%${req.query.q}%`),
eb("public_id", "like", `%${req.query.q}%`),
]),
);
const fingerprint = cursorFingerprint({
kind: "admin-users",
q: req.query.q ?? "",
status: req.query.status ?? "",
});
if (req.query.cursor) {
const cursor = decodePageCursor(req.query.cursor, fingerprint);
query = query.where(
sql<boolean>`(created_at < ${cursor.value} or (created_at = ${cursor.value} and id > ${cursor.id}))`,
);
}
const rows = await query
.orderBy("created_at", "desc")
.orderBy("id")
.limit(101)
.execute();
const items = rows.slice(0, 100);
const last = items.at(-1);
return {
items: await adminUserDetails(db, items),
nextCursor:
rows.length > 100 && last
? encodePageCursor(fingerprint, last.created_at, last.id)
: null,
};
},
);
route<{