matrix-js-sdk 41.4.0 → 41.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (109) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/README.md +1 -0
  3. package/lib/@types/json.d.ts +7 -0
  4. package/lib/@types/json.d.ts.map +1 -0
  5. package/lib/@types/json.js +1 -0
  6. package/lib/@types/json.js.map +1 -0
  7. package/lib/@types/requests.d.ts +6 -9
  8. package/lib/@types/requests.d.ts.map +1 -1
  9. package/lib/@types/requests.js.map +1 -1
  10. package/lib/client.d.ts +17 -2
  11. package/lib/client.d.ts.map +1 -1
  12. package/lib/client.js +27 -12
  13. package/lib/client.js.map +1 -1
  14. package/lib/filter.d.ts +20 -5
  15. package/lib/filter.d.ts.map +1 -1
  16. package/lib/filter.js +21 -0
  17. package/lib/filter.js.map +1 -1
  18. package/lib/models/user.d.ts +5 -0
  19. package/lib/models/user.d.ts.map +1 -1
  20. package/lib/models/user.js +5 -0
  21. package/lib/models/user.js.map +1 -1
  22. package/lib/oidc/authorize.d.ts +60 -0
  23. package/lib/oidc/authorize.d.ts.map +1 -1
  24. package/lib/oidc/authorize.js +115 -2
  25. package/lib/oidc/authorize.js.map +1 -1
  26. package/lib/oidc/register.d.ts.map +1 -1
  27. package/lib/oidc/register.js +5 -0
  28. package/lib/oidc/register.js.map +1 -1
  29. package/lib/rendezvous/MSC4108SignInWithQR.d.ts +19 -2
  30. package/lib/rendezvous/MSC4108SignInWithQR.d.ts.map +1 -1
  31. package/lib/rendezvous/MSC4108SignInWithQR.js +126 -36
  32. package/lib/rendezvous/MSC4108SignInWithQR.js.map +1 -1
  33. package/lib/rendezvous/channels/MSC4108SecureChannel.d.ts.map +1 -1
  34. package/lib/rendezvous/channels/MSC4108SecureChannel.js +4 -2
  35. package/lib/rendezvous/channels/MSC4108SecureChannel.js.map +1 -1
  36. package/lib/rendezvous/index.d.ts +36 -0
  37. package/lib/rendezvous/index.d.ts.map +1 -1
  38. package/lib/rendezvous/index.js +115 -0
  39. package/lib/rendezvous/index.js.map +1 -1
  40. package/lib/rendezvous/transports/MSC4108RendezvousSession.d.ts +1 -1
  41. package/lib/rendezvous/transports/MSC4108RendezvousSession.d.ts.map +1 -1
  42. package/lib/rendezvous/transports/MSC4108RendezvousSession.js.map +1 -1
  43. package/lib/rust-crypto/rust-crypto.d.ts.map +1 -1
  44. package/lib/rust-crypto/rust-crypto.js +2 -2
  45. package/lib/rust-crypto/rust-crypto.js.map +1 -1
  46. package/lib/store/index.d.ts +17 -1
  47. package/lib/store/index.d.ts.map +1 -1
  48. package/lib/store/index.js.map +1 -1
  49. package/lib/store/indexeddb-backend.d.ts +4 -0
  50. package/lib/store/indexeddb-backend.d.ts.map +1 -1
  51. package/lib/store/indexeddb-backend.js.map +1 -1
  52. package/lib/store/indexeddb-local-backend.d.ts +4 -1
  53. package/lib/store/indexeddb-local-backend.d.ts.map +1 -1
  54. package/lib/store/indexeddb-local-backend.js +45 -3
  55. package/lib/store/indexeddb-local-backend.js.map +1 -1
  56. package/lib/store/indexeddb-remote-backend.d.ts +4 -0
  57. package/lib/store/indexeddb-remote-backend.d.ts.map +1 -1
  58. package/lib/store/indexeddb-remote-backend.js +21 -3
  59. package/lib/store/indexeddb-remote-backend.js.map +1 -1
  60. package/lib/store/indexeddb-store-worker.d.ts.map +1 -1
  61. package/lib/store/indexeddb-store-worker.js +10 -1
  62. package/lib/store/indexeddb-store-worker.js.map +1 -1
  63. package/lib/store/indexeddb.d.ts +4 -0
  64. package/lib/store/indexeddb.d.ts.map +1 -1
  65. package/lib/store/indexeddb.js +18 -0
  66. package/lib/store/indexeddb.js.map +1 -1
  67. package/lib/store/memory.d.ts +5 -1
  68. package/lib/store/memory.d.ts.map +1 -1
  69. package/lib/store/memory.js +19 -0
  70. package/lib/store/memory.js.map +1 -1
  71. package/lib/store/stub.d.ts +3 -0
  72. package/lib/store/stub.d.ts.map +1 -1
  73. package/lib/store/stub.js +15 -0
  74. package/lib/store/stub.js.map +1 -1
  75. package/lib/sync-accumulator.d.ts +15 -0
  76. package/lib/sync-accumulator.d.ts.map +1 -1
  77. package/lib/sync-accumulator.js +4 -0
  78. package/lib/sync-accumulator.js.map +1 -1
  79. package/lib/sync.d.ts +9 -1
  80. package/lib/sync.d.ts.map +1 -1
  81. package/lib/sync.js +51 -9
  82. package/lib/sync.js.map +1 -1
  83. package/lib/webrtc/call.d.ts.map +1 -1
  84. package/lib/webrtc/call.js +1 -2
  85. package/lib/webrtc/call.js.map +1 -1
  86. package/package.json +7 -7
  87. package/src/@types/json.ts +16 -0
  88. package/src/@types/requests.ts +6 -9
  89. package/src/client.ts +40 -12
  90. package/src/filter.ts +31 -5
  91. package/src/models/user.ts +6 -0
  92. package/src/oidc/authorize.ts +135 -2
  93. package/src/oidc/register.ts +5 -0
  94. package/src/rendezvous/MSC4108SignInWithQR.ts +117 -4
  95. package/src/rendezvous/channels/MSC4108SecureChannel.ts +10 -2
  96. package/src/rendezvous/index.ts +115 -0
  97. package/src/rendezvous/transports/MSC4108RendezvousSession.ts +1 -1
  98. package/src/rust-crypto/rust-crypto.ts +6 -3
  99. package/src/store/index.ts +20 -1
  100. package/src/store/indexeddb-backend.ts +4 -0
  101. package/src/store/indexeddb-local-backend.ts +32 -1
  102. package/src/store/indexeddb-remote-backend.ts +13 -0
  103. package/src/store/indexeddb-store-worker.ts +9 -0
  104. package/src/store/indexeddb.ts +13 -0
  105. package/src/store/memory.ts +14 -1
  106. package/src/store/stub.ts +12 -0
  107. package/src/sync-accumulator.ts +16 -1
  108. package/src/sync.ts +48 -4
  109. package/src/webrtc/call.ts +1 -2
