matrix-nodejs-homeserver 0.0.0-stage → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (141) hide show
  1. package/LICENSE +75 -0
  2. package/README.md +479 -2
  3. package/dist/adapters/auth.d.ts +50 -0
  4. package/dist/adapters/auth.js +18 -0
  5. package/dist/adapters/cluster.d.ts +55 -0
  6. package/dist/adapters/cluster.js +249 -0
  7. package/dist/adapters/media.d.ts +50 -0
  8. package/dist/adapters/media.js +63 -0
  9. package/dist/adapters/s3.d.ts +33 -0
  10. package/dist/adapters/s3.js +95 -0
  11. package/dist/api/account.js +594 -0
  12. package/dist/api/admin.js +267 -0
  13. package/dist/api/appservice.js +45 -0
  14. package/dist/api/backup.js +280 -0
  15. package/dist/api/federation.js +826 -0
  16. package/dist/api/filters.js +88 -0
  17. package/dist/api/index.js +47 -0
  18. package/dist/api/legacy.js +183 -0
  19. package/dist/api/media.js +271 -0
  20. package/dist/api/misc.js +95 -0
  21. package/dist/api/preview.js +201 -0
  22. package/dist/api/profile.js +176 -0
  23. package/dist/api/push.js +202 -0
  24. package/dist/api/relationships.js +270 -0
  25. package/dist/api/rooms.js +1487 -0
  26. package/dist/api/rtc.d.ts +23 -0
  27. package/dist/api/rtc.js +66 -0
  28. package/dist/api/search.js +161 -0
  29. package/dist/api/slidingsync.js +474 -0
  30. package/dist/api/spaces.js +177 -0
  31. package/dist/api/sync.js +609 -0
  32. package/dist/api/threadsubs.js +140 -0
  33. package/dist/api/threepid.js +155 -0
  34. package/dist/api/uia.js +127 -0
  35. package/dist/api/user.js +329 -0
  36. package/dist/core/admin.d.ts +84 -0
  37. package/dist/core/admin.js +308 -0
  38. package/dist/core/adminroom.d.ts +49 -0
  39. package/dist/core/adminroom.js +483 -0
  40. package/dist/core/appservices.d.ts +74 -0
  41. package/dist/core/appservices.js +369 -0
  42. package/dist/core/audit.d.ts +50 -0
  43. package/dist/core/audit.js +86 -0
  44. package/dist/core/auth.d.ts +48 -0
  45. package/dist/core/auth.js +237 -0
  46. package/dist/core/authrules.d.ts +4 -0
  47. package/dist/core/authrules.js +348 -0
  48. package/dist/core/cluster.d.ts +66 -0
  49. package/dist/core/cluster.js +191 -0
  50. package/dist/core/crypto.d.ts +10 -0
  51. package/dist/core/crypto.js +100 -0
  52. package/dist/core/delayed.d.ts +39 -0
  53. package/dist/core/delayed.js +160 -0
  54. package/dist/core/errors.d.ts +9 -0
  55. package/dist/core/errors.js +45 -0
  56. package/dist/core/events.d.ts +32 -0
  57. package/dist/core/events.js +186 -0
  58. package/dist/core/glob.js +66 -0
  59. package/dist/core/identity.d.ts +24 -0
  60. package/dist/core/identity.js +96 -0
  61. package/dist/core/ids.js +36 -0
  62. package/dist/core/invitefilter.js +36 -0
  63. package/dist/core/json.js +16 -0
  64. package/dist/core/keys.d.ts +36 -0
  65. package/dist/core/keys.js +450 -0
  66. package/dist/core/m.d.ts +209 -0
  67. package/dist/core/m.js +182 -0
  68. package/dist/core/notifier.d.ts +17 -0
  69. package/dist/core/notifier.js +54 -0
  70. package/dist/core/oauth.d.ts +38 -0
  71. package/dist/core/oauth.js +108 -0
  72. package/dist/core/partialstate.d.ts +32 -0
  73. package/dist/core/partialstate.js +198 -0
  74. package/dist/core/phone.js +268 -0
  75. package/dist/core/policy.d.ts +29 -0
  76. package/dist/core/policy.js +97 -0
  77. package/dist/core/profile.js +39 -0
  78. package/dist/core/push.d.ts +46 -0
  79. package/dist/core/push.js +307 -0
  80. package/dist/core/pushrules.js +229 -0
  81. package/dist/core/ratelimit.d.ts +23 -0
  82. package/dist/core/ratelimit.js +77 -0
  83. package/dist/core/rooms.d.ts +215 -0
  84. package/dist/core/rooms.js +1731 -0
  85. package/dist/core/settings.d.ts +11 -0
  86. package/dist/core/settings.js +29 -0
  87. package/dist/core/sso.d.ts +46 -0
  88. package/dist/core/sso.js +165 -0
  89. package/dist/core/stateres.d.ts +4 -0
  90. package/dist/core/stateres.js +209 -0
  91. package/dist/core/threepid.d.ts +80 -0
  92. package/dist/core/threepid.js +275 -0
  93. package/dist/core/typing.d.ts +16 -0
  94. package/dist/core/typing.js +60 -0
  95. package/dist/federation/client.d.ts +51 -0
  96. package/dist/federation/client.js +279 -0
  97. package/dist/federation/index.d.ts +153 -0
  98. package/dist/federation/index.js +1059 -0
  99. package/dist/federation/keyring.d.ts +26 -0
  100. package/dist/federation/keyring.js +122 -0
  101. package/dist/federation/sender.d.ts +26 -0
  102. package/dist/federation/sender.js +164 -0
  103. package/dist/homeserver.d.ts +224 -0
  104. package/dist/homeserver.js +302 -0
  105. package/dist/http/adapters.d.ts +40 -0
  106. package/dist/http/adapters.js +130 -0
  107. package/dist/http/handler.d.ts +8 -0
  108. package/dist/http/handler.js +181 -0
  109. package/dist/http/input.js +24 -0
  110. package/dist/http/procedure.js +25 -0
  111. package/dist/http/router.d.ts +43 -0
  112. package/dist/http/router.js +56 -0
  113. package/dist/index.d.ts +26 -0
  114. package/dist/index.js +15 -0
  115. package/dist/storage/memory.d.ts +5 -0
  116. package/dist/storage/memory.js +122 -0
  117. package/dist/storage/schema.d.ts +4 -0
  118. package/dist/storage/schema.js +664 -0
  119. package/dist/storage/sql.d.ts +72 -0
  120. package/dist/storage/sql.js +274 -0
  121. package/dist/storage/types.d.ts +55 -0
  122. package/dist/vendor/zod/LICENSE +21 -0
  123. package/dist/vendor/zod/v4/classic/errors.js +54 -0
  124. package/dist/vendor/zod/v4/classic/parse.js +17 -0
  125. package/dist/vendor/zod/v4/classic/schemas.js +865 -0
  126. package/dist/vendor/zod/v4/core/api.js +512 -0
  127. package/dist/vendor/zod/v4/core/checks.js +300 -0
  128. package/dist/vendor/zod/v4/core/core.js +109 -0
  129. package/dist/vendor/zod/v4/core/doc.js +35 -0
  130. package/dist/vendor/zod/v4/core/errors.js +118 -0
  131. package/dist/vendor/zod/v4/core/json-schema-processors.js +428 -0
  132. package/dist/vendor/zod/v4/core/memoizer.js +255 -0
  133. package/dist/vendor/zod/v4/core/parse.js +206 -0
  134. package/dist/vendor/zod/v4/core/regexes.js +73 -0
  135. package/dist/vendor/zod/v4/core/registries.js +48 -0
  136. package/dist/vendor/zod/v4/core/schemas.js +1378 -0
  137. package/dist/vendor/zod/v4/core/to-json-schema.js +448 -0
  138. package/dist/vendor/zod/v4/core/util.js +537 -0
  139. package/dist/vendor/zod/v4/core/versions.js +8 -0
  140. package/dist/vendor/zod/v4/locales/en.js +110 -0
  141. package/package.json +65 -4
