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.
Files changed (43) hide show
  1. package/CHANGELOG.md +15 -0
  2. package/lib/client.d.ts +1 -2
  3. package/lib/client.d.ts.map +1 -1
  4. package/lib/client.js +16 -8
  5. package/lib/client.js.map +1 -1
  6. package/lib/http-api/errors.d.ts +8 -0
  7. package/lib/http-api/errors.d.ts.map +1 -1
  8. package/lib/http-api/errors.js +12 -0
  9. package/lib/http-api/errors.js.map +1 -1
  10. package/lib/matrixrtc/MatrixRTCSession.d.ts +5 -0
  11. package/lib/matrixrtc/MatrixRTCSession.d.ts.map +1 -1
  12. package/lib/matrixrtc/MatrixRTCSession.js +2 -1
  13. package/lib/matrixrtc/MatrixRTCSession.js.map +1 -1
  14. package/lib/oauth/authorize.d.ts +2 -4
  15. package/lib/oauth/authorize.d.ts.map +1 -1
  16. package/lib/oauth/authorize.js.map +1 -1
  17. package/lib/oauth/error.d.ts +44 -0
  18. package/lib/oauth/error.d.ts.map +1 -1
  19. package/lib/oauth/error.js +53 -0
  20. package/lib/oauth/error.js.map +1 -1
  21. package/lib/oauth/index.d.ts.map +1 -1
  22. package/lib/oauth/index.js +19 -2
  23. package/lib/oauth/index.js.map +1 -1
  24. package/lib/oauth/tokenRefresher.d.ts.map +1 -1
  25. package/lib/oauth/tokenRefresher.js +4 -2
  26. package/lib/oauth/tokenRefresher.js.map +1 -1
  27. package/lib/secret-storage.d.ts +1 -1
  28. package/lib/secret-storage.d.ts.map +1 -1
  29. package/lib/secret-storage.js +9 -32
  30. package/lib/secret-storage.js.map +1 -1
  31. package/lib/sliding-sync-sdk.d.ts.map +1 -1
  32. package/lib/sliding-sync-sdk.js +54 -1
  33. package/lib/sliding-sync-sdk.js.map +1 -1
  34. package/package.json +2 -2
  35. package/src/client.ts +19 -11
  36. package/src/http-api/errors.ts +16 -0
  37. package/src/matrixrtc/MatrixRTCSession.ts +8 -1
  38. package/src/oauth/authorize.ts +2 -5
  39. package/src/oauth/error.ts +69 -0
  40. package/src/oauth/index.ts +19 -2
  41. package/src/oauth/tokenRefresher.ts +9 -2
  42. package/src/secret-storage.ts +8 -31
  43. package/src/sliding-sync-sdk.ts +74 -0
@@ -1,3 +1,4 @@
1
+ import { HTTPError } from "../http-api/errors.ts";
1
2
  /**
2
3
  * Errors expected to be encountered during OAuth2 discovery, client registration, and authentication.
3
4
  * Not intended to be displayed directly to the user.
@@ -16,4 +17,47 @@ export declare enum OAuth2Error {
16
17
  RevokeTokenFailed = "Failed to revoke token",
17
18
  DeviceAuthorizationGrantFailed = "Failed to perform device authorization grant"
18
19
  }
20
+ /**
21
+ * An error response from an OAuth 2.0 endpoint,
22
+ * as specified in https://datatracker.ietf.org/doc/html/rfc6749#section-5.2
23
+ */
24
+ export interface OAuth2ErrorResponse {
25
+ /** A single ASCII error code, e.g. `invalid_grant`. */
26
+ error: string;
27
+ /** Human-readable ASCII text providing additional information about the error. */
28
+ error_description?: string;
29
+ /** A URI identifying a human-readable web page with information about the error. */
30
+ error_uri?: string;
31
+ }
32
+ /**
33
+ * Check whether the given (JSON-parsed) response body is an OAuth 2.0 error response
34
+ * as specified in https://datatracker.ietf.org/doc/html/rfc6749#section-5.2
35
+ * @param response - the parsed response body to check
36
+ * @returns whether the response is a valid {@link OAuth2ErrorResponse}
37
+ */
38
+ export declare function isOAuth2ErrorResponse(response: unknown): response is OAuth2ErrorResponse;
39
+ /**
40
+ * An error thrown when a request to an OAuth 2.0 endpoint fails with a body matching the error
41
+ * response format specified in [RFC 6749 section 5.2](https://datatracker.ietf.org/doc/html/rfc6749#section-5.2).
42
+ */
43
+ export declare class OAuth2HTTPError extends HTTPError implements OAuth2ErrorResponse {
44
+ /**
45
+ * RFC 6749 section 5.2 error code, e.g. `invalid_grant`
46
+ *
47
+ * IANA matains a registry of valid values at
48
+ * https://www.iana.org/assignments/oauth-parameters/oauth-parameters.xhtml#extensions-error
49
+ */
50
+ error: string;
51
+ /**
52
+ * RFC 6749 section 5.2 human-readable ASCII text providing additional information about the error.
53
+ * This field is optional and may be omitted by the endpoint.
54
+ */
55
+ error_description?: string;
56
+ /**
57
+ * RFC 6749 section 5.2 URI identifying a human-readable web page with information about the error.
58
+ * This field is optional and may be omitted by the endpoint.
59
+ */
60
+ error_uri?: string;
61
+ constructor(msg: string, httpStatus: number | undefined, httpHeaders: Headers | undefined, { error, error_description, error_uri }: OAuth2ErrorResponse);
62
+ }
19
63
  //# sourceMappingURL=error.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"error.d.ts","sourceRoot":"","sources":["../../src/oauth/error.ts"],"names":[],"mappings":"AAgBA;;;GAGG;AACH,oBAAY,WAAW;IACnB,OAAO,+CAA+C;IACtD,SAAS,6DAA6D;IACtE,+BAA+B,uCAAuC;IACtE,yBAAyB,gCAAgC;IACzD,0BAA0B,0CAA0C;IACpE,kBAAkB,sCAAsC;IACxD,0BAA0B,kCAAkC;IAC5D,kCAAkC,0CAA0C;IAC5E,2BAA2B,iEAAiE;IAC5F,kBAAkB,4BAA4B;IAC9C,iBAAiB,2BAA2B;IAC5C,8BAA8B,iDAAiD;CAClF"}
1
+ {"version":3,"file":"error.d.ts","sourceRoot":"","sources":["../../src/oauth/error.ts"],"names":[],"mappings":"AAiBA,OAAO,EAAE,SAAS,EAAE,MAAM,uBAAuB,CAAC;AAElD;;;GAGG;AACH,oBAAY,WAAW;IACnB,OAAO,+CAA+C;IACtD,SAAS,6DAA6D;IACtE,+BAA+B,uCAAuC;IACtE,yBAAyB,gCAAgC;IACzD,0BAA0B,0CAA0C;IACpE,kBAAkB,sCAAsC;IACxD,0BAA0B,kCAAkC;IAC5D,kCAAkC,0CAA0C;IAC5E,2BAA2B,iEAAiE;IAC5F,kBAAkB,4BAA4B;IAC9C,iBAAiB,2BAA2B;IAC5C,8BAA8B,iDAAiD;CAClF;AAED;;;GAGG;AACH,MAAM,WAAW,mBAAmB;IAChC,uDAAuD;IACvD,KAAK,EAAE,MAAM,CAAC;IACd,kFAAkF;IAClF,iBAAiB,CAAC,EAAE,MAAM,CAAC;IAC3B,oFAAoF;IACpF,SAAS,CAAC,EAAE,MAAM,CAAC;CACtB;AAED;;;;;GAKG;AACH,wBAAgB,qBAAqB,CAAC,QAAQ,EAAE,OAAO,GAAG,QAAQ,IAAI,mBAAmB,CAOxF;AAED;;;GAGG;AACH,qBAAa,eAAgB,SAAQ,SAAU,YAAW,mBAAmB;IACzE;;;;;OAKG;IACI,KAAK,EAAE,MAAM,CAAC;IAErB;;;OAGG;IACI,iBAAiB,CAAC,EAAE,MAAM,CAAC;IAElC;;;OAGG;IACI,SAAS,CAAC,EAAE,MAAM,CAAC;IAE1B,YACI,GAAG,EAAE,MAAM,EACX,UAAU,EAAE,MAAM,GAAG,SAAS,EAC9B,WAAW,EAAE,OAAO,GAAG,SAAS,EAChC,EAAE,KAAK,EAAE,iBAAiB,EAAE,SAAS,EAAE,EAAE,mBAAmB,EAM/D;CACJ"}
@@ -1,3 +1,4 @@
1
+ import _defineProperty from "@babel/runtime/helpers/defineProperty";
1
2
  /*
2
3
  Copyright 2023 The Matrix.org Foundation C.I.C.
3
4
 
@@ -14,6 +15,9 @@ See the License for the specific language governing permissions and
14
15
  limitations under the License.
15
16
  */
