matrix-js-sdk 42.2.0 → 42.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +15 -0
- package/lib/client.d.ts +1 -2
- package/lib/client.d.ts.map +1 -1
- package/lib/client.js +16 -8
- package/lib/client.js.map +1 -1
- package/lib/http-api/errors.d.ts +8 -0
- package/lib/http-api/errors.d.ts.map +1 -1
- package/lib/http-api/errors.js +12 -0
- package/lib/http-api/errors.js.map +1 -1
- package/lib/matrixrtc/MatrixRTCSession.d.ts +5 -0
- package/lib/matrixrtc/MatrixRTCSession.d.ts.map +1 -1
- package/lib/matrixrtc/MatrixRTCSession.js +2 -1
- package/lib/matrixrtc/MatrixRTCSession.js.map +1 -1
- package/lib/oauth/authorize.d.ts +2 -4
- package/lib/oauth/authorize.d.ts.map +1 -1
- package/lib/oauth/authorize.js.map +1 -1
- package/lib/oauth/error.d.ts +44 -0
- package/lib/oauth/error.d.ts.map +1 -1
- package/lib/oauth/error.js +53 -0
- package/lib/oauth/error.js.map +1 -1
- package/lib/oauth/index.d.ts.map +1 -1
- package/lib/oauth/index.js +19 -2
- package/lib/oauth/index.js.map +1 -1
- package/lib/oauth/tokenRefresher.d.ts.map +1 -1
- package/lib/oauth/tokenRefresher.js +4 -2
- package/lib/oauth/tokenRefresher.js.map +1 -1
- package/lib/secret-storage.d.ts +1 -1
- package/lib/secret-storage.d.ts.map +1 -1
- package/lib/secret-storage.js +9 -32
- package/lib/secret-storage.js.map +1 -1
- package/lib/sliding-sync-sdk.d.ts.map +1 -1
- package/lib/sliding-sync-sdk.js +54 -1
- package/lib/sliding-sync-sdk.js.map +1 -1
- package/package.json +2 -2
- package/src/client.ts +19 -11
- package/src/http-api/errors.ts +16 -0
- package/src/matrixrtc/MatrixRTCSession.ts +8 -1
- package/src/oauth/authorize.ts +2 -5
- package/src/oauth/error.ts +69 -0
- package/src/oauth/index.ts +19 -2
- package/src/oauth/tokenRefresher.ts +9 -2
- package/src/secret-storage.ts +8 -31
- package/src/sliding-sync-sdk.ts +74 -0
package/lib/http-api/errors.d.ts
CHANGED
|
@@ -35,6 +35,14 @@ export declare class HTTPError extends Error {
|
|
|
35
35
|
*/
|
|
36
36
|
getRetryAfterMs(): number | null;
|
|
37
37
|
}
|
|
38
|
+
/**
|
|
39
|
+
* Check if the given (JSON-parsed) response body looks like a Matrix error
|
|
40
|
+
* response as specified in https://spec.matrix.org/v1.19/client-server-api/#standard-error-response
|
|
41
|
+
*
|
|
42
|
+
* @param response - the parsed response body to check
|
|
43
|
+
* @returns whether the response is a valid {@link MatrixError}
|
|
44
|
+
*/
|
|
45
|
+
export declare function isMatrixErrorResponse(response: unknown): response is MatrixError;
|
|
38
46
|
export declare class MatrixError extends HTTPError {
|
|
39
47
|
url?: string | undefined;
|
|
40
48
|
event?: MatrixEvent | undefined;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"errors.d.ts","sourceRoot":"","sources":["../../src/http-api/errors.ts"],"names":[],"mappings":"AAgBA,OAAO,EAAE,KAAK,eAAe,IAAI,kBAAkB,EAAE,MAAM,mBAAmB,CAAC;AAE/E,OAAO,EAAE,KAAK,WAAW,EAAE,MAAM,uBAAuB,CAAC;AACzD,OAAO,EAAE,KAAK,WAAW,EAAE,MAAM,oBAAoB,CAAC;AACtD,OAAO,EAAE,eAAe,EAAE,MAAM,uBAAuB,CAAC;
|
|
1
|
+
{"version":3,"file":"errors.d.ts","sourceRoot":"","sources":["../../src/http-api/errors.ts"],"names":[],"mappings":"AAgBA,OAAO,EAAE,KAAK,eAAe,IAAI,kBAAkB,EAAE,MAAM,mBAAmB,CAAC;AAE/E,OAAO,EAAE,KAAK,WAAW,EAAE,MAAM,uBAAuB,CAAC;AACzD,OAAO,EAAE,KAAK,WAAW,EAAE,MAAM,oBAAoB,CAAC;AACtD,OAAO,EAAE,eAAe,EAAE,MAAM,uBAAuB,CAAC;AAGxD,UAAU,UAAW,SAAQ,OAA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AAK,EAAE,OAAO,EAAE,SAAS,EAAE,MAAM,GAAG,MAAM,CAS7E;AAED;;;;;GAKG;AACH,qBAAa,eAAgB,SAAQ,KAAK;IACtC,YAAmB,OAAO,EAAE,MAAM,EAAE,KAAK,CAAC,EAAE,KAAK,EAEhD;IAED,IAAW,IAAI,IAAI,MAAM,CAExB;CACJ;AAED;;;;GAIG;AACH,qBAAa,iBAAkB,SAAQ,KAAK;IACxC,YAAmB,KAAK,CAAC,EAAE,KAAK,EAE/B;IAED,IAAW,IAAI,IAAI,MAAM,CAExB;CACJ;AAED;;;GAGG;AACH,qBAAa,uBAAwB,SAAQ,KAAK;IAC9C,YAAmB,KAAK,CAAC,EAAE,KAAK,EAE/B;IAED,IAAW,IAAI,IAAI,MAAM,CAExB;CACJ;AAED,eAAO,MAAM,qBAAqB,sDAAyD,CAAC;AAE5F;;;;GAIG;AACH,qBAAa,iBAAkB,SAAQ,WAAW;IAC9C;;;OAGG;IACH,SAAgB,KAAK,EAAE,GAAG,CAAC,MAAM,CAAC,CAAC;IACnC;;OAEG;IACH,SAAgB,MAAM,CAAC,EAAE,IAAI,CAAC;IAC9B,YAAmB,GAAG,KAAK,EAAE,qBAAqB,CAAC,OAAO,WAAW,CAAC,EASrE;CACJ"}
|
package/lib/http-api/errors.js
CHANGED
|
@@ -17,6 +17,7 @@ limitations under the License.
|
|
|
17
17
|
*/
|
|
18
18
|
|
|
19
19
|
import { NamespacedValue } from "../NamespacedValue.js";
|
|
20
|
+
import { hasRequiredStringProperty, isRecord } from "../@types/type-guards.js";
|
|
20
21
|
/**
|
|
21
22
|
* Construct a generic HTTP error. This is a JavaScript Error with additional information
|
|
22
23
|
* specific to HTTP responses.
|
|
@@ -68,6 +69,17 @@ export class HTTPError extends Error {
|
|
|
68
69
|
return null;
|
|
69
70
|
}
|
|
70
71
|
}
|
|
72
|
+
|
|
73
|
+
/**
|
|
74
|
+
* Check if the given (JSON-parsed) response body looks like a Matrix error
|
|
75
|
+
* response as specified in https://spec.matrix.org/v1.19/client-server-api/#standard-error-response
|
|
76
|
+
*
|
|
77
|
+
* @param response - the parsed response body to check
|
|
78
|
+
* @returns whether the response is a valid {@link MatrixError}
|
|
79
|
+
*/
|
|
80
|
+
export function isMatrixErrorResponse(response) {
|
|
81
|
+
return isRecord(response) && hasRequiredStringProperty(response, "error") && hasRequiredStringProperty(response, "errcode");
|
|
82
|
+
}
|
|
71
83
|
export class MatrixError extends HTTPError {
|
|
72
84
|
/**
|
|
73
85
|
* Construct a Matrix error. This is a JavaScript Error with additional
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"errors.js","names":[],"sources":["../../src/http-api/errors.ts"],"sourcesContent":["/*\nCopyright 2022 - 2024 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { type IMatrixApiError as IWidgetMatrixError } from \"matrix-widget-api\";\n\nimport { type IUsageLimit } from \"../@types/partials.ts\";\nimport { type MatrixEvent } from \"../models/event.ts\";\nimport { NamespacedValue } from \"../NamespacedValue.ts\";\n\ninterface IErrorJson extends Partial<IUsageLimit> {\n [key: string]: any; // extensible\n errcode?: string;\n error?: string;\n}\n\n/**\n * Construct a generic HTTP error. This is a JavaScript Error with additional information\n * specific to HTTP responses.\n * @param msg - The error message to include.\n * @param httpStatus - The HTTP response status code.\n * @param httpHeaders - The HTTP response headers.\n */\nexport class HTTPError extends Error {\n public constructor(\n msg: string,\n public readonly httpStatus?: number,\n public readonly httpHeaders?: Headers,\n ) {\n super(msg);\n }\n\n /**\n * Check if this error was due to rate-limiting on the server side (and should therefore be retried after a delay).\n *\n * If this returns `true`, {@link getRetryAfterMs} can be called to retrieve the server-side\n * recommendation for the retry period.\n *\n * @returns Whether this error is due to rate-limiting.\n */\n public isRateLimitError(): boolean {\n return this.httpStatus === 429;\n }\n\n /**\n * @returns The recommended delay in milliseconds to wait before retrying\n * the request that triggered this error, or null if no delay is recommended.\n * @throws Error if the recommended delay is an invalid value.\n * @see {@link safeGetRetryAfterMs} for a version of this check that doesn't throw.\n */\n public getRetryAfterMs(): number | null {\n const retryAfter = this.httpHeaders?.get(\"Retry-After\");\n if (retryAfter != null) {\n if (/^\\d+$/.test(retryAfter)) {\n const ms = Number.parseInt(retryAfter) * 1000;\n if (!Number.isFinite(ms)) {\n throw new Error(\"Retry-After header integer value is too large\");\n }\n return ms;\n }\n const date = new Date(retryAfter);\n if (date.toUTCString() !== retryAfter) {\n throw new Error(\"Retry-After header value is not a valid HTTP-date or non-negative decimal integer\");\n }\n return date.getTime() - Date.now();\n }\n return null;\n }\n}\n\nexport class MatrixError extends HTTPError {\n // The Matrix 'errcode' value, e.g. \"M_FORBIDDEN\".\n public readonly errcode?: string;\n // The Matrix 'error' value.\n public readonly error?: string;\n // The raw Matrix error JSON used to construct this object.\n public data: IErrorJson;\n\n /**\n * Construct a Matrix error. This is a JavaScript Error with additional\n * information specific to the standard Matrix error response.\n * @param errorJson - The Matrix error JSON returned from the homeserver.\n * @param httpStatus - The numeric HTTP status code given\n * @param httpHeaders - The HTTP response headers given\n */\n public constructor(\n errorJson: IErrorJson = {},\n httpStatus?: number,\n public url?: string,\n public event?: MatrixEvent,\n httpHeaders?: Headers,\n ) {\n let message = errorJson.error || \"Unknown message\";\n if (httpStatus) {\n message = `[${httpStatus}] ${message}`;\n }\n if (url) {\n message = `${message} (${url})`;\n }\n super(`MatrixError: ${message}`, httpStatus, httpHeaders);\n this.errcode = errorJson.errcode;\n this.error = errorJson.error;\n this.name = errorJson.errcode || \"Unknown error code\";\n this.data = errorJson;\n }\n\n public isRateLimitError(): boolean {\n return (\n this.errcode === \"M_LIMIT_EXCEEDED\" ||\n ((this.errcode === \"M_UNKNOWN\" || this.errcode === undefined) && super.isRateLimitError())\n );\n }\n\n public getRetryAfterMs(): number | null {\n const headerValue = super.getRetryAfterMs();\n if (headerValue !== null) {\n return headerValue;\n }\n // Note: retry_after_ms is deprecated as of spec version v1.10\n if (this.errcode === \"M_LIMIT_EXCEEDED\" && \"retry_after_ms\" in this.data) {\n if (!Number.isInteger(this.data.retry_after_ms)) {\n throw new Error(\"retry_after_ms is not an integer\");\n }\n return this.data.retry_after_ms;\n }\n return null;\n }\n\n /**\n * @returns this error expressed as a JSON payload\n * for use by Widget API error responses.\n */\n public asWidgetApiErrorData(): IWidgetMatrixError {\n const headers: Record<string, string> = {};\n if (this.httpHeaders) {\n for (const [name, value] of this.httpHeaders) {\n headers[name] = value;\n }\n }\n return {\n http_status: this.httpStatus ?? 400,\n http_headers: headers,\n url: this.url ?? \"\",\n response: {\n errcode: this.errcode ?? \"M_UNKNOWN\",\n error: this.data.error ?? \"Unknown message\",\n ...this.data,\n },\n };\n }\n\n /**\n * @returns a new {@link MatrixError} from a JSON payload\n * received from Widget API error responses.\n */\n public static fromWidgetApiErrorData(data: IWidgetMatrixError): MatrixError {\n return new MatrixError(data.response, data.http_status, data.url, undefined, new Headers(data.http_headers));\n }\n}\n\n/**\n * @returns The recommended delay in milliseconds to wait before retrying the request.\n * @param error - The error to check for a retry delay.\n * @param defaultMs - The delay to use if the error was not due to rate-limiting or if no valid delay is recommended.\n */\nexport function safeGetRetryAfterMs(error: unknown, defaultMs: number): number {\n if (!(error instanceof HTTPError) || !error.isRateLimitError()) {\n return defaultMs;\n }\n try {\n return error.getRetryAfterMs() ?? defaultMs;\n } catch {\n return defaultMs;\n }\n}\n\n/**\n * Construct a ConnectionError. This is a JavaScript Error indicating\n * that a request failed because of some error with the connection, either\n * CORS was not correctly configured on the server, the server didn't response,\n * the request timed out, or the internet connection on the client side went down.\n */\nexport class ConnectionError extends Error {\n public constructor(message: string, cause?: Error) {\n super(message + (cause ? `: ${cause.message}` : \"\"));\n }\n\n public get name(): string {\n return \"ConnectionError\";\n }\n}\n\n/**\n * Construct a TokenRefreshError. This indicates that a request failed due to the token being expired,\n * and attempting to refresh said token also failed but in a way which was not indicative of token invalidation.\n * Assumed to be a temporary failure.\n */\nexport class TokenRefreshError extends Error {\n public constructor(cause?: Error) {\n super(cause?.message ?? \"\");\n }\n\n public get name(): string {\n return \"TokenRefreshError\";\n }\n}\n\n/**\n * Construct a TokenRefreshError. This indicates that a request failed due to the token being expired,\n * and attempting to refresh said token failed in a way indicative of token invalidation.\n */\nexport class TokenRefreshLogoutError extends Error {\n public constructor(cause?: Error) {\n super(cause?.message ?? \"\");\n }\n\n public get name(): string {\n return \"TokenRefreshLogoutError\";\n }\n}\n\nexport const MatrixSafetyErrorCode = new NamespacedValue(null, \"ORG.MATRIX.MSC4387_SAFETY\");\n\n/***\n * This error is thrown when the homeserver refuses to handle an action due to a\n * safety concern.\n * @see https://github.com/matrix-org/matrix-spec-proposals/pull/4387\n */\nexport class MatrixSafetyError extends MatrixError {\n /**\n * The kinds of harms detected by the server.\n * @see https://github.com/matrix-org/matrix-spec-proposals/pull/4387 for a list of spec defined harms.\n */\n public readonly harms: Set<string>;\n /**\n * The date at which a request can be reattempted.\n */\n public readonly expiry?: Date;\n public constructor(...props: ConstructorParameters<typeof MatrixError>) {\n super(...props);\n const body = props[0];\n\n this.harms = new Set(body && \"harms\" in body && Array.isArray(body.harms) ? body.harms : []);\n this.message = `${super.message} (${[...this.harms].join(\", \")})`;\n if (body && \"expiry\" in body && typeof body.expiry === \"number\") {\n this.expiry = new Date(body.expiry);\n }\n }\n}\n"],"mappings":";;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAMA,SAAS,eAAe,QAAQ,uBAAuB;AAQvD;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO,MAAM,SAAS,SAAS,KAAK,CAAC;EAC1B,WAAW,CACd,GA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,MAAM,CAAC;IACvC;EACJ;AACJ","ignoreList":[]}
|
|
1
|
+
{"version":3,"file":"errors.js","names":[],"sources":["../../src/http-api/errors.ts"],"sourcesContent":["/*\nCopyright 2022 - 2024 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { type IMatrixApiError as IWidgetMatrixError } from \"matrix-widget-api\";\n\nimport { type IUsageLimit } from \"../@types/partials.ts\";\nimport { type MatrixEvent } from \"../models/event.ts\";\nimport { NamespacedValue } from \"../NamespacedValue.ts\";\nimport { hasRequiredStringProperty, isRecord } from \"../@types/type-guards.ts\";\n\ninterface IErrorJson extends Partial<IUsageLimit> {\n [key: string]: any; // extensible\n errcode?: string;\n error?: string;\n}\n\n/**\n * Construct a generic HTTP error. This is a JavaScript Error with additional information\n * specific to HTTP responses.\n * @param msg - The error message to include.\n * @param httpStatus - The HTTP response status code.\n * @param httpHeaders - The HTTP response headers.\n */\nexport class HTTPError extends Error {\n public constructor(\n msg: string,\n public readonly httpStatus?: number,\n public readonly httpHeaders?: Headers,\n ) {\n super(msg);\n }\n\n /**\n * Check if this error was due to rate-limiting on the server side (and should therefore be retried after a delay).\n *\n * If this returns `true`, {@link getRetryAfterMs} can be called to retrieve the server-side\n * recommendation for the retry period.\n *\n * @returns Whether this error is due to rate-limiting.\n */\n public isRateLimitError(): boolean {\n return this.httpStatus === 429;\n }\n\n /**\n * @returns The recommended delay in milliseconds to wait before retrying\n * the request that triggered this error, or null if no delay is recommended.\n * @throws Error if the recommended delay is an invalid value.\n * @see {@link safeGetRetryAfterMs} for a version of this check that doesn't throw.\n */\n public getRetryAfterMs(): number | null {\n const retryAfter = this.httpHeaders?.get(\"Retry-After\");\n if (retryAfter != null) {\n if (/^\\d+$/.test(retryAfter)) {\n const ms = Number.parseInt(retryAfter) * 1000;\n if (!Number.isFinite(ms)) {\n throw new Error(\"Retry-After header integer value is too large\");\n }\n return ms;\n }\n const date = new Date(retryAfter);\n if (date.toUTCString() !== retryAfter) {\n throw new Error(\"Retry-After header value is not a valid HTTP-date or non-negative decimal integer\");\n }\n return date.getTime() - Date.now();\n }\n return null;\n }\n}\n\n/**\n * Check if the given (JSON-parsed) response body looks like a Matrix error\n * response as specified in https://spec.matrix.org/v1.19/client-server-api/#standard-error-response\n *\n * @param response - the parsed response body to check\n * @returns whether the response is a valid {@link MatrixError}\n */\nexport function isMatrixErrorResponse(response: unknown): response is MatrixError {\n return (\n isRecord(response) &&\n hasRequiredStringProperty(response, \"error\") &&\n hasRequiredStringProperty(response, \"errcode\")\n );\n}\n\nexport class MatrixError extends HTTPError {\n // The Matrix 'errcode' value, e.g. \"M_FORBIDDEN\".\n public readonly errcode?: string;\n // The Matrix 'error' value.\n public readonly error?: string;\n // The raw Matrix error JSON used to construct this object.\n public data: IErrorJson;\n\n /**\n * Construct a Matrix error. This is a JavaScript Error with additional\n * information specific to the standard Matrix error response.\n * @param errorJson - The Matrix error JSON returned from the homeserver.\n * @param httpStatus - The numeric HTTP status code given\n * @param httpHeaders - The HTTP response headers given\n */\n public constructor(\n errorJson: IErrorJson = {},\n httpStatus?: number,\n public url?: string,\n public event?: MatrixEvent,\n httpHeaders?: Headers,\n ) {\n let message = errorJson.error || \"Unknown message\";\n if (httpStatus) {\n message = `[${httpStatus}] ${message}`;\n }\n if (url) {\n message = `${message} (${url})`;\n }\n super(`MatrixError: ${message}`, httpStatus, httpHeaders);\n this.errcode = errorJson.errcode;\n this.error = errorJson.error;\n this.name = errorJson.errcode || \"Unknown error code\";\n this.data = errorJson;\n }\n\n public isRateLimitError(): boolean {\n return (\n this.errcode === \"M_LIMIT_EXCEEDED\" ||\n ((this.errcode === \"M_UNKNOWN\" || this.errcode === undefined) && super.isRateLimitError())\n );\n }\n\n public getRetryAfterMs(): number | null {\n const headerValue = super.getRetryAfterMs();\n if (headerValue !== null) {\n return headerValue;\n }\n // Note: retry_after_ms is deprecated as of spec version v1.10\n if (this.errcode === \"M_LIMIT_EXCEEDED\" && \"retry_after_ms\" in this.data) {\n if (!Number.isInteger(this.data.retry_after_ms)) {\n throw new Error(\"retry_after_ms is not an integer\");\n }\n return this.data.retry_after_ms;\n }\n return null;\n }\n\n /**\n * @returns this error expressed as a JSON payload\n * for use by Widget API error responses.\n */\n public asWidgetApiErrorData(): IWidgetMatrixError {\n const headers: Record<string, string> = {};\n if (this.httpHeaders) {\n for (const [name, value] of this.httpHeaders) {\n headers[name] = value;\n }\n }\n return {\n http_status: this.httpStatus ?? 400,\n http_headers: headers,\n url: this.url ?? \"\",\n response: {\n errcode: this.errcode ?? \"M_UNKNOWN\",\n error: this.data.error ?? \"Unknown message\",\n ...this.data,\n },\n };\n }\n\n /**\n * @returns a new {@link MatrixError} from a JSON payload\n * received from Widget API error responses.\n */\n public static fromWidgetApiErrorData(data: IWidgetMatrixError): MatrixError {\n return new MatrixError(data.response, data.http_status, data.url, undefined, new Headers(data.http_headers));\n }\n}\n\n/**\n * @returns The recommended delay in milliseconds to wait before retrying the request.\n * @param error - The error to check for a retry delay.\n * @param defaultMs - The delay to use if the error was not due to rate-limiting or if no valid delay is recommended.\n */\nexport function safeGetRetryAfterMs(error: unknown, defaultMs: number): number {\n if (!(error instanceof HTTPError) || !error.isRateLimitError()) {\n return defaultMs;\n }\n try {\n return error.getRetryAfterMs() ?? defaultMs;\n } catch {\n return defaultMs;\n }\n}\n\n/**\n * Construct a ConnectionError. This is a JavaScript Error indicating\n * that a request failed because of some error with the connection, either\n * CORS was not correctly configured on the server, the server didn't response,\n * the request timed out, or the internet connection on the client side went down.\n */\nexport class ConnectionError extends Error {\n public constructor(message: string, cause?: Error) {\n super(message + (cause ? `: ${cause.message}` : \"\"));\n }\n\n public get name(): string {\n return \"ConnectionError\";\n }\n}\n\n/**\n * Construct a TokenRefreshError. This indicates that a request failed due to the token being expired,\n * and attempting to refresh said token also failed but in a way which was not indicative of token invalidation.\n * Assumed to be a temporary failure.\n */\nexport class TokenRefreshError extends Error {\n public constructor(cause?: Error) {\n super(cause?.message ?? \"\");\n }\n\n public get name(): string {\n return \"TokenRefreshError\";\n }\n}\n\n/**\n * Construct a TokenRefreshError. This indicates that a request failed due to the token being expired,\n * and attempting to refresh said token failed in a way indicative of token invalidation.\n */\nexport class TokenRefreshLogoutError extends Error {\n public constructor(cause?: Error) {\n super(cause?.message ?? \"\");\n }\n\n public get name(): string {\n return \"TokenRefreshLogoutError\";\n }\n}\n\nexport const MatrixSafetyErrorCode = new NamespacedValue(null, \"ORG.MATRIX.MSC4387_SAFETY\");\n\n/***\n * This error is thrown when the homeserver refuses to handle an action due to a\n * safety concern.\n * @see https://github.com/matrix-org/matrix-spec-proposals/pull/4387\n */\nexport class MatrixSafetyError extends MatrixError {\n /**\n * The kinds of harms detected by the server.\n * @see https://github.com/matrix-org/matrix-spec-proposals/pull/4387 for a list of spec defined harms.\n */\n public readonly harms: Set<string>;\n /**\n * The date at which a request can be reattempted.\n */\n public readonly expiry?: Date;\n public constructor(...props: ConstructorParameters<typeof MatrixError>) {\n super(...props);\n const body = props[0];\n\n this.harms = new Set(body && \"harms\" in body && Array.isArray(body.harms) ? body.harms : []);\n this.message = `${super.message} (${[...this.harms].join(\", \")})`;\n if (body && \"expiry\" in body && typeof body.expiry === \"number\") {\n this.expiry = new Date(body.expiry);\n }\n }\n}\n"],"mappings":";;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAMA,SAAS,eAAe,QAAQ,uBAAuB;AACvD,SAAS,yBAAyB,EAAE,QAAQ,QAAQ,0BAA0B;AAQ9E;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO,MAAM,SAAS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AAG,GAAG,KAAK,CAAC,OAAO,KAAK,CAAC,GAAG,IAAI,CAAC,KAAK,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,GAAG;IACjE,IAAI,IAAI,IAAI,QAAQ,IAAI,IAAI,IAAI,OAAO,IAAI,CAAC,MAAM,KAAK,QAAQ,EAAE;MAC7D,IAAI,CAAC,MAAM,GAAG,IAAI,IAAI,CAAC,IAAI,CAAC,MAAM,CAAC;IACvC;EACJ;AACJ","ignoreList":[]}
|
|
@@ -36,6 +36,11 @@ export interface SessionConfig {
|
|
|
36
36
|
* Determines the kind of call this will be.
|
|
37
37
|
*/
|
|
38
38
|
callIntent?: RTCCallIntent;
|
|
39
|
+
/**
|
|
40
|
+
* How long (in milliseconds) the callee's client should keep ringing/waiting for an
|
|
41
|
+
* answer before the sender gives up and the call notification is considered timed out.
|
|
42
|
+
*/
|
|
43
|
+
notificationLifetimeMs?: number;
|
|
39
44
|
}
|
|
40
45
|
export interface MembershipConfig {
|
|
41
46
|
/**
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"MatrixRTCSession.d.ts","sourceRoot":"","sources":["../../src/matrixrtc/MatrixRTCSession.ts"],"names":[],"mappings":"AAiBA,OAAO,EAAE,iBAAiB,EAAE,MAAM,kCAAkC,CAAC;AAErE,OAAO,EAAE,KAAK,IAAI,EAAE,MAAM,mBAAmB,CAAC;AAC9C,OAAO,EAAE,KAAK,YAAY,EAAE,MAAM,cAAc,CAAC;AAIjD,OAAO,EAAE,cAAc,EAAE,MAAM,qBAAqB,CAAC;AAGrD,OAAO,EAAE,KAAK,2BAA2B,EAA2B,MAAM,wBAAwB,CAAC;AAEnG,OAAO,KAAK,EACR,UAAU,EACV,mBAAmB,EACnB,MAAM,EACN,uBAAuB,EACvB,aAAa,EACb,SAAS,EACT,eAAe,EACf,mBAAmB,EACtB,MAAM,YAAY,CAAC;AACpB,OAAO,EACH,sBAAsB,EACtB,KAAK,gCAAgC,EAExC,MAAM,yBAAyB,C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AAE,MAAM,GAAG,SAAqB,GAAG,OAAO,CAAC,OAAO,CAAC,CAcvF;IACD;;;;OAIG;IACI,aAAa,IAAI,SAAS,GAAG,SAAS,CAG5C;IAEM,mBAAmB,IAAI,cAAc,GAAG,SAAS,CAEvD;IAED;;;;;;OAMG;IACI,sBAAsB,IAAI,aAAa,GAAG,SAAS,CASzD;IAEY,gBAAgB,CAAC,UAAU,EAAE,aAAa,GAAG,OAAO,CAAC,IAAI,CAAC,CAMtE;IAED;;;OAGG;IACI,oBAAoB,IAAI,IAAI,CAYlC;IAED;;OAEG;IACH,OAAO,CAAC,cAAc;IAqBtB;;;;;;OAMG;IACH,OAAO,CAAC,cAAc;IAsCtB;;OAEG;IACH,OAAO,CAAC,QAAQ,CAAC,kBAAkB,CAEjC;IAEF;;OAEG;IACH,OAAO,CAAC,QAAQ,CAAC,gBAAgB,CAI/B;IAEF;;OAEG;IACH,OAAO,CAAC,QAAQ,CAAC,mBAAmB,CAYlC;IAEF;;OAEG;IAEI,yBAAyB,QAAa,OAAO,CAAC,IAAI,CAAC,CAExD;IAGF,OAAO,CAAC,gCAAgC,CAAoC;IAE5E;;;;OAIG;IACH,OAAO,CAAC,+BAA+B;IAcvC;;;;;;OAMG;IACH,OAAO,CAAC,QAAQ,CAAC,yBAAyB,CAkDxC;CACL"}
|
|
@@ -475,6 +475,7 @@ export class MatrixRTCSession extends TypedEventEmitter {
|
|
|
475
475
|
* @param callIntent The type of call this is (e.g. "audio").
|
|
476
476
|
*/
|
|
477
477
|
sendCallNotify(parentEventId, notificationType, callIntent) {
|
|
478
|
+
const lifetime = this.joinConfig?.notificationLifetimeMs ?? 90000;
|
|
478
479
|
const sendNotificationEvent = async () => {
|
|
479
480
|
const content = {
|
|
480
481
|
"m.mentions": {
|
|
@@ -487,7 +488,7 @@ export class MatrixRTCSession extends TypedEventEmitter {
|
|
|
487
488
|
rel_type: RelationType.Reference
|
|
488
489
|
},
|
|
489
490
|
"sender_ts": Date.now(),
|
|
490
|
-
"lifetime":
|
|
491
|
+
"lifetime": lifetime
|
|
491
492
|
};
|
|
492
493
|
if (callIntent) {
|
|
493
494
|
content["m.call.intent"] = callIntent;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"MatrixRTCSession.js","names":[],"sources":["../../src/matrixrtc/MatrixRTCSession.ts"],"sourcesContent":["/*\nCopyright 2023 - 2026 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 Logger, logger as rootLogger } from \"../logger.ts\";\nimport { TypedEventEmitter } from \"../models/typed-event-emitter.ts\";\nimport { EventTimeline } from \"../models/event-timeline.ts\";\nimport { type Room } from \"../models/room.ts\";\nimport { type MatrixClient } from \"../client.ts\";\nimport { EventType, RelationType } from \"../@types/event.ts\";\nimport { KnownMembership } from \"../@types/membership.ts\";\nimport { type ISendEventResponse } from \"../@types/requests.ts\";\nimport { CallMembership } from \"./CallMembership.ts\";\nimport { RoomStateEvent } from \"../models/room-state.ts\";\nimport { MembershipManager, StickyEventMembershipManager } from \"./MembershipManager.ts\";\nimport { type CallMembershipIdentityParts, type IEncryptionManager } from \"./EncryptionManager.ts\";\nimport { logDurationSync } from \"../utils.ts\";\nimport type {\n Statistics,\n RTCNotificationType,\n Status,\n IRTCNotificationContent,\n RTCCallIntent,\n Transport,\n SlotDescription,\n RtcSlotEventContent,\n} from \"./types.ts\";\nimport {\n MembershipManagerEvent,\n type MembershipManagerEventHandlerMap,\n type IMembershipManager,\n} from \"./IMembershipManager.ts\";\nimport { RTCEncryptionManager } from \"./RTCEncryptionManager.ts\";\nimport { ToDeviceKeyTransport } from \"./ToDeviceKeyTransport.ts\";\nimport { TypedReEmitter } from \"../ReEmitter.ts\";\nimport { type IContent, type MatrixEvent } from \"../models/event.ts\";\nimport { RoomStickyEventsEvent, type RoomStickyEventsMap } from \"../models/room-sticky-events.ts\";\nimport { computeSlotId } from \"./utils.ts\";\n\n/**\n * Events emitted by MatrixRTCSession\n */\nexport enum MatrixRTCSessionEvent {\n // A member joined, left, or updated a property of their membership.\n MembershipsChanged = \"memberships_changed\",\n // We joined or left the session: our own local idea of whether we are joined,\n // separate from MembershipsChanged, ie. independent of whether our member event\n // has successfully gone through.\n JoinStateChanged = \"join_state_changed\",\n // The key used to encrypt media has changed\n EncryptionKeyChanged = \"encryption_key_changed\",\n /** The membership manager had to shut down caused by an unrecoverable error */\n MembershipManagerError = \"membership_manager_error\",\n /** The RTCSession did send a call notification caused by joining the call as the first member */\n DidSendCallNotification = \"did_send_call_notification\",\n}\n\nexport type MatrixRTCSessionEventHandlerMap = {\n [MatrixRTCSessionEvent.MembershipsChanged]: (\n oldMemberships: CallMembership[],\n newMemberships: CallMembership[],\n ) => void;\n [MatrixRTCSessionEvent.JoinStateChanged]: (isJoined: boolean) => void;\n [MatrixRTCSessionEvent.EncryptionKeyChanged]: (\n key: Uint8Array<ArrayBuffer>,\n encryptionKeyIndex: number,\n membership: CallMembershipIdentityParts,\n rtcBackendIdentity: string,\n ) => void;\n [MatrixRTCSessionEvent.MembershipManagerError]: (error: unknown) => void;\n [MatrixRTCSessionEvent.DidSendCallNotification]: (\n notificationContentNew: { event_id: string } & IRTCNotificationContent,\n ) => void;\n};\n\nexport interface SessionConfig {\n /**\n * What kind of notification to send when starting the session.\n * @default `undefined` (no notification)\n */\n notificationType?: RTCNotificationType;\n\n /**\n * Determines the kind of call this will be.\n */\n callIntent?: RTCCallIntent;\n}\n\n// The names follow these principles:\n// - we use the technical term delay if the option is related to delayed events.\n// - we use delayedLeaveEvent if the option is related to the delayed leave event.\n// - we use membershipEvent if the option is related to the rtc member state event.\n// - we use the technical term expiry if the option is related to the expiry field of the membership state event.\n// - we use a `Ms` postfix if the option is a duration to avoid using words like:\n// `time`, `duration`, `delay`, `timeout`... that might be mistaken/confused with technical terms.\nexport interface MembershipConfig {\n /**\n * The timeout (in milliseconds) after we joined the call, that our membership should expire\n * unless we have explicitly updated it.\n *\n * This is what goes into the m.rtc.member event expiry field and is typically set to a number of hours.\n */\n membershipEventExpiryMs?: number;\n\n /**\n * The time in (in milliseconds) which the manager will prematurely send the updated state event before the membership `expires` time to make sure it\n * sends the updated state event early enough.\n *\n * A headroom of 1000ms and a `membershipExpiryTimeout` of 10000ms would result in the first membership event update after 9s and\n * a membership event that would be considered expired after 10s.\n *\n * This value does not have an effect on the value of `SessionMembershipData.expires`.\n */\n membershipEventExpiryHeadroomMs?: number;\n\n /**\n * The timeout (in milliseconds) with which the deleayed leave event on the server is configured.\n * After this time the server will set the event to the disconnected stat if it has not received a keep-alive from the client.\n */\n delayedLeaveEventDelayMs?: number;\n\n /**\n * The interval (in milliseconds) in which the client will send membership keep-alives to the server.\n */\n delayedLeaveEventRestartMs?: number;\n\n /**\n * The maximum number of retries that the manager will do for delayed event sending/updating and state event sending when a server rate limit has been hit.\n */\n maximumRateLimitRetryCount?: number;\n\n /**\n * The maximum number of retries that the manager will do for delayed event sending/updating and state event sending when a network error occurs.\n */\n maximumNetworkErrorRetryCount?: number;\n\n /**\n * The time (in milliseconds) after which we will retry a http request if it\n * failed to send due to a network error. (send membership event, send delayed event, restart delayed event...)\n */\n networkErrorRetryMs?: number;\n\n /**\n * The time (in milliseconds) after which a we consider a delayed event restart http request to have failed.\n * Setting this to a lower value will result in more frequent retries but also a higher chance of failiour.\n *\n * In the presence of network packet loss (hurting TCP connections), the custom delayedEventRestartLocalTimeoutMs\n * helps by keeping more delayed event reset candidates in flight,\n * improving the chances of a successful reset. (its is equivalent to the js-sdk `localTimeout` configuration,\n * but only applies to calls to the `_unstable_restartScheduledDelayedEvent` endpoint\n * or the `_unstable_updateDelayedEvent` endpoint with a body of `{action:\"restart\"}`.)\n */\n delayedLeaveEventRestartLocalTimeoutMs?: number;\n\n /**\n * Send membership using sticky events rather than state events.\n * This also make the client use the new m.rtc.member MSC4354 event format. (instead of m.call.member)\n *\n * **WARNING**: This is an unstable feature and not all clients will support it.\n */\n unstableSendStickyEvents?: boolean;\n}\n\nexport interface EncryptionConfig {\n /**\n * If true, generate and share a media key for this participant,\n * and emit MatrixRTCSessionEvent.EncryptionKeyChanged when\n * media keys for other participants become available.\n */\n manageMediaKeys?: boolean;\n /**\n * The minimum time (in milliseconds) between each attempt to send encryption key(s).\n * e.g. if this is set to 1000, then we will send at most one key event every second.\n * @deprecated - Not used by the new encryption manager.\n */\n updateEncryptionKeyThrottle?: number;\n\n /**\n * Sometimes it is necessary to rotate the encryption key after a membership update.\n * For performance reasons we might not want to rotate the key immediately but allow future memberships to use the same key.\n * If 5 people join in a row in less than 5 seconds, we don't want to rotate the key for each of them.\n * If 5 people leave in a row in less than 5 seconds, we don't want to rotate the key for each of them.\n * So we do share the key which was already used live for <5s to new joiners.\n * This does result in a potential leak up to the configured time of call media.\n * This has to be considered when choosing a value for this property.\n */\n keyRotationGracePeriodMs?: number;\n\n /**\n * The delay (in milliseconds) after a member leaves before we create and publish a new key, because people\n * tend to leave calls at the same time.\n * @deprecated - Not used by the new encryption manager.\n */\n makeKeyDelay?: number;\n /**\n * The delay (in milliseconds) between sending a new key and starting to encrypt with it. This\n * gives others a chance to receive the new key to minimize the chance they get media they can't decrypt.\n *\n * The higher this value is, the better it is for existing members as they will have a smoother experience.\n * But it impacts new joiners: They will always have to wait `useKeyDelay` before being able to decrypt the media\n * (as it will be encrypted with the new key after the delay only), even if the key has already arrived before the delay.\n */\n useKeyDelay?: number;\n}\nexport type JoinSessionConfig = SessionConfig & MembershipConfig & EncryptionConfig;\n\ninterface SessionMembershipsForSlotOpts {\n /**\n * Listen for incoming sticky member events. If disabled, this session will\n * ignore any incoming sticky events.\n */\n listenForStickyEvents: boolean;\n /**\n * Listen for incoming member state events (legacy). If disabled, this session will\n * ignore any incoming state events.\n */\n listenForMemberStateEvents: boolean;\n}\n\nconst DEFAULT_SESSION_MEMBERSHIPS_FOR_SLOT_OPTS: SessionMembershipsForSlotOpts = {\n listenForStickyEvents: true,\n listenForMemberStateEvents: true,\n};\n\n/**\n * A MatrixRTCSession manages the membership & properties of a MatrixRTC session.\n * This class doesn't deal with media at all, just membership & properties of a session.\n */\nexport class MatrixRTCSession extends TypedEventEmitter<\n MatrixRTCSessionEvent | MembershipManagerEvent,\n MatrixRTCSessionEventHandlerMap & MembershipManagerEventHandlerMap\n> {\n private membershipManager?: IMembershipManager;\n private encryptionManager?: IEncryptionManager;\n private joinConfig?: SessionConfig;\n private logger: Logger;\n\n private pendingNotificationToSend: undefined | RTCNotificationType;\n /**\n * This timeout is responsible to track any expiration. We need to know when we have to start\n * to ignore other call members. There is no callback for this. This timeout will always be configured to\n * emit when the next membership expires.\n */\n private expiryTimeout?: ReturnType<typeof setTimeout>;\n\n public memberships: CallMembership[] = [];\n\n /**\n * Resolves when the session has calculated the initial membership of the session.\n */\n public readonly initialMembershipCalculated: Promise<void>;\n /**\n * Does membership need to be recalculated? This is set to false upon\n * recalculation.\n */\n private membershipNeedsRecalculation = false;\n\n /**\n * The statistics for this session.\n */\n public statistics: Statistics = {\n counters: {\n roomEventEncryptionKeysSent: 0,\n roomEventEncryptionKeysReceived: 0,\n },\n totals: {\n roomEventEncryptionKeysReceivedTotalAge: 0,\n },\n };\n\n public get membershipStatus(): Status | undefined {\n return this.membershipManager?.status;\n }\n public get probablyLeft(): boolean | undefined {\n return this.membershipManager?.probablyLeft;\n }\n public get delayId(): string | undefined {\n return this.membershipManager?.delayId;\n }\n\n /**\n * The callId (sessionId) of the call.\n *\n * It can be undefined since the callId is only known once the first membership joins.\n * The callId is the property that, per definition, groups memberships into one call.\n * @deprecated use `slotId` instead.\n */\n public get callId(): string | undefined {\n return this.slotDescription?.id;\n }\n /**\n * The slotId of the call.\n * `{application}#{appSpecificId}`\n * It can be undefined since the slotId is only known once the first membership joins.\n * The slotId is the property that, per definition, groups memberships into one call.\n */\n public get slotId(): string | undefined {\n return computeSlotId(this.slotDescription);\n }\n\n /**\n * Reads the current slot state event's content for this session.\n *\n * @returns The slot event's content, or `undefined` if no slot event exists for this session.\n */\n public getRtcSlot(): RtcSlotEventContent | undefined {\n return getSlotEventContent(this.roomSubset, this.slotDescription);\n }\n\n /**\n * Whether this session's slot is closed.\n *\n * @returns `true` if the slot is closed, `false` if the slot is open or `undefined`\n * if no slot exists.\n */\n public isSlotClosed(): boolean | undefined {\n return isSlotClosed(this.roomSubset, this.slotDescription);\n }\n\n /**\n * Returns all the call memberships for a room that match the provided `sessionDescription`,\n * oldest first.\n *\n * By default, this will return *both* sticky and member state events.\n */\n public static async sessionMembershipsForSlot(\n room: Pick<Room, \"getLiveTimeline\" | \"roomId\" | \"hasMembershipState\" | \"_unstable_getStickyEvents\">,\n slotDescription: SlotDescription,\n // default both true this implied we combine sticky and state events for the final call state\n // (prefer sticky events in case of a duplicate)\n options: SessionMembershipsForSlotOpts = DEFAULT_SESSION_MEMBERSHIPS_FOR_SLOT_OPTS,\n ): Promise<CallMembership[]> {\n const logger = rootLogger.getChild(\n `[MatrixRTCSession ${room.roomId} ${slotDescription.application}#${slotDescription.id}]`,\n );\n const callMemberEvents = collectMembersEvents(room, slotDescription, options, logger);\n\n const callMemberships = await computeBackendIdentityAndVerifyMemberEvents(\n room,\n callMemberEvents,\n slotDescription,\n logger,\n );\n\n callMemberships.sort((a, b) => a.createdTs() - b.createdTs());\n if (callMemberships.length > 1) {\n logger.debug(\n `Call memberships in room ${room.roomId}, in order: `,\n callMemberships.map((m) => [m.createdTs(), m.userId]),\n );\n }\n\n return callMemberships;\n }\n\n /**\n * Return the MatrixRTC session for the room.\n * This returned session can be used to find out if there are active sessions\n * for the requested room and `slotDescription`.\n */\n public static sessionForSlot(\n client: MatrixClient,\n room: Room,\n slotDescription: SlotDescription,\n opts?: SessionMembershipsForSlotOpts,\n ): MatrixRTCSession {\n return new MatrixRTCSession(client, room, slotDescription, opts);\n }\n\n /**\n * WARN: this can in theory only be a subset of the room with the properties required by\n * this class.\n * Outside of tests this most likely will be a full room, however.\n * @deprecated Relying on a full Room object being available here is an anti-pattern. You should be tracking\n * the room object in your own code and passing it in when needed.\n */\n public get room(): Room {\n return this.roomSubset as Room;\n }\n\n /**\n * This constructs a room session. When using MatrixRTC inside the js-sdk this is expected\n * to be used with the MatrixRTCSessionManager exclusively.\n *\n * In cases where you don't use the js-sdk but build on top of another Matrix stack this class can be used standalone\n * to manage a joined MatrixRTC session.\n *\n * @param client A subset of the {@link MatrixClient} that lets the session interact with the Matrix room.\n * @param roomSubset The room this session is attached to. A subset of a js-sdk Room that the session needs.\n * @param slotDescription The slot description is a virtual address where participants are allowed to meet.\n * This session will only manage memberships that match this slot description.Sessions are distinct if any of\n * those properties are distinct: `roomSubset.roomId`, `slotDescription.application`, `slotDescription.id`.\n * @param calculateMembershipsOpts - Options to configure how memberships are calculated for this session.\n */\n public constructor(\n private readonly client: Pick<\n MatrixClient,\n | \"getUserId\"\n | \"getDeviceId\"\n | \"sendEvent\"\n | \"sendStateEvent\"\n | \"_unstable_sendDelayedStateEvent\"\n | \"_unstable_updateDelayedEvent\"\n | \"_unstable_cancelScheduledDelayedEvent\"\n | \"_unstable_restartScheduledDelayedEvent\"\n | \"_unstable_sendScheduledDelayedEvent\"\n | \"_unstable_sendStickyEvent\"\n | \"_unstable_sendStickyDelayedEvent\"\n | \"cancelPendingEvent\"\n | \"encryptAndSendToDevice\"\n | \"off\"\n | \"on\"\n | \"decryptEventIfNeeded\"\n >,\n private roomSubset: Pick<\n Room,\n | \"getLiveTimeline\"\n | \"roomId\"\n | \"getVersion\"\n | \"hasMembershipState\"\n | \"on\"\n | \"off\"\n | \"_unstable_getStickyEvents\"\n >,\n\n public readonly slotDescription: SlotDescription,\n private readonly calculateMembershipsOpts?: SessionMembershipsForSlotOpts,\n ) {\n super();\n this.logger = rootLogger.getChild(\n `[MatrixRTCSession ${roomSubset.roomId} ${slotDescription.application}#${slotDescription.id}]`,\n );\n\n this.roomSubset.on(RoomStateEvent.Members, this.onRoomMemberUpdate);\n this.roomSubset.on(RoomStateEvent.Events, this.onRoomStateEvent);\n this.roomSubset.on(RoomStickyEventsEvent.Update, this.onStickyEventUpdate);\n\n this.initialMembershipCalculated = this.ensureRecalculateSessionMembers();\n this.setExpiryTimer();\n }\n /*\n * Returns true if we intend to be participating in the MatrixRTC session.\n * This is determined by checking if the relativeExpiry has been set.\n */\n public isJoined(): boolean {\n return this.membershipManager?.isJoined() ?? false;\n }\n\n /**\n * Performs cleanup & removes timers for client shutdown\n */\n public async stop(): Promise<void> {\n await this.membershipManager?.leave(1000);\n if (this.expiryTimeout) {\n clearTimeout(this.expiryTimeout);\n this.expiryTimeout = undefined;\n }\n\n this.roomSubset.off(RoomStateEvent.Members, this.onRoomMemberUpdate);\n this.roomSubset.off(RoomStateEvent.Events, this.onRoomStateEvent);\n this.roomSubset.off(RoomStickyEventsEvent.Update, this.onStickyEventUpdate);\n }\n\n private reEmitter = new TypedReEmitter<\n MatrixRTCSessionEvent | MembershipManagerEvent,\n MatrixRTCSessionEventHandlerMap & MembershipManagerEventHandlerMap\n >(this);\n\n /**\n * Announces this user and device as joined to the MatrixRTC session,\n * and continues to update the membership event to keep it valid until\n * leaveRoomSession() is called\n * This will not subscribe to updates: remember to call subscribe() separately if\n * desired.\n * This method will return immediately and the session will be joined in the background.\n * @param ownMembershipIdentity the identity of the user and device joining the session.\n * This will be put into the content.member.\n * @param fociPreferred the list of preferred foci to use in the joined RTC membership event.\n * If multiSfuFocus is set, this is only needed if this client wants to publish to multiple transports simultaneously.\n * @param multiSfuFocus the active focus to use in the joined RTC membership event. Setting this implies the\n * membership manager will operate in a multi-SFU connection mode. If `undefined`, an `oldest_membership`\n * transport selection will be used instead.\n * @param joinConfig - Additional configuration for the joined session.\n */\n public joinRTCSession(\n ownMembershipIdentity: CallMembershipIdentityParts,\n fociPreferred: Transport[],\n multiSfuFocus?: Transport,\n joinConfig?: JoinSessionConfig,\n ): void {\n if (this.isJoined()) {\n this.logger.info(`Already joined to session in room ${this.roomSubset.roomId}: ignoring join call`);\n return;\n } else {\n // Create MembershipManager and pass the RTCSession logger (with room id info)\n this.membershipManager = joinConfig?.unstableSendStickyEvents\n ? new StickyEventMembershipManager(\n joinConfig,\n this.roomSubset,\n this.client,\n this.slotDescription,\n ownMembershipIdentity.memberId,\n this.logger,\n )\n : new MembershipManager(joinConfig, this.roomSubset, this.client, this.slotDescription, this.logger);\n\n this.reEmitter.reEmit(this.membershipManager, [\n MembershipManagerEvent.ProbablyLeft,\n MembershipManagerEvent.StatusChanged,\n MembershipManagerEvent.DelayIdChanged,\n ]);\n // Create Encryption manager\n const [room, client, statistics] = [this.roomSubset, this.client, this.statistics];\n const transport = new ToDeviceKeyTransport(ownMembershipIdentity, room.roomId, client, statistics);\n this.encryptionManager = new RTCEncryptionManager(\n ownMembershipIdentity,\n () => this.memberships,\n transport,\n (\n keyBin: Uint8Array<ArrayBuffer>,\n encryptionKeyIndex: number,\n membership: CallMembershipIdentityParts,\n rtcBackendIdentity: string,\n ) => {\n this.emit(\n MatrixRTCSessionEvent.EncryptionKeyChanged,\n keyBin,\n encryptionKeyIndex,\n membership,\n rtcBackendIdentity,\n );\n },\n this.logger,\n );\n }\n\n this.joinConfig = joinConfig;\n this.pendingNotificationToSend = this.joinConfig?.notificationType;\n\n // Join!\n this.membershipManager.join(fociPreferred, multiSfuFocus, (e) => {\n this.logger.error(\"MembershipManager encountered an unrecoverable error: \", e);\n this.emit(MatrixRTCSessionEvent.MembershipManagerError, e);\n this.emit(MatrixRTCSessionEvent.JoinStateChanged, this.isJoined());\n });\n this.encryptionManager.join(joinConfig);\n\n this.emit(MatrixRTCSessionEvent.JoinStateChanged, true);\n }\n\n /**\n *\n * @param fociPreferred\n * @param multiSfuFocus\n * @param joinConfig\n * @deprecated use the joinRTCSession method instead\n */\n public joinRoomSession(\n fociPreferred: Transport[],\n multiSfuFocus?: Transport,\n joinConfig?: JoinSessionConfig,\n ): void {\n const [userId, deviceId] = [this.client.getUserId()!, this.client.getDeviceId()!];\n // TODO this wants to become a UUID\n const memberId = `${userId}:${deviceId}`;\n this.joinRTCSession({ userId, deviceId, memberId }, fociPreferred, multiSfuFocus, joinConfig);\n }\n\n /**\n * Announces this user and device as having left the MatrixRTC session\n * and stops scheduled updates.\n * This will not unsubscribe from updates: remember to call unsubscribe() separately if\n * desired.\n * The membership update required to leave the session will retry if it fails.\n * Without network connection the promise will never resolve.\n * A timeout can be provided so that there is a guarantee for the promise to resolve.\n * @returns Whether the membership update was attempted and did not time out.\n */\n public async leaveRoomSession(timeout: number | undefined = undefined): Promise<boolean> {\n if (!this.isJoined()) {\n this.logger.info(`Not joined to session in room ${this.roomSubset.roomId}: ignoring leave call`);\n return false;\n }\n\n this.logger.info(`Leaving call session in room ${this.roomSubset.roomId}`);\n\n this.encryptionManager!.leave();\n\n const leavePromise = this.membershipManager!.leave(timeout);\n this.emit(MatrixRTCSessionEvent.JoinStateChanged, false);\n\n return await leavePromise;\n }\n /**\n * This returns the focus in use by the oldest membership.\n * Do not use since this might be just the focus for the oldest membership. others might use a different focus.\n * @deprecated use `member.getTransport(session.getOldestMembership())` instead for the specific member you want to get the focus for.\n */\n public getFocusInUse(): Transport | undefined {\n const oldestMembership = this.getOldestMembership();\n return oldestMembership?.getTransport(oldestMembership);\n }\n\n public getOldestMembership(): CallMembership | undefined {\n return this.memberships[0];\n }\n\n /**\n * Get the call intent for the current call, based on what members are advertising. If one or more\n * members disagree on the current call intent, or nobody specifies one then `undefined` is returned.\n *\n * If all members that specify a call intent agree, that value is returned.\n * @returns A call intent, or `undefined` if no consensus or not given.\n */\n public getConsensusCallIntent(): RTCCallIntent | undefined {\n const getFirstCallIntent = this.memberships.find((m) => !!m.callIntent)?.callIntent;\n if (!getFirstCallIntent) {\n return undefined;\n }\n if (this.memberships.every((m) => !m.callIntent || m.callIntent === getFirstCallIntent)) {\n return getFirstCallIntent;\n }\n return undefined;\n }\n\n public async updateCallIntent(callIntent: RTCCallIntent): Promise<void> {\n const myMembership = this.membershipManager?.ownMembership;\n if (!myMembership) {\n throw Error(\"Not connected yet\");\n }\n await this.membershipManager?.updateCallIntent(callIntent);\n }\n\n /**\n * Re-emit an EncryptionKeyChanged event for each tracked encryption key. This can be used to export\n * the keys.\n */\n public reemitEncryptionKeys(): void {\n this.encryptionManager?.getEncryptionKeys().forEach((keyRing, key) => {\n keyRing.forEach((keyInfo) => {\n this.emit(\n MatrixRTCSessionEvent.EncryptionKeyChanged,\n keyInfo.key,\n keyInfo.keyIndex,\n keyInfo.membership,\n keyInfo.rtcBackendIdentity,\n );\n });\n });\n }\n\n /**\n * Sets a timer for the soonest membership expiry\n */\n private setExpiryTimer(): void {\n if (this.expiryTimeout) {\n clearTimeout(this.expiryTimeout);\n this.expiryTimeout = undefined;\n }\n\n let soonestExpiry;\n for (const membership of this.memberships) {\n const thisExpiry = membership.getMsUntilExpiry();\n // If getMsUntilExpiry is undefined we have a MSC4143 (MatrixRTC) compliant event - it never expires\n // but will be reliably resent on disconnect.\n if (thisExpiry !== undefined && (soonestExpiry === undefined || thisExpiry < soonestExpiry)) {\n soonestExpiry = thisExpiry;\n }\n }\n\n if (soonestExpiry != undefined) {\n this.expiryTimeout = setTimeout(() => void this.ensureRecalculateSessionMembers(), soonestExpiry);\n }\n }\n\n /**\n * Sends notification events to indiciate the call has started.\n * Note: This does not return a promise, instead scheduling the notification events to be sent.\n * @param parentEventId Event id linking to your RTC call membership event.\n * @param notificationType The type of notification to send\n * @param callIntent The type of call this is (e.g. \"audio\").\n */\n private sendCallNotify(\n parentEventId: string,\n notificationType: RTCNotificationType,\n callIntent?: RTCCallIntent,\n ): void {\n const sendNotificationEvent = async (): Promise<{\n response: ISendEventResponse;\n content: IRTCNotificationContent;\n }> => {\n const content: IRTCNotificationContent = {\n \"m.mentions\": { user_ids: [], room: true },\n \"notification_type\": notificationType,\n \"m.relates_to\": {\n event_id: parentEventId,\n rel_type: RelationType.Reference,\n },\n \"sender_ts\": Date.now(),\n \"lifetime\": 30_000, // 30 seconds\n };\n if (callIntent) {\n content[\"m.call.intent\"] = callIntent;\n }\n const response = await this.client.sendEvent(this.roomSubset.roomId, EventType.RTCNotification, content);\n return { response, content };\n };\n\n void sendNotificationEvent()\n .then((notification) => {\n // Join event_id and origin event content\n const newResult = { ...notification.response, ...notification.content };\n this.emit(MatrixRTCSessionEvent.DidSendCallNotification, newResult);\n })\n .catch(([errorLegacy, errorNew]) =>\n this.logger.error(\"Failed to send call notification\", errorLegacy, errorNew),\n );\n }\n\n /**\n * Call this when the Matrix room members have changed.\n */\n private readonly onRoomMemberUpdate = (): void => {\n void this.ensureRecalculateSessionMembers();\n };\n\n /**\n * Call this when a room state event has been updated.\n */\n private readonly onRoomStateEvent = (event: MatrixEvent): void => {\n if (event.getType() !== EventType.RTCSlot) return;\n if (event.getStateKey() !== computeSlotId(this.slotDescription)) return;\n void this.ensureRecalculateSessionMembers();\n };\n\n /**\n * Call this when a sticky event update has occured.\n */\n private readonly onStickyEventUpdate: RoomStickyEventsMap[RoomStickyEventsEvent.Update] = (\n added,\n updated,\n removed,\n ): void => {\n if (\n [...added, ...removed, ...updated.flatMap((v) => [v.current, v.previous])].some(\n (e) => e.getType() === EventType.RTCMembership,\n )\n ) {\n void this.ensureRecalculateSessionMembers();\n }\n };\n\n /**\n * Call this when something changed that may impacts the current MatrixRTC members in this session.\n */\n // We allow this name schema since this function should only be used for testing purposes.\n public _onRTCSessionMemberUpdate = async (): Promise<void> => {\n await this.recalculateSessionMembers();\n };\n\n // helper variables to make sure we do not have parallel running recalculations.\n private recalculateSessionMembersPromise: Promise<void> = Promise.resolve();\n\n /**\n * Ensures that membership is recalculated when the state of the session may have changed.\n * Also ensures that only one recalculation is made at a time.\n * @returns A promise resolving when the state has been recalculated.\n */\n private ensureRecalculateSessionMembers(): Promise<void> {\n if (this.membershipNeedsRecalculation) {\n // We have already requested recalcuation, don't attempt a new one.\n return this.recalculateSessionMembersPromise;\n }\n this.membershipNeedsRecalculation = true;\n // Chain the recalculation.\n this.recalculateSessionMembersPromise = this.recalculateSessionMembersPromise.then(\n () => this.recalculateSessionMembers(),\n () => this.recalculateSessionMembers(),\n );\n return this.recalculateSessionMembersPromise;\n }\n\n /**\n * Call this when anything that could impact rtc memberships has changed: Room Members or RTC members.\n *\n * Examines the latest call memberships and handles any encryption key sending or rotation that is needed.\n *\n * This function should be called when the room members or call memberships might have changed.\n */\n private readonly recalculateSessionMembers = async (): Promise<void> => {\n // Clear the flag.\n this.membershipNeedsRecalculation = false;\n const oldMemberships = this.memberships;\n\n this.memberships = await MatrixRTCSession.sessionMembershipsForSlot(\n this.room,\n this.slotDescription,\n this.calculateMembershipsOpts,\n );\n\n const changed =\n oldMemberships.length != this.memberships.length ||\n oldMemberships.some((m, i) => !CallMembership.equal(m, this.memberships[i]));\n\n if (changed) {\n this.logger.info(\n `Memberships for call in room ${this.roomSubset.roomId} have changed: emitting (${this.memberships.length} members)`,\n );\n logDurationSync(this.logger, \"emit MatrixRTCSessionEvent.MembershipsChanged\", () => {\n this.emit(MatrixRTCSessionEvent.MembershipsChanged, oldMemberships, this.memberships);\n });\n\n void this.membershipManager?.onRTCSessionMemberUpdate(this.memberships);\n // The `ownMembership` will be set when calling `onRTCSessionMemberUpdate`.\n const ownMembership = this.membershipManager?.ownMembership;\n if (this.pendingNotificationToSend && ownMembership && oldMemberships.length === 0) {\n // If we're the first member in the call, we're responsible for\n // sending the notification event\n if (ownMembership.eventId && this.joinConfig?.notificationType) {\n this.sendCallNotify(\n ownMembership.eventId,\n this.joinConfig.notificationType,\n ownMembership.callIntent,\n );\n } else {\n this.logger.warn(\"Own membership eventId is undefined, cannot send call notification\");\n }\n }\n // If anyone else joins the session it is no longer our responsibility to send the notification.\n // (If we were the joiner we already did sent the notification in the block above.)\n if (this.memberships.length > 0) this.pendingNotificationToSend = undefined;\n } else {\n this.logger.debug(`No membership changes detected for room ${this.roomSubset.roomId}`);\n }\n // This also needs to be done if `changed` = false\n // A member might have updated their fingerprint (created_ts)\n this.encryptionManager?.onMembershipsUpdate(oldMemberships);\n\n this.setExpiryTimer();\n };\n}\n\n/// Private helpers\nasync function computeBackendIdentityAndVerifyMemberEvents(\n room: Pick<Room, \"hasMembershipState\">,\n callMemberEvents: MatrixEvent[],\n slotDescription: SlotDescription,\n logger: Logger,\n): Promise<CallMembership[]> {\n const callMemberships: CallMembership[] = [];\n\n for (const memberEvent of callMemberEvents) {\n const content = memberEvent.getContent();\n\n // Quick filter to avoid unneeded processing of invalid events or left events.\n if (!quickFilterNonRelevantContents(content, logger)) {\n continue;\n }\n\n try {\n const membership = await CallMembership.parseFromEvent(memberEvent);\n\n if (isValidMembership(membership, room, slotDescription, logger)) {\n callMemberships.push(membership);\n }\n } catch (e) {\n logger.warn(\"Couldn't construct call membership: \", e);\n }\n }\n\n return callMemberships;\n}\n\nfunction quickFilterNonRelevantContents(content: IContent, logger: Logger): boolean {\n // Ignore sticky keys for the count\n const eventKeysCount = Object.keys(content).filter((k) => k !== \"msc4354_sticky_key\").length;\n // Don't even bother about empty events (saves us from costly type/\"key in\" checks in bigger rooms)\n if (eventKeysCount === 0) return false;\n\n // We first decide if it's a MSC4143 event (per device state key)\n if (eventKeysCount > 1 && \"application\" in content) {\n // We have a MSC4143 event membership event with a proper joined content\n return true;\n } else if (eventKeysCount === 1 && \"memberships\" in content) {\n // Events used to have this format in the past, but are now deprecated.\n // Given that state events ~cannot be deleted, there can be some remaining events in the room, just ignore them.\n return false;\n } else {\n // Invalid or left content\n return false;\n }\n}\n\nfunction isValidMembership(\n membership: CallMembership,\n room: Pick<Room, \"hasMembershipState\">,\n slotDescription: SlotDescription,\n logger: Logger,\n): boolean {\n if (membership.slotDescription.id !== slotDescription.id) {\n logger.info(\n `Ignoring membership of user ${membership.userId} for a different slot. Theirs: ${JSON.stringify(membership.slotDescription)}, Expected: ${JSON.stringify(slotDescription)}`,\n );\n return false;\n }\n\n if (membership.isExpired()) {\n logger.info(`Ignoring expired device membership ${membership.userId}/${membership.deviceId}`);\n return false;\n }\n\n if (!room.hasMembershipState(membership.userId ?? \"\", KnownMembership.Join)) {\n logger.info(`Ignoring membership of user ${membership.userId} who is not in the room.`);\n return false;\n }\n\n return true;\n}\n\n/**\n * Reads the slot state event's content for the given slot description.\n *\n * @returns The slot event's content, or `undefined` if no slot event exists for the given description.\n */\nfunction getSlotEventContent(\n room: Pick<Room, \"getLiveTimeline\">,\n slotDescription: SlotDescription,\n): RtcSlotEventContent | undefined {\n const slotId = computeSlotId(slotDescription);\n const slotEvent = room\n .getLiveTimeline()\n .getState(EventTimeline.FORWARDS)\n ?.getStateEvents(EventType.RTCSlot, slotId);\n if (!slotEvent) return undefined;\n\n return slotEvent.getContent<RtcSlotEventContent>();\n}\n\n/**\n * Whether the given slot is closed.\n *\n * @returns `true` if the slot is closed, `false` if the slot is open or `undefined`\n * if no slot exists.\n */\nfunction isSlotClosed(room: Pick<Room, \"getLiveTimeline\">, slotDescription: SlotDescription): boolean | undefined {\n const content = getSlotEventContent(room, slotDescription) as Partial<RtcSlotEventContent> | undefined;\n if (content === undefined) return undefined;\n\n return (\n content.status !== \"open\" ||\n typeof content.application !== \"object\" ||\n content.application?.type !== slotDescription.application\n );\n}\n\n/**\n * Collects the raw member events from room state and sticky store.\n */\nfunction collectMembersEvents(\n room: Pick<Room, \"getLiveTimeline\" | \"roomId\" | \"_unstable_getStickyEvents\">,\n slotDescription: SlotDescription,\n options: SessionMembershipsForSlotOpts,\n logger: Logger,\n): MatrixEvent[] {\n const { listenForStickyEvents, listenForMemberStateEvents } = options;\n let callMemberEvents: MatrixEvent[] = [];\n if (listenForStickyEvents && !isSlotClosed(room, slotDescription)) {\n // prefill with sticky events\n callMemberEvents = [...room._unstable_getStickyEvents()].filter((e) => e.getType() === EventType.RTCMembership);\n }\n if (listenForMemberStateEvents) {\n const roomState = room.getLiveTimeline().getState(EventTimeline.FORWARDS);\n if (!roomState) {\n logger.warn(\"Couldn't get state for room \" + room.roomId + \"using empty membership array\");\n return [];\n }\n const callMemberStateEvents = roomState.getStateEvents(EventType.GroupCallMemberPrefix);\n callMemberEvents = callMemberEvents.concat(\n callMemberStateEvents.filter(\n (callMemberStateEvent) =>\n !callMemberEvents.some(\n // only care about state events which have keys which we have not yet seen in the sticky events.\n // TODO: I believe this can discard a joined state event if there is a matching left sticky event.\n (stickyEvent) =>\n stickyEvent.getContent().msc4354_sticky_key === callMemberStateEvent.getStateKey(),\n ),\n ),\n );\n }\n return callMemberEvents;\n}\n"],"mappings":";;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA,SAAsB,MAAM,IAAI,UAAU,QAAQ,cAAc;AAChE,SAAS,iBAAiB,QAAQ,kCAAkC;AACpE,SAAS,aAAa,QAAQ,6BAA6B;AAG3D,SAAS,SAAS,EAAE,YAAY,QAAQ,oBAAoB;AAC5D,SAAS,eAAe,QAAQ,yBAAyB;AAEzD,SAAS,cAAc,QAAQ,qBAAqB;AACpD,SAAS,cAAc,QAAQ,yBAAyB;AACxD,SAAS,iBAAiB,EAAE,4BAA4B,QAAQ,wBAAwB;AAExF,SAAS,eAAe,QAAQ,aAAa;AAW7C,SACI,sBAAsB,QAGnB,yBAAyB;AAChC,SAAS,oBAAoB,QAAQ,2BAA2B;AAChE,SAAS,oBAAoB,QAAQ,2BAA2B;AAChE,SAAS,cAAc,QAAQ,iBAAiB;AAEhD,SAAS,qBAAqB,QAAkC,iCAAiC;AACjG,SAAS,aAAa,QAAQ,YAAY;;AAE1C;AACA;AACA;AACA,WAAY,qBAAqB,0BAArB,qBAAqB;EAC7B;EADQ,qBAAqB;EAG7B;EACA;EACA;EALQ,qBAAqB;EAO7B;EAPQ,qBAAqB;EAS7B;EATQ,qBAAqB;EAW7B;EAXQ,qBAAqB;EAAA,OAArB,qBAAqB;AAAA;;AA8CjC;A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OAAO,EAAE;IACb;IACA,MAAM,qBAAqB,GAAG,SAAS,CAAC,cAAc,CAAC,SAAS,CAAC,qBAAqB,CAAC;IACvF,gBAAgB,GAAG,gBAAgB,CAAC,MAAM,CACtC,qBAAqB,CAAC,MAAM,CACvB,oBAAoB,IACjB,CAAC,gBAAgB,CAAC,IAAI;IAClB;IACA;IACC,WAAW,IACR,WAAW,CAAC,UAAU,CAAC,CAAC,CAAC,kBAAkB,KAAK,oBAAoB,CAAC,WAAW,CAAC,CACzF,CACR,CACJ,CAAC;EACL;EACA,OAAO,gBAAgB;AAC3B","ignoreList":[]}
|
|
1
|
+
{"version":3,"file":"MatrixRTCSession.js","names":[],"sources":["../../src/matrixrtc/MatrixRTCSession.ts"],"sourcesContent":["/*\nCopyright 2023 - 2026 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 Logger, logger as rootLogger } from \"../logger.ts\";\nimport { TypedEventEmitter } from \"../models/typed-event-emitter.ts\";\nimport { EventTimeline } from \"../models/event-timeline.ts\";\nimport { type Room } from \"../models/room.ts\";\nimport { type MatrixClient } from \"../client.ts\";\nimport { EventType, RelationType } from \"../@types/event.ts\";\nimport { KnownMembership } from \"../@types/membership.ts\";\nimport { type ISendEventResponse } from \"../@types/requests.ts\";\nimport { CallMembership } from \"./CallMembership.ts\";\nimport { RoomStateEvent } from \"../models/room-state.ts\";\nimport { MembershipManager, StickyEventMembershipManager } from \"./MembershipManager.ts\";\nimport { type CallMembershipIdentityParts, type IEncryptionManager } from \"./EncryptionManager.ts\";\nimport { logDurationSync } from \"../utils.ts\";\nimport type {\n Statistics,\n RTCNotificationType,\n Status,\n IRTCNotificationContent,\n RTCCallIntent,\n Transport,\n SlotDescription,\n RtcSlotEventContent,\n} from \"./types.ts\";\nimport {\n MembershipManagerEvent,\n type MembershipManagerEventHandlerMap,\n type IMembershipManager,\n} from \"./IMembershipManager.ts\";\nimport { RTCEncryptionManager } from \"./RTCEncryptionManager.ts\";\nimport { ToDeviceKeyTransport } from \"./ToDeviceKeyTransport.ts\";\nimport { TypedReEmitter } from \"../ReEmitter.ts\";\nimport { type IContent, type MatrixEvent } from \"../models/event.ts\";\nimport { RoomStickyEventsEvent, type RoomStickyEventsMap } from \"../models/room-sticky-events.ts\";\nimport { computeSlotId } from \"./utils.ts\";\n\n/**\n * Events emitted by MatrixRTCSession\n */\nexport enum MatrixRTCSessionEvent {\n // A member joined, left, or updated a property of their membership.\n MembershipsChanged = \"memberships_changed\",\n // We joined or left the session: our own local idea of whether we are joined,\n // separate from MembershipsChanged, ie. independent of whether our member event\n // has successfully gone through.\n JoinStateChanged = \"join_state_changed\",\n // The key used to encrypt media has changed\n EncryptionKeyChanged = \"encryption_key_changed\",\n /** The membership manager had to shut down caused by an unrecoverable error */\n MembershipManagerError = \"membership_manager_error\",\n /** The RTCSession did send a call notification caused by joining the call as the first member */\n DidSendCallNotification = \"did_send_call_notification\",\n}\n\nexport type MatrixRTCSessionEventHandlerMap = {\n [MatrixRTCSessionEvent.MembershipsChanged]: (\n oldMemberships: CallMembership[],\n newMemberships: CallMembership[],\n ) => void;\n [MatrixRTCSessionEvent.JoinStateChanged]: (isJoined: boolean) => void;\n [MatrixRTCSessionEvent.EncryptionKeyChanged]: (\n key: Uint8Array<ArrayBuffer>,\n encryptionKeyIndex: number,\n membership: CallMembershipIdentityParts,\n rtcBackendIdentity: string,\n ) => void;\n [MatrixRTCSessionEvent.MembershipManagerError]: (error: unknown) => void;\n [MatrixRTCSessionEvent.DidSendCallNotification]: (\n notificationContentNew: { event_id: string } & IRTCNotificationContent,\n ) => void;\n};\n\nexport interface SessionConfig {\n /**\n * What kind of notification to send when starting the session.\n * @default `undefined` (no notification)\n */\n notificationType?: RTCNotificationType;\n\n /**\n * Determines the kind of call this will be.\n */\n callIntent?: RTCCallIntent;\n\n /**\n * How long (in milliseconds) the callee's client should keep ringing/waiting for an\n * answer before the sender gives up and the call notification is considered timed out.\n */\n notificationLifetimeMs?: number;\n}\n\n// The names follow these principles:\n// - we use the technical term delay if the option is related to delayed events.\n// - we use delayedLeaveEvent if the option is related to the delayed leave event.\n// - we use membershipEvent if the option is related to the rtc member state event.\n// - we use the technical term expiry if the option is related to the expiry field of the membership state event.\n// - we use a `Ms` postfix if the option is a duration to avoid using words like:\n// `time`, `duration`, `delay`, `timeout`... that might be mistaken/confused with technical terms.\nexport interface MembershipConfig {\n /**\n * The timeout (in milliseconds) after we joined the call, that our membership should expire\n * unless we have explicitly updated it.\n *\n * This is what goes into the m.rtc.member event expiry field and is typically set to a number of hours.\n */\n membershipEventExpiryMs?: number;\n\n /**\n * The time in (in milliseconds) which the manager will prematurely send the updated state event before the membership `expires` time to make sure it\n * sends the updated state event early enough.\n *\n * A headroom of 1000ms and a `membershipExpiryTimeout` of 10000ms would result in the first membership event update after 9s and\n * a membership event that would be considered expired after 10s.\n *\n * This value does not have an effect on the value of `SessionMembershipData.expires`.\n */\n membershipEventExpiryHeadroomMs?: number;\n\n /**\n * The timeout (in milliseconds) with which the deleayed leave event on the server is configured.\n * After this time the server will set the event to the disconnected stat if it has not received a keep-alive from the client.\n */\n delayedLeaveEventDelayMs?: number;\n\n /**\n * The interval (in milliseconds) in which the client will send membership keep-alives to the server.\n */\n delayedLeaveEventRestartMs?: number;\n\n /**\n * The maximum number of retries that the manager will do for delayed event sending/updating and state event sending when a server rate limit has been hit.\n */\n maximumRateLimitRetryCount?: number;\n\n /**\n * The maximum number of retries that the manager will do for delayed event sending/updating and state event sending when a network error occurs.\n */\n maximumNetworkErrorRetryCount?: number;\n\n /**\n * The time (in milliseconds) after which we will retry a http request if it\n * failed to send due to a network error. (send membership event, send delayed event, restart delayed event...)\n */\n networkErrorRetryMs?: number;\n\n /**\n * The time (in milliseconds) after which a we consider a delayed event restart http request to have failed.\n * Setting this to a lower value will result in more frequent retries but also a higher chance of failiour.\n *\n * In the presence of network packet loss (hurting TCP connections), the custom delayedEventRestartLocalTimeoutMs\n * helps by keeping more delayed event reset candidates in flight,\n * improving the chances of a successful reset. (its is equivalent to the js-sdk `localTimeout` configuration,\n * but only applies to calls to the `_unstable_restartScheduledDelayedEvent` endpoint\n * or the `_unstable_updateDelayedEvent` endpoint with a body of `{action:\"restart\"}`.)\n */\n delayedLeaveEventRestartLocalTimeoutMs?: number;\n\n /**\n * Send membership using sticky events rather than state events.\n * This also make the client use the new m.rtc.member MSC4354 event format. (instead of m.call.member)\n *\n * **WARNING**: This is an unstable feature and not all clients will support it.\n */\n unstableSendStickyEvents?: boolean;\n}\n\nexport interface EncryptionConfig {\n /**\n * If true, generate and share a media key for this participant,\n * and emit MatrixRTCSessionEvent.EncryptionKeyChanged when\n * media keys for other participants become available.\n */\n manageMediaKeys?: boolean;\n /**\n * The minimum time (in milliseconds) between each attempt to send encryption key(s).\n * e.g. if this is set to 1000, then we will send at most one key event every second.\n * @deprecated - Not used by the new encryption manager.\n */\n updateEncryptionKeyThrottle?: number;\n\n /**\n * Sometimes it is necessary to rotate the encryption key after a membership update.\n * For performance reasons we might not want to rotate the key immediately but allow future memberships to use the same key.\n * If 5 people join in a row in less than 5 seconds, we don't want to rotate the key for each of them.\n * If 5 people leave in a row in less than 5 seconds, we don't want to rotate the key for each of them.\n * So we do share the key which was already used live for <5s to new joiners.\n * This does result in a potential leak up to the configured time of call media.\n * This has to be considered when choosing a value for this property.\n */\n keyRotationGracePeriodMs?: number;\n\n /**\n * The delay (in milliseconds) after a member leaves before we create and publish a new key, because people\n * tend to leave calls at the same time.\n * @deprecated - Not used by the new encryption manager.\n */\n makeKeyDelay?: number;\n /**\n * The delay (in milliseconds) between sending a new key and starting to encrypt with it. This\n * gives others a chance to receive the new key to minimize the chance they get media they can't decrypt.\n *\n * The higher this value is, the better it is for existing members as they will have a smoother experience.\n * But it impacts new joiners: They will always have to wait `useKeyDelay` before being able to decrypt the media\n * (as it will be encrypted with the new key after the delay only), even if the key has already arrived before the delay.\n */\n useKeyDelay?: number;\n}\nexport type JoinSessionConfig = SessionConfig & MembershipConfig & EncryptionConfig;\n\ninterface SessionMembershipsForSlotOpts {\n /**\n * Listen for incoming sticky member events. If disabled, this session will\n * ignore any incoming sticky events.\n */\n listenForStickyEvents: boolean;\n /**\n * Listen for incoming member state events (legacy). If disabled, this session will\n * ignore any incoming state events.\n */\n listenForMemberStateEvents: boolean;\n}\n\nconst DEFAULT_SESSION_MEMBERSHIPS_FOR_SLOT_OPTS: SessionMembershipsForSlotOpts = {\n listenForStickyEvents: true,\n listenForMemberStateEvents: true,\n};\n\n/**\n * A MatrixRTCSession manages the membership & properties of a MatrixRTC session.\n * This class doesn't deal with media at all, just membership & properties of a session.\n */\nexport class MatrixRTCSession extends TypedEventEmitter<\n MatrixRTCSessionEvent | MembershipManagerEvent,\n MatrixRTCSessionEventHandlerMap & MembershipManagerEventHandlerMap\n> {\n private membershipManager?: IMembershipManager;\n private encryptionManager?: IEncryptionManager;\n private joinConfig?: SessionConfig;\n private logger: Logger;\n\n private pendingNotificationToSend: undefined | RTCNotificationType;\n /**\n * This timeout is responsible to track any expiration. We need to know when we have to start\n * to ignore other call members. There is no callback for this. This timeout will always be configured to\n * emit when the next membership expires.\n */\n private expiryTimeout?: ReturnType<typeof setTimeout>;\n\n public memberships: CallMembership[] = [];\n\n /**\n * Resolves when the session has calculated the initial membership of the session.\n */\n public readonly initialMembershipCalculated: Promise<void>;\n /**\n * Does membership need to be recalculated? This is set to false upon\n * recalculation.\n */\n private membershipNeedsRecalculation = false;\n\n /**\n * The statistics for this session.\n */\n public statistics: Statistics = {\n counters: {\n roomEventEncryptionKeysSent: 0,\n roomEventEncryptionKeysReceived: 0,\n },\n totals: {\n roomEventEncryptionKeysReceivedTotalAge: 0,\n },\n };\n\n public get membershipStatus(): Status | undefined {\n return this.membershipManager?.status;\n }\n public get probablyLeft(): boolean | undefined {\n return this.membershipManager?.probablyLeft;\n }\n public get delayId(): string | undefined {\n return this.membershipManager?.delayId;\n }\n\n /**\n * The callId (sessionId) of the call.\n *\n * It can be undefined since the callId is only known once the first membership joins.\n * The callId is the property that, per definition, groups memberships into one call.\n * @deprecated use `slotId` instead.\n */\n public get callId(): string | undefined {\n return this.slotDescription?.id;\n }\n /**\n * The slotId of the call.\n * `{application}#{appSpecificId}`\n * It can be undefined since the slotId is only known once the first membership joins.\n * The slotId is the property that, per definition, groups memberships into one call.\n */\n public get slotId(): string | undefined {\n return computeSlotId(this.slotDescription);\n }\n\n /**\n * Reads the current slot state event's content for this session.\n *\n * @returns The slot event's content, or `undefined` if no slot event exists for this session.\n */\n public getRtcSlot(): RtcSlotEventContent | undefined {\n return getSlotEventContent(this.roomSubset, this.slotDescription);\n }\n\n /**\n * Whether this session's slot is closed.\n *\n * @returns `true` if the slot is closed, `false` if the slot is open or `undefined`\n * if no slot exists.\n */\n public isSlotClosed(): boolean | undefined {\n return isSlotClosed(this.roomSubset, this.slotDescription);\n }\n\n /**\n * Returns all the call memberships for a room that match the provided `sessionDescription`,\n * oldest first.\n *\n * By default, this will return *both* sticky and member state events.\n */\n public static async sessionMembershipsForSlot(\n room: Pick<Room, \"getLiveTimeline\" | \"roomId\" | \"hasMembershipState\" | \"_unstable_getStickyEvents\">,\n slotDescription: SlotDescription,\n // default both true this implied we combine sticky and state events for the final call state\n // (prefer sticky events in case of a duplicate)\n options: SessionMembershipsForSlotOpts = DEFAULT_SESSION_MEMBERSHIPS_FOR_SLOT_OPTS,\n ): Promise<CallMembership[]> {\n const logger = rootLogger.getChild(\n `[MatrixRTCSession ${room.roomId} ${slotDescription.application}#${slotDescription.id}]`,\n );\n const callMemberEvents = collectMembersEvents(room, slotDescription, options, logger);\n\n const callMemberships = await computeBackendIdentityAndVerifyMemberEvents(\n room,\n callMemberEvents,\n slotDescription,\n logger,\n );\n\n callMemberships.sort((a, b) => a.createdTs() - b.createdTs());\n if (callMemberships.length > 1) {\n logger.debug(\n `Call memberships in room ${room.roomId}, in order: `,\n callMemberships.map((m) => [m.createdTs(), m.userId]),\n );\n }\n\n return callMemberships;\n }\n\n /**\n * Return the MatrixRTC session for the room.\n * This returned session can be used to find out if there are active sessions\n * for the requested room and `slotDescription`.\n */\n public static sessionForSlot(\n client: MatrixClient,\n room: Room,\n slotDescription: SlotDescription,\n opts?: SessionMembershipsForSlotOpts,\n ): MatrixRTCSession {\n return new MatrixRTCSession(client, room, slotDescription, opts);\n }\n\n /**\n * WARN: this can in theory only be a subset of the room with the properties required by\n * this class.\n * Outside of tests this most likely will be a full room, however.\n * @deprecated Relying on a full Room object being available here is an anti-pattern. You should be tracking\n * the room object in your own code and passing it in when needed.\n */\n public get room(): Room {\n return this.roomSubset as Room;\n }\n\n /**\n * This constructs a room session. When using MatrixRTC inside the js-sdk this is expected\n * to be used with the MatrixRTCSessionManager exclusively.\n *\n * In cases where you don't use the js-sdk but build on top of another Matrix stack this class can be used standalone\n * to manage a joined MatrixRTC session.\n *\n * @param client A subset of the {@link MatrixClient} that lets the session interact with the Matrix room.\n * @param roomSubset The room this session is attached to. A subset of a js-sdk Room that the session needs.\n * @param slotDescription The slot description is a virtual address where participants are allowed to meet.\n * This session will only manage memberships that match this slot description.Sessions are distinct if any of\n * those properties are distinct: `roomSubset.roomId`, `slotDescription.application`, `slotDescription.id`.\n * @param calculateMembershipsOpts - Options to configure how memberships are calculated for this session.\n */\n public constructor(\n private readonly client: Pick<\n MatrixClient,\n | \"getUserId\"\n | \"getDeviceId\"\n | \"sendEvent\"\n | \"sendStateEvent\"\n | \"_unstable_sendDelayedStateEvent\"\n | \"_unstable_updateDelayedEvent\"\n | \"_unstable_cancelScheduledDelayedEvent\"\n | \"_unstable_restartScheduledDelayedEvent\"\n | \"_unstable_sendScheduledDelayedEvent\"\n | \"_unstable_sendStickyEvent\"\n | \"_unstable_sendStickyDelayedEvent\"\n | \"cancelPendingEvent\"\n | \"encryptAndSendToDevice\"\n | \"off\"\n | \"on\"\n | \"decryptEventIfNeeded\"\n >,\n private roomSubset: Pick<\n Room,\n | \"getLiveTimeline\"\n | \"roomId\"\n | \"getVersion\"\n | \"hasMembershipState\"\n | \"on\"\n | \"off\"\n | \"_unstable_getStickyEvents\"\n >,\n\n public readonly slotDescription: SlotDescription,\n private readonly calculateMembershipsOpts?: SessionMembershipsForSlotOpts,\n ) {\n super();\n this.logger = rootLogger.getChild(\n `[MatrixRTCSession ${roomSubset.roomId} ${slotDescription.application}#${slotDescription.id}]`,\n );\n\n this.roomSubset.on(RoomStateEvent.Members, this.onRoomMemberUpdate);\n this.roomSubset.on(RoomStateEvent.Events, this.onRoomStateEvent);\n this.roomSubset.on(RoomStickyEventsEvent.Update, this.onStickyEventUpdate);\n\n this.initialMembershipCalculated = this.ensureRecalculateSessionMembers();\n this.setExpiryTimer();\n }\n /*\n * Returns true if we intend to be participating in the MatrixRTC session.\n * This is determined by checking if the relativeExpiry has been set.\n */\n public isJoined(): boolean {\n return this.membershipManager?.isJoined() ?? false;\n }\n\n /**\n * Performs cleanup & removes timers for client shutdown\n */\n public async stop(): Promise<void> {\n await this.membershipManager?.leave(1000);\n if (this.expiryTimeout) {\n clearTimeout(this.expiryTimeout);\n this.expiryTimeout = undefined;\n }\n\n this.roomSubset.off(RoomStateEvent.Members, this.onRoomMemberUpdate);\n this.roomSubset.off(RoomStateEvent.Events, this.onRoomStateEvent);\n this.roomSubset.off(RoomStickyEventsEvent.Update, this.onStickyEventUpdate);\n }\n\n private reEmitter = new TypedReEmitter<\n MatrixRTCSessionEvent | MembershipManagerEvent,\n MatrixRTCSessionEventHandlerMap & MembershipManagerEventHandlerMap\n >(this);\n\n /**\n * Announces this user and device as joined to the MatrixRTC session,\n * and continues to update the membership event to keep it valid until\n * leaveRoomSession() is called\n * This will not subscribe to updates: remember to call subscribe() separately if\n * desired.\n * This method will return immediately and the session will be joined in the background.\n * @param ownMembershipIdentity the identity of the user and device joining the session.\n * This will be put into the content.member.\n * @param fociPreferred the list of preferred foci to use in the joined RTC membership event.\n * If multiSfuFocus is set, this is only needed if this client wants to publish to multiple transports simultaneously.\n * @param multiSfuFocus the active focus to use in the joined RTC membership event. Setting this implies the\n * membership manager will operate in a multi-SFU connection mode. If `undefined`, an `oldest_membership`\n * transport selection will be used instead.\n * @param joinConfig - Additional configuration for the joined session.\n */\n public joinRTCSession(\n ownMembershipIdentity: CallMembershipIdentityParts,\n fociPreferred: Transport[],\n multiSfuFocus?: Transport,\n joinConfig?: JoinSessionConfig,\n ): void {\n if (this.isJoined()) {\n this.logger.info(`Already joined to session in room ${this.roomSubset.roomId}: ignoring join call`);\n return;\n } else {\n // Create MembershipManager and pass the RTCSession logger (with room id info)\n this.membershipManager = joinConfig?.unstableSendStickyEvents\n ? new StickyEventMembershipManager(\n joinConfig,\n this.roomSubset,\n this.client,\n this.slotDescription,\n ownMembershipIdentity.memberId,\n this.logger,\n )\n : new MembershipManager(joinConfig, this.roomSubset, this.client, this.slotDescription, this.logger);\n\n this.reEmitter.reEmit(this.membershipManager, [\n MembershipManagerEvent.ProbablyLeft,\n MembershipManagerEvent.StatusChanged,\n MembershipManagerEvent.DelayIdChanged,\n ]);\n // Create Encryption manager\n const [room, client, statistics] = [this.roomSubset, this.client, this.statistics];\n const transport = new ToDeviceKeyTransport(ownMembershipIdentity, room.roomId, client, statistics);\n this.encryptionManager = new RTCEncryptionManager(\n ownMembershipIdentity,\n () => this.memberships,\n transport,\n (\n keyBin: Uint8Array<ArrayBuffer>,\n encryptionKeyIndex: number,\n membership: CallMembershipIdentityParts,\n rtcBackendIdentity: string,\n ) => {\n this.emit(\n MatrixRTCSessionEvent.EncryptionKeyChanged,\n keyBin,\n encryptionKeyIndex,\n membership,\n rtcBackendIdentity,\n );\n },\n this.logger,\n );\n }\n\n this.joinConfig = joinConfig;\n this.pendingNotificationToSend = this.joinConfig?.notificationType;\n\n // Join!\n this.membershipManager.join(fociPreferred, multiSfuFocus, (e) => {\n this.logger.error(\"MembershipManager encountered an unrecoverable error: \", e);\n this.emit(MatrixRTCSessionEvent.MembershipManagerError, e);\n this.emit(MatrixRTCSessionEvent.JoinStateChanged, this.isJoined());\n });\n this.encryptionManager.join(joinConfig);\n\n this.emit(MatrixRTCSessionEvent.JoinStateChanged, true);\n }\n\n /**\n *\n * @param fociPreferred\n * @param multiSfuFocus\n * @param joinConfig\n * @deprecated use the joinRTCSession method instead\n */\n public joinRoomSession(\n fociPreferred: Transport[],\n multiSfuFocus?: Transport,\n joinConfig?: JoinSessionConfig,\n ): void {\n const [userId, deviceId] = [this.client.getUserId()!, this.client.getDeviceId()!];\n // TODO this wants to become a UUID\n const memberId = `${userId}:${deviceId}`;\n this.joinRTCSession({ userId, deviceId, memberId }, fociPreferred, multiSfuFocus, joinConfig);\n }\n\n /**\n * Announces this user and device as having left the MatrixRTC session\n * and stops scheduled updates.\n * This will not unsubscribe from updates: remember to call unsubscribe() separately if\n * desired.\n * The membership update required to leave the session will retry if it fails.\n * Without network connection the promise will never resolve.\n * A timeout can be provided so that there is a guarantee for the promise to resolve.\n * @returns Whether the membership update was attempted and did not time out.\n */\n public async leaveRoomSession(timeout: number | undefined = undefined): Promise<boolean> {\n if (!this.isJoined()) {\n this.logger.info(`Not joined to session in room ${this.roomSubset.roomId}: ignoring leave call`);\n return false;\n }\n\n this.logger.info(`Leaving call session in room ${this.roomSubset.roomId}`);\n\n this.encryptionManager!.leave();\n\n const leavePromise = this.membershipManager!.leave(timeout);\n this.emit(MatrixRTCSessionEvent.JoinStateChanged, false);\n\n return await leavePromise;\n }\n /**\n * This returns the focus in use by the oldest membership.\n * Do not use since this might be just the focus for the oldest membership. others might use a different focus.\n * @deprecated use `member.getTransport(session.getOldestMembership())` instead for the specific member you want to get the focus for.\n */\n public getFocusInUse(): Transport | undefined {\n const oldestMembership = this.getOldestMembership();\n return oldestMembership?.getTransport(oldestMembership);\n }\n\n public getOldestMembership(): CallMembership | undefined {\n return this.memberships[0];\n }\n\n /**\n * Get the call intent for the current call, based on what members are advertising. If one or more\n * members disagree on the current call intent, or nobody specifies one then `undefined` is returned.\n *\n * If all members that specify a call intent agree, that value is returned.\n * @returns A call intent, or `undefined` if no consensus or not given.\n */\n public getConsensusCallIntent(): RTCCallIntent | undefined {\n const getFirstCallIntent = this.memberships.find((m) => !!m.callIntent)?.callIntent;\n if (!getFirstCallIntent) {\n return undefined;\n }\n if (this.memberships.every((m) => !m.callIntent || m.callIntent === getFirstCallIntent)) {\n return getFirstCallIntent;\n }\n return undefined;\n }\n\n public async updateCallIntent(callIntent: RTCCallIntent): Promise<void> {\n const myMembership = this.membershipManager?.ownMembership;\n if (!myMembership) {\n throw Error(\"Not connected yet\");\n }\n await this.membershipManager?.updateCallIntent(callIntent);\n }\n\n /**\n * Re-emit an EncryptionKeyChanged event for each tracked encryption key. This can be used to export\n * the keys.\n */\n public reemitEncryptionKeys(): void {\n this.encryptionManager?.getEncryptionKeys().forEach((keyRing, key) => {\n keyRing.forEach((keyInfo) => {\n this.emit(\n MatrixRTCSessionEvent.EncryptionKeyChanged,\n keyInfo.key,\n keyInfo.keyIndex,\n keyInfo.membership,\n keyInfo.rtcBackendIdentity,\n );\n });\n });\n }\n\n /**\n * Sets a timer for the soonest membership expiry\n */\n private setExpiryTimer(): void {\n if (this.expiryTimeout) {\n clearTimeout(this.expiryTimeout);\n this.expiryTimeout = undefined;\n }\n\n let soonestExpiry;\n for (const membership of this.memberships) {\n const thisExpiry = membership.getMsUntilExpiry();\n // If getMsUntilExpiry is undefined we have a MSC4143 (MatrixRTC) compliant event - it never expires\n // but will be reliably resent on disconnect.\n if (thisExpiry !== undefined && (soonestExpiry === undefined || thisExpiry < soonestExpiry)) {\n soonestExpiry = thisExpiry;\n }\n }\n\n if (soonestExpiry != undefined) {\n this.expiryTimeout = setTimeout(() => void this.ensureRecalculateSessionMembers(), soonestExpiry);\n }\n }\n\n /**\n * Sends notification events to indiciate the call has started.\n * Note: This does not return a promise, instead scheduling the notification events to be sent.\n * @param parentEventId Event id linking to your RTC call membership event.\n * @param notificationType The type of notification to send\n * @param callIntent The type of call this is (e.g. \"audio\").\n */\n private sendCallNotify(\n parentEventId: string,\n notificationType: RTCNotificationType,\n callIntent?: RTCCallIntent,\n ): void {\n const lifetime = this.joinConfig?.notificationLifetimeMs ?? 90_000;\n const sendNotificationEvent = async (): Promise<{\n response: ISendEventResponse;\n content: IRTCNotificationContent;\n }> => {\n const content: IRTCNotificationContent = {\n \"m.mentions\": { user_ids: [], room: true },\n \"notification_type\": notificationType,\n \"m.relates_to\": {\n event_id: parentEventId,\n rel_type: RelationType.Reference,\n },\n \"sender_ts\": Date.now(),\n \"lifetime\": lifetime,\n };\n if (callIntent) {\n content[\"m.call.intent\"] = callIntent;\n }\n const response = await this.client.sendEvent(this.roomSubset.roomId, EventType.RTCNotification, content);\n return { response, content };\n };\n\n void sendNotificationEvent()\n .then((notification) => {\n // Join event_id and origin event content\n const newResult = { ...notification.response, ...notification.content };\n this.emit(MatrixRTCSessionEvent.DidSendCallNotification, newResult);\n })\n .catch(([errorLegacy, errorNew]) =>\n this.logger.error(\"Failed to send call notification\", errorLegacy, errorNew),\n );\n }\n\n /**\n * Call this when the Matrix room members have changed.\n */\n private readonly onRoomMemberUpdate = (): void => {\n void this.ensureRecalculateSessionMembers();\n };\n\n /**\n * Call this when a room state event has been updated.\n */\n private readonly onRoomStateEvent = (event: MatrixEvent): void => {\n if (event.getType() !== EventType.RTCSlot) return;\n if (event.getStateKey() !== computeSlotId(this.slotDescription)) return;\n void this.ensureRecalculateSessionMembers();\n };\n\n /**\n * Call this when a sticky event update has occured.\n */\n private readonly onStickyEventUpdate: RoomStickyEventsMap[RoomStickyEventsEvent.Update] = (\n added,\n updated,\n removed,\n ): void => {\n if (\n [...added, ...removed, ...updated.flatMap((v) => [v.current, v.previous])].some(\n (e) => e.getType() === EventType.RTCMembership,\n )\n ) {\n void this.ensureRecalculateSessionMembers();\n }\n };\n\n /**\n * Call this when something changed that may impacts the current MatrixRTC members in this session.\n */\n // We allow this name schema since this function should only be used for testing purposes.\n public _onRTCSessionMemberUpdate = async (): Promise<void> => {\n await this.recalculateSessionMembers();\n };\n\n // helper variables to make sure we do not have parallel running recalculations.\n private recalculateSessionMembersPromise: Promise<void> = Promise.resolve();\n\n /**\n * Ensures that membership is recalculated when the state of the session may have changed.\n * Also ensures that only one recalculation is made at a time.\n * @returns A promise resolving when the state has been recalculated.\n */\n private ensureRecalculateSessionMembers(): Promise<void> {\n if (this.membershipNeedsRecalculation) {\n // We have already requested recalcuation, don't attempt a new one.\n return this.recalculateSessionMembersPromise;\n }\n this.membershipNeedsRecalculation = true;\n // Chain the recalculation.\n this.recalculateSessionMembersPromise = this.recalculateSessionMembersPromise.then(\n () => this.recalculateSessionMembers(),\n () => this.recalculateSessionMembers(),\n );\n return this.recalculateSessionMembersPromise;\n }\n\n /**\n * Call this when anything that could impact rtc memberships has changed: Room Members or RTC members.\n *\n * Examines the latest call memberships and handles any encryption key sending or rotation that is needed.\n *\n * This function should be called when the room members or call memberships might have changed.\n */\n private readonly recalculateSessionMembers = async (): Promise<void> => {\n // Clear the flag.\n this.membershipNeedsRecalculation = false;\n const oldMemberships = this.memberships;\n\n this.memberships = await MatrixRTCSession.sessionMembershipsForSlot(\n this.room,\n this.slotDescription,\n this.calculateMembershipsOpts,\n );\n\n const changed =\n oldMemberships.length != this.memberships.length ||\n oldMemberships.some((m, i) => !CallMembership.equal(m, this.memberships[i]));\n\n if (changed) {\n this.logger.info(\n `Memberships for call in room ${this.roomSubset.roomId} have changed: emitting (${this.memberships.length} members)`,\n );\n logDurationSync(this.logger, \"emit MatrixRTCSessionEvent.MembershipsChanged\", () => {\n this.emit(MatrixRTCSessionEvent.MembershipsChanged, oldMemberships, this.memberships);\n });\n\n void this.membershipManager?.onRTCSessionMemberUpdate(this.memberships);\n // The `ownMembership` will be set when calling `onRTCSessionMemberUpdate`.\n const ownMembership = this.membershipManager?.ownMembership;\n if (this.pendingNotificationToSend && ownMembership && oldMemberships.length === 0) {\n // If we're the first member in the call, we're responsible for\n // sending the notification event\n if (ownMembership.eventId && this.joinConfig?.notificationType) {\n this.sendCallNotify(\n ownMembership.eventId,\n this.joinConfig.notificationType,\n ownMembership.callIntent,\n );\n } else {\n this.logger.warn(\"Own membership eventId is undefined, cannot send call notification\");\n }\n }\n // If anyone else joins the session it is no longer our responsibility to send the notification.\n // (If we were the joiner we already did sent the notification in the block above.)\n if (this.memberships.length > 0) this.pendingNotificationToSend = undefined;\n } else {\n this.logger.debug(`No membership changes detected for room ${this.roomSubset.roomId}`);\n }\n // This also needs to be done if `changed` = false\n // A member might have updated their fingerprint (created_ts)\n this.encryptionManager?.onMembershipsUpdate(oldMemberships);\n\n this.setExpiryTimer();\n };\n}\n\n/// Private helpers\nasync function computeBackendIdentityAndVerifyMemberEvents(\n room: Pick<Room, \"hasMembershipState\">,\n callMemberEvents: MatrixEvent[],\n slotDescription: SlotDescription,\n logger: Logger,\n): Promise<CallMembership[]> {\n const callMemberships: CallMembership[] = [];\n\n for (const memberEvent of callMemberEvents) {\n const content = memberEvent.getContent();\n\n // Quick filter to avoid unneeded processing of invalid events or left events.\n if (!quickFilterNonRelevantContents(content, logger)) {\n continue;\n }\n\n try {\n const membership = await CallMembership.parseFromEvent(memberEvent);\n\n if (isValidMembership(membership, room, slotDescription, logger)) {\n callMemberships.push(membership);\n }\n } catch (e) {\n logger.warn(\"Couldn't construct call membership: \", e);\n }\n }\n\n return callMemberships;\n}\n\nfunction quickFilterNonRelevantContents(content: IContent, logger: Logger): boolean {\n // Ignore sticky keys for the count\n const eventKeysCount = Object.keys(content).filter((k) => k !== \"msc4354_sticky_key\").length;\n // Don't even bother about empty events (saves us from costly type/\"key in\" checks in bigger rooms)\n if (eventKeysCount === 0) return false;\n\n // We first decide if it's a MSC4143 event (per device state key)\n if (eventKeysCount > 1 && \"application\" in content) {\n // We have a MSC4143 event membership event with a proper joined content\n return true;\n } else if (eventKeysCount === 1 && \"memberships\" in content) {\n // Events used to have this format in the past, but are now deprecated.\n // Given that state events ~cannot be deleted, there can be some remaining events in the room, just ignore them.\n return false;\n } else {\n // Invalid or left content\n return false;\n }\n}\n\nfunction isValidMembership(\n membership: CallMembership,\n room: Pick<Room, \"hasMembershipState\">,\n slotDescription: SlotDescription,\n logger: Logger,\n): boolean {\n if (membership.slotDescription.id !== slotDescription.id) {\n logger.info(\n `Ignoring membership of user ${membership.userId} for a different slot. Theirs: ${JSON.stringify(membership.slotDescription)}, Expected: ${JSON.stringify(slotDescription)}`,\n );\n return false;\n }\n\n if (membership.isExpired()) {\n logger.info(`Ignoring expired device membership ${membership.userId}/${membership.deviceId}`);\n return false;\n }\n\n if (!room.hasMembershipState(membership.userId ?? \"\", KnownMembership.Join)) {\n logger.info(`Ignoring membership of user ${membership.userId} who is not in the room.`);\n return false;\n }\n\n return true;\n}\n\n/**\n * Reads the slot state event's content for the given slot description.\n *\n * @returns The slot event's content, or `undefined` if no slot event exists for the given description.\n */\nfunction getSlotEventContent(\n room: Pick<Room, \"getLiveTimeline\">,\n slotDescription: SlotDescription,\n): RtcSlotEventContent | undefined {\n const slotId = computeSlotId(slotDescription);\n const slotEvent = room\n .getLiveTimeline()\n .getState(EventTimeline.FORWARDS)\n ?.getStateEvents(EventType.RTCSlot, slotId);\n if (!slotEvent) return undefined;\n\n return slotEvent.getContent<RtcSlotEventContent>();\n}\n\n/**\n * Whether the given slot is closed.\n *\n * @returns `true` if the slot is closed, `false` if the slot is open or `undefined`\n * if no slot exists.\n */\nfunction isSlotClosed(room: Pick<Room, \"getLiveTimeline\">, slotDescription: SlotDescription): boolean | undefined {\n const content = getSlotEventContent(room, slotDescription) as Partial<RtcSlotEventContent> | undefined;\n if (content === undefined) return undefined;\n\n return (\n content.status !== \"open\" ||\n typeof content.application !== \"object\" ||\n content.application?.type !== slotDescription.application\n );\n}\n\n/**\n * Collects the raw member events from room state and sticky store.\n */\nfunction collectMembersEvents(\n room: Pick<Room, \"getLiveTimeline\" | \"roomId\" | \"_unstable_getStickyEvents\">,\n slotDescription: SlotDescription,\n options: SessionMembershipsForSlotOpts,\n logger: Logger,\n): MatrixEvent[] {\n const { listenForStickyEvents, listenForMemberStateEvents } = options;\n let callMemberEvents: MatrixEvent[] = [];\n if (listenForStickyEvents && !isSlotClosed(room, slotDescription)) {\n // prefill with sticky events\n callMemberEvents = [...room._unstable_getStickyEvents()].filter((e) => e.getType() === EventType.RTCMembership);\n }\n if (listenForMemberStateEvents) {\n const roomState = room.getLiveTimeline().getState(EventTimeline.FORWARDS);\n if (!roomState) {\n logger.warn(\"Couldn't get state for room \" + room.roomId + \"using empty membership array\");\n return [];\n }\n const callMemberStateEvents = roomState.getStateEvents(EventType.GroupCallMemberPrefix);\n callMemberEvents = callMemberEvents.concat(\n callMemberStateEvents.filter(\n (callMemberStateEvent) =>\n !callMemberEvents.some(\n // only care about state events which have keys which we have not yet seen in the sticky events.\n // TODO: I believe this can discard a joined state event if there is a matching left sticky event.\n (stickyEvent) =>\n stickyEvent.getContent().msc4354_sticky_key === callMemberStateEvent.getStateKey(),\n ),\n ),\n );\n }\n return callMemberEvents;\n}\n"],"mappings":";;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA,SAAsB,MAAM,IAAI,UAAU,QAAQ,cAAc;AAChE,SAAS,iBAAiB,QAAQ,kCAAkC;AACpE,SAAS,aAAa,QAAQ,6BAA6B;AAG3D,SAAS,SAAS,EAAE,YAAY,QAAQ,oBAAoB;AAC5D,SAAS,eAAe,QAAQ,yBAAyB;AAEzD,SAAS,cAAc,QAAQ,qBAAqB;AACpD,SAAS,cAAc,QAAQ,yBAAyB;AACxD,SAAS,iBAAiB,EAAE,4BAA4B,QAAQ,wBAAwB;AAExF,SAAS,eAAe,QAAQ,aAAa;AAW7C,SACI,sBAAsB,QAGnB,yBAAyB;AAChC,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eAAe,CAAC,EAAE;IAC/D;IACA,gBAAgB,GAAG,CAAC,GAAG,IAAI,CAAC,yBAAyB,CAAC,CAAC,CAAC,CAAC,MAAM,CAAE,CAAC,IAAK,CAAC,CAAC,OAAO,CAAC,CAAC,KAAK,SAAS,CAAC,aAAa,CAAC;EACnH;EACA,IAAI,0BAA0B,EAAE;IAC5B,MAAM,SAAS,GAAG,IAAI,CAAC,eAAe,CAAC,CAAC,CAAC,QAAQ,CAAC,aAAa,CAAC,QAAQ,CAAC;IACzE,IAAI,CAAC,SAAS,EAAE;MACZ,MAAM,CAAC,IAAI,CAAC,8BAA8B,GAAG,IAAI,CAAC,MAAM,GAAG,8BAA8B,CAAC;MAC1F,OAAO,EAAE;IACb;IACA,MAAM,qBAAqB,GAAG,SAAS,CAAC,cAAc,CAAC,SAAS,CAAC,qBAAqB,CAAC;IACvF,gBAAgB,GAAG,gBAAgB,CAAC,MAAM,CACtC,qBAAqB,CAAC,MAAM,CACvB,oBAAoB,IACjB,CAAC,gBAAgB,CAAC,IAAI;IAClB;IACA;IACC,WAAW,IACR,WAAW,CAAC,UAAU,CAAC,CAAC,CAAC,kBAAkB,KAAK,oBAAoB,CAAC,WAAW,CAAC,CACzF,CACR,CACJ,CAAC;EACL;EACA,OAAO,gBAAgB;AAC3B","ignoreList":[]}
|
package/lib/oauth/authorize.d.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { type OAuth2ErrorResponse } from "./error.ts";
|
|
1
2
|
import { type ValidatedAuthMetadata } from "./discover.ts";
|
|
2
3
|
/**
|
|
3
4
|
* The expected response type from the token endpoint during authorization code flow
|
|
@@ -63,10 +64,7 @@ export declare function isValidDeviceAccessTokenResponse(response: unknown): res
|
|
|
63
64
|
/**
|
|
64
65
|
* Error from the OAuth2 token endpoint when exchanging a token for grant_type device_code.
|
|
65
66
|
*/
|
|
66
|
-
export interface DeviceAccessTokenError {
|
|
67
|
-
error: string;
|
|
68
|
-
error_description?: string;
|
|
69
|
-
error_uri?: string;
|
|
67
|
+
export interface DeviceAccessTokenError extends OAuth2ErrorResponse {
|
|
70
68
|
session_state?: string;
|
|
71
69
|
}
|
|
72
70
|
/**
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"authorize.d.ts","sourceRoot":"","sources":["../../src/oauth/authorize.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"authorize.d.ts","sourceRoot":"","sources":["../../src/oauth/authorize.ts"],"names":[],"mappings":"AAiBA,OAAO,EAAe,KAAK,mBAAmB,EAAE,MAAM,YAAY,CAAC;AACnE,OAAO,EAAE,KAAK,qBAAqB,EAAE,MAAM,eAAe,CAAC;AAY3D;;;;;GAKG;AACH,MAAM,MAAM,mBAAmB,GAAG,IAAI,CAAC,kBAAkB,EAAE,YAAY,CAAC,GAAG;IACvE,UAAU,EAAE,QAAQ,CAAC;CACxB,CAAC;AAEF;;;;;;;GAOG;AACH,UAAU,kBAAkB;IACxB,UAAU,EAAE,QAAQ,GAAG,QAAQ,CAAC;IAChC,YAAY,EAAE,MAAM,CAAC;IACrB,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB,KAAK,CAAC,EAAE,MAAM,CAAC;CAClB;AAED;;;;GAIG;AACH,wBAAgB,2BAA2B,CAAC,QAAQ,EAAE,OAAO,GAAG,OAAO,CAAC,QAAQ,IAAI,kBAAkB,CAarG;AAED;;;GAGG;AACH,eAAO,MAAM,aAAa,cAAe,MAAM,KAAG,MAGjD,CAAC;AAEF;;;;;;;;GAQG;AACH,eAAO,MAAM,qCAAqC,aAAc,kBAAkB,KAAG,mBAGnF,CAAC;AAEH;;GAEG;AACH,MAAM,WAAW,yBAAyB;IACtC,YAAY,EAAE,MAAM,CAAC;IACrB,UAAU,EAAE,MAAM,CAAC;IACnB,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,UAAU,CAAC,EAAE,MAAM,CAAC;CACvB;AAED;;;;GAIG;AACH,wBAAgB,gCAAgC,CAAC,QAAQ,EAAE,OAAO,GAAG,QAAQ,IAAI,yBAAyB,CASzG;AAED;;GAEG;AACH,MAAM,WAAW,sBAAuB,SAAQ,mBAAmB;IAC/D,aAAa,CAAC,EAAE,MAAM,CAAC;CAC1B;AAED;;;GAGG;AACH,MAAM,WAAW,2BAA2B;IACxC,oCAAoC;IACpC,WAAW,EAAE,MAAM,CAAC;IACpB,sCAAsC;IACtC,SAAS,EAAE,MAAM,CAAC;IAClB;;;OAGG;IACH,gBAAgB,EAAE,MAAM,CAAC;IACzB;;OAEG;IACH,yBAAyB,CAAC,EAAE,MAAM,CAAC;IACnC,oEAAoE;IACpE,UAAU,EAAE,MAAM,CAAC;IACnB;;;OAGG;IACH,QAAQ,CAAC,EAAE,MAAM,CAAC;CACrB;AAED;;;;GAIG;AACH,wBAAgB,mCAAmC,CAC/C,QAAQ,EAAE,OAAO,GAClB,OAAO,CAAC,QAAQ,IAAI,2BAA2B,CAYjD;AAED;;;;;;;;GAQG;AACH,eAAO,MAAM,wBAAwB,mCAIlC;IACC,QAAQ,EAAE,MAAM,CAAC;IACjB,KAAK,EAAE,MAAM,CAAC;IACd,QAAQ,EAAE,qBAAqB,CAAC;CACnC,KAAG,OAAO,CAAC,2BAA2B,CAmBtC,CAAC;AAEF;;;;;;;;GAQG;AACH,eAAO,MAAM,0BAA0B,qCAIpC;IACC,OAAO,EAAE,2BAA2B,CAAC;IACrC,QAAQ,EAAE,qBAAqB,CAAC;IAChC,QAAQ,EAAE,MAAM,CAAC;CACpB,KAAG,OAAO,CAAC,yBAAyB,GAAG,sBAAsB,CAkC7D,CAAC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"authorize.js","names":[],"sources":["../../src/oauth/authorize.ts"],"sourcesContent":["/*\nCopyright 2023 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { secureRandomString } from \"../randomstring.ts\";\nimport { OAuth2Error } from \"./error.ts\";\nimport { type ValidatedAuthMetadata } from \"./discover.ts\";\nimport {\n hasOptionalNumberProperty,\n hasOptionalStringProperty,\n hasRequiredNumberProperty,\n hasRequiredStringProperty,\n isRecord,\n} from \"../@types/type-guards.ts\";\nimport { Method } from \"../http-api/index.ts\";\nimport { OAuthGrantType } from \"./register.ts\";\nimport { sleep } from \"../utils.ts\";\n\n/**\n * The expected response type from the token endpoint during authorization code flow\n * Normalized to always use capitalized 'Bearer' for token_type\n *\n * See https://datatracker.ietf.org/doc/html/rfc6749#section-4.1.4\n */\nexport type BearerTokenResponse = Omit<ValidTokenResponse, \"token_type\"> & {\n token_type: \"Bearer\";\n};\n\n/**\n * Metadata from OAuth 2.0 token_endpoint as per\n * https://datatracker.ietf.org/doc/html/rfc6749#section-5.1\n * With validated properties required in type\n *\n * This response is expected for the authorization code grant and refresh token grant,\n * as defined in the Matrix spec.\n */\ninterface ValidTokenResponse {\n token_type: \"Bearer\" | \"bearer\";\n access_token: string;\n expires_in?: number;\n refresh_token?: string;\n scope?: string;\n}\n\n/**\n * Validate the given response matches the format expected for a {@link ValidTokenResponse}\n * @param response - the response to validate\n * @throws if the response does not match the expected format\n */\nexport function validateBearerTokenResponse(response: unknown): asserts response is ValidTokenResponse {\n if (\n !isRecord(response) ||\n !hasRequiredStringProperty(response, \"token_type\") ||\n // token_type is case-insensitive, some OPs return `token_type: \"bearer\"`\n response[\"token_type\"].toLowerCase() !== \"bearer\" ||\n !hasRequiredStringProperty(response, \"access_token\") ||\n !hasOptionalNumberProperty(response, \"expires_in\") ||\n !hasOptionalStringProperty(response, \"refresh_token\") ||\n !hasOptionalStringProperty(response, \"scope\")\n ) {\n throw new Error(OAuth2Error.InvalidBearerTokenResponse);\n }\n}\n\n/**\n * Generate the scope used in authorization request with OAuth2 IdP\n * @returns scope\n */\nexport const generateScope = (deviceId?: string): string => {\n const safeDeviceId = deviceId ?? secureRandomString(10);\n return `urn:matrix:client:api:* urn:matrix:client:device:${safeDeviceId}`;\n};\n\n/**\n * Normalize token_type to use capital case to make consuming the token response easier\n * token_type is case insensitive, and it is spec-compliant for OPs to return token_type: \"bearer\"\n * Later, when used in auth headers it is case sensitive and must be Bearer\n * See: https://datatracker.ietf.org/doc/html/rfc6749#section-4.1.4\n *\n * @param response - validated token response\n * @returns response with token_type set to 'Bearer'\n */\nexport const normalizeBearerTokenResponseTokenType = (response: ValidTokenResponse): BearerTokenResponse => ({\n ...response,\n token_type: \"Bearer\",\n});\n\n/**\n * Response from the OAuth2 token endpoint when exchanging a token for grant_type device_code.\n */\nexport interface DeviceAccessTokenResponse {\n access_token: string;\n token_type: string;\n refresh_token?: string;\n scope?: string;\n expires_in?: number;\n}\n\n/**\n * Validate the given response matches the format expected for a {@link DeviceAccessTokenResponse}\n * @param response - the response to validate\n * @throws if the response does not match the expected format\n */\nexport function isValidDeviceAccessTokenResponse(response: unknown): response is DeviceAccessTokenResponse {\n return (\n isRecord(response) &&\n hasRequiredStringProperty(response, \"access_token\") &&\n hasRequiredStringProperty(response, \"token_type\") &&\n hasOptionalStringProperty(response, \"refresh_token\") &&\n hasOptionalStringProperty(response, \"scope\") &&\n hasOptionalNumberProperty(response, \"expires_in\")\n );\n}\n\n/**\n * Error from the OAuth2 token endpoint when exchanging a token for grant_type device_code.\n */\nexport interface DeviceAccessTokenError {\n error: string;\n error_description?: string;\n error_uri?: string;\n session_state?: string;\n}\n\n/**\n * Response from the OAuth2 device authorization endpoint.\n * As specified in https://datatracker.ietf.org/doc/html/rfc8628#section-3.2\n */\nexport interface DeviceAuthorizationResponse {\n /** The device verification code. */\n device_code: string;\n /** The end-user verification code. */\n user_code: string;\n /**\n * The end-user verification URI on the authorization server.\n * The URI should be short and easy to remember as end users will be asked to manually type it into their user agent.\n */\n verification_uri: string;\n /**\n * The URI which doesn’t require the user to manually type the user_code, designed for non-textual transmission.\n */\n verification_uri_complete?: string;\n /** The lifetime in seconds of the \"device_code\" and \"user_code\". */\n expires_in: number;\n /**\n * The minimum amount of time in seconds that the client SHOULD wait between polling requests to the token endpoint.\n * If no value is provided, clients MUST use 5 as the default.\n */\n interval?: number;\n}\n\n/**\n * Validate the given response matches the format expected for a {@link DeviceAuthorizationResponse}\n * @param response - the response to validate\n * @throws if the response does not match the expected format\n */\nexport function validateDeviceAuthorizationResponse(\n response: unknown,\n): asserts response is DeviceAuthorizationResponse {\n if (\n !isRecord(response) ||\n !hasRequiredStringProperty(response, \"device_code\") ||\n !hasRequiredStringProperty(response, \"user_code\") ||\n !hasRequiredStringProperty(response, \"verification_uri\") ||\n !hasRequiredNumberProperty(response, \"expires_in\") ||\n !hasOptionalStringProperty(response, \"verification_uri_complete\") ||\n !hasOptionalNumberProperty(response, \"interval\")\n ) {\n throw new Error(OAuth2Error.InvalidDeviceAuthorizationResponse);\n }\n}\n\n/**\n * Begin OAuth2 device authorization flow.\n * @param options - The device authorization parameters.\n * @param options.clientId - the client ID returned from client registration.\n * @param options.scope - the scope to request for authorization.\n * @param options.metadata - the validated OAuth2 metadata for the Identity Provider.\n * @returns a promise that resolves to a device access token response,\n * or an error response if the user denies authorization or the device code expires.\n */\nexport const startDeviceAuthorization = async ({\n clientId,\n scope,\n metadata,\n}: {\n clientId: string;\n scope: string;\n metadata: ValidatedAuthMetadata;\n}): Promise<DeviceAuthorizationResponse> => {\n const body = new URLSearchParams({ client_id: clientId, scope: scope }).toString();\n\n const url = metadata.device_authorization_endpoint;\n if (!url) {\n throw new Error(\"No device_authorization_endpoint given\");\n }\n\n const response = await fetch(url, {\n method: Method.Post,\n headers: {\n \"Content-Type\": \"application/x-www-form-urlencoded\",\n },\n body,\n });\n\n const data = await response.json();\n validateDeviceAuthorizationResponse(data);\n return data;\n};\n\n/**\n * Polls the OAuth2 token endpoint until we get a device access token response, or encounter an unrecoverable error.\n * @param options - The device authorization parameters.\n * @param options.session - The session returned from a previous call to {@link startDeviceAuthorization}.\n * @param options.metadata - The validated OAuth2 metadata for the Identity Provider.\n * @param options.clientId - The client ID returned from client registration.\n * @returns a promise that resolves to a device access token response,\n * or an error response if the user denies authorization or the device code expires.\n */\nexport const waitForDeviceAuthorization = async ({\n session,\n metadata,\n clientId,\n}: {\n session: DeviceAuthorizationResponse;\n metadata: ValidatedAuthMetadata;\n clientId: string;\n}): Promise<DeviceAccessTokenResponse | DeviceAccessTokenError> => {\n let interval = (session.interval ?? 5) * 1000; // poll interval\n const expiration = Date.now() + session.expires_in * 1000;\n do {\n const body = new URLSearchParams({\n device_code: session.device_code,\n grant_type: OAuthGrantType.DeviceAuthorization,\n client_id: clientId,\n }).toString();\n const response = await fetch(metadata.token_endpoint, {\n method: Method.Post,\n headers: { \"Content-Type\": \"application/x-www-form-urlencoded\" },\n body,\n });\n\n const data = await response.json();\n\n if (response.ok && isValidDeviceAccessTokenResponse(data)) {\n return data;\n }\n const errorResponse = data as DeviceAccessTokenError;\n switch (errorResponse.error) {\n case \"authorization_pending\":\n break;\n case \"slow_down\":\n interval += 5000;\n break;\n case \"access_denied\":\n case \"expired_token\":\n return errorResponse;\n }\n await sleep(interval);\n } while (Date.now() < expiration);\n return { error: \"expired\" };\n};\n"],"mappings":";AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA,SAAS,kBAAkB,QAAQ,oBAAoB;AACvD,SAAS,WAAW,QAAQ,YAAY;AAExC,SACI,yBAAyB,EACzB,yBAAyB,EACzB,yBAAyB,EACzB,yBAAyB,EACzB,QAAQ,QACL,0BAA0B;AACjC,SAAS,MAAM,QAAQ,sBAAsB;AAC7C,SAAS,cAAc,QAAQ,eAAe;AA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oreList":[]}
|
|
1
|
+
{"version":3,"file":"authorize.js","names":[],"sources":["../../src/oauth/authorize.ts"],"sourcesContent":["/*\nCopyright 2023 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { secureRandomString } from \"../randomstring.ts\";\nimport { OAuth2Error, type OAuth2ErrorResponse } from \"./error.ts\";\nimport { type ValidatedAuthMetadata } from \"./discover.ts\";\nimport {\n hasOptionalNumberProperty,\n hasOptionalStringProperty,\n hasRequiredNumberProperty,\n hasRequiredStringProperty,\n isRecord,\n} from \"../@types/type-guards.ts\";\nimport { Method } from \"../http-api/index.ts\";\nimport { OAuthGrantType } from \"./register.ts\";\nimport { sleep } from \"../utils.ts\";\n\n/**\n * The expected response type from the token endpoint during authorization code flow\n * Normalized to always use capitalized 'Bearer' for token_type\n *\n * See https://datatracker.ietf.org/doc/html/rfc6749#section-4.1.4\n */\nexport type BearerTokenResponse = Omit<ValidTokenResponse, \"token_type\"> & {\n token_type: \"Bearer\";\n};\n\n/**\n * Metadata from OAuth 2.0 token_endpoint as per\n * https://datatracker.ietf.org/doc/html/rfc6749#section-5.1\n * With validated properties required in type\n *\n * This response is expected for the authorization code grant and refresh token grant,\n * as defined in the Matrix spec.\n */\ninterface ValidTokenResponse {\n token_type: \"Bearer\" | \"bearer\";\n access_token: string;\n expires_in?: number;\n refresh_token?: string;\n scope?: string;\n}\n\n/**\n * Validate the given response matches the format expected for a {@link ValidTokenResponse}\n * @param response - the response to validate\n * @throws if the response does not match the expected format\n */\nexport function validateBearerTokenResponse(response: unknown): asserts response is ValidTokenResponse {\n if (\n !isRecord(response) ||\n !hasRequiredStringProperty(response, \"token_type\") ||\n // token_type is case-insensitive, some OPs return `token_type: \"bearer\"`\n response[\"token_type\"].toLowerCase() !== \"bearer\" ||\n !hasRequiredStringProperty(response, \"access_token\") ||\n !hasOptionalNumberProperty(response, \"expires_in\") ||\n !hasOptionalStringProperty(response, \"refresh_token\") ||\n !hasOptionalStringProperty(response, \"scope\")\n ) {\n throw new Error(OAuth2Error.InvalidBearerTokenResponse);\n }\n}\n\n/**\n * Generate the scope used in authorization request with OAuth2 IdP\n * @returns scope\n */\nexport const generateScope = (deviceId?: string): string => {\n const safeDeviceId = deviceId ?? secureRandomString(10);\n return `urn:matrix:client:api:* urn:matrix:client:device:${safeDeviceId}`;\n};\n\n/**\n * Normalize token_type to use capital case to make consuming the token response easier\n * token_type is case insensitive, and it is spec-compliant for OPs to return token_type: \"bearer\"\n * Later, when used in auth headers it is case sensitive and must be Bearer\n * See: https://datatracker.ietf.org/doc/html/rfc6749#section-4.1.4\n *\n * @param response - validated token response\n * @returns response with token_type set to 'Bearer'\n */\nexport const normalizeBearerTokenResponseTokenType = (response: ValidTokenResponse): BearerTokenResponse => ({\n ...response,\n token_type: \"Bearer\",\n});\n\n/**\n * Response from the OAuth2 token endpoint when exchanging a token for grant_type device_code.\n */\nexport interface DeviceAccessTokenResponse {\n access_token: string;\n token_type: string;\n refresh_token?: string;\n scope?: string;\n expires_in?: number;\n}\n\n/**\n * Validate the given response matches the format expected for a {@link DeviceAccessTokenResponse}\n * @param response - the response to validate\n * @throws if the response does not match the expected format\n */\nexport function isValidDeviceAccessTokenResponse(response: unknown): response is DeviceAccessTokenResponse {\n return (\n isRecord(response) &&\n hasRequiredStringProperty(response, \"access_token\") &&\n hasRequiredStringProperty(response, \"token_type\") &&\n hasOptionalStringProperty(response, \"refresh_token\") &&\n hasOptionalStringProperty(response, \"scope\") &&\n hasOptionalNumberProperty(response, \"expires_in\")\n );\n}\n\n/**\n * Error from the OAuth2 token endpoint when exchanging a token for grant_type device_code.\n */\nexport interface DeviceAccessTokenError extends OAuth2ErrorResponse {\n session_state?: string;\n}\n\n/**\n * Response from the OAuth2 device authorization endpoint.\n * As specified in https://datatracker.ietf.org/doc/html/rfc8628#section-3.2\n */\nexport interface DeviceAuthorizationResponse {\n /** The device verification code. */\n device_code: string;\n /** The end-user verification code. */\n user_code: string;\n /**\n * The end-user verification URI on the authorization server.\n * The URI should be short and easy to remember as end users will be asked to manually type it into their user agent.\n */\n verification_uri: string;\n /**\n * The URI which doesn’t require the user to manually type the user_code, designed for non-textual transmission.\n */\n verification_uri_complete?: string;\n /** The lifetime in seconds of the \"device_code\" and \"user_code\". */\n expires_in: number;\n /**\n * The minimum amount of time in seconds that the client SHOULD wait between polling requests to the token endpoint.\n * If no value is provided, clients MUST use 5 as the default.\n */\n interval?: number;\n}\n\n/**\n * Validate the given response matches the format expected for a {@link DeviceAuthorizationResponse}\n * @param response - the response to validate\n * @throws if the response does not match the expected format\n */\nexport function validateDeviceAuthorizationResponse(\n response: unknown,\n): asserts response is DeviceAuthorizationResponse {\n if (\n !isRecord(response) ||\n !hasRequiredStringProperty(response, \"device_code\") ||\n !hasRequiredStringProperty(response, \"user_code\") ||\n !hasRequiredStringProperty(response, \"verification_uri\") ||\n !hasRequiredNumberProperty(response, \"expires_in\") ||\n !hasOptionalStringProperty(response, \"verification_uri_complete\") ||\n !hasOptionalNumberProperty(response, \"interval\")\n ) {\n throw new Error(OAuth2Error.InvalidDeviceAuthorizationResponse);\n }\n}\n\n/**\n * Begin OAuth2 device authorization flow.\n * @param options - The device authorization parameters.\n * @param options.clientId - the client ID returned from client registration.\n * @param options.scope - the scope to request for authorization.\n * @param options.metadata - the validated OAuth2 metadata for the Identity Provider.\n * @returns a promise that resolves to a device access token response,\n * or an error response if the user denies authorization or the device code expires.\n */\nexport const startDeviceAuthorization = async ({\n clientId,\n scope,\n metadata,\n}: {\n clientId: string;\n scope: string;\n metadata: ValidatedAuthMetadata;\n}): Promise<DeviceAuthorizationResponse> => {\n const body = new URLSearchParams({ client_id: clientId, scope: scope }).toString();\n\n const url = metadata.device_authorization_endpoint;\n if (!url) {\n throw new Error(\"No device_authorization_endpoint given\");\n }\n\n const response = await fetch(url, {\n method: Method.Post,\n headers: {\n \"Content-Type\": \"application/x-www-form-urlencoded\",\n },\n body,\n });\n\n const data = await response.json();\n validateDeviceAuthorizationResponse(data);\n return data;\n};\n\n/**\n * Polls the OAuth2 token endpoint until we get a device access token response, or encounter an unrecoverable error.\n * @param options - The device authorization parameters.\n * @param options.session - The session returned from a previous call to {@link startDeviceAuthorization}.\n * @param options.metadata - The validated OAuth2 metadata for the Identity Provider.\n * @param options.clientId - The client ID returned from client registration.\n * @returns a promise that resolves to a device access token response,\n * or an error response if the user denies authorization or the device code expires.\n */\nexport const waitForDeviceAuthorization = async ({\n session,\n metadata,\n clientId,\n}: {\n session: DeviceAuthorizationResponse;\n metadata: ValidatedAuthMetadata;\n clientId: string;\n}): Promise<DeviceAccessTokenResponse | DeviceAccessTokenError> => {\n let interval = (session.interval ?? 5) * 1000; // poll interval\n const expiration = Date.now() + session.expires_in * 1000;\n do {\n const body = new URLSearchParams({\n device_code: session.device_code,\n grant_type: OAuthGrantType.DeviceAuthorization,\n client_id: clientId,\n }).toString();\n const response = await fetch(metadata.token_endpoint, {\n method: Method.Post,\n headers: { \"Content-Type\": \"application/x-www-form-urlencoded\" },\n body,\n });\n\n const data = await response.json();\n\n if (response.ok && isValidDeviceAccessTokenResponse(data)) {\n return data;\n }\n const errorResponse = data as DeviceAccessTokenError;\n switch (errorResponse.error) {\n case \"authorization_pending\":\n break;\n case \"slow_down\":\n interval += 5000;\n break;\n case \"access_denied\":\n case \"expired_token\":\n return errorResponse;\n }\n await sleep(interval);\n } while (Date.now() < expiration);\n return { error: \"expired\" };\n};\n"],"mappings":";AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA,SAAS,kBAAkB,QAAQ,oBAAoB;AACvD,SAAS,WA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