matrix-js-sdk 41.4.0 → 41.5.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.
Files changed (109) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/README.md +1 -0
  3. package/lib/@types/json.d.ts +7 -0
  4. package/lib/@types/json.d.ts.map +1 -0
  5. package/lib/@types/json.js +1 -0
  6. package/lib/@types/json.js.map +1 -0
  7. package/lib/@types/requests.d.ts +6 -9
  8. package/lib/@types/requests.d.ts.map +1 -1
  9. package/lib/@types/requests.js.map +1 -1
  10. package/lib/client.d.ts +17 -2
  11. package/lib/client.d.ts.map +1 -1
  12. package/lib/client.js +27 -12
  13. package/lib/client.js.map +1 -1
  14. package/lib/filter.d.ts +20 -5
  15. package/lib/filter.d.ts.map +1 -1
  16. package/lib/filter.js +21 -0
  17. package/lib/filter.js.map +1 -1
  18. package/lib/models/user.d.ts +5 -0
  19. package/lib/models/user.d.ts.map +1 -1
  20. package/lib/models/user.js +5 -0
  21. package/lib/models/user.js.map +1 -1
  22. package/lib/oidc/authorize.d.ts +60 -0
  23. package/lib/oidc/authorize.d.ts.map +1 -1
  24. package/lib/oidc/authorize.js +115 -2
  25. package/lib/oidc/authorize.js.map +1 -1
  26. package/lib/oidc/register.d.ts.map +1 -1
  27. package/lib/oidc/register.js +5 -0
  28. package/lib/oidc/register.js.map +1 -1
  29. package/lib/rendezvous/MSC4108SignInWithQR.d.ts +19 -2
  30. package/lib/rendezvous/MSC4108SignInWithQR.d.ts.map +1 -1
  31. package/lib/rendezvous/MSC4108SignInWithQR.js +126 -36
  32. package/lib/rendezvous/MSC4108SignInWithQR.js.map +1 -1
  33. package/lib/rendezvous/channels/MSC4108SecureChannel.d.ts.map +1 -1
  34. package/lib/rendezvous/channels/MSC4108SecureChannel.js +4 -2
  35. package/lib/rendezvous/channels/MSC4108SecureChannel.js.map +1 -1
  36. package/lib/rendezvous/index.d.ts +36 -0
  37. package/lib/rendezvous/index.d.ts.map +1 -1
  38. package/lib/rendezvous/index.js +115 -0
  39. package/lib/rendezvous/index.js.map +1 -1
  40. package/lib/rendezvous/transports/MSC4108RendezvousSession.d.ts +1 -1
  41. package/lib/rendezvous/transports/MSC4108RendezvousSession.d.ts.map +1 -1
  42. package/lib/rendezvous/transports/MSC4108RendezvousSession.js.map +1 -1
  43. package/lib/rust-crypto/rust-crypto.d.ts.map +1 -1
  44. package/lib/rust-crypto/rust-crypto.js +2 -2
  45. package/lib/rust-crypto/rust-crypto.js.map +1 -1
  46. package/lib/store/index.d.ts +17 -1
  47. package/lib/store/index.d.ts.map +1 -1
  48. package/lib/store/index.js.map +1 -1
  49. package/lib/store/indexeddb-backend.d.ts +4 -0
  50. package/lib/store/indexeddb-backend.d.ts.map +1 -1
  51. package/lib/store/indexeddb-backend.js.map +1 -1
  52. package/lib/store/indexeddb-local-backend.d.ts +4 -1
  53. package/lib/store/indexeddb-local-backend.d.ts.map +1 -1
  54. package/lib/store/indexeddb-local-backend.js +45 -3
  55. package/lib/store/indexeddb-local-backend.js.map +1 -1
  56. package/lib/store/indexeddb-remote-backend.d.ts +4 -0
  57. package/lib/store/indexeddb-remote-backend.d.ts.map +1 -1
  58. package/lib/store/indexeddb-remote-backend.js +21 -3
  59. package/lib/store/indexeddb-remote-backend.js.map +1 -1
  60. package/lib/store/indexeddb-store-worker.d.ts.map +1 -1
  61. package/lib/store/indexeddb-store-worker.js +10 -1
  62. package/lib/store/indexeddb-store-worker.js.map +1 -1
  63. package/lib/store/indexeddb.d.ts +4 -0
  64. package/lib/store/indexeddb.d.ts.map +1 -1
  65. package/lib/store/indexeddb.js +18 -0
  66. package/lib/store/indexeddb.js.map +1 -1
  67. package/lib/store/memory.d.ts +5 -1
  68. package/lib/store/memory.d.ts.map +1 -1
  69. package/lib/store/memory.js +19 -0
  70. package/lib/store/memory.js.map +1 -1
  71. package/lib/store/stub.d.ts +3 -0
  72. package/lib/store/stub.d.ts.map +1 -1
  73. package/lib/store/stub.js +15 -0
  74. package/lib/store/stub.js.map +1 -1
  75. package/lib/sync-accumulator.d.ts +15 -0
  76. package/lib/sync-accumulator.d.ts.map +1 -1
  77. package/lib/sync-accumulator.js +4 -0
  78. package/lib/sync-accumulator.js.map +1 -1
  79. package/lib/sync.d.ts +9 -1
  80. package/lib/sync.d.ts.map +1 -1
  81. package/lib/sync.js +51 -9
  82. package/lib/sync.js.map +1 -1
  83. package/lib/webrtc/call.d.ts.map +1 -1
  84. package/lib/webrtc/call.js +1 -2
  85. package/lib/webrtc/call.js.map +1 -1
  86. package/package.json +7 -7
  87. package/src/@types/json.ts +16 -0
  88. package/src/@types/requests.ts +6 -9
  89. package/src/client.ts +40 -12
  90. package/src/filter.ts +31 -5
  91. package/src/models/user.ts +6 -0
  92. package/src/oidc/authorize.ts +135 -2
  93. package/src/oidc/register.ts +5 -0
  94. package/src/rendezvous/MSC4108SignInWithQR.ts +117 -4
  95. package/src/rendezvous/channels/MSC4108SecureChannel.ts +10 -2
  96. package/src/rendezvous/index.ts +115 -0
  97. package/src/rendezvous/transports/MSC4108RendezvousSession.ts +1 -1
  98. package/src/rust-crypto/rust-crypto.ts +6 -3
  99. package/src/store/index.ts +20 -1
  100. package/src/store/indexeddb-backend.ts +4 -0
  101. package/src/store/indexeddb-local-backend.ts +32 -1
  102. package/src/store/indexeddb-remote-backend.ts +13 -0
  103. package/src/store/indexeddb-store-worker.ts +9 -0
  104. package/src/store/indexeddb.ts +13 -0
  105. package/src/store/memory.ts +14 -1
  106. package/src/store/stub.ts +12 -0
  107. package/src/sync-accumulator.ts +16 -1
  108. package/src/sync.ts +48 -4
  109. package/src/webrtc/call.ts +1 -2
package/lib/filter.d.ts CHANGED
@@ -2,11 +2,13 @@ import { type EventType, type RelationType } from "./@types/event.ts";
2
2
  import { FilterComponent, type IFilterComponent } from "./filter-component.ts";
3
3
  import { type MatrixEvent } from "./models/event.ts";
4
4
  export interface IFilterDefinition {
5
- event_fields?: string[];
6
- event_format?: "client" | "federation";
7
- presence?: IFilterComponent;
8
- account_data?: IFilterComponent;
9
- room?: IRoomFilter;
5
+ "event_fields"?: string[];
6
+ "event_format"?: "client" | "federation";
7
+ "presence"?: IFilterComponent;
8
+ "account_data"?: IFilterComponent;
9
+ "room"?: IRoomFilter;
10
+ "profile_fields"?: ProfileFieldsFilter;
11
+ "org.matrix.msc4429.profile_fields"?: ProfileFieldsFilter;
10
12
  }