16
17
 
18
+ import { hasOptionalStringProperty, hasRequiredStringProperty, isRecord } from "../@types/type-guards.js";
19
+ import { HTTPError } from "../http-api/errors.js";
20
+
17
21
  /**
18
22
  * Errors expected to be encountered during OAuth2 discovery, client registration, and authentication.
19
23
  * Not intended to be displayed directly to the user.
@@ -33,4 +37,53 @@ export let OAuth2Error = /*#__PURE__*/function (OAuth2Error) {
33
37
  OAuth2Error["DeviceAuthorizationGrantFailed"] = "Failed to perform device authorization grant";
34
38
  return OAuth2Error;
35
39
  }({});
40
+
41
+ /**
42
+ * An error response from an OAuth 2.0 endpoint,
43
+ * as specified in https://datatracker.ietf.org/doc/html/rfc6749#section-5.2
44
+ */
45
+
46
+ /**
47
+ * Check whether the given (JSON-parsed) response body is an OAuth 2.0 error response
48
+ * as specified in https://datatracker.ietf.org/doc/html/rfc6749#section-5.2
49
+ * @param response - the parsed response body to check
50
+ * @returns whether the response is a valid {@link OAuth2ErrorResponse}
51
+ */
52
+ export function isOAuth2ErrorResponse(response) {
53
+ return isRecord(response) && hasRequiredStringProperty(response, "error") && hasOptionalStringProperty(response, "error_description") && hasOptionalStringProperty(response, "error_uri");
54
+ }
55
+
56
+ /**
57
+ * An error thrown when a request to an OAuth 2.0 endpoint fails with a body matching the error
58
+ * response format specified in [RFC 6749 section 5.2](https://datatracker.ietf.org/doc/html/rfc6749#section-5.2).
59
+ */
60
+ export class OAuth2HTTPError extends HTTPError {
61
+ constructor(msg, httpStatus, httpHeaders, {
62
+ error,
63
+ error_description,
64
+ error_uri
65
+ }) {
66
+ super(msg, httpStatus, httpHeaders);
67
+ /**
68
+ * RFC 6749 section 5.2 error code, e.g. `invalid_grant`
69
+ *
70
+ * IANA matains a registry of valid values at
71
+ * https://www.iana.org/assignments/oauth-parameters/oauth-parameters.xhtml#extensions-error
72
+ */
73
+ _defineProperty(this, "error", void 0);
74
+ /**
75
+ * RFC 6749 section 5.2 human-readable ASCII text providing additional information about the error.
76
+ * This field is optional and may be omitted by the endpoint.
77
+ */
78
+ _defineProperty(this, "error_description", void 0);
79
+ /**
80
+ * RFC 6749 section 5.2 URI identifying a human-readable web page with information about the error.
81
+ * This field is optional and may be omitted by the endpoint.
82
+ */
83
+ _defineProperty(this, "error_uri", void 0);
84
+ this.error = error;
85
+ this.error_description = error_description;
86
+ this.error_uri = error_uri;
87
+ }
88
+ }
36
89
  //# sourceMappingURL=error.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"error.js","names":[],"sources":["../../src/oauth/error.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\n/**\n * Errors expected to be encountered during OAuth2 discovery, client registration, and authentication.\n * Not intended to be displayed directly to the user.\n */\nexport enum OAuth2Error {\n General = \"Something went wrong with OAuth2 discovery\",\n OpSupport = \"Configured OAuth2 OP does not support required functions\",\n DynamicRegistrationNotSupported = \"Dynamic registration not supported\",\n DynamicRegistrationFailed = \"Dynamic registration failed\",\n DynamicRegistrationInvalid = \"Dynamic registration invalid response\",\n CodeExchangeFailed = \"Failed to exchange code for token\",\n InvalidBearerTokenResponse = \"Invalid bearer token response\",\n InvalidDeviceAuthorizationResponse = \"Invalid device authorization response\",\n MissingOrInvalidStoredState = \"State required to finish logging in is not found in storage.\",\n RefreshTokenFailed = \"Failed to refresh token\",\n RevokeTokenFailed = \"Failed to revoke token\",\n DeviceAuthorizationGrantFailed = \"Failed to perform device authorization grant\",\n}\n"],"mappings":"AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,WAAY,WAAW,0BAAX,WAAW;EAAX,WAAW;EAAX,WAAW;EAAX,WAAW;EAAX,WAAW;EAAX,WAAW;EAAX,WAAW;EAAX,WAAW;EAAX,WAAW;EAAX,WAAW;EAAX,WAAW;EAAX,WAAW;EAAX,WAAW;EAAA,OAAX,WAAW;AAAA","ignoreList":[]}