@@ -1 +1 @@
1
- {"version":3,"file":"register.d.ts","sourceRoot":"","sources":["../../src/oidc/register.ts"],"names":[],"mappings":"AAgBA,OAAO,EAAE,KAAK,gBAAgB,EAAE,MAAM,YAAY,CAAC;AAInD,OAAO,EAAE,KAAK,aAAa,EAAE,MAAM,qBAAqB,CAAC;AAEzD;;GA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EAAE,MAAM,CAAC;IACnC,gBAAgB,EAAE,KAAK,GAAG,QAAQ,CAAC;CACtC;AAED;;GAEG;AACH,oBAAY,cAAc;IACtB;;OAEG;IACH,iBAAiB,uBAAuB;IACxC;;OAEG;IACH,YAAY,kBAAkB;IAC9B;;;;;;OAMG;IACH,mBAAmB,iDAAiD;CACvE;AAED;;;;GAIG;AACH,eAAO,MAAM,iBAAiB,EAAE,MAA2C,CAAC;AAW5E;;;;;;;GAOG;AACH,eAAO,MAAM,kBAAkB,GAC3B,qBAAqB,gBAAgB,EACrC,gBAAgB,8BAA8B,KAC/C,OAAO,CAAC,MAAM,CAgEhB,CAAC"}
@@ -83,6 +83,11 @@ export var registerOidcClient = /*#__PURE__*/function () {
83
83
  if (grantTypes.some(scope => !delegatedAuthConfig.grant_types_supported.includes(scope))) {
84
84
  throw new Error(OidcError.DynamicRegistrationNotSupported);
85
85
  }
86
+
87
+ // ask for device authorization grant if supported
88
+ if (delegatedAuthConfig.grant_types_supported.includes(OAuthGrantType.DeviceAuthorization)) {
89
+ grantTypes.push(OAuthGrantType.DeviceAuthorization);
90
+ }
86
91
  var commonBase = new URL(clientMetadata.clientUri);
87
92
 
88
93
  // https://openid.net/specs/openid-connect-registration-1_0.html
@@ -1 +1 @@
1
- {"version":3,"file":"register.js","names":["OidcError","Method","logger","OAuthGrantType","DEVICE_CODE_SCOPE","DeviceAuthorization","urlHasCommonBase","base","urlStr","url","URL","protocol","hostname","endsWith","concat","registerOidcClient","_ref","_asyncToGenerator","delegatedAuthConfig","clientMetadata","registration_endpoint","Error","DynamicRegistrationNotSupported","grantTypes","AuthorizationCode","RefreshToken","some","scope","grant_types_supported","includes","commonBase","clientUri","metadata","client_name","clientName","client_uri","response_types","grant_types","redirect_uris","redirectUris","id_token_signed_response_alg","token_endpoint_auth_method","application_type","applicationType","contacts","logo_uri","logoUri","undefined","policy_uri","policyUri","tos_uri","tosUri","headers","response","fetch","method","Post","body","JSON","stringify","status","DynamicRegistrationFailed","json","clientId","DynamicRegistrationInvalid","error","Object","values","message","_x","_x2","apply","arguments"],"sources":["../../src/oidc/register.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 OidcClientConfig } from \"./index.ts\";\nimport { OidcError } from \"./error.ts\";\nimport { Method } from \"../http-api/index.ts\";\nimport { logger } from \"../logger.ts\";\nimport { type NonEmptyArray } from \"../@types/common.ts\";\n\n/**\n * Client metadata passed to registration endpoint\n */\nexport type OidcRegistrationClientMetadata = {\n clientName: OidcRegistrationRequestBody[\"client_name\"];\n clientUri: OidcRegistrationRequestBody[\"client_uri\"];\n logoUri?: OidcRegistrationRequestBody[\"logo_uri\"];\n applicationType: OidcRegistrationRequestBody[\"application_type\"];\n redirectUris: OidcRegistrationRequestBody[\"redirect_uris\"];\n contacts: OidcRegistrationRequestBody[\"contacts\"];\n tosUri: OidcRegistrationRequestBody[\"tos_uri\"];\n policyUri: OidcRegistrationRequestBody[\"policy_uri\"];\n};\n\n/**\n * Request body for dynamic registration as defined by https://github.com/matrix-org/matrix-spec-proposals/pull/2966\n */\ninterface OidcRegistrationRequestBody {\n client_name?: string;\n client_uri: string;\n logo_uri?: string;\n contacts?: string[];\n tos_uri?: string;\n policy_uri?: string;\n redirect_uris?: NonEmptyArray<string>;\n response_types?: NonEmptyArray<string>;\n grant_types?: NonEmptyArray<string>;\n id_token_signed_response_alg?: string;\n token_endpoint_auth_method: string;\n application_type: \"web\" | \"native\";\n}\n\n/**\n * The OAuth 2.0 grant types that are defined for Matrix in https://spec.matrix.org/v1.17/client-server-api/#grant-types\n */\nexport enum OAuthGrantType {\n /**\n * See https://spec.matrix.org/v1.17/client-server-api/#authorization-code-grant\n */\n AuthorizationCode = \"authorization_code\",\n /**\n * https://spec.matrix.org/v1.17/client-server-api/#refresh-token-grant\n */\n RefreshToken = \"refresh_token\",\n /**\n * The OAuth 2.0 Device Authorization Grant type identifier as per\n * https://www.rfc-editor.org/rfc/rfc8628.html#section-7.2 from\n * [MSC4341](https://github.com/matrix-org/matrix-spec-proposals/pull/4341).\n *\n * @experimental Note that this is UNSTABLE and may have breaking changes without notice.\n */\n DeviceAuthorization = \"urn:ietf:params:oauth:grant-type:device_code\",\n}\n\n/**\n * The name \"scope\" is a misnomer here as it is actually a \"grant type\".\n *\n * @deprecated use `OAuthGrantType.DeviceAuthorization` instead\n */\nexport const DEVICE_CODE_SCOPE: string = OAuthGrantType.DeviceAuthorization;\n\n// Check that URIs have a common base, as per the MSC2966 definition\nconst urlHasCommonBase = (base: URL, urlStr?: string): boolean => {\n if (!urlStr) return false;\n const url = new URL(urlStr);\n if (url.protocol !== base.protocol) return false;\n if (url.hostname !== base.hostname && !url.hostname.endsWith(`.${base.hostname}`)) return false;\n return true;\n};\n\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 delegatedAuthConfig - Auth config from {@link discoverAndValidateOIDCIssuerWellKnown}\n * @param clientMetadata - The metadata for the client which to register\n * @returns Promise<string> resolved with registered clientId\n * @throws when registration is not supported, on failed request or invalid response\n */\nexport const registerOidcClient = async (\n delegatedAuthConfig: OidcClientConfig,\n clientMetadata: OidcRegistrationClientMetadata,\n): Promise<string> => {\n if (!delegatedAuthConfig.registration_endpoint) {\n throw new Error(OidcError.DynamicRegistrationNotSupported);\n }\n\n const grantTypes: NonEmptyArray<string> = [OAuthGrantType.AuthorizationCode, OAuthGrantType.RefreshToken];\n if (grantTypes.some((scope) => !delegatedAuthConfig.grant_types_supported.includes(scope))) {\n throw new Error(OidcError.DynamicRegistrationNotSupported);\n }\n\n const commonBase = new URL(clientMetadata.clientUri);\n\n // https://openid.net/specs/openid-connect-registration-1_0.html\n const metadata: OidcRegistrationRequestBody = {\n client_name: clientMetadata.clientName,\n client_uri: clientMetadata.clientUri,\n response_types: [\"code\"],\n grant_types: grantTypes,\n redirect_uris: clientMetadata.redirectUris,\n id_token_signed_response_alg: \"RS256\",\n token_endpoint_auth_method: \"none\",\n application_type: clientMetadata.applicationType,\n contacts: clientMetadata.contacts,\n logo_uri: urlHasCommonBase(commonBase, clientMetadata.logoUri) ? clientMetadata.logoUri : undefined,\n policy_uri: urlHasCommonBase(commonBase, clientMetadata.policyUri) ? clientMetadata.policyUri : undefined,\n tos_uri: urlHasCommonBase(commonBase, clientMetadata.tosUri) ? clientMetadata.tosUri : undefined,\n };\n\n const headers = {\n \"Accept\": \"application/json\",\n \"Content-Type\": \"application/json\",\n };\n\n try {\n const response = await fetch(delegatedAuthConfig.registration_endpoint, {\n method: Method.Post,\n headers,\n body: JSON.stringify(metadata),\n });\n\n if (response.status >= 400) {\n throw new Error(OidcError.DynamicRegistrationFailed);\n }\n\n const body = await response.json();\n const clientId = body[\"client_id\"];\n if (!clientId || typeof clientId !== \"string\") {\n throw new Error(OidcError.DynamicRegistrationInvalid);\n }\n\n return clientId;\n } catch (error) {\n if (Object.values(OidcError).includes((error as Error).message as OidcError)) {\n throw error;\n } else {\n logger.error(\"Dynamic registration request failed\", error);\n throw new Error(OidcError.DynamicRegistrationFailed);\n }\n }\n};\n"],"mappings":";AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAGA,SAASA,SAAS,QAAQ,YAAY;AACtC,SAASC,MAAM,QAAQ,sBAAsB;AAC7C,SAASC,MAAM,QAAQ,cAAc;;AAGrC;AACA;AACA;;AAYA;AACA;AACA;;AAgBA;AACA;AACA;AACA,WAAYC,cAAc,0BAAdA,cAAc;EACtB;AACJ;AACA;EAHYA,cAAc;EAKtB;AACJ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CAAC,WAAW,CAAC;MAClC,IAAI,CAACM,QAAQ,IAAI,OAAOA,QAAQ,KAAK,QAAQ,EAAE;QAC3C,MAAM,IAAI1C,KAAK,CAACrB,SAAS,CAACgE,0BAA0B,CAAC;MACzD;MAEA,OAAOD,QAAQ;IACnB,CAAC,CAAC,OAAOE,KAAK,EAAE;MACZ,IAAIC,MAAM,CAACC,MAAM,CAACnE,SAAS,CAAC,CAAC6B,QAAQ,CAAEoC,KAAK,CAAWG,OAAoB,CAAC,EAAE;QAC1E,MAAMH,KAAK;MACf,CAAC,MAAM;QACH/D,MAAM,CAAC+D,KAAK,CAAC,qCAAqC,EAAEA,KAAK,CAAC;QAC1D,MAAM,IAAI5C,KAAK,CAACrB,SAAS,CAAC6D,yBAAyB,CAAC;MACxD;IACJ;EACJ,CAAC;EAAA,gBA9DY9C,kBAAkBA,CAAAsD,EAAA,EAAAC,GAAA;IAAA,OAAAtD,IAAA,CAAAuD,KAAA,OAAAC,SAAA;EAAA;AAAA,GA8D9B","ignoreList":[]}
1
+ {"version":3,"file":"register.js","names":["OidcError","Method","logger","OAuthGrantType","DEVICE_CODE_SCOPE","DeviceAuthorization","urlHasCommonBase","base","urlStr","url","URL","protocol","hostname","endsWith","concat","registerOidcClient","_ref","_asyncToGenerator","delegatedAuthConfig","clientMetadata","registration_endpoint","Error","DynamicRegistrationNotSupported","grantTypes","AuthorizationCode","RefreshToken","some","scope","grant_types_supported","includes","push","commonBase","clientUri","metadata","client_name","clientName","client_uri","response_types","grant_types","redirect_uris","redirectUris","id_token_signed_response_alg","token_endpoint_auth_method","application_type","applicationType","contacts","logo_uri","logoUri","undefined","policy_uri","policyUri","tos_uri","tosUri","headers","response","fetch","method","Post","body","JSON","stringify","status","DynamicRegistrationFailed","json","clientId","DynamicRegistrationInvalid","error","Object","values","message","_x","_x2","apply","arguments"],"sources":["../../src/oidc/register.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 OidcClientConfig } from \"./index.ts\";\nimport { OidcError } from \"./error.ts\";\nimport { Method } from \"../http-api/index.ts\";\nimport { logger } from \"../logger.ts\";\nimport { type NonEmptyArray } from \"../@types/common.ts\";\n\n/**\n * Client metadata passed to registration endpoint\n */\nexport type OidcRegistrationClientMetadata = {\n clientName: OidcRegistrationRequestBody[\"client_name\"];\n clientUri: OidcRegistrationRequestBody[\"client_uri\"];\n logoUri?: OidcRegistrationRequestBody[\"logo_uri\"];\n applicationType: OidcRegistrationRequestBody[\"application_type\"];\n redirectUris: OidcRegistrationRequestBody[\"redirect_uris\"];\n contacts: OidcRegistrationRequestBody[\"contacts\"];\n tosUri: OidcRegistrationRequestBody[\"tos_uri\"];\n policyUri: OidcRegistrationRequestBody[\"policy_uri\"];\n};\n\n/**\n * Request body for dynamic registration as defined by https://github.com/matrix-org/matrix-spec-proposals/pull/2966\n */\ninterface OidcRegistrationRequestBody {\n client_name?: string;\n client_uri: string;\n logo_uri?: string;\n contacts?: string[];\n tos_uri?: string;\n policy_uri?: string;\n redirect_uris?: NonEmptyArray<string>;\n response_types?: NonEmptyArray<string>;\n grant_types?: NonEmptyArray<string>;\n id_token_signed_response_alg?: string;\n token_endpoint_auth_method: string;\n application_type: \"web\" | \"native\";\n}\n\n/**\n * The OAuth 2.0 grant types that are defined for Matrix in https://spec.matrix.org/v1.17/client-server-api/#grant-types\n */\nexport enum OAuthGrantType {\n /**\n * See https://spec.matrix.org/v1.17/client-server-api/#authorization-code-grant\n */\n AuthorizationCode = \"authorization_code\",\n /**\n * https://spec.matrix.org/v1.17/client-server-api/#refresh-token-grant\n */\n RefreshToken = \"refresh_token\",\n /**\n * The OAuth 2.0 Device Authorization Grant type identifier as per\n * https://www.rfc-editor.org/rfc/rfc8628.html#section-7.2 from\n * [MSC4341](https://github.com/matrix-org/matrix-spec-proposals/pull/4341).\n *\n * @experimental Note that this is UNSTABLE and may have breaking changes without notice.\n */\n DeviceAuthorization = \"urn:ietf:params:oauth:grant-type:device_code\",\n}\n\n/**\n * The name \"scope\" is a misnomer here as it is actually a \"grant type\".\n *\n * @deprecated use `OAuthGrantType.DeviceAuthorization` instead\n */\nexport const DEVICE_CODE_SCOPE: string = OAuthGrantType.DeviceAuthorization;\n\n// Check that URIs have a common base, as per the MSC2966 definition\nconst urlHasCommonBase = (base: URL, urlStr?: string): boolean => {\n if (!urlStr) return false;\n const url = new URL(urlStr);\n if (url.protocol !== base.protocol) return false;\n if (url.hostname !== base.hostname && !url.hostname.endsWith(`.${base.hostname}`)) return false;\n return true;\n};\n\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 delegatedAuthConfig - Auth config from {@link discoverAndValidateOIDCIssuerWellKnown}\n * @param clientMetadata - The metadata for the client which to register\n * @returns Promise<string> resolved with registered clientId\n * @throws when registration is not supported, on failed request or invalid response\n */\nexport const registerOidcClient = async (\n delegatedAuthConfig: OidcClientConfig,\n clientMetadata: OidcRegistrationClientMetadata,\n): Promise<string> => {\n if (!delegatedAuthConfig.registration_endpoint) {\n throw new Error(OidcError.DynamicRegistrationNotSupported);\n }\n\n const grantTypes: NonEmptyArray<string> = [OAuthGrantType.AuthorizationCode, OAuthGrantType.RefreshToken];\n if (grantTypes.some((scope) => !delegatedAuthConfig.grant_types_supported.includes(scope))) {\n throw new Error(OidcError.DynamicRegistrationNotSupported);\n }\n\n // ask for device authorization grant if supported\n if (delegatedAuthConfig.grant_types_supported.includes(OAuthGrantType.DeviceAuthorization)) {\n grantTypes.push(OAuthGrantType.DeviceAuthorization);\n }\n\n const commonBase = new URL(clientMetadata.clientUri);\n\n // https://openid.net/specs/openid-connect-registration-1_0.html\n const metadata: OidcRegistrationRequestBody = {\n client_name: clientMetadata.clientName,\n client_uri: clientMetadata.clientUri,\n response_types: [\"code\"],\n grant_types: grantTypes,\n redirect_uris: clientMetadata.redirectUris,\n id_token_signed_response_alg: \"RS256\",\n token_endpoint_auth_method: \"none\",\n application_type: clientMetadata.applicationType,\n contacts: clientMetadata.contacts,\n logo_uri: urlHasCommonBase(commonBase, clientMetadata.logoUri) ? clientMetadata.logoUri : undefined,\n policy_uri: urlHasCommonBase(commonBase, clientMetadata.policyUri) ? clientMetadata.policyUri : undefined,\n tos_uri: urlHasCommonBase(commonBase, clientMetadata.tosUri) ? clientMetadata.tosUri : undefined,\n };\n\n const headers = {\n \"Accept\": \"application/json\",\n \"Content-Type\": \"application/json\",\n };\n\n try {\n const response = await fetch(delegatedAuthConfig.registration_endpoint, {\n method: Method.Post,\n headers,\n body: JSON.stringify(metadata),\n });\n\n if (response.status >= 400) {\n throw new Error(OidcError.DynamicRegistrationFailed);\n }\n\n const body = await response.json();\n const clientId = body[\"client_id\"];\n if (!clientId || typeof clientId !== \"string\") {\n throw new Error(OidcError.DynamicRegistrationInvalid);\n }\n\n return clientId;\n } catch (error) {\n if (Object.values(OidcError).includes((error as Error).message as OidcError)) {\n throw error;\n } else {\n logger.error(\"Dynamic registration request failed\", error);\n throw new Error(OidcError.DynamicRegistrationFailed);\n }\n }\n};\n"],"mappings":";AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAGA,SAASA,SAAS,QAAQ,YAAY;AACtC,SAASC,MAAM,QAAQ,sBAAsB;AAC7C,SAASC,MAAM,QAAQ,cAAc;;AAGrC;AACA;AACA;;AAYA;AACA;AACA;;AAgBA;AACA;AACA;AACA,WAAYC,cAAc,0BAAdA,cAAc;EACtB;AACJ;AACA;EAHYA,cAAc;EAKtB;AACJ;AACA;EAPYA,cAAc;EAStB;A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,KAAK,CAACrB,SAAS,CAAC8D,yBAAyB,CAAC;MACxD;MAEA,IAAMJ,IAAI,SAASJ,QAAQ,CAACS,IAAI,CAAC,CAAC;MAClC,IAAMC,QAAQ,GAAGN,IAAI,CAAC,WAAW,CAAC;MAClC,IAAI,CAACM,QAAQ,IAAI,OAAOA,QAAQ,KAAK,QAAQ,EAAE;QAC3C,MAAM,IAAI3C,KAAK,CAACrB,SAAS,CAACiE,0BAA0B,CAAC;MACzD;MAEA,OAAOD,QAAQ;IACnB,CAAC,CAAC,OAAOE,KAAK,EAAE;MACZ,IAAIC,MAAM,CAACC,MAAM,CAACpE,SAAS,CAAC,CAAC6B,QAAQ,CAAEqC,KAAK,CAAWG,OAAoB,CAAC,EAAE;QAC1E,MAAMH,KAAK;MACf,CAAC,MAAM;QACHhE,MAAM,CAACgE,KAAK,CAAC,qCAAqC,EAAEA,KAAK,CAAC;QAC1D,MAAM,IAAI7C,KAAK,CAACrB,SAAS,CAAC8D,yBAAyB,CAAC;MACxD;IACJ;EACJ,CAAC;EAAA,gBAnEY/C,kBAAkBA,CAAAuD,EAAA,EAAAC,GAAA;IAAA,OAAAvD,IAAA,CAAAwD,KAAA,OAAAC,SAAA;EAAA;AAAA,GAmE9B","ignoreList":[]}
@@ -1,6 +1,7 @@
1
1
  import { ClientRendezvousFailureReason, MSC4108FailureReason, type RendezvousFailureListener } from "./index.ts";
2
2
  import { type MatrixClient } from "../client.ts";
3
3
  import { type MSC4108SecureChannel } from "./channels/MSC4108SecureChannel.ts";
4
+ import { type DeviceAccessTokenResponse, type ValidatedAuthMetadata } from "../oidc/index.ts";
4
5
  import { type CryptoApi } from "../crypto-api/index.ts";
5
6
  /**
6
7
  * Enum representing the payload types transmissible over [MSC4108](https://github.com/matrix-org/matrix-spec-proposals/pull/4108)
@@ -40,6 +41,8 @@ export declare class MSC4108SignInWithQR {
40
41
  private readonly ourIntent;
41
42
  private _code?;
42
43
  private expectingNewDeviceId?;
44
+ private metadata?;
45
+ private grantInProgress?;
43
46
  /**
44
47
  * Returns the check code for the secure channel or undefined if not generated yet.
45
48
  */
@@ -79,12 +82,26 @@ export declare class MSC4108SignInWithQR {
79
82
  /**
80
83
  * The second & third step in the OIDC QR login process.
81
84
  * To be called after `negotiateProtocols` for the existing device.
82
- * To be called after OIDC negotiation for the new device. (Currently unsupported)
85
+ * To be called after OIDC negotiation for the new device.
86
+ *
87
+ * @param input - Required for the new device to start the device authorization grant, not required for the existing device reciprocating the login
83
88
  */
84
- deviceAuthorizationGrant(): Promise<{
89
+ deviceAuthorizationGrant(input?: {
90
+ metadata: ValidatedAuthMetadata;
91
+ clientId: string;
92
+ deviceId: string;
93
+ }): Promise<{
85
94
  verificationUri?: string;
86
95
  userCode?: string;
87
96
  }>;
97
+ /**
98
+ * The fourth step in the OIDC QR login process.
99
+ * The reciprocating device must perform step 5 for this method to resolve.
100
+ * To be called after {@link deviceAuthorizationGrant} only on the new device.
101
+ */
102
+ completeLoginOnNewDevice({ clientId, }: {
103
+ clientId: string;
104
+ }): Promise<DeviceAccessTokenResponse | undefined>;
88
105
  /**
89
106
  * The fifth (and final) step in the OIDC QR login process.
90
107
  * To be called after the new device has completed authentication.
@@ -1 +1 @@
1
- {"version":3,"file":"MSC4108SignInWithQR.d.ts","sourceRoot":"","sources":["../../src/rendezvous/MSC4108SignInWithQR.ts"],"names":[],"mappings":"AAkBA,OAAO,EACH,6BAA6B,EAC7B,oBAAoB,EAEpB,KAAK,yBAAyB,EACjC,MAAM,YAAY,CAAC;AACpB,OAAO,EAAE,KAAK,YAAY,EAAE,MAAM,cAAc,CAAC;AAEjD,OAAO,EAAE,KAAK,oBAAoB,EAAE,MAAM,oCAAoC,CAAC;AAI/E,OAAO,EAAE,KAAK,SAAS,EAAE,MAAM,wBAAwB,CAAC;AAExD;;;;GAIG;AACH,oBAAY,WAAW;IACnB,SAAS,sBAAsB;IAC/B,QAAQ,qBAAqB;IAC7B,OAAO,oBAAoB;IAC3B,OAAO,oBAAoB;IAC3B,O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;;;;OAIG;IACU,wBAAwB,CAAC,EAClC,QAAQ,GACX,EAAE;QACC,QAAQ,EAAE,MAAM,CAAC;KACpB,GAAG,OAAO,CAAC,yBAAyB,GAAG,SAAS,CAAC;IAsDlD;;;OAGG;IACU,YAAY,IAAI,OAAO,CAAC;QAAE,OAAO,CAAC,EAAE,IAAI,CAAC,cAAc,EAAE,MAAM,CAAC,CAAA;KAAE,CAAC;YAyFlE,OAAO;YAIP,IAAI;IAIlB;;OAEG;IACU,4BAA4B,IAAI,OAAO,CAAC,IAAI,CAAC;IAU1D;;;OAGG;IACU,MAAM,CAAC,MAAM,EAAE,oBAAoB,GAAG,6BAA6B,GAAG,OAAO,CAAC,IAAI,CAAC;IAKhG;;OAEG;IACU,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC;CAGtC"}
@@ -23,7 +23,7 @@ import { ClientRendezvousFailureReason, MSC4108FailureReason, RendezvousError }
23
23
  import { logger } from "../logger.js";
24
24
  import { MatrixError } from "../http-api/index.js";
25
25
  import { sleep } from "../utils.js";
26
- import { OAuthGrantType } from "../oidc/index.js";
26
+ import { generateScope, OAuthGrantType, startDeviceAuthorization, waitForDeviceAuthorization } from "../oidc/index.js";
27
27
  /**
28
28
  * Enum representing the payload types transmissible over [MSC4108](https://github.com/matrix-org/matrix-spec-proposals/pull/4108)
29
29
  * secure channels.
@@ -77,6 +77,8 @@ export class MSC4108SignInWithQR {
77
77
  _defineProperty(this, "ourIntent", void 0);
78
78
  _defineProperty(this, "_code", void 0);
79
79
  _defineProperty(this, "expectingNewDeviceId", void 0);
80
+ _defineProperty(this, "metadata", void 0);
81
+ _defineProperty(this, "grantInProgress", void 0);
80
82
  this.ourIntent = client ? QrCodeIntent.Reciprocate : QrCodeIntent.Login;
81
83
  }
82
84
 
@@ -184,13 +186,47 @@ export class MSC4108SignInWithQR {
184
186
  /**
185
187
  * The second & third step in the OIDC QR login process.
186
188
  * To be called after `negotiateProtocols` for the existing device.
187
- * To be called after OIDC negotiation for the new device. (Currently unsupported)
189
+ * To be called after OIDC negotiation for the new device.
190
+ *
191
+ * @param input - Required for the new device to start the device authorization grant, not required for the existing device reciprocating the login
188
192
  */
189
- deviceAuthorizationGrant() {
193
+ deviceAuthorizationGrant(input) {
190
194
  var _this3 = this;
191
195
  return _asyncToGenerator(function* () {
192
196
  if (_this3.isNewDevice) {
193
- throw new Error("New device flows around OIDC are not yet implemented");
197
+ var _dagResponse$verifica;
198
+ if (!input) {
199
+ throw new Error("Input must be provided for new device");
200
+ }
201
+ var {
202
+ metadata,
203
+ clientId,
204
+ deviceId
205
+ } = input;
206
+ var scope = generateScope(deviceId);
207
+
208
+ // MSC4108-Flow: NewDevice - start device authorization grant
209
+ var dagResponse = yield startDeviceAuthorization({
210
+ clientId,
211
+ scope,
212
+ metadata
213
+ });
214
+ _this3.metadata = metadata;
215
+ _this3.grantInProgress = dagResponse;
216
+ var protocol = {
217
+ type: PayloadType.Protocol,
218
+ protocol: "device_authorization_grant",
219
+ device_id: deviceId,
220
+ device_authorization_grant: {
221
+ verification_uri: dagResponse.verification_uri,
222
+ verification_uri_complete: dagResponse.verification_uri_complete
223
+ }
224
+ };
225
+ yield _this3.send(protocol);
226
+ return {
227
+ verificationUri: (_dagResponse$verifica = dagResponse.verification_uri_complete) !== null && _dagResponse$verifica !== void 0 ? _dagResponse$verifica : dagResponse.verification_uri,
228
+ userCode: dagResponse.user_code
229
+ };
194
230
  } else {
195
231
  // The user needs to do step 7 for the out-of-band confirmation
196
232
  // but, first we receive the protocol chosen by the other device so that
@@ -246,25 +282,79 @@ export class MSC4108SignInWithQR {
246
282
  })();
247
283
  }
248
284
 
285
+ /**
286
+ * The fourth step in the OIDC QR login process.
287
+ * The reciprocating device must perform step 5 for this method to resolve.
288
+ * To be called after {@link deviceAuthorizationGrant} only on the new device.
289
+ */
290
+ completeLoginOnNewDevice(_ref) {
291
+ var _this4 = this;
292
+ return _asyncToGenerator(function* () {
293
+ var {
294
+ clientId
295
+ } = _ref;
296
+ if (!_this4.isNewDevice || !_this4.grantInProgress || !_this4.metadata) {
297
+ throw new Error("Can only complete login on new device");
298
+ }
299
+ logger.info("Waiting for protocol accepted message");
300
+ // wait for accepted message
301
+ var payload = yield _this4.receive();
302
+ if (!payload) {
303
+ throw new RendezvousError("No response from existing device", MSC4108FailureReason.UnexpectedMessageReceived);
304
+ }
305
+ if (payload.type === PayloadType.Failure) {
306
+ throw new RendezvousError("Failed", payload.reason);
307
+ }
308
+ if (payload.type !== PayloadType.ProtocolAccepted) {
309
+ throw new RendezvousError("Unexpected message received", MSC4108FailureReason.UnexpectedMessageReceived);
310
+ }
311
+
312
+ // poll for DAG
313
+ var res = yield waitForDeviceAuthorization({
314
+ session: _this4.grantInProgress,
315
+ metadata: _this4.metadata,
316
+ clientId
317
+ });
318
+ if (!res) {
319
+ throw new RendezvousError("No response from device authorization endpoint", ClientRendezvousFailureReason.Unknown);
320
+ }
321
+ if ("error" in res) {
322
+ var reason = MSC4108FailureReason.UnexpectedMessageReceived;
323
+ if (res.error === "expired_token") {
324
+ reason = MSC4108FailureReason.AuthorizationExpired;
325
+ } else if (res.error === "access_denied") {
326
+ reason = MSC4108FailureReason.UserCancelled;
327
+ }
328
+ var _payload = {
329
+ type: PayloadType.Failure,
330
+ reason
331
+ };
332
+ yield _this4.send(_payload);
333
+ return undefined;
334
+ }
335
+ return res;
336
+ })();
337
+ }
338
+
249
339
  /**
250
340
  * The fifth (and final) step in the OIDC QR login process.
251
341
  * To be called after the new device has completed authentication.
252
342
  */
253
343
  shareSecrets() {
254
- var _this4 = this;
344
+ var _this5 = this;
255
345
  return _asyncToGenerator(function* () {
256
- if (_this4.isNewDevice) {
257
- yield _this4.send({
346
+ if (_this5.isNewDevice) {
347
+ yield _this5.send({
258
348
  type: PayloadType.Success
259
349
  });
260
350
  // then wait for secrets
261
351
  logger.info("Waiting for secrets message");
262
- var payload = yield _this4.receive();
352
+ var payload = yield _this5.receive();
263
353
  if ((payload === null || payload === void 0 ? void 0 : payload.type) === PayloadType.Failure) {
264
354
  throw new RendezvousError("Failed", payload.reason);
265
355
  }
266
356
  if ((payload === null || payload === void 0 ? void 0 : payload.type) !== PayloadType.Secrets) {
267
- yield _this4.send({
357
+ yield _this5.send({
268
358
  type: PayloadType.Failure,
269
359
  reason: MSC4108FailureReason.UnexpectedMessageReceived
270
360
  });
@@ -275,22 +365,22 @@ export class MSC4108SignInWithQR {
275
365
  };
276
366
  // then done?
277
367
  } else {
278
- if (!_this4.expectingNewDeviceId) {
368
+ if (!_this5.expectingNewDeviceId) {
279
369
  throw new Error("No new device ID expected");
280
370
  }
281
- yield _this4.send({
371
+ yield _this5.send({
282
372
  type: PayloadType.ProtocolAccepted
283
373
  });
284
374
  logger.info("Waiting for outcome message");
285
- var _payload = yield _this4.receive();
286
- if ((_payload === null || _payload === void 0 ? void 0 : _payload.type) === PayloadType.Failure) {
287
- throw new RendezvousError("Failed", _payload.reason);
375
+ var _payload2 = yield _this5.receive();
376
+ if ((_payload2 === null || _payload2 === void 0 ? void 0 : _payload2.type) === PayloadType.Failure) {
377
+ throw new RendezvousError("Failed", _payload2.reason);
288
378
  }
289
- if ((_payload === null || _payload === void 0 ? void 0 : _payload.type) === PayloadType.Declined) {
379
+ if ((_payload2 === null || _payload2 === void 0 ? void 0 : _payload2.type) === PayloadType.Declined) {
290
380
  throw new RendezvousError("User declined", ClientRendezvousFailureReason.UserDeclined);
291
381
  }
292
- if ((_payload === null || _payload === void 0 ? void 0 : _payload.type) !== PayloadType.Success) {
293
- yield _this4.send({
382
+ if ((_payload2 === null || _payload2 === void 0 ? void 0 : _payload2.type) !== PayloadType.Success) {
383
+ yield _this5.send({
294
384
  type: PayloadType.Failure,
295
385
  reason: MSC4108FailureReason.UnexpectedMessageReceived
296
386
  });
@@ -300,16 +390,16 @@ export class MSC4108SignInWithQR {
300
390
  do {
301
391
  // is the device visible via the Homeserver?
302
392
  try {
303
- var _this4$client;
304
- var device = yield (_this4$client = _this4.client) === null || _this4$client === void 0 ? void 0 : _this4$client.getDevice(_this4.expectingNewDeviceId);
393
+ var _this5$client;
394
+ var device = yield (_this5$client = _this5.client) === null || _this5$client === void 0 ? void 0 : _this5$client.getDevice(_this5.expectingNewDeviceId);
305
395
  if (device) {
306
396
  // if so, return the secrets
307
- var secretsBundle = yield _this4.client.getCrypto().exportSecretsBundle();
308
- if (_this4.channel.cancelled) {
397
+ var secretsBundle = yield _this5.client.getCrypto().exportSecretsBundle();
398
+ if (_this5.channel.cancelled) {
309
399
  throw new RendezvousError("User cancelled", MSC4108FailureReason.UserCancelled);
310
400
  }
311
401
  // send secrets
312
- yield _this4.send(_objectSpread({
402
+ yield _this5.send(_objectSpread({
313
403
  type: PayloadType.Secrets
314
404
  }, secretsBundle));
315
405
  return {
@@ -326,7 +416,7 @@ export class MSC4108SignInWithQR {
326
416
  }
327
417
  yield sleep(1000);
328
418
  } while (Date.now() < timeout);
329
- yield _this4.send({
419
+ yield _this5.send({
330
420
  type: PayloadType.Failure,
331
421
  reason: MSC4108FailureReason.DeviceNotFound
332
422
  });
@@ -335,15 +425,15 @@ export class MSC4108SignInWithQR {
335
425
  })();
336
426
  }
337
427
  receive() {
338
- var _this5 = this;
428
+ var _this6 = this;
339
429
  return _asyncToGenerator(function* () {
340
- return yield _this5.channel.secureReceive();
430
+ return yield _this6.channel.secureReceive();
341
431
  })();
342
432
  }
343
433
  send(payload) {
344
- var _this6 = this;
434
+ var _this7 = this;
345
435
  return _asyncToGenerator(function* () {
346
- yield _this6.channel.secureSend(payload);
436
+ yield _this7.channel.secureSend(payload);
347
437
  })();
348
438
  }
349
439
 
@@ -351,12 +441,12 @@ export class MSC4108SignInWithQR {
351
441
  * Decline the login on the existing device.
352
442
  */
353
443
  declineLoginOnExistingDevice() {
354
- var _this7 = this;
444
+ var _this8 = this;
355
445
  return _asyncToGenerator(function* () {
356
- if (!_this7.isExistingDevice) {
446
+ if (!_this8.isExistingDevice) {
357
447
  throw new Error("Can only decline login on existing device");
358
448
  }
359
- yield _this7.send({
449
+ yield _this8.send({
360
450
  type: PayloadType.Failure,
361
451
  reason: MSC4108FailureReason.UserCancelled
362
452
  });
@@ -368,11 +458,11 @@ export class MSC4108SignInWithQR {
368
458
  * @param reason the reason for the cancellation
369
459
  */
370
460
  cancel(reason) {
371
- var _this8 = this;
461
+ var _this9 = this;
372
462
  return _asyncToGenerator(function* () {
373
- var _this8$onFailure;
374
- (_this8$onFailure = _this8.onFailure) === null || _this8$onFailure === void 0 || _this8$onFailure.call(_this8, reason);
375
- yield _this8.channel.cancel(reason);
463
+ var _this9$onFailure;
464
+ (_this9$onFailure = _this9.onFailure) === null || _this9$onFailure === void 0 || _this9$onFailure.call(_this9, reason);
465
+ yield _this9.channel.cancel(reason);
376
466
  })();
377
467
  }
378
468
 
@@ -380,9 +470,9 @@ export class MSC4108SignInWithQR {
380
470
  * Closes the rendezvous session.
381
471
  */
382
472
  close() {
383
- var _this9 = this;
473
+ var _this0 = this;
384
474
  return _asyncToGenerator(function* () {
385
- yield _this9.channel.close();
475
+ yield _this0.channel.close();
386
476
  })();
387
477
  }
388
478
  }
@@ -1 +1 @@
1
- {"version":3,"file":"MSC4108SignInWithQR.js","names":["QrCodeIntent","ClientRendezvousFailureReason","MSC4108FailureReason","RendezvousError","logger","MatrixError","sleep","OAuthGrantType","PayloadType","isDeviceAuthorizationGrantProtocolPayload","payload","protocol","MSC4108SignInWithQR","checkCode","_this$channel","channel","getCheckCode","constructor","didScanCode","client","onFailure","_defineProperty","ourIntent","Reciprocate","Login","code","_code","generateCode","_this","_asyncToGenerator","getDomain","isExistingDevice","isNewDevice","negotiateProtocols","_this2","info","concat","connect","_oidcClientConfig","oidcClientConfig","getAuthMetadata","e","error","grant_types_supported","includes","DeviceAuthorization","send","type","Protocols","protocols","homeserver","Failure","reason","UnsupportedProtocol","receive","UnexpectedMessageReceived","serverName","deviceAuthorizationGrant","_this3","Error","Protocol","device_authorization_grant","dag","device_id","expectingNewDeviceId","verification_uri","verificationUri","verification_uri_complete","verificationUriComplete","deviceAlreadyExists","_this3$client","getDevice","err","httpStatus","DeviceAlreadyExists","shareSecrets","_this4","Success","Secrets","secrets","ProtocolAccepted","Declined","UserDeclined","timeout","Date","now","_this4$client","device","secretsBundle","getCrypto","exportSecretsBundle","cancelled","UserCancelled","_objectSpread","DeviceNotFound","_this5","secureReceive","_this6","secureSend","declineLoginOnExistingDevice","_this7","cancel","_this8","_this8$onFailure","call","close","_this9"],"sources":["../../src/rendezvous/MSC4108SignInWithQR.ts"],"sourcesContent":["/*\nCopyright 2024 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { QrCodeIntent } from \"@matrix-org/matrix-sdk-crypto-wasm\";\n\nimport {\n ClientRendezvousFailureReason,\n MSC4108FailureReason,\n RendezvousError,\n type RendezvousFailureListener,\n} from \"./index.ts\";\nimport { type MatrixClient } from \"../client.ts\";\nimport { logger } from \"../logger.ts\";\nimport { type MSC4108SecureChannel } from \"./channels/MSC4108SecureChannel.ts\";\nimport { MatrixError } from \"../http-api/index.ts\";\nimport { sleep } from \"../utils.ts\";\nimport { OAuthGrantType, type OidcClientConfig } from \"../oidc/index.ts\";\nimport { type CryptoApi } from \"../crypto-api/index.ts\";\n\n/**\n * Enum representing the payload types transmissible over [MSC4108](https://github.com/matrix-org/matrix-spec-proposals/pull/4108)\n * secure channels.\n * @experimental Note that this is UNSTABLE and may have breaking changes without notice.\n */\nexport enum PayloadType {\n Protocols = \"m.login.protocols\",\n Protocol = \"m.login.protocol\",\n Failure = \"m.login.failure\",\n Success = \"m.login.success\",\n Secrets = \"m.login.secrets\",\n ProtocolAccepted = \"m.login.protocol_accepted\",\n Declined = \"m.login.declined\",\n}\n\n/**\n * Type representing the base payload format for [MSC4108](https://github.com/matrix-org/matrix-spec-proposals/pull/4108)\n * messages sent over the secure channel.\n * @experimental Note that this is UNSTABLE and may have breaking changes without notice.\n */\nexport interface MSC4108Payload {\n type: PayloadType;\n}\n\ninterface ProtocolsPayload extends MSC4108Payload {\n type: PayloadType.Protocols;\n protocols: string[];\n homeserver: string;\n}\n\ninterface ProtocolPayload extends MSC4108Payload {\n type: PayloadType.Protocol;\n protocol: Exclude<string, \"device_authorization_grant\">;\n device_id: string;\n}\n\ninterface DeviceAuthorizationGrantProtocolPayload extends ProtocolPayload {\n protocol: \"device_authorization_grant\";\n device_authorization_grant: {\n verification_uri: string;\n verification_uri_complete?: string;\n };\n}\n\nfunction isDeviceAuthorizationGrantProtocolPayload(\n payload: ProtocolPayload,\n): payload is DeviceAuthorizationGrantProtocolPayload {\n return payload.protocol === \"device_authorization_grant\";\n}\n\ninterface FailurePayload extends MSC4108Payload {\n type: PayloadType.Failure;\n reason: MSC4108FailureReason;\n homeserver?: string;\n}\n\ninterface DeclinedPayload extends MSC4108Payload {\n type: PayloadType.Declined;\n}\n\ninterface SuccessPayload extends MSC4108Payload {\n type: PayloadType.Success;\n}\n\ninterface AcceptedPayload extends MSC4108Payload {\n type: PayloadType.ProtocolAccepted;\n}\n\ninterface SecretsPayload extends MSC4108Payload, Awaited<ReturnType<NonNullable<CryptoApi[\"exportSecretsBundle\"]>>> {\n type: PayloadType.Secrets;\n}\n\n/**\n * Prototype of the unstable [MSC4108](https://github.com/matrix-org/matrix-spec-proposals/pull/4108)\n * sign in with QR + OIDC flow.\n * @experimental Note that this is UNSTABLE and may have breaking changes without notice.\n */\nexport class MSC4108SignInWithQR {\n private readonly ourIntent: QrCodeIntent;\n private _code?: Uint8Array;\n private expectingNewDeviceId?: string;\n\n /**\n * Returns the check code for the secure channel or undefined if not generated yet.\n */\n public get checkCode(): string | undefined {\n return this.channel?.getCheckCode();\n }\n\n /**\n * @param channel - The secure channel used for communication\n * @param client - The Matrix client in used on the device already logged in\n * @param didScanCode - Whether this side of the channel scanned the QR code from the other party\n * @param onFailure - Callback for when the rendezvous fails\n */\n public constructor(\n private readonly channel: MSC4108SecureChannel,\n private readonly didScanCode: boolean,\n private readonly client?: MatrixClient,\n public onFailure?: RendezvousFailureListener,\n ) {\n this.ourIntent = client ? QrCodeIntent.Reciprocate : QrCodeIntent.Login;\n }\n\n /**\n * Returns the code representing the rendezvous suitable for rendering in a QR code or undefined if not generated yet.\n */\n public get code(): Uint8Array | undefined {\n return this._code;\n }\n\n /**\n * Generate the code including doing partial set up of the channel where required.\n */\n public async generateCode(): Promise<void> {\n if (this._code) {\n return;\n }\n\n if (this.ourIntent === QrCodeIntent.Reciprocate && this.client) {\n this._code = await this.channel.generateCode(this.ourIntent, this.client.getDomain()!);\n } else if (this.ourIntent === QrCodeIntent.Login) {\n this._code = await this.channel.generateCode(this.ourIntent);\n }\n }\n\n /**\n * Returns true if the device is the already logged in device reciprocating a new login on the other side of the channel.\n */\n public get isExistingDevice(): boolean {\n return this.ourIntent === QrCodeIntent.Reciprocate;\n }\n\n /**\n * Returns true if the device is the new device logging in being reciprocated by the device on the other side of the channel.\n */\n public get isNewDevice(): boolean {\n return !this.isExistingDevice;\n }\n\n /**\n * The first step in the OIDC QR login process.\n * To be called after the QR code has been rendered or scanned.\n * The scanning device has to discover the homeserver details, if they scanned the code then they already have it.\n * If the new device is the one rendering the QR code then it has to wait be sent the homeserver details via the rendezvous channel.\n */\n public async negotiateProtocols(): Promise<{ serverName?: string }> {\n logger.info(`negotiateProtocols(isNewDevice=${this.isNewDevice} didScanCode=${this.didScanCode})`);\n await this.channel.connect();\n\n if (this.didScanCode) {\n // Secure Channel step 6 completed, we trust the channel\n\n if (this.isNewDevice) {\n // MSC4108-Flow: ExistingScanned - take homeserver from QR code which should already be set\n } else {\n // MSC4108-Flow: NewScanned -send protocols message\n let oidcClientConfig: OidcClientConfig | undefined;\n try {\n oidcClientConfig = await this.client!.getAuthMetadata();\n } catch (e) {\n logger.error(\"Failed to discover OIDC metadata\", e);\n }\n\n if (oidcClientConfig?.grant_types_supported.includes(OAuthGrantType.DeviceAuthorization)) {\n await this.send<ProtocolsPayload>({\n type: PayloadType.Protocols,\n protocols: [\"device_authorization_grant\"],\n homeserver: this.client!.getDomain()!,\n });\n } else {\n await this.send<FailurePayload>({\n type: PayloadType.Failure,\n reason: MSC4108FailureReason.UnsupportedProtocol,\n });\n throw new RendezvousError(\n \"Device code grant unsupported\",\n MSC4108FailureReason.UnsupportedProtocol,\n );\n }\n }\n } else if (this.isNewDevice) {\n // MSC4108-Flow: ExistingScanned - wait for protocols message\n logger.info(\"Waiting for protocols message\");\n const payload = await this.receive<ProtocolsPayload>();\n\n if (payload?.type === PayloadType.Failure) {\n throw new RendezvousError(\"Failed\", payload.reason);\n }\n\n if (payload?.type !== PayloadType.Protocols) {\n await this.send<FailurePayload>({\n type: PayloadType.Failure,\n reason: MSC4108FailureReason.UnexpectedMessageReceived,\n });\n throw new RendezvousError(\n \"Unexpected message received\",\n MSC4108FailureReason.UnexpectedMessageReceived,\n );\n }\n\n return { serverName: payload.homeserver };\n } else {\n // MSC4108-Flow: NewScanned - nothing to do\n }\n return {};\n }\n\n /**\n * The second & third step in the OIDC QR login process.\n * To be called after `negotiateProtocols` for the existing device.\n * To be called after OIDC negotiation for the new device. (Currently unsupported)\n */\n public async deviceAuthorizationGrant(): Promise<{\n verificationUri?: string;\n userCode?: string;\n }> {\n if (this.isNewDevice) {\n throw new Error(\"New device flows around OIDC are not yet implemented\");\n } else {\n // The user needs to do step 7 for the out-of-band confirmation\n // but, first we receive the protocol chosen by the other device so that\n // the confirmation_uri is ready to go\n logger.info(\"Waiting for protocol message\");\n const payload = await this.receive<ProtocolPayload | DeviceAuthorizationGrantProtocolPayload>();\n\n if (payload?.type === PayloadType.Failure) {\n throw new RendezvousError(\"Failed\", payload.reason);\n }\n\n if (payload?.type !== PayloadType.Protocol) {\n await this.send<FailurePayload>({\n type: PayloadType.Failure,\n reason: MSC4108FailureReason.UnexpectedMessageReceived,\n });\n throw new RendezvousError(\n \"Unexpected message received\",\n MSC4108FailureReason.UnexpectedMessageReceived,\n );\n }\n\n if (isDeviceAuthorizationGrantProtocolPayload(payload)) {\n const { device_authorization_grant: dag, device_id: expectingNewDeviceId } = payload;\n const { verification_uri: verificationUri, verification_uri_complete: verificationUriComplete } = dag;\n\n let deviceAlreadyExists = true;\n try {\n await this.client?.getDevice(expectingNewDeviceId);\n } catch (err: MatrixError | unknown) {\n if (err instanceof MatrixError && err.httpStatus === 404) {\n deviceAlreadyExists = false;\n }\n }\n\n if (deviceAlreadyExists) {\n await this.send<FailurePayload>({\n type: PayloadType.Failure,\n reason: MSC4108FailureReason.DeviceAlreadyExists,\n });\n throw new RendezvousError(\n \"Specified device ID already exists\",\n MSC4108FailureReason.DeviceAlreadyExists,\n );\n }\n\n this.expectingNewDeviceId = expectingNewDeviceId;\n\n return { verificationUri: verificationUriComplete ?? verificationUri };\n }\n\n await this.send<FailurePayload>({\n type: PayloadType.Failure,\n reason: MSC4108FailureReason.UnsupportedProtocol,\n });\n throw new RendezvousError(\n \"Received a request for an unsupported protocol\",\n MSC4108FailureReason.UnsupportedProtocol,\n );\n }\n }\n\n /**\n * The fifth (and final) step in the OIDC QR login process.\n * To be called after the new device has completed authentication.\n */\n public async shareSecrets(): Promise<{ secrets?: Omit<SecretsPayload, \"type\"> }> {\n if (this.isNewDevice) {\n await this.send<SuccessPayload>({\n type: PayloadType.Success,\n });\n // then wait for secrets\n logger.info(\"Waiting for secrets message\");\n const payload = await this.receive<SecretsPayload>();\n if (payload?.type === PayloadType.Failure) {\n throw new RendezvousError(\"Failed\", payload.reason);\n }\n\n if (payload?.type !== PayloadType.Secrets) {\n await this.send<FailurePayload>({\n type: PayloadType.Failure,\n reason: MSC4108FailureReason.UnexpectedMessageReceived,\n });\n throw new RendezvousError(\n \"Unexpected message received\",\n MSC4108FailureReason.UnexpectedMessageReceived,\n );\n }\n return { secrets: payload };\n // then done?\n } else {\n if (!this.expectingNewDeviceId) {\n throw new Error(\"No new device ID expected\");\n }\n await this.send<AcceptedPayload>({\n type: PayloadType.ProtocolAccepted,\n });\n\n logger.info(\"Waiting for outcome message\");\n const payload = await this.receive<SuccessPayload | DeclinedPayload>();\n\n if (payload?.type === PayloadType.Failure) {\n throw new RendezvousError(\"Failed\", payload.reason);\n }\n\n if (payload?.type === PayloadType.Declined) {\n throw new RendezvousError(\"User declined\", ClientRendezvousFailureReason.UserDeclined);\n }\n\n if (payload?.type !== PayloadType.Success) {\n await this.send<FailurePayload>({\n type: PayloadType.Failure,\n reason: MSC4108FailureReason.UnexpectedMessageReceived,\n });\n throw new RendezvousError(\"Unexpected message\", MSC4108FailureReason.UnexpectedMessageReceived);\n }\n\n const timeout = Date.now() + 10000; // wait up to 10 seconds\n do {\n // is the device visible via the Homeserver?\n try {\n const device = await this.client?.getDevice(this.expectingNewDeviceId);\n\n if (device) {\n // if so, return the secrets\n const secretsBundle = await this.client!.getCrypto()!.exportSecretsBundle!();\n if (this.channel.cancelled) {\n throw new RendezvousError(\"User cancelled\", MSC4108FailureReason.UserCancelled);\n }\n // send secrets\n await this.send<SecretsPayload>({\n type: PayloadType.Secrets,\n ...secretsBundle,\n });\n return { secrets: secretsBundle };\n // let the other side close the rendezvous session\n }\n } catch (err: MatrixError | unknown) {\n if (err instanceof MatrixError && err.httpStatus === 404) {\n // not found, so keep waiting until timeout\n } else {\n throw err;\n }\n }\n await sleep(1000);\n } while (Date.now() < timeout);\n\n await this.send<FailurePayload>({\n type: PayloadType.Failure,\n reason: MSC4108FailureReason.DeviceNotFound,\n });\n throw new RendezvousError(\"New device not found\", MSC4108FailureReason.DeviceNotFound);\n }\n }\n\n private async receive<T extends MSC4108Payload>(): Promise<T | FailurePayload | undefined> {\n return (await this.channel.secureReceive()) as T | undefined;\n }\n\n private async send<T extends MSC4108Payload>(payload: T): Promise<void> {\n await this.channel.secureSend(payload);\n }\n\n /**\n * Decline the login on the existing device.\n */\n public async declineLoginOnExistingDevice(): Promise<void> {\n if (!this.isExistingDevice) {\n throw new Error(\"Can only decline login on existing device\");\n }\n await this.send<FailurePayload>({\n type: PayloadType.Failure,\n reason: MSC4108FailureReason.UserCancelled,\n });\n }\n\n /**\n * Cancels the rendezvous session.\n * @param reason the reason for the cancellation\n */\n public async cancel(reason: MSC4108FailureReason | ClientRendezvousFailureReason): Promise<void> {\n this.onFailure?.(reason);\n await this.channel.cancel(reason);\n }\n\n /**\n * Closes the rendezvous session.\n */\n public async close(): Promise<void> {\n await this.channel.close();\n }\n}\n"],"mappings":";;;;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA,SAASA,YAAY,QAAQ,oCAAoC;AAEjE,SACIC,6BAA6B,EAC7BC,oBAAoB,EACpBC,eAAe,QAEZ,YAAY;AAEnB,SAASC,MAAM,QAAQ,cAAc;AAErC,SAASC,WAAW,QAAQ,sBAAsB;AAClD,SAASC,KAAK,QAAQ,aAAa;AACnC,SAASC,cAAc,QAA+B,kBAAkB;AAGxE;AACA;AACA;AACA;AACA;AACA,WAAYC,WAAW,0BAAXA,WAAW;EAAXA,WAAW;EAAXA,WAAW;EAAXA,WAAW;EAAXA,WAAW;EAAXA,WAAW;EAAXA,WAAW;EAAXA,WAAW;EAAA,OAAXA,WAAW;AAAA;;AAUvB;AACA;AACA;AACA;AACA;;AAyBA,SAASC,yCAAyCA,CAC9CC,OAAwB,EAC0B;EAClD,OAAOA,OAAO,CAACC,QAAQ,KAAK,4BAA4B;AAC5D;AAwBA;AACA;AACA;AACA;AACA;AACA,OAAO,MAAMC,mBAAmB,CAAC;EAK7B;AACJ;AACA;EACI,IAAWC,SAASA,CAAA,EAAuB;IAAA,IAAAC,aAAA;IACvC,QAAAA,aAAA,GAAO,IAAI,CAACC,OAAO,cAAAD,aAAA,uBAAZA,aAAA,CAAcE,YAAY,CAAC,CAA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AAI,CAAClF,OAAO,CAACmF,UAAU,CAACxF,OAAO,CAAC;IAAC;EAC3C;;EAEA;AACJ;AACA;EACiByF,4BAA4BA,CAAA,EAAkB;IAAA,IAAAC,MAAA;IAAA,OAAAvE,iBAAA;MACvD,IAAI,CAACuE,MAAI,CAACrE,gBAAgB,EAAE;QACxB,MAAM,IAAI4B,KAAK,CAAC,2CAA2C,CAAC;MAChE;MACA,MAAMyC,MAAI,CAACtD,IAAI,CAAiB;QAC5BC,IAAI,EAAEvC,WAAW,CAAC2C,OAAO;QACzBC,MAAM,EAAElD,oBAAoB,CAAC0F;MACjC,CAAC,CAAC;IAAC;EACP;;EAEA;AACJ;AACA;AACA;EACiBS,MAAMA,CAACjD,MAA4D,EAAiB;IAAA,IAAAkD,MAAA;IAAA,OAAAzE,iBAAA;MAAA,IAAA0E,gBAAA;MAC7F,CAAAA,gBAAA,GAAAD,MAAI,CAAClF,SAAS,cAAAmF,gBAAA,eAAdA,gBAAA,CAAAC,IAAA,CAAAF,MAAI,EAAalD,MAAM,CAAC;MACxB,MAAMkD,MAAI,CAACvF,OAAO,CAACsF,MAAM,CAACjD,MAAM,CAAC;IAAC;EACtC;;EAEA;AACJ;AACA;EACiBqD,KAAKA,CAAA,EAAkB;IAAA,IAAAC,MAAA;IAAA,OAAA7E,iBAAA;MAChC,MAAM6E,MAAI,CAAC3F,OAAO,CAAC0F,KAAK,CAAC,CAAC;IAAC;EAC/B;AACJ","ignoreList":[]}
1
+ {"version":3,"file":"MSC4108SignInWithQR.js","names":["QrCodeIntent","ClientRendezvousFailureReason","MSC4108FailureReason","RendezvousError","logger","MatrixError","sleep","generateScope","OAuthGrantType","startDeviceAuthorization","waitForDeviceAuthorization","PayloadType","isDeviceAuthorizationGrantProtocolPayload","payload","protocol","MSC4108SignInWithQR","checkCode","_this$channel","channel","getCheckCode","constructor","didScanCode","client","onFailure","_defineProperty","ourIntent","Reciprocate","Login","code","_code","generateCode","_this","_asyncToGenerator","getDomain","isExistingDevice","isNewDevice","negotiateProtocols","_this2","info","concat","connect","_oidcClientConfig","oidcClientConfig","getAuthMetadata","e","error","grant_types_supported","includes","DeviceAuthorization","send","type","Protocols","protocols","homeserver","Failure","reason","UnsupportedProtocol","receive","UnexpectedMessageReceived","serverName","deviceAuthorizationGrant","input","_this3","_dagResponse$verifica","Error","metadata","clientId","deviceId","scope","dagResponse","grantInProgress","Protocol","device_id","device_authorization_grant","verification_uri","verification_uri_complete","verificationUri","userCode","user_code","dag","expectingNewDeviceId","verificationUriComplete","deviceAlreadyExists","_this3$client","getDevice","err","httpStatus","DeviceAlreadyExists","completeLoginOnNewDevice","_ref","_this4","ProtocolAccepted","res","session","Unknown","AuthorizationExpired","UserCancelled","undefined","shareSecrets","_this5","Success","Secrets","secrets","Declined","UserDeclined","timeout","Date","now","_this5$client","device","secretsBundle","getCrypto","exportSecretsBundle","cancelled","_objectSpread","DeviceNotFound","_this6","secureReceive","_this7","secureSend","declineLoginOnExistingDevice","_this8","cancel","_this9","_this9$onFailure","call","close","_this0"],"sources":["../../src/rendezvous/MSC4108SignInWithQR.ts"],"sourcesContent":["/*\nCopyright 2024 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { QrCodeIntent } from \"@matrix-org/matrix-sdk-crypto-wasm\";\n\nimport {\n ClientRendezvousFailureReason,\n MSC4108FailureReason,\n RendezvousError,\n type RendezvousFailureListener,\n} from \"./index.ts\";\nimport { type MatrixClient } from \"../client.ts\";\nimport { logger } from \"../logger.ts\";\nimport { type MSC4108SecureChannel } from \"./channels/MSC4108SecureChannel.ts\";\nimport { MatrixError } from \"../http-api/index.ts\";\nimport { sleep } from \"../utils.ts\";\nimport {\n type DeviceAccessTokenResponse,\n type DeviceAuthorizationResponse,\n generateScope,\n OAuthGrantType,\n startDeviceAuthorization,\n type ValidatedAuthMetadata,\n waitForDeviceAuthorization,\n type OidcClientConfig,\n} from \"../oidc/index.ts\";\nimport { type CryptoApi } from \"../crypto-api/index.ts\";\n\n/**\n * Enum representing the payload types transmissible over [MSC4108](https://github.com/matrix-org/matrix-spec-proposals/pull/4108)\n * secure channels.\n * @experimental Note that this is UNSTABLE and may have breaking changes without notice.\n */\nexport enum PayloadType {\n Protocols = \"m.login.protocols\",\n Protocol = \"m.login.protocol\",\n Failure = \"m.login.failure\",\n Success = \"m.login.success\",\n Secrets = \"m.login.secrets\",\n ProtocolAccepted = \"m.login.protocol_accepted\",\n Declined = \"m.login.declined\",\n}\n\n/**\n * Type representing the base payload format for [MSC4108](https://github.com/matrix-org/matrix-spec-proposals/pull/4108)\n * messages sent over the secure channel.\n * @experimental Note that this is UNSTABLE and may have breaking changes without notice.\n */\nexport interface MSC4108Payload {\n type: PayloadType;\n}\n\ninterface ProtocolsPayload extends MSC4108Payload {\n type: PayloadType.Protocols;\n protocols: string[];\n homeserver: string;\n}\n\ninterface ProtocolPayload extends MSC4108Payload {\n type: PayloadType.Protocol;\n protocol: Exclude<string, \"device_authorization_grant\">;\n device_id: string;\n}\n\ninterface DeviceAuthorizationGrantProtocolPayload extends ProtocolPayload {\n protocol: \"device_authorization_grant\";\n device_authorization_grant: {\n verification_uri: string;\n verification_uri_complete?: string;\n };\n}\n\nfunction isDeviceAuthorizationGrantProtocolPayload(\n payload: ProtocolPayload,\n): payload is DeviceAuthorizationGrantProtocolPayload {\n return payload.protocol === \"device_authorization_grant\";\n}\n\ninterface FailurePayload extends MSC4108Payload {\n type: PayloadType.Failure;\n reason: MSC4108FailureReason;\n homeserver?: string;\n}\n\ninterface DeclinedPayload extends MSC4108Payload {\n type: PayloadType.Declined;\n}\n\ninterface SuccessPayload extends MSC4108Payload {\n type: PayloadType.Success;\n}\n\ninterface AcceptedPayload extends MSC4108Payload {\n type: PayloadType.ProtocolAccepted;\n}\n\ninterface SecretsPayload extends MSC4108Payload, Awaited<ReturnType<NonNullable<CryptoApi[\"exportSecretsBundle\"]>>> {\n type: PayloadType.Secrets;\n}\n\n/**\n * Prototype of the unstable [MSC4108](https://github.com/matrix-org/matrix-spec-proposals/pull/4108)\n * sign in with QR + OIDC flow.\n * @experimental Note that this is UNSTABLE and may have breaking changes without notice.\n */\nexport class MSC4108SignInWithQR {\n private readonly ourIntent: QrCodeIntent;\n private _code?: Uint8Array;\n private expectingNewDeviceId?: string;\n private metadata?: ValidatedAuthMetadata;\n private grantInProgress?: DeviceAuthorizationResponse;\n\n /**\n * Returns the check code for the secure channel or undefined if not generated yet.\n */\n public get checkCode(): string | undefined {\n return this.channel?.getCheckCode();\n }\n\n /**\n * @param channel - The secure channel used for communication\n * @param client - The Matrix client in used on the device already logged in\n * @param didScanCode - Whether this side of the channel scanned the QR code from the other party\n * @param onFailure - Callback for when the rendezvous fails\n */\n public constructor(\n private readonly channel: MSC4108SecureChannel,\n private readonly didScanCode: boolean,\n private readonly client?: MatrixClient,\n public onFailure?: RendezvousFailureListener,\n ) {\n this.ourIntent = client ? QrCodeIntent.Reciprocate : QrCodeIntent.Login;\n }\n\n /**\n * Returns the code representing the rendezvous suitable for rendering in a QR code or undefined if not generated yet.\n */\n public get code(): Uint8Array | undefined {\n return this._code;\n }\n\n /**\n * Generate the code including doing partial set up of the channel where required.\n */\n public async generateCode(): Promise<void> {\n if (this._code) {\n return;\n }\n\n if (this.ourIntent === QrCodeIntent.Reciprocate && this.client) {\n this._code = await this.channel.generateCode(this.ourIntent, this.client.getDomain()!);\n } else if (this.ourIntent === QrCodeIntent.Login) {\n this._code = await this.channel.generateCode(this.ourIntent);\n }\n }\n\n /**\n * Returns true if the device is the already logged in device reciprocating a new login on the other side of the channel.\n */\n public get isExistingDevice(): boolean {\n return this.ourIntent === QrCodeIntent.Reciprocate;\n }\n\n /**\n * Returns true if the device is the new device logging in being reciprocated by the device on the other side of the channel.\n */\n public get isNewDevice(): boolean {\n return !this.isExistingDevice;\n }\n\n /**\n * The first step in the OIDC QR login process.\n * To be called after the QR code has been rendered or scanned.\n * The scanning device has to discover the homeserver details, if they scanned the code then they already have it.\n * If the new device is the one rendering the QR code then it has to wait be sent the homeserver details via the rendezvous channel.\n */\n public async negotiateProtocols(): Promise<{ serverName?: string }> {\n logger.info(`negotiateProtocols(isNewDevice=${this.isNewDevice} didScanCode=${this.didScanCode})`);\n await this.channel.connect();\n\n if (this.didScanCode) {\n // Secure Channel step 6 completed, we trust the channel\n\n if (this.isNewDevice) {\n // MSC4108-Flow: ExistingScanned - take homeserver from QR code which should already be set\n } else {\n // MSC4108-Flow: NewScanned -send protocols message\n let oidcClientConfig: OidcClientConfig | undefined;\n try {\n oidcClientConfig = await this.client!.getAuthMetadata();\n } catch (e) {\n logger.error(\"Failed to discover OIDC metadata\", e);\n }\n\n if (oidcClientConfig?.grant_types_supported.includes(OAuthGrantType.DeviceAuthorization)) {\n await this.send<ProtocolsPayload>({\n type: PayloadType.Protocols,\n protocols: [\"device_authorization_grant\"],\n homeserver: this.client!.getDomain()!,\n });\n } else {\n await this.send<FailurePayload>({\n type: PayloadType.Failure,\n reason: MSC4108FailureReason.UnsupportedProtocol,\n });\n throw new RendezvousError(\n \"Device code grant unsupported\",\n MSC4108FailureReason.UnsupportedProtocol,\n );\n }\n }\n } else if (this.isNewDevice) {\n // MSC4108-Flow: ExistingScanned - wait for protocols message\n logger.info(\"Waiting for protocols message\");\n const payload = await this.receive<ProtocolsPayload>();\n\n if (payload?.type === PayloadType.Failure) {\n throw new RendezvousError(\"Failed\", payload.reason);\n }\n\n if (payload?.type !== PayloadType.Protocols) {\n await this.send<FailurePayload>({\n type: PayloadType.Failure,\n reason: MSC4108FailureReason.UnexpectedMessageReceived,\n });\n throw new RendezvousError(\n \"Unexpected message received\",\n MSC4108FailureReason.UnexpectedMessageReceived,\n );\n }\n\n return { serverName: payload.homeserver };\n } else {\n // MSC4108-Flow: NewScanned - nothing to do\n }\n return {};\n }\n\n /**\n * The second & third step in the OIDC QR login process.\n * To be called after `negotiateProtocols` for the existing device.\n * To be called after OIDC negotiation for the new device.\n *\n * @param input - Required for the new device to start the device authorization grant, not required for the existing device reciprocating the login\n */\n public async deviceAuthorizationGrant(input?: {\n metadata: ValidatedAuthMetadata;\n clientId: string;\n deviceId: string;\n }): Promise<{\n verificationUri?: string;\n userCode?: string;\n }> {\n if (this.isNewDevice) {\n if (!input) {\n throw new Error(\"Input must be provided for new device\");\n }\n\n const { metadata, clientId, deviceId } = input;\n\n const scope = generateScope(deviceId);\n\n // MSC4108-Flow: NewDevice - start device authorization grant\n const dagResponse = await startDeviceAuthorization({\n clientId,\n scope,\n metadata,\n });\n\n this.metadata = metadata;\n this.grantInProgress = dagResponse;\n\n const protocol: DeviceAuthorizationGrantProtocolPayload = {\n type: PayloadType.Protocol,\n protocol: \"device_authorization_grant\",\n device_id: deviceId,\n device_authorization_grant: {\n verification_uri: dagResponse.verification_uri,\n verification_uri_complete: dagResponse.verification_uri_complete,\n },\n };\n\n await this.send(protocol);\n\n return {\n verificationUri: dagResponse.verification_uri_complete ?? dagResponse.verification_uri,\n userCode: dagResponse.user_code,\n };\n } else {\n // The user needs to do step 7 for the out-of-band confirmation\n // but, first we receive the protocol chosen by the other device so that\n // the confirmation_uri is ready to go\n logger.info(\"Waiting for protocol message\");\n const payload = await this.receive<ProtocolPayload | DeviceAuthorizationGrantProtocolPayload>();\n\n if (payload?.type === PayloadType.Failure) {\n throw new RendezvousError(\"Failed\", payload.reason);\n }\n\n if (payload?.type !== PayloadType.Protocol) {\n await this.send<FailurePayload>({\n type: PayloadType.Failure,\n reason: MSC4108FailureReason.UnexpectedMessageReceived,\n });\n throw new RendezvousError(\n \"Unexpected message received\",\n MSC4108FailureReason.UnexpectedMessageReceived,\n );\n }\n\n if (isDeviceAuthorizationGrantProtocolPayload(payload)) {\n const { device_authorization_grant: dag, device_id: expectingNewDeviceId } = payload;\n const { verification_uri: verificationUri, verification_uri_complete: verificationUriComplete } = dag;\n\n let deviceAlreadyExists = true;\n try {\n await this.client?.getDevice(expectingNewDeviceId);\n } catch (err: MatrixError | unknown) {\n if (err instanceof MatrixError && err.httpStatus === 404) {\n deviceAlreadyExists = false;\n }\n }\n\n if (deviceAlreadyExists) {\n await this.send<FailurePayload>({\n type: PayloadType.Failure,\n reason: MSC4108FailureReason.DeviceAlreadyExists,\n });\n throw new RendezvousError(\n \"Specified device ID already exists\",\n MSC4108FailureReason.DeviceAlreadyExists,\n );\n }\n\n this.expectingNewDeviceId = expectingNewDeviceId;\n\n return { verificationUri: verificationUriComplete ?? verificationUri };\n }\n\n await this.send<FailurePayload>({\n type: PayloadType.Failure,\n reason: MSC4108FailureReason.UnsupportedProtocol,\n });\n throw new RendezvousError(\n \"Received a request for an unsupported protocol\",\n MSC4108FailureReason.UnsupportedProtocol,\n );\n }\n }\n\n /**\n * The fourth step in the OIDC QR login process.\n * The reciprocating device must perform step 5 for this method to resolve.\n * To be called after {@link deviceAuthorizationGrant} only on the new device.\n */\n public async completeLoginOnNewDevice({\n clientId,\n }: {\n clientId: string;\n }): Promise<DeviceAccessTokenResponse | undefined> {\n if (!this.isNewDevice || !this.grantInProgress || !this.metadata) {\n throw new Error(\"Can only complete login on new device\");\n }\n\n logger.info(\"Waiting for protocol accepted message\");\n // wait for accepted message\n const payload = await this.receive<AcceptedPayload | FailurePayload>();\n\n if (!payload) {\n throw new RendezvousError(\n \"No response from existing device\",\n MSC4108FailureReason.UnexpectedMessageReceived,\n );\n }\n if (payload.type === PayloadType.Failure) {\n throw new RendezvousError(\"Failed\", (payload as FailurePayload).reason);\n }\n if (payload.type !== PayloadType.ProtocolAccepted) {\n throw new RendezvousError(\"Unexpected message received\", MSC4108FailureReason.UnexpectedMessageReceived);\n }\n\n // poll for DAG\n const res = await waitForDeviceAuthorization({\n session: this.grantInProgress,\n metadata: this.metadata,\n clientId,\n });\n\n if (!res) {\n throw new RendezvousError(\n \"No response from device authorization endpoint\",\n ClientRendezvousFailureReason.Unknown,\n );\n }\n\n if (\"error\" in res) {\n let reason: MSC4108FailureReason = MSC4108FailureReason.UnexpectedMessageReceived;\n if (res.error === \"expired_token\") {\n reason = MSC4108FailureReason.AuthorizationExpired;\n } else if (res.error === \"access_denied\") {\n reason = MSC4108FailureReason.UserCancelled;\n }\n const payload: FailurePayload = {\n type: PayloadType.Failure,\n reason,\n };\n await this.send(payload);\n return undefined;\n }\n\n return res;\n }\n\n /**\n * The fifth (and final) step in the OIDC QR login process.\n * To be called after the new device has completed authentication.\n */\n public async shareSecrets(): Promise<{ secrets?: Omit<SecretsPayload, \"type\"> }> {\n if (this.isNewDevice) {\n await this.send<SuccessPayload>({\n type: PayloadType.Success,\n });\n // then wait for secrets\n logger.info(\"Waiting for secrets message\");\n const payload = await this.receive<SecretsPayload>();\n if (payload?.type === PayloadType.Failure) {\n throw new RendezvousError(\"Failed\", payload.reason);\n }\n\n if (payload?.type !== PayloadType.Secrets) {\n await this.send<FailurePayload>({\n type: PayloadType.Failure,\n reason: MSC4108FailureReason.UnexpectedMessageReceived,\n });\n throw new RendezvousError(\n \"Unexpected message received\",\n MSC4108FailureReason.UnexpectedMessageReceived,\n );\n }\n return { secrets: payload };\n // then done?\n } else {\n if (!this.expectingNewDeviceId) {\n throw new Error(\"No new device ID expected\");\n }\n await this.send<AcceptedPayload>({\n type: PayloadType.ProtocolAccepted,\n });\n\n logger.info(\"Waiting for outcome message\");\n const payload = await this.receive<SuccessPayload | DeclinedPayload>();\n\n if (payload?.type === PayloadType.Failure) {\n throw new RendezvousError(\"Failed\", payload.reason);\n }\n\n if (payload?.type === PayloadType.Declined) {\n throw new RendezvousError(\"User declined\", ClientRendezvousFailureReason.UserDeclined);\n }\n\n if (payload?.type !== PayloadType.Success) {\n await this.send<FailurePayload>({\n type: PayloadType.Failure,\n reason: MSC4108FailureReason.UnexpectedMessageReceived,\n });\n throw new RendezvousError(\"Unexpected message\", MSC4108FailureReason.UnexpectedMessageReceived);\n }\n\n const timeout = Date.now() + 10000; // wait up to 10 seconds\n do {\n // is the device visible via the Homeserver?\n try {\n const device = await this.client?.getDevice(this.expectingNewDeviceId);\n\n if (device) {\n // if so, return the secrets\n const secretsBundle = await this.client!.getCrypto()!.exportSecretsBundle!();\n if (this.channel.cancelled) {\n throw new RendezvousError(\"User cancelled\", MSC4108FailureReason.UserCancelled);\n }\n // send secrets\n await this.send<SecretsPayload>({\n type: PayloadType.Secrets,\n ...secretsBundle,\n });\n return { secrets: secretsBundle };\n // let the other side close the rendezvous session\n }\n } catch (err: MatrixError | unknown) {\n if (err instanceof MatrixError && err.httpStatus === 404) {\n // not found, so keep waiting until timeout\n } else {\n throw err;\n }\n }\n await sleep(1000);\n } while (Date.now() < timeout);\n\n await this.send<FailurePayload>({\n type: PayloadType.Failure,\n reason: MSC4108FailureReason.DeviceNotFound,\n });\n throw new RendezvousError(\"New device not found\", MSC4108FailureReason.DeviceNotFound);\n }\n }\n\n private async receive<T extends MSC4108Payload>(): Promise<T | FailurePayload | undefined> {\n return (await this.channel.secureReceive()) as T | undefined;\n }\n\n private async send<T extends MSC4108Payload>(payload: T): Promise<void> {\n await this.channel.secureSend(payload);\n }\n\n /**\n * Decline the login on the existing device.\n */\n public async declineLoginOnExistingDevice(): Promise<void> {\n if (!this.isExistingDevice) {\n throw new Error(\"Can only decline login on existing device\");\n }\n await this.send<FailurePayload>({\n type: PayloadType.Failure,\n reason: MSC4108FailureReason.UserCancelled,\n });\n }\n\n /**\n * Cancels the rendezvous session.\n * @param reason the reason for the cancellation\n */\n public async cancel(reason: MSC4108FailureReason | ClientRendezvousFailureReason): Promise<void> {\n this.onFailure?.(reason);\n await this.channel.cancel(reason);\n }\n\n /**\n * Closes the rendezvous session.\n */\n public async close(): Promise<void> {\n await this.channel.close();\n }\n}\n"],"mappings":";;;;AAAA;AACA;AACA;AACA;AACA;AACA;AAC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EAAErD,oBAAoB,CAAC8F;MACjC,CAAC,CAAC;IAAC;EACP;;EAEA;AACJ;AACA;AACA;EACiB0B,MAAMA,CAACnE,MAA4D,EAAiB;IAAA,IAAAoE,MAAA;IAAA,OAAA3F,iBAAA;MAAA,IAAA4F,gBAAA;MAC7F,CAAAA,gBAAA,GAAAD,MAAI,CAACpG,SAAS,cAAAqG,gBAAA,eAAdA,gBAAA,CAAAC,IAAA,CAAAF,MAAI,EAAapE,MAAM,CAAC;MACxB,MAAMoE,MAAI,CAACzG,OAAO,CAACwG,MAAM,CAACnE,MAAM,CAAC;IAAC;EACtC;;EAEA;AACJ;AACA;EACiBuE,KAAKA,CAAA,EAAkB;IAAA,IAAAC,MAAA;IAAA,OAAA/F,iBAAA;MAChC,MAAM+F,MAAI,CAAC7G,OAAO,CAAC4G,KAAK,CAAC,CAAC;IAAC;EAC/B;AACJ","ignoreList":[]}
@@ -1 +1 @@
1
- {"version":3,"file":"MSC4108SecureChannel.d.ts","sourceRoot":"","sources":["../../../src/rendezvous/channels/MSC4108SecureChannel.ts"],"names":[],"mappings":"AAgBA,OAAO,EACH,KAAK,mBAAmB,EAIxB,YAAY,EACf,MAAM,oCAAoC,CAAC;AAE5C,OAAO,EACH,6BAA6B,EAC7B,oBAAoB,EACpB,KAAK,cAAc,EAEnB,KAAK,yBAAyB,EACjC,MAAM,aAAa,CAAC;AACrB,OAAO,EAAE,KAAK,wBAAwB,EAAE,MAAM,2CAA2C,CAAC;AAG1F;;;;;GAKG;AACH,qBAAa,oBAAoB;IAMzB,OAAO,CAAC,iBAAiB;IACzB,OAAO,CAAC,cAAc,CAAC;IAChB,SAAS,CAAC,EAAE,yBAAyB;IAPhD,OAAO,CAAC,QAAQ,CAAC,aAAa,CAAQ;IACtC,OAAO,CAAC,kBAAkB,CAAC,CAAmB;IAC9C,OAAO,CAAC,SAAS,CAAS;gBAGd,iBAAiB,EAAE,wBAAwB,EAC3C,cAAc,CAAC,EAAE,mBAAmB,YAAA,EACrC,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AAC,EAAE,yBAAyB;IAPhD,OAAO,CAAC,QAAQ,CAAC,aAAa,CAAQ;IACtC,OAAO,CAAC,kBAAkB,CAAC,CAAmB;IAC9C,OAAO,CAAC,SAAS,CAAS;gBAGd,iBAAiB,EAAE,wBAAwB,EAC3C,cAAc,CAAC,EAAE,mBAAmB,YAAA,EACrC,SAAS,CAAC,EAAE,yBAAyB,YAAA;IAKhD;;;;OAIG;IACU,YAAY,CAAC,IAAI,EAAE,YAAY,CAAC,KAAK,GAAG,OAAO,CAAC,UAAU,CAAC;IAC3D,YAAY,CAAC,IAAI,EAAE,YAAY,CAAC,WAAW,EAAE,UAAU,EAAE,MAAM,GAAG,OAAO,CAAC,UAAU,CAAC;IAelG;;OAEG;IACI,YAAY,IAAI,MAAM,GAAG,SAAS;IAWzC;;OAEG;IACU,OAAO,IAAI,OAAO,CAAC,IAAI,CAAC;YAyGvB,OAAO;YAQP,OAAO;IAQrB;;;OAGG;IACU,UAAU,CAAC,CAAC,SAAS,cAAc,EAAE,OAAO,EAAE,CAAC,GAAG,OAAO,CAAC,IAAI,CAAC;IAW5E;;OAEG;IACU,aAAa,CAAC,CAAC,SAAS,cAAc,KAAK,OAAO,CAAC,OAAO,CAAC,CAAC,CAAC,GAAG,SAAS,CAAC;IAgBvF;;OAEG;IACU,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC;IAInC;;;OAGG;IACU,MAAM,CAAC,MAAM,EAAE,oBAAoB,GAAG,6BAA6B,GAAG,OAAO,CAAC,IAAI,CAAC;IAchG;;OAEG;IACH,IAAW,SAAS,IAAI,OAAO,CAE9B;CACJ"}
@@ -132,7 +132,7 @@ export class MSC4108SecureChannel {
132
132
  logger.info("Waiting for LoginInitiateMessage");
133
133
  var loginInitiateMessage = yield _this2.rendezvousSession.receive();
134
134
  if (!loginInitiateMessage) {
135
- throw new Error("No response from other device");
135
+ throw new RendezvousError("No response from other device", MSC4108FailureReason.UnexpectedMessageReceived);
136
136
  }
137
137
  var {
138
138
  channel,
@@ -231,7 +231,9 @@ export class MSC4108SecureChannel {
231
231
  yield _this8.rendezvousSession.cancel(reason);
232
232
  (_this8$onFailure = _this8.onFailure) === null || _this8$onFailure === void 0 || _this8$onFailure.call(_this8, reason);
233
233
  } finally {
234
- yield _this8.close();
234
+ if (reason !== ClientRendezvousFailureReason.UserDeclined && reason !== MSC4108FailureReason.UserCancelled) {
235
+ yield _this8.close();
236
+ }
235
237
  }
236
238
  })();
237
239
  }