matrix-js-sdk 42.1.0 → 42.2.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 +8 -0
- package/lib/@types/beacon.d.ts +1 -1
- package/lib/@types/beacon.js +1 -1
- package/lib/@types/beacon.js.map +1 -1
- package/lib/@types/extensible_events.d.ts.map +1 -1
- package/lib/@types/extensible_events.js.map +1 -1
- package/lib/autodiscovery.js.map +1 -1
- package/lib/browser-index.js.map +1 -1
- package/lib/client.d.ts +12 -5
- package/lib/client.d.ts.map +1 -1
- package/lib/client.js +23 -26
- package/lib/client.js.map +1 -1
- package/lib/common-crypto/key-passphrase.js +1 -1
- package/lib/common-crypto/key-passphrase.js.map +1 -1
- package/lib/crypto/store/indexeddb-crypto-store-backend.js +2 -1
- package/lib/crypto/store/indexeddb-crypto-store-backend.js.map +1 -1
- package/lib/crypto/store/indexeddb-crypto-store.d.ts.map +1 -1
- package/lib/crypto/store/indexeddb-crypto-store.js +1 -1
- package/lib/crypto/store/indexeddb-crypto-store.js.map +1 -1
- package/lib/crypto/store/memory-crypto-store.js.map +1 -1
- package/lib/embedded.d.ts +16 -0
- package/lib/embedded.d.ts.map +1 -1
- package/lib/embedded.js +19 -6
- package/lib/embedded.js.map +1 -1
- package/lib/matrixrtc/MatrixRTCSession.js.map +1 -1
- package/lib/matrixrtc/MembershipManager.js.map +1 -1
- package/lib/matrixrtc/MembershipManagerActionScheduler.js.map +1 -1
- package/lib/matrixrtc/RTCEncryptionManager.js.map +1 -1
- package/lib/matrixrtc/ToDeviceKeyTransport.js.map +1 -1
- package/lib/matrixrtc/membershipData/rtc.js.map +1 -1
- package/lib/matrixrtc/utils.d.ts +0 -1
- package/lib/matrixrtc/utils.d.ts.map +1 -1
- package/lib/matrixrtc/utils.js +0 -1
- package/lib/matrixrtc/utils.js.map +1 -1
- package/lib/models/event-timeline-set.js +3 -3
- package/lib/models/event-timeline-set.js.map +1 -1
- package/lib/models/event.d.ts.map +1 -1
- package/lib/models/event.js.map +1 -1
- package/lib/models/invites-ignorer.js.map +1 -1
- package/lib/models/poll.js.map +1 -1
- package/lib/models/read-receipt.js.map +1 -1
- package/lib/models/relations-container.d.ts +10 -0
- package/lib/models/relations-container.d.ts.map +1 -1
- package/lib/models/relations-container.js +39 -17
- package/lib/models/relations-container.js.map +1 -1
- package/lib/models/relations.js +1 -1
- package/lib/models/relations.js.map +1 -1
- package/lib/models/room.js +3 -3
- package/lib/models/room.js.map +1 -1
- package/lib/models/thread.d.ts +3 -0
- package/lib/models/thread.d.ts.map +1 -1
- package/lib/models/thread.js +36 -3
- package/lib/models/thread.js.map +1 -1
- package/lib/oauth/authorize.js +1 -1
- package/lib/oauth/authorize.js.map +1 -1
- package/lib/oauth/index.js +4 -2
- package/lib/oauth/index.js.map +1 -1
- package/lib/pollingCachedValue.d.ts +77 -0
- package/lib/pollingCachedValue.d.ts.map +1 -0
- package/lib/pollingCachedValue.js +160 -0
- package/lib/pollingCachedValue.js.map +1 -0
- package/lib/pushprocessor.js.map +1 -1
- package/lib/receipt-accumulator.d.ts.map +1 -1
- package/lib/receipt-accumulator.js.map +1 -1
- package/lib/rendezvous/MSC4108SignInWithQR.d.ts.map +1 -1
- package/lib/rendezvous/MSC4108SignInWithQR.js +2 -3
- package/lib/rendezvous/MSC4108SignInWithQR.js.map +1 -1
- package/lib/rtcTransportsCachedValue.d.ts +9 -0
- package/lib/rtcTransportsCachedValue.d.ts.map +1 -0
- package/lib/rtcTransportsCachedValue.js +38 -0
- package/lib/rtcTransportsCachedValue.js.map +1 -0
- package/lib/rust-crypto/PerSessionKeyBackupDownloader.js.map +1 -1
- package/lib/rust-crypto/backup.d.ts +2 -3
- package/lib/rust-crypto/backup.d.ts.map +1 -1
- package/lib/rust-crypto/backup.js.map +1 -1
- package/lib/rust-crypto/index.d.ts +10 -4
- package/lib/rust-crypto/index.d.ts.map +1 -1
- package/lib/rust-crypto/index.js +20 -3
- package/lib/rust-crypto/index.js.map +1 -1
- package/lib/rust-crypto/libolm_migration.js.map +1 -1
- package/lib/rust-crypto/rust-crypto.js.map +1 -1
- package/lib/sliding-sync-sdk.js.map +1 -1
- package/lib/sliding-sync.js.map +1 -1
- package/lib/store/indexeddb-local-backend.js +1 -1
- package/lib/store/indexeddb-local-backend.js.map +1 -1
- package/lib/store/indexeddb-store-worker.d.ts.map +1 -1
- package/lib/store/indexeddb-store-worker.js +1 -0
- package/lib/store/indexeddb-store-worker.js.map +1 -1
- package/lib/sync.d.ts.map +1 -1
- package/lib/sync.js.map +1 -1
- package/lib/utils.d.ts +1 -1
- package/lib/utils.d.ts.map +1 -1
- package/lib/utils.js +1 -0
- package/lib/utils.js.map +1 -1
- package/lib/webrtc/call.js.map +1 -1
- package/lib/webrtc/groupCall.js.map +1 -1
- package/lib/webrtc/mediaHandler.js.map +1 -1
- package/lib/webrtc/stats/callStatsReportGatherer.js.map +1 -1
- package/lib/webrtc/stats/transportStatsBuilder.js.map +1 -1
- package/lib/wellKnownCachedValue.d.ts +8 -0
- package/lib/wellKnownCachedValue.d.ts.map +1 -0
- package/lib/wellKnownCachedValue.js +34 -0
- package/lib/wellKnownCachedValue.js.map +1 -0
- package/package.json +4 -4
- package/src/@types/beacon.ts +1 -1
- package/src/@types/extensible_events.ts +3 -4
- package/src/autodiscovery.ts +2 -2
- package/src/browser-index.ts +1 -1
- package/src/client.ts +48 -40
- package/src/common-crypto/key-passphrase.ts +1 -1
- package/src/crypto/store/indexeddb-crypto-store-backend.ts +2 -1
- package/src/crypto/store/indexeddb-crypto-store.ts +1 -3
- package/src/crypto/store/memory-crypto-store.ts +1 -1
- package/src/embedded.ts +34 -11
- package/src/matrixrtc/MatrixRTCSession.ts +3 -3
- package/src/matrixrtc/MembershipManager.ts +1 -1
- package/src/matrixrtc/MembershipManagerActionScheduler.ts +1 -1
- package/src/matrixrtc/RTCEncryptionManager.ts +2 -2
- package/src/matrixrtc/ToDeviceKeyTransport.ts +3 -3
- package/src/matrixrtc/membershipData/rtc.ts +1 -1
- package/src/matrixrtc/utils.ts +0 -2
- package/src/models/event-timeline-set.ts +3 -3
- package/src/models/event.ts +7 -10
- package/src/models/invites-ignorer.ts +1 -1
- package/src/models/poll.ts +1 -1
- package/src/models/read-receipt.ts +1 -1
- package/src/models/relations-container.ts +55 -19
- package/src/models/relations.ts +1 -1
- package/src/models/room.ts +9 -9
- package/src/models/thread.ts +49 -4
- package/src/oauth/authorize.ts +1 -1
- package/src/oauth/index.ts +2 -2
- package/src/pollingCachedValue.ts +184 -0
- package/src/pushprocessor.ts +3 -3
- package/src/receipt-accumulator.ts +1 -2
- package/src/rendezvous/MSC4108SignInWithQR.ts +3 -4
- package/src/rtcTransportsCachedValue.ts +40 -0
- package/src/rust-crypto/PerSessionKeyBackupDownloader.ts +1 -1
- package/src/rust-crypto/backup.ts +1 -5
- package/src/rust-crypto/index.ts +23 -25
- package/src/rust-crypto/libolm_migration.ts +1 -1
- package/src/rust-crypto/rust-crypto.ts +3 -3
- package/src/sliding-sync-sdk.ts +1 -1
- package/src/sliding-sync.ts +1 -1
- package/src/store/indexeddb-local-backend.ts +1 -1
- package/src/store/indexeddb-store-worker.ts +1 -0
- package/src/sync.ts +4 -3
- package/src/utils.ts +3 -2
- package/src/webrtc/call.ts +6 -6
- package/src/webrtc/groupCall.ts +7 -7
- package/src/webrtc/mediaHandler.ts +1 -1
- package/src/webrtc/stats/callStatsReportGatherer.ts +2 -2
- package/src/webrtc/stats/transportStatsBuilder.ts +1 -1
- package/src/wellKnownCachedValue.ts +34 -0
package/lib/models/thread.d.ts
CHANGED
|
@@ -92,6 +92,8 @@ export declare class Thread extends ReadReceipt<ThreadEmittedEvents, ThreadEvent
|
|
|
92
92
|
*/
|
|
93
93
|
initialEventsFetched: boolean;
|
|
94
94
|
private initalEventFetchProm;
|
|
95
|
+
private preInitEventTargets;
|
|
96
|
+
private preInitObserverState;
|
|
95
97
|
/**
|
|
96
98
|
* An array of events to add to the timeline once the thread has been initialised
|
|
97
99
|
* with server suppport.
|
|
@@ -137,6 +139,7 @@ export declare class Thread extends ReadReceipt<ThreadEmittedEvents, ThreadEvent
|
|
|
137
139
|
*/
|
|
138
140
|
addEvent(event: MatrixEvent, toStartOfTimeline: boolean, emit?: boolean): void;
|
|
139
141
|
private addRelatedThreadEvent;
|
|
142
|
+
private findPreInitTargetEvent;
|
|
140
143
|
processEvent(event: MatrixEvent | null | undefined): Promise<void>;
|
|
141
144
|
/**
|
|
142
145
|
* Processes the receipts that were caught during initial sync
|
|
@@ -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,MAAM,4BAA4B,CAAC;AAGpG,oBAAY,WAAW;IACnB,GAAG,eAAe;IAClB,MAAM,kBAAkB;IACxB,QAAQ,oBAAoB;IAC5B,UAAU,sBAAsB;IAChC,MAAM,kBAAkB;CAC3B;AAED,MAAM,MAAM,mBAAmB,GAAG,OAAO,CAAC,WAAW,EAAE,WAAW,CAAC,GAAG,CAAC,GAAG,SAAS,CAAC,QAAQ,GAAG,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AgB,wBAAwB,CAAC,IAAI,EAAE,gBAAgB,GAAG,IAAI,GAAG,KAAK,GAAG,cAAc,CAO9F"}
|
package/lib/models/thread.js
CHANGED
|
@@ -109,6 +109,10 @@ export class Thread extends ReadReceipt {
|
|
|
109
109
|
*/
|
|
110
110
|
_defineProperty(this, "initialEventsFetched", !Thread.hasServerSideSupport);
|
|
111
111
|
_defineProperty(this, "initalEventFetchProm", void 0);
|
|
112
|
+
_defineProperty(this, "preInitEventTargets", new Map());
|
|
113
|
+
_defineProperty(this, "preInitObserverState", {
|
|
114
|
+
active: true
|
|
115
|
+
});
|
|
112
116
|
/**
|
|
113
117
|
* An array of events to add to the timeline once the thread has been initialised
|
|
114
118
|
* with server suppport.
|
|
@@ -190,6 +194,9 @@ export class Thread extends ReadReceipt {
|
|
|
190
194
|
}, this.client, this);
|
|
191
195
|
this.reEmitter = new TypedReEmitter(this);
|
|
192
196
|
this.reEmitter.reEmit(this.timelineSet, [RoomEvent.Timeline, RoomEvent.TimelineReset]);
|
|
197
|
+
this.once(ThreadEvent.Delete, () => {
|
|
198
|
+
this.preInitObserverState.active = false;
|
|
199
|
+
});
|
|
193
200
|
this.room.on(MatrixEventEvent.BeforeRedaction, this.onBeforeRedaction);
|
|
194
201
|
this.room.on(RoomEvent.Redaction, this.onRedaction);
|
|
195
202
|
this.room.on(RoomEvent.LocalEchoUpdated, this.onLocalEcho);
|
|
@@ -301,6 +308,10 @@ export class Thread extends ReadReceipt {
|
|
|
301
308
|
// Modify this event to point at our room's state, and mark its thread
|
|
302
309
|
// as this.
|
|
303
310
|
this.setEventMetadata(event);
|
|
311
|
+
const eventId = event.getId();
|
|
312
|
+
if (!this.initialEventsFetched && eventId && !event.isRelation(RelationType.Annotation) && !event.isRelation(RelationType.Replace)) {
|
|
313
|
+
this.preInitEventTargets.set(eventId, event);
|
|
314
|
+
}
|
|
304
315
|
|
|
305
316
|
// Decide whether this event is going to be added at the end of the timeline.
|
|
306
317
|
const lastReply = this.lastReply();
|
|
@@ -366,12 +377,30 @@ export class Thread extends ReadReceipt {
|
|
|
366
377
|
*/
|
|
367
378
|
this.replayEvents?.push(event);
|
|
368
379
|
|
|
369
|
-
//
|
|
370
|
-
// reaction counts/summary visible while the thread is still initialising.
|
|
371
|
-
// Only aggregate as child: parent aggregation is unnecessary here.
|
|
380
|
+
// Aggregate annotations immediately to keep reaction counts visible.
|
|
372
381
|
if (event.isRelation(RelationType.Annotation)) {
|
|
373
382
|
this.timelineSet.relations?.aggregateChildEvent(event, this.timelineSet);
|
|
374
383
|
}
|
|
384
|
+
|
|
385
|
+
// Edits can also be aggregated immediately when their target is already
|
|
386
|
+
// known. If it is not known yet, replay still handles them after pagination.
|
|
387
|
+
if (event.isRelation(RelationType.Replace)) {
|
|
388
|
+
const targetEventId = event.getRelation()?.event_id;
|
|
389
|
+
const targetEvent = targetEventId ? this.findPreInitTargetEvent(targetEventId) : undefined;
|
|
390
|
+
if (targetEvent && targetEventId) {
|
|
391
|
+
const weakThread = new WeakRef(this);
|
|
392
|
+
const observerState = this.preInitObserverState;
|
|
393
|
+
const eventId = event.getId();
|
|
394
|
+
void this.timelineSet.relations.aggregateChildEvent(event, this.timelineSet, targetEvent).then(() => {
|
|
395
|
+
const thread = weakThread.deref();
|
|
396
|
+
if (!thread || !observerState.active) return;
|
|
397
|
+
const effectiveTarget = thread.findPreInitTargetEvent(targetEventId);
|
|
398
|
+
if (effectiveTarget?.replacingEvent()?.getId() === eventId) {
|
|
399
|
+
thread.emit(ThreadEvent.Update, thread);
|
|
400
|
+
}
|
|
401
|
+
}).catch(error => logger.error("Failed to aggregate pre-initialization thread edit: ", error));
|
|
402
|
+
}
|
|
403
|
+
}
|
|
375
404
|
} else {
|
|
376
405
|
// Case 2: this is happening later, and we have a timeline. In
|
|
377
406
|
// this case, these events might be out-of order.
|
|
@@ -399,6 +428,9 @@ export class Thread extends ReadReceipt {
|
|
|
399
428
|
// Aggregation is handled by EventTimelineSet when inserting/adding.
|
|
400
429
|
}
|
|
401
430
|
}
|
|
431
|
+
findPreInitTargetEvent(eventId) {
|
|
432
|
+
return this.timelineSet.findEventById(eventId) ?? this.room.findEventById(eventId) ?? this.preInitEventTargets.get(eventId) ?? (this.lastEvent?.getId() === eventId ? this.lastEvent : undefined);
|
|
433
|
+
}
|
|
402
434
|
async processEvent(event) {
|
|
403
435
|
if (event) {
|
|
404
436
|
this.setEventMetadata(event);
|
|
@@ -549,6 +581,7 @@ export class Thread extends ReadReceipt {
|
|
|
549
581
|
this.addEvent(event, false);
|
|
550
582
|
}
|
|
551
583
|
this.replayEvents = null;
|
|
584
|
+
this.preInitEventTargets.clear();
|
|
552
585
|
// just to make sure that, if we've created a timeline window for this thread before the thread itself
|
|
553
586
|
// existed (e.g. when creating a new thread), we'll make sure the panel is force refreshed correctly.
|
|
554
587
|
this.emit(RoomEvent.TimelineReset, this.room, this.timelineSet, true);
|
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\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\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 // 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 // For annotations (reactions), aggregate immediately (pre-init) to keep\n // reaction counts/summary visible while the thread is still initialising.\n // Only aggregate as child: parent aggregation is unnecessary here.\n if (event.isRelation(RelationType.Annotation)) {\n this.timelineSet.relations?.aggregateChildEvent(event, this.timelineSet);\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 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 // 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,y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pE,OAAO,IAAI,CAAC,IAAI,CAAC,2BAA2B,CAAC,MAAM,CAAC;EACxD;AACJ;;AAEA;AACA;AACA;AACA;AACA;AACA;AALA,gBAzzBa,MAAM,0BACsB,cAAc,CAAC,IAAI;AAAA,gBAD/C,MAAM,8BAE0B,cAAc,CAAC,IAAI;AAAA,gBAFnD,MAAM,uCAGmC,cAAc,CAAC,IAAI;AA4zBzE,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":[]}
|
|
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 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,S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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":[]}
|
package/lib/oauth/authorize.js
CHANGED
|
@@ -18,7 +18,7 @@ limitations under the License.
|
|
|
18
18
|
import { secureRandomString } from "../randomstring.js";
|
|
19
19
|
import { OAuth2Error } from "./error.js";
|
|
20
20
|
import { hasOptionalNumberProperty, hasOptionalStringProperty, hasRequiredNumberProperty, hasRequiredStringProperty, isRecord } from "../@types/type-guards.js";
|
|
21
|
-
import { Method } from "../http-api";
|
|
21
|
+
import { Method } from "../http-api/index.js";
|
|
22
22
|
import { OAuthGrantType } from "./register.js";
|
|
23
23
|
import { sleep } from "../utils.js";
|
|
24
24
|
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"authorize.js","names":[],"sources":["../../src/oauth/authorize.ts"],"sourcesContent":["/*\nCopyright 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 { secureRandomString } from \"../randomstring.ts\";\nimport { OAuth2Error } from \"./error.ts\";\nimport { type ValidatedAuthMetadata } from \"./discover.ts\";\nimport {\n hasOptionalNumberProperty,\n hasOptionalStringProperty,\n hasRequiredNumberProperty,\n hasRequiredStringProperty,\n isRecord,\n} from \"../@types/type-guards.ts\";\nimport { Method } from \"../http-api\";\nimport { OAuthGrantType } from \"./register.ts\";\nimport { sleep } from \"../utils.ts\";\n\n/**\n * The expected response type from the token endpoint during authorization code flow\n * Normalized to always use capitalized 'Bearer' for token_type\n *\n * See https://datatracker.ietf.org/doc/html/rfc6749#section-4.1.4\n */\nexport type BearerTokenResponse = Omit<ValidTokenResponse, \"token_type\"> & {\n token_type: \"Bearer\";\n};\n\n/**\n * Metadata from OAuth 2.0 token_endpoint as per\n * https://datatracker.ietf.org/doc/html/rfc6749#section-5.1\n * With validated properties required in type\n *\n * This response is expected for the authorization code grant and refresh token grant,\n * as defined in the Matrix spec.\n */\ninterface ValidTokenResponse {\n token_type: \"Bearer\" | \"bearer\";\n access_token: string;\n expires_in?: number;\n refresh_token?: string;\n scope?: string;\n}\n\n/**\n * Validate the given response matches the format expected for a {@link ValidTokenResponse}\n * @param response - the response to validate\n * @throws if the response does not match the expected format\n */\nexport function validateBearerTokenResponse(response: unknown): asserts response is ValidTokenResponse {\n if (\n !isRecord(response) ||\n !hasRequiredStringProperty(response, \"token_type\") ||\n // token_type is case-insensitive, some OPs return `token_type: \"bearer\"`\n response[\"token_type\"].toLowerCase() !== \"bearer\" ||\n !hasRequiredStringProperty(response, \"access_token\") ||\n !hasOptionalNumberProperty(response, \"expires_in\") ||\n !hasOptionalStringProperty(response, \"refresh_token\") ||\n !hasOptionalStringProperty(response, \"scope\")\n ) {\n throw new Error(OAuth2Error.InvalidBearerTokenResponse);\n }\n}\n\n/**\n * Generate the scope used in authorization request with OAuth2 IdP\n * @returns scope\n */\nexport const generateScope = (deviceId?: string): string => {\n const safeDeviceId = deviceId ?? secureRandomString(10);\n return `urn:matrix:client:api:* urn:matrix:client:device:${safeDeviceId}`;\n};\n\n/**\n * Normalize token_type to use capital case to make consuming the token response easier\n * token_type is case insensitive, and it is spec-compliant for OPs to return token_type: \"bearer\"\n * Later, when used in auth headers it is case sensitive and must be Bearer\n * See: https://datatracker.ietf.org/doc/html/rfc6749#section-4.1.4\n *\n * @param response - validated token response\n * @returns response with token_type set to 'Bearer'\n */\nexport const normalizeBearerTokenResponseTokenType = (response: ValidTokenResponse): BearerTokenResponse => ({\n ...response,\n token_type: \"Bearer\",\n});\n\n/**\n * Response from the OAuth2 token endpoint when exchanging a token for grant_type device_code.\n */\nexport interface DeviceAccessTokenResponse {\n access_token: string;\n token_type: string;\n refresh_token?: string;\n scope?: string;\n expires_in?: number;\n}\n\n/**\n * Validate the given response matches the format expected for a {@link DeviceAccessTokenResponse}\n * @param response - the response to validate\n * @throws if the response does not match the expected format\n */\nexport function isValidDeviceAccessTokenResponse(response: unknown): response is DeviceAccessTokenResponse {\n return (\n isRecord(response) &&\n hasRequiredStringProperty(response, \"access_token\") &&\n hasRequiredStringProperty(response, \"token_type\") &&\n hasOptionalStringProperty(response, \"refresh_token\") &&\n hasOptionalStringProperty(response, \"scope\") &&\n hasOptionalNumberProperty(response, \"expires_in\")\n );\n}\n\n/**\n * Error from the OAuth2 token endpoint when exchanging a token for grant_type device_code.\n */\nexport interface DeviceAccessTokenError {\n error: string;\n error_description?: string;\n error_uri?: string;\n session_state?: string;\n}\n\n/**\n * Response from the OAuth2 device authorization endpoint.\n * As specified in https://datatracker.ietf.org/doc/html/rfc8628#section-3.2\n */\nexport interface DeviceAuthorizationResponse {\n /** The device verification code. */\n device_code: string;\n /** The end-user verification code. */\n user_code: string;\n /**\n * The end-user verification URI on the authorization server.\n * The URI should be short and easy to remember as end users will be asked to manually type it into their user agent.\n */\n verification_uri: string;\n /**\n * The URI which doesn’t require the user to manually type the user_code, designed for non-textual transmission.\n */\n verification_uri_complete?: string;\n /** The lifetime in seconds of the \"device_code\" and \"user_code\". */\n expires_in: number;\n /**\n * The minimum amount of time in seconds that the client SHOULD wait between polling requests to the token endpoint.\n * If no value is provided, clients MUST use 5 as the default.\n */\n interval?: number;\n}\n\n/**\n * Validate the given response matches the format expected for a {@link DeviceAuthorizationResponse}\n * @param response - the response to validate\n * @throws if the response does not match the expected format\n */\nexport function validateDeviceAuthorizationResponse(\n response: unknown,\n): asserts response is DeviceAuthorizationResponse {\n if (\n !isRecord(response) ||\n !hasRequiredStringProperty(response, \"device_code\") ||\n !hasRequiredStringProperty(response, \"user_code\") ||\n !hasRequiredStringProperty(response, \"verification_uri\") ||\n !hasRequiredNumberProperty(response, \"expires_in\") ||\n !hasOptionalStringProperty(response, \"verification_uri_complete\") ||\n !hasOptionalNumberProperty(response, \"interval\")\n ) {\n throw new Error(OAuth2Error.InvalidDeviceAuthorizationResponse);\n }\n}\n\n/**\n * Begin OAuth2 device authorization flow.\n * @param options - The device authorization parameters.\n * @param options.clientId - the client ID returned from client registration.\n * @param options.scope - the scope to request for authorization.\n * @param options.metadata - the validated OAuth2 metadata for the Identity Provider.\n * @returns a promise that resolves to a device access token response,\n * or an error response if the user denies authorization or the device code expires.\n */\nexport const startDeviceAuthorization = async ({\n clientId,\n scope,\n metadata,\n}: {\n clientId: string;\n scope: string;\n metadata: ValidatedAuthMetadata;\n}): Promise<DeviceAuthorizationResponse> => {\n const body = new URLSearchParams({ client_id: clientId, scope: scope }).toString();\n\n const url = metadata.device_authorization_endpoint;\n if (!url) {\n throw new Error(\"No device_authorization_endpoint given\");\n }\n\n const response = await fetch(url, {\n method: Method.Post,\n headers: {\n \"Content-Type\": \"application/x-www-form-urlencoded\",\n },\n body,\n });\n\n const data = await response.json();\n validateDeviceAuthorizationResponse(data);\n return data;\n};\n\n/**\n * Polls the OAuth2 token endpoint until we get a device access token response, or encounter an unrecoverable error.\n * @param options - The device authorization parameters.\n * @param options.session - The session returned from a previous call to {@link startDeviceAuthorization}.\n * @param options.metadata - The validated OAuth2 metadata for the Identity Provider.\n * @param options.clientId - The client ID returned from client registration.\n * @returns a promise that resolves to a device access token response,\n * or an error response if the user denies authorization or the device code expires.\n */\nexport const waitForDeviceAuthorization = async ({\n session,\n metadata,\n clientId,\n}: {\n session: DeviceAuthorizationResponse;\n metadata: ValidatedAuthMetadata;\n clientId: string;\n}): Promise<DeviceAccessTokenResponse | DeviceAccessTokenError> => {\n let interval = (session.interval ?? 5) * 1000; // poll interval\n const expiration = Date.now() + session.expires_in * 1000;\n do {\n const body = new URLSearchParams({\n device_code: session.device_code,\n grant_type: OAuthGrantType.DeviceAuthorization,\n client_id: clientId,\n }).toString();\n const response = await fetch(metadata.token_endpoint, {\n method: Method.Post,\n headers: { \"Content-Type\": \"application/x-www-form-urlencoded\" },\n body,\n });\n\n const data = await response.json();\n\n if (response.ok && isValidDeviceAccessTokenResponse(data)) {\n return data;\n }\n const errorResponse = data as DeviceAccessTokenError;\n switch (errorResponse.error) {\n case \"authorization_pending\":\n break;\n case \"slow_down\":\n interval += 5000;\n break;\n case \"access_denied\":\n case \"expired_token\":\n return errorResponse;\n }\n await sleep(interval);\n } while (Date.now() < expiration);\n return { error: \"expired\" };\n};\n"],"mappings":";AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA,SAAS,kBAAkB,QAAQ,oBAAoB;AACvD,SAAS,WAAW,QAAQ,YAAY;AAExC,SACI,yBAAyB,EACzB,yBAAyB,EACzB,yBAAyB,EACzB,yBAAyB,EACzB,QAAQ,QACL,0BAA0B;AACjC,SAAS,MAAM,QAAQ,aAAa;AACpC,SAAS,cAAc,QAAQ,eAAe;AAC9C,SAAS,KAAK,QAAQ,aAAa;;AAEnC;AACA;AACA;AACA;AACA;AACA;;AAKA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AASA;AACA;AACA;AACA;AACA;AACA,OAAO,SAAS,2BAA2B,CAAC,QAAiB,EAA0C;EACnG,IACI,CAAC,QAAQ,CAAC,QAAQ,CAAC,IACnB,CAAC,yBAAyB,CAAC,QAAQ,EAAE,YAAY,CAAC;EAClD;EACA,QAAQ,CAAC,YAAY,CAAC,CAAC,WAAW,CAAC,CAAC,KAAK,QAA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UAAU,GAAG,IAAI;EACzD,GAAG;IACC,MAAM,IAAI,GAAG,IAAI,eAAe,CAAC;MAC7B,WAAW,EAAE,OAAO,CAAC,WAAW;MAChC,UAAU,EAAE,cAAc,CAAC,mBAAmB;MAC9C,SAAS,EAAE;IACf,CAAC,CAAC,CAAC,QAAQ,CAAC,CAAC;IACb,MAAM,QAAQ,GAAG,MAAM,KAAK,CAAC,QAAQ,CAAC,cAAc,EAAE;MAClD,MAAM,EAAE,MAAM,CAAC,IAAI;MACnB,OAAO,EAAE;QAAE,cAAc,EAAE;MAAoC,CAAC;MAChE;IACJ,CAAC,CAAC;IAEF,MAAM,IAAI,GAAG,MAAM,QAAQ,CAAC,IAAI,CAAC,CAAC;IAElC,IAAI,QAAQ,CAAC,EAAE,IAAI,gCAAgC,CAAC,IAAI,CAAC,EAAE;MACvD,OAAO,IAAI;IACf;IACA,MAAM,aAAa,GAAG,IAA8B;IACpD,QAAQ,aAAa,CAAC,KAAK;MACvB,KAAK,uBAAuB;QACxB;MACJ,KAAK,WAAW;QACZ,QAAQ,IAAI,IAAI;QAChB;MACJ,KAAK,eAAe;MACpB,KAAK,eAAe;QAChB,OAAO,aAAa;IAC5B;IACA,MAAM,KAAK,CAAC,QAAQ,CAAC;EACzB,CAAC,QAAQ,IAAI,CAAC,GAAG,CAAC,CAAC,GAAG,UAAU;EAChC,OAAO;IAAE,KAAK,EAAE;EAAU,CAAC;AAC/B,CAAC","ignoreList":[]}
|
|
1
|
+
{"version":3,"file":"authorize.js","names":[],"sources":["../../src/oauth/authorize.ts"],"sourcesContent":["/*\nCopyright 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 { secureRandomString } from \"../randomstring.ts\";\nimport { OAuth2Error } from \"./error.ts\";\nimport { type ValidatedAuthMetadata } from \"./discover.ts\";\nimport {\n hasOptionalNumberProperty,\n hasOptionalStringProperty,\n hasRequiredNumberProperty,\n hasRequiredStringProperty,\n isRecord,\n} from \"../@types/type-guards.ts\";\nimport { Method } from \"../http-api/index.ts\";\nimport { OAuthGrantType } from \"./register.ts\";\nimport { sleep } from \"../utils.ts\";\n\n/**\n * The expected response type from the token endpoint during authorization code flow\n * Normalized to always use capitalized 'Bearer' for token_type\n *\n * See https://datatracker.ietf.org/doc/html/rfc6749#section-4.1.4\n */\nexport type BearerTokenResponse = Omit<ValidTokenResponse, \"token_type\"> & {\n token_type: \"Bearer\";\n};\n\n/**\n * Metadata from OAuth 2.0 token_endpoint as per\n * https://datatracker.ietf.org/doc/html/rfc6749#section-5.1\n * With validated properties required in type\n *\n * This response is expected for the authorization code grant and refresh token grant,\n * as defined in the Matrix spec.\n */\ninterface ValidTokenResponse {\n token_type: \"Bearer\" | \"bearer\";\n access_token: string;\n expires_in?: number;\n refresh_token?: string;\n scope?: string;\n}\n\n/**\n * Validate the given response matches the format expected for a {@link ValidTokenResponse}\n * @param response - the response to validate\n * @throws if the response does not match the expected format\n */\nexport function validateBearerTokenResponse(response: unknown): asserts response is ValidTokenResponse {\n if (\n !isRecord(response) ||\n !hasRequiredStringProperty(response, \"token_type\") ||\n // token_type is case-insensitive, some OPs return `token_type: \"bearer\"`\n response[\"token_type\"].toLowerCase() !== \"bearer\" ||\n !hasRequiredStringProperty(response, \"access_token\") ||\n !hasOptionalNumberProperty(response, \"expires_in\") ||\n !hasOptionalStringProperty(response, \"refresh_token\") ||\n !hasOptionalStringProperty(response, \"scope\")\n ) {\n throw new Error(OAuth2Error.InvalidBearerTokenResponse);\n }\n}\n\n/**\n * Generate the scope used in authorization request with OAuth2 IdP\n * @returns scope\n */\nexport const generateScope = (deviceId?: string): string => {\n const safeDeviceId = deviceId ?? secureRandomString(10);\n return `urn:matrix:client:api:* urn:matrix:client:device:${safeDeviceId}`;\n};\n\n/**\n * Normalize token_type to use capital case to make consuming the token response easier\n * token_type is case insensitive, and it is spec-compliant for OPs to return token_type: \"bearer\"\n * Later, when used in auth headers it is case sensitive and must be Bearer\n * See: https://datatracker.ietf.org/doc/html/rfc6749#section-4.1.4\n *\n * @param response - validated token response\n * @returns response with token_type set to 'Bearer'\n */\nexport const normalizeBearerTokenResponseTokenType = (response: ValidTokenResponse): BearerTokenResponse => ({\n ...response,\n token_type: \"Bearer\",\n});\n\n/**\n * Response from the OAuth2 token endpoint when exchanging a token for grant_type device_code.\n */\nexport interface DeviceAccessTokenResponse {\n access_token: string;\n token_type: string;\n refresh_token?: string;\n scope?: string;\n expires_in?: number;\n}\n\n/**\n * Validate the given response matches the format expected for a {@link DeviceAccessTokenResponse}\n * @param response - the response to validate\n * @throws if the response does not match the expected format\n */\nexport function isValidDeviceAccessTokenResponse(response: unknown): response is DeviceAccessTokenResponse {\n return (\n isRecord(response) &&\n hasRequiredStringProperty(response, \"access_token\") &&\n hasRequiredStringProperty(response, \"token_type\") &&\n hasOptionalStringProperty(response, \"refresh_token\") &&\n hasOptionalStringProperty(response, \"scope\") &&\n hasOptionalNumberProperty(response, \"expires_in\")\n );\n}\n\n/**\n * Error from the OAuth2 token endpoint when exchanging a token for grant_type device_code.\n */\nexport interface DeviceAccessTokenError {\n error: string;\n error_description?: string;\n error_uri?: string;\n session_state?: string;\n}\n\n/**\n * Response from the OAuth2 device authorization endpoint.\n * As specified in https://datatracker.ietf.org/doc/html/rfc8628#section-3.2\n */\nexport interface DeviceAuthorizationResponse {\n /** The device verification code. */\n device_code: string;\n /** The end-user verification code. */\n user_code: string;\n /**\n * The end-user verification URI on the authorization server.\n * The URI should be short and easy to remember as end users will be asked to manually type it into their user agent.\n */\n verification_uri: string;\n /**\n * The URI which doesn’t require the user to manually type the user_code, designed for non-textual transmission.\n */\n verification_uri_complete?: string;\n /** The lifetime in seconds of the \"device_code\" and \"user_code\". */\n expires_in: number;\n /**\n * The minimum amount of time in seconds that the client SHOULD wait between polling requests to the token endpoint.\n * If no value is provided, clients MUST use 5 as the default.\n */\n interval?: number;\n}\n\n/**\n * Validate the given response matches the format expected for a {@link DeviceAuthorizationResponse}\n * @param response - the response to validate\n * @throws if the response does not match the expected format\n */\nexport function validateDeviceAuthorizationResponse(\n response: unknown,\n): asserts response is DeviceAuthorizationResponse {\n if (\n !isRecord(response) ||\n !hasRequiredStringProperty(response, \"device_code\") ||\n !hasRequiredStringProperty(response, \"user_code\") ||\n !hasRequiredStringProperty(response, \"verification_uri\") ||\n !hasRequiredNumberProperty(response, \"expires_in\") ||\n !hasOptionalStringProperty(response, \"verification_uri_complete\") ||\n !hasOptionalNumberProperty(response, \"interval\")\n ) {\n throw new Error(OAuth2Error.InvalidDeviceAuthorizationResponse);\n }\n}\n\n/**\n * Begin OAuth2 device authorization flow.\n * @param options - The device authorization parameters.\n * @param options.clientId - the client ID returned from client registration.\n * @param options.scope - the scope to request for authorization.\n * @param options.metadata - the validated OAuth2 metadata for the Identity Provider.\n * @returns a promise that resolves to a device access token response,\n * or an error response if the user denies authorization or the device code expires.\n */\nexport const startDeviceAuthorization = async ({\n clientId,\n scope,\n metadata,\n}: {\n clientId: string;\n scope: string;\n metadata: ValidatedAuthMetadata;\n}): Promise<DeviceAuthorizationResponse> => {\n const body = new URLSearchParams({ client_id: clientId, scope: scope }).toString();\n\n const url = metadata.device_authorization_endpoint;\n if (!url) {\n throw new Error(\"No device_authorization_endpoint given\");\n }\n\n const response = await fetch(url, {\n method: Method.Post,\n headers: {\n \"Content-Type\": \"application/x-www-form-urlencoded\",\n },\n body,\n });\n\n const data = await response.json();\n validateDeviceAuthorizationResponse(data);\n return data;\n};\n\n/**\n * Polls the OAuth2 token endpoint until we get a device access token response, or encounter an unrecoverable error.\n * @param options - The device authorization parameters.\n * @param options.session - The session returned from a previous call to {@link startDeviceAuthorization}.\n * @param options.metadata - The validated OAuth2 metadata for the Identity Provider.\n * @param options.clientId - The client ID returned from client registration.\n * @returns a promise that resolves to a device access token response,\n * or an error response if the user denies authorization or the device code expires.\n */\nexport const waitForDeviceAuthorization = async ({\n session,\n metadata,\n clientId,\n}: {\n session: DeviceAuthorizationResponse;\n metadata: ValidatedAuthMetadata;\n clientId: string;\n}): Promise<DeviceAccessTokenResponse | DeviceAccessTokenError> => {\n let interval = (session.interval ?? 5) * 1000; // poll interval\n const expiration = Date.now() + session.expires_in * 1000;\n do {\n const body = new URLSearchParams({\n device_code: session.device_code,\n grant_type: OAuthGrantType.DeviceAuthorization,\n client_id: clientId,\n }).toString();\n const response = await fetch(metadata.token_endpoint, {\n method: Method.Post,\n headers: { \"Content-Type\": \"application/x-www-form-urlencoded\" },\n body,\n });\n\n const data = await response.json();\n\n if (response.ok && isValidDeviceAccessTokenResponse(data)) {\n return data;\n }\n const errorResponse = data as DeviceAccessTokenError;\n switch (errorResponse.error) {\n case \"authorization_pending\":\n break;\n case \"slow_down\":\n interval += 5000;\n break;\n case \"access_denied\":\n case \"expired_token\":\n return errorResponse;\n }\n await sleep(interval);\n } while (Date.now() < expiration);\n return { error: \"expired\" };\n};\n"],"mappings":";AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA,SAAS,kBAAkB,QAAQ,oBAAoB;AACvD,SAAS,WAAW,QAAQ,YAAY;AAExC,SACI,yBAAyB,EACzB,yBAAyB,EACzB,yBAAyB,EACzB,yBAAyB,EACzB,QAAQ,QACL,0BAA0B;AACjC,SAAS,MAAM,QAAQ,sBAAsB;AAC7C,SAAS,cAAc,QAAQ,eAAe;AAC9C,SAAS,KAAK,QAAQ,aAAa;;AAEnC;AACA;AACA;AACA;AACA;AACA;;AAKA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AASA;AACA;AACA;AACA;AACA;AACA,OAAO,SAAS,2BAA2B,CAAC,QAAiB,E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C,KAAkE;EAC/D,IAAI,QAAQ,GAAG,CAAC,OAAO,CAAC,QAAQ,IAAI,CAAC,IAAI,IAAI,CAAC,CAAC;EAC/C,MAAM,UAAU,GAAG,IAAI,CAAC,GAAG,CAAC,CAAC,GAAG,OAAO,CAAC,UAAU,GAAG,IAAI;EACzD,GAAG;IACC,MAAM,IAAI,GAAG,IAAI,eAAe,CAAC;MAC7B,WAAW,EAAE,OAAO,CAAC,WAAW;MAChC,UAAU,EAAE,cAAc,CAAC,mBAAmB;MAC9C,SAAS,EAAE;IACf,CAAC,CAAC,CAAC,QAAQ,CAAC,CAAC;IACb,MAAM,QAAQ,GAAG,MAAM,KAAK,CAAC,QAAQ,CAAC,cAAc,EAAE;MAClD,MAAM,EAAE,MAAM,CAAC,IAAI;MACnB,OAAO,EAAE;QAAE,cAAc,EAAE;MAAoC,CAAC;MAChE;IACJ,CAAC,CAAC;IAEF,MAAM,IAAI,GAAG,MAAM,QAAQ,CAAC,IAAI,CAAC,CAAC;IAElC,IAAI,QAAQ,CAAC,EAAE,IAAI,gCAAgC,CAAC,IAAI,CAAC,EAAE;MACvD,OAAO,IAAI;IACf;IACA,MAAM,aAAa,GAAG,IAA8B;IACpD,QAAQ,aAAa,CAAC,KAAK;MACvB,KAAK,uBAAuB;QACxB;MACJ,KAAK,WAAW;QACZ,QAAQ,IAAI,IAAI;QAChB;MACJ,KAAK,eAAe;MACpB,KAAK,eAAe;QAChB,OAAO,aAAa;IAC5B;IACA,MAAM,KAAK,CAAC,QAAQ,CAAC;EACzB,CAAC,QAAQ,IAAI,CAAC,GAAG,CAAC,CAAC,GAAG,UAAU;EAChC,OAAO;IAAE,KAAK,EAAE;EAAU,CAAC;AAC/B,CAAC","ignoreList":[]}
|
package/lib/oauth/index.js
CHANGED
|
@@ -20,7 +20,7 @@ import { generateScope, normalizeBearerTokenResponseTokenType, startDeviceAuthor
|
|
|
20
20
|
import { OAuthGrantType, urlHasCommonBase, validateRegistrationResponse } from "./register.js";
|
|
21
21
|
import { encodeUnpaddedBase64Url } from "../base64.js";
|
|
22
22
|
import { sha256 } from "../digest.js";
|
|
23
|
-
import { HTTPError, Method } from "../http-api";
|
|
23
|
+
import { HTTPError, Method } from "../http-api/index.js";
|
|
24
24
|
import { logger } from "../logger.js";
|
|
25
25
|
import { OAuth2Error } from "./error.js";
|
|
26
26
|
import { secureRandomString } from "../randomstring.js";
|
|
@@ -87,7 +87,9 @@ export class OAuth2 {
|
|
|
87
87
|
throw error;
|
|
88
88
|
} else {
|
|
89
89
|
logger.error("Dynamic registration request failed", error);
|
|
90
|
-
throw new Error(OAuth2Error.DynamicRegistrationFailed
|
|
90
|
+
throw new Error(OAuth2Error.DynamicRegistrationFailed, {
|
|
91
|
+
cause: error
|
|
92
|
+
});
|
|
91
93
|
}
|
|
92
94
|
}
|
|
93
95
|
}
|