1
+ {"version":3,"file":"error.js","names":[],"sources":["../../src/oauth/error.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 { hasOptionalStringProperty, hasRequiredStringProperty, isRecord } from \"../@types/type-guards.ts\";\nimport { HTTPError } from \"../http-api/errors.ts\";\n\n/**\n * Errors expected to be encountered during OAuth2 discovery, client registration, and authentication.\n * Not intended to be displayed directly to the user.\n */\nexport enum OAuth2Error {\n General = \"Something went wrong with OAuth2 discovery\",\n OpSupport = \"Configured OAuth2 OP does not support required functions\",\n DynamicRegistrationNotSupported = \"Dynamic registration not supported\",\n DynamicRegistrationFailed = \"Dynamic registration failed\",\n DynamicRegistrationInvalid = \"Dynamic registration invalid response\",\n CodeExchangeFailed = \"Failed to exchange code for token\",\n InvalidBearerTokenResponse = \"Invalid bearer token response\",\n InvalidDeviceAuthorizationResponse = \"Invalid device authorization response\",\n MissingOrInvalidStoredState = \"State required to finish logging in is not found in storage.\",\n RefreshTokenFailed = \"Failed to refresh token\",\n RevokeTokenFailed = \"Failed to revoke token\",\n DeviceAuthorizationGrantFailed = \"Failed to perform device authorization grant\",\n}\n\n/**\n * An error response from an OAuth 2.0 endpoint,\n * as specified in https://datatracker.ietf.org/doc/html/rfc6749#section-5.2\n */\nexport interface OAuth2ErrorResponse {\n /** A single ASCII error code, e.g. `invalid_grant`. */\n error: string;\n /** Human-readable ASCII text providing additional information about the error. */\n error_description?: string;\n /** A URI identifying a human-readable web page with information about the error. */\n error_uri?: string;\n}\n\n/**\n * Check whether the given (JSON-parsed) response body is an OAuth 2.0 error response\n * as specified in https://datatracker.ietf.org/doc/html/rfc6749#section-5.2\n * @param response - the parsed response body to check\n * @returns whether the response is a valid {@link OAuth2ErrorResponse}\n */\nexport function isOAuth2ErrorResponse(response: unknown): response is OAuth2ErrorResponse {\n return (\n isRecord(response) &&\n hasRequiredStringProperty(response, \"error\") &&\n hasOptionalStringProperty(response, \"error_description\") &&\n hasOptionalStringProperty(response, \"error_uri\")\n );\n}\n\n/**\n * An error thrown when a request to an OAuth 2.0 endpoint fails with a body matching the error\n * response format specified in [RFC 6749 section 5.2](https://datatracker.ietf.org/doc/html/rfc6749#section-5.2).\n */\nexport class OAuth2HTTPError extends HTTPError implements OAuth2ErrorResponse {\n /**\n * RFC 6749 section 5.2 error code, e.g. `invalid_grant`\n *\n * IANA matains a registry of valid values at\n * https://www.iana.org/assignments/oauth-parameters/oauth-parameters.xhtml#extensions-error\n */\n public error: string;\n\n /**\n * RFC 6749 section 5.2 human-readable ASCII text providing additional information about the error.\n * This field is optional and may be omitted by the endpoint.\n */\n public error_description?: string;\n\n /**\n * RFC 6749 section 5.2 URI identifying a human-readable web page with information about the error.\n * This field is optional and may be omitted by the endpoint.\n */\n public error_uri?: string;\n\n public constructor(\n msg: string,\n httpStatus: number | undefined,\n httpHeaders: Headers | undefined,\n { error, error_description, error_uri }: OAuth2ErrorResponse,\n ) {\n super(msg, httpStatus, httpHeaders);\n this.error = error;\n this.error_description = error_description;\n this.error_uri = error_uri;\n }\n}\n"],"mappings":";AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA,SAAS,yBAAyB,EAAE,yBAAyB,EAAE,QAAQ,QAAQ,0BAA0B;AACzG,SAAS,SAAS,QAAQ,uBAAuB;;AAEjD;AACA;AACA;AACA;AACA,WAAY,WAAW,0BAAX,WAAW;EAAX,WAAW;EAAX,WAAW;EAAX,WAAW;EAAX,WAAW;EAAX,WAAW;EAAX,WAAW;EAAX,WAAW;EAAX,WAAW;EAAX,WAAW;EAAX,WAAW;EAAX,WAAW;EAAX,WAAW;EAAA,OAAX,WAAW;AAAA;;AAevB;AACA;AACA;AACA;;AAUA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO,SAAS,qBAAqB,CAAC,QAAiB,EAAmC;EACtF,OACI,QAAQ,CAAC,QAAQ,CAAC,IAClB,yBAAyB,CAAC,QAAQ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;;OAIG;IACU,WAAW,CAAC,KAAK,EAAE,MAAM,EAAE,IAAI,CAAC,EAAE,cAAc,GAAG,eAAe,GAAG,OAAO,CAAC,IAAI,CAAC,CAY9F;IAED;;;;;OAKG;IACU,6BAA6B,CAAC,KAAK,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,2BAA2B,CAAC,CAM/F;IAED;;;;;OAKG;IACU,+BAA+B,CACxC,OAAO,EAAE,2BAA2B,GACrC,OAAO,CAAC,yBAAyB,GAAG,sBAAsB,CAAC,CAM7D;YAEa,KAAK;CAsCtB"}
@@ -20,9 +20,9 @@ import { generateScope, normalizeBearerTokenResponseTokenType, startDeviceAuthor
20
20
  import { OAuthGrantType, urlHasCommonBase, validateRegistrationResponse } from "./register.js";
21
21
  import { encodeUnpaddedBase64Url } from "../base64.js";
22
22
  import { sha256 } from "../digest.js";
23
- import { HTTPError, Method } from "../http-api/index.js";
23
+ import { HTTPError, isMatrixErrorResponse, MatrixError, Method } from "../http-api/index.js";
24
24
  import { logger } from "../logger.js";
25
- import { OAuth2Error } from "./error.js";
25
+ import { isOAuth2ErrorResponse, OAuth2Error, OAuth2HTTPError } from "./error.js";
26
26
  import { secureRandomString } from "../randomstring.js";
27
27
  export * from "./authorize.js";
28
28
  export * from "./error.js";
@@ -228,6 +228,23 @@ export class OAuth2 {
228
228
  body: params
229
229
  });
230
230
  if (res.status >= 400) {
231
+ let body;
232
+ try {
233
+ body = await res.json();
234
+ } catch {
235
+ // The endpoint didn't give us a JSON body, so we can't determine the error type. We'll throw a generic
236
+ // HTTPError below.
237
+ }
238
+ // Because the Matrix C-S API error response format is so similar to the OAuth 2.0 error response format
239
+ // the ordering of these checks is important. We want to check for a Matrix error response first, and only
240
+ // if it isn't one do we check for an OAuth 2.0 error response.
241
+ // This essentially relies on `errcode` not being present in an OAuth 2.0 error response.
242
+ if (isMatrixErrorResponse(body)) {
243
+ throw new MatrixError(body, res.status, undefined, undefined, res.headers);
244
+ }
245
+ if (isOAuth2ErrorResponse(body)) {
246
+ throw new OAuth2HTTPError(error, res.status, res.headers, body);
247
+ }
231
248
  throw new HTTPError(error, res.status, res.headers);
232
249
  }