11
13
  export interface IRoomEventFilter extends IFilterComponent {
12
14
  "lazy_load_members"?: boolean;
@@ -30,6 +32,12 @@ interface IRoomFilter {
30
32
  timeline?: IRoomEventFilter;
31
33
  account_data?: IRoomEventFilter;
32
34
  }
35
+ /**
36
+ * Filter section used for requesting a set of extended profile fields that will be sent down the sync stream.
37
+ */
38
+ interface ProfileFieldsFilter {
39
+ ids: string[];
40
+ }
33
41
  export declare class Filter {
34
42
  readonly userId: string | undefined | null;
35
43
  filterId?: string | undefined;
@@ -92,6 +100,13 @@ export declare class Filter {
92
100
  * in responses.
93
101
  */
94
102
  setIncludeLeaveRooms(includeLeave: boolean): void;
103
+ /**
104
+ * Set the list of fields to be included in the profile information sent down the sync stream.
105
+ * @param ids The field IDs to sync.
106
+ * @param stable Whether to use the stable or unstable versions of this filter.
107
+ * @experimental
108
+ */
109
+ setUnstableMSC4429SyncUserProfiles(ids: string[], stable: boolean): void;
95
110
  }
96
111
  export {};
97
112
  //# sourceMappingURL=filter.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"filter.d.ts","sourceRoot":"","sources":["../src/filter.ts"],"names":[],"mappings":"AAgBA,OAAO,EAAE,KAAK,SAAS,EAAE,KAAK,YAAY,EAAE,MAAM,mBAAmB,CAAC;AAEtE,OAAO,EAAE,eAAe,EAAE,KAAK,gBAAgB,EAAE,MAAM,uBAAuB,CAAC;AAC/E,OAAO,EAAE,KAAK,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAiBrD,MAAM,WAAW,iBAAiB;IAC9B,YAAY,CAAC,EAAE,MAAM,EAAE,CAAC;IAC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,CAAC,MAAM,EAAE,MAAM,GAAG,SAAS,GAAG,IAAI,EAAE,QAAQ,EAAE,MAAM,EAAE,OAAO,EAAE,iBAAiB,GAAG,MAAM;IAM/G,OAAO,CAAC,UAAU,CAAyB;IAC3C,OAAO,CAAC,UAAU,CAAC,CAAkB;IACrC,OAAO,CAAC,kBAAkB,CAAC,CAAkB;IAE7C;;;;OAIG;gBAEiB,MAAM,EAAE,MAAM,GAAG,SAAS,GAAG,IAAI,EAC1C,QAAQ,CAAC,EAAE,MAAM,YAAA;IAG5B;;;OAGG;IACI,WAAW,IAAI,MAAM,GAAG,SAAS;IAIxC;;;OAGG;IACI,aAAa,IAAI,iBAAiB;IAIzC;;;OAGG;IACI,aAAa,CAAC,UAAU,EAAE,iBAAiB,GAAG,IAAI;IAiEzD;;;OAGG;IACI,8BAA8B,IAAI,eAAe,GAAG,SAAS;IAIpE;;;;;OAKG;IACI,kBAAkB,CAAC,MAAM,EAAE,WAAW,EAAE,GAAG,WAAW,EAAE;IAU/D;;;OAGG;IACI,gBAAgB,CAAC,KAAK,EAAE,MAAM,GAAG,IAAI;IAI5C;;OAEG;IACI,4BAA4B,CAAC,OAAO,EAAE,OAAO,GAAG,IAAI;IAapD,kBAAkB,CAAC,OAAO,EAAE,OAAO,GAAG,IAAI;IAIjD;;;;OAIG;IACI,oBAAoB,CAAC,YAAY,EAAE,OAAO,GAAG,IAAI;IAIxD;;;;;OAKG;IACI,kCAAkC,CAAC,GAAG,EAAE,MAAM,EAAE,EAAE,MAAM,EAAE,OAAO,GAAG,IAAI;CAMlF"}
package/lib/filter.js CHANGED
@@ -19,6 +19,9 @@ limitations under the License.
19
19
 
20
20
  import { UNREAD_THREAD_NOTIFICATIONS } from "./@types/sync.js";
21
21
  import { FilterComponent } from "./filter-component.js";
22
+ import { NamespacedValue } from "./NamespacedValue.js";
23
+ var profileFieldsFilterName = new NamespacedValue("profile_fields", "org.matrix.msc4429.profile_fields");
24
+
22
25
  /**
23
26
  */
24
27
  function setProp(obj, keyNesting, val) {
@@ -35,6 +38,10 @@ function setProp(obj, keyNesting, val) {
35
38
 
36
39
  /* eslint-disable camelcase */
37
40
 
41
+ /**
42
+ * Filter section used for requesting a set of extended profile fields that will be sent down the sync stream.
43
+ */
44
+
38
45
  /* eslint-enable camelcase */
39
46
 
40
47
  export class Filter {
@@ -200,6 +207,20 @@ export class Filter {
200
207
  setIncludeLeaveRooms(includeLeave) {
201
208
  setProp(this.definition, "room.include_leave", includeLeave);
202
209
  }
210
+
211
+ /**
212
+ * Set the list of fields to be included in the profile information sent down the sync stream.
213
+ * @param ids The field IDs to sync.
214
+ * @param stable Whether to use the stable or unstable versions of this filter.
215
+ * @experimental
216
+ */
217
+ setUnstableMSC4429SyncUserProfiles(ids, stable) {
218
+ var _profileFieldsFilterN;
219
+ var field = stable ? profileFieldsFilterName.name : (_profileFieldsFilterN = profileFieldsFilterName.unstable) !== null && _profileFieldsFilterN !== void 0 ? _profileFieldsFilterN : profileFieldsFilterName.name;
220
+ this.definition[field] = {
221
+ ids
222
+ };
223
+ }
203
224
  }
204
225
  _defineProperty(Filter, "LAZY_LOADING_MESSAGES_FILTER", {
205
226
  lazy_load_members: true
package/lib/filter.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"filter.js","names":["UNREAD_THREAD_NOTIFICATIONS","FilterComponent","setProp","obj","keyNesting","val","nestedKeys","split","currentObj","i","length","Filter","fromJson","userId","filterId","jsonObj","filter","setDefinition","constructor","_defineProperty","getFilterId","getDefinition","definition","roomFilterJson","room","roomFilterFields","rooms","not_rooms","roomFilter","roomTimelineFilter","timeline","getRoomTimelineFilterComponent","filterRoomTimeline","events","setTimelineLimit","limit","setUnreadThreadNotifications","enabled","_this$definition","_this$definition2","_objectSpread","name","setLazyLoadMembers","setIncludeLeaveRooms","includeLeave","lazy_load_members"],"sources":["../src/filter.ts"],"sourcesContent":["/*\nCopyright 2015 - 2021 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 EventType, type RelationType } from \"./@types/event.ts\";\nimport { UNREAD_THREAD_NOTIFICATIONS } from \"./@types/sync.ts\";\nimport { FilterComponent, type IFilterComponent } from \"./filter-component.ts\";\nimport { type MatrixEvent } from \"./models/event.ts\";\n\n/**\n */\nfunction setProp(obj: Record<string, any>, keyNesting: string, val: any): void {\n const nestedKeys = keyNesting.split(\".\") as [keyof typeof obj];\n let currentObj = obj;\n for (let i = 0; i < nestedKeys.length - 1; i++) {\n if (!currentObj[nestedKeys[i]]) {\n currentObj[nestedKeys[i]] = {};\n }\n currentObj = currentObj[nestedKeys[i]];\n }\n currentObj[nestedKeys[nestedKeys.length - 1]] = val;\n}\n\n/* eslint-disable camelcase */\nexport interface IFilterDefinition {\n event_fields?: string[];\n event_format?: \"client\" | \"federation\";\n presence?: IFilterComponent;\n account_data?: IFilterComponent;\n room?: IRoomFilter;\n}\n\nexport interface IRoomEventFilter extends IFilterComponent {\n \"lazy_load_members\"?: boolean;\n \"include_redundant_members\"?: boolean;\n \"types\"?: Array<EventType | string>;\n \"related_by_senders\"?: Array<RelationType | string>;\n \"related_by_rel_types\"?: string[];\n \"unread_thread_notifications\"?: boolean;\n \"org.matrix.msc3773.unread_thread_notifications\"?: boolean;\n\n // Unstable values\n \"io.element.relation_senders\"?: Array<RelationType | string>;\n \"io.element.relation_types\"?: string[];\n}\n\ninterface IStateFilter extends IRoomEventFilter {}\n\ninterface IRoomFilter {\n not_rooms?: string[];\n rooms?: string[];\n ephemeral?: IRoomEventFilter;\n include_leave?: boolean;\n state?: IStateFilter;\n timeline?: IRoomEventFilter;\n account_data?: IRoomEventFilter;\n}\n/* eslint-enable camelcase */\n\nexport class Filter {\n public static LAZY_LOADING_MESSAGES_FILTER = {\n lazy_load_members: true,\n };\n\n /**\n * Create a filter from existing data.\n */\n public static fromJson(userId: string | undefined | null, filterId: string, jsonObj: IFilterDefinition): Filter {\n const filter = new Filter(userId, filterId);\n filter.setDefinition(jsonObj);\n return filter;\n }\n\n private definition: IFilterDefinition = {};\n private roomFilter?: FilterComponent;\n private roomTimelineFilter?: FilterComponent;\n\n /**\n * Construct a new Filter.\n * @param userId - The user ID for this filter.\n * @param filterId - The filter ID if known.\n */\n public constructor(\n public readonly userId: string | undefined | null,\n public filterId?: string,\n ) {}\n\n /**\n * Get the ID of this filter on your homeserver (if known)\n * @returns The filter ID\n */\n public getFilterId(): string | undefined {\n return this.filterId;\n }\n\n /**\n * Get the JSON body of the filter.\n * @returns The filter definition\n */\n public getDefinition(): IFilterDefinition {\n return this.definition;\n }\n\n /**\n * Set the JSON body of the filter\n * @param definition - The filter definition\n */\n public setDefinition(definition: IFilterDefinition): void {\n this.definition = definition;\n\n // This is all ported from synapse's FilterCollection()\n\n // definitions look something like:\n // {\n // \"room\": {\n // \"rooms\": [\"!abcde:example.com\"],\n // \"not_rooms\": [\"!123456:example.com\"],\n // \"state\": {\n // \"types\": [\"m.room.*\"],\n // \"not_rooms\": [\"!726s6s6q:example.com\"],\n // \"lazy_load_members\": true,\n // },\n // \"timeline\": {\n // \"limit\": 10,\n // \"types\": [\"m.room.message\"],\n // \"not_rooms\": [\"!726s6s6q:example.com\"],\n // \"not_senders\": [\"@spam:example.com\"]\n // \"contains_url\": true\n // },\n // \"ephemeral\": {\n // \"types\": [\"m.receipt\", \"m.typing\"],\n // \"not_rooms\": [\"!726s6s6q:example.com\"],\n // \"not_senders\": [\"@spam:example.com\"]\n // }\n // },\n // \"presence\": {\n // \"types\": [\"m.presence\"],\n // \"not_senders\": [\"@alice:example.com\"]\n // },\n // \"event_format\": \"client\",\n // \"event_fields\": [\"type\", \"content\", \"sender\"]\n // }\n\n const roomFilterJson = definition.room;\n\n // consider the top level rooms/not_rooms filter\n const roomFilterFields: IRoomFilter = {};\n if (roomFilterJson) {\n if (roomFilterJson.rooms) {\n roomFilterFields.rooms = roomFilterJson.rooms;\n }\n if (roomFilterJson.rooms) {\n roomFilterFields.not_rooms = roomFilterJson.not_rooms;\n }\n }\n\n this.roomFilter = new FilterComponent(roomFilterFields, this.userId);\n this.roomTimelineFilter = new FilterComponent(roomFilterJson?.timeline || {}, this.userId);\n\n // don't bother porting this from synapse yet:\n // this._room_state_filter =\n // new FilterComponent(roomFilterJson.state || {});\n // this._room_ephemeral_filter =\n // new FilterComponent(roomFilterJson.ephemeral || {});\n // this._room_account_data_filter =\n // new FilterComponent(roomFilterJson.account_data || {});\n // this._presence_filter =\n // new FilterComponent(definition.presence || {});\n // this._account_data_filter =\n // new FilterComponent(definition.account_data || {});\n }\n\n /**\n * Get the room.timeline filter component of the filter\n * @returns room timeline filter component\n */\n public getRoomTimelineFilterComponent(): FilterComponent | undefined {\n return this.roomTimelineFilter;\n }\n\n /**\n * Filter the list of events based on whether they are allowed in a timeline\n * based on this filter\n * @param events - the list of events being filtered\n * @returns the list of events which match the filter\n */\n public filterRoomTimeline(events: MatrixEvent[]): MatrixEvent[] {\n if (this.roomFilter) {\n events = this.roomFilter.filter(events);\n }\n if (this.roomTimelineFilter) {\n events = this.roomTimelineFilter.filter(events);\n }\n return events;\n }\n\n /**\n * Set the max number of events to return for each room's timeline.\n * @param limit - The max number of events to return for each room.\n */\n public setTimelineLimit(limit: number): void {\n setProp(this.definition, \"room.timeline.limit\", limit);\n }\n\n /**\n * Enable threads unread notification\n */\n public setUnreadThreadNotifications(enabled: boolean): void {\n this.definition = {\n ...this.definition,\n room: {\n ...this.definition?.room,\n timeline: {\n ...this.definition?.room?.timeline,\n [UNREAD_THREAD_NOTIFICATIONS.name]: enabled,\n },\n },\n };\n }\n\n public setLazyLoadMembers(enabled: boolean): void {\n setProp(this.definition, \"room.state.lazy_load_members\", enabled);\n }\n\n /**\n * Control whether left rooms should be included in responses.\n * @param includeLeave - True to make rooms the user has left appear\n * in responses.\n */\n public setIncludeLeaveRooms(includeLeave: boolean): void {\n setProp(this.definition, \"room.include_leave\", includeLeave);\n }\n}\n"],"mappings":";;;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAGA,SAASA,2BAA2B,QAAQ,kBAAkB;AAC9D,SAASC,eAAe,QAA+B,uBAAuB;AAG9E;AACA;AACA,SAASC,OAAOA,CAACC,GAAwB,EAAEC,UAAkB,EAAEC,GAAQ,EAAQ;EAC3E,IAAMC,UAAU,GAAGF,UAAU,CAACG,KAAK,CAAC,GAAG,CAAuB;EAC9D,IAAIC,UAAU,GAAGL,GAAG;EACpB,KAAK,IAAIM,CAAC,GAAG,CAAC,EAAEA,CAAC,GAAGH,UAAU,CAACI,MAAM,GAAG,CAAC,EAAED,CAAC,EAAE,EAAE;IAC5C,IAAI,CAACD,UAAU,CAACF,UAAU,CAACG,CAAC,CAAC,CAAC,EAAE;MAC5BD,UAAU,CAACF,UAAU,CAACG,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC;IAClC;IACAD,UAAU,GAAGA,UAAU,CAACF,UAAU,CAACG,CAAC,CAAC,CAAC;EAC1C;EACAD,UAAU,CAACF,UAAU,CAACA,UAAU,CAACI,MAAM,GAAG,CAAC,CAAC,CAAC,GAAGL,GAAG;AACvD;;AAEA;;AAkCA;;AAEA,OAAO,MAAMM,MAAM,CAAC;EAKhB;AACJ;AACA;EACI,OAAcC,QAAQA,CAACC,MAAiC,EAAEC,QAAgB,EAAEC,OAA0B,EAAU;IAC5G,IAAMC,MAAM,GAAG,IAAIL,MAAM,CAACE,MAAM,EAAEC,QAAQ,CAAC;IAC3CE,MAAM,CAACC,aAAa,CAACF,OAAO,CAAC;IAC7B,OAAOC,MAAM;EACjB;EAMA;AACJ;AACA;AACA;AACA;EACWE,WAAWA,CACEL,MAAiC,E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;EACWM,oBAAoBA,CAACC,YAAqB,EAAQ;IACrD1C,OAAO,CAAC,IAAI,CAACoB,UAAU,EAAE,oBAAoB,EAAEsB,YAAY,CAAC;EAChE;AACJ;AAACzB,eAAA,CA7KYR,MAAM,kCAC8B;EACzCkC,iBAAiB,EAAE;AACvB,CAAC","ignoreList":[]}
1
+ {"version":3,"file":"filter.js","names":["UNREAD_THREAD_NOTIFICATIONS","FilterComponent","NamespacedValue","profileFieldsFilterName","setProp","obj","keyNesting","val","nestedKeys","split","currentObj","i","length","Filter","fromJson","userId","filterId","jsonObj","filter","setDefinition","constructor","_defineProperty","getFilterId","getDefinition","definition","roomFilterJson","room","roomFilterFields","rooms","not_rooms","roomFilter","roomTimelineFilter","timeline","getRoomTimelineFilterComponent","filterRoomTimeline","events","setTimelineLimit","limit","setUnreadThreadNotifications","enabled","_this$definition","_this$definition2","_objectSpread","name","setLazyLoadMembers","setIncludeLeaveRooms","includeLeave","setUnstableMSC4429SyncUserProfiles","ids","stable","_profileFieldsFilterN","field","unstable","lazy_load_members"],"sources":["../src/filter.ts"],"sourcesContent":["/*\nCopyright 2015 - 2021 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 EventType, type RelationType } from \"./@types/event.ts\";\nimport { UNREAD_THREAD_NOTIFICATIONS } from \"./@types/sync.ts\";\nimport { FilterComponent, type IFilterComponent } from \"./filter-component.ts\";\nimport { type MatrixEvent } from \"./models/event.ts\";\nimport { NamespacedValue } from \"./NamespacedValue.ts\";\n\nconst profileFieldsFilterName = new NamespacedValue(\"profile_fields\", \"org.matrix.msc4429.profile_fields\");\n\n/**\n */\nfunction setProp(obj: Record<string, any>, keyNesting: string, val: any): void {\n const nestedKeys = keyNesting.split(\".\") as [keyof typeof obj];\n let currentObj = obj;\n for (let i = 0; i < nestedKeys.length - 1; i++) {\n if (!currentObj[nestedKeys[i]]) {\n currentObj[nestedKeys[i]] = {};\n }\n currentObj = currentObj[nestedKeys[i]];\n }\n currentObj[nestedKeys[nestedKeys.length - 1]] = val;\n}\n\n/* eslint-disable camelcase */\nexport interface IFilterDefinition {\n \"event_fields\"?: string[];\n \"event_format\"?: \"client\" | \"federation\";\n \"presence\"?: IFilterComponent;\n \"account_data\"?: IFilterComponent;\n \"room\"?: IRoomFilter;\n \"profile_fields\"?: ProfileFieldsFilter;\n \"org.matrix.msc4429.profile_fields\"?: ProfileFieldsFilter;\n}\n\nexport interface IRoomEventFilter extends IFilterComponent {\n \"lazy_load_members\"?: boolean;\n \"include_redundant_members\"?: boolean;\n \"types\"?: Array<EventType | string>;\n \"related_by_senders\"?: Array<RelationType | string>;\n \"related_by_rel_types\"?: string[];\n \"unread_thread_notifications\"?: boolean;\n \"org.matrix.msc3773.unread_thread_notifications\"?: boolean;\n\n // Unstable values\n \"io.element.relation_senders\"?: Array<RelationType | string>;\n \"io.element.relation_types\"?: string[];\n}\n\ninterface IStateFilter extends IRoomEventFilter {}\n\ninterface IRoomFilter {\n not_rooms?: string[];\n rooms?: string[];\n ephemeral?: IRoomEventFilter;\n include_leave?: boolean;\n state?: IStateFilter;\n timeline?: IRoomEventFilter;\n account_data?: IRoomEventFilter;\n}\n\n/**\n * Filter section used for requesting a set of extended profile fields that will be sent down the sync stream.\n */\ninterface ProfileFieldsFilter {\n ids: string[];\n}\n\n/* eslint-enable camelcase */\n\nexport class Filter {\n public static LAZY_LOADING_MESSAGES_FILTER = {\n lazy_load_members: true,\n };\n\n /**\n * Create a filter from existing data.\n */\n public static fromJson(userId: string | undefined | null, filterId: string, jsonObj: IFilterDefinition): Filter {\n const filter = new Filter(userId, filterId);\n filter.setDefinition(jsonObj);\n return filter;\n }\n\n private definition: IFilterDefinition = {};\n private roomFilter?: FilterComponent;\n private roomTimelineFilter?: FilterComponent;\n\n /**\n * Construct a new Filter.\n * @param userId - The user ID for this filter.\n * @param filterId - The filter ID if known.\n */\n public constructor(\n public readonly userId: string | undefined | null,\n public filterId?: string,\n ) {}\n\n /**\n * Get the ID of this filter on your homeserver (if known)\n * @returns The filter ID\n */\n public getFilterId(): string | undefined {\n return this.filterId;\n }\n\n /**\n * Get the JSON body of the filter.\n * @returns The filter definition\n */\n public getDefinition(): IFilterDefinition {\n return this.definition;\n }\n\n /**\n * Set the JSON body of the filter\n * @param definition - The filter definition\n */\n public setDefinition(definition: IFilterDefinition): void {\n this.definition = definition;\n\n // This is all ported from synapse's FilterCollection()\n\n // definitions look something like:\n // {\n // \"room\": {\n // \"rooms\": [\"!abcde:example.com\"],\n // \"not_rooms\": [\"!123456:example.com\"],\n // \"state\": {\n // \"types\": [\"m.room.*\"],\n // \"not_rooms\": [\"!726s6s6q:example.com\"],\n // \"lazy_load_members\": true,\n // },\n // \"timeline\": {\n // \"limit\": 10,\n // \"types\": [\"m.room.message\"],\n // \"not_rooms\": [\"!726s6s6q:example.com\"],\n // \"not_senders\": [\"@spam:example.com\"]\n // \"contains_url\": true\n // },\n // \"ephemeral\": {\n // \"types\": [\"m.receipt\", \"m.typing\"],\n // \"not_rooms\": [\"!726s6s6q:example.com\"],\n // \"not_senders\": [\"@spam:example.com\"]\n // }\n // },\n // \"presence\": {\n // \"types\": [\"m.presence\"],\n // \"not_senders\": [\"@alice:example.com\"]\n // },\n // \"event_format\": \"client\",\n // \"event_fields\": [\"type\", \"content\", \"sender\"]\n // }\n\n const roomFilterJson = definition.room;\n\n // consider the top level rooms/not_rooms filter\n const roomFilterFields: IRoomFilter = {};\n if (roomFilterJson) {\n if (roomFilterJson.rooms) {\n roomFilterFields.rooms = roomFilterJson.rooms;\n }\n if (roomFilterJson.rooms) {\n roomFilterFields.not_rooms = roomFilterJson.not_rooms;\n }\n }\n\n this.roomFilter = new FilterComponent(roomFilterFields, this.userId);\n this.roomTimelineFilter = new FilterComponent(roomFilterJson?.timeline || {}, this.userId);\n\n // don't bother porting this from synapse yet:\n // this._room_state_filter =\n // new FilterComponent(roomFilterJson.state || {});\n // this._room_ephemeral_filter =\n // new FilterComponent(roomFilterJson.ephemeral || {});\n // this._room_account_data_filter =\n // new FilterComponent(roomFilterJson.account_data || {});\n // this._presence_filter =\n // new FilterComponent(definition.presence || {});\n // this._account_data_filter =\n // new FilterComponent(definition.account_data || {});\n }\n\n /**\n * Get the room.timeline filter component of the filter\n * @returns room timeline filter component\n */\n public getRoomTimelineFilterComponent(): FilterComponent | undefined {\n return this.roomTimelineFilter;\n }\n\n /**\n * Filter the list of events based on whether they are allowed in a timeline\n * based on this filter\n * @param events - the list of events being filtered\n * @returns the list of events which match the filter\n */\n public filterRoomTimeline(events: MatrixEvent[]): MatrixEvent[] {\n if (this.roomFilter) {\n events = this.roomFilter.filter(events);\n }\n if (this.roomTimelineFilter) {\n events = this.roomTimelineFilter.filter(events);\n }\n return events;\n }\n\n /**\n * Set the max number of events to return for each room's timeline.\n * @param limit - The max number of events to return for each room.\n */\n public setTimelineLimit(limit: number): void {\n setProp(this.definition, \"room.timeline.limit\", limit);\n }\n\n /**\n * Enable threads unread notification\n */\n public setUnreadThreadNotifications(enabled: boolean): void {\n this.definition = {\n ...this.definition,\n room: {\n ...this.definition?.room,\n timeline: {\n ...this.definition?.room?.timeline,\n [UNREAD_THREAD_NOTIFICATIONS.name]: enabled,\n },\n },\n };\n }\n\n public setLazyLoadMembers(enabled: boolean): void {\n setProp(this.definition, \"room.state.lazy_load_members\", enabled);\n }\n\n /**\n * Control whether left rooms should be included in responses.\n * @param includeLeave - True to make rooms the user has left appear\n * in responses.\n */\n public setIncludeLeaveRooms(includeLeave: boolean): void {\n setProp(this.definition, \"room.include_leave\", includeLeave);\n }\n\n /**\n * Set the list of fields to be included in the profile information sent down the sync stream.\n * @param ids The field IDs to sync.\n * @param stable Whether to use the stable or unstable versions of this filter.\n * @experimental\n */\n public setUnstableMSC4429SyncUserProfiles(ids: string[], stable: boolean): void {\n const field = stable\n ? profileFieldsFilterName.name\n : (profileFieldsFilterName.unstable ?? profileFieldsFilterName.name);\n this.definition[field] = { ids };\n }\n}\n"],"mappings":";;;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAGA,SAASA,2BAA2B,QAAQ,kBAAkB;AAC9D,SAASC,eAAe,QAA+B,uBAAuB;AAE9E,SAASC,eAAe,QAAQ,sBAAsB;AAEtD,IAAMC,uBAAuB,GAAG,IAAID,eAAe,CAAC,gBAAgB,EAAE,mCAAmC,CAAC;;AAE1G;AACA;AACA,SAASE,OAAOA,CAACC,GAAwB,EAAEC,UAAkB,EAAEC,GAAQ,EAAQ;EAC3E,IAAMC,UAAU,GAAGF,UAAU,CAACG,KAAK,CAAC,GAAG,CAAuB;EAC9D,IAAIC,UAAU,GAAGL,GAAG;EACpB,KAAK,IAAIM,CAAC,GAAG,CAAC,EAAEA,CAAC,GAAGH,UAAU,CAACI,MAAM,GAAG,CAAC,EAAED,CAAC,EAAE,EAAE;IAC5C,IAAI,CAACD,UAAU,CAACF,UAAU,CAACG,CAAC,CAAC,CAAC,EAAE;MAC5BD,UAAU,CAACF,UAAU,CAACG,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC;IAClC;IACAD,UAAU,GAAGA,UAAU,CAACF,UAAU,CAACG,CAAC,CAAC,CAAC;EAC1C;EACAD,UAAU,CAACF,UAAU,CAACA,UAAU,CAACI,MAAM,GAAG,CAAC,CAAC,CAAC,GAAGL,GAAG;AACvD;;AAEA;;AAqCA;AACA;AACA;;AAKA;;AAEA,OAAO,MAAMM,MAAM,CAAC;EAKhB;AACJ;AACA;EACI,OAAcC,QAAQA,CAACC,MAAiC,EAAEC,QAAgB,EAAEC,OAA0B,EAAU;IAC5G,IAAMC,MAAM,GAAG,IA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;MAC9C;IACJ,EACJ;EACL;EAEOK,kBAAkBA,CAACL,OAAgB,EAAQ;IAC9CnC,OAAO,CAAC,IAAI,CAACoB,UAAU,EAAE,8BAA8B,EAAEe,OAAO,CAAC;EACrE;;EAEA;AACJ;AACA;AACA;AACA;EACWM,oBAAoBA,CAACC,YAAqB,EAAQ;IACrD1C,OAAO,CAAC,IAAI,CAACoB,UAAU,EAAE,oBAAoB,EAAEsB,YAAY,CAAC;EAChE;;EAEA;AACJ;AACA;AACA;AACA;AACA;EACWC,kCAAkCA,CAACC,GAAa,EAAEC,MAAe,EAAQ;IAAA,IAAAC,qBAAA;IAC5E,IAAMC,KAAK,GAAGF,MAAM,GACd9C,uBAAuB,CAACwC,IAAI,IAAAO,qBAAA,GAC3B/C,uBAAuB,CAACiD,QAAQ,cAAAF,qBAAA,cAAAA,qBAAA,GAAI/C,uBAAuB,CAACwC,IAAK;IACxE,IAAI,CAACnB,UAAU,CAAC2B,KAAK,CAAC,GAAG;MAAEH;IAAI,CAAC;EACpC;AACJ;AAAC3B,eAAA,CA1LYR,MAAM,kCAC8B;EACzCwC,iBAAiB,EAAE;AACvB,CAAC","ignoreList":[]}
@@ -1,3 +1,4 @@
1
+ import { type Json, type JsonValue } from "../@types/json.ts";
1
2
  import { type MatrixClient } from "../matrix.ts";
2
3
  import { type MatrixEvent } from "./event.ts";
3
4
  import { TypedEventEmitter } from "./typed-event-emitter.ts";
@@ -8,6 +9,10 @@ export declare enum UserEvent {
8
9
  CurrentlyActive = "User.currentlyActive",
9
10
  LastPresenceTs = "User.lastPresenceTs"
10
11
  }
12
+ /**
13
+ * An object of extended profile attributes for a user as it arrives down the sync stream.
14
+ */
15
+ export type SyncUserProfile = Record<string, Json | JsonValue>;
11
16
  export type UserEventHandlerMap = {
12
17
  /**
13
18
  * Fires whenever any user's display name changes.
@@ -1 +1 @@
1
- {"version":3,"file":"user.d.ts","sourceRoot":"","sources":["../../src/models/user.ts"],"names":[],"mappings":"AAgBA,OAAO,EAA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;;;OAIG;IACI,SAAS,CAAC,EAAE,MAAM,CAAC;IAC1B;;;;OAIG;IACI,iBAAiB,CAAC,EAAE,MAAM,CAAC;IAClC;;;;OAIG;IACI,QAAQ,SAAa;IAC5B;;;;;OAKG;IACI,aAAa,SAAK;IACzB;;;;;OAKG;IACI,cAAc,SAAK;IAC1B;;;;;OAKG;IACI,eAAe,UAAS;IAC/B;;;;OAIG;IACI,MAAM,EAAE;QACX,0CAA0C;QAC1C,QAAQ,CAAC,EAAE,WAAW,CAAC;QACvB,OAAO,CAAC,EAAE,WAAW,CAAC;KACzB,CAAM;IAEP;;;;OAIG;gBACgC,MAAM,EAAE,MAAM;IAOjD;;;;;;OAMG;WACW,UAAU,CAAC,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,YAAY,GAAG,IAAI;IAYpE;;;;;;;;;;OAUG;IACI,gBAAgB,CAAC,KAAK,EAAE,WAAW,GAAG,IAAI;IA+CjD;;;;OAIG;IACI,cAAc,CAAC,IAAI,EAAE,MAAM,GAAG,IAAI;IAQzC;;;;OAIG;IACI,iBAAiB,CAAC,IAAI,CAAC,EAAE,MAAM,GAAG,IAAI;IAI7C;;;;OAIG;IACI,YAAY,CAAC,GAAG,CAAC,EAAE,MAAM,GAAG,IAAI;IAQvC;;OAEG;IACH,OAAO,CAAC,kBAAkB;IAI1B;;;;;OAKG;IACI,mBAAmB,IAAI,MAAM;IAIpC;;;;OAIG;IACI,eAAe,IAAI,MAAM;CAGnC"}
@@ -24,6 +24,11 @@ export var UserEvent = /*#__PURE__*/function (UserEvent) {
24
24
  UserEvent["LastPresenceTs"] = "User.lastPresenceTs";
25
25
  return UserEvent;
26
26
  }({});
27
+
28
+ /**
29
+ * An object of extended profile attributes for a user as it arrives down the sync stream.
30
+ */
31
+
27
32
  export class User extends TypedEventEmitter {
28
33
  /**
29
34
  * Construct a new User. A User must have an ID and can optionally have extra information associated with it.
@@ -1 +1 @@
1
- {"version":3,"file":"user.js","names":["TypedEventEmitter","UserEvent","User","constructor","userId","_defineProperty","displayName","rawDisplayName","updateModifiedTime","createUser","client","user","reEmitter","reEmit","AvatarUrl","DisplayName","Presence","CurrentlyActive","LastPresenceTs","setPresenceEvent","event","getType","firstFire","events","presence","eventsToFire","getContent","push","avatar_url","avatarUrl","displayname","currently_active","undefined","currentlyActive","status_msg","presenceStatusMsg","lastActiveAgo","last_active_ago","lastPresenceTs","Date","now","eventToFire","emit","setDisplayName","name","oldName","setRawDisplayName","setAvatarUrl","url","oldUrl","modified","getLastModifiedTime","getLastActiveTs"],"sources":["../../src/models/user.ts"],"sourcesContent":["/*\nCopyright 2015 - 2021 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 } from \"../matrix.ts\";\nimport { type MatrixEvent } from \"./event.ts\";\nimport { TypedEventEmitter } from \"./typed-event-emitter.ts\";\n\nexport enum UserEvent {\n DisplayName = \"User.displayName\",\n AvatarUrl = \"User.avatarUrl\",\n Presence = \"User.presence\",\n CurrentlyActive = \"User.currentlyActive\",\n LastPresenceTs = \"User.lastPresenceTs\",\n}\n\nexport type UserEventHandlerMap = {\n /**\n * Fires whenever any user's display name changes.\n * @param event - The matrix event which caused this event to fire.\n * @param user - The user whose User.displayName changed.\n * @example\n * ```\n * matrixClient.on(\"User.displayName\", function(event, user){\n * var newName = user.displayName;\n * });\n * ```\n */\n [UserEvent.DisplayName]: (event: MatrixEvent | undefined, user: User) => void;\n /**\n * Fires whenever any user's avatar URL changes.\n * @param event - The matrix event which caused this event to fire.\n * @param user - The user whose User.avatarUrl changed.\n * @example\n * ```\n * matrixClient.on(\"User.avatarUrl\", function(event, user){\n * var newUrl = user.avatarUrl;\n * });\n * ```\n */\n [UserEvent.AvatarUrl]: (event: MatrixEvent | undefined, user: User) => void;\n /**\n * Fires whenever any user's presence changes.\n * @param event - The matrix event which caused this event to fire.\n * @param user - The user whose User.presence changed.\n * @example\n * ```\n * matrixClient.on(\"User.presence\", function(event, user){\n * var newPresence = user.presence;\n * });\n * ```\n */\n [UserEvent.Presence]: (event: MatrixEvent | undefined, user: User) => void;\n /**\n * Fires whenever any user's currentlyActive changes.\n * @param event - The matrix event which caused this event to fire.\n * @param user - The user whose User.currentlyActive changed.\n * @example\n * ```\n * matrixClient.on(\"User.currentlyActive\", function(event, user){\n * var newCurrentlyActive = user.currentlyActive;\n * });\n * ```\n */\n [UserEvent.CurrentlyActive]: (event: MatrixEvent | undefined, user: User) => void;\n /**\n * Fires whenever any user's lastPresenceTs changes,\n * ie. whenever any presence event is received for a user.\n * @param event - The matrix event which caused this event to fire.\n * @param user - The user whose User.lastPresenceTs changed.\n * @example\n * ```\n * matrixClient.on(\"User.lastPresenceTs\", function(event, user){\n * var newlastPresenceTs = user.lastPresenceTs;\n * });\n * ```\n */\n [UserEvent.LastPresenceTs]: (event: MatrixEvent | undefined, user: User) => void;\n};\n\nexport class User extends TypedEventEmitter<UserEvent, UserEventHandlerMap> {\n private modified = -1;\n\n /**\n * The 'displayname' of the user if known.\n * @privateRemarks\n * Should be read-only\n */\n public displayName?: string;\n public rawDisplayName?: string;\n /**\n * The 'avatar_url' of the user if known.\n * @privateRemarks\n * Should be read-only\n */\n public avatarUrl?: string;\n /**\n * The presence status message if known.\n * @privateRemarks\n * Should be read-only\n */\n public presenceStatusMsg?: string;\n /**\n * The presence enum if known.\n * @privateRemarks\n * Should be read-only\n */\n public presence = \"offline\";\n /**\n * Timestamp (ms since the epoch) for when we last received presence data for this user.\n * We can subtract lastActiveAgo from this to approximate an absolute value for when a user was last active.\n * @privateRemarks\n * Should be read-only\n */\n public lastActiveAgo = 0;\n /**\n * The time elapsed in ms since the user interacted proactively with the server,\n * or we saw a message from the user\n * @privateRemarks\n * Should be read-only\n */\n public lastPresenceTs = 0;\n /**\n * Whether we should consider lastActiveAgo to be an approximation\n * and that the user should be seen as active 'now'\n * @privateRemarks\n * Should be read-only\n */\n public currentlyActive = false;\n /**\n * The events describing this user.\n * @privateRemarks\n * Should be read-only\n */\n public events: {\n /** The m.presence event for this user. */\n presence?: MatrixEvent;\n profile?: MatrixEvent;\n } = {};\n\n /**\n * Construct a new User. A User must have an ID and can optionally have extra information associated with it.\n * @param userId - Required. The ID of this user.\n * @deprecated use `User.createUser`\n */\n public constructor(public readonly userId: string) {\n super();\n this.displayName = userId;\n this.rawDisplayName = userId;\n this.updateModifiedTime();\n }\n\n /**\n * Construct a new User whose events will also emit on MatrixClient.\n * A User must have an ID and can optionally have extra information associated with it.\n * @param userId - Required. The ID of this user.\n * @param client - An instance of MatrixClient object\n * @returns User object with reEmitter setup on client\n */\n public static createUser(userId: string, client: MatrixClient): User {\n const user = new User(userId);\n client.reEmitter.reEmit(user, [\n UserEvent.AvatarUrl,\n UserEvent.DisplayName,\n UserEvent.Presence,\n UserEvent.CurrentlyActive,\n UserEvent.LastPresenceTs,\n ]);\n return user;\n }\n\n /**\n * Update this User with the given presence event. May fire \"User.presence\",\n * \"User.avatarUrl\" and/or \"User.displayName\" if this event updates this user's\n * properties.\n * @param event - The `m.presence` event.\n *\n * @remarks\n * Fires {@link UserEvent.Presence}\n * Fires {@link UserEvent.DisplayName}\n * Fires {@link UserEvent.AvatarUrl}\n */\n public setPresenceEvent(event: MatrixEvent): void {\n if (event.getType() !== \"m.presence\") {\n return;\n }\n const firstFire = this.events.presence === null;\n this.events.presence = event;\n\n const eventsToFire: UserEvent[] = [];\n if (event.getContent().presence !== this.presence || firstFire) {\n eventsToFire.push(UserEvent.Presence);\n }\n if (event.getContent().avatar_url && event.getContent().avatar_url !== this.avatarUrl) {\n eventsToFire.push(UserEvent.AvatarUrl);\n }\n if (event.getContent().displayname && event.getContent().displayname !== this.displayName) {\n eventsToFire.push(UserEvent.DisplayName);\n }\n if (\n event.getContent().currently_active !== undefined &&\n event.getContent().currently_active !== this.currentlyActive\n ) {\n eventsToFire.push(UserEvent.CurrentlyActive);\n }\n\n this.presence = event.getContent().presence;\n eventsToFire.push(UserEvent.LastPresenceTs);\n\n if (event.getContent().status_msg) {\n this.presenceStatusMsg = event.getContent().status_msg;\n }\n if (event.getContent().displayname) {\n this.displayName = event.getContent().displayname;\n }\n if (event.getContent().avatar_url) {\n this.avatarUrl = event.getContent().avatar_url;\n }\n this.lastActiveAgo = event.getContent().last_active_ago;\n this.lastPresenceTs = Date.now();\n this.currentlyActive = event.getContent().currently_active;\n\n this.updateModifiedTime();\n\n for (const eventToFire of eventsToFire) {\n this.emit(eventToFire, event, this);\n }\n }\n\n /**\n * Manually set this user's display name. No event is emitted in response to this\n * as there is no underlying MatrixEvent to emit with.\n * @param name - The new display name.\n */\n public setDisplayName(name: string): void {\n const oldName = this.displayName;\n this.displayName = name;\n if (name !== oldName) {\n this.updateModifiedTime();\n }\n }\n\n /**\n * Manually set this user's non-disambiguated display name. No event is emitted\n * in response to this as there is no underlying MatrixEvent to emit with.\n * @param name - The new display name.\n */\n public setRawDisplayName(name?: string): void {\n this.rawDisplayName = name;\n }\n\n /**\n * Manually set this user's avatar URL. No event is emitted in response to this\n * as there is no underlying MatrixEvent to emit with.\n * @param url - The new avatar URL.\n */\n public setAvatarUrl(url?: string): void {\n const oldUrl = this.avatarUrl;\n this.avatarUrl = url;\n if (url !== oldUrl) {\n this.updateModifiedTime();\n }\n }\n\n /**\n * Update the last modified time to the current time.\n */\n private updateModifiedTime(): void {\n this.modified = Date.now();\n }\n\n /**\n * Get the timestamp when this User was last updated. This timestamp is\n * updated when this User receives a new Presence event which has updated a\n * property on this object. It is updated <i>before</i> firing events.\n * @returns The timestamp\n */\n public getLastModifiedTime(): number {\n return this.modified;\n }\n\n /**\n * Get the absolute timestamp when this User was last known active on the server.\n * It is *NOT* accurate if this.currentlyActive is true.\n * @returns The timestamp\n */\n public getLastActiveTs(): number {\n return this.lastPresenceTs - this.lastActiveAgo;\n }\n}\n"],"mappings":";AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAIA,SAASA,iBAAiB,QAAQ,0BAA0B;AAE5D,WAAYC,SAAS,0BAATA,SAAS;EAATA,SAAS;EAATA,SAAS;EAATA,SAAS;EAATA,SAAS;EAATA,SAAS;EAAA,OAATA,SAAS;AAAA;AAwErB,OAAO,MAAMC,IAAI,SAASF,iBAAiB,CAAiC;EA4DxE;AACJ;AACA;AACA;AACA;EACWG,WAAWA,CAAiBC,MAAc,EAAE;IAC/C,KAAK,CAAC,CAAC;IAAC,KADuBA,MAAc,GAAdA,MAAc;IAAAC,eAAA,mBAhE9B,CAAC,CAAC;IAErB;AACJ;AACA;AACA;AACA;IAJIA,eAAA;IAAAA,eAAA;IAOA;AACJ;AACA;AACA;AACA;IAJIA,eAAA;IAMA;AACJ;AACA;AACA;AACA;IAJIA,eAAA;IAMA;AACJ;AACA;AACA;AACA;IAJIA,eAAA,mBAKkB,SAAS;IAC3B;AACJ;AACA;AACA;AACA;AACA;IALIA,eAAA,wBAMuB,CAAC;IACxB;AACJ;AACA;AACA;AACA;AACA;IALIA,eAAA,yBAMwB,CAAC;IACzB;AACJ;AACA;AACA;AACA;AACA;IALIA,eAAA,0BAMyB,KAAK;IAC9B;AACJ;AACA;AACA;AACA;IAJIA,eAAA,iBASI,CAAC,CAAC;IASF,IAAI,CAACC,WAAW,GAAGF,MAAM;IACzB,IAAI,CAACG,cAAc,GAAGH,MAAM;IAC5B,IAAI,CAACI,kBAAkB,CAAC,CAAC;EAC7B;;EAEA;AACJ;AACA;AACA;AACA;AACA;AACA;EACI,OAAcC,UAAUA,CAACL,MAAc,EAAEM,MAAoB,EAAQ;IACjE,IAAMC,IAAI,GAAG,IAAIT,IAAI,CAACE,MAAM,CAAC;IAC7BM,MAAM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C,kBAAkB,CAAC,CAAC;IAC7B;EACJ;;EAEA;AACJ;AACA;AACA;AACA;EACWsC,iBAAiBA,CAACF,IAAa,EAAQ;IAC1C,IAAI,CAACrC,cAAc,GAAGqC,IAAI;EAC9B;;EAEA;AACJ;AACA;AACA;AACA;EACWG,YAAYA,CAACC,GAAY,EAAQ;IACpC,IAAMC,MAAM,GAAG,IAAI,CAACpB,SAAS;IAC7B,IAAI,CAACA,SAAS,GAAGmB,GAAG;IACpB,IAAIA,GAAG,KAAKC,MAAM,EAAE;MAChB,IAAI,CAACzC,kBAAkB,CAAC,CAAC;IAC7B;EACJ;;EAEA;AACJ;AACA;EACYA,kBAAkBA,CAAA,EAAS;IAC/B,IAAI,CAAC0C,QAAQ,GAAGX,IAAI,CAACC,GAAG,CAAC,CAAC;EAC9B;;EAEA;AACJ;AACA;AACA;AACA;AACA;EACWW,mBAAmBA,CAAA,EAAW;IACjC,OAAO,IAAI,CAACD,QAAQ;EACxB;;EAEA;AACJ;AACA;AACA;AACA;EACWE,eAAeA,CAAA,EAAW;IAC7B,OAAO,IAAI,CAACd,cAAc,GAAG,IAAI,CAACF,aAAa;EACnD;AACJ","ignoreList":[]}
1
+ {"version":3,"file":"user.js","names":["TypedEventEmitter","UserEvent","User","constructor","userId","_defineProperty","displayName","rawDisplayName","updateModifiedTime","createUser","client","user","reEmitter","reEmit","AvatarUrl","DisplayName","Presence","CurrentlyActive","LastPresenceTs","setPresenceEvent","event","getType","firstFire","events","presence","eventsToFire","getContent","push","avatar_url","avatarUrl","displayname","currently_active","undefined","currentlyActive","status_msg","presenceStatusMsg","lastActiveAgo","last_active_ago","lastPresenceTs","Date","now","eventToFire","emit","setDisplayName","name","oldName","setRawDisplayName","setAvatarUrl","url","oldUrl","modified","getLastModifiedTime","getLastActiveTs"],"sources":["../../src/models/user.ts"],"sourcesContent":["/*\nCopyright 2015 - 2021 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 Json, type JsonValue } from \"../@types/json.ts\";\nimport { type MatrixClient } from \"../matrix.ts\";\nimport { type MatrixEvent } from \"./event.ts\";\nimport { TypedEventEmitter } from \"./typed-event-emitter.ts\";\n\nexport enum UserEvent {\n DisplayName = \"User.displayName\",\n AvatarUrl = \"User.avatarUrl\",\n Presence = \"User.presence\",\n CurrentlyActive = \"User.currentlyActive\",\n LastPresenceTs = \"User.lastPresenceTs\",\n}\n\n/**\n * An object of extended profile attributes for a user as it arrives down the sync stream.\n */\nexport type SyncUserProfile = Record<string, Json | JsonValue>;\n\nexport type UserEventHandlerMap = {\n /**\n * Fires whenever any user's display name changes.\n * @param event - The matrix event which caused this event to fire.\n * @param user - The user whose User.displayName changed.\n * @example\n * ```\n * matrixClient.on(\"User.displayName\", function(event, user){\n * var newName = user.displayName;\n * });\n * ```\n */\n [UserEvent.DisplayName]: (event: MatrixEvent | undefined, user: User) => void;\n /**\n * Fires whenever any user's avatar URL changes.\n * @param event - The matrix event which caused this event to fire.\n * @param user - The user whose User.avatarUrl changed.\n * @example\n * ```\n * matrixClient.on(\"User.avatarUrl\", function(event, user){\n * var newUrl = user.avatarUrl;\n * });\n * ```\n */\n [UserEvent.AvatarUrl]: (event: MatrixEvent | undefined, user: User) => void;\n /**\n * Fires whenever any user's presence changes.\n * @param event - The matrix event which caused this event to fire.\n * @param user - The user whose User.presence changed.\n * @example\n * ```\n * matrixClient.on(\"User.presence\", function(event, user){\n * var newPresence = user.presence;\n * });\n * ```\n */\n [UserEvent.Presence]: (event: MatrixEvent | undefined, user: User) => void;\n /**\n * Fires whenever any user's currentlyActive changes.\n * @param event - The matrix event which caused this event to fire.\n * @param user - The user whose User.currentlyActive changed.\n * @example\n * ```\n * matrixClient.on(\"User.currentlyActive\", function(event, user){\n * var newCurrentlyActive = user.currentlyActive;\n * });\n * ```\n */\n [UserEvent.CurrentlyActive]: (event: MatrixEvent | undefined, user: User) => void;\n /**\n * Fires whenever any user's lastPresenceTs changes,\n * ie. whenever any presence event is received for a user.\n * @param event - The matrix event which caused this event to fire.\n * @param user - The user whose User.lastPresenceTs changed.\n * @example\n * ```\n * matrixClient.on(\"User.lastPresenceTs\", function(event, user){\n * var newlastPresenceTs = user.lastPresenceTs;\n * });\n * ```\n */\n [UserEvent.LastPresenceTs]: (event: MatrixEvent | undefined, user: User) => void;\n};\n\nexport class User extends TypedEventEmitter<UserEvent, UserEventHandlerMap> {\n private modified = -1;\n\n /**\n * The 'displayname' of the user if known.\n * @privateRemarks\n * Should be read-only\n */\n public displayName?: string;\n public rawDisplayName?: string;\n /**\n * The 'avatar_url' of the user if known.\n * @privateRemarks\n * Should be read-only\n */\n public avatarUrl?: string;\n /**\n * The presence status message if known.\n * @privateRemarks\n * Should be read-only\n */\n public presenceStatusMsg?: string;\n /**\n * The presence enum if known.\n * @privateRemarks\n * Should be read-only\n */\n public presence = \"offline\";\n /**\n * Timestamp (ms since the epoch) for when we last received presence data for this user.\n * We can subtract lastActiveAgo from this to approximate an absolute value for when a user was last active.\n * @privateRemarks\n * Should be read-only\n */\n public lastActiveAgo = 0;\n /**\n * The time elapsed in ms since the user interacted proactively with the server,\n * or we saw a message from the user\n * @privateRemarks\n * Should be read-only\n */\n public lastPresenceTs = 0;\n /**\n * Whether we should consider lastActiveAgo to be an approximation\n * and that the user should be seen as active 'now'\n * @privateRemarks\n * Should be read-only\n */\n public currentlyActive = false;\n /**\n * The events describing this user.\n * @privateRemarks\n * Should be read-only\n */\n public events: {\n /** The m.presence event for this user. */\n presence?: MatrixEvent;\n profile?: MatrixEvent;\n } = {};\n\n /**\n * Construct a new User. A User must have an ID and can optionally have extra information associated with it.\n * @param userId - Required. The ID of this user.\n * @deprecated use `User.createUser`\n */\n public constructor(public readonly userId: string) {\n super();\n this.displayName = userId;\n this.rawDisplayName = userId;\n this.updateModifiedTime();\n }\n\n /**\n * Construct a new User whose events will also emit on MatrixClient.\n * A User must have an ID and can optionally have extra information associated with it.\n * @param userId - Required. The ID of this user.\n * @param client - An instance of MatrixClient object\n * @returns User object with reEmitter setup on client\n */\n public static createUser(userId: string, client: MatrixClient): User {\n const user = new User(userId);\n client.reEmitter.reEmit(user, [\n UserEvent.AvatarUrl,\n UserEvent.DisplayName,\n UserEvent.Presence,\n UserEvent.CurrentlyActive,\n UserEvent.LastPresenceTs,\n ]);\n return user;\n }\n\n /**\n * Update this User with the given presence event. May fire \"User.presence\",\n * \"User.avatarUrl\" and/or \"User.displayName\" if this event updates this user's\n * properties.\n * @param event - The `m.presence` event.\n *\n * @remarks\n * Fires {@link UserEvent.Presence}\n * Fires {@link UserEvent.DisplayName}\n * Fires {@link UserEvent.AvatarUrl}\n */\n public setPresenceEvent(event: MatrixEvent): void {\n if (event.getType() !== \"m.presence\") {\n return;\n }\n const firstFire = this.events.presence === null;\n this.events.presence = event;\n\n const eventsToFire: UserEvent[] = [];\n if (event.getContent().presence !== this.presence || firstFire) {\n eventsToFire.push(UserEvent.Presence);\n }\n if (event.getContent().avatar_url && event.getContent().avatar_url !== this.avatarUrl) {\n eventsToFire.push(UserEvent.AvatarUrl);\n }\n if (event.getContent().displayname && event.getContent().displayname !== this.displayName) {\n eventsToFire.push(UserEvent.DisplayName);\n }\n if (\n event.getContent().currently_active !== undefined &&\n event.getContent().currently_active !== this.currentlyActive\n ) {\n eventsToFire.push(UserEvent.CurrentlyActive);\n }\n\n this.presence = event.getContent().presence;\n eventsToFire.push(UserEvent.LastPresenceTs);\n\n if (event.getContent().status_msg) {\n this.presenceStatusMsg = event.getContent().status_msg;\n }\n if (event.getContent().displayname) {\n this.displayName = event.getContent().displayname;\n }\n if (event.getContent().avatar_url) {\n this.avatarUrl = event.getContent().avatar_url;\n }\n this.lastActiveAgo = event.getContent().last_active_ago;\n this.lastPresenceTs = Date.now();\n this.currentlyActive = event.getContent().currently_active;\n\n this.updateModifiedTime();\n\n for (const eventToFire of eventsToFire) {\n this.emit(eventToFire, event, this);\n }\n }\n\n /**\n * Manually set this user's display name. No event is emitted in response to this\n * as there is no underlying MatrixEvent to emit with.\n * @param name - The new display name.\n */\n public setDisplayName(name: string): void {\n const oldName = this.displayName;\n this.displayName = name;\n if (name !== oldName) {\n this.updateModifiedTime();\n }\n }\n\n /**\n * Manually set this user's non-disambiguated display name. No event is emitted\n * in response to this as there is no underlying MatrixEvent to emit with.\n * @param name - The new display name.\n */\n public setRawDisplayName(name?: string): void {\n this.rawDisplayName = name;\n }\n\n /**\n * Manually set this user's avatar URL. No event is emitted in response to this\n * as there is no underlying MatrixEvent to emit with.\n * @param url - The new avatar URL.\n */\n public setAvatarUrl(url?: string): void {\n const oldUrl = this.avatarUrl;\n this.avatarUrl = url;\n if (url !== oldUrl) {\n this.updateModifiedTime();\n }\n }\n\n /**\n * Update the last modified time to the current time.\n */\n private updateModifiedTime(): void {\n this.modified = Date.now();\n }\n\n /**\n * Get the timestamp when this User was last updated. This timestamp is\n * updated when this User receives a new Presence event which has updated a\n * property on this object. It is updated <i>before</i> firing events.\n * @returns The timestamp\n */\n public getLastModifiedTime(): number {\n return this.modified;\n }\n\n /**\n * Get the absolute timestamp when this User was last known active on the server.\n * It is *NOT* accurate if this.currentlyActive is true.\n * @returns The timestamp\n */\n public getLastActiveTs(): number {\n return this.lastPresenceTs - this.lastActiveAgo;\n }\n}\n"],"mappings":";AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAKA,SAASA,iBAAiB,QAAQ,0BAA0B;AAE5D,WAAYC,SAAS,0BAATA,SAAS;EAATA,SAAS;EAATA,SAAS;EAATA,SAAS;EAATA,SAAS;EAATA,SAAS;EAAA,OAATA,SAAS;AAAA;;AAQrB;AACA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AM,EAAE;MAChB,IAAI,CAACzC,kBAAkB,CAAC,CAAC;IAC7B;EACJ;;EAEA;AACJ;AACA;EACYA,kBAAkBA,CAAA,EAAS;IAC/B,IAAI,CAAC0C,QAAQ,GAAGX,IAAI,CAACC,GAAG,CAAC,CAAC;EAC9B;;EAEA;AACJ;AACA;AACA;AACA;AACA;EACWW,mBAAmBA,CAAA,EAAW;IACjC,OAAO,IAAI,CAACD,QAAQ;EACxB;;EAEA;AACJ;AACA;AACA;AACA;EACWE,eAAeA,CAAA,EAAW;IAC7B,OAAO,IAAI,CAACd,cAAc,GAAG,IAAI,CAACF,aAAa;EACnD;AACJ","ignoreList":[]}
@@ -94,4 +94,64 @@ export declare const completeAuthorizationCodeGrant: (code: string, state: strin
94
94
  idTokenClaims: IdTokenClaims;
95
95
  identityServerUrl?: string;
96
96
  }>;
97
+ /**
98
+ * Response from the OIDC token endpoint when exchanging a token for grant_type device_code.
99
+ */
100
+ export interface DeviceAccessTokenResponse {
101
+ id_token?: string;
102
+ access_token: string;
103
+ token_type: string;
104
+ refresh_token?: string;
105
+ scope?: string;
106
+ expires_in?: number;
107
+ session_state?: string;
108
+ }
109
+ /**
110
+ * Error from the OIDC token endpoint when exchanging a token for grant_type device_code.
111
+ */
112
+ export interface DeviceAccessTokenError {
113
+ error: string;
114
+ error_description?: string;
115
+ error_uri?: string;
116
+ session_state?: string;
117
+ }
118
+ /**
119
+ * Response from the OIDC device authorization endpoint.
120
+ */
121
+ export interface DeviceAuthorizationResponse {
122
+ device_code: string;
123
+ user_code: string;
124
+ verification_uri: string;
125
+ verification_uri_complete?: string;
126
+ expires_in: number;
127
+ interval?: number;
128
+ }
129
+ /**
130
+ * Begin OIDC device authorization flow.
131
+ * @param options - The device authorization parameters.
132
+ * @param options.clientId - the client ID returned from client registration.
133
+ * @param options.scope - the scope to request for authorization.
134
+ * @param options.metadata - the validated OIDC metadata for the Identity Provider.
135
+ * @returns a promise that resolves to a device access token response,
136
+ * or an error response if the user denies authorization or the device code expires.
137
+ */
138
+ export declare const startDeviceAuthorization: ({ clientId, scope, metadata, }: {
139
+ clientId: string;
140
+ scope: string;
141
+ metadata: ValidatedAuthMetadata;
142
+ }) => Promise<DeviceAuthorizationResponse>;
143
+ /**
144
+ * Polls the OIDC token endpoint until we get a device access token response, or encounter an unrecoverable error.
145
+ * @param options - The device authorization parameters.
146
+ * @param options.session - The session returned from a previous call to {@link startDeviceAuthorization}.
147
+ * @param options.metadata - The validated OIDC metadata for the Identity Provider.
148
+ * @param options.clientId - The client ID returned from client registration.
149
+ * @returns a promise that resolves to a device access token response,
150
+ * or an error response if the user denies authorization or the device code expires.
151
+ */
152
+ export declare const waitForDeviceAuthorization: ({ session, metadata, clientId, }: {
153
+ session: DeviceAuthorizationResponse;
154
+ metadata: ValidatedAuthMetadata;
155
+ clientId: string;
156
+ }) => Promise<DeviceAccessTokenResponse | DeviceAccessTokenError>;
97
157
  //# sourceMappingURL=authorize.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"authorize.d.ts","sourceRoot":"","sources":["../../src/oidc/authorize.ts"],"names":[],"mappings":"AAgBA,OAAO,EACH,KAAK,aAAa,EAGlB,KAAK,uBAAuB,EAI/B,MAAM,gBAAgB,CAAC;AAKxB,OAAO,EACH,KAAK,mBAAmB,EAGxB,KAAK,qBAAqB,EAG7B,MAAM,eAAe,CAAC;AAKvB,YAAY,EAAE,mBAAmB,EAAE,CAAC;AAEpC;;;;GAIG;AACH,MAAM,MAAM,mBAAmB,GAAG;IAC9B,KAAK,EAAE,MAAM,CAAC;IACd,KAAK,EAAE,MAAM,CAAC;IACd,WAAW,EAAE,MAAM,CAAC;IACpB,YAAY,EAAE,MAAM,CAAC;IACrB,KAAK,EAAE,MAAM,CAAC;CACjB,CAAC;AAEF;;;;GAIG;AACH,eAAO,MAAM,aAAa,GAAI,WAAW,MAAM,KAAG,MAGjD,CAAC;AAcF;;;;;;;GAOG;AACH,eAAO,MAAM,2BAA2B,GAAI,iBAAiB;IAAE,W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BAA0B,GAAU,kCAI9C;IACC,OAAO,EAAE,2BAA2B,CAAC;IACrC,QAAQ,EAAE,qBAAqB,CAAC;IAChC,QAAQ,EAAE,MAAM,CAAC;CACpB,KAAG,OAAO,CAAC,yBAAyB,GAAG,sBAAsB,CAgC7D,CAAC"}
@@ -25,6 +25,9 @@ import { OidcError } from "./error.js";
25
25
  import { validateBearerTokenResponse, validateIdToken, validateStoredUserState } from "./validate.js";
26
26
  import { sha256 } from "../digest.js";
27
27
  import { encodeUnpaddedBase64Url } from "../base64.js";
28
+ import { OAuthGrantType } from "./register.js";
29
+ import { sleep } from "../utils.js";
30
+ import { Method } from "../http-api/index.js";
28
31
 
29
32
  // reexport for backwards compatibility
30
33
 
@@ -263,8 +266,11 @@ export var completeAuthorizationCodeGrant = /*#__PURE__*/function () {
263
266
 
264
267
  // throws when response is invalid
265
268
  validateBearerTokenResponse(signinResponse);
266
- // throws when token is invalid
267
- validateIdToken(signinResponse.id_token, client.settings.authority, client.settings.client_id, userState.nonce);
269
+ if (signinResponse.id_token) {
270
+ // The token is not yet in the Matrix spec so consider it optional
271
+ // throws when token is invalid
272
+ validateIdToken(signinResponse.id_token, client.settings.authority, client.settings.client_id, userState.nonce);
273
+ }
268
274
  var normalizedTokenResponse = normalizeBearerTokenResponseTokenType(signinResponse);
269
275
  return {
270
276
  oidcClientSettings: {
@@ -291,4 +297,111 @@ export var completeAuthorizationCodeGrant = /*#__PURE__*/function () {
291
297
  return _ref7.apply(this, arguments);
292
298
  };
293
299
  }();
300
+
301
+ /**
302
+ * Response from the OIDC token endpoint when exchanging a token for grant_type device_code.
303
+ */
304
+
305
+ /**
306
+ * Error from the OIDC token endpoint when exchanging a token for grant_type device_code.
307
+ */
308
+
309
+ /**
310
+ * Response from the OIDC device authorization endpoint.
311
+ */
312
+
313
+ /**
314
+ * Begin OIDC device authorization flow.
315
+ * @param options - The device authorization parameters.
316
+ * @param options.clientId - the client ID returned from client registration.
317
+ * @param options.scope - the scope to request for authorization.
318
+ * @param options.metadata - the validated OIDC metadata for the Identity Provider.
319
+ * @returns a promise that resolves to a device access token response,
320
+ * or an error response if the user denies authorization or the device code expires.
321
+ */
322
+ export var startDeviceAuthorization = /*#__PURE__*/function () {
323
+ var _ref9 = _asyncToGenerator(function* (_ref8) {
324
+ var {
325
+ clientId,
326
+ scope,
327
+ metadata
328
+ } = _ref8;
329
+ var body = new URLSearchParams({
330
+ client_id: clientId,
331
+ scope: scope
332
+ }).toString();
333
+ var url = metadata.device_authorization_endpoint;
334
+ if (!url) {
335
+ throw new Error("No device_authorization_endpoint given");
336
+ }
337
+ var response = yield fetch(url, {
338
+ method: Method.Post,
339
+ headers: {
340
+ "Content-Type": "application/x-www-form-urlencoded"
341
+ },
342
+ body
343
+ });
344
+ return yield response.json();
345
+ });
346
+ return function startDeviceAuthorization(_x8) {
347
+ return _ref9.apply(this, arguments);
348
+ };
349
+ }();
350
+
351
+ /**
352
+ * Polls the OIDC token endpoint until we get a device access token response, or encounter an unrecoverable error.
353
+ * @param options - The device authorization parameters.
354
+ * @param options.session - The session returned from a previous call to {@link startDeviceAuthorization}.
355
+ * @param options.metadata - The validated OIDC metadata for the Identity Provider.
356
+ * @param options.clientId - The client ID returned from client registration.
357
+ * @returns a promise that resolves to a device access token response,
358
+ * or an error response if the user denies authorization or the device code expires.
359
+ */
360
+ export var waitForDeviceAuthorization = /*#__PURE__*/function () {
361
+ var _ref1 = _asyncToGenerator(function* (_ref0) {
362
+ var _session$interval;
363
+ var {
364
+ session,
365
+ metadata,
366
+ clientId
367
+ } = _ref0;
368
+ var interval = ((_session$interval = session.interval) !== null && _session$interval !== void 0 ? _session$interval : 5) * 1000; // poll interval
369
+ var expiration = Date.now() + session.expires_in * 1000;
370
+ do {
371
+ var body = new URLSearchParams({
372
+ device_code: session.device_code,
373
+ grant_type: OAuthGrantType.DeviceAuthorization,
374
+ client_id: clientId
375
+ }).toString();
376
+ var response = yield fetch(metadata.token_endpoint, {
377
+ method: Method.Post,
378
+ headers: {
379
+ "Content-Type": "application/x-www-form-urlencoded"
380
+ },
381
+ body
382
+ });
383
+ if (response.ok) {
384
+ return yield response.json();
385
+ }
386
+ var errorResponse = yield response.json();
387
+ switch (errorResponse.error) {
388
+ case "authorization_pending":
389
+ break;
390
+ case "slow_down":
391
+ interval += 5000;
392
+ break;
393
+ case "access_denied":
394
+ case "expired_token":
395
+ return errorResponse;
396
+ }
397
+ yield sleep(interval);
398
+ } while (Date.now() < expiration);
399
+ return {
400
+ error: "expired"
401
+ };
402
+ });
403
+ return function waitForDeviceAuthorization(_x9) {
404
+ return _ref1.apply(this, arguments);
405
+ };
406
+ }();
294
407
  //# sourceMappingURL=authorize.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"authorize.js","names":["Log","OidcClient","SigninResponse","SigninState","WebStorageStateStore","logger","secureRandomString","OidcError","validateBearerTokenResponse","validateIdToken","validateStoredUserState","sha256","encodeUnpaddedBase64Url","generateScope","deviceId","safeDeviceId","concat","generateCodeChallenge","_ref","_asyncToGenerator","codeVerifier","globalThis","crypto","subtle","warn","hashBuffer","_x","apply","arguments","generateAuthorizationParams","_ref2","redirectUri","scope","state","nonce","generateAuthorizationUrl","_ref4","authorizationUrl","clientId","_ref3","url","URL","searchParams","append","toString","_x2","_x3","_x4","generateOidcAuthorizationUrl","_ref6","_ref5","metadata","homeserverUrl","identityServerUrl","prompt","urlState","loginHint","responseMode","oidcClient","_objectSpread","client_id","redirect_uri","authority","issuer","response_mode","response_type","stateStore","prefix","store","window","sessionStorage","userState","request","createSigninRequest","url_state","login_hint","_x5","normalizeBearerTokenResponseTokenType","response","id_token","expires_at","refresh_token","access_token","token_type","completeAuthorizationCodeGrant","_ref7","code","length","undefined","reconstructedUrl","location","origin","params","URLSearchParams","search","hash","setLogger","stateString","get","Error","MissingOrInvalidStoredState","signInState","fromStorageString","client","signinResponse","processSigninResponse","href","settings","normalizedTokenResponse","oidcClientSettings","tokenResponse","idTokenClaims","profile","error","errorType","message","Object","values","includes","CodeExchangeFailed","_x6","_x7"],"sources":["../../src/oidc/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 {\n type IdTokenClaims,\n Log,\n OidcClient,\n type SigninRequestCreateArgs,\n SigninResponse,\n SigninState,\n WebStorageStateStore,\n} from \"oidc-client-ts\";\n\nimport { logger } from \"../logger.ts\";\nimport { secureRandomString } from \"../randomstring.ts\";\nimport { OidcError } from \"./error.ts\";\nimport {\n type BearerTokenResponse,\n type UserState,\n validateBearerTokenResponse,\n type ValidatedAuthMetadata,\n validateIdToken,\n validateStoredUserState,\n} from \"./validate.ts\";\nimport { sha256 } from \"../digest.ts\";\nimport { encodeUnpaddedBase64Url } from \"../base64.ts\";\n\n// reexport for backwards compatibility\nexport type { BearerTokenResponse };\n\n/**\n * Authorization parameters which are used in the authentication request of an OIDC auth code flow.\n *\n * See https://openid.net/specs/openid-connect-basic-1_0.html#RequestParameters.\n */\nexport type AuthorizationParams = {\n state: string;\n scope: string;\n redirectUri: string;\n codeVerifier: string;\n nonce: string;\n};\n\n/**\n * @experimental\n * Generate the scope used in authorization request with OIDC OP\n * @returns scope\n */\nexport const generateScope = (deviceId?: string): string => {\n const safeDeviceId = deviceId ?? secureRandomString(10);\n return `openid urn:matrix:org.matrix.msc2967.client:api:* urn:matrix:org.matrix.msc2967.client:device:${safeDeviceId}`;\n};\n\n// https://www.rfc-editor.org/rfc/rfc7636\nconst generateCodeChallenge = async (codeVerifier: string): Promise<string> => {\n if (!globalThis.crypto.subtle) {\n // @TODO(kerrya) should this be allowed? configurable?\n logger.warn(\"A secure context is required to generate code challenge. Using plain text code challenge\");\n return codeVerifier;\n }\n\n const hashBuffer = await sha256(codeVerifier);\n return encodeUnpaddedBase64Url(hashBuffer);\n};\n\n/**\n * Generate authorization params to pass to {@link generateAuthorizationUrl}.\n *\n * Used as part of an authorization code OIDC flow: see https://openid.net/specs/openid-connect-basic-1_0.html#CodeFlow.\n *\n * @param redirectUri - absolute url for OP to redirect to after authorization\n * @returns AuthorizationParams\n */\nexport const generateAuthorizationParams = ({ redirectUri }: { redirectUri: string }): AuthorizationParams => ({\n scope: generateScope(),\n redirectUri,\n state: secureRandomString(8),\n nonce: secureRandomString(8),\n codeVerifier: secureRandomString(64), // https://tools.ietf.org/html/rfc7636#section-4.1 length needs to be 43-128 characters\n});\n\n/**\n * @deprecated use generateOidcAuthorizationUrl\n * Generate a URL to attempt authorization with the OP\n * See https://openid.net/specs/openid-connect-basic-1_0.html#CodeRequest\n * @param authorizationUrl - endpoint to attempt authorization with the OP\n * @param clientId - id of this client as registered with the OP\n * @param authorizationParams - params to be used in the url\n * @returns a Promise with the url as a string\n */\nexport const generateAuthorizationUrl = async (\n authorizationUrl: string,\n clientId: string,\n { scope, redirectUri, state, nonce, codeVerifier }: AuthorizationParams,\n): Promise<string> => {\n const url = new URL(authorizationUrl);\n url.searchParams.append(\"response_mode\", \"query\");\n url.searchParams.append(\"response_type\", \"code\");\n url.searchParams.append(\"redirect_uri\", redirectUri);\n url.searchParams.append(\"client_id\", clientId);\n url.searchParams.append(\"state\", state);\n url.searchParams.append(\"scope\", scope);\n url.searchParams.append(\"nonce\", nonce);\n\n url.searchParams.append(\"code_challenge_method\", \"S256\");\n url.searchParams.append(\"code_challenge\", await generateCodeChallenge(codeVerifier));\n\n return url.toString();\n};\n\n/**\n * @experimental\n * Generate a URL to attempt authorization with the OP\n * See https://openid.net/specs/openid-connect-basic-1_0.html#CodeRequest\n * @param metadata - validated metadata from OP discovery\n * @param clientId - this client's id as registered with the OP\n * @param homeserverUrl - used to establish the session on return from the OP\n * @param identityServerUrl - used to establish the session on return from the OP\n * @param nonce - state\n * @param prompt - indicates to the OP which flow the user should see - eg login or registration\n * See https://openid.net/specs/openid-connect-prompt-create-1_0.html#name-prompt-parameter\n * @param urlState - value to append to the opaque state identifier to uniquely identify the callback\n * @param loginHint - value to send as the `login_hint` to the OP, giving a hint about the login identifier the user might use to log in.\n * See {@link https://openid.net/specs/openid-connect-core-1_0.html#AuthRequest OIDC core 3.1.2.1}.\n * @param responseMode - value to send as the `response_mode` to the OP, selecting how auth is passed back during redirect.\n * See {@link https://openid.net/specs/openid-connect-core-1_0.html#AuthRequest OIDC core 3.1.2.1}.\n * @returns a Promise with the url as a string\n */\nexport const generateOidcAuthorizationUrl = async ({\n metadata,\n redirectUri,\n clientId,\n homeserverUrl,\n identityServerUrl,\n nonce,\n prompt,\n urlState,\n loginHint,\n responseMode = \"query\",\n}: {\n clientId: string;\n metadata: ValidatedAuthMetadata;\n homeserverUrl: string;\n identityServerUrl?: string;\n redirectUri: string;\n nonce: string;\n prompt?: string;\n urlState?: string;\n loginHint?: string;\n responseMode?: SigninRequestCreateArgs[\"response_mode\"];\n}): Promise<string> => {\n const scope = generateScope();\n const oidcClient = new OidcClient({\n ...metadata,\n client_id: clientId,\n redirect_uri: redirectUri,\n authority: metadata.issuer,\n response_mode: responseMode,\n response_type: \"code\",\n scope,\n stateStore: new WebStorageStateStore({ prefix: \"mx_oidc_\", store: window.sessionStorage }),\n });\n const userState: UserState = { homeserverUrl, nonce, identityServerUrl };\n const request = await oidcClient.createSigninRequest({\n state: userState,\n nonce,\n prompt,\n url_state: urlState,\n login_hint: loginHint,\n });\n\n return request.url;\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 */\nconst normalizeBearerTokenResponseTokenType = (response: SigninResponse): BearerTokenResponse =>\n ({\n id_token: response.id_token,\n scope: response.scope,\n expires_at: response.expires_at,\n refresh_token: response.refresh_token,\n access_token: response.access_token,\n token_type: \"Bearer\",\n }) as BearerTokenResponse;\n\n/**\n * @experimental\n * Attempt to exchange authorization code for bearer token.\n *\n * Takes the authorization code returned by the OpenID Provider via the authorization URL, and makes a\n * request to the Token Endpoint, to obtain the access token, refresh token, etc.\n *\n * @param code - authorization code as returned by OP during authorization\n * @param state - authorization state param as returned by OP during authorization\n * @param responseMode - the response mode used for authentication\n * @returns valid bearer token response\n * @throws An `Error` with `message` set to an entry in {@link OidcError},\n * when the request fails, or the returned token response is invalid.\n */\nexport const completeAuthorizationCodeGrant = async (\n code: string,\n state: string,\n responseMode: SigninRequestCreateArgs[\"response_mode\"] = \"query\",\n): Promise<{\n oidcClientSettings: { clientId: string; issuer: string };\n tokenResponse: BearerTokenResponse;\n homeserverUrl: string;\n idTokenClaims: IdTokenClaims;\n identityServerUrl?: string;\n}> => {\n /**\n * Element Web strips and changes the url on starting the app\n * Use the code and state from query params to rebuild a url\n * so that oidc-client can parse it\n */\n const reconstructedUrl = new URL(window.location.origin);\n\n const params = new URLSearchParams({ code, state });\n if (responseMode === \"query\") {\n reconstructedUrl.search = params.toString();\n } else {\n reconstructedUrl.hash = `#${params.toString()}`;\n }\n\n // set oidc-client to use our logger\n Log.setLogger(logger);\n try {\n const response = new SigninResponse(params);\n\n const stateStore = new WebStorageStateStore({ prefix: \"mx_oidc_\", store: window.sessionStorage });\n\n // retrieve the state we put in storage at the start of oidc auth flow\n const stateString = await stateStore.get(response.state!);\n if (!stateString) {\n throw new Error(OidcError.MissingOrInvalidStoredState);\n }\n\n // hydrate the sign in state and create a client\n // the stored sign in state includes oidc configuration we set at the start of the oidc login flow\n const signInState = await SigninState.fromStorageString(stateString);\n const client = new OidcClient({ ...signInState, stateStore });\n\n // validate the code and state, and attempt to swap the code for tokens\n const signinResponse = await client.processSigninResponse(reconstructedUrl.href);\n\n // extra values we stored at the start of the login flow\n // used to complete login in the client\n const userState = signinResponse.userState;\n validateStoredUserState(userState);\n\n // throws when response is invalid\n validateBearerTokenResponse(signinResponse);\n // throws when token is invalid\n validateIdToken(signinResponse.id_token, client.settings.authority, client.settings.client_id, userState.nonce);\n const normalizedTokenResponse = normalizeBearerTokenResponseTokenType(signinResponse);\n\n return {\n oidcClientSettings: {\n clientId: client.settings.client_id,\n issuer: client.settings.authority,\n },\n tokenResponse: normalizedTokenResponse,\n homeserverUrl: userState.homeserverUrl,\n identityServerUrl: userState.identityServerUrl,\n idTokenClaims: signinResponse.profile,\n };\n } catch (error) {\n logger.error(\"Oidc login failed\", error);\n const errorType = (error as Error).message;\n\n // rethrow errors that we recognise\n if (Object.values(OidcError).includes(errorType as any)) {\n throw error;\n }\n throw new Error(OidcError.CodeExchangeFailed);\n }\n};\n"],"mappings":";;;;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA,SAEIA,GAAG,EACHC,UAAU,EAEVC,cAAc,EACdC,WAAW,EACXC,oBAAoB,QACjB,gBAAgB;AAEvB,SAASC,MAAM,QAAQ,cAAc;AACrC,SAASC,kBAAkB,QAAQ,oBAAoB;AACvD,SAASC,SAAS,QAAQ,YAAY;AACtC,SAGIC,2BAA2B,EAE3BC,eAAe,EACfC,uBAAuB,QACpB,eAAe;AACtB,SAASC,MAAM,QAAQ,cAAc;AACrC,SAASC,uBAAuB,QAAQ,cAAc;;AAEtD;;AAGA;AACA;AACA;AACA;AACA;;AASA;AACA;AACA;AACA;AACA;AACA,OAAO,IAAMC,aAAa,GAAIC,QAAiB,IAAa;EACxD,IAAMC,YAAY,GAAGD,QAAQ,aAARA,QAAQ,cAARA,QAAQ,GAAIR,kBAAkB,CAAC,EAAE,CAAC;EACvD,wGAAAU,MAAA,CAAwGD,YAAY;AACxH,CAAC;;AAED;AACA,IAAME,qBAAqB;EAAA,I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AACjC,SAAS;MAC1C7D,uBAAuB,CAAC6D,SAAS,CAAC;;MAElC;MACA/D,2BAA2B,CAACgG,cAAc,CAAC;MAC3C;MACA/F,eAAe,CAAC+F,cAAc,CAACzB,QAAQ,EAAEwB,MAAM,CAACI,QAAQ,CAAC7C,SAAS,EAAEyC,MAAM,CAACI,QAAQ,CAAC/C,SAAS,EAAEW,SAAS,CAACrC,KAAK,CAAC;MAC/G,IAAM0E,uBAAuB,GAAG/B,qCAAqC,CAAC2B,cAAc,CAAC;MAErF,OAAO;QACHK,kBAAkB,EAAE;UAChBvE,QAAQ,EAAEiE,MAAM,CAACI,QAAQ,CAAC/C,SAAS;UACnCG,MAAM,EAAEwC,MAAM,CAACI,QAAQ,CAAC7C;QAC5B,CAAC;QACDgD,aAAa,EAAEF,uBAAuB;QACtCxD,aAAa,EAAEmB,SAAS,CAACnB,aAAa;QACtCC,iBAAiB,EAAEkB,SAAS,CAAClB,iBAAiB;QAC9C0D,aAAa,EAAEP,cAAc,CAACQ;MAClC,CAAC;IACL,CAAC,CAAC,OAAOC,KAAK,EAAE;MACZ5G,MAAM,CAAC4G,KAAK,CAAC,mBAAmB,EAAEA,KAAK,CAAC;MACxC,IAAMC,SAAS,GAAID,KAAK,CAAWE,OAAO;;MAE1C;MACA,IAAIC,MAAM,CAACC,MAAM,CAAC9G,SAAS,CAAC,CAAC+G,QAAQ,CAACJ,SAAgB,CAAC,EAAE;QACrD,MAAMD,KAAK;MACf;MACA,MAAM,IAAId,KAAK,CAAC5F,SAAS,CAACgH,kBAAkB,CAAC;IACjD;EACJ,CAAC;EAAA,gBA7EYnC,8BAA8BA,CAAAoC,GAAA,EAAAC,GAAA;IAAA,OAAApC,KAAA,CAAA1D,KAAA,OAAAC,SAAA;EAAA;AAAA,GA6E1C","ignoreList":[]}
1
+ {"version":3,"file":"authorize.js","names":["Log","OidcClient","SigninResponse","SigninState","WebStorageStateStore","logger","secureRandomString","OidcError","validateBearerTokenResponse","validateIdToken","validateStoredUserState","sha256","encodeUnpaddedBase64Url","OAuthGrantType","sleep","Method","generateScope","deviceId","safeDeviceId","concat","generateCodeChallenge","_ref","_asyncToGenerator","codeVerifier","globalThis","crypto","subtle","warn","hashBuffer","_x","apply","arguments","generateAuthorizationParams","_ref2","redirectUri","scope","state","nonce","generateAuthorizationUrl","_ref4","authorizationUrl","clientId","_ref3","url","URL","searchParams","append","toString","_x2","_x3","_x4","generateOidcAuthorizationUrl","_ref6","_ref5","metadata","homeserverUrl","identityServerUrl","prompt","urlState","loginHint","responseMode","oidcClient","_objectSpread","client_id","redirect_uri","authority","issuer","response_mode","response_type","stateStore","prefix","store","window","sessionStorage","userState","request","createSigninRequest","url_state","login_hint","_x5","normalizeBearerTokenResponseTokenType","response","id_token","expires_at","refresh_token","access_token","token_type","completeAuthorizationCodeGrant","_ref7","code","length","undefined","reconstructedUrl","location","origin","params","URLSearchParams","search","hash","setLogger","stateString","get","Error","MissingOrInvalidStoredState","signInState","fromStorageString","client","signinResponse","processSigninResponse","href","settings","normalizedTokenResponse","oidcClientSettings","tokenResponse","idTokenClaims","profile","error","errorType","message","Object","values","includes","CodeExchangeFailed","_x6","_x7","startDeviceAuthorization","_ref9","_ref8","body","device_authorization_endpoint","fetch","method","Post","headers","json","_x8","waitForDeviceAuthorization","_ref1","_ref0","_session$interval","session","interval","expiration","Date","now","expires_in","device_code","grant_type","DeviceAuthorization","token_endpoint","ok","errorResponse","_x9"],"sources":["../../src/oidc/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 {\n type IdTokenClaims,\n Log,\n OidcClient,\n type SigninRequestCreateArgs,\n SigninResponse,\n SigninState,\n WebStorageStateStore,\n} from \"oidc-client-ts\";\n\nimport { logger } from \"../logger.ts\";\nimport { secureRandomString } from \"../randomstring.ts\";\nimport { OidcError } from \"./error.ts\";\nimport {\n type BearerTokenResponse,\n type UserState,\n validateBearerTokenResponse,\n type ValidatedAuthMetadata,\n validateIdToken,\n validateStoredUserState,\n} from \"./validate.ts\";\nimport { sha256 } from \"../digest.ts\";\nimport { encodeUnpaddedBase64Url } from \"../base64.ts\";\nimport { OAuthGrantType } from \"./register.ts\";\nimport { sleep } from \"../utils.ts\";\nimport { Method } from \"../http-api/index.ts\";\n\n// reexport for backwards compatibility\nexport type { BearerTokenResponse };\n\n/**\n * Authorization parameters which are used in the authentication request of an OIDC auth code flow.\n *\n * See https://openid.net/specs/openid-connect-basic-1_0.html#RequestParameters.\n */\nexport type AuthorizationParams = {\n state: string;\n scope: string;\n redirectUri: string;\n codeVerifier: string;\n nonce: string;\n};\n\n/**\n * @experimental\n * Generate the scope used in authorization request with OIDC OP\n * @returns scope\n */\nexport const generateScope = (deviceId?: string): string => {\n const safeDeviceId = deviceId ?? secureRandomString(10);\n return `openid urn:matrix:org.matrix.msc2967.client:api:* urn:matrix:org.matrix.msc2967.client:device:${safeDeviceId}`;\n};\n\n// https://www.rfc-editor.org/rfc/rfc7636\nconst generateCodeChallenge = async (codeVerifier: string): Promise<string> => {\n if (!globalThis.crypto.subtle) {\n // @TODO(kerrya) should this be allowed? configurable?\n logger.warn(\"A secure context is required to generate code challenge. Using plain text code challenge\");\n return codeVerifier;\n }\n\n const hashBuffer = await sha256(codeVerifier);\n return encodeUnpaddedBase64Url(hashBuffer);\n};\n\n/**\n * Generate authorization params to pass to {@link generateAuthorizationUrl}.\n *\n * Used as part of an authorization code OIDC flow: see https://openid.net/specs/openid-connect-basic-1_0.html#CodeFlow.\n *\n * @param redirectUri - absolute url for OP to redirect to after authorization\n * @returns AuthorizationParams\n */\nexport const generateAuthorizationParams = ({ redirectUri }: { redirectUri: string }): AuthorizationParams => ({\n scope: generateScope(),\n redirectUri,\n state: secureRandomString(8),\n nonce: secureRandomString(8),\n codeVerifier: secureRandomString(64), // https://tools.ietf.org/html/rfc7636#section-4.1 length needs to be 43-128 characters\n});\n\n/**\n * @deprecated use generateOidcAuthorizationUrl\n * Generate a URL to attempt authorization with the OP\n * See https://openid.net/specs/openid-connect-basic-1_0.html#CodeRequest\n * @param authorizationUrl - endpoint to attempt authorization with the OP\n * @param clientId - id of this client as registered with the OP\n * @param authorizationParams - params to be used in the url\n * @returns a Promise with the url as a string\n */\nexport const generateAuthorizationUrl = async (\n authorizationUrl: string,\n clientId: string,\n { scope, redirectUri, state, nonce, codeVerifier }: AuthorizationParams,\n): Promise<string> => {\n const url = new URL(authorizationUrl);\n url.searchParams.append(\"response_mode\", \"query\");\n url.searchParams.append(\"response_type\", \"code\");\n url.searchParams.append(\"redirect_uri\", redirectUri);\n url.searchParams.append(\"client_id\", clientId);\n url.searchParams.append(\"state\", state);\n url.searchParams.append(\"scope\", scope);\n url.searchParams.append(\"nonce\", nonce);\n\n url.searchParams.append(\"code_challenge_method\", \"S256\");\n url.searchParams.append(\"code_challenge\", await generateCodeChallenge(codeVerifier));\n\n return url.toString();\n};\n\n/**\n * @experimental\n * Generate a URL to attempt authorization with the OP\n * See https://openid.net/specs/openid-connect-basic-1_0.html#CodeRequest\n * @param metadata - validated metadata from OP discovery\n * @param clientId - this client's id as registered with the OP\n * @param homeserverUrl - used to establish the session on return from the OP\n * @param identityServerUrl - used to establish the session on return from the OP\n * @param nonce - state\n * @param prompt - indicates to the OP which flow the user should see - eg login or registration\n * See https://openid.net/specs/openid-connect-prompt-create-1_0.html#name-prompt-parameter\n * @param urlState - value to append to the opaque state identifier to uniquely identify the callback\n * @param loginHint - value to send as the `login_hint` to the OP, giving a hint about the login identifier the user might use to log in.\n * See {@link https://openid.net/specs/openid-connect-core-1_0.html#AuthRequest OIDC core 3.1.2.1}.\n * @param responseMode - value to send as the `response_mode` to the OP, selecting how auth is passed back during redirect.\n * See {@link https://openid.net/specs/openid-connect-core-1_0.html#AuthRequest OIDC core 3.1.2.1}.\n * @returns a Promise with the url as a string\n */\nexport const generateOidcAuthorizationUrl = async ({\n metadata,\n redirectUri,\n clientId,\n homeserverUrl,\n identityServerUrl,\n nonce,\n prompt,\n urlState,\n loginHint,\n responseMode = \"query\",\n}: {\n clientId: string;\n metadata: ValidatedAuthMetadata;\n homeserverUrl: string;\n identityServerUrl?: string;\n redirectUri: string;\n nonce: string;\n prompt?: string;\n urlState?: string;\n loginHint?: string;\n responseMode?: SigninRequestCreateArgs[\"response_mode\"];\n}): Promise<string> => {\n const scope = generateScope();\n const oidcClient = new OidcClient({\n ...metadata,\n client_id: clientId,\n redirect_uri: redirectUri,\n authority: metadata.issuer,\n response_mode: responseMode,\n response_type: \"code\",\n scope,\n stateStore: new WebStorageStateStore({ prefix: \"mx_oidc_\", store: window.sessionStorage }),\n });\n const userState: UserState = { homeserverUrl, nonce, identityServerUrl };\n const request = await oidcClient.createSigninRequest({\n state: userState,\n nonce,\n prompt,\n url_state: urlState,\n login_hint: loginHint,\n });\n\n return request.url;\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 */\nconst normalizeBearerTokenResponseTokenType = (response: SigninResponse): BearerTokenResponse =>\n ({\n id_token: response.id_token,\n scope: response.scope,\n expires_at: response.expires_at,\n refresh_token: response.refresh_token,\n access_token: response.access_token,\n token_type: \"Bearer\",\n }) as BearerTokenResponse;\n\n/**\n * @experimental\n * Attempt to exchange authorization code for bearer token.\n *\n * Takes the authorization code returned by the OpenID Provider via the authorization URL, and makes a\n * request to the Token Endpoint, to obtain the access token, refresh token, etc.\n *\n * @param code - authorization code as returned by OP during authorization\n * @param state - authorization state param as returned by OP during authorization\n * @param responseMode - the response mode used for authentication\n * @returns valid bearer token response\n * @throws An `Error` with `message` set to an entry in {@link OidcError},\n * when the request fails, or the returned token response is invalid.\n */\nexport const completeAuthorizationCodeGrant = async (\n code: string,\n state: string,\n responseMode: SigninRequestCreateArgs[\"response_mode\"] = \"query\",\n): Promise<{\n oidcClientSettings: { clientId: string; issuer: string };\n tokenResponse: BearerTokenResponse;\n homeserverUrl: string;\n idTokenClaims: IdTokenClaims;\n identityServerUrl?: string;\n}> => {\n /**\n * Element Web strips and changes the url on starting the app\n * Use the code and state from query params to rebuild a url\n * so that oidc-client can parse it\n */\n const reconstructedUrl = new URL(window.location.origin);\n\n const params = new URLSearchParams({ code, state });\n if (responseMode === \"query\") {\n reconstructedUrl.search = params.toString();\n } else {\n reconstructedUrl.hash = `#${params.toString()}`;\n }\n\n // set oidc-client to use our logger\n Log.setLogger(logger);\n try {\n const response = new SigninResponse(params);\n\n const stateStore = new WebStorageStateStore({ prefix: \"mx_oidc_\", store: window.sessionStorage });\n\n // retrieve the state we put in storage at the start of oidc auth flow\n const stateString = await stateStore.get(response.state!);\n if (!stateString) {\n throw new Error(OidcError.MissingOrInvalidStoredState);\n }\n\n // hydrate the sign in state and create a client\n // the stored sign in state includes oidc configuration we set at the start of the oidc login flow\n const signInState = await SigninState.fromStorageString(stateString);\n const client = new OidcClient({ ...signInState, stateStore });\n\n // validate the code and state, and attempt to swap the code for tokens\n const signinResponse = await client.processSigninResponse(reconstructedUrl.href);\n\n // extra values we stored at the start of the login flow\n // used to complete login in the client\n const userState = signinResponse.userState;\n validateStoredUserState(userState);\n\n // throws when response is invalid\n validateBearerTokenResponse(signinResponse);\n if (signinResponse.id_token) {\n // The token is not yet in the Matrix spec so consider it optional\n // throws when token is invalid\n validateIdToken(\n signinResponse.id_token,\n client.settings.authority,\n client.settings.client_id,\n userState.nonce,\n );\n }\n const normalizedTokenResponse = normalizeBearerTokenResponseTokenType(signinResponse);\n\n return {\n oidcClientSettings: {\n clientId: client.settings.client_id,\n issuer: client.settings.authority,\n },\n tokenResponse: normalizedTokenResponse,\n homeserverUrl: userState.homeserverUrl,\n identityServerUrl: userState.identityServerUrl,\n idTokenClaims: signinResponse.profile,\n };\n } catch (error) {\n logger.error(\"Oidc login failed\", error);\n const errorType = (error as Error).message;\n\n // rethrow errors that we recognise\n if (Object.values(OidcError).includes(errorType as any)) {\n throw error;\n }\n throw new Error(OidcError.CodeExchangeFailed);\n }\n};\n\n/**\n * Response from the OIDC token endpoint when exchanging a token for grant_type device_code.\n */\nexport interface DeviceAccessTokenResponse {\n id_token?: string;\n access_token: string;\n token_type: string;\n refresh_token?: string;\n scope?: string;\n expires_in?: number;\n session_state?: string;\n}\n\n/**\n * Error from the OIDC 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 OIDC device authorization endpoint.\n */\nexport interface DeviceAuthorizationResponse {\n device_code: string;\n user_code: string;\n verification_uri: string;\n verification_uri_complete?: string;\n expires_in: number;\n interval?: number;\n}\n\n/**\n * Begin OIDC 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 OIDC 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 return (await response.json()) as DeviceAuthorizationResponse;\n};\n\n/**\n * Polls the OIDC 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 OIDC 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 if (response.ok) {\n return (await response.json()) as DeviceAccessTokenResponse;\n }\n const errorResponse = (await response.json()) 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,SAEIA,GAAG,EACHC,UAAU,EAEVC,cAAc,EACdC,WAAW,EACXC,oBAAoB,QACjB,gBAAgB;AAEvB,SAASC,MAAM,QAAQ,cAAc;AACrC,SAASC,kBAAkB,QAAQ,oBAAoB;AACvD,SAASC,SAAS,QAAQ,YAAY;AACtC,SAGIC,2BAA2B,EAE3BC,eAAe,EACfC,uBAAuB,QACpB,eAAe;AACtB,SAAS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