@unwanted/matrix-sdk-mini 34.13.0 → 36.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/lib/@types/event.d.ts +25 -0
- package/lib/@types/event.d.ts.map +1 -1
- package/lib/@types/event.js +5 -0
- package/lib/@types/event.js.map +1 -1
- package/lib/client.d.ts +43 -8
- package/lib/client.d.ts.map +1 -1
- package/lib/client.js +147 -85
- package/lib/client.js.map +1 -1
- package/lib/embedded.d.ts +2 -1
- package/lib/embedded.d.ts.map +1 -1
- package/lib/embedded.js +57 -74
- package/lib/embedded.js.map +1 -1
- package/lib/feature.d.ts.map +1 -1
- package/lib/feature.js +2 -1
- package/lib/feature.js.map +1 -1
- package/lib/http-api/errors.d.ts +3 -3
- package/lib/http-api/errors.js +3 -3
- package/lib/http-api/errors.js.map +1 -1
- package/lib/http-api/utils.js +2 -2
- package/lib/http-api/utils.js.map +1 -1
- package/lib/models/event-timeline.d.ts.map +1 -1
- package/lib/models/event-timeline.js +1 -21
- package/lib/models/event-timeline.js.map +1 -1
- package/lib/models/event.d.ts +11 -1
- package/lib/models/event.d.ts.map +1 -1
- package/lib/models/event.js +48 -5
- package/lib/models/event.js.map +1 -1
- package/lib/models/invites-ignorer-types.d.ts +27 -0
- package/lib/models/invites-ignorer-types.d.ts.map +1 -0
- package/lib/models/invites-ignorer-types.js +36 -0
- package/lib/models/invites-ignorer-types.js.map +1 -0
- package/lib/models/invites-ignorer.d.ts +2 -26
- package/lib/models/invites-ignorer.d.ts.map +1 -1
- package/lib/models/invites-ignorer.js +2 -27
- package/lib/models/invites-ignorer.js.map +1 -1
- package/lib/models/room-member.d.ts +6 -1
- package/lib/models/room-member.d.ts.map +1 -1
- package/lib/models/room-member.js +7 -1
- package/lib/models/room-member.js.map +1 -1
- package/lib/models/room.d.ts +6 -1
- package/lib/models/room.d.ts.map +1 -1
- package/lib/models/room.js +7 -1
- package/lib/models/room.js.map +1 -1
- package/lib/oidc/authorize.d.ts +2 -2
- package/lib/oidc/authorize.d.ts.map +1 -1
- package/lib/oidc/authorize.js +5 -5
- package/lib/oidc/authorize.js.map +1 -1
- package/lib/oidc/discovery.d.ts +8 -0
- package/lib/oidc/discovery.d.ts.map +1 -1
- package/lib/oidc/discovery.js +22 -11
- package/lib/oidc/discovery.js.map +1 -1
- package/lib/oidc/index.d.ts +3 -4
- package/lib/oidc/index.d.ts.map +1 -1
- package/lib/oidc/index.js.map +1 -1
- package/lib/oidc/register.js +3 -3
- package/lib/oidc/register.js.map +1 -1
- package/lib/oidc/tokenRefresher.d.ts.map +1 -1
- package/lib/oidc/tokenRefresher.js +6 -5
- package/lib/oidc/tokenRefresher.js.map +1 -1
- package/lib/oidc/validate.d.ts +9 -23
- package/lib/oidc/validate.d.ts.map +1 -1
- package/lib/oidc/validate.js +13 -28
- package/lib/oidc/validate.js.map +1 -1
- package/lib/randomstring.d.ts +30 -3
- package/lib/randomstring.d.ts.map +1 -1
- package/lib/randomstring.js +68 -16
- package/lib/randomstring.js.map +1 -1
- package/lib/store/indexeddb-local-backend.js +4 -2
- package/lib/store/indexeddb-local-backend.js.map +1 -1
- package/lib/testing.d.ts +17 -0
- package/lib/testing.d.ts.map +1 -1
- package/lib/testing.js +42 -0
- package/lib/testing.js.map +1 -1
- package/package.json +5 -5
- package/src/@types/event.ts +17 -0
- package/src/client.ts +86 -28
- package/src/embedded.ts +39 -49
- package/src/feature.ts +1 -0
- package/src/http-api/errors.ts +3 -3
- package/src/http-api/utils.ts +2 -2
- package/src/models/event-timeline.ts +1 -21
- package/src/models/event.ts +46 -0
- package/src/models/invites-ignorer-types.ts +48 -0
- package/src/models/invites-ignorer.ts +7 -42
- package/src/models/room-member.ts +16 -1
- package/src/models/room.ts +16 -1
- package/src/oidc/authorize.ts +7 -7
- package/src/oidc/discovery.ts +16 -10
- package/src/oidc/index.ts +3 -4
- package/src/oidc/register.ts +3 -3
- package/src/oidc/tokenRefresher.ts +3 -2
- package/src/oidc/validate.ts +40 -63
- package/src/randomstring.ts +65 -19
- package/src/store/indexeddb-local-backend.ts +2 -2
- package/src/testing.ts +41 -0
package/lib/oidc/validate.js.map
CHANGED
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"file":"validate.js","names":["jwtDecode","logger","OidcError","isRecord","value","Array","isArray","requiredStringProperty","wellKnown","key","optionalStringProperty","error","concat","optionalStringArrayProperty","every","v","requiredArrayValue","array","includes","validateOIDCIssuerWellKnown","Error","OpSupport","isInvalid","some","isValid","authorizationEndpoint","tokenEndpoint","registrationEndpoint","accountManagementEndpoint","accountManagementActionsSupported","isValidatedIssuerMetadata","metadata","decodeIdToken","token","validateIdToken","idToken","issuer","clientId","nonce","claims","iss","aud","undefined","exp","Date","now","InvalidIdToken","validateStoredUserState","userState","MissingOrInvalidStoredState","isValidBearerTokenResponse","response","toLowerCase","validateBearerTokenResponse","InvalidBearerTokenResponse"],"sources":["../../src/oidc/validate.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 { jwtDecode } from \"jwt-decode\";\nimport { IdTokenClaims, OidcMetadata, SigninResponse } from \"oidc-client-ts\";\n\nimport { logger } from \"../logger.ts\";\nimport { OidcError } from \"./error.ts\";\n\nexport type ValidatedIssuerConfig = {\n authorizationEndpoint: string;\n tokenEndpoint: string;\n registrationEndpoint?: string;\n accountManagementEndpoint?: string;\n accountManagementActionsSupported?: string[];\n};\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n !!value && typeof value === \"object\" && !Array.isArray(value);\nconst requiredStringProperty = (wellKnown: Record<string, unknown>, key: string): boolean => {\n if (!wellKnown[key] || !optionalStringProperty(wellKnown, key)) {\n logger.error(`Missing or invalid property: ${key}`);\n return false;\n }\n return true;\n};\nconst optionalStringProperty = (wellKnown: Record<string, unknown>, key: string): boolean => {\n if (!!wellKnown[key] && typeof wellKnown[key] !== \"string\") {\n logger.error(`Invalid property: ${key}`);\n return false;\n }\n return true;\n};\nconst optionalStringArrayProperty = (wellKnown: Record<string, unknown>, key: string): boolean => {\n if (\n !!wellKnown[key] &&\n (!Array.isArray(wellKnown[key]) || !(<unknown[]>wellKnown[key]).every((v) => typeof v === \"string\"))\n ) {\n logger.error(`Invalid property: ${key}`);\n return false;\n }\n return true;\n};\nconst requiredArrayValue = (wellKnown: Record<string, unknown>, key: string, value: any): boolean => {\n const array = wellKnown[key];\n if (!array || !Array.isArray(array) || !array.includes(value)) {\n logger.error(`Invalid property: ${key}. ${value} is required.`);\n return false;\n }\n return true;\n};\n\n/**\n * Validates issuer `.well-known/openid-configuration`\n * As defined in RFC5785 https://openid.net/specs/openid-connect-discovery-1_0.html\n * validates that OP is compatible with Element's OIDC flow\n * @param wellKnown - json object\n * @returns valid issuer config\n * @throws Error - when issuer config is not found or is invalid\n */\nexport const validateOIDCIssuerWellKnown = (wellKnown: unknown): ValidatedIssuerConfig => {\n if (!isRecord(wellKnown)) {\n logger.error(\"Issuer configuration not found or malformed\");\n throw new Error(OidcError.OpSupport);\n }\n\n const isInvalid = [\n requiredStringProperty(wellKnown, \"authorization_endpoint\"),\n requiredStringProperty(wellKnown, \"token_endpoint\"),\n requiredStringProperty(wellKnown, \"revocation_endpoint\"),\n optionalStringProperty(wellKnown, \"registration_endpoint\"),\n optionalStringProperty(wellKnown, \"account_management_uri\"),\n optionalStringProperty(wellKnown, \"device_authorization_endpoint\"),\n optionalStringArrayProperty(wellKnown, \"account_management_actions_supported\"),\n requiredArrayValue(wellKnown, \"response_types_supported\", \"code\"),\n requiredArrayValue(wellKnown, \"grant_types_supported\", \"authorization_code\"),\n requiredArrayValue(wellKnown, \"code_challenge_methods_supported\", \"S256\"),\n ].some((isValid) => !isValid);\n\n if (!isInvalid) {\n return {\n authorizationEndpoint: <string>wellKnown[\"authorization_endpoint\"],\n tokenEndpoint: <string>wellKnown[\"token_endpoint\"],\n registrationEndpoint: <string>wellKnown[\"registration_endpoint\"],\n accountManagementEndpoint: <string>wellKnown[\"account_management_uri\"],\n accountManagementActionsSupported: <string[]>wellKnown[\"account_management_actions_supported\"],\n };\n }\n\n logger.error(\"Issuer configuration not valid\");\n throw new Error(OidcError.OpSupport);\n};\n\n/**\n * Metadata from OIDC authority discovery\n * With validated properties required in type\n */\nexport type ValidatedIssuerMetadata = Partial<OidcMetadata> &\n Pick<\n OidcMetadata,\n | \"issuer\"\n | \"authorization_endpoint\"\n | \"token_endpoint\"\n | \"registration_endpoint\"\n | \"revocation_endpoint\"\n | \"response_types_supported\"\n | \"grant_types_supported\"\n | \"code_challenge_methods_supported\"\n | \"device_authorization_endpoint\"\n > & {\n // MSC2965 extensions to the OIDC spec\n account_management_uri?: string;\n account_management_actions_supported?: string[];\n };\n\n/**\n * Wraps validateOIDCIssuerWellKnown in a type assertion\n * that asserts expected properties are present\n * (Typescript assertions cannot be arrow functions)\n * @param metadata - issuer openid-configuration response\n * @throws when metadata validation fails\n */\nexport function isValidatedIssuerMetadata(\n metadata: Partial<OidcMetadata>,\n): asserts metadata is ValidatedIssuerMetadata {\n validateOIDCIssuerWellKnown(metadata);\n}\n\nexport const decodeIdToken = (token: string): IdTokenClaims => {\n try {\n return jwtDecode<IdTokenClaims>(token);\n } catch (error) {\n logger.error(\"Could not decode id_token\", error);\n throw error;\n }\n};\n\n/**\n * Validate idToken\n * https://openid.net/specs/openid-connect-core-1_0.html#IDTokenValidation\n * @param idToken - id token from token endpoint\n * @param issuer - issuer for the OP as found during discovery\n * @param clientId - this client's id as registered with the OP\n * @param nonce - nonce used in the authentication request\n * @throws when id token is invalid\n */\nexport const validateIdToken = (\n idToken: string | undefined,\n issuer: string,\n clientId: string,\n nonce: string | undefined,\n): void => {\n try {\n if (!idToken) {\n throw new Error(\"No ID token\");\n }\n const claims = decodeIdToken(idToken);\n\n // The Issuer Identifier for the OpenID Provider MUST exactly match the value of the iss (issuer) Claim.\n if (claims.iss !== issuer) {\n throw new Error(\"Invalid issuer\");\n }\n /**\n * The Client MUST validate that the aud (audience) Claim contains its client_id value registered at the Issuer identified by the iss (issuer) Claim as an audience.\n * The aud (audience) Claim MAY contain an array with more than one element.\n * The ID Token MUST be rejected if the ID Token does not list the Client as a valid audience, or if it contains additional audiences not trusted by the Client.\n * EW: Don't accept tokens with other untrusted audiences\n * */\n if (claims.aud !== clientId) {\n throw new Error(\"Invalid audience\");\n }\n\n /**\n * If a nonce value was sent in the Authentication Request, a nonce Claim MUST be present and its value checked\n * to verify that it is the same value as the one that was sent in the Authentication Request.\n */\n if (nonce !== undefined && claims.nonce !== nonce) {\n throw new Error(\"Invalid nonce\");\n }\n\n /**\n * The current time MUST be before the time represented by the exp Claim.\n * exp is an epoch timestamp in seconds\n * */\n if (!claims.exp || Date.now() > claims.exp * 1000) {\n throw new Error(\"Invalid expiry\");\n }\n } catch (error) {\n logger.error(\"Invalid ID token\", error);\n throw new Error(OidcError.InvalidIdToken);\n }\n};\n\n/**\n * State we ask OidcClient to store when starting oidc authorization flow (in `generateOidcAuthorizationUrl`)\n * so that we can access it on return from the OP and complete login\n */\nexport type UserState = {\n /**\n * Remember which server we were trying to login to\n */\n homeserverUrl: string;\n identityServerUrl?: string;\n /**\n * Used to validate id token\n */\n nonce: string;\n};\n/**\n * Validate stored user state exists and is valid\n * @param userState - userState returned by oidcClient.processSigninResponse\n * @throws when userState is invalid\n */\nexport function validateStoredUserState(userState: unknown): asserts userState is UserState {\n if (!isRecord(userState)) {\n logger.error(\"Stored user state not found\");\n throw new Error(OidcError.MissingOrInvalidStoredState);\n }\n const isInvalid = [\n requiredStringProperty(userState, \"homeserverUrl\"),\n requiredStringProperty(userState, \"nonce\"),\n optionalStringProperty(userState, \"identityServerUrl\"),\n ].some((isValid) => !isValid);\n\n if (isInvalid) {\n throw new Error(OidcError.MissingOrInvalidStoredState);\n }\n}\n\n/**\n * The expected response type from the token endpoint during authorization code flow\n * Normalized to always use capitalized 'Bearer' for token_type\n *\n * See https://datatracker.ietf.org/doc/html/rfc6749#section-4.1.4,\n * https://openid.net/specs/openid-connect-basic-1_0.html#TokenOK.\n */\nexport type BearerTokenResponse = {\n token_type: \"Bearer\";\n access_token: string;\n scope: string;\n refresh_token?: string;\n expires_in?: number;\n // from oidc-client-ts\n expires_at?: number;\n id_token: string;\n};\n\n/**\n * Make required properties required in type\n */\ntype ValidSignInResponse = SigninResponse &\n BearerTokenResponse & {\n token_type: \"Bearer\" | \"bearer\";\n };\n\nconst isValidBearerTokenResponse = (response: unknown): response is ValidSignInResponse =>\n isRecord(response) &&\n requiredStringProperty(response, \"token_type\") &&\n // token_type is case insensitive, some OPs return `token_type: \"bearer\"`\n (response[\"token_type\"] as string).toLowerCase() === \"bearer\" &&\n requiredStringProperty(response, \"access_token\") &&\n requiredStringProperty(response, \"refresh_token\") &&\n (!(\"expires_in\" in response) || typeof response[\"expires_in\"] === \"number\");\n\nexport function validateBearerTokenResponse(response: unknown): asserts response is ValidSignInResponse {\n if (!isValidBearerTokenResponse(response)) {\n throw new Error(OidcError.InvalidBearerTokenResponse);\n }\n}\n"],"mappings":"AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA,SAASA,SAAS,QAAQ,YAAY;AAGtC,SAASC,MAAM,QAAQ,cAAc;AACrC,SAASC,SAAS,QAAQ,YAAY;AAUtC,IAAMC,QAAQ,GAAIC,KAAc,IAC5B,CAAC,CAACA,KAAK,IAAI,OAAOA,KAAK,KAAK,QAAQ,IAAI,CAACC,KAAK,CAACC,OAAO,CAACF,KAAK,CAAC;AACjE,IAAMG,sBAAsB,GAAGA,CAACC,SAAkC,EAAEC,GAAW,KAAc;EACz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AC4C,QAAQ,EAAE,eAAe,CAAC,KAChD,EAAE,YAAY,IAAIA,QAAQ,CAAC,IAAI,OAAOA,QAAQ,CAAC,YAAY,CAAC,KAAK,QAAQ,CAAC;AAE/E,OAAO,SAASE,2BAA2BA,CAACF,QAAiB,EAA2C;EACpG,IAAI,CAACD,0BAA0B,CAACC,QAAQ,CAAC,EAAE;IACvC,MAAM,IAAI/B,KAAK,CAAClB,SAAS,CAACoD,0BAA0B,CAAC;EACzD;AACJ","ignoreList":[]}
|
1
|
+
{"version":3,"file":"validate.js","names":["jwtDecode","logger","OidcError","isRecord","value","Array","isArray","requiredStringProperty","wellKnown","key","optionalStringProperty","error","concat","optionalStringArrayProperty","every","v","requiredArrayValue","array","includes","validateAuthMetadata","authMetadata","Error","OpSupport","isInvalid","some","isValid","decodeIdToken","token","validateIdToken","idToken","issuer","clientId","nonce","claims","iss","sanitisedAuds","aud","undefined","exp","Date","now","InvalidIdToken","validateStoredUserState","userState","MissingOrInvalidStoredState","isValidBearerTokenResponse","response","toLowerCase","validateBearerTokenResponse","InvalidBearerTokenResponse"],"sources":["../../src/oidc/validate.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 { jwtDecode } from \"jwt-decode\";\nimport { IdTokenClaims, OidcMetadata, SigninResponse } from \"oidc-client-ts\";\n\nimport { logger } from \"../logger.ts\";\nimport { OidcError } from \"./error.ts\";\n\n/**\n * Metadata from OIDC authority discovery\n * With validated properties required in type\n */\nexport type ValidatedAuthMetadata = Partial<OidcMetadata> &\n Pick<\n OidcMetadata,\n | \"issuer\"\n | \"authorization_endpoint\"\n | \"token_endpoint\"\n | \"revocation_endpoint\"\n | \"response_types_supported\"\n | \"grant_types_supported\"\n | \"code_challenge_methods_supported\"\n > & {\n // MSC2965 extensions to the OIDC spec\n account_management_uri?: string;\n account_management_actions_supported?: string[];\n // The OidcMetadata type from oidc-client-ts does not include `prompt_values_supported`\n // even though it is part of the OIDC spec\n prompt_values_supported?: string[];\n };\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n !!value && typeof value === \"object\" && !Array.isArray(value);\nconst requiredStringProperty = (wellKnown: Record<string, unknown>, key: string): boolean => {\n if (!wellKnown[key] || !optionalStringProperty(wellKnown, key)) {\n logger.error(`Missing or invalid property: ${key}`);\n return false;\n }\n return true;\n};\nconst optionalStringProperty = (wellKnown: Record<string, unknown>, key: string): boolean => {\n if (!!wellKnown[key] && typeof wellKnown[key] !== \"string\") {\n logger.error(`Invalid property: ${key}`);\n return false;\n }\n return true;\n};\nconst optionalStringArrayProperty = (wellKnown: Record<string, unknown>, key: string): boolean => {\n if (\n !!wellKnown[key] &&\n (!Array.isArray(wellKnown[key]) || !(<unknown[]>wellKnown[key]).every((v) => typeof v === \"string\"))\n ) {\n logger.error(`Invalid property: ${key}`);\n return false;\n }\n return true;\n};\nconst requiredArrayValue = (wellKnown: Record<string, unknown>, key: string, value: any): boolean => {\n const array = wellKnown[key];\n if (!array || !Array.isArray(array) || !array.includes(value)) {\n logger.error(`Invalid property: ${key}. ${value} is required.`);\n return false;\n }\n return true;\n};\n\n/**\n * Validates issuer `.well-known/openid-configuration`\n * As defined in RFC5785 https://openid.net/specs/openid-connect-discovery-1_0.html\n * validates that OP is compatible with Element's OIDC flow\n * @param authMetadata - json object\n * @returns valid issuer config\n * @throws Error - when issuer config is not found or is invalid\n */\nexport const validateAuthMetadata = (authMetadata: unknown): ValidatedAuthMetadata => {\n if (!isRecord(authMetadata)) {\n logger.error(\"Issuer configuration not found or malformed\");\n throw new Error(OidcError.OpSupport);\n }\n\n const isInvalid = [\n requiredStringProperty(authMetadata, \"issuer\"),\n requiredStringProperty(authMetadata, \"authorization_endpoint\"),\n requiredStringProperty(authMetadata, \"token_endpoint\"),\n requiredStringProperty(authMetadata, \"revocation_endpoint\"),\n optionalStringProperty(authMetadata, \"registration_endpoint\"),\n optionalStringProperty(authMetadata, \"account_management_uri\"),\n optionalStringProperty(authMetadata, \"device_authorization_endpoint\"),\n optionalStringArrayProperty(authMetadata, \"account_management_actions_supported\"),\n requiredArrayValue(authMetadata, \"response_types_supported\", \"code\"),\n requiredArrayValue(authMetadata, \"grant_types_supported\", \"authorization_code\"),\n requiredArrayValue(authMetadata, \"code_challenge_methods_supported\", \"S256\"),\n optionalStringArrayProperty(authMetadata, \"prompt_values_supported\"),\n ].some((isValid) => !isValid);\n\n if (!isInvalid) {\n return authMetadata as ValidatedAuthMetadata;\n }\n\n logger.error(\"Issuer configuration not valid\");\n throw new Error(OidcError.OpSupport);\n};\n\nexport const decodeIdToken = (token: string): IdTokenClaims => {\n try {\n return jwtDecode<IdTokenClaims>(token);\n } catch (error) {\n logger.error(\"Could not decode id_token\", error);\n throw error;\n }\n};\n\n/**\n * Validate idToken\n * https://openid.net/specs/openid-connect-core-1_0.html#IDTokenValidation\n * @param idToken - id token from token endpoint\n * @param issuer - issuer for the OP as found during discovery\n * @param clientId - this client's id as registered with the OP\n * @param nonce - nonce used in the authentication request\n * @throws when id token is invalid\n */\nexport const validateIdToken = (\n idToken: string | undefined,\n issuer: string,\n clientId: string,\n nonce: string | undefined,\n): void => {\n try {\n if (!idToken) {\n throw new Error(\"No ID token\");\n }\n const claims = decodeIdToken(idToken);\n\n // The Issuer Identifier for the OpenID Provider MUST exactly match the value of the iss (issuer) Claim.\n if (claims.iss !== issuer) {\n throw new Error(\"Invalid issuer\");\n }\n /**\n * The Client MUST validate that the aud (audience) Claim contains its client_id value registered at the Issuer identified by the iss (issuer) Claim as an audience.\n * The aud (audience) Claim MAY contain an array with more than one element.\n * The ID Token MUST be rejected if the ID Token does not list the Client as a valid audience, or if it contains additional audiences not trusted by the Client.\n * EW: Don't accept tokens with other untrusted audiences\n * */\n const sanitisedAuds = typeof claims.aud === \"string\" ? [claims.aud] : claims.aud;\n if (!sanitisedAuds.includes(clientId)) {\n throw new Error(\"Invalid audience\");\n }\n\n /**\n * If a nonce value was sent in the Authentication Request, a nonce Claim MUST be present and its value checked\n * to verify that it is the same value as the one that was sent in the Authentication Request.\n */\n if (nonce !== undefined && claims.nonce !== nonce) {\n throw new Error(\"Invalid nonce\");\n }\n\n /**\n * The current time MUST be before the time represented by the exp Claim.\n * exp is an epoch timestamp in seconds\n * */\n if (!claims.exp || Date.now() > claims.exp * 1000) {\n throw new Error(\"Invalid expiry\");\n }\n } catch (error) {\n logger.error(\"Invalid ID token\", error);\n throw new Error(OidcError.InvalidIdToken);\n }\n};\n\n/**\n * State we ask OidcClient to store when starting oidc authorization flow (in `generateOidcAuthorizationUrl`)\n * so that we can access it on return from the OP and complete login\n */\nexport type UserState = {\n /**\n * Remember which server we were trying to login to\n */\n homeserverUrl: string;\n identityServerUrl?: string;\n /**\n * Used to validate id token\n */\n nonce: string;\n};\n/**\n * Validate stored user state exists and is valid\n * @param userState - userState returned by oidcClient.processSigninResponse\n * @throws when userState is invalid\n */\nexport function validateStoredUserState(userState: unknown): asserts userState is UserState {\n if (!isRecord(userState)) {\n logger.error(\"Stored user state not found\");\n throw new Error(OidcError.MissingOrInvalidStoredState);\n }\n const isInvalid = [\n requiredStringProperty(userState, \"homeserverUrl\"),\n requiredStringProperty(userState, \"nonce\"),\n optionalStringProperty(userState, \"identityServerUrl\"),\n ].some((isValid) => !isValid);\n\n if (isInvalid) {\n throw new Error(OidcError.MissingOrInvalidStoredState);\n }\n}\n\n/**\n * The expected response type from the token endpoint during authorization code flow\n * Normalized to always use capitalized 'Bearer' for token_type\n *\n * See https://datatracker.ietf.org/doc/html/rfc6749#section-4.1.4,\n * https://openid.net/specs/openid-connect-basic-1_0.html#TokenOK.\n */\nexport type BearerTokenResponse = {\n token_type: \"Bearer\";\n access_token: string;\n scope: string;\n refresh_token?: string;\n expires_in?: number;\n // from oidc-client-ts\n expires_at?: number;\n id_token: string;\n};\n\n/**\n * Make required properties required in type\n */\ntype ValidSignInResponse = SigninResponse &\n BearerTokenResponse & {\n token_type: \"Bearer\" | \"bearer\";\n };\n\nconst isValidBearerTokenResponse = (response: unknown): response is ValidSignInResponse =>\n isRecord(response) &&\n requiredStringProperty(response, \"token_type\") &&\n // token_type is case insensitive, some OPs return `token_type: \"bearer\"`\n (response[\"token_type\"] as string).toLowerCase() === \"bearer\" &&\n requiredStringProperty(response, \"access_token\") &&\n requiredStringProperty(response, \"refresh_token\") &&\n (!(\"expires_in\" in response) || typeof response[\"expires_in\"] === \"number\");\n\nexport function validateBearerTokenResponse(response: unknown): asserts response is ValidSignInResponse {\n if (!isValidBearerTokenResponse(response)) {\n throw new Error(OidcError.InvalidBearerTokenResponse);\n }\n}\n"],"mappings":"AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA,SAASA,SAAS,QAAQ,YAAY;AAGtC,SAASC,MAAM,QAAQ,cAAc;AACrC,SAASC,SAAS,QAAQ,YAAY;;AAEtC;AACA;AACA;AACA;;AAoBA,IAAMC,QAAQ,GAAIC,KAAc,IAC5B,CAAC,CAACA,KAAK,IAAI,OAAOA,KAAK,KAAK,QAAQ,IAAI,CAACC,KAAK,CAACC,OAAO,CAACF,KAAK,CAAC;AACjE,IAAMG,sBAAsB,GAAGA,CAACC,SAAkC,EAAEC,GAAW,KAAc;EACzF,IAAI,CAACD,SAAS,CAACC,GAAG,CAAC,IAAI,CAACC,sBAAsB,CAACF,SAAS,EAAEC,GAAG,CAAC,EAAE;IAC5DR,MAAM,CAACU,KAAK,iCAAAC,MAAA,CAAiCH,GAAG,CAAE,CAAC;IACnD,OAAO,KAAK;EAChB;EACA,OAAO,IAAI;AACf,CAAC;AACD,IAAMC,sBAAsB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for use in {@link secureRandomStringFrom}
|
3
|
+
* (can be combined with other such exports or other characters by appending strings)
|
4
|
+
*/
|
5
|
+
export declare const LOWERCASE = "abcdefghijklmnopqrstuvwxyz";
|
6
|
+
/**
|
7
|
+
* String representing the uppercase latin alphabet for use in secureRandomStringFrom
|
8
|
+
* (can be combined with other such exports or other characters by appending strings)
|
9
|
+
*/
|
10
|
+
export declare const UPPERCASE = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
|
11
|
+
/**
|
12
|
+
* String representing the arabic numerals for use in secureRandomStringFrom
|
13
|
+
* (can be combined with other such exports or other characters by appending strings)
|
14
|
+
*/
|
15
|
+
export declare const DIGITS = "0123456789";
|
1
16
|
export declare function secureRandomBase64Url(len: number): string;
|
2
|
-
|
3
|
-
|
4
|
-
|
17
|
+
/**
|
18
|
+
* Generates a random string of uppercase and lowercase letters plus digits using a
|
19
|
+
* cryptographically secure random number generator.
|
20
|
+
* @param len The length of the string to generate
|
21
|
+
* @returns Random string of uppercase and lowercase letters plus digits of length `len`
|
22
|
+
*/
|
23
|
+
export declare function secureRandomString(len: number): string;
|
24
|
+
/**
|
25
|
+
* Generate a cryptographically secure random string using characters given.
|
26
|
+
*
|
27
|
+
* @param len - The length of the string to generate (must be positive and less than 32768).
|
28
|
+
* @param chars - The characters to use in the random string (between 2 and 256 characters long).
|
29
|
+
* @returns Random string of characters of length `len`.
|
30
|
+
*/
|
31
|
+
export declare function secureRandomStringFrom(len: number, chars: string): string;
|
5
32
|
//# sourceMappingURL=randomstring.d.ts.map
|
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"file":"randomstring.d.ts","sourceRoot":"","sources":["../src/randomstring.ts"],"names":[],"mappings":"
|
1
|
+
{"version":3,"file":"randomstring.d.ts","sourceRoot":"","sources":["../src/randomstring.ts"],"names":[],"mappings":"AAmBA;;;GAGG;AACH,eAAO,MAAM,SAAS,+BAA+B,CAAC;AAEtD;;;GAGG;AACH,eAAO,MAAM,SAAS,+BAA+B,CAAC;AAEtD;;;GAGG;AACH,eAAO,MAAM,MAAM,eAAe,CAAC;AAEnC,wBAAgB,qBAAqB,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,CAKzD;AAED;;;;;GAKG;AACH,wBAAgB,kBAAkB,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,CAEtD;AAED;;;;;;GAMG;AACH,wBAAgB,sBAAsB,CAAC,GAAG,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,GAAG,MAAM,CAmCzE"}
|
package/lib/randomstring.js
CHANGED
@@ -16,28 +16,80 @@ limitations under the License.
|
|
16
16
|
*/
|
17
17
|
|
18
18
|
import { encodeUnpaddedBase64Url } from "./base64.js";
|
19
|
-
|
20
|
-
|
21
|
-
|
19
|
+
|
20
|
+
/**
|
21
|
+
* String representing the lowercase latin alphabet for use in {@link secureRandomStringFrom}
|
22
|
+
* (can be combined with other such exports or other characters by appending strings)
|
23
|
+
*/
|
24
|
+
export var LOWERCASE = "abcdefghijklmnopqrstuvwxyz";
|
25
|
+
|
26
|
+
/**
|
27
|
+
* String representing the uppercase latin alphabet for use in secureRandomStringFrom
|
28
|
+
* (can be combined with other such exports or other characters by appending strings)
|
29
|
+
*/
|
30
|
+
export var UPPERCASE = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
|
31
|
+
|
32
|
+
/**
|
33
|
+
* String representing the arabic numerals for use in secureRandomStringFrom
|
34
|
+
* (can be combined with other such exports or other characters by appending strings)
|
35
|
+
*/
|
36
|
+
export var DIGITS = "0123456789";
|
22
37
|
export function secureRandomBase64Url(len) {
|
23
38
|
var key = new Uint8Array(len);
|
24
39
|
globalThis.crypto.getRandomValues(key);
|
25
40
|
return encodeUnpaddedBase64Url(key);
|
26
41
|
}
|
27
|
-
|
28
|
-
|
29
|
-
|
30
|
-
|
31
|
-
|
32
|
-
|
33
|
-
|
34
|
-
|
42
|
+
|
43
|
+
/**
|
44
|
+
* Generates a random string of uppercase and lowercase letters plus digits using a
|
45
|
+
* cryptographically secure random number generator.
|
46
|
+
* @param len The length of the string to generate
|
47
|
+
* @returns Random string of uppercase and lowercase letters plus digits of length `len`
|
48
|
+
*/
|
49
|
+
export function secureRandomString(len) {
|
50
|
+
return secureRandomStringFrom(len, UPPERCASE + LOWERCASE + DIGITS);
|
35
51
|
}
|
36
|
-
|
37
|
-
|
38
|
-
|
39
|
-
|
52
|
+
|
53
|
+
/**
|
54
|
+
* Generate a cryptographically secure random string using characters given.
|
55
|
+
*
|
56
|
+
* @param len - The length of the string to generate (must be positive and less than 32768).
|
57
|
+
* @param chars - The characters to use in the random string (between 2 and 256 characters long).
|
58
|
+
* @returns Random string of characters of length `len`.
|
59
|
+
*/
|
60
|
+
export function secureRandomStringFrom(len, chars) {
|
61
|
+
// This is intended for latin strings so 256 possibilities should be more than enough and
|
62
|
+
// means we can use random bytes, minimising the amount of entropy we need to ask for.
|
63
|
+
if (chars.length < 2 || chars.length > 256) {
|
64
|
+
throw new Error("Character set must be between 2 and 256 characters long");
|
65
|
+
}
|
66
|
+
if (len < 1 || len > 32768) {
|
67
|
+
throw new Error("Requested random string length must be between 1 and 32768");
|
68
|
+
}
|
69
|
+
// We'll generate random unsigned bytes, so get the largest number less than 256 that is a multiple
|
70
|
+
// of the length of the character set: We'll need to discard any random values that are larger than
|
71
|
+
// this as we can't possibly map them onto the character set while keeping each character equally
|
72
|
+
// likely to be chosen (minus 1 to convert to indices in a string). (Essentially, we're using a d8
|
73
|
+
// to choose between 7 possibilities and re-rolling on an 8, keeping all 7 outcomes equally likely.)
|
74
|
+
// Our random values must be strictly less than this
|
75
|
+
var randomValueCutoff = 256 - 256 % chars.length;
|
76
|
+
// Grab 30% more entropy than we need. This should be enough that we can discard the values that are
|
77
|
+
// too high without having to go back and grab more unless we're super unlucky.
|
78
|
+
var entropyBuffer = new Uint8Array(Math.floor(len * 1.3));
|
79
|
+
// Mark all of this buffer as used to start with (we haven't populated it with entropy yet) so it will
|
80
|
+
// be filled on the first iteration.
|
81
|
+
var entropyBufferPos = entropyBuffer.length;
|
82
|
+
var result = [];
|
83
|
+
while (result.length < len) {
|
84
|
+
if (entropyBufferPos === entropyBuffer.length) {
|
85
|
+
globalThis.crypto.getRandomValues(entropyBuffer);
|
86
|
+
entropyBufferPos = 0;
|
87
|
+
}
|
88
|
+
var randomByte = entropyBuffer[entropyBufferPos++];
|
89
|
+
if (randomByte < randomValueCutoff) {
|
90
|
+
result.push(chars[randomByte % chars.length]);
|
91
|
+
}
|
40
92
|
}
|
41
|
-
return
|
93
|
+
return result.join("");
|
42
94
|
}
|
43
95
|
//# sourceMappingURL=randomstring.js.map
|
package/lib/randomstring.js.map
CHANGED
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"file":"randomstring.js","names":["encodeUnpaddedBase64Url","LOWERCASE","UPPERCASE","DIGITS","secureRandomBase64Url","len","key","Uint8Array","globalThis","crypto","getRandomValues","
|
1
|
+
{"version":3,"file":"randomstring.js","names":["encodeUnpaddedBase64Url","LOWERCASE","UPPERCASE","DIGITS","secureRandomBase64Url","len","key","Uint8Array","globalThis","crypto","getRandomValues","secureRandomString","secureRandomStringFrom","chars","length","Error","randomValueCutoff","entropyBuffer","Math","floor","entropyBufferPos","result","randomByte","push","join"],"sources":["../src/randomstring.ts"],"sourcesContent":["/*\nCopyright 2018 New Vector Ltd\nCopyright 2019 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 { encodeUnpaddedBase64Url } from \"./base64.ts\";\n\n/**\n * String representing the lowercase latin alphabet for use in {@link secureRandomStringFrom}\n * (can be combined with other such exports or other characters by appending strings)\n */\nexport const LOWERCASE = \"abcdefghijklmnopqrstuvwxyz\";\n\n/**\n * String representing the uppercase latin alphabet for use in secureRandomStringFrom\n * (can be combined with other such exports or other characters by appending strings)\n */\nexport const UPPERCASE = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\";\n\n/**\n * String representing the arabic numerals for use in secureRandomStringFrom\n * (can be combined with other such exports or other characters by appending strings)\n */\nexport const DIGITS = \"0123456789\";\n\nexport function secureRandomBase64Url(len: number): string {\n const key = new Uint8Array(len);\n globalThis.crypto.getRandomValues(key);\n\n return encodeUnpaddedBase64Url(key);\n}\n\n/**\n * Generates a random string of uppercase and lowercase letters plus digits using a\n * cryptographically secure random number generator.\n * @param len The length of the string to generate\n * @returns Random string of uppercase and lowercase letters plus digits of length `len`\n */\nexport function secureRandomString(len: number): string {\n return secureRandomStringFrom(len, UPPERCASE + LOWERCASE + DIGITS);\n}\n\n/**\n * Generate a cryptographically secure random string using characters given.\n *\n * @param len - The length of the string to generate (must be positive and less than 32768).\n * @param chars - The characters to use in the random string (between 2 and 256 characters long).\n * @returns Random string of characters of length `len`.\n */\nexport function secureRandomStringFrom(len: number, chars: string): string {\n // This is intended for latin strings so 256 possibilities should be more than enough and\n // means we can use random bytes, minimising the amount of entropy we need to ask for.\n if (chars.length < 2 || chars.length > 256) {\n throw new Error(\"Character set must be between 2 and 256 characters long\");\n }\n if (len < 1 || len > 32768) {\n throw new Error(\"Requested random string length must be between 1 and 32768\");\n }\n // We'll generate random unsigned bytes, so get the largest number less than 256 that is a multiple\n // of the length of the character set: We'll need to discard any random values that are larger than\n // this as we can't possibly map them onto the character set while keeping each character equally\n // likely to be chosen (minus 1 to convert to indices in a string). (Essentially, we're using a d8\n // to choose between 7 possibilities and re-rolling on an 8, keeping all 7 outcomes equally likely.)\n // Our random values must be strictly less than this\n const randomValueCutoff = 256 - (256 % chars.length);\n // Grab 30% more entropy than we need. This should be enough that we can discard the values that are\n // too high without having to go back and grab more unless we're super unlucky.\n const entropyBuffer = new Uint8Array(Math.floor(len * 1.3));\n // Mark all of this buffer as used to start with (we haven't populated it with entropy yet) so it will\n // be filled on the first iteration.\n let entropyBufferPos = entropyBuffer.length;\n const result = [];\n while (result.length < len) {\n if (entropyBufferPos === entropyBuffer.length) {\n globalThis.crypto.getRandomValues(entropyBuffer);\n entropyBufferPos = 0;\n }\n const randomByte = entropyBuffer[entropyBufferPos++];\n if (randomByte < randomValueCutoff) {\n result.push(chars[randomByte % chars.length]);\n }\n }\n\n return result.join(\"\");\n}\n"],"mappings":"AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA,SAASA,uBAAuB,QAAQ,aAAa;;AAErD;AACA;AACA;AACA;AACA,OAAO,IAAMC,SAAS,GAAG,4BAA4B;;AAErD;AACA;AACA;AACA;AACA,OAAO,IAAMC,SAAS,GAAG,4BAA4B;;AAErD;AACA;AACA;AACA;AACA,OAAO,IAAMC,MAAM,GAAG,YAAY;AAElC,OAAO,SAASC,qBAAqBA,CAACC,GAAW,EAAU;EACvD,IAAMC,GAAG,GAAG,IAAIC,UAAU,CAACF,GAAG,CAAC;EAC/BG,UAAU,CAACC,MAAM,CAACC,eAAe,CAACJ,GAAG,CAAC;EAEtC,OAAON,uBAAuB,CAACM,GAAG,CAAC;AACvC;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO,SAASK,kBAAkBA,CAACN,GAAW,EAAU;EACpD,OAAOO,sBAAsB,CAACP,GAAG,EAAEH,SAAS,GAAGD,SAAS,GAAGE,MAAM,CAAC;AACtE;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO,SAASS,sBAAsBA,CAACP,GAAW,EAAEQ,KAAa,EAAU;EACvE;EACA;EACA,IAAIA,KAAK,CAACC,MAAM,GAAG,CAAC,IAAID,KAAK,CAACC,MAAM,GAAG,GAAG,EAAE;IACxC,MAAM,IAAIC,KAAK,CAAC,yDAAyD,CAAC;EAC9E;EACA,IAAIV,GAAG,GAAG,CAAC,IAAIA,GAAG,GAAG,KAAK,EAAE;IACxB,MAAM,IAAIU,KAAK,CAAC,4DAA4D,CAAC;EACjF;EACA;EACA;EACA;EACA;EACA;EACA;EACA,IAAMC,iBAAiB,GAAG,GAAG,GAAI,GAAG,GAAGH,KAAK,CAACC,MAAO;EACpD;EACA;EACA,IAAMG,aAAa,GAAG,IAAIV,UAAU,CAACW,IAAI,CAACC,KAAK,CAACd,GAAG,GAAG,GAAG,CAAC,CAAC;EAC3D;EACA;EACA,IAAIe,gBAAgB,GAAGH,aAAa,CAACH,MAAM;EAC3C,IAAMO,MAAM,GAAG,EAAE;EACjB,OAAOA,MAAM,CAACP,MAAM,GAAGT,GAAG,EAAE;IACxB,IAAIe,gBAAgB,KAAKH,aAAa,CAACH,MAAM,EAAE;MAC3CN,UAAU,CAACC,MAAM,CAACC,eAAe,CAACO,aAAa,CAAC;MAChDG,gBAAgB,GAAG,CAAC;IACxB;IACA,IAAME,UAAU,GAAGL,aAAa,CAACG,gBAAgB,EAAE,CAAC;IACpD,IAAIE,UAAU,GAAGN,iBAAiB,EAAE;MAChCK,MAAM,CAACE,IAAI,CAACV,KAAK,CAACS,UAAU,GAAGT,KAAK,CAACC,MAAM,CAAC,CAAC;IACjD;EACJ;EAEA,OAAOO,MAAM,CAACG,IAAI,CAAC,EAAE,CAAC;AAC1B","ignoreList":[]}
|
@@ -69,7 +69,8 @@ function selectQuery(store, keyRange, resultMapper) {
|
|
69
69
|
return new Promise((resolve, reject) => {
|
70
70
|
var results = [];
|
71
71
|
query.onerror = () => {
|
72
|
-
|
72
|
+
var _query$error;
|
73
|
+
reject(new Error("Query failed: " + ((_query$error = query.error) === null || _query$error === void 0 ? void 0 : _query$error.name)));
|
73
74
|
};
|
74
75
|
// collect results
|
75
76
|
query.onsuccess = () => {
|
@@ -332,10 +333,11 @@ export class LocalIndexedDBStoreBackend {
|
|
332
333
|
logger.log("can't yet delete indexeddb ".concat(this.dbName, " because it is open elsewhere"));
|
333
334
|
};
|
334
335
|
req.onerror = () => {
|
336
|
+
var _req$error;
|
335
337
|
// in firefox, with indexedDB disabled, this fails with a
|
336
338
|
// DOMError. We treat this as non-fatal, so that we can still
|
337
339
|
// use the app.
|
338
|
-
logger.warn("unable to delete js-sdk store indexeddb: ".concat(req.error));
|
340
|
+
logger.warn("unable to delete js-sdk store indexeddb: ".concat((_req$error = req.error) === null || _req$error === void 0 ? void 0 : _req$error.name));
|
339
341
|
resolve();
|
340
342
|
};
|
341
343
|
req.onsuccess = () => {
|
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"file":"indexeddb-local-backend.js","names":["SyncAccumulator","deepCopy","promiseTry","exists","idbExists","logger","DB_MIGRATIONS","db","createObjectStore","keyPath","oobMembersStore","createIndex","autoIncrement","VERSION","length","selectQuery","store","keyRange","resultMapper","query","openCursor","Promise","resolve","reject","results","onerror","Error","error","onsuccess","cursor","result","push","continue","txnAsPromise","txn","oncomplete","event","reqAsEventPromise","req","reqAsPromise","err","reqAsCursorPromise","then","LocalIndexedDBStoreBackend","indexedDB","dbName","constructor","arguments","undefined","_defineProperty","syncAccumulator","connect","onClose","_this","disconnected","log","open","onupgradeneeded","ev","oldVersion","concat","_isNewlyCreated","forEach","migration","index","onblocked","_asyncToGenerator","onversionchange","_this$db","close","onclose","init","isNewlyCreated","all","loadAccountData","loadSyncData","_ref2","accountData","syncData","accumulate","next_batch","nextBatch","rooms","roomsData","account_data","events","getOutOfBandMembers","roomId","tx","transaction","objectStore","roomIndex","range","IDBKeyRange","only","request","membershipEvents","oobWritten","record","value","oob_written","setOutOfBandMembers","_this2","e","put","markerObject","room_id","state_key","clearOutOfBandMembers","_this3","readTx","roomRange","minStateKeyProm","openKeyCursor","primaryKey","maxStateKeyProm","minStateKey","maxStateKey","writeTx","writeStore","membersKeyRange","bound","delete","clearDatabase","_this$db2","deleteDatabase","warn","getSavedSync","copy","data","getJSON","getNextBatchToken","setSyncData","syncToDatabase","userTuples","_this4","syncToDatabasePromise","pendingUserPresenceData","unshift","doSyncToDatabase","_this5","persistUserPresenceEvents","persistAccountData","persistSyncData","clobber","tuples","tuple","userId","getUserPresenceEvents","getClientOptions","_cursor$value","options","storeClientOptions","_this6","saveToDeviceBatches","batches","_this7","batch","add","getOldestToDeviceBatch","_this8","resultBatch","id","key","txnId","eventType","removeToDeviceBatch","_this9","destroy","_this10","_this10$db"],"sources":["../../src/store/indexeddb-local-backend.ts"],"sourcesContent":["/*\nCopyright 2017 - 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { IMinimalEvent, ISyncData, ISyncResponse, SyncAccumulator } from \"../sync-accumulator.ts\";\nimport { deepCopy, promiseTry } from \"../utils.ts\";\nimport { exists as idbExists } from \"../indexeddb-helpers.ts\";\nimport { logger } from \"../logger.ts\";\nimport { IStateEventWithRoomId, IStoredClientOpts } from \"../matrix.ts\";\nimport { ISavedSync } from \"./index.ts\";\nimport { IIndexedDBBackend, UserTuple } from \"./indexeddb-backend.ts\";\nimport { IndexedToDeviceBatch, ToDeviceBatchWithTxnId } from \"../models/ToDeviceMessage.ts\";\n\ntype DbMigration = (db: IDBDatabase) => void;\nconst DB_MIGRATIONS: DbMigration[] = [\n (db): void => {\n // Make user store, clobber based on user ID. (userId property of User objects)\n db.createObjectStore(\"users\", { keyPath: [\"userId\"] });\n\n // Make account data store, clobber based on event type.\n // (event.type property of MatrixEvent objects)\n db.createObjectStore(\"accountData\", { keyPath: [\"type\"] });\n\n // Make /sync store (sync tokens, room data, etc), always clobber (const key).\n db.createObjectStore(\"sync\", { keyPath: [\"clobber\"] });\n },\n (db): void => {\n const oobMembersStore = db.createObjectStore(\"oob_membership_events\", {\n keyPath: [\"room_id\", \"state_key\"],\n });\n oobMembersStore.createIndex(\"room\", \"room_id\");\n },\n (db): void => {\n db.createObjectStore(\"client_options\", { keyPath: [\"clobber\"] });\n },\n (db): void => {\n db.createObjectStore(\"to_device_queue\", { autoIncrement: true });\n },\n // Expand as needed.\n];\nconst VERSION = DB_MIGRATIONS.length;\n\n/**\n * Helper method to collect results from a Cursor and promiseify it.\n * @param store - The store to perform openCursor on.\n * @param keyRange - Optional key range to apply on the cursor.\n * @param resultMapper - A function which is repeatedly called with a\n * Cursor.\n * Return the data you want to keep.\n * @returns Promise which resolves to an array of whatever you returned from\n * resultMapper.\n */\nfunction selectQuery<T>(\n store: IDBObjectStore,\n keyRange: IDBKeyRange | IDBValidKey | undefined,\n resultMapper: (cursor: IDBCursorWithValue) => T,\n): Promise<T[]> {\n const query = store.openCursor(keyRange);\n return new Promise((resolve, reject) => {\n const results: T[] = [];\n query.onerror = (): void => {\n reject(new Error(\"Query failed: \" + query.error));\n };\n // collect results\n query.onsuccess = (): void => {\n const cursor = query.result;\n if (!cursor) {\n resolve(results);\n return; // end of results\n }\n results.push(resultMapper(cursor));\n cursor.continue();\n };\n });\n}\n\nfunction txnAsPromise(txn: IDBTransaction): Promise<Event> {\n return new Promise((resolve, reject) => {\n txn.oncomplete = function (event): void {\n resolve(event);\n };\n txn.onerror = function (): void {\n reject(txn.error);\n };\n });\n}\n\nfunction reqAsEventPromise(req: IDBRequest): Promise<Event> {\n return new Promise((resolve, reject) => {\n req.onsuccess = function (event): void {\n resolve(event);\n };\n req.onerror = function (): void {\n reject(req.error);\n };\n });\n}\n\nfunction reqAsPromise(req: IDBRequest): Promise<IDBRequest> {\n return new Promise((resolve, reject) => {\n req.onsuccess = (): void => resolve(req);\n req.onerror = (err): void => reject(err);\n });\n}\n\nfunction reqAsCursorPromise<T>(req: IDBRequest<T>): Promise<T> {\n return reqAsEventPromise(req).then((event) => req.result);\n}\n\nexport class LocalIndexedDBStoreBackend implements IIndexedDBBackend {\n public static exists(indexedDB: IDBFactory, dbName: string): Promise<boolean> {\n dbName = \"matrix-js-sdk:\" + (dbName || \"default\");\n return idbExists(indexedDB, dbName);\n }\n\n private readonly dbName: string;\n private readonly syncAccumulator: SyncAccumulator;\n private db?: IDBDatabase;\n private disconnected = true;\n private _isNewlyCreated = false;\n private syncToDatabasePromise?: Promise<void>;\n private pendingUserPresenceData: UserTuple[] = [];\n\n /**\n * Does the actual reading from and writing to the indexeddb\n *\n * Construct a new Indexed Database store backend. This requires a call to\n * `connect()` before this store can be used.\n * @param indexedDB - The Indexed DB interface e.g\n * `window.indexedDB`\n * @param dbName - Optional database name. The same name must be used\n * to open the same database.\n */\n public constructor(\n private readonly indexedDB: IDBFactory,\n dbName = \"default\",\n ) {\n this.dbName = \"matrix-js-sdk:\" + dbName;\n this.syncAccumulator = new SyncAccumulator();\n }\n\n /**\n * Attempt to connect to the database. This can fail if the user does not\n * grant permission.\n * @returns Promise which resolves if successfully connected.\n */\n public connect(onClose?: () => void): Promise<void> {\n if (!this.disconnected) {\n logger.log(`LocalIndexedDBStoreBackend.connect: already connected or connecting`);\n return Promise.resolve();\n }\n\n this.disconnected = false;\n\n logger.log(`LocalIndexedDBStoreBackend.connect: connecting...`);\n const req = this.indexedDB.open(this.dbName, VERSION);\n req.onupgradeneeded = (ev): void => {\n const db = req.result;\n const oldVersion = ev.oldVersion;\n logger.log(`LocalIndexedDBStoreBackend.connect: upgrading from ${oldVersion}`);\n if (oldVersion < 1) {\n // The database did not previously exist\n this._isNewlyCreated = true;\n }\n DB_MIGRATIONS.forEach((migration, index) => {\n if (oldVersion <= index) migration(db);\n });\n };\n\n req.onblocked = (): void => {\n logger.log(`can't yet open LocalIndexedDBStoreBackend because it is open elsewhere`);\n };\n\n logger.log(`LocalIndexedDBStoreBackend.connect: awaiting connection...`);\n return reqAsEventPromise(req).then(async () => {\n logger.log(`LocalIndexedDBStoreBackend.connect: connected`);\n this.db = req.result;\n\n // add a poorly-named listener for when deleteDatabase is called\n // so we can close our db connections.\n this.db.onversionchange = (): void => {\n this.db?.close(); // this does not call onclose\n this.disconnected = true;\n this.db = undefined;\n };\n this.db.onclose = (): void => {\n this.disconnected = true;\n this.db = undefined;\n onClose?.();\n };\n\n await this.init();\n });\n }\n\n /** @returns whether or not the database was newly created in this session. */\n public isNewlyCreated(): Promise<boolean> {\n return Promise.resolve(this._isNewlyCreated);\n }\n\n /**\n * Having connected, load initial data from the database and prepare for use\n * @returns Promise which resolves on success\n */\n private init(): Promise<unknown> {\n return Promise.all([this.loadAccountData(), this.loadSyncData()]).then(([accountData, syncData]) => {\n logger.log(`LocalIndexedDBStoreBackend: loaded initial data`);\n this.syncAccumulator.accumulate(\n {\n next_batch: syncData.nextBatch,\n rooms: syncData.roomsData,\n account_data: {\n events: accountData,\n },\n },\n true,\n );\n });\n }\n\n /**\n * Returns the out-of-band membership events for this room that\n * were previously loaded.\n * @returns the events, potentially an empty array if OOB loading didn't yield any new members\n * @returns in case the members for this room haven't been stored yet\n */\n public getOutOfBandMembers(roomId: string): Promise<IStateEventWithRoomId[] | null> {\n return new Promise<IStateEventWithRoomId[] | null>((resolve, reject) => {\n const tx = this.db!.transaction([\"oob_membership_events\"], \"readonly\");\n const store = tx.objectStore(\"oob_membership_events\");\n const roomIndex = store.index(\"room\");\n const range = IDBKeyRange.only(roomId);\n const request = roomIndex.openCursor(range);\n\n const membershipEvents: IStateEventWithRoomId[] = [];\n // did we encounter the oob_written marker object\n // amongst the results? That means OOB member\n // loading already happened for this room\n // but there were no members to persist as they\n // were all known already\n let oobWritten = false;\n\n request.onsuccess = (): void => {\n const cursor = request.result;\n if (!cursor) {\n // Unknown room\n if (!membershipEvents.length && !oobWritten) {\n return resolve(null);\n }\n return resolve(membershipEvents);\n }\n const record = cursor.value;\n if (record.oob_written) {\n oobWritten = true;\n } else {\n membershipEvents.push(record);\n }\n cursor.continue();\n };\n request.onerror = (err): void => {\n reject(err);\n };\n }).then((events) => {\n logger.log(`LL: got ${events?.length} membershipEvents from storage for room ${roomId} ...`);\n return events;\n });\n }\n\n /**\n * Stores the out-of-band membership events for this room. Note that\n * it still makes sense to store an empty array as the OOB status for the room is\n * marked as fetched, and getOutOfBandMembers will return an empty array instead of null\n * @param membershipEvents - the membership events to store\n */\n public async setOutOfBandMembers(roomId: string, membershipEvents: IStateEventWithRoomId[]): Promise<void> {\n logger.log(`LL: backend about to store ${membershipEvents.length}` + ` members for ${roomId}`);\n const tx = this.db!.transaction([\"oob_membership_events\"], \"readwrite\");\n const store = tx.objectStore(\"oob_membership_events\");\n membershipEvents.forEach((e) => {\n store.put(e);\n });\n // aside from all the events, we also write a marker object to the store\n // to mark the fact that OOB members have been written for this room.\n // It's possible that 0 members need to be written as all where previously know\n // but we still need to know whether to return null or [] from getOutOfBandMembers\n // where null means out of band members haven't been stored yet for this room\n const markerObject = {\n room_id: roomId,\n oob_written: true,\n state_key: 0,\n };\n store.put(markerObject);\n await txnAsPromise(tx);\n logger.log(`LL: backend done storing for ${roomId}!`);\n }\n\n public async clearOutOfBandMembers(roomId: string): Promise<void> {\n // the approach to delete all members for a room\n // is to get the min and max state key from the index\n // for that room, and then delete between those\n // keys in the store.\n // this should be way faster than deleting every member\n // individually for a large room.\n const readTx = this.db!.transaction([\"oob_membership_events\"], \"readonly\");\n const store = readTx.objectStore(\"oob_membership_events\");\n const roomIndex = store.index(\"room\");\n const roomRange = IDBKeyRange.only(roomId);\n\n const minStateKeyProm = reqAsCursorPromise(roomIndex.openKeyCursor(roomRange, \"next\")).then(\n (cursor) => (<IDBValidKey[]>cursor?.primaryKey)[1],\n );\n const maxStateKeyProm = reqAsCursorPromise(roomIndex.openKeyCursor(roomRange, \"prev\")).then(\n (cursor) => (<IDBValidKey[]>cursor?.primaryKey)[1],\n );\n const [minStateKey, maxStateKey] = await Promise.all([minStateKeyProm, maxStateKeyProm]);\n\n const writeTx = this.db!.transaction([\"oob_membership_events\"], \"readwrite\");\n const writeStore = writeTx.objectStore(\"oob_membership_events\");\n const membersKeyRange = IDBKeyRange.bound([roomId, minStateKey], [roomId, maxStateKey]);\n\n logger.log(\n `LL: Deleting all users + marker in storage for room ${roomId}, with key range:`,\n [roomId, minStateKey],\n [roomId, maxStateKey],\n );\n await reqAsPromise(writeStore.delete(membersKeyRange));\n }\n\n /**\n * Clear the entire database. This should be used when logging out of a client\n * to prevent mixing data between accounts. Closes the database.\n * @returns Resolved when the database is cleared.\n */\n public clearDatabase(): Promise<void> {\n return new Promise((resolve) => {\n logger.log(`Removing indexeddb instance: ${this.dbName}`);\n\n // Close the database first to avoid firing unexpected close events\n this.db?.close();\n\n const req = this.indexedDB.deleteDatabase(this.dbName);\n\n req.onblocked = (): void => {\n logger.log(`can't yet delete indexeddb ${this.dbName} because it is open elsewhere`);\n };\n\n req.onerror = (): void => {\n // in firefox, with indexedDB disabled, this fails with a\n // DOMError. We treat this as non-fatal, so that we can still\n // use the app.\n logger.warn(`unable to delete js-sdk store indexeddb: ${req.error}`);\n resolve();\n };\n\n req.onsuccess = (): void => {\n logger.log(`Removed indexeddb instance: ${this.dbName}`);\n resolve();\n };\n });\n }\n\n /**\n * @param copy - If false, the data returned is from internal\n * buffers and must not be mutated. Otherwise, a copy is made before\n * returning such that the data can be safely mutated. Default: true.\n *\n * @returns Promise which resolves with a sync response to restore the\n * client state to where it was at the last save, or null if there\n * is no saved sync data.\n */\n public getSavedSync(copy = true): Promise<ISavedSync | null> {\n const data = this.syncAccumulator.getJSON();\n if (!data.nextBatch) return Promise.resolve(null);\n if (copy) {\n // We must deep copy the stored data so that the /sync processing code doesn't\n // corrupt the internal state of the sync accumulator (it adds non-clonable keys)\n return Promise.resolve(deepCopy(data));\n } else {\n return Promise.resolve(data);\n }\n }\n\n public getNextBatchToken(): Promise<string> {\n return Promise.resolve(this.syncAccumulator.getNextBatchToken());\n }\n\n public setSyncData(syncData: ISyncResponse): Promise<void> {\n return Promise.resolve().then(() => {\n this.syncAccumulator.accumulate(syncData);\n });\n }\n\n /**\n * Sync users and all accumulated sync data to the database.\n * If a previous sync is in flight, the new data will be added to the\n * next sync and the current sync's promise will be returned.\n * @param userTuples - The user tuples\n * @returns Promise which resolves if the data was persisted.\n */\n public async syncToDatabase(userTuples: UserTuple[]): Promise<void> {\n if (this.syncToDatabasePromise) {\n logger.warn(\"Skipping syncToDatabase() as persist already in flight\");\n this.pendingUserPresenceData.push(...userTuples);\n return this.syncToDatabasePromise;\n }\n userTuples.unshift(...this.pendingUserPresenceData);\n this.syncToDatabasePromise = this.doSyncToDatabase(userTuples);\n return this.syncToDatabasePromise;\n }\n\n private async doSyncToDatabase(userTuples: UserTuple[]): Promise<void> {\n try {\n const syncData = this.syncAccumulator.getJSON(true);\n await Promise.all([\n this.persistUserPresenceEvents(userTuples),\n this.persistAccountData(syncData.accountData),\n this.persistSyncData(syncData.nextBatch, syncData.roomsData),\n ]);\n } finally {\n this.syncToDatabasePromise = undefined;\n }\n }\n\n /**\n * Persist rooms /sync data along with the next batch token.\n * @param nextBatch - The next_batch /sync value.\n * @param roomsData - The 'rooms' /sync data from a SyncAccumulator\n * @returns Promise which resolves if the data was persisted.\n */\n private persistSyncData(nextBatch: string, roomsData: ISyncResponse[\"rooms\"]): Promise<void> {\n logger.log(\"Persisting sync data up to\", nextBatch);\n return promiseTry<void>(() => {\n const txn = this.db!.transaction([\"sync\"], \"readwrite\");\n const store = txn.objectStore(\"sync\");\n store.put({\n clobber: \"-\", // constant key so will always clobber\n nextBatch,\n roomsData,\n }); // put == UPSERT\n return txnAsPromise(txn).then(() => {\n logger.log(\"Persisted sync data up to\", nextBatch);\n });\n });\n }\n\n /**\n * Persist a list of account data events. Events with the same 'type' will\n * be replaced.\n * @param accountData - An array of raw user-scoped account data events\n * @returns Promise which resolves if the events were persisted.\n */\n private persistAccountData(accountData: IMinimalEvent[]): Promise<void> {\n return promiseTry<void>(() => {\n const txn = this.db!.transaction([\"accountData\"], \"readwrite\");\n const store = txn.objectStore(\"accountData\");\n for (const event of accountData) {\n store.put(event); // put == UPSERT\n }\n return txnAsPromise(txn).then();\n });\n }\n\n /**\n * Persist a list of [user id, presence event] they are for.\n * Users with the same 'userId' will be replaced.\n * Presence events should be the event in its raw form (not the Event\n * object)\n * @param tuples - An array of [userid, event] tuples\n * @returns Promise which resolves if the users were persisted.\n */\n private persistUserPresenceEvents(tuples: UserTuple[]): Promise<void> {\n return promiseTry<void>(() => {\n const txn = this.db!.transaction([\"users\"], \"readwrite\");\n const store = txn.objectStore(\"users\");\n for (const tuple of tuples) {\n store.put({\n userId: tuple[0],\n event: tuple[1],\n }); // put == UPSERT\n }\n return txnAsPromise(txn).then();\n });\n }\n\n /**\n * Load all user presence events from the database. This is not cached.\n * FIXME: It would probably be more sensible to store the events in the\n * sync.\n * @returns A list of presence events in their raw form.\n */\n public getUserPresenceEvents(): Promise<UserTuple[]> {\n return promiseTry<UserTuple[]>(() => {\n const txn = this.db!.transaction([\"users\"], \"readonly\");\n const store = txn.objectStore(\"users\");\n return selectQuery(store, undefined, (cursor) => {\n return [cursor.value.userId, cursor.value.event];\n });\n });\n }\n\n /**\n * Load all the account data events from the database. This is not cached.\n * @returns A list of raw global account events.\n */\n private loadAccountData(): Promise<IMinimalEvent[]> {\n logger.log(`LocalIndexedDBStoreBackend: loading account data...`);\n return promiseTry<IMinimalEvent[]>(() => {\n const txn = this.db!.transaction([\"accountData\"], \"readonly\");\n const store = txn.objectStore(\"accountData\");\n return selectQuery(store, undefined, (cursor) => {\n return cursor.value;\n }).then((result: IMinimalEvent[]) => {\n logger.log(`LocalIndexedDBStoreBackend: loaded account data`);\n return result;\n });\n });\n }\n\n /**\n * Load the sync data from the database.\n * @returns An object with \"roomsData\" and \"nextBatch\" keys.\n */\n private loadSyncData(): Promise<ISyncData> {\n logger.log(`LocalIndexedDBStoreBackend: loading sync data...`);\n return promiseTry<ISyncData>(() => {\n const txn = this.db!.transaction([\"sync\"], \"readonly\");\n const store = txn.objectStore(\"sync\");\n return selectQuery(store, undefined, (cursor) => {\n return cursor.value;\n }).then((results: ISyncData[]) => {\n logger.log(`LocalIndexedDBStoreBackend: loaded sync data`);\n if (results.length > 1) {\n logger.warn(\"loadSyncData: More than 1 sync row found.\");\n }\n return results.length > 0 ? results[0] : ({} as ISyncData);\n });\n });\n }\n\n public getClientOptions(): Promise<IStoredClientOpts | undefined> {\n return Promise.resolve().then(() => {\n const txn = this.db!.transaction([\"client_options\"], \"readonly\");\n const store = txn.objectStore(\"client_options\");\n return selectQuery(store, undefined, (cursor) => {\n return cursor.value?.options;\n }).then((results) => results[0]);\n });\n }\n\n public async storeClientOptions(options: IStoredClientOpts): Promise<void> {\n const txn = this.db!.transaction([\"client_options\"], \"readwrite\");\n const store = txn.objectStore(\"client_options\");\n store.put({\n clobber: \"-\", // constant key so will always clobber\n options: options,\n }); // put == UPSERT\n await txnAsPromise(txn);\n }\n\n public async saveToDeviceBatches(batches: ToDeviceBatchWithTxnId[]): Promise<void> {\n const txn = this.db!.transaction([\"to_device_queue\"], \"readwrite\");\n const store = txn.objectStore(\"to_device_queue\");\n for (const batch of batches) {\n store.add(batch);\n }\n await txnAsPromise(txn);\n }\n\n public async getOldestToDeviceBatch(): Promise<IndexedToDeviceBatch | null> {\n const txn = this.db!.transaction([\"to_device_queue\"], \"readonly\");\n const store = txn.objectStore(\"to_device_queue\");\n const cursor = await reqAsCursorPromise(store.openCursor());\n if (!cursor) return null;\n\n const resultBatch = cursor.value as ToDeviceBatchWithTxnId;\n\n return {\n id: cursor.key as number,\n txnId: resultBatch.txnId,\n eventType: resultBatch.eventType,\n batch: resultBatch.batch,\n };\n }\n\n public async removeToDeviceBatch(id: number): Promise<void> {\n const txn = this.db!.transaction([\"to_device_queue\"], \"readwrite\");\n const store = txn.objectStore(\"to_device_queue\");\n store.delete(id);\n await txnAsPromise(txn);\n }\n\n /*\n * Close the database\n */\n public async destroy(): Promise<void> {\n this.db?.close();\n }\n}\n"],"mappings":";;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;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AC,CAAC,iBAAiB,CAAC,EAAE,UAAU,CAAC;MACjE,IAAMzE,KAAK,GAAGkB,GAAG,CAACwD,WAAW,CAAC,iBAAiB,CAAC;MAChD,IAAM7D,MAAM,SAASY,kBAAkB,CAACzB,KAAK,CAACI,UAAU,CAAC,CAAC,CAAC;MAC3D,IAAI,CAACS,MAAM,EAAE,OAAO,IAAI;MAExB,IAAMoI,WAAW,GAAGpI,MAAM,CAACsE,KAA+B;MAE1D,OAAO;QACH+D,EAAE,EAAErI,MAAM,CAACsI,GAAa;QACxBC,KAAK,EAAEH,WAAW,CAACG,KAAK;QACxBC,SAAS,EAAEJ,WAAW,CAACI,SAAS;QAChCR,KAAK,EAAEI,WAAW,CAACJ;MACvB,CAAC;IAAC;EACN;EAEaS,mBAAmBA,CAACJ,EAAU,EAAiB;IAAA,IAAAK,MAAA;IAAA,OAAArG,iBAAA;MACxD,IAAMhC,GAAG,GAAGqI,MAAI,CAAChK,EAAE,CAAEkF,WAAW,CAAC,CAAC,iBAAiB,CAAC,EAAE,WAAW,CAAC;MAClE,IAAMzE,KAAK,GAAGkB,GAAG,CAACwD,WAAW,CAAC,iBAAiB,CAAC;MAChD1E,KAAK,CAAC0G,MAAM,CAACwC,EAAE,CAAC;MAChB,MAAMjI,YAAY,CAACC,GAAG,CAAC;IAAC;EAC5B;;EAEA;AACJ;AACA;EACiBsI,OAAOA,CAAA,EAAkB;IAAA,IAAAC,OAAA;IAAA,OAAAvG,iBAAA;MAAA,IAAAwG,UAAA;MAClC,CAAAA,UAAA,GAAAD,OAAI,CAAClK,EAAE,cAAAmK,UAAA,eAAPA,UAAA,CAASrG,KAAK,CAAC,CAAC;IAAC;EACrB;AACJ","ignoreList":[]}
|
1
|
+
{"version":3,"file":"indexeddb-local-backend.js","names":["SyncAccumulator","deepCopy","promiseTry","exists","idbExists","logger","DB_MIGRATIONS","db","createObjectStore","keyPath","oobMembersStore","createIndex","autoIncrement","VERSION","length","selectQuery","store","keyRange","resultMapper","query","openCursor","Promise","resolve","reject","results","onerror","_query$error","Error","error","name","onsuccess","cursor","result","push","continue","txnAsPromise","txn","oncomplete","event","reqAsEventPromise","req","reqAsPromise","err","reqAsCursorPromise","then","LocalIndexedDBStoreBackend","indexedDB","dbName","constructor","arguments","undefined","_defineProperty","syncAccumulator","connect","onClose","_this","disconnected","log","open","onupgradeneeded","ev","oldVersion","concat","_isNewlyCreated","forEach","migration","index","onblocked","_asyncToGenerator","onversionchange","_this$db","close","onclose","init","isNewlyCreated","all","loadAccountData","loadSyncData","_ref2","accountData","syncData","accumulate","next_batch","nextBatch","rooms","roomsData","account_data","events","getOutOfBandMembers","roomId","tx","transaction","objectStore","roomIndex","range","IDBKeyRange","only","request","membershipEvents","oobWritten","record","value","oob_written","setOutOfBandMembers","_this2","e","put","markerObject","room_id","state_key","clearOutOfBandMembers","_this3","readTx","roomRange","minStateKeyProm","openKeyCursor","primaryKey","maxStateKeyProm","minStateKey","maxStateKey","writeTx","writeStore","membersKeyRange","bound","delete","clearDatabase","_this$db2","deleteDatabase","_req$error","warn","getSavedSync","copy","data","getJSON","getNextBatchToken","setSyncData","syncToDatabase","userTuples","_this4","syncToDatabasePromise","pendingUserPresenceData","unshift","doSyncToDatabase","_this5","persistUserPresenceEvents","persistAccountData","persistSyncData","clobber","tuples","tuple","userId","getUserPresenceEvents","getClientOptions","_cursor$value","options","storeClientOptions","_this6","saveToDeviceBatches","batches","_this7","batch","add","getOldestToDeviceBatch","_this8","resultBatch","id","key","txnId","eventType","removeToDeviceBatch","_this9","destroy","_this10","_this10$db"],"sources":["../../src/store/indexeddb-local-backend.ts"],"sourcesContent":["/*\nCopyright 2017 - 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { IMinimalEvent, ISyncData, ISyncResponse, SyncAccumulator } from \"../sync-accumulator.ts\";\nimport { deepCopy, promiseTry } from \"../utils.ts\";\nimport { exists as idbExists } from \"../indexeddb-helpers.ts\";\nimport { logger } from \"../logger.ts\";\nimport { IStateEventWithRoomId, IStoredClientOpts } from \"../matrix.ts\";\nimport { ISavedSync } from \"./index.ts\";\nimport { IIndexedDBBackend, UserTuple } from \"./indexeddb-backend.ts\";\nimport { IndexedToDeviceBatch, ToDeviceBatchWithTxnId } from \"../models/ToDeviceMessage.ts\";\n\ntype DbMigration = (db: IDBDatabase) => void;\nconst DB_MIGRATIONS: DbMigration[] = [\n (db): void => {\n // Make user store, clobber based on user ID. (userId property of User objects)\n db.createObjectStore(\"users\", { keyPath: [\"userId\"] });\n\n // Make account data store, clobber based on event type.\n // (event.type property of MatrixEvent objects)\n db.createObjectStore(\"accountData\", { keyPath: [\"type\"] });\n\n // Make /sync store (sync tokens, room data, etc), always clobber (const key).\n db.createObjectStore(\"sync\", { keyPath: [\"clobber\"] });\n },\n (db): void => {\n const oobMembersStore = db.createObjectStore(\"oob_membership_events\", {\n keyPath: [\"room_id\", \"state_key\"],\n });\n oobMembersStore.createIndex(\"room\", \"room_id\");\n },\n (db): void => {\n db.createObjectStore(\"client_options\", { keyPath: [\"clobber\"] });\n },\n (db): void => {\n db.createObjectStore(\"to_device_queue\", { autoIncrement: true });\n },\n // Expand as needed.\n];\nconst VERSION = DB_MIGRATIONS.length;\n\n/**\n * Helper method to collect results from a Cursor and promiseify it.\n * @param store - The store to perform openCursor on.\n * @param keyRange - Optional key range to apply on the cursor.\n * @param resultMapper - A function which is repeatedly called with a\n * Cursor.\n * Return the data you want to keep.\n * @returns Promise which resolves to an array of whatever you returned from\n * resultMapper.\n */\nfunction selectQuery<T>(\n store: IDBObjectStore,\n keyRange: IDBKeyRange | IDBValidKey | undefined,\n resultMapper: (cursor: IDBCursorWithValue) => T,\n): Promise<T[]> {\n const query = store.openCursor(keyRange);\n return new Promise((resolve, reject) => {\n const results: T[] = [];\n query.onerror = (): void => {\n reject(new Error(\"Query failed: \" + query.error?.name));\n };\n // collect results\n query.onsuccess = (): void => {\n const cursor = query.result;\n if (!cursor) {\n resolve(results);\n return; // end of results\n }\n results.push(resultMapper(cursor));\n cursor.continue();\n };\n });\n}\n\nfunction txnAsPromise(txn: IDBTransaction): Promise<Event> {\n return new Promise((resolve, reject) => {\n txn.oncomplete = function (event): void {\n resolve(event);\n };\n txn.onerror = function (): void {\n reject(txn.error);\n };\n });\n}\n\nfunction reqAsEventPromise(req: IDBRequest): Promise<Event> {\n return new Promise((resolve, reject) => {\n req.onsuccess = function (event): void {\n resolve(event);\n };\n req.onerror = function (): void {\n reject(req.error);\n };\n });\n}\n\nfunction reqAsPromise(req: IDBRequest): Promise<IDBRequest> {\n return new Promise((resolve, reject) => {\n req.onsuccess = (): void => resolve(req);\n req.onerror = (err): void => reject(err);\n });\n}\n\nfunction reqAsCursorPromise<T>(req: IDBRequest<T>): Promise<T> {\n return reqAsEventPromise(req).then((event) => req.result);\n}\n\nexport class LocalIndexedDBStoreBackend implements IIndexedDBBackend {\n public static exists(indexedDB: IDBFactory, dbName: string): Promise<boolean> {\n dbName = \"matrix-js-sdk:\" + (dbName || \"default\");\n return idbExists(indexedDB, dbName);\n }\n\n private readonly dbName: string;\n private readonly syncAccumulator: SyncAccumulator;\n private db?: IDBDatabase;\n private disconnected = true;\n private _isNewlyCreated = false;\n private syncToDatabasePromise?: Promise<void>;\n private pendingUserPresenceData: UserTuple[] = [];\n\n /**\n * Does the actual reading from and writing to the indexeddb\n *\n * Construct a new Indexed Database store backend. This requires a call to\n * `connect()` before this store can be used.\n * @param indexedDB - The Indexed DB interface e.g\n * `window.indexedDB`\n * @param dbName - Optional database name. The same name must be used\n * to open the same database.\n */\n public constructor(\n private readonly indexedDB: IDBFactory,\n dbName = \"default\",\n ) {\n this.dbName = \"matrix-js-sdk:\" + dbName;\n this.syncAccumulator = new SyncAccumulator();\n }\n\n /**\n * Attempt to connect to the database. This can fail if the user does not\n * grant permission.\n * @returns Promise which resolves if successfully connected.\n */\n public connect(onClose?: () => void): Promise<void> {\n if (!this.disconnected) {\n logger.log(`LocalIndexedDBStoreBackend.connect: already connected or connecting`);\n return Promise.resolve();\n }\n\n this.disconnected = false;\n\n logger.log(`LocalIndexedDBStoreBackend.connect: connecting...`);\n const req = this.indexedDB.open(this.dbName, VERSION);\n req.onupgradeneeded = (ev): void => {\n const db = req.result;\n const oldVersion = ev.oldVersion;\n logger.log(`LocalIndexedDBStoreBackend.connect: upgrading from ${oldVersion}`);\n if (oldVersion < 1) {\n // The database did not previously exist\n this._isNewlyCreated = true;\n }\n DB_MIGRATIONS.forEach((migration, index) => {\n if (oldVersion <= index) migration(db);\n });\n };\n\n req.onblocked = (): void => {\n logger.log(`can't yet open LocalIndexedDBStoreBackend because it is open elsewhere`);\n };\n\n logger.log(`LocalIndexedDBStoreBackend.connect: awaiting connection...`);\n return reqAsEventPromise(req).then(async () => {\n logger.log(`LocalIndexedDBStoreBackend.connect: connected`);\n this.db = req.result;\n\n // add a poorly-named listener for when deleteDatabase is called\n // so we can close our db connections.\n this.db.onversionchange = (): void => {\n this.db?.close(); // this does not call onclose\n this.disconnected = true;\n this.db = undefined;\n };\n this.db.onclose = (): void => {\n this.disconnected = true;\n this.db = undefined;\n onClose?.();\n };\n\n await this.init();\n });\n }\n\n /** @returns whether or not the database was newly created in this session. */\n public isNewlyCreated(): Promise<boolean> {\n return Promise.resolve(this._isNewlyCreated);\n }\n\n /**\n * Having connected, load initial data from the database and prepare for use\n * @returns Promise which resolves on success\n */\n private init(): Promise<unknown> {\n return Promise.all([this.loadAccountData(), this.loadSyncData()]).then(([accountData, syncData]) => {\n logger.log(`LocalIndexedDBStoreBackend: loaded initial data`);\n this.syncAccumulator.accumulate(\n {\n next_batch: syncData.nextBatch,\n rooms: syncData.roomsData,\n account_data: {\n events: accountData,\n },\n },\n true,\n );\n });\n }\n\n /**\n * Returns the out-of-band membership events for this room that\n * were previously loaded.\n * @returns the events, potentially an empty array if OOB loading didn't yield any new members\n * @returns in case the members for this room haven't been stored yet\n */\n public getOutOfBandMembers(roomId: string): Promise<IStateEventWithRoomId[] | null> {\n return new Promise<IStateEventWithRoomId[] | null>((resolve, reject) => {\n const tx = this.db!.transaction([\"oob_membership_events\"], \"readonly\");\n const store = tx.objectStore(\"oob_membership_events\");\n const roomIndex = store.index(\"room\");\n const range = IDBKeyRange.only(roomId);\n const request = roomIndex.openCursor(range);\n\n const membershipEvents: IStateEventWithRoomId[] = [];\n // did we encounter the oob_written marker object\n // amongst the results? That means OOB member\n // loading already happened for this room\n // but there were no members to persist as they\n // were all known already\n let oobWritten = false;\n\n request.onsuccess = (): void => {\n const cursor = request.result;\n if (!cursor) {\n // Unknown room\n if (!membershipEvents.length && !oobWritten) {\n return resolve(null);\n }\n return resolve(membershipEvents);\n }\n const record = cursor.value;\n if (record.oob_written) {\n oobWritten = true;\n } else {\n membershipEvents.push(record);\n }\n cursor.continue();\n };\n request.onerror = (err): void => {\n reject(err);\n };\n }).then((events) => {\n logger.log(`LL: got ${events?.length} membershipEvents from storage for room ${roomId} ...`);\n return events;\n });\n }\n\n /**\n * Stores the out-of-band membership events for this room. Note that\n * it still makes sense to store an empty array as the OOB status for the room is\n * marked as fetched, and getOutOfBandMembers will return an empty array instead of null\n * @param membershipEvents - the membership events to store\n */\n public async setOutOfBandMembers(roomId: string, membershipEvents: IStateEventWithRoomId[]): Promise<void> {\n logger.log(`LL: backend about to store ${membershipEvents.length}` + ` members for ${roomId}`);\n const tx = this.db!.transaction([\"oob_membership_events\"], \"readwrite\");\n const store = tx.objectStore(\"oob_membership_events\");\n membershipEvents.forEach((e) => {\n store.put(e);\n });\n // aside from all the events, we also write a marker object to the store\n // to mark the fact that OOB members have been written for this room.\n // It's possible that 0 members need to be written as all where previously know\n // but we still need to know whether to return null or [] from getOutOfBandMembers\n // where null means out of band members haven't been stored yet for this room\n const markerObject = {\n room_id: roomId,\n oob_written: true,\n state_key: 0,\n };\n store.put(markerObject);\n await txnAsPromise(tx);\n logger.log(`LL: backend done storing for ${roomId}!`);\n }\n\n public async clearOutOfBandMembers(roomId: string): Promise<void> {\n // the approach to delete all members for a room\n // is to get the min and max state key from the index\n // for that room, and then delete between those\n // keys in the store.\n // this should be way faster than deleting every member\n // individually for a large room.\n const readTx = this.db!.transaction([\"oob_membership_events\"], \"readonly\");\n const store = readTx.objectStore(\"oob_membership_events\");\n const roomIndex = store.index(\"room\");\n const roomRange = IDBKeyRange.only(roomId);\n\n const minStateKeyProm = reqAsCursorPromise(roomIndex.openKeyCursor(roomRange, \"next\")).then(\n (cursor) => (<IDBValidKey[]>cursor?.primaryKey)[1],\n );\n const maxStateKeyProm = reqAsCursorPromise(roomIndex.openKeyCursor(roomRange, \"prev\")).then(\n (cursor) => (<IDBValidKey[]>cursor?.primaryKey)[1],\n );\n const [minStateKey, maxStateKey] = await Promise.all([minStateKeyProm, maxStateKeyProm]);\n\n const writeTx = this.db!.transaction([\"oob_membership_events\"], \"readwrite\");\n const writeStore = writeTx.objectStore(\"oob_membership_events\");\n const membersKeyRange = IDBKeyRange.bound([roomId, minStateKey], [roomId, maxStateKey]);\n\n logger.log(\n `LL: Deleting all users + marker in storage for room ${roomId}, with key range:`,\n [roomId, minStateKey],\n [roomId, maxStateKey],\n );\n await reqAsPromise(writeStore.delete(membersKeyRange));\n }\n\n /**\n * Clear the entire database. This should be used when logging out of a client\n * to prevent mixing data between accounts. Closes the database.\n * @returns Resolved when the database is cleared.\n */\n public clearDatabase(): Promise<void> {\n return new Promise((resolve) => {\n logger.log(`Removing indexeddb instance: ${this.dbName}`);\n\n // Close the database first to avoid firing unexpected close events\n this.db?.close();\n\n const req = this.indexedDB.deleteDatabase(this.dbName);\n\n req.onblocked = (): void => {\n logger.log(`can't yet delete indexeddb ${this.dbName} because it is open elsewhere`);\n };\n\n req.onerror = (): void => {\n // in firefox, with indexedDB disabled, this fails with a\n // DOMError. We treat this as non-fatal, so that we can still\n // use the app.\n logger.warn(`unable to delete js-sdk store indexeddb: ${req.error?.name}`);\n resolve();\n };\n\n req.onsuccess = (): void => {\n logger.log(`Removed indexeddb instance: ${this.dbName}`);\n resolve();\n };\n });\n }\n\n /**\n * @param copy - If false, the data returned is from internal\n * buffers and must not be mutated. Otherwise, a copy is made before\n * returning such that the data can be safely mutated. Default: true.\n *\n * @returns Promise which resolves with a sync response to restore the\n * client state to where it was at the last save, or null if there\n * is no saved sync data.\n */\n public getSavedSync(copy = true): Promise<ISavedSync | null> {\n const data = this.syncAccumulator.getJSON();\n if (!data.nextBatch) return Promise.resolve(null);\n if (copy) {\n // We must deep copy the stored data so that the /sync processing code doesn't\n // corrupt the internal state of the sync accumulator (it adds non-clonable keys)\n return Promise.resolve(deepCopy(data));\n } else {\n return Promise.resolve(data);\n }\n }\n\n public getNextBatchToken(): Promise<string> {\n return Promise.resolve(this.syncAccumulator.getNextBatchToken());\n }\n\n public setSyncData(syncData: ISyncResponse): Promise<void> {\n return Promise.resolve().then(() => {\n this.syncAccumulator.accumulate(syncData);\n });\n }\n\n /**\n * Sync users and all accumulated sync data to the database.\n * If a previous sync is in flight, the new data will be added to the\n * next sync and the current sync's promise will be returned.\n * @param userTuples - The user tuples\n * @returns Promise which resolves if the data was persisted.\n */\n public async syncToDatabase(userTuples: UserTuple[]): Promise<void> {\n if (this.syncToDatabasePromise) {\n logger.warn(\"Skipping syncToDatabase() as persist already in flight\");\n this.pendingUserPresenceData.push(...userTuples);\n return this.syncToDatabasePromise;\n }\n userTuples.unshift(...this.pendingUserPresenceData);\n this.syncToDatabasePromise = this.doSyncToDatabase(userTuples);\n return this.syncToDatabasePromise;\n }\n\n private async doSyncToDatabase(userTuples: UserTuple[]): Promise<void> {\n try {\n const syncData = this.syncAccumulator.getJSON(true);\n await Promise.all([\n this.persistUserPresenceEvents(userTuples),\n this.persistAccountData(syncData.accountData),\n this.persistSyncData(syncData.nextBatch, syncData.roomsData),\n ]);\n } finally {\n this.syncToDatabasePromise = undefined;\n }\n }\n\n /**\n * Persist rooms /sync data along with the next batch token.\n * @param nextBatch - The next_batch /sync value.\n * @param roomsData - The 'rooms' /sync data from a SyncAccumulator\n * @returns Promise which resolves if the data was persisted.\n */\n private persistSyncData(nextBatch: string, roomsData: ISyncResponse[\"rooms\"]): Promise<void> {\n logger.log(\"Persisting sync data up to\", nextBatch);\n return promiseTry<void>(() => {\n const txn = this.db!.transaction([\"sync\"], \"readwrite\");\n const store = txn.objectStore(\"sync\");\n store.put({\n clobber: \"-\", // constant key so will always clobber\n nextBatch,\n roomsData,\n }); // put == UPSERT\n return txnAsPromise(txn).then(() => {\n logger.log(\"Persisted sync data up to\", nextBatch);\n });\n });\n }\n\n /**\n * Persist a list of account data events. Events with the same 'type' will\n * be replaced.\n * @param accountData - An array of raw user-scoped account data events\n * @returns Promise which resolves if the events were persisted.\n */\n private persistAccountData(accountData: IMinimalEvent[]): Promise<void> {\n return promiseTry<void>(() => {\n const txn = this.db!.transaction([\"accountData\"], \"readwrite\");\n const store = txn.objectStore(\"accountData\");\n for (const event of accountData) {\n store.put(event); // put == UPSERT\n }\n return txnAsPromise(txn).then();\n });\n }\n\n /**\n * Persist a list of [user id, presence event] they are for.\n * Users with the same 'userId' will be replaced.\n * Presence events should be the event in its raw form (not the Event\n * object)\n * @param tuples - An array of [userid, event] tuples\n * @returns Promise which resolves if the users were persisted.\n */\n private persistUserPresenceEvents(tuples: UserTuple[]): Promise<void> {\n return promiseTry<void>(() => {\n const txn = this.db!.transaction([\"users\"], \"readwrite\");\n const store = txn.objectStore(\"users\");\n for (const tuple of tuples) {\n store.put({\n userId: tuple[0],\n event: tuple[1],\n }); // put == UPSERT\n }\n return txnAsPromise(txn).then();\n });\n }\n\n /**\n * Load all user presence events from the database. This is not cached.\n * FIXME: It would probably be more sensible to store the events in the\n * sync.\n * @returns A list of presence events in their raw form.\n */\n public getUserPresenceEvents(): Promise<UserTuple[]> {\n return promiseTry<UserTuple[]>(() => {\n const txn = this.db!.transaction([\"users\"], \"readonly\");\n const store = txn.objectStore(\"users\");\n return selectQuery(store, undefined, (cursor) => {\n return [cursor.value.userId, cursor.value.event];\n });\n });\n }\n\n /**\n * Load all the account data events from the database. This is not cached.\n * @returns A list of raw global account events.\n */\n private loadAccountData(): Promise<IMinimalEvent[]> {\n logger.log(`LocalIndexedDBStoreBackend: loading account data...`);\n return promiseTry<IMinimalEvent[]>(() => {\n const txn = this.db!.transaction([\"accountData\"], \"readonly\");\n const store = txn.objectStore(\"accountData\");\n return selectQuery(store, undefined, (cursor) => {\n return cursor.value;\n }).then((result: IMinimalEvent[]) => {\n logger.log(`LocalIndexedDBStoreBackend: loaded account data`);\n return result;\n });\n });\n }\n\n /**\n * Load the sync data from the database.\n * @returns An object with \"roomsData\" and \"nextBatch\" keys.\n */\n private loadSyncData(): Promise<ISyncData> {\n logger.log(`LocalIndexedDBStoreBackend: loading sync data...`);\n return promiseTry<ISyncData>(() => {\n const txn = this.db!.transaction([\"sync\"], \"readonly\");\n const store = txn.objectStore(\"sync\");\n return selectQuery(store, undefined, (cursor) => {\n return cursor.value;\n }).then((results: ISyncData[]) => {\n logger.log(`LocalIndexedDBStoreBackend: loaded sync data`);\n if (results.length > 1) {\n logger.warn(\"loadSyncData: More than 1 sync row found.\");\n }\n return results.length > 0 ? results[0] : ({} as ISyncData);\n });\n });\n }\n\n public getClientOptions(): Promise<IStoredClientOpts | undefined> {\n return Promise.resolve().then(() => {\n const txn = this.db!.transaction([\"client_options\"], \"readonly\");\n const store = txn.objectStore(\"client_options\");\n return selectQuery(store, undefined, (cursor) => {\n return cursor.value?.options;\n }).then((results) => results[0]);\n });\n }\n\n public async storeClientOptions(options: IStoredClientOpts): Promise<void> {\n const txn = this.db!.transaction([\"client_options\"], \"readwrite\");\n const store = txn.objectStore(\"client_options\");\n store.put({\n clobber: \"-\", // constant key so will always clobber\n options: options,\n }); // put == UPSERT\n await txnAsPromise(txn);\n }\n\n public async saveToDeviceBatches(batches: ToDeviceBatchWithTxnId[]): Promise<void> {\n const txn = this.db!.transaction([\"to_device_queue\"], \"readwrite\");\n const store = txn.objectStore(\"to_device_queue\");\n for (const batch of batches) {\n store.add(batch);\n }\n await txnAsPromise(txn);\n }\n\n public async getOldestToDeviceBatch(): Promise<IndexedToDeviceBatch | null> {\n const txn = this.db!.transaction([\"to_device_queue\"], \"readonly\");\n const store = txn.objectStore(\"to_device_queue\");\n const cursor = await reqAsCursorPromise(store.openCursor());\n if (!cursor) return null;\n\n const resultBatch = cursor.value as ToDeviceBatchWithTxnId;\n\n return {\n id: cursor.key as number,\n txnId: resultBatch.txnId,\n eventType: resultBatch.eventType,\n batch: resultBatch.batch,\n };\n }\n\n public async removeToDeviceBatch(id: number): Promise<void> {\n const txn = this.db!.transaction([\"to_device_queue\"], \"readwrite\");\n const store = txn.objectStore(\"to_device_queue\");\n store.delete(id);\n await txnAsPromise(txn);\n }\n\n /*\n * Close the database\n */\n public async destroy(): Promise<void> {\n this.db?.close();\n }\n}\n"],"mappings":";;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA,SAAkDA,eAAe,QAAQ,wBAAwB;AACjG,SAASC,QAAQ,EAAEC,UAAU,QAAQ,aAAa;AAClD,SAASC,MAAM,IAAIC,SAAS,QAAQ,yBAAyB;AAC7D,SAASC,MAAM,QAAQ,cAAc;AAOrC,IAAMC,aAA4B,GAAG,CAChCC,EAAE,IAAW;EACV;EACAA,EAAE,CAACC,iBAAiB,CAAC,OAAO,EAAE;IAAEC,OAAO,EAAE,CAAC,QAAQ;EAAE,CAAC,CAAC;;EAEtD;EACA;EACAF,EAAE,CAACC,iBAAiB,CAAC,aAAa,EAAE;IAAEC,OAAO,EAAE,CAAC,MAAM;EAAE,CAAC,CAAC;;EAE1D;EACAF,EAAE,CAACC,iBAAiB,CAAC,MAAM,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AAE,EAAEtI,MAAM,CAACuI,GAAa;QACxBC,KAAK,EAAEH,WAAW,CAACG,KAAK;QACxBC,SAAS,EAAEJ,WAAW,CAACI,SAAS;QAChCR,KAAK,EAAEI,WAAW,CAACJ;MACvB,CAAC;IAAC;EACN;EAEaS,mBAAmBA,CAACJ,EAAU,EAAiB;IAAA,IAAAK,MAAA;IAAA,OAAAtG,iBAAA;MACxD,IAAMhC,GAAG,GAAGsI,MAAI,CAACnK,EAAE,CAAEoF,WAAW,CAAC,CAAC,iBAAiB,CAAC,EAAE,WAAW,CAAC;MAClE,IAAM3E,KAAK,GAAGoB,GAAG,CAACwD,WAAW,CAAC,iBAAiB,CAAC;MAChD5E,KAAK,CAAC4G,MAAM,CAACyC,EAAE,CAAC;MAChB,MAAMlI,YAAY,CAACC,GAAG,CAAC;IAAC;EAC5B;;EAEA;AACJ;AACA;EACiBuI,OAAOA,CAAA,EAAkB;IAAA,IAAAC,OAAA;IAAA,OAAAxG,iBAAA;MAAA,IAAAyG,UAAA;MAClC,CAAAA,UAAA,GAAAD,OAAI,CAACrK,EAAE,cAAAsK,UAAA,eAAPA,UAAA,CAAStG,KAAK,CAAC,CAAC;IAAC;EACrB;AACJ","ignoreList":[]}
|
package/lib/testing.d.ts
CHANGED
@@ -7,6 +7,7 @@
|
|
7
7
|
*/
|
8
8
|
import { IContent, IUnsigned, MatrixEvent } from "./models/event.ts";
|
9
9
|
import { EventType } from "./@types/event.ts";
|
10
|
+
import { OidcClientConfig, ValidatedAuthMetadata } from "./oidc/index.ts";
|
10
11
|
/**
|
11
12
|
* Create a {@link MatrixEvent}.
|
12
13
|
*
|
@@ -30,4 +31,20 @@ export declare function mkMatrixEvent(opts: {
|
|
30
31
|
/** Optional `unsigned` data for the event. */
|
31
32
|
unsigned?: IUnsigned;
|
32
33
|
}): MatrixEvent;
|
34
|
+
/**
|
35
|
+
* Makes a valid OidcClientConfig with minimum valid values
|
36
|
+
* @param issuer used as the base for all other urls
|
37
|
+
* @param additionalGrantTypes to add to the default grant types
|
38
|
+
* @returns OidcClientConfig
|
39
|
+
* @experimental
|
40
|
+
*/
|
41
|
+
export declare const makeDelegatedAuthConfig: (issuer?: string, additionalGrantTypes?: string[]) => OidcClientConfig;
|
42
|
+
/**
|
43
|
+
* Useful for mocking <issuer>/.well-known/openid-configuration
|
44
|
+
* @param issuer used as the base for all other urls
|
45
|
+
* @param additionalGrantTypes to add to the default grant types
|
46
|
+
* @returns ValidatedAuthMetadata
|
47
|
+
* @experimental
|
48
|
+
*/
|
49
|
+
export declare const mockOpenIdConfiguration: (issuer?: string, additionalGrantTypes?: string[]) => ValidatedAuthMetadata;
|
33
50
|
//# sourceMappingURL=testing.d.ts.map
|
package/lib/testing.d.ts.map
CHANGED
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"file":"testing.d.ts","sourceRoot":"","sources":["../src/testing.ts"],"names":[],"mappings":"AAgBA;;;;;;GAMG;AAEH,OAAO,EAAE,QAAQ,EAAU,SAAS,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAE7E,OAAO,EAAE,SAAS,EAAE,MAAM,mBAAmB,CAAC;
|
1
|
+
{"version":3,"file":"testing.d.ts","sourceRoot":"","sources":["../src/testing.ts"],"names":[],"mappings":"AAgBA;;;;;;GAMG;AAEH,OAAO,EAAE,QAAQ,EAAU,SAAS,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAE7E,OAAO,EAAE,SAAS,EAAE,MAAM,mBAAmB,CAAC;AAC9C,OAAO,EAAE,gBAAgB,EAAE,qBAAqB,EAAE,MAAM,iBAAiB,CAAC;AAE1E;;;;GAIG;AACH,wBAAgB,aAAa,CAAC,IAAI,EAAE;IAChC,4BAA4B;IAC5B,MAAM,EAAE,MAAM,CAAC;IAEf,+BAA+B;IAC/B,MAAM,EAAE,MAAM,CAAC;IAEf,6BAA6B;IAC7B,IAAI,EAAE,SAAS,GAAG,MAAM,CAAC;IAEzB,wFAAwF;IACxF,QAAQ,CAAC,EAAE,MAAM,CAAC;IAElB,iGAAiG;IACjG,EAAE,CAAC,EAAE,MAAM,CAAC;IAEZ,wGAAwG;IACxG,OAAO,CAAC,EAAE,MAAM,CAAC;IAEjB,4BAA4B;IAC5B,OAAO,EAAE,QAAQ,CAAC;IAElB,8CAA8C;IAC9C,QAAQ,CAAC,EAAE,SAAS,CAAC;CACxB,GAAG,WAAW,CAyBd;AAED;;;;;;GAMG;AACH,eAAO,MAAM,uBAAuB,2CAEV,MAAM,EAAE,KAC/B,gBAMF,CAAC;AACF;;;;;;GAMG;AACH,eAAO,MAAM,uBAAuB,2CAEV,MAAM,EAAE,KAC/B,qBAWD,CAAC"}
|
package/lib/testing.js
CHANGED
@@ -1,3 +1,6 @@
|
|
1
|
+
import _defineProperty from "@babel/runtime/helpers/defineProperty";
|
2
|
+
function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
|
3
|
+
function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
|
1
4
|
/*
|
2
5
|
Copyright 2024 The Matrix.org Foundation C.I.C.
|
3
6
|
|
@@ -54,4 +57,43 @@ export function mkMatrixEvent(opts) {
|
|
54
57
|
};
|
55
58
|
return mxEvent;
|
56
59
|
}
|
60
|
+
|
61
|
+
/**
|
62
|
+
* Makes a valid OidcClientConfig with minimum valid values
|
63
|
+
* @param issuer used as the base for all other urls
|
64
|
+
* @param additionalGrantTypes to add to the default grant types
|
65
|
+
* @returns OidcClientConfig
|
66
|
+
* @experimental
|
67
|
+
*/
|
68
|
+
export var makeDelegatedAuthConfig = function makeDelegatedAuthConfig() {
|
69
|
+
var issuer = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : "https://auth.org/";
|
70
|
+
var additionalGrantTypes = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : [];
|
71
|
+
var metadata = mockOpenIdConfiguration(issuer, additionalGrantTypes);
|
72
|
+
return _objectSpread(_objectSpread({}, metadata), {}, {
|
73
|
+
signingKeys: null
|
74
|
+
});
|
75
|
+
};
|
76
|
+
/**
|
77
|
+
* Useful for mocking <issuer>/.well-known/openid-configuration
|
78
|
+
* @param issuer used as the base for all other urls
|
79
|
+
* @param additionalGrantTypes to add to the default grant types
|
80
|
+
* @returns ValidatedAuthMetadata
|
81
|
+
* @experimental
|
82
|
+
*/
|
83
|
+
export var mockOpenIdConfiguration = function mockOpenIdConfiguration() {
|
84
|
+
var issuer = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : "https://auth.org/";
|
85
|
+
var additionalGrantTypes = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : [];
|
86
|
+
return {
|
87
|
+
issuer,
|
88
|
+
revocation_endpoint: issuer + "revoke",
|
89
|
+
token_endpoint: issuer + "token",
|
90
|
+
authorization_endpoint: issuer + "auth",
|
91
|
+
registration_endpoint: issuer + "registration",
|
92
|
+
device_authorization_endpoint: issuer + "device",
|
93
|
+
jwks_uri: issuer + "jwks",
|
94
|
+
response_types_supported: ["code"],
|
95
|
+
grant_types_supported: ["authorization_code", "refresh_token", ...additionalGrantTypes],
|
96
|
+
code_challenge_methods_supported: ["S256"]
|
97
|
+
};
|
98
|
+
};
|
57
99
|
//# sourceMappingURL=testing.js.map
|