@@ -0,0 +1,140 @@
1
+ import { isObject } from "../core/json.js";
2
+ import { M } from "../core/m.js";
3
+ import { MatrixError, errors } from "../core/errors.js";
4
+ import { procedure } from "../http/procedure.js";
5
+ //#region src/api/threadsubs.ts
6
+ const VERSIONS = ["unstable/io.element.msc4306"];
7
+ const notInThread = () => new MatrixError(400, "IO.ELEMENT.MSC4306.M_NOT_IN_THREAD", "Event is not in this thread");
8
+ const conflicting = () => new MatrixError(409, "IO.ELEMENT.MSC4306.M_CONFLICTING_UNSUBSCRIPTION", "The thread was unsubscribed after this event");
9
+ function key(userId, roomId, threadId) {
10
+ return [
11
+ {
12
+ field: "user_id",
13
+ value: userId
14
+ },
15
+ {
16
+ field: "room_id",
17
+ value: roomId
18
+ },
19
+ {
20
+ field: "thread_id",
21
+ value: threadId
22
+ }
23
+ ];
24
+ }
25
+ /** Whether the user is subscribed to a thread: true, false (explicitly unsubscribed or never subscribed). */
26
+ async function isSubscribed(hs, userId, roomId, threadId) {
27
+ return !!(await hs.db.findOne("thread_subscriptions", key(userId, roomId, threadId)))?.subscribed;
28
+ }
29
+ async function visibleEvent(ctx, userId, roomId, eventId) {
30
+ const ev = await ctx.hs.rooms.getEvent(eventId);
31
+ if (!ev || ev.pdu.room_id !== roomId) return null;
32
+ const [visible] = await ctx.hs.rooms.filterVisible(userId, roomId, [ev]);
33
+ return visible ?? null;
34
+ }
35
+ async function threadRoot(ctx, userId) {
36
+ const { roomId, threadId } = ctx.params;
37
+ const root = await visibleEvent(ctx, userId, roomId, threadId);
38
+ if (!root) throw errors.notFound("Unknown thread root");
39
+ return root;
40
+ }
41
+ function registerThreadSubscriptionRoutes(r) {
42
+ const path = "/rooms/:roomId/thread/:threadId/subscription";
43
+ r.client("GET", path, procedure({
44
+ auth: "user",
45
+ handler: async (ctx) => {
46
+ const s = ctx.session;
47
+ await threadRoot(ctx, s.userId);
48
+ const row = await ctx.hs.db.findOne("thread_subscriptions", key(s.userId, ctx.params.roomId, ctx.params.threadId));
49
+ if (!row?.subscribed) throw errors.notFound("Not subscribed to this thread");
50
+ return { automatic: !!row.automatic };
51
+ }
52
+ }), VERSIONS);
53
+ r.client("PUT", path, procedure({
54
+ auth: "user",
55
+ handler: async (ctx) => {
56
+ const s = ctx.session;
57
+ const hs = ctx.hs;
58
+ const { roomId, threadId } = ctx.params;
59
+ await threadRoot(ctx, s.userId);
60
+ const body = await ctx.json();
61
+ const cause = isObject(body) ? body.automatic : void 0;
62
+ if (cause !== void 0 && typeof cause !== "string") throw errors.badJson("automatic must be an event ID");
63
+ let causeStream = null;
64
+ if (typeof cause === "string") {
65
+ const ev = await visibleEvent(ctx, s.userId, roomId, cause);
66
+ const rel = ev?.pdu.content?.[M.RELATES_TO];
67
+ if (!ev || !isObject(rel) || rel.rel_type !== M.THREAD || rel.event_id !== threadId) throw notInThread();
68
+ causeStream = ev.stream;
69
+ }
70
+ await hs.cluster.lock(`threadsub:${s.userId}:${roomId}:${threadId}`, async () => {
71
+ const row = await hs.db.findOne("thread_subscriptions", key(s.userId, roomId, threadId));
72
+ if (causeStream !== null) {
73
+ if (row && row.unsubscribed_after !== null && causeStream <= row.unsubscribed_after) throw conflicting();
74
+ if (row?.subscribed) return;
75
+ } else if (row?.subscribed && !row.automatic) return;
76
+ await hs.streams.write((stream) => hs.db.upsert("thread_subscriptions", {
77
+ user_id: s.userId,
78
+ room_id: roomId,
79
+ thread_id: threadId,
80
+ subscribed: true,
81
+ automatic: causeStream !== null,
82
+ unsubscribed_after: row?.unsubscribed_after ?? null,
83
+ stream
84
+ }));
85
+ });
86
+ hs.notifier.notify([s.userId]);
87
+ return {};
88
+ }
89
+ }), VERSIONS);
90
+ r.client("DELETE", path, procedure({
91
+ auth: "user",
92
+ handler: async (ctx) => {
93
+ const s = ctx.session;
94
+ const hs = ctx.hs;
95
+ const { roomId, threadId } = ctx.params;
96
+ await threadRoot(ctx, s.userId);
97
+ await hs.cluster.lock(`threadsub:${s.userId}:${roomId}:${threadId}`, async () => {
98
+ if (!(await hs.db.findOne("thread_subscriptions", key(s.userId, roomId, threadId)))?.subscribed) return;
99
+ const position = await hs.streams.position();
100
+ await hs.streams.write((stream) => hs.db.upsert("thread_subscriptions", {
101
+ user_id: s.userId,
102
+ room_id: roomId,
103
+ thread_id: threadId,
104
+ subscribed: false,
105
+ automatic: false,
106
+ unsubscribed_after: position,
107
+ stream
108
+ }));
109
+ });
110
+ hs.notifier.notify([s.userId]);
111
+ return {};
112
+ }
113
+ }), VERSIONS);
114
+ }
115
+ /** MSC4308 sliding sync extension: subscription changes in (since, to]. */
116
+ async function threadSubscriptionsExtension(hs, userId, ext, since, to) {
117
+ const limit = Math.min(Math.max(Number(ext.limit ?? 100) || 100, 1), 1e3);
118
+ const where = [{
119
+ field: "user_id",
120
+ value: userId
121
+ }];
122
+ if (since !== null) where.push({
123
+ field: "stream",
124
+ operator: "gt",
125
+ value: since
126
+ });
127
+ const rows = (await hs.db.findMany("thread_subscriptions", { where })).filter((r) => r.stream <= to && (since !== null || r.subscribed)).sort((a, b) => b.stream - a.stream);
128
+ const out = {};
129
+ for (const row of rows.slice(0, limit)) {
130
+ const section = row.subscribed ? "subscribed" : "unsubscribed";
131
+ ((out[section] ??= {})[row.room_id] ??= {})[row.thread_id] = row.subscribed ? {
132
+ automatic: !!row.automatic,
133
+ bump_stamp: row.stream
134
+ } : { bump_stamp: row.stream };
135
+ }
136
+ if (rows.length > limit) out.prev_batch = String(rows[limit - 1].stream);
137
+ return out;
138
+ }
139
+ //#endregion
140
+ export { isSubscribed, registerThreadSubscriptionRoutes, threadSubscriptionsExtension };
@@ -0,0 +1,155 @@
1
+ import { M } from "../core/m.js";
2
+ import { MatrixError, errors } from "../core/errors.js";
3
+ import { canonicalAddress, isMedium } from "../core/threepid.js";
4
+ import { enum as _enum, string } from "../vendor/zod/v4/classic/schemas.js";
5
+ import { body, fail, lenient } from "../http/input.js";
6
+ import { procedure } from "../http/procedure.js";
7
+ import { requireUia } from "./uia.js";
8
+ //#region src/api/threepid.ts
9
+ const submitField = string(fail("M_MISSING_PARAM", "sid, client_secret and token are required"));
10
+ const submitBody = body({
11
+ sid: submitField,
12
+ client_secret: submitField,
13
+ token: submitField
14
+ });
15
+ const bindField = (name) => string(fail("M_MISSING_PARAM", `Missing ${name}`));
16
+ const bindBody = body({
17
+ client_secret: bindField("client_secret"),
18
+ id_access_token: bindField("id_access_token"),
19
+ id_server: bindField("id_server"),
20
+ sid: bindField("sid")
21
+ });
22
+ const threepidBody = body({
23
+ medium: _enum(["email", "msisdn"], fail("M_INVALID_PARAM", "Unsupported medium")),
24
+ address: string(fail("M_INVALID_PARAM", "Invalid address")),
25
+ id_server: string(fail("M_INVALID_PARAM", "id_server must be a string")).optional()
26
+ });
27
+ function notDelegated(ctx) {
28
+ if (ctx.hs.oauth) throw errors.unrecognized("Managed by the OAuth provider");
29
+ }
30
+ function registerThreepidRoutes(r) {
31
+ const requestToken = (purpose, medium) => async (ctx) => {
32
+ notDelegated(ctx);
33
+ await ctx.rateLimit(purpose === "register" ? "register" : "login");
34
+ return ctx.hs.threepids.requestToken(purpose, medium, ctx.input);
35
+ };
36
+ for (const medium of ["email", "msisdn"]) {
37
+ r.client("POST", `/register/${medium}/requestToken`, procedure({
38
+ input: body({}),
39
+ handler: requestToken("register", medium)
40
+ }));
41
+ r.client("POST", `/account/password/${medium}/requestToken`, procedure({
42
+ input: body({}),
43
+ handler: requestToken("password_reset", medium)
44
+ }));
45
+ r.client("POST", `/account/3pid/${medium}/requestToken`, procedure({
46
+ input: body({}),
47
+ handler: requestToken("add_threepid", medium)
48
+ }));
49
+ }
50
+ const submitPath = "/_matrix/client/unstable/threepid/submit_token";
51
+ r.get(submitPath, procedure({ handler: async (ctx) => {
52
+ const q = ctx.query;
53
+ let nextLink = null;
54
+ let message = "Your address has been validated. You can return to your Matrix client.";
55
+ let status = 200;
56
+ try {
57
+ nextLink = await ctx.hs.threepids.submitToken(q.get("sid") ?? "", q.get("client_secret") ?? "", q.get("token") ?? "");
58
+ } catch (err) {
59
+ message = err instanceof MatrixError ? `Validation failed: ${err.message}.` : "Validation failed.";
60
+ status = 400;
61
+ }
62
+ if (nextLink && status === 200) return Response.redirect(nextLink, 302);
63
+ return new Response(`<!doctype html><meta charset="utf-8"><title>${ctx.hs.serverName}</title><p>${message}</p>`, {
64
+ status,
65
+ headers: { "content-type": "text/html; charset=utf-8" }
66
+ });
67
+ } }));
68
+ r.post(submitPath, procedure({
69
+ input: submitBody,
70
+ handler: async (ctx) => {
71
+ const body = ctx.input;
72
+ await ctx.hs.threepids.submitToken(body.sid, body.client_secret, body.token);
73
+ return { success: true };
74
+ }
75
+ }));
76
+ r.client("GET", "/account/3pid", procedure({
77
+ auth: "user",
78
+ handler: async (ctx) => {
79
+ const s = ctx.session;
80
+ return { threepids: await ctx.hs.threepids.list(s.userId) };
81
+ }
82
+ }));
83
+ r.client("POST", "/account/3pid/add", procedure({
84
+ input: body({
85
+ sid: lenient(string()),
86
+ client_secret: lenient(string())
87
+ }),
88
+ handler: async (ctx) => {
89
+ notDelegated(ctx);
90
+ const s = await ctx.auth();
91
+ const body = ctx.input;
92
+ await requireUia(ctx.hs, body, [[M.LOGIN.PASSWORD]], s.userId);
93
+ const validated = await ctx.hs.threepids.validated({
94
+ sid: body.sid,
95
+ client_secret: body.client_secret
96
+ });
97
+ if (!validated) throw new MatrixError(400, "M_THREEPID_AUTH_FAILED", "The address has not been validated");
98
+ await ctx.hs.threepids.add(s.userId, validated);
99
+ return {};
100
+ }
101
+ }));
102
+ r.client("POST", "/account/3pid/bind", procedure({
103
+ auth: "user",
104
+ input: bindBody,
105
+ handler: async (ctx) => {
106
+ const s = ctx.session;
107
+ const body = ctx.input;
108
+ const res = await ctx.hs.identityServers.bind(body.id_server, body.id_access_token, body.sid, body.client_secret, s.userId);
109
+ if (res && isMedium(res.medium) && typeof res.address === "string") await ctx.hs.db.upsert("threepid_bindings", {
110
+ user_id: s.userId,
111
+ medium: res.medium,
112
+ address: res.address,
113
+ id_server: body.id_server
114
+ });
115
+ return {};
116
+ }
117
+ }));
118
+ const parseThreepid = (body) => {
119
+ const address = canonicalAddress(body.medium, body.address);
120
+ if (!address) throw errors.invalidParam("Invalid address");
121
+ return {
122
+ medium: body.medium,
123
+ address,
124
+ idServer: body.id_server
125
+ };
126
+ };
127
+ r.client("POST", "/account/3pid/delete", procedure({
128
+ input: threepidBody,
129
+ handler: async (ctx) => {
130
+ notDelegated(ctx);
131
+ const s = await ctx.auth();
132
+ const { medium, address, idServer } = parseThreepid(ctx.input);
133
+ const result = await ctx.hs.threepids.unbindAll(s.userId, medium, address, idServer);
134
+ await ctx.hs.threepids.remove(s.userId, medium, address);
135
+ return { id_server_unbind_result: result };
136
+ }
137
+ }));
138
+ r.client("POST", "/account/3pid/unbind", procedure({
139
+ auth: "user",
140
+ input: threepidBody,
141
+ handler: async (ctx) => {
142
+ const s = ctx.session;
143
+ const { medium, address, idServer } = parseThreepid(ctx.input);
144
+ return { id_server_unbind_result: await ctx.hs.threepids.unbindAll(s.userId, medium, address, idServer) };
145
+ }
146
+ }));
147
+ r.client("POST", "/account/3pid", procedure({
148
+ auth: "user",
149
+ handler: async () => {
150
+ throw errors.threepidDenied();
151
+ }
152
+ }));
153
+ }
154
+ //#endregion
155
+ export { registerThreepidRoutes };
@@ -0,0 +1,127 @@
1
+ import { isObject } from "../core/json.js";
2
+ import { randomString } from "../core/crypto.js";
3
+ import { M, UNSTABLE } from "../core/m.js";
4
+ import { MatrixError, errors } from "../core/errors.js";
5
+ //#region src/api/uia.ts
6
+ const UIA_TTL_MS = 6e5;
7
+ /**
8
+ * User-interactive authentication. Resolves when one of `flows` has been
9
+ * completed; otherwise throws the 401 response describing what is required.
10
+ * `userId` binds password stages to an already-authenticated user.
11
+ */
12
+ async function requireUia(hs, body, flows, userId) {
13
+ if (hs.oauth && flows.some((f) => f.includes(M.LOGIN.PASSWORD))) flows = [[M.OAUTH], [UNSTABLE.ORG.MATRIX.CROSS_SIGNING_RESET]];
14
+ const auth = isObject(body.auth) ? body.auth : null;
15
+ let sessionId = typeof auth?.session === "string" ? auth.session : void 0;
16
+ const stored = sessionId ? await hs.cluster.get(`uia:${sessionId}`) : null;
17
+ const session = {
18
+ completed: new Set(stored?.completed ?? []),
19
+ userId: stored ? stored.userId : userId,
20
+ threepids: stored?.threepids ?? []
21
+ };
22
+ if (!stored) sessionId = randomString(24);
23
+ const save = () => hs.cluster.set(`uia:${sessionId}`, {
24
+ completed: [...session.completed],
25
+ userId: session.userId,
26
+ threepids: session.threepids
27
+ }, UIA_TTL_MS);
28
+ const oauthUrl = hs.oauth?.options.accountManagementUrl ?? hs.oauth?.options.issuer;
29
+ const params = hs.oauth ? {
30
+ [M.OAUTH]: { url: oauthUrl },
31
+ [UNSTABLE.ORG.MATRIX.CROSS_SIGNING_RESET]: { url: oauthUrl }
32
+ } : {};
33
+ const challenge = (extra = {}) => new MatrixError(401, extra.errcode ? String(extra.errcode) : "M_FORBIDDEN", String(extra.error ?? "Authentication required"), {
34
+ flows: flows.map((stages) => ({ stages })),
35
+ params,
36
+ session: sessionId,
37
+ completed: [...session.completed],
38
+ ...extra
39
+ });
40
+ if (auth?.type === M.LOGIN.DUMMY && !auth.session && typeof body.username === "string" && !userId) {
41
+ if (await hs.cluster.get(`uia-register:${body.username.toLowerCase()}`)) throw challenge({
42
+ errcode: "M_FORBIDDEN",
43
+ error: "Missing session"
44
+ });
45
+ }
46
+ if (auth?.type) switch (auth.type) {
47
+ case M.LOGIN.DUMMY:
48
+ session.completed.add(M.LOGIN.DUMMY);
49
+ break;
50
+ case M.OAUTH:
51
+ case UNSTABLE.ORG.MATRIX.CROSS_SIGNING_RESET:
52
+ if (!hs.oauth) throw challenge({
53
+ errcode: "M_UNRECOGNIZED",
54
+ error: "OAuth is not enabled"
55
+ });
56
+ session.completed.add(auth.type);
57
+ break;
58
+ case M.LOGIN.REGISTRATION_TOKEN: {
59
+ const { registrationTokenValid } = await import("./account.js");
60
+ if (typeof auth.token !== "string" || !await registrationTokenValid(hs, auth.token)) throw challenge({
61
+ errcode: "M_FORBIDDEN",
62
+ error: "Invalid registration token"
63
+ });
64
+ session.completed.add(M.LOGIN.REGISTRATION_TOKEN);
65
+ break;
66
+ }
67
+ case M.LOGIN.PASSWORD: {
68
+ const identifier = isObject(auth.identifier) ? auth.identifier : {
69
+ type: M.ID.USER,
70
+ user: auth.user
71
+ };
72
+ const user = typeof identifier.user === "string" ? identifier.user : "";
73
+ const target = user.startsWith("@") ? user : `@${user.toLowerCase()}:${hs.serverName}`;
74
+ if (userId && target !== userId) throw errors.forbidden("Credentials do not match the authenticated user");
75
+ const row = await hs.db.findOne("users", [{
76
+ field: "user_id",
77
+ value: target
78
+ }]);
79
+ if (!(row && !row.deactivated && typeof auth.password === "string" && await hs.userAuth.checkPassword({
80
+ userId: target,
81
+ localpart: target.slice(1).split(":")[0],
82
+ password: auth.password,
83
+ storedHash: row.password_hash
84
+ }))) throw challenge({
85
+ errcode: "M_FORBIDDEN",
86
+ error: "Invalid password"
87
+ });
88
+ session.completed.add(M.LOGIN.PASSWORD);
89
+ break;
90
+ }
91
+ case M.LOGIN.EMAIL.IDENTITY:
92
+ case M.LOGIN.MSISDN: {
93
+ const validated = await hs.threepids.validated(auth.threepid_creds ?? auth.threepidCreds);
94
+ const medium = auth.type === M.LOGIN.EMAIL.IDENTITY ? "email" : "msisdn";
95
+ if (!validated || validated.medium !== medium) throw challenge({
96
+ errcode: "M_UNAUTHORIZED",
97
+ error: "The address has not been validated"
98
+ });
99
+ if (session.userId && await hs.threepids.userFor(validated.medium, validated.address) !== session.userId) throw challenge({
100
+ errcode: "M_FORBIDDEN",
101
+ error: "This address does not belong to your account"
102
+ });
103
+ session.threepids = [...session.threepids.filter((t) => t.medium !== medium), validated];
104
+ session.completed.add(auth.type);
105
+ break;
106
+ }
107
+ default: throw challenge({
108
+ errcode: "M_UNRECOGNIZED",
109
+ error: `Unsupported auth type ${auth.type}`
110
+ });
111
+ }
112
+ if (!flows.some((stages) => stages.every((s) => session.completed.has(s)))) {
113
+ await save();
114
+ if (!userId && typeof body.username === "string") await hs.cluster.set(`uia-register:${body.username.toLowerCase()}`, sessionId, UIA_TTL_MS);
115
+ if (auth?.type) throw challenge();
116
+ const e = challenge();
117
+ throw new MatrixError(401, "M_FORBIDDEN", "", {
118
+ ...e.extra,
119
+ errcode: void 0,
120
+ error: void 0
121
+ });
122
+ }
123
+ await hs.cluster.delete(`uia:${sessionId}`);
124
+ return { threepids: session.threepids };
125
+ }
126
+ //#endregion
127
+ export { requireUia };