233
250
  return await res.json();
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":[],"sources":["../../src/oauth/index.ts"],"sourcesContent":["/*\nCopyright 2023 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport {\n type BearerTokenResponse,\n type DeviceAccessTokenError,\n type DeviceAccessTokenResponse,\n type DeviceAuthorizationResponse,\n generateScope,\n normalizeBearerTokenResponseTokenType,\n startDeviceAuthorization,\n validateBearerTokenResponse,\n waitForDeviceAuthorization,\n} from \"./authorize.ts\";\nimport type { ValidatedAuthMetadata } from \"./discover.ts\";\nimport {\n OAuthGrantType,\n type OAuthRegistrationRequest,\n urlHasCommonBase,\n validateRegistrationResponse,\n} from \"./register.ts\";\nimport { encodeUnpaddedBase64Url } from \"../base64.ts\";\nimport { sha256 } from \"../digest.ts\";\nimport { HTTPError, Method } from \"../http-api/index.ts\";\nimport { logger } from \"../logger.ts\";\nimport { OAuth2Error } from \"./error.ts\";\nimport { secureRandomString } from \"../randomstring.ts\";\nimport { type NonEmptyArray } from \"../@types/common.ts\";\n\nexport * from \"./authorize.ts\";\nexport * from \"./error.ts\";\nexport * from \"./register.ts\";\nexport * from \"./tokenRefresher.ts\";\nexport * from \"./discover.ts\";\n\n/**\n * Type representing the persistent context needed for typical OAuth flows\n */\ntype Context = {\n /** The OAuth client ID */\n clientId: string;\n /** The desired device ID */\n deviceId?: string;\n /** The seed used to generate the challenge code */\n codeVerifier?: string;\n /** The URI to redirect the user to with credentials after auth */\n redirectUri: string;\n};\n\nexport class OAuth2 {\n /**\n * Attempts dynamic registration against the configured registration endpoint.\n * Will ignore any URIs that do not use client_uri as a common base as per the spec.\n * @param authMetadata - Auth config from {@link MatrixClient.getAuthMetadata}\n * @param clientMetadata - The metadata for the client which to register,\n * grant_types & response_types & token_endpoint_auth_method will be sanely calculated if omitted.\n * @returns Promise<string> resolved with registered clientId\n * @throws when registration is not supported, on failed request or invalid response\n */\n public static async registerClient(\n authMetadata: ValidatedAuthMetadata,\n clientMetadata: OAuthRegistrationRequest,\n ): Promise<string> {\n const defaultGrantTypes: NonEmptyArray<string> = [\n OAuthGrantType.AuthorizationCode,\n OAuthGrantType.RefreshToken,\n ];\n // ask for device authorization grant if supported\n if (authMetadata.grant_types_supported.includes(OAuthGrantType.DeviceAuthorization)) {\n defaultGrantTypes.push(OAuthGrantType.DeviceAuthorization);\n }\n\n const grantTypes = clientMetadata.grant_types ?? defaultGrantTypes;\n if (grantTypes.some((scope) => !authMetadata.grant_types_supported.includes(scope))) {\n throw new Error(OAuth2Error.DynamicRegistrationNotSupported);\n }\n\n const commonBase = new URL(clientMetadata.client_uri);\n\n const request: OAuthRegistrationRequest = {\n // Apply some defaults\n response_types: [\"code\"],\n token_endpoint_auth_method: \"none\",\n ...clientMetadata,\n grant_types: grantTypes,\n logo_uri: urlHasCommonBase(commonBase, clientMetadata.logo_uri) ? clientMetadata.logo_uri : undefined,\n policy_uri: urlHasCommonBase(commonBase, clientMetadata.policy_uri) ? clientMetadata.policy_uri : undefined,\n tos_uri: urlHasCommonBase(commonBase, clientMetadata.tos_uri) ? clientMetadata.tos_uri : undefined,\n };\n\n try {\n const response = await fetch(authMetadata.registration_endpoint, {\n method: Method.Post,\n headers: {\n \"Accept\": \"application/json\",\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify(request),\n });\n\n if (response.status >= 400) {\n throw new Error(OAuth2Error.DynamicRegistrationFailed);\n }\n\n const registrationResponse = await response.json();\n if (validateRegistrationResponse(registrationResponse)) {\n return registrationResponse.client_id;\n }\n\n throw new Error(OAuth2Error.DynamicRegistrationInvalid);\n } catch (error) {\n if (Object.values(OAuth2Error).includes((error as Error).message as OAuth2Error)) {\n throw error;\n } else {\n logger.error(\"Dynamic registration request failed\", error);\n throw new Error(OAuth2Error.DynamicRegistrationFailed, { cause: error });\n }\n }\n }\n\n public readonly context: Required<Context>;\n\n public constructor(\n public readonly metadata: ValidatedAuthMetadata,\n context: Context,\n ) {\n this.context = {\n clientId: context.clientId,\n redirectUri: context.redirectUri,\n deviceId: context.deviceId ?? secureRandomString(10),\n codeVerifier: context.codeVerifier ?? secureRandomString(96),\n };\n }\n\n /**\n * Generate a URL to attempt authorization with the OP\n * See https://spec.matrix.org/v1.18/client-server-api/#authorization-code-flow\n * @param state - A unique opaque identifier, like a transaction ID,\n * that will allow the client to maintain state between the authorization request and the callback.\n * The app should use this to key the storage for where the rest of the auth context is saved.\n * @param responseMode - The manner in which the IdP should send the secrets back to the app. Defaults to `fragment` for privacy.\n * @param prompt - Optional prompt parameter to pass to the IdP to signal intent, e.g. `create` for User registration.\n * @param scope - The OAuth2 scope to request, will be generated based on the device ID if omitted.\n * @returns a Promise with the url as a string\n */\n public async generateAuthorizationCodeGrantUrl(\n state: string,\n responseMode: \"fragment\" | \"query\" = \"fragment\",\n prompt?: string,\n scope?: string,\n ): Promise<string> {\n const challenge = encodeUnpaddedBase64Url(await sha256(this.context.codeVerifier));\n\n const url = new URL(this.metadata.authorization_endpoint);\n url.searchParams.set(\"response_type\", \"code\");\n url.searchParams.set(\"response_mode\", responseMode);\n url.searchParams.set(\"client_id\", this.context.clientId);\n url.searchParams.set(\"redirect_uri\", this.context.redirectUri);\n url.searchParams.set(\"scope\", scope ?? generateScope(this.context.deviceId));\n url.searchParams.set(\"state\", state);\n url.searchParams.set(\"code_challenge_method\", \"S256\");\n url.searchParams.set(\"code_challenge\", challenge);\n\n if (prompt) {\n url.searchParams.set(\"prompt\", prompt);\n }\n\n return url.toString();\n }\n\n /**\n * Attempt to exchange authorization code for bearer token.\n *\n * Takes the authorization code returned by the OAuth2 Provider via the authorization URL, and makes a\n * request to the Token Endpoint, to obtain the access token, refresh token, etc.\n *\n * @param code - authorization code as returned by IdP during authorization\n * @returns a validated bearer token response\n * @throws An `Error` with `message` set to an entry in {@link OAuth2Error},\n * when the request fails, or the returned token response is invalid.\n */\n public async completeAuthorizationCodeGrant(code: string): Promise<BearerTokenResponse> {\n const params = new URLSearchParams();\n params.append(\"grant_type\", \"authorization_code\");\n params.append(\"client_id\", this.context.clientId);\n params.append(\"code_verifier\", this.context.codeVerifier);\n params.append(\"redirect_uri\", this.context.redirectUri);\n params.append(\"code\", code);\n\n const tokenResponse = await this.fetch(\"token\", params, OAuth2Error.CodeExchangeFailed);\n\n // throws when response is invalid\n validateBearerTokenResponse(tokenResponse);\n return normalizeBearerTokenResponseTokenType(tokenResponse);\n }\n\n /**\n * Refresh the access token using the given refresh token and the refresh token grant\n * @param refreshToken - the token to use to refresh the access token\n */\n public async performRefreshTokenGrant(refreshToken: string): Promise<BearerTokenResponse> {\n const params = new URLSearchParams();\n params.append(\"grant_type\", \"refresh_token\");\n params.append(\"client_id\", this.context.clientId);\n params.append(\"refresh_token\", refreshToken);\n\n const tokenResponse = await this.fetch(\"token\", params, OAuth2Error.RefreshTokenFailed);\n\n // throws when response is invalid\n validateBearerTokenResponse(tokenResponse);\n return normalizeBearerTokenResponseTokenType(tokenResponse);\n }\n\n /**\n * Revokes the given token\n * @param token - the token to remove\n * @param type - the type of token, acts as a hint to the IdP\n */\n public async revokeToken(token: string, type?: \"access_token\" | \"refresh_token\"): Promise<void> {\n const params = new URLSearchParams();\n params.append(\"token\", token);\n params.append(\"client_id\", this.context.clientId);\n if (type) {\n params.append(\"token_type_hint\", type);\n }\n\n await this.fetch(\"revocation\", params, OAuth2Error.RevokeTokenFailed);\n\n const headers = new Headers();\n headers.set(\"Content-Type\", \"application/x-www-form-urlencoded\");\n }\n\n /**\n * Begin OAuth2 device authorization flow.\n * @param scope - the scope to request for authorization.\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 */\n public async startDeviceAuthorizationGrant(scope?: string): Promise<DeviceAuthorizationResponse> {\n return startDeviceAuthorization({\n scope: scope ?? generateScope(this.context.deviceId),\n metadata: this.metadata,\n clientId: this.context.clientId,\n });\n }\n\n /**\n * Polls the OAuth2 token endpoint until we get a device access token response, or encounter an unrecoverable error.\n * @param session - The session returned from a previous call to {@link OAuth2.startDeviceAuthorizationGrant}.\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 */\n public async waitForDeviceAuthorizationGrant(\n session: DeviceAuthorizationResponse,\n ): Promise<DeviceAccessTokenResponse | DeviceAccessTokenError> {\n return waitForDeviceAuthorization({\n session,\n metadata: this.metadata,\n clientId: this.context.clientId,\n });\n }\n\n private async fetch(\n target: \"token\" | \"registration\" | \"revocation\",\n params: URLSearchParams,\n error: OAuth2Error,\n ): Promise<unknown> {\n const url = this.metadata[`${target}_endpoint`];\n const res = await fetch(url, {\n method: Method.Post,\n headers: {\n \"Content-Type\": \"application/x-www-form-urlencoded\",\n \"Accept\": \"application/json\",\n },\n body: params,\n });\n\n if (res.status >= 400) {\n throw new HTTPError(error, res.status, res.headers);\n }\n\n return await res.json();\n }\n}\n"],"mappings":";;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA,SAKI,aAAa,EACb,qCAAqC,EACrC,wBAAwB,EACxB,2BAA2B,EAC3B,0BAA0B,QACvB,gBAAgB;AAEvB,SACI,cAAc,EAEd,gBAAgB,EAChB,4BAA4B,QACzB,eAAe;AACtB,SAAS,uBAAuB,QAAQ,cAAc;AACtD,SAAS,MAAM,QAAQ,cAAc;AACrC,SAAS,SAAS,EAAE,MAAM,QAAQ,sBAAsB;AACxD,SAAS,MAAM,QAAQ,cAAc;AACrC,SAAS,WAAW,QAAQ,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E;MACd,CAAC;MACD,IAAI,EAAE;IACV,CAAC,CAAC;IAEF,IAAI,GAAG,CAAC,MAAM,IAAI,GAAG,EAAE;MACnB,MAAM,IAAI,SAAS,CAAC,KAAK,EAAE,GAAG,CAAC,MAAM,EAAE,GAAG,CAAC,OAAO,CAAC;IACvD;IAEA,OAAO,MAAM,GAAG,CAAC,IAAI,CAAC,CAAC;EAC3B;AACJ","ignoreList":[]}
1
+ {"version":3,"file":"index.js","names":[],"sources":["../../src/oauth/index.ts"],"sourcesContent":["/*\nCopyright 2023 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport {\n type BearerTokenResponse,\n type DeviceAccessTokenError,\n type DeviceAccessTokenResponse,\n type DeviceAuthorizationResponse,\n generateScope,\n normalizeBearerTokenResponseTokenType,\n startDeviceAuthorization,\n validateBearerTokenResponse,\n waitForDeviceAuthorization,\n} from \"./authorize.ts\";\nimport type { ValidatedAuthMetadata } from \"./discover.ts\";\nimport {\n OAuthGrantType,\n type OAuthRegistrationRequest,\n urlHasCommonBase,\n validateRegistrationResponse,\n} from \"./register.ts\";\nimport { encodeUnpaddedBase64Url } from \"../base64.ts\";\nimport { sha256 } from \"../digest.ts\";\nimport { HTTPError, isMatrixErrorResponse, MatrixError, Method } from \"../http-api/index.ts\";\nimport { logger } from \"../logger.ts\";\nimport { isOAuth2ErrorResponse, OAuth2Error, OAuth2HTTPError } from \"./error.ts\";\nimport { secureRandomString } from \"../randomstring.ts\";\nimport { type NonEmptyArray } from \"../@types/common.ts\";\n\nexport * from \"./authorize.ts\";\nexport * from \"./error.ts\";\nexport * from \"./register.ts\";\nexport * from \"./tokenRefresher.ts\";\nexport * from \"./discover.ts\";\n\n/**\n * Type representing the persistent context needed for typical OAuth flows\n */\ntype Context = {\n /** The OAuth client ID */\n clientId: string;\n /** The desired device ID */\n deviceId?: string;\n /** The seed used to generate the challenge code */\n codeVerifier?: string;\n /** The URI to redirect the user to with credentials after auth */\n redirectUri: string;\n};\n\nexport class OAuth2 {\n /**\n * Attempts dynamic registration against the configured registration endpoint.\n * Will ignore any URIs that do not use client_uri as a common base as per the spec.\n * @param authMetadata - Auth config from {@link MatrixClient.getAuthMetadata}\n * @param clientMetadata - The metadata for the client which to register,\n * grant_types & response_types & token_endpoint_auth_method will be sanely calculated if omitted.\n * @returns Promise<string> resolved with registered clientId\n * @throws when registration is not supported, on failed request or invalid response\n */\n public static async registerClient(\n authMetadata: ValidatedAuthMetadata,\n clientMetadata: OAuthRegistrationRequest,\n ): Promise<string> {\n const defaultGrantTypes: NonEmptyArray<string> = [\n OAuthGrantType.AuthorizationCode,\n OAuthGrantType.RefreshToken,\n ];\n // ask for device authorization grant if supported\n if (authMetadata.grant_types_supported.includes(OAuthGrantType.DeviceAuthorization)) {\n defaultGrantTypes.push(OAuthGrantType.DeviceAuthorization);\n }\n\n const grantTypes = clientMetadata.grant_types ?? defaultGrantTypes;\n if (grantTypes.some((scope) => !authMetadata.grant_types_supported.includes(scope))) {\n throw new Error(OAuth2Error.DynamicRegistrationNotSupported);\n }\n\n const commonBase = new URL(clientMetadata.client_uri);\n\n const request: OAuthRegistrationRequest = {\n // Apply some defaults\n response_types: [\"code\"],\n token_endpoint_auth_method: \"none\",\n ...clientMetadata,\n grant_types: grantTypes,\n logo_uri: urlHasCommonBase(commonBase, clientMetadata.logo_uri) ? clientMetadata.logo_uri : undefined,\n policy_uri: urlHasCommonBase(commonBase, clientMetadata.policy_uri) ? clientMetadata.policy_uri : undefined,\n tos_uri: urlHasCommonBase(commonBase, clientMetadata.tos_uri) ? clientMetadata.tos_uri : undefined,\n };\n\n try {\n const response = await fetch(authMetadata.registration_endpoint, {\n method: Method.Post,\n headers: {\n \"Accept\": \"application/json\",\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify(request),\n });\n\n if (response.status >= 400) {\n throw new Error(OAuth2Error.DynamicRegistrationFailed);\n }\n\n const registrationResponse = await response.json();\n if (validateRegistrationResponse(registrationResponse)) {\n return registrationResponse.client_id;\n }\n\n throw new Error(OAuth2Error.DynamicRegistrationInvalid);\n } catch (error) {\n if (Object.values(OAuth2Error).includes((error as Error).message as OAuth2Error)) {\n throw error;\n } else {\n logger.error(\"Dynamic registration request failed\", error);\n throw new Error(OAuth2Error.DynamicRegistrationFailed, { cause: error });\n }\n }\n }\n\n public readonly context: Required<Context>;\n\n public constructor(\n public readonly metadata: ValidatedAuthMetadata,\n context: Context,\n ) {\n this.context = {\n clientId: context.clientId,\n redirectUri: context.redirectUri,\n deviceId: context.deviceId ?? secureRandomString(10),\n codeVerifier: context.codeVerifier ?? secureRandomString(96),\n };\n }\n\n /**\n * Generate a URL to attempt authorization with the OP\n * See https://spec.matrix.org/v1.18/client-server-api/#authorization-code-flow\n * @param state - A unique opaque identifier, like a transaction ID,\n * that will allow the client to maintain state between the authorization request and the callback.\n * The app should use this to key the storage for where the rest of the auth context is saved.\n * @param responseMode - The manner in which the IdP should send the secrets back to the app. Defaults to `fragment` for privacy.\n * @param prompt - Optional prompt parameter to pass to the IdP to signal intent, e.g. `create` for User registration.\n * @param scope - The OAuth2 scope to request, will be generated based on the device ID if omitted.\n * @returns a Promise with the url as a string\n */\n public async generateAuthorizationCodeGrantUrl(\n state: string,\n responseMode: \"fragment\" | \"query\" = \"fragment\",\n prompt?: string,\n scope?: string,\n ): Promise<string> {\n const challenge = encodeUnpaddedBase64Url(await sha256(this.context.codeVerifier));\n\n const url = new URL(this.metadata.authorization_endpoint);\n url.searchParams.set(\"response_type\", \"code\");\n url.searchParams.set(\"response_mode\", responseMode);\n url.searchParams.set(\"client_id\", this.context.clientId);\n url.searchParams.set(\"redirect_uri\", this.context.redirectUri);\n url.searchParams.set(\"scope\", scope ?? generateScope(this.context.deviceId));\n url.searchParams.set(\"state\", state);\n url.searchParams.set(\"code_challenge_method\", \"S256\");\n url.searchParams.set(\"code_challenge\", challenge);\n\n if (prompt) {\n url.searchParams.set(\"prompt\", prompt);\n }\n\n return url.toString();\n }\n\n /**\n * Attempt to exchange authorization code for bearer token.\n *\n * Takes the authorization code returned by the OAuth2 Provider via the authorization URL, and makes a\n * request to the Token Endpoint, to obtain the access token, refresh token, etc.\n *\n * @param code - authorization code as returned by IdP during authorization\n * @returns a validated bearer token response\n * @throws An `Error` with `message` set to an entry in {@link OAuth2Error},\n * when the request fails, or the returned token response is invalid.\n */\n public async completeAuthorizationCodeGrant(code: string): Promise<BearerTokenResponse> {\n const params = new URLSearchParams();\n params.append(\"grant_type\", \"authorization_code\");\n params.append(\"client_id\", this.context.clientId);\n params.append(\"code_verifier\", this.context.codeVerifier);\n params.append(\"redirect_uri\", this.context.redirectUri);\n params.append(\"code\", code);\n\n const tokenResponse = await this.fetch(\"token\", params, OAuth2Error.CodeExchangeFailed);\n\n // throws when response is invalid\n validateBearerTokenResponse(tokenResponse);\n return normalizeBearerTokenResponseTokenType(tokenResponse);\n }\n\n /**\n * Refresh the access token using the given refresh token and the refresh token grant\n * @param refreshToken - the token to use to refresh the access token\n */\n public async performRefreshTokenGrant(refreshToken: string): Promise<BearerTokenResponse> {\n const params = new URLSearchParams();\n params.append(\"grant_type\", \"refresh_token\");\n params.append(\"client_id\", this.context.clientId);\n params.append(\"refresh_token\", refreshToken);\n\n const tokenResponse = await this.fetch(\"token\", params, OAuth2Error.RefreshTokenFailed);\n\n // throws when response is invalid\n validateBearerTokenResponse(tokenResponse);\n return normalizeBearerTokenResponseTokenType(tokenResponse);\n }\n\n /**\n * Revokes the given token\n * @param token - the token to remove\n * @param type - the type of token, acts as a hint to the IdP\n */\n public async revokeToken(token: string, type?: \"access_token\" | \"refresh_token\"): Promise<void> {\n const params = new URLSearchParams();\n params.append(\"token\", token);\n params.append(\"client_id\", this.context.clientId);\n if (type) {\n params.append(\"token_type_hint\", type);\n }\n\n await this.fetch(\"revocation\", params, OAuth2Error.RevokeTokenFailed);\n\n const headers = new Headers();\n headers.set(\"Content-Type\", \"application/x-www-form-urlencoded\");\n }\n\n /**\n * Begin OAuth2 device authorization flow.\n * @param scope - the scope to request for authorization.\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 */\n public async startDeviceAuthorizationGrant(scope?: string): Promise<DeviceAuthorizationResponse> {\n return startDeviceAuthorization({\n scope: scope ?? generateScope(this.context.deviceId),\n metadata: this.metadata,\n clientId: this.context.clientId,\n });\n }\n\n /**\n * Polls the OAuth2 token endpoint until we get a device access token response, or encounter an unrecoverable error.\n * @param session - The session returned from a previous call to {@link OAuth2.startDeviceAuthorizationGrant}.\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 */\n public async waitForDeviceAuthorizationGrant(\n session: DeviceAuthorizationResponse,\n ): Promise<DeviceAccessTokenResponse | DeviceAccessTokenError> {\n return waitForDeviceAuthorization({\n session,\n metadata: this.metadata,\n clientId: this.context.clientId,\n });\n }\n\n private async fetch(\n target: \"token\" | \"registration\" | \"revocation\",\n params: URLSearchParams,\n error: OAuth2Error,\n ): Promise<unknown> {\n const url = this.metadata[`${target}_endpoint`];\n const res = await fetch(url, {\n method: Method.Post,\n headers: {\n \"Content-Type\": \"application/x-www-form-urlencoded\",\n \"Accept\": \"application/json\",\n },\n body: params,\n });\n\n if (res.status >= 400) {\n let body: unknown;\n try {\n body = await res.json();\n } catch {\n // The endpoint didn't give us a JSON body, so we can't determine the error type. We'll throw a generic\n // HTTPError below.\n }\n // Because the Matrix C-S API error response format is so similar to the OAuth 2.0 error response format\n // the ordering of these checks is important. We want to check for a Matrix error response first, and only\n // if it isn't one do we check for an OAuth 2.0 error response.\n // This essentially relies on `errcode` not being present in an OAuth 2.0 error response.\n if (isMatrixErrorResponse(body)) {\n throw new MatrixError(body, res.status, undefined, undefined, res.headers);\n }\n if (isOAuth2ErrorResponse(body)) {\n throw new OAuth2HTTPError(error, res.status, res.headers, body);\n }\n throw new HTTPError(error, res.status, res.headers);\n }\n\n return await res.json();\n }\n}\n"],"mappings":";;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA,SAKI,aAAa,EACb,qCAAqC,EACrC,wBAAwB,EACxB,2BAA2B,EAC3B,0BAA0B,QACvB,gBAAgB;AAEvB,SACI,cAAc,EAEd,gBAAgB,EAChB,4BAA4B,QACzB,eAAe;AACtB,SAAS,uBAAuB,QAAQ,cAAc;AACtD,SAAS,MAAM,QAAQ,cAAc;AACrC,SAAS,SAAS,EAAE,qBAAqB,EAAE,WAAW,EAAE,MAAM,QAAQ,sBAAsB;AAC5F,SAAS,MAAM,QAAQ,cAAc;AACrC,SAAS,qBAAqB,EAAE,WAAW,EAAE,eAAe,QAAQ,YAAY;AAChF,SAAS,kBAAkB,QAAQ,oBAAoB;AAGvD,cAAc,gBAAgB;AAC9B,cAAc,YAAY;AAC1B,cAAc,eAAe;AAC7B,cAAc,qBAAqB;AACnC,cAAc,eAAe;;AAE7B;AACA;AACA;;AAYA,OAAO,MAAM,MAAM,CAAC;EAChB;AACJ;AACA;AACA;AACA;AACA;AACA;AACA;AACA;EACI,aAAoB,cAAc,CAC9B,YAAmC,EACnC,cAAwC,EACzB;IACf,MAAM,iBAAwC,GAAG,CAC7C,cAAc,CAAC,iBAAiB,EAChC,cAAc,CAAC,YAAY,CAC9B;IACD;IACA,IAAI,YAAY,CAAC,qBAAqB,CAAC,QAAQ,CAAC,cAAc,CAAC,mBAAmB,CAAC,EAAE;MACjF,iBAAiB,CAAC,IAAI,CAAC,cAAc,CAAC,mBAAmB,CAAC;IAC9D;IAEA,MAAM,UAAU,GAAG,cAAc,CAAC,WAAW,IAAI,iBAAiB;IAClE,IAAI,UAAU,CAAC,IAAI,C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AAM,EAAE,GAAG,CAAC,OAAO,CAAC;IACvD;IAEA,OAAO,MAAM,GAAG,CAAC,IAAI,CAAC,CAAC;EAC3B;AACJ","ignoreList":[]}
@@ -1 +1 @@
1
- {"version":3,"file":"tokenRefresher.d.ts","sourceRoot":"","sources":["../../src/oauth/tokenRefresher.ts"],"names":[],"mappings":"AAgBA,OAAO,EAAE,KAAK,YAAY,EAAa,KAAK,oBAAoB,EAA2B,MAAM,sBAAsB,CAAC;AACxH,OAAO,EAAE,KAAK,MAAM,EAAE,MAAM,YAAY,CAAC;AAEzC;;GAEG;AACH,qBAAa,cAAc;IAInB,OAAO,CAAC,QAAQ,CAAC,IAAI;IACrB,OAAO,CAAC,QAAQ,CAAC,SAAS;IAJ9B,OAAO,CAAC,sBAAsB,CAAC,CAAwB;IAEvD,YACqB,IAAI,EAAE,MAAM,EACZ,SAAS,EAAE,CAAC,MAAM,EAAE,YAAY,KAAK,OAAO,CAAC,IAAI,CAAC,EACnE;IAEJ;;;;;OAKG;IACI,oBAAoB,EAAE,oBAAoB,CAiB/C;IAEF,OAAO,CAAC,mBAAmB;YAKb,YAAY;CAgB7B"}
1
+ {"version":3,"file":"tokenRefresher.d.ts","sourceRoot":"","sources":["../../src/oauth/tokenRefresher.ts"],"names":[],"mappings":"AAgBA,OAAO,EAAE,KAAK,YAAY,EAAa,KAAK,oBAAoB,EAA2B,MAAM,sBAAsB,CAAC;AAExH,OAAO,EAAE,KAAK,MAAM,EAAE,MAAM,YAAY,CAAC;AAEzC;;GAEG;AACH,qBAAa,cAAc;IAInB,OAAO,CAAC,QAAQ,CAAC,IAAI;IACrB,OAAO,CAAC,QAAQ,CAAC,SAAS;IAJ9B,OAAO,CAAC,sBAAsB,CAAC,CAAwB;IAEvD,YACqB,IAAI,EAAE,MAAM,EACZ,SAAS,EAAE,CAAC,MAAM,EAAE,YAAY,KAAK,OAAO,CAAC,IAAI,CAAC,EACnE;IAEJ;;;;;OAKG;IACI,oBAAoB,EAAE,oBAAoB,CAiB/C;IAEF,OAAO,CAAC,mBAAmB;YAWb,YAAY;CAgB7B"}
@@ -16,6 +16,7 @@ limitations under the License.
16
16
  */
17
17
 
18
18
  import { HTTPError, TokenRefreshLogoutError } from "../http-api/index.js";
19
+ import { OAuth2HTTPError } from "./error.js";
19
20
  /**
20
21
  * Class responsible for refreshing OAuth2 access tokens
21
22
  */
@@ -49,8 +50,9 @@ export class TokenRefresher {
49
50
  this.onRefresh = onRefresh;
50
51
  }
51
52
  shouldLogoutOnError(error) {
52
- // As per https://spec.matrix.org/v1.18/client-server-api/#refresh-token-grant
53
- return typeof error.httpStatus === "number" && error.httpStatus < 500 && error.httpStatus >= 400;
53
+ // Treat as logout as per https://spec.matrix.org/v1.18/client-server-api/#refresh-token-grant
54
+ // after making sure it is an RFC 6749 section 5.2 error response
55
+ return error instanceof OAuth2HTTPError && typeof error.httpStatus === "number" && error.httpStatus < 500 && error.httpStatus >= 400;
54
56
  }
55
57
  async getNewTokens(refreshToken) {
56
58
  const requestStart = Date.now();
@@ -1 +1 @@
1
- {"version":3,"file":"tokenRefresher.js","names":[],"sources":["../../src/oauth/tokenRefresher.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 { type AccessTokens, HTTPError, type TokenRefreshFunction, TokenRefreshLogoutError } from \"../http-api/index.ts\";\nimport { type OAuth2 } from \"./index.ts\";\n\n/**\n * Class responsible for refreshing OAuth2 access tokens\n */\nexport class TokenRefresher {\n private inflightRefreshRequest?: Promise<AccessTokens>;\n\n public constructor(\n private readonly auth: OAuth2,\n private readonly onRefresh: (tokens: AccessTokens) => Promise<void>,\n ) {}\n\n /**\n * Attempt token refresh using given refresh token\n * @param refreshToken - refresh token to use in request with token issuer\n * @returns tokens - Promise that resolves with new access and refresh tokens\n * @throws when token refresh fails\n */\n public tokenRefreshFunction: TokenRefreshFunction = async (refreshToken: string): Promise<AccessTokens> => {\n if (!this.inflightRefreshRequest) {\n this.inflightRefreshRequest = this.getNewTokens(refreshToken);\n }\n\n try {\n const tokens = await this.inflightRefreshRequest;\n return tokens;\n } catch (e) {\n // If we encounter a 40x error then signal that it should cause a logout by upgrading it to a TokenRefreshLogoutError\n if (e instanceof HTTPError && this.shouldLogoutOnError(e)) {\n throw new TokenRefreshLogoutError(e);\n }\n throw e;\n } finally {\n this.inflightRefreshRequest = undefined;\n }\n };\n\n private shouldLogoutOnError(error: HTTPError): boolean {\n // As per https://spec.matrix.org/v1.18/client-server-api/#refresh-token-grant\n return typeof error.httpStatus === \"number\" && error.httpStatus < 500 && error.httpStatus >= 400;\n }\n\n private async getNewTokens(refreshToken: string): Promise<AccessTokens> {\n const requestStart = Date.now();\n\n const response = await this.auth.performRefreshTokenGrant(refreshToken);\n\n const tokens = {\n accessToken: response.access_token,\n refreshToken: response.refresh_token,\n // We use the request start time to calculate the expiry time as we don't know when the server received our request\n expiry: response.expires_in ? new Date(requestStart + response.expires_in * 1000) : undefined,\n } satisfies AccessTokens;\n\n await this.onRefresh(tokens);\n\n return tokens;\n }\n}\n"],"mappings":";AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA,SAA4B,SAAS,EAA6B,uBAAuB,QAAQ,sBAAsB;AAGvH;AACA;AACA;AACA,OAAO,MAAM,cAAc,CAAC;EAGjB,WAAW,CACG,IAAY,EACZ,SAAkD,EACrE;IAAA;IAEF;AACJ;AACA;AACA;AACA;AACA;IALI,8CAMoD,MAAO,YAAoB,IAA4B;MACvG,IAAI,CAAC,IAAI,CAAC,sBAAsB,EAAE;Q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*\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 { type AccessTokens, HTTPError, type TokenRefreshFunction, TokenRefreshLogoutError } from \"../http-api/index.ts\";\nimport { OAuth2HTTPError } from \"./error.ts\";\nimport { type OAuth2 } from \"./index.ts\";\n\n/**\n * Class responsible for refreshing OAuth2 access tokens\n */\nexport class TokenRefresher {\n private inflightRefreshRequest?: Promise<AccessTokens>;\n\n public constructor(\n private readonly auth: OAuth2,\n private readonly onRefresh: (tokens: AccessTokens) => Promise<void>,\n ) {}\n\n /**\n * Attempt token refresh using given refresh token\n * @param refreshToken - refresh token to use in request with token issuer\n * @returns tokens - Promise that resolves with new access and refresh tokens\n * @throws when token refresh fails\n */\n public tokenRefreshFunction: TokenRefreshFunction = async (refreshToken: string): Promise<AccessTokens> => {\n if (!this.inflightRefreshRequest) {\n this.inflightRefreshRequest = this.getNewTokens(refreshToken);\n }\n\n try {\n const tokens = await this.inflightRefreshRequest;\n return tokens;\n } catch (e) {\n // If we encounter a 40x error then signal that it should cause a logout by upgrading it to a TokenRefreshLogoutError\n if (e instanceof HTTPError && this.shouldLogoutOnError(e)) {\n throw new TokenRefreshLogoutError(e);\n }\n throw e;\n } finally {\n this.inflightRefreshRequest = undefined;\n }\n };\n\n private shouldLogoutOnError(error: HTTPError): boolean {\n // Treat as logout as per https://spec.matrix.org/v1.18/client-server-api/#refresh-token-grant\n // after making sure it is an RFC 6749 section 5.2 error response\n return (\n error instanceof OAuth2HTTPError &&\n typeof error.httpStatus === \"number\" &&\n error.httpStatus < 500 &&\n error.httpStatus >= 400\n );\n }\n\n private async getNewTokens(refreshToken: string): Promise<AccessTokens> {\n const requestStart = Date.now();\n\n const response = await this.auth.performRefreshTokenGrant(refreshToken);\n\n const tokens = {\n accessToken: response.access_token,\n refreshToken: response.refresh_token,\n // We use the request start time to calculate the expiry time as we don't know when the server received our request\n expiry: response.expires_in ? new Date(requestStart + response.expires_in * 1000) : undefined,\n } satisfies AccessTokens;\n\n await this.onRefresh(tokens);\n\n return tokens;\n }\n}\n"],"mappings":";AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA,SAA4B,SAAS,EAA6B,uBAAuB,QAAQ,sBAAsB;AACvH,SAAS,eAAe,QAAQ,YAAY;AAG5C;AACA;AACA;AACA,OAAO,MAAM,cAAc,CAAC;EAGjB,WAAW,CACG,IAAY,EACZ,SAAkD,EACrE;IAAA;IAEF;AACJ;AACA;AACA;AACA;AACA;IALI,8CAMoD,MAAO,YAAoB,IAA4B;MACvG,IAAI,CAAC,IAAI,CAAC,sBAAsB,EAAE;QAC9B,IAAI,CAAC,sBAAsB,GAAG,IAAI,CAAC,YAAY,CAAC,YAAY,CAAC;MACjE;MAEA,IAAI;QACA,MAAM,MAAM,GAAG,MAAM,IAAI,CAAC,sBAAsB;QAChD,OAAO,MAAM;MACjB,CAAC,CAAC,OAAO,CAAC,EAAE;QACR;QACA,IAAI,CAAC,YAAY,SAAS,IAAI,IAAI,CAAC,mBAAmB,CAAC,CAAC,CAAC,EAAE;UACvD,MAAM,IAAI,uBAAuB,CAAC,CAAC,CAAC;QACxC;QACA,MAAM,CAAC;MACX,CAAC,SAAS;QACN,IAAI,CAAC,sBAAsB,GAAG,SAAS;MAC3C;IACJ,CAAC;IAAA,KA3BoB,IAAY,GAAZ,IAAY;IAAA,KACZ,SAAkD,GAAlD,SAAkD;EACpE;EA2BK,mBAAmB,CAAC,KAAgB,EAAW;IACnD;IACA;IACA,OACI,KAAK,YAAY,eAAe,IAChC,OAAO,KAAK,CAAC,UAAU,KAAK,QAAQ,IACpC,KAAK,CAAC,UAAU,GAAG,GAAG,IACtB,KAAK,CAAC,UAAU,IAAI,GAAG;EAE/B;EAEA,MAAc,YAAY,CAAC,YAAoB,EAAyB;IACpE,MAAM,YAAY,GAAG,IAAI,CAAC,GAAG,CAAC,CAAC;IAE/B,MAAM,QAAQ,GAAG,MAAM,IAAI,CAAC,IAAI,CAAC,wBAAwB,CAAC,YAAY,CAAC;IAEvE,MAAM,MAAM,GAAG;MACX,WAAW,EAAE,QAAQ,CAAC,YAAY;MAClC,YAAY,EAAE,QAAQ,CAAC,aAAa;MACpC;MACA,MAAM,EAAE,QAAQ,CAAC,UAAU,GAAG,IAAI,IAAI,CAAC,YAAY,GAAG,QAAQ,CAAC,UAAU,GAAG,IAAI,CAAC,GAAG;IACxF,CAAwB;IAExB,MAAM,IAAI,CAAC,SAAS,CAAC,MAAM,CAAC;IAE5B,OAAO,MAAM;EACjB;AACJ","ignoreList":[]}
@@ -4,7 +4,7 @@
4
4
  * @see https://spec.matrix.org/v1.6/client-server-api/#storage
5
5
  */
6
6
  import { type TypedEventEmitter } from "./models/typed-event-emitter.ts";
7
- import { ClientEvent, type ClientEventHandlerMap } from "./client.ts";
7
+ import { type ClientEvent, type ClientEventHandlerMap } from "./client.ts";
8
8
  import { type AESEncryptedSecretStoragePayload } from "./@types/AESEncryptedSecretStoragePayload.ts";
9
9
  import { type AccountDataEvents, type SecretStorageAccountDataEvents } from "./@types/event.ts";
10
10
  import { type EmptyObject } from "./@types/common.ts";
@@ -1 +1 @@
1
- {"version":3,"file":"secret-storage.d.ts","sourceRoot":"","sources":["../src/secret-storage.ts"],"names":[],"mappings":"AAgBA;;;;GAIG;AAEH,OAAO,EAAE,KAAK,iBAAiB,EAAE,MAAM,iCAAiC,CAAC;AACzE,OAAO,EAAE,WAAW,EAAE,KAAK,qBAAqB,EAAE,MAAM,aAAa,CAAC;AAMtE,OAAO,EAAE,KAAK,gCAAgC,EAAE,MAAM,8CAA8C,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,IAAI,EAAE,gBAAgB,GAAG,OAAO,CAAC,MAAM,GAAG,SAAS,CAAC,CAmCpE;IAED;;;;;;;;OAQG;IACU,QAAQ,CAAC,IAAI,EAAE,gBAAgB,GAAG,OAAO,CAAC,MAAM,CAAC,MAAM,EAAE,gCAAgC,CAAC,GAAG,IAAI,CAAC,CAsB9G;YAEa,mBAAmB;CAoCpC;AAED;;;;;GAKG;AACH,wBAAgB,kBAAkB,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM,CAcxD;AAKD;;;;;;;;GAQG;AACH,wBAAgB,iBAAiB,CAC7B,GAAG,EAAE,UAAU,CAAC,WAAW,CAAC,EAC5B,EAAE,CAAC,EAAE,MAAM,GACZ,OAAO,CAAC,gCAAgC,CAAC,CAE3C"}
@@ -20,7 +20,6 @@ limitations under the License.
20
20
  * @see https://spec.matrix.org/v1.6/client-server-api/#storage
21
21
  */
22
22
 
23
- import { ClientEvent } from "./client.js";
24
23
  import { secureRandomString } from "./randomstring.js";
25
24
  import { logger } from "./logger.js";
26
25
  import encryptAESSecretStorageItem from "./utils/encryptAESSecretStorageItem.js";
@@ -131,37 +130,15 @@ export class ServerSideSecretStorageImpl {
131
130
  /**
132
131
  * Implementation of {@link ServerSideSecretStorage#setDefaultKeyId}.
133
132
  */
134
- setDefaultKeyId(keyId) {
135
- return new Promise((resolve, reject) => {
136
- const listener = ev => {
137
- if (ev.getType() !== "m.secret_storage.default_key") {
138
- // Different account data item
139
- return;
140
- }
141
-
142
- // If keyId === null, the content should be an empty object.
143
- // Otherwise, the `key` in the content object should match keyId.
144
- const content = ev.getContent();
145
- const isSameKey = keyId === null ? Object.keys(content).length === 0 : content.key === keyId;
146
- if (isSameKey) {
147
- this.accountDataAdapter.removeListener(ClientEvent.AccountData, listener);
148
- resolve();
149
- }
150
- };
151
- this.accountDataAdapter.on(ClientEvent.AccountData, listener);
152
-
153
- // The spec [1] says that the value of the account data entry should be an object with a `key` property.
154
- // It doesn't specify how to delete the default key; we do it by setting the account data to an empty object.
155
- //
156
- // [1]: https://spec.matrix.org/v1.13/client-server-api/#key-storage
157
- const newValue = keyId === null ? {} : {
158
- key: keyId
159
- };
160
- this.accountDataAdapter.setAccountData("m.secret_storage.default_key", newValue).catch(e => {
161
- this.accountDataAdapter.removeListener(ClientEvent.AccountData, listener);
162
- reject(e);
163
- });
164
- });
133
+ async setDefaultKeyId(keyId) {
134
+ // The spec [1] says that the value of the account data entry should be an object with a `key` property.
135
+ // It doesn't specify how to delete the default key; we do it by setting the account data to an empty object.
136
+ //
137
+ // [1]: https://spec.matrix.org/v1.13/client-server-api/#key-storage
138
+ const newValue = keyId === null ? {} : {
139
+ key: keyId
140
+ };
141
+ await this.accountDataAdapter.setAccountData("m.secret_storage.default_key", newValue);
165
142
  }
166
143
 
167
144
  /**