matrix-js-sdk 43.0.0 → 44.0.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/CHANGELOG.md +28 -0
- package/lib/matrixrtc/CallMembership.d.ts +30 -25
- package/lib/matrixrtc/CallMembership.d.ts.map +1 -1
- package/lib/matrixrtc/CallMembership.js +91 -100
- package/lib/matrixrtc/CallMembership.js.map +1 -1
- package/lib/matrixrtc/EncryptionManager.d.ts +6 -4
- package/lib/matrixrtc/EncryptionManager.d.ts.map +1 -1
- package/lib/matrixrtc/EncryptionManager.js.map +1 -1
- package/lib/matrixrtc/IMembershipManager.d.ts +2 -15
- package/lib/matrixrtc/IMembershipManager.d.ts.map +1 -1
- package/lib/matrixrtc/IMembershipManager.js.map +1 -1
- package/lib/matrixrtc/LivekitTransport.d.ts +36 -7
- package/lib/matrixrtc/LivekitTransport.d.ts.map +1 -1
- package/lib/matrixrtc/LivekitTransport.js +29 -2
- package/lib/matrixrtc/LivekitTransport.js.map +1 -1
- package/lib/matrixrtc/MatrixRTCSession.d.ts +12 -51
- package/lib/matrixrtc/MatrixRTCSession.d.ts.map +1 -1
- package/lib/matrixrtc/MatrixRTCSession.js +10 -66
- package/lib/matrixrtc/MatrixRTCSession.js.map +1 -1
- package/lib/matrixrtc/MembershipManager.d.ts +5 -10
- package/lib/matrixrtc/MembershipManager.d.ts.map +1 -1
- package/lib/matrixrtc/MembershipManager.js +25 -44
- package/lib/matrixrtc/MembershipManager.js.map +1 -1
- package/lib/matrixrtc/RTCEncryptionManager.d.ts +8 -8
- package/lib/matrixrtc/RTCEncryptionManager.d.ts.map +1 -1
- package/lib/matrixrtc/RTCEncryptionManager.js +30 -22
- package/lib/matrixrtc/RTCEncryptionManager.js.map +1 -1
- package/lib/matrixrtc/ToDeviceKeyTransport.js +7 -8
- package/lib/matrixrtc/ToDeviceKeyTransport.js.map +1 -1
- package/lib/matrixrtc/membershipData/rtc.d.ts +8 -13
- package/lib/matrixrtc/membershipData/rtc.d.ts.map +1 -1
- package/lib/matrixrtc/membershipData/rtc.js +2 -11
- package/lib/matrixrtc/membershipData/rtc.js.map +1 -1
- package/lib/matrixrtc/membershipData/session.d.ts +6 -2
- package/lib/matrixrtc/membershipData/session.d.ts.map +1 -1
- package/lib/matrixrtc/membershipData/session.js +3 -0
- package/lib/matrixrtc/membershipData/session.js.map +1 -1
- package/lib/matrixrtc/types.d.ts +5 -0
- package/lib/matrixrtc/types.d.ts.map +1 -1
- package/lib/matrixrtc/types.js +5 -0
- package/lib/matrixrtc/types.js.map +1 -1
- package/lib/models/event-timeline-set.d.ts +9 -2
- package/lib/models/event-timeline-set.d.ts.map +1 -1
- package/lib/models/event-timeline-set.js +8 -5
- package/lib/models/event-timeline-set.js.map +1 -1
- package/lib/models/room-sticky-events.d.ts +17 -2
- package/lib/models/room-sticky-events.d.ts.map +1 -1
- package/lib/models/room-sticky-events.js +88 -47
- package/lib/models/room-sticky-events.js.map +1 -1
- package/lib/models/room.d.ts +1 -1
- package/lib/models/room.d.ts.map +1 -1
- package/lib/models/room.js +8 -2
- package/lib/models/room.js.map +1 -1
- package/lib/models/thread.d.ts.map +1 -1
- package/lib/models/thread.js +23 -2
- package/lib/models/thread.js.map +1 -1
- package/lib/rendezvous/MSC4108SignInWithQR.d.ts +3 -3
- package/lib/rendezvous/MSC4108SignInWithQR.d.ts.map +1 -1
- package/lib/rendezvous/MSC4108SignInWithQR.js.map +1 -1
- package/lib/rendezvous/SignInWithQRFlow.d.ts +95 -0
- package/lib/rendezvous/SignInWithQRFlow.d.ts.map +1 -0
- package/lib/rendezvous/SignInWithQRFlow.js +3 -0
- package/lib/rendezvous/SignInWithQRFlow.js.map +1 -0
- package/lib/rendezvous/index.d.ts +1 -0
- package/lib/rendezvous/index.d.ts.map +1 -1
- package/lib/rendezvous/index.js.map +1 -1
- package/lib/rust-crypto/index.js +5 -1
- package/lib/rust-crypto/index.js.map +1 -1
- package/package.json +3 -3
- package/src/matrixrtc/CallMembership.ts +85 -95
- package/src/matrixrtc/EncryptionManager.ts +6 -4
- package/src/matrixrtc/IMembershipManager.ts +2 -15
- package/src/matrixrtc/LivekitTransport.ts +58 -9
- package/src/matrixrtc/MatrixRTCSession.ts +21 -80
- package/src/matrixrtc/MembershipManager.ts +23 -40
- package/src/matrixrtc/RTCEncryptionManager.ts +51 -39
- package/src/matrixrtc/ToDeviceKeyTransport.ts +7 -7
- package/src/matrixrtc/membershipData/rtc.ts +9 -23
- package/src/matrixrtc/membershipData/session.ts +14 -2
- package/src/matrixrtc/types.ts +6 -0
- package/src/models/event-timeline-set.ts +19 -4
- package/src/models/room-sticky-events.ts +92 -58
- package/src/models/room.ts +8 -2
- package/src/models/thread.ts +25 -3
- package/src/rendezvous/MSC4108SignInWithQR.ts +3 -3
- package/src/rendezvous/SignInWithQRFlow.ts +117 -0
- package/src/rendezvous/index.ts +1 -0
- package/src/rust-crypto/index.ts +5 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"thread.d.ts","sourceRoot":"","sources":["../../src/models/thread.ts"],"names":[],"mappings":"AAgBA,OAAO,EAAE,KAAK,YAAY,EAAE,oBAAoB,EAAE,MAAM,cAAc,CAAC;AAGvE,OAAO,EAAmC,WAAW,EAAoB,MAAM,YAAY,CAAC;AAC5F,OAAO,EAAa,aAAa,EAAE,MAAM,qBAAqB,CAAC;AAC/D,OAAO,EAAE,gBAAgB,EAAE,KAAK,0BAA0B,EAAE,MAAM,yBAAyB,CAAC;AAC5F,OAAO,EAAE,KAAK,qBAAqB,EAAE,KAAK,IAAI,EAAE,SAAS,EAAE,MAAM,WAAW,CAAC;AAC7E,OAAO,EAAE,KAAK,SAAS,EAAE,MAAM,iBAAiB,CAAC;AACjD,OAAO,EAAE,+BAA+B,EAAE,MAAM,uBAAuB,CAAC;AAExE,OAAO,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAChD,OAAO,EAAE,KAAK,sBAAsB,EAAE,KAAK,OAAO,EAAe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;CACJ;AAYD,eAAO,MAAM,yBAAyB,sFAGrC,CAAC;AACF,eAAO,MAAM,2BAA2B,sFAGvC,CAAC;AACF,eAAO,MAAM,oBAAoB,kEAAuE,CAAC;AAEzG,oBAAY,gBAAgB;IACxB,EAAE,IAAA;IACF,GAAG,IAAA;CACN;AAED,wBAAgB,wBAAwB,CAAC,IAAI,EAAE,gBAAgB,GAAG,IAAI,GAAG,KAAK,GAAG,cAAc,CAO9F"}
|
package/lib/models/thread.js
CHANGED
|
@@ -51,6 +51,27 @@ export function determineFeatureSupport(stable, unstable) {
|
|
|
51
51
|
return FeatureSupport.None;
|
|
52
52
|
}
|
|
53
53
|
}
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* Cap on how many threads fetch their initial events at the same time. Each fetch is a (recursive) `/relations`
|
|
57
|
+
* request, and opening a thread list creates every thread in the room at once; without a cap a room with dozens
|
|
58
|
+
* of threads fires dozens of concurrent heavy requests, which can starve everything else the homeserver worker is doing.
|
|
59
|
+
*/
|
|
60
|
+
const MAX_CONCURRENT_INITIAL_FETCHES = 3;
|
|
61
|
+
let runningInitialFetches = 0;
|
|
62
|
+
const waitingInitialFetches = [];
|
|
63
|
+
async function withInitialFetchSlot(fn) {
|
|
64
|
+
if (runningInitialFetches >= MAX_CONCURRENT_INITIAL_FETCHES) {
|
|
65
|
+
await new Promise(resolve => waitingInitialFetches.push(resolve));
|
|
66
|
+
}
|
|
67
|
+
runningInitialFetches++;
|
|
68
|
+
try {
|
|
69
|
+
return await fn();
|
|
70
|
+
} finally {
|
|
71
|
+
runningInitialFetches--;
|
|
72
|
+
waitingInitialFetches.shift()?.();
|
|
73
|
+
}
|
|
74
|
+
}
|
|
54
75
|
export class Thread extends ReadReceipt {
|
|
55
76
|
constructor(id, rootEvent, opts) {
|
|
56
77
|
super();
|
|
@@ -573,9 +594,9 @@ export class Thread extends ReadReceipt {
|
|
|
573
594
|
this.timelineSet.addEventsToTimeline([this.rootEvent], true, false, this.liveTimeline, null);
|
|
574
595
|
this.liveTimeline.setPaginationToken(null, Direction.Backward);
|
|
575
596
|
} else {
|
|
576
|
-
this.initalEventFetchProm = this.client.paginateEventTimeline(this.liveTimeline, {
|
|
597
|
+
this.initalEventFetchProm = withInitialFetchSlot(() => this.client.paginateEventTimeline(this.liveTimeline, {
|
|
577
598
|
backwards: true
|
|
578
|
-
});
|
|
599
|
+
}));
|
|
579
600
|
await this.initalEventFetchProm;
|
|
580
601
|
}
|
|
581
602
|
// We have now fetched the initial events, so set the flag. We need to do this before
|
package/lib/models/thread.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"thread.js","names":[],"sources":["../../src/models/thread.ts"],"sourcesContent":["/*\nCopyright 2021 - 2023 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { type MatrixClient, PendingEventOrdering } from \"../client.ts\";\nimport { TypedReEmitter } from \"../ReEmitter.ts\";\nimport { RelationType } from \"../@types/event.ts\";\nimport { type IThreadBundledRelationship, MatrixEvent, MatrixEventEvent } from \"./event.ts\";\nimport { Direction, EventTimeline } from \"./event-timeline.ts\";\nimport { EventTimelineSet, type EventTimelineSetHandlerMap } from \"./event-timeline-set.ts\";\nimport { type NotificationCountType, type Room, RoomEvent } from \"./room.ts\";\nimport { type RoomState } from \"./room-state.ts\";\nimport { ServerControlledNamespacedValue } from \"../NamespacedValue.ts\";\nimport { logger } from \"../logger.ts\";\nimport { ReadReceipt } from \"./read-receipt.ts\";\nimport { type CachedReceiptStructure, type Receipt, ReceiptType } from \"../@types/read_receipts.ts\";\nimport { Feature, ServerSupport } from \"../feature.ts\";\n\nexport enum ThreadEvent {\n New = \"Thread.new\",\n Update = \"Thread.update\",\n NewReply = \"Thread.newReply\",\n ViewThread = \"Thread.viewThread\",\n Delete = \"Thread.delete\",\n}\n\nexport type ThreadEmittedEvents = Exclude<ThreadEvent, ThreadEvent.New> | RoomEvent.Timeline | RoomEvent.TimelineReset;\n\nexport type ThreadEventHandlerMap = {\n [ThreadEvent.Update]: (thread: Thread) => void;\n [ThreadEvent.NewReply]: (thread: Thread, event: MatrixEvent) => void;\n [ThreadEvent.ViewThread]: () => void;\n [ThreadEvent.Delete]: (thread: Thread) => void;\n} & EventTimelineSetHandlerMap;\n\ninterface IThreadOpts {\n room: Room;\n client: MatrixClient;\n pendingEventOrdering?: PendingEventOrdering;\n receipts?: CachedReceiptStructure[];\n}\n\nexport enum FeatureSupport {\n None = 0,\n Experimental = 1,\n Stable = 2,\n}\n\nexport function determineFeatureSupport(stable: boolean, unstable: boolean): FeatureSupport {\n if (stable) {\n return FeatureSupport.Stable;\n } else if (unstable) {\n return FeatureSupport.Experimental;\n } else {\n return FeatureSupport.None;\n }\n}\n\nexport class Thread extends ReadReceipt<ThreadEmittedEvents, ThreadEventHandlerMap> {\n public static hasServerSideSupport = FeatureSupport.None;\n public static hasServerSideListSupport = FeatureSupport.None;\n public static hasServerSideFwdPaginationSupport = FeatureSupport.None;\n\n /**\n * A reference to all the events ID at the bottom of the threads\n */\n public readonly timelineSet: EventTimelineSet;\n\n private _currentUserParticipated = false;\n\n private reEmitter: TypedReEmitter<ThreadEmittedEvents, ThreadEventHandlerMap>;\n\n /**\n * The last event in this thread, if we don't yet have this in the timeline.\n *\n * When we run {@link processRootEvent} (which I think happens during the\n * setting-up of the thread), we set this to the event pointed to by the\n * server in `latest_event` [1] that came through with the thread root.\n *\n * [1]: https://spec.matrix.org/v1.8/client-server-api/#server-side-aggregation-of-mthread-relationships\n *\n * Later, when we have populated the timeline, this is set to undefined, so\n * that methods like {@link replyToEvent} fall through to use lastReply,\n * which looks in the timeline for the latest event that is a \"thread reply\"\n * i.e. directly refers to the thread root with an m.thread relation.\n *\n * So it looks like this is only really relevant when initialEventsFetched\n * is false, because as soon as the initial events have been fetched, we\n * should have a proper chunk of timeline from the pagination fetch.\n *\n * If all replies in this thread are redacted, this is set to the root\n * event. I'm not clear what the meaning of this is, since usually after the\n * initial events have been fetched, lastEvent should be undefined.\n * In fact, the whole usage inside onRedaction looks suspect - it may be\n * that we were thinking lastEvent always refers to the actual last event,\n * but it only does so before initialEventsFetched becomes true.\n *\n * The usage of lastEvent inside {@link onEcho} looks suspicious, since I'd\n * think we probably mean {@link replyToEvent} there - we are trying not to\n * echo a duplicate event, and we probably want that behaviour even after\n * initialEventsFetched has become true.\n *\n * -- andyb\n */\n private lastEvent: MatrixEvent | undefined;\n\n private replyCount = 0;\n private lastPendingEvent: MatrixEvent | undefined;\n private pendingReplyCount = 0;\n\n public readonly room: Room;\n public readonly client: MatrixClient;\n private readonly pendingEventOrdering: PendingEventOrdering;\n private processRootEventPromise?: Promise<void>;\n\n /**\n * Whether or not we need to fetch the initial set of events for the thread. We can\n * only do this if the server has support for it, so if it doesn't we just pretend\n * that we've already fetched them.\n */\n public initialEventsFetched = !Thread.hasServerSideSupport;\n private initalEventFetchProm: Promise<boolean> | undefined;\n private preInitEventTargets = new Map<string, MatrixEvent>();\n private preInitObserverState = { active: true };\n\n /**\n * An array of events to add to the timeline once the thread has been initialised\n * with server suppport.\n */\n public replayEvents: MatrixEvent[] | null = [];\n\n public constructor(\n public readonly id: string,\n public rootEvent: MatrixEvent | undefined,\n opts: IThreadOpts,\n ) {\n super();\n\n // each Event in the thread adds a reemitter, so we could hit the listener limit.\n this.setMaxListeners(1000);\n\n if (!opts?.room) {\n // Logging/debugging for https://github.com/vector-im/element-web/issues/22141\n // Hope is that we end up with a more obvious stack trace.\n throw new Error(\"element-web#22141: A thread requires a room in order to function\");\n }\n\n this.room = opts.room;\n this.client = opts.client;\n this.pendingEventOrdering = opts.pendingEventOrdering ?? PendingEventOrdering.Chronological;\n this.timelineSet = new EventTimelineSet(\n this.room,\n {\n timelineSupport: true,\n pendingEvents: true,\n },\n this.client,\n this,\n );\n this.reEmitter = new TypedReEmitter(this);\n\n this.reEmitter.reEmit(this.timelineSet, [RoomEvent.Timeline, RoomEvent.TimelineReset]);\n this.once(ThreadEvent.Delete, () => {\n this.preInitObserverState.active = false;\n });\n\n this.room.on(MatrixEventEvent.BeforeRedaction, this.onBeforeRedaction);\n this.room.on(RoomEvent.Redaction, this.onRedaction);\n this.room.on(RoomEvent.LocalEchoUpdated, this.onLocalEcho);\n this.room.on(RoomEvent.TimelineReset, this.onTimelineReset);\n this.timelineSet.on(RoomEvent.Timeline, this.onTimelineEvent);\n\n this.processReceipts(opts.receipts);\n\n // even if this thread is thought to be originating from this client, we initialise it as we may be in a\n // gappy sync and a thread around this event may already exist.\n this.updateThreadMetadata();\n this.setEventMetadata(this.rootEvent);\n }\n\n private onTimelineReset = async (): Promise<void> => {\n // We hit a gappy sync, ask the server for an update\n await this.processRootEventPromise;\n this.processRootEventPromise = undefined;\n };\n\n private async fetchRootEvent(): Promise<void> {\n // Always fetch the root event, even if we already have it, so we can get the latest\n // state (via unsigned).\n try {\n const eventData = await this.client.fetchRoomEvent(this.roomId, this.id);\n const mapper = this.client.getEventMapper();\n this.rootEvent = mapper(eventData); // will merge with existing event object if such is known\n } catch (e) {\n logger.error(\"Failed to fetch thread root to construct thread with\", e);\n }\n await this.processEvent(this.rootEvent);\n }\n\n public static setServerSideSupport(status: FeatureSupport): void {\n Thread.hasServerSideSupport = status;\n // XXX: This global latching behaviour is really unexpected and means that you can't undo when moving to a server without support\n if (status !== FeatureSupport.Stable) {\n FILTER_RELATED_BY_SENDERS.setPreferUnstable(true);\n FILTER_RELATED_BY_REL_TYPES.setPreferUnstable(true);\n THREAD_RELATION_TYPE.setPreferUnstable(true);\n }\n }\n\n public static setServerSideListSupport(status: FeatureSupport): void {\n Thread.hasServerSideListSupport = status;\n }\n\n public static setServerSideFwdPaginationSupport(status: FeatureSupport): void {\n Thread.hasServerSideFwdPaginationSupport = status;\n }\n\n private onBeforeRedaction = (event: MatrixEvent, redaction: MatrixEvent): void => {\n if (\n event?.isRelation(THREAD_RELATION_TYPE.name) &&\n this.room.eventShouldLiveIn(event).threadId === this.id &&\n event.getId() !== this.id && // the root event isn't counted in the length so ignore this redaction\n !redaction.status // only respect it when it succeeds\n ) {\n this.replyCount--;\n this.updatePendingReplyCount();\n this.emit(ThreadEvent.Update, this);\n }\n };\n\n private onRedaction = async (event: MatrixEvent, room: Room, threadRootId?: string): Promise<void> => {\n if (threadRootId !== this.id) return; // ignore redactions for other timelines\n if (this.replyCount <= 0) {\n for (const threadEvent of this.timeline) {\n this.clearEventMetadata(threadEvent);\n }\n this.lastEvent = this.rootEvent;\n this._currentUserParticipated = false;\n this.emit(ThreadEvent.Delete, this);\n } else {\n if (this.lastEvent?.getId() === event.getAssociatedId()) {\n // XXX: If our last event got redacted we query the server for the last event once again\n await this.processRootEventPromise;\n this.processRootEventPromise = undefined;\n }\n await this.updateThreadMetadata();\n }\n };\n\n private onTimelineEvent = (\n event: MatrixEvent,\n room: Room | undefined,\n toStartOfTimeline: boolean | undefined,\n ): void => {\n // Add a synthesized receipt when paginating forward in the timeline\n if (!toStartOfTimeline) {\n const sender = event.getSender();\n if (sender && room && this.shouldSendLocalEchoReceipt(sender, event)) {\n room.addLocalEchoReceipt(sender, event, ReceiptType.Read);\n }\n if (event.getId() !== this.id && event.isRelation(THREAD_RELATION_TYPE.name)) {\n this.replyCount++;\n }\n }\n this.onEcho(event, toStartOfTimeline ?? false);\n };\n\n private shouldSendLocalEchoReceipt(sender: string, event: MatrixEvent): boolean {\n const recursionSupport = this.client.canSupport.get(Feature.RelationsRecursion) ?? ServerSupport.Unsupported;\n\n if (recursionSupport === ServerSupport.Unsupported) {\n // Normally we add a local receipt, but if we don't have\n // recursion support, then events may arrive out of order, so we\n // only create a receipt if it's after our existing receipt.\n const oldReceiptEventId = this.getReadReceiptForUserId(sender)?.eventId;\n if (oldReceiptEventId) {\n const receiptEvent = this.findEventById(oldReceiptEventId);\n if (receiptEvent && receiptEvent.getTs() > event.getTs()) {\n return false;\n }\n }\n }\n\n return true;\n }\n\n private onLocalEcho = (event: MatrixEvent): void => {\n this.onEcho(event, false);\n };\n\n private onEcho = async (event: MatrixEvent, toStartOfTimeline: boolean): Promise<void> => {\n if (event.threadRootId !== this.id) return; // ignore echoes for other timelines\n if (this.lastEvent === event) return; // ignore duplicate events\n await this.updateThreadMetadata();\n if (!event.isRelation(THREAD_RELATION_TYPE.name)) return; // don't send a new reply event for reactions or edits\n if (toStartOfTimeline) return; // ignore messages added to the start of the timeline\n // Clear the lastEvent and instead start tracking locally using lastReply\n this.lastEvent = undefined;\n this.emit(ThreadEvent.NewReply, this, event);\n };\n\n public get roomState(): RoomState {\n return this.room.getLiveTimeline().getState(EventTimeline.FORWARDS)!;\n }\n\n private addEventToTimeline(event: MatrixEvent, toStartOfTimeline: boolean): void {\n if (!this.findEventById(event.getId()!)) {\n this.timelineSet.addEventToTimeline(event, this.liveTimeline, {\n toStartOfTimeline,\n fromCache: false,\n roomState: this.roomState,\n addToState: false,\n });\n }\n }\n\n /**\n * TEMPORARY. Only call this when MSC3981 is not available, and we have some\n * late-arriving events to insert, because we recursively found them as part\n * of populating a thread. When we have MSC3981 we won't need it, because\n * they will all be supplied by the homeserver in one request, and they will\n * already be in the right order in that response.\n * This is a copy of addEventToTimeline above, modified to call\n * insertEventIntoTimeline so this event is inserted into our best guess of\n * the right place based on timestamp. (We should be using Sync Order but we\n * don't have it.)\n *\n * @internal\n */\n public insertEventIntoTimeline(event: MatrixEvent): void {\n const eventId = event.getId();\n if (!eventId) {\n return;\n }\n // If the event is already in this thread, bail out\n if (this.findEventById(eventId)) {\n return;\n }\n this.timelineSet.insertEventIntoTimeline(event, this.liveTimeline, this.roomState, false);\n }\n\n public addEvents(events: MatrixEvent[], toStartOfTimeline: boolean): void {\n events.forEach((ev) => this.addEvent(ev, toStartOfTimeline, false));\n this.updateThreadMetadata();\n }\n\n /**\n * Add an event to the thread and updates\n * the tail/root references if needed\n * Will fire \"Thread.update\"\n * @param event - The event to add\n * @param toStartOfTimeline - whether the event is being added\n * to the start (and not the end) of the timeline.\n * @param emit - whether to emit the Update event if the thread was updated or not.\n */\n public addEvent(event: MatrixEvent, toStartOfTimeline: boolean, emit = true): void {\n // Modify this event to point at our room's state, and mark its thread\n // as this.\n this.setEventMetadata(event);\n\n // The bundled `current_user_participated` flag from the server lags behind local activity,\n // so relying on it alone drops just-sent replies out of \"participated\" views until the next\n // root event bundle refresh. Latch it as soon as the current user authors a thread reply,\n // matching the server's participated semantics: an m.thread relation, not a reaction or edit.\n if (event.getSender() === this.client.getUserId() && event.isRelation(THREAD_RELATION_TYPE.name)) {\n this._currentUserParticipated = true;\n }\n\n const eventId = event.getId();\n if (\n !this.initialEventsFetched &&\n eventId &&\n !event.isRelation(RelationType.Annotation) &&\n !event.isRelation(RelationType.Replace)\n ) {\n this.preInitEventTargets.set(eventId, event);\n }\n\n // Decide whether this event is going to be added at the end of the timeline.\n const lastReply = this.lastReply();\n const isNewestReply = !lastReply || event.localTimestamp >= lastReply.localTimestamp;\n\n if (!Thread.hasServerSideSupport) {\n // When there's no server-side support, just add it to the end of the timeline.\n this.addEventToTimeline(event, toStartOfTimeline);\n this.client.decryptEventIfNeeded(event);\n } else if (event.isRelation(RelationType.Annotation) || event.isRelation(RelationType.Replace)) {\n this.addRelatedThreadEvent(event, toStartOfTimeline);\n return;\n } else if (!toStartOfTimeline && isNewestReply) {\n // When we've asked for the event to be added to the end,\n // and this event belongs at the end, add it.\n this.addEventToTimeline(event, false);\n this.fetchEditsWhereNeeded(event);\n } else {\n // Otherwise, we should add it, but we suspect it is out of order.\n // This may be because we've just created the thread object and are\n // still fetching events, in which case add it where we think is sensible\n // and it will be removed and replaced with the events from the pagination\n // request once that completes.\n if (toStartOfTimeline) {\n // If we're adding at the start of the timeline, it doesn't\n // matter that it's out of order.\n this.addEventToTimeline(event, toStartOfTimeline);\n } else {\n // We think this event might be out of order, because isNewestReply\n // is false (otherwise we would have gone into the earlier if\n // clause), so try to insert it in the right place based on\n // timestamp.\n this.insertEventIntoTimeline(event);\n }\n }\n\n if (\n event.getId() !== this.id &&\n event.isRelation(THREAD_RELATION_TYPE.name) &&\n !toStartOfTimeline &&\n isNewestReply\n ) {\n // Clear the last event as we have the latest end of the timeline\n this.lastEvent = undefined;\n }\n\n if (emit) {\n this.emit(ThreadEvent.NewReply, this, event);\n this.updateThreadMetadata();\n }\n }\n\n private addRelatedThreadEvent(event: MatrixEvent, toStartOfTimeline: boolean): void {\n // If this event is not a direct member of the thread, but is a\n // reference to something that is, then we have two cases:\n\n if (!this.initialEventsFetched) {\n // Case 1: we haven't yet fetched events from the server. In\n // this case, when we do, the events we get back might only be\n // the first-order ones, so this event (which is second-order -\n // a reference to something directly in the thread) needs to be\n // kept so we can replay it when the first-order ones turn up.\n\n /**\n * A thread can be fully discovered via a single sync response\n * And when that's the case we still ask the server to do an initialisation\n * as it's the safest to ensure we have everything.\n * However when we are in that scenario we might loose annotation or edits\n *\n * This fix keeps a reference to those events and replay them once the thread\n * has been initialised properly.\n */\n this.replayEvents?.push(event);\n\n // Aggregate annotations immediately to keep reaction counts visible.\n if (event.isRelation(RelationType.Annotation)) {\n this.timelineSet.relations?.aggregateChildEvent(event, this.timelineSet);\n }\n\n // Edits can also be aggregated immediately when their target is already\n // known. If it is not known yet, replay still handles them after pagination.\n if (event.isRelation(RelationType.Replace)) {\n const targetEventId = event.getRelation()?.event_id;\n const targetEvent = targetEventId ? this.findPreInitTargetEvent(targetEventId) : undefined;\n if (targetEvent && targetEventId) {\n const weakThread = new WeakRef(this);\n const observerState = this.preInitObserverState;\n const eventId = event.getId();\n void this.timelineSet.relations\n .aggregateChildEvent(event, this.timelineSet, targetEvent)\n .then(() => {\n const thread = weakThread.deref();\n if (!thread || !observerState.active) return;\n const effectiveTarget = thread.findPreInitTargetEvent(targetEventId);\n if (effectiveTarget?.replacingEvent()?.getId() === eventId) {\n thread.emit(ThreadEvent.Update, thread);\n }\n })\n .catch((error) => logger.error(\"Failed to aggregate pre-initialization thread edit: \", error));\n }\n }\n } else {\n // Case 2: this is happening later, and we have a timeline. In\n // this case, these events might be out-of order.\n //\n // Specifically, if the server doesn't support recursion, so we\n // only get these events through sync, they might be coming\n // later than the first-order ones, so we insert them based on\n // timestamp (despite the problems with this documented in\n // #3325).\n //\n // If the server does support recursion, we should have got all\n // the interspersed events from the server when we fetched the\n // initial events, so if they are coming via sync they should be\n // the latest ones, so we can add them as normal.\n //\n // (Note that both insertEventIntoTimeline and addEventToTimeline\n // do nothing if we have seen this event before.)\n\n const recursionSupport =\n this.client.canSupport.get(Feature.RelationsRecursion) ?? ServerSupport.Unsupported;\n\n if (recursionSupport === ServerSupport.Unsupported) {\n this.insertEventIntoTimeline(event);\n } else {\n this.addEventToTimeline(event, toStartOfTimeline);\n }\n // Aggregation is handled by EventTimelineSet when inserting/adding.\n }\n }\n\n private findPreInitTargetEvent(eventId: string): MatrixEvent | undefined {\n return (\n this.timelineSet.findEventById(eventId) ??\n this.room.findEventById(eventId) ??\n this.preInitEventTargets.get(eventId) ??\n (this.lastEvent?.getId() === eventId ? this.lastEvent : undefined)\n );\n }\n\n public async processEvent(event: MatrixEvent | null | undefined): Promise<void> {\n if (event) {\n this.setEventMetadata(event);\n await this.fetchEditsWhereNeeded(event);\n }\n }\n\n /**\n * Processes the receipts that were caught during initial sync\n * When clients become aware of a thread, they try to retrieve those read receipts\n * and apply them to the current thread\n * @param receipts - A collection of the receipts cached from initial sync\n */\n private processReceipts(receipts: CachedReceiptStructure[] = []): void {\n for (const { eventId, receiptType, userId, receipt, synthetic } of receipts) {\n this.addReceiptToStructure(eventId, receiptType as ReceiptType, userId, receipt, synthetic);\n }\n }\n\n private getRootEventBundledRelationship(rootEvent = this.rootEvent): IThreadBundledRelationship | undefined {\n return rootEvent?.getServerAggregatedRelation<IThreadBundledRelationship>(THREAD_RELATION_TYPE.name);\n }\n\n private async processRootEvent(): Promise<void> {\n const bundledRelationship = this.getRootEventBundledRelationship();\n if (Thread.hasServerSideSupport && bundledRelationship) {\n this.replyCount = bundledRelationship.count;\n this._currentUserParticipated = !!bundledRelationship.current_user_participated;\n\n const mapper = this.client.getEventMapper();\n // re-insert roomId\n this.lastEvent = mapper({\n ...bundledRelationship.latest_event,\n room_id: this.roomId,\n });\n this.updatePendingReplyCount();\n await this.processEvent(this.lastEvent);\n }\n }\n\n private updatePendingReplyCount(): void {\n const unfilteredPendingEvents =\n this.pendingEventOrdering === PendingEventOrdering.Detached ? this.room.getPendingEvents() : this.events;\n const pendingEvents = unfilteredPendingEvents.filter(\n (ev) =>\n ev.threadRootId === this.id &&\n ev.isRelation(THREAD_RELATION_TYPE.name) &&\n ev.status !== null &&\n ev.getId() !== this.lastEvent?.getId(),\n );\n this.lastPendingEvent = pendingEvents.length ? pendingEvents[pendingEvents.length - 1] : undefined;\n this.pendingReplyCount = pendingEvents.length;\n }\n\n /**\n * Reset the live timeline of all timelineSets, and start new ones.\n *\n * <p>This is used when /sync returns a 'limited' timeline. 'Limited' means that there's a gap between the messages\n * /sync returned, and the last known message in our timeline. In such a case, our live timeline isn't live anymore\n * and has to be replaced by a new one. To make sure we can continue paginating our timelines correctly, we have to\n * set new pagination tokens on the old and the new timeline.\n *\n * @param backPaginationToken - token for back-paginating the new timeline\n * @param forwardPaginationToken - token for forward-paginating the old live timeline,\n * if absent or null, all timelines are reset, removing old ones (including the previous live\n * timeline which would otherwise be unable to paginate forwards without this token).\n * Removing just the old live timeline whilst preserving previous ones is not supported.\n */\n public async resetLiveTimeline(\n backPaginationToken?: string | null,\n forwardPaginationToken?: string | null,\n ): Promise<void> {\n const oldLive = this.liveTimeline;\n this.timelineSet.resetLiveTimeline(backPaginationToken ?? undefined, forwardPaginationToken ?? undefined);\n const newLive = this.liveTimeline;\n\n // FIXME: Remove the following as soon as https://github.com/matrix-org/synapse/issues/14830 is resolved.\n //\n // The pagination API for thread timelines currently can't handle the type of pagination tokens returned by sync\n //\n // To make this work anyway, we'll have to transform them into one of the types that the API can handle.\n // One option is passing the tokens to /messages, which can handle sync tokens, and returns the right format.\n // /messages does not return new tokens on requests with a limit of 0.\n // This means our timelines might overlap a slight bit, but that's not an issue, as we deduplicate messages\n // anyway.\n\n let newBackward: string | undefined;\n let oldForward: string | undefined;\n if (backPaginationToken) {\n const res = await this.client.createMessagesRequest(this.roomId, backPaginationToken, 1, Direction.Forward);\n newBackward = res.end;\n }\n if (forwardPaginationToken) {\n const res = await this.client.createMessagesRequest(\n this.roomId,\n forwardPaginationToken,\n 1,\n Direction.Backward,\n );\n oldForward = res.start;\n }\n // Only replace the token if we don't have paginated away from this position already. This situation doesn't\n // occur today, but if the above issue is resolved, we'd have to go down this path.\n if (forwardPaginationToken && oldLive.getPaginationToken(Direction.Forward) === forwardPaginationToken) {\n oldLive.setPaginationToken(oldForward ?? null, Direction.Forward);\n }\n if (backPaginationToken && newLive.getPaginationToken(Direction.Backward) === backPaginationToken) {\n newLive.setPaginationToken(newBackward ?? null, Direction.Backward);\n }\n }\n\n private async updateThreadFromRootEvent(): Promise<void> {\n if (Thread.hasServerSideSupport) {\n // Ensure we show *something* as soon as possible, we'll update it as soon as we get better data, but we\n // don't want the thread preview to be empty if we can avoid it\n if (!this.initialEventsFetched && !this.lastEvent) {\n await this.processRootEvent();\n }\n await this.fetchRootEvent();\n }\n await this.processRootEvent();\n }\n\n private async updateThreadMetadata(): Promise<void> {\n this.updatePendingReplyCount();\n\n if (!this.processRootEventPromise) {\n // We only want to do this once otherwise we end up rolling back to the last unsigned summary we have for the thread\n this.processRootEventPromise = this.updateThreadFromRootEvent();\n }\n await this.processRootEventPromise;\n\n if (!this.initialEventsFetched) {\n if (this.initalEventFetchProm) {\n await this.initalEventFetchProm;\n } else {\n // fetch initial events to allow proper pagination\n try {\n // clear out any events that were added before the pagination request\n // completed (eg. from sync). They'll be replaced by those from the pagination.\n // Really, we should do this after the pagination request completes, but\n // paginateEventTimeline does the request and adds the events in one go, so\n // this would need a refactor in order to do. It's therefore possible there's\n // a remaining race where an event comes in while the pagination request is\n // happening.\n this.timelineSet.resetLiveTimeline();\n // if the thread has regular events, this will just load the last reply.\n // if the thread is newly created, this will load the root event.\n if (this.replyCount === 0 && this.rootEvent) {\n this.timelineSet.addEventsToTimeline([this.rootEvent], true, false, this.liveTimeline, null);\n this.liveTimeline.setPaginationToken(null, Direction.Backward);\n } else {\n this.initalEventFetchProm = this.client.paginateEventTimeline(this.liveTimeline, {\n backwards: true,\n });\n await this.initalEventFetchProm;\n }\n // We have now fetched the initial events, so set the flag. We need to do this before\n // we actually add the events, so `this.addEvents` knows that it can now safely add\n // them rather than buffer them in the pending event list. The main thing is that this\n // must remain false while the async fetch happens, so we don't try to add events before\n // the pagination has finished. The important thing is that we're not await-ing anything\n // else between setting this and adding events, so no races.\n this.initialEventsFetched = true;\n for (const event of this.replayEvents!) {\n this.addEvent(event, false);\n }\n this.replayEvents = null;\n this.preInitEventTargets.clear();\n // just to make sure that, if we've created a timeline window for this thread before the thread itself\n // existed (e.g. when creating a new thread), we'll make sure the panel is force refreshed correctly.\n this.emit(RoomEvent.TimelineReset, this.room, this.timelineSet, true);\n } catch (e) {\n logger.error(\"Failed to load start of newly created thread: \", e);\n this.initialEventsFetched = false;\n }\n }\n }\n\n this.emit(ThreadEvent.Update, this);\n }\n\n // XXX: Workaround for https://github.com/matrix-org/matrix-spec-proposals/pull/2676/files#r827240084\n private async fetchEditsWhereNeeded(...events: MatrixEvent[]): Promise<unknown> {\n const recursionSupport = this.client.canSupport.get(Feature.RelationsRecursion) ?? ServerSupport.Unsupported;\n if (recursionSupport === ServerSupport.Unsupported) {\n return Promise.all(\n events.filter(isAnEncryptedThreadMessage).map(async (event: MatrixEvent) => {\n try {\n const relations = await this.client.relations(\n this.roomId,\n event.getId()!,\n RelationType.Replace,\n event.getType(),\n {\n limit: 1,\n },\n );\n if (relations.events.length) {\n const editEvent = relations.events[0];\n event.makeReplaced(editEvent);\n this.insertEventIntoTimeline(editEvent);\n }\n } catch (e) {\n logger.error(\"Failed to load edits for encrypted thread event\", e);\n }\n }),\n );\n }\n }\n\n public setEventMetadata(event: MatrixEvent | null | undefined): void {\n if (event) {\n EventTimeline.setEventMetadata(event, this.roomState, false);\n event.setThread(this);\n }\n }\n\n public clearEventMetadata(event: MatrixEvent | null | undefined): void {\n if (event) {\n event.setThread(undefined);\n delete event.event?.unsigned?.[\"m.relations\"]?.[THREAD_RELATION_TYPE.name];\n }\n }\n\n /**\n * Finds an event by ID in the current thread\n */\n public findEventById(eventId: string): MatrixEvent | undefined {\n return this.timelineSet.findEventById(eventId);\n }\n\n /**\n * Return last reply to the thread, if known.\n */\n public lastReply(\n matches: (ev: MatrixEvent) => boolean = (ev): boolean => ev.isRelation(THREAD_RELATION_TYPE.name),\n ): MatrixEvent | null {\n for (let i = this.timeline.length - 1; i >= 0; i--) {\n const event = this.timeline[i];\n if (matches(event)) {\n return event;\n }\n }\n return null;\n }\n\n public get roomId(): string {\n return this.room.roomId;\n }\n\n /**\n * The number of messages in the thread\n * Only count rel_type=m.thread as we want to\n * exclude annotations from that number\n */\n public get length(): number {\n return this.replyCount + this.pendingReplyCount;\n }\n\n /**\n * A getter for the last event of the thread.\n * This might be a synthesized event, if so, it will not emit any events to listeners.\n */\n public get replyToEvent(): MatrixEvent | null {\n return this.lastPendingEvent ?? this.lastEvent ?? this.lastReply();\n }\n\n /**\n * The live event timeline for this thread.\n * @deprecated Present for backwards compatibility.\n * Use this.events instead\n * @returns The live event timeline for this thread.\n */\n public get timeline(): MatrixEvent[] {\n return this.events;\n }\n\n public get events(): MatrixEvent[] {\n return this.liveTimeline.getEvents();\n }\n\n public has(eventId: string): boolean {\n return this.timelineSet.findEventById(eventId) instanceof MatrixEvent;\n }\n\n public get hasCurrentUserParticipated(): boolean {\n return this._currentUserParticipated;\n }\n\n public get liveTimeline(): EventTimeline {\n return this.timelineSet.getLiveTimeline();\n }\n\n public getUnfilteredTimelineSet(): EventTimelineSet {\n return this.timelineSet;\n }\n\n public addReceipt(event: MatrixEvent, synthetic: boolean): void {\n throw new Error(\"Unsupported function on the thread model\");\n }\n\n /**\n * Get the ID of the event that a given user has read up to within this thread,\n * or null if we have received no read receipt (at all) from them.\n * @param userId - The user ID to get read receipt event ID for\n * @param ignoreSynthesized - If true, return only receipts that have been\n * sent by the server, not implicit ones generated\n * by the JS SDK.\n * @returns ID of the latest event that the given user has read, or null.\n */\n public getEventReadUpTo(userId: string, ignoreSynthesized?: boolean): string | null {\n // TODO: we think the implementation here is not right. Here is a sketch\n // of the right answer:\n //\n // for event in timeline.events.reversed():\n // if room.hasUserReadEvent(event):\n // return event\n // return null\n //\n // If this is too slow, we might be able to improve it by trying walking\n // forward from the threaded receipt in this thread. We could alternate\n // between backwards-from-front and forwards-from-threaded-receipt to\n // improve our chances of hitting the right answer sooner.\n //\n // Either way, it's still fundamentally slow because we have to walk\n // events.\n //\n // We also might just want to limit the time we spend on this by giving\n // up after, say, 100 events.\n //\n // --- andyb\n\n const isCurrentUser = userId === this.client.getUserId();\n const lastReply = this.timeline[this.timeline.length - 1];\n if (isCurrentUser && lastReply) {\n // If the last activity in a thread is prior to the first threaded read receipt\n // sent in the room (suggesting that it was sent before the user started\n // using a client that supported threaded read receipts), we want to\n // consider this thread as read.\n const beforeFirstThreadedReceipt = lastReply.getTs() < this.room.getOldestThreadedReceiptTs();\n const lastReplyId = lastReply.getId();\n // Some unsent events do not have an ID, we do not want to consider them read\n if (beforeFirstThreadedReceipt && lastReplyId) {\n return lastReplyId;\n }\n }\n\n const readUpToId = super.getEventReadUpTo(userId, ignoreSynthesized);\n\n // Check whether the unthreaded read receipt for that user is more recent\n // than the read receipt inside that thread.\n if (lastReply) {\n const unthreadedReceipt = this.room.getLastUnthreadedReceiptFor(userId);\n if (!unthreadedReceipt) {\n return readUpToId;\n }\n\n for (let i = this.timeline?.length - 1; i >= 0; --i) {\n const ev = this.timeline[i];\n // If we encounter the `readUpToId` we do not need to look further\n // there is no \"more recent\" unthreaded read receipt\n if (ev.getId() === readUpToId) return readUpToId;\n\n // Inspecting events from most recent to oldest, we're checking\n // whether an unthreaded read receipt is more recent that the current event.\n // We usually prefer relying on the order of the DAG but in this scenario\n // it is not possible and we have to rely on timestamp\n if (ev.getTs() < unthreadedReceipt.ts) return ev.getId() ?? readUpToId;\n }\n }\n\n return readUpToId;\n }\n\n /**\n * Determine if the given user has read a particular event.\n *\n * It is invalid to call this method with an event that is not part of this thread.\n *\n * This is not a definitive check as it only checks the events that have been\n * loaded client-side at the time of execution.\n * @param userId - The user ID to check the read state of.\n * @param eventId - The event ID to check if the user read.\n * @returns True if the user has read the event, false otherwise.\n */\n public hasUserReadEvent(userId: string, eventId: string): boolean {\n if (userId === this.client.getUserId()) {\n // Consider an event read if it's part of a thread that is before the\n // first threaded receipt sent in that room. It is likely that it is\n // part of a thread that was created before MSC3771 was implemented.\n // Or before the last unthreaded receipt for the logged in user\n const beforeFirstThreadedReceipt =\n (this.lastReply()?.getTs() ?? 0) < this.room.getOldestThreadedReceiptTs();\n const unthreadedReceiptTs = this.room.getLastUnthreadedReceiptFor(userId)?.ts ?? 0;\n const beforeLastUnthreadedReceipt = (this?.lastReply()?.getTs() ?? 0) < unthreadedReceiptTs;\n if (beforeFirstThreadedReceipt || beforeLastUnthreadedReceipt) {\n return true;\n }\n }\n\n return this.room.hasUserReadEvent(userId, eventId);\n }\n\n public setUnread(type: NotificationCountType, count: number): void {\n return this.room.setThreadUnreadNotificationCount(this.id, type, count);\n }\n\n /**\n * Returns the most recent unthreaded receipt for a given user\n * @param userId - the MxID of the User\n * @returns an unthreaded Receipt. Can be undefined if receipts have been disabled\n * or a user chooses to use private read receipts (or we have simply not received\n * a receipt from this user yet).\n */\n public getLastUnthreadedReceiptFor(userId: string): Receipt | undefined {\n return this.room.getLastUnthreadedReceiptFor(userId);\n }\n}\n\n/**\n * Decide whether an event deserves to have its potential edits fetched.\n *\n * @returns true if this event is encrypted and is a message that is part of a\n * thread - either inside it, or a root.\n */\nfunction isAnEncryptedThreadMessage(event: MatrixEvent): boolean {\n return event.isEncrypted() && (event.isRelation(THREAD_RELATION_TYPE.name) || event.isThreadRoot);\n}\n\nexport const FILTER_RELATED_BY_SENDERS = new ServerControlledNamespacedValue(\n \"related_by_senders\",\n \"io.element.relation_senders\",\n);\nexport const FILTER_RELATED_BY_REL_TYPES = new ServerControlledNamespacedValue(\n \"related_by_rel_types\",\n \"io.element.relation_types\",\n);\nexport const THREAD_RELATION_TYPE = new ServerControlledNamespacedValue(\"m.thread\", \"io.element.thread\");\n\nexport enum ThreadFilterType {\n My,\n All,\n}\n\nexport function threadFilterTypeToFilter(type: ThreadFilterType | null): \"all\" | \"participated\" {\n switch (type) {\n case ThreadFilterType.My:\n return \"participated\";\n default:\n return \"all\";\n }\n}\n"],"mappings":";;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA,SAA4B,oBAAoB,QAAQ,cAAc;AACtE,SAAS,cAAc,QAAQ,iBAAiB;AAChD,SAAS,YAAY,QAAQ,oBAAoB;AACjD,SAA0C,WAAW,EAAE,gBAAgB,QAAQ,YAAY;AAC3F,SAAS,SAAS,EAAE,aAAa,QAAQ,qBAAqB;AAC9D,SAAS,gBAAgB,QAAyC,yBAAyB;AAC3F,SAAgD,SAAS,QAAQ,WAAW;AAE5E,SAAS,+BAA+B,QAAQ,uBAAuB;AACvE,SAAS,MAAM,QAAQ,cAAc;AACrC,SAAS,WAAW,QAAQ,mBAAmB;AAC/C,SAAoD,WAAW,QAAQ,4BAA4B;AACnG,SAAS,OAAO,EAAE,aAAa,QAAQ,eAAe;AAEtD,WAAY,WAAW,0BAAX,WAAW;EAAX,WAAW;EAAX,WAAW;EAAX,WAAW;EAAX,WAAW;EAAX,WAAW;EAAA,OAAX,WAAW;AAAA;AAwBvB,WAAY,cAAc,0BAAd,cAAc;EAAd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,gBAAgB,CAAhB,gBAAgB;EAAA,OAAhB,gBAAgB;AAAA;AAK5B,OAAO,SAAS,wBAAwB,CAAC,IAA6B,EAA0B;EAC5F,QAAQ,IAAI;IACR,KAAK,gBAAgB,CAAC,EAAE;MACpB,OAAO,cAAc;IACzB;MACI,OAAO,KAAK;EACpB;AACJ","ignoreList":[]}
|
|
1
|
+
{"version":3,"file":"thread.js","names":[],"sources":["../../src/models/thread.ts"],"sourcesContent":["/*\nCopyright 2021 - 2023 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { type MatrixClient, PendingEventOrdering } from \"../client.ts\";\nimport { TypedReEmitter } from \"../ReEmitter.ts\";\nimport { RelationType } from \"../@types/event.ts\";\nimport { type IThreadBundledRelationship, MatrixEvent, MatrixEventEvent } from \"./event.ts\";\nimport { Direction, EventTimeline } from \"./event-timeline.ts\";\nimport { EventTimelineSet, type EventTimelineSetHandlerMap } from \"./event-timeline-set.ts\";\nimport { type NotificationCountType, type Room, RoomEvent } from \"./room.ts\";\nimport { type RoomState } from \"./room-state.ts\";\nimport { ServerControlledNamespacedValue } from \"../NamespacedValue.ts\";\nimport { logger } from \"../logger.ts\";\nimport { ReadReceipt } from \"./read-receipt.ts\";\nimport { type CachedReceiptStructure, type Receipt, ReceiptType } from \"../@types/read_receipts.ts\";\nimport { Feature, ServerSupport } from \"../feature.ts\";\n\nexport enum ThreadEvent {\n New = \"Thread.new\",\n Update = \"Thread.update\",\n NewReply = \"Thread.newReply\",\n ViewThread = \"Thread.viewThread\",\n Delete = \"Thread.delete\",\n}\n\nexport type ThreadEmittedEvents = Exclude<ThreadEvent, ThreadEvent.New> | RoomEvent.Timeline | RoomEvent.TimelineReset;\n\nexport type ThreadEventHandlerMap = {\n [ThreadEvent.Update]: (thread: Thread) => void;\n [ThreadEvent.NewReply]: (thread: Thread, event: MatrixEvent) => void;\n [ThreadEvent.ViewThread]: () => void;\n [ThreadEvent.Delete]: (thread: Thread) => void;\n} & EventTimelineSetHandlerMap;\n\ninterface IThreadOpts {\n room: Room;\n client: MatrixClient;\n pendingEventOrdering?: PendingEventOrdering;\n receipts?: CachedReceiptStructure[];\n}\n\nexport enum FeatureSupport {\n None = 0,\n Experimental = 1,\n Stable = 2,\n}\n\nexport function determineFeatureSupport(stable: boolean, unstable: boolean): FeatureSupport {\n if (stable) {\n return FeatureSupport.Stable;\n } else if (unstable) {\n return FeatureSupport.Experimental;\n } else {\n return FeatureSupport.None;\n }\n}\n\n/**\n * Cap on how many threads fetch their initial events at the same time. Each fetch is a (recursive) `/relations`\n * request, and opening a thread list creates every thread in the room at once; without a cap a room with dozens\n * of threads fires dozens of concurrent heavy requests, which can starve everything else the homeserver worker is doing.\n */\nconst MAX_CONCURRENT_INITIAL_FETCHES = 3;\nlet runningInitialFetches = 0;\nconst waitingInitialFetches: (() => void)[] = [];\n\nasync function withInitialFetchSlot<T>(fn: () => Promise<T>): Promise<T> {\n if (runningInitialFetches >= MAX_CONCURRENT_INITIAL_FETCHES) {\n await new Promise<void>((resolve) => waitingInitialFetches.push(resolve));\n }\n runningInitialFetches++;\n try {\n return await fn();\n } finally {\n runningInitialFetches--;\n waitingInitialFetches.shift()?.();\n }\n}\n\nexport class Thread extends ReadReceipt<ThreadEmittedEvents, ThreadEventHandlerMap> {\n public static hasServerSideSupport = FeatureSupport.None;\n public static hasServerSideListSupport = FeatureSupport.None;\n public static hasServerSideFwdPaginationSupport = FeatureSupport.None;\n\n /**\n * A reference to all the events ID at the bottom of the threads\n */\n public readonly timelineSet: EventTimelineSet;\n\n private _currentUserParticipated = false;\n\n private reEmitter: TypedReEmitter<ThreadEmittedEvents, ThreadEventHandlerMap>;\n\n /**\n * The last event in this thread, if we don't yet have this in the timeline.\n *\n * When we run {@link processRootEvent} (which I think happens during the\n * setting-up of the thread), we set this to the event pointed to by the\n * server in `latest_event` [1] that came through with the thread root.\n *\n * [1]: https://spec.matrix.org/v1.8/client-server-api/#server-side-aggregation-of-mthread-relationships\n *\n * Later, when we have populated the timeline, this is set to undefined, so\n * that methods like {@link replyToEvent} fall through to use lastReply,\n * which looks in the timeline for the latest event that is a \"thread reply\"\n * i.e. directly refers to the thread root with an m.thread relation.\n *\n * So it looks like this is only really relevant when initialEventsFetched\n * is false, because as soon as the initial events have been fetched, we\n * should have a proper chunk of timeline from the pagination fetch.\n *\n * If all replies in this thread are redacted, this is set to the root\n * event. I'm not clear what the meaning of this is, since usually after the\n * initial events have been fetched, lastEvent should be undefined.\n * In fact, the whole usage inside onRedaction looks suspect - it may be\n * that we were thinking lastEvent always refers to the actual last event,\n * but it only does so before initialEventsFetched becomes true.\n *\n * The usage of lastEvent inside {@link onEcho} looks suspicious, since I'd\n * think we probably mean {@link replyToEvent} there - we are trying not to\n * echo a duplicate event, and we probably want that behaviour even after\n * initialEventsFetched has become true.\n *\n * -- andyb\n */\n private lastEvent: MatrixEvent | undefined;\n\n private replyCount = 0;\n private lastPendingEvent: MatrixEvent | undefined;\n private pendingReplyCount = 0;\n\n public readonly room: Room;\n public readonly client: MatrixClient;\n private readonly pendingEventOrdering: PendingEventOrdering;\n private processRootEventPromise?: Promise<void>;\n\n /**\n * Whether or not we need to fetch the initial set of events for the thread. We can\n * only do this if the server has support for it, so if it doesn't we just pretend\n * that we've already fetched them.\n */\n public initialEventsFetched = !Thread.hasServerSideSupport;\n private initalEventFetchProm: Promise<boolean> | undefined;\n private preInitEventTargets = new Map<string, MatrixEvent>();\n private preInitObserverState = { active: true };\n\n /**\n * An array of events to add to the timeline once the thread has been initialised\n * with server suppport.\n */\n public replayEvents: MatrixEvent[] | null = [];\n\n public constructor(\n public readonly id: string,\n public rootEvent: MatrixEvent | undefined,\n opts: IThreadOpts,\n ) {\n super();\n\n // each Event in the thread adds a reemitter, so we could hit the listener limit.\n this.setMaxListeners(1000);\n\n if (!opts?.room) {\n // Logging/debugging for https://github.com/vector-im/element-web/issues/22141\n // Hope is that we end up with a more obvious stack trace.\n throw new Error(\"element-web#22141: A thread requires a room in order to function\");\n }\n\n this.room = opts.room;\n this.client = opts.client;\n this.pendingEventOrdering = opts.pendingEventOrdering ?? PendingEventOrdering.Chronological;\n this.timelineSet = new EventTimelineSet(\n this.room,\n {\n timelineSupport: true,\n pendingEvents: true,\n },\n this.client,\n this,\n );\n this.reEmitter = new TypedReEmitter(this);\n\n this.reEmitter.reEmit(this.timelineSet, [RoomEvent.Timeline, RoomEvent.TimelineReset]);\n this.once(ThreadEvent.Delete, () => {\n this.preInitObserverState.active = false;\n });\n\n this.room.on(MatrixEventEvent.BeforeRedaction, this.onBeforeRedaction);\n this.room.on(RoomEvent.Redaction, this.onRedaction);\n this.room.on(RoomEvent.LocalEchoUpdated, this.onLocalEcho);\n this.room.on(RoomEvent.TimelineReset, this.onTimelineReset);\n this.timelineSet.on(RoomEvent.Timeline, this.onTimelineEvent);\n\n this.processReceipts(opts.receipts);\n\n // even if this thread is thought to be originating from this client, we initialise it as we may be in a\n // gappy sync and a thread around this event may already exist.\n this.updateThreadMetadata();\n this.setEventMetadata(this.rootEvent);\n }\n\n private onTimelineReset = async (): Promise<void> => {\n // We hit a gappy sync, ask the server for an update\n await this.processRootEventPromise;\n this.processRootEventPromise = undefined;\n };\n\n private async fetchRootEvent(): Promise<void> {\n // Always fetch the root event, even if we already have it, so we can get the latest\n // state (via unsigned).\n try {\n const eventData = await this.client.fetchRoomEvent(this.roomId, this.id);\n const mapper = this.client.getEventMapper();\n this.rootEvent = mapper(eventData); // will merge with existing event object if such is known\n } catch (e) {\n logger.error(\"Failed to fetch thread root to construct thread with\", e);\n }\n await this.processEvent(this.rootEvent);\n }\n\n public static setServerSideSupport(status: FeatureSupport): void {\n Thread.hasServerSideSupport = status;\n // XXX: This global latching behaviour is really unexpected and means that you can't undo when moving to a server without support\n if (status !== FeatureSupport.Stable) {\n FILTER_RELATED_BY_SENDERS.setPreferUnstable(true);\n FILTER_RELATED_BY_REL_TYPES.setPreferUnstable(true);\n THREAD_RELATION_TYPE.setPreferUnstable(true);\n }\n }\n\n public static setServerSideListSupport(status: FeatureSupport): void {\n Thread.hasServerSideListSupport = status;\n }\n\n public static setServerSideFwdPaginationSupport(status: FeatureSupport): void {\n Thread.hasServerSideFwdPaginationSupport = status;\n }\n\n private onBeforeRedaction = (event: MatrixEvent, redaction: MatrixEvent): void => {\n if (\n event?.isRelation(THREAD_RELATION_TYPE.name) &&\n this.room.eventShouldLiveIn(event).threadId === this.id &&\n event.getId() !== this.id && // the root event isn't counted in the length so ignore this redaction\n !redaction.status // only respect it when it succeeds\n ) {\n this.replyCount--;\n this.updatePendingReplyCount();\n this.emit(ThreadEvent.Update, this);\n }\n };\n\n private onRedaction = async (event: MatrixEvent, room: Room, threadRootId?: string): Promise<void> => {\n if (threadRootId !== this.id) return; // ignore redactions for other timelines\n if (this.replyCount <= 0) {\n for (const threadEvent of this.timeline) {\n this.clearEventMetadata(threadEvent);\n }\n this.lastEvent = this.rootEvent;\n this._currentUserParticipated = false;\n this.emit(ThreadEvent.Delete, this);\n } else {\n if (this.lastEvent?.getId() === event.getAssociatedId()) {\n // XXX: If our last event got redacted we query the server for the last event once again\n await this.processRootEventPromise;\n this.processRootEventPromise = undefined;\n }\n await this.updateThreadMetadata();\n }\n };\n\n private onTimelineEvent = (\n event: MatrixEvent,\n room: Room | undefined,\n toStartOfTimeline: boolean | undefined,\n ): void => {\n // Add a synthesized receipt when paginating forward in the timeline\n if (!toStartOfTimeline) {\n const sender = event.getSender();\n if (sender && room && this.shouldSendLocalEchoReceipt(sender, event)) {\n room.addLocalEchoReceipt(sender, event, ReceiptType.Read);\n }\n if (event.getId() !== this.id && event.isRelation(THREAD_RELATION_TYPE.name)) {\n this.replyCount++;\n }\n }\n this.onEcho(event, toStartOfTimeline ?? false);\n };\n\n private shouldSendLocalEchoReceipt(sender: string, event: MatrixEvent): boolean {\n const recursionSupport = this.client.canSupport.get(Feature.RelationsRecursion) ?? ServerSupport.Unsupported;\n\n if (recursionSupport === ServerSupport.Unsupported) {\n // Normally we add a local receipt, but if we don't have\n // recursion support, then events may arrive out of order, so we\n // only create a receipt if it's after our existing receipt.\n const oldReceiptEventId = this.getReadReceiptForUserId(sender)?.eventId;\n if (oldReceiptEventId) {\n const receiptEvent = this.findEventById(oldReceiptEventId);\n if (receiptEvent && receiptEvent.getTs() > event.getTs()) {\n return false;\n }\n }\n }\n\n return true;\n }\n\n private onLocalEcho = (event: MatrixEvent): void => {\n this.onEcho(event, false);\n };\n\n private onEcho = async (event: MatrixEvent, toStartOfTimeline: boolean): Promise<void> => {\n if (event.threadRootId !== this.id) return; // ignore echoes for other timelines\n if (this.lastEvent === event) return; // ignore duplicate events\n await this.updateThreadMetadata();\n if (!event.isRelation(THREAD_RELATION_TYPE.name)) return; // don't send a new reply event for reactions or edits\n if (toStartOfTimeline) return; // ignore messages added to the start of the timeline\n // Clear the lastEvent and instead start tracking locally using lastReply\n this.lastEvent = undefined;\n this.emit(ThreadEvent.NewReply, this, event);\n };\n\n public get roomState(): RoomState {\n return this.room.getLiveTimeline().getState(EventTimeline.FORWARDS)!;\n }\n\n private addEventToTimeline(event: MatrixEvent, toStartOfTimeline: boolean): void {\n if (!this.findEventById(event.getId()!)) {\n this.timelineSet.addEventToTimeline(event, this.liveTimeline, {\n toStartOfTimeline,\n fromCache: false,\n roomState: this.roomState,\n addToState: false,\n });\n }\n }\n\n /**\n * TEMPORARY. Only call this when MSC3981 is not available, and we have some\n * late-arriving events to insert, because we recursively found them as part\n * of populating a thread. When we have MSC3981 we won't need it, because\n * they will all be supplied by the homeserver in one request, and they will\n * already be in the right order in that response.\n * This is a copy of addEventToTimeline above, modified to call\n * insertEventIntoTimeline so this event is inserted into our best guess of\n * the right place based on timestamp. (We should be using Sync Order but we\n * don't have it.)\n *\n * @internal\n */\n public insertEventIntoTimeline(event: MatrixEvent): void {\n const eventId = event.getId();\n if (!eventId) {\n return;\n }\n // If the event is already in this thread, bail out\n if (this.findEventById(eventId)) {\n return;\n }\n this.timelineSet.insertEventIntoTimeline(event, this.liveTimeline, this.roomState, false);\n }\n\n public addEvents(events: MatrixEvent[], toStartOfTimeline: boolean): void {\n events.forEach((ev) => this.addEvent(ev, toStartOfTimeline, false));\n this.updateThreadMetadata();\n }\n\n /**\n * Add an event to the thread and updates\n * the tail/root references if needed\n * Will fire \"Thread.update\"\n * @param event - The event to add\n * @param toStartOfTimeline - whether the event is being added\n * to the start (and not the end) of the timeline.\n * @param emit - whether to emit the Update event if the thread was updated or not.\n */\n public addEvent(event: MatrixEvent, toStartOfTimeline: boolean, emit = true): void {\n // Modify this event to point at our room's state, and mark its thread\n // as this.\n this.setEventMetadata(event);\n\n // The bundled `current_user_participated` flag from the server lags behind local activity,\n // so relying on it alone drops just-sent replies out of \"participated\" views until the next\n // root event bundle refresh. Latch it as soon as the current user authors a thread reply,\n // matching the server's participated semantics: an m.thread relation, not a reaction or edit.\n if (event.getSender() === this.client.getUserId() && event.isRelation(THREAD_RELATION_TYPE.name)) {\n this._currentUserParticipated = true;\n }\n\n const eventId = event.getId();\n if (\n !this.initialEventsFetched &&\n eventId &&\n !event.isRelation(RelationType.Annotation) &&\n !event.isRelation(RelationType.Replace)\n ) {\n this.preInitEventTargets.set(eventId, event);\n }\n\n // Decide whether this event is going to be added at the end of the timeline.\n const lastReply = this.lastReply();\n const isNewestReply = !lastReply || event.localTimestamp >= lastReply.localTimestamp;\n\n if (!Thread.hasServerSideSupport) {\n // When there's no server-side support, just add it to the end of the timeline.\n this.addEventToTimeline(event, toStartOfTimeline);\n this.client.decryptEventIfNeeded(event);\n } else if (event.isRelation(RelationType.Annotation) || event.isRelation(RelationType.Replace)) {\n this.addRelatedThreadEvent(event, toStartOfTimeline);\n return;\n } else if (!toStartOfTimeline && isNewestReply) {\n // When we've asked for the event to be added to the end,\n // and this event belongs at the end, add it.\n this.addEventToTimeline(event, false);\n this.fetchEditsWhereNeeded(event);\n } else {\n // Otherwise, we should add it, but we suspect it is out of order.\n // This may be because we've just created the thread object and are\n // still fetching events, in which case add it where we think is sensible\n // and it will be removed and replaced with the events from the pagination\n // request once that completes.\n if (toStartOfTimeline) {\n // If we're adding at the start of the timeline, it doesn't\n // matter that it's out of order.\n this.addEventToTimeline(event, toStartOfTimeline);\n } else {\n // We think this event might be out of order, because isNewestReply\n // is false (otherwise we would have gone into the earlier if\n // clause), so try to insert it in the right place based on\n // timestamp.\n this.insertEventIntoTimeline(event);\n }\n }\n\n if (\n event.getId() !== this.id &&\n event.isRelation(THREAD_RELATION_TYPE.name) &&\n !toStartOfTimeline &&\n isNewestReply\n ) {\n // Clear the last event as we have the latest end of the timeline\n this.lastEvent = undefined;\n }\n\n if (emit) {\n this.emit(ThreadEvent.NewReply, this, event);\n this.updateThreadMetadata();\n }\n }\n\n private addRelatedThreadEvent(event: MatrixEvent, toStartOfTimeline: boolean): void {\n // If this event is not a direct member of the thread, but is a\n // reference to something that is, then we have two cases:\n\n if (!this.initialEventsFetched) {\n // Case 1: we haven't yet fetched events from the server. In\n // this case, when we do, the events we get back might only be\n // the first-order ones, so this event (which is second-order -\n // a reference to something directly in the thread) needs to be\n // kept so we can replay it when the first-order ones turn up.\n\n /**\n * A thread can be fully discovered via a single sync response\n * And when that's the case we still ask the server to do an initialisation\n * as it's the safest to ensure we have everything.\n * However when we are in that scenario we might loose annotation or edits\n *\n * This fix keeps a reference to those events and replay them once the thread\n * has been initialised properly.\n */\n this.replayEvents?.push(event);\n\n // Aggregate annotations immediately to keep reaction counts visible.\n if (event.isRelation(RelationType.Annotation)) {\n this.timelineSet.relations?.aggregateChildEvent(event, this.timelineSet);\n }\n\n // Edits can also be aggregated immediately when their target is already\n // known. If it is not known yet, replay still handles them after pagination.\n if (event.isRelation(RelationType.Replace)) {\n const targetEventId = event.getRelation()?.event_id;\n const targetEvent = targetEventId ? this.findPreInitTargetEvent(targetEventId) : undefined;\n if (targetEvent && targetEventId) {\n const weakThread = new WeakRef(this);\n const observerState = this.preInitObserverState;\n const eventId = event.getId();\n void this.timelineSet.relations\n .aggregateChildEvent(event, this.timelineSet, targetEvent)\n .then(() => {\n const thread = weakThread.deref();\n if (!thread || !observerState.active) return;\n const effectiveTarget = thread.findPreInitTargetEvent(targetEventId);\n if (effectiveTarget?.replacingEvent()?.getId() === eventId) {\n thread.emit(ThreadEvent.Update, thread);\n }\n })\n .catch((error) => logger.error(\"Failed to aggregate pre-initialization thread edit: \", error));\n }\n }\n } else {\n // Case 2: this is happening later, and we have a timeline. In\n // this case, these events might be out-of order.\n //\n // Specifically, if the server doesn't support recursion, so we\n // only get these events through sync, they might be coming\n // later than the first-order ones, so we insert them based on\n // timestamp (despite the problems with this documented in\n // #3325).\n //\n // If the server does support recursion, we should have got all\n // the interspersed events from the server when we fetched the\n // initial events, so if they are coming via sync they should be\n // the latest ones, so we can add them as normal.\n //\n // (Note that both insertEventIntoTimeline and addEventToTimeline\n // do nothing if we have seen this event before.)\n\n const recursionSupport =\n this.client.canSupport.get(Feature.RelationsRecursion) ?? ServerSupport.Unsupported;\n\n if (recursionSupport === ServerSupport.Unsupported) {\n this.insertEventIntoTimeline(event);\n } else {\n this.addEventToTimeline(event, toStartOfTimeline);\n }\n // Aggregation is handled by EventTimelineSet when inserting/adding.\n }\n }\n\n private findPreInitTargetEvent(eventId: string): MatrixEvent | undefined {\n return (\n this.timelineSet.findEventById(eventId) ??\n this.room.findEventById(eventId) ??\n this.preInitEventTargets.get(eventId) ??\n (this.lastEvent?.getId() === eventId ? this.lastEvent : undefined)\n );\n }\n\n public async processEvent(event: MatrixEvent | null | undefined): Promise<void> {\n if (event) {\n this.setEventMetadata(event);\n await this.fetchEditsWhereNeeded(event);\n }\n }\n\n /**\n * Processes the receipts that were caught during initial sync\n * When clients become aware of a thread, they try to retrieve those read receipts\n * and apply them to the current thread\n * @param receipts - A collection of the receipts cached from initial sync\n */\n private processReceipts(receipts: CachedReceiptStructure[] = []): void {\n for (const { eventId, receiptType, userId, receipt, synthetic } of receipts) {\n this.addReceiptToStructure(eventId, receiptType as ReceiptType, userId, receipt, synthetic);\n }\n }\n\n private getRootEventBundledRelationship(rootEvent = this.rootEvent): IThreadBundledRelationship | undefined {\n return rootEvent?.getServerAggregatedRelation<IThreadBundledRelationship>(THREAD_RELATION_TYPE.name);\n }\n\n private async processRootEvent(): Promise<void> {\n const bundledRelationship = this.getRootEventBundledRelationship();\n if (Thread.hasServerSideSupport && bundledRelationship) {\n this.replyCount = bundledRelationship.count;\n this._currentUserParticipated = !!bundledRelationship.current_user_participated;\n\n const mapper = this.client.getEventMapper();\n // re-insert roomId\n this.lastEvent = mapper({\n ...bundledRelationship.latest_event,\n room_id: this.roomId,\n });\n this.updatePendingReplyCount();\n await this.processEvent(this.lastEvent);\n }\n }\n\n private updatePendingReplyCount(): void {\n const unfilteredPendingEvents =\n this.pendingEventOrdering === PendingEventOrdering.Detached ? this.room.getPendingEvents() : this.events;\n const pendingEvents = unfilteredPendingEvents.filter(\n (ev) =>\n ev.threadRootId === this.id &&\n ev.isRelation(THREAD_RELATION_TYPE.name) &&\n ev.status !== null &&\n ev.getId() !== this.lastEvent?.getId(),\n );\n this.lastPendingEvent = pendingEvents.length ? pendingEvents[pendingEvents.length - 1] : undefined;\n this.pendingReplyCount = pendingEvents.length;\n }\n\n /**\n * Reset the live timeline of all timelineSets, and start new ones.\n *\n * <p>This is used when /sync returns a 'limited' timeline. 'Limited' means that there's a gap between the messages\n * /sync returned, and the last known message in our timeline. In such a case, our live timeline isn't live anymore\n * and has to be replaced by a new one. To make sure we can continue paginating our timelines correctly, we have to\n * set new pagination tokens on the old and the new timeline.\n *\n * @param backPaginationToken - token for back-paginating the new timeline\n * @param forwardPaginationToken - token for forward-paginating the old live timeline,\n * if absent or null, all timelines are reset, removing old ones (including the previous live\n * timeline which would otherwise be unable to paginate forwards without this token).\n * Removing just the old live timeline whilst preserving previous ones is not supported.\n */\n public async resetLiveTimeline(\n backPaginationToken?: string | null,\n forwardPaginationToken?: string | null,\n ): Promise<void> {\n const oldLive = this.liveTimeline;\n this.timelineSet.resetLiveTimeline(backPaginationToken ?? undefined, forwardPaginationToken ?? undefined);\n const newLive = this.liveTimeline;\n\n // FIXME: Remove the following as soon as https://github.com/matrix-org/synapse/issues/14830 is resolved.\n //\n // The pagination API for thread timelines currently can't handle the type of pagination tokens returned by sync\n //\n // To make this work anyway, we'll have to transform them into one of the types that the API can handle.\n // One option is passing the tokens to /messages, which can handle sync tokens, and returns the right format.\n // /messages does not return new tokens on requests with a limit of 0.\n // This means our timelines might overlap a slight bit, but that's not an issue, as we deduplicate messages\n // anyway.\n\n let newBackward: string | undefined;\n let oldForward: string | undefined;\n if (backPaginationToken) {\n const res = await this.client.createMessagesRequest(this.roomId, backPaginationToken, 1, Direction.Forward);\n newBackward = res.end;\n }\n if (forwardPaginationToken) {\n const res = await this.client.createMessagesRequest(\n this.roomId,\n forwardPaginationToken,\n 1,\n Direction.Backward,\n );\n oldForward = res.start;\n }\n // Only replace the token if we don't have paginated away from this position already. This situation doesn't\n // occur today, but if the above issue is resolved, we'd have to go down this path.\n if (forwardPaginationToken && oldLive.getPaginationToken(Direction.Forward) === forwardPaginationToken) {\n oldLive.setPaginationToken(oldForward ?? null, Direction.Forward);\n }\n if (backPaginationToken && newLive.getPaginationToken(Direction.Backward) === backPaginationToken) {\n newLive.setPaginationToken(newBackward ?? null, Direction.Backward);\n }\n }\n\n private async updateThreadFromRootEvent(): Promise<void> {\n if (Thread.hasServerSideSupport) {\n // Ensure we show *something* as soon as possible, we'll update it as soon as we get better data, but we\n // don't want the thread preview to be empty if we can avoid it\n if (!this.initialEventsFetched && !this.lastEvent) {\n await this.processRootEvent();\n }\n await this.fetchRootEvent();\n }\n await this.processRootEvent();\n }\n\n private async updateThreadMetadata(): Promise<void> {\n this.updatePendingReplyCount();\n\n if (!this.processRootEventPromise) {\n // We only want to do this once otherwise we end up rolling back to the last unsigned summary we have for the thread\n this.processRootEventPromise = this.updateThreadFromRootEvent();\n }\n await this.processRootEventPromise;\n\n if (!this.initialEventsFetched) {\n if (this.initalEventFetchProm) {\n await this.initalEventFetchProm;\n } else {\n // fetch initial events to allow proper pagination\n try {\n // clear out any events that were added before the pagination request\n // completed (eg. from sync). They'll be replaced by those from the pagination.\n // Really, we should do this after the pagination request completes, but\n // paginateEventTimeline does the request and adds the events in one go, so\n // this would need a refactor in order to do. It's therefore possible there's\n // a remaining race where an event comes in while the pagination request is\n // happening.\n this.timelineSet.resetLiveTimeline();\n // if the thread has regular events, this will just load the last reply.\n // if the thread is newly created, this will load the root event.\n if (this.replyCount === 0 && this.rootEvent) {\n this.timelineSet.addEventsToTimeline([this.rootEvent], true, false, this.liveTimeline, null);\n this.liveTimeline.setPaginationToken(null, Direction.Backward);\n } else {\n this.initalEventFetchProm = withInitialFetchSlot(() =>\n this.client.paginateEventTimeline(this.liveTimeline, { backwards: true }),\n );\n await this.initalEventFetchProm;\n }\n // We have now fetched the initial events, so set the flag. We need to do this before\n // we actually add the events, so `this.addEvents` knows that it can now safely add\n // them rather than buffer them in the pending event list. The main thing is that this\n // must remain false while the async fetch happens, so we don't try to add events before\n // the pagination has finished. The important thing is that we're not await-ing anything\n // else between setting this and adding events, so no races.\n this.initialEventsFetched = true;\n for (const event of this.replayEvents!) {\n this.addEvent(event, false);\n }\n this.replayEvents = null;\n this.preInitEventTargets.clear();\n // just to make sure that, if we've created a timeline window for this thread before the thread itself\n // existed (e.g. when creating a new thread), we'll make sure the panel is force refreshed correctly.\n this.emit(RoomEvent.TimelineReset, this.room, this.timelineSet, true);\n } catch (e) {\n logger.error(\"Failed to load start of newly created thread: \", e);\n this.initialEventsFetched = false;\n }\n }\n }\n\n this.emit(ThreadEvent.Update, this);\n }\n\n // XXX: Workaround for https://github.com/matrix-org/matrix-spec-proposals/pull/2676/files#r827240084\n private async fetchEditsWhereNeeded(...events: MatrixEvent[]): Promise<unknown> {\n const recursionSupport = this.client.canSupport.get(Feature.RelationsRecursion) ?? ServerSupport.Unsupported;\n if (recursionSupport === ServerSupport.Unsupported) {\n return Promise.all(\n events.filter(isAnEncryptedThreadMessage).map(async (event: MatrixEvent) => {\n try {\n const relations = await this.client.relations(\n this.roomId,\n event.getId()!,\n RelationType.Replace,\n event.getType(),\n {\n limit: 1,\n },\n );\n if (relations.events.length) {\n const editEvent = relations.events[0];\n event.makeReplaced(editEvent);\n this.insertEventIntoTimeline(editEvent);\n }\n } catch (e) {\n logger.error(\"Failed to load edits for encrypted thread event\", e);\n }\n }),\n );\n }\n }\n\n public setEventMetadata(event: MatrixEvent | null | undefined): void {\n if (event) {\n EventTimeline.setEventMetadata(event, this.roomState, false);\n event.setThread(this);\n }\n }\n\n public clearEventMetadata(event: MatrixEvent | null | undefined): void {\n if (event) {\n event.setThread(undefined);\n delete event.event?.unsigned?.[\"m.relations\"]?.[THREAD_RELATION_TYPE.name];\n }\n }\n\n /**\n * Finds an event by ID in the current thread\n */\n public findEventById(eventId: string): MatrixEvent | undefined {\n return this.timelineSet.findEventById(eventId);\n }\n\n /**\n * Return last reply to the thread, if known.\n */\n public lastReply(\n matches: (ev: MatrixEvent) => boolean = (ev): boolean => ev.isRelation(THREAD_RELATION_TYPE.name),\n ): MatrixEvent | null {\n for (let i = this.timeline.length - 1; i >= 0; i--) {\n const event = this.timeline[i];\n if (matches(event)) {\n return event;\n }\n }\n return null;\n }\n\n public get roomId(): string {\n return this.room.roomId;\n }\n\n /**\n * The number of messages in the thread\n * Only count rel_type=m.thread as we want to\n * exclude annotations from that number\n */\n public get length(): number {\n return this.replyCount + this.pendingReplyCount;\n }\n\n /**\n * A getter for the last event of the thread.\n * This might be a synthesized event, if so, it will not emit any events to listeners.\n */\n public get replyToEvent(): MatrixEvent | null {\n return this.lastPendingEvent ?? this.lastEvent ?? this.lastReply();\n }\n\n /**\n * The live event timeline for this thread.\n * @deprecated Present for backwards compatibility.\n * Use this.events instead\n * @returns The live event timeline for this thread.\n */\n public get timeline(): MatrixEvent[] {\n return this.events;\n }\n\n public get events(): MatrixEvent[] {\n return this.liveTimeline.getEvents();\n }\n\n public has(eventId: string): boolean {\n return this.timelineSet.findEventById(eventId) instanceof MatrixEvent;\n }\n\n public get hasCurrentUserParticipated(): boolean {\n return this._currentUserParticipated;\n }\n\n public get liveTimeline(): EventTimeline {\n return this.timelineSet.getLiveTimeline();\n }\n\n public getUnfilteredTimelineSet(): EventTimelineSet {\n return this.timelineSet;\n }\n\n public addReceipt(event: MatrixEvent, synthetic: boolean): void {\n throw new Error(\"Unsupported function on the thread model\");\n }\n\n /**\n * Get the ID of the event that a given user has read up to within this thread,\n * or null if we have received no read receipt (at all) from them.\n * @param userId - The user ID to get read receipt event ID for\n * @param ignoreSynthesized - If true, return only receipts that have been\n * sent by the server, not implicit ones generated\n * by the JS SDK.\n * @returns ID of the latest event that the given user has read, or null.\n */\n public getEventReadUpTo(userId: string, ignoreSynthesized?: boolean): string | null {\n // TODO: we think the implementation here is not right. Here is a sketch\n // of the right answer:\n //\n // for event in timeline.events.reversed():\n // if room.hasUserReadEvent(event):\n // return event\n // return null\n //\n // If this is too slow, we might be able to improve it by trying walking\n // forward from the threaded receipt in this thread. We could alternate\n // between backwards-from-front and forwards-from-threaded-receipt to\n // improve our chances of hitting the right answer sooner.\n //\n // Either way, it's still fundamentally slow because we have to walk\n // events.\n //\n // We also might just want to limit the time we spend on this by giving\n // up after, say, 100 events.\n //\n // --- andyb\n\n const isCurrentUser = userId === this.client.getUserId();\n const lastReply = this.timeline[this.timeline.length - 1];\n if (isCurrentUser && lastReply) {\n // If the last activity in a thread is prior to the first threaded read receipt\n // sent in the room (suggesting that it was sent before the user started\n // using a client that supported threaded read receipts), we want to\n // consider this thread as read.\n const beforeFirstThreadedReceipt = lastReply.getTs() < this.room.getOldestThreadedReceiptTs();\n const lastReplyId = lastReply.getId();\n // Some unsent events do not have an ID, we do not want to consider them read\n if (beforeFirstThreadedReceipt && lastReplyId) {\n return lastReplyId;\n }\n }\n\n const readUpToId = super.getEventReadUpTo(userId, ignoreSynthesized);\n\n // Check whether the unthreaded read receipt for that user is more recent\n // than the read receipt inside that thread.\n if (lastReply) {\n const unthreadedReceipt = this.room.getLastUnthreadedReceiptFor(userId);\n if (!unthreadedReceipt) {\n return readUpToId;\n }\n\n for (let i = this.timeline?.length - 1; i >= 0; --i) {\n const ev = this.timeline[i];\n // If we encounter the `readUpToId` we do not need to look further\n // there is no \"more recent\" unthreaded read receipt\n if (ev.getId() === readUpToId) return readUpToId;\n\n // Inspecting events from most recent to oldest, we're checking\n // whether an unthreaded read receipt is more recent that the current event.\n // We usually prefer relying on the order of the DAG but in this scenario\n // it is not possible and we have to rely on timestamp\n if (ev.getTs() < unthreadedReceipt.ts) return ev.getId() ?? readUpToId;\n }\n }\n\n return readUpToId;\n }\n\n /**\n * Determine if the given user has read a particular event.\n *\n * It is invalid to call this method with an event that is not part of this thread.\n *\n * This is not a definitive check as it only checks the events that have been\n * loaded client-side at the time of execution.\n * @param userId - The user ID to check the read state of.\n * @param eventId - The event ID to check if the user read.\n * @returns True if the user has read the event, false otherwise.\n */\n public hasUserReadEvent(userId: string, eventId: string): boolean {\n if (userId === this.client.getUserId()) {\n // Consider an event read if it's part of a thread that is before the\n // first threaded receipt sent in that room. It is likely that it is\n // part of a thread that was created before MSC3771 was implemented.\n // Or before the last unthreaded receipt for the logged in user\n const beforeFirstThreadedReceipt =\n (this.lastReply()?.getTs() ?? 0) < this.room.getOldestThreadedReceiptTs();\n const unthreadedReceiptTs = this.room.getLastUnthreadedReceiptFor(userId)?.ts ?? 0;\n const beforeLastUnthreadedReceipt = (this?.lastReply()?.getTs() ?? 0) < unthreadedReceiptTs;\n if (beforeFirstThreadedReceipt || beforeLastUnthreadedReceipt) {\n return true;\n }\n }\n\n return this.room.hasUserReadEvent(userId, eventId);\n }\n\n public setUnread(type: NotificationCountType, count: number): void {\n return this.room.setThreadUnreadNotificationCount(this.id, type, count);\n }\n\n /**\n * Returns the most recent unthreaded receipt for a given user\n * @param userId - the MxID of the User\n * @returns an unthreaded Receipt. Can be undefined if receipts have been disabled\n * or a user chooses to use private read receipts (or we have simply not received\n * a receipt from this user yet).\n */\n public getLastUnthreadedReceiptFor(userId: string): Receipt | undefined {\n return this.room.getLastUnthreadedReceiptFor(userId);\n }\n}\n\n/**\n * Decide whether an event deserves to have its potential edits fetched.\n *\n * @returns true if this event is encrypted and is a message that is part of a\n * thread - either inside it, or a root.\n */\nfunction isAnEncryptedThreadMessage(event: MatrixEvent): boolean {\n return event.isEncrypted() && (event.isRelation(THREAD_RELATION_TYPE.name) || event.isThreadRoot);\n}\n\nexport const FILTER_RELATED_BY_SENDERS = new ServerControlledNamespacedValue(\n \"related_by_senders\",\n \"io.element.relation_senders\",\n);\nexport const FILTER_RELATED_BY_REL_TYPES = new ServerControlledNamespacedValue(\n \"related_by_rel_types\",\n \"io.element.relation_types\",\n);\nexport const THREAD_RELATION_TYPE = new ServerControlledNamespacedValue(\"m.thread\", \"io.element.thread\");\n\nexport enum ThreadFilterType {\n My,\n All,\n}\n\nexport function threadFilterTypeToFilter(type: ThreadFilterType | null): \"all\" | \"participated\" {\n switch (type) {\n case ThreadFilterType.My:\n return \"participated\";\n default:\n return \"all\";\n }\n}\n"],"mappings":";;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA,SAA4B,oBAAoB,QAAQ,cAAc;AACtE,SAAS,cAAc,QAAQ,iBAAiB;AAChD,SAAS,YAAY,QAAQ,oBAAoB;AACjD,SAA0C,WAAW,EAAE,gBAAgB,QAAQ,YAAY;AAC3F,SAAS,SAAS,EAAE,aAAa,QAAQ,qBAAqB;AAC9D,SAAS,gBAAgB,QAAyC,yBAAyB;AAC3F,SAAgD,SAAS,QAAQ,WAAW;AAE5E,SAAS,+BAA+B,QAA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AEA;AACJ;AACA;AACA;AACA;AACA;AACA;EACW,2BAA2B,CAAC,MAAc,EAAuB;IACpE,OAAO,IAAI,CAAC,IAAI,CAAC,2BAA2B,CAAC,MAAM,CAAC;EACxD;AACJ;;AAEA;AACA;AACA;AACA;AACA;AACA;AALA,gBA/2Ba,MAAM,0BACsB,cAAc,CAAC,IAAI;AAAA,gBAD/C,MAAM,8BAE0B,cAAc,CAAC,IAAI;AAAA,gBAFnD,MAAM,uCAGmC,cAAc,CAAC,IAAI;AAk3BzE,SAAS,0BAA0B,CAAC,KAAkB,EAAW;EAC7D,OAAO,KAAK,CAAC,WAAW,CAAC,CAAC,KAAK,KAAK,CAAC,UAAU,CAAC,oBAAoB,CAAC,IAAI,CAAC,IAAI,KAAK,CAAC,YAAY,CAAC;AACrG;AAEA,OAAO,MAAM,yBAAyB,GAAG,IAAI,+BAA+B,CACxE,oBAAoB,EACpB,6BACJ,CAAC;AACD,OAAO,MAAM,2BAA2B,GAAG,IAAI,+BAA+B,CAC1E,sBAAsB,EACtB,2BACJ,CAAC;AACD,OAAO,MAAM,oBAAoB,GAAG,IAAI,+BAA+B,CAAC,UAAU,EAAE,mBAAmB,CAAC;AAExG,WAAY,gBAAgB,0BAAhB,gBAAgB;EAAhB,gBAAgB,CAAhB,gBAAgB;EAAhB,gBAAgB,CAAhB,gBAAgB;EAAA,OAAhB,gBAAgB;AAAA;AAK5B,OAAO,SAAS,wBAAwB,CAAC,IAA6B,EAA0B;EAC5F,QAAQ,IAAI;IACR,KAAK,gBAAgB,CAAC,EAAE;MACpB,OAAO,cAAc;IACzB;MACI,OAAO,KAAK;EACpB;AACJ","ignoreList":[]}
|
|
@@ -2,7 +2,7 @@ import { ClientRendezvousFailureReason, MSC4108FailureReason, type RendezvousFai
|
|
|
2
2
|
import { type MatrixClient } from "../client.ts";
|
|
3
3
|
import { type MSC4108SecureChannel } from "./channels/MSC4108SecureChannel.ts";
|
|
4
4
|
import { type DeviceAccessTokenResponse, type ValidatedAuthMetadata } from "../oauth/index.ts";
|
|
5
|
-
import { type
|
|
5
|
+
import { type SignInWithQRSecrets, type SignInWithQRFlow } from "./SignInWithQRFlow.ts";
|
|
6
6
|
/**
|
|
7
7
|
* Enum representing the payload types transmissible over [MSC4108](https://github.com/matrix-org/matrix-spec-proposals/pull/4108)
|
|
8
8
|
* secure channels.
|
|
@@ -25,7 +25,7 @@ export declare enum PayloadType {
|
|
|
25
25
|
export interface MSC4108Payload {
|
|
26
26
|
type: PayloadType;
|
|
27
27
|
}
|
|
28
|
-
interface SecretsPayload extends MSC4108Payload,
|
|
28
|
+
interface SecretsPayload extends MSC4108Payload, SignInWithQRSecrets {
|
|
29
29
|
type: PayloadType.Secrets;
|
|
30
30
|
}
|
|
31
31
|
/**
|
|
@@ -33,7 +33,7 @@ interface SecretsPayload extends MSC4108Payload, Awaited<ReturnType<NonNullable<
|
|
|
33
33
|
* sign in with QR + OAuth2 flow.
|
|
34
34
|
* @experimental Note that this is UNSTABLE and may have breaking changes without notice.
|
|
35
35
|
*/
|
|
36
|
-
export declare class MSC4108SignInWithQR {
|
|
36
|
+
export declare class MSC4108SignInWithQR implements SignInWithQRFlow {
|
|
37
37
|
private readonly channel;
|
|
38
38
|
private readonly didScanCode;
|
|
39
39
|
private readonly client?;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"MSC4108SignInWithQR.d.ts","sourceRoot":"","sources":["../../src/rendezvous/MSC4108SignInWithQR.ts"],"names":[],"mappings":"AAkBA,OAAO,EACH,6BAA6B,EAC7B,oBAAoB,EAEpB,KAAK,yBAAyB,EACjC,MAAM,YAAY,CAAC;AACpB,OAAO,EAAE,KAAK,YAAY,EAAE,MAAM,cAAc,CAAC;AAEjD,OAAO,EAAE,KAAK,oBAAoB,EAAE,MAAM,oCAAoC,CAAC;AAG/E,OAAO,EACH,KAAK,yBAAyB,EAK9B,KAAK,qBAAqB,EAE7B,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,KAAK,
|
|
1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B,GAAG,OAAO,CAAC,IAAI,CAAC,CAG/F;IAED;;OAEG;IACU,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC,CAElC;CACJ"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"MSC4108SignInWithQR.js","names":[],"sources":["../../src/rendezvous/MSC4108SignInWithQR.ts"],"sourcesContent":["/*\nCopyright 2024 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { QrCodeIntent } from \"@matrix-org/matrix-sdk-crypto-wasm\";\n\nimport {\n ClientRendezvousFailureReason,\n MSC4108FailureReason,\n RendezvousError,\n type RendezvousFailureListener,\n} from \"./index.ts\";\nimport { type MatrixClient } from \"../client.ts\";\nimport { logger } from \"../logger.ts\";\nimport { type MSC4108SecureChannel } from \"./channels/MSC4108SecureChannel.ts\";\nimport { MatrixError } from \"../http-api/index.ts\";\nimport { sleep } from \"../utils.ts\";\nimport {\n type DeviceAccessTokenResponse,\n type DeviceAuthorizationResponse,\n generateScope,\n OAuthGrantType,\n startDeviceAuthorization,\n type ValidatedAuthMetadata,\n waitForDeviceAuthorization,\n} from \"../oauth/index.ts\";\nimport { type CryptoApi } from \"../crypto-api/index.ts\";\n\n/**\n * Enum representing the payload types transmissible over [MSC4108](https://github.com/matrix-org/matrix-spec-proposals/pull/4108)\n * secure channels.\n * @experimental Note that this is UNSTABLE and may have breaking changes without notice.\n */\nexport enum PayloadType {\n Protocols = \"m.login.protocols\",\n Protocol = \"m.login.protocol\",\n Failure = \"m.login.failure\",\n Success = \"m.login.success\",\n Secrets = \"m.login.secrets\",\n ProtocolAccepted = \"m.login.protocol_accepted\",\n Declined = \"m.login.declined\",\n}\n\n/**\n * Type representing the base payload format for [MSC4108](https://github.com/matrix-org/matrix-spec-proposals/pull/4108)\n * messages sent over the secure channel.\n * @experimental Note that this is UNSTABLE and may have breaking changes without notice.\n */\nexport interface MSC4108Payload {\n type: PayloadType;\n}\n\ninterface ProtocolsPayload extends MSC4108Payload {\n type: PayloadType.Protocols;\n protocols: string[];\n homeserver: string;\n}\n\ninterface ProtocolPayload extends MSC4108Payload {\n type: PayloadType.Protocol;\n protocol: Exclude<string, \"device_authorization_grant\">;\n device_id: string;\n}\n\ninterface DeviceAuthorizationGrantProtocolPayload extends ProtocolPayload {\n protocol: \"device_authorization_grant\";\n device_authorization_grant: {\n verification_uri: string;\n verification_uri_complete?: string;\n };\n}\n\nfunction isDeviceAuthorizationGrantProtocolPayload(\n payload: ProtocolPayload,\n): payload is DeviceAuthorizationGrantProtocolPayload {\n return payload.protocol === \"device_authorization_grant\";\n}\n\ninterface FailurePayload extends MSC4108Payload {\n type: PayloadType.Failure;\n reason: MSC4108FailureReason;\n homeserver?: string;\n}\n\ninterface DeclinedPayload extends MSC4108Payload {\n type: PayloadType.Declined;\n}\n\ninterface SuccessPayload extends MSC4108Payload {\n type: PayloadType.Success;\n}\n\ninterface AcceptedPayload extends MSC4108Payload {\n type: PayloadType.ProtocolAccepted;\n}\n\ninterface SecretsPayload extends MSC4108Payload, Awaited<ReturnType<NonNullable<CryptoApi[\"exportSecretsBundle\"]>>> {\n type: PayloadType.Secrets;\n}\n\n/**\n * Prototype of the unstable [MSC4108](https://github.com/matrix-org/matrix-spec-proposals/pull/4108)\n * sign in with QR + OAuth2 flow.\n * @experimental Note that this is UNSTABLE and may have breaking changes without notice.\n */\nexport class MSC4108SignInWithQR {\n private readonly ourIntent: QrCodeIntent;\n private _code?: Uint8Array;\n private expectingNewDeviceId?: string;\n private metadata?: ValidatedAuthMetadata;\n private grantInProgress?: DeviceAuthorizationResponse;\n\n /**\n * Returns the check code for the secure channel or undefined if not generated yet.\n */\n public get checkCode(): string | undefined {\n return this.channel?.getCheckCode();\n }\n\n /**\n * @param channel - The secure channel used for communication\n * @param client - The Matrix client in used on the device already logged in\n * @param didScanCode - Whether this side of the channel scanned the QR code from the other party\n * @param onFailure - Callback for when the rendezvous fails\n */\n public constructor(\n private readonly channel: MSC4108SecureChannel,\n private readonly didScanCode: boolean,\n private readonly client?: MatrixClient,\n public onFailure?: RendezvousFailureListener,\n ) {\n this.ourIntent = client ? QrCodeIntent.Reciprocate : QrCodeIntent.Login;\n }\n\n /**\n * Returns the code representing the rendezvous suitable for rendering in a QR code or undefined if not generated yet.\n */\n public get code(): Uint8Array | undefined {\n return this._code;\n }\n\n /**\n * Generate the code including doing partial set up of the channel where required.\n */\n public async generateCode(): Promise<void> {\n if (this._code) {\n return;\n }\n\n if (this.ourIntent === QrCodeIntent.Reciprocate && this.client) {\n this._code = await this.channel.generateCode(this.ourIntent, this.client.getDomain()!);\n } else if (this.ourIntent === QrCodeIntent.Login) {\n this._code = await this.channel.generateCode(this.ourIntent);\n }\n }\n\n /**\n * Returns true if the device is the already logged in device reciprocating a new login on the other side of the channel.\n */\n public get isExistingDevice(): boolean {\n return this.ourIntent === QrCodeIntent.Reciprocate;\n }\n\n /**\n * Returns true if the device is the new device logging in being reciprocated by the device on the other side of the channel.\n */\n public get isNewDevice(): boolean {\n return !this.isExistingDevice;\n }\n\n /**\n * The first step in the OAuth2 QR login process.\n * To be called after the QR code has been rendered or scanned.\n * The scanning device has to discover the homeserver details, if they scanned the code then they already have it.\n * If the new device is the one rendering the QR code then it has to wait be sent the homeserver details via the rendezvous channel.\n */\n public async negotiateProtocols(): Promise<{ serverName?: string }> {\n logger.info(`negotiateProtocols(isNewDevice=${this.isNewDevice} didScanCode=${this.didScanCode})`);\n await this.channel.connect();\n\n if (this.didScanCode) {\n // Secure Channel step 6 completed, we trust the channel\n\n if (this.isNewDevice) {\n // MSC4108-Flow: ExistingScanned - take homeserver from QR code which should already be set\n } else {\n // MSC4108-Flow: NewScanned -send protocols message\n let authMetadata: ValidatedAuthMetadata | undefined;\n try {\n authMetadata = await this.client!.getAuthMetadata();\n } catch (e) {\n logger.error(\"Failed to discover OAuth2 metadata\", e);\n }\n\n if (authMetadata?.grant_types_supported.includes(OAuthGrantType.DeviceAuthorization)) {\n await this.send<ProtocolsPayload>({\n type: PayloadType.Protocols,\n protocols: [\"device_authorization_grant\"],\n homeserver: this.client!.getDomain()!,\n });\n } else {\n await this.send<FailurePayload>({\n type: PayloadType.Failure,\n reason: MSC4108FailureReason.UnsupportedProtocol,\n });\n throw new RendezvousError(\n \"Device code grant unsupported\",\n MSC4108FailureReason.UnsupportedProtocol,\n );\n }\n }\n } else if (this.isNewDevice) {\n // MSC4108-Flow: ExistingScanned - wait for protocols message\n logger.info(\"Waiting for protocols message\");\n const payload = await this.receive<ProtocolsPayload>();\n\n if (payload?.type === PayloadType.Failure) {\n throw new RendezvousError(\"Failed\", payload.reason);\n }\n\n if (payload?.type !== PayloadType.Protocols) {\n await this.send<FailurePayload>({\n type: PayloadType.Failure,\n reason: MSC4108FailureReason.UnexpectedMessageReceived,\n });\n throw new RendezvousError(\n \"Unexpected message received\",\n MSC4108FailureReason.UnexpectedMessageReceived,\n );\n }\n\n return { serverName: payload.homeserver };\n } else {\n // MSC4108-Flow: NewScanned - nothing to do\n }\n return {};\n }\n\n /**\n * The second & third step in the OAuth2 QR login process.\n * To be called after `negotiateProtocols` for the existing device.\n * To be called after OAuth2 negotiation for the new device.\n *\n * @param input - Required for the new device to start the device authorization grant, not required for the existing device reciprocating the login\n */\n public async deviceAuthorizationGrant(input?: {\n metadata: ValidatedAuthMetadata;\n clientId: string;\n deviceId: string;\n }): Promise<{\n verificationUri?: string;\n userCode?: string;\n }> {\n if (this.isNewDevice) {\n if (!input) {\n throw new Error(\"Input must be provided for new device\");\n }\n\n const { metadata, clientId, deviceId } = input;\n\n const scope = generateScope(deviceId);\n\n // MSC4108-Flow: NewDevice - start device authorization grant\n const dagResponse = await startDeviceAuthorization({\n clientId,\n scope,\n metadata,\n });\n\n this.metadata = metadata;\n this.grantInProgress = dagResponse;\n\n const protocol: DeviceAuthorizationGrantProtocolPayload = {\n type: PayloadType.Protocol,\n protocol: \"device_authorization_grant\",\n device_id: deviceId,\n device_authorization_grant: {\n verification_uri: dagResponse.verification_uri,\n verification_uri_complete: dagResponse.verification_uri_complete,\n },\n };\n\n await this.send(protocol);\n\n return {\n verificationUri: dagResponse.verification_uri_complete ?? dagResponse.verification_uri,\n userCode: dagResponse.user_code,\n };\n } else {\n // The user needs to do step 7 for the out-of-band confirmation\n // but, first we receive the protocol chosen by the other device so that\n // the confirmation_uri is ready to go\n logger.info(\"Waiting for protocol message\");\n const payload = await this.receive<ProtocolPayload | DeviceAuthorizationGrantProtocolPayload>();\n\n if (payload?.type === PayloadType.Failure) {\n throw new RendezvousError(\"Failed\", payload.reason);\n }\n\n if (payload?.type !== PayloadType.Protocol) {\n await this.send<FailurePayload>({\n type: PayloadType.Failure,\n reason: MSC4108FailureReason.UnexpectedMessageReceived,\n });\n throw new RendezvousError(\n \"Unexpected message received\",\n MSC4108FailureReason.UnexpectedMessageReceived,\n );\n }\n\n if (isDeviceAuthorizationGrantProtocolPayload(payload)) {\n const { device_authorization_grant: dag, device_id: expectingNewDeviceId } = payload;\n const { verification_uri: verificationUri, verification_uri_complete: verificationUriComplete } = dag;\n\n let deviceAlreadyExists = true;\n try {\n await this.client?.getDevice(expectingNewDeviceId);\n } catch (err: MatrixError | unknown) {\n if (err instanceof MatrixError && err.httpStatus === 404) {\n deviceAlreadyExists = false;\n }\n }\n\n if (deviceAlreadyExists) {\n await this.send<FailurePayload>({\n type: PayloadType.Failure,\n reason: MSC4108FailureReason.DeviceAlreadyExists,\n });\n throw new RendezvousError(\n \"Specified device ID already exists\",\n MSC4108FailureReason.DeviceAlreadyExists,\n );\n }\n\n this.expectingNewDeviceId = expectingNewDeviceId;\n\n return { verificationUri: verificationUriComplete ?? verificationUri };\n }\n\n await this.send<FailurePayload>({\n type: PayloadType.Failure,\n reason: MSC4108FailureReason.UnsupportedProtocol,\n });\n throw new RendezvousError(\n \"Received a request for an unsupported protocol\",\n MSC4108FailureReason.UnsupportedProtocol,\n );\n }\n }\n\n /**\n * The fourth step in the OAuth2 QR login process.\n * The reciprocating device must perform step 5 for this method to resolve.\n * To be called after {@link deviceAuthorizationGrant} only on the new device.\n */\n public async completeLoginOnNewDevice({\n clientId,\n }: {\n clientId: string;\n }): Promise<DeviceAccessTokenResponse | undefined> {\n if (!this.isNewDevice || !this.grantInProgress || !this.metadata) {\n throw new Error(\"Can only complete login on new device\");\n }\n\n logger.info(\"Waiting for protocol accepted message\");\n // wait for accepted message\n const payload = await this.receive<AcceptedPayload | FailurePayload>();\n\n if (!payload) {\n throw new RendezvousError(\n \"No response from existing device\",\n MSC4108FailureReason.UnexpectedMessageReceived,\n );\n }\n if (payload.type === PayloadType.Failure) {\n throw new RendezvousError(\"Failed\", payload.reason);\n }\n if (payload.type !== PayloadType.ProtocolAccepted) {\n throw new RendezvousError(\"Unexpected message received\", MSC4108FailureReason.UnexpectedMessageReceived);\n }\n\n // poll for DAG\n const res = await waitForDeviceAuthorization({\n session: this.grantInProgress,\n metadata: this.metadata,\n clientId,\n });\n\n if (!res) {\n throw new RendezvousError(\n \"No response from device authorization endpoint\",\n ClientRendezvousFailureReason.Unknown,\n );\n }\n\n if (\"error\" in res) {\n let reason: MSC4108FailureReason = MSC4108FailureReason.UnexpectedMessageReceived;\n if (res.error === \"expired_token\") {\n reason = MSC4108FailureReason.AuthorizationExpired;\n } else if (res.error === \"access_denied\") {\n reason = MSC4108FailureReason.UserCancelled;\n }\n await this.send({\n type: PayloadType.Failure,\n reason,\n } satisfies FailurePayload);\n\n throw new RendezvousError(\"Rejection from device authorization endpoint\", reason);\n }\n\n return res;\n }\n\n /**\n * The fifth (and final) step in the OAuth2 QR login process.\n * To be called after the new device has completed authentication.\n */\n public async shareSecrets(): Promise<{ secrets?: Omit<SecretsPayload, \"type\"> }> {\n if (this.isNewDevice) {\n await this.send<SuccessPayload>({\n type: PayloadType.Success,\n });\n // then wait for secrets\n logger.info(\"Waiting for secrets message\");\n const payload = await this.receive<SecretsPayload>();\n if (payload?.type === PayloadType.Failure) {\n throw new RendezvousError(\"Failed\", payload.reason);\n }\n\n if (payload?.type !== PayloadType.Secrets) {\n await this.send<FailurePayload>({\n type: PayloadType.Failure,\n reason: MSC4108FailureReason.UnexpectedMessageReceived,\n });\n throw new RendezvousError(\n \"Unexpected message received\",\n MSC4108FailureReason.UnexpectedMessageReceived,\n );\n }\n return { secrets: payload };\n // then done?\n } else {\n if (!this.expectingNewDeviceId) {\n throw new Error(\"No new device ID expected\");\n }\n await this.send<AcceptedPayload>({\n type: PayloadType.ProtocolAccepted,\n });\n\n logger.info(\"Waiting for outcome message\");\n const payload = await this.receive<SuccessPayload | DeclinedPayload>();\n\n if (payload?.type === PayloadType.Failure) {\n throw new RendezvousError(\"Failed\", payload.reason);\n }\n\n if (payload?.type === PayloadType.Declined) {\n throw new RendezvousError(\"User declined\", ClientRendezvousFailureReason.UserDeclined);\n }\n\n if (payload?.type !== PayloadType.Success) {\n await this.send<FailurePayload>({\n type: PayloadType.Failure,\n reason: MSC4108FailureReason.UnexpectedMessageReceived,\n });\n throw new RendezvousError(\"Unexpected message\", MSC4108FailureReason.UnexpectedMessageReceived);\n }\n\n const timeout = Date.now() + 10000; // wait up to 10 seconds\n do {\n // is the device visible via the Homeserver?\n try {\n const device = await this.client?.getDevice(this.expectingNewDeviceId);\n\n if (device) {\n // if so, return the secrets\n const secretsBundle = await this.client!.getCrypto()!.exportSecretsBundle!();\n if (this.channel.cancelled) {\n throw new RendezvousError(\"User cancelled\", MSC4108FailureReason.UserCancelled);\n }\n // send secrets\n await this.send<SecretsPayload>({\n type: PayloadType.Secrets,\n ...secretsBundle,\n });\n return { secrets: secretsBundle };\n // let the other side close the rendezvous session\n }\n } catch (err: MatrixError | unknown) {\n if (err instanceof MatrixError && err.httpStatus === 404) {\n // not found, so keep waiting until timeout\n } else {\n throw err;\n }\n }\n await sleep(1000);\n } while (Date.now() < timeout);\n\n await this.send<FailurePayload>({\n type: PayloadType.Failure,\n reason: MSC4108FailureReason.DeviceNotFound,\n });\n throw new RendezvousError(\"New device not found\", MSC4108FailureReason.DeviceNotFound);\n }\n }\n\n private async receive<T extends MSC4108Payload>(): Promise<T | FailurePayload | undefined> {\n return (await this.channel.secureReceive()) as T | undefined;\n }\n\n private async send<T extends MSC4108Payload>(payload: T): Promise<void> {\n await this.channel.secureSend(payload);\n }\n\n /**\n * Decline the login on the existing device.\n */\n public async declineLoginOnExistingDevice(): Promise<void> {\n if (!this.isExistingDevice) {\n throw new Error(\"Can only decline login on existing device\");\n }\n await this.send<FailurePayload>({\n type: PayloadType.Failure,\n reason: MSC4108FailureReason.UserCancelled,\n });\n }\n\n /**\n * Cancels the rendezvous session.\n * @param reason the reason for the cancellation\n */\n public async cancel(reason: MSC4108FailureReason | ClientRendezvousFailureReason): Promise<void> {\n this.onFailure?.(reason);\n await this.channel.cancel(reason);\n }\n\n /**\n * Closes the rendezvous session.\n */\n public async close(): Promise<void> {\n await this.channel.close();\n }\n}\n"],"mappings":";;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA,SAAS,YAAY,QAAQ,oCAAoC;AAEjE,SACI,6BAA6B,EAC7B,oBAAoB,EACpB,eAAe,QAEZ,YAAY;AAEnB,SAAS,MAAM,QAAQ,cAAc;AAErC,SAAS,WAAW,QAAQ,sBAAsB;AAClD,SAAS,KAAK,QAAQ,aAAa;AACnC,SAGI,aAAa,EACb,cAAc,EACd,wBAAwB,EAExB,0BAA0B,QACvB,mBAAmB;AAG1B;AACA;AACA;AACA;AACA;AACA,WAAY,WAAW,0BAAX,WAAW;EAAX,WAAW;EAAX,WAAW;EAAX,WAAW;EAAX,WAAW;EAAX,WAAW;EAAX,WAAW;EAAX,WAAW;EAAA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GAAkB;IACvD,IAAI,CAAC,IAAI,CAAC,gBAAgB,EAAE;MACxB,MAAM,IAAI,KAAK,CAAC,2CAA2C,CAAC;IAChE;IACA,MAAM,IAAI,CAAC,IAAI,CAAiB;MAC5B,IAAI,EAAE,WAAW,CAAC,OAAO;MACzB,MAAM,EAAE,oBAAoB,CAAC;IACjC,CAAC,CAAC;EACN;;EAEA;AACJ;AACA;AACA;EACI,MAAa,MAAM,CAAC,MAA4D,EAAiB;IAC7F,IAAI,CAAC,SAAS,GAAG,MAAM,CAAC;IACxB,MAAM,IAAI,CAAC,OAAO,CAAC,MAAM,CAAC,MAAM,CAAC;EACrC;;EAEA;AACJ;AACA;EACI,MAAa,KAAK,GAAkB;IAChC,MAAM,IAAI,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;EAC9B;AACJ","ignoreList":[]}
|
|
1
|
+
{"version":3,"file":"MSC4108SignInWithQR.js","names":[],"sources":["../../src/rendezvous/MSC4108SignInWithQR.ts"],"sourcesContent":["/*\nCopyright 2024 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { QrCodeIntent } from \"@matrix-org/matrix-sdk-crypto-wasm\";\n\nimport {\n ClientRendezvousFailureReason,\n MSC4108FailureReason,\n RendezvousError,\n type RendezvousFailureListener,\n} from \"./index.ts\";\nimport { type MatrixClient } from \"../client.ts\";\nimport { logger } from \"../logger.ts\";\nimport { type MSC4108SecureChannel } from \"./channels/MSC4108SecureChannel.ts\";\nimport { MatrixError } from \"../http-api/index.ts\";\nimport { sleep } from \"../utils.ts\";\nimport {\n type DeviceAccessTokenResponse,\n type DeviceAuthorizationResponse,\n generateScope,\n OAuthGrantType,\n startDeviceAuthorization,\n type ValidatedAuthMetadata,\n waitForDeviceAuthorization,\n} from \"../oauth/index.ts\";\nimport { type SignInWithQRSecrets, type SignInWithQRFlow } from \"./SignInWithQRFlow.ts\";\n\n/**\n * Enum representing the payload types transmissible over [MSC4108](https://github.com/matrix-org/matrix-spec-proposals/pull/4108)\n * secure channels.\n * @experimental Note that this is UNSTABLE and may have breaking changes without notice.\n */\nexport enum PayloadType {\n Protocols = \"m.login.protocols\",\n Protocol = \"m.login.protocol\",\n Failure = \"m.login.failure\",\n Success = \"m.login.success\",\n Secrets = \"m.login.secrets\",\n ProtocolAccepted = \"m.login.protocol_accepted\",\n Declined = \"m.login.declined\",\n}\n\n/**\n * Type representing the base payload format for [MSC4108](https://github.com/matrix-org/matrix-spec-proposals/pull/4108)\n * messages sent over the secure channel.\n * @experimental Note that this is UNSTABLE and may have breaking changes without notice.\n */\nexport interface MSC4108Payload {\n type: PayloadType;\n}\n\ninterface ProtocolsPayload extends MSC4108Payload {\n type: PayloadType.Protocols;\n protocols: string[];\n homeserver: string;\n}\n\ninterface ProtocolPayload extends MSC4108Payload {\n type: PayloadType.Protocol;\n protocol: Exclude<string, \"device_authorization_grant\">;\n device_id: string;\n}\n\ninterface DeviceAuthorizationGrantProtocolPayload extends ProtocolPayload {\n protocol: \"device_authorization_grant\";\n device_authorization_grant: {\n verification_uri: string;\n verification_uri_complete?: string;\n };\n}\n\nfunction isDeviceAuthorizationGrantProtocolPayload(\n payload: ProtocolPayload,\n): payload is DeviceAuthorizationGrantProtocolPayload {\n return payload.protocol === \"device_authorization_grant\";\n}\n\ninterface FailurePayload extends MSC4108Payload {\n type: PayloadType.Failure;\n reason: MSC4108FailureReason;\n homeserver?: string;\n}\n\ninterface DeclinedPayload extends MSC4108Payload {\n type: PayloadType.Declined;\n}\n\ninterface SuccessPayload extends MSC4108Payload {\n type: PayloadType.Success;\n}\n\ninterface AcceptedPayload extends MSC4108Payload {\n type: PayloadType.ProtocolAccepted;\n}\n\ninterface SecretsPayload extends MSC4108Payload, SignInWithQRSecrets {\n type: PayloadType.Secrets;\n}\n\n/**\n * Prototype of the unstable [MSC4108](https://github.com/matrix-org/matrix-spec-proposals/pull/4108)\n * sign in with QR + OAuth2 flow.\n * @experimental Note that this is UNSTABLE and may have breaking changes without notice.\n */\nexport class MSC4108SignInWithQR implements SignInWithQRFlow {\n private readonly ourIntent: QrCodeIntent;\n private _code?: Uint8Array;\n private expectingNewDeviceId?: string;\n private metadata?: ValidatedAuthMetadata;\n private grantInProgress?: DeviceAuthorizationResponse;\n\n /**\n * Returns the check code for the secure channel or undefined if not generated yet.\n */\n public get checkCode(): string | undefined {\n return this.channel?.getCheckCode();\n }\n\n /**\n * @param channel - The secure channel used for communication\n * @param client - The Matrix client in used on the device already logged in\n * @param didScanCode - Whether this side of the channel scanned the QR code from the other party\n * @param onFailure - Callback for when the rendezvous fails\n */\n public constructor(\n private readonly channel: MSC4108SecureChannel,\n private readonly didScanCode: boolean,\n private readonly client?: MatrixClient,\n public onFailure?: RendezvousFailureListener,\n ) {\n this.ourIntent = client ? QrCodeIntent.Reciprocate : QrCodeIntent.Login;\n }\n\n /**\n * Returns the code representing the rendezvous suitable for rendering in a QR code or undefined if not generated yet.\n */\n public get code(): Uint8Array | undefined {\n return this._code;\n }\n\n /**\n * Generate the code including doing partial set up of the channel where required.\n */\n public async generateCode(): Promise<void> {\n if (this._code) {\n return;\n }\n\n if (this.ourIntent === QrCodeIntent.Reciprocate && this.client) {\n this._code = await this.channel.generateCode(this.ourIntent, this.client.getDomain()!);\n } else if (this.ourIntent === QrCodeIntent.Login) {\n this._code = await this.channel.generateCode(this.ourIntent);\n }\n }\n\n /**\n * Returns true if the device is the already logged in device reciprocating a new login on the other side of the channel.\n */\n public get isExistingDevice(): boolean {\n return this.ourIntent === QrCodeIntent.Reciprocate;\n }\n\n /**\n * Returns true if the device is the new device logging in being reciprocated by the device on the other side of the channel.\n */\n public get isNewDevice(): boolean {\n return !this.isExistingDevice;\n }\n\n /**\n * The first step in the OAuth2 QR login process.\n * To be called after the QR code has been rendered or scanned.\n * The scanning device has to discover the homeserver details, if they scanned the code then they already have it.\n * If the new device is the one rendering the QR code then it has to wait be sent the homeserver details via the rendezvous channel.\n */\n public async negotiateProtocols(): Promise<{ serverName?: string }> {\n logger.info(`negotiateProtocols(isNewDevice=${this.isNewDevice} didScanCode=${this.didScanCode})`);\n await this.channel.connect();\n\n if (this.didScanCode) {\n // Secure Channel step 6 completed, we trust the channel\n\n if (this.isNewDevice) {\n // MSC4108-Flow: ExistingScanned - take homeserver from QR code which should already be set\n } else {\n // MSC4108-Flow: NewScanned -send protocols message\n let authMetadata: ValidatedAuthMetadata | undefined;\n try {\n authMetadata = await this.client!.getAuthMetadata();\n } catch (e) {\n logger.error(\"Failed to discover OAuth2 metadata\", e);\n }\n\n if (authMetadata?.grant_types_supported.includes(OAuthGrantType.DeviceAuthorization)) {\n await this.send<ProtocolsPayload>({\n type: PayloadType.Protocols,\n protocols: [\"device_authorization_grant\"],\n homeserver: this.client!.getDomain()!,\n });\n } else {\n await this.send<FailurePayload>({\n type: PayloadType.Failure,\n reason: MSC4108FailureReason.UnsupportedProtocol,\n });\n throw new RendezvousError(\n \"Device code grant unsupported\",\n MSC4108FailureReason.UnsupportedProtocol,\n );\n }\n }\n } else if (this.isNewDevice) {\n // MSC4108-Flow: ExistingScanned - wait for protocols message\n logger.info(\"Waiting for protocols message\");\n const payload = await this.receive<ProtocolsPayload>();\n\n if (payload?.type === PayloadType.Failure) {\n throw new RendezvousError(\"Failed\", payload.reason);\n }\n\n if (payload?.type !== PayloadType.Protocols) {\n await this.send<FailurePayload>({\n type: PayloadType.Failure,\n reason: MSC4108FailureReason.UnexpectedMessageReceived,\n });\n throw new RendezvousError(\n \"Unexpected message received\",\n MSC4108FailureReason.UnexpectedMessageReceived,\n );\n }\n\n return { serverName: payload.homeserver };\n } else {\n // MSC4108-Flow: NewScanned - nothing to do\n }\n return {};\n }\n\n /**\n * The second & third step in the OAuth2 QR login process.\n * To be called after `negotiateProtocols` for the existing device.\n * To be called after OAuth2 negotiation for the new device.\n *\n * @param input - Required for the new device to start the device authorization grant, not required for the existing device reciprocating the login\n */\n public async deviceAuthorizationGrant(input?: {\n metadata: ValidatedAuthMetadata;\n clientId: string;\n deviceId: string;\n }): Promise<{\n verificationUri?: string;\n userCode?: string;\n }> {\n if (this.isNewDevice) {\n if (!input) {\n throw new Error(\"Input must be provided for new device\");\n }\n\n const { metadata, clientId, deviceId } = input;\n\n const scope = generateScope(deviceId);\n\n // MSC4108-Flow: NewDevice - start device authorization grant\n const dagResponse = await startDeviceAuthorization({\n clientId,\n scope,\n metadata,\n });\n\n this.metadata = metadata;\n this.grantInProgress = dagResponse;\n\n const protocol: DeviceAuthorizationGrantProtocolPayload = {\n type: PayloadType.Protocol,\n protocol: \"device_authorization_grant\",\n device_id: deviceId,\n device_authorization_grant: {\n verification_uri: dagResponse.verification_uri,\n verification_uri_complete: dagResponse.verification_uri_complete,\n },\n };\n\n await this.send(protocol);\n\n return {\n verificationUri: dagResponse.verification_uri_complete ?? dagResponse.verification_uri,\n userCode: dagResponse.user_code,\n };\n } else {\n // The user needs to do step 7 for the out-of-band confirmation\n // but, first we receive the protocol chosen by the other device so that\n // the confirmation_uri is ready to go\n logger.info(\"Waiting for protocol message\");\n const payload = await this.receive<ProtocolPayload | DeviceAuthorizationGrantProtocolPayload>();\n\n if (payload?.type === PayloadType.Failure) {\n throw new RendezvousError(\"Failed\", payload.reason);\n }\n\n if (payload?.type !== PayloadType.Protocol) {\n await this.send<FailurePayload>({\n type: PayloadType.Failure,\n reason: MSC4108FailureReason.UnexpectedMessageReceived,\n });\n throw new RendezvousError(\n \"Unexpected message received\",\n MSC4108FailureReason.UnexpectedMessageReceived,\n );\n }\n\n if (isDeviceAuthorizationGrantProtocolPayload(payload)) {\n const { device_authorization_grant: dag, device_id: expectingNewDeviceId } = payload;\n const { verification_uri: verificationUri, verification_uri_complete: verificationUriComplete } = dag;\n\n let deviceAlreadyExists = true;\n try {\n await this.client?.getDevice(expectingNewDeviceId);\n } catch (err: MatrixError | unknown) {\n if (err instanceof MatrixError && err.httpStatus === 404) {\n deviceAlreadyExists = false;\n }\n }\n\n if (deviceAlreadyExists) {\n await this.send<FailurePayload>({\n type: PayloadType.Failure,\n reason: MSC4108FailureReason.DeviceAlreadyExists,\n });\n throw new RendezvousError(\n \"Specified device ID already exists\",\n MSC4108FailureReason.DeviceAlreadyExists,\n );\n }\n\n this.expectingNewDeviceId = expectingNewDeviceId;\n\n return { verificationUri: verificationUriComplete ?? verificationUri };\n }\n\n await this.send<FailurePayload>({\n type: PayloadType.Failure,\n reason: MSC4108FailureReason.UnsupportedProtocol,\n });\n throw new RendezvousError(\n \"Received a request for an unsupported protocol\",\n MSC4108FailureReason.UnsupportedProtocol,\n );\n }\n }\n\n /**\n * The fourth step in the OAuth2 QR login process.\n * The reciprocating device must perform step 5 for this method to resolve.\n * To be called after {@link deviceAuthorizationGrant} only on the new device.\n */\n public async completeLoginOnNewDevice({\n clientId,\n }: {\n clientId: string;\n }): Promise<DeviceAccessTokenResponse | undefined> {\n if (!this.isNewDevice || !this.grantInProgress || !this.metadata) {\n throw new Error(\"Can only complete login on new device\");\n }\n\n logger.info(\"Waiting for protocol accepted message\");\n // wait for accepted message\n const payload = await this.receive<AcceptedPayload | FailurePayload>();\n\n if (!payload) {\n throw new RendezvousError(\n \"No response from existing device\",\n MSC4108FailureReason.UnexpectedMessageReceived,\n );\n }\n if (payload.type === PayloadType.Failure) {\n throw new RendezvousError(\"Failed\", payload.reason);\n }\n if (payload.type !== PayloadType.ProtocolAccepted) {\n throw new RendezvousError(\"Unexpected message received\", MSC4108FailureReason.UnexpectedMessageReceived);\n }\n\n // poll for DAG\n const res = await waitForDeviceAuthorization({\n session: this.grantInProgress,\n metadata: this.metadata,\n clientId,\n });\n\n if (!res) {\n throw new RendezvousError(\n \"No response from device authorization endpoint\",\n ClientRendezvousFailureReason.Unknown,\n );\n }\n\n if (\"error\" in res) {\n let reason: MSC4108FailureReason = MSC4108FailureReason.UnexpectedMessageReceived;\n if (res.error === \"expired_token\") {\n reason = MSC4108FailureReason.AuthorizationExpired;\n } else if (res.error === \"access_denied\") {\n reason = MSC4108FailureReason.UserCancelled;\n }\n await this.send({\n type: PayloadType.Failure,\n reason,\n } satisfies FailurePayload);\n\n throw new RendezvousError(\"Rejection from device authorization endpoint\", reason);\n }\n\n return res;\n }\n\n /**\n * The fifth (and final) step in the OAuth2 QR login process.\n * To be called after the new device has completed authentication.\n */\n public async shareSecrets(): Promise<{ secrets?: Omit<SecretsPayload, \"type\"> }> {\n if (this.isNewDevice) {\n await this.send<SuccessPayload>({\n type: PayloadType.Success,\n });\n // then wait for secrets\n logger.info(\"Waiting for secrets message\");\n const payload = await this.receive<SecretsPayload>();\n if (payload?.type === PayloadType.Failure) {\n throw new RendezvousError(\"Failed\", payload.reason);\n }\n\n if (payload?.type !== PayloadType.Secrets) {\n await this.send<FailurePayload>({\n type: PayloadType.Failure,\n reason: MSC4108FailureReason.UnexpectedMessageReceived,\n });\n throw new RendezvousError(\n \"Unexpected message received\",\n MSC4108FailureReason.UnexpectedMessageReceived,\n );\n }\n return { secrets: payload };\n // then done?\n } else {\n if (!this.expectingNewDeviceId) {\n throw new Error(\"No new device ID expected\");\n }\n await this.send<AcceptedPayload>({\n type: PayloadType.ProtocolAccepted,\n });\n\n logger.info(\"Waiting for outcome message\");\n const payload = await this.receive<SuccessPayload | DeclinedPayload>();\n\n if (payload?.type === PayloadType.Failure) {\n throw new RendezvousError(\"Failed\", payload.reason);\n }\n\n if (payload?.type === PayloadType.Declined) {\n throw new RendezvousError(\"User declined\", ClientRendezvousFailureReason.UserDeclined);\n }\n\n if (payload?.type !== PayloadType.Success) {\n await this.send<FailurePayload>({\n type: PayloadType.Failure,\n reason: MSC4108FailureReason.UnexpectedMessageReceived,\n });\n throw new RendezvousError(\"Unexpected message\", MSC4108FailureReason.UnexpectedMessageReceived);\n }\n\n const timeout = Date.now() + 10000; // wait up to 10 seconds\n do {\n // is the device visible via the Homeserver?\n try {\n const device = await this.client?.getDevice(this.expectingNewDeviceId);\n\n if (device) {\n // if so, return the secrets\n const secretsBundle = await this.client!.getCrypto()!.exportSecretsBundle!();\n if (this.channel.cancelled) {\n throw new RendezvousError(\"User cancelled\", MSC4108FailureReason.UserCancelled);\n }\n // send secrets\n await this.send<SecretsPayload>({\n type: PayloadType.Secrets,\n ...secretsBundle,\n });\n return { secrets: secretsBundle };\n // let the other side close the rendezvous session\n }\n } catch (err: MatrixError | unknown) {\n if (err instanceof MatrixError && err.httpStatus === 404) {\n // not found, so keep waiting until timeout\n } else {\n throw err;\n }\n }\n await sleep(1000);\n } while (Date.now() < timeout);\n\n await this.send<FailurePayload>({\n type: PayloadType.Failure,\n reason: MSC4108FailureReason.DeviceNotFound,\n });\n throw new RendezvousError(\"New device not found\", MSC4108FailureReason.DeviceNotFound);\n }\n }\n\n private async receive<T extends MSC4108Payload>(): Promise<T | FailurePayload | undefined> {\n return (await this.channel.secureReceive()) as T | undefined;\n }\n\n private async send<T extends MSC4108Payload>(payload: T): Promise<void> {\n await this.channel.secureSend(payload);\n }\n\n /**\n * Decline the login on the existing device.\n */\n public async declineLoginOnExistingDevice(): Promise<void> {\n if (!this.isExistingDevice) {\n throw new Error(\"Can only decline login on existing device\");\n }\n await this.send<FailurePayload>({\n type: PayloadType.Failure,\n reason: MSC4108FailureReason.UserCancelled,\n });\n }\n\n /**\n * Cancels the rendezvous session.\n * @param reason the reason for the cancellation\n */\n public async cancel(reason: MSC4108FailureReason | ClientRendezvousFailureReason): Promise<void> {\n this.onFailure?.(reason);\n await this.channel.cancel(reason);\n }\n\n /**\n * Closes the rendezvous session.\n */\n public async close(): Promise<void> {\n await this.channel.close();\n }\n}\n"],"mappings":";;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA,SAAS,Y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