@lifeready/core 8.0.13 → 8.0.15
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/bundles/lifeready-core.umd.js +118 -24
- package/bundles/lifeready-core.umd.js.map +1 -1
- package/bundles/lifeready-core.umd.min.js +1 -1
- package/bundles/lifeready-core.umd.min.js.map +1 -1
- package/esm2015/lib/api/query-processor/query-processor.service.js +11 -1
- package/esm2015/lib/api/types/lr-graphql.types.js +6 -1
- package/esm2015/lib/auth/auth.service.js +6 -1
- package/esm2015/lib/life-ready.config.js +6 -3
- package/esm2015/lib/plan/plan.types.js +1 -1
- package/esm2015/lib/scenario/scenario.service.js +5 -5
- package/esm2015/lib/trusted-party/trusted-party.gql.private.js +3 -1
- package/esm2015/lib/trusted-party/trusted-party.service.js +56 -8
- package/esm2015/lib/trusted-party/trusted-party.types.js +1 -1
- package/fesm2015/lifeready-core.js +83 -10
- package/fesm2015/lifeready-core.js.map +1 -1
- package/lib/api/types/lr-graphql.types.d.ts +9 -0
- package/lib/auth/auth.service.d.ts +1 -0
- package/lib/life-ready.config.d.ts +2 -0
- package/lib/plan/plan.types.d.ts +1 -0
- package/lib/trusted-party/trusted-party.gql.private.d.ts +2 -1
- package/lib/trusted-party/trusted-party.service.d.ts +39 -14
- package/lib/trusted-party/trusted-party.types.d.ts +9 -2
- package/lifeready-core.metadata.json +1 -1
- package/package.json +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"lifeready-core.js","sources":["../../../../projects/core/src/lib/key/key.types.ts","../../../../projects/core/src/lib/_common/kc-lodash.ts","../../../../projects/core/src/lib/_common/exceptions.ts","../../../../projects/core/src/lib/_common/utils.ts","../../../../projects/core/src/lib/time/time.service.ts","../../../../projects/core/src/lib/encryption/encryption.service.ts","../../../../projects/core/src/lib/web-crypto/web-crypto.service.ts","../../../../projects/core/src/lib/key/key-factory.service.ts","../../../../projects/core/src/lib/life-ready.config.ts","../../../../projects/core/src/lib/persist/persist.service.ts","../../../../projects/core/src/lib/key/key.service.ts","../../../../projects/core/src/lib/key/key-graph.service.ts","../../../../projects/core/src/lib/api/lr-apollo.service.ts","../../../../projects/core/src/lib/_common/ast.ts","../../../../projects/core/src/lib/_common/queries.gql.ts","../../../../projects/core/src/lib/_common/run-outside-angular.ts","../../../../projects/core/src/lib/api/query-processor/common-processors.service.ts","../../../../projects/core/src/lib/api/query-processor/tp-password-reset-processor.service.ts","../../../../projects/core/src/lib/api/query-processor/query-processor.service.ts","../../../../projects/core/src/lib/_common/deferred-promise.ts","../../../../projects/core/src/lib/api/lr-graphql/lr-mutation-base.ts","../../../../projects/core/src/lib/api/lr-graphql/lr-mutation.ts","../../../../projects/core/src/lib/api/lr-graphql/lr-merged-mutation.ts","../../../../projects/core/src/lib/api/lr-graphql/lr-graphql.service.ts","../../../../projects/core/src/lib/api/lr-graphql/lr.service.ts","../../../../projects/core/src/lib/api/types/graphql.types.ts","../../../../projects/core/src/lib/api/types/lr-graphql.types.ts","../../../../projects/core/src/lib/auth/auth.config.ts","../../../../projects/core/src/lib/idle/idle.types.ts","../../../../projects/core/src/lib/idle/idle.service.ts","../../../../projects/core/src/lib/contact-card/contact-card.gql.ts","../../../../projects/core/src/lib/key/key-meta.service.ts","../../../../projects/core/src/lib/key-exchange/key-exchange.gql.ts","../../../../projects/core/src/lib/profile/profile.types.ts","../../../../projects/core/src/lib/shared-contact-card/shared-contact-card.service.ts","../../../../projects/core/src/lib/profile/profile.gql.ts","../../../../projects/core/src/lib/profile/profile.service.ts","../../../../projects/core/src/lib/password/password.gql.ts","../../../../projects/core/src/lib/password/password.service.ts","../../../../projects/core/src/lib/tp-password-reset/tp-password-reset.constants.ts","../../../../projects/core/src/lib/slip39/slip39.service.ts","../../../../projects/core/src/lib/tp-assembly/tp-assembly.private.gql.ts","../../../../projects/core/src/lib/tp-assembly/tp-assembly.ts","../../../../projects/core/src/lib/tp-password-reset/tp-password-reset.controller.ts","../../../../projects/core/src/lib/tp-password-reset/tp-password-reset.gql.ts","../../../../projects/core/src/lib/_common/key.ts","../../../../projects/core/src/lib/auth/auth.gql.private.ts","../../../../projects/core/src/lib/auth/auth.types.ts","../../../../projects/core/src/lib/auth/auth.service.ts","../../../../projects/core/src/lib/contact-card/contact-card2.gql.ts","../../../../projects/core/src/lib/contact-card/contact-card2.service.ts","../../../../projects/core/src/lib/file-upload/file-upload.service.ts","../../../../projects/core/src/lib/item/item.gql.ts","../../../../projects/core/src/lib/lock/lock.gql.ts","../../../../projects/core/src/lib/lock/lock.service.ts","../../../../projects/core/src/lib/item/item.gql.private.ts","../../../../projects/core/src/lib/item/item.service.ts","../../../../projects/core/src/lib/key-exchange/key-exchange.service.ts","../../../../projects/core/src/lib/lbop/lbop.service.ts","../../../../projects/core/src/lib/life-ready.module.ts","../../../../projects/core/src/lib/notification/notification.gql.ts","../../../../projects/core/src/lib/notification/notification.service.ts","../../../../projects/core/src/lib/plan/plan.gql.ts","../../../../projects/core/src/lib/plan/plan.service.ts","../../../../projects/core/src/lib/profile/profile-details.service.ts","../../../../projects/core/src/lib/register/register.service.ts","../../../../projects/core/src/lib/register/register.types.ts","../../../../projects/core/src/lib/reminder/reminder.gql.ts","../../../../projects/core/src/lib/reminder/reminder.service.ts","../../../../projects/core/src/lib/scenario/scenario.gql.ts","../../../../projects/core/src/lib/scenario/scenario.constants.ts","../../../../projects/core/src/lib/scenario/scenario.controller.ts","../../../../projects/core/src/lib/scenario/scenario.private.gql.ts","../../../../projects/core/src/lib/scenario/scenario.service.ts","../../../../projects/core/src/lib/server-config/server-config.gql.ts","../../../../projects/core/src/lib/server-config/server-config.service.ts","../../../../projects/core/src/lib/shared-contact-card/shared-contact-card2.gql.ts","../../../../projects/core/src/lib/shared-contact-card/shared-contact-card2.service.ts","../../../../projects/core/src/lib/tp-password-reset/tp-password-reset.private.gql.ts","../../../../projects/core/src/lib/tp-password-reset/tp-password-reset.private.service.ts","../../../../projects/core/src/lib/tp-password-reset/tp-password-reset-request.service.ts","../../../../projects/core/src/lib/_common/storage.ts","../../../../projects/core/src/lib/tp-password-reset/tp-password-reset-user.service.ts","../../../../projects/core/src/lib/tp-password-reset/tp-password-reset.service.ts","../../../../projects/core/src/lib/trusted-party/trusted-party.gql.ts","../../../../projects/core/src/lib/trusted-party/trusted-party.gql.private.ts","../../../../projects/core/src/lib/trusted-party/trusted-party.service.ts","../../../../projects/core/src/lib/two-factor/two-factor.service.ts","../../../../projects/core/src/lib/user/user.gql.ts","../../../../projects/core/src/lib/user/user.service.ts","../../../../projects/core/src/public-api.ts","../../../../projects/core/src/lifeready-core.ts"],"sourcesContent":["import { JWK } from 'node-jose';\nimport { JSONObject, PassKeyNode } from '../api/types';\nimport { HasEdges, SomeRequired } from '../_common/types';\n\nexport interface Key {\n id: string;\n pbk?: string;\n jwk?: JWK.Key;\n}\n\nexport interface PassKeyParams {\n kid: string;\n salt: string;\n iterations: number;\n}\n\nexport interface PassIdpParams {\n salt: string;\n iterations: number;\n}\n\nexport interface LbopKeyParams {\n kid: string;\n salt: string;\n iterations: number;\n}\n\nexport interface PassIdpVerifier {\n wrappedPrK: Record<string, JSONObject>;\n pbk: Record<string, JSONObject>;\n}\n\nexport interface LbopKeyVerifier {\n wrappedKey: Record<string, JSONObject>;\n key: Record<string, JSONObject>;\n}\n\nexport type PassKey = SomeRequired<PassKeyNode, 'id'>;\n\nexport interface KeyLink {\n keyId: string;\n wrappingKeyId: string;\n nestedWrappingKeyIds: string[];\n wrappedKey: string; // JWE json string\n}\n\nexport interface PassKeyLink {\n keyId: string;\n passKeyId: string;\n wrappedKey: string; // JWE json string\n}\n\nexport enum KeyGraphNodeType {\n Key = 'key',\n PassKey = 'passKey',\n}\n\nexport interface KeyGraphNode {\n type: KeyGraphNodeType;\n data: Key | PassKey;\n}\n\nexport enum KeyGraphEdgeType {\n KeyLink = 'keyLink',\n PassKeyLink = 'passKeyLink',\n}\n\nexport interface KeyGraphEdge {\n type: KeyGraphEdgeType;\n data: KeyLink | PassKeyLink;\n}\n\nexport interface KeyGraphResponse {\n keys?: Key[];\n keyLinks?: KeyLink[];\n passKeys?: PassKey[];\n passKeyLinks?: PassKeyLink[];\n}\n\nexport interface HasKeyGraph {\n // The name of the keyGraph field returned from both queries and mutations are the same\n keyGraph?: KeyGraphResponse;\n}\n\nexport enum PayloadType {\n JSON = 'JSON',\n UINT_8_ARRAY = 'UINT_8_ARRAY',\n}\n\nexport interface DeriveKeyResult {\n jwk: JWK.Key;\n}\n\nexport interface DerivePassIdpParams extends PassIdpParams {\n password: CryptoKey;\n}\n\nexport interface DerivePassKeyParams extends PassKeyParams {\n password: CryptoKey;\n}\n\nexport interface DeriveLbopKeyParams extends PassKeyParams {\n password: CryptoKey;\n}\n\nexport interface HasKeyGraphEdges<T> extends HasKeyGraph {\n list: HasEdges<T>;\n}\n","// This file is in the \"lr-lodash\" directory so that we can use the barrel file\n// to create the lodash namespace. If we put this into the \"functions\" folder, then\n// other functions in there that uses lodash won't have the lodash namespace.\n// The internet says this style of import improves bundle size. At least we only have to\n// do this in a single place here.\nimport cloneDeep from 'lodash/cloneDeep';\nimport isEqual from 'lodash/isEqual';\nimport keyBy from 'lodash/keyBy';\nimport omit from 'lodash/omit';\n\nexport { cloneDeep, isEqual, keyBy, omit };\n","/* eslint-disable @typescript-eslint/no-explicit-any */\nimport { GraphQLError } from 'graphql';\nimport { lodash } from '.';\n\nexport function handleApolloError(errors: ReadonlyArray<GraphQLError>) {\n if (!errors || !errors.length) return;\n\n const kcErrors = errors.map((x) => {\n return new KcError({\n code: x.extensions && x.extensions.code,\n source: x.extensions && x.extensions.source,\n data: x.extensions && lodash.omit(x.extensions, ['code', 'source']),\n message: x.message,\n debug: {\n locations: x.locations as any,\n path: x.path as string[],\n },\n });\n });\n\n throw new KcException(...kcErrors);\n}\n\nexport class KcError {\n /**\n * The _tag prevents being able to return an object when a class is required:\n * ref: https://medium.com/decathlondevelopers/whats-the-problem-with-typescript-s-classes-2e60aaad3f6\n * Example:\n * // This works because KcError is being treated as a type.\n * function test(): KcError {\n * return {message: \"123\"};\n * }\n * With the private _tag property, the above will cause a compiler error because _tag property is missing\n * from the returned object.\n *\n * The _type property also provides a type indicator when serialising the class to POJO.\n */\n private _type: 'KcError' = 'KcError';\n\n code?: string;\n source?: string;\n data?: any;\n message: string;\n debug?: {\n locations: {\n line: number;\n column: number;\n }[];\n path: string[];\n };\n\n constructor(options: Partial<KcError>) {\n this.code = options.code;\n this.source = options.source;\n this.data = options.data;\n this.message = options.message;\n this.debug = options.debug;\n }\n}\n\nexport class KcException {\n private _type: 'KcException' = 'KcException';\n\n public errors: KcError[];\n\n /**\n *\n * @param errors Each argument is a KcError.\n */\n constructor(...errors: KcError[]) {\n this.errors = errors;\n }\n\n public toString() {\n return this.errors.map((t) => JSON.stringify(t, null, 2));\n }\n}\n\nexport enum KcErrorCode {\n // API errors\n ARCHIVED_RESOURCE = 'ARCHIVED_RESOURCE',\n BAD_ARGUMENT = 'BAD_ARGUMENT',\n BAD_SIGNATURE = 'BAD_SIGNATURE',\n BAD_STATE = 'BAD_STATE',\n CHANGED_PERMISSIONS = 'CHANGED_PERMISSIONS',\n CONCURRENT_ACCESS = 'CONCURRENT_ACCESS',\n CONFIG_ERROR = 'CONFIG_ERROR',\n CYCLE_DETECTED = 'CYCLE_DETECTED',\n EXPIRED = 'EXPIRED',\n INVALID_TOKEN = 'INVALID_TOKEN',\n INTERNAL_ERROR = 'INTERNAL_ERROR',\n JSON_DECODE_ERROR = 'JSON_DECODE_ERROR',\n KEY_MISMATCH = 'KEY_MISMATCH',\n LIMIT_REACHED = 'LIMIT_REACHED',\n LOCKED = 'LOCKED',\n LOGIC_ERROR = 'LOGIC_ERROR',\n LR_DEBUG_ONLY = 'LR_DEBUG_ONLY',\n MIN_DELAY = 'MIN_DELAY',\n MISSING_FIELD = 'MISSING_FIELD',\n MISSING_FIELD_VALUE = 'MISSING_FIELD_VALUE',\n MISSING_QUERY_PARAM = 'MISSING_QUERY_PARAM',\n NOT_IMPLEMENTED = 'NOT_IMPLEMENTED',\n OBJECT_DOES_NOT_EXIST = 'OBJECT_DOES_NOT_EXIST',\n OBJECT_EXISTS = 'OBJECT_EXISTS',\n RANGE_ERROR = 'RANGE_ERROR',\n TRUSTED_PARTY_NOT_FOUND = 'TRUSTED_PARTY_NOT_FOUND',\n UNAUTHENTICATED_USER = 'UNAUTHENTICATED_USER',\n USER_NOT_FOUND = 'USER_NOT_FOUND',\n VERSION_MISMATCH = 'VERSION_MISMATCH',\n WRONG_PERMISSIONS = 'WRONG_PERMISSIONS',\n\n // KC client errors\n AUTH = 'AUTH',\n BAD_LOGIC = 'BAD_LOGIC',\n BAD_REQUEST = 'BAD_REQUEST',\n BAD_TIME_SYNC = 'BAD_TIME_SYNC',\n CODE_MISMATCH = 'CODE_MISMATCH',\n ENCRYPTION = 'ENCRYPTION',\n NOT_FOUND = 'NOT_FOUND',\n SUSPICIOUS_OPERATION = 'SUSPICIOUS_OPERATION',\n UNSUPPORTED = 'UNSUPPORTED',\n}\n\nexport class KcAuthException extends KcException {\n constructor(message) {\n super(new KcError({ code: KcErrorCode.AUTH, message }));\n }\n}\n\nexport class KcBadArgumentException extends KcException {\n constructor(message: string) {\n super(new KcError({ code: KcErrorCode.BAD_ARGUMENT, message }));\n }\n}\n\nexport class KcBadLogicException extends KcException {\n constructor(message) {\n super(new KcError({ code: KcErrorCode.BAD_LOGIC, message }));\n }\n}\nexport class KcBadRequestException extends KcException {\n constructor(message) {\n super(new KcError({ code: KcErrorCode.BAD_REQUEST, message }));\n }\n}\n\nexport class KcBadSignatureException extends KcException {\n constructor(message) {\n super(new KcError({ code: KcErrorCode.BAD_SIGNATURE, message }));\n }\n}\n\nexport class KcBadStateException extends KcException {\n constructor(message) {\n super(\n new KcError({\n code: KcErrorCode.BAD_STATE,\n message,\n })\n );\n }\n}\n\nexport class KcBadTimeSyncException extends KcException {\n constructor(message) {\n super(\n new KcError({\n code: KcErrorCode.BAD_TIME_SYNC,\n message,\n })\n );\n }\n}\n\nexport class KcCodeMismatchException extends KcException {\n constructor(message) {\n super(new KcError({ code: KcErrorCode.CODE_MISMATCH, message }));\n }\n}\n\nexport class KcConcurrentAccessException extends KcException {\n constructor(message) {\n super(new KcError({ code: KcErrorCode.CONCURRENT_ACCESS, message }));\n }\n}\n\nexport class KcEncryptionException extends KcException {\n constructor(message) {\n super(new KcError({ code: KcErrorCode.ENCRYPTION, message }));\n }\n}\n\nexport class KcInternalErrorException extends KcException {\n constructor(message) {\n super(new KcError({ code: KcErrorCode.INTERNAL_ERROR, message }));\n }\n}\n\nexport class KcLockedException extends KcException {\n constructor(message) {\n super(\n new KcError({\n code: KcErrorCode.LOCKED,\n message,\n })\n );\n }\n}\n\nexport class KcNotFoundException extends KcException {\n constructor(message) {\n super(new KcError({ code: KcErrorCode.NOT_FOUND, message }));\n }\n}\n\nexport class KcSuspiciousOperationException extends KcException {\n constructor(message) {\n super(new KcError({ code: KcErrorCode.SUSPICIOUS_OPERATION, message }));\n }\n}\n\nexport class KcUnsupportedException extends KcException {\n constructor(message) {\n super(\n new KcError({\n code: KcErrorCode.UNSUPPORTED,\n message,\n })\n );\n }\n}\n","/* eslint-disable @typescript-eslint/no-explicit-any */\n\nimport { AuthClass } from '@aws-amplify/auth/lib-esm/Auth';\nimport { KcBadLogicException } from './exceptions';\n\n// promote everything to a promise.\nexport function promiseAllMayAsync(values: any[]): Promise<any> | any {\n if (!Array.isArray(values)) {\n throw new Error('not array');\n }\n if (values.some((value) => value?.then)) {\n const ret = Promise.all(values);\n return ret;\n } else {\n return values;\n }\n}\n\nfunction remap(obj, values) {\n const ret = {};\n for (const [i, key] of Object.keys(obj).entries()) {\n ret[key] = values[i];\n }\n return ret;\n}\n\nexport function mapValuesMayAsync(\n obj: Record<string, any>,\n // callback can either return a Promise, or a value.\n // The Promise<any> type is redundant but it shows that it can return a promise\n callback: (\n value: any,\n key: string,\n obj: Record<string, any>\n ) => any | Promise<any>\n): Promise<any> | any {\n const values = promiseAllMayAsync(\n Object.entries(obj).map(([key, value]) => callback(value, key, obj))\n );\n\n if (values.then) {\n return values.then((resolvedValues) => remap(obj, resolvedValues));\n } else {\n return remap(obj, values);\n }\n}\n\nexport function mapValuesAsync(\n obj: Record<string, any>,\n // callback can either return a Promise, or a value.\n // The Promise<any> type is redundant but it shows that it can return a promise\n // By default, it returns the value without any process, so you can use\n // this to simply wait for all promises in an object to resolve.\n callback?: (\n value: any,\n key: string,\n obj: Record<string, any>\n ) => any | Promise<any>\n): Promise<any> {\n const values = Promise.all(\n Object.entries(obj).map(([key, value]) =>\n callback ? callback(value, key, obj) : value\n )\n );\n\n return values.then((resolvedValues) => remap(obj, resolvedValues));\n}\n\n/**\n * Returns the defaultValue when value is undefined\n * @param value The value to check\n * @param defaultValue The value to return if value is undefined.\n */\nexport function undefinedDefault(value: any, defaultValue: any) {\n return value === undefined ? defaultValue : value;\n}\n\nexport async function getAccessJwtToken(auth: AuthClass): Promise<string> {\n try {\n return (await auth.currentSession()).getAccessToken().getJwtToken();\n } catch (error) {\n // The error thrown by Cognito is of type string.\n return '';\n }\n}\n\nexport function assert_xor(options: Record<string, unknown>) {\n const keys = Object.keys(options);\n if (keys.length != 2) {\n throw new KcBadLogicException(\n 'You must provide exactly 2 fields in the argument.'\n );\n }\n\n if (options[keys[0]] != null && options[keys[1]] != null) {\n throw new KcBadLogicException(\n `You can not specify both ${keys[0]} and ${keys[1]}`\n );\n }\n\n if (options[keys[0]] == null && options[keys[1]] == null) {\n throw new KcBadLogicException(\n `You must specify either ${keys[0]} and ${keys[1]}`\n );\n }\n}\n","import { Injectable } from '@angular/core';\nimport { AuthClass } from '@aws-amplify/auth/lib-esm/Auth';\nimport { Apollo } from 'apollo-angular';\nimport gql from 'graphql-tag';\nimport * as moment_ from 'moment';\nimport {\n handleApolloError,\n KcBadTimeSyncException,\n} from '../_common/exceptions';\nimport { getAccessJwtToken } from '../_common/utils';\n// Ref: https://stackoverflow.com/questions/59735280/angular-8-moment-error-cannot-call-a-namespace-moment\nconst moment = moment_;\n\nexport const ServerTimeQuery = gql`\n query {\n serverTime {\n timestamp\n }\n }\n`;\n\ninterface ServerTime {\n timestamp: string;\n}\n\n@Injectable({\n providedIn: 'root',\n})\nexport class TimeService {\n VERIFY_ENABLED = true;\n\n private readonly MAX_DIFF_MSEC = moment\n .duration({ seconds: 30 })\n .asMilliseconds();\n\n offsetMs: number = null; // Millisecond offset of local clock.\n verified = false; // Verified with independent time source\n\n constructor(private auth: AuthClass, private apollo: Apollo) {}\n\n // Get time from independent source to confirm.\n private async verifyCognito(): Promise<void> {\n const accessToken = await getAccessJwtToken(this.auth);\n if (!accessToken) {\n return;\n }\n\n // Request headers from AWS Amplify Auth lib\n // accept: */*\n // accept-encoding: gzip, deflate, br\n // accept-language: en-GB,en-US;q=0.9,en;q=0.8\n // cache-control: no-cache\n // content-length: 1089\n // content-type: application/x-amz-json-1.1\n // origin: http://localhost:4200\n // pragma: no-cache\n // referer: http://localhost:4200/\n // sec-fetch-dest: empty\n // sec-fetch-mode: cors\n // sec-fetch-site: cross-site\n // user-agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.132 Safari/537.36\n // x-amz-target: AWSCognitoIdentityProviderService.GetUser\n // x-amz-user-agent: aws-amplify/0.1.x js\n\n // We are only interested in the Date field.\n // AZ: I suppose we could use any end-point that provides a reliable Date field in the header. And we don't\n // need to be authenticated. Even a 400 response would have a Date header. But the worry is that AWS might\n // think it's some sort of attack, and block the IP or domain. At least in an authenticated call it can't be\n // seen as illegitimate.\n const response = await fetch(\n 'https://cognito-idp.ap-southeast-2.amazonaws.com/',\n {\n method: 'POST', // *GET, POST, PUT, DELETE, etc.\n mode: 'cors', // no-cors, *cors, same-origin\n cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached\n headers: {\n 'x-amz-target': 'AWSCognitoIdentityProviderService.GetUser',\n 'x-amz-user-agent': 'aws-amplify/0.1.x js',\n 'Content-Type': 'application/x-amz-json-1.1',\n },\n // redirect: 'follow', // manual, *follow, error\n // referrerPolicy: 'no-referrer', // no-referrer, *no-referrer-when-downgrade, origin, origin-when-cross-origin, same-origin, strict-origin, strict-origin-when-cross-origin, unsafe-url\n body: JSON.stringify({\n AccessToken: accessToken,\n }), // body data type must match \"Content-Type\" header\n }\n );\n\n const now = Date.now();\n\n const verifyTime = moment(response.headers.get('Date')).valueOf();\n const serverTime = now + this.offsetMs;\n const diff = Math.abs(serverTime - verifyTime);\n\n if (diff > this.MAX_DIFF_MSEC) {\n throw new KcBadTimeSyncException(\n `Server time does not match independent source. ServerTime: ${serverTime}, Cognito time: ${verifyTime}`\n );\n }\n\n this.verified = true;\n }\n\n private async refresh(): Promise<void> {\n const start = Date.now();\n const res = await this.apollo\n .query<{ serverTime: ServerTime }>({ query: ServerTimeQuery })\n .toPromise();\n const end = Date.now();\n\n handleApolloError(res.errors);\n\n const serverTime = parseInt(res.data.serverTime.timestamp, 10);\n\n const roundtrip = end - start;\n this.offsetMs = Math.round(serverTime - (start + roundtrip / 2));\n\n if (this.VERIFY_ENABLED) {\n await this.verifyCognito();\n }\n }\n\n async serverNow(): Promise<number> {\n let needsRefresh = false;\n\n // First call\n if (this.offsetMs === null) {\n needsRefresh = true;\n }\n\n if (this.VERIFY_ENABLED) {\n // logged in but not yet verified time matches.\n if (!this.verified && (await getAccessJwtToken(this.auth))) {\n needsRefresh = true;\n }\n }\n\n if (needsRefresh) {\n await this.refresh();\n }\n\n return Date.now() + this.offsetMs;\n }\n\n /**\n * This is the sync version to get now. Call serverNow() first, otherwise this will print error\n * because the server time offset is not known. But it will return the current time as a fallback\n * so as to not introduce any crashes.\n *\n */\n now(): number {\n if (this.offsetMs === null) {\n console.error(\n 'Server time offset not known. You must await serverNow() first. Returning local clock instead.'\n );\n return Date.now();\n } else {\n return Date.now() + this.offsetMs;\n }\n }\n\n /**\n * Calls this.now() and converts to a Date object.\n */\n date(): Date {\n return new Date(this.now());\n }\n}\n","/* eslint-disable @typescript-eslint/no-explicit-any */\nimport { Injectable } from '@angular/core';\nimport { JWE, JWK, JWS } from 'node-jose';\nimport { JSONObject } from '../api/types';\nimport { Key, PayloadType } from '../key/key.types';\nimport { TimeService } from '../time/time.service';\nimport {\n KcBadArgumentException,\n KcBadSignatureException,\n} from './../_common/exceptions';\n\nexport enum JoseSerialization {\n JSON = 'JSON',\n COMPACT = 'COMPACT',\n}\n\nexport interface VerifyOptions {\n payloadType?: PayloadType;\n returnOnlyPayload?: boolean; // If true, return only the decoded payload.\n}\n\nexport interface DecryptOptions {\n payloadType?: PayloadType;\n returnOnlyPayload?: boolean; // If true, return only the decoded payload.\n serializations?: JoseSerialization[];\n}\n\nexport const VERIFY_OPTIONS_DEFAULT: VerifyOptions = {\n payloadType: PayloadType.JSON,\n returnOnlyPayload: true,\n};\n\nexport const DECRYPT_OPTIONS_DEFAULT: DecryptOptions = {\n payloadType: PayloadType.JSON,\n returnOnlyPayload: true,\n serializations: [JoseSerialization.JSON],\n};\n\nexport function isSymmetricKey(key: JWK.Key) {\n // TODO: make sure this covers all cases.\n return key.kty === 'oct';\n}\n\nexport function asJwk(key: JWK.Key | Key | any): JWK.Key | null {\n // TODO: make sure this covers all cases.\n // Excluded:\n // key.use - only for public keys, Ref: https://tools.ietf.org/html/rfc7517#section-4.2\n\n if (key.id && key.jwk) {\n return key.jwk;\n } else if (key.keystore && key.length && key.kty && key.kid && key.alg) {\n return key;\n } else {\n return null;\n }\n}\n\n@Injectable({\n providedIn: 'root',\n})\nexport class EncryptionService {\n constructor(private timeService: TimeService) {}\n\n async decrypt(\n key: JWK.Key | Key, // string is assumed to be key.id, will unwrap key.\n jwe: Record<string, JSONObject> | string, // string will be JSON.parsed\n options?: DecryptOptions\n ): Promise<JWE.DecryptResult | any> {\n const opt = {\n algorithms: ['dir', 'A*GCM', 'RSA-OAEP-*'],\n };\n\n options = {\n ...DECRYPT_OPTIONS_DEFAULT,\n ...options,\n };\n\n if ((key as Key).jwk) {\n key = (key as Key).jwk;\n }\n\n if (typeof jwe === 'string') {\n if (options.serializations.includes(JoseSerialization.JSON)) {\n try {\n jwe = JSON.parse(jwe);\n } catch (error) {\n if (options.serializations.includes(JoseSerialization.COMPACT)) {\n console.log(\n 'Not a JSON-formatted JWE, it maybe compact serialisation format.'\n );\n } else {\n throw error;\n }\n }\n }\n }\n\n // {result} is a Object with:\n // * header: the combined 'protected' and 'unprotected' header members\n // * protected: an array of the member names from the \"protected\" member\n // * key: Key used to decrypt\n // * payload: Buffer of the decrypted content\n // * plaintext: Buffer of the decrypted content (alternate), just a reference to payload\n const res = await JWE.createDecrypt(key as JWK.Key, opt).decrypt(\n jwe as any\n );\n\n res.payload = this.decodePayload(options.payloadType, res.payload);\n\n if (options.returnOnlyPayload) {\n return res.payload;\n } else {\n return res;\n }\n }\n\n // TODO rename this to encrypt() and use as the most common use case\n async encryptToString(\n key: JWK.Key,\n content: ArrayBuffer | string | Record<string, JSONObject>\n ): Promise<string> {\n return JSON.stringify(await this.encrypt(key, content));\n }\n\n // TODO rename this to encryptToJSON() and use this when required.\n async encrypt(\n key: JWK.Key,\n content: ArrayBuffer | string | Record<string, JSONObject>\n ): Promise<any> {\n if (content == null) {\n throw new Error('Encrypting null/undefined content.');\n }\n\n if (!(content instanceof ArrayBuffer)) {\n content = new TextEncoder().encode(JSON.stringify(content));\n }\n\n return JWE.createEncrypt(\n {\n contentAlg: 'A256GCM',\n fields: {\n timestamp: await this.timeService.serverNow(),\n },\n } as any,\n key\n )\n .update(content)\n .final() as any;\n }\n\n // <AZ> Unlike signContent, the serialised \"content\" variable is contained inside\n // the result. So ordering of fields within \"content\" is not an issue.\n async sign(\n key: JWK.Key,\n content: Buffer | string | Record<string, JSONObject>\n ): Promise<any> {\n const signer = JWS.createSign(\n {\n fields: {\n timestamp: await this.timeService.serverNow(),\n },\n },\n key\n );\n\n if (content instanceof Buffer) {\n signer.update(content);\n } else {\n signer.update(JSON.stringify(content), 'utf8');\n }\n\n return signer.final();\n }\n\n async signToString(\n key: JWK.Key,\n content: Buffer | string | Record<string, JSONObject>\n ): Promise<string> {\n return JSON.stringify(await this.sign(key, content));\n }\n\n async verify(\n key: JWK.Key,\n jws: Record<string, JSONObject>,\n options?: VerifyOptions\n ): Promise<any> {\n const opt = {\n algorithms: ['RS*'],\n };\n\n options = {\n ...VERIFY_OPTIONS_DEFAULT,\n ...options,\n };\n\n try {\n const res = await JWS.createVerify(key, opt).verify(jws as any);\n\n res.payload = this.decodePayload(options.payloadType, res.payload);\n\n if (options.returnOnlyPayload) {\n return res.payload;\n } else {\n return res;\n }\n } catch (error) {\n throw new KcBadSignatureException(`Bad signature: ${error}`);\n }\n }\n\n async encryptThenSign(\n {\n key,\n sigPrk,\n }: {\n key: JWK.Key;\n sigPrk: JWK.Key;\n },\n content: ArrayBuffer | string | Record<string, JSONObject>\n ): Promise<{ cipher: string; sig: string }> {\n const cipher = JSON.stringify(await this.encrypt(key, content));\n const sig = await this.sign(sigPrk, cipher);\n delete sig.payload;\n\n return {\n cipher,\n sig: JSON.stringify(sig),\n };\n }\n\n private decodePayload(\n payloadType: PayloadType,\n payload: Uint8Array\n ): Uint8Array | any {\n switch (payloadType) {\n case PayloadType.JSON:\n return JSON.parse(new TextDecoder().decode(payload));\n case PayloadType.UINT_8_ARRAY:\n return payload;\n default:\n throw new KcBadArgumentException(`Unknown payloadType: ${payloadType}`);\n }\n }\n}\n","import { Injectable } from '@angular/core';\n\n@Injectable({\n providedIn: 'root',\n})\nexport class WebCryptoService {\n kcCrypto: Crypto = window.crypto;\n\n toHex(buffer: ArrayBuffer) {\n // Ref: https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/digest\n const array = Array.from(new Uint8Array(buffer)); // convert buffer to byte array\n const hex = array.map((b) => b.toString(16).padStart(2, '0')).join(''); // convert bytes to hex string\n return hex;\n }\n\n async stringDigest(algorithm: string, message: string): Promise<string> {\n const encoder = new TextEncoder();\n const data = encoder.encode(message);\n const hash = await this.kcCrypto.subtle.digest(algorithm, data);\n return this.toHex(hash);\n }\n}\n","import { Injectable } from '@angular/core';\nimport { JWK } from 'node-jose';\nimport { JSONObject } from '../api/types';\nimport { WebCryptoService } from '../web-crypto/web-crypto.service';\nimport {\n KcBadArgumentException,\n KcSuspiciousOperationException,\n} from '../_common/exceptions';\nimport {\n DeriveKeyResult,\n DeriveLbopKeyParams,\n DerivePassIdpParams,\n DerivePassKeyParams,\n LbopKeyParams,\n PassIdpParams,\n PassKeyParams,\n} from './key.types';\n\n@Injectable({\n providedIn: 'root',\n})\nexport class KeyFactoryService {\n constructor(private webCryptoService: WebCryptoService) {\n this.kcCrypto = this.webCryptoService.kcCrypto;\n }\n private readonly kcCrypto: Crypto;\n private readonly store: [];\n // Global keys store. Otherwise, each call to asKey creates a new keyStore.\n // <AZ> Did not seem to improve speed.\n // public static keyStore = JWK.createKeyStore();\n\n // AZ: This can't be change easily. It's basically a PassK or PassIdp rotation.\n // todo: we should eventually increase this periodically to match with Moore's law.\n // The iterations for each key are kept by the server as well but we assume the value\n // from the server is not trustworthy, so need to have minimum thresholds here.\n // If creating new keys, these minimum are used.\n public readonly MIN_PASS_IDP_PBKDF_ITER = 100000;\n public readonly MIN_PASS_KEY_PBKDF_ITER = 100000;\n public readonly MIN_LBOP_KEY_PBKDF_ITER = 100000;\n\n // These are used as the default values. They must be larger than the minimum values.\n public readonly DEFAULT_PASS_IDP_PBKDF_ITER = this.MIN_PASS_IDP_PBKDF_ITER;\n public readonly DEFAULT_PASS_KEY_PBKDF_ITER = this.MIN_PASS_KEY_PBKDF_ITER;\n public readonly DEFAULT_LBOP_KEY_PBKDF_ITER = this.MIN_LBOP_KEY_PBKDF_ITER;\n\n static asKey(\n key: string | Buffer | Record<string, JSONObject> | JWK.RawKey,\n form?:\n | 'json'\n | 'private'\n | 'pkcs8'\n | 'public'\n | 'spki'\n | 'pkix'\n | 'x509'\n | 'pem',\n extras?: Record<string, unknown>\n ): Promise<JWK.Key> {\n // <AZ> Using a single global key store did not seem to improve speed.\n // return KeyFactoryService.keyStore.add(key, form, extras);\n return JWK.asKey(key, form, extras);\n }\n\n randomString(digits: number): string {\n if (digits <= 0) {\n throw new KcBadArgumentException('digits <= 0');\n }\n const validChars =\n 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';\n let array = new Uint32Array(digits);\n this.kcCrypto.getRandomValues(array);\n array = array.map((x) => validChars.charCodeAt(x % validChars.length));\n return String.fromCharCode.apply(null, array);\n }\n\n randomDigitsNoZeros(digits: number): string {\n return this.randomChoices([1, 2, 3, 4, 5, 6, 7, 8, 9], digits).join('');\n }\n\n randomChoices<T>(array: T[], chooseN: number): T[] {\n if (array.length <= 1) {\n throw new KcBadArgumentException('array.length <= 0');\n }\n if (chooseN <= 0) {\n throw new KcBadArgumentException('chooseN <= 0');\n }\n const values = new Uint32Array(chooseN);\n this.kcCrypto.getRandomValues(values);\n const ret: T[] = [];\n values.forEach((v) => ret.push(array[v % array.length]));\n return ret;\n }\n\n createSalt(): string {\n return this.randomString(16);\n }\n\n async createKey(): Promise<JWK.Key> {\n const key = await this.kcCrypto.subtle.generateKey(\n {\n name: 'AES-GCM',\n length: 256, // can be 128, 192, or 256\n },\n true, // whether the key is extractable (i.e. can be used in exportKey)\n ['encrypt', 'decrypt'] // must be [\"encrypt\", \"decrypt\"] or [\"wrapKey\", \"unwrapKey\"]\n );\n\n const jwk = await this.kcCrypto.subtle.exportKey('jwk', key);\n\n // Removing the fields not needed by node-jose\n delete jwk.ext;\n delete jwk.key_ops;\n\n return KeyFactoryService.asKey(jwk);\n }\n\n async createSignKey(): Promise<JWK.Key> {\n const key = await this.kcCrypto.subtle.generateKey(\n {\n name: 'HMAC',\n hash: { name: 'SHA-512' },\n },\n true,\n ['sign', 'verify']\n );\n\n const jwk = await this.kcCrypto.subtle.exportKey('jwk', key);\n\n // Removing the fields not needed by node-jose\n delete jwk.key_ops;\n delete jwk.ext;\n\n return KeyFactoryService.asKey(jwk);\n }\n\n async createPkcKey(): Promise<JWK.Key> {\n // node-jose is not using Forge properly. It should be calling the async version of\n // pki.rsa.generateKeyPair() with a callback. Instead it calls the sync version. Webcrypto\n // does not support sync version, so it uses the javascript implementation, which is way too slow.\n // So we generate using webcrypto and import the key.\n // Unfortunately Elliptical Curve is not supported by Webcrypto. So we have to settle for RSA.\n const key = await this.kcCrypto.subtle.generateKey(\n {\n name: 'RSA-OAEP',\n modulusLength: 2048, // can be 1024, 2048, 3072, 4096 ... 16384\n // As per suggestion: https://developer.mozilla.org/en-US/docs/Web/API/RsaHashedKeyGenParams\n publicExponent: new Uint8Array([0x01, 0x00, 0x01]),\n hash: { name: 'SHA-256' }, // can be \"SHA-1\", \"SHA-256\", \"SHA-384\", or \"SHA-512\"\n },\n true, // whether the key is extractable (i.e. can be used in exportKey)\n ['encrypt', 'decrypt'] // must be [\"encrypt\", \"decrypt\"] or [\"wrapKey\", \"unwrapKey\"]\n );\n\n const jwk = await this.kcCrypto.subtle.exportKey('jwk', key.privateKey);\n // Removing the fields not needed by node-jose\n delete jwk.key_ops;\n delete jwk.ext;\n\n return KeyFactoryService.asKey(jwk);\n }\n\n async createPkcSignKey(): Promise<JWK.Key> {\n const key = await this.kcCrypto.subtle.generateKey(\n {\n name: 'RSASSA-PKCS1-v1_5',\n modulusLength: 2048, // can be 1024, 2048, or 4096\n // As per suggestion: https://developer.mozilla.org/en-US/docs/Web/API/RsaHashedKeyGenParams\n publicExponent: new Uint8Array([0x01, 0x00, 0x01]),\n hash: { name: 'SHA-256' }, // can be \"SHA-1\", \"SHA-256\", \"SHA-384\", or \"SHA-512\"\n },\n true, // whether the key is extractable (i.e. can be used in exportKey)\n ['sign', 'verify'] // can be any combination of \"sign\" and \"verify\"\n );\n\n const jwk = await this.kcCrypto.subtle.exportKey('jwk', key.privateKey);\n\n // Removing the fields not needed by node-jose\n delete jwk.key_ops;\n delete jwk.ext;\n\n return KeyFactoryService.asKey(jwk);\n }\n\n async importPassword(plainPassword: string): Promise<CryptoKey> {\n const enc = new TextEncoder();\n return this.kcCrypto.subtle.importKey(\n 'raw',\n enc.encode(plainPassword),\n 'PBKDF2',\n false,\n ['deriveKey']\n );\n }\n\n async deriveKey({\n password,\n salt,\n iterations,\n kid,\n }: {\n password: CryptoKey;\n salt: string;\n iterations: number;\n kid?: string;\n }): Promise<DeriveKeyResult> {\n const passKey = await this.kcCrypto.subtle.deriveKey(\n {\n name: 'PBKDF2',\n salt: new TextEncoder().encode(salt),\n iterations,\n hash: 'SHA-256',\n },\n password,\n { name: 'AES-GCM', length: 256 },\n true,\n ['encrypt', 'decrypt']\n );\n\n const passKeyJson: JSONObject = await this.kcCrypto.subtle.exportKey(\n 'jwk',\n passKey\n );\n if (kid) {\n passKeyJson.kid = kid;\n }\n\n const jwk = await KeyFactoryService.asKey(passKeyJson);\n\n return { jwk };\n }\n\n async derivePassIdp(params: DerivePassIdpParams): Promise<DeriveKeyResult> {\n if (params.iterations < this.MIN_PASS_IDP_PBKDF_ITER) {\n throw new KcSuspiciousOperationException(\n `The number of PassIdp key derivation iterations sent from the server (${params.iterations}) is lower than the minimum (${this.MIN_PASS_IDP_PBKDF_ITER})`\n );\n }\n return this.deriveKey(params);\n }\n\n async derivePassKey(params: DerivePassKeyParams): Promise<DeriveKeyResult> {\n if (params.iterations < this.MIN_PASS_KEY_PBKDF_ITER) {\n throw new KcSuspiciousOperationException(\n `The number of PassKey key derivation iterations sent from the server(${params.iterations}) is lower than the minimum(${this.MIN_PASS_KEY_PBKDF_ITER})`\n );\n }\n return this.deriveKey(params);\n }\n\n async deriveLbopKey(params: DeriveLbopKeyParams): Promise<DeriveKeyResult> {\n if (params.iterations < this.MIN_LBOP_KEY_PBKDF_ITER) {\n throw new KcSuspiciousOperationException(\n `The number of LbopKey key derivation iterations sent from the server(${params.iterations}) is lower than the minimum(${this.MIN_LBOP_KEY_PBKDF_ITER})`\n );\n }\n return this.deriveKey(params);\n }\n\n async createKid(): Promise<string> {\n // todo: AZ: node-jose source uses node's default UUID() function for kid, so just change to use that.\n // for now, we are just creating a new key to use it's kid.\n // The kid is a part of the JWK system. LR backend maintains the key hierarchy separately with it's own\n // key id. But we just use it here as a double check.\n return (await this.createKey()).kid;\n }\n\n async createPassIdpParams(): Promise<PassIdpParams> {\n return {\n salt: this.createSalt(),\n iterations: this.DEFAULT_PASS_IDP_PBKDF_ITER,\n };\n }\n\n async createPassKeyParams(): Promise<PassKeyParams> {\n return {\n salt: this.createSalt(),\n kid: await this.createKid(),\n iterations: this.DEFAULT_PASS_KEY_PBKDF_ITER,\n };\n }\n\n async createLbopKeyParams(): Promise<LbopKeyParams> {\n return {\n salt: this.createSalt(),\n // todo: AZ: node-jose source uses node's default UUID() function for kid, so just change to use that.\n // for now, we are just creating a new key to use it's kid.\n // The kid is a part of the JWK system. LR backend maintains the key hierarchy separately with it's own\n // key id. But we just use it here as a double check.\n kid: await this.createKid(),\n iterations: this.DEFAULT_PASS_KEY_PBKDF_ITER,\n };\n }\n}\n","/* eslint-disable @typescript-eslint/no-explicit-any */\nimport { InjectionToken } from '@angular/core';\nimport {\n ApolloClientOptions,\n ApolloLink,\n createHttpLink,\n DefaultOptions,\n from,\n InMemoryCache,\n} from '@apollo/client/core';\nimport { setContext } from '@apollo/client/link/context';\nimport { RetryLink } from '@apollo/client/link/retry';\nimport { AuthClass } from '@aws-amplify/auth/lib-esm/Auth';\nimport { GraphQLError } from 'graphql';\nimport { KcErrorCode } from './_common/exceptions';\nimport { getAccessJwtToken } from './_common/utils';\n\n// The injection token string is set to be the same as the const stand name since you\n// can possibly have different tokens with the same type (i.e. KcConfig). So it would not\n// be appropriate to use \"KcConfig\" as the token string.\nexport const KC_CONFIG = new InjectionToken<KcConfig>('KC_CONFIG');\nconst RETRY_ERROR_CODES = [KcErrorCode.CONCURRENT_ACCESS];\n\nexport async function httpOptions(auth: AuthClass, config: KcConfig) {\n const token = await getAccessJwtToken(auth);\n\n const debugUsername = config.debug?.username;\n\n return {\n withCredentials: true,\n headers: {\n ...(token && { authorization: `Bearer ${token}` }),\n ...(debugUsername && { 'x-kc-dev-user': debugUsername }),\n },\n };\n}\n\nexport interface KcConfig {\n authUrl: string;\n apiUrl: string;\n apolloUrl: string;\n userPoolId: string;\n userPoolWebClientId: string;\n apolloConfig?: ApolloClientOptions<any>;\n // Mainly to allow localhost to not needing this. Default to falsy\n disableSessionEncryptionKey?: boolean;\n // There's no compiler level switch exclude variables from the interface.\n // The only mechanism is to use replacement of files. But it's too cumbersome.\n // So we use runtime check instead to ensure debug config is null in production.\n debug?: {\n username?: string;\n };\n}\n\nexport const configureApollo = (\n config: KcConfig,\n auth: AuthClass\n): ApolloClientOptions<any> => {\n const defaultOptions: DefaultOptions = {\n watchQuery: {\n fetchPolicy: 'no-cache',\n errorPolicy: 'all',\n },\n query: {\n fetchPolicy: 'no-cache',\n errorPolicy: 'all',\n },\n mutate: {\n fetchPolicy: 'no-cache',\n errorPolicy: 'all',\n },\n };\n\n const authLink = setContext(async (_, { headers }) => {\n const options = await httpOptions(auth, config);\n\n return {\n ...options,\n headers: {\n ...headers,\n ...options.headers,\n },\n };\n });\n\n // We are only retrying on certain errors, like the CONCURRENT_ACCESS gql\n // error which indicates DB race condition. So can be safely retried.\n const retryIf = (error, _) => {\n // The RetryLink is called on network error as well, so we need to filter for GraphQL errors.\n if (error instanceof GraphQLErrorException) {\n if (\n error.errors.some((e) => RETRY_ERROR_CODES.includes(e.extensions?.code))\n ) {\n return true;\n }\n }\n\n return false;\n };\n\n const retryLink = new RetryLink({\n delay: {\n initial: 300,\n max: Infinity,\n jitter: true,\n },\n attempts: {\n max: 3,\n retryIf,\n },\n });\n\n class GraphQLErrorException extends Error {\n constructor(public errors: readonly GraphQLError[]) {\n super(errors.map((e) => e.message).join(', '));\n }\n }\n\n // Throw exception on gql errors which effectively promotes it to a network\n // error, which can then be handled by the RetryLink.\n const promoteGqlErrors = new ApolloLink((operation, forward) => {\n return forward(operation).map((data) => {\n if (data && data.errors) {\n const errors = data.errors.filter((e) =>\n RETRY_ERROR_CODES.includes(e.extensions?.code)\n );\n\n if (errors.length > 0) {\n throw new GraphQLErrorException(data.errors);\n }\n }\n return data;\n });\n });\n\n const httpLink = createHttpLink({\n uri: config.apolloUrl,\n // Sending the sessionid cookie so that the server can use session data when needed.\n // eg. setting the session encryption key.\n credentials: 'include',\n });\n\n return {\n link: from([retryLink, promoteGqlErrors, authLink, httpLink]),\n cache: new InMemoryCache(),\n defaultOptions,\n ...config.apolloConfig,\n };\n};\n","/* eslint-disable @typescript-eslint/no-explicit-any */\nimport { Injectable, Injector, isDevMode } from '@angular/core';\nimport { CookieService } from 'ngx-cookie-service';\nimport { JWK } from 'node-jose';\nimport { EncryptionService } from '../encryption/encryption.service';\nimport { KeyFactoryService as KFS } from '../key/key-factory.service';\nimport { KcBadArgumentException } from '../_common/exceptions';\n\ninterface Item {\n data: string;\n expiry?: string; // iso format\n serverSession?: boolean;\n}\n\ninterface CookieItem {\n key: any;\n}\n\n@Injectable({\n providedIn: 'root',\n})\nexport class PersistService {\n private readonly KEY_PREFIX = 'lrSession-';\n\n private cookieSecure = true;\n private serverSessionEncryptionKey: JWK.Key = null;\n\n constructor(\n private keyFactory: KFS,\n private cookieService: CookieService,\n private encryptionService: EncryptionService,\n private injector: Injector\n ) {\n if (isDevMode()) {\n this.setCookieSecure(false);\n }\n }\n\n setServerSessionEncryptionKey(key: JWK.Key) {\n this.serverSessionEncryptionKey = key;\n }\n\n clearServerSessionEncryptionKey() {\n this.serverSessionEncryptionKey = null;\n }\n\n // It's important that set and delete cookie use exactly the same set of parameters.\n private getCookieParams() {\n return {\n path: '/',\n domain: null, // which means the current domain of the frontend app.\n secure: this.cookieSecure,\n sameSite: 'Lax' as 'Lax' | 'None' | 'Strict',\n };\n }\n\n public clear() {\n // Remove all cookies\n Object.keys(this.cookieService.getAll()).forEach((key) => {\n if (key.startsWith(this.KEY_PREFIX)) {\n this.deletePrefixedName(key);\n }\n });\n\n // Remove all persisted session variables\n Object.keys(localStorage).forEach((key) => {\n if (key.startsWith(this.KEY_PREFIX)) {\n this.deletePrefixedName(key);\n }\n });\n }\n\n public setCookieSecure(value: boolean) {\n this.cookieSecure = value;\n if (!value) {\n if (isDevMode()) {\n console.warn(\n 'The cookie secure flag in persistService has been set to false, set it to true in production mode'\n );\n } else {\n throw new KcBadArgumentException(\n 'Can not set PersistService cookie secure flag to false in production mode.'\n );\n }\n }\n }\n\n private prefixName(name: string): string {\n return this.KEY_PREFIX + name;\n }\n\n public delete(name: string): void {\n this.deletePrefixedName(this.prefixName(name));\n }\n\n private deletePrefixedName(prefixedName: string): void {\n const params = this.getCookieParams();\n this.cookieService.delete(\n prefixedName, // name: string,\n params.path, // path?: string,\n params.domain, // domain ?: string,\n params.secure, // secure ?: boolean,\n params.sameSite // sameSite ?: 'Lax' | 'None' | 'Strict'): void;\n );\n localStorage.removeItem(prefixedName);\n }\n\n public async set({\n name,\n value,\n serverSession,\n expiry,\n }: {\n name: string;\n value: any;\n serverSession: boolean;\n expiry?: Date;\n }): Promise<void> {\n const prefixedName = this.prefixName(name);\n\n let item: Item;\n\n if (serverSession) {\n item = {\n serverSession: true,\n data: await this.encryptionService.encryptToString(\n this.serverSessionEncryptionKey,\n value\n ),\n };\n } else {\n item = {\n data: value,\n };\n }\n\n if (expiry) {\n const key = await this.keyFactory.createKey();\n item.expiry = expiry.toISOString();\n item.data = await this.encryptionService.encryptToString(key, item.data);\n\n const cookieItem: CookieItem = {\n key: key.toJSON(true),\n };\n\n // If path is set to anything other than \"/\" then the cookie is only\n // accessible by JS if the current URL has the same prefix as the path.\n // Ideally we don't want the encryption key cookie to be sent at all, but\n // since the encrypted content is held in localstorage, it is not a security\n // risk, i.e. it is at least as secure as storing only in localstorage.\n const params = this.getCookieParams();\n this.cookieService.set(\n prefixedName, // name: string,\n JSON.stringify(cookieItem), // value: string,\n expiry, // expires?: number | Date,\n params.path, // path?: string,\n params.domain, // domain?: string,\n params.secure, // secure?: boolean,\n params.sameSite // sameSite?: 'Lax' | 'None' | 'Strict'\n );\n }\n\n localStorage.setItem(prefixedName, JSON.stringify(item));\n }\n\n public async get(name: string): Promise<any> {\n const prefixedName = this.prefixName(name);\n\n try {\n const ret = await this.getImpl(prefixedName);\n if (ret == null) {\n // Clear any cookies to keep things in sync.\n this.deletePrefixedName(prefixedName);\n }\n return ret;\n } catch (error) {\n this.deletePrefixedName(prefixedName);\n throw error;\n }\n }\n\n private async getImpl(name: string): Promise<any> {\n const itemString = localStorage.getItem(name);\n if (!itemString) {\n return null;\n }\n\n const item: Item = JSON.parse(itemString);\n\n let data: any;\n\n if (item.expiry) {\n const cookieItemString = this.cookieService.get(name);\n if (!cookieItemString) {\n // Probably expired, but we won't make any interpretations since if we only used\n // cookies we can't tell if it's expired or explicitly removed. So we just make\n // the behaviour here consistent with that.\n console.log('No cookie.');\n return null;\n }\n\n const cookieItem = JSON.parse(cookieItemString);\n\n const key = await KFS.asKey(cookieItem.key);\n\n data = await this.encryptionService.decrypt(key, item.data);\n } else {\n data = item.data;\n }\n\n if (item.serverSession) {\n data = await this.encryptionService.decrypt(\n this.serverSessionEncryptionKey,\n data\n );\n }\n\n return data;\n }\n}\n","import { Inject, Injectable } from '@angular/core';\nimport { KcConfig, KC_CONFIG } from '../life-ready.config';\nimport { PersistService } from '../persist/persist.service';\nimport { KcNotFoundException } from '../_common/exceptions';\nimport { KeyFactoryService as KFS } from './key-factory.service';\nimport { Key, PassKey } from './key.types';\n\nexport class UserKeys {\n passKey: PassKey;\n masterKey: Key;\n rootKey?: Key;\n pxk?: Key;\n sigPxk?: Key;\n}\n\n@Injectable({\n providedIn: 'root',\n})\nexport class KeyService {\n private readonly STORE_MASTER_KEY = 'masterKey';\n // variables\n private keys: UserKeys;\n private masterKey: Key;\n\n // AZ: This can't be change easily. It's basically a PassK or PassIdp rotation.\n // todo: we should eventually increase this periodically to match with Moore's law.\n // The iterations for each key are kept by the server as well but we assume the value\n // from the server is not trustworthy, so need to have minimum thresholds here.\n // If creating new keys, these minimum are used.\n public readonly MIN_PASS_IDP_PBKDF_ITER = 100000;\n public readonly MIN_PASS_KEY_PBKDF_ITER = 100000;\n public readonly MIN_LBOP_KEY_PBKDF_ITER = 100000;\n\n // These are used as the default values. They must be larger than the minimum values.\n public readonly DEFAULT_PASS_IDP_PBKDF_ITER = this.MIN_PASS_IDP_PBKDF_ITER;\n public readonly DEFAULT_PASS_KEY_PBKDF_ITER = this.MIN_PASS_KEY_PBKDF_ITER;\n public readonly DEFAULT_LBOP_KEY_PBKDF_ITER = this.MIN_LBOP_KEY_PBKDF_ITER;\n\n constructor(\n @Inject(KC_CONFIG) private config: KcConfig,\n private persistService: PersistService\n ) {\n this.resetKeys();\n }\n\n resetKeys() {\n this.keys = null;\n this.masterKey = null;\n }\n\n purgeKeys() {\n this.resetKeys();\n this.persistService.clear();\n }\n\n setKeys(keys: UserKeys) {\n this.keys = keys;\n }\n\n public get currentPassKey(): Key {\n return this.keys.passKey;\n }\n\n public get currentMasterKey(): Key {\n return this.keys.masterKey;\n }\n\n public get currentRootKey(): Key {\n return this.keys.rootKey;\n }\n\n public get currentPxk(): Key {\n return this.keys.pxk;\n }\n\n public get currentSigPxk(): Key {\n return this.keys.sigPxk;\n }\n\n private expiresAfter(seconds: number): Date {\n return new Date(Date.now() + 1000 * seconds);\n }\n\n async persistMasterKey(\n masterKey: Key,\n expiresAfterSeconds: number\n ): Promise<void> {\n const storedKey = {\n id: masterKey.id,\n jwk: masterKey.jwk.toJSON(true),\n };\n\n this.masterKey = masterKey;\n\n // Save in an expirable cookie.\n await this.persistService.set({\n name: this.STORE_MASTER_KEY,\n value: storedKey,\n expiry: this.expiresAfter(expiresAfterSeconds),\n serverSession: !this.config.disableSessionEncryptionKey,\n });\n }\n\n async setMasterKeyExpiresAfterSeconds(seconds: number): Promise<void> {\n const storedKey = await this.persistService.get(this.STORE_MASTER_KEY);\n if (storedKey == null) {\n throw new KcNotFoundException(\n `Can not find masterKey in persisted storage using name: ${this.STORE_MASTER_KEY}`\n );\n }\n await this.persistService.set({\n name: this.STORE_MASTER_KEY,\n value: storedKey,\n expiry: this.expiresAfter(seconds),\n serverSession: !this.config.disableSessionEncryptionKey,\n });\n }\n\n // There's little benefit in using WebCrypto's none-extractable keys because if there\n // is an XSS attack, then the attacker has control over the js that downloads the keys. The\n // attacker can modify the code to import the keys as extractable. So none-extractable keys\n // are only useful if they are already persisted and the user cannot download any more keys,\n // which is not feasible.\n // So storing the PassKey in localstorage for now, at least till we know what the usage\n // pattern is, i.e. how often do we need to use the RootK, MaterK, and PassK.\n async loadMasterKey(masterKeyId: string): Promise<Key> {\n if (!this.masterKey) {\n const storedKey = await this.persistService.get(this.STORE_MASTER_KEY);\n\n if (!storedKey) {\n throw new KcNotFoundException(\n 'Could not find masterKey in persisted storage'\n );\n }\n\n if (storedKey.id !== masterKeyId) {\n throw new KcNotFoundException(\n `masterKeyId ${storedKey.id} in persisted storage does not match the one requested ${masterKeyId}`\n );\n }\n\n storedKey.jwk = await KFS.asKey(storedKey.jwk);\n\n this.masterKey = storedKey;\n }\n\n return this.masterKey;\n }\n}\n","/* eslint-disable @typescript-eslint/no-explicit-any */\nimport { Injectable } from '@angular/core';\nimport graphlib, { Graph } from '@dagrejs/graphlib';\nimport { JWK } from 'node-jose';\nimport { JSONObject } from '../api/types';\nimport {\n asJwk,\n DecryptOptions,\n EncryptionService,\n isSymmetricKey,\n} from '../encryption/encryption.service';\nimport { lodash } from '../_common';\nimport {\n KcBadArgumentException,\n KcBadLogicException,\n KcBadStateException,\n KcEncryptionException,\n KcNotFoundException,\n} from '../_common/exceptions';\nimport {\n KeyFactoryService,\n KeyFactoryService as KFS,\n} from './key-factory.service';\nimport { KeyService, UserKeys } from './key.service';\nimport {\n Key,\n KeyGraphEdge,\n KeyGraphEdgeType,\n KeyGraphNode,\n KeyGraphNodeType,\n KeyGraphResponse,\n KeyLink,\n PassKey,\n PayloadType,\n} from './key.types';\n\nexport interface GraphKey extends Key {\n task?: Promise<any>;\n}\n\n@Injectable({\n providedIn: 'root',\n})\nexport class KeyGraphService {\n private graph: Graph;\n // private keyCache: {\n // [id: string]: Key;\n // };\n\n constructor(\n private encryptionService: EncryptionService,\n private keyService: KeyService,\n private keyFactory: KeyFactoryService\n ) {\n this.purgeKeys();\n }\n\n purgeKeys() {\n this.graph = new Graph();\n // this.keyCache = null;\n }\n\n async populateKeys(userKey: UserKeys) {\n this.keyService.setKeys({\n passKey: userKey.passKey,\n masterKey: await this.keyService.loadMasterKey(userKey.masterKey.id),\n rootKey: await this.unwrapKey(userKey.masterKey.id, userKey.rootKey.id),\n pxk: await this.unwrapKey(userKey.masterKey.id, userKey.pxk.id),\n sigPxk: await this.unwrapKey(userKey.masterKey.id, userKey.sigPxk.id),\n });\n }\n\n hasKey(keyId: string) {\n return !!this.graph.node(keyId);\n }\n\n private getNode(id, type): GraphKey | PassKey {\n const node = this.graph.node(id);\n if (!node) {\n throw new KcNotFoundException(\n `Key graphs does not contain key id: ${id}`\n );\n }\n if (node.type !== type) {\n throw new KcBadStateException(`Key with id ${id} is not of type ${type}`);\n }\n return node.data;\n }\n\n key(id): GraphKey {\n return this.getNode(id, KeyGraphNodeType.Key);\n }\n\n passKey(id): PassKey {\n return this.getNode(id, KeyGraphNodeType.PassKey);\n }\n\n addKeys(src: KeyGraphResponse) {\n // Keys\n if (src.keys) {\n // What key graph returns can not be customized. So keys are essentially immutable.\n // Therefore, if a key exists, there's no reason to update it.\n for (const key of src.keys) {\n // Note using Relay global id allows us to not worry about clashing node id\n if (this.graph.hasNode(key.id)) {\n continue;\n }\n\n const node: KeyGraphNode = {\n type: KeyGraphNodeType.Key,\n data: lodash.cloneDeep(key),\n };\n\n this.graph.setNode(key.id, node);\n }\n }\n\n // KeyLinks\n if (src.keyLinks) {\n for (const keyLink of src.keyLinks) {\n if (this.graph.hasEdge(keyLink.wrappingKeyId, keyLink.keyId)) {\n continue;\n }\n\n const edge: KeyGraphEdge = {\n type: KeyGraphEdgeType.KeyLink,\n data: lodash.cloneDeep(keyLink),\n };\n // Edge goes from wrapping key to wrapped key.\n this.graph.setEdge(keyLink.wrappingKeyId, keyLink.keyId, edge);\n }\n }\n\n // PassKeyLinks\n if (src.passKeyLinks) {\n for (const passKeyLink of src.passKeyLinks) {\n if (this.graph.hasEdge(passKeyLink.passKeyId, passKeyLink.keyId)) {\n continue;\n }\n\n const edge: KeyGraphEdge = {\n type: KeyGraphEdgeType.PassKeyLink,\n data: lodash.cloneDeep(passKeyLink),\n };\n // Edge goes from wrapping key to wrapped key.\n this.graph.setEdge(passKeyLink.passKeyId, passKeyLink.keyId, edge);\n }\n }\n\n // The graph is the single source of truth. These are lazily calculated.\n // this.keyCache = null;\n }\n\n tracePath(distances, keyId: string): KeyGraphEdge[] {\n // The node label is the same as the id of the key nodes.\n const ret: KeyGraphEdge[] = [];\n let node = keyId;\n if (!distances[node].predecessor) {\n return null;\n }\n\n while (distances[node].predecessor) {\n const child = distances[node].predecessor;\n ret.push(this.graph.edge(child, node));\n node = child;\n }\n\n // After reverse, the first element is the passkey\n ret.reverse();\n\n return ret;\n }\n\n getPath(knownKeyId: string, keyId: string): KeyGraphEdge[] {\n if (!knownKeyId || typeof knownKeyId !== 'string') {\n throw new KcEncryptionException(\n `Param knownKeyId wrong format: ${knownKeyId}`\n );\n }\n if (!keyId || typeof keyId !== 'string') {\n throw new KcEncryptionException(`Param keyId wrong format: ${keyId}`);\n }\n\n // => { A: { distance: 0 },\n // B: { distance: 6, predecessor: 'C' },\n // C: { distance: 4, predecessor: 'A' },\n // D: { distance: 2, predecessor: 'A' },\n // E: { distance: 8, predecessor: 'F' },\n // F: { distance: 4, predecessor: 'D' } }\n const distances = graphlib.alg.dijkstra(this.graph, knownKeyId);\n\n // Trace path from keyId to knownKeyId\n return this.tracePath(distances, keyId);\n }\n\n async getJwkKey(\n keyOrId: string | Key,\n getKeyIdCallback?: () => Promise<string> | string\n ): Promise<JWK.Key> {\n return (await this.getKey(keyOrId, getKeyIdCallback)).jwk;\n }\n\n // We assume that when a keyId is fetched, the key graph\n // for the key is also returned and merged into the client-side\n // key graph. By insisting a keyId is returned instead of the\n // actual key we ensure key-graph is consistent.\n async getKey(\n keyOrId: string | Key,\n getKeyIdCallback?: () => Promise<string> | string\n ): Promise<Key> {\n let keyId = typeof keyOrId === 'string' ? keyOrId : keyOrId?.id;\n\n if (!this.hasKey(keyId) && getKeyIdCallback) {\n const keyIdFromCallback = await getKeyIdCallback();\n\n if (keyId != null && keyId != keyIdFromCallback) {\n throw new KcBadLogicException(\n 'Requested keyId is not in the key cache, so an API request was made to populate the key cache.' +\n 'But the key returned by the API does NOT match the requested keyId.' +\n 'This is a programming logic error.'\n );\n }\n\n keyId = keyIdFromCallback;\n }\n // else, continue and let it fail.\n\n const key = this.key(keyId);\n if (key.jwk) {\n return key;\n } else {\n return this.unwrapKey(this.keyService.currentMasterKey.id, keyId);\n }\n }\n\n private async _unwrapLink(\n wrappingKey: JWK.Key,\n link: KeyGraphEdge,\n dstKey: GraphKey\n ) {\n const wrappedKey = JSON.parse(link.data.wrappedKey);\n\n // Signatures of keys contain the key itself. This way we only need\n // to access the KeyLinks to decrypt/verify keys.\n let nextRawKey;\n if (wrappedKey.signatures) {\n nextRawKey = await this.encryptionService.verify(wrappingKey, wrappedKey);\n } else {\n nextRawKey = await this.encryptionService.decrypt(\n wrappingKey,\n wrappedKey\n );\n }\n\n // Handle nested keys. i.e. Enc{K1}{K2}{K3}(raw key 4), where:\n // K1: link.wrappingKey\n // K2: link.nestedWrappingKey[0]\n // K3: link.nestedWrappingKey[1]\n if (link.type == KeyGraphEdgeType.KeyLink) {\n const data = link.data as KeyLink;\n if (data.nestedWrappingKeyIds) {\n for (const nestedWrappingKeyId of data.nestedWrappingKeyIds) {\n const key = await this.getKey(nestedWrappingKeyId);\n nextRawKey = await this.encryptionService.decrypt(\n key.jwk,\n nextRawKey\n );\n }\n }\n }\n\n dstKey.jwk = await KFS.asKey(nextRawKey);\n dstKey.task = null;\n }\n\n private async _unwrap(key: JWK.Key, path: KeyGraphEdge[]): Promise<JWK.Key> {\n for (const link of path) {\n const dstKey = this.key(link.data.keyId);\n if (dstKey.jwk) {\n key = dstKey.jwk;\n continue;\n }\n\n if (!dstKey.task) {\n dstKey.task = this._unwrapLink(key, link, dstKey);\n }\n\n await dstKey.task;\n key = dstKey.jwk;\n }\n\n return key;\n }\n\n public async unwrapWithPassKey(\n passKeyId: string,\n passKey: JWK.Key,\n keyId: string\n ): Promise<Key> {\n // Get path of the directory key.\n const path = this.getPath(passKeyId, keyId);\n\n return {\n id: keyId,\n jwk: await this._unwrap(passKey, path),\n };\n }\n\n async unwrapKey(masterKeyId: string, keyId: string): Promise<Key> {\n // The first key should be a masterKey\n const masterKey = await this.keyService.loadMasterKey(masterKeyId);\n\n if (masterKeyId === keyId) {\n return masterKey;\n }\n\n // Get path of the directory key.\n const path = this.getPath(masterKey.id, keyId);\n\n return {\n id: keyId,\n jwk: await this._unwrap(masterKey.jwk, path),\n };\n }\n\n async decryptFromString<T>(\n keyOrId: string | Key,\n cipherData: string,\n options?: DecryptOptions\n ): Promise<T> {\n if (cipherData) {\n const key = await this.getJwkKey(keyOrId);\n return (await this.encryptionService.decrypt(\n key,\n JSON.parse(cipherData),\n options\n )) as any;\n }\n return null;\n }\n\n async decryptFile(keyId: string, file: any): Promise<any> {\n const key = await this.getJwkKey(keyId);\n return (await this.encryptionService.decrypt(key, file, {\n payloadType: PayloadType.UINT_8_ARRAY,\n })) as any;\n }\n\n // TODO rename this to encrypt() and use as the most common usecase\n async encryptToString(\n key: string | Key | JWK.Key,\n content: any\n ): Promise<string> {\n // Empty string should be encrypted since you want to clear the field.\n // Null is not encrypted because it's not valid JSON in the old JSON spec. Use\n // empty string instead. It'll function as a logic false as well.\n // Note that passing in empty string means it'll be encrypted which verifies\n // it's integrity. But we still want to have a way to set the DB field\n // to NULL, so we explicitly return null when content == null. A null\n // variable in graphql mutation on KC server clears the field to NULL.\n if (content == null) {\n return null;\n }\n\n const jwk = asJwk(key) || (await this.getJwkKey(key as string | Key));\n return this.encryptionService.encryptToString(jwk, content);\n }\n\n // Wraps a symmetric encryption key.\n // Throws exception if wrapping public keys.\n async wrapKey(\n wrappingKey: string | Key | JWK.Key,\n key: JWK.Key\n ): Promise<string> {\n if (!isSymmetricKey(key)) {\n throw new KcBadArgumentException(\n 'Only allowing wrapping of symmetric keys.'\n );\n }\n\n return this.encryptToString(wrappingKey, key.toJSON(true));\n }\n\n // TODO\n // async wrapPublicKey<T>();\n // async wrapPrivateKey<T>();\n\n async encryptWithNewKey(wrappingKeyId: string, cipherClearJson: JSONObject) {\n const key = await this.keyFactory.createKey();\n const wrappedKey = await this.encryptToString(\n wrappingKeyId,\n key.toJSON(true)\n );\n const cipher = await this.encryptToString(key, cipherClearJson);\n\n return {\n key,\n wrappingKeyId,\n wrappedKey,\n cipher,\n };\n }\n}\n","/* eslint-disable @typescript-eslint/no-explicit-any */\nimport { Injectable } from '@angular/core';\nimport { MutationOptions, QueryOptions } from '@apollo/client/core';\nimport { Apollo } from 'apollo-angular';\nimport { KeyGraphService } from '../key/key-graph.service';\nimport { HasKeyGraph } from '../key/key.types';\nimport { handleApolloError } from '../_common/exceptions';\n\n@Injectable({\n providedIn: 'root',\n})\nexport class LrApolloService {\n constructor(private apollo: Apollo, private keyGraph: KeyGraphService) {}\n\n private addKeys(response) {\n if ((response.data as HasKeyGraph).keyGraph) {\n this.keyGraph.addKeys((response.data as HasKeyGraph).keyGraph);\n }\n }\n\n async query<T, V = { [key: string]: any }>(\n options: QueryOptions<V>\n ): Promise<T> {\n const response = await this.apollo.query<T, V>(options).toPromise();\n\n handleApolloError(response.errors);\n\n this.addKeys(response);\n\n return response.data;\n }\n\n async mutate<T extends any, V = { [key: string]: any }>(\n options: MutationOptions<T, V>\n ): Promise<T> {\n const response = await this.apollo.mutate<T>(options).toPromise();\n\n handleApolloError(response.errors);\n\n this.addKeys(response);\n\n return response.data;\n }\n}\n","/* eslint-disable @typescript-eslint/no-explicit-any */\n// Abstract Syntax Tree\n\nimport {\n DocumentNode,\n FieldNode,\n FragmentDefinitionNode,\n NameNode,\n OperationDefinitionNode,\n OperationTypeNode,\n} from 'graphql';\nimport gql from 'graphql-tag';\nimport { KcBadArgumentException, KcBadLogicException } from './exceptions';\n\nexport function getAstOperation(\n astDocument,\n operation: OperationTypeNode\n): OperationDefinitionNode {\n const operations = astDocument.definitions.filter(\n (def: OperationDefinitionNode) => def.kind === 'OperationDefinition'\n );\n\n if (operations.length > 1) {\n throw new KcBadLogicException(\n `There can be only one '${operation}' operation, instead there are ${operations.length}`\n );\n }\n\n return operations[0];\n}\n\nexport function getQuery(doc: DocumentNode): OperationDefinitionNode {\n return getAstOperation(doc, 'query');\n}\n\nexport function getMutation(doc: DocumentNode): OperationDefinitionNode {\n return getAstOperation(doc, 'mutation');\n}\n\nexport function getFragments(doc: DocumentNode): FragmentDefinitionNode[] {\n return doc.definitions.filter(\n (def) => def.kind === 'FragmentDefinition'\n ) as FragmentDefinitionNode[];\n}\n\nexport function getFragment(astDocument: DocumentNode): FragmentDefinitionNode {\n const fragments = getFragments(astDocument);\n if (fragments.length > 1) {\n throw new KcBadArgumentException(\n 'GraphQL document can only contain one fragment.'\n );\n }\n return fragments[0];\n}\n\nexport function name(value: string): NameNode {\n return {\n kind: 'Name',\n value,\n };\n}\n\nexport function getAliasOrName(field: FieldNode) {\n return field.alias?.value || field.name.value;\n}\n\n// Collocates the type with the document.\n// eslint-disable-next-line @typescript-eslint/no-empty-interface, @typescript-eslint/no-unused-vars\nexport interface TypedDocumentNode<T> extends DocumentNode {}\n\nexport function gqlTyped<T = any>(\n literals: ReadonlyArray<string> | Readonly<string>,\n ...placeholders: any[]\n): TypedDocumentNode<T> {\n return gql(literals, ...placeholders) as TypedDocumentNode<T>;\n}\n","import gql from 'graphql-tag';\n\nconst KeyGraphFragmentBase = `\n{\n keys {\n id\n }\n keyLinks {\n keyId\n wrappingKeyId\n nestedWrappingKeyIds\n wrappedKey\n }\n passKeys {\n id\n }\n passKeyLinks {\n keyId\n passKeyId\n wrappedKey\n }\n __typename\n}\n`;\n\nexport const KeyGraphFragment = gql`\nfragment KeyGraphFragment on KeyGraphType ${KeyGraphFragmentBase}\n`;\n\nexport const KeyGraphField = `keyGraph ${KeyGraphFragmentBase}`;\n\nexport const FetchKeyGraphField = `keyGraph: fetchKeyGraph ${KeyGraphFragmentBase}`;\n\nexport const DirectoryQuery = gql`\n query Directory($id: LrRelayIdInput!, $cachedKeyIds: [LrRelayIdInput!]) {\n directory(id: $id) {\n id\n keyId\n plainMeta\n cipherMeta\n }\n keyGraph(cachedKeyIds: $cachedKeyIds) {\n ...KeyGraphFragment\n }\n }\n ${KeyGraphFragment}\n`;\n","/* eslint-disable @typescript-eslint/no-explicit-any */\nimport { KcBadLogicException } from './exceptions';\n\nexport interface RunOutsideAngularConfig {\n ngZoneName: string;\n // If true, a single change detection is triggered on resolve of the Promise returned\n // from the function.\n // else, the entire function is run outside of zone.\n // Note that if this is disabled, then change detection is not triggered even if you\n // use async pipes to subscribe to observables on the resulting promise. This is because\n // async pipes only _marks_ a component for change detection, it doesn't actually _trigger_\n // the change detection cycle.\n exceptLastPromise?: boolean;\n // Any method or property you wish to exclude from patch. The methods in EXCLUDE_METHODS are\n // never patched.\n excludeMethods?: string[];\n // If true, patch the setters as well. Settings are some\n // Note that setters do not return any thing. But they can still issue async calls.\n // These async calls are not visible to the wrapper. So we can't issue change detection\n // for setters when they are running outside angular.\n // Note that getters are not patched because getter and setter must use the same type. So if\n // the getter returns a promise, then the setting must alway take a promise. It doesn't make\n // much sense to use getters and setters this way. And if getter returns a value, then there's\n // no need to patch it to run outside angular.\n patchSetters?: boolean;\n}\n\n/**\n * If you wish to change the behaviour of those, you'll need to create a derived\n * class and override the methods.\n * However, can't figure out a way to call the super() in the derived class ctor, error says\n * the super call can't be in tested function.\n */\nexport const EXCLUDE_METHODS = [\n 'constructor',\n 'ngOnChanges',\n 'ngOnInit',\n 'ngDoCheck',\n 'ngAfterContentInit',\n 'ngAfterContentChecked',\n 'ngAfterViewInit',\n 'ngAfterViewChecked',\n 'ngOnDestroy',\n];\n\n// Patch all methods of the class.\n//\n// Note, this will not patch functions in the base class, it only\n// patches the function defined in the current class because it's\n// using getOwnPropertyNames(). You should be using composition for\n// services anyway.\n//\n// Ref: https://stackoverflow.com/a/44409244\n// The above approach might be a bit old. Now that we have ngZone.runOutsideAngular(),\n// we should probably use that and not touch any angular zone internals. But the approach\n// above doesn't require injecting ngZone.\n//\n// Ref: https://github.com/2ng/run-outside-angular/blob/master/src/run-outside-angular.ts\nexport function RunOutsideAngular({\n ngZoneName,\n exceptLastPromise = true,\n excludeMethods = [],\n patchSetters = true,\n}: RunOutsideAngularConfig) {\n return (target: any) => {\n function run(original, args) {\n if (!this[ngZoneName]) {\n throw new KcBadLogicException(\n `RunOutsideAngular decorator requires that ${target.name} inject NgZone as ${ngZoneName}`\n );\n }\n // runOutsideAngular() synchronously runs the callback and returns the result.\n const result = this[ngZoneName].runOutsideAngular(() =>\n original.apply(this, args)\n );\n\n if (exceptLastPromise && result?.then) {\n // Bring back into zone which will trigger change detection properly.\n // If this doesn't work, then we'll have to trigger change detection explicitly.\n return Promise.resolve(result);\n } else {\n return result;\n }\n }\n\n // There should be no reason to run any of the ones in EXCLUDE_METHODS outside angular.\n // So we always exclude them from patching. You can always explicit implement these ones differently.\n excludeMethods = [...excludeMethods, ...EXCLUDE_METHODS];\n\n const methods = Object.getOwnPropertyNames(target.prototype);\n\n methods\n .filter((method) => !excludeMethods.includes(method))\n .forEach((method) => {\n // Patch setters\n // Note that setters do not return any thing. But they can still issue async calls.\n // These async calls are not visible to the wrapper. So we can't issue change detection\n // for setters when they are running outside angular.\n if (\n patchSetters &&\n Object.getOwnPropertyDescriptor(target.prototype, method).set\n ) {\n const original = Object.getOwnPropertyDescriptor(\n target.prototype,\n method\n ).set;\n\n Object.defineProperty(target.prototype, method, {\n set(...args) {\n return run.apply(this, [original, args]);\n },\n });\n }\n\n if (typeof target.prototype[method] === 'function') {\n const original = target.prototype[method];\n\n target.prototype[method] = function (...args) {\n return run.apply(this, [original, args]);\n };\n }\n });\n\n return target;\n };\n}\n","/* eslint-disable @typescript-eslint/no-explicit-any */\nimport { Injectable, NgZone } from '@angular/core';\nimport { KeyGraphService } from '../../key/key-graph.service';\nimport { KcBadLogicException } from '../../_common/exceptions';\nimport { RunOutsideAngular } from '../../_common/run-outside-angular';\nimport { Connection } from '../types';\n\nexport interface ProcessorOptions {\n hasKeys: boolean;\n}\n\nexport const DefaultProcessorOptions: ProcessorOptions = {\n hasKeys: true,\n};\n\n// Sent to each processor for context information\nexport interface ProcessorContext {\n path: ReadonlyArray<string>;\n // processor can set this to false if child fields should\n // not be processed any further\n processChildren: boolean;\n}\n\nexport interface ProcessorCallbackParams<T = any> {\n field: T;\n context: ProcessorContext;\n options: ProcessorOptions;\n}\n\nexport type ProcessorCallback<T = any> = (\n params: ProcessorCallbackParams<T>\n) => T | Promise<T>;\n\ninterface ParseJsonProcessorOptions {\n plainFieldName?: string;\n jsonFieldSuffix?: string;\n}\n\ninterface DecryptionProcessorOptions {\n cipherFieldName?: string;\n clearFieldSuffix?: string;\n getKeyId?: (params: ProcessorCallbackParams) => Promise<string> | string;\n}\n\nexport async function processConnection<Node>(\n field: Connection<Node>,\n processNode: (node: Node) => Node | Promise<Node>\n): Promise<Connection<Node>> {\n return {\n ...field,\n edges: await Promise.all(\n field.edges.map(async (edge) => ({\n ...edge,\n node: await processNode(edge.node),\n }))\n ),\n };\n}\n\n@RunOutsideAngular({\n ngZoneName: 'ngZone',\n})\n@Injectable({\n providedIn: 'root',\n})\nexport class CommonProcessorsService {\n constructor(private ngZone: NgZone, private keyGraph: KeyGraphService) {}\n\n series(processors: ProcessorCallback[]): ProcessorCallback {\n return async ({ field, context, options }) => {\n for (const processor of processors) {\n field = await processor({ field, context, options });\n }\n return field;\n };\n }\n\n makeJsonParseProcessor({\n plainFieldName,\n jsonFieldSuffix = 'Json',\n }: ParseJsonProcessorOptions = {}): ProcessorCallback {\n const jsonFieldName = plainFieldName + jsonFieldSuffix;\n\n return ({ field }) => {\n if (field[plainFieldName] == null || jsonFieldName in field) {\n // if plainFieldName is undefined or null, then don't parse it.\n // if you parse it, then JSON.parse(null) and JSON.parse(\"null\") both return null, so\n // you can't distinguish between the two.\n // If clearFieldName already exists in node as a property, then we don't\n // need to process it again, even if it's value can be undefined or null even.\n return field;\n }\n\n try {\n return {\n ...field,\n [jsonFieldName]: JSON.parse(field[plainFieldName]),\n };\n } catch (error) {\n return field;\n }\n };\n }\n\n makeDecryptionProcessor({\n cipherFieldName,\n clearFieldSuffix = 'ClearJson',\n getKeyId = null,\n }: DecryptionProcessorOptions = {}): ProcessorCallback {\n const clearFieldName = cipherFieldName + clearFieldSuffix;\n\n return async (params) => {\n const { field, context, options } = params;\n\n // Can't decrypt anything if key graph is not returned\n if (!options.hasKeys) {\n return field;\n }\n\n const cipherField = field[cipherFieldName];\n\n // cipherField can be empty string, null or undefined.\n if (!cipherField || clearFieldName in field) {\n return field;\n }\n\n const keyId = getKeyId\n ? await getKeyId(params)\n : field.keyId || field.key?.id;\n\n if (!keyId) {\n const keyIdName = getKeyId ? 'key-id' : 'keyId or key.id';\n throw new KcBadLogicException(\n `Query response does not contain ${keyIdName} field: ${context.path.join(\n '.'\n )}`\n );\n }\n\n return this.keyGraph\n .decryptFromString(keyId, cipherField)\n .then((clear) => ({\n ...field,\n [clearFieldName]: clear,\n }));\n };\n }\n}\n","import { Injectable, NgZone } from '@angular/core';\nimport { KeyGraphService } from '../../key/key-graph.service';\nimport { Key } from '../../key/key.types';\nimport { KcBadRequestException } from '../../_common/exceptions';\nimport { RunOutsideAngular } from '../../_common/run-outside-angular';\nimport {\n ID,\n TpAssemblyApproverNode,\n TpAssemblyNode,\n TpPasswordResetNode,\n TpPasswordResetUser,\n TpPasswordResetUserApprovalNode,\n TpSubAssemblyNode,\n} from '../types';\nimport {\n processConnection,\n ProcessorCallbackParams,\n} from './common-processors.service';\n\n@RunOutsideAngular({\n ngZoneName: 'ngZone',\n})\n@Injectable({\n providedIn: 'root',\n})\nexport class TpPasswordResetProcessorService {\n constructor(private ngZone: NgZone, private keyGraph: KeyGraphService) {}\n\n async processTpPasswordResetUser(\n node: TpPasswordResetUser\n ): Promise<TpPasswordResetUser> {\n const pxk = node.pxk?.id && (await this.keyGraph.getKey(node.pxk.id));\n\n const ret = {\n ...node,\n };\n\n if (pxk && node.approvals) {\n ret.approvals = await Promise.all(\n node.approvals.map((approval) =>\n this.processTpPasswordResetUserApprovalNode(approval, pxk)\n )\n );\n }\n\n return ret;\n }\n\n private async processTpPasswordResetUserApprovalNode(\n approval: TpPasswordResetUserApprovalNode,\n pxk: Key\n ) {\n const ret = {\n ...approval,\n };\n\n if (approval.receiverCipher) {\n ret.receiverCipherClearJson = this.keyGraph.decryptFromString(\n pxk,\n approval.receiverCipher\n );\n }\n\n if (approval.receiverCipherPartialAssemblyKey) {\n ret.receiverCipherPartialAssemblyKeyClearJson =\n await this.keyGraph.decryptFromString(\n pxk,\n approval.receiverCipherPartialAssemblyKey\n );\n }\n return ret;\n }\n\n makeTpPasswordResetNodeProcessor() {\n return async ({\n field,\n }: ProcessorCallbackParams): Promise<TpPasswordResetNode> => {\n const ret = {\n ...field,\n };\n\n if (field.assembly) {\n if (field.applied == null) {\n throw new KcBadRequestException(\n 'If you request for field \"assembly\" in the TpPasswordResetNode, then you must also request the \"applied\" field'\n );\n }\n\n ret.assembly = await this.processTpAssemblyNode(\n field.assembly,\n field.applied\n );\n }\n\n return ret;\n };\n }\n\n private async processTpAssemblyNode(\n assembly: TpAssemblyNode,\n applied: boolean\n ): Promise<TpAssemblyNode> {\n // Subject key is encrypted user the master key. So if reset has been applied, then\n // these keys are not available any more.\n const { subjectKey, assemblyKey, assemblyCipherData, subAssemblies } =\n assembly;\n\n const ret: TpAssemblyNode = {\n ...assembly,\n subAssemblies: await processConnection(subAssemblies, (node) =>\n this.processTpSubAssemblyNode(node, subjectKey.id, applied)\n ),\n };\n\n if (!applied) {\n if (assemblyCipherData) {\n ret.assemblyCipherDataClearJson = await this.keyGraph.decryptFromString(\n assemblyKey.id,\n assemblyCipherData\n );\n }\n }\n\n return ret;\n }\n\n private async processTpSubAssemblyNode(\n subAssembly: TpSubAssemblyNode,\n subjectKeyId: ID,\n applied: boolean\n ): Promise<TpSubAssemblyNode> {\n const { subjectCipherData, approvers } = subAssembly;\n\n // const ret: TpSubAssemblyNode = {\n // ...subAssembly,\n // approvers: {\n // ...approvers,\n // edges: await Promise.all(\n // approvers.edges.map(async (edge) => ({\n // ...edge,\n // node: await this.processTpAssemblyApproverNode(edge.node, applied),\n // }))\n // ),\n // },\n // };\n const ret: TpSubAssemblyNode = {\n ...subAssembly,\n approvers: await processConnection(approvers, (node) =>\n this.processTpAssemblyApproverNode(node, applied)\n ),\n };\n\n if (!applied) {\n if (subjectCipherData) {\n ret.subjectCipherDataClearJson = await this.keyGraph.decryptFromString(\n subjectKeyId,\n subjectCipherData\n );\n }\n }\n\n return ret;\n }\n\n private async processTpAssemblyApproverNode(\n approver: TpAssemblyApproverNode,\n _applied: boolean\n ) {\n return approver;\n }\n}\n","/* eslint-disable @typescript-eslint/no-explicit-any */\nimport { Injectable, NgZone } from '@angular/core';\nimport { KeyService } from '../../key/key.service';\nimport { KcBadLogicException } from '../../_common/exceptions';\nimport { RunOutsideAngular } from '../../_common/run-outside-angular';\nimport { mapValuesMayAsync, promiseAllMayAsync } from '../../_common/utils';\nimport {\n CommonProcessorsService,\n DefaultProcessorOptions,\n // FieldContext,\n ProcessorCallback,\n ProcessorCallbackParams,\n ProcessorContext,\n ProcessorOptions,\n} from './common-processors.service';\nimport { TpPasswordResetProcessorService } from './tp-password-reset-processor.service';\n\nfunction extendPath(context: ProcessorContext, key: string): ProcessorContext {\n return {\n ...context,\n path: [...context.path, key],\n };\n}\n\n@RunOutsideAngular({\n ngZoneName: 'ngZone',\n})\n@Injectable({\n providedIn: 'root',\n})\nexport class QueryProcessorService {\n readonly TYPENAME = '__typename';\n private processors: { [key: string]: ProcessorCallback } = {};\n\n async processQuery(\n fields: { [key: string]: any },\n options: ProcessorOptions\n ) {\n options = {\n ...DefaultProcessorOptions,\n ...options,\n };\n\n // The top level query does not have __typename\n const ret = mapValuesMayAsync(fields, (field, key) =>\n this.processField({\n field,\n context: {\n path: [key],\n processChildren: true,\n },\n options,\n })\n );\n return ret;\n }\n\n // Either returns a Promise, or a value.\n // The Promise<any> type is redundant but it shows that it can return a promise\n // We are not using async on the function because we don't want auto promotion into a Promise, which\n // always defer execution into the event loops. It is costly and unnecessary for objects\n // with only native data types.\n private async processField({\n field,\n context,\n options,\n }: ProcessorCallbackParams) {\n if (field?.then) {\n throw new KcBadLogicException(\n 'processField() should not receive thenable.'\n );\n }\n\n if (field == null) {\n return null;\n }\n\n const newParams: ProcessorCallbackParams = {\n field,\n context: {\n ...context,\n // Processors modifies this field to communicate back to the caller.\n processChildren: true,\n },\n options,\n };\n\n // TODO allow registering processors by field name so we can process primitive fields as well.\n // We have common fields like \"created\", \"modified\" that be processed based on name.\n if (field[this.TYPENAME]) {\n // It's a custom object type\n const processor = this.processors[field[this.TYPENAME]];\n if (processor) {\n // Returns either a value or a promise.\n field = processor(newParams);\n }\n\n const processChildren = (childField) => {\n if (\n context.processChildren &&\n childField !== null &&\n typeof childField === 'object'\n ) {\n return mapValuesMayAsync(childField, (x, key) =>\n this.processField({\n field: x,\n context: extendPath(context, key),\n options,\n })\n );\n } else {\n return childField;\n }\n };\n\n // Keep processing all child fields\n if (field.then) {\n // Wait for field to resolve\n field = field.then((resolvedField) => {\n return processChildren(resolvedField);\n });\n } else {\n // Field is already resolved\n field = processChildren(field);\n }\n } else {\n // Keep processing all child fields\n if (context.processChildren) {\n if (Array.isArray(field)) {\n field = promiseAllMayAsync(\n (field as Array<any>).map((x, i) =>\n this.processField({\n field: x,\n context: extendPath(context, i.toString()),\n options,\n })\n )\n );\n }\n }\n }\n\n return field;\n }\n\n private registerProcessor(name: string, processor: ProcessorCallback) {\n if (this.processors[name]) {\n throw new KcBadLogicException(\n `Processor for field ${name} already exists.`\n );\n }\n this.processors[name] = processor;\n }\n\n constructor(\n private ngZone: NgZone,\n private keyService: KeyService,\n private common: CommonProcessorsService,\n private tpprProcessor: TpPasswordResetProcessorService\n ) {\n this.registerProcessor(\n 'DirectoryNode',\n common.series([\n common.makeJsonParseProcessor({\n plainFieldName: 'plainMeta',\n }),\n common.makeDecryptionProcessor({\n cipherFieldName: 'cipherMeta',\n }),\n ])\n );\n this.registerProcessor(\n 'FileStateNode',\n common.series([\n common.makeJsonParseProcessor({\n plainFieldName: 'plainMeta',\n }),\n common.makeDecryptionProcessor({\n cipherFieldName: 'cipherMeta',\n }),\n ])\n );\n this.registerProcessor(\n 'ContactCardNode',\n common.makeDecryptionProcessor({\n cipherFieldName: 'cipherData',\n })\n );\n this.registerProcessor(\n 'SharedContactCardNode',\n common.series([\n common.makeJsonParseProcessor({\n plainFieldName: 'ownerPlainData',\n }),\n common.makeDecryptionProcessor({\n cipherFieldName: 'ownerCipherData',\n getKeyId: ({ field }) => {\n return field.ownerKey.id;\n },\n }),\n common.makeDecryptionProcessor({\n cipherFieldName: 'receiverCipherData',\n getKeyId: ({ field }) => {\n return field.receiverKey.id;\n },\n }),\n common.makeDecryptionProcessor({\n cipherFieldName: 'sharedCipherData',\n getKeyId: ({ field }) => field.sharedKey.id,\n }),\n ])\n );\n this.registerProcessor(\n 'TpPasswordResetNode',\n this.tpprProcessor.makeTpPasswordResetNodeProcessor()\n );\n this.registerProcessor(\n 'SharedTpClaimApproverNode',\n common.series([\n common.makeDecryptionProcessor({\n cipherFieldName: 'sharedCipherApprovalData',\n getKeyId: ({ field }) => field.sharedKey.id,\n }),\n common.makeDecryptionProcessor({\n cipherFieldName: 'sharedCipherPartialAssemblyKey',\n getKeyId: ({ field }) => field.sharedKey.id,\n }),\n ])\n );\n this.registerProcessor(\n 'TpAssemblyAsApproverNode',\n common.series([\n common.makeDecryptionProcessor({\n cipherFieldName: 'sharedCipherData',\n getKeyId: ({ field }) => field.sharedKey.id,\n }),\n ])\n );\n this.registerProcessor(\n 'ScenarioNode',\n common.series([\n common.makeDecryptionProcessor({\n cipherFieldName: 'subjectCipherData',\n getKeyId: ({ field }) => field.subjectKey.id,\n }),\n ])\n );\n this.registerProcessor(\n 'ScenarioReceiverNode',\n common.series([\n common.makeDecryptionProcessor({\n cipherFieldName: 'sharedCipherData',\n getKeyId: ({ field }) => field.sharedKey.id,\n }),\n ])\n );\n this.registerProcessor(\n 'ScenarioReceiverDirectoryNode',\n common.series([\n common.makeDecryptionProcessor({\n cipherFieldName: 'sharedCipherData',\n getKeyId: ({ field }) => field.sharedKey.id,\n }),\n ])\n );\n this.registerProcessor(\n 'SharedScenarioReceiverDirectoryNode',\n common.series([\n common.makeDecryptionProcessor({\n cipherFieldName: 'sharedCipherData',\n getKeyId: ({ field }) => field.sharedKey.id,\n }),\n ])\n );\n this.registerProcessor(\n 'ScenarioReceiverFileNode',\n common.series([\n common.makeDecryptionProcessor({\n cipherFieldName: 'sharedCipherData',\n getKeyId: ({ field }) => field.sharedKey.id,\n }),\n ])\n );\n this.registerProcessor(\n 'SharedScenarioReceiverFileNode',\n common.series([\n common.makeDecryptionProcessor({\n cipherFieldName: 'sharedCipherData',\n getKeyId: ({ field }) => field.sharedKey.id,\n }),\n ])\n );\n this.registerProcessor(\n 'SharedScenarioReceiverNode',\n common.series([\n common.makeDecryptionProcessor({\n cipherFieldName: 'sharedCipherData',\n getKeyId: ({ field }) => field.sharedKey.id,\n }),\n ])\n );\n this.registerProcessor(\n 'ScenarioApproverAssemblyNode',\n common.series([\n common.makeDecryptionProcessor({\n cipherFieldName: 'assemblyCipherData',\n getKeyId: ({ field }) => field.assemblyKey.id,\n }),\n ])\n );\n this.registerProcessor(\n 'ScenarioApproverSubAssemblyNode',\n common.series([\n common.makeDecryptionProcessor({\n cipherFieldName: 'subjectCipherData',\n getKeyId: ({ field }) => field.subjectKey.id,\n }),\n ])\n );\n this.registerProcessor(\n 'ScenarioApproverNode',\n common.series([\n common.makeDecryptionProcessor({\n cipherFieldName: 'sharedCipherData',\n getKeyId: ({ field }) => field.sharedKey.id,\n }),\n common.makeDecryptionProcessor({\n cipherFieldName: 'sharedCipherApprovalData',\n getKeyId: ({ field }) => field.sharedKey.id,\n }),\n common.makeDecryptionProcessor({\n cipherFieldName: 'sharedCipherPartialAssemblyKey',\n getKeyId: ({ field }) => field.sharedKey.id,\n }),\n ])\n );\n this.registerProcessor(\n 'ScenarioClaimantNode',\n common.series([\n common.makeDecryptionProcessor({\n cipherFieldName: 'sharedCipherData',\n getKeyId: ({ field }) => field.sharedKey.id,\n }),\n ])\n );\n this.registerProcessor(\n 'TpAssemblyNode',\n common.series([\n common.makeDecryptionProcessor({\n cipherFieldName: 'subjectCipherData',\n getKeyId: ({ field }) => field.subjectKey.id,\n }),\n ])\n );\n this.registerProcessor(\n 'TpSubAssemblyNode',\n common.series([\n common.makeDecryptionProcessor({\n cipherFieldName: 'subjectCipherData',\n getKeyId: ({ field }) => field.subjectKey.id,\n }),\n ])\n );\n this.registerProcessor(\n 'NotificationNode',\n common.series([\n common.makeJsonParseProcessor({\n plainFieldName: 'plainMeta',\n }),\n common.makeJsonParseProcessor({\n plainFieldName: 'plainData',\n }),\n ])\n );\n this.registerProcessor(\n 'UserNode',\n common.series([\n common.makeJsonParseProcessor({\n plainFieldName: 'config',\n }),\n ])\n );\n this.registerProcessor(\n 'ReminderNode',\n common.series([\n common.makeJsonParseProcessor({\n plainFieldName: 'plain',\n }),\n ])\n );\n }\n}\n","/* eslint-disable @typescript-eslint/no-explicit-any */\nexport type ResolvePromise<T> = (value?: T | PromiseLike<T>) => void;\nexport type RejectPromise = (reason?: any) => void;\n\nexport class DeferredPromise<T> {\n public readonly promise: Promise<T>;\n /* tslint:disable: variable-name */\n private _resolve: ResolvePromise<T>;\n /* tslint:disable: variable-name */\n private _reject: RejectPromise;\n /* tslint:disable: variable-name */\n private _fulfilled = false;\n\n constructor() {\n this.promise = new Promise<T>((resolve, reject) => {\n this._resolve = resolve;\n this._reject = reject;\n }).finally(() => {\n // finally() simply gets called on both then() and catch(). The promise\n // chain continues on.\n this._fulfilled = true;\n });\n }\n\n get resolve() {\n return this._resolve;\n }\n\n get reject() {\n return this._reject;\n }\n\n get fulfilled() {\n return this._fulfilled;\n }\n}\n","/* eslint-disable @typescript-eslint/no-explicit-any */\nimport { OperationVariables } from '@apollo/client/core';\nimport { FragmentSpreadNode } from 'graphql';\nimport gql from 'graphql-tag';\nimport { getQuery, TypedDocumentNode } from '../../_common/ast';\nimport { DeferredPromise } from '../../_common/deferred-promise';\nimport { KcBadStateException } from '../../_common/exceptions';\n\nexport interface LrMutationData<T, TVariables = OperationVariables> {\n mutation: TypedDocumentNode<T>;\n variables?: TVariables;\n}\n\nexport const fragmentSpreadAstSelection = getQuery(gql`\n query {\n ...FragmentName\n }\n`).selectionSet.selections[0] as FragmentSpreadNode;\n\n// const fragmentSpreadAstSelection = () =>\n// lodash.deepClone(_fragmentSpreadAstSelection) as FragmentSpreadNode;\n\n/**\n * DECISION: LrMutationBase does not provide a convenience method to call lrGraphQL.lrMutate()\n * because this class could be made independent of what lib is used to call the API. If we\n * provided a configurable call back to make the API call, then the typing for that callback\n * needs to be known. But since the API lib (eg. Apollo) has it's own unique return type, so\n * it's not possible to do in general.\n */\nexport abstract class LrMutationBase<T, TVariables = OperationVariables> {\n protected mutation: TypedDocumentNode<T>;\n protected variables?: TVariables;\n /* tslint:disable:variable-name */\n protected _executed = false;\n\n // protected promises: DeferredPromise<T>[] = [];\n public readonly deferredPromise = new DeferredPromise<T>();\n\n get promise(): Promise<T> {\n return this.deferredPromise.promise;\n }\n\n resolve(value: T) {\n this.deferredPromise.resolve(value);\n }\n\n reject(reason?: any) {\n this.deferredPromise.reject(reason);\n }\n\n get lrMutationData(): LrMutationData<T, TVariables> {\n return {\n mutation: this.mutation,\n variables: this.variables,\n };\n }\n\n get executed() {\n return this._executed;\n }\n\n setExecuted() {\n if (this._executed) {\n throw new KcBadStateException('Already executed');\n }\n this._executed = true;\n }\n}\n","/* eslint-disable @typescript-eslint/no-explicit-any */\nimport { OperationVariables } from '@apollo/client/core';\nimport { DocumentNode, FieldNode, FragmentDefinitionNode } from 'graphql';\nimport * as ast from '../../_common/ast';\nimport {\n getAliasOrName,\n getFragments,\n getMutation,\n TypedDocumentNode,\n} from '../../_common/ast';\nimport { lodash } from '../../_common';\nimport {\n fragmentSpreadAstSelection,\n LrMutationBase,\n LrMutationData,\n} from './lr-mutation-base';\n\nexport class LrMutation<\n T extends any,\n TVariables = OperationVariables\n> extends LrMutationBase<T, TVariables> {\n constructor(options: LrMutationData<T, TVariables>) {\n super();\n this.mutation = options.mutation;\n this.variables = options.variables;\n }\n\n /**\n * Select a different set of fields from the mutation. Example usage:\n *\n * interface CreateDirectoryMutationResult {\n * createDirectory: {\n * directory: DirectoryNode;\n * };\n * };\n *\n * const CreateDirectoryMutation = gqlTyped<CreateDirectoryMutationResult>`\n * mutation CreateDirectoryMutation(...) {\n * createDirectory(...) {\n * directory {\n * id\n * }\n * }\n * }\n * `\n * interface CreateDirectoryFragmentResult {\n * createDirectory: {\n * directory: DirectoryNode;\n * };\n * };\n *\n * const CreateDirectoryFragment = gqlTyped<CreateDirectoryFragmentResult>`\n * // Note that the string 'createDirectory' can not be changed.\n * // It must match with the mutation field above.\n * // The 'CreateDirectoryPayload' is the return type of the mutation.\n * fragment createDirectory on CreateDirectoryPayload {\n * directory {\n * plainMeta\n * }\n * }\n * `\n * lrGraphQLService.lrMutate({\n * mutation: CreateDirectoryMutation\n * }).select(CreateDirectoryFragment).createDirectory.directory.plainMeta.\n *\n * @param fragments\n * @returns\n */\n select<TResult>(fragments: TypedDocumentNode<TResult>) {\n // Don't touch the original\n const mutationDoc = lodash.cloneDeep(this.mutation) as DocumentNode;\n const mutationNode = getMutation(mutationDoc);\n\n const fragmentMap = {} as { [key: string]: FragmentDefinitionNode };\n getFragments(fragments).forEach((fragment: FragmentDefinitionNode) => {\n // Using '_' as the delimiter for the dummy suffix which only serves to make fragment names\n // unique since apollo client demands unique fragment names.\n fragmentMap[fragment.name.value.split('_')[0]] = fragment;\n });\n\n const replaceFieldSelection = (selection: FieldNode) => {\n const field = selection as FieldNode;\n const fieldName = getAliasOrName(field);\n const fragment = fragmentMap[fieldName];\n\n if (!fragment) {\n return;\n }\n\n // Make the entire selection of the mutation a spread of\n // a fragment using the same name as the mutation field.\n // We will also rename the fragment to the same name.\n field.selectionSet.selections = [\n {\n ...fragmentSpreadAstSelection,\n name: ast.name(fragment.name.value),\n },\n ];\n };\n\n mutationNode.selectionSet.selections.forEach((selection) => {\n if (selection.kind === 'Field') {\n replaceFieldSelection(selection);\n }\n });\n\n return new LrMutation({\n mutation: {\n ...mutationDoc,\n definitions: [\n // Remove all existing fragments\n ...mutationDoc.definitions.filter(\n (def) => def.kind !== 'FragmentDefinition'\n ),\n ...fragments.definitions,\n ],\n } as TypedDocumentNode<TResult>,\n variables: this.variables,\n });\n }\n}\n","/* eslint-disable @typescript-eslint/no-explicit-any */\nimport {\n ArgumentNode,\n DocumentNode,\n FieldNode,\n FragmentDefinitionNode,\n FragmentSpreadNode,\n SelectionNode,\n SelectionSetNode,\n VariableDefinitionNode,\n} from 'graphql';\nimport { lodash } from '../../_common';\nimport * as ast from '../../_common/ast';\nimport { getAliasOrName, getFragments, getMutation } from '../../_common/ast';\nimport {\n KcBadLogicException,\n KcUnsupportedException,\n} from '../../_common/exceptions';\nimport { LrMutation } from './lr-mutation';\nimport { LrMutationBase } from './lr-mutation-base';\n\nconst lrMergedMutationDoc: DocumentNode = {\n kind: 'Document',\n definitions: [\n {\n kind: 'OperationDefinition',\n operation: 'mutation',\n name: {\n kind: 'Name',\n value: 'lrMergedMutation',\n },\n variableDefinitions: [],\n directives: [],\n selectionSet: {\n kind: 'SelectionSet',\n selections: [],\n },\n },\n ],\n // TODO What to do about these? Serialise and reparse?\n // \"loc\": {\n // \"start\": 0,\n // \"end\": 204\n // }\n};\n\nexport class LrMergedMutation<T> extends LrMutationBase<T> {\n public readonly descendants: Set<LrMutationBase<any>>;\n protected prefixes: string[];\n\n constructor(public readonly lrMutations: LrMutationBase<any>[]) {\n super();\n\n const { mutation, variables, prefixes } = this.merge();\n this.mutation = mutation;\n this.variables = variables;\n this.prefixes = prefixes;\n this.descendants = this.getDescendants();\n }\n\n static create<T1, T2>(\n lrMutations: [\n LrMutationBase<T1> | LrMergedMutation<T1>,\n LrMutationBase<T2> | LrMergedMutation<T2>\n ]\n ): LrMergedMutation<[T1, T2]>;\n\n static create<T1, T2, T3>(\n lrMutations: [\n LrMutationBase<T1> | LrMergedMutation<T1>,\n LrMutationBase<T2> | LrMergedMutation<T2>,\n LrMutationBase<T3> | LrMergedMutation<T3>\n ]\n ): LrMergedMutation<[T1, T2, T3]>;\n\n static create<T1, T2, T3, T4>(\n lrMutations: [\n LrMutationBase<T1> | LrMergedMutation<T1>,\n LrMutationBase<T2> | LrMergedMutation<T2>,\n LrMutationBase<T3> | LrMergedMutation<T3>,\n LrMutationBase<T4> | LrMergedMutation<T4>\n ]\n ): LrMergedMutation<[T1, T2, T3, T4]>;\n\n static create<T1, T2, T3, T4, T5>(\n lrMutations: [\n LrMutationBase<T1> | LrMergedMutation<T1>,\n LrMutationBase<T2> | LrMergedMutation<T2>,\n LrMutationBase<T3> | LrMergedMutation<T3>,\n LrMutationBase<T4> | LrMergedMutation<T4>,\n LrMutationBase<T5> | LrMergedMutation<T5>\n ]\n ): LrMergedMutation<[T1, T2, T3, T4, T5]>;\n\n static create<T>(lrMutations: LrMutationBase<T>[]): LrMergedMutation<T[]>;\n\n static create(lrMutations: LrMutationBase<any>[]): LrMergedMutation<any[]>;\n\n static create(lrMutations: LrMutationBase<any>[]) {\n return new LrMergedMutation(lrMutations);\n }\n\n private getDescendants() {\n const ret = new Set<LrMutationBase<any>>();\n\n const addOrThrow = (item) => {\n if (ret.has(item)) {\n throw new KcBadLogicException(\n 'Classes that are derived from LrMutationBase can not be used more than once in a merged mutation.'\n );\n }\n\n ret.add(item);\n };\n\n this.lrMutations.forEach((lrMutation) => {\n if (lrMutation instanceof LrMutation) {\n addOrThrow(lrMutation);\n } else if (lrMutation instanceof LrMergedMutation) {\n lrMutation.descendants.forEach((t) => addOrThrow(t));\n } else {\n throw new KcUnsupportedException(\n `LrMergeMutation can not handle class: ${lrMutation.constructor.name}`\n );\n }\n });\n\n return ret;\n }\n\n resolve(value: any) {\n // Resolves any promises waiting for the child mutations\n for (let i = 0; i < this.lrMutations.length; ++i) {\n const prefix = this.prefixes[i];\n\n // Remove the prefix and resolve child mutation.\n const res: any = {};\n for (const key2 in value) {\n if (key2.startsWith(prefix)) {\n const originalKey = key2.slice(prefix.length);\n res[originalKey] = value[key2];\n }\n }\n this.lrMutations[i].resolve(res);\n }\n\n // Resolves to the result of children\n Promise.all(this.lrMutations.map((m) => m.promise)).then(\n (childValues: any) => {\n // Resolves any promises waiting for the current merged mutation\n super.resolve(childValues);\n }\n );\n }\n\n reject(reason?: any) {\n super.reject(reason);\n this.lrMutations.forEach((lrMutation) => lrMutation.reject(reason));\n }\n\n setExecuted() {\n super.setExecuted();\n this.lrMutations.forEach((lrMutation) => lrMutation.setExecuted());\n }\n\n private renameVariableDefinition(varDef: VariableDefinitionNode, prefix) {\n return {\n ...varDef,\n variable: {\n ...varDef.variable,\n name: ast.name(prefix + varDef.variable.name.value),\n },\n };\n }\n\n private renameVariableDefinitions(\n varDefs: ReadonlyArray<VariableDefinitionNode>,\n prefix\n ) {\n return varDefs.map((varDef) =>\n this.renameVariableDefinition(varDef, prefix)\n );\n }\n\n private renameArgument(arg: ArgumentNode, prefix) {\n if (arg.value.kind !== 'Variable') {\n return arg;\n }\n\n return {\n ...arg,\n value: {\n ...arg.value,\n name: ast.name(prefix + arg.value.name.value),\n },\n };\n }\n\n private renameField(selection: FieldNode, prefix): FieldNode {\n // Only handling type Field\n if (selection.kind !== 'Field') {\n return selection;\n }\n\n const alias = prefix + getAliasOrName(selection);\n const args = selection.arguments.map((arg) =>\n this.renameArgument(arg, prefix)\n );\n\n return {\n ...selection,\n alias: {\n kind: 'Name',\n value: alias,\n },\n arguments: args,\n };\n }\n\n private renameFragmentSpread(\n selection: FragmentSpreadNode,\n prefix\n ): FragmentSpreadNode {\n return {\n ...selection,\n name: ast.name(prefix + selection.name.value),\n };\n }\n\n private processSelection(selection: SelectionNode, prefix): SelectionNode {\n switch (selection.kind) {\n case 'FragmentSpread':\n return this.renameFragmentSpread(selection, prefix);\n case 'Field':\n // Continue to process children for nested selections.\n if (selection.selectionSet) {\n return {\n ...selection,\n selectionSet: this.processSelectionSet(\n selection.selectionSet,\n prefix\n ),\n };\n } else {\n return selection;\n }\n default:\n return selection;\n }\n }\n\n private processSelectionSet(\n selectionSet: SelectionSetNode,\n prefix\n ): SelectionSetNode {\n return {\n ...selectionSet,\n selections: selectionSet.selections.map((selection) =>\n this.processSelection(selection, prefix)\n ),\n };\n }\n\n private renameSelections(\n selections: ReadonlyArray<SelectionNode>,\n prefix\n ): SelectionNode[] {\n return selections.map((selection) => {\n switch (selection.kind) {\n case 'Field':\n return this.processSelection(\n this.renameField(selection, prefix),\n prefix\n );\n default:\n return selection;\n }\n });\n }\n\n private renameFragmentDefinition(fragment: FragmentDefinitionNode, prefix) {\n const ret = {\n ...fragment,\n name: ast.name(prefix + fragment.name.value),\n };\n\n if (fragment.selectionSet) {\n ret.selectionSet = this.processSelectionSet(\n fragment.selectionSet,\n prefix\n );\n }\n\n return ret;\n }\n\n private renameFragmentDefinitions(\n fragments: FragmentDefinitionNode[],\n prefix\n ) {\n return fragments.map((fragment) =>\n this.renameFragmentDefinition(fragment, prefix)\n );\n }\n\n private merge() {\n let variableDefinitions: VariableDefinitionNode[] = [];\n let selections: SelectionNode[] = [];\n const mergedVariables = {};\n let mergedFragments: FragmentDefinitionNode[] = [];\n\n const prefixes: string[] = [];\n\n // Just wait for everything to resolve because we have to\n // merge the doc synchronously.\n this.lrMutations.forEach((lrMutation, idx) => {\n // Sometimes typing won't catch everything. So need to dynamically check the\n // type to be sure.\n if (!(lrMutation instanceof LrMutationBase)) {\n throw new KcBadLogicException(\n 'An mutation in the array is not of type LrMutationBase.'\n );\n }\n\n const { mutation, variables } = lrMutation.lrMutationData;\n\n const childMutationNode = getMutation(mutation);\n\n // Prefixing all mutation fields so they don't conflict.\n let prefix = `item${idx}_`;\n if (childMutationNode.name) {\n prefix += childMutationNode.name.value + '_';\n }\n\n prefixes.push(prefix);\n\n // Rename and merge variables\n variableDefinitions = [\n ...variableDefinitions,\n ...this.renameVariableDefinitions(\n childMutationNode.variableDefinitions,\n prefix\n ),\n ];\n\n // Rename and merge selections\n selections = [\n ...selections,\n ...this.renameSelections(\n childMutationNode.selectionSet.selections,\n prefix\n ),\n ];\n\n // Rename and merge variables\n for (const key2 of Object.keys(variables)) {\n mergedVariables[prefix + key2] = variables[key2];\n }\n\n // Rename and merge fragments\n const fragments = getFragments(mutation);\n mergedFragments = [\n ...mergedFragments,\n ...this.renameFragmentDefinitions(fragments, prefix),\n ];\n });\n\n const mergedMutation: DocumentNode = lodash.cloneDeep(lrMergedMutationDoc);\n const mutationNode = getMutation(mergedMutation);\n // Add in the mutation selections\n mutationNode.selectionSet.selections = selections;\n // Add in the variables\n // variableDefinitions is readonly property.\n (mutationNode as any).variableDefinitions = variableDefinitions;\n // Add in the fragments\n (mergedMutation as any).definitions = [\n ...mergedMutation.definitions,\n ...mergedFragments,\n ];\n\n return {\n mutation: mergedMutation,\n variables: mergedVariables,\n prefixes,\n };\n }\n}\n","/* eslint-disable @typescript-eslint/no-explicit-any */\nimport { Injectable, NgZone } from '@angular/core';\nimport {\n FetchPolicy,\n MutationOptions,\n OperationVariables,\n QueryOptions,\n} from '@apollo/client/core';\nimport { MutationBaseOptions } from '@apollo/client/core/watchQueryOptions';\nimport { Apollo } from 'apollo-angular';\nimport { FieldNode } from 'graphql';\nimport gql from 'graphql-tag';\nimport * as gqlPrinter from 'graphql/language/printer';\nimport { KeyGraphService } from '../../key/key-graph.service';\nimport { HasKeyGraph } from '../../key/key.types';\nimport { lodash } from '../../_common';\nimport { getMutation, getQuery, TypedDocumentNode } from '../../_common/ast';\nimport {\n handleApolloError,\n KcBadStateException,\n KcUnsupportedException,\n} from '../../_common/exceptions';\nimport { FetchKeyGraphField, KeyGraphField } from '../../_common/queries.gql';\nimport { RunOutsideAngular } from '../../_common/run-outside-angular';\nimport { MayAsync } from '../../_common/types';\nimport { ProcessorOptions, QueryProcessorService } from '../query-processor';\nimport { LrMergedMutation } from './lr-merged-mutation';\nimport { LrMutationBase } from './lr-mutation-base';\n\n// Data structures\n// --------------------------------------------------------------------------\nconst keyGraphFieldAstSelection = getQuery(gql`\nquery {\n ${KeyGraphField}\n}\n`).selectionSet.selections[0] as FieldNode;\n\nconst fetchKeyGraphFieldAstSelection = getQuery(gql`\nquery {\n ${FetchKeyGraphField}\n}\n`).selectionSet.selections[0] as FieldNode;\n\n// const keyGraphFieldAstSelection = () =>\n// lodash.deepClone(_keyGraphFieldAstSelection) as FieldNode;\n// const fetchKeyGraphFieldAstSelection = () =>\n// lodash.deepClone(_fetchKeyGraphFieldAstSelection) as FieldNode;\n\nexport interface LrQueryOptions<T, TVariables>\n extends QueryOptions<TVariables> {\n query: TypedDocumentNode<T>;\n includeKeyGraph?: boolean;\n name?: string;\n processorOptions?: ProcessorOptions;\n}\n\n// Copied from MutationOptions\n// Removed required field \"mutation\". The \"variables\" field is still there\n// but it's dynamically checked.\nexport interface LrMutationOptions<\n T = {\n [key: string]: any;\n },\n TVariables = OperationVariables\n> extends MutationBaseOptions<T, TVariables> {\n context?: any;\n fetchPolicy?: FetchPolicy;\n includeKeyGraph?: boolean;\n name?: string;\n}\n\n// The \"mutation\" and \"variable\" fields are inherited but dynamically prohibited because\n// they are provided by LrMutation. It's a bit unclean but avoids a lot of typing work.\nexport interface LrApolloMutationOptions<T, TVariables = OperationVariables>\n extends MutationOptions<T, TVariables> {\n mutation: TypedDocumentNode<T>;\n includeKeyGraph?: boolean;\n name?: string;\n processorOptions?: ProcessorOptions;\n}\n\ninterface LrGraphQLServiceStats {\n queryCount: number;\n mutationCount: number;\n}\n\n@RunOutsideAngular({\n ngZoneName: 'ngZone',\n})\n@Injectable({\n providedIn: 'root',\n})\nexport class LrGraphQLService {\n private stats: LrGraphQLServiceStats = {\n queryCount: 0,\n mutationCount: 0,\n };\n\n constructor(\n private ngZone: NgZone,\n private apollo: Apollo,\n private keyGraph: KeyGraphService,\n private queryProcessor: QueryProcessorService\n ) {}\n\n async query<T, V = { [key: string]: any }>(\n options: LrQueryOptions<T, V>\n ): Promise<T> {\n // Make copies to avoid side effect.\n options = lodash.cloneDeep(options);\n\n // Append the key graph query\n const includeKeyGraph = this.isIncludeKeyGraph(options.includeKeyGraph);\n if (includeKeyGraph) {\n const operation = getQuery(options.query);\n operation.selectionSet.selections = [\n ...operation.selectionSet.selections,\n keyGraphFieldAstSelection,\n ];\n }\n\n if (options.name) {\n const operation = getQuery(options.query);\n (operation.name as any) = {\n kind: 'Name',\n value: options.name,\n };\n }\n\n const response = await this.apollo.query<T, V>(options).toPromise();\n\n this.stats.queryCount++;\n\n handleApolloError(response.errors);\n\n this.addKeys(response);\n\n const data = await this.queryProcessor.processQuery(\n response.data,\n options.processorOptions\n );\n\n return data;\n }\n\n private async lrMutateImpl(lrMutation, options?) {\n if (options?.variables) {\n throw new KcUnsupportedException(\n 'Unsupported field: \"options.variables\"'\n );\n }\n\n if (lrMutation.executed) {\n throw new KcBadStateException(\n 'LrMutation has already executed. LrMutation can only be used once in a lrMutate() call. Create new instances of LrMutation.'\n );\n }\n\n lrMutation.setExecuted();\n\n return this.apolloMutate({\n ...options,\n ...lrMutation.lrMutationData,\n })\n .then((res) => {\n // Resolve promises set on the lrMutation rather than the lrMutate() call.\n lrMutation.resolve(res);\n // Still need to return value to the promise waiting for the results of lrMutate().\n return res;\n })\n .catch((error) => {\n lrMutation.reject(error);\n throw error;\n });\n }\n\n async apolloMutate<T extends any, TVariables = { [key: string]: any }>(\n options: LrApolloMutationOptions<T, TVariables>\n ): Promise<T> {\n // Make copies to avoid side effect.\n options = {\n ...options,\n mutation: lodash.cloneDeep(options.mutation),\n };\n\n // Append the key graph query\n const includeKeyGraph = this.isIncludeKeyGraph(options.includeKeyGraph);\n\n if (includeKeyGraph) {\n const operation = getMutation(options.mutation);\n operation.selectionSet.selections = [\n ...operation.selectionSet.selections,\n fetchKeyGraphFieldAstSelection,\n ];\n }\n\n if (options.name) {\n const operation = getMutation(options.mutation);\n (operation.name as any) = {\n kind: 'Name',\n value: options.name,\n };\n }\n\n // Format to string and parse again. This allows the \"loc\": { \"start\": ... }\n // part of the DocumentNode to be correctly setup. It's extra processing\n // in serialising and parsing, but probably minimal overhead.\n options.mutation = gql(gqlPrinter.print(options.mutation));\n\n const response = await this.apollo.mutate<T>(options).toPromise();\n\n this.stats.mutationCount++;\n\n handleApolloError(response.errors);\n\n this.addKeys(response);\n\n const data = await this.queryProcessor.processQuery(\n response.data,\n options.processorOptions\n );\n\n return data;\n }\n\n statsSnapshot(): LrGraphQLServiceStats {\n return lodash.cloneDeep(this.stats);\n }\n\n private addKeys(response) {\n if ((response.data as HasKeyGraph).keyGraph) {\n this.keyGraph.addKeys((response.data as HasKeyGraph).keyGraph);\n delete response.data.keyGraph;\n }\n }\n\n private isIncludeKeyGraph(includeKeyGraph) {\n // Default to true when null or undefined.\n return includeKeyGraph == null ? true : false;\n }\n\n async lrMutate<T1, TVariables1, T2, TVariables2>(\n lrMutations: [\n LrMutationMayAsync<T1, TVariables1>,\n LrMutationMayAsync<T2, TVariables2>\n ],\n options?: LrMutationOptions\n ): Promise<[T1, T2]>;\n\n async lrMutate<T1, TVariables1, T2, TVariables2, T3, TVariables3>(\n lrMutations: [\n LrMutationMayAsync<T1, TVariables1>,\n LrMutationMayAsync<T2, TVariables2>,\n LrMutationMayAsync<T3, TVariables3>\n ],\n options?: LrMutationOptions\n ): Promise<[T1, T2, T3]>;\n\n async lrMutate<\n T1,\n TVariables1,\n T2,\n TVariables2,\n T3,\n TVariables3,\n T4,\n TVariables4\n >(\n lrMutations: [\n LrMutationMayAsync<T1, TVariables1>,\n LrMutationMayAsync<T2, TVariables2>,\n LrMutationMayAsync<T3, TVariables3>,\n LrMutationMayAsync<T4, TVariables4>\n ],\n options?: LrMutationOptions\n ): Promise<[T1, T2, T3, T4]>;\n\n async lrMutate<\n T1,\n TVariables1,\n T2,\n TVariables2,\n T3,\n TVariables3,\n T4,\n TVariables4,\n T5,\n TVariables5\n >(\n lrMutations: [\n LrMutationMayAsync<T1, TVariables1>,\n LrMutationMayAsync<T2, TVariables2>,\n LrMutationMayAsync<T3, TVariables3>,\n LrMutationMayAsync<T4, TVariables4>,\n LrMutationMayAsync<T5, TVariables5>\n ],\n options?: LrMutationOptions\n ): Promise<[T1, T2, T3, T4, T5]>;\n\n async lrMutate<T, TVariables = { [key: string]: any }>(\n lrMutation: LrMutationMayAsync<T, TVariables>,\n options?: LrMutationOptions<T, TVariables>\n ): Promise<T>;\n\n async lrMutate<T, TVariables = { [key: string]: any }>(\n lrMutations: LrMutationMayAsync<T, TVariables>[],\n options?: LrMutationOptions\n );\n\n async lrMutate<T, TVariables = { [key: string]: any }>(\n lrMutations:\n | LrMutationMayAsync<T, TVariables>[]\n | LrMutationMayAsync<T, TVariables>,\n options?: LrMutationOptions\n ) {\n if (lrMutations instanceof Array) {\n const merged = LrMergedMutation.create(await Promise.all(lrMutations));\n await this.lrMutateImpl(merged, options);\n return merged.promise;\n } else {\n const resolved = await lrMutations;\n await this.lrMutateImpl(resolved, options);\n return resolved.promise;\n }\n }\n}\n\nexport type LrMutationMayAsync<T, TVariables = OperationVariables> = MayAsync<\n LrMutationBase<T, TVariables>\n>;\n","import { Injector } from '@angular/core';\nimport {\n LrGraphQLService,\n LrMutationOptions,\n LrQueryOptions,\n} from './lr-graphql.service';\nimport { LrMutationBase } from './lr-mutation-base';\n\nexport class LrService {\n protected lrGraphQL: LrGraphQLService;\n\n constructor(injector: Injector) {\n this.lrGraphQL = injector.get(LrGraphQLService);\n }\n\n protected async mutate<T, TVariables>(\n lrMutation:\n | LrMutationBase<T, TVariables>\n | Promise<LrMutationBase<T, TVariables>>,\n options?: LrMutationOptions<T, TVariables>\n ) {\n return this.lrGraphQL.lrMutate(lrMutation, options);\n }\n\n protected async query<T, V>(options: LrQueryOptions<T, V>) {\n return this.lrGraphQL.query(options);\n }\n}\n","// ------------------------------------------------------\n// Basic types\n// ------------------------------------------------------\n// These types map directory to types of the same name in graphql.\n// We use these aliases in case in the future we wish to reify the types and do\n// additional automated conversion.\n\nexport type ID = string;\n// Server requires this to have certain format. But client\n// just treats this as an opaque string.\nexport type LrRelayIdInput = string;\nexport type DateTime = string;\n// This is basically the results of: JSON.stringify(obj)\n// Server validated to make sure it can JSON.parse() this.\nexport type LrJSONString = string;\n// JSONString is a type from graphene. DB JSON fields maps to this type\n// automatically.\n// Where as LrJSONString is out custom implementation for input variables.\nexport type JSONString = string;\n// This avoid triggering linting rule that prohibits using type any.\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport type JSONObject = any;\nexport type LrEmail = string;\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport type GenericScalar = any;\nexport type UUID = string;\n\nexport interface Node {\n id?: string;\n}\n\nexport interface TimeStamped {\n created?: DateTime;\n modified?: DateTime;\n}\n\nexport interface Edge<NodeType extends Node> {\n node?: NodeType;\n cursor?: string;\n}\n\nexport interface Connection<NodeType> {\n pageInfo?: PageInfo;\n edges?: Edge<NodeType>[];\n}\n\nexport interface PageInfo {\n hasNextPage?: boolean;\n hasPreviousPage?: boolean;\n startCursor?: string;\n endCursor?: string;\n}\n","import {\n Connection,\n DateTime,\n GenericScalar,\n ID,\n JSONObject,\n JSONString,\n LrEmail,\n Node,\n TimeStamped,\n} from './graphql.types';\n\nexport function mapEdges<T>(connection: Connection<T>) {\n return connection.edges.map((edge) => edge.node);\n}\n\nexport interface LrNList<T> {\n list?: T[];\n}\n\nexport interface FeaturesNode {\n myVault?: string[];\n tpVault?: string[];\n shareVault?: string[];\n}\n\nexport enum UserDeleteState {\n REQUESTED = 'REQUESTED',\n}\n\nexport interface UserDeleteNode extends Node, TimeStamped {\n state?: UserDeleteState;\n}\n\nexport enum PlanState {\n ENABLED = 'ENABLED',\n DISABLED = 'DISABLED',\n}\n\nexport interface PlanNode extends Node {\n name?: string;\n data?: JSONString;\n state?: PlanState;\n}\n\nexport interface UserPlanStripeNode extends Node, TimeStamped {\n subscriptionId?: string;\n priceId?: string;\n}\n\nexport interface UserPlanNode extends Node, TimeStamped {\n user?: UserNode;\n plan?: PlanNode;\n periodEnd?: DateTime;\n stripe?: UserPlanStripeNode;\n issuer?: UserNode;\n}\n\nexport interface UserStripeNode extends Node, TimeStamped {\n customer?: GenericScalar;\n}\n\nexport interface PassKeyNode extends Node, TimeStamped {\n passKeyParams?: GenericScalar;\n passIdpParams?: GenericScalar;\n wrappedPassIdpVerifierPrk?: GenericScalar;\n}\n\nexport interface CurrentUserKeyNode extends Node, TimeStamped {\n passKeys?: PassKeyNode[];\n passKey?: PassKeyNode;\n rootKey?: KeyNode;\n masterKey?: KeyNode;\n pxk?: KeyNode;\n sigPxk?: KeyNode;\n}\n\n// ------------------------------------------------------\n// Node types\n// ------------------------------------------------------\nexport interface UserNode extends Node {\n username?: string;\n contactCards?: Connection<ContactCardNode>;\n currentUserKey?: CurrentUserKeyNode;\n ownedContactCard?: SharedContactCardNode;\n receivedContactCard?: SharedContactCardNode;\n isCurrentUser?: boolean;\n haveTp?: boolean;\n stripe?: UserStripeNode;\n userPlans?: Connection<UserPlanNode>;\n userDelete?: UserDeleteNode;\n features?: FeaturesNode;\n featureState?: UserFeatureState;\n sessionEncryptionKey?: string;\n plans?: IssuedPlanNode[];\n paymentMethods?: PaymentMethodNode[];\n billingHistory?: BillingField[];\n availablePlans?: AvailablePlanField[];\n config?: JSONString;\n configJson?: JSONObject;\n dateJoined?: string;\n}\n\nexport interface UserFeatureState extends TimeStamped {\n notificationsLastViewed?: DateTime;\n}\n\nexport interface PublicProfile {\n userId?: ID;\n email?: string;\n}\n\nexport interface ServerTime {\n timestamp?: string;\n}\n\nexport interface KeyNode extends Node, TimeStamped {\n pbk?: string;\n}\n\nexport interface ContactCardNode extends Node, TimeStamped {\n owner?: UserNode;\n publicDataSig?: string;\n publicSearchableSig?: string;\n sigPxk?: KeyNode;\n defaultFrom?: DateTime;\n publicData?: string;\n publicSearchable?: string;\n cipherData?: string;\n cipherDataClearJson?: JSONObject;\n key?: KeyNode;\n plainData?: string;\n plainDataSig?: string;\n}\n\nexport interface AccessControlledResource {\n accessRole?: AccessRoleChoice;\n permissions?: PermissionChoice[];\n tpAccessRoles?: AccessRole[];\n allAccessRoles?: AllAccessRole[];\n confidentiality?: ConfidentialResource;\n}\n\nexport interface DirectoryNode\n extends Node,\n TimeStamped,\n AccessControlledResource {\n plainMeta?: JSONString;\n plainMetaJson?: JSONObject;\n cipherMeta?: string;\n cipherMetaClearJson?: JSONObject;\n archived?: boolean;\n keyId?: ID;\n childFileLinks?: Connection<FileLinkNode>;\n childDirectoryLinks?: Connection<DirectoryLinkNode>;\n parentDirectoryLinks?: Connection<DirectoryLinkNode>;\n nParentDirectoryLinks?: LrNList<DirectoryLinkNode>;\n nChildDirectoryLinks?: LrNList<DirectoryLinkNode>;\n nChildFileLinks?: LrNList<FileLinkNode>;\n descendants?: Descendants;\n lock?: LockField;\n lockVersion?: string;\n shares?: Connection<DirectoryShareNode>;\n nShares?: LrNList<DirectoryShareNode>;\n reminder?: ReminderNode;\n}\n\nexport interface FileNode extends Node, TimeStamped, AccessControlledResource {\n currentVersion?: FileVersionNode;\n archived?: boolean;\n versions?: Connection<FileVersionNode>;\n keyId?: ID;\n parentDirectoryLinks?: Connection<FileLinkNode>;\n nParentDirectoryLinks?: LrNList<FileLinkNode>;\n lock?: LockField;\n lockVersion?: string;\n shares?: Connection<FileShareNode>;\n nShares?: LrNList<FileShareNode>;\n}\n\nexport interface DirectoryLinkNode extends Node, TimeStamped {\n parentDirectory?: DirectoryNode;\n childDirectory?: DirectoryNode;\n linkType?: LinkTypeField;\n}\n\nexport interface FileLinkNode extends Node, TimeStamped {\n parentDirectory?: DirectoryNode;\n childFile?: FileNode;\n linkType?: LinkTypeField;\n}\n\nexport enum ShareTypeChoice {\n TP = 'TP',\n DETACHED = 'DETACHED',\n}\n\nexport enum DetachedShareStateChoice {\n IN_PROGRESS = 'IN_PROGRESS',\n COMPLETED = 'COMPLETED',\n}\n\n// Not a generic so we can pick fields from this interface.\nexport interface ItemShareBase extends Node, TimeStamped {\n tp?: TpNode;\n role?: AccessRoleChoice;\n issuer?: PublicProfile;\n isIssuer?: boolean;\n subject?: PublicProfile;\n shareType?: ShareTypeChoice;\n detachedShareState?: DetachedShareStateChoice;\n}\n\nexport interface ItemShare<ItemType> extends ItemShareBase {\n item?: ItemType;\n}\nexport type DirectoryShareNode = ItemShare<DirectoryNode>;\nexport type FileShareNode = ItemShare<FileNode>;\n\nexport interface Descendants {\n directories?: Connection<DirectoryNode>;\n files?: Connection<FileNode>;\n directoriesCount?: number;\n filesCount?: number;\n}\n\nexport enum AccessRoleChoice {\n READER = 'READER',\n WRITER = 'WRITER',\n ADMIN = 'ADMIN',\n CUSTODIAN = 'CUSTODIAN',\n DENY = 'DENY',\n OWNER = 'OWNER',\n}\n\nexport enum AccessRoleChoiceOrder {\n READER = 0,\n WRITER = 1,\n ADMIN = 2,\n CUSTODIAN = 3,\n DENY = 4,\n CONFIDENTIAL = 5,\n OWNER = 6,\n}\n\nexport enum AccessRoleMethodChoice {\n INHERITED = 'INHERITED',\n DIRECT = 'DIRECT',\n}\n\nexport enum PermissionChoice {\n CREATE = 'CREATE',\n READ = 'READ',\n UPDATE = 'UPDATE',\n DELETE = 'DELETE',\n SHARE = 'SHARE',\n ARCHIVE = 'ARCHIVE',\n ACCESS_ARCHIVED = 'ACCESS_ARCHIVED',\n UNARCHIVE = 'UNARCHIVE',\n SET_CONFIDENTIAL = 'SET_CONFIDENTIAL',\n}\n\nexport interface ConfidentialResource {\n isConfidential?: boolean;\n method?: AccessRoleMethodChoice;\n}\n\nexport interface InheritedRole {\n role?: AccessRoleChoice;\n source?: DirectoryNode;\n}\n\nexport interface AccessRoleBase {\n role?: AccessRoleChoice;\n method?: AccessRoleMethodChoice;\n inheritedRole?: InheritedRole;\n isIssuer?: boolean;\n}\n\nexport interface AccessRole extends AccessRoleBase {\n issuer?: UserNode;\n subject?: UserNode;\n tp?: TpNode;\n}\n\nexport interface AllAccessRole extends AccessRoleBase {\n issuer?: PublicProfile;\n subject?: PublicProfile;\n}\n\nexport enum FileOperationField {\n CREATE = 'CREATE',\n READ = 'READ',\n UPDATE = 'UPDATE',\n REVERT = 'REVERT',\n DELETE = 'DELETE',\n}\n\nexport interface FileVersionNode extends Node, TimeStamped {\n file?: FileNode;\n state?: FileStateNode;\n operation?: FileOperationField;\n author?: UserNode;\n}\nexport interface FileStateNode extends Node, TimeStamped {\n plainMeta?: JSONString;\n plainMetaJson?: JSONObject;\n cipherMeta?: string;\n cipherMetaClearJson?: JSONObject;\n contentResource?: string;\n versions?: Connection<FileVersionNode>;\n keyId?: ID;\n}\n\nexport enum KeyExchangeOtkState {\n OTK_INITIATED = 'OTK_INITIATED',\n OTK_ACCEPTED = 'OTK_ACCEPTED',\n OTK_COMPLETED = 'OTK_COMPLETED',\n}\n\n// These fields are not optional because they are not within the user's control to select in a gql query.\nexport interface ContactCardSharedCipherData {\n // Shared read access between initiator and responder. But only the initiator has write access.\n sharedCipherDataClearJson: JSONObject;\n}\n\n/**\n * The contents of the one-time key cipher\n * These fields are not optional because they are not within the user's control to select in a gql query.\n */\nexport interface OtKeyCipherClearJson2 {\n // Used to confirm to the initiator that the responder has access to the one-time key.\n nonce: string;\n // Data sent from initiator to the responder\n initiator: {\n oneTimePbk: Record<string, JSONObject>; // one-time public encryption key the responder will use to send data back to the initiator\n pbk: Record<string, JSONObject>; // public encryption key\n sigPbk: Record<string, JSONObject>; // public signing key\n message?: JSONObject;\n contactCard?: ContactCardSharedCipherData;\n };\n}\n\nexport interface KeyExchangeOtkNode extends Node, TimeStamped {\n state?: KeyExchangeOtkState;\n sharedKey?: KeyNode;\n mkSharedKey?: KeyNode;\n initiatorSigPxk?: KeyNode;\n responderSigPxk?: KeyNode;\n initiatorOneTimePbkCipher?: string;\n otKeyParams?: string;\n otKeyCipher?: string;\n otKeyCipherClearJson?: OtKeyCipherClearJson2;\n responderPbkCipher?: string;\n}\n\nexport enum KeyExchangeState {\n IN_PROGRESS = 'IN_PROGRESS',\n COMPLETED = 'COMPLETED',\n DECLINED = 'DECLINED',\n CANCELLED = 'CANCELLED',\n DELETED = 'DELETED',\n}\n\nexport enum KeyExchangeMode {\n OTK = 'OTK',\n}\n\nexport interface KeyExchangeNode extends Node, TimeStamped {\n expiryTime?: DateTime;\n token?: string;\n tokenExpiryTime?: DateTime;\n state?: KeyExchangeState;\n mode?: KeyExchangeMode;\n initiator?: UserNode;\n responder?: UserNode;\n initiatorRootKeyCipher?: string;\n responderRootKeyCipher?: string;\n initiatorActionRequired?: boolean;\n responderActionRequired?: boolean;\n createTp?: boolean;\n otk?: KeyExchangeOtkNode;\n isInitiator?: boolean;\n isExpired?: boolean;\n responderEmailAddress?: LrEmail;\n}\n\nexport interface SharedItems {\n descendants: Descendants;\n directories?: Connection<DirectoryNode>;\n files?: Connection<FileNode>;\n}\n\nexport interface SharedContactCardNode extends Node, TimeStamped {\n owner?: UserNode;\n receiver?: UserNode;\n sharedKey?: KeyNode;\n sharedCipherData?: string;\n sharedCipherDataClearJson?: JSONObject;\n sharedCipherDataSig?: string;\n sharedCipherDataSigPxk?: KeyNode;\n ownerCipherData?: string;\n ownerCipherDataClearJson?: JSONObject;\n ownerKey?: KeyNode;\n ownerPlainData?: string;\n ownerPlainDataJson?: JSONObject;\n ownerPlainDataSig?: string;\n receiverCipherData?: string;\n receiverCipherDataClearJson?: JSONObject;\n receiverKey?: KeyNode;\n}\n\nexport interface UserSharedKeyNode extends Node, TimeStamped {\n keyExchange?: KeyExchangeNode;\n user?: UserNode;\n userPrk?: KeyNode;\n userSigPrk?: KeyNode;\n other?: UserNode;\n otherPbk?: KeyNode;\n otherSigPbk?: KeyNode;\n sharedKey?: KeyNode;\n mkSharedKey?: KeyNode;\n mkPxk?: KeyNode;\n mkReshareRequestCipher?: string;\n mkReshareResponseCipher?: string;\n mkReshareRequestCipherClearJson?: JSONObject;\n mkReshareResponseCipherClearJson?: JSONObject;\n mkReshareRequestSent?: boolean;\n mkReshareResponseSent?: boolean;\n}\n\nexport interface CurrentUserSharedKeyNode extends Node, TimeStamped {\n user?: UserNode;\n other?: UserNode;\n userSharedKey?: UserSharedKeyNode;\n}\n\nexport interface TpNode extends Node, TimeStamped {\n user?: UserNode;\n other?: UserNode;\n currentUserSharedKey?: CurrentUserSharedKeyNode;\n isCompleted?: boolean;\n sharedKey?: KeyNode;\n sharedContactCard?: SharedContactCardNode;\n myContactCard?: SharedContactCardNode;\n myItems?: SharedItems;\n theirItems?: SharedItems;\n myScenarios?: Connection<ScenarioNode>;\n sharedScenarios?: Connection<SharedScenarioNode>;\n}\n\nexport enum TpAssemblyState {\n DISABLED = 'DISABLED',\n ENABLED = 'ENABLED',\n CLAIMED = 'CLAIMED',\n APPROVED = 'APPROVED',\n REJECTED = 'REJECTED',\n EXPIRED = 'EXPIRED',\n CANCELLED = 'CANCELLED',\n RESET = 'RESET',\n}\n\nexport enum TpClaimState {\n CLAIMED = 'CLAIMED',\n APPROVED = 'APPROVED',\n REJECTED = 'REJECTED',\n EXPIRED = 'EXPIRED',\n CANCELLED = 'CANCELLED',\n RESET = 'RESET',\n}\n\nexport enum TpClaimApproverState {\n CLAIMED = 'CLAIMED',\n APPROVED = 'APPROVED',\n REJECTED = 'REJECTED',\n}\n\nexport interface TpPasswordResetApproval extends Node, TimeStamped {\n approverEmail?: string;\n receiverCipher?: string;\n receiverCipherClearJson?: JSONObject;\n receiverCipherPartialAssemblyKey?: string;\n receiverCipherPartialAssemblyKeyClearJson?: JSONObject;\n}\n\nexport interface TpPasswordResetUserApprovalNode extends Node, TimeStamped {\n receiverCipher?: string;\n receiverCipherClearJson?: JSONObject;\n receiverCipherPartialAssemblyKey?: string;\n receiverCipherPartialAssemblyKeyClearJson?: JSONObject;\n approverEmail?: string;\n}\n\nexport interface TpPasswordResetUserApprover {\n name?: string;\n email?: string;\n state?: TpClaimApproverState;\n}\n\nexport interface TpPasswordResetUserSubAssembly {\n singleReject?: boolean;\n quorum?: number;\n approvers?: TpPasswordResetUserApprover[];\n}\n\nexport interface TpPasswordResetUserAssembly {\n singleReject?: boolean;\n quorum?: number;\n subAssemblies?: TpPasswordResetUserSubAssembly[];\n}\n\nexport interface TpPasswordResetUser {\n username?: string;\n resetUsername?: string;\n state?: TpClaimState;\n passKey?: PassKeyNode;\n masterKey?: KeyNode;\n pxk?: KeyNode;\n sessionEncryptionKey?: string;\n approvals?: TpPasswordResetUserApprovalNode[];\n assemblyCipherData?: string;\n wrappedAssemblyKeyVerifierPrk?: string;\n assembly?: TpPasswordResetUserAssembly;\n requestAgainAfter?: DateTime;\n}\n\nexport interface TpPasswordResetNode extends Node, TimeStamped {\n assembly?: TpAssemblyNode;\n request?: TpPasswordResetRequestNode;\n applied?: boolean;\n}\n\nexport interface TpPasswordResetRequestNode extends Node, TimeStamped {\n state?: TpClaimState;\n}\n\nexport interface TpAssemblyNode extends Node, TimeStamped {\n id?: ID;\n singleReject?: boolean;\n quorum?: number;\n canMeetQuorum?: boolean;\n subjectKey?: KeyNode;\n subjectCipherData?: string;\n subjectCipherDataClearJson?: JSONObject;\n assemblyKey?: KeyNode;\n assemblyCipherData?: string;\n assemblyCipherDataClearJson?: JSONObject;\n subAssemblies?: Connection<TpSubAssemblyNode>;\n}\n\nexport interface TpSubAssemblyNode extends Node, TimeStamped {\n singleReject?: boolean;\n quorum?: number;\n subjectCipherData?: string;\n subjectCipherDataClearJson?: JSONObject;\n approvers?: Connection<TpAssemblyApproverNode>;\n}\n\nexport interface TpAssemblyApproverNode extends Node, TimeStamped {\n sharedKey?: KeyNode;\n sharedCipherData?: string;\n sharedCipherDataClearJson?: JSONObject;\n sharedCipherApprovalData?: string;\n sharedCipherApprovalDataClearJson?: JSONObject;\n tp?: TpNode;\n}\n\nexport interface SharedTpPasswordResetNode extends Node, TimeStamped {\n assembly?: SharedTpAssemblyNode;\n tp?: TpNode;\n sharedRequest?: SharedTpPasswordResetRequestNode;\n}\n\nexport interface SharedTpAssemblyNode extends Node, TimeStamped {\n asApprovers?: Connection<TpAssemblyAsApproverNode>;\n}\n\nexport interface TpAssemblyAsApproverNode extends Node, TimeStamped {\n sharedKey?: KeyNode;\n sharedCipherData?: string;\n sharedCipherDataClearJson?: JSONObject;\n}\n\nexport interface SharedTpPasswordResetRequestNode extends Node, TimeStamped {\n claim?: SharedTpClaimNode;\n pxk?: KeyNode;\n}\n\nexport interface SharedTpClaimNode extends Node, TimeStamped {\n state?: TpClaimState;\n asClaimApprovers?: Connection<SharedTpClaimApproverNode>;\n}\n\nexport interface SharedTpClaimApproverNode extends Node, TimeStamped {\n state?: TpClaimApproverState;\n sharedKey?: KeyNode;\n sharedCipherApprovalData?: string;\n sharedCipherApprovalDataClearJson?: JSONObject;\n sharedCipherPartialAssemblyKey?: string;\n sharedCipherPartialAssemblyKeyClearJson?: JSONObject;\n receiverApprovals?: Connection<SharedTpClaimReceiverApprovalNode>;\n}\n\nexport interface SharedTpClaimReceiverApprovalNode extends Node, TimeStamped {\n pxk?: KeyNode;\n}\n\nexport enum LockState {\n UNLOCKED = 'UNLOCKED',\n MUTEX_LOCKED = 'MUTEX_LOCKED',\n}\n\nexport enum ScenarioState {\n DISABLED = 'DISABLED',\n ENABLED = 'ENABLED',\n CLAIMED = 'CLAIMED',\n APPROVED = 'APPROVED',\n}\n\nexport enum ClaimState {\n CLAIMED = 'CLAIMED',\n EXPIRED = 'EXPIRED',\n APPROVED = 'APPROVED',\n REJECTED = 'REJECTED',\n CANCELLED = 'CANCELLED',\n RESET = 'RESET',\n}\n\nexport enum ClaimApproverState {\n CLAIMED = 'CLAIMED',\n APPROVED = 'APPROVED',\n REJECTED = 'REJECTED',\n}\n\nexport enum ScenarioLastClaimState {\n CLAIMED = 'CLAIMED',\n APPROVED = 'APPROVED',\n REJECTED = 'REJECTED',\n EXPIRED = 'EXPIRED',\n CANCELLED = 'CANCELLED',\n RESET = 'RESET',\n}\n\nexport interface ScenarioLatestClaim {\n state?: ScenarioLastClaimState;\n created?: DateTime;\n claimAgainAfter?: DateTime;\n}\n\nexport interface ScenarioNode extends Node, TimeStamped {\n subject?: UserNode;\n subjectKey?: KeyNode;\n subjectCipherData?: string;\n subjectCipherDataClearJson?: JSONObject;\n assembly?: TpAssemblyNode;\n state?: ScenarioState;\n claimants?: Connection<ScenarioClaimantNode>;\n receivers?: Connection<ScenarioReceiverNode>;\n claims?: Connection<ScenarioClaimNode>;\n claim?: ScenarioClaimNode;\n assemblyState?: ScenarioAssemblyState;\n latestClaim?: ScenarioLatestClaim;\n inactiveSeconds?: number;\n}\n\nexport interface ScenarioClaimNode extends Node, TimeStamped {\n claimant?: ScenarioClaimantNode;\n state?: ClaimState;\n scenario?: ScenarioNode;\n}\n\nexport interface ScenarioAssemblyState {\n singleReject?: boolean;\n quorum?: number;\n subAssemblyStates?: ScenarioSubAssemblyState[];\n}\n\nexport interface ScenarioSubAssemblyState {\n singleReject?: boolean;\n quorum?: number;\n approverStates?: ScenarioAssemblyApproverState[];\n}\n\nexport interface ScenarioAssemblyApproverState {\n state?: TpClaimApproverState;\n}\n\nexport interface ReceiverItems {\n receiverDirectories?: Connection<ScenarioReceiverDirectoryNode>;\n receiverFiles?: Connection<ScenarioReceiverFileNode>;\n}\n\nexport interface SharedScenarioReceiverItems {\n receiverDirectories?: Connection<SharedScenarioReceiverDirectoryNode>;\n receiverFiles?: Connection<SharedScenarioReceiverFileNode>;\n}\n\nexport interface ScenarioReceiverNodeBase extends Node, TimeStamped {\n sharedKey?: KeyNode;\n sharedCipherData?: string;\n sharedCipherDataClearJson?: JSONObject;\n pbk?: KeyNode;\n tp?: TpNode;\n}\n\n// For now these are the same but they may diverge in the future.\nexport interface ScenarioReceiverNode extends ScenarioReceiverNodeBase {\n receiverItems?: ReceiverItems;\n}\n\nexport interface SharedScenarioReceiverNode extends ScenarioReceiverNodeBase {\n receiverItems?: SharedScenarioReceiverItems;\n}\n\nexport type ReceiverDirectoryAccessRole = AccessRoleChoice;\n\nexport interface ScenarioReceiverItemNode extends Node, TimeStamped {\n sharedKey?: KeyNode;\n sharedCipherData?: string;\n sharedCipherDataClearJson?: JSONObject;\n accessRole?: ReceiverDirectoryAccessRole;\n}\n\nexport interface ScenarioReceiverDirectoryNode\n extends ScenarioReceiverItemNode {\n receiver?: ScenarioReceiverNode;\n directory?: DirectoryNode;\n}\n\nexport interface ScenarioReceiverFileNode extends ScenarioReceiverItemNode {\n receiver?: ScenarioReceiverNode;\n file?: FileNode;\n}\n\nexport interface SharedScenarioReceiverDirectoryNode\n extends ScenarioReceiverItemNode {\n receiver?: SharedScenarioReceiverNode;\n directory?: DirectoryNode;\n}\n\nexport interface SharedScenarioReceiverFileNode\n extends ScenarioReceiverItemNode {\n receiver?: SharedScenarioReceiverNode;\n file?: FileNode;\n}\n\nexport interface ScenarioClaimantNode extends Node, TimeStamped {\n tp?: TpNode;\n sharedKey?: KeyNode;\n sharedCipherData?: string;\n sharedCipherDataClearJson?: JSONObject;\n}\n\nexport interface SharedScenarioNode extends Node, TimeStamped {\n subject?: UserNode;\n state?: ScenarioState;\n tp?: TpNode;\n asClaimant?: ScenarioClaimantNode;\n asReceiver?: ScenarioReceiverNode;\n assembly?: SharedTpAssemblyNode;\n sharedClaim?: SharedScenarioClaimNode;\n assemblyState?: ScenarioAssemblyState;\n latestClaim?: ScenarioLatestClaim;\n}\n\nexport interface SharedScenarioClaimNode extends Node, TimeStamped {\n state?: ClaimState;\n sharedScenario?: SharedScenarioNode;\n isClaimant?: boolean;\n asClaimReceiver?: SharedScenarioClaimReceiverNode;\n claim?: SharedTpClaimNode;\n}\n\nexport interface SharedScenarioClaimApproverNode extends Node, TimeStamped {\n receivers?: Connection<SharedScenarioReceiverNode>;\n state?: ClaimApproverState;\n approver?: TpAssemblyApproverNode;\n}\n\nexport interface SharedScenarioClaimReceiverNode extends Node, TimeStamped {\n received?: DateTime;\n assemblyKeyId?: ID;\n approvals?: Connection<SharedScenarioClaimReceivedApprovalNode>;\n}\n\nexport interface SharedScenarioClaimReceivedApprovalNode\n extends Node,\n TimeStamped {\n receiverCipher?: string;\n receiverCipherPartialAssemblyKey?: string;\n pxk?: KeyNode;\n}\n\nexport interface NotificationNode extends Node, TimeStamped {\n plainData?: JSONString;\n plainMeta?: JSONString;\n timeRead?: DateTime;\n}\n\nexport interface NotificationManagementState extends Node, TimeStamped {\n lastViewed?: DateTime;\n}\n\nexport enum LinkTypeField {\n HARD = 'HARD',\n SOFT = 'SOFT',\n REFERENCE = 'REFERENCE',\n}\n\nexport interface MessageNode extends Node, TimeStamped {\n sender?: UserNode;\n receiver?: UserNode;\n sharedKey?: KeyNode;\n senderSigPbk?: KeyNode;\n plainMessage?: string;\n plainMessageJson?: string;\n signedCipherMessage?: string;\n signedCipherMessageClearJson?: JSONObject;\n}\n\nexport interface LockField {\n created?: DateTime;\n modified?: DateTime;\n expiryTime?: DateTime;\n version?: string;\n state?: LockState;\n}\n\nexport interface ServerConfig {\n relayConnectionMaxLimit?: number;\n}\n\nexport interface AvailablePlanField {\n issuerUid?: string;\n planUid?: string;\n name?: string;\n description?: string;\n priceOptions?: PriceOptionField[];\n trial?: TrialPeriodField;\n}\n\nexport interface PriceOptionField {\n priceId?: string;\n name?: string;\n description?: string;\n amount?: number;\n currency?: string;\n intervalUnit?: string;\n intervalCount?: number;\n}\n\nexport interface TrialPeriodField {\n years?: number;\n months?: number;\n weeks?: number;\n days?: number;\n}\n\nexport interface PaymentCaptureField {\n stripeIntentId?: string;\n stripeClientSecret?: string;\n}\n\nexport interface PaymentMethodNode extends Node, TimeStamped {\n card?: PaymentCardField;\n invoice?: PaymentInvoiceField;\n isDefault?: boolean;\n}\n\nexport interface PaymentCardField {\n brand?: string;\n lastFourDigits?: string;\n expiryYear?: number;\n expiryMonth?: number;\n}\n\nexport interface PaymentInvoiceField {\n email?: string;\n}\n\nexport interface PromotionalCodeField {\n amountOff?: number;\n currency?: string;\n percentOff?: number;\n name?: string;\n duration?: string;\n durationInMonths?: number;\n}\n\nexport interface PeriodField {\n start?: DateTime;\n end?: DateTime;\n}\n\nexport interface IssuedPlanNode extends Node, TimeStamped {\n name?: string;\n description?: string;\n currentStates?: IssuedPlanStateNode[];\n currentPeriod?: PeriodField;\n currentPriceOption?: PriceOptionField;\n upcomingInvoice?: BillingField;\n alternativePriceOptions?: PriceOptionField[];\n scheduledPriceChanges?: PriceChangeField[];\n}\n\nexport interface IssuedPlanStateNode extends Node, TimeStamped {\n periodStart?: DateTime;\n periodEnd?: DateTime;\n state?: PlanStateField;\n}\n\nexport enum PlanStateField {\n TRIALLING = 'TRIALLING',\n ACTIVE = 'ACTIVE',\n CANCELLED = 'CANCELLED',\n EXPIRED = 'EXPIRED',\n}\n\nexport interface BillingField {\n invoiceNumber?: string;\n total?: number;\n amountDue?: number;\n currency?: string;\n documentUrl?: string;\n status?: string;\n periodStart?: DateTime;\n periodEnd?: DateTime;\n finalisedAt?: DateTime;\n paidAt?: DateTime;\n paid?: boolean;\n nextPaymentAttempt?: DateTime;\n}\n\nexport interface PriceChangeField {\n periodStart?: DateTime;\n priceOption?: PriceOptionField;\n}\n\nexport interface ReminderNode extends Node, TimeStamped {\n plain?: JSONString;\n plainJson?: JSONObject;\n firstEvent?: DateTime;\n notifyAheadSeconds?: number;\n notifyAt?: DateTime;\n directory?: DirectoryNode;\n}\n","import { AuthClass } from '@aws-amplify/auth/lib-esm/Auth';\nimport { KcConfig } from '../life-ready.config';\n\nexport function handleCognitoCallback<T>(\n method: (callback: (err?: Error, result?: T) => void) => void\n): Promise<T> {\n return new Promise<T>((resolve, reject) =>\n method((err, result) => (err ? reject(err) : resolve(result)))\n );\n}\n\nexport const awsFetch = (authUrl: string) => {\n const fetch = window.fetch;\n\n return (url, options) => {\n const pass = () => fetch(url, options);\n\n if (!options || !options.headers || !options.headers['X-Amz-Target']) {\n return pass();\n }\n\n const operation = options.headers['X-Amz-Target'].split('.');\n if (\n operation.length < 2 ||\n operation[0] !== 'AWSCognitoIdentityProviderService'\n ) {\n return pass();\n }\n\n const body = JSON.parse(options.body);\n\n if (body && body.ClientMetadata && body.ClientMetadata.noProxy === 'true') {\n return pass();\n }\n\n let custom = false;\n\n if (operation[1] === 'RespondToAuthChallenge') {\n if (body && body.ChallengeName === 'NEW_PASSWORD_REQUIRED') {\n return pass();\n }\n custom = true;\n } else if (operation[1] === 'InitiateAuth') {\n if (body.AuthFlow === 'REFRESH_TOKEN_AUTH') {\n custom = true;\n }\n }\n\n if (!custom) {\n return pass();\n }\n\n return fetch(`${authUrl}auth/proxy/`, {\n ...options,\n credentials: 'include',\n });\n };\n};\n\nexport const configureAmplifyAuth = (\n { authUrl: authUrl, userPoolId, userPoolWebClientId }: KcConfig,\n auth: AuthClass\n) => {\n return () => {\n const tokens = userPoolId.split('_');\n if (tokens.length < 2) {\n throw new Error('userPoolId should have this format: {aws-region}_xxxxx');\n }\n\n window.fetch = awsFetch(authUrl);\n\n auth.configure({\n // REQUIRED - Amazon Cognito Region\n region: tokens[0],\n // OPTIONAL - Amazon Cognito User Pool ID\n userPoolId,\n // OPTIONAL - Amazon Cognito Web Client ID (26-char alphanumeric string)\n userPoolWebClientId,\n // OPTIONAL - Enforce user authentication prior to accessing AWS resources or not\n mandatorySignIn: false,\n });\n };\n};\n","export enum Config {\n TIMEOUT = 0.01, // seconds, min value 0.01, after state is idle, wait for TIMEOUT seconds before taking action\n IDLE = 60 * 20, // seconds, period of inactivity to consider state as idle\n KEEP_ALIVE_INTERVAL = 60 * 1, // seconds, triggered on a regular basis while active (i.e. while not idling)\n}\n\nexport interface KeepaliveResult {\n session: {\n expires_after_seconds: number;\n };\n}\n","import { HttpClient } from '@angular/common/http';\nimport { Inject, Injectable } from '@angular/core';\nimport { AuthClass } from '@aws-amplify/auth/lib-esm/Auth';\nimport { DEFAULT_INTERRUPTSOURCES, Idle } from '@ng-idle/core';\nimport { Keepalive } from '@ng-idle/keepalive';\nimport { KeyService } from '../key/key.service';\nimport { Key } from '../key/key.types';\nimport { httpOptions, KcConfig, KC_CONFIG } from '../life-ready.config';\nimport {\n KcBadArgumentException,\n KcBadStateException,\n} from '../_common/exceptions';\nimport { Config, KeepaliveResult } from './idle.types';\n\n/**\n * onInit: true when onTimeout is called from the init() function. i.e. tab was closed and on reloading the webapp it already timed out.\n */\nexport type IdleServiceOnTimeout = ({\n onInit: boolean,\n}) => void | Promise<void>;\n\nexport type IdleServiceOnKeepalive = () => void | Promise<void>;\n\nexport interface IdleServiceInit {\n // Keep these as callbacks so we can ensure they are called immediately without going into the\n // event loop.\n onTimeout?: IdleServiceOnTimeout;\n onKeepalive?: IdleServiceOnKeepalive;\n idleSec?: number;\n timeoutSec?: number;\n keepAliveIntervalSec?: number;\n}\n\n@Injectable({\n providedIn: 'root',\n})\nexport class IdleService {\n private readonly IDLE_EXPIRY_KEY = 'ng2Idle.main.expiry';\n private readonly IDLING_KEY = 'ng2Idle.main.idling';\n\n private initCalled = false;\n private onTimeout: IdleServiceOnTimeout;\n private onKeepalive: IdleServiceOnKeepalive;\n\n constructor(\n @Inject(KC_CONFIG) private config: KcConfig,\n private http: HttpClient,\n private idle: Idle,\n private keepalive: Keepalive,\n private keyService: KeyService,\n private auth: AuthClass\n ) {}\n\n private assertInit(): void {\n if (!this.initCalled) {\n throw new KcBadStateException('Call IdleService.init() first.');\n }\n }\n\n public async init(params?: IdleServiceInit): Promise<void> {\n if (this.initCalled) {\n throw new KcBadStateException(\n 'IdleService.init() can only be called once. IdleService.start() calls init() with default values if init() has not been called yet.'\n );\n }\n\n this.initCalled = true;\n\n // Defaults\n params = {\n onTimeout: null,\n onKeepalive: null,\n idleSec: Config.IDLE,\n timeoutSec: Config.TIMEOUT,\n keepAliveIntervalSec: Config.KEEP_ALIVE_INTERVAL,\n ...params,\n };\n\n // If timeoutSec == 0 then the onTimeout() callback is never called.\n if (params.timeoutSec < 0.01) {\n throw new KcBadArgumentException(\n 'Minimum value for IdleService.init({ timeoutSec }) is 0.01'\n );\n }\n\n this.onTimeout = params.onTimeout;\n this.onKeepalive = params.onKeepalive;\n\n // ------------------------------------------------------------------------\n // Setup Idle\n // ------------------------------------------------------------------------\n // sets an idle timeout of 5 seconds, for testing purposes.\n this.idle.setIdle(params.idleSec);\n // sets a timeout period of 5 seconds. after 10 seconds of inactivity, the user will be considered timed out.\n this.idle.setTimeout(params.timeoutSec);\n // sets the default interrupts, in this case, things like clicks, scrolls, touches to the document\n this.idle.setInterrupts(DEFAULT_INTERRUPTSOURCES);\n\n this.idle.onIdleEnd.subscribe(() => console.log('Idle stopped'));\n this.idle.onIdleStart.subscribe(() => console.log('Idle started'));\n\n this.idle.onTimeout.subscribe(async () => {\n console.log('Idle timed out');\n this.reset();\n await Promise.resolve(\n this.onTimeout && this.onTimeout({ onInit: false })\n );\n });\n this.idle.onTimeoutWarning.subscribe((countdown) =>\n console.log(`Will timeout in ${countdown} seconds!`)\n );\n\n // ------------------------------------------------------------------------\n // Setup Keepalive\n // ------------------------------------------------------------------------\n // Ref: https://github.com/moribvndvs/ng2-idle#readme\n // ng-idle will instruct @ng-idle/keepalive to ping while the user is active, and stop once\n // they go idle or time out. When the user resumes activity or the idle state is reset, it will\n // ping immediately and then resume pinging.\n this.keepalive.interval(params.keepAliveIntervalSec);\n console.log(\n `Keep alive interval set at: ${Config.KEEP_ALIVE_INTERVAL} seconds`\n );\n\n this.keepalive.onPing.subscribe(() => this.onPing());\n\n // If the browser tab has been closed for a period longer thant the inactivity\n // period, then we should logout right from the start.\n const idleExpiry = localStorage.getItem(this.IDLE_EXPIRY_KEY);\n if (\n idleExpiry &&\n parseInt(idleExpiry, 10) + this.idle.getTimeout() * 1000 < Date.now()\n ) {\n this.reset();\n await Promise.resolve(this.onTimeout && this.onTimeout({ onInit: true }));\n }\n }\n\n public async keepalivePost(): Promise<{\n expiresAfterSeconds: number;\n keepaliveResult: KeepaliveResult;\n }> {\n const keepaliveResult = await this.http\n .post<KeepaliveResult>(\n `${this.config.authUrl}auth/keepalive/`,\n null,\n // /auth/keepalive/ will be extending the sessions cookie.\n await httpOptions(this.auth, this.config)\n )\n .toPromise();\n\n return {\n keepaliveResult,\n expiresAfterSeconds:\n this.idle.getIdle() +\n this.idle.getTimeout() +\n this.keepalive.interval(),\n };\n }\n\n public async persistMasterKey(masterKey: Key): Promise<void> {\n // The keepalive API call extends the server-side session, the session cookie expiry, refresh key cookie\n // expiry, and returns the session expiry.\n // NOTE Use time delta rather than absolute time, since client clock and server clock maybe\n // out of sync. We can't use the serverTime() functionality because the cookie expiry still\n // run on local clock.\n const { expiresAfterSeconds } = await this.keepalivePost();\n\n // Persist the derived passKey\n await this.keyService.persistMasterKey(masterKey, expiresAfterSeconds);\n }\n\n private async onPing(): Promise<void> {\n console.log(\n `Keep alive triggered at time: ${Date.now()}. Interval set at: ${this.keepalive.interval()} seconds`\n );\n\n // Keepalive API will extend the session expiry.\n const { expiresAfterSeconds } = await this.keepalivePost();\n\n // Extend the expiry of the persisted key\n await this.keyService.setMasterKeyExpiresAfterSeconds(expiresAfterSeconds);\n\n await Promise.resolve(this.onKeepalive && this.onKeepalive());\n }\n\n public async start(): Promise<void> {\n if (!this.initCalled) {\n await this.init();\n }\n\n if (this.idle.isRunning()) {\n return;\n }\n\n // Ping does not seem to happen right at the start. So we call it explicitly\n await this.onPing();\n\n this.idle.watch();\n }\n\n public stop(): void {\n this.idle.stop();\n this.reset();\n }\n\n private reset() {\n localStorage.removeItem(this.IDLE_EXPIRY_KEY);\n localStorage.removeItem(this.IDLING_KEY);\n }\n}\n","import { KeyGraphField } from '../_common/queries.gql';\nimport gql from 'graphql-tag';\n\nexport const ContactCardFields = `\nid\npublicData\npublicSearchable\ncipherData\nkey {\n id\n}\n`;\n\nexport const ContactCardQuery = gql`\nquery ContactCardQuery(\n$id: LrRelayIdInput!\n) {\ncontactCard (\n id: $id\n) {\n ${ContactCardFields}\n}\n${KeyGraphField}\n}`;\n\nexport const SearchContactCardQuery = gql`\nquery SearchContactCardQuery(\n $publicSearchable: LrJSONFilter!\n) {\n searchContactCards(\n publicSearchable: $publicSearchable\n orderBy: \"created\"\n ) {\n edges {\n node {\n ${ContactCardFields}\n }\n }\n }\n ${KeyGraphField}\n}`;\n\nexport const ContactCardListQuery = gql`\nquery ContactCardListQuery {\n contactCards(\n orderBy: \"created\"\n ) {\n edges {\n node {\n ${ContactCardFields}\n }\n }\n }\n ${KeyGraphField}\n}`;\n\nexport const CreateContactCardMutation = gql`\nmutation CreateContactCardMutation(\n $input: CreateContactCardInput!\n) {\n createContactCard(input: $input) {\n contactCard {\n ${ContactCardFields}\n }\n }\n}`;\n\nexport const UpdateContactCardMutation = gql`\nmutation UpdateContactCardMutation(\n $input: UpdateContactCardInput!\n) {\n updateContactCard(input: $input) {\n contactCard {\n ${ContactCardFields}\n }\n }\n}`;\n\nexport const DeleteContactCardMutation = gql`\n mutation DeleteContactCardMutation($input: DeleteContactCardInput!) {\n deleteContactCard(input: $input) {\n id\n }\n }\n`;\n","/* eslint-disable @typescript-eslint/no-explicit-any */\nimport { Injectable } from '@angular/core';\nimport { JWK } from 'node-jose';\nimport { LrApolloService } from '../api/lr-apollo.service';\nimport { ID } from '../api/types';\n// import { GetCategoryKeyIdQuery } from '../category/category.gql';\nimport { EncryptionService } from '../encryption/encryption.service';\nimport { gqlTyped } from '../_common/ast';\nimport { KeyFactoryService } from './key-factory.service';\nimport { KeyGraphService } from './key-graph.service';\nimport { KeyService } from './key.service';\n\nexport interface DirectoryKeyQueryResult {\n directory: {\n keyId: ID;\n };\n}\nexport const DirectoryKeyQuery = gqlTyped<DirectoryKeyQueryResult>`\nquery DirectoryKeyQuery($id: LrRelayIdInput!) {\n directory(id: $id) {\n keyId\n }\n}\n`;\n\nexport interface HasCipherMeta {\n keyId: string;\n cipherMeta: string;\n}\n\nexport class WrappedContent {\n key: JWK.Key;\n cipherMeta: string;\n wrappedKeys?: WrappingKey[];\n rootKey?: WrappingKey;\n}\n\nexport class WrappingKey {\n directoryId?: string;\n wrappingKeyId: string;\n wrappedKey: string;\n}\n\n@Injectable({\n providedIn: 'root',\n})\nexport class KeyMetaService {\n constructor(\n private encryptionService: EncryptionService,\n private keyGraph: KeyGraphService,\n private lrApollo: LrApolloService,\n private keyService: KeyService,\n private keyFactory: KeyFactoryService\n ) {}\n\n async decryptMeta<T>(metaHaver: HasCipherMeta): Promise<T> {\n if (metaHaver.cipherMeta) {\n const key = await this.keyGraph.getJwkKey(metaHaver.keyId);\n return (await this.encryptionService.decrypt(\n key,\n JSON.parse(metaHaver.cipherMeta)\n )) as any;\n }\n return null;\n }\n\n async doubleWrapContent(\n secureContent: any,\n categoryIds: string[],\n fileContent?: ArrayBuffer\n ) {\n const key = await this.keyFactory.createKey();\n\n const wrappedContent = await this.wrapContent(\n key.toJSON(true),\n categoryIds\n );\n\n return {\n rootKey: wrappedContent.rootKey,\n wrappedKeys: wrappedContent.wrappedKeys,\n doubleWrappedKey: wrappedContent.cipherMeta,\n cipherMeta: secureContent\n ? JSON.stringify(\n await this.encryptionService.encrypt(key, secureContent)\n )\n : null,\n cipherFileContent: fileContent\n ? JSON.stringify(await this.encryptionService.encrypt(key, fileContent))\n : null,\n };\n }\n\n async reWrapContent(keyId: string, secureContent: any) {\n const key = await this.keyGraph.getJwkKey(keyId);\n const newKey = await this.keyFactory.createKey();\n\n return {\n doubleWrappedKey: JSON.stringify(\n await this.encryptionService.encrypt(key, newKey.toJSON(true))\n ),\n cipherMeta: secureContent\n ? JSON.stringify(\n await this.encryptionService.encrypt(newKey, secureContent)\n )\n : null,\n };\n }\n\n async wrapContent(\n secureContent: any,\n categoryIds?: string[]\n ): Promise<WrappedContent> {\n const key = await this.keyFactory.createKey();\n\n let wrappedKeys: WrappingKey[];\n let rootWrappingKey: WrappingKey;\n\n if (categoryIds && categoryIds.length) {\n wrappedKeys = await Promise.all(\n categoryIds.map(async (categoryId) => {\n const parentKey = await this.getDirectoryKeyId(categoryId);\n const wrappedKey = JSON.stringify(\n await this.encryptionService.encrypt(\n parentKey.key,\n key.toJSON(true)\n )\n );\n return {\n directoryId: categoryId,\n wrappingKeyId: parentKey.keyId,\n wrappedKey,\n };\n })\n );\n } else {\n // Adding to root directory\n const rootKey = this.keyService.currentRootKey;\n const wrappedKey = JSON.stringify(\n await this.encryptionService.encrypt(rootKey.jwk, key.toJSON(true))\n );\n rootWrappingKey = {\n wrappingKeyId: rootKey.id,\n wrappedKey,\n };\n }\n\n return {\n key,\n rootKey: rootWrappingKey,\n wrappedKeys,\n cipherMeta: secureContent\n ? JSON.stringify(\n await this.encryptionService.encrypt(key, secureContent)\n )\n : null,\n };\n }\n\n async wrapContentWithKey(\n secureContent: any,\n keyId: string\n ): Promise<WrappedContent> {\n const key = await this.keyFactory.createKey();\n\n const wrappedKey = await this.keyGraph.encryptToString(\n keyId,\n key.toJSON(true)\n );\n\n return {\n key,\n rootKey: {\n wrappingKeyId: keyId,\n wrappedKey,\n },\n cipherMeta: secureContent\n ? JSON.stringify(\n await this.encryptionService.encrypt(key, secureContent)\n )\n : null,\n };\n }\n\n private async getDirectoryKeyId(\n categoryId: string\n ): Promise<{ keyId: string; key: any }> {\n const { directory } = await this.lrApollo.query<any>({\n query: DirectoryKeyQuery,\n variables: {\n id: categoryId,\n },\n });\n\n return {\n keyId: directory.keyId,\n key: await this.keyGraph.getJwkKey(directory.keyId),\n };\n }\n}\n","import { JWK } from 'node-jose';\nimport {\n Connection,\n DateTime,\n ID,\n JSONObject,\n JSONString,\n LrEmail,\n OtKeyCipherClearJson2,\n} from '../api/types';\nimport { gqlTyped } from '../_common/ast';\n\nexport type KeyExchangeState2 =\n | 'IN_PROGRESS'\n | 'COMPLETED'\n | 'DECLINED'\n | 'CANCELLED'\n | 'DELETED';\n\nexport interface KeyExchangeFieldsResult {\n id: ID;\n token: string;\n state: KeyExchangeState2;\n mode: 'OTK';\n isInitiator: boolean;\n initiator: {\n id: ID;\n username: string;\n config: JSONString;\n configJson: JSONObject;\n };\n responder: {\n id: ID;\n username: string;\n };\n created: DateTime;\n modified: DateTime;\n tokenExpiryTime: DateTime;\n isExpired: boolean;\n initiatorRootKeyCipher: string;\n initiatorRootKeyCipherClearJson: JSONObject;\n initiatorActionRequired: boolean;\n responderActionRequired: boolean;\n responderEmailAddress: LrEmail;\n otk: {\n state: 'OTK_INITIATED' | 'OTK_ACCEPTED' | 'OTK_COMPLETED';\n otKeyParams: string;\n otKeyCipher: string;\n otKey?: JWK.Key;\n otKeyCipherClearJson?: OtKeyCipherClearJson2;\n sharedKey: {\n id: ID;\n };\n mkSharedKey: {\n id: ID;\n };\n initiatorSigPxk: {\n id: ID;\n };\n responderSigPxk: {\n id: ID;\n };\n initiatorOneTimePbkCipher: string;\n initiatorOneTimePbkCipherClearJson: JSONObject;\n responderPbkCipher: string;\n };\n}\n\nexport const KeyExchangeFields = `\n id\n token\n state\n mode\n isInitiator\n initiator {\n id\n username\n config\n }\n responder {\n id\n username\n }\n created\n modified\n tokenExpiryTime\n isExpired\n initiatorRootKeyCipher\n initiatorActionRequired\n responderActionRequired\n responderEmailAddress\n otk {\n state\n otKeyParams\n otKeyCipher\n sharedKey {\n id\n }\n mkSharedKey {\n id\n }\n initiatorSigPxk {\n id\n }\n responderSigPxk {\n id\n }\n initiatorOneTimePbkCipher\n responderPbkCipher\n }\n`;\n\nexport interface UserSharedKeyFieldsResult {\n userSigPrk: {\n id: ID;\n };\n otherSigPbk: {\n id: ID;\n };\n sharedKey: {\n id: ID;\n };\n mkSharedKey: {\n id: ID;\n };\n mkPxk: {\n id: ID;\n pbk: JSONObject;\n };\n mkReshareRequestCipher: string;\n mkReshareResponseCipher: string;\n mkReshareRequestSent: boolean;\n mkReshareResponseSent: boolean;\n}\nexport const UserSharedKeyFields = `\n userSigPrk {\n id\n }\n otherSigPbk {\n id\n }\n sharedKey {\n id\n }\n mkSharedKey {\n id\n }\n mkPxk {\n id\n pbk\n }\n mkReshareRequestCipher\n mkReshareResponseCipher\n mkReshareRequestSent\n mkReshareResponseSent\n`;\n\nexport interface KeyExchangesQuery2 {\n keyExchanges: Connection<KeyExchangeFieldsResult>;\n}\nexport const KeyExchangesQuery2 = gqlTyped<KeyExchangesQuery2>`\nquery KeyExchangesQuery2($state: String) {\n keyExchanges(state: $state) {\n edges {\n node {\n ${KeyExchangeFields}\n }\n }\n }\n}\n`;\n\nexport interface KeyExchangeQuery2 {\n keyExchange: KeyExchangeFieldsResult;\n}\nexport const KeyExchangeQuery2 = gqlTyped<KeyExchangeQuery2>`\nquery KeyExchangeQuery2($id: LrRelayIdInput!) {\n keyExchange(id: $id) {\n ${KeyExchangeFields}\n }\n}\n`;\n\n// Key graph is only available for authenticated users. This query\n// is for unauthenticated users.\nexport interface KeyExchangeTokenQuery2 {\n keyExchange: KeyExchangeFieldsResult;\n}\nexport const KeyExchangeTokenQuery2 = gqlTyped<KeyExchangeTokenQuery2>`\nquery KeyExchangeTokenQuery2($id: LrRelayIdInput!, $token: String) {\n keyExchange(id: $id, token: $token) {\n ${KeyExchangeFields}\n }\n}\n`;\n\nexport interface CancelKeyExchangeMutation {\n cancelKeyExchange: {\n keyExchange: {\n id: ID;\n };\n };\n}\nexport const CancelKeyExchangeMutation = gqlTyped<CancelKeyExchangeMutation>`\nmutation CancelKeyExchangeMutation($input: CancelKeyExchangeInput!) {\n cancelKeyExchange(input: $input) {\n keyExchange {\n id\n }\n }\n}\n`;\n\nexport interface DeclineKeyExchangeMutation {\n declineKeyExchange: {\n keyExchange: {\n id: ID;\n };\n };\n}\nexport const DeclineKeyExchangeMutation = gqlTyped<DeclineKeyExchangeMutation>`\nmutation DeclineKeyExchangeMutation($input: DeclineKeyExchangeInput!) {\n declineKeyExchange(input: $input) {\n keyExchange {\n id\n }\n }\n}\n`;\n\nexport interface InitiateKeyExchangeOtkMutation {\n initiateKeyExchangeOtk: {\n keyExchange: KeyExchangeFieldsResult;\n };\n}\nexport const InitiateKeyExchangeOtkMutation = gqlTyped<InitiateKeyExchangeOtkMutation>`\nmutation InitiateKeyExchangeOtkMutation(\n $input: InitiateKeyExchangeOtkInput!\n) {\n initiateKeyExchangeOtk(input: $input) {\n keyExchange {\n ${KeyExchangeFields}\n }\n }\n}\n`;\n\nexport interface RespondKeyExchangeOtkMutation {\n respondKeyExchangeOtk: {\n keyExchange: KeyExchangeFieldsResult;\n userSharedKey: UserSharedKeyFieldsResult;\n tp: {\n id: ID;\n user: {\n config: unknown;\n };\n };\n };\n}\nexport const RespondKeyExchangeOtkMutation = gqlTyped<RespondKeyExchangeOtkMutation>`\nmutation RespondKeyExchangeOtkMutation($input: RespondKeyExchangeOtkInput!) {\n respondKeyExchangeOtk(input: $input) {\n keyExchange {\n ${KeyExchangeFields}\n }\n userSharedKey {\n ${UserSharedKeyFields}\n }\n tp {\n id\n user {\n config\n }\n }\n }\n}\n`;\n\nexport interface CompleteKeyExchangeOtkMutation {\n completeKeyExchangeOtk: {\n keyExchange: KeyExchangeFieldsResult;\n userSharedKey: UserSharedKeyFieldsResult;\n tp: {\n id: ID;\n user: {\n config: unknown;\n };\n };\n };\n}\nexport const CompleteKeyExchangeOtkMutation = gqlTyped<CompleteKeyExchangeOtkMutation>`\nmutation CompleteKeyExchangeOtkMutation(\n $input: CompleteKeyExchangeOtkInput!\n) {\n completeKeyExchangeOtk(input: $input) {\n keyExchange {\n ${KeyExchangeFields}\n }\n userSharedKey {\n ${UserSharedKeyFields}\n }\n tp {\n id\n user {\n config\n }\n }\n }\n}\n`;\n\nexport interface CurrentUserSharedKeyQuery2 {\n currentUserSharedKey: {\n userSharedKey: UserSharedKeyFieldsResult;\n };\n}\nexport const CurrentUserSharedKeyQuery2 = gqlTyped<CurrentUserSharedKeyQuery2>`\nquery CurrentUserSharedKeyQuery2(\n $username: String\n $userId: LrRelayIdInput\n) {\n currentUserSharedKey(\n username: $username\n userId: $userId\n ) {\n userSharedKey {\n ${UserSharedKeyFields}\n }\n }\n}\n`;\n","/* eslint-disable @typescript-eslint/no-explicit-any */\nimport { DateTime, UserDeleteNode, UserSharedKeyNode } from '../api/types';\nimport { IdKeyPair } from '../item/item.types';\nimport { PassKey } from '../key/key.types';\n\nexport enum FeatureAction {\n // Just the one for now\n ACCESS = 'access',\n}\n\nexport class Features {\n myVault: FeatureAction[];\n tpVault: FeatureAction[];\n shareVault: FeatureAction[];\n}\n\nexport class CurrentUserKey {\n passKey: PassKey;\n masterKey: { id: string };\n rootKey?: { id: string };\n pxk?: { id: string };\n sigPxk?: { id: string };\n}\n\nexport class ApiCurrentUser {\n id: string;\n username: string;\n currentUserKey: CurrentUserKey;\n userDelete: UserDeleteNode;\n features: Features;\n sessionEncryptionKey: string;\n dateJoined: DateTime;\n}\n\nexport class ApiContactCard {\n id: string;\n cipherData: string;\n key: {\n id: string;\n };\n}\n\nexport class ContactCardName {\n name: string;\n title?: string;\n firstName?: string;\n lastName?: string;\n\n constructor(input: any) {\n this.name = input.name;\n this.title = input.title;\n this.firstName = input.firstName;\n this.lastName = input.lastName;\n }\n}\n\nexport class ContactCardAddress {\n fullAddress: string;\n streetAddress: string;\n streetAddress2?: string;\n suburb: string;\n state: string;\n postcode: string;\n country: string;\n countryCode?: string;\n}\n\nexport class MainContactCardProperty<T> {\n value: T;\n hasMultiple: boolean;\n\n values?: { id: string; label: string; value: T }[];\n}\n\nexport class MainContactCardFields {\n name: MainContactCardProperty<ContactCardName>;\n email: MainContactCardProperty<string>;\n image: MainContactCardProperty<string>;\n phone: MainContactCardProperty<string>;\n address: MainContactCardProperty<ContactCardAddress>;\n}\n\nexport interface MainContactCard extends IdKeyPair {\n fields: MainContactCardFields;\n}\n\nexport class MainContactCardPlainFields {\n name: ContactCardName;\n}\n\nexport class TrustedPartyDetails {\n name: ContactCardName;\n email?: string;\n image?: string;\n phones?: { label: string; value: string }[];\n addresses?: {\n label: string;\n value: ContactCardAddress;\n }[];\n}\n\nexport class SharedTrustedPartyDetails extends TrustedPartyDetails {\n id: string;\n ownedKeyId: string;\n sharedKeyId: string;\n}\n\nexport class TPFeatures {\n sharedVault: SharedVaultFeature;\n}\n\nexport class SharedVaultFeature {\n hasAccess: boolean;\n}\n\nexport enum TrustedPartyType {\n User = 'user',\n Organisation = 'organisation',\n}\n\nexport class TrustedParty {\n id: string;\n type: TrustedPartyType;\n name: string;\n\n hasScenarios: boolean;\n hasSharedVault: boolean;\n details: TrustedPartyDetails;\n mySharedDetails: SharedTrustedPartyDetails;\n userSharedKey: UserSharedKeyNode;\n username: string;\n features: TPFeatures;\n}\n","import { Injectable } from '@angular/core';\nimport gql from 'graphql-tag';\nimport { LrApolloService } from '../api/lr-apollo.service';\nimport { JSONObject } from '../api/types';\nimport { EncryptionService } from '../encryption/encryption.service';\nimport { KeyGraphService } from '../key/key-graph.service';\nimport { KeyService } from '../key/key.service';\nimport { Key } from '../key/key.types';\nimport {\n ContactCardName,\n SharedTrustedPartyDetails,\n TrustedPartyDetails,\n} from '../profile/profile.types';\nimport { User } from '../user/user.types';\n\nexport const SharedContactCardFields = `\n id\n owner {\n id\n username\n }\n ownerKey {\n id\n }\n ownerCipherData\n receiver {\n id\n username\n }\n receiverKey {\n id\n }\n receiverCipherData\n sharedKey {\n id\n }\n sharedCipherData\n sharedCipherDataSig\n sharedCipherDataSigPxk {\n id\n }\n`;\n\nconst UpdateOwnedContactCard = gql`\nmutation UpdateOwnedContactCard(\n $input: UpdateOwnedContactCardInput!\n) {\n updateOwnedContactCard(\n input: $input\n ) {\n ownedContactCard {\n ${SharedContactCardFields}\n }\n }\n}`;\n\ninterface UpdateOwnedContactCard {\n updateOwnedContactCard: {\n ownedContactCard: SharedContactCard;\n };\n}\n\nexport interface SharedContactCard {\n id: string;\n owner: User;\n ownerKey: Key;\n ownerCipherData: string;\n receiver: User;\n receiverKey: Key;\n receiverCipherData: string;\n sharedKey: Key;\n sharedCipherData: string;\n // Decrypted\n plainOwnerCipherDataJson: JSONObject;\n plainReceiverCipherDataJson: JSONObject;\n plainSharedCipherDataJson: JSONObject;\n}\n\n@Injectable({\n providedIn: 'root',\n})\nexport class SharedContactCardService {\n constructor(\n private keyService: KeyService,\n private lrApollo: LrApolloService,\n private keyGraph: KeyGraphService,\n private encryptionService: EncryptionService\n ) {}\n\n async decryptSharedTrustedPartyDetails(\n cc: SharedContactCard\n ): Promise<SharedTrustedPartyDetails> {\n const details = await this.decryptTrustedPartyDetails(cc);\n\n return {\n id: cc.id,\n ownedKeyId: cc.ownerKey.id,\n sharedKeyId: cc.sharedKey.id,\n ...details,\n };\n }\n\n async decryptTrustedPartyDetails(\n cc: SharedContactCard\n ): Promise<TrustedPartyDetails> {\n if (cc && cc.sharedKey && cc.sharedCipherData) {\n try {\n return await this.encryptionService.decrypt(\n await this.keyGraph.getJwkKey(cc.sharedKey.id),\n cc.sharedCipherData\n );\n } catch (e) {\n console.error('Cannot decrypt trusted party details', e);\n }\n }\n return null;\n }\n\n async updateMySharedContactCard(\n id: string,\n ownedKeyId: string,\n sharedKeyId: string,\n contactCard: TrustedPartyDetails\n ): Promise<void> {\n const ownerKey = await this.keyGraph.getKey(ownedKeyId);\n const sharedKey = await this.keyGraph.getKey(sharedKeyId);\n const sigPxk = this.keyService.currentSigPxk;\n\n const sharedCipherData = await this.encryptionService.encrypt(\n sharedKey.jwk,\n contactCard\n );\n const sharedCipherDataSig = JSON.stringify(\n await this.encryptionService.sign(sigPxk.jwk, sharedCipherData)\n );\n\n const ownerPlainData = {\n name: new ContactCardName(contactCard.name),\n };\n const ownerPlainDataSig = JSON.stringify(\n await this.encryptionService.sign(sigPxk.jwk, ownerPlainData)\n );\n\n await this.lrApollo.mutate<UpdateOwnedContactCard>({\n mutation: UpdateOwnedContactCard,\n variables: {\n input: {\n id,\n ownerCipherData: '',\n ownerKeyId: ownerKey.id,\n sharedCipherDataSig,\n sharedKeyId: sharedKey.id,\n sigPxkId: sigPxk.id,\n ownerPlainDataSig,\n },\n },\n });\n }\n}\n","/* eslint-disable @typescript-eslint/no-explicit-any */\nimport gql from 'graphql-tag';\nimport { Connection, ContactCardNode, TpNode } from '../api/types';\nimport {\n KeyExchangeFields,\n UserSharedKeyFields,\n} from '../key-exchange/key-exchange.gql';\nimport { HasKeyGraph } from '../key/key.types';\nimport { SharedContactCardFields } from '../shared-contact-card/shared-contact-card.service';\nimport { gqlTyped } from '../_common/ast';\nimport { KeyGraphFragment } from '../_common/queries.gql';\nimport { HasEdges } from './../_common/types';\nimport { ApiContactCard, ApiCurrentUser } from './profile.types';\n\nexport const TrustedPartyProperties = `\n id\n user {\n id\n username\n }\n other{\n id\n username,\n features {\n shareVault\n }\n }\n sharedContactCard {\n ${SharedContactCardFields}\n }\n myContactCard {\n ${SharedContactCardFields}\n }\n sharedScenarios {\n edges {\n node {\n id\n }\n }\n }\n theirItems {\n directories {\n edges {\n node {\n id\n }\n }\n }\n }\n currentUserSharedKey {\n userSharedKey {\n keyExchange {\n ${KeyExchangeFields}\n }\n ${UserSharedKeyFields}\n }\n }`;\n\nexport interface CurrentUserQueryType extends HasKeyGraph {\n currentUser: ApiCurrentUser;\n contactCards: HasEdges<ApiContactCard>;\n userPlans: any[];\n}\n\nexport const CurrentUserQuery = gql`\n query {\n currentUser {\n id\n username\n currentUserKey {\n passKey {\n id\n passKeyParams\n passIdpParams\n wrappedPassIdpVerifierPrk\n created\n }\n masterKey {\n id\n }\n rootKey {\n id\n }\n pxk {\n id\n }\n sigPxk {\n id\n }\n }\n userDelete {\n id\n created\n state\n }\n features {\n myVault\n tpVault\n shareVault\n }\n sessionEncryptionKey\n dateJoined\n }\n userPlans {\n id\n stripe {\n subscriptionId\n }\n plan {\n name\n data\n state\n }\n periodEnd\n }\n contactCards(orderBy: \"created\") {\n edges {\n node {\n id\n key {\n id\n }\n cipherData\n plainData\n }\n }\n }\n keyGraph {\n ...KeyGraphFragment\n }\n }\n ${KeyGraphFragment}\n`;\n\nexport const CreateContactCardMutation = gql`\n mutation CreateContactCardMutation($input: CreateContactCardInput!) {\n createContactCard(input: $input) {\n contactCard {\n id\n key {\n id\n }\n cipherData\n }\n }\n }\n`;\n\nexport const UpdateContactCardMutation = gql`\n mutation UpdateContactCardMutation($input: UpdateContactCardInput!) {\n updateContactCard(input: $input) {\n contactCard {\n id\n key {\n id\n }\n cipherData\n }\n }\n }\n`;\n\nexport interface TrustedPartiesQueryResult {\n tps: Connection<TpNode>;\n}\nexport const TrustedPartiesQuery = gqlTyped<TrustedPartiesQueryResult>`\nquery TrustedPartiesQuery {\n tps {\n edges {\n node {\n ${TrustedPartyProperties}\n }\n }\n }\n}`;\n\nexport interface ContactCardsQueryResult {\n contactCards: Connection<ContactCardNode>;\n}\nexport const ContactCardsQuery = gqlTyped<ContactCardsQueryResult>`\nquery ContactCardsQuery {\n contactCards(orderBy: \"created\") {\n edges {\n node {\n id\n cipherData\n key {\n id\n }\n }\n }\n }\n}\n`;\n","/* eslint-disable @typescript-eslint/no-explicit-any */\nimport { HttpClient } from '@angular/common/http';\nimport { Inject, Injectable } from '@angular/core';\nimport { LrApolloService } from '../api/lr-apollo.service';\nimport {\n ContactCardListQuery,\n DeleteContactCardMutation,\n} from '../contact-card/contact-card.gql';\nimport { ContactCard } from '../contact-card/contact-card.service';\nimport { EncryptionService } from '../encryption/encryption.service';\nimport { KeyGraphService } from '../key/key-graph.service';\nimport { KeyMetaService } from '../key/key-meta.service';\nimport { KeyService } from '../key/key.service';\nimport { KcConfig, KC_CONFIG } from '../life-ready.config';\nimport {\n CreateContactCardMutation,\n CurrentUserQuery,\n CurrentUserQueryType,\n UpdateContactCardMutation,\n} from './profile.gql';\nimport {\n ApiContactCard,\n ApiCurrentUser,\n ContactCardName,\n MainContactCard,\n MainContactCardFields,\n MainContactCardPlainFields,\n} from './profile.types';\n\n@Injectable({\n providedIn: 'root',\n})\nexport class ProfileService {\n constructor(\n @Inject(KC_CONFIG) private config: KcConfig,\n private http: HttpClient,\n private lrApollo: LrApolloService,\n private keyService: KeyService,\n private keyMetaService: KeyMetaService,\n private keyGraph: KeyGraphService,\n private encryptionService: EncryptionService\n ) {}\n\n async getCurrentUser(): Promise<{\n currentUser: ApiCurrentUser;\n contactCard: ApiContactCard;\n }> {\n const { currentUser, contactCards } =\n await this.lrApollo.query<CurrentUserQueryType>({\n query: CurrentUserQuery,\n });\n\n const contactCard = contactCards.edges.map((x) => x.node)[0];\n\n return {\n currentUser,\n contactCard,\n };\n }\n\n async decryptContactCard(\n contactCard: ApiContactCard\n ): Promise<MainContactCard> {\n if (!contactCard) {\n return null;\n }\n\n const details = await this.keyGraph.decryptFromString<any>(\n contactCard.key.id,\n contactCard.cipherData\n );\n\n return {\n id: contactCard.id,\n keyId: contactCard.key.id,\n ...details,\n };\n }\n\n async updateDetails(\n id: string,\n keyId: string,\n fields: MainContactCardFields\n ): Promise<MainContactCard> {\n const res = await (id\n ? this.updateContactCard(id, keyId, fields)\n : this.createContactCard(fields));\n\n return {\n fields,\n id: res.id,\n keyId: res.key.id,\n };\n }\n\n private async prepareContactCardInput(\n contactCard: MainContactCardFields\n ): Promise<any> {\n const sigPxk = this.keyService.currentSigPxk;\n\n const publicDataSig = JSON.stringify(\n await this.encryptionService.sign(sigPxk.jwk, '')\n );\n const publicSearchableSig = JSON.stringify(\n await this.encryptionService.sign(sigPxk.jwk, '')\n );\n\n const plainDataJson: MainContactCardPlainFields = {\n // contactCard.name.value may have additional attributes such as the id of the contact card.\n // So we create a clean version. Otherwise it will fail server checks.\n name: new ContactCardName(contactCard.name.value),\n };\n const plainDataSig = JSON.stringify(\n await this.encryptionService.sign(sigPxk.jwk, plainDataJson)\n );\n\n return {\n sigPxkId: sigPxk.id,\n publicDataSig,\n publicSearchableSig,\n plainDataSig,\n };\n }\n\n private async createContactCard(\n contactCard: MainContactCardFields\n ): Promise<ApiContactCard> {\n const input = await this.prepareContactCardInput(contactCard);\n\n const { rootKey, cipherMeta } = await this.keyMetaService.wrapContent(\n contactCard\n );\n\n const data = await this.lrApollo.mutate<{\n createContactCard: { contactCard: ApiContactCard };\n }>({\n mutation: CreateContactCardMutation,\n variables: {\n input: {\n ...input,\n cipherData: cipherMeta,\n wrappingKeyId: rootKey.wrappingKeyId,\n wrappedKey: rootKey.wrappedKey,\n default: true, // Use this contact card as default contact card.\n },\n },\n });\n return data.createContactCard.contactCard;\n }\n\n private async updateContactCard(\n id: string,\n keyId: string,\n contactCard: MainContactCardFields\n ): Promise<ApiContactCard> {\n const input = await this.prepareContactCardInput(contactCard);\n\n const cipherData = await this.keyGraph.encryptToString(keyId, contactCard);\n\n const data = await this.lrApollo.mutate<{\n updateContactCard: { contactCard: ApiContactCard };\n }>({\n mutation: UpdateContactCardMutation,\n variables: {\n input: {\n ...input,\n id,\n cipherData,\n },\n },\n });\n return data.updateContactCard.contactCard;\n }\n\n async decryptContactCardEdges(edges): Promise<ContactCard[]> {\n return Promise.all(\n edges.map(async (edge: any) => {\n const cc = edge.node as ContactCard;\n return await this.decryptContactCard(cc);\n })\n );\n }\n\n async getContactCards(): Promise<ContactCard[]> {\n const data = await this.lrApollo.query<any>({\n query: ContactCardListQuery,\n });\n\n return await this.decryptContactCardEdges(data.contactCards.edges);\n }\n\n async deleteContactCard(id: string): Promise<string> {\n const data = await this.lrApollo.mutate<any>({\n mutation: DeleteContactCardMutation,\n variables: {\n input: {\n id,\n },\n },\n });\n\n return data.deleteContactCard.id;\n }\n\n async signOut(): Promise<void> {\n await this.http\n .post(`${this.config.authUrl}auth/sign-out/`, null, {\n withCredentials: true,\n responseType: 'text',\n })\n .toPromise();\n }\n}\n","import gql from 'graphql-tag';\n\nexport const PasswordChangeRequestMutation = gql`\n mutation {\n passwordChangeRequest(input: {}) {\n challenge\n }\n }\n`;\n\nexport const PasswordChangeMutation = gql`\n mutation PasswordChange($input: PasswordChangeInput!) {\n passwordChange(input: $input) {\n token\n newPassKey {\n id\n }\n }\n }\n`;\n\nexport const PasswordChangeConfigQuery = gql`\n query PasswordChangeConfigQuery {\n passwordChangeConfig {\n maxAuthAgeSeconds\n authTime\n serverTime\n }\n }\n`;\n","import { HttpClient } from '@angular/common/http';\nimport { Inject, Injectable } from '@angular/core';\nimport { CognitoUser } from '@aws-amplify/auth';\nimport { AuthClass } from '@aws-amplify/auth/lib-esm/Auth';\nimport * as moment_ from 'moment';\nimport { Duration } from 'moment';\nimport { JWK, JWS } from 'node-jose';\nimport { JSONObject } from '../api/types';\nimport { PassKeyBundle } from '../auth/auth.types';\nimport { EncryptionService } from '../encryption/encryption.service';\nimport { KeyFactoryService as KFS } from '../key/key-factory.service';\nimport { KeyGraphService } from '../key/key-graph.service';\nimport { httpOptions, KcConfig, KC_CONFIG } from '../life-ready.config';\nimport { ProfileService } from '../profile/profile.service';\nimport { ApiCurrentUser } from '../profile/profile.types';\nimport { WebCryptoService } from '../web-crypto/web-crypto.service';\nimport { KcAuthException } from '../_common/exceptions';\nimport { LrApolloService } from './../api/lr-apollo.service';\nimport {\n PasswordChangeConfigQuery,\n PasswordChangeMutation,\n PasswordChangeRequestMutation,\n} from './password.gql';\n\n// Ref: https://stackoverflow.com/questions/59735280/angular-8-moment-error-cannot-call-a-namespace-moment\nconst moment = moment_;\n\ninterface PasswordChangeRequestMutation {\n passwordChangeRequest: {\n challenge: {\n serverNonce: string;\n };\n };\n}\n\ninterface PasswordChangeMutation {\n passwordChange: {\n token: string;\n newPassKey: {\n id: string;\n };\n };\n}\n\nexport interface PasswordChangeConfig {\n maxAuthAgeSeconds: number;\n authTime: string | Date;\n serverTime: string | Date;\n}\n\nexport class PasswordCheck {\n length?: number;\n timeToCrack?: Duration;\n passwordExposed?: number;\n}\n\n@Injectable({\n providedIn: 'root',\n})\nexport class PasswordService {\n private readonly CLIENT_NONCE_LENGTH = 32;\n\n constructor(\n @Inject(KC_CONFIG) private config: KcConfig,\n private http: HttpClient,\n private apollo: LrApolloService,\n private auth: AuthClass,\n private profileService: ProfileService,\n private keyFactory: KFS,\n private encryptionService: EncryptionService,\n private keyGraph: KeyGraphService,\n private webCryptoService: WebCryptoService\n ) {}\n\n public async checkPassword(plainPassword: string): Promise<PasswordCheck> {\n const { years } = this.passwordStrength(plainPassword);\n\n return {\n length: plainPassword.length,\n timeToCrack: moment.duration({ years }),\n passwordExposed: await this.getExposureCount(plainPassword),\n };\n }\n\n public async getExposureCount(plainPassword: string): Promise<number> {\n const sha1Password = await this.webCryptoService.stringDigest(\n 'SHA-1',\n plainPassword\n );\n const first5sha1 = sha1Password.substring(0, 5);\n\n const response = await this.http\n .get(`https://api.pwnedpasswords.com/range/${first5sha1}`, {\n responseType: 'text',\n })\n .toPromise();\n\n const results = new RegExp(\n `^(?:${sha1Password.substring(5)}:)(?<count>\\\\d+)$`,\n 'im'\n ).exec(response);\n\n if (results) {\n return +results.groups.count;\n }\n return 0;\n }\n\n public getPassIdpString(passIdp: JWK.Key) {\n return (passIdp.toJSON(true) as JSONObject).k;\n }\n\n public async createPassKeyBundle(\n password: CryptoKey\n ): Promise<PassKeyBundle> {\n const passIdpParams = await this.keyFactory.createPassIdpParams();\n const passIdp = (\n await this.keyFactory.derivePassIdp({\n password,\n ...passIdpParams,\n })\n ).jwk;\n\n const passKeyParams = await this.keyFactory.createPassKeyParams();\n const passKey = (\n await this.keyFactory.derivePassKey({\n password,\n ...passKeyParams,\n })\n ).jwk;\n\n const passIdpVerifier = await this.keyFactory.createPkcSignKey();\n\n const wrappedPassIdpVerifierPrk = await this.encryptionService.encrypt(\n passKey,\n passIdpVerifier.toJSON(true)\n );\n\n // There are two formats that the private key can be represented in JWK:\n // https://tools.ietf.org/html/rfc8017#page-9\n // The second form is an optimization:\n // https://crypto.stackexchange.com/questions/19413/what-are-dp-and-dq-in-encryption-by-rsa-in-c\n\n return {\n passKeyParams,\n passKey,\n passIdpParams,\n passIdp,\n passIdpVerifier,\n wrappedPassIdpVerifierPrk,\n };\n }\n\n /**\n * We need to allow for interruption of the process at any point. Each API call can be considered\n * atomic and either succeeds or fails.\n *\n * The LR server APIs use semaphore tokens for locking critical operations, so concurrent calls will\n * fail.\n *\n * We assume the worst case for IdP API calls. So we use the semaphore token from LR to prevent\n * concurrent calls to IdP APIs, but we have to assume that the IdP API calls will either succeed or\n * fail within a reasonable amount of time.\n *\n * Each location where the server state changes can be a potential point of interruption.\n * Potential points of interruption are marked with: --Potential Failure Point--\n *\n * Places for timeout:\n * - Login age too old at call to: verifyPassword()\n * - Login age too old at call to: changePasswordMutation()\n * - Semaphore token expires at call to: changePasswordComplete()\n *\n * Tests:\n * - Potential Failure Point 1: should be able to restart the process, user remains signed in.\n * - Potential Failure Point 2: should enter recovery flow\n * - Potential Failure Point 3: should enter recovery flow\n * - Potential Failure Point 4: should enter recovery flow\n *\n */\n\n public async isLoginRequired(): Promise<boolean> {\n const changePasswordConfig = await this.getChangePasswordConfig();\n const authTime = moment(changePasswordConfig.authTime);\n const serverTime = moment(changePasswordConfig.serverTime);\n const duration = moment.duration(serverTime.diff(authTime));\n const seconds = duration.asSeconds();\n if (seconds > changePasswordConfig.maxAuthAgeSeconds) {\n return true;\n } else {\n return false;\n }\n }\n\n public async changePassword(password: CryptoKey, newPassword: CryptoKey) {\n const cognitoUser: CognitoUser = await this.auth.currentAuthenticatedUser();\n\n // Not checking that passwords are different. It makes it easier to test.\n const { currentUser } = await this.profileService.getCurrentUser();\n\n const { passIdp, signedChallenge } = await this.verifyPassword(\n password,\n currentUser\n );\n\n // --Potential Failure Point 1--\n // verifyPassword() asks for a current password challenge hence changes server state.\n // Place break points here to test the failure scenarios.\n\n // Generate the new passIdp\n const newPassKey = await this.createPassKeyBundle(newPassword);\n\n // Re-encrypt master key with new key\n const masterKey = await this.keyGraph.getKey(\n currentUser.currentUserKey.masterKey.id\n );\n const newWrappedMasterKey = await this.encryptionService.encrypt(\n newPassKey.passKey,\n masterKey.jwk.toJSON(true)\n );\n\n // If the IdP change password failed, we need to go into recovery mode by forcing\n // a login. We can't logout the user just yet since the IdP password change needs\n // the user to be logged in. We _can_ removed any persisted session values for the IdP\n // but that seems like too much trouble.\n\n const { token } = await this.changePasswordMutation(\n signedChallenge,\n currentUser.currentUserKey.masterKey.id,\n newWrappedMasterKey,\n newPassKey\n );\n\n // --Potential Failure Point 2--\n // changePasswordMutation() uploads new keys and obtains a semaphore lock to prevent any other\n // clients from performing IdP password change.\n\n // Now we can do the IdP password change.\n // todo: Add this back in\n await this.auth.changePassword(\n cognitoUser,\n this.getPassIdpString(passIdp),\n this.getPassIdpString(newPassKey.passIdp)\n );\n\n // --Potential Failure Point 3--\n // IdP password change\n\n // Note that changePassword() could throw an exception for a number of reason. It could throw\n // a network timeout for example. But we don't know if it's the response that timed out and\n // the idp password change was actually carried out. So we have to be extra conservative and\n // only act on a clear success. Otherwise we go into recover mode.\n await this.changePasswordComplete({ useNewPassword: true, token });\n }\n\n public async changePasswordComplete(options: {\n useNewPassword: boolean;\n token?: string;\n }) {\n const { useNewPassword, token } = options;\n return this.http\n .post(\n `${this.config.authUrl}users/password-change-complete/`,\n {\n use_new_password: useNewPassword,\n ...(token && { token }),\n },\n await httpOptions(this.auth, this.config)\n )\n .toPromise();\n }\n\n private async getVerifierPrK(\n passKey: JWK.Key,\n wrappedPrK: Record<string, JSONObject>\n ): Promise<JWK.Key> {\n try {\n const prkJson = await this.encryptionService.decrypt(passKey, wrappedPrK);\n return KFS.asKey(prkJson);\n } catch (error) {\n throw new KcAuthException('Wrong current password');\n }\n }\n\n private async verifyPassword(\n password: CryptoKey,\n currentUser: ApiCurrentUser\n ): Promise<{ passIdp: JWK.Key; signedChallenge: JWS.CreateSignResult }> {\n // Get information from the server to prepare for password change.\n const passwordRequest =\n await this.apollo.mutate<PasswordChangeRequestMutation>({\n mutation: PasswordChangeRequestMutation,\n variables: {},\n });\n\n // Get the old passKey so we can decrypt the old password verifier\n const passKeyResult = await this.keyFactory.derivePassKey({\n password,\n ...currentUser.currentUserKey.passKey.passKeyParams,\n });\n\n const verifierPrK = await this.getVerifierPrK(\n passKeyResult.jwk,\n currentUser.currentUserKey.passKey.wrappedPassIdpVerifierPrk\n );\n\n // Sign the server challenge to prove to the server we can decrypt the password verifier.\n // Generate\n const clientNonce = this.keyFactory.randomString(this.CLIENT_NONCE_LENGTH);\n\n const signedChallenge = await this.encryptionService.sign(verifierPrK, {\n serverNonce: passwordRequest.passwordChangeRequest.challenge.serverNonce,\n clientNonce,\n });\n\n const passIdpResult = await this.keyFactory.derivePassIdp({\n password,\n ...currentUser.currentUserKey.passKey.passIdpParams,\n });\n\n return {\n passIdp: passIdpResult.jwk,\n signedChallenge,\n };\n }\n\n private async changePasswordMutation(\n signedChallenge: JWS.CreateSignResult,\n masterKeyId: string,\n newWrappedMasterKey: Record<string, JSONObject>,\n passKeyBundle: PassKeyBundle\n ): Promise<{ token: string; newPassKeyId: string }> {\n const response = await this.apollo.mutate<PasswordChangeMutation>({\n mutation: PasswordChangeMutation,\n variables: {\n input: {\n signedChallenge: JSON.stringify(signedChallenge),\n masterKeyId,\n newWrappedMasterKey: JSON.stringify(newWrappedMasterKey),\n newPassKey: {\n passIdpParams: JSON.stringify(passKeyBundle.passIdpParams),\n passIdpVerifierPbk: JSON.stringify(\n passKeyBundle.passIdpVerifier.toJSON()\n ),\n wrappedPassIdpVerifierPrk: JSON.stringify(\n passKeyBundle.wrappedPassIdpVerifierPrk\n ),\n passKeyParams: JSON.stringify(passKeyBundle.passKeyParams),\n },\n },\n },\n });\n return {\n token: response.passwordChange.token,\n newPassKeyId: response.passwordChange.newPassKey.id,\n };\n }\n\n async getChangePasswordConfig(): Promise<PasswordChangeConfig> {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const res = await this.apollo.query<any>({\n query: PasswordChangeConfigQuery,\n });\n\n const ret = res.passwordChangeConfig as PasswordChangeConfig;\n\n ret.authTime = new Date(ret.authTime);\n ret.serverTime = new Date(ret.serverTime);\n return ret;\n }\n\n public passwordStrength(password): { years: number; bits: number } {\n const upper = /[A-Z]/g;\n const lower = /[a-z]/g;\n const digit = /[0-9]/g;\n\n const upperChoices = 26;\n const lowerChoices = 26;\n const digitChoices = 10;\n const specialChoices = 30; // /[!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~]/g\n\n function instanceCount(str, re) {\n return ((str || '').match(re) || []).length;\n }\n\n const uppers = instanceCount(password, upper);\n const lowers = instanceCount(password, lower);\n const digits = instanceCount(password, digit);\n const specials = password.length - uppers - lowers - digits;\n\n let choices = 0;\n if (uppers) {\n choices += upperChoices;\n }\n if (lowers) {\n choices += lowerChoices;\n }\n if (digits) {\n choices += digitChoices;\n }\n if (specials) {\n choices += specialChoices;\n }\n\n if (password.length === 0) {\n return {\n years: 0,\n // bits of entropy\n bits: 0,\n };\n }\n\n const permutations = Math.pow(choices, password.length);\n\n const years =\n (54000 * permutations) /\n Math.pow(upperChoices + lowerChoices + digitChoices, 12);\n return {\n years,\n // bits of entropy\n bits: Math.round(Math.log2(permutations)),\n };\n }\n}\n","export const TP_PASSWORD_RESET_CLIENT_NONCE_LENGTH = 32;\nexport const TP_PASSWORD_RESET_SLIP39_PASSPHRASE = 'lifeready';\nexport const TP_PASSWORD_RESET_USERNAME_SUFFIX = '.tp_password_reset';\n","import { Injectable } from '@angular/core';\nimport { Slip39, Slip39Helper } from 'slip39';\n\nexport class SecretShare {\n constructor(\n public assembly: number = 0,\n public subAssembly: number = 0,\n public mnemonics: string = ''\n ) {}\n}\n\nexport class SubAssembly {\n constructor(\n public index: number,\n public threshold: number = 0,\n public size: number = 0\n ) {\n this.clearShares();\n }\n\n shares: SecretShare[];\n\n public clearShares() {\n this.shares = [];\n }\n\n public addShare(share: SecretShare) {\n this.shares.push(share);\n }\n}\n\nexport class Assembly {\n constructor(public threshold: number = 0) {\n this.clearSubAssemblies();\n }\n\n subAssemblies: SubAssembly[];\n\n public size() {\n return this.subAssemblies.length;\n }\n\n public clearSubAssemblies() {\n this.subAssemblies = [];\n }\n\n public addSubAssembly(subAssembly: SubAssembly) {\n this.subAssemblies.push(subAssembly);\n }\n}\n\nexport class SubQuorum {\n shares: string[];\n\n constructor(public subAssemblyIndex: number) {\n this.clearShares();\n }\n\n public clearShares() {\n this.shares = [];\n }\n\n public addShare(share: string) {\n this.shares.push(share);\n }\n}\n\nexport class Quorum {\n subQuora: SubQuorum[];\n\n constructor() {\n this.clearSubQuora();\n }\n\n public clearSubQuora() {\n this.subQuora = [];\n }\n\n public addSubQuorum(subQuorum: SubQuorum) {\n this.subQuora.push(subQuorum);\n }\n\n public serialiseShares() {\n let shares = [];\n\n this.subQuora.forEach((subQuorum) => {\n shares = shares.concat(subQuorum.shares);\n });\n\n return shares;\n }\n}\n\n@Injectable({\n providedIn: 'root',\n})\nexport class Slip39Service {\n public async generateShares(secret, passphrase: string, assembly: Assembly) {\n // Hex-encode secret.\n let ems = btoa(secret);\n ems = Slip39Helper.slip39EncodeHex(ems);\n\n // Construct group specifications\n const groups = [];\n\n for (const sa of assembly.subAssemblies) {\n groups.push([sa.threshold, sa.size]);\n }\n\n // Split!\n const slip = await Slip39.fromArray(ems, {\n passphrase,\n threshold: assembly.threshold,\n groups,\n title: '',\n });\n\n // Extract shares\n assembly.subAssemblies.forEach((sa, isa) => {\n // Remove any existing shares\n sa.clearShares();\n\n for (let im = 0; im < sa.size; im++) {\n // Construct the path to the share, formatted as \"r/<subassembly index>/<member index>\"\n // with <subassembly index> and <member index> being two-digit, zero-padded integers.\n const path =\n 'r/' +\n isa.toString().padStart(2, '0') +\n '/' +\n im.toString().padStart(2, '0');\n const mnemonics = slip.fromPath(path).mnemonics[0];\n const share = new SecretShare(isa, im, mnemonics);\n\n sa.addShare(share);\n }\n });\n }\n\n // Remove all redundant shares. i.e. keep only enough members and groups to satisfy the thresholds.\n private minimalSet(mnemonics: string[]): string[] {\n // Decode the mnemonics and sort then into groups.\n let groupThresh = null;\n const groups = new Map();\n for (const mnemonic of mnemonics) {\n const decoded = Slip39Helper.decodeMnemonic(mnemonic);\n\n if (groupThresh && groupThresh !== decoded.groupThreshold) {\n throw new Error('groupThreshold is different in mnemonics');\n }\n\n groupThresh = decoded.groupThreshold;\n\n // Note that Slip39.recoverSecret() will do all the error checking again. So it's not critical\n // that we error check here. So we just optimistically assume it's all good.\n let g = groups.get(decoded.groupIndex);\n if (g == null) {\n g = {\n memberThreshold: decoded.memberThreshold,\n members: [],\n };\n groups.set(decoded.groupIndex, g);\n }\n\n g.members.push({\n mnemonic,\n decoded,\n });\n }\n\n // Keep the minimum set of groups that meet threshold.\n const mnemonicsMinSet = [];\n let groupCount = 0;\n for (const g of groups.values()) {\n // Keep only groups that meet threshold\n if (g.members.length < g.memberThreshold) {\n continue;\n }\n\n // Keep minimum number of approvals needed for group\n g.members.slice(0, g.memberThreshold).forEach((member) => {\n mnemonicsMinSet.push(member.mnemonic);\n });\n\n ++groupCount;\n if (groupCount >= groupThresh) {\n break;\n }\n }\n\n return mnemonicsMinSet;\n }\n\n public async recoverSecret(shares: string[], passphrase: string) {\n shares = this.minimalSet(shares);\n\n const recovered = await Slip39.recoverSecret(shares, passphrase);\n\n const secret = Slip39Helper.slip39DecodeHex(recovered);\n\n return atob(secret);\n }\n}\n","import { Connection, TpNode } from '../api/types';\nimport { gqlTyped } from '../_common/ast';\n\nexport interface TpsKeysQueryResult {\n tps: Connection<TpNode>;\n}\nexport const TpsKeysQuery = gqlTyped<TpsKeysQueryResult>`\nquery TpsKeysQuery($ids: [ID]) {\n tps(id_In: $ids) {\n edges {\n node {\n id\n currentUserSharedKey {\n userSharedKey {\n sharedKey {\n id\n }\n mkSharedKey {\n id\n }\n }\n }\n }\n }\n }\n}`;\n","import { Injector } from '@angular/core';\nimport { JWK } from 'node-jose';\nimport { LrGraphQLService } from '../api/lr-graphql';\nimport {\n Connection,\n JSONObject,\n mapEdges,\n TpAssemblyNode,\n TpNode,\n TpSubAssemblyNode,\n} from '../api/types';\nimport { EncryptionService } from '../encryption/encryption.service';\nimport { KeyFactoryService } from '../key/key-factory.service';\nimport { KeyGraphService } from '../key/key-graph.service';\nimport { KeyService } from '../key/key.service';\nimport { Key } from '../key/key.types';\nimport * as slip from '../slip39/slip39.service';\nimport {\n KcBadArgumentException,\n KcBadStateException,\n} from '../_common/exceptions';\nimport { TpsKeysQuery } from './tp-assembly.private.gql';\nimport {\n CreateTpAssemblyInput,\n CreateTpSubAssemblyInput,\n PartialAssemblyKey,\n TpAssemblyApproverInput,\n UpdateTpAssemblyInput,\n UpdateTpSubAssemblyInput,\n} from './tp-assembly.types';\n\nexport abstract class TpAssemblyController {\n abstract slip39Passphrase: string;\n\n protected keyFactory: KeyFactoryService;\n protected keyService: KeyService;\n protected encryptionService: EncryptionService;\n protected keyGraph: KeyGraphService;\n protected slip39Service: slip.Slip39Service;\n protected lrGraphQl: LrGraphQLService;\n\n constructor(injector: Injector) {\n this.keyFactory = injector.get(KeyFactoryService);\n this.keyService = injector.get(KeyService);\n this.encryptionService = injector.get(EncryptionService);\n this.keyGraph = injector.get(KeyGraphService);\n this.slip39Service = injector.get(slip.Slip39Service);\n this.lrGraphQl = injector.get(LrGraphQLService);\n }\n\n abstract getTpWrappingKeyId(tp: TpNode): string;\n\n async recoverAssemblyKey(partials: PartialAssemblyKey[]) {\n // Every receiverPbkCipher should contain this and they should all be the same.\n let assemblyKeyParams: Record<string, JSONObject>;\n\n const shares = partials.map((partial) => {\n if (assemblyKeyParams) {\n if (\n JSON.stringify(assemblyKeyParams) !==\n JSON.stringify(partial.assemblyKeyParams)\n ) {\n throw new KcBadStateException(\n 'The assembly key parameters are different between the approvals.'\n );\n }\n } else {\n assemblyKeyParams = partial.assemblyKeyParams;\n }\n return partial.slip39.share.mnemonics;\n });\n\n const rawAssemblyKey = await this.slip39Service.recoverSecret(\n shares,\n this.slip39Passphrase\n );\n\n return await KeyFactoryService.asKey({\n ...assemblyKeyParams,\n k: rawAssemblyKey,\n });\n }\n\n protected async prepareTpWrappingKey(\n tp: TpAssemblyApproverInput\n ): Promise<Key> {\n return this.keyGraph.getKey(tp.wrappingKeyId);\n }\n\n protected async prepareAssembly({\n subjectKey,\n rootKey,\n }: {\n subjectKey: JWK.Key;\n rootKey: JWK.Key;\n }) {\n const assemblyKey = await this.keyFactory.createKey();\n\n const { k: rawAssemblyKey, ...assemblyKeyParams } = assemblyKey.toJSON(\n true\n ) as JSONObject;\n const assemblyKeyVerifierPrk = await this.keyFactory.createPkcSignKey();\n const wrappedAssemblyKeyVerifierPrk =\n await this.encryptionService.encryptToString(\n assemblyKey,\n assemblyKeyVerifierPrk.toJSON(true)\n );\n const assemblyKeyVerifierPbk = JSON.stringify(\n assemblyKeyVerifierPrk.toJSON()\n );\n\n const subjectKeyWrappedAssemblyKey =\n await this.encryptionService.encryptToString(\n subjectKey,\n assemblyKey.toJSON(true)\n );\n\n // Encrypt the rootKey with the assemblyKey\n const assemblyCipherData = await this.encryptionService.encryptToString(\n assemblyKey,\n {\n rootKey: rootKey.toJSON(true),\n }\n );\n\n return {\n assemblyKey,\n rawAssemblyKey,\n assemblyKeyParams,\n subjectKeyWrappedAssemblyKey,\n assemblyCipherData,\n assemblyKeyVerifierPbk,\n wrappedAssemblyKeyVerifierPrk,\n };\n }\n\n protected async prepareCreateSubAssemblies({\n input,\n subjectKey,\n slipSubAssemblies,\n assemblyKeyParams,\n }: {\n input: CreateTpSubAssemblyInput[];\n subjectKey: JWK.Key;\n slipSubAssemblies: slip.SubAssembly[];\n assemblyKeyParams; // TODO type this\n }) {\n return Promise.all(\n input.map(async (sa, saIndex) => {\n const subjectCipherData = await this.encryptionService.encryptToString(\n subjectKey,\n sa.subjectCipherDataClearJson || ''\n );\n\n const createApprovers = await Promise.all(\n sa.approverTps.map(async (approverTp, approverIndex) =>\n this.prepareApprover({\n tp: approverTp,\n approverIndex,\n slipSubAssembly: slipSubAssemblies[saIndex],\n assemblyKeyParams,\n subjectKey,\n })\n )\n );\n\n return {\n singleReject: sa.singleReject,\n quorum: sa.quorum,\n subjectCipherData,\n createApprovers,\n };\n })\n );\n }\n\n protected async prepareUpdateSubAssemblies({\n input,\n subjectKey,\n slipSubAssemblies,\n assemblyKeyParams,\n subAssemblies,\n }: {\n input: UpdateTpSubAssemblyInput[];\n subjectKey: JWK.Key;\n slipSubAssemblies: slip.SubAssembly[];\n assemblyKeyParams; // TODO type this\n subAssemblies: Connection<TpSubAssemblyNode>;\n }) {\n if (slipSubAssemblies.length !== input.length) {\n throw new KcBadArgumentException(\n 'The slipSubAssemblies must be the same length as the input'\n );\n }\n\n return Promise.all(\n input.map(async (sa, saIndex) => {\n const subjectCipherData = await this.encryptionService.encryptToString(\n subjectKey,\n sa.subjectCipherDataClearJson || ''\n );\n\n // Get the existing sub-assembly\n const existingSa = subAssemblies.edges.find(\n (edge) => edge.node.id === sa.id\n ).node;\n\n // Get approvers that do not exist yet\n const createApprovers = [];\n const updateApprovers = [];\n\n sa.approverTps.forEach((tp) => {\n const approver = existingSa.approvers.edges.find(\n (edge) => edge.node.tp.id === tp.tpId\n )?.node;\n if (approver) {\n updateApprovers.push({\n tp,\n approverId: approver.id,\n });\n } else {\n createApprovers.push({\n tp,\n });\n }\n });\n\n const slipSubAssembly = slipSubAssemblies[saIndex];\n\n return {\n subAssemblyId: sa.id,\n singleReject: sa.singleReject,\n quorum: sa.quorum,\n subjectCipherData,\n createApprovers: await Promise.all(\n createApprovers.map(async ({ tp }, approverIndex) =>\n this.prepareApprover({\n tp,\n approverIndex,\n slipSubAssembly,\n assemblyKeyParams,\n subjectKey,\n })\n )\n ),\n updateApprovers: await Promise.all(\n updateApprovers.map(async ({ tp, approverId }, approverIndex) =>\n this.prepareApprover({\n approverId,\n tp,\n approverIndex: approverIndex + createApprovers.length,\n slipSubAssembly,\n assemblyKeyParams,\n subjectKey,\n })\n )\n ),\n };\n })\n );\n }\n\n private fillWrappingKeyId(input: CreateTpSubAssemblyInput[], tps: TpNode[]) {\n // Fill in wrappingKeyId if not present\n input.forEach((sa) => {\n sa.approverTps.forEach((approver) => {\n if (!approver.wrappingKeyId) {\n const tp = tps.find((x) => x.id === approver.tpId);\n approver.wrappingKeyId = this.getTpWrappingKeyId(tp);\n }\n });\n });\n }\n\n private getInputApprovers(input: CreateTpSubAssemblyInput[]) {\n const tpIds: string[] = [];\n input.forEach((sa) => {\n sa.approverTps.forEach((approver) => {\n tpIds.push(approver.tpId);\n });\n });\n return tpIds;\n }\n\n public async prepareCreate(input: CreateTpAssemblyInput) {\n const rootKey = this.keyService.currentRootKey;\n const subjectKey = await this.keyFactory.createKey();\n const rootKeyWrappedSubjectKey = await this.keyGraph.wrapKey(\n rootKey,\n subjectKey\n );\n\n const { assemblyKey, rawAssemblyKey, assemblyKeyParams, ...assemblyInput } =\n await this.prepareAssembly({\n rootKey: rootKey.jwk,\n subjectKey,\n });\n\n const slipAssembly = await this.prepareSlip39(\n input.createSubAssemblies,\n input.quorum,\n rawAssemblyKey\n );\n\n const tpIds = this.getInputApprovers(input.createSubAssemblies);\n\n // This should contain all the TPs that we need to update the assembly.\n const tps = mapEdges(\n (\n await this.lrGraphQl.query({\n query: TpsKeysQuery,\n variables: {\n ids: tpIds,\n },\n })\n ).tps\n );\n\n // Fill in wrappingKeyId if not present\n this.fillWrappingKeyId(input.createSubAssemblies, tps);\n\n const createSubAssemblies = await this.prepareCreateSubAssemblies({\n input: input.createSubAssemblies,\n assemblyKeyParams,\n slipSubAssemblies: slipAssembly.subAssemblies,\n subjectKey,\n });\n\n const subjectCipherData = await this.encryptionService.encryptToString(\n subjectKey,\n input.subjectCipherDataClearJson || ''\n );\n\n return {\n assemblyKey,\n mutationInput: {\n ...assemblyInput,\n singleReject: input.singleReject,\n quorum: input.quorum,\n subjectCipherData,\n createSubAssemblies,\n rootKeyId: rootKey.id,\n rootKeyWrappedSubjectKey,\n },\n };\n }\n\n private getAssemblyApprovers(assembly: TpAssemblyNode) {\n const tpIds: string[] = [];\n\n // Find all TPs that belong to sub-assemblies\n mapEdges(assembly.subAssemblies).map((sa) => {\n mapEdges(sa.approvers).forEach((approver) => tpIds.push(approver.tp.id));\n });\n\n return tpIds;\n }\n\n public async prepareUpdate(\n input: UpdateTpAssemblyInput,\n assembly: TpAssemblyNode // TODO type this to only what we need.\n ) {\n input = {\n createSubAssemblies: [],\n ...input,\n };\n\n const createSubAssembliesInput = input.createSubAssemblies || [];\n const updateSubAssembliesInput = input.updateSubAssemblies || [];\n const deleteSubAssembliesInput = input.deleteSubAssemblies || [];\n\n // Must have at least one.\n if (\n createSubAssembliesInput.length === 0 &&\n updateSubAssembliesInput.length === 0 &&\n deleteSubAssembliesInput.length === 0\n ) {\n throw new KcBadArgumentException(\n 'Must specify at least one of: [createSubAssemblies, updateSubAssemblies, deleteSubAssemblies]'\n );\n }\n\n const rootKey = this.keyService.currentRootKey;\n const subjectKey = await this.keyGraph.getKey(assembly.subjectKey.id);\n\n const { assemblyKey, rawAssemblyKey, assemblyKeyParams, ...assemblyInput } =\n await this.prepareAssembly({\n rootKey: rootKey.jwk,\n subjectKey: subjectKey.jwk,\n });\n\n // Find all the TPs that we need, duplicates are no problem.\n // Existing approvers\n const tpIds = this.getAssemblyApprovers(assembly).concat(\n this.getInputApprovers(createSubAssembliesInput),\n this.getInputApprovers(updateSubAssembliesInput)\n );\n\n // This should contain all the TPs that we need to update the assembly.\n const tps = mapEdges(\n (\n await this.lrGraphQl.query({\n query: TpsKeysQuery,\n variables: {\n ids: tpIds,\n },\n })\n ).tps\n );\n\n // Auto fill the updateSubAssemblies with existing sub assemblies if they are not\n // explicitly deleted.\n mapEdges(assembly.subAssemblies).forEach((existing) => {\n // Deleting existing, don't include it\n if (deleteSubAssembliesInput.includes(existing.id)) {\n return;\n }\n\n // Update already specified in the input\n if (updateSubAssembliesInput.some((sa) => sa.id === existing.id)) {\n return;\n }\n\n const approverTps: TpAssemblyApproverInput[] = mapEdges(\n existing.approvers\n ).map((approver) => {\n return {\n tpId: approver.tp.id,\n sharedCipherDataClearJson: approver.sharedCipherDataClearJson,\n sharedCipherApprovalDataClearJson:\n approver.sharedCipherApprovalDataClearJson,\n };\n });\n\n updateSubAssembliesInput.push({\n id: existing.id,\n quorum: existing.quorum,\n singleReject: existing.singleReject,\n approverTps,\n subjectCipherDataClearJson: existing.subjectCipherDataClearJson,\n });\n });\n\n // Fill in wrappingKeyId if not present\n this.fillWrappingKeyId(createSubAssembliesInput, tps);\n this.fillWrappingKeyId(updateSubAssembliesInput, tps);\n\n let slipAssembly;\n try {\n slipAssembly = await this.prepareSlip39(\n (createSubAssembliesInput || []).concat(updateSubAssembliesInput || []),\n input.quorum,\n rawAssemblyKey\n );\n } catch (error) {\n // TODO this sometimes happens. Maybe missing await.\n console.log('Error while creating slip assembly', error);\n }\n\n const common = {\n assemblyKeyParams,\n subjectKey: subjectKey.jwk,\n };\n\n const createSubAssemblies = await this.prepareCreateSubAssemblies({\n ...common,\n input: createSubAssembliesInput,\n // Need to match the slip sub assemblies to the input\n slipSubAssemblies: slipAssembly.subAssemblies.slice(\n 0,\n createSubAssembliesInput.length\n ),\n });\n\n const updateSubAssemblies = await this.prepareUpdateSubAssemblies({\n ...common,\n input: updateSubAssembliesInput,\n // Add an offset to the sub assemblies to skip the one that are created.\n slipSubAssemblies: slipAssembly.subAssemblies.slice(\n createSubAssembliesInput.length\n ),\n subAssemblies: assembly.subAssemblies,\n });\n\n const subjectCipherData = await this.encryptionService.encryptToString(\n subjectKey.jwk,\n input.subjectCipherDataClearJson ?? assembly.subjectCipherDataClearJson\n );\n\n return {\n assemblyKey,\n mutationInput: {\n ...assemblyInput,\n singleReject: input.singleReject,\n quorum: input.quorum,\n subjectCipherData,\n subjectKeyId: subjectKey.id,\n createSubAssemblies,\n updateSubAssemblies,\n },\n };\n }\n\n private async prepareApprover({\n approverId,\n tp,\n approverIndex,\n slipSubAssembly,\n assemblyKeyParams,\n subjectKey,\n }: {\n approverId?: string; // Given if updating existing approver\n tp: TpAssemblyApproverInput;\n approverIndex: number;\n slipSubAssembly: slip.SubAssembly;\n assemblyKeyParams: Record<string, JSONObject>;\n subjectKey: JWK.Key;\n }) {\n const tpWrappingKey = await this.prepareTpWrappingKey(tp);\n // shared key is rotated every time.\n const sharedKey = await this.keyFactory.createKey();\n\n // For TP to access shared_key\n const tpWrappedSharedKey = await this.encryptionService.encryptToString(\n tpWrappingKey.jwk,\n sharedKey.toJSON(true)\n );\n // For subject to access shared_key\n const subjectKeyWrappedSharedKey =\n await this.encryptionService.encryptToString(\n subjectKey,\n sharedKey.toJSON(true)\n );\n\n // If quorum is 1, then using the same share for every member.\n const share =\n slipSubAssembly.threshold === 1\n ? slipSubAssembly.shares[0]\n : slipSubAssembly.shares[approverIndex];\n\n const partialAssemblyKey: PartialAssemblyKey = {\n slip39: {\n share,\n subAssembly: {\n quorum: slipSubAssembly.threshold,\n size: slipSubAssembly.size,\n },\n },\n assemblyKeyParams,\n };\n\n const sharedCipherData = await this.encryptionService.encryptToString(\n sharedKey,\n tp.sharedCipherDataClearJson || ''\n );\n\n const sharedCipherApprovalData =\n await this.encryptionService.encryptToString(\n sharedKey,\n tp.sharedCipherApprovalDataClearJson || ''\n );\n\n const sharedCipherPartialAssemblyKey =\n await this.encryptionService.encryptToString(\n sharedKey,\n partialAssemblyKey\n );\n\n return {\n tpWrappingKeyId: tpWrappingKey.id,\n tpWrappedSharedKey,\n subjectKeyWrappedSharedKey,\n sharedCipherData,\n sharedCipherApprovalData,\n sharedCipherPartialAssemblyKey,\n approverId: approverId || void 0, // If existing approver\n tpId: approverId ? void 0 : tp.tpId, // else adding new TP\n };\n }\n\n validateApprovers(approvers: TpNode[]): void {\n // Ensure all approvers have mkSharedKey.\n for (const tp of approvers) {\n if (!tp.currentUserSharedKey.userSharedKey.mkSharedKey) {\n const msg = `tp ${tp.other.username} does not have mkSharedKey`;\n console.log(msg);\n throw new KcBadArgumentException(msg);\n }\n }\n }\n\n // Prepare slip39\n protected async prepareSlip39(\n subAssemblies,\n assemblyQuorum: number,\n rawAssemblyKey: string\n ): Promise<slip.Assembly> {\n // Is there enough sub assemblies to meet quorum\n if (subAssemblies.length < assemblyQuorum) {\n throw new KcBadArgumentException(\n 'Not enough sub assemblies to meet quorum'\n );\n }\n\n const slipAssembly = new slip.Assembly(assemblyQuorum);\n\n subAssemblies.forEach((sa, index) => {\n let approverCount = sa.approverTps.length;\n\n // slip39 restricts quorum == 1 to have only 1 member. So we just share the same\n // partial key for all sub assembly members.\n if (sa.quorum === 1) {\n approverCount = 1;\n }\n slipAssembly.addSubAssembly(\n new slip.SubAssembly(index, sa.quorum, approverCount)\n );\n });\n\n await this.slip39Service.generateShares(\n rawAssemblyKey,\n this.slip39Passphrase,\n slipAssembly\n );\n return slipAssembly;\n }\n}\n","import { Injectable, Injector, NgZone } from '@angular/core';\nimport { TpNode } from '../api/types';\nimport { TpAssemblyController } from '../tp-assembly/tp-assembly';\nimport { RunOutsideAngular } from '../_common/run-outside-angular';\nimport { TP_PASSWORD_RESET_SLIP39_PASSPHRASE } from './tp-password-reset.constants';\n\n@RunOutsideAngular({\n ngZoneName: 'ngZone',\n})\n@Injectable({\n providedIn: 'root',\n})\nexport class TpPasswordResetAssemblyController extends TpAssemblyController {\n slip39Passphrase = TP_PASSWORD_RESET_SLIP39_PASSPHRASE;\n\n constructor(private ngZone: NgZone, private injector: Injector) {\n super(injector);\n }\n\n getTpWrappingKeyId(tp: TpNode) {\n return tp.currentUserSharedKey.userSharedKey.mkSharedKey.id;\n }\n}\n","import { ID, JSONObject } from '../api/types';\nimport { gqlTyped } from '../_common/ast';\n\nexport interface CancelTpPasswordResetRequestMutationResult {\n cancelTpPasswordResetRequest: {\n id: ID;\n };\n}\nexport const CancelTpPasswordResetRequestMutation = gqlTyped<CancelTpPasswordResetRequestMutationResult>`\nmutation CancelTpPasswordResetRequestMutation {\n cancelTpPasswordResetRequest(input: {}) {\n id\n }\n}`;\n\nexport interface CreateTpAssemblyKeyChallengeMutationResult {\n createTpAssemblyKeyChallenge: {\n challenge: JSONObject;\n };\n}\nexport const CreateTpAssemblyKeyChallengeMutation = gqlTyped<CreateTpAssemblyKeyChallengeMutationResult>`\nmutation CreateTpAssemblyKeyChallengeMutation(\n $input: CreateTpAssemblyKeyChallengeInput!\n) {\n createTpAssemblyKeyChallenge(input: $input) {\n challenge\n }\n}`;\n\nexport interface PreCompleteTpPasswordResetRequestMutationResult {\n preCompleteTpPasswordResetRequest: {\n idpPassword: string;\n };\n}\nexport const PreCompleteTpPasswordResetRequestMutation = gqlTyped<PreCompleteTpPasswordResetRequestMutationResult>`\nmutation PreCompleteTpPasswordResetRequestMutation(\n $input: PreCompleteTpPasswordResetRequestInput!\n) {\n preCompleteTpPasswordResetRequest(input: $input) {\n idpPassword\n }\n}`;\n\nexport interface CompleteTpPasswordResetRequestMutationResult {\n completeTpPasswordResetRequest: {\n id: ID;\n };\n}\nexport const CompleteTpPasswordResetRequestMutation = gqlTyped<CompleteTpPasswordResetRequestMutationResult>`\nmutation CompleteTpPasswordResetRequestMutation(\n $input: CompleteTpPasswordResetRequestInput!\n) {\n completeTpPasswordResetRequest(input: $input) {\n id\n }\n}`;\n\nexport interface ApproveTpPasswordResetRequestMutationResult {\n approveTpPasswordResetRequest: {\n claimApprover: {\n id: ID;\n };\n };\n}\nexport const ApproveTpPasswordResetRequestMutation = gqlTyped<ApproveTpPasswordResetRequestMutationResult>`\nmutation ApproveTpPasswordResetRequestMutation(\n $input: ApproveTpPasswordResetRequestInput!\n) {\n approveTpPasswordResetRequest(input: $input) {\n claimApprover {\n id\n }\n }\n}`;\n\nexport interface RejectTpPasswordResetRequestMutationResult {\n rejectTpPasswordResetRequest: {\n claimApprover: {\n id: ID;\n };\n };\n}\nexport const RejectTpPasswordResetRequestMutation = gqlTyped<RejectTpPasswordResetRequestMutationResult>`\nmutation RejectTpPasswordResetRequestMutation(\n $input: RejectTpPasswordResetRequestInput!\n) {\n rejectTpPasswordResetRequest(input: $input) {\n claimApprover {\n id\n }\n }\n}`;\n\nexport interface CreateTpPasswordResetMutationResult {\n createTpPasswordReset: {\n tpPasswordReset: {\n id: ID;\n };\n };\n}\nexport const CreateTpPasswordResetMutation = gqlTyped<CreateTpPasswordResetMutationResult>`\nmutation CreateTpPasswordResetMutation($input: CreateTpPasswordResetInput!) {\n createTpPasswordReset(input: $input) {\n tpPasswordReset {\n id\n }\n }\n}`;\n\nexport interface DeleteTpPasswordResetMutationResult {\n deleteTpPasswordReset: {\n id: ID;\n };\n}\nexport const DeleteTpPasswordResetMutation = gqlTyped<DeleteTpPasswordResetMutationResult>`\nmutation DeleteTpPasswordResetMutation {\n deleteTpPasswordReset(input: {}) {\n id\n }\n}`;\n\nexport interface UpdateTpPasswordResetMutationResult {\n updateTpPasswordReset: {\n tpPasswordReset: {\n id: ID;\n };\n };\n}\nexport const UpdateTpPasswordResetMutation = gqlTyped<UpdateTpPasswordResetMutationResult>`\nmutation UpdateTpPasswordResetMutation($input: UpdateTpPasswordResetInput!) {\n updateTpPasswordReset(input: $input) {\n tpPasswordReset {\n id\n }\n }\n}`;\n","export class KeyContainer {\n private timer: NodeJS.Timeout;\n\n constructor(private _key: CryptoKey, timeout: number) {\n this.timer = setTimeout(() => {\n this._key = null;\n }, timeout);\n }\n get key(): CryptoKey {\n return this._key;\n }\n\n /**\n * Clears the reference to the key, clears the timer, return the key.\n * It's important to call this function when the key is no longer needed because\n * the anonymous function in setTimeout() holds a reference to \"this\", and hence\n * keeps the \"this._key\" reference until the timer expired. So if we have used\n * the key before it expired, we should clear the \"this._key\" reference immediately.\n */\n pop(): CryptoKey {\n const ret = this._key;\n this._key = null;\n if (this.timer) {\n clearTimeout(this.timer);\n this.timer = null;\n }\n return ret;\n }\n}\n","import {\n TpPasswordResetUser,\n TpPasswordResetUserApprovalNode,\n TpPasswordResetUserApprover,\n TpPasswordResetUserAssembly,\n TpPasswordResetUserSubAssembly,\n UserNode,\n} from '../api/types';\nimport { UserKeys } from '../key/key.service';\nimport { gqlTyped } from '../_common/ast';\nimport { KeyGraphFragment } from '../_common/queries.gql';\n\nexport interface CurrentUserQueryResult {\n currentUser: Pick<\n Required<UserNode>,\n 'id' | 'username' | 'sessionEncryptionKey'\n > & {\n currentUserKey: UserKeys;\n };\n}\nexport const CurrentUserQuery = gqlTyped<CurrentUserQueryResult>`\nquery {\n currentUser {\n id\n username\n currentUserKey {\n passKey {\n id\n passKeyParams\n passIdpParams\n wrappedPassIdpVerifierPrk\n created\n }\n masterKey {\n id\n }\n rootKey {\n id\n }\n pxk {\n id\n }\n sigPxk {\n id\n }\n }\n sessionEncryptionKey\n }\n keyGraph {\n ...KeyGraphFragment\n }\n}\n${KeyGraphFragment}\n`;\n\nexport interface ResetUserQueryResult {\n tpPasswordResetUser: Pick<\n Required<TpPasswordResetUser>,\n | 'username'\n | 'sessionEncryptionKey'\n | 'state'\n | 'passKey'\n | 'masterKey'\n | 'pxk'\n | 'approvals'\n | 'assemblyCipherData'\n | 'wrappedAssemblyKeyVerifierPrk'\n > & {\n assembly: Pick<\n Required<TpPasswordResetUserAssembly>,\n 'singleReject' | 'quorum'\n > & {\n subAssemblies: (Pick<\n Required<TpPasswordResetUserSubAssembly>,\n 'singleReject' | 'quorum'\n > & {\n approvers: Pick<\n Required<TpPasswordResetUserApprover>,\n 'name' | 'email' | 'state'\n >[];\n })[];\n };\n approvals: Pick<\n Required<TpPasswordResetUserApprovalNode>,\n | 'id'\n | 'modified'\n | 'approverEmail'\n | 'receiverCipher'\n | 'receiverCipherPartialAssemblyKey'\n >;\n };\n}\nexport const ResetUserQuery = gqlTyped<ResetUserQueryResult>`\nquery ResetUserQuery {\n tpPasswordResetUser {\n username\n sessionEncryptionKey\n state\n passKey {\n id\n passKeyParams\n passIdpParams\n }\n masterKey {\n id\n }\n pxk {\n id\n }\n assembly {\n singleReject\n quorum\n subAssemblies {\n singleReject\n quorum\n approvers {\n name\n email\n state\n }\n }\n }\n approvals {\n id\n modified\n approverEmail\n receiverCipher\n receiverCipherPartialAssemblyKey\n }\n assemblyCipherData\n wrappedAssemblyKeyVerifierPrk\n }\n}`;\n\nexport interface SetSessionEncryptionKeyMutation {\n setSessionEncryptionKey: {\n sessionEncryptionKey: string;\n };\n}\nexport const SetSessionEncryptionKeyMutation = gqlTyped<SetSessionEncryptionKeyMutation>`\nmutation SetSessionEncryptionKeyMutation($input: SetSessionEncryptionKeyInput!) {\n setSessionEncryptionKey(input: $input) {\n sessionEncryptionKey\n }\n}\n`;\n","import { CognitoUser } from '@aws-amplify/auth';\nimport { CognitoUserAttribute } from 'amazon-cognito-identity-js';\nimport { JWK } from 'node-jose';\nimport {\n ID,\n JSONObject,\n TpClaimState,\n TpPasswordResetUser,\n TpPasswordResetUserApprovalNode,\n TpPasswordResetUserApprover,\n TpPasswordResetUserAssembly,\n TpPasswordResetUserSubAssembly,\n UserNode,\n} from '../api/types';\nimport { PassIdpParams, PassKeyParams } from '../key/key.types';\n\nexport type AuthUser = Pick<Required<UserNode>, 'username'> & {\n id?: ID; // The reset user does not return an id.\n sub: string;\n loginEmail: string;\n resetUser: null | {\n state: TpClaimState;\n };\n};\n\nexport type LogoutListener = () => void | Promise<void>;\n\nexport interface LoginOptions {\n // If true, complete any TP password reset requests right after login.\n // This is mainly for debugging and testing purposes.\n tpPasswordResetAutoComplete?: boolean;\n}\n\nexport enum RecoveryStatus {\n NONE = 'NONE',\n NEW_PASSWORD = 'NEW_PASSWORD',\n OLD_PASSWORD = 'OLD_PASSWORD',\n}\n\nexport enum PasswordChangeStatus {\n IN_PROGRESS = 'IN_PROGRESS',\n RECOVERY = 'RECOVERY',\n}\n\nexport interface PassIdpResult {\n passwordChangeStatus?: PasswordChangeStatus;\n currentPassIdpParams: PassIdpParams;\n newPassIdpParams: PassIdpParams;\n tpPasswordReset: {\n passIdpParams: PassIdpParams;\n resetUsername: string;\n };\n}\n\nexport enum CognitoChallengeName {\n NEW_PASSWORD_REQUIRED = 'NEW_PASSWORD_REQUIRED',\n SMS_MFA = 'SMS_MFA',\n SOFTWARE_TOKEN_MFA = 'SOFTWARE_TOKEN_MFA',\n MFA_SETUP = 'MFA_SETUP',\n}\n\nexport type LrCognitoUser = CognitoUser & {\n // These are missing types. Bug in the lib basically.\n challengeName: CognitoChallengeName;\n challengeParam: JSONObject;\n};\n\nexport type LrCognitoUserAttribute = CognitoUserAttribute;\n\nexport interface LoginChallenge {\n cognitoUser: LrCognitoUser;\n // In the event a password change process has failed, we need to know\n // if the new or old password was used. This allows us to track it.\n recoveryStatus: RecoveryStatus;\n}\n\nexport interface LoginResult {\n challenge?: LoginChallenge;\n user?: AuthUser;\n}\n\nexport interface PassKeyBundle {\n passKeyParams: PassKeyParams;\n passKey: JWK.Key;\n passIdpParams: PassIdpParams;\n passIdp: JWK.Key;\n passIdpVerifier: JWK.Key;\n wrappedPassIdpVerifierPrk: Record<string, JSONObject>;\n}\n\nexport type ResetUser = Pick<\n Required<TpPasswordResetUser>,\n 'username' | 'state' | 'approvals'\n> & {\n assembly: Pick<\n Required<TpPasswordResetUserAssembly>,\n 'singleReject' | 'quorum'\n > & {\n subAssemblies: (Pick<\n Required<TpPasswordResetUserSubAssembly>,\n 'singleReject' | 'quorum'\n > & {\n approvers: Pick<\n Required<TpPasswordResetUserApprover>,\n 'name' | 'email' | 'state'\n >[];\n })[];\n };\n approvals: Pick<\n Required<TpPasswordResetUserApprovalNode>,\n | 'id'\n | 'modified'\n | 'approverEmail'\n | 'receiverCipher'\n | 'receiverCipherPartialAssemblyKey'\n >;\n};\n","import { HttpClient } from '@angular/common/http';\nimport { Inject, Injectable, Injector, isDevMode, NgZone } from '@angular/core';\nimport { CognitoUser } from '@aws-amplify/auth';\nimport { AuthClass } from '@aws-amplify/auth/lib-esm/Auth';\nimport { Hub } from '@aws-amplify/core';\nimport { CognitoUserAttribute } from 'amazon-cognito-identity-js';\nimport { JWK } from 'node-jose';\nimport { LrGraphQLService, LrMutation, LrService } from '../api/lr-graphql';\nimport { TpClaimState } from '../api/types';\nimport { EncryptionService } from '../encryption/encryption.service';\nimport { IdleService } from '../idle/idle.service';\nimport { KeyFactoryService } from '../key/key-factory.service';\nimport { KeyGraphService } from '../key/key-graph.service';\nimport { KeyService, UserKeys } from '../key/key.service';\nimport { PassIdpParams } from '../key/key.types';\nimport { KcConfig, KC_CONFIG } from '../life-ready.config';\nimport { PasswordService } from '../password/password.service';\nimport { PersistService } from '../persist/persist.service';\nimport {\n TP_PASSWORD_RESET_CLIENT_NONCE_LENGTH,\n TP_PASSWORD_RESET_USERNAME_SUFFIX,\n} from '../tp-password-reset/tp-password-reset.constants';\nimport { TpPasswordResetAssemblyController } from '../tp-password-reset/tp-password-reset.controller';\nimport {\n CompleteTpPasswordResetRequestMutation,\n CreateTpAssemblyKeyChallengeMutation,\n PreCompleteTpPasswordResetRequestMutation,\n} from '../tp-password-reset/tp-password-reset.gql';\nimport {\n KcBadRequestException,\n KcBadStateException,\n KcConcurrentAccessException,\n KcInternalErrorException,\n} from '../_common/exceptions';\nimport { KeyContainer } from '../_common/key';\nimport { RunOutsideAngular } from '../_common/run-outside-angular';\nimport {\n CurrentUserQuery,\n CurrentUserQueryResult,\n ResetUserQuery,\n ResetUserQueryResult,\n SetSessionEncryptionKeyMutation,\n} from './auth.gql.private';\nimport {\n AuthUser,\n CognitoChallengeName,\n LoginChallenge,\n LoginOptions,\n LoginResult,\n LogoutListener,\n LrCognitoUser,\n LrCognitoUserAttribute,\n PassIdpResult,\n PasswordChangeStatus,\n RecoveryStatus,\n} from './auth.types';\n\n@RunOutsideAngular({\n ngZoneName: 'ngZone',\n})\n@Injectable({\n providedIn: 'root',\n})\nexport class AuthService extends LrService {\n static CHALLENGE_TIMEOUT = 1000 * 60 * 5;\n\n // Could use rxjs observables here. But trying to have kc-client use as little angular\n // features as possible. Rxjs is not used anywhere else in kc-client.\n private logoutListeners = new Set<LogoutListener>();\n private user: AuthUser;\n // Stores the password for use after mfa verification to decrypt masterKey.\n private password: KeyContainer = null;\n\n constructor(\n private ngZone: NgZone,\n private injector: Injector,\n private http: HttpClient,\n private cognito: AuthClass,\n private api: LrGraphQLService,\n private keyService: KeyService,\n private keyGraphService: KeyGraphService,\n private keyFactoryService: KeyFactoryService,\n private passwordService: PasswordService,\n private idleService: IdleService,\n private persistService: PersistService,\n private encryptionService: EncryptionService,\n private assemblyController: TpPasswordResetAssemblyController,\n @Inject(KC_CONFIG) private kcConfig: KcConfig\n ) {\n super(injector);\n if (!isDevMode()) {\n if (this.kcConfig.debug != null) {\n throw new KcBadRequestException(\n 'In production mode, \"KcConfig.debug\" must be set to null'\n );\n }\n }\n }\n\n importPassword(plainPassword: string): Promise<CryptoKey> {\n return this.keyFactoryService.importPassword(plainPassword);\n }\n\n async logout(): Promise<void> {\n // Notify all listeners to clean up.\n await Promise.all([...this.logoutListeners].map((callback) => callback()));\n\n this.user = null;\n this.keyService.purgeKeys();\n this.keyGraphService.purgeKeys();\n\n // Sign out on both cognito and kc-server\n await Promise.all([this.cognito.signOut(), this.kcLogout()]);\n\n if (this.kcConfig.debug?.username) {\n this.kcConfig.debug.username = null;\n }\n }\n\n addLogoutListener(callback: LogoutListener) {\n this.logoutListeners.add(callback);\n }\n\n removeLogoutListener(callback: LogoutListener) {\n this.logoutListeners.delete(callback);\n }\n\n async login(\n emailOrPhone: string,\n password: CryptoKey,\n { tpPasswordResetAutoComplete = true }: LoginOptions = {}\n ): Promise<LoginResult> {\n let loginResult: LoginResult = await this.loginImpl(emailOrPhone, password);\n\n // Save the password for use after meeting challenge.\n if (loginResult.challenge) {\n this.password = new KeyContainer(password, AuthService.CHALLENGE_TIMEOUT);\n\n return loginResult;\n }\n\n if (\n tpPasswordResetAutoComplete &&\n loginResult.user.resetUser?.state === TpClaimState.APPROVED\n ) {\n await this.completeResetRequest(password);\n loginResult = await this.loginImpl(emailOrPhone, password);\n }\n\n return loginResult;\n }\n\n async verifyLogin(options: {\n challenge: LoginChallenge;\n code: string;\n rememberMe: boolean;\n }): Promise<LoginResult> {\n const { challenge, code, rememberMe } = options;\n\n const VALID_CHALLENGE_NAMES = [\n CognitoChallengeName.SMS_MFA,\n CognitoChallengeName.SOFTWARE_TOKEN_MFA,\n ];\n\n if (!VALID_CHALLENGE_NAMES.includes(challenge.cognitoUser.challengeName)) {\n throw new KcBadRequestException(\n `challengeName must be one of ${VALID_CHALLENGE_NAMES}`\n );\n }\n\n // TODO: this.auth.confirmSignIn() could return another challenge.\n const cognitoUser = await this.cognito.confirmSignIn(\n challenge.cognitoUser,\n code,\n challenge.cognitoUser.challengeName as\n | CognitoChallengeName.SMS_MFA\n | CognitoChallengeName.SOFTWARE_TOKEN_MFA\n );\n\n await this.handlePostAuth(challenge.recoveryStatus);\n\n const user = await this.loadUser(cognitoUser, this.password.pop());\n\n // This is not strictly necessary since the this.password.pop() already clears the\n // password inside the container. But doesn't hurt either.\n this.password = null;\n\n if (rememberMe) {\n cognitoUser.setDeviceStatusRemembered({\n onSuccess: () => {\n return;\n },\n onFailure: (e) => console.error(e),\n });\n }\n\n return {\n user,\n };\n }\n\n async getUser(): Promise<AuthUser> {\n if (this.user) {\n return this.user;\n }\n\n const cognitoUser = await this.cognito.currentAuthenticatedUser();\n\n return this.loadUser(cognitoUser);\n }\n\n async refreshAccessToken() {\n const cognitoUser: CognitoUser =\n await this.cognito.currentAuthenticatedUser();\n const refreshToken = cognitoUser.getSignInUserSession().getRefreshToken();\n\n console.log('Token refresh...');\n return new Promise((resolve, reject) => {\n cognitoUser.refreshSession(refreshToken, (err) => {\n if (err) {\n console.error('Error refreshing token: ', err);\n reject(err);\n } else {\n console.log('Token refresh complete');\n resolve(0);\n }\n });\n });\n }\n\n // ----------------------------------------------------------------------------------------------------\n // Helpers\n // ----------------------------------------------------------------------------------------------------\n\n private async fetchCurrentUser() {\n return (\n await this.api.query<CurrentUserQueryResult>({\n query: CurrentUserQuery,\n processorOptions: {\n hasKeys: false, // Don't try to decrypt anything because keys have not been setup yet\n },\n })\n ).currentUser;\n }\n\n private async fetchResetUser() {\n return (\n await this.api.query<ResetUserQueryResult>({\n query: ResetUserQuery,\n processorOptions: {\n hasKeys: false, // Don't try to decrypt anything because keys have not been setup yet\n },\n })\n ).tpPasswordResetUser;\n }\n\n private async kcLogout(): Promise<void> {\n await this.http\n .post(`${this.kcConfig.authUrl}auth/sign-out/`, null, {\n withCredentials: true,\n responseType: 'text',\n })\n .toPromise();\n }\n\n private async fetchPassIdpParams(\n emailOrPhone: string\n ): Promise<PassIdpResult> {\n return await this.http\n .get<PassIdpResult>(\n `${\n this.kcConfig.authUrl\n }users/pass-idp-params/?login_name=${encodeURIComponent(emailOrPhone)}`\n )\n .toPromise();\n }\n\n private async loginImpl(\n emailOrPhone: string,\n password: CryptoKey\n ): Promise<LoginResult> {\n await this.logout();\n const loginIdpResult = await this.loginIdp(emailOrPhone, password);\n\n // Can't get the user yet because we still ned to meet MFA challenges\n if (\n [\n CognitoChallengeName.SMS_MFA,\n CognitoChallengeName.SOFTWARE_TOKEN_MFA,\n ].includes(loginIdpResult.cognitoUser.challengeName)\n ) {\n return {\n challenge: {\n cognitoUser: loginIdpResult.cognitoUser,\n recoveryStatus: loginIdpResult.recoveryStatus,\n },\n };\n }\n\n await this.handlePostAuth(loginIdpResult.recoveryStatus);\n // There should be no MFA on the TP reset user.\n const user = await this.loadUser(loginIdpResult.cognitoUser, password);\n\n return {\n user,\n };\n }\n\n private async loginIdp(\n emailOrPhone: string,\n password: CryptoKey\n ): Promise<LoginChallenge> {\n // Download the salt needed to derive the PassIdp\n const passIdpApiResult = await this.fetchPassIdpParams(emailOrPhone);\n\n if (\n passIdpApiResult.passwordChangeStatus === PasswordChangeStatus.IN_PROGRESS\n ) {\n throw new KcConcurrentAccessException('A password change is in progress');\n }\n\n if (\n passIdpApiResult.passwordChangeStatus === PasswordChangeStatus.RECOVERY\n ) {\n console.log('In recovery mode.');\n\n // Let's say we don't know if the password is the new one or the old one. We just have to try both.\n try {\n const user: LoginChallenge = {\n cognitoUser: await this.loginIdpImpl(\n emailOrPhone,\n password,\n passIdpApiResult.newPassIdpParams\n ),\n recoveryStatus: RecoveryStatus.NEW_PASSWORD,\n };\n // New password worked. Let's set to the current password\n\n // --Potential Failure Point 1--\n // if changePasswordComplete() doesn't get called, then it should remain\n\n console.log('New password works!');\n\n return user;\n } catch (error) {\n // Just bubble up any other type of error.\n if (error.code !== 'NotAuthorizedException') {\n throw error;\n }\n // pass, try again assuming it's the old password\n }\n\n // Now assume it's the previous password. Any exception is allowed to bubble up.\n try {\n const user: LoginChallenge = {\n cognitoUser: await this.loginIdpImpl(\n emailOrPhone,\n password,\n passIdpApiResult.currentPassIdpParams\n ),\n recoveryStatus: RecoveryStatus.OLD_PASSWORD,\n };\n // Old password worked.\n console.log('Old password works!');\n\n return user;\n } catch (error) {\n // Just bubble up any other type of error.\n throw error.code === 'NotAuthorizedException'\n ? new KcBadRequestException(\n 'The password change request was interrupted, please try to login with both your new and old password'\n )\n : error;\n }\n }\n\n // Try again as the TP password reset account\n if (passIdpApiResult.tpPasswordReset) {\n try {\n // TP password reset is in process. We need to try the password against both\n // original account and the new reset account.\n const reset = passIdpApiResult.tpPasswordReset;\n const user: LoginChallenge = {\n cognitoUser: await this.loginIdpImpl(\n reset.resetUsername,\n password,\n reset.passIdpParams\n ),\n recoveryStatus: RecoveryStatus.NONE,\n };\n\n return user;\n } catch (err) {\n // continue, try again as regular user.\n }\n }\n\n // Login as regular user\n const user: LoginChallenge = {\n cognitoUser: await this.loginIdpImpl(\n emailOrPhone,\n password,\n passIdpApiResult.currentPassIdpParams\n ),\n recoveryStatus: RecoveryStatus.NONE,\n };\n\n return user;\n }\n\n private async loginIdpImpl(\n emailOrPhone: string,\n password: CryptoKey,\n passIdpParams: PassIdpParams\n ): Promise<LrCognitoUser> {\n const passIdpResult = await this.keyFactoryService.derivePassIdp({\n password,\n ...passIdpParams,\n });\n\n // Use the derived password to signin with cognito\n return this.cognito.signIn(\n emailOrPhone,\n this.passwordService.getPassIdpString(passIdpResult.jwk)\n );\n }\n\n private async handlePostAuth(recoveryStatus: RecoveryStatus) {\n await this.handlePasswordRecovery(recoveryStatus);\n await this.handleSessionEncryptionKey();\n }\n\n private async handlePasswordRecovery(recoveryStatus: RecoveryStatus) {\n if (recoveryStatus !== RecoveryStatus.NONE) {\n await this.passwordService.changePasswordComplete({\n useNewPassword: recoveryStatus === RecoveryStatus.NEW_PASSWORD,\n });\n }\n }\n\n private async handleSessionEncryptionKey() {\n if (this.kcConfig.disableSessionEncryptionKey) {\n if (!isDevMode()) {\n const msg =\n 'You should not set disableSessionEncryptionKey=True in mode prod. It defaults to false.';\n console.error(msg);\n throw new KcInternalErrorException(msg);\n } else {\n console.warn(\n 'You have set disableSessionEncryptionKey=True. Make sure not to do this in prod mode.'\n );\n }\n } else {\n // Set the session key to a new encryption key for this session\n const sessionEncryptionKey = await this.keyFactoryService.createKey();\n await this.lrGraphQL.lrMutate(\n new LrMutation({\n mutation: SetSessionEncryptionKeyMutation,\n variables: {\n input: {\n sessionEncryptionKey: JSON.stringify(\n sessionEncryptionKey.toJSON(true)\n ),\n },\n },\n }),\n {\n includeKeyGraph: false,\n }\n );\n\n this.persistService.setServerSessionEncryptionKey(sessionEncryptionKey);\n }\n }\n\n private getCognitoUserAttribute(\n attributeName: string,\n userAttributes: CognitoUserAttribute[]\n ) {\n const userAttribute = userAttributes.find(\n (x) => x.getName() === attributeName\n );\n\n return userAttribute ? userAttribute.getValue() : null;\n }\n\n private async loadUserKeys(options: {\n userKeys: UserKeys;\n password?: CryptoKey;\n sessionEncryptionKey?: string;\n }) {\n const { userKeys, password, sessionEncryptionKey } = options;\n\n if (sessionEncryptionKey) {\n this.persistService.setServerSessionEncryptionKey(\n await JWK.asKey(sessionEncryptionKey)\n );\n }\n\n // password is not needed if the master key is already persisted.\n if (password) {\n const passKey = (\n await this.keyFactoryService.derivePassKey({\n password,\n ...userKeys.passKey.passKeyParams,\n })\n ).jwk;\n\n await this.idleService.persistMasterKey(\n await this.keyGraphService.unwrapWithPassKey(\n userKeys.passKey.id,\n passKey,\n userKeys.masterKey.id\n )\n );\n }\n }\n\n private async loadUser(\n cognitoUser: CognitoUser,\n password?: CryptoKey\n ): Promise<AuthUser> {\n if (cognitoUser.getUsername().endsWith(TP_PASSWORD_RESET_USERNAME_SUFFIX)) {\n this.user = await this.loadResetUser(cognitoUser, password);\n } else {\n this.user = await this.loadRegularUser(cognitoUser, password);\n }\n\n await this.idleService.start(); // Run idleService whenever user is logged in.\n\n return this.user;\n }\n\n private async loadRegularUser(\n cognitoUser: CognitoUser,\n password?: CryptoKey\n ): Promise<AuthUser> {\n const currentUser = await this.fetchCurrentUser();\n\n await this.loadUserKeys({\n userKeys: currentUser.currentUserKey,\n password,\n sessionEncryptionKey: currentUser.sessionEncryptionKey,\n });\n\n // Regular user populates all keys\n await this.keyGraphService.populateKeys(currentUser.currentUserKey);\n\n const { id, username } = currentUser;\n const userAttributes = await this.cognito.userAttributes(cognitoUser);\n\n return {\n id,\n username,\n sub: this.getCognitoUserAttribute('sub', userAttributes),\n loginEmail: this.getCognitoUserAttribute('email', userAttributes),\n resetUser: null,\n };\n }\n\n private async loadResetUser(\n cognitoUser: CognitoUser,\n password?: CryptoKey\n ): Promise<AuthUser> {\n const resetUser = await this.fetchResetUser();\n\n const userKeys = {\n passKey: {\n id: resetUser.passKey.id,\n passKeyParams: resetUser.passKey.passKeyParams,\n },\n masterKey: {\n id: resetUser.masterKey.id,\n },\n };\n\n await this.loadUserKeys({\n userKeys,\n password,\n sessionEncryptionKey: resetUser.sessionEncryptionKey,\n });\n\n // Reset user only sets a subset of keys\n await this.keyService.setKeys(userKeys);\n\n const { username } = resetUser;\n const userAttributes = await this.cognito.userAttributes(cognitoUser);\n\n return {\n username,\n sub: this.getCognitoUserAttribute('sub', userAttributes),\n loginEmail: this.getCognitoUserAttribute('email', userAttributes),\n resetUser: {\n state: resetUser.state,\n },\n };\n }\n\n private async recoverAssemblyKey(\n resetUser: ResetUserQueryResult['tpPasswordResetUser']\n ): Promise<JWK.Key> {\n const prk = await this.keyGraphService.getKey(resetUser.pxk.id);\n\n const partials = await Promise.all(\n resetUser.approvals\n .filter((approval) => !!approval.receiverCipherPartialAssemblyKey)\n .map((approval) =>\n this.encryptionService.decrypt(\n prk,\n approval.receiverCipherPartialAssemblyKey\n )\n )\n );\n\n return this.assemblyController.recoverAssemblyKey(partials);\n }\n\n async completeResetRequest(newPassword: CryptoKey): Promise<void> {\n const resetUser = await this.fetchResetUser();\n\n if (resetUser.state !== TpClaimState.APPROVED) {\n throw new KcBadStateException(\n 'Password reset request has not been approved.'\n );\n }\n\n // --------------------------------------------------------------\n // Prepare all materials to ensure there are no errors.\n // --------------------------------------------------------------\n const assemblyKey = await this.recoverAssemblyKey(resetUser);\n\n const { rootKey } = await this.encryptionService.decrypt(\n assemblyKey,\n resetUser.assemblyCipherData\n );\n\n // Making sure it's a valid key.\n const rootKeyJwk = await JWK.asKey(rootKey);\n\n const masterKey = await this.keyGraphService.getKey(resetUser.masterKey.id);\n\n const masterKeyWrappedRootKey =\n await this.encryptionService.encryptToString(\n masterKey.jwk,\n rootKeyJwk.toJSON(true)\n );\n\n // The new password\n const newPassIdpResult = await this.keyFactoryService.derivePassIdp({\n password: newPassword,\n ...resetUser.passKey.passIdpParams,\n });\n\n const newIdpPassword = this.passwordService.getPassIdpString(\n newPassIdpResult.jwk\n );\n\n // --------------------------------------------------------------\n // Get assembly key challenge\n // --------------------------------------------------------------\n const challenge = (\n await this.lrGraphQL.lrMutate(\n new LrMutation({\n mutation: CreateTpAssemblyKeyChallengeMutation,\n variables: {\n input: {},\n },\n }),\n {\n includeKeyGraph: false,\n }\n )\n ).createTpAssemblyKeyChallenge.challenge;\n\n // Sign the challenge\n // Generate a client side nonce that's no in the server's control.\n challenge.clientNonce = this.keyFactoryService.randomString(\n TP_PASSWORD_RESET_CLIENT_NONCE_LENGTH\n );\n\n const assemblyKeyVerifierPrk = await this.encryptionService.decrypt(\n assemblyKey,\n resetUser.wrappedAssemblyKeyVerifierPrk\n );\n const signedChallenge = await this.encryptionService.sign(\n assemblyKeyVerifierPrk,\n challenge\n );\n\n // --------------------------------------------------------------\n // Change password for the original user\n // --------------------------------------------------------------\n const tempIdpPassword = (\n await this.lrGraphQL.lrMutate(\n new LrMutation({\n mutation: PreCompleteTpPasswordResetRequestMutation,\n variables: {\n input: {\n signedChallenge: JSON.stringify(signedChallenge),\n },\n },\n }),\n {\n includeKeyGraph: false,\n }\n )\n ).preCompleteTpPasswordResetRequest.idpPassword;\n\n // --------------------------------------------------------------\n // Login as the original user using new temporary password\n // --------------------------------------------------------------\n // At this point, the original account's password has been changed\n // to a temporary password. It is no longer possible for the user\n // to use the original password to login. Any successful login\n // can only be using the temporary password. So it's safe to assume\n // that we want to \"complete\" the password reset.\n\n // There maybe 2FA so we listen for the auth event from Amplify.\n const retPromise = new Promise<void>((resolve) => {\n const listener = async (data) => {\n if (data.payload.event !== 'signIn') {\n return;\n }\n\n Hub.remove('auth', listener);\n\n await this.cognito.signIn(resetUser.username, newIdpPassword);\n\n // Switch over to the new set of keys\n await this.lrGraphQL.lrMutate(\n new LrMutation({\n mutation: CompleteTpPasswordResetRequestMutation,\n variables: {\n input: {\n masterKeyWrappedRootKey,\n masterKeyId: masterKey.id,\n },\n },\n })\n );\n\n resolve();\n };\n\n Hub.listen('auth', listener);\n });\n\n // Signin as the original user. Password has been reset to temporary one. It should return\n // with NEW_PASSWORD_REQUIRED\n let user = await this.cognito.signIn(resetUser.username, tempIdpPassword, {\n noProxy: 'true',\n });\n\n if (user.challengeName !== 'NEW_PASSWORD_REQUIRED') {\n throw new KcInternalErrorException(\n 'Expecting Cognito to have done a password reset after call to PreCompleteTpPasswordResetRequestMutation.'\n );\n }\n\n // Set new password on Idp\n // the awsFetch() function passes NEW_PASSWORD_REQUIRED directly to AWS without\n // going through the proxy.\n user = await this.cognito.completeNewPassword(user, newIdpPassword, {});\n\n return retPromise;\n }\n\n // ------------------------------------------------------\n // Debug utilities\n // ------------------------------------------------------\n async debugLogin(username: string, password: CryptoKey): Promise<AuthUser> {\n // This will fail if debug is null. But when debug is null, this function\n // should not be called.\n this.kcConfig.debug.username = username;\n\n // This mechanism only works in a browser session because it needs to set cookies etc.\n // But it sets the last_login field for the users which we need in some tests.\n await this.http\n .get(\n `${\n this.kcConfig.authUrl\n }debug_only/users/login/?username=${encodeURIComponent(username)}`\n )\n .toPromise();\n\n return this.debugLoadUser(password);\n }\n\n private async debugLoadUser(password: CryptoKey): Promise<AuthUser> {\n const currentUser = await this.fetchCurrentUser();\n\n const { id, username, currentUserKey } = currentUser;\n\n // Debug mode can not deal with session encryption key yet.\n // NO SESSION ENCRYPTION KEY.\n\n const passKey = (\n await this.keyFactoryService.derivePassKey({\n password,\n ...currentUserKey.passKey.passKeyParams,\n })\n ).jwk;\n\n const masterKey = await this.keyGraphService.unwrapWithPassKey(\n currentUserKey.passKey.id,\n passKey,\n currentUserKey.masterKey.id\n );\n\n await this.idleService.persistMasterKey(masterKey);\n\n await this.keyGraphService.populateKeys(currentUserKey);\n\n this.user = {\n id,\n username,\n resetUser: null,\n sub: 'DEBUG_MODE',\n loginEmail: 'DEBUG_MODE',\n };\n\n return this.user;\n }\n\n /**\n * Clears the caches user. So we can simulate a page refresh and test getUser().\n */\n debugClearUser() {\n this.user = null;\n }\n\n async getCurrentUserAttributes(): Promise<LrCognitoUserAttribute[]> {\n const cognitoUser = await this.cognito.currentAuthenticatedUser();\n const userAttributes = await this.cognito.userAttributes(cognitoUser);\n\n return userAttributes;\n }\n}\n","import { ID } from '../api/types';\nimport { gqlTyped } from '../_common/ast';\n\nexport interface CreateContactCardMutationResult {\n createContactCard: {\n contactCard: {\n id: ID;\n };\n };\n}\nexport const CreateContactCardMutation = gqlTyped<CreateContactCardMutationResult>`\nmutation CreateContactCardMutation(\n $input: CreateContactCardInput!\n) {\n createContactCard(input: $input) {\n contactCard {\n id\n }\n }\n}\n`;\n\nexport interface UpdateContactCardMutationResult {\n updateContactCard: {\n contactCard: {\n id: ID;\n };\n };\n}\nexport const UpdateContactCardMutation = gqlTyped<UpdateContactCardMutationResult>`\nmutation UpdateContactCardMutation($input: UpdateContactCardInput!) {\n updateContactCard(input: $input) {\n contactCard {\n id\n }\n }\n}\n`;\n\nexport interface DeleteContactCardMutationResult {\n deleteContactCard: {\n deleteContactCard: {\n id: ID;\n };\n };\n}\nexport const DeleteContactCardMutation = gqlTyped<DeleteContactCardMutationResult>`\nmutation DeleteContactCardMutation($input: DeleteContactCardInput!) {\n deleteContactCard(input: $input) {\n id\n }\n}\n`;\n","import { Injectable, NgZone } from '@angular/core';\nimport { LrMutation } from '../api/lr-graphql';\nimport { JSONObject } from '../api/types';\nimport { EncryptionService } from '../encryption/encryption.service';\nimport { KeyFactoryService } from '../key/key-factory.service';\nimport { KeyGraphService } from '../key/key-graph.service';\nimport { KeyMetaService } from '../key/key-meta.service';\nimport { KeyService } from '../key/key.service';\nimport { MainContactCardPlainFields } from '../profile/profile.types';\nimport { RunOutsideAngular } from '../_common/run-outside-angular';\nimport {\n CreateContactCardMutation,\n DeleteContactCardMutation,\n UpdateContactCardMutation,\n} from './contact-card2.gql';\n\nexport interface CreateContactCardInput2 {\n publicDataJson: JSONObject;\n publicSearchableJson: JSONObject;\n plainCipherDataJson: JSONObject;\n plainDataJson: MainContactCardPlainFields;\n}\n\n// These contact name fields are enforced by the server so that it can send out emails with\n// appropriate format.\nexport interface ContactCardName2 {\n name: string;\n title?: string;\n firstName?: string;\n lastName?: string;\n // additional fields are not allowed by the server\n}\n\nexport class OwnerPlainDataJson {\n name: ContactCardName2;\n}\n\nexport interface UpdateContactCardInput2 extends CreateContactCardInput2 {\n id: string;\n keyId: string;\n}\n\n@RunOutsideAngular({\n ngZoneName: 'ngZone',\n})\n@Injectable({\n providedIn: 'root',\n})\nexport class ContactCard2Service {\n constructor(\n private keyFactory: KeyFactoryService,\n private keyService: KeyService,\n private encryptionService: EncryptionService,\n private keyGraph: KeyGraphService,\n private keyMetaService: KeyMetaService,\n private ngZone: NgZone\n ) {}\n\n async createContactCard(input: CreateContactCardInput2) {\n // Get encryption key\n const rootKey = this.keyService.currentRootKey;\n const key = await this.keyFactory.createKey();\n const wrappedKey = await this.keyGraph.encryptToString(\n rootKey.jwk,\n key.toJSON(true)\n );\n const cipherData = await this.keyGraph.encryptToString(\n key,\n input.plainCipherDataJson\n );\n\n const params = await this.prepareContactCardInput(input);\n\n return new LrMutation({\n mutation: CreateContactCardMutation,\n variables: {\n input: {\n ...params,\n wrappingKeyId: rootKey.id,\n wrappedKey,\n cipherData,\n },\n },\n });\n }\n\n async updateContactCard(input: UpdateContactCardInput2) {\n // Get encryption key\n const cipherData = await this.keyGraph.encryptToString(\n input.keyId,\n input.plainCipherDataJson\n );\n\n const params = await this.prepareContactCardInput(input);\n\n return new LrMutation({\n mutation: UpdateContactCardMutation,\n variables: {\n input: {\n ...params,\n id: input.id,\n cipherData,\n },\n },\n });\n }\n\n deleteContactCard(id: string) {\n return new LrMutation({\n mutation: DeleteContactCardMutation,\n variables: {\n input: {\n id,\n },\n },\n });\n }\n\n private async prepareContactCardInput(input: CreateContactCardInput2) {\n const sigPxk = this.keyService.currentSigPxk;\n const publicDataSig = JSON.stringify(\n await this.encryptionService.sign(sigPxk.jwk, input.publicDataJson)\n );\n const publicSearchableSig = JSON.stringify(\n await this.encryptionService.sign(sigPxk.jwk, input.publicSearchableJson)\n );\n const plainDataSig = JSON.stringify(\n await this.encryptionService.sign(sigPxk.jwk, input.plainDataJson)\n );\n\n return {\n sigPxkId: sigPxk.id,\n publicDataSig,\n publicSearchableSig,\n plainDataSig,\n };\n }\n}\n","import { HttpClient } from '@angular/common/http';\nimport { Inject, Injectable } from '@angular/core';\nimport { AuthClass } from '@aws-amplify/auth/lib-esm/Auth';\nimport { JSONObject } from '../api/types';\nimport { httpOptions, KcConfig, KC_CONFIG } from '../life-ready.config';\nimport { UploadEncryptedFileOptions } from './file-upload.types';\n\n@Injectable({\n providedIn: 'root',\n})\nexport class FileUploadService {\n constructor(\n @Inject(KC_CONFIG) private config: KcConfig,\n private http: HttpClient,\n private auth: AuthClass\n ) {}\n\n async downloadEncryptedFileJson(\n fileStateNodeId: string\n ): Promise<JSONObject> {\n return JSON.parse(await this.downloadEncryptedFile(fileStateNodeId));\n }\n\n async downloadEncryptedFile(fileStateNodeId: string): Promise<string> {\n const url = `${this.config.apiUrl}files/download/?file_state_node_id=${fileStateNodeId}`;\n\n const content = await this.http\n .get(url, {\n ...(await httpOptions(this.auth, this.config)),\n responseType: 'text',\n })\n .toPromise();\n\n return content;\n }\n\n async loadFile(file: File | ArrayBuffer): Promise<ArrayBuffer> {\n if (file instanceof ArrayBuffer) {\n return file;\n } else {\n return new Promise<ArrayBuffer>((resolve) => {\n const reader = new FileReader();\n reader.onload = () => {\n // OK to type cast here since we are using readAsArrayBuffer.\n resolve(reader.result as ArrayBuffer);\n };\n reader.readAsArrayBuffer(file);\n });\n }\n }\n\n async uploadEncryptedFile(\n options: UploadEncryptedFileOptions\n ): Promise<string> {\n const { encryptedContent, fileName } = options;\n\n const formData = new FormData();\n formData.append('content', new Blob([encryptedContent]), fileName);\n\n const { content_resource } = await this.http\n .post<{ content_resource }>(\n `${this.config.apiUrl}files/upload/`,\n formData,\n await httpOptions(this.auth, this.config)\n )\n .toPromise();\n\n return content_resource;\n }\n}\n","import { DateTime, ID } from '../api/types';\nimport { gqlTyped } from '../_common/ast';\n\nexport interface CreateDirectoryMutationResult {\n createDirectory: {\n directory: {\n id: ID;\n keyId: ID;\n };\n };\n}\nexport const CreateDirectoryMutation = gqlTyped<CreateDirectoryMutationResult>`\nmutation CreateDirectoryMutation($input: CreateDirectoryInput!) {\n createDirectory(input: $input) {\n directory {\n id\n keyId\n }\n }\n}\n`;\n\nexport interface UpdateDirectoryMutationResult {\n updateDirectory: {\n directory: {\n id: ID;\n modified: DateTime;\n };\n };\n}\nexport const UpdateDirectoryMutation = gqlTyped<UpdateDirectoryMutationResult>`\nmutation UpdateDirectoryMutation($input: UpdateDirectoryInput!) {\n updateDirectory(input: $input) {\n directory {\n id\n modified\n }\n }\n}\n`;\n\nexport interface DeleteDirectoryMutationResult {\n deleteDirectory: {\n id: ID;\n };\n}\nexport const DeleteDirectoryMutation = gqlTyped<DeleteDirectoryMutationResult>`\nmutation DeleteDirectoryMutation($input: DeleteDirectoryInput!) {\n deleteDirectory(input: $input) {\n id\n }\n}\n`;\n\nexport interface CreateFileMutationResult {\n createFile: {\n file: {\n id: ID;\n keyId: ID;\n };\n };\n}\nexport const CreateFileMutation = gqlTyped<CreateFileMutationResult>`\nmutation CreateFileMutation($input: CreateFileInput!) {\n createFile(input: $input) {\n file {\n id\n keyId\n }\n }\n}\n`;\n\nexport interface UpdateFileMutationResult {\n updateFile: {\n file: {\n id: ID;\n };\n };\n}\nexport const UpdateFileMutation = gqlTyped<UpdateFileMutationResult>`\nmutation UpdateFileMutation($input: UpdateFileInput!) {\n updateFile(input: $input) {\n file {\n id\n }\n }\n}\n`;\n\nexport interface RevertFileMutationResult {\n revertFile: {\n file: {\n id: ID;\n };\n };\n}\nexport const RevertFileMutation = gqlTyped<RevertFileMutationResult>`\nmutation RevertFileMutation($input: RevertFileInput!) {\n revertFile(input: $input) {\n file {\n id\n }\n }\n}\n`;\n\nexport interface DeleteFileMutationResult {\n deleteFile: {\n id: ID;\n };\n}\nexport const DeleteFileMutation = gqlTyped<DeleteFileMutationResult>`\nmutation DeleteFileMutation($input: DeleteFileInput!) {\n deleteFile(input: $input) {\n id\n }\n}\n`;\n\nexport interface ArchiveDirectoryMutationResult {\n archiveDirectory: {\n directory: {\n id: ID;\n };\n };\n}\nexport const ArchiveDirectoryMutation = gqlTyped<ArchiveDirectoryMutationResult>`\nmutation ArchiveDirectoryMutation($input: ArchiveDirectoryInput!) {\n archiveDirectory(input: $input) {\n directory {\n id\n }\n }\n}\n`;\n\nexport interface ArchiveFileMutationResult {\n archiveFile: {\n file: {\n id: ID;\n };\n };\n}\nexport const ArchiveFileMutation = gqlTyped<ArchiveFileMutationResult>`\nmutation ArchiveFileMutation($input: ArchiveFileInput!) {\n archiveFile(input: $input) {\n file {\n id\n }\n }\n}\n`;\n\nexport interface UnarchiveDirectoryMutationResult {\n unarchiveDirectory: {\n directory: {\n id: ID;\n };\n };\n}\nexport const UnarchiveDirectoryMutation = gqlTyped<UnarchiveDirectoryMutationResult>`\nmutation UnarchiveDirectoryMutation($input: UnarchiveDirectoryInput!) {\n unarchiveDirectory(input: $input) {\n directory {\n id\n }\n }\n}\n`;\n\nexport interface UnarchiveFileMutationResult {\n unarchiveFile: {\n file: {\n id: ID;\n };\n };\n}\nexport const UnarchiveFileMutation = gqlTyped<UnarchiveFileMutationResult>`\nmutation UnarchiveFileMutation($input: UnarchiveFileInput!) {\n unarchiveFile(input: $input) {\n file {\n id\n }\n }\n}\n`;\n\nexport interface ChangeDirectoryParentsMutationResult {\n changeDirectoryParents: {\n directory: {\n id: ID;\n };\n };\n}\nexport const ChangeDirectoryParentsMutation = gqlTyped<ChangeDirectoryParentsMutationResult>`\nmutation ChangeDirectoryParentsMutation($input: ChangeDirectoryParentsInput!) {\n changeDirectoryParents(input: $input) {\n directory {\n id\n }\n }\n}\n`;\n\nexport interface ChangeFileParentsMutationResult {\n changeFileParents: {\n file: {\n id: ID;\n };\n };\n}\nexport const ChangeFileParentsMutation = gqlTyped<ChangeFileParentsMutationResult>`\nmutation ChangeFileParentsMutation($input: ChangeFileParentsInput!) {\n changeFileParents(input: $input) {\n file {\n id\n }\n }\n}\n`;\n\nexport interface BeginDeleteChildItemLinksWindowMutationResult {\n beginDeleteChildItemLinksWindow: {\n begin: DateTime;\n end: DateTime;\n scheduled: DateTime;\n windowMs: number;\n directory: {\n id: ID;\n };\n };\n}\nexport const BeginDeleteChildItemLinksWindowMutation = gqlTyped<BeginDeleteChildItemLinksWindowMutationResult>`\nmutation BeginDeleteChildItemLinksWindowMutation($input: BeginDeleteChildItemLinksWindowInput!) {\n beginDeleteChildItemLinksWindow(input: $input) {\n begin\n end\n scheduled\n windowMs\n directory {\n id\n }\n }\n}\n`;\n\n// This locks the user\nexport interface TempDirectoryQueryResult {\n rootDirectories: {\n edges: {\n node: {\n id: ID;\n keyId: ID;\n };\n }[];\n };\n lock: {\n version: string;\n };\n}\nexport const TempDirectoryQuery = gqlTyped<TempDirectoryQueryResult>`\nquery TempDirectoryQuery($plainMeta: LrJSONFilter!) {\n rootDirectories(plainMeta: $plainMeta, first: 2, orderBy: \"created\") {\n edges {\n node {\n id\n keyId\n }\n }\n }\n lock {\n version\n }\n}\n`;\n\nexport interface SetFileConfidentialMutationResult {\n setFileConfidential: {\n file: {\n id: ID;\n };\n };\n}\nexport const SetFileConfidentialMutation = gqlTyped<SetFileConfidentialMutationResult>`\nmutation SetFileConfidentialMutation($input: SetFileConfidentialInput!) {\n setFileConfidential(input: $input) {\n file {\n id\n }\n }\n}\n`;\n\nexport interface SetDirectoryConfidentialMutationResult {\n setDirectoryConfidential: {\n directory: {\n id: ID;\n };\n };\n}\nexport const SetDirectoryConfidentialMutation = gqlTyped<SetDirectoryConfidentialMutationResult>`\nmutation SetDirectoryConfidentialMutation($input: SetDirectoryConfidentialInput!) {\n setDirectoryConfidential(input: $input) {\n directory {\n id\n }\n }\n}\n`;\n","import { DateTime, LockState, UUID } from '../api/types';\nimport { gqlTyped } from '../_common/ast';\n\nexport interface LockFragmentResult {\n created: DateTime;\n modified: DateTime;\n version?: UUID;\n expiryTime: DateTime;\n state: LockState;\n}\nexport const LockFragment = gqlTyped<LockFragmentResult>`\nfragment LockFragment on LockField {\n created\n modified\n version\n expiryTime\n state\n}`;\n\nexport interface UpdateLockMutationResult {\n updateLock: {\n lock: LockFragmentResult;\n };\n}\nexport const UpdateLockMutation = gqlTyped<UpdateLockMutationResult>`\nmutation UpdateLockMutation($input: UpdateLockInput!) {\n updateLock(input: $input) {\n lock {\n ...LockFragment\n }\n }\n}\n${LockFragment}\n`;\n\nexport interface AcquireLockMutationResult {\n acquireLock: {\n lock: LockFragmentResult;\n };\n}\nexport const AcquireLockMutation = gqlTyped<AcquireLockMutationResult>`\nmutation AcquireLockMutation($input: AcquireLockInput!) {\n acquireLock(input: $input) {\n lock {\n ...LockFragment\n }\n }\n}\n${LockFragment}\n`;\n\nexport interface ReleaseLockMutationResult {\n releaseLock: {\n lock: LockFragmentResult;\n };\n}\nexport const ReleaseLockMutation = gqlTyped<ReleaseLockMutationResult>`\nmutation ReleaseLockMutation($input: ReleaseLockInput!) {\n releaseLock(input: $input) {\n lock {\n ...LockFragment\n }\n }\n}\n${LockFragment}\n`;\n","import { Injectable, Injector, NgZone } from '@angular/core';\nimport { LrMutation, LrService } from '../api/lr-graphql';\nimport { RunOutsideAngular } from '../_common/run-outside-angular';\nimport {\n AcquireLockMutation,\n ReleaseLockMutation,\n UpdateLockMutation,\n} from './lock.gql';\n\n@RunOutsideAngular({\n ngZoneName: 'ngZone',\n})\n@Injectable({\n providedIn: 'root',\n})\nexport class LockService extends LrService {\n constructor(private ngZone: NgZone, private injector: Injector) {\n super(injector);\n }\n\n // Updating the lock version is always to be down along with another mutation.\n updateLockMutation(options: { resourceId?: string; version: string }) {\n return new LrMutation({\n mutation: UpdateLockMutation,\n variables: {\n input: {\n resourceId: options.resourceId,\n version: options.version,\n },\n },\n });\n }\n\n acquireLockMutation(options: { resourceId?: string; timeoutMs: number }) {\n return new LrMutation({\n mutation: AcquireLockMutation,\n variables: {\n input: {\n resourceId: options.resourceId,\n timeoutMs: options.timeoutMs,\n },\n },\n });\n }\n\n releaseLockMutation(options: { resourceId: string; version: string }) {\n return new LrMutation({\n mutation: ReleaseLockMutation,\n variables: {\n input: {\n resourceId: options.resourceId,\n version: options.version,\n },\n },\n });\n }\n}\n","import { ID } from '../api/types';\nimport { gqlTyped } from '../_common/ast';\n\nexport interface DirectoryKeyQueryResult {\n directory: {\n keyId: ID;\n };\n}\nexport const DirectoryKeyQuery = gqlTyped<DirectoryKeyQueryResult>`\nquery DirectoryKeyQuery($id: LrRelayIdInput!) {\n directory(id: $id) {\n keyId\n }\n}\n`;\n\nexport interface FileKeyQueryResult {\n file: {\n keyId: ID;\n };\n}\nexport const FileKeyQuery = gqlTyped<FileKeyQueryResult>`\nquery FileKeyQuery($id: LrRelayIdInput!) {\n file(id: $id) {\n keyId\n }\n}\n`;\n\nexport interface DirectoryKeyFromDirectoryShareQueryResult {\n directoryShare: {\n item: {\n keyId: ID;\n };\n };\n}\nexport const DirectoryKeyFromDirectoryShareQuery = gqlTyped<DirectoryKeyFromDirectoryShareQueryResult>`\nquery DirectoryKeyFromDirectoryShareQuery($id: LrRelayIdInput!) {\n directoryShare(id: $id) {\n item {\n keyId\n }\n }\n}\n`;\n\nexport interface FileKeyFromFileShareQueryResult {\n fileShare: {\n item: {\n keyId: ID;\n };\n };\n}\nexport const FileKeyFromFileShareQuery = gqlTyped<FileKeyFromFileShareQueryResult>`\nquery FileKeyFromFileShareQuery($id: LrRelayIdInput!) {\n fileShare(id: $id) {\n item {\n keyId\n }\n }\n}\n`;\n\nexport interface FileStateKeyQueryResult {\n fileState: {\n keyId: ID;\n };\n}\nexport const FileStateKeyQuery = gqlTyped<FileStateKeyQueryResult>`\nquery FileStateKeyQuery($id: LrRelayIdInput!) {\n fileState(id: $id) {\n keyId\n }\n}\n`;\n","import { Injectable, Injector, NgZone } from '@angular/core';\nimport { JWK } from 'node-jose';\nimport { LrMutation, LrService } from '../api/lr-graphql';\nimport { ID, JSONObject, LinkTypeField, LrRelayIdInput } from '../api/types';\nimport { AuthService } from '../auth/auth.service';\nimport { FileUploadService } from '../file-upload/file-upload.service';\nimport { KeyFactoryService } from '../key/key-factory.service';\nimport { KeyGraphService } from '../key/key-graph.service';\nimport { KeyService } from '../key/key.service';\nimport { PayloadType } from '../key/key.types';\nimport { LockService } from '../lock/lock.service';\nimport { KcBadArgumentException } from '../_common/exceptions';\nimport { RunOutsideAngular } from '../_common/run-outside-angular';\nimport {\n ArchiveDirectoryMutation,\n ArchiveFileMutation,\n BeginDeleteChildItemLinksWindowMutation,\n ChangeDirectoryParentsMutation,\n ChangeFileParentsMutation,\n CreateDirectoryMutation,\n CreateFileMutation,\n DeleteDirectoryMutation,\n DeleteFileMutation,\n RevertFileMutation,\n SetDirectoryConfidentialMutation,\n SetFileConfidentialMutation,\n TempDirectoryQuery,\n UnarchiveDirectoryMutation,\n UnarchiveFileMutation,\n UpdateDirectoryMutation,\n UpdateFileMutation,\n} from './item.gql';\nimport {\n DirectoryKeyFromDirectoryShareQuery,\n DirectoryKeyQuery,\n FileKeyFromFileShareQuery,\n FileKeyQuery,\n FileStateKeyQuery,\n} from './item.gql.private';\nimport {\n ArchiveDirectoryOptions,\n BeginDeleteChildItemLinksWindowOptions,\n ChangeDirectoryParentsOptions,\n ChangeFileParentsOptions,\n ChangeItemParentsOptions,\n CreateDirectoryOptions,\n CreateDirectoryWithStagingOptions,\n CreateFileOptions,\n CreateFileWithStagingOptions,\n DownloadFileContentOptions,\n IdKeyPair,\n ParentDirectoryInput,\n ParentDirectoryOptions,\n ParentRootDirectoryInput,\n RevertFileOptions,\n SetDirectoryConfidentialOptions,\n SetFileConfidentialOptions,\n UnarchiveDirectoryOptions,\n UpdateDirectoryOptions,\n UpdateFileOptions,\n} from './item.types';\n\n@RunOutsideAngular({\n ngZoneName: 'ngZone',\n})\n@Injectable({\n providedIn: 'root',\n})\nexport class ItemService extends LrService {\n // Caching the temp directory.\n private tempDirectory: IdKeyPair = null;\n\n constructor(\n private ngZone: NgZone,\n private injector: Injector,\n private fileUploadService: FileUploadService,\n private keyService: KeyService,\n private keyFactory: KeyFactoryService,\n private keyGraph: KeyGraphService,\n private lockService: LockService,\n private authService: AuthService\n ) {\n super(injector);\n this.authService.addLogoutListener(() => this.onLogout());\n }\n\n static TEMP_DIRECTORY_PLAIN_META = { kcType: 'temp' };\n static TEMP_DIRECTORY_PLAIN_META_FILTER = JSON.stringify({\n filter: [\n {\n contains: ItemService.TEMP_DIRECTORY_PLAIN_META,\n },\n ],\n });\n\n async downloadFileContent(\n options: DownloadFileContentOptions\n ): Promise<Uint8Array> {\n const fileContent = await this.fileUploadService.downloadEncryptedFile(\n options.fileStateNodeId\n );\n\n const fileStateKey = await this.keyGraph.getKey(\n options.fileStateKeyId,\n () => this.getFileStateKeyId(options.fileStateNodeId)\n );\n\n return this.keyGraph.decryptFromString(fileStateKey, fileContent, {\n payloadType: PayloadType.UINT_8_ARRAY,\n });\n }\n\n async getDirectoryKeyId(directoryId: LrRelayIdInput) {\n return (\n await this.query({\n query: DirectoryKeyQuery,\n variables: {\n id: directoryId,\n },\n })\n ).directory.keyId;\n }\n\n async getFileKeyId(fileId: LrRelayIdInput) {\n return (\n await this.query({\n query: FileKeyQuery,\n variables: {\n id: fileId,\n },\n })\n ).file.keyId;\n }\n\n async getDirectoryKeyIdFromDirectoryShare(directoryShareId: LrRelayIdInput) {\n return (\n await this.query({\n query: DirectoryKeyFromDirectoryShareQuery,\n variables: {\n id: directoryShareId,\n },\n })\n ).directoryShare.item.keyId;\n }\n\n async getFileKeyIdFromFileShare(fileShareId: LrRelayIdInput) {\n return (\n await this.query({\n query: FileKeyFromFileShareQuery,\n variables: {\n id: fileShareId,\n },\n })\n ).fileShare.item.keyId;\n }\n\n async getDirectoryKey(\n directoryId: LrRelayIdInput,\n directoryKeyId?: LrRelayIdInput\n ) {\n return this.keyGraph.getKey(directoryKeyId, () =>\n this.getDirectoryKeyId(directoryId)\n );\n }\n\n async getFileKey(fileId: LrRelayIdInput, fileKeyId?: LrRelayIdInput) {\n return this.keyGraph.getKey(fileKeyId, () => this.getFileKeyId(fileId));\n }\n\n createDirectory(options: CreateDirectoryOptions) {\n return this.mutate(this.createDirectoryMutation(options));\n }\n\n async createDirectoryMutation(options: CreateDirectoryOptions) {\n return new LrMutation({\n mutation: CreateDirectoryMutation,\n variables: {\n input: await this.prepareCreateDirectory(options),\n },\n });\n }\n\n updateDirectory(options: UpdateDirectoryOptions) {\n return this.mutate(this.updateDirectoryMutation(options));\n }\n\n async updateDirectoryMutation(options: UpdateDirectoryOptions) {\n return new LrMutation({\n mutation: UpdateDirectoryMutation,\n variables: {\n input: await this.prepareUpdateDirectory(options),\n },\n });\n }\n\n deleteDirectory(id: ID) {\n return this.mutate(this.deleteDirectoryMutation(id));\n }\n\n deleteDirectoryMutation(id: ID) {\n return new LrMutation({\n mutation: DeleteDirectoryMutation,\n variables: {\n input: {\n directoryId: id,\n },\n },\n });\n }\n\n createFile(options: CreateFileOptions) {\n return this.mutate(this.createFileMutation(options));\n }\n\n async createFileMutation(options: CreateFileOptions) {\n return new LrMutation({\n mutation: CreateFileMutation,\n variables: {\n input: await this.prepareCreateFile(options),\n },\n });\n }\n\n updateFile(options: UpdateFileOptions) {\n return this.mutate(this.updateFileMutation(options));\n }\n\n async updateFileMutation(options: UpdateFileOptions) {\n return new LrMutation({\n mutation: UpdateFileMutation,\n variables: {\n input: await this.prepareUpdateFile(options),\n },\n });\n }\n\n revertFile(options: RevertFileOptions) {\n return this.mutate(this.revertFileMutation(options));\n }\n\n async revertFileMutation(options: RevertFileOptions) {\n return new LrMutation({\n mutation: RevertFileMutation,\n variables: {\n input: options,\n },\n });\n }\n\n deleteFile(id: ID) {\n return this.mutate(this.deleteFileMutation(id));\n }\n\n deleteFileMutation(id: ID) {\n return new LrMutation({\n mutation: DeleteFileMutation,\n variables: {\n input: {\n fileId: id,\n },\n },\n });\n }\n\n archiveDirectory(directoryId: string, options: ArchiveDirectoryOptions) {\n return this.mutate(this.archiveDirectoryMutation(directoryId, options));\n }\n\n archiveDirectoryMutation(\n directoryId: string,\n options: ArchiveDirectoryOptions\n ) {\n return new LrMutation({\n mutation: ArchiveDirectoryMutation,\n variables: {\n input: {\n directoryId,\n recursive: options.recursive,\n },\n },\n });\n }\n\n archiveFile(fileId: string) {\n return this.mutate(this.archiveFileMutation(fileId));\n }\n\n archiveFileMutation(fileId: string) {\n return new LrMutation({\n mutation: ArchiveFileMutation,\n variables: {\n input: {\n fileId,\n },\n },\n });\n }\n\n unarchiveDirectory(directoryId: string, options: UnarchiveDirectoryOptions) {\n return this.mutate(this.unarchiveDirectoryMutation(directoryId, options));\n }\n\n unarchiveDirectoryMutation(\n directoryId: string,\n options: UnarchiveDirectoryOptions\n ) {\n return new LrMutation({\n mutation: UnarchiveDirectoryMutation,\n variables: {\n input: {\n directoryId,\n recursive: options.recursive,\n },\n },\n });\n }\n\n unarchiveFile(fileId: string) {\n return this.mutate(this.unarchiveFileMutation(fileId));\n }\n\n unarchiveFileMutation(fileId: string) {\n return new LrMutation({\n mutation: UnarchiveFileMutation,\n variables: {\n input: {\n fileId,\n },\n },\n });\n }\n\n changeDirectoryParents(options: ChangeDirectoryParentsOptions) {\n return this.mutate(this.changeDirectoryParentsMutation(options));\n }\n\n async changeDirectoryParentsMutation(options: ChangeDirectoryParentsOptions) {\n return new LrMutation({\n mutation: ChangeDirectoryParentsMutation,\n variables: {\n input: await this.prepareChangeDirectoryParents(options),\n },\n });\n }\n\n async changeFileParents(options: ChangeFileParentsOptions) {\n return this.mutate(this.changeFileParentsMutation(options));\n }\n\n async changeFileParentsMutation(options: ChangeFileParentsOptions) {\n return new LrMutation({\n mutation: ChangeFileParentsMutation,\n variables: {\n input: await this.prepareChangeFileParents(options),\n },\n });\n }\n\n beginDeleteChildItemLinksWindow(\n options: BeginDeleteChildItemLinksWindowOptions\n ) {\n return this.mutate(this.beginDeleteChildItemLinksWindowMutation(options));\n }\n\n /**\n * Schedule cleanup of the hard links in a directory.\n * The server will delete all hard link within the directory within a time window: starting from now and\n * ending at requestWindowMs after now.\n * The server decides _when_ it will perform the delete. It's not guaranteed that it will perform\n * the delete at \"now + requestWindowMs\", but it will happen at some time after \"now + requestWindowMs\".\n * This allows multiple overlapping calls to this function and the server allocates enough for each request.\n * The server has a setting that allows for a maximum value on requestWindowMs. If the requested value\n * is larger than this maximum, the call will fail.\n */\n async beginDeleteChildItemLinksWindowMutation(\n options: BeginDeleteChildItemLinksWindowOptions\n ) {\n return new LrMutation({\n mutation: BeginDeleteChildItemLinksWindowMutation,\n variables: {\n input: options,\n },\n });\n }\n\n /**\n *\n * This method may raise VERSION_MISMATCH exception if there is a race condition\n * when multiple clients try to create the temp directory.\n *\n * TODO There is a retry mechanism in graphql with exponential back off but that's internal.\n * But need to use an exponential back off lib if we want to retry here.\n *\n * @returns The ID of the temp directory\n *\n */\n async ensureTempDirectory(): Promise<IdKeyPair> {\n if (this.tempDirectory) {\n return this.tempDirectory;\n }\n\n const existing = await this.query({\n query: TempDirectoryQuery,\n variables: {\n plainMeta: ItemService.TEMP_DIRECTORY_PLAIN_META_FILTER,\n },\n });\n\n if (existing.rootDirectories.edges.length > 1) {\n console.error(\n `There is more than 1 temp directory (plainMeta filter: ${ItemService.TEMP_DIRECTORY_PLAIN_META_FILTER})`\n );\n }\n\n if (existing.rootDirectories.edges.length === 0) {\n // Doesn't exist yet, create it\n const createDirectory = await this.createDirectoryMutation({\n asRootDirectory: true,\n plainMetaJson: ItemService.TEMP_DIRECTORY_PLAIN_META,\n });\n\n // Optimistic lock on the current user.\n const updateLock = this.lockService.updateLockMutation({\n version: existing.lock?.version,\n });\n\n // Because this.mutate() only handles simple types we need to use the more\n // advanced this.lrGraphQL.lrMutate()\n const [createDirectoryResult] = await this.lrGraphQL.lrMutate([\n createDirectory,\n updateLock,\n ]);\n\n const { id, keyId } = createDirectoryResult.createDirectory.directory;\n\n this.tempDirectory = {\n id,\n keyId,\n };\n } else {\n // Return existing temp\n const { id, keyId } = existing.rootDirectories.edges[0].node;\n\n this.tempDirectory = {\n id,\n keyId,\n };\n }\n\n return this.tempDirectory;\n }\n\n async createDirectoryWithStaging(options: CreateDirectoryWithStagingOptions) {\n return this.mutate(this.createDirectoryWithStagingMutation(options));\n }\n\n /**\n * You must run this mutation within the temp directory cleanup window on the\n * server, otherwise the temp directory will get cleaned up.\n *\n */\n async createDirectoryWithStagingMutation(\n options: CreateDirectoryWithStagingOptions\n ) {\n const tempDir = await this.ensureTempDirectory();\n\n // Clear the temp directory of the ones we are about to create.\n // NOTE: this mutation can not be merged into a single mutation with the\n // the createDirectory mutation because it uses the current server time to\n // clean up. So it must successfully complete before the creation of the\n // directories.\n await this.beginDeleteChildItemLinksWindow({\n directoryId: tempDir.id,\n requestWindowMs: options.requestWindowMs,\n });\n\n // Create the directory that has contents\n const directory = (\n await this.createDirectory({\n cipherMetaClearJson: options.cipherMetaClearJson,\n parentDirectories: [\n {\n directoryId: tempDir.id,\n wrappingKeyId: tempDir.keyId,\n },\n ],\n plainMetaJson: options.plainMetaJson,\n })\n ).createDirectory.directory;\n\n // Call back with item that's currently in staging.\n await options.onCreatedInStaging({\n id: directory.id,\n keyId: directory.keyId,\n });\n\n // TODO client-side check for timeout on requestWindowMs\n // TODO return the server time where delete is scheduled. Expirable mutation\n\n // Return the mutation that moves the directory into the dst directories\n return this.changeDirectoryParentsMutation({\n directoryId: directory.id,\n directoryKeyId: directory.keyId,\n parentsToRemove: [tempDir.id],\n parentsToAdd: options.parentDirectories,\n });\n }\n\n async createFileWithStaging(options: CreateFileWithStagingOptions) {\n return this.mutate(this.createFileWithStagingMutation(options));\n }\n\n async createFileWithStagingMutation(options: CreateFileWithStagingOptions) {\n const tempDir = await this.ensureTempDirectory();\n\n // Clear the temp directory of the ones we are about to create.\n // NOTE: this mutation can not be merged into a single mutation with the\n // the createDirectory mutation because it uses the current server time to\n // clean up. So it must successfully complete before the creation of the\n // directories.\n await this.beginDeleteChildItemLinksWindow({\n directoryId: tempDir.id,\n requestWindowMs: options.requestWindowMs,\n });\n\n // Create the file\n const file = (\n await this.createFile({\n ...options,\n parentDirectories: [\n {\n directoryId: tempDir.id,\n wrappingKeyId: tempDir.keyId,\n },\n ],\n })\n ).createFile.file;\n\n // Call back with item that's currently in staging.\n await options.onCreatedInStaging({\n id: file.id,\n keyId: file.keyId,\n });\n\n // TODO client-side check for timeout on requestWindowMs\n // TODO return the server time where delete is scheduled. Expirable mutation\n\n // Return the mutation that moves the directory into the dst directories\n return this.changeFileParentsMutation({\n fileId: file.id,\n fileKeyId: file.keyId,\n parentsToRemove: [tempDir.id],\n parentsToAdd: options.parentDirectories,\n });\n }\n\n async setFileConfidential(options: SetFileConfidentialOptions) {\n return this.mutate(this.setFileConfidentialMutation(options));\n }\n\n async setFileConfidentialMutation(options: SetFileConfidentialOptions) {\n return new LrMutation({\n mutation: SetFileConfidentialMutation,\n variables: {\n input: {\n fileId: options.fileId,\n confidential: options.confidential,\n },\n },\n });\n }\n\n async setDirectoryConfidential(options: SetDirectoryConfidentialOptions) {\n return this.mutate(this.setDirectoryConfidentialMutation(options));\n }\n\n async setDirectoryConfidentialMutation(\n options: SetDirectoryConfidentialOptions\n ) {\n return new LrMutation({\n mutation: SetDirectoryConfidentialMutation,\n variables: {\n input: {\n directoryId: options.directoryId,\n confidential: options.confidential,\n },\n },\n });\n }\n\n // ------------------------------------------------------------------------------\n // ------------------------------------------------------------------------------\n // Helpers\n // ------------------------------------------------------------------------------\n // ------------------------------------------------------------------------------\n\n private async prepareParentDirectory(\n options: ParentDirectoryOptions,\n newKey: JWK.Key\n ): Promise<ParentDirectoryInput> {\n const { directoryId, linkType, wrappingKeyId } = options;\n\n if (linkType == LinkTypeField.REFERENCE) {\n if (wrappingKeyId) {\n throw new KcBadArgumentException(\n 'Do not specify wrappingKeyId when link type is REFERENCE.'\n );\n }\n return {\n directoryId,\n linkType,\n };\n } else {\n // If directory's key is not already in the key graph, then need to\n // fetch the directory's key.\n const wrappingKey = await this.getDirectoryKey(\n directoryId,\n wrappingKeyId\n );\n\n return {\n directoryId,\n wrappingKeyId: wrappingKey.id,\n wrappedKey: await this.keyGraph.wrapKey(wrappingKey, newKey),\n linkType,\n };\n }\n }\n\n private async getFileStateKeyId(fileStateNodeId: LrRelayIdInput) {\n return (\n await this.query({\n query: FileStateKeyQuery,\n variables: {\n id: fileStateNodeId,\n },\n })\n ).fileState.keyId;\n }\n\n private async prepareCreateFileState(\n fileKey: JWK.Key,\n options: CreateFileOptions | UpdateFileOptions\n ) {\n // Each version of the file is encrypted using a new key.\n const fileStateKey = await this.keyFactory.createKey();\n\n const fileContent =\n options.file && (await this.fileUploadService.loadFile(options.file));\n\n let contentResource: string;\n if (fileContent) {\n const cipherFileContent = await this.keyGraph.encryptToString(\n fileStateKey,\n fileContent\n );\n if (options.upload) {\n contentResource = await options.upload(cipherFileContent);\n } else {\n contentResource = await this.fileUploadService.uploadEncryptedFile({\n encryptedContent: cipherFileContent,\n });\n }\n }\n\n return {\n ...(await this.prepareItem(fileStateKey, options)),\n wrappedStateKey: await this.keyGraph.wrapKey(fileKey, fileStateKey),\n contentResource,\n };\n }\n\n private async prepareChangeItemParents(\n options: ChangeItemParentsOptions,\n itemKey: JWK.Key\n ) {\n const parentsToAdd = options.parentsToAdd\n ? await Promise.all(\n options.parentsToAdd.map((t) =>\n this.prepareParentDirectory(t, itemKey)\n )\n )\n : [];\n\n return {\n directoriesToRemove: options.parentsToRemove || [],\n directoriesToAdd: parentsToAdd,\n };\n }\n\n private async prepareItem(\n key: JWK.Key,\n options: { plainMetaJson?: JSONObject; cipherMetaClearJson?: JSONObject }\n ) {\n const { plainMetaJson, cipherMetaClearJson } = options;\n\n return {\n plainMeta: plainMetaJson && JSON.stringify(plainMetaJson),\n cipherMeta:\n cipherMetaClearJson &&\n (await this.keyGraph.encryptToString(key, cipherMetaClearJson)),\n };\n }\n\n private async prepareCreateDirectory(options: CreateDirectoryOptions) {\n const directoryKey = await this.keyFactory.createKey();\n options.parentDirectories = options.parentDirectories || [];\n if (!options.asRootDirectory && !options.parentDirectories?.length) {\n throw new KcBadArgumentException(\n 'A new directory must be either a root directory or a sub-directory. So you must provide either parentDirectories or asRootDirectory parameter.'\n );\n }\n\n if (options.asRootDirectory && options.parentDirectories?.length) {\n throw new KcBadArgumentException(\n 'A new directory must be either a root directory or a sub-directory. So you can only provide either parentDirectories or asRootDirectory parameter.'\n );\n }\n\n const parentDirectories = await Promise.all(\n options.parentDirectories?.map((t) =>\n this.prepareParentDirectory(t, directoryKey)\n )\n );\n\n // TODO this is rather an unfortunate name, change it to asRootDirectory.\n let parentRootDirectory: ParentRootDirectoryInput;\n if (options.asRootDirectory) {\n const rootKey = this.keyService.currentRootKey;\n parentRootDirectory = {\n wrappingKeyId: rootKey.id,\n wrappedKey: await this.keyGraph.wrapKey(rootKey, directoryKey),\n };\n }\n\n const itemInput = await this.prepareItem(directoryKey, options);\n\n return {\n ...itemInput,\n parentDirectories,\n parentRootDirectory,\n };\n }\n\n private async prepareUpdateDirectory(options: UpdateDirectoryOptions) {\n const directoryKey = await this.getDirectoryKey(\n options.directoryId,\n options.directoryKeyId\n );\n\n const itemInput = await this.prepareItem(directoryKey.jwk, options);\n\n return {\n ...itemInput,\n directoryId: options.directoryId,\n };\n }\n\n private async prepareCreateFile(options: CreateFileOptions) {\n const fileKey = await this.keyFactory.createKey();\n\n const parentDirectories = await Promise.all(\n options.parentDirectories.map((t) =>\n this.prepareParentDirectory(t, fileKey)\n )\n );\n\n const input = await this.prepareCreateFileState(fileKey, options);\n\n return {\n ...input,\n parentDirectories,\n };\n }\n\n private async prepareUpdateFile(options: UpdateFileOptions) {\n const fileKey = await this.getFileKey(options.fileId, options.fileKeyId);\n const input = await this.prepareCreateFileState(fileKey.jwk, options);\n\n return {\n ...input,\n fileId: options.fileId,\n };\n }\n\n private async prepareChangeDirectoryParents(\n options: ChangeDirectoryParentsOptions\n ) {\n const directoryKey = await this.getDirectoryKey(\n options.directoryId,\n options.directoryKeyId\n );\n\n const input = await this.prepareChangeItemParents(\n options,\n directoryKey.jwk\n );\n\n return {\n ...input,\n directoryId: options.directoryId,\n };\n }\n\n private async prepareChangeFileParents(options: ChangeFileParentsOptions) {\n const fileKey = await this.getFileKey(options.fileId, options.fileKeyId);\n\n const input = await this.prepareChangeItemParents(options, fileKey.jwk);\n\n return {\n ...input,\n fileId: options.fileId,\n };\n }\n\n private onLogout() {\n // Clear all cached data.\n this.tempDirectory = null;\n }\n}\n","import { Injectable, Injector, NgZone } from '@angular/core';\nimport { JWK } from 'node-jose';\nimport { LrMutation, LrService } from '../api/lr-graphql';\nimport {\n ContactCardSharedCipherData,\n JSONObject,\n OtKeyCipherClearJson2,\n} from '../api/types';\nimport { OwnerPlainDataJson } from '../contact-card/contact-card2.service';\nimport {\n EncryptionService,\n JoseSerialization,\n} from '../encryption/encryption.service';\nimport { KeyFactoryService } from '../key/key-factory.service';\nimport { KeyGraphService } from '../key/key-graph.service';\nimport { KeyService } from '../key/key.service';\nimport { KcCodeMismatchException } from '../_common/exceptions';\nimport { RunOutsideAngular } from '../_common/run-outside-angular';\nimport {\n CancelKeyExchangeMutation,\n CompleteKeyExchangeOtkMutation,\n CurrentUserSharedKeyQuery2,\n DeclineKeyExchangeMutation,\n InitiateKeyExchangeOtkMutation,\n KeyExchangeFieldsResult,\n KeyExchangeQuery2,\n KeyExchangesQuery2,\n KeyExchangeState2,\n KeyExchangeTokenQuery2,\n RespondKeyExchangeOtkMutation,\n} from './key-exchange.gql';\n\n/**\n * The decrypted content of the one-time key cipher;\n * When user supplies this information the lib doesn't need to do another API call\n * to fetch the key exchange node. And since the typical use case is to display\n * some information to the user, the key exchange node would already have been\n * fetched and decrypted.\n */\nexport interface DecryptedOtk2 {\n otKeyCipherClearJson: OtKeyCipherClearJson2;\n otKey: JWK.Key; // The one-time key\n}\n\nexport interface ContactCardReceiverCipherData {\n // The receiver of the contact card keeps a copy\n // of the owner's contact card information, encrypted using the receiver's keys. So that when\n // the owner decides to update their shared contact card at a later date, the receiver can\n // compare against the original contact card sent during key exchange. This way, the owner\n // can't unilaterally update their shared contact card without the receiver knowing about it.\n receiverCipherDataClearJson: JSONObject;\n}\n\nexport interface ContactCardOwnerPlainData {\n // Accessible by the server and the owner. Server side notification emails need to know some\n // information about the owner.\n // The owner could either be the initiator or the responder.\n ownerPlainDataJson: OwnerPlainDataJson;\n}\n\nexport interface ContactCardOwnerCipherData {\n // Owner only access to this data\n ownerCipherDataClearJson: JSONObject;\n}\n\n/**\n * Sending contact card information from the owner to the receiver.\n */\nexport type SendContactCardInput = ContactCardOwnerPlainData &\n ContactCardOwnerCipherData &\n ContactCardSharedCipherData;\n\nexport interface InitiateOtkInput2 {\n // Note that if neither email nor responderUsername are given, the one-time key\n // can still be sent to the responder via OOB\n email?: string;\n message?: JSONObject;\n contactCard?: SendContactCardInput;\n // If True, to upgrade an email invite to an existing user invite if the email\n // is already associated with an existing user.\n upgrade?: boolean;\n}\n\nexport interface RespondOtkInput2 {\n keyExchangeId: string;\n token: string;\n decryptedOtk: DecryptedOtk2;\n message?: JSONObject;\n // The initiator is the owner fo the initiatorContactCard, the responder\n // is the receiver.\n initiatorContactCard?: ContactCardReceiverCipherData;\n responderContactCard?: SendContactCardInput;\n}\n\nexport interface CompleteOtkInput2 {\n keyExchangeId: string;\n // This is a part of the key exchange data. It's encrypted using the root key\n initiatorRootKeyCipher: string;\n // This is a part of the key exchange data. It's encrypted using the one-time key.\n initiatorOneTimePbkCipher: string;\n // The responder is the owner fo the responderContactCard, the initiator\n // is the receiver.\n responderContactCard?: ContactCardReceiverCipherData;\n // The initiator can update the cipher data that are only visible to them. It makes\n // less sense to update the shared data because the responder would have already seen\n // the shared data and accepted that it's legit.\n // But in any case, the initiator can update the shared contact card info at any time.\n initiatorContactCard?: ContactCardOwnerCipherData;\n}\n\nexport interface InitiatorRootKeyCipherClearJson2 {\n nonce: string;\n oneTimePrk: Record<string, JSONObject>; // one-time public encryption key responder use to send data back to initiator\n otKey: Record<string, JSONObject>; // one-time symmetric key that needs to be shared OOB\n initiatorContactCard?: ContactCardOwnerCipherData &\n ContactCardSharedCipherData;\n initiator: {\n message?: JSONObject;\n contactCard?: ContactCardSharedCipherData;\n };\n}\n\nexport interface InitiatorOneTimePbkCipherClearJson {\n nonce: string;\n sharedKey: Record<string, JSONObject>;\n mkSharedKey: Record<string, JSONObject>;\n responder: {\n pbk: Record<string, JSONObject>;\n sigPbk: Record<string, JSONObject>;\n message?: JSONObject;\n contactCard?: ContactCardSharedCipherData & {\n // Note that this is _not_ the same key as the sharedKey. The sharedKey wraps\n // this key in the key graph. But because this key has not been entered into\n // the key graph when the responder calls the API, we pass the JWK directly here.\n sharedCipherKey: Record<string, JSONObject>;\n };\n };\n}\n\nexport interface GetKeyExchangeOptions2 {\n // The otKey as a raw string. i.e. key.toJSON(true).k\n otKeyK?: string;\n // User need the token if they have not responded to the key exchange yet.\n // Once they've responded (hence proven they have the OOB Key) they become\n // the \"responder\" of this exchange, and can access it when signed in.\n token?: string;\n}\n\n@RunOutsideAngular({\n ngZoneName: 'ngZone',\n})\n@Injectable({\n providedIn: 'root',\n})\nexport class KeyExchangeService extends LrService {\n private readonly CLIENT_NONCE_LENGTH = 32;\n\n constructor(\n private ngZone: NgZone,\n private injector: Injector,\n private keyFactory: KeyFactoryService,\n private keyService: KeyService,\n private encryptionService: EncryptionService,\n private keyGraph: KeyGraphService\n ) {\n super(injector);\n }\n\n private async getOtKey(\n keyExchange: KeyExchangeFieldsResult,\n otKeyK?: string\n ): Promise<JWK.Key> {\n if (otKeyK) {\n return await KeyFactoryService.asKey({\n ...JSON.parse(keyExchange.otk.otKeyParams),\n k: otKeyK,\n });\n } else if (\n keyExchange.otk.state === 'OTK_INITIATED' &&\n !keyExchange.isInitiator &&\n keyExchange.otk.responderPbkCipher\n ) {\n // Assuming existing user getting invited where OTK is wrapped in responder's public key.\n const prk = this.keyService.currentPxk;\n const decryptedCipher = await this.encryptionService.decrypt(\n prk.jwk,\n JSON.parse(keyExchange.otk.responderPbkCipher),\n {\n serializations: [JoseSerialization.COMPACT],\n }\n );\n if (decryptedCipher.otKey) {\n return await KeyFactoryService.asKey(decryptedCipher.otKey);\n }\n }\n return null;\n }\n\n private async decryptOtk(\n keyExchange: KeyExchangeFieldsResult,\n otKeyK?: string\n ): Promise<KeyExchangeFieldsResult> {\n const otKey = await this.getOtKey(keyExchange, otKeyK);\n\n let otk = keyExchange.otk;\n\n if (otKey && otk.otKeyCipher) {\n otk = {\n ...otk,\n otKey,\n otKeyCipherClearJson: await this.encryptionService.decrypt(\n otKey,\n keyExchange.otk.otKeyCipher\n ),\n };\n }\n\n return {\n ...keyExchange,\n otk,\n };\n }\n\n private async decryptResponseCipher(\n otKey: JWK.Key,\n otPrk: JWK.Key,\n content: JSONObject\n ): Promise<InitiatorOneTimePbkCipherClearJson> {\n // The response could be wrapped by the OtK in addition to the OtPbk\n try {\n content = await this.encryptionService.decrypt(otKey, content);\n } catch (error) {\n if (error.message !== 'no key found') {\n throw error;\n }\n // Do nothing to support older versions where message is not wrapped with otk.\n }\n\n // The Prk is single-use and only used to send information from the responder back to the initiator.\n return await this.encryptionService.decrypt(otPrk, content);\n }\n\n private async decryptKeyExchangeAsInitiator(\n keyExchange: KeyExchangeFieldsResult\n ): Promise<KeyExchangeFieldsResult> {\n const rootKey = this.keyService.currentRootKey;\n\n // Decrypt using the root key to get the Prk\n const initiatorRootKeyCipherClearJson =\n (await this.encryptionService.decrypt(\n rootKey.jwk,\n keyExchange.initiatorRootKeyCipher\n )) as InitiatorRootKeyCipherClearJson2;\n\n const otKey = await KeyFactoryService.asKey(\n initiatorRootKeyCipherClearJson.otKey\n );\n\n keyExchange = {\n ...keyExchange,\n initiatorRootKeyCipherClearJson,\n };\n\n let otk = keyExchange.otk;\n\n if (otk.initiatorOneTimePbkCipher) {\n otk = {\n ...otk,\n initiatorOneTimePbkCipherClearJson: await this.decryptResponseCipher(\n otKey,\n await KeyFactoryService.asKey(\n initiatorRootKeyCipherClearJson.oneTimePrk\n ),\n otk.initiatorOneTimePbkCipher\n ),\n };\n }\n\n if (otk.otKeyCipher) {\n otk.otKeyCipherClearJson = await this.encryptionService.decrypt(\n otKey,\n otk.otKeyCipher\n );\n }\n\n return {\n ...keyExchange,\n otk,\n };\n }\n\n private async decryptKeyExchangeAsResponder(\n keyExchange: KeyExchangeFieldsResult,\n otKeyK?: string\n ) {\n return this.decryptOtk(keyExchange, otKeyK);\n }\n\n async decryptKeyExchange(\n keyExchange: KeyExchangeFieldsResult,\n otKeyK?: string\n ) {\n if (keyExchange.isInitiator) {\n return this.decryptKeyExchangeAsInitiator(keyExchange);\n } else {\n return this.decryptKeyExchangeAsResponder(keyExchange, otKeyK);\n }\n }\n\n async getKeyExchanges({ state }: { state?: KeyExchangeState2 } = {}) {\n const { keyExchanges } = await this.query({\n query: KeyExchangesQuery2,\n variables: {\n state,\n },\n });\n\n return Promise.all(\n keyExchanges.edges.map((edge) => this.decryptKeyExchange(edge.node))\n );\n }\n\n /**\n * @param id If the current user can responder the key exchange if they are either the initiator or the receiver.\n * @param token If not signed in, or not the initiator or responder, 'token' must be given.\n * @param otKeyK Is the raw one-time key (string). If the responder is explicitly specified at time of initiation, then\n * it's possible to have the otKey wrapped by the public key of the responder. In which case, the otKeyK is not needed.\n */\n async getKeyExchange(\n id: string,\n { otKeyK, token }: GetKeyExchangeOptions2 = {}\n ) {\n const res = await this.query({\n query: token ? KeyExchangeTokenQuery2 : KeyExchangeQuery2,\n variables: {\n id,\n token,\n },\n includeKeyGraph: !token, // if !token then we are post auth, so can fetch keyGraph\n });\n return this.decryptKeyExchange(res.keyExchange, otKeyK);\n }\n\n public async getCurrentUserSharedKey(input: {\n username?: string;\n userId?: string;\n }) {\n return this.query({\n query: CurrentUserSharedKeyQuery2,\n variables: {\n username: input.username,\n userId: input.userId,\n },\n });\n }\n\n cancelKeyExchange(id: string) {\n return this.mutate(this.cancelKeyExchangeMutation(id));\n }\n\n cancelKeyExchangeMutation(id: string) {\n return new LrMutation({\n mutation: CancelKeyExchangeMutation,\n variables: {\n input: {\n id,\n },\n },\n });\n }\n\n declineKeyExchange(id: string, token: string) {\n return this.mutate(this.declineKeyExchangeMutation(id, token));\n }\n\n declineKeyExchangeMutation(id: string, token: string) {\n return new LrMutation({\n mutation: DeclineKeyExchangeMutation,\n variables: {\n input: {\n id,\n token,\n },\n },\n });\n }\n\n async initiateOtk(input: InitiateOtkInput2 = {}) {\n return this.mutate((await this.initiateOtkMutation(input)).lrMutation);\n }\n\n async initiateOtkMutation({\n message,\n email,\n contactCard,\n upgrade,\n }: InitiateOtkInput2 = {}) {\n const otKey = await this.keyFactory.createKey();\n const nonce = this.keyFactory.randomString(this.CLIENT_NONCE_LENGTH);\n\n // New PKC key for encryption. This key is used only once when the responder sends\n // back their signing public key.\n const initiatorOneTimePrk = await this.keyFactory.createPkcKey();\n\n // Option 1: New PKC key for signing\n // const initiatorSigPrk = await this.keyService.createPkcSignKey();\n\n // Option 2: Use the user's global signing key.\n // This key is used to prove the initiator's identity.\n const initiatorPrk = this.keyService.currentPxk;\n const initiatorSigPrk = this.keyService.currentSigPxk;\n\n let initiatorPlainDataSig: string = null;\n\n if (contactCard && contactCard.ownerPlainDataJson) {\n initiatorPlainDataSig = await this.encryptionService.signToString(\n initiatorSigPrk.jwk,\n contactCard.ownerPlainDataJson\n );\n }\n\n const initiator = {\n message,\n contactCard: contactCard && {\n sharedCipherDataClearJson: contactCard.sharedCipherDataClearJson,\n },\n };\n\n // Content to be encrypted using the OTK.\n const plainOtKeyCipher: OtKeyCipherClearJson2 = {\n // TODO Make sure we also put the OOB code in here as well since the OOB code is the\n // _only_ information the KC server does not have access to. The server may have\n // access to OTK and hence the nonce here. It's good to have both the nonce and OOB code\n // since the user may not be using the OOB code. And it's simple to always include\n // the nonce, so why not.\n nonce,\n initiator: {\n ...initiator,\n oneTimePbk: initiatorOneTimePrk.toJSON(), // one-time public encryption key responder use to send data back to initiator\n pbk: initiatorPrk.jwk.toJSON(), // public encryption key\n sigPbk: initiatorSigPrk.jwk.toJSON(), // public signing key\n },\n };\n\n const otKeyCipher = await this.keyGraph.encryptToString(\n otKey,\n plainOtKeyCipher\n );\n\n // Content to be encrypted using the initiator's root key.\n const initiatorRootKeyCipherClearJson: InitiatorRootKeyCipherClearJson2 = {\n nonce,\n oneTimePrk: initiatorOneTimePrk.toJSON(true),\n // Should not need to keep this encrypted since we are using the global signing key.\n // sigPrk: initiatorSigPrk.toJSON(true),\n\n // Save it in case the initiator want to decode the otKeyCipher.\n // Since the otKey is only used once, and that otKeyCipher contains only\n // the public key of the initiator, it's safe just leave the otKey stored here.\n otKey: otKey.toJSON(true),\n // These should be storing information such as how the fields of the shared contact card is\n // derived from the master contact card.\n initiatorContactCard: contactCard,\n initiator,\n };\n\n const rootKey = this.keyService.currentRootKey;\n const initiatorRootKeyCipher = await this.keyGraph.encryptToString(\n rootKey.jwk,\n initiatorRootKeyCipherClearJson\n );\n\n // The raw OTK\n const otKeyK: string = (otKey.toJSON(true) as JSONObject).k;\n\n // API call\n const lrMutation = new LrMutation({\n mutation: InitiateKeyExchangeOtkMutation,\n variables: {\n input: {\n // These will be stored on the server\n initiatorRootKeyCipher,\n initiatorPxkId: initiatorPrk.id,\n initiatorSigPxkId: initiatorSigPrk.id,\n // These will be sent to the responder\n otKeyParams: JSON.stringify(otKey.toJSON()),\n otKeyCipher,\n sendEmail: email && {\n email,\n rawOtKey: otKeyK,\n },\n createTp: true,\n initiatorPlainDataSig,\n upgrade,\n },\n },\n });\n\n return { lrMutation, otKeyK };\n }\n\n respondOtk(input: RespondOtkInput2) {\n return this.mutate(this.respondOtkMutation(input));\n }\n\n async respondOtkMutation({\n keyExchangeId,\n token,\n decryptedOtk,\n message,\n initiatorContactCard,\n responderContactCard,\n }: RespondOtkInput2) {\n const rootKey = this.keyService.currentRootKey;\n\n const masterKey = this.keyService.currentMasterKey;\n\n const sharedKey = await this.keyFactory.createKey();\n const mkSharedKey = await this.keyFactory.createKey();\n\n const rkWrappedSharedKey = await this.encryptionService.encrypt(\n rootKey.jwk,\n sharedKey.toJSON(true)\n );\n const mkWrappedMkSharedKey = await this.encryptionService.encrypt(\n masterKey.jwk,\n mkSharedKey.toJSON(true)\n );\n\n const initiatorOneTimePbk = await KeyFactoryService.asKey(\n decryptedOtk.otKeyCipherClearJson.initiator.oneTimePbk\n );\n\n const initiatorPbk = await KeyFactoryService.asKey(\n decryptedOtk.otKeyCipherClearJson.initiator.pbk\n );\n const initiatorSigPbk = await KeyFactoryService.asKey(\n decryptedOtk.otKeyCipherClearJson.initiator.sigPbk\n );\n\n // Option 1: Using new Prk for each TP pair\n // Create a new public signing key for the responder.\n // const responderSigPrk = await this.keyService.createPkcSignKey()\n // const rkWrappedResponderSigPrk = await this.encrypt(rootKey, responderSigPrk.toJSON(true));\n\n // Option 2: Responder already has a signing Prk\n const responderPrk = this.keyService.currentPxk;\n const responderSigPrk = this.keyService.currentSigPxk;\n\n const signedInitiatorPbk = await this.encryptionService.sign(\n responderSigPrk.jwk,\n initiatorPbk.toJSON()\n );\n const signedInitiatorSigPbk = await this.encryptionService.sign(\n responderSigPrk.jwk,\n initiatorSigPbk.toJSON()\n );\n\n const initiatorOneTimePbkCipherClearJson: InitiatorOneTimePbkCipherClearJson =\n {\n nonce: decryptedOtk.otKeyCipherClearJson.nonce,\n sharedKey: sharedKey.toJSON(true),\n mkSharedKey: mkSharedKey.toJSON(true),\n responder: {\n pbk: responderPrk.jwk.toJSON(), // public key\n sigPbk: responderSigPrk.jwk.toJSON(), // public key\n message,\n },\n };\n\n let receivedCardInput;\n if (decryptedOtk.otKeyCipherClearJson.initiator.contactCard) {\n // Set the info about the initiator to be the ones sent by the initiator. We need th responder to do the encryption here\n // because the initiator does not have the shared key yet, and we want the responder to have a functional contact card after\n // this exchange. The initiator can double check the contact details are correct and sign it when it completes the exchange.\n const sharedCipherDataClearJson =\n decryptedOtk.otKeyCipherClearJson.initiator.contactCard\n .sharedCipherDataClearJson;\n\n // Create keys\n const receiverKey = await this.keyFactory.createKey();\n const ccSharedKey = await this.keyFactory.createKey();\n const sigPxk = this.keyService.currentSigPxk;\n\n receivedCardInput = {\n receiverWrappedKey: JSON.stringify(\n await this.encryptionService.encrypt(\n rootKey.jwk,\n receiverKey.toJSON(true)\n )\n ),\n receiverWrappingKeyId: rootKey.id,\n receiverCipherData: initiatorContactCard\n ? JSON.stringify(\n await this.encryptionService.encrypt(\n receiverKey,\n initiatorContactCard.receiverCipherDataClearJson\n )\n )\n : '',\n sharedWrappedKey: JSON.stringify(\n await this.encryptionService.encrypt(\n sharedKey,\n ccSharedKey.toJSON(true)\n )\n ),\n };\n\n const sharedCipherData = await this.encryptionService.encrypt(\n ccSharedKey,\n sharedCipherDataClearJson\n );\n receivedCardInput.sharedCipherDataSig = JSON.stringify(\n await this.encryptionService.sign(sigPxk.jwk, sharedCipherData)\n );\n receivedCardInput.sigPxkId = sigPxk.id;\n\n initiatorOneTimePbkCipherClearJson.responder.contactCard = {\n ...initiatorOneTimePbkCipherClearJson.responder.contactCard,\n sharedCipherKey: ccSharedKey.toJSON(true),\n };\n }\n\n let responderCardInput;\n if (responderContactCard) {\n // Create keys\n const ownerKey = await this.keyFactory.createKey();\n const ccSharedKey = await this.keyFactory.createKey();\n const sigPxk = this.keyService.currentSigPxk;\n\n responderCardInput = {\n ownerWrappedKey: JSON.stringify(\n await this.encryptionService.encrypt(\n rootKey.jwk,\n ownerKey.toJSON(true)\n )\n ),\n ownerWrappingKeyId: rootKey.id,\n ownerCipherData: responderContactCard.ownerCipherDataClearJson\n ? JSON.stringify(\n await this.encryptionService.encrypt(\n ownerKey,\n responderContactCard.ownerCipherDataClearJson\n )\n )\n : '',\n\n sharedWrappedKey: JSON.stringify(\n await this.encryptionService.encrypt(\n sharedKey,\n ccSharedKey.toJSON(true)\n )\n ),\n };\n\n const sharedCipherData = await this.encryptionService.encrypt(\n ccSharedKey,\n responderContactCard.sharedCipherDataClearJson\n );\n responderCardInput.sharedCipherDataSig = JSON.stringify(\n await this.encryptionService.sign(sigPxk.jwk, sharedCipherData)\n );\n responderCardInput.sigPxkId = sigPxk.id;\n\n if (responderContactCard.ownerPlainDataJson) {\n responderCardInput.ownerPlainDataSig = JSON.stringify(\n await this.encryptionService.sign(\n responderSigPrk.jwk,\n responderContactCard.ownerPlainDataJson\n )\n );\n }\n\n // Contact card info readable by the initiator\n initiatorOneTimePbkCipherClearJson.responder.contactCard = {\n ...initiatorOneTimePbkCipherClearJson.responder.contactCard,\n sharedCipherDataClearJson:\n responderContactCard.sharedCipherDataClearJson,\n };\n }\n\n // Encrypt with one-time public key\n let initiatorOneTimePbkCipher = await this.encryptionService.encrypt(\n initiatorOneTimePbk,\n initiatorOneTimePbkCipherClearJson\n );\n\n // Encrypt with the otk again to keep use of asymmetric keys to a minimum.\n initiatorOneTimePbkCipher = await this.encryptionService.encrypt(\n decryptedOtk.otKey,\n initiatorOneTimePbkCipher\n );\n\n return new LrMutation({\n mutation: RespondKeyExchangeOtkMutation,\n variables: {\n input: {\n keyExchangeId,\n keyExchangeToken: token,\n rootKeyId: rootKey.id,\n masterKeyId: masterKey.id,\n // These will be stored on the server\n responderPxkId: responderPrk.id,\n responderSigPxkId: responderSigPrk.id,\n signedInitiatorPbk: JSON.stringify(signedInitiatorPbk),\n signedInitiatorSigPbk: JSON.stringify(signedInitiatorSigPbk),\n // rkWrappedInitiatorSigPbk: JSON.stringify(rkWrappedInitiatorSigPbk),\n\n // Option 1: Using new Prk for each TP pair\n // rkWrappedResponderSigPrk: JSON.stringify(rkWrappedResponderSigPrk),\n rkWrappedSharedKey: JSON.stringify(rkWrappedSharedKey),\n mkWrappedMkSharedKey: JSON.stringify(mkWrappedMkSharedKey),\n // These will be sent to the initiator\n initiatorOneTimePbkCipher: JSON.stringify(initiatorOneTimePbkCipher),\n initiatorContactCard: receivedCardInput,\n responderContactCard: responderCardInput,\n },\n },\n });\n }\n\n completeOtk(input: CompleteOtkInput2) {\n return this.mutate(this.completeOtkMutation(input));\n }\n\n async completeOtkMutation({\n keyExchangeId,\n initiatorRootKeyCipher,\n initiatorOneTimePbkCipher,\n responderContactCard,\n initiatorContactCard,\n }: CompleteOtkInput2) {\n const rootKey = this.keyService.currentRootKey;\n const masterKey = this.keyService.currentMasterKey;\n\n // Decrypt using the root key to get the Prk\n const initiatorRootKeyCipherClearJson =\n (await this.encryptionService.decrypt(\n rootKey.jwk,\n initiatorRootKeyCipher\n )) as InitiatorRootKeyCipherClearJson2;\n\n // The Prk is single-use and only used to send information from the responder back to the initiator.\n const plainInitiatorOneTimePbkCipher = await this.decryptResponseCipher(\n await KeyFactoryService.asKey(initiatorRootKeyCipherClearJson.otKey),\n await KeyFactoryService.asKey(initiatorRootKeyCipherClearJson.oneTimePrk),\n initiatorOneTimePbkCipher\n );\n\n // Check the nonce match to ensure the responder was the one holding the OTK\n if (\n initiatorRootKeyCipherClearJson.nonce !==\n plainInitiatorOneTimePbkCipher.nonce\n ) {\n throw new KcCodeMismatchException(\n 'The nonce returned by responder does not match with the one created by the initiator.'\n );\n }\n\n // Option 1: Assuming the signing key is unique between users.\n // const initiatorSigPrk = await KFS.asKey(ke.plainInitiatorRootKeyCipher.sigPrk);\n // const rkWrappedInitiatorSigPrk = await this.encrypt(rootKey, initiatorSigPrk.toJSON(true));\n\n // Option 2: Use the user's global signing key.\n // In this case the initiatorSigPrk is already a part of the key graph.\n // So there's nothing to do here.\n\n // Protected the signing public key of the responder.\n const initiatorSigPrk = this.keyService.currentSigPxk;\n const responderSigPbk = await KeyFactoryService.asKey(\n plainInitiatorOneTimePbkCipher.responder.sigPbk\n );\n const responderPbk = await KeyFactoryService.asKey(\n plainInitiatorOneTimePbkCipher.responder.pbk\n );\n\n const signedResponderPbk = await this.encryptionService.sign(\n initiatorSigPrk.jwk,\n responderPbk.toJSON()\n );\n const signedResponderSigPbk = await this.encryptionService.sign(\n initiatorSigPrk.jwk,\n responderSigPbk.toJSON()\n );\n\n const sharedKey = await KeyFactoryService.asKey(\n plainInitiatorOneTimePbkCipher.sharedKey\n );\n const rkWrappedSharedKey = await this.encryptionService.encrypt(\n rootKey.jwk,\n sharedKey.toJSON(true)\n );\n\n const mkSharedKey = await KeyFactoryService.asKey(\n plainInitiatorOneTimePbkCipher.mkSharedKey\n );\n const mkWrappedMkSharedKey = await this.encryptionService.encrypt(\n masterKey.jwk,\n mkSharedKey.toJSON(true)\n );\n\n let responderContactCardCipherInput;\n if (responderContactCard) {\n // Create key\n const receiverKey = await this.keyFactory.createKey();\n\n responderContactCardCipherInput = {\n receiverWrappedKey: JSON.stringify(\n await this.encryptionService.encrypt(\n rootKey.jwk,\n receiverKey.toJSON(true)\n )\n ),\n receiverWrappingKeyId: rootKey.id,\n receiverCipherData: JSON.stringify(\n await this.encryptionService.encrypt(\n receiverKey,\n responderContactCard.receiverCipherDataClearJson\n )\n ),\n };\n }\n\n // Get the data needed from the initiator's cipher data.\n let initiatorContactCardCipherInput;\n let initiatorContactCardSharedCipherInput;\n if (initiatorRootKeyCipherClearJson.initiatorContactCard) {\n // The initiatorContactCard created during the creation of the invite and encrypted using the initiator's\n // root key\n const initiatorContactCardFromInit =\n initiatorRootKeyCipherClearJson.initiatorContactCard;\n const ownerKey = await this.keyFactory.createKey();\n const sharedCipherKey = await KeyFactoryService.asKey(\n plainInitiatorOneTimePbkCipher.responder.contactCard.sharedCipherKey\n );\n\n const ownerWrappedKey = JSON.stringify(\n await this.encryptionService.encrypt(rootKey.jwk, ownerKey.toJSON(true))\n );\n\n // Allow the initiatorContactCard parameter to override\n const ownerCipherDataClearJson =\n initiatorContactCard?.ownerCipherDataClearJson ||\n initiatorContactCardFromInit.ownerCipherDataClearJson;\n\n const ownerCipherData = ownerCipherDataClearJson\n ? await this.keyGraph.encryptToString(\n ownerKey,\n ownerCipherDataClearJson\n )\n : '';\n\n initiatorContactCardCipherInput = {\n ownerWrappedKey,\n ownerWrappingKeyId: rootKey.id,\n ownerCipherData,\n };\n\n initiatorContactCardSharedCipherInput = {\n sigPxkId: initiatorSigPrk.id,\n };\n\n const sharedCipherData = await this.encryptionService.encrypt(\n sharedCipherKey,\n initiatorContactCardFromInit.sharedCipherDataClearJson\n );\n initiatorContactCardSharedCipherInput.sharedCipherDataSig =\n JSON.stringify(\n await this.encryptionService.sign(\n initiatorSigPrk.jwk,\n sharedCipherData\n )\n );\n }\n\n // TODO ideally we update the shared data in the contact card sent to the responder as well since that\n // CC was created by the responder.\n\n return new LrMutation({\n mutation: CompleteKeyExchangeOtkMutation,\n variables: {\n input: {\n keyExchangeId,\n rootKeyId: rootKey.id,\n masterKeyId: masterKey.id,\n initiatorSigPxkId: initiatorSigPrk.id,\n signedResponderPbk: JSON.stringify(signedResponderPbk),\n signedResponderSigPbk: JSON.stringify(signedResponderSigPbk),\n rkWrappedSharedKey: JSON.stringify(rkWrappedSharedKey),\n mkWrappedMkSharedKey: JSON.stringify(mkWrappedMkSharedKey),\n responderContactCardCipher: responderContactCardCipherInput,\n initiatorContactCardCipher: initiatorContactCardCipherInput,\n initiatorContactCardSharedCipher:\n initiatorContactCardSharedCipherInput,\n },\n },\n });\n }\n}\n","/* eslint-disable @typescript-eslint/no-explicit-any */\nimport { HttpClient } from '@angular/common/http';\nimport { Inject, Injectable } from '@angular/core';\nimport { AuthClass } from '@aws-amplify/auth/lib-esm/Auth';\nimport gql from 'graphql-tag';\nimport { JWK } from 'node-jose';\nimport { Slip39Helper } from 'slip39';\nimport { LrApolloService } from '../api/lr-apollo.service';\nimport { EncryptionService } from '../encryption/encryption.service';\nimport { KeyFactoryService as KFS } from '../key/key-factory.service';\nimport { KeyService } from '../key/key.service';\nimport { PassKeyParams } from '../key/key.types';\nimport { KcConfig, KC_CONFIG } from '../life-ready.config';\nimport { PasswordService } from '../password/password.service';\nimport {\n KcBadLogicException,\n KcError,\n KcException,\n KcInternalErrorException,\n} from '../_common/exceptions';\n\nexport const ERROR_SOURCE = 'LBOP';\nexport enum KcLbopErrorCode {\n INVALID_PASSPHRASE = 'INVALID_PASSPHRASE',\n}\n\ninterface SetPasswordApiResult {\n username: string;\n idpPassword: string;\n setPasswordToken: string;\n}\n\nexport interface SetPasswordParams {\n lbopId: string;\n newPassword: CryptoKey;\n verifiedToken: string;\n masterKeyId: string;\n masterKey: JWK.Key;\n}\n\nexport interface VerifyContactParams {\n email?: string;\n phone?: string;\n}\n\nexport interface VerifyContactResult {\n // The claim_id identifies the Email/SMS confirmation\n claimId: string;\n}\n\nexport interface ConfirmContactParams {\n claimId: string;\n vCode: string;\n}\n\nexport interface ConfirmContactResult {\n // The token to prove the client had the correct confirmation code.\n token: string;\n}\n\nexport interface VerifyParams {\n claimId: string;\n claimToken: string;\n lbop: string;\n}\n\nexport interface VerifyResult {\n // userId: string;\n lbopId: string;\n verifiedToken: string;\n masterKeyId: string;\n masterKey: JWK.Key;\n}\n\nexport interface ChallengeResultLbop {\n lbopId: string;\n lbopKeyParams: PassKeyParams;\n wrappedLbopKeyVerifier: any;\n}\n\nexport interface ChallengeResult {\n challenge: {\n serverNonce: string;\n };\n lbops: ChallengeResultLbop[];\n}\n\nexport interface Lbop {\n id: string;\n partial?: string;\n name?: string;\n lbopString?: string;\n}\n\nexport interface CreateLbopParams {\n name?: string;\n}\n\ninterface CreateLbopQuery {\n createLbop: {\n lbop: Lbop;\n };\n}\n\nexport const CreateLbopQuery = gql`\n mutation CreateLbop($input: CreateLbopInput!) {\n createLbop(input: $input) {\n lbop {\n id\n }\n }\n }\n`;\n\ninterface DeleteLbopQuery {\n deleteLbop: Lbop;\n}\n\nexport const DeleteLbopQuery = gql`\n mutation DeleteLbop($input: DeleteLbopInput!) {\n deleteLbop(input: $input) {\n id\n }\n }\n`;\n\nexport interface UpdateLbopParams {\n id: string;\n name: string;\n}\n\ninterface UpdateLbopQuery {\n updateLbop: Lbop;\n}\n\nexport const UpdateLbopQuery = gql`\n mutation UpdateLbop($input: UpdateLbopInput!) {\n updateLbop(input: $input) {\n lbop {\n id\n }\n }\n }\n`;\n\nexport const LbopQuery = gql`\n query Lbop($id: LrRelayIdInput!) {\n lbop(id: $id) {\n id\n cipherMeta\n }\n }\n`;\n\ninterface LbopsQuery {\n lbops: any;\n}\n\nexport const LbopsQuery = gql`\n query Lbops {\n lbops {\n edges {\n node {\n id\n cipherMeta\n }\n }\n }\n }\n`;\n\n@Injectable({\n providedIn: 'root',\n})\nexport class LbopService {\n private readonly CLIENT_NONCE_LENGTH = 32;\n // There are 1024 words (10 bits), so 25 words should give ~256 bits of entropy.\n private readonly LBOP_WORDS = 25;\n\n constructor(\n @Inject(KC_CONFIG) private config: KcConfig,\n private http: HttpClient,\n private lrApollo: LrApolloService,\n private auth: AuthClass,\n private keyFactory: KFS,\n private keyService: KeyService,\n private encryptionService: EncryptionService,\n private passwordService: PasswordService\n ) {}\n\n private getPartial(lbopString: string): string {\n return lbopString.split(' ')[0];\n }\n\n public async remove(id: string): Promise<string> {\n const res = await this.lrApollo.mutate<any>({\n mutation: DeleteLbopQuery,\n variables: {\n input: {\n id,\n },\n },\n });\n\n return res.deleteLbop.id;\n }\n\n public async update({ id, name }: UpdateLbopParams): Promise<Lbop> {\n const lbop = await this.get(id);\n lbop.name = name;\n\n const masterKey = this.keyService.currentMasterKey;\n const cipherMeta = await this.encryptionService.encrypt(\n masterKey.jwk,\n lbop\n );\n\n const res = await this.lrApollo.mutate<UpdateLbopQuery>({\n mutation: UpdateLbopQuery,\n variables: {\n input: {\n id,\n cipherMeta: JSON.stringify(cipherMeta),\n },\n },\n });\n\n return res.updateLbop;\n }\n\n public async get(id: string): Promise<Lbop> {\n const res = await this.lrApollo.query<any>({\n query: LbopQuery,\n variables: {\n id,\n },\n });\n\n const masterKey = this.keyService.currentMasterKey;\n\n const plainCipherMeta = await this.encryptionService.decrypt(\n masterKey.jwk,\n JSON.parse(res.lbop.cipherMeta)\n );\n\n return {\n id: res.id,\n ...plainCipherMeta,\n };\n }\n\n public async list(): Promise<Lbop[]> {\n const res = await this.lrApollo.query<LbopsQuery>({\n query: LbopsQuery,\n });\n\n const masterKey = await this.keyService.currentMasterKey;\n\n return Promise.all(\n res.lbops.edges.map(async (edge) => {\n const plainCipherMeta = await this.encryptionService.decrypt(\n masterKey.jwk,\n JSON.parse(edge.node.cipherMeta)\n );\n return {\n id: edge.node.id,\n ...plainCipherMeta,\n };\n })\n );\n }\n\n public async create({ name }: CreateLbopParams): Promise<Lbop> {\n if (Slip39Helper.WORD_LIST.length !== 1024) {\n throw new KcBadLogicException('Slip39Helper.WORD_LIST.length != 1024');\n }\n\n // Get existing to make sure there are not duplicate first words\n const lbops = await this.list();\n\n // Generate new one\n let lbopString: string;\n // eslint-disable-next-line no-constant-condition\n while (true) {\n lbopString = this.keyFactory\n .randomChoices(Slip39Helper.WORD_LIST, this.LBOP_WORDS)\n .join(' ');\n const partial = this.getPartial(lbopString);\n\n if (!lbops.some((lbop) => lbop.partial === partial)) {\n break;\n }\n }\n\n const lbopKeyParams = await this.keyFactory.createLbopKeyParams();\n const lbopKey = (\n await this.keyFactory.deriveLbopKey({\n password: await this.keyFactory.importPassword(lbopString),\n ...lbopKeyParams,\n })\n ).jwk;\n\n const lbopKeyVerifier = await this.keyFactory.createSignKey();\n const wrappedLbopKeyVerifier = await this.encryptionService.encrypt(\n lbopKey,\n lbopKeyVerifier.toJSON(true)\n );\n\n // Re-encrypt master key with new key\n const masterKey = this.keyService.currentMasterKey;\n const wrappedMasterKey = await this.encryptionService.encrypt(\n lbopKey,\n masterKey.jwk.toJSON(true)\n );\n\n const meta = {\n ...(name && { name }),\n partial: this.getPartial(lbopString),\n };\n const cipherMeta = await this.encryptionService.encrypt(\n masterKey.jwk,\n meta\n );\n\n const res = await this.lrApollo.mutate<CreateLbopQuery>({\n mutation: CreateLbopQuery,\n variables: {\n input: {\n cipherMeta: JSON.stringify(cipherMeta),\n lbopKeyParams: JSON.stringify(lbopKeyParams),\n lbopKeyVerifier: JSON.stringify(lbopKeyVerifier.toJSON(true)),\n wrappedLbopKeyVerifier: JSON.stringify(wrappedLbopKeyVerifier),\n masterKeyId: masterKey.id,\n wrappedMasterKey: JSON.stringify(wrappedMasterKey),\n },\n },\n });\n\n return {\n ...res.createLbop.lbop,\n lbopString,\n };\n }\n\n // --------------------------------------------------------------------------------------------------------------------\n // --------------------------------------------------------------------------------------------------------------------\n // Flow below are for password reset via LBOP\n //\n // --Potential Failure Point xxx--\n //\n // Look for the above and you can test by interrupting at these points.\n //\n // The LBOP reset process can be restarted at any point before the call to \"set-password/\". Once \"set-password/\" has been\n // called, we assume the client has a short period of time to change the Idp password to the one they've chosen. The \"set-password/\"\n // will set the Idp password to a temporary random password. The user can no longer login using their current password. If the Idp\n // password change process does not complete or takes longer than the lockout period, the account will not be accessible and a new\n // LBOP password reset must be carried out.\n // --------------------------------------------------------------------------------------------------------------------\n // --------------------------------------------------------------------------------------------------------------------\n private async verifyLbops(\n challengeResult: ChallengeResult,\n lbopString: string\n ): Promise<{\n lbop: ChallengeResultLbop;\n signedChallenge: any;\n lbopKey: JWK.Key;\n }> {\n const clientNonce = this.keyFactory.randomString(this.CLIENT_NONCE_LENGTH);\n\n for (const lbop of challengeResult.lbops) {\n const lbopKey = (\n await this.keyFactory.deriveLbopKey({\n password: await this.keyFactory.importPassword(lbopString),\n ...lbop.lbopKeyParams,\n })\n ).jwk;\n\n // If decoding successful then it's the correct lbop\n try {\n const lbopKeyVerifier = (await this.encryptionService.decrypt(\n lbopKey,\n lbop.wrappedLbopKeyVerifier\n )) as any;\n\n // Force a bad signature.\n // const serverNonce = challengeResult.challenge.serverNonce + \"1\",\n\n const serverNonce = challengeResult.challenge.serverNonce;\n\n const signedChallenge = await this.encryptionService.sign(\n lbopKeyVerifier,\n {\n serverNonce,\n clientNonce,\n }\n );\n\n return {\n lbop,\n signedChallenge,\n lbopKey,\n };\n } catch (error) {\n continue;\n }\n }\n throw new KcException(\n new KcError({\n source: ERROR_SOURCE,\n code: KcLbopErrorCode.INVALID_PASSPHRASE,\n message: 'Invalid passphrase.',\n })\n );\n }\n\n public async verifyContact(\n params: VerifyContactParams\n ): Promise<VerifyContactResult> {\n const ret = this.http\n .post<VerifyContactResult>(\n `${this.config.authUrl}users/lbop-reset/verify-contact/`,\n params\n )\n .toPromise();\n\n // --Potential Failure Point 1 --\n // The contact verifications are throttled. But otherwise harmless.\n\n return ret;\n }\n\n public async confirmContact(\n params: ConfirmContactParams\n ): Promise<ConfirmContactResult> {\n return this.http\n .post<ConfirmContactResult>(`${this.config.authUrl}cove/respond/`, {\n claim_id: params.claimId,\n v_code: params.vCode,\n })\n .toPromise();\n\n // --Potential Failure Point 2 --\n // A verified claim for a contact does not prevent new ones from being generated. So it should be fine to just start again.\n }\n\n public async verify(params: VerifyParams): Promise<VerifyResult> {\n const challengeResult = await this.http\n .post<ChallengeResult>(\n `${this.config.authUrl}users/lbop-reset/get-challenge/`,\n {\n claimId: params.claimId,\n claimToken: params.claimToken,\n }\n )\n .toPromise();\n\n // --Potential Failure Point 3 --\n // This does not lock anything. A second call to \"get-challenge/\" will create a new challenge amd invalidate the first one.\n const { signedChallenge, lbop, lbopKey } = await this.verifyLbops(\n challengeResult,\n params.lbop\n );\n\n const res = await this.http\n .post<any>(`${this.config.authUrl}users/lbop-reset/verify-challenge/`, {\n lbopId: lbop.lbopId,\n signedChallenge,\n })\n .toPromise();\n\n // --Potential Failure Point 4 --\n // This does not lock anything. So ok to restart.\n\n return {\n lbopId: lbop.lbopId,\n verifiedToken: res.verifiedToken,\n masterKeyId: res.masterKeyId,\n masterKey: await KFS.asKey(\n await this.encryptionService.decrypt(lbopKey, res.wrappedMasterKey)\n ),\n };\n }\n\n public async setPassword(params: SetPasswordParams): Promise<any> {\n // Generate the new password derived keys\n const passKeyBundle = await this.passwordService.createPassKeyBundle(\n params.newPassword\n );\n\n // Re-encrypt master key with new key\n const newWrappedMasterKey = await this.encryptionService.encrypt(\n passKeyBundle.passKey,\n params.masterKey.toJSON(true)\n );\n\n const result = await this.http\n .post<SetPasswordApiResult>(\n `${this.config.authUrl}users/lbop-reset/set-password/`,\n {\n lbopId: params.lbopId,\n verifiedToken: params.verifiedToken,\n masterKeyId: params.masterKeyId,\n newWrappedMasterKey,\n newPassKey: {\n passKeyParams: passKeyBundle.passKeyParams,\n passIdpParams: passKeyBundle.passIdpParams,\n passIdpVerifierPbk: passKeyBundle.passIdpVerifier.toJSON(),\n wrappedPassIdpVerifierPrk: passKeyBundle.wrappedPassIdpVerifierPrk,\n },\n }\n )\n .toPromise();\n\n // --Potential Failure Point 5 --\n // A timed mutex is locked. The Idp password change must occur within a period of time.\n // If interrupted here, the user can not login with their old password again. They must\n // start the whole LBOP password reset process again.\n\n // This call will go through the LR proxy which is OK since the LR server knows\n // the temporary password anyway.\n let user = await this.auth.signIn(result.username, result.idpPassword, {\n noProxy: 'true',\n });\n\n if (user.challengeName !== 'NEW_PASSWORD_REQUIRED') {\n throw new KcInternalErrorException(\n 'Expecting Cognito to have done a password reset.'\n );\n }\n\n // --Potential Failure Point 6 --\n // Must restart the LBOP password reset process again.\n\n // Set new password on Idp\n user = await this.auth.completeNewPassword(\n user,\n this.passwordService.getPassIdpString(passKeyBundle.passIdp),\n {}\n );\n\n // --Potential Failure Point 7 --\n // Must restart the LBOP password reset process again.\n\n await this.auth.signOut();\n\n return await this.http\n .post<any>(`${this.config.authUrl}users/lbop-reset/complete/`, {\n lbopId: params.lbopId,\n setPasswordToken: result.setPasswordToken,\n })\n .toPromise();\n }\n}\n","import { HttpClientModule } from '@angular/common/http';\nimport { APP_INITIALIZER, ModuleWithProviders, NgModule } from '@angular/core';\nimport Auth from '@aws-amplify/auth';\nimport { AuthClass } from '@aws-amplify/auth/lib-esm/Auth';\nimport { NgIdleKeepaliveModule } from '@ng-idle/keepalive';\nimport { APOLLO_OPTIONS } from 'apollo-angular';\nimport { configureAmplifyAuth } from './auth/auth.config';\nimport { configureApollo, KcConfig, KC_CONFIG } from './life-ready.config';\n\n@NgModule({\n imports: [HttpClientModule, NgIdleKeepaliveModule.forRoot()],\n})\nexport class LifeReadyModule {\n public static forRoot(\n config: KcConfig\n ): ModuleWithProviders<LifeReadyModule> {\n return {\n ngModule: LifeReadyModule,\n providers: [\n {\n provide: KC_CONFIG,\n useValue: config,\n },\n {\n provide: AuthClass,\n useValue: Auth,\n },\n {\n provide: APP_INITIALIZER,\n useFactory: configureAmplifyAuth,\n deps: [KC_CONFIG, AuthClass],\n multi: true,\n },\n {\n provide: APOLLO_OPTIONS,\n useFactory: configureApollo,\n deps: [KC_CONFIG, AuthClass],\n },\n ],\n };\n }\n}\n","import { gqlTyped } from '../_common/ast';\nimport { DateTime, ID } from '../api/types';\n\nexport interface UpdateNotificationMutationResult {\n updateNotification: {\n notification: {\n id: ID;\n };\n };\n}\nexport const UpdateNotificationMutation = gqlTyped<UpdateNotificationMutationResult>`\nmutation UpdateNotificationMutation($input: UpdateNotificationInput!) {\n updateNotification(input: $input) {\n notification {\n id\n }\n }\n}\n`;\n\nexport interface UpdateAllNotificationsReadStateMutationResult {\n updateAllNotificationsReadState: {\n count: number;\n };\n}\nexport const UpdateAllNotificationsReadStateMutation = gqlTyped<UpdateAllNotificationsReadStateMutationResult>`\nmutation UpdateAllNotificationsReadStateMutation($input: UpdateAllNotificationsReadStateInput!) {\n updateAllNotificationsReadState(input: $input) {\n count\n }\n}\n`;\n\nexport interface DebugCreateNotificationMutationResult {\n debugCreateNotification: {\n notification: {\n id: ID;\n };\n };\n}\nexport const DebugCreateNotificationMutation = gqlTyped<DebugCreateNotificationMutationResult>`\nmutation DebugCreateNotificationMutation($input: DebugCreateNotificationInput!) {\n debugCreateNotification(input: $input) {\n notification {\n id\n }\n }\n}\n`;\n\nexport interface DebugDeleteAllNotificationsMutationResult {\n debugDeleteAllNotifications: {\n count: number;\n };\n}\nexport const DebugDeleteAllNotificationsMutation = gqlTyped<DebugDeleteAllNotificationsMutationResult>`\nmutation DebugDeleteAllNotificationsMutation($input: DebugDeleteAllNotificationsInput!) {\n debugDeleteAllNotifications(input: $input) {\n count\n }\n}\n`;\n\nexport interface UpdateNotificationFeatureStateMutationResult {\n updateNotificationFeatureState: {\n featureState: {\n notificationsLastViewed: DateTime;\n };\n };\n}\nexport const UpdateNotificationFeatureStateMutation = gqlTyped<UpdateNotificationFeatureStateMutationResult>`\nmutation UpdateNotificationFeatureStateMutation($input: UpdateNotificationFeatureStateInput!) {\n updateNotificationFeatureState(input: $input) {\n featureState {\n notificationsLastViewed\n\t\t}\n }\n}\n`;\n","import { Injectable, Injector, NgZone } from '@angular/core';\nimport { LrMutation, LrService } from '../api/lr-graphql';\nimport { JSONObject } from '../api/types';\nimport { RunOutsideAngular } from '../_common/run-outside-angular';\nimport {\n DebugCreateNotificationMutation,\n DebugDeleteAllNotificationsMutation,\n UpdateAllNotificationsReadStateMutation,\n UpdateNotificationFeatureStateMutation,\n UpdateNotificationMutation,\n} from './notification.gql';\n\nexport interface UpdateNotificationOptions {\n notificationId: string;\n hasBeenRead: boolean;\n}\n\nexport interface UpdateAllNotificationsReadStateOptions {\n hasBeenRead: boolean;\n}\n\nexport interface DebugCreateNotificationOptions {\n receiverId: string;\n plainData?: Record<string, JSONObject>;\n plainMeta?: Record<string, JSONObject>;\n hasBeenRead?: boolean;\n timeRead?: Date;\n}\n\nexport interface DebugDeleteAllNotificationsOptions {\n receiverId: string;\n}\n\nexport interface UpdateNotificationFeatureStateOptions {\n lastViewed: Date | null;\n}\n\n@RunOutsideAngular({\n ngZoneName: 'ngZone',\n})\n@Injectable({\n providedIn: 'root',\n})\nexport class NotificationService extends LrService {\n constructor(private ngZone: NgZone, private injector: Injector) {\n super(injector);\n }\n\n async updateNotification(options: UpdateNotificationOptions) {\n return this.mutate(this.updateNotificationMutation(options));\n }\n\n async updateNotificationMutation(options: UpdateNotificationOptions) {\n return new LrMutation({\n mutation: UpdateNotificationMutation,\n variables: {\n input: {\n ...options,\n },\n },\n });\n }\n\n async updateAllNotificationsReadState(\n options: UpdateAllNotificationsReadStateOptions\n ) {\n return this.mutate(this.updateAllNotificationsReadStateMutation(options));\n }\n\n async updateAllNotificationsReadStateMutation(\n options: UpdateAllNotificationsReadStateOptions\n ) {\n return new LrMutation({\n mutation: UpdateAllNotificationsReadStateMutation,\n variables: {\n input: {\n ...options,\n },\n },\n });\n }\n\n async debugCreateNotification(options: DebugCreateNotificationOptions) {\n return this.mutate(this.debugCreateNotificationMutation(options));\n }\n\n async debugCreateNotificationMutation(\n options: DebugCreateNotificationOptions\n ) {\n return new LrMutation({\n mutation: DebugCreateNotificationMutation,\n variables: {\n input: {\n receiverId: options.receiverId,\n hasBeenRead: options.hasBeenRead,\n timeRead: options.timeRead?.toISOString(),\n plainData: JSON.stringify(options.plainData),\n plainMeta: JSON.stringify(options.plainMeta),\n },\n },\n });\n }\n\n async debugDeleteAllNotifications(\n options: DebugDeleteAllNotificationsOptions\n ) {\n return this.mutate(this.debugDeleteAllNotificationsMutation(options));\n }\n\n async debugDeleteAllNotificationsMutation(\n options: DebugDeleteAllNotificationsOptions\n ) {\n return new LrMutation({\n mutation: DebugDeleteAllNotificationsMutation,\n variables: {\n input: {\n receiverId: options.receiverId,\n },\n },\n });\n }\n\n async updateNotificationFeatureState(\n options: UpdateNotificationFeatureStateOptions\n ) {\n return this.mutate(this.updateNotificationFeatureStateMutation(options));\n }\n\n async updateNotificationFeatureStateMutation(\n options: UpdateNotificationFeatureStateOptions\n ) {\n return new LrMutation({\n mutation: UpdateNotificationFeatureStateMutation,\n variables: {\n input: {\n lastViewed: options.lastViewed?.toISOString(),\n clearLastViewed: options.lastViewed == null || undefined,\n },\n },\n });\n }\n}\n","import {\n ID,\n PaymentCaptureField,\n PaymentCardField,\n PaymentMethodNode,\n} from '../api/types';\nimport { gqlTyped } from '../_common/ast';\n\nexport interface InitiateStripePaymentMethodCaptureMutationResult {\n initiateStripePaymentMethodCapture: {\n paymentCapture: Required<PaymentCaptureField>;\n };\n}\nexport const InitiateStripePaymentMethodCaptureMutation = gqlTyped<InitiateStripePaymentMethodCaptureMutationResult>`\nmutation InitiateStripePaymentMethodCaptureMutation {\n initiateStripePaymentMethodCapture(input: {}) {\n paymentCapture {\n stripeIntentId\n stripeClientSecret\n }\n }\n}\n`;\n\nexport interface CompleteStripePaymentMethodCaptureMutationResult {\n completeStripePaymentMethodCapture: {\n // We don't have a DeepRequired implementation yet, so have to explicitly make\n // the child fields required.\n paymentMethod: Required<Omit<PaymentMethodNode, 'invoice'>> & {\n card: Required<PaymentCardField>;\n };\n };\n}\nexport const CompleteStripePaymentMethodCaptureMutation = gqlTyped<CompleteStripePaymentMethodCaptureMutationResult>`\nmutation CompleteStripePaymentMethodCaptureMutation($input: CompleteStripePaymentMethodCaptureInput!) {\n completeStripePaymentMethodCapture(input: $input) {\n paymentMethod {\n id\n created\n modified\n card {\n brand\n lastFourDigits\n expiryYear\n expiryMonth\n }\n isDefault \n }\n }\n}\n`;\n\nexport interface RemovePaymentMethodMutationResult {\n removePaymentMethod: {\n id: ID;\n };\n}\nexport const RemovePaymentMethodMutation = gqlTyped<RemovePaymentMethodMutationResult>`\nmutation RemovePaymentMethodMutation($input: RemovePaymentMethodInput!) {\n removePaymentMethod(input: $input) {\n id\n }\n}\n`;\n\nexport interface SetDefaultPaymentMethodMutationResult {\n setDefaultPaymentMethod: {\n paymentMethod: {\n id: ID;\n };\n };\n}\nexport const SetDefaultPaymentMethodMutation = gqlTyped<SetDefaultPaymentMethodMutationResult>`\nmutation SetDefaultPaymentMethodMutation($input: SetDefaultPaymentMethodInput!) {\n setDefaultPaymentMethod(input: $input) {\n paymentMethod {\n id\n } \n }\n}\n`;\n\nexport interface RemoveDefaultPaymentMethodMutationResult {\n removeDefaultPaymentMethod: {\n paymentMethod: {\n id: ID;\n };\n };\n}\nexport const RemoveDefaultPaymentMethodMutation = gqlTyped<RemoveDefaultPaymentMethodMutationResult>`\nmutation RemoveDefaultPaymentMethodMutation {\n removeDefaultPaymentMethod(input: {}) {\n paymentMethod {\n id\n } \n }\n}\n`;\n\nexport interface IssuePlanMutationResult {\n issuePlan: {\n plan: {\n id: ID;\n };\n };\n}\nexport const IssuePlanMutation = gqlTyped<IssuePlanMutationResult>`\nmutation IssuePlanMutation($input: IssuePlanInput!) {\n issuePlan(input: $input) {\n plan {\n id\n }\n }\n}\n`;\n\nexport interface CancelPlanMutationResult {\n cancelPlan: {\n plan: {\n id: ID;\n };\n };\n}\nexport const CancelPlanMutation = gqlTyped<CancelPlanMutationResult>`\nmutation CancelPlanMutation($input: CancelPlanInput!) {\n cancelPlan(input: $input) {\n plan {\n id\n } \n }\n}\n`;\n\nexport interface ChangePriceOptionMutationResult {\n changePriceOption: {\n plan: {\n id: ID;\n };\n };\n}\nexport const ChangePriceOptionMutation = gqlTyped<ChangePriceOptionMutationResult>`\nmutation ChangePriceOptionMutation($input: ChangePriceOptionInput!) {\n changePriceOption(input: $input) {\n plan {\n id\n }\n }\n}\n`;\n\nexport interface ReactivatePlanMutationResult {\n reactivatePlan: {\n plan: {\n id: ID;\n };\n };\n}\nexport const ReactivatePlanMutation = gqlTyped<ReactivatePlanMutationResult>`\nmutation ReactivatePlanMutation($input: ReactivatePlanInput!) {\n reactivatePlan(input: $input) {\n plan {\n id\n }\n }\n}\n`;\n","import { Injectable, Injector, NgZone } from '@angular/core';\nimport { LrMutation, LrService } from '../api/lr-graphql';\nimport { LrRelayIdInput } from '../api/types';\nimport { RunOutsideAngular } from '../_common/run-outside-angular';\nimport {\n CancelPlanMutation,\n ChangePriceOptionMutation,\n CompleteStripePaymentMethodCaptureMutation,\n InitiateStripePaymentMethodCaptureMutation,\n IssuePlanMutation,\n ReactivatePlanMutation,\n RemoveDefaultPaymentMethodMutation,\n RemovePaymentMethodMutation,\n SetDefaultPaymentMethodMutation,\n} from './plan.gql';\nimport {\n CancelPlanOptions,\n ChangePriceOptionOptions,\n IssuePlanOptions,\n} from './plan.types';\n\n@RunOutsideAngular({\n ngZoneName: 'ngZone',\n})\n@Injectable({\n providedIn: 'root',\n})\nexport class PlanService extends LrService {\n constructor(private ngZone: NgZone, private injector: Injector) {\n super(injector);\n }\n\n initiateStripePaymentMethodCapture() {\n return this.mutate(this.initiateStripePaymentMethodCaptureMutation());\n }\n\n /**\n * Starts a stripe payment capture intent. On intent can only add one card.\n * @returns Promise that resolves to a mutation\n */\n initiateStripePaymentMethodCaptureMutation() {\n return new LrMutation({\n mutation: InitiateStripePaymentMethodCaptureMutation,\n variables: {\n input: {},\n },\n });\n }\n\n completeStripePaymentMethodCapture(stripeIntentId: string) {\n return this.mutate(\n this.completeStripePaymentMethodCaptureMutation(stripeIntentId)\n );\n }\n\n /**\n * Completes the payment capture intent. Call this after calling stripe.confirmCardSetup.\n *\n * The return result of this mutation can be used to update the UI. Because this is a mutation\n * we always get the most up to date data from the BD.\n *\n * @returns Promise that resolves to a mutation with the just created PaymentMethodNode\n */\n completeStripePaymentMethodCaptureMutation(stripeIntentId: string) {\n return new LrMutation({\n mutation: CompleteStripePaymentMethodCaptureMutation,\n variables: {\n input: { stripeIntentId },\n },\n });\n }\n\n setDefaultPaymentMethod(paymentMethodId: LrRelayIdInput) {\n return this.mutate(this.setDefaultPaymentMethodMutation(paymentMethodId));\n }\n\n /**\n * Mutation that sets the default payment method for the current user.\n *\n * @param paymentMethodId The id from PaymentMethodNode\n * @returns Promise that resolves to a mutation\n */\n setDefaultPaymentMethodMutation(paymentMethodId: LrRelayIdInput) {\n return new LrMutation({\n mutation: SetDefaultPaymentMethodMutation,\n variables: {\n input: {\n paymentMethodId,\n },\n },\n });\n }\n\n removeDefaultPaymentMethod() {\n return this.mutate(this.removeDefaultPaymentMethodMutation());\n }\n\n /**\n * Mutation that removes a the default payment method\n *\n * @returns Promise that resolves to a mutation\n */\n removeDefaultPaymentMethodMutation() {\n return new LrMutation({\n mutation: RemoveDefaultPaymentMethodMutation,\n variables: {\n input: {},\n },\n });\n }\n\n issuePlan(options: IssuePlanOptions) {\n return this.mutate(this.issuePlanMutation(options));\n }\n\n /**\n * Mutation that issues a new plan for the current user.\n *\n * @param options.issuerUid The same issuerUid that is in the AvailablePlanField returned by queries such as availablePublicPlans\n * @param options.planUid The same planUid that is in the AvailablePlanField returned by queries such as availablePublicPlans\n * @param options.priceId The priceId from PriceOptionField (eg. inside AvailablePlanField)\n * @param options.promotionalCode promotion code where applicable\n * @returns Promise that resolves to a mutation\n */\n issuePlanMutation(options: IssuePlanOptions) {\n return new LrMutation({\n mutation: IssuePlanMutation,\n variables: {\n input: options,\n },\n });\n }\n\n removePaymentMethod(paymentMethodId: string) {\n return this.mutate(this.removePaymentMethodMutation(paymentMethodId));\n }\n\n /**\n * Mutation that removes a payment method for the current user\n *\n * @param paymentMethodId The id from PaymentMethodNode\n * @returns Promise that resolves to a mutation\n */\n removePaymentMethodMutation(paymentMethodId: LrRelayIdInput) {\n return new LrMutation({\n mutation: RemovePaymentMethodMutation,\n variables: {\n input: {\n paymentMethodId,\n },\n },\n });\n }\n\n cancelPlan(options: CancelPlanOptions) {\n return this.mutate(this.cancelPlanMutation(options));\n }\n\n /**\n * Mutation that removes a payment method for the current user\n *\n * @param options.planId The id from IssuedPlanNode\n * @param options.immediate If true, cancel plan effective immediately. Default false.\n * @returns Promise that resolves to a mutation\n */\n cancelPlanMutation(options: CancelPlanOptions) {\n return new LrMutation({\n mutation: CancelPlanMutation,\n variables: {\n input: options,\n },\n });\n }\n\n changePriceOption(options: ChangePriceOptionOptions) {\n return this.mutate(this.changePriceOptionMutation(options));\n }\n\n /**\n * Change the price option for a plan.\n *\n * @param options.planId The id from IssuedPlanNode\n * @param options.priceId The priceId from PriceOptionField (eg. inside AvailablePlanField)\n * @returns Promise that resolves to a mutation\n */\n changePriceOptionMutation(options: ChangePriceOptionOptions) {\n return new LrMutation({\n mutation: ChangePriceOptionMutation,\n variables: {\n input: options,\n },\n });\n }\n\n reactivatePlan(planId: LrRelayIdInput) {\n return this.mutate(this.reactivatePlanMutation(planId));\n }\n\n /**\n * Reactivate a cancelled plan with a specified price option.\n *\n * @param options.planId The id from IssuedPlanNode\n * @returns Promise that resolves to a mutation\n */\n reactivatePlanMutation(planId: LrRelayIdInput) {\n return new LrMutation({\n mutation: ReactivatePlanMutation,\n variables: {\n input: { planId },\n },\n });\n }\n}\n","/* eslint-disable @typescript-eslint/no-explicit-any */\nimport { Injectable } from '@angular/core';\nimport { LrGraphQLService } from '../api/lr-graphql';\nimport { mapEdges, TpNode } from '../api/types';\nimport { SharedContactCardService } from '../shared-contact-card/shared-contact-card.service';\nimport { lodash } from '../_common';\nimport { ContactCardsQuery, TrustedPartiesQuery } from './profile.gql';\nimport { ProfileService } from './profile.service';\nimport {\n MainContactCard,\n MainContactCardFields,\n MainContactCardProperty,\n SharedTrustedPartyDetails,\n TrustedParty,\n TrustedPartyDetails,\n TrustedPartyType,\n} from './profile.types';\n\nenum ContactFields {\n Name = 'name',\n Email = 'email',\n Image = 'image',\n Phone = 'phone',\n Address = 'address',\n}\n\nconst FieldNames = [\n ContactFields.Name,\n ContactFields.Email,\n ContactFields.Image,\n ContactFields.Phone,\n ContactFields.Address,\n];\n\ninterface FieldChange {\n field: string;\n id: string;\n label: string;\n oldValue?: any;\n newValue?: any;\n}\n\n@Injectable({\n providedIn: 'root',\n})\nexport class ProfileDetailsService {\n constructor(\n private sharedContactCardService: SharedContactCardService,\n private profileService: ProfileService,\n private api: LrGraphQLService\n ) {}\n\n async updateDetails(fields: MainContactCardFields): Promise<MainContactCard> {\n console.log('updateDetails()');\n const mainContactCard = await this.fetchMainContactCard();\n\n const updatedMainContactCard = await this.profileService.updateDetails(\n mainContactCard?.id,\n mainContactCard?.keyId,\n fields\n );\n\n await this.synchronizeContactCards(fields, mainContactCard?.fields);\n\n return updatedMainContactCard;\n }\n\n async updateTrustedPartyDetails(details: SharedTrustedPartyDetails) {\n const { id, ownedKeyId, sharedKeyId, ...contactCard } = details;\n\n await this.sharedContactCardService.updateMySharedContactCard(\n id,\n ownedKeyId,\n sharedKeyId,\n contactCard\n );\n\n await this.synchronizeSharedDetails(details);\n }\n\n async synchronizeSharedDetails(details: TrustedPartyDetails) {\n let hasNewValues = false;\n\n // Used to be a getCurrentUser() call which returns a caches version of the contact card.\n // Now we just make an API call. So ok to modify the returned value.\n const mainContactCard = await this.fetchMainContactCard();\n\n if (details.name) {\n const property = this.checkField(\n details.name,\n mainContactCard.fields.name\n );\n\n if (property) {\n mainContactCard.fields.name = property;\n hasNewValues = true;\n }\n }\n\n if (details.email) {\n const property = this.checkField(\n details.email,\n mainContactCard.fields.email\n );\n\n if (property) {\n mainContactCard.fields.email = property;\n hasNewValues = true;\n }\n }\n\n if (details.image) {\n const property = this.checkField(\n details.image,\n mainContactCard.fields.image\n );\n\n if (property) {\n mainContactCard.fields.image = property;\n hasNewValues = true;\n }\n }\n\n if (details.phones && details.phones.length) {\n for (const phone of details.phones) {\n const property = this.checkField(\n phone.value,\n mainContactCard.fields.phone,\n phone.label\n );\n\n if (property) {\n mainContactCard.fields.phone = property;\n hasNewValues = true;\n }\n }\n }\n\n if (details.addresses && details.addresses.length) {\n for (const address of details.addresses) {\n const property = this.checkField(\n address.value,\n mainContactCard.fields.address,\n address.label\n );\n\n if (property) {\n mainContactCard.fields.address = property;\n hasNewValues = true;\n }\n }\n }\n\n if (hasNewValues) {\n await this.profileService.updateDetails(\n mainContactCard.id,\n mainContactCard.keyId,\n mainContactCard.fields\n );\n }\n }\n\n // ------------------------------------------------------------------\n // Helpers\n // ------------------------------------------------------------------\n private async fetchMainContactCard(): Promise<MainContactCard | null> {\n const mainContactCard = (await this.api.query({ query: ContactCardsQuery }))\n .contactCards.edges[0]?.node;\n\n return mainContactCard\n ? {\n id: mainContactCard.id,\n keyId: mainContactCard.key.id,\n fields: mainContactCard.cipherDataClearJson as MainContactCardFields,\n }\n : null;\n }\n\n private async getTrustedParties(): Promise<TrustedParty[]> {\n const { tps } = await this.api.query({\n query: TrustedPartiesQuery,\n });\n\n return mapEdges(tps).map((tp) => this.mapTrustedParty(tp));\n }\n\n private mapTrustedParty(tp: TpNode): TrustedParty {\n const tpDetails: TrustedPartyDetails =\n tp.sharedContactCard.sharedCipherDataClearJson;\n\n const myDetails: SharedTrustedPartyDetails = {\n ...tp.myContactCard.sharedCipherDataClearJson,\n id: tp.myContactCard.id,\n ownedKeyId: tp.myContactCard.ownerKey.id,\n sharedKeyId: tp.myContactCard.sharedKey.id,\n };\n\n return {\n id: tp.id,\n type: TrustedPartyType.User,\n hasScenarios: !!tp.sharedScenarios.edges.length,\n hasSharedVault: !!tp.theirItems.directories.edges.length,\n name: tpDetails?.name?.name,\n details: tpDetails,\n mySharedDetails: myDetails,\n userSharedKey: tp.currentUserSharedKey.userSharedKey,\n username: tp.other.username,\n features: {\n sharedVault: {\n hasAccess:\n (tp.other.features?.shareVault || ['noaccess'])[0] === 'access',\n },\n },\n };\n }\n\n private async synchronizeContactCards(\n newFields: MainContactCardFields,\n oldFields: MainContactCardFields\n ): Promise<void> {\n if (!oldFields) return;\n\n const changes = this.getChanges(newFields, oldFields);\n\n if (changes.length === 0) return;\n\n const trustedParties = await this.getTrustedParties();\n\n if (trustedParties.length === 0) return;\n\n for (const details of trustedParties.map((x) => x.mySharedDetails)) {\n await this.synchronizeSharedContactCard(details, changes);\n }\n }\n\n private getChanges(\n newFields: MainContactCardFields,\n oldFields: MainContactCardFields\n ): FieldChange[] {\n const changes: FieldChange[] = [];\n\n for (const field of FieldNames) {\n const oldField = oldFields[field];\n if (oldField && oldField.values) {\n for (const oldValue of oldField.values) {\n const newValue = (newFields[field].values as any[])?.find(\n (x) => x.id === oldValue.id\n );\n\n if (!newValue) {\n changes.push({\n field,\n id: oldValue.id,\n label: oldValue.label,\n oldValue: oldValue.value,\n });\n } else if (!lodash.isEqual(newValue.value, oldValue.value)) {\n changes.push({\n field,\n id: oldValue.id,\n label: oldValue.label,\n oldValue: oldValue.value,\n newValue: newValue.value,\n });\n }\n }\n }\n }\n return changes;\n }\n\n private async synchronizeSharedContactCard(\n details: SharedTrustedPartyDetails,\n changes: FieldChange[]\n ): Promise<void> {\n let hasChanged = false;\n for (const change of changes) {\n switch (change.field) {\n case ContactFields.Phone:\n {\n const value =\n details.phones &&\n details.phones.find((x) => x.label === change.label);\n\n if (value) {\n hasChanged = true;\n value.value = change.newValue;\n }\n }\n break;\n case ContactFields.Address:\n {\n const value =\n details.addresses &&\n details.addresses.find((x) => x.label === change.label);\n\n if (value) {\n hasChanged = true;\n value.value = change.newValue;\n }\n }\n break;\n default: {\n const value = details[change.field];\n\n if (lodash.isEqual(value, change.oldValue)) {\n hasChanged = true;\n details[change.field] = change.newValue;\n }\n }\n }\n }\n if (hasChanged) {\n const { id, ownedKeyId, sharedKeyId, ...contactCard } = details;\n\n await this.sharedContactCardService.updateMySharedContactCard(\n id,\n ownedKeyId,\n sharedKeyId,\n contactCard\n );\n }\n }\n\n private checkField<T>(\n field: T,\n property: MainContactCardProperty<T>,\n label: string = null\n ) {\n property = property || { value: field, hasMultiple: false };\n property.values = property.values || [];\n\n if (\n property.values.length === 0 ||\n property.values.every((x) => !lodash.isEqual(field, x.value))\n ) {\n property.values.push({\n id: `${label}-${new Date().getTime()}`,\n label,\n value: field,\n });\n property.hasMultiple = property.values.length > 1;\n property.value = property.value || field;\n return property;\n }\n return null;\n }\n}\n","import { HttpClient } from '@angular/common/http';\nimport { Inject, Injectable } from '@angular/core';\nimport { AuthClass } from '@aws-amplify/auth/lib-esm/Auth';\nimport { JSONObject } from '../api/types';\nimport { EncryptionService } from '../encryption/encryption.service';\nimport { KeyFactoryService } from '../key/key-factory.service';\nimport { KcConfig, KC_CONFIG } from '../life-ready.config';\nimport { PasswordService } from '../password/password.service';\nimport { RegisterResult } from './register.types';\n\n@Injectable({\n providedIn: 'root',\n})\nexport class RegisterService {\n constructor(\n @Inject(KC_CONFIG) private config: KcConfig,\n private auth: AuthClass,\n private http: HttpClient,\n private keyFactory: KeyFactoryService,\n private encryptionService: EncryptionService,\n private passwordService: PasswordService\n ) {}\n\n /**\n * Request a verification code to be sent out to an email.\n * @return Info needed to be submitted along with the verification code\n */\n public async verifyEmail(email: string): Promise<string> {\n const { claim_id } = await this.http\n .post<{ claim_id }>(`${this.config.authUrl}cove/claim/email/`, {\n address: email,\n context: 'signup',\n })\n .toPromise();\n return claim_id;\n }\n\n public async verifyPhone(phoneNumber: string): Promise<string> {\n const { claim_id } = await this.http\n .post<{ claim_id }>(`${this.config.authUrl}cove/claim/sms/`, {\n address: phoneNumber,\n context: 'signup',\n })\n .toPromise();\n return claim_id;\n }\n\n public async confirmVerificationCode(\n verificationId: string,\n verificationCode: string\n ): Promise<string> {\n const { token } = await this.http\n .post<{ token }>(`${this.config.authUrl}cove/respond/`, {\n claim_id: verificationId,\n v_code: verificationCode,\n })\n .toPromise();\n return token;\n }\n\n public async register(\n email: string,\n password: CryptoKey,\n verificationId: string,\n verificationToken: string,\n verificationType: 'email' | 'phone' = 'email'\n ): Promise<RegisterResult> {\n // Generate the key material needed for PassIdp which will be the password used for Cognito.\n const passKeyBundle = await this.passwordService.createPassKeyBundle(\n password\n );\n\n const masterKey = await this.keyFactory.createKey();\n const wrappedMasterKey = await this.encryptionService.encrypt(\n passKeyBundle.passKey,\n masterKey.toJSON(true)\n );\n\n const rootKey = await this.keyFactory.createKey();\n const wrappedRootKey = await this.encryptionService.encrypt(\n masterKey,\n rootKey.toJSON(true)\n );\n\n // Encryption PKC key\n const prk = await this.keyFactory.createPkcKey();\n const wrappedPrk = await this.encryptionService.encrypt(\n rootKey,\n prk.toJSON(true)\n );\n\n // Signing PKC key\n const sigPrk = await this.keyFactory.createPkcSignKey();\n const wrappedSigPrk = await this.encryptionService.encrypt(\n rootKey,\n sigPrk.toJSON(true)\n );\n\n // API call to setup profile\n const user = await this.http\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n .post<any>(`${this.config.authUrl}users/`, {\n claims: [\n {\n type: verificationType,\n token: verificationToken,\n claim_id: verificationId,\n },\n ],\n pass_idp_params: passKeyBundle.passIdpParams,\n pass_idp_verifier_pbk: passKeyBundle.passIdpVerifier.toJSON(),\n wrapped_pass_idp_verifier_prk: passKeyBundle.wrappedPassIdpVerifierPrk,\n pass_key_params: passKeyBundle.passKeyParams,\n wrapped_master_key: wrappedMasterKey,\n wrapped_root_key: wrappedRootKey,\n pbk: prk.toJSON(), // public encryption key\n wrapped_prk: wrappedPrk,\n sig_pbk: sigPrk.toJSON(), // public signing key\n wrapped_sig_prk: wrappedSigPrk,\n })\n .toPromise();\n\n // API call to create user on cognito\n const attributes = {};\n user.claims.forEach((claim) => {\n attributes[claim.type] = claim.value;\n });\n\n // Random suffix for uniqueness. If there's a duplicate, then used just needs to\n // sign up again. But chances of collision is low.\n const suffix = this.keyFactory.randomDigitsNoZeros(4);\n\n const cognitoUser = await this.auth.signUp({\n username: `${email.split('@')[0]}.${suffix}`,\n password: this.passwordService.getPassIdpString(passKeyBundle.passIdp),\n attributes,\n // Unfortunately, validationData is not passed to the post\n // confirmation cognito trigger. So can can't do the association there.\n // The current workflow will create a new user on LR before signing up\n // with Cognito. Then Cognito can use the user.id and user.pre_sign_up_token to\n // do the validation of the attributes.\n // validationData: [\n // new CognitoUserAttribute({\n // Name: \"user_id\",\n // Value: String(user.id)\n // }),\n // new CognitoUserAttribute({\n // Name: \"user_pre_sign_up_token\",\n // Value: user.pre_sign_up_token\n // })\n // ]\n clientMetadata: {\n user_id: String(user.id),\n user_pre_sign_up_token: String(user.pre_sign_up_token),\n },\n });\n\n return {\n username: cognitoUser.user.getUsername(),\n userId: user.id,\n preSignUpToken: user.pre_sign_up_token,\n userSub: cognitoUser.userSub,\n };\n }\n\n public async hibpBreachedAccounts(account: string) {\n // The account is just the email\n try {\n const response = await this.http\n .get<JSONObject>(\n `${this.config.authUrl}users/hibp/breachedaccount/${account}/?truncateResponse=false`\n )\n .toPromise();\n return response;\n } catch (error) {\n if (error.status === 404) {\n return null;\n } else {\n throw error;\n }\n }\n }\n}\n","export class RegisterResult {\n username: string;\n userId: string;\n preSignUpToken: string;\n userSub: string;\n}\n","import { ID } from '../api/types';\nimport { gqlTyped } from '../_common/ast';\n\nexport interface CreateReminderMutationResult {\n createReminder: {\n reminder: {\n id: ID;\n };\n };\n}\nexport const CreateReminderMutation = gqlTyped<CreateReminderMutationResult>`\nmutation CreateReminderMutation($input: CreateReminderInput!) {\n createReminder(input: $input) {\n reminder {\n id\n }\n }\n}\n`;\n\nexport interface UpdateReminderMutationResult {\n updateReminder: {\n reminder: {\n id: ID;\n };\n };\n}\nexport const UpdateReminderMutation = gqlTyped<UpdateReminderMutationResult>`\nmutation UpdateReminderMutation($input: UpdateReminderInput!) {\n updateReminder(input: $input) {\n reminder {\n id\n }\n }\n}\n`;\n\nexport interface DeleteReminderMutationResult {\n deleteReminder: {\n id: ID;\n };\n}\nexport const DeleteReminderMutation = gqlTyped<DeleteReminderMutationResult>`\nmutation DeleteReminderMutation($input: DeleteReminderInput!) {\n deleteReminder(input: $input) {\n id\n }\n}\n`;\n","import { Injectable, Injector, NgZone } from '@angular/core';\nimport { LrMutation, LrService } from '../api/lr-graphql';\nimport { LrRelayIdInput } from '../api/types';\nimport { RunOutsideAngular } from '../_common/run-outside-angular';\nimport {\n CreateReminderMutation,\n DeleteReminderMutation,\n UpdateReminderMutation,\n} from './reminder.gql';\nimport { CreateReminderOptions, UpdateReminderOptions } from './reminder.types';\n\n@RunOutsideAngular({\n ngZoneName: 'ngZone',\n})\n@Injectable({\n providedIn: 'root',\n})\nexport class ReminderService extends LrService {\n constructor(private ngZone: NgZone, private injector: Injector) {\n super(injector);\n }\n\n createReminder(options: CreateReminderOptions) {\n return this.mutate(this.createReminderMutation(options));\n }\n\n async createReminderMutation(options: CreateReminderOptions) {\n return new LrMutation({\n mutation: CreateReminderMutation,\n variables: {\n input: {\n directoryId: options.directoryId,\n firstEvent: options.firstEvent.toISOString(),\n plain: JSON.stringify(options.plainJson),\n notifyAheadSeconds: options.notifyAheadSeconds ?? 0,\n },\n },\n });\n }\n\n updateReminder(options: UpdateReminderOptions) {\n return this.mutate(this.updateReminderMutation(options));\n }\n\n async updateReminderMutation(options: UpdateReminderOptions) {\n return new LrMutation({\n mutation: UpdateReminderMutation,\n variables: {\n input: {\n id: options.id,\n firstEvent: options.firstEvent?.toISOString(),\n // Ok to use undefined in side JSON.stringify: JSON.stringify(undefined) === undefined\n // Passing in undefined to plain means don't update the plain field.\n plain: JSON.stringify(options.plainJson ?? undefined),\n notifyAheadSeconds: options.notifyAheadSeconds,\n },\n },\n });\n }\n\n deleteReminder(id: LrRelayIdInput) {\n return this.mutate(this.deleteReminderMutation(id));\n }\n\n async deleteReminderMutation(id: LrRelayIdInput) {\n return new LrMutation({\n mutation: DeleteReminderMutation,\n variables: {\n input: {\n id,\n },\n },\n });\n }\n}\n","import { gqlTyped } from '../_common/ast';\n\nexport interface CreateScenarioMutationResult {\n createScenario: {\n scenario: {\n id: string;\n };\n };\n}\nexport const CreateScenarioMutation = gqlTyped<CreateScenarioMutationResult>`\nmutation CreateScenarioMutation($input: CreateScenarioInput!) {\n createScenario(input: $input) {\n scenario {\n id\n }\n }\n}\n`;\n\nexport interface UpdateScenarioMutationResult {\n updateScenario: {\n scenario: {\n id: string;\n };\n };\n}\nexport const UpdateScenarioMutation = gqlTyped<UpdateScenarioMutationResult>`\nmutation UpdateScenarioMutation($input: UpdateScenarioInput!) {\n updateScenario(input: $input) {\n scenario {\n id\n }\n }\n}\n`;\n\nexport interface DeleteScenarioMutationResult {\n deleteScenario: {\n id: string;\n };\n}\nexport const DeleteScenarioMutation = gqlTyped<DeleteScenarioMutationResult>`\nmutation DeleteScenarioMutation($input: DeleteScenarioInput!) {\n deleteScenario(input: $input) {\n id\n }\n}\n`;\n\nexport interface CreateScenarioClaimMutationResult {\n createScenarioClaim: {\n sharedClaim: {\n id: string;\n };\n };\n}\nexport const CreateScenarioClaimMutation = gqlTyped<CreateScenarioClaimMutationResult>`\nmutation CreateScenarioClaimMutation($input: CreateScenarioClaimInput!) {\n createScenarioClaim(input: $input) {\n sharedClaim {\n id\n }\n }\n}\n`;\n\nexport interface CancelScenarioClaimMutationResult {\n cancelScenarioClaim: {\n sharedClaim: {\n id: string;\n };\n };\n}\nexport const CancelScenarioClaimMutation = gqlTyped<CancelScenarioClaimMutationResult>`\nmutation CancelScenarioClaimMutation($input: CancelScenarioClaimInput!) {\n cancelScenarioClaim(input: $input) {\n sharedClaim {\n id\n }\n }\n}\n`;\n\nexport interface RejectScenarioClaimMutationResult {\n rejectScenarioClaim: {\n claimApprover: {\n id: string;\n };\n };\n}\nexport const RejectScenarioClaimMutation = gqlTyped<RejectScenarioClaimMutationResult>`\nmutation RejectScenarioClaimMutation($input: RejectScenarioClaimInput!) {\n rejectScenarioClaim(input: $input) {\n claimApprover {\n id\n }\n }\n}\n`;\n\nexport interface ApproveScenarioClaimMutationResult {\n approveScenarioClaim: {\n claimApprover: {\n id: string;\n };\n };\n}\nexport const ApproveScenarioClaimMutation = gqlTyped<ApproveScenarioClaimMutationResult>`\nmutation ApproveScenarioClaimMutation($input: ApproveScenarioClaimInput!) {\n approveScenarioClaim(input: $input) {\n claimApprover {\n id\n }\n }\n}\n`;\n\nexport interface ReceiveScenarioClaimMutationResult {\n receiveScenarioClaim2: {\n sharedClaim: {\n id: string;\n };\n };\n}\nexport const ReceiveScenarioClaimMutation = gqlTyped<ReceiveScenarioClaimMutationResult>`\nmutation ReceiveScenarioClaimMutation($input: ReceiveScenarioClaimInput!) {\n receiveScenarioClaim(input: $input) {\n sharedClaim {\n id\n }\n }\n}\n`;\n\nexport interface DebugExpireScenarioClaimMutationResult {\n debugExpireScenarioClaim: {\n scenarioClaim: {\n id: string;\n };\n };\n}\nexport const DebugExpireScenarioClaimMutation = gqlTyped<DebugExpireScenarioClaimMutationResult>`\nmutation DebugExpireScenarioClaimMutation($input: DebugExpireScenarioClaimInput!) {\n debugExpireScenarioClaim(input: $input) {\n scenarioClaim {\n id\n }\n }\n}\n`;\n\nexport interface DebugExpireTpPasswordResetRequestMutationResult {\n debugExpireTpPasswordResetRequest: {\n passwordResetRequest: {\n id: string;\n };\n };\n}\nexport const DebugExpireTpPasswordResetRequestMutation = gqlTyped<DebugExpireTpPasswordResetRequestMutationResult>`\nmutation DebugExpireTpPasswordResetRequestMutation($input: DebugExpireTpPasswordResetRequestInput!) {\n debugExpireTpPasswordResetRequest(input: $input) {\n passwordResetRequest {\n id\n }\n }\n}\n`;\n","export const SCENARIO_SLIP39_PASSPHRASE = 'lifeready';\n","import { Injectable, Injector, NgZone } from '@angular/core';\nimport { TpNode } from '../api/types';\nimport { TpAssemblyController } from '../tp-assembly/tp-assembly';\nimport { RunOutsideAngular } from '../_common/run-outside-angular';\nimport { SCENARIO_SLIP39_PASSPHRASE } from './scenario.constants';\n\n@RunOutsideAngular({\n ngZoneName: 'ngZone',\n})\n@Injectable({\n providedIn: 'root',\n})\nexport class ScenarioAssemblyController extends TpAssemblyController {\n slip39Passphrase = SCENARIO_SLIP39_PASSPHRASE;\n\n constructor(private ngZone: NgZone, private injector: Injector) {\n super(injector);\n }\n\n getTpWrappingKeyId(tp: TpNode) {\n return tp.currentUserSharedKey.userSharedKey.sharedKey.id;\n }\n}\n","import { ScenarioNode, SharedScenarioNode } from '../api/types';\nimport { gqlTyped } from '../_common/ast';\n\n/**\n * This is a query that is used internally by the services for mutations. It\n * contains the minimum amount of information for the information the services\n * need. You'll probably want to write your own query to your liking if you\n * want to retrieve a scenario. For example, there a separate query in the\n * scenario.service.spec.ts\n */\nexport interface ScenarioQueryResult {\n scenario: ScenarioNode;\n}\nexport const ScenarioQuery = gqlTyped<ScenarioQueryResult>`\nquery ScenarioQuery(\n $scenarioId: LrRelayIdInput!\n) {\n scenario(id: $scenarioId) {\n id\n state\n assembly {\n quorum\n singleReject\n assemblyKey {\n id\n }\n subjectKey {\n id\n }\n subjectCipherData\n subAssemblies {\n edges {\n node {\n id\n subjectKey {\n id\n }\n subjectCipherData\n quorum\n singleReject\n approvers {\n edges {\n node {\n id\n tp {\n id\n }\n sharedKey {\n id\n }\n }\n }\n }\n }\n }\n }\n }\n claimants {\n edges {\n node {\n tp {\n id\n }\n sharedKey {\n id\n }\n }\n }\n }\n receivers {\n edges {\n node {\n tp {\n id\n }\n sharedKey {\n id\n }\n sharedCipherData\n receiverItems {\n receiverDirectories {\n edges {\n node {\n id\n sharedCipherData\n sharedKey {\n id\n }\n accessRole\n directory {\n id\n keyId\n }\n }\n }\n }\n receiverFiles {\n edges {\n node {\n id\n sharedCipherData\n sharedKey {\n id\n }\n accessRole\n file {\n id\n keyId\n }\n }\n }\n }\n }\n }\n }\n }\n }\n}`;\n\nexport interface SharedScenarioQueryResult {\n sharedScenario: SharedScenarioNode;\n}\nexport const SharedScenarioQuery = gqlTyped<SharedScenarioQueryResult>`\nquery SharedScenarioQuery($scenarioId: LrRelayIdInput!) {\n sharedScenario(id: $scenarioId) {\n id\n state\n tp {\n id\n }\n asClaimant {\n sharedKey {\n id\n }\n sharedCipherData\n }\n asReceiver {\n sharedKey {\n id\n }\n sharedCipherData\n pbk {\n id\n }\n receiverItems {\n receiverDirectories {\n edges {\n node {\n id\n }\n }\n }\n }\n }\n assembly {\n asApprovers {\n edges {\n node {\n id\n sharedKey {\n id\n }\n sharedCipherData\n }\n }\n }\n }\n sharedClaim {\n\t \t\tid\n isClaimant\n claim {\n state\n asClaimApprovers {\n edges {\n node {\n id\n state\n sharedKey {\n id\n }\n sharedCipherApprovalData\n sharedCipherPartialAssemblyKey\n receiverApprovals {\n edges {\n node {\n id\n pxk {\n id\n }\n }\n }\n }\n }\n }\n }\n }\n asClaimReceiver {\n received\n assemblyKeyId\n approvals {\n edges {\n node {\n receiverCipher\n receiverCipherPartialAssemblyKey\n pxk {\n id\n }\n }\n }\n }\n }\n }\n }\n}\n`;\n","import { Injectable, Injector, NgZone } from '@angular/core';\nimport { JWK } from 'node-jose';\nimport { LrMergedMutation, LrMutation, LrService } from '../api/lr-graphql';\nimport {\n AccessRoleChoice,\n JSONObject,\n mapEdges,\n ScenarioNode,\n ScenarioReceiverNode,\n ScenarioState,\n SharedScenarioClaimReceivedApprovalNode,\n SharedTpClaimApproverNode,\n TpClaimApproverState,\n TpNode,\n} from '../api/types';\nimport { EncryptionService } from '../encryption/encryption.service';\nimport { ItemService } from '../item/item.service';\nimport { IdKeyPair } from '../item/item.types';\nimport { KeyGraphService } from '../key/key-graph.service';\nimport { TpsKeysQuery } from '../tp-assembly/tp-assembly.private.gql';\nimport { PartialAssemblyKey } from '../tp-assembly/tp-assembly.types';\nimport {\n KcBadArgumentException,\n KcBadStateException,\n} from '../_common/exceptions';\nimport { RunOutsideAngular } from '../_common/run-outside-angular';\nimport { assert_xor } from '../_common/utils';\nimport { ScenarioAssemblyController } from './scenario.controller';\nimport {\n ApproveScenarioClaimMutation,\n CancelScenarioClaimMutation,\n CreateScenarioClaimMutation,\n CreateScenarioMutation,\n DebugExpireScenarioClaimMutation,\n DeleteScenarioMutation,\n ReceiveScenarioClaimMutation,\n RejectScenarioClaimMutation,\n UpdateScenarioMutation,\n} from './scenario.gql';\nimport { ScenarioQuery, SharedScenarioQuery } from './scenario.private.gql';\nimport {\n CreateClaimantOptions,\n CreateParticipantOptions,\n CreateReceiverOptions,\n CreateScenarioOptions,\n ParticipantOptions,\n ReceiverDirectoryOptions,\n ReceiverFileOptions,\n ReceiverItemOptions,\n ResetScenarioOptions,\n UpdateClaimantOptions,\n UpdateReceiverOptions,\n UpdateScenarioOptions,\n} from './scenario.types';\n\nexport function throwClaimIdMismatch() {\n throw new KcBadArgumentException(\n 'claimId does not match with the current claimId of the scenario'\n );\n}\n\nexport function throwClaimNotApproved() {\n throw new KcBadStateException('Scenario claim has not been approved');\n}\n\n@RunOutsideAngular({\n ngZoneName: 'ngZone',\n})\n@Injectable({\n providedIn: 'root',\n})\nexport class ScenarioService extends LrService {\n constructor(\n private ngZone: NgZone,\n private injector: Injector,\n private keyGraph: KeyGraphService,\n private itemService: ItemService,\n private assemblyController: ScenarioAssemblyController,\n private encryptionService: EncryptionService\n ) {\n super(injector);\n }\n public static SLIP39_PASSPHRASE = 'lifeready';\n\n private prepareAddReceiverDirectory = this.prepareReceiverDirectory;\n private prepareUpdateReceiverDirectory = this.prepareReceiverDirectory;\n\n private prepareAddReceiverFile = this.prepareReceiverFile;\n private prepareUpdateReceiverFile = this.prepareReceiverFile;\n\n // Scenarios\n async createScenario(options: CreateScenarioOptions) {\n return this.mutate(this.createScenarioMutation(options));\n }\n\n async createScenarioMutation(options: CreateScenarioOptions) {\n const input = await this.prepareCreateScenarioMutation(options);\n return new LrMutation({\n mutation: CreateScenarioMutation,\n variables: {\n input,\n },\n });\n }\n\n async updateScenario(options: UpdateScenarioOptions) {\n return this.mutate(this.updateScenarioMutation(options));\n }\n\n async updateScenarioMutation(options: UpdateScenarioOptions) {\n const scenario = (await this.getScenario(options.scenarioId)).scenario;\n const input = await this.prepareUpdateScenario(options, scenario);\n return new LrMutation({\n mutation: UpdateScenarioMutation,\n variables: {\n input,\n },\n });\n }\n\n async resetScenario(options: ResetScenarioOptions) {\n return this.mutate(this.resetScenarioMutation(options));\n }\n\n async resetScenarioMutation(options: ResetScenarioOptions) {\n const scenario = (await this.getScenario(options.scenarioId)).scenario;\n\n const { assembly } = scenario;\n\n // Just need to do an update without changing approvers. This will recreate\n // all assembly keys.\n const updateSubAssemblies = mapEdges(assembly.subAssemblies).map((sa) => {\n const approverTps = mapEdges(sa.approvers).map((approver) => ({\n tpId: approver.tp.id,\n }));\n\n return {\n id: sa.id,\n quorum: sa.quorum,\n singleReject: sa.singleReject,\n subjectCipherDataClearJson: sa.subjectCipherDataClearJson,\n approverTps,\n };\n });\n\n const input = await this.prepareUpdateScenario(\n {\n scenarioId: options.scenarioId,\n enabled: options.enabled,\n updateAssembly: {\n quorum: assembly.quorum,\n singleReject: assembly.singleReject,\n updateSubAssemblies,\n },\n },\n scenario\n );\n\n return new LrMutation({\n mutation: UpdateScenarioMutation, // updating scenario resets it\n variables: {\n input,\n },\n });\n }\n\n async deleteScenario(scenarioId: string) {\n return this.lrGraphQL.lrMutate(this.deleteScenarioMutation(scenarioId));\n }\n\n async deleteScenarioMutation(scenarioId: string) {\n return new LrMutation({\n mutation: DeleteScenarioMutation,\n variables: { input: { scenarioId } },\n });\n }\n\n // Claims\n async createClaim(scenarioId: string) {\n return this.mutate(this.createClaimMutation(scenarioId));\n }\n\n async createClaimMutation(scenarioId: string) {\n return new LrMutation({\n mutation: CreateScenarioClaimMutation,\n variables: { input: { scenarioId } },\n });\n }\n\n async cancelClaim(claimId: string) {\n return this.mutate(this.cancelClaimMutation(claimId));\n }\n\n async cancelClaimMutation(claimId: string) {\n return new LrMutation({\n mutation: CancelScenarioClaimMutation,\n variables: { input: { claimId } },\n });\n }\n\n async rejectClaim(sharedScenarioId: string, claimId: string) {\n return this.mutate(this.rejectClaimMutation(sharedScenarioId, claimId));\n }\n\n async rejectClaimMutation(sharedScenarioId: string, claimId: string) {\n const mutations = await this.prepareRejectClaimMutations(\n sharedScenarioId,\n claimId\n );\n return LrMergedMutation.create(await Promise.all(mutations));\n }\n\n async approveClaim(sharedScenarioId: string, sharedClaimId: string) {\n // TODO this needs a cast so the result is not ANY.\n return this.mutate(\n this.approveClaimMutation(sharedScenarioId, sharedClaimId)\n );\n }\n\n async approveClaimMutation(sharedScenarioId: string, sharedClaimId: string) {\n const mutations = await this.prepareApproveClaimMutations(\n sharedScenarioId,\n sharedClaimId\n );\n return LrMergedMutation.create(await Promise.all(mutations));\n }\n\n async receiveClaim(scenarioId: string, sharedClaimId: string) {\n return this.mutate(this.receiveClaim2Mutation(scenarioId, sharedClaimId));\n }\n\n async receiveClaim2Mutation(scenarioId: string, sharedClaimId: string) {\n return new LrMutation({\n mutation: ReceiveScenarioClaimMutation,\n variables: {\n input: await this.prepareReceiveClaim2(scenarioId, sharedClaimId),\n },\n });\n }\n\n async debugExpireClaim(scenarioId: string) {\n return this.mutate(this.debugExpireClaimMutation(scenarioId));\n }\n\n async debugExpireClaimMutation(scenarioId: string) {\n return new LrMutation({\n mutation: DebugExpireScenarioClaimMutation,\n variables: {\n input: { scenarioId },\n },\n });\n }\n\n // --------------------------------------------------------------------------------\n // --------------------------------------------------------------------------------\n // Helpers\n // --------------------------------------------------------------------------------\n // --------------------------------------------------------------------------------\n private async getScenario(scenarioId: string) {\n return this.query({\n query: ScenarioQuery,\n variables: { scenarioId },\n });\n }\n\n private async getSharedScenario(scenarioId: string, claimId?: string) {\n const ret = await this.query({\n query: SharedScenarioQuery,\n variables: {\n scenarioId,\n },\n });\n\n if (claimId && ret.sharedScenario.sharedClaim.id !== claimId) {\n throwClaimIdMismatch();\n }\n\n return ret;\n }\n\n private async getParticipantTpsKeys(options: CreateParticipantOptions[]) {\n const tpIds = options.map((x) => x.tpId);\n\n // This should contain all the TPs that we need to update the assembly.\n const tps = mapEdges(\n (\n await this.lrGraphQL.query({\n query: TpsKeysQuery,\n variables: {\n ids: tpIds,\n },\n })\n ).tps\n );\n\n return tps;\n }\n\n private fillTpSharedKeyId(\n options: CreateParticipantOptions[],\n tps: TpNode[]\n ) {\n options.forEach((participant) => {\n if (!participant.tpSharedKeyId) {\n const tp = tps.find((x) => x.id === participant.tpId);\n participant.tpSharedKeyId =\n tp.currentUserSharedKey.userSharedKey.sharedKey.id;\n }\n });\n }\n\n private async prepareCreateScenarioMutation(options: CreateScenarioOptions) {\n const { assemblyKey, mutationInput: createAssembly } =\n await this.assemblyController.prepareCreate(options.createAssembly);\n\n const createReceiversOptions = options.createReceivers || [];\n const createClaimantsOptions = options.createClaimants || [];\n\n // Fetch all the TPs so we don't have to pass in tpSharedKeyId\n const creatParticipantsOptions = createReceiversOptions.concat(\n createClaimantsOptions\n );\n\n const tps = await this.getParticipantTpsKeys(creatParticipantsOptions);\n\n this.fillTpSharedKeyId(creatParticipantsOptions, tps);\n\n const createReceivers = await Promise.all(\n createReceiversOptions.map((receiver) =>\n this.prepareCreateReceiver(receiver, assemblyKey)\n )\n );\n\n const createClaimants = await Promise.all(\n createClaimantsOptions.map((x) => this.prepareCreateClaimant(x))\n );\n\n return {\n enabled: options.enabled,\n inactiveSeconds: options.inactiveSeconds,\n createAssembly,\n createReceivers,\n createClaimants,\n };\n }\n\n private async prepareUpdateScenario(\n options: UpdateScenarioOptions,\n scenario: ScenarioNode\n ) {\n let assemblyKey = await this.keyGraph.getJwkKey(\n scenario.assembly.assemblyKey.id\n );\n\n const updateAssembly = options.updateAssembly\n ? await (async () => {\n // Assembly key is always rotated when updating assembly.\n const result = await this.assemblyController.prepareUpdate(\n options.updateAssembly,\n scenario.assembly\n );\n // Use new assembly key.\n assemblyKey = result.assemblyKey;\n return result.mutationInput;\n })()\n : undefined;\n\n const createReceiversOptions = options.createReceivers || [];\n const createClaimantsOptions = options.createClaimants || [];\n\n // Fetch all the TPs so we don't have to pass in tpSharedKeyId\n const creatParticipantsOptions = createReceiversOptions.concat(\n createClaimantsOptions\n );\n\n const tps = await this.getParticipantTpsKeys(creatParticipantsOptions);\n\n this.fillTpSharedKeyId(creatParticipantsOptions, tps);\n\n const createReceivers =\n options.createReceivers &&\n (await Promise.all(\n options.createReceivers.map((x) =>\n this.prepareCreateReceiver(x, assemblyKey)\n )\n ));\n\n const existingReceivers = mapEdges(scenario.receivers);\n let updateReceivers = options.updateReceivers\n ? await Promise.all(\n options.updateReceivers.map((updateReceiver) => {\n // Find the receiver we are updating\n const existingReceiver = existingReceivers.find(\n (x) => x.tp.id === updateReceiver.tpId\n );\n\n return this.prepareUpdateReceiver(\n updateReceiver,\n assemblyKey,\n existingReceiver\n );\n })\n )\n : [];\n\n // Fill in any missing receivers when updating assembly.\n if (options.updateAssembly) {\n // Filter out the receivers that will be deleted or already updated.\n const existing = existingReceivers.filter(\n (existingReceiver) =>\n !(options.deleteReceivers || []).includes(existingReceiver.tp.id) &&\n !updateReceivers.some(\n (updateReceiver) => updateReceiver.tpId === existingReceiver.tp.id\n )\n );\n updateReceivers = updateReceivers.concat(\n await this.prepareExistingReceivers(existing, assemblyKey)\n );\n }\n\n const createClaimants =\n options.createClaimants &&\n (await Promise.all(\n options.createClaimants.map((x) => this.prepareCreateClaimant(x))\n ));\n\n const existingClaimants = mapEdges(scenario.claimants);\n const updateClaimants =\n options.updateClaimants &&\n (await Promise.all(\n options.updateClaimants.map((x) => {\n // Find the claimant we are updating\n const claimant = existingClaimants.find(\n (existingClaimant) => existingClaimant.tp.id === x.tpId\n );\n return this.prepareUpdateClaimant(x, claimant.sharedKey.id);\n })\n ));\n\n return {\n scenarioId: options.scenarioId,\n enabled: options.enabled,\n inactiveSeconds: options.inactiveSeconds,\n updateAssembly,\n createReceivers,\n updateReceivers,\n deleteReceivers: options.deleteReceivers,\n createClaimants,\n updateClaimants,\n deleteClaimants: options.deleteClaimants,\n };\n }\n\n private async prepareReceiverItem(options: {\n receiverItemOptions: ReceiverItemOptions;\n receiverSharedKey: JWK.Key;\n assemblyKey: JWK.Key;\n directory?: IdKeyPair;\n file?: IdKeyPair;\n }) {\n const {\n receiverItemOptions,\n receiverSharedKey,\n assemblyKey,\n directory,\n file,\n } = options;\n\n assert_xor({ directory, file });\n\n const { accessRole } = receiverItemOptions;\n\n if (accessRole == AccessRoleChoice.DENY) {\n const ret = {\n accessRole,\n itemKeyId: null,\n wrappedItemKey: null,\n sharedCipherData: null,\n };\n\n if (directory) {\n // Cryptographic access to item is not required.\n return {\n ...ret,\n directoryId: directory.id,\n };\n } else {\n return {\n ...ret,\n fileId: file.id,\n };\n }\n } else {\n // TODO this should be batched\n let itemKey;\n if (directory) {\n itemKey = await this.itemService.getDirectoryKey(\n directory.id,\n directory.keyId\n );\n } else {\n itemKey = await this.itemService.getFileKey(file.id, file.keyId);\n }\n\n let wrappedItemKey = await this.keyGraph.encryptToString(\n receiverSharedKey,\n itemKey.jwk.toJSON(true)\n );\n\n const sharedCipherData = await this.keyGraph.encryptToString(\n receiverSharedKey,\n receiverItemOptions.sharedCipherDataClearJson || ''\n );\n\n wrappedItemKey = await this.keyGraph.encryptToString(\n assemblyKey,\n wrappedItemKey\n );\n\n const ret = {\n accessRole,\n itemKeyId: itemKey.id,\n wrappedItemKey,\n sharedCipherData,\n };\n\n if (directory) {\n return {\n ...ret,\n directoryId: directory.id,\n };\n } else {\n return {\n ...ret,\n fileId: file.id,\n };\n }\n }\n }\n\n private async prepareReceiverDirectory(\n options: ReceiverDirectoryOptions,\n receiverSharedKey: JWK.Key,\n assemblyKey: JWK.Key\n ) {\n return this.prepareReceiverItem({\n receiverItemOptions: options,\n receiverSharedKey,\n assemblyKey,\n directory: {\n id: options.directoryId,\n keyId: options.directoryKeyId,\n },\n });\n }\n\n private async prepareReceiverFile(\n options: ReceiverFileOptions,\n receiverSharedKey: JWK.Key,\n assemblyKey: JWK.Key\n ) {\n return this.prepareReceiverItem({\n receiverItemOptions: options,\n receiverSharedKey,\n assemblyKey,\n file: {\n id: options.fileId,\n keyId: options.fileKeyId,\n },\n });\n }\n\n private async prepareCreateReceiver(\n options: CreateReceiverOptions,\n assemblyKey: JWK.Key\n ) {\n const { sharedKey, mutationInput } = await this.prepareCreateParticipant(\n options\n );\n\n const addDirectories =\n options.addDirectories &&\n (await Promise.all(\n options.addDirectories.map((x) =>\n this.prepareAddReceiverDirectory(x, sharedKey.key, assemblyKey)\n )\n ));\n\n const addFiles =\n options.addFiles &&\n (await Promise.all(\n options.addFiles.map((x) =>\n this.prepareAddReceiverFile(x, sharedKey.key, assemblyKey)\n )\n ));\n\n return {\n ...mutationInput,\n addDirectories,\n addFiles,\n };\n }\n\n private async prepareUpdateReceiver(\n options: UpdateReceiverOptions,\n assemblyKey: JWK.Key,\n existingReceiver: ScenarioReceiverNode\n ) {\n const sharedKeyId = existingReceiver.sharedKey.id;\n\n const deleteDirectoriesOptions = options.deleteDirectories || [];\n const updateDirectoriesOptions = options.updateDirectories || [];\n\n const deleteFilesOptions = options.deleteFiles || [];\n const updateFilesOptions = options.updateFiles || [];\n\n // Fill in any missing update directories\n mapEdges(existingReceiver.receiverItems.receiverDirectories).forEach(\n (existingDirectory) => {\n if (deleteDirectoriesOptions.includes(existingDirectory.directory.id)) {\n return;\n }\n\n if (\n updateDirectoriesOptions.find(\n (x) => x.directoryId === existingDirectory.directory.id\n )\n ) {\n return;\n }\n\n updateDirectoriesOptions.push({\n accessRole: existingDirectory.accessRole,\n directoryId: existingDirectory.directory.id,\n directoryKeyId: existingDirectory.directory.keyId,\n sharedCipherDataClearJson:\n existingDirectory.sharedCipherDataClearJson,\n });\n }\n );\n\n // Fill in any missing update directories\n mapEdges(existingReceiver.receiverItems.receiverFiles).forEach(\n (existingFile) => {\n if (deleteFilesOptions.includes(existingFile.file.id)) {\n return;\n }\n\n if (updateFilesOptions.find((x) => x.fileId === existingFile.file.id)) {\n return;\n }\n\n updateFilesOptions.push({\n accessRole: existingFile.accessRole,\n fileId: existingFile.file.id,\n fileKeyId: existingFile.file.keyId,\n sharedCipherDataClearJson: existingFile.sharedCipherDataClearJson,\n });\n }\n );\n\n const { sharedKey, mutationInput } = await this.prepareUpdateParticipant(\n options,\n sharedKeyId\n );\n\n const addDirectories =\n options.addDirectories &&\n (await Promise.all(\n options.addDirectories.map((x) =>\n this.prepareAddReceiverDirectory(x, sharedKey, assemblyKey)\n )\n ));\n\n const addFiles =\n options.addFiles &&\n (await Promise.all(\n options.addFiles.map((x) =>\n this.prepareAddReceiverFile(x, sharedKey, assemblyKey)\n )\n ));\n\n const updateDirectories = await Promise.all(\n updateDirectoriesOptions.map((x) =>\n this.prepareUpdateReceiverDirectory(x, sharedKey, assemblyKey)\n )\n );\n\n const updateFiles = await Promise.all(\n updateFilesOptions.map((x) =>\n this.prepareUpdateReceiverFile(x, sharedKey, assemblyKey)\n )\n );\n\n return {\n ...mutationInput,\n addDirectories,\n addFiles,\n updateDirectories,\n updateFiles,\n deleteDirectories: options.deleteDirectories,\n deleteFiles: options.deleteFiles,\n };\n }\n\n private async prepareExistingReceiver(\n existingReceiver: ScenarioReceiverNode,\n assemblyKey: JWK.Key\n ) {\n const updateDirectories = mapEdges(\n existingReceiver.receiverItems.receiverDirectories\n ).map(({ accessRole, sharedCipherDataClearJson, directory }) => ({\n accessRole,\n sharedCipherDataClearJson,\n directoryId: directory.id,\n directoryKeyId: directory.keyId,\n }));\n\n const updateFiles = mapEdges(\n existingReceiver.receiverItems.receiverFiles\n ).map(({ accessRole, sharedCipherDataClearJson, file }) => ({\n accessRole,\n sharedCipherDataClearJson,\n fileId: file.id,\n fileKeyId: file.keyId,\n }));\n\n // Fill it in with existing receiver.\n return this.prepareUpdateReceiver(\n {\n tpId: existingReceiver.tp.id,\n sharedCipherDataClearJson: existingReceiver.sharedCipherDataClearJson,\n updateDirectories,\n updateFiles,\n },\n assemblyKey,\n existingReceiver\n );\n }\n\n private async prepareExistingReceivers(\n existingReceivers: ScenarioReceiverNode[],\n assemblyKey: JWK.Key\n ) {\n return Promise.all(\n existingReceivers.map((existingReceiver) =>\n this.prepareExistingReceiver(existingReceiver, assemblyKey)\n )\n );\n }\n\n private async prepareCreateParticipant(options: CreateParticipantOptions) {\n const sharedKey = await this.keyGraph.encryptWithNewKey(\n options.tpSharedKeyId,\n options.sharedCipherDataClearJson || ''\n );\n return {\n sharedKey,\n mutationInput: {\n tpId: options.tpId,\n tpSharedKeyId: options.tpSharedKeyId,\n tpSharedKeyWrappedSharedKey: sharedKey.wrappedKey,\n sharedCipherData: sharedKey.cipher,\n },\n };\n }\n\n private async prepareUpdateParticipant(\n options: ParticipantOptions,\n sharedKeyId: string\n ) {\n const sharedKey = await this.keyGraph.getJwkKey(sharedKeyId);\n\n const sharedCipherData = await this.keyGraph.encryptToString(\n sharedKey,\n options.sharedCipherDataClearJson || ''\n );\n\n return {\n sharedKey,\n mutationInput: {\n tpId: options.tpId,\n sharedKeyId,\n sharedCipherData,\n },\n };\n }\n\n private async prepareCreateClaimant(options: CreateClaimantOptions) {\n const { mutationInput } = await this.prepareCreateParticipant(options);\n return mutationInput;\n }\n\n private async prepareUpdateClaimant(\n options: UpdateClaimantOptions,\n sharedKeyId: string\n ) {\n const { mutationInput } = await this.prepareUpdateParticipant(\n options,\n sharedKeyId\n );\n\n return mutationInput;\n }\n\n async prepareReceiveClaim2(scenarioId: string, sharedClaimId: string) {\n // Get all the shared items\n const sharedScenario = (\n await this.getSharedScenario(scenarioId, sharedClaimId)\n ).sharedScenario;\n\n if (sharedScenario.state !== ScenarioState.APPROVED) {\n throwClaimNotApproved();\n }\n\n const approvals = mapEdges(\n sharedScenario.sharedClaim.asClaimReceiver.approvals\n );\n\n const assemblyKey = await this.recoverAssemblyKey(approvals);\n\n // Wrap assembly key with shared key.\n //???\n // This sharedKey is created just for this scenario. It's wrapped by the tpSharedKey.\n const sharedKey = await this.keyGraph.getKey(\n sharedScenario.asReceiver.sharedKey.id\n );\n\n const sharedKeyWrappedAssemblyKey = await this.keyGraph.encryptToString(\n sharedKey,\n assemblyKey.toJSON(true)\n );\n\n return {\n scenarioClaimId: sharedClaimId,\n sharedKeyWrappedAssemblyKey,\n sharedKeyId: sharedKey.id,\n assemblyKeyId: sharedScenario.sharedClaim.asClaimReceiver.assemblyKeyId,\n };\n }\n\n // async prepareReceiveClaim(scenarioId: string, sharedClaimId: string) {\n // // Get all the shared items\n // const sharedScenario = (\n // await this.getSharedScenario(scenarioId, sharedClaimId)\n // ).sharedScenario;\n\n // if (sharedScenario.state !== ScenarioState.APPROVED) {\n // throwClaimNotApproved();\n // }\n\n // const approvals = mapEdges(\n // sharedScenario.sharedClaim.asClaimReceiver.approvals\n // );\n\n // const assemblyKey = await this.recoverAssemblyKey(approvals);\n\n // // Decrypt all items\n // const receiverDirectories = await Promise.all(\n // sharedScenario.asReceiver.receiverItems.receiverDirectories.edges\n // .map((edge) => edge.node)\n // .map(async (receiverDirectory) => {\n // const wrappedItemKey = await this.encryptionService.decrypt(\n // assemblyKey,\n // receiverDirectory.wrappedItemKey\n // );\n\n // return {\n // receiverDirectoryId: receiverDirectory.id,\n // // Looks like receiverDirectory.wrappedItemKey has no other content in side it except a wrapped key.\n // // So we can turn this in to a doubly wrapped key and just release the assembly key.\n\n // receiverSharedKeyWrappedItemKey: wrappedItemKey, // the wrappedItemKey is already wrapped by receiverSharedKey\n // };\n // })\n // );\n\n // return {\n // scenarioClaimId: sharedClaimId,\n // receiverDirectories,\n // };\n // }\n\n private async recoverAssemblyKey(\n approvals: SharedScenarioClaimReceivedApprovalNode[]\n ) {\n const partials = await Promise.all(\n approvals.map((approval) =>\n this.keyGraph.decryptFromString<PartialAssemblyKey>(\n approval.pxk.id,\n approval.receiverCipherPartialAssemblyKey\n )\n )\n );\n\n return this.assemblyController.recoverAssemblyKey(partials);\n }\n\n private async asClaimApprovers(\n sharedScenarioId,\n claimId,\n state: TpClaimApproverState\n ) {\n const sharedScenario = (\n await this.getSharedScenario(sharedScenarioId, claimId)\n ).sharedScenario;\n\n return mapEdges(sharedScenario.sharedClaim.claim.asClaimApprovers).filter(\n (asClaimApprover) => asClaimApprover.state === state\n );\n }\n\n private async prepareApproveClaimMutations(\n sharedScenarioId: string,\n claimId: string\n ) {\n // The current user may be acting as approvers in multiple sub-assemblies so\n // we approve them all.\n const asClaimApprovers = await this.asClaimApprovers(\n sharedScenarioId,\n claimId,\n TpClaimApproverState.CLAIMED\n );\n\n return asClaimApprovers.map(\n async (asClaimApprover) =>\n new LrMutation({\n mutation: ApproveScenarioClaimMutation,\n variables: {\n input: await this.prepareApproveClaim(asClaimApprover),\n },\n })\n );\n }\n\n private async prepareApproveClaim(\n asClaimApprover: SharedTpClaimApproverNode\n ) {\n const receiverApprovals = await Promise.all(\n mapEdges(asClaimApprover.receiverApprovals).map((receiverApproval) =>\n this.prepareReceiverApproval({\n receiverApprovalId: receiverApproval.id,\n receiverApprovalPxkId: receiverApproval.pxk.id,\n sharedCipherPartialAssemblyKeyClearJson:\n asClaimApprover.sharedCipherPartialAssemblyKeyClearJson,\n })\n )\n );\n\n return {\n claimApproverId: asClaimApprover.id,\n receiverApprovals,\n };\n }\n\n private async prepareReceiverApproval(options: {\n receiverApprovalId: string;\n receiverApprovalPxkId: string;\n sharedCipherPartialAssemblyKeyClearJson: JSONObject;\n }) {\n return {\n receiverApprovalId: options.receiverApprovalId,\n // TODO allow sending of messages to receiver.\n receiverCipher: '',\n receiverCipherPartialAssemblyKey: await this.keyGraph.encryptToString(\n options.receiverApprovalPxkId,\n options.sharedCipherPartialAssemblyKeyClearJson\n ),\n };\n }\n\n private async prepareRejectClaimMutations(\n sharedScenarioId: string,\n claimId: string\n ) {\n // The current user may be acting as approvers in multiple sub-assemblies so\n // we reject them all.\n const asClaimApprovers = await this.asClaimApprovers(\n sharedScenarioId,\n claimId,\n TpClaimApproverState.CLAIMED\n );\n\n return asClaimApprovers.map(\n async (asClaimApprover) =>\n new LrMutation({\n mutation: RejectScenarioClaimMutation,\n variables: {\n input: { claimApproverId: asClaimApprover.id },\n },\n })\n );\n }\n}\n","import { ServerConfig } from '../api/types';\nimport { gqlTyped } from '../_common/ast';\n\nexport interface ServerConfigQueryResult {\n serverConfig: Pick<Required<ServerConfig>, 'relayConnectionMaxLimit'>;\n}\nexport const ServerConfigQuery = gqlTyped<ServerConfigQueryResult>`\nquery ServerConfigQuery {\n serverConfig {\n relayConnectionMaxLimit\n }\n}\n`;\n","import { Injectable, Injector, NgZone } from '@angular/core';\nimport { LrService } from '../api/lr-graphql';\nimport { RunOutsideAngular } from '../_common/run-outside-angular';\nimport {\n ServerConfigQuery,\n ServerConfigQueryResult,\n} from './server-config.gql';\n\n@RunOutsideAngular({\n ngZoneName: 'ngZone',\n})\n@Injectable({\n providedIn: 'root',\n})\nexport class ServerConfigService extends LrService {\n private serverConfig: ServerConfigQueryResult['serverConfig']; // cache\n\n constructor(private ngZone: NgZone, private injector: Injector) {\n super(injector);\n }\n\n async getConfig() {\n if (this.serverConfig == null) {\n this.serverConfig = (\n await this.query({\n query: ServerConfigQuery,\n includeKeyGraph: false,\n })\n ).serverConfig;\n }\n\n return this.serverConfig;\n }\n}\n","import { ID } from '../api/types';\nimport { gqlTyped } from '../_common/ast';\n\nexport interface UpdateOwnedContactCardMutation {\n updateOwnedContactCard: {\n ownedContactCard: {\n id: ID;\n };\n };\n}\nexport const UpdateOwnedContactCardMutation = gqlTyped<UpdateOwnedContactCardMutation>`\nmutation UpdateOwnedContactCardMutation(\n $input: UpdateOwnedContactCardInput!\n) {\n updateOwnedContactCard(input: $input) {\n ownedContactCard {\n id\n }\n }\n}`;\n\nexport interface UpdateReceivedContactCardMutation {\n updateReceivedContactCard: {\n receivedContactCard: {\n id: ID;\n };\n };\n}\nexport const UpdateReceivedContactCardMutation = gqlTyped<UpdateReceivedContactCardMutation>`\nmutation UpdateReceivedContactCardMutation(\n $input: UpdateReceivedContactCardInput!\n) {\n updateReceivedContactCard(input: $input) {\n receivedContactCard {\n id\n }\n }\n}`;\n\nexport interface GetOwnedContactCardKeyIdsQuery {\n ownedContactCard: {\n sharedKey: {\n id: ID;\n };\n ownerKey: {\n id: ID;\n };\n };\n}\nexport const GetOwnedContactCardKeyIdsQuery = gqlTyped<GetOwnedContactCardKeyIdsQuery>`\nquery GetOwnedContactCardKeyIdsQuery($id: LrRelayIdInput!) {\n ownedContactCard(id: $id) {\n sharedKey {\n id\n }\n ownerKey {\n id\n }\n }\n}`;\n\nexport interface GetReceivedContactCardKeyIdQuery {\n receivedContactCard: {\n receiverKey: {\n id: ID;\n };\n };\n}\nexport const GetReceivedContactCardKeyIdQuery = gqlTyped<GetReceivedContactCardKeyIdQuery>`\nquery GetReceivedContactCardKeyIdQuery($id: LrRelayIdInput!) {\n receivedContactCard(id: $id) {\n receiverKey {\n id\n }\n }\n}`;\n","import { Injectable, NgZone } from '@angular/core';\nimport { LrGraphQLService, LrMutation } from '../api/lr-graphql';\nimport { LrRelayIdInput } from '../api/types';\nimport { EncryptionService } from '../encryption/encryption.service';\nimport {\n ContactCardReceiverCipherData,\n SendContactCardInput,\n} from '../key-exchange/key-exchange.service';\nimport { KeyGraphService } from '../key/key-graph.service';\nimport { KeyService } from '../key/key.service';\nimport { Key } from '../key/key.types';\nimport { RunOutsideAngular } from '../_common/run-outside-angular';\nimport {\n GetOwnedContactCardKeyIdsQuery,\n GetReceivedContactCardKeyIdQuery,\n UpdateOwnedContactCardMutation,\n UpdateReceivedContactCardMutation,\n} from './shared-contact-card2.gql';\n\nexport interface UpdateOwnedContactCardInput extends SendContactCardInput {\n id: LrRelayIdInput;\n ownerKeyId?: LrRelayIdInput;\n sharedKeyId?: LrRelayIdInput;\n}\n\nexport interface UpdateReceivedContactCardInput\n extends ContactCardReceiverCipherData {\n id: LrRelayIdInput;\n receiverKeyId?: LrRelayIdInput;\n}\n\n@RunOutsideAngular({\n ngZoneName: 'ngZone',\n})\n@Injectable({\n providedIn: 'root',\n})\nexport class SharedContactCard2Service {\n constructor(\n private ngZone: NgZone,\n private keyService: KeyService,\n private keyGraph: KeyGraphService,\n private encryptionService: EncryptionService,\n private lrGraphQL: LrGraphQLService\n ) {}\n\n private async getOwnedContactCardKeyIds(id: LrRelayIdInput) {\n const { ownedContactCard: cc } = await this.lrGraphQL.query({\n query: GetOwnedContactCardKeyIdsQuery,\n variables: {\n id,\n },\n });\n\n return {\n sharedKeyId: cc.sharedKey.id,\n ownerKeyId: cc.ownerKey.id,\n };\n }\n\n private async getReceivedContactCardKeyId(id: LrRelayIdInput) {\n return (\n await this.lrGraphQL.query({\n query: GetReceivedContactCardKeyIdQuery,\n variables: {\n id,\n },\n })\n ).receivedContactCard.receiverKey.id;\n }\n\n async updateOwnedContactCard({\n id,\n ownerKeyId,\n sharedKeyId,\n ownerPlainDataJson,\n ownerCipherDataClearJson,\n sharedCipherDataClearJson,\n }: UpdateOwnedContactCardInput) {\n let ownerKey: Key;\n let sharedKey: Key;\n\n try {\n ownerKey = await this.keyGraph.getKey(ownerKeyId);\n sharedKey = await this.keyGraph.getKey(sharedKeyId);\n } catch (error) {\n const keys = await this.getOwnedContactCardKeyIds(id);\n\n // try again\n ownerKey = await this.keyGraph.getKey(keys.ownerKeyId);\n sharedKey = await this.keyGraph.getKey(keys.sharedKeyId);\n }\n\n const sigPxk = this.keyService.currentSigPxk;\n\n const sharedCipherData = await this.encryptionService.encrypt(\n sharedKey.jwk,\n sharedCipherDataClearJson\n );\n const sharedCipherDataSig = JSON.stringify(\n await this.encryptionService.sign(sigPxk.jwk, sharedCipherData)\n );\n\n const ownerPlainDataSig = JSON.stringify(\n await this.encryptionService.sign(sigPxk.jwk, ownerPlainDataJson)\n );\n\n const ownerCipherData = await this.encryptionService.encryptToString(\n ownerKey.jwk,\n ownerCipherDataClearJson\n );\n\n return new LrMutation({\n mutation: UpdateOwnedContactCardMutation,\n variables: {\n input: {\n id,\n ownerCipherData,\n ownerKeyId: ownerKey.id,\n sharedCipherDataSig,\n sharedKeyId: sharedKey.id,\n sigPxkId: sigPxk.id,\n ownerPlainDataSig,\n },\n },\n });\n }\n\n async updateReceivedContactCard({\n id,\n receiverKeyId,\n receiverCipherDataClearJson,\n }: UpdateReceivedContactCardInput) {\n const receiverKey = await this.keyGraph.getKey(receiverKeyId, () =>\n this.getReceivedContactCardKeyId(id)\n );\n\n const receiverCipherData = await this.encryptionService.encryptToString(\n receiverKey.jwk,\n receiverCipherDataClearJson\n );\n\n return new LrMutation({\n mutation: UpdateReceivedContactCardMutation,\n variables: {\n input: {\n id,\n receiverCipherData,\n receiverKeyId: receiverKey.id,\n },\n },\n });\n }\n}\n","import { GenericScalar, ID } from '../api/types';\nimport { DateTime, JSONObject } from '../api/types/graphql.types';\nimport {\n TpClaimApproverState,\n TpClaimState,\n} from '../api/types/lr-graphql.types';\nimport { gqlTyped } from '../_common/ast';\n\nexport interface SharedTpPasswordResetFragmentResult {\n id: ID;\n tp: {\n id: ID;\n other: {\n username: string;\n };\n };\n assembly: {\n asApprovers: {\n edges: {\n node: {\n id: ID;\n sharedKey: {\n id: ID;\n };\n sharedCipherData: string;\n sharedCipherDataClearJson: JSONObject;\n };\n }[];\n };\n };\n sharedRequest: {\n id: ID;\n pxk: {\n id: ID;\n pbk: string;\n };\n claim: {\n id: ID;\n state: TpClaimState;\n asClaimApprovers: {\n edges: {\n node: {\n id: ID;\n state: TpClaimApproverState;\n sharedKey: {\n id: ID;\n };\n sharedCipherApprovalData: string;\n sharedCipherApprovalDataClearJson: JSONObject;\n sharedCipherPartialAssemblyKey: string;\n sharedCipherPartialAssemblyKeyClearJson: JSONObject;\n receiverApprovals: {\n edges: {\n node: {\n id: ID;\n };\n }[];\n };\n };\n }[];\n };\n };\n };\n}\nconst SharedTpPasswordResetFragment = gqlTyped<SharedTpPasswordResetFragmentResult>`\nfragment SharedTpPasswordResetFragment on SharedTpPasswordResetNode {\n id\n tp {\n id\n other {\n username\n }\n }\n assembly {\n asApprovers {\n edges {\n node {\n id\n sharedKey {\n id\n }\n sharedCipherData\n }\n }\n }\n }\n sharedRequest {\n id\n pxk {\n id\n pbk\n }\n claim {\n id\n state\n asClaimApprovers {\n edges {\n node {\n id\n state\n sharedKey {\n id\n }\n sharedCipherApprovalData\n sharedCipherPartialAssemblyKey\n receiverApprovals {\n edges {\n node {\n id\n }\n }\n }\n }\n }\n }\n }\n }\n}`;\n\nexport interface SharedTpPasswordResetsQueryResult {\n sharedTpPasswordResets: {\n edges: {\n node: SharedTpPasswordResetFragmentResult;\n }[];\n };\n}\nexport const SharedTpPasswordResetsQuery = gqlTyped<SharedTpPasswordResetsQueryResult>`\nquery SharedTpPasswordResetsQuery {\n sharedTpPasswordResets {\n edges {\n node {\n ...SharedTpPasswordResetFragment\n }\n }\n }\n}\n${SharedTpPasswordResetFragment}\n`;\n\nexport interface SharedTpPasswordResetQueryResult {\n sharedTpPasswordReset: SharedTpPasswordResetFragmentResult;\n}\nexport const SharedTpPasswordResetQuery = gqlTyped<SharedTpPasswordResetQueryResult>`\nquery SharedTpPasswordResetQuery($id: LrRelayIdInput!) {\n sharedTpPasswordReset(id: $id) {\n ...SharedTpPasswordResetFragment\n }\n}\n${SharedTpPasswordResetFragment}\n`;\n\nexport interface TpPasswordResetUserQueryResult {\n tpPasswordResetUser: {\n username: string;\n resetUsername: string;\n state: TpClaimState;\n passKey: {\n id: ID;\n passKeyParams: GenericScalar;\n passIdpParams: GenericScalar;\n };\n masterKey: {\n id: ID;\n };\n pxk: {\n id: ID;\n };\n sessionEncryptionKey: string;\n assembly: {\n singleReject: boolean;\n quorum: number;\n subAssemblies: {\n singleReject: boolean;\n quorum: number;\n approvers: {\n name: string;\n email: string;\n state: TpClaimApproverState;\n }[];\n }[];\n };\n approvals: {\n id: ID;\n modified: DateTime;\n approverEmail: string;\n receiverCipher: string;\n receiverCipherPartialAssemblyKey: string;\n }[];\n assemblyCipherData: string;\n wrappedAssemblyKeyVerifierPrk: string;\n requestAgainAfter: DateTime;\n };\n}\nexport const TpPasswordResetUserQuery = gqlTyped<TpPasswordResetUserQueryResult>`\nquery TpPasswordResetUserQuery {\n tpPasswordResetUser {\n username\n resetUsername\n state\n passKey {\n id\n passKeyParams\n passIdpParams\n }\n masterKey {\n id\n }\n pxk {\n id\n }\n sessionEncryptionKey\n assembly {\n singleReject\n quorum\n subAssemblies {\n singleReject\n quorum\n approvers {\n name\n email\n state\n }\n }\n }\n approvals {\n id\n modified\n approverEmail\n receiverCipher\n receiverCipherPartialAssemblyKey\n }\n assemblyCipherData\n wrappedAssemblyKeyVerifierPrk\n requestAgainAfter\n }\n}`;\n\nexport interface TpPasswordResetQueryResult {\n tpPasswordReset: {\n id: ID;\n applied: boolean;\n assembly: {\n singleReject: boolean;\n quorum: number;\n canMeetQuorum: boolean;\n subjectCipherData: string;\n subjectCipherDataClearJson: JSONObject;\n subjectKey: {\n id: ID;\n };\n assemblyKey: {\n id: ID;\n };\n assemblyCipherData: string;\n subAssemblies: {\n edges: {\n node: {\n id: ID;\n singleReject: boolean;\n quorum: number;\n subjectCipherData: string;\n subjectCipherDataClearJson: JSONObject;\n subjectKey: {\n id: ID;\n };\n approvers: {\n edges: {\n node: {\n id: ID;\n tp: {\n id: ID;\n };\n sharedKey: {\n id: ID;\n };\n sharedCipherData: string;\n };\n }[];\n };\n };\n }[];\n };\n };\n };\n}\nexport const TpPasswordResetQuery = gqlTyped<TpPasswordResetQueryResult>`\nquery TpPasswordResetQuery {\n tpPasswordReset {\n id\n applied\n assembly {\n singleReject\n quorum\n canMeetQuorum\n subjectCipherData\n subjectKey {\n id\n }\n assemblyKey {\n id\n }\n assemblyCipherData\n subAssemblies {\n edges {\n node {\n id\n singleReject\n quorum\n subjectCipherData\n subjectKey {\n id\n }\n approvers {\n edges {\n node {\n id\n tp {\n id\n }\n sharedKey {\n id\n }\n sharedCipherData\n }\n }\n }\n }\n }\n }\n }\n }\n}`;\n","import { Injectable, Injector, NgZone } from '@angular/core';\nimport { LrService } from '../api/lr-graphql';\nimport { RunOutsideAngular } from '../_common/run-outside-angular';\nimport {\n SharedTpPasswordResetQuery,\n SharedTpPasswordResetsQuery,\n TpPasswordResetQuery,\n} from './tp-password-reset.private.gql';\n\n@RunOutsideAngular({\n ngZoneName: 'ngZone',\n})\n@Injectable({\n providedIn: 'root',\n})\nexport class TpPasswordResetPrivateService extends LrService {\n constructor(private ngZone: NgZone, private injector: Injector) {\n super(injector);\n }\n\n async getReset() {\n return (\n await this.query({\n query: TpPasswordResetQuery,\n })\n ).tpPasswordReset;\n }\n\n async getSharedResets() {\n return (\n await this.query({\n query: SharedTpPasswordResetsQuery,\n })\n ).sharedTpPasswordResets;\n }\n\n async getSharedReset(id) {\n return (\n await this.query({\n query: SharedTpPasswordResetQuery,\n variables: {\n id,\n },\n })\n ).sharedTpPasswordReset;\n }\n}\n","import { Injectable, Injector, NgZone } from '@angular/core';\nimport { JWK } from 'node-jose';\nimport { LrMergedMutation, LrMutation, LrService } from '../api/lr-graphql';\nimport { TpAssemblyState, TpClaimApproverState } from '../api/types';\nimport { EncryptionService } from '../encryption/encryption.service';\nimport { KcBadStateException } from '../_common/exceptions';\nimport { RunOutsideAngular } from '../_common/run-outside-angular';\nimport {\n ApproveTpPasswordResetRequestMutation,\n RejectTpPasswordResetRequestMutation,\n} from './tp-password-reset.gql';\nimport { TpPasswordResetPrivateService } from './tp-password-reset.private.service';\n\n@RunOutsideAngular({\n ngZoneName: 'ngZone',\n})\n@Injectable({\n providedIn: 'root',\n})\nexport class TpPasswordResetRequestService extends LrService {\n constructor(\n private ngZone: NgZone,\n private injector: Injector,\n private encryptionService: EncryptionService,\n private privateService: TpPasswordResetPrivateService\n ) {\n super(injector);\n }\n\n private activeRequestOrRaise(sharedReset): void {\n const state = sharedReset.sharedRequest.claim.state;\n if (state !== TpAssemblyState.CLAIMED) {\n throw new KcBadStateException(`Claim is already in ${state} state.`);\n }\n }\n\n rejectRequest(sharedResetId: string) {\n return this.mutate(this.rejectRequestMutation(sharedResetId));\n }\n\n async rejectRequestMutation(sharedResetId: string) {\n const sharedReset = await this.privateService.getSharedReset(sharedResetId);\n\n this.activeRequestOrRaise(sharedReset);\n\n return LrMergedMutation.create(\n sharedReset.sharedRequest.claim.asClaimApprovers.edges\n .filter((edge) => edge.node.state === TpClaimApproverState.CLAIMED)\n .map(\n (edge) =>\n new LrMutation({\n mutation: RejectTpPasswordResetRequestMutation,\n variables: { input: { claimApproverId: edge.node.id } },\n })\n )\n );\n }\n\n async approveRequest(sharedResetId: string, pbkFingerPrint?: string) {\n return this.lrGraphQL.lrMutate(\n await this.approveRequestMutation(sharedResetId, pbkFingerPrint)\n );\n }\n\n async approveRequestMutation(\n sharedResetId: string,\n _pbkFingerPrint?: string\n ) {\n const sharedReset = await this.privateService.getSharedReset(sharedResetId);\n\n this.activeRequestOrRaise(sharedReset);\n\n const pbk = await JWK.asKey(JSON.parse(sharedReset.sharedRequest.pxk.pbk));\n\n // TODO <AZ> Verify pbk against pbkFingerPrint\n\n const claimApprovers =\n sharedReset.sharedRequest.claim.asClaimApprovers.edges.filter(\n (edge) => edge.node.state === TpClaimApproverState.CLAIMED\n );\n\n // A single approver may belong to multiple sub-assemblies. We approve them all here in a single\n // transaction.\n return LrMergedMutation.create(\n await Promise.all(\n claimApprovers.map(async (approverEdge) => {\n const ca = approverEdge.node;\n const input = {\n claimApproverId: ca.id,\n receiverApprovals: await Promise.all(\n ca.receiverApprovals.edges.map(async (receiverEdge) => {\n const ra = receiverEdge.node;\n return {\n receiverApprovalId: ra.id,\n receiverCipher: '',\n receiverCipherPartialAssemblyKey:\n await this.encryptionService.encryptToString(\n pbk,\n ca.sharedCipherPartialAssemblyKeyClearJson\n ),\n };\n })\n ),\n };\n\n return new LrMutation({\n mutation: ApproveTpPasswordResetRequestMutation,\n variables: {\n input,\n },\n });\n })\n )\n );\n }\n}\n","import { KcBadArgumentException } from './exceptions';\n\nconst COGNITO_LOCALSTORAGE_PREFIX = 'CognitoIdentityServiceProvider';\n\n/**\n * Remove all keys in localstorage with matching prefix.\n * A prefix must be specified. If you want to remove everything, then just use localStorage.clear().\n *\n * @param prefix Keys with this prefix will be removed.\n */\nexport function clearLocalStorage(prefix: string) {\n if (!prefix) {\n throw new KcBadArgumentException('You must specify a non empty prefix.');\n }\n\n // Remove all persisted session variables\n Object.keys(localStorage).forEach((key) => {\n if (key.startsWith(prefix)) {\n localStorage.removeItem(key);\n }\n });\n}\n\n/**\n * Clear all items related to cognito in localstorage.\n * The remember device function sometimes interferes with creating new users\n * on TP based password reset.\n */\nexport function clearCognitoLocalStorage() {\n clearLocalStorage(COGNITO_LOCALSTORAGE_PREFIX);\n}\n","import { HttpClient } from '@angular/common/http';\nimport { Inject, Injectable, Injector, NgZone } from '@angular/core';\nimport { AuthClass } from '@aws-amplify/auth/lib-esm/Auth';\nimport { ISignUpResult } from 'amazon-cognito-identity-js';\nimport { LrService } from '../api/lr-graphql';\nimport { EncryptionService } from '../encryption/encryption.service';\nimport { KeyFactoryService } from '../key/key-factory.service';\nimport { KcConfig, KC_CONFIG } from '../life-ready.config';\nimport { PasswordService } from '../password/password.service';\nimport { RunOutsideAngular } from '../_common/run-outside-angular';\nimport { clearCognitoLocalStorage } from '../_common/storage';\nimport { RequestResetResult } from './tp-password-reset.types';\n\n@RunOutsideAngular({\n ngZoneName: 'ngZone',\n})\n@Injectable({\n providedIn: 'root',\n})\nexport class TpPasswordResetUserService extends LrService {\n constructor(\n private ngZone: NgZone,\n private injector: Injector,\n @Inject(KC_CONFIG) private config: KcConfig,\n private keyFactory: KeyFactoryService,\n private encryptionService: EncryptionService,\n private passwordService: PasswordService,\n private http: HttpClient,\n private auth: AuthClass\n ) {\n super(injector);\n }\n\n async verifyEmailContact(email): Promise<{ claimId: string }> {\n const params = {\n email,\n };\n return (\n this.http\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n .post<any>(\n `${this.config.authUrl}tp/password-reset/verify-contact/`,\n params\n )\n .toPromise()\n );\n }\n\n async verifyContactRespond(\n claimId: string,\n claimCode: string\n ): Promise<string> {\n const { token } = await this.http\n .post<{ token }>(`${this.config.authUrl}cove/respond/`, {\n claim_id: claimId,\n v_code: claimCode,\n })\n .toPromise();\n return token;\n }\n\n async requestReset(\n password: CryptoKey,\n claimId: string,\n claimToken: string\n ): Promise<{\n requestResetResult: RequestResetResult;\n signUpResult: ISignUpResult;\n }> {\n // Clearing all localstorage data because cognito has the \"remember device\" functionality which sometimes\n // does not work properly. Clearing localstorage seems to solve this issue.\n clearCognitoLocalStorage();\n\n // Generate the key materials\n const passKeyBundle = await this.passwordService.createPassKeyBundle(\n password\n );\n\n const masterKey = await this.keyFactory.createKey();\n const wrappedMasterKey = await this.encryptionService.encrypt(\n passKeyBundle.passKey,\n masterKey.toJSON(true)\n );\n\n // Ephemeral PKC key\n const prk = await this.keyFactory.createPkcKey();\n const masterKeyWrappedPrk = await this.encryptionService.encrypt(\n masterKey,\n prk.toJSON(true)\n );\n\n // API call to setup reset request\n const requestResetResult = await this.http\n .post<RequestResetResult>(\n `${this.config.authUrl}tp/password-reset/request/`,\n {\n claimId,\n claimToken,\n pass_key_params: passKeyBundle.passKeyParams,\n pass_idp_params: passKeyBundle.passIdpParams,\n pass_idp_verifier_pbk: passKeyBundle.passIdpVerifier.toJSON(), // public key\n wrapped_pass_idp_verifier_prk:\n passKeyBundle.wrappedPassIdpVerifierPrk,\n wrapped_master_key: wrappedMasterKey,\n pbk: prk.toJSON(), // ephemeral public key\n master_key_wrapped_prk: masterKeyWrappedPrk,\n }\n )\n .toPromise();\n\n console.log('Using new password');\n\n // API call to create user on cognito\n const signUpResult = await this.auth.signUp({\n username: requestResetResult.reset_username,\n password: this.passwordService.getPassIdpString(passKeyBundle.passIdp),\n clientMetadata: {\n tp_password_reset_request: JSON.stringify({\n id: requestResetResult.id,\n associate_reset_user_token:\n requestResetResult.associate_reset_user_token,\n }),\n },\n });\n\n console.log('requestRest done');\n\n return {\n requestResetResult,\n signUpResult,\n };\n }\n}\n","import { Injectable, Injector, NgZone } from '@angular/core';\nimport { LrMutation, LrService } from '../api/lr-graphql';\nimport { TpNode } from '../api/types';\nimport { DebugExpireTpPasswordResetRequestMutation } from '../scenario/scenario.gql';\nimport {\n CreateTpAssemblyInput,\n UpdateTpAssemblyInput,\n} from '../tp-assembly/tp-assembly.types';\nimport { RunOutsideAngular } from '../_common/run-outside-angular';\nimport { TP_PASSWORD_RESET_SLIP39_PASSPHRASE } from './tp-password-reset.constants';\nimport { TpPasswordResetAssemblyController } from './tp-password-reset.controller';\nimport {\n CancelTpPasswordResetRequestMutation,\n CreateTpPasswordResetMutation,\n DeleteTpPasswordResetMutation,\n UpdateTpPasswordResetMutation,\n} from './tp-password-reset.gql';\nimport { TpPasswordResetPrivateService } from './tp-password-reset.private.service';\n\n@RunOutsideAngular({\n ngZoneName: 'ngZone',\n})\n@Injectable({\n providedIn: 'root',\n})\nexport class TpPasswordResetService extends LrService {\n slip39Passphrase = TP_PASSWORD_RESET_SLIP39_PASSPHRASE;\n\n constructor(\n private ngZone: NgZone,\n private injector: Injector,\n private privateService: TpPasswordResetPrivateService,\n private assemblyController: TpPasswordResetAssemblyController\n ) {\n super(injector);\n }\n\n cancelResetRequest() {\n return this.mutate(this.cancelResetRequestMutation());\n }\n\n cancelResetRequestMutation() {\n return new LrMutation({\n mutation: CancelTpPasswordResetRequestMutation,\n });\n }\n\n deleteReset() {\n return this.mutate(this.deleteResetMutation());\n }\n\n deleteResetMutation() {\n return new LrMutation({\n mutation: DeleteTpPasswordResetMutation,\n });\n }\n\n validateApprovers(approvers: TpNode[]): void {\n return this.assemblyController.validateApprovers(approvers);\n }\n\n createReset(input: CreateTpAssemblyInput) {\n return this.mutate(this.createResetMutation(input));\n }\n\n async createResetMutation(input: CreateTpAssemblyInput) {\n const { mutationInput } = await this.assemblyController.prepareCreate(\n input\n );\n\n return new LrMutation({\n mutation: CreateTpPasswordResetMutation,\n variables: {\n input: {\n assembly: {\n ...mutationInput,\n },\n },\n },\n });\n }\n\n updateReset(input: UpdateTpAssemblyInput) {\n return this.mutate(this.updateResetMutation(input));\n }\n\n async updateResetMutation(input: UpdateTpAssemblyInput) {\n const passwordReset = await this.privateService.getReset();\n\n const { mutationInput } = await this.assemblyController.prepareUpdate(\n input,\n passwordReset.assembly\n );\n\n return new LrMutation({\n mutation: UpdateTpPasswordResetMutation,\n variables: {\n input: {\n assembly: {\n ...mutationInput,\n },\n },\n },\n });\n }\n\n debugExpireResetRequest(username: string) {\n return this.mutate(this.debugExpireResetRequestMutation(username), {\n includeKeyGraph: false,\n });\n }\n\n async debugExpireResetRequestMutation(username: string) {\n return new LrMutation({\n mutation: DebugExpireTpPasswordResetRequestMutation,\n variables: {\n input: {\n username,\n },\n },\n });\n }\n}\n","import { ID } from '../api/types';\nimport { gqlTyped } from '../_common/ast';\n\nexport interface DeleteTpMutation {\n deleteTp: {\n id: ID;\n };\n}\nexport const DeleteTpMutation = gqlTyped<DeleteTpMutation>`\nmutation DeleteTpMutation($input: DeleteTpInput!) {\n deleteTp(input: $input) {\n id\n }\n}\n`;\n\nexport interface CreateDirectoryShareMutationResult {\n createDirectoryShare: {\n directoryShare: {\n id: ID;\n };\n };\n}\nexport const CreateDirectoryShareMutation = gqlTyped<CreateDirectoryShareMutationResult>`\nmutation CreateDirectoryShareMutation($input: CreateDirectoryShareInput!) {\n createDirectoryShare(input: $input) {\n directoryShare {\n id\n }\n }\n}\n`;\n\nexport interface CreateFileShareMutationResult {\n createFileShare: {\n fileShare: {\n id: ID;\n };\n };\n}\nexport const CreateFileShareMutation = gqlTyped<CreateFileShareMutationResult>`\nmutation CreateFileShareMutation($input: CreateFileShareInput!) {\n createFileShare(input: $input) {\n fileShare {\n id\n }\n }\n}\n`;\n\nexport interface UpdateDirectoryShareMutationResult {\n updateDirectoryShare: {\n directoryShare: {\n id: ID;\n };\n };\n}\nexport const UpdateDirectoryShareMutation = gqlTyped<UpdateDirectoryShareMutationResult>`\nmutation UpdateDirectoryShareMutation($input: UpdateDirectoryShareInput!) {\n updateDirectoryShare(input: $input) {\n directoryShare {\n id\n }\n }\n}\n`;\n\nexport interface UpdateFileShareMutationResult {\n updateFileShare: {\n fileShare: {\n id: ID;\n };\n };\n}\nexport const UpdateFileShareMutation = gqlTyped<UpdateFileShareMutationResult>`\nmutation UpdateFileShareMutation($input: UpdateFileShareInput!) {\n updateFileShare(input: $input) {\n fileShare {\n id\n }\n }\n}\n`;\n\nexport interface DeleteDirectoryShareMutationResult {\n deleteDirectoryShare: {\n id: ID;\n };\n}\nexport const DeleteDirectoryShareMutation = gqlTyped<DeleteDirectoryShareMutationResult>`\nmutation DeleteDirectoryShareMutation($input: DeleteDirectoryShareInput!) {\n deleteDirectoryShare(input: $input) {\n id\n }\n}\n`;\n\nexport interface DeleteFileShareMutationResult {\n deleteFileShare: {\n id: ID;\n };\n}\nexport const DeleteFileShareMutation = gqlTyped<DeleteFileShareMutationResult>`\nmutation DeleteFileShareMutation($input: DeleteFileShareInput!) {\n deleteFileShare(input: $input) {\n id\n }\n}\n`;\n\nexport interface CompleteDetachedDirectoryShareMutationResult {\n completeDetachedDirectoryShare: {\n directoryShare: {\n id: ID;\n };\n };\n}\nexport const CompleteDetachedDirectoryShareMutation = gqlTyped<CompleteDetachedDirectoryShareMutationResult>`\nmutation CompleteDetachedDirectoryShareMutation($input: CompleteDetachedDirectoryShareInput!) {\n completeDetachedDirectoryShare(input: $input) {\n directoryShare {\n id\n }\n }\n}\n`;\n\nexport interface CompleteDetachedFileShareMutationResult {\n completeDetachedDirectoryShare: {\n directoryShare: {\n id: ID;\n };\n };\n}\nexport const CompleteDetachedFileShareMutation = gqlTyped<CompleteDetachedFileShareMutationResult>`\nmutation CompleteDetachedFileShareMutation($input: CompleteDetachedFileShareInput!) {\n completeDetachedFileShare(input: $input) {\n fileShare {\n id\n }\n }\n}\n`;\n\nexport interface RequestTpMkReshareMutation {\n requestTpMkReshare: {\n id: ID;\n };\n}\nexport const RequestTpMkReshareMutation = gqlTyped<RequestTpMkReshareMutation>`\nmutation RequestTpMkReshareMutation($input: RequestTpMkReshareInput!) {\n requestTpMkReshare(input: $input) {\n id\n }\n}`;\n\nexport interface RespondTpMkReshareMutation {\n respondTpMkReshare: {\n id: ID;\n };\n}\nexport const RespondTpMkReshareMutation = gqlTyped<RespondTpMkReshareMutation>`\n mutation RespondTpMkReshareMutation($input: RespondTpMkReshareInput!) {\n respondTpMkReshare(input: $input) {\n id\n }\n }\n`;\n\nexport interface CompleteTpMkReshareMutation {\n completeTpMkReshare: {\n id: ID;\n };\n}\nexport const CompleteTpMkReshareMutation = gqlTyped<CompleteTpMkReshareMutation>`\nmutation CompleteTpMkReshareMutation($input: CompleteTpMkReshareInput!) {\n completeTpMkReshare(input: $input) {\n id\n }\n}`;\n","import { ID } from '../api/types';\nimport { gqlTyped } from '../_common/ast';\n\nexport interface TpCurrentUserSharedKeyQuery {\n tp: {\n currentUserSharedKey: {\n userSharedKey: {\n sharedKey: {\n id: ID;\n };\n mkSharedKey: {\n id: ID;\n };\n mkPxk: {\n id: ID;\n };\n mkReshareRequestCipher: string;\n mkReshareRequestSent: boolean;\n mkReshareResponseCipher: string;\n mkReshareResponseSent: boolean;\n };\n };\n };\n}\nexport const TpCurrentUserSharedKeyQuery = gqlTyped<TpCurrentUserSharedKeyQuery>`\nquery TpCurrentUserSharedKeyQuery($id: LrRelayIdInput!) {\n tp(id: $id){\n currentUserSharedKey {\n userSharedKey {\n sharedKey {\n id\n }\n mkSharedKey {\n id\n }\n mkPxk {\n id\n }\n mkReshareRequestCipher\n mkReshareRequestSent\n mkReshareResponseCipher\n mkReshareResponseSent\n }\n }\n }\n}\n`;\n\nexport interface ItemShareQueryResult {\n item: {\n id: string;\n };\n tp: {\n id: string;\n };\n}\n\nexport interface DirectoryShareQueryResult {\n directoryShare: ItemShareQueryResult;\n}\nexport const DirectoryShareQuery = gqlTyped<DirectoryShareQueryResult>`\nquery DirectoryShareQuery($id: LrRelayIdInput!) {\n directoryShare(id: $id) {\n item {\n id\n }\n tp {\n id\n }\n }\n}\n`;\n\nexport interface FileShareQueryResult {\n fileShare: ItemShareQueryResult;\n}\nexport const FileShareQuery = gqlTyped<FileShareQueryResult>`\nquery FileShareItemIdQuery($id: LrRelayIdInput!) {\n fileShare(id: $id) {\n item {\n id\n }\n tp {\n id\n }\n }\n}\n`;\n","import { Injectable, Injector, NgZone } from '@angular/core';\nimport { JWK } from 'node-jose';\nimport { LrMutation, LrService } from '../api/lr-graphql';\nimport { AccessRoleChoice, LrRelayIdInput } from '../api/types';\nimport { EncryptionService } from '../encryption/encryption.service';\nimport { ItemService } from '../item/item.service';\nimport { KeyFactoryService } from '../key/key-factory.service';\nimport { KeyGraphService } from '../key/key-graph.service';\nimport { KeyService } from '../key/key.service';\nimport { Key } from '../key/key.types';\nimport {\n KcBadArgumentException,\n KcBadStateException,\n} from '../_common/exceptions';\nimport { RunOutsideAngular } from '../_common/run-outside-angular';\nimport {\n CompleteDetachedDirectoryShareMutation,\n CompleteDetachedFileShareMutation,\n CompleteTpMkReshareMutation,\n CreateDirectoryShareMutation,\n CreateFileShareMutation,\n DeleteDirectoryShareMutation,\n DeleteFileShareMutation,\n DeleteTpMutation,\n RequestTpMkReshareMutation,\n RespondTpMkReshareMutation,\n UpdateDirectoryShareMutation,\n UpdateFileShareMutation,\n} from './trusted-party.gql';\nimport {\n DirectoryShareQuery,\n DirectoryShareQueryResult,\n FileShareQuery,\n FileShareQueryResult,\n ItemShareQueryResult,\n TpCurrentUserSharedKeyQuery,\n} from './trusted-party.gql.private';\nimport {\n CompleteDetachedItemShareOptions,\n CreateItemShareOptions,\n UpdateItemShareOptions,\n} from './trusted-party.types';\n\n@RunOutsideAngular({\n ngZoneName: 'ngZone',\n})\n@Injectable({\n providedIn: 'root',\n})\nexport class TrustedPartyService extends LrService {\n constructor(\n private ngZone: NgZone,\n private injector: Injector,\n private keyGraph: KeyGraphService,\n private itemService: ItemService,\n private keyService: KeyService,\n private keyFactory: KeyFactoryService,\n private encryptionService: EncryptionService\n ) {\n super(injector);\n }\n\n deleteTp(tpId: LrRelayIdInput) {\n return this.mutate(this.deleteTpMutation(tpId));\n }\n\n deleteTpMutation(tpId: LrRelayIdInput) {\n return new LrMutation({\n mutation: DeleteTpMutation,\n variables: {\n input: {\n id: tpId,\n },\n },\n });\n }\n\n async createDirectoryShare(options: CreateItemShareOptions) {\n return this.mutate(this.createDirectoryShareMutation(options));\n }\n\n async createDirectoryShareMutation(options: CreateItemShareOptions) {\n return new LrMutation({\n mutation: CreateDirectoryShareMutation,\n variables: await this.prepareCreateItemShareMutation({\n ...options,\n isDirectory: true,\n }),\n });\n }\n\n async createFileShare(options: CreateItemShareOptions) {\n return this.mutate(this.createFileShareMutation(options));\n }\n\n async createFileShareMutation(options: CreateItemShareOptions) {\n return new LrMutation({\n mutation: CreateFileShareMutation,\n variables: await this.prepareCreateItemShareMutation({\n ...options,\n isDirectory: false,\n }),\n });\n }\n\n private async prepareCreateItemShareMutation(\n options: CreateItemShareOptions & { isDirectory: boolean }\n ) {\n const {\n itemId,\n itemKeyId,\n tpId,\n tpSharedKeyId,\n accessRole,\n isDirectory,\n shareType,\n } = options;\n\n if (accessRole == AccessRoleChoice.DENY) {\n if (itemKeyId || tpSharedKeyId) {\n throw new KcBadArgumentException(\n 'If accessRole is AccessRoleChoice.DENY, must not specify any of itemId, itemKeyId, or tpSharedKeyId parameters'\n );\n }\n\n return {\n input: {\n itemId,\n tpId,\n accessRole,\n itemKeyId: null,\n wrappingKeyId: null,\n wrappedItemKey: null,\n shareType,\n },\n };\n }\n\n const itemKey = await this.keyGraph.getKey(itemKeyId, () =>\n isDirectory\n ? this.itemService.getDirectoryKeyId(itemId)\n : this.itemService.getFileKeyId(itemId)\n );\n\n const wrappingKey = await this.keyGraph.getKey(tpSharedKeyId, () =>\n this.getTpCurrentUserSharedKey(tpId).then((res) => res.sharedKey.id)\n );\n const wrappedItemKey = await this.keyGraph.wrapKey(\n wrappingKey,\n itemKey.jwk\n );\n\n return {\n input: {\n itemId,\n tpId,\n accessRole,\n itemKeyId: itemKey.id,\n wrappingKeyId: wrappingKey.id,\n wrappedItemKey,\n shareType,\n },\n };\n }\n\n async updateDirectoryShare(options: UpdateItemShareOptions) {\n return this.mutate(this.updateDirectoryShareMutation(options));\n }\n\n async updateDirectoryShareMutation(options: UpdateItemShareOptions) {\n return new LrMutation({\n mutation: UpdateDirectoryShareMutation,\n variables: await this.prepareUpdateItemShareMutation({\n ...options,\n isDirectory: true,\n }),\n });\n }\n\n async updateFileShare(options: UpdateItemShareOptions) {\n return this.mutate(this.updateFileShareMutation(options));\n }\n\n async updateFileShareMutation(options: UpdateItemShareOptions) {\n return new LrMutation({\n mutation: UpdateFileShareMutation,\n variables: await this.prepareUpdateItemShareMutation({\n ...options,\n isDirectory: false,\n }),\n });\n }\n\n private getDirectoryShare(\n itemShareId: string\n ): Promise<DirectoryShareQueryResult> {\n return this.lrGraphQL.query({\n query: DirectoryShareQuery,\n variables: {\n id: itemShareId,\n },\n });\n }\n\n private getFileShare(itemShareId: string): Promise<FileShareQueryResult> {\n return this.lrGraphQL.query({\n query: FileShareQuery,\n variables: {\n id: itemShareId,\n },\n });\n }\n\n private async prepareUpdateItemShareMutation(\n options: UpdateItemShareOptions & { isDirectory: boolean }\n ) {\n const {\n itemShareId,\n accessRole,\n isDirectory,\n itemId,\n itemKeyId,\n tpId,\n tpSharedKeyId,\n } = options;\n\n if (accessRole == AccessRoleChoice.DENY) {\n if (itemId || itemKeyId || tpId || tpSharedKeyId) {\n throw new KcBadArgumentException(\n 'If accessRole is AccessRoleChoice.DENY, must not specify any of itemId, itemKeyId, tpId, or tpSharedKeyId parameters'\n );\n }\n\n return {\n input: {\n id: itemShareId,\n accessRole,\n itemKeyId: null,\n wrappingKeyId: null,\n wrappedItemKey: null,\n },\n };\n }\n\n // Caching the result so we only need one call.\n let itemShare: ItemShareQueryResult;\n\n const getItemShare = async (): Promise<ItemShareQueryResult> => {\n if (!itemShare) {\n if (isDirectory) {\n itemShare = (await this.getDirectoryShare(itemShareId))\n .directoryShare;\n } else {\n itemShare = (await this.getFileShare(itemShareId)).fileShare;\n }\n }\n\n return itemShare;\n };\n\n const itemKey = await this.keyGraph.getKey(\n itemKeyId,\n async (): Promise<string> => {\n const itemId_ = itemId || (await getItemShare()).item.id;\n if (isDirectory) {\n return this.itemService.getDirectoryKeyId(itemId_);\n } else {\n return this.itemService.getFileKeyId(itemId_);\n }\n }\n );\n\n const wrappingKey = await this.keyGraph.getKey(\n tpSharedKeyId,\n async (): Promise<string> => {\n const tpId_ = tpId || (await getItemShare()).tp.id;\n return (await this.getTpCurrentUserSharedKey(tpId_)).sharedKey.id;\n }\n );\n\n const wrappedItemKey = await this.keyGraph.wrapKey(\n wrappingKey,\n itemKey.jwk\n );\n\n return {\n input: {\n id: itemShareId,\n accessRole,\n itemKeyId: itemKey.id,\n wrappingKeyId: wrappingKey.id,\n wrappedItemKey,\n },\n };\n }\n\n async deleteDirectoryShare(id: string) {\n return this.mutate(this.deleteDirectoryShareMutation(id));\n }\n\n async deleteDirectoryShareMutation(id: string) {\n return new LrMutation({\n mutation: DeleteDirectoryShareMutation,\n variables: {\n input: {\n id,\n },\n },\n });\n }\n\n async deleteFileShare(id: string) {\n return this.mutate(this.deleteFileShareMutation(id));\n }\n\n async deleteFileShareMutation(id: string) {\n return new LrMutation({\n mutation: DeleteFileShareMutation,\n variables: {\n input: {\n id,\n },\n },\n });\n }\n\n async completeDetachedDirectoryShare(\n options: CompleteDetachedItemShareOptions\n ) {\n return this.mutate(this.completeDetachedDirectoryShareMutation(options));\n }\n\n async completeDetachedDirectoryShareMutation(\n options: CompleteDetachedItemShareOptions\n ) {\n return new LrMutation({\n mutation: CompleteDetachedDirectoryShareMutation,\n variables: await this.prepareCompleteDetachedItemShareMutation({\n ...options,\n isDirectory: true,\n }),\n });\n }\n\n async completeDetachedFileShare(options: CompleteDetachedItemShareOptions) {\n return this.mutate(this.completeDetachedFileShareMutation(options));\n }\n\n async completeDetachedFileShareMutation(\n options: CompleteDetachedItemShareOptions\n ) {\n return new LrMutation({\n mutation: CompleteDetachedFileShareMutation,\n variables: await this.prepareCompleteDetachedItemShareMutation({\n ...options,\n isDirectory: false,\n }),\n });\n }\n\n private async prepareCompleteDetachedItemShareMutation(\n options: CompleteDetachedItemShareOptions & { isDirectory: boolean }\n ) {\n const { itemShareId, itemKeyId, isDirectory } = options;\n\n const itemKey = await this.keyGraph.getKey(itemKeyId, () =>\n isDirectory\n ? this.itemService.getDirectoryKeyIdFromDirectoryShare(itemShareId)\n : this.itemService.getFileKeyIdFromFileShare(itemShareId)\n );\n\n const rootKey = this.keyService.currentRootKey;\n\n const wrappedKey = await this.keyGraph.wrapKey(rootKey, itemKey.jwk);\n\n return {\n input: {\n id: itemShareId,\n keyId: itemKey.id,\n wrappingKeyId: rootKey.id,\n wrappedKey,\n },\n };\n }\n\n async requestMkReshareMutation(tpId: LrRelayIdInput) {\n const userSharedKey = await this.getTpCurrentUserSharedKey(tpId);\n\n if (userSharedKey.mkSharedKey) {\n throw new KcBadStateException('TP already has mkSharedKey');\n }\n\n const masterKey = this.keyService.currentMasterKey;\n const prk = await this.keyFactory.createPkcKey();\n const mkWrappedMkPrk = await this.encryptionService.encryptToString(\n masterKey.jwk,\n prk.toJSON(true)\n );\n\n const sharedKey = await this.keyGraph.getKey(userSharedKey.sharedKey.id);\n const mkReshareRequestCipher = await this.encryptionService.encryptToString(\n sharedKey.jwk,\n {\n pbk: prk.toJSON(),\n }\n );\n\n return await new LrMutation({\n mutation: RequestTpMkReshareMutation,\n variables: {\n input: {\n tpId,\n masterKeyId: masterKey.id,\n mkPbk: JSON.stringify(prk.toJSON()),\n mkWrappedMkPrk,\n sharedKeyId: sharedKey.id,\n mkReshareRequestCipher,\n },\n },\n });\n }\n\n async respondMkReshare(tpId: LrRelayIdInput) {\n const userSharedKey = await this.getTpCurrentUserSharedKey(tpId);\n\n if (!userSharedKey.mkSharedKey) {\n throw new KcBadStateException(\n 'No access to the mkSharedKey so cannot reshare it with TP'\n );\n }\n\n const sharedKey = await this.keyGraph.getKey(userSharedKey.sharedKey.id);\n const plainMkReshareRequestCipher = await this.encryptionService.decrypt(\n sharedKey,\n userSharedKey.mkReshareRequestCipher\n );\n const pbk = await JWK.asKey(plainMkReshareRequestCipher.pbk);\n const mkSharedKey = await this.keyGraph.getKey(\n userSharedKey.mkSharedKey.id\n );\n\n const plainMkReshareResponseCipher = {\n mkSharedKey: {\n id: mkSharedKey.id,\n jwk: mkSharedKey.jwk.toJSON(true),\n },\n };\n\n // Wrap with sharedKey then again with Pbk\n const mkReshareResponseCipher =\n await this.encryptionService.encryptToString(\n pbk,\n await this.encryptionService.encryptToString(\n sharedKey.jwk,\n plainMkReshareResponseCipher\n )\n );\n\n return new LrMutation({\n mutation: RespondTpMkReshareMutation,\n variables: {\n input: {\n tpId,\n mkSharedKeyId: mkSharedKey.id,\n mkReshareResponseCipher,\n },\n },\n });\n }\n\n async completeMkReshare(tpId: LrRelayIdInput) {\n const userSharedKey = await this.getTpCurrentUserSharedKey(tpId);\n\n const sharedKey = await this.keyGraph.getKey(userSharedKey.sharedKey.id);\n const prk = await this.keyGraph.getKey(userSharedKey.mkPxk.id);\n const plainMkReshareResponseCipher = await this.encryptionService.decrypt(\n sharedKey,\n await this.encryptionService.decrypt(\n prk,\n userSharedKey.mkReshareResponseCipher\n )\n );\n\n // Double check it's a valid key.\n const mkSharedKey: Key = {\n id: plainMkReshareResponseCipher.mkSharedKey.id,\n jwk: await JWK.asKey(plainMkReshareResponseCipher.mkSharedKey.jwk),\n };\n\n const masterKey = this.keyService.currentMasterKey;\n const mkWrappedMkSharedKey = await this.encryptionService.encryptToString(\n masterKey.jwk,\n mkSharedKey.jwk.toJSON(true)\n );\n\n return new LrMutation({\n mutation: CompleteTpMkReshareMutation,\n variables: {\n input: {\n tpId,\n masterKeyId: masterKey.id,\n mkSharedKeyId: mkSharedKey.id,\n mkWrappedMkSharedKey,\n },\n },\n });\n }\n\n // ------------------------------------------------------------------------------------\n // ------------------------------------------------------------------------------------\n // Helpers\n // ------------------------------------------------------------------------------------\n // ------------------------------------------------------------------------------------\n private async getTpCurrentUserSharedKey(tpId: LrRelayIdInput) {\n return (\n await this.lrGraphQL.query({\n query: TpCurrentUserSharedKeyQuery,\n variables: {\n id: tpId,\n },\n })\n ).tp.currentUserSharedKey.userSharedKey;\n }\n}\n","import { Injectable } from '@angular/core';\nimport { CognitoUser } from '@aws-amplify/auth';\nimport { AuthClass } from '@aws-amplify/auth/lib-esm/Auth';\nimport { KcBadArgumentException } from '../_common/exceptions';\n\n@Injectable({\n providedIn: 'root',\n})\nexport class TwoFactorService {\n constructor(private auth: AuthClass) {}\n\n public async getPreferredMFA(): Promise<string> {\n const cognitoUser: CognitoUser = await this.auth.currentAuthenticatedUser();\n\n return await this.auth.getPreferredMFA(cognitoUser);\n }\n\n public async setPreferredMFA(\n method: 'TOTP' | 'SMS' | 'NOMFA'\n ): Promise<void> {\n const cognitoUser: CognitoUser = await this.auth.currentAuthenticatedUser();\n\n await this.auth.setPreferredMFA(cognitoUser, method);\n }\n\n public async setPhoneNumber(phone): Promise<void> {\n const cognitoUser: CognitoUser = await this.auth.currentAuthenticatedUser();\n\n await this.auth.updateUserAttributes(cognitoUser, {\n phone_number: phone,\n });\n }\n\n public async getSMSCode() {\n await this.auth.verifyCurrentUserAttribute('phone_number');\n }\n\n public async verifySMSCode(verificationCode: string) {\n await this.auth.verifyCurrentUserAttributeSubmit(\n 'phone_number',\n verificationCode\n );\n }\n\n public async getSoftwareToken(): Promise<{ code: string; codeUri: string }> {\n const [cognitoUser, userInfo] = await Promise.all([\n this.auth.currentAuthenticatedUser(),\n this.auth.currentUserInfo(),\n ]);\n\n const code = await this.auth.setupTOTP(cognitoUser);\n\n const email = userInfo.attributes.email;\n if (!email) {\n throw new KcBadArgumentException('No email associated with user.');\n }\n\n return {\n code,\n codeUri: `otpauth://totp/${email}?secret=${code}&issuer=LifeReady`,\n };\n }\n\n public async verifySoftwareToken(totpCode: string): Promise<void> {\n const cognitoUser: CognitoUser = await this.auth.currentAuthenticatedUser();\n\n await this.auth.verifyTotpToken(cognitoUser, totpCode);\n }\n}\n","import gql from 'graphql-tag';\nimport { HasKeyGraph } from '../key/key.types';\nimport { User } from './user.types';\n\nexport interface UserQueryType extends HasKeyGraph {\n user: User;\n}\n\nexport const RequestUserDeleteMutation = gql`\n mutation RequestUserDelete($input: RequestUserDeleteInput!) {\n requestUserDelete(input: $input) {\n userDelete {\n state\n created\n }\n }\n }\n`;\n\nexport const CancelUserDeleteMutation = gql`\n mutation CancelUserDelete($input: CancelUserDeleteInput!) {\n cancelUserDelete(input: $input) {\n id\n }\n }\n`;\n\nexport const LoginHistoryQuery = gql`\n query LoginHistory($first: Int, $after: String) {\n loginHistory(first: $first, after: $after) {\n pageInfo {\n hasNextPage\n hasPreviousPage\n startCursor\n endCursor\n }\n events\n }\n }\n`;\n","/* eslint-disable @typescript-eslint/no-explicit-any */\nimport { Injectable } from '@angular/core';\nimport { LrApolloService } from '../api/lr-apollo.service';\nimport { UserDeleteNode } from '../api/types';\nimport {\n CancelUserDeleteMutation,\n LoginHistoryQuery,\n RequestUserDeleteMutation,\n} from './user.gql';\n\n@Injectable({\n providedIn: 'root',\n})\nexport class UserService {\n constructor(private lrApollo: LrApolloService) {}\n\n async requestUserDelete(): Promise<UserDeleteNode> {\n const res = await this.lrApollo.mutate<{ requestUserDelete: any }>({\n mutation: RequestUserDeleteMutation,\n variables: {\n input: {},\n },\n });\n\n return res.requestUserDelete.userDelete;\n }\n\n async cancelUserDelete(): Promise<string> {\n const res = await this.lrApollo.mutate<{ cancelUserDelete: any }>({\n mutation: CancelUserDeleteMutation,\n variables: {\n input: {},\n },\n });\n\n return res.cancelUserDelete.id;\n }\n\n async loginHistory(first: number = null, after: string = null): Promise<any> {\n // first: return first n entries\n // after: pass in the pageInfo.endCursor to paginate\n const res = await this.lrApollo.query<{ loginHistory: any }>({\n query: LoginHistoryQuery,\n variables: {\n first,\n after,\n },\n });\n\n return res.loginHistory;\n }\n}\n","/*\n * Public API Surface of lr-auth\n */\n\nexport * from './lib/api/lr-apollo.service';\nexport * from './lib/api/lr-graphql';\nexport * from './lib/api/query-processor';\nexport * from './lib/api/types';\nexport * from './lib/auth/auth.config';\nexport * from './lib/auth/auth.service';\nexport * from './lib/auth/auth.types';\nexport * from './lib/contact-card/contact-card2.service';\nexport * from './lib/file-upload/file-upload.service';\nexport * from './lib/idle/idle.service';\nexport * from './lib/idle/idle.types';\nexport * from './lib/item/item.gql';\nexport * from './lib/item/item.service';\nexport * from './lib/item/item.types';\nexport * from './lib/key-exchange/key-exchange.gql';\nexport * from './lib/key-exchange/key-exchange.service';\nexport * from './lib/lbop/lbop.service';\nexport * from './lib/life-ready.config';\nexport * from './lib/life-ready.module';\nexport * from './lib/lock/lock.service';\nexport * from './lib/notification/notification.service';\nexport * from './lib/password/password.service';\nexport * from './lib/persist/persist.service';\nexport * from './lib/plan/plan.service';\nexport * from './lib/plan/plan.types';\nexport * from './lib/profile/profile-details.service';\nexport * from './lib/profile/profile.gql';\nexport * from './lib/profile/profile.service';\nexport * from './lib/profile/profile.types';\nexport * from './lib/register/register.service';\nexport * from './lib/register/register.types';\nexport * from './lib/reminder/reminder.service';\nexport * from './lib/reminder/reminder.types';\nexport * from './lib/scenario/scenario.gql';\nexport * from './lib/scenario/scenario.service';\nexport * from './lib/scenario/scenario.types';\nexport * from './lib/server-config/server-config.service';\nexport * from './lib/shared-contact-card/shared-contact-card2.gql';\nexport * from './lib/shared-contact-card/shared-contact-card2.service';\nexport * from './lib/time/time.service';\nexport * from './lib/tp-assembly/tp-assembly.types';\nexport * from './lib/tp-password-reset/tp-password-reset-request.service';\nexport * from './lib/tp-password-reset/tp-password-reset-user.service';\nexport * from './lib/tp-password-reset/tp-password-reset.gql';\nexport * from './lib/tp-password-reset/tp-password-reset.service';\nexport * from './lib/tp-password-reset/tp-password-reset.types';\nexport * from './lib/trusted-party/trusted-party.service';\nexport * from './lib/trusted-party/trusted-party.types';\nexport * from './lib/two-factor/two-factor.service';\nexport * from './lib/user/user.gql';\nexport * from './lib/user/user.service';\nexport * from './lib/user/user.types';\nexport * from './lib/web-crypto/web-crypto.service';\nexport { gqlTyped } from './lib/_common/ast';\nexport * from './lib/_common/exceptions';\nexport * from './lib/_common/queries.gql';\n","/**\n * Generated bundle index. Do not edit.\n */\n\nexport * from './public-api';\n\nexport {RunOutsideAngular as ɵf} from './lib/_common/run-outside-angular';\nexport {LrGraphQLService as ɵg,LrService as ɵe} from './lib/api/lr-graphql';\nexport {EncryptionService as ɵb} from './lib/encryption/encryption.service';\nexport {KeyFactoryService as ɵd} from './lib/key/key-factory.service';\nexport {KeyGraphService as ɵa} from './lib/key/key-graph.service';\nexport {KeyMetaService as ɵh} from './lib/key/key-meta.service';\nexport {KeyService as ɵc} from './lib/key/key.service';\nexport {ScenarioAssemblyController as ɵm} from './lib/scenario/scenario.controller';\nexport {SharedContactCardFields as ɵk,SharedContactCardService as ɵl} from './lib/shared-contact-card/shared-contact-card.service';\nexport {TpAssemblyController as ɵj} from './lib/tp-assembly/tp-assembly';\nexport {TpPasswordResetAssemblyController as ɵi} from './lib/tp-password-reset/tp-password-reset.controller';\nexport {TpPasswordResetPrivateService as ɵn} from './lib/tp-password-reset/tp-password-reset.private.service';"],"names":["lodash.omit","KFS","lodash.cloneDeep","ast.name","gqlPrinter.print","CreateContactCardMutation","UpdateContactCardMutation","moment","slip.Slip39Service","slip.Assembly","slip.SubAssembly","CurrentUserQuery","DeleteContactCardMutation","DirectoryKeyQuery","lodash.isEqual"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AAoDA,IAAY,gBAGX;AAHD,WAAY,gBAAgB;IAC1B,+BAAW,CAAA;IACX,uCAAmB,CAAA;AACrB,CAAC,EAHW,gBAAgB,KAAhB,gBAAgB,QAG3B;AAOD,IAAY,gBAGX;AAHD,WAAY,gBAAgB;IAC1B,uCAAmB,CAAA;IACnB,+CAA2B,CAAA;AAC7B,CAAC,EAHW,gBAAgB,KAAhB,gBAAgB,QAG3B;AAmBD,IAAY,WAGX;AAHD,WAAY,WAAW;IACrB,4BAAa,CAAA;IACb,4CAA6B,CAAA;AAC/B,CAAC,EAHW,WAAW,KAAX,WAAW;;ACpFvB;;SCIgB,iBAAiB,CAAC,MAAmC;IACnE,IAAI,CAAC,MAAM,IAAI,CAAC,MAAM,CAAC,MAAM;QAAE,OAAO;IAEtC,MAAM,QAAQ,GAAG,MAAM,CAAC,GAAG,CAAC,CAAC,CAAC;QAC5B,OAAO,IAAI,OAAO,CAAC;YACjB,IAAI,EAAE,CAAC,CAAC,UAAU,IAAI,CAAC,CAAC,UAAU,CAAC,IAAI;YACvC,MAAM,EAAE,CAAC,CAAC,UAAU,IAAI,CAAC,CAAC,UAAU,CAAC,MAAM;YAC3C,IAAI,EAAE,C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AAQ,CAAC,MAAM,CAA4B;gBAChE,QAAQ,EAAE,wBAAwB;gBAClC,SAAS,EAAE;oBACT,KAAK,EAAE,EAAE;iBACV;aACF,CAAC,CAAC;YAEH,OAAO,GAAG,CAAC,gBAAgB,CAAC,EAAE,CAAC;SAChC;KAAA;IAEK,YAAY,CAAC,QAAgB,IAAI,EAAE,QAAgB,IAAI;;;;YAG3D,MAAM,GAAG,GAAG,MAAM,IAAI,CAAC,QAAQ,CAAC,KAAK,CAAwB;gBAC3D,KAAK,EAAE,iBAAiB;gBACxB,SAAS,EAAE;oBACT,KAAK;oBACL,KAAK;iBACN;aACF,CAAC,CAAC;YAEH,OAAO,GAAG,CAAC,YAAY,CAAC;SACzB;KAAA;;;;YAxCF,UAAU,SAAC;gBACV,UAAU,EAAE,MAAM;aACnB;;;YAVQ,eAAe;;;ACFxB;;;;ACAA;;;;;;"}
|
|
1
|
+
{"version":3,"file":"lifeready-core.js","sources":["../../../../projects/core/src/lib/key/key.types.ts","../../../../projects/core/src/lib/_common/kc-lodash.ts","../../../../projects/core/src/lib/_common/exceptions.ts","../../../../projects/core/src/lib/_common/utils.ts","../../../../projects/core/src/lib/time/time.service.ts","../../../../projects/core/src/lib/encryption/encryption.service.ts","../../../../projects/core/src/lib/web-crypto/web-crypto.service.ts","../../../../projects/core/src/lib/key/key-factory.service.ts","../../../../projects/core/src/lib/life-ready.config.ts","../../../../projects/core/src/lib/persist/persist.service.ts","../../../../projects/core/src/lib/key/key.service.ts","../../../../projects/core/src/lib/key/key-graph.service.ts","../../../../projects/core/src/lib/api/lr-apollo.service.ts","../../../../projects/core/src/lib/_common/ast.ts","../../../../projects/core/src/lib/_common/queries.gql.ts","../../../../projects/core/src/lib/_common/run-outside-angular.ts","../../../../projects/core/src/lib/api/query-processor/common-processors.service.ts","../../../../projects/core/src/lib/api/query-processor/tp-password-reset-processor.service.ts","../../../../projects/core/src/lib/api/query-processor/query-processor.service.ts","../../../../projects/core/src/lib/_common/deferred-promise.ts","../../../../projects/core/src/lib/api/lr-graphql/lr-mutation-base.ts","../../../../projects/core/src/lib/api/lr-graphql/lr-mutation.ts","../../../../projects/core/src/lib/api/lr-graphql/lr-merged-mutation.ts","../../../../projects/core/src/lib/api/lr-graphql/lr-graphql.service.ts","../../../../projects/core/src/lib/api/lr-graphql/lr.service.ts","../../../../projects/core/src/lib/api/types/graphql.types.ts","../../../../projects/core/src/lib/api/types/lr-graphql.types.ts","../../../../projects/core/src/lib/auth/auth.config.ts","../../../../projects/core/src/lib/idle/idle.types.ts","../../../../projects/core/src/lib/idle/idle.service.ts","../../../../projects/core/src/lib/contact-card/contact-card.gql.ts","../../../../projects/core/src/lib/key/key-meta.service.ts","../../../../projects/core/src/lib/key-exchange/key-exchange.gql.ts","../../../../projects/core/src/lib/profile/profile.types.ts","../../../../projects/core/src/lib/shared-contact-card/shared-contact-card.service.ts","../../../../projects/core/src/lib/profile/profile.gql.ts","../../../../projects/core/src/lib/profile/profile.service.ts","../../../../projects/core/src/lib/password/password.gql.ts","../../../../projects/core/src/lib/password/password.service.ts","../../../../projects/core/src/lib/tp-password-reset/tp-password-reset.constants.ts","../../../../projects/core/src/lib/slip39/slip39.service.ts","../../../../projects/core/src/lib/tp-assembly/tp-assembly.private.gql.ts","../../../../projects/core/src/lib/tp-assembly/tp-assembly.ts","../../../../projects/core/src/lib/tp-password-reset/tp-password-reset.controller.ts","../../../../projects/core/src/lib/tp-password-reset/tp-password-reset.gql.ts","../../../../projects/core/src/lib/_common/key.ts","../../../../projects/core/src/lib/auth/auth.gql.private.ts","../../../../projects/core/src/lib/auth/auth.types.ts","../../../../projects/core/src/lib/auth/auth.service.ts","../../../../projects/core/src/lib/contact-card/contact-card2.gql.ts","../../../../projects/core/src/lib/contact-card/contact-card2.service.ts","../../../../projects/core/src/lib/file-upload/file-upload.service.ts","../../../../projects/core/src/lib/item/item.gql.ts","../../../../projects/core/src/lib/lock/lock.gql.ts","../../../../projects/core/src/lib/lock/lock.service.ts","../../../../projects/core/src/lib/item/item.gql.private.ts","../../../../projects/core/src/lib/item/item.service.ts","../../../../projects/core/src/lib/key-exchange/key-exchange.service.ts","../../../../projects/core/src/lib/lbop/lbop.service.ts","../../../../projects/core/src/lib/life-ready.module.ts","../../../../projects/core/src/lib/notification/notification.gql.ts","../../../../projects/core/src/lib/notification/notification.service.ts","../../../../projects/core/src/lib/plan/plan.gql.ts","../../../../projects/core/src/lib/plan/plan.service.ts","../../../../projects/core/src/lib/profile/profile-details.service.ts","../../../../projects/core/src/lib/register/register.service.ts","../../../../projects/core/src/lib/register/register.types.ts","../../../../projects/core/src/lib/reminder/reminder.gql.ts","../../../../projects/core/src/lib/reminder/reminder.service.ts","../../../../projects/core/src/lib/scenario/scenario.gql.ts","../../../../projects/core/src/lib/scenario/scenario.constants.ts","../../../../projects/core/src/lib/scenario/scenario.controller.ts","../../../../projects/core/src/lib/scenario/scenario.private.gql.ts","../../../../projects/core/src/lib/scenario/scenario.service.ts","../../../../projects/core/src/lib/server-config/server-config.gql.ts","../../../../projects/core/src/lib/server-config/server-config.service.ts","../../../../projects/core/src/lib/shared-contact-card/shared-contact-card2.gql.ts","../../../../projects/core/src/lib/shared-contact-card/shared-contact-card2.service.ts","../../../../projects/core/src/lib/tp-password-reset/tp-password-reset.private.gql.ts","../../../../projects/core/src/lib/tp-password-reset/tp-password-reset.private.service.ts","../../../../projects/core/src/lib/tp-password-reset/tp-password-reset-request.service.ts","../../../../projects/core/src/lib/_common/storage.ts","../../../../projects/core/src/lib/tp-password-reset/tp-password-reset-user.service.ts","../../../../projects/core/src/lib/tp-password-reset/tp-password-reset.service.ts","../../../../projects/core/src/lib/trusted-party/trusted-party.gql.ts","../../../../projects/core/src/lib/trusted-party/trusted-party.gql.private.ts","../../../../projects/core/src/lib/trusted-party/trusted-party.service.ts","../../../../projects/core/src/lib/two-factor/two-factor.service.ts","../../../../projects/core/src/lib/user/user.gql.ts","../../../../projects/core/src/lib/user/user.service.ts","../../../../projects/core/src/public-api.ts","../../../../projects/core/src/lifeready-core.ts"],"sourcesContent":["import { JWK } from 'node-jose';\nimport { JSONObject, PassKeyNode } from '../api/types';\nimport { HasEdges, SomeRequired } from '../_common/types';\n\nexport interface Key {\n id: string;\n pbk?: string;\n jwk?: JWK.Key;\n}\n\nexport interface PassKeyParams {\n kid: string;\n salt: string;\n iterations: number;\n}\n\nexport interface PassIdpParams {\n salt: string;\n iterations: number;\n}\n\nexport interface LbopKeyParams {\n kid: string;\n salt: string;\n iterations: number;\n}\n\nexport interface PassIdpVerifier {\n wrappedPrK: Record<string, JSONObject>;\n pbk: Record<string, JSONObject>;\n}\n\nexport interface LbopKeyVerifier {\n wrappedKey: Record<string, JSONObject>;\n key: Record<string, JSONObject>;\n}\n\nexport type PassKey = SomeRequired<PassKeyNode, 'id'>;\n\nexport interface KeyLink {\n keyId: string;\n wrappingKeyId: string;\n nestedWrappingKeyIds: string[];\n wrappedKey: string; // JWE json string\n}\n\nexport interface PassKeyLink {\n keyId: string;\n passKeyId: string;\n wrappedKey: string; // JWE json string\n}\n\nexport enum KeyGraphNodeType {\n Key = 'key',\n PassKey = 'passKey',\n}\n\nexport interface KeyGraphNode {\n type: KeyGraphNodeType;\n data: Key | PassKey;\n}\n\nexport enum KeyGraphEdgeType {\n KeyLink = 'keyLink',\n PassKeyLink = 'passKeyLink',\n}\n\nexport interface KeyGraphEdge {\n type: KeyGraphEdgeType;\n data: KeyLink | PassKeyLink;\n}\n\nexport interface KeyGraphResponse {\n keys?: Key[];\n keyLinks?: KeyLink[];\n passKeys?: PassKey[];\n passKeyLinks?: PassKeyLink[];\n}\n\nexport interface HasKeyGraph {\n // The name of the keyGraph field returned from both queries and mutations are the same\n keyGraph?: KeyGraphResponse;\n}\n\nexport enum PayloadType {\n JSON = 'JSON',\n UINT_8_ARRAY = 'UINT_8_ARRAY',\n}\n\nexport interface DeriveKeyResult {\n jwk: JWK.Key;\n}\n\nexport interface DerivePassIdpParams extends PassIdpParams {\n password: CryptoKey;\n}\n\nexport interface DerivePassKeyParams extends PassKeyParams {\n password: CryptoKey;\n}\n\nexport interface DeriveLbopKeyParams extends PassKeyParams {\n password: CryptoKey;\n}\n\nexport interface HasKeyGraphEdges<T> extends HasKeyGraph {\n list: HasEdges<T>;\n}\n","// This file is in the \"lr-lodash\" directory so that we can use the barrel file\n// to create the lodash namespace. If we put this into the \"functions\" folder, then\n// other functions in there that uses lodash won't have the lodash namespace.\n// The internet says this style of import improves bundle size. At least we only have to\n// do this in a single place here.\nimport cloneDeep from 'lodash/cloneDeep';\nimport isEqual from 'lodash/isEqual';\nimport keyBy from 'lodash/keyBy';\nimport omit from 'lodash/omit';\n\nexport { cloneDeep, isEqual, keyBy, omit };\n","/* eslint-disable @typescript-eslint/no-explicit-any */\nimport { GraphQLError } from 'graphql';\nimport { lodash } from '.';\n\nexport function handleApolloError(errors: ReadonlyArray<GraphQLError>) {\n if (!errors || !errors.length) return;\n\n const kcErrors = errors.map((x) => {\n return new KcError({\n code: x.extensions && x.extensions.code,\n source: x.extensions && x.extensions.source,\n data: x.extensions && lodash.omit(x.extensions, ['code', 'source']),\n message: x.message,\n debug: {\n locations: x.locations as any,\n path: x.path as string[],\n },\n });\n });\n\n throw new KcException(...kcErrors);\n}\n\nexport class KcError {\n /**\n * The _tag prevents being able to return an object when a class is required:\n * ref: https://medium.com/decathlondevelopers/whats-the-problem-with-typescript-s-classes-2e60aaad3f6\n * Example:\n * // This works because KcError is being treated as a type.\n * function test(): KcError {\n * return {message: \"123\"};\n * }\n * With the private _tag property, the above will cause a compiler error because _tag property is missing\n * from the returned object.\n *\n * The _type property also provides a type indicator when serialising the class to POJO.\n */\n private _type: 'KcError' = 'KcError';\n\n code?: string;\n source?: string;\n data?: any;\n message: string;\n debug?: {\n locations: {\n line: number;\n column: number;\n }[];\n path: string[];\n };\n\n constructor(options: Partial<KcError>) {\n this.code = options.code;\n this.source = options.source;\n this.data = options.data;\n this.message = options.message;\n this.debug = options.debug;\n }\n}\n\nexport class KcException {\n private _type: 'KcException' = 'KcException';\n\n public errors: KcError[];\n\n /**\n *\n * @param errors Each argument is a KcError.\n */\n constructor(...errors: KcError[]) {\n this.errors = errors;\n }\n\n public toString() {\n return this.errors.map((t) => JSON.stringify(t, null, 2));\n }\n}\n\nexport enum KcErrorCode {\n // API errors\n ARCHIVED_RESOURCE = 'ARCHIVED_RESOURCE',\n BAD_ARGUMENT = 'BAD_ARGUMENT',\n BAD_SIGNATURE = 'BAD_SIGNATURE',\n BAD_STATE = 'BAD_STATE',\n CHANGED_PERMISSIONS = 'CHANGED_PERMISSIONS',\n CONCURRENT_ACCESS = 'CONCURRENT_ACCESS',\n CONFIG_ERROR = 'CONFIG_ERROR',\n CYCLE_DETECTED = 'CYCLE_DETECTED',\n EXPIRED = 'EXPIRED',\n INVALID_TOKEN = 'INVALID_TOKEN',\n INTERNAL_ERROR = 'INTERNAL_ERROR',\n JSON_DECODE_ERROR = 'JSON_DECODE_ERROR',\n KEY_MISMATCH = 'KEY_MISMATCH',\n LIMIT_REACHED = 'LIMIT_REACHED',\n LOCKED = 'LOCKED',\n LOGIC_ERROR = 'LOGIC_ERROR',\n LR_DEBUG_ONLY = 'LR_DEBUG_ONLY',\n MIN_DELAY = 'MIN_DELAY',\n MISSING_FIELD = 'MISSING_FIELD',\n MISSING_FIELD_VALUE = 'MISSING_FIELD_VALUE',\n MISSING_QUERY_PARAM = 'MISSING_QUERY_PARAM',\n NOT_IMPLEMENTED = 'NOT_IMPLEMENTED',\n OBJECT_DOES_NOT_EXIST = 'OBJECT_DOES_NOT_EXIST',\n OBJECT_EXISTS = 'OBJECT_EXISTS',\n RANGE_ERROR = 'RANGE_ERROR',\n TRUSTED_PARTY_NOT_FOUND = 'TRUSTED_PARTY_NOT_FOUND',\n UNAUTHENTICATED_USER = 'UNAUTHENTICATED_USER',\n USER_NOT_FOUND = 'USER_NOT_FOUND',\n VERSION_MISMATCH = 'VERSION_MISMATCH',\n WRONG_PERMISSIONS = 'WRONG_PERMISSIONS',\n\n // KC client errors\n AUTH = 'AUTH',\n BAD_LOGIC = 'BAD_LOGIC',\n BAD_REQUEST = 'BAD_REQUEST',\n BAD_TIME_SYNC = 'BAD_TIME_SYNC',\n CODE_MISMATCH = 'CODE_MISMATCH',\n ENCRYPTION = 'ENCRYPTION',\n NOT_FOUND = 'NOT_FOUND',\n SUSPICIOUS_OPERATION = 'SUSPICIOUS_OPERATION',\n UNSUPPORTED = 'UNSUPPORTED',\n}\n\nexport class KcAuthException extends KcException {\n constructor(message) {\n super(new KcError({ code: KcErrorCode.AUTH, message }));\n }\n}\n\nexport class KcBadArgumentException extends KcException {\n constructor(message: string) {\n super(new KcError({ code: KcErrorCode.BAD_ARGUMENT, message }));\n }\n}\n\nexport class KcBadLogicException extends KcException {\n constructor(message) {\n super(new KcError({ code: KcErrorCode.BAD_LOGIC, message }));\n }\n}\nexport class KcBadRequestException extends KcException {\n constructor(message) {\n super(new KcError({ code: KcErrorCode.BAD_REQUEST, message }));\n }\n}\n\nexport class KcBadSignatureException extends KcException {\n constructor(message) {\n super(new KcError({ code: KcErrorCode.BAD_SIGNATURE, message }));\n }\n}\n\nexport class KcBadStateException extends KcException {\n constructor(message) {\n super(\n new KcError({\n code: KcErrorCode.BAD_STATE,\n message,\n })\n );\n }\n}\n\nexport class KcBadTimeSyncException extends KcException {\n constructor(message) {\n super(\n new KcError({\n code: KcErrorCode.BAD_TIME_SYNC,\n message,\n })\n );\n }\n}\n\nexport class KcCodeMismatchException extends KcException {\n constructor(message) {\n super(new KcError({ code: KcErrorCode.CODE_MISMATCH, message }));\n }\n}\n\nexport class KcConcurrentAccessException extends KcException {\n constructor(message) {\n super(new KcError({ code: KcErrorCode.CONCURRENT_ACCESS, message }));\n }\n}\n\nexport class KcEncryptionException extends KcException {\n constructor(message) {\n super(new KcError({ code: KcErrorCode.ENCRYPTION, message }));\n }\n}\n\nexport class KcInternalErrorException extends KcException {\n constructor(message) {\n super(new KcError({ code: KcErrorCode.INTERNAL_ERROR, message }));\n }\n}\n\nexport class KcLockedException extends KcException {\n constructor(message) {\n super(\n new KcError({\n code: KcErrorCode.LOCKED,\n message,\n })\n );\n }\n}\n\nexport class KcNotFoundException extends KcException {\n constructor(message) {\n super(new KcError({ code: KcErrorCode.NOT_FOUND, message }));\n }\n}\n\nexport class KcSuspiciousOperationException extends KcException {\n constructor(message) {\n super(new KcError({ code: KcErrorCode.SUSPICIOUS_OPERATION, message }));\n }\n}\n\nexport class KcUnsupportedException extends KcException {\n constructor(message) {\n super(\n new KcError({\n code: KcErrorCode.UNSUPPORTED,\n message,\n })\n );\n }\n}\n","/* eslint-disable @typescript-eslint/no-explicit-any */\n\nimport { AuthClass } from '@aws-amplify/auth/lib-esm/Auth';\nimport { KcBadLogicException } from './exceptions';\n\n// promote everything to a promise.\nexport function promiseAllMayAsync(values: any[]): Promise<any> | any {\n if (!Array.isArray(values)) {\n throw new Error('not array');\n }\n if (values.some((value) => value?.then)) {\n const ret = Promise.all(values);\n return ret;\n } else {\n return values;\n }\n}\n\nfunction remap(obj, values) {\n const ret = {};\n for (const [i, key] of Object.keys(obj).entries()) {\n ret[key] = values[i];\n }\n return ret;\n}\n\nexport function mapValuesMayAsync(\n obj: Record<string, any>,\n // callback can either return a Promise, or a value.\n // The Promise<any> type is redundant but it shows that it can return a promise\n callback: (\n value: any,\n key: string,\n obj: Record<string, any>\n ) => any | Promise<any>\n): Promise<any> | any {\n const values = promiseAllMayAsync(\n Object.entries(obj).map(([key, value]) => callback(value, key, obj))\n );\n\n if (values.then) {\n return values.then((resolvedValues) => remap(obj, resolvedValues));\n } else {\n return remap(obj, values);\n }\n}\n\nexport function mapValuesAsync(\n obj: Record<string, any>,\n // callback can either return a Promise, or a value.\n // The Promise<any> type is redundant but it shows that it can return a promise\n // By default, it returns the value without any process, so you can use\n // this to simply wait for all promises in an object to resolve.\n callback?: (\n value: any,\n key: string,\n obj: Record<string, any>\n ) => any | Promise<any>\n): Promise<any> {\n const values = Promise.all(\n Object.entries(obj).map(([key, value]) =>\n callback ? callback(value, key, obj) : value\n )\n );\n\n return values.then((resolvedValues) => remap(obj, resolvedValues));\n}\n\n/**\n * Returns the defaultValue when value is undefined\n * @param value The value to check\n * @param defaultValue The value to return if value is undefined.\n */\nexport function undefinedDefault(value: any, defaultValue: any) {\n return value === undefined ? defaultValue : value;\n}\n\nexport async function getAccessJwtToken(auth: AuthClass): Promise<string> {\n try {\n return (await auth.currentSession()).getAccessToken().getJwtToken();\n } catch (error) {\n // The error thrown by Cognito is of type string.\n return '';\n }\n}\n\nexport function assert_xor(options: Record<string, unknown>) {\n const keys = Object.keys(options);\n if (keys.length != 2) {\n throw new KcBadLogicException(\n 'You must provide exactly 2 fields in the argument.'\n );\n }\n\n if (options[keys[0]] != null && options[keys[1]] != null) {\n throw new KcBadLogicException(\n `You can not specify both ${keys[0]} and ${keys[1]}`\n );\n }\n\n if (options[keys[0]] == null && options[keys[1]] == null) {\n throw new KcBadLogicException(\n `You must specify either ${keys[0]} and ${keys[1]}`\n );\n }\n}\n","import { Injectable } from '@angular/core';\nimport { AuthClass } from '@aws-amplify/auth/lib-esm/Auth';\nimport { Apollo } from 'apollo-angular';\nimport gql from 'graphql-tag';\nimport * as moment_ from 'moment';\nimport {\n handleApolloError,\n KcBadTimeSyncException,\n} from '../_common/exceptions';\nimport { getAccessJwtToken } from '../_common/utils';\n// Ref: https://stackoverflow.com/questions/59735280/angular-8-moment-error-cannot-call-a-namespace-moment\nconst moment = moment_;\n\nexport const ServerTimeQuery = gql`\n query {\n serverTime {\n timestamp\n }\n }\n`;\n\ninterface ServerTime {\n timestamp: string;\n}\n\n@Injectable({\n providedIn: 'root',\n})\nexport class TimeService {\n VERIFY_ENABLED = true;\n\n private readonly MAX_DIFF_MSEC = moment\n .duration({ seconds: 30 })\n .asMilliseconds();\n\n offsetMs: number = null; // Millisecond offset of local clock.\n verified = false; // Verified with independent time source\n\n constructor(private auth: AuthClass, private apollo: Apollo) {}\n\n // Get time from independent source to confirm.\n private async verifyCognito(): Promise<void> {\n const accessToken = await getAccessJwtToken(this.auth);\n if (!accessToken) {\n return;\n }\n\n // Request headers from AWS Amplify Auth lib\n // accept: */*\n // accept-encoding: gzip, deflate, br\n // accept-language: en-GB,en-US;q=0.9,en;q=0.8\n // cache-control: no-cache\n // content-length: 1089\n // content-type: application/x-amz-json-1.1\n // origin: http://localhost:4200\n // pragma: no-cache\n // referer: http://localhost:4200/\n // sec-fetch-dest: empty\n // sec-fetch-mode: cors\n // sec-fetch-site: cross-site\n // user-agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.132 Safari/537.36\n // x-amz-target: AWSCognitoIdentityProviderService.GetUser\n // x-amz-user-agent: aws-amplify/0.1.x js\n\n // We are only interested in the Date field.\n // AZ: I suppose we could use any end-point that provides a reliable Date field in the header. And we don't\n // need to be authenticated. Even a 400 response would have a Date header. But the worry is that AWS might\n // think it's some sort of attack, and block the IP or domain. At least in an authenticated call it can't be\n // seen as illegitimate.\n const response = await fetch(\n 'https://cognito-idp.ap-southeast-2.amazonaws.com/',\n {\n method: 'POST', // *GET, POST, PUT, DELETE, etc.\n mode: 'cors', // no-cors, *cors, same-origin\n cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached\n headers: {\n 'x-amz-target': 'AWSCognitoIdentityProviderService.GetUser',\n 'x-amz-user-agent': 'aws-amplify/0.1.x js',\n 'Content-Type': 'application/x-amz-json-1.1',\n },\n // redirect: 'follow', // manual, *follow, error\n // referrerPolicy: 'no-referrer', // no-referrer, *no-referrer-when-downgrade, origin, origin-when-cross-origin, same-origin, strict-origin, strict-origin-when-cross-origin, unsafe-url\n body: JSON.stringify({\n AccessToken: accessToken,\n }), // body data type must match \"Content-Type\" header\n }\n );\n\n const now = Date.now();\n\n const verifyTime = moment(response.headers.get('Date')).valueOf();\n const serverTime = now + this.offsetMs;\n const diff = Math.abs(serverTime - verifyTime);\n\n if (diff > this.MAX_DIFF_MSEC) {\n throw new KcBadTimeSyncException(\n `Server time does not match independent source. ServerTime: ${serverTime}, Cognito time: ${verifyTime}`\n );\n }\n\n this.verified = true;\n }\n\n private async refresh(): Promise<void> {\n const start = Date.now();\n const res = await this.apollo\n .query<{ serverTime: ServerTime }>({ query: ServerTimeQuery })\n .toPromise();\n const end = Date.now();\n\n handleApolloError(res.errors);\n\n const serverTime = parseInt(res.data.serverTime.timestamp, 10);\n\n const roundtrip = end - start;\n this.offsetMs = Math.round(serverTime - (start + roundtrip / 2));\n\n if (this.VERIFY_ENABLED) {\n await this.verifyCognito();\n }\n }\n\n async serverNow(): Promise<number> {\n let needsRefresh = false;\n\n // First call\n if (this.offsetMs === null) {\n needsRefresh = true;\n }\n\n if (this.VERIFY_ENABLED) {\n // logged in but not yet verified time matches.\n if (!this.verified && (await getAccessJwtToken(this.auth))) {\n needsRefresh = true;\n }\n }\n\n if (needsRefresh) {\n await this.refresh();\n }\n\n return Date.now() + this.offsetMs;\n }\n\n /**\n * This is the sync version to get now. Call serverNow() first, otherwise this will print error\n * because the server time offset is not known. But it will return the current time as a fallback\n * so as to not introduce any crashes.\n *\n */\n now(): number {\n if (this.offsetMs === null) {\n console.error(\n 'Server time offset not known. You must await serverNow() first. Returning local clock instead.'\n );\n return Date.now();\n } else {\n return Date.now() + this.offsetMs;\n }\n }\n\n /**\n * Calls this.now() and converts to a Date object.\n */\n date(): Date {\n return new Date(this.now());\n }\n}\n","/* eslint-disable @typescript-eslint/no-explicit-any */\nimport { Injectable } from '@angular/core';\nimport { JWE, JWK, JWS } from 'node-jose';\nimport { JSONObject } from '../api/types';\nimport { Key, PayloadType } from '../key/key.types';\nimport { TimeService } from '../time/time.service';\nimport {\n KcBadArgumentException,\n KcBadSignatureException,\n} from './../_common/exceptions';\n\nexport enum JoseSerialization {\n JSON = 'JSON',\n COMPACT = 'COMPACT',\n}\n\nexport interface VerifyOptions {\n payloadType?: PayloadType;\n returnOnlyPayload?: boolean; // If true, return only the decoded payload.\n}\n\nexport interface DecryptOptions {\n payloadType?: PayloadType;\n returnOnlyPayload?: boolean; // If true, return only the decoded payload.\n serializations?: JoseSerialization[];\n}\n\nexport const VERIFY_OPTIONS_DEFAULT: VerifyOptions = {\n payloadType: PayloadType.JSON,\n returnOnlyPayload: true,\n};\n\nexport const DECRYPT_OPTIONS_DEFAULT: DecryptOptions = {\n payloadType: PayloadType.JSON,\n returnOnlyPayload: true,\n serializations: [JoseSerialization.JSON],\n};\n\nexport function isSymmetricKey(key: JWK.Key) {\n // TODO: make sure this covers all cases.\n return key.kty === 'oct';\n}\n\nexport function asJwk(key: JWK.Key | Key | any): JWK.Key | null {\n // TODO: make sure this covers all cases.\n // Excluded:\n // key.use - only for public keys, Ref: https://tools.ietf.org/html/rfc7517#section-4.2\n\n if (key.id && key.jwk) {\n return key.jwk;\n } else if (key.keystore && key.length && key.kty && key.kid && key.alg) {\n return key;\n } else {\n return null;\n }\n}\n\n@Injectable({\n providedIn: 'root',\n})\nexport class EncryptionService {\n constructor(private timeService: TimeService) {}\n\n async decrypt(\n key: JWK.Key | Key, // string is assumed to be key.id, will unwrap key.\n jwe: Record<string, JSONObject> | string, // string will be JSON.parsed\n options?: DecryptOptions\n ): Promise<JWE.DecryptResult | any> {\n const opt = {\n algorithms: ['dir', 'A*GCM', 'RSA-OAEP-*'],\n };\n\n options = {\n ...DECRYPT_OPTIONS_DEFAULT,\n ...options,\n };\n\n if ((key as Key).jwk) {\n key = (key as Key).jwk;\n }\n\n if (typeof jwe === 'string') {\n if (options.serializations.includes(JoseSerialization.JSON)) {\n try {\n jwe = JSON.parse(jwe);\n } catch (error) {\n if (options.serializations.includes(JoseSerialization.COMPACT)) {\n console.log(\n 'Not a JSON-formatted JWE, it maybe compact serialisation format.'\n );\n } else {\n throw error;\n }\n }\n }\n }\n\n // {result} is a Object with:\n // * header: the combined 'protected' and 'unprotected' header members\n // * protected: an array of the member names from the \"protected\" member\n // * key: Key used to decrypt\n // * payload: Buffer of the decrypted content\n // * plaintext: Buffer of the decrypted content (alternate), just a reference to payload\n const res = await JWE.createDecrypt(key as JWK.Key, opt).decrypt(\n jwe as any\n );\n\n res.payload = this.decodePayload(options.payloadType, res.payload);\n\n if (options.returnOnlyPayload) {\n return res.payload;\n } else {\n return res;\n }\n }\n\n // TODO rename this to encrypt() and use as the most common use case\n async encryptToString(\n key: JWK.Key,\n content: ArrayBuffer | string | Record<string, JSONObject>\n ): Promise<string> {\n return JSON.stringify(await this.encrypt(key, content));\n }\n\n // TODO rename this to encryptToJSON() and use this when required.\n async encrypt(\n key: JWK.Key,\n content: ArrayBuffer | string | Record<string, JSONObject>\n ): Promise<any> {\n if (content == null) {\n throw new Error('Encrypting null/undefined content.');\n }\n\n if (!(content instanceof ArrayBuffer)) {\n content = new TextEncoder().encode(JSON.stringify(content));\n }\n\n return JWE.createEncrypt(\n {\n contentAlg: 'A256GCM',\n fields: {\n timestamp: await this.timeService.serverNow(),\n },\n } as any,\n key\n )\n .update(content)\n .final() as any;\n }\n\n // <AZ> Unlike signContent, the serialised \"content\" variable is contained inside\n // the result. So ordering of fields within \"content\" is not an issue.\n async sign(\n key: JWK.Key,\n content: Buffer | string | Record<string, JSONObject>\n ): Promise<any> {\n const signer = JWS.createSign(\n {\n fields: {\n timestamp: await this.timeService.serverNow(),\n },\n },\n key\n );\n\n if (content instanceof Buffer) {\n signer.update(content);\n } else {\n signer.update(JSON.stringify(content), 'utf8');\n }\n\n return signer.final();\n }\n\n async signToString(\n key: JWK.Key,\n content: Buffer | string | Record<string, JSONObject>\n ): Promise<string> {\n return JSON.stringify(await this.sign(key, content));\n }\n\n async verify(\n key: JWK.Key,\n jws: Record<string, JSONObject>,\n options?: VerifyOptions\n ): Promise<any> {\n const opt = {\n algorithms: ['RS*'],\n };\n\n options = {\n ...VERIFY_OPTIONS_DEFAULT,\n ...options,\n };\n\n try {\n const res = await JWS.createVerify(key, opt).verify(jws as any);\n\n res.payload = this.decodePayload(options.payloadType, res.payload);\n\n if (options.returnOnlyPayload) {\n return res.payload;\n } else {\n return res;\n }\n } catch (error) {\n throw new KcBadSignatureException(`Bad signature: ${error}`);\n }\n }\n\n async encryptThenSign(\n {\n key,\n sigPrk,\n }: {\n key: JWK.Key;\n sigPrk: JWK.Key;\n },\n content: ArrayBuffer | string | Record<string, JSONObject>\n ): Promise<{ cipher: string; sig: string }> {\n const cipher = JSON.stringify(await this.encrypt(key, content));\n const sig = await this.sign(sigPrk, cipher);\n delete sig.payload;\n\n return {\n cipher,\n sig: JSON.stringify(sig),\n };\n }\n\n private decodePayload(\n payloadType: PayloadType,\n payload: Uint8Array\n ): Uint8Array | any {\n switch (payloadType) {\n case PayloadType.JSON:\n return JSON.parse(new TextDecoder().decode(payload));\n case PayloadType.UINT_8_ARRAY:\n return payload;\n default:\n throw new KcBadArgumentException(`Unknown payloadType: ${payloadType}`);\n }\n }\n}\n","import { Injectable } from '@angular/core';\n\n@Injectable({\n providedIn: 'root',\n})\nexport class WebCryptoService {\n kcCrypto: Crypto = window.crypto;\n\n toHex(buffer: ArrayBuffer) {\n // Ref: https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/digest\n const array = Array.from(new Uint8Array(buffer)); // convert buffer to byte array\n const hex = array.map((b) => b.toString(16).padStart(2, '0')).join(''); // convert bytes to hex string\n return hex;\n }\n\n async stringDigest(algorithm: string, message: string): Promise<string> {\n const encoder = new TextEncoder();\n const data = encoder.encode(message);\n const hash = await this.kcCrypto.subtle.digest(algorithm, data);\n return this.toHex(hash);\n }\n}\n","import { Injectable } from '@angular/core';\nimport { JWK } from 'node-jose';\nimport { JSONObject } from '../api/types';\nimport { WebCryptoService } from '../web-crypto/web-crypto.service';\nimport {\n KcBadArgumentException,\n KcSuspiciousOperationException,\n} from '../_common/exceptions';\nimport {\n DeriveKeyResult,\n DeriveLbopKeyParams,\n DerivePassIdpParams,\n DerivePassKeyParams,\n LbopKeyParams,\n PassIdpParams,\n PassKeyParams,\n} from './key.types';\n\n@Injectable({\n providedIn: 'root',\n})\nexport class KeyFactoryService {\n constructor(private webCryptoService: WebCryptoService) {\n this.kcCrypto = this.webCryptoService.kcCrypto;\n }\n private readonly kcCrypto: Crypto;\n private readonly store: [];\n // Global keys store. Otherwise, each call to asKey creates a new keyStore.\n // <AZ> Did not seem to improve speed.\n // public static keyStore = JWK.createKeyStore();\n\n // AZ: This can't be change easily. It's basically a PassK or PassIdp rotation.\n // todo: we should eventually increase this periodically to match with Moore's law.\n // The iterations for each key are kept by the server as well but we assume the value\n // from the server is not trustworthy, so need to have minimum thresholds here.\n // If creating new keys, these minimum are used.\n public readonly MIN_PASS_IDP_PBKDF_ITER = 100000;\n public readonly MIN_PASS_KEY_PBKDF_ITER = 100000;\n public readonly MIN_LBOP_KEY_PBKDF_ITER = 100000;\n\n // These are used as the default values. They must be larger than the minimum values.\n public readonly DEFAULT_PASS_IDP_PBKDF_ITER = this.MIN_PASS_IDP_PBKDF_ITER;\n public readonly DEFAULT_PASS_KEY_PBKDF_ITER = this.MIN_PASS_KEY_PBKDF_ITER;\n public readonly DEFAULT_LBOP_KEY_PBKDF_ITER = this.MIN_LBOP_KEY_PBKDF_ITER;\n\n static asKey(\n key: string | Buffer | Record<string, JSONObject> | JWK.RawKey,\n form?:\n | 'json'\n | 'private'\n | 'pkcs8'\n | 'public'\n | 'spki'\n | 'pkix'\n | 'x509'\n | 'pem',\n extras?: Record<string, unknown>\n ): Promise<JWK.Key> {\n // <AZ> Using a single global key store did not seem to improve speed.\n // return KeyFactoryService.keyStore.add(key, form, extras);\n return JWK.asKey(key, form, extras);\n }\n\n randomString(digits: number): string {\n if (digits <= 0) {\n throw new KcBadArgumentException('digits <= 0');\n }\n const validChars =\n 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';\n let array = new Uint32Array(digits);\n this.kcCrypto.getRandomValues(array);\n array = array.map((x) => validChars.charCodeAt(x % validChars.length));\n return String.fromCharCode.apply(null, array);\n }\n\n randomDigitsNoZeros(digits: number): string {\n return this.randomChoices([1, 2, 3, 4, 5, 6, 7, 8, 9], digits).join('');\n }\n\n randomChoices<T>(array: T[], chooseN: number): T[] {\n if (array.length <= 1) {\n throw new KcBadArgumentException('array.length <= 0');\n }\n if (chooseN <= 0) {\n throw new KcBadArgumentException('chooseN <= 0');\n }\n const values = new Uint32Array(chooseN);\n this.kcCrypto.getRandomValues(values);\n const ret: T[] = [];\n values.forEach((v) => ret.push(array[v % array.length]));\n return ret;\n }\n\n createSalt(): string {\n return this.randomString(16);\n }\n\n async createKey(): Promise<JWK.Key> {\n const key = await this.kcCrypto.subtle.generateKey(\n {\n name: 'AES-GCM',\n length: 256, // can be 128, 192, or 256\n },\n true, // whether the key is extractable (i.e. can be used in exportKey)\n ['encrypt', 'decrypt'] // must be [\"encrypt\", \"decrypt\"] or [\"wrapKey\", \"unwrapKey\"]\n );\n\n const jwk = await this.kcCrypto.subtle.exportKey('jwk', key);\n\n // Removing the fields not needed by node-jose\n delete jwk.ext;\n delete jwk.key_ops;\n\n return KeyFactoryService.asKey(jwk);\n }\n\n async createSignKey(): Promise<JWK.Key> {\n const key = await this.kcCrypto.subtle.generateKey(\n {\n name: 'HMAC',\n hash: { name: 'SHA-512' },\n },\n true,\n ['sign', 'verify']\n );\n\n const jwk = await this.kcCrypto.subtle.exportKey('jwk', key);\n\n // Removing the fields not needed by node-jose\n delete jwk.key_ops;\n delete jwk.ext;\n\n return KeyFactoryService.asKey(jwk);\n }\n\n async createPkcKey(): Promise<JWK.Key> {\n // node-jose is not using Forge properly. It should be calling the async version of\n // pki.rsa.generateKeyPair() with a callback. Instead it calls the sync version. Webcrypto\n // does not support sync version, so it uses the javascript implementation, which is way too slow.\n // So we generate using webcrypto and import the key.\n // Unfortunately Elliptical Curve is not supported by Webcrypto. So we have to settle for RSA.\n const key = await this.kcCrypto.subtle.generateKey(\n {\n name: 'RSA-OAEP',\n modulusLength: 2048, // can be 1024, 2048, 3072, 4096 ... 16384\n // As per suggestion: https://developer.mozilla.org/en-US/docs/Web/API/RsaHashedKeyGenParams\n publicExponent: new Uint8Array([0x01, 0x00, 0x01]),\n hash: { name: 'SHA-256' }, // can be \"SHA-1\", \"SHA-256\", \"SHA-384\", or \"SHA-512\"\n },\n true, // whether the key is extractable (i.e. can be used in exportKey)\n ['encrypt', 'decrypt'] // must be [\"encrypt\", \"decrypt\"] or [\"wrapKey\", \"unwrapKey\"]\n );\n\n const jwk = await this.kcCrypto.subtle.exportKey('jwk', key.privateKey);\n // Removing the fields not needed by node-jose\n delete jwk.key_ops;\n delete jwk.ext;\n\n return KeyFactoryService.asKey(jwk);\n }\n\n async createPkcSignKey(): Promise<JWK.Key> {\n const key = await this.kcCrypto.subtle.generateKey(\n {\n name: 'RSASSA-PKCS1-v1_5',\n modulusLength: 2048, // can be 1024, 2048, or 4096\n // As per suggestion: https://developer.mozilla.org/en-US/docs/Web/API/RsaHashedKeyGenParams\n publicExponent: new Uint8Array([0x01, 0x00, 0x01]),\n hash: { name: 'SHA-256' }, // can be \"SHA-1\", \"SHA-256\", \"SHA-384\", or \"SHA-512\"\n },\n true, // whether the key is extractable (i.e. can be used in exportKey)\n ['sign', 'verify'] // can be any combination of \"sign\" and \"verify\"\n );\n\n const jwk = await this.kcCrypto.subtle.exportKey('jwk', key.privateKey);\n\n // Removing the fields not needed by node-jose\n delete jwk.key_ops;\n delete jwk.ext;\n\n return KeyFactoryService.asKey(jwk);\n }\n\n async importPassword(plainPassword: string): Promise<CryptoKey> {\n const enc = new TextEncoder();\n return this.kcCrypto.subtle.importKey(\n 'raw',\n enc.encode(plainPassword),\n 'PBKDF2',\n false,\n ['deriveKey']\n );\n }\n\n async deriveKey({\n password,\n salt,\n iterations,\n kid,\n }: {\n password: CryptoKey;\n salt: string;\n iterations: number;\n kid?: string;\n }): Promise<DeriveKeyResult> {\n const passKey = await this.kcCrypto.subtle.deriveKey(\n {\n name: 'PBKDF2',\n salt: new TextEncoder().encode(salt),\n iterations,\n hash: 'SHA-256',\n },\n password,\n { name: 'AES-GCM', length: 256 },\n true,\n ['encrypt', 'decrypt']\n );\n\n const passKeyJson: JSONObject = await this.kcCrypto.subtle.exportKey(\n 'jwk',\n passKey\n );\n if (kid) {\n passKeyJson.kid = kid;\n }\n\n const jwk = await KeyFactoryService.asKey(passKeyJson);\n\n return { jwk };\n }\n\n async derivePassIdp(params: DerivePassIdpParams): Promise<DeriveKeyResult> {\n if (params.iterations < this.MIN_PASS_IDP_PBKDF_ITER) {\n throw new KcSuspiciousOperationException(\n `The number of PassIdp key derivation iterations sent from the server (${params.iterations}) is lower than the minimum (${this.MIN_PASS_IDP_PBKDF_ITER})`\n );\n }\n return this.deriveKey(params);\n }\n\n async derivePassKey(params: DerivePassKeyParams): Promise<DeriveKeyResult> {\n if (params.iterations < this.MIN_PASS_KEY_PBKDF_ITER) {\n throw new KcSuspiciousOperationException(\n `The number of PassKey key derivation iterations sent from the server(${params.iterations}) is lower than the minimum(${this.MIN_PASS_KEY_PBKDF_ITER})`\n );\n }\n return this.deriveKey(params);\n }\n\n async deriveLbopKey(params: DeriveLbopKeyParams): Promise<DeriveKeyResult> {\n if (params.iterations < this.MIN_LBOP_KEY_PBKDF_ITER) {\n throw new KcSuspiciousOperationException(\n `The number of LbopKey key derivation iterations sent from the server(${params.iterations}) is lower than the minimum(${this.MIN_LBOP_KEY_PBKDF_ITER})`\n );\n }\n return this.deriveKey(params);\n }\n\n async createKid(): Promise<string> {\n // todo: AZ: node-jose source uses node's default UUID() function for kid, so just change to use that.\n // for now, we are just creating a new key to use it's kid.\n // The kid is a part of the JWK system. LR backend maintains the key hierarchy separately with it's own\n // key id. But we just use it here as a double check.\n return (await this.createKey()).kid;\n }\n\n async createPassIdpParams(): Promise<PassIdpParams> {\n return {\n salt: this.createSalt(),\n iterations: this.DEFAULT_PASS_IDP_PBKDF_ITER,\n };\n }\n\n async createPassKeyParams(): Promise<PassKeyParams> {\n return {\n salt: this.createSalt(),\n kid: await this.createKid(),\n iterations: this.DEFAULT_PASS_KEY_PBKDF_ITER,\n };\n }\n\n async createLbopKeyParams(): Promise<LbopKeyParams> {\n return {\n salt: this.createSalt(),\n // todo: AZ: node-jose source uses node's default UUID() function for kid, so just change to use that.\n // for now, we are just creating a new key to use it's kid.\n // The kid is a part of the JWK system. LR backend maintains the key hierarchy separately with it's own\n // key id. But we just use it here as a double check.\n kid: await this.createKid(),\n iterations: this.DEFAULT_PASS_KEY_PBKDF_ITER,\n };\n }\n}\n","/* eslint-disable @typescript-eslint/no-explicit-any */\nimport { InjectionToken } from '@angular/core';\nimport {\n ApolloClientOptions,\n ApolloLink,\n createHttpLink,\n DefaultOptions,\n from,\n InMemoryCache,\n} from '@apollo/client/core';\nimport { setContext } from '@apollo/client/link/context';\nimport { RetryLink } from '@apollo/client/link/retry';\nimport { AuthClass } from '@aws-amplify/auth/lib-esm/Auth';\nimport { GraphQLError } from 'graphql';\nimport { KcErrorCode } from './_common/exceptions';\nimport { getAccessJwtToken } from './_common/utils';\n\n// The injection token string is set to be the same as the const stand name since you\n// can possibly have different tokens with the same type (i.e. KcConfig). So it would not\n// be appropriate to use \"KcConfig\" as the token string.\nexport const KC_CONFIG = new InjectionToken<KcConfig>('KC_CONFIG');\nconst RETRY_ERROR_CODES = [KcErrorCode.CONCURRENT_ACCESS];\n\nexport async function httpOptions(auth: AuthClass, config: KcConfig) {\n const token = await getAccessJwtToken(auth);\n\n const debugUsername = config.debug?.username;\n const debugRbacCacheMode = config.debug?.rbacCacheMode;\n\n return {\n withCredentials: true,\n headers: {\n ...(token && { authorization: `Bearer ${token}` }),\n ...(debugUsername && { 'x-kc-dev-user': debugUsername }),\n ...(debugRbacCacheMode && {\n 'x-kc-dev-rbac-cache-mode': debugRbacCacheMode,\n }),\n },\n };\n}\n\nexport interface KcConfig {\n authUrl: string;\n apiUrl: string;\n apolloUrl: string;\n userPoolId: string;\n userPoolWebClientId: string;\n apolloConfig?: ApolloClientOptions<any>;\n // Mainly to allow localhost to not needing this. Default to falsy\n disableSessionEncryptionKey?: boolean;\n // There's no compiler level switch exclude variables from the interface.\n // The only mechanism is to use replacement of files. But it's too cumbersome.\n // So we use runtime check instead to ensure debug config is null in production.\n debug?: {\n username?: string;\n rbacCacheMode?: string;\n };\n}\n\nexport const configureApollo = (\n config: KcConfig,\n auth: AuthClass\n): ApolloClientOptions<any> => {\n const defaultOptions: DefaultOptions = {\n watchQuery: {\n fetchPolicy: 'no-cache',\n errorPolicy: 'all',\n },\n query: {\n fetchPolicy: 'no-cache',\n errorPolicy: 'all',\n },\n mutate: {\n fetchPolicy: 'no-cache',\n errorPolicy: 'all',\n },\n };\n\n const authLink = setContext(async (_, { headers }) => {\n const options = await httpOptions(auth, config);\n\n return {\n ...options,\n headers: {\n ...headers,\n ...options.headers,\n },\n };\n });\n\n // We are only retrying on certain errors, like the CONCURRENT_ACCESS gql\n // error which indicates DB race condition. So can be safely retried.\n const retryIf = (error, _) => {\n // The RetryLink is called on network error as well, so we need to filter for GraphQL errors.\n if (error instanceof GraphQLErrorException) {\n if (\n error.errors.some((e) => RETRY_ERROR_CODES.includes(e.extensions?.code))\n ) {\n return true;\n }\n }\n\n return false;\n };\n\n const retryLink = new RetryLink({\n delay: {\n initial: 300,\n max: Infinity,\n jitter: true,\n },\n attempts: {\n max: 3,\n retryIf,\n },\n });\n\n class GraphQLErrorException extends Error {\n constructor(public errors: readonly GraphQLError[]) {\n super(errors.map((e) => e.message).join(', '));\n }\n }\n\n // Throw exception on gql errors which effectively promotes it to a network\n // error, which can then be handled by the RetryLink.\n const promoteGqlErrors = new ApolloLink((operation, forward) => {\n return forward(operation).map((data) => {\n if (data && data.errors) {\n const errors = data.errors.filter((e) =>\n RETRY_ERROR_CODES.includes(e.extensions?.code)\n );\n\n if (errors.length > 0) {\n throw new GraphQLErrorException(data.errors);\n }\n }\n return data;\n });\n });\n\n const httpLink = createHttpLink({\n uri: config.apolloUrl,\n // Sending the sessionid cookie so that the server can use session data when needed.\n // eg. setting the session encryption key.\n credentials: 'include',\n });\n\n return {\n link: from([retryLink, promoteGqlErrors, authLink, httpLink]),\n cache: new InMemoryCache(),\n defaultOptions,\n ...config.apolloConfig,\n };\n};\n","/* eslint-disable @typescript-eslint/no-explicit-any */\nimport { Injectable, Injector, isDevMode } from '@angular/core';\nimport { CookieService } from 'ngx-cookie-service';\nimport { JWK } from 'node-jose';\nimport { EncryptionService } from '../encryption/encryption.service';\nimport { KeyFactoryService as KFS } from '../key/key-factory.service';\nimport { KcBadArgumentException } from '../_common/exceptions';\n\ninterface Item {\n data: string;\n expiry?: string; // iso format\n serverSession?: boolean;\n}\n\ninterface CookieItem {\n key: any;\n}\n\n@Injectable({\n providedIn: 'root',\n})\nexport class PersistService {\n private readonly KEY_PREFIX = 'lrSession-';\n\n private cookieSecure = true;\n private serverSessionEncryptionKey: JWK.Key = null;\n\n constructor(\n private keyFactory: KFS,\n private cookieService: CookieService,\n private encryptionService: EncryptionService,\n private injector: Injector\n ) {\n if (isDevMode()) {\n this.setCookieSecure(false);\n }\n }\n\n setServerSessionEncryptionKey(key: JWK.Key) {\n this.serverSessionEncryptionKey = key;\n }\n\n clearServerSessionEncryptionKey() {\n this.serverSessionEncryptionKey = null;\n }\n\n // It's important that set and delete cookie use exactly the same set of parameters.\n private getCookieParams() {\n return {\n path: '/',\n domain: null, // which means the current domain of the frontend app.\n secure: this.cookieSecure,\n sameSite: 'Lax' as 'Lax' | 'None' | 'Strict',\n };\n }\n\n public clear() {\n // Remove all cookies\n Object.keys(this.cookieService.getAll()).forEach((key) => {\n if (key.startsWith(this.KEY_PREFIX)) {\n this.deletePrefixedName(key);\n }\n });\n\n // Remove all persisted session variables\n Object.keys(localStorage).forEach((key) => {\n if (key.startsWith(this.KEY_PREFIX)) {\n this.deletePrefixedName(key);\n }\n });\n }\n\n public setCookieSecure(value: boolean) {\n this.cookieSecure = value;\n if (!value) {\n if (isDevMode()) {\n console.warn(\n 'The cookie secure flag in persistService has been set to false, set it to true in production mode'\n );\n } else {\n throw new KcBadArgumentException(\n 'Can not set PersistService cookie secure flag to false in production mode.'\n );\n }\n }\n }\n\n private prefixName(name: string): string {\n return this.KEY_PREFIX + name;\n }\n\n public delete(name: string): void {\n this.deletePrefixedName(this.prefixName(name));\n }\n\n private deletePrefixedName(prefixedName: string): void {\n const params = this.getCookieParams();\n this.cookieService.delete(\n prefixedName, // name: string,\n params.path, // path?: string,\n params.domain, // domain ?: string,\n params.secure, // secure ?: boolean,\n params.sameSite // sameSite ?: 'Lax' | 'None' | 'Strict'): void;\n );\n localStorage.removeItem(prefixedName);\n }\n\n public async set({\n name,\n value,\n serverSession,\n expiry,\n }: {\n name: string;\n value: any;\n serverSession: boolean;\n expiry?: Date;\n }): Promise<void> {\n const prefixedName = this.prefixName(name);\n\n let item: Item;\n\n if (serverSession) {\n item = {\n serverSession: true,\n data: await this.encryptionService.encryptToString(\n this.serverSessionEncryptionKey,\n value\n ),\n };\n } else {\n item = {\n data: value,\n };\n }\n\n if (expiry) {\n const key = await this.keyFactory.createKey();\n item.expiry = expiry.toISOString();\n item.data = await this.encryptionService.encryptToString(key, item.data);\n\n const cookieItem: CookieItem = {\n key: key.toJSON(true),\n };\n\n // If path is set to anything other than \"/\" then the cookie is only\n // accessible by JS if the current URL has the same prefix as the path.\n // Ideally we don't want the encryption key cookie to be sent at all, but\n // since the encrypted content is held in localstorage, it is not a security\n // risk, i.e. it is at least as secure as storing only in localstorage.\n const params = this.getCookieParams();\n this.cookieService.set(\n prefixedName, // name: string,\n JSON.stringify(cookieItem), // value: string,\n expiry, // expires?: number | Date,\n params.path, // path?: string,\n params.domain, // domain?: string,\n params.secure, // secure?: boolean,\n params.sameSite // sameSite?: 'Lax' | 'None' | 'Strict'\n );\n }\n\n localStorage.setItem(prefixedName, JSON.stringify(item));\n }\n\n public async get(name: string): Promise<any> {\n const prefixedName = this.prefixName(name);\n\n try {\n const ret = await this.getImpl(prefixedName);\n if (ret == null) {\n // Clear any cookies to keep things in sync.\n this.deletePrefixedName(prefixedName);\n }\n return ret;\n } catch (error) {\n this.deletePrefixedName(prefixedName);\n throw error;\n }\n }\n\n private async getImpl(name: string): Promise<any> {\n const itemString = localStorage.getItem(name);\n if (!itemString) {\n return null;\n }\n\n const item: Item = JSON.parse(itemString);\n\n let data: any;\n\n if (item.expiry) {\n const cookieItemString = this.cookieService.get(name);\n if (!cookieItemString) {\n // Probably expired, but we won't make any interpretations since if we only used\n // cookies we can't tell if it's expired or explicitly removed. So we just make\n // the behaviour here consistent with that.\n console.log('No cookie.');\n return null;\n }\n\n const cookieItem = JSON.parse(cookieItemString);\n\n const key = await KFS.asKey(cookieItem.key);\n\n data = await this.encryptionService.decrypt(key, item.data);\n } else {\n data = item.data;\n }\n\n if (item.serverSession) {\n data = await this.encryptionService.decrypt(\n this.serverSessionEncryptionKey,\n data\n );\n }\n\n return data;\n }\n}\n","import { Inject, Injectable } from '@angular/core';\nimport { KcConfig, KC_CONFIG } from '../life-ready.config';\nimport { PersistService } from '../persist/persist.service';\nimport { KcNotFoundException } from '../_common/exceptions';\nimport { KeyFactoryService as KFS } from './key-factory.service';\nimport { Key, PassKey } from './key.types';\n\nexport class UserKeys {\n passKey: PassKey;\n masterKey: Key;\n rootKey?: Key;\n pxk?: Key;\n sigPxk?: Key;\n}\n\n@Injectable({\n providedIn: 'root',\n})\nexport class KeyService {\n private readonly STORE_MASTER_KEY = 'masterKey';\n // variables\n private keys: UserKeys;\n private masterKey: Key;\n\n // AZ: This can't be change easily. It's basically a PassK or PassIdp rotation.\n // todo: we should eventually increase this periodically to match with Moore's law.\n // The iterations for each key are kept by the server as well but we assume the value\n // from the server is not trustworthy, so need to have minimum thresholds here.\n // If creating new keys, these minimum are used.\n public readonly MIN_PASS_IDP_PBKDF_ITER = 100000;\n public readonly MIN_PASS_KEY_PBKDF_ITER = 100000;\n public readonly MIN_LBOP_KEY_PBKDF_ITER = 100000;\n\n // These are used as the default values. They must be larger than the minimum values.\n public readonly DEFAULT_PASS_IDP_PBKDF_ITER = this.MIN_PASS_IDP_PBKDF_ITER;\n public readonly DEFAULT_PASS_KEY_PBKDF_ITER = this.MIN_PASS_KEY_PBKDF_ITER;\n public readonly DEFAULT_LBOP_KEY_PBKDF_ITER = this.MIN_LBOP_KEY_PBKDF_ITER;\n\n constructor(\n @Inject(KC_CONFIG) private config: KcConfig,\n private persistService: PersistService\n ) {\n this.resetKeys();\n }\n\n resetKeys() {\n this.keys = null;\n this.masterKey = null;\n }\n\n purgeKeys() {\n this.resetKeys();\n this.persistService.clear();\n }\n\n setKeys(keys: UserKeys) {\n this.keys = keys;\n }\n\n public get currentPassKey(): Key {\n return this.keys.passKey;\n }\n\n public get currentMasterKey(): Key {\n return this.keys.masterKey;\n }\n\n public get currentRootKey(): Key {\n return this.keys.rootKey;\n }\n\n public get currentPxk(): Key {\n return this.keys.pxk;\n }\n\n public get currentSigPxk(): Key {\n return this.keys.sigPxk;\n }\n\n private expiresAfter(seconds: number): Date {\n return new Date(Date.now() + 1000 * seconds);\n }\n\n async persistMasterKey(\n masterKey: Key,\n expiresAfterSeconds: number\n ): Promise<void> {\n const storedKey = {\n id: masterKey.id,\n jwk: masterKey.jwk.toJSON(true),\n };\n\n this.masterKey = masterKey;\n\n // Save in an expirable cookie.\n await this.persistService.set({\n name: this.STORE_MASTER_KEY,\n value: storedKey,\n expiry: this.expiresAfter(expiresAfterSeconds),\n serverSession: !this.config.disableSessionEncryptionKey,\n });\n }\n\n async setMasterKeyExpiresAfterSeconds(seconds: number): Promise<void> {\n const storedKey = await this.persistService.get(this.STORE_MASTER_KEY);\n if (storedKey == null) {\n throw new KcNotFoundException(\n `Can not find masterKey in persisted storage using name: ${this.STORE_MASTER_KEY}`\n );\n }\n await this.persistService.set({\n name: this.STORE_MASTER_KEY,\n value: storedKey,\n expiry: this.expiresAfter(seconds),\n serverSession: !this.config.disableSessionEncryptionKey,\n });\n }\n\n // There's little benefit in using WebCrypto's none-extractable keys because if there\n // is an XSS attack, then the attacker has control over the js that downloads the keys. The\n // attacker can modify the code to import the keys as extractable. So none-extractable keys\n // are only useful if they are already persisted and the user cannot download any more keys,\n // which is not feasible.\n // So storing the PassKey in localstorage for now, at least till we know what the usage\n // pattern is, i.e. how often do we need to use the RootK, MaterK, and PassK.\n async loadMasterKey(masterKeyId: string): Promise<Key> {\n if (!this.masterKey) {\n const storedKey = await this.persistService.get(this.STORE_MASTER_KEY);\n\n if (!storedKey) {\n throw new KcNotFoundException(\n 'Could not find masterKey in persisted storage'\n );\n }\n\n if (storedKey.id !== masterKeyId) {\n throw new KcNotFoundException(\n `masterKeyId ${storedKey.id} in persisted storage does not match the one requested ${masterKeyId}`\n );\n }\n\n storedKey.jwk = await KFS.asKey(storedKey.jwk);\n\n this.masterKey = storedKey;\n }\n\n return this.masterKey;\n }\n}\n","/* eslint-disable @typescript-eslint/no-explicit-any */\nimport { Injectable } from '@angular/core';\nimport graphlib, { Graph } from '@dagrejs/graphlib';\nimport { JWK } from 'node-jose';\nimport { JSONObject } from '../api/types';\nimport {\n asJwk,\n DecryptOptions,\n EncryptionService,\n isSymmetricKey,\n} from '../encryption/encryption.service';\nimport { lodash } from '../_common';\nimport {\n KcBadArgumentException,\n KcBadLogicException,\n KcBadStateException,\n KcEncryptionException,\n KcNotFoundException,\n} from '../_common/exceptions';\nimport {\n KeyFactoryService,\n KeyFactoryService as KFS,\n} from './key-factory.service';\nimport { KeyService, UserKeys } from './key.service';\nimport {\n Key,\n KeyGraphEdge,\n KeyGraphEdgeType,\n KeyGraphNode,\n KeyGraphNodeType,\n KeyGraphResponse,\n KeyLink,\n PassKey,\n PayloadType,\n} from './key.types';\n\nexport interface GraphKey extends Key {\n task?: Promise<any>;\n}\n\n@Injectable({\n providedIn: 'root',\n})\nexport class KeyGraphService {\n private graph: Graph;\n // private keyCache: {\n // [id: string]: Key;\n // };\n\n constructor(\n private encryptionService: EncryptionService,\n private keyService: KeyService,\n private keyFactory: KeyFactoryService\n ) {\n this.purgeKeys();\n }\n\n purgeKeys() {\n this.graph = new Graph();\n // this.keyCache = null;\n }\n\n async populateKeys(userKey: UserKeys) {\n this.keyService.setKeys({\n passKey: userKey.passKey,\n masterKey: await this.keyService.loadMasterKey(userKey.masterKey.id),\n rootKey: await this.unwrapKey(userKey.masterKey.id, userKey.rootKey.id),\n pxk: await this.unwrapKey(userKey.masterKey.id, userKey.pxk.id),\n sigPxk: await this.unwrapKey(userKey.masterKey.id, userKey.sigPxk.id),\n });\n }\n\n hasKey(keyId: string) {\n return !!this.graph.node(keyId);\n }\n\n private getNode(id, type): GraphKey | PassKey {\n const node = this.graph.node(id);\n if (!node) {\n throw new KcNotFoundException(\n `Key graphs does not contain key id: ${id}`\n );\n }\n if (node.type !== type) {\n throw new KcBadStateException(`Key with id ${id} is not of type ${type}`);\n }\n return node.data;\n }\n\n key(id): GraphKey {\n return this.getNode(id, KeyGraphNodeType.Key);\n }\n\n passKey(id): PassKey {\n return this.getNode(id, KeyGraphNodeType.PassKey);\n }\n\n addKeys(src: KeyGraphResponse) {\n // Keys\n if (src.keys) {\n // What key graph returns can not be customized. So keys are essentially immutable.\n // Therefore, if a key exists, there's no reason to update it.\n for (const key of src.keys) {\n // Note using Relay global id allows us to not worry about clashing node id\n if (this.graph.hasNode(key.id)) {\n continue;\n }\n\n const node: KeyGraphNode = {\n type: KeyGraphNodeType.Key,\n data: lodash.cloneDeep(key),\n };\n\n this.graph.setNode(key.id, node);\n }\n }\n\n // KeyLinks\n if (src.keyLinks) {\n for (const keyLink of src.keyLinks) {\n if (this.graph.hasEdge(keyLink.wrappingKeyId, keyLink.keyId)) {\n continue;\n }\n\n const edge: KeyGraphEdge = {\n type: KeyGraphEdgeType.KeyLink,\n data: lodash.cloneDeep(keyLink),\n };\n // Edge goes from wrapping key to wrapped key.\n this.graph.setEdge(keyLink.wrappingKeyId, keyLink.keyId, edge);\n }\n }\n\n // PassKeyLinks\n if (src.passKeyLinks) {\n for (const passKeyLink of src.passKeyLinks) {\n if (this.graph.hasEdge(passKeyLink.passKeyId, passKeyLink.keyId)) {\n continue;\n }\n\n const edge: KeyGraphEdge = {\n type: KeyGraphEdgeType.PassKeyLink,\n data: lodash.cloneDeep(passKeyLink),\n };\n // Edge goes from wrapping key to wrapped key.\n this.graph.setEdge(passKeyLink.passKeyId, passKeyLink.keyId, edge);\n }\n }\n\n // The graph is the single source of truth. These are lazily calculated.\n // this.keyCache = null;\n }\n\n tracePath(distances, keyId: string): KeyGraphEdge[] {\n // The node label is the same as the id of the key nodes.\n const ret: KeyGraphEdge[] = [];\n let node = keyId;\n if (!distances[node].predecessor) {\n return null;\n }\n\n while (distances[node].predecessor) {\n const child = distances[node].predecessor;\n ret.push(this.graph.edge(child, node));\n node = child;\n }\n\n // After reverse, the first element is the passkey\n ret.reverse();\n\n return ret;\n }\n\n getPath(knownKeyId: string, keyId: string): KeyGraphEdge[] {\n if (!knownKeyId || typeof knownKeyId !== 'string') {\n throw new KcEncryptionException(\n `Param knownKeyId wrong format: ${knownKeyId}`\n );\n }\n if (!keyId || typeof keyId !== 'string') {\n throw new KcEncryptionException(`Param keyId wrong format: ${keyId}`);\n }\n\n // => { A: { distance: 0 },\n // B: { distance: 6, predecessor: 'C' },\n // C: { distance: 4, predecessor: 'A' },\n // D: { distance: 2, predecessor: 'A' },\n // E: { distance: 8, predecessor: 'F' },\n // F: { distance: 4, predecessor: 'D' } }\n const distances = graphlib.alg.dijkstra(this.graph, knownKeyId);\n\n // Trace path from keyId to knownKeyId\n return this.tracePath(distances, keyId);\n }\n\n async getJwkKey(\n keyOrId: string | Key,\n getKeyIdCallback?: () => Promise<string> | string\n ): Promise<JWK.Key> {\n return (await this.getKey(keyOrId, getKeyIdCallback)).jwk;\n }\n\n // We assume that when a keyId is fetched, the key graph\n // for the key is also returned and merged into the client-side\n // key graph. By insisting a keyId is returned instead of the\n // actual key we ensure key-graph is consistent.\n async getKey(\n keyOrId: string | Key,\n getKeyIdCallback?: () => Promise<string> | string\n ): Promise<Key> {\n let keyId = typeof keyOrId === 'string' ? keyOrId : keyOrId?.id;\n\n if (!this.hasKey(keyId) && getKeyIdCallback) {\n const keyIdFromCallback = await getKeyIdCallback();\n\n if (keyId != null && keyId != keyIdFromCallback) {\n throw new KcBadLogicException(\n 'Requested keyId is not in the key cache, so an API request was made to populate the key cache.' +\n 'But the key returned by the API does NOT match the requested keyId.' +\n 'This is a programming logic error.'\n );\n }\n\n keyId = keyIdFromCallback;\n }\n // else, continue and let it fail.\n\n const key = this.key(keyId);\n if (key.jwk) {\n return key;\n } else {\n return this.unwrapKey(this.keyService.currentMasterKey.id, keyId);\n }\n }\n\n private async _unwrapLink(\n wrappingKey: JWK.Key,\n link: KeyGraphEdge,\n dstKey: GraphKey\n ) {\n const wrappedKey = JSON.parse(link.data.wrappedKey);\n\n // Signatures of keys contain the key itself. This way we only need\n // to access the KeyLinks to decrypt/verify keys.\n let nextRawKey;\n if (wrappedKey.signatures) {\n nextRawKey = await this.encryptionService.verify(wrappingKey, wrappedKey);\n } else {\n nextRawKey = await this.encryptionService.decrypt(\n wrappingKey,\n wrappedKey\n );\n }\n\n // Handle nested keys. i.e. Enc{K1}{K2}{K3}(raw key 4), where:\n // K1: link.wrappingKey\n // K2: link.nestedWrappingKey[0]\n // K3: link.nestedWrappingKey[1]\n if (link.type == KeyGraphEdgeType.KeyLink) {\n const data = link.data as KeyLink;\n if (data.nestedWrappingKeyIds) {\n for (const nestedWrappingKeyId of data.nestedWrappingKeyIds) {\n const key = await this.getKey(nestedWrappingKeyId);\n nextRawKey = await this.encryptionService.decrypt(\n key.jwk,\n nextRawKey\n );\n }\n }\n }\n\n dstKey.jwk = await KFS.asKey(nextRawKey);\n dstKey.task = null;\n }\n\n private async _unwrap(key: JWK.Key, path: KeyGraphEdge[]): Promise<JWK.Key> {\n for (const link of path) {\n const dstKey = this.key(link.data.keyId);\n if (dstKey.jwk) {\n key = dstKey.jwk;\n continue;\n }\n\n if (!dstKey.task) {\n dstKey.task = this._unwrapLink(key, link, dstKey);\n }\n\n await dstKey.task;\n key = dstKey.jwk;\n }\n\n return key;\n }\n\n public async unwrapWithPassKey(\n passKeyId: string,\n passKey: JWK.Key,\n keyId: string\n ): Promise<Key> {\n // Get path of the directory key.\n const path = this.getPath(passKeyId, keyId);\n\n return {\n id: keyId,\n jwk: await this._unwrap(passKey, path),\n };\n }\n\n async unwrapKey(masterKeyId: string, keyId: string): Promise<Key> {\n // The first key should be a masterKey\n const masterKey = await this.keyService.loadMasterKey(masterKeyId);\n\n if (masterKeyId === keyId) {\n return masterKey;\n }\n\n // Get path of the directory key.\n const path = this.getPath(masterKey.id, keyId);\n\n return {\n id: keyId,\n jwk: await this._unwrap(masterKey.jwk, path),\n };\n }\n\n async decryptFromString<T>(\n keyOrId: string | Key,\n cipherData: string,\n options?: DecryptOptions\n ): Promise<T> {\n if (cipherData) {\n const key = await this.getJwkKey(keyOrId);\n return (await this.encryptionService.decrypt(\n key,\n JSON.parse(cipherData),\n options\n )) as any;\n }\n return null;\n }\n\n async decryptFile(keyId: string, file: any): Promise<any> {\n const key = await this.getJwkKey(keyId);\n return (await this.encryptionService.decrypt(key, file, {\n payloadType: PayloadType.UINT_8_ARRAY,\n })) as any;\n }\n\n // TODO rename this to encrypt() and use as the most common usecase\n async encryptToString(\n key: string | Key | JWK.Key,\n content: any\n ): Promise<string> {\n // Empty string should be encrypted since you want to clear the field.\n // Null is not encrypted because it's not valid JSON in the old JSON spec. Use\n // empty string instead. It'll function as a logic false as well.\n // Note that passing in empty string means it'll be encrypted which verifies\n // it's integrity. But we still want to have a way to set the DB field\n // to NULL, so we explicitly return null when content == null. A null\n // variable in graphql mutation on KC server clears the field to NULL.\n if (content == null) {\n return null;\n }\n\n const jwk = asJwk(key) || (await this.getJwkKey(key as string | Key));\n return this.encryptionService.encryptToString(jwk, content);\n }\n\n // Wraps a symmetric encryption key.\n // Throws exception if wrapping public keys.\n async wrapKey(\n wrappingKey: string | Key | JWK.Key,\n key: JWK.Key\n ): Promise<string> {\n if (!isSymmetricKey(key)) {\n throw new KcBadArgumentException(\n 'Only allowing wrapping of symmetric keys.'\n );\n }\n\n return this.encryptToString(wrappingKey, key.toJSON(true));\n }\n\n // TODO\n // async wrapPublicKey<T>();\n // async wrapPrivateKey<T>();\n\n async encryptWithNewKey(wrappingKeyId: string, cipherClearJson: JSONObject) {\n const key = await this.keyFactory.createKey();\n const wrappedKey = await this.encryptToString(\n wrappingKeyId,\n key.toJSON(true)\n );\n const cipher = await this.encryptToString(key, cipherClearJson);\n\n return {\n key,\n wrappingKeyId,\n wrappedKey,\n cipher,\n };\n }\n}\n","/* eslint-disable @typescript-eslint/no-explicit-any */\nimport { Injectable } from '@angular/core';\nimport { MutationOptions, QueryOptions } from '@apollo/client/core';\nimport { Apollo } from 'apollo-angular';\nimport { KeyGraphService } from '../key/key-graph.service';\nimport { HasKeyGraph } from '../key/key.types';\nimport { handleApolloError } from '../_common/exceptions';\n\n@Injectable({\n providedIn: 'root',\n})\nexport class LrApolloService {\n constructor(private apollo: Apollo, private keyGraph: KeyGraphService) {}\n\n private addKeys(response) {\n if ((response.data as HasKeyGraph).keyGraph) {\n this.keyGraph.addKeys((response.data as HasKeyGraph).keyGraph);\n }\n }\n\n async query<T, V = { [key: string]: any }>(\n options: QueryOptions<V>\n ): Promise<T> {\n const response = await this.apollo.query<T, V>(options).toPromise();\n\n handleApolloError(response.errors);\n\n this.addKeys(response);\n\n return response.data;\n }\n\n async mutate<T extends any, V = { [key: string]: any }>(\n options: MutationOptions<T, V>\n ): Promise<T> {\n const response = await this.apollo.mutate<T>(options).toPromise();\n\n handleApolloError(response.errors);\n\n this.addKeys(response);\n\n return response.data;\n }\n}\n","/* eslint-disable @typescript-eslint/no-explicit-any */\n// Abstract Syntax Tree\n\nimport {\n DocumentNode,\n FieldNode,\n FragmentDefinitionNode,\n NameNode,\n OperationDefinitionNode,\n OperationTypeNode,\n} from 'graphql';\nimport gql from 'graphql-tag';\nimport { KcBadArgumentException, KcBadLogicException } from './exceptions';\n\nexport function getAstOperation(\n astDocument,\n operation: OperationTypeNode\n): OperationDefinitionNode {\n const operations = astDocument.definitions.filter(\n (def: OperationDefinitionNode) => def.kind === 'OperationDefinition'\n );\n\n if (operations.length > 1) {\n throw new KcBadLogicException(\n `There can be only one '${operation}' operation, instead there are ${operations.length}`\n );\n }\n\n return operations[0];\n}\n\nexport function getQuery(doc: DocumentNode): OperationDefinitionNode {\n return getAstOperation(doc, 'query');\n}\n\nexport function getMutation(doc: DocumentNode): OperationDefinitionNode {\n return getAstOperation(doc, 'mutation');\n}\n\nexport function getFragments(doc: DocumentNode): FragmentDefinitionNode[] {\n return doc.definitions.filter(\n (def) => def.kind === 'FragmentDefinition'\n ) as FragmentDefinitionNode[];\n}\n\nexport function getFragment(astDocument: DocumentNode): FragmentDefinitionNode {\n const fragments = getFragments(astDocument);\n if (fragments.length > 1) {\n throw new KcBadArgumentException(\n 'GraphQL document can only contain one fragment.'\n );\n }\n return fragments[0];\n}\n\nexport function name(value: string): NameNode {\n return {\n kind: 'Name',\n value,\n };\n}\n\nexport function getAliasOrName(field: FieldNode) {\n return field.alias?.value || field.name.value;\n}\n\n// Collocates the type with the document.\n// eslint-disable-next-line @typescript-eslint/no-empty-interface, @typescript-eslint/no-unused-vars\nexport interface TypedDocumentNode<T> extends DocumentNode {}\n\nexport function gqlTyped<T = any>(\n literals: ReadonlyArray<string> | Readonly<string>,\n ...placeholders: any[]\n): TypedDocumentNode<T> {\n return gql(literals, ...placeholders) as TypedDocumentNode<T>;\n}\n","import gql from 'graphql-tag';\n\nconst KeyGraphFragmentBase = `\n{\n keys {\n id\n }\n keyLinks {\n keyId\n wrappingKeyId\n nestedWrappingKeyIds\n wrappedKey\n }\n passKeys {\n id\n }\n passKeyLinks {\n keyId\n passKeyId\n wrappedKey\n }\n __typename\n}\n`;\n\nexport const KeyGraphFragment = gql`\nfragment KeyGraphFragment on KeyGraphType ${KeyGraphFragmentBase}\n`;\n\nexport const KeyGraphField = `keyGraph ${KeyGraphFragmentBase}`;\n\nexport const FetchKeyGraphField = `keyGraph: fetchKeyGraph ${KeyGraphFragmentBase}`;\n\nexport const DirectoryQuery = gql`\n query Directory($id: LrRelayIdInput!, $cachedKeyIds: [LrRelayIdInput!]) {\n directory(id: $id) {\n id\n keyId\n plainMeta\n cipherMeta\n }\n keyGraph(cachedKeyIds: $cachedKeyIds) {\n ...KeyGraphFragment\n }\n }\n ${KeyGraphFragment}\n`;\n","/* eslint-disable @typescript-eslint/no-explicit-any */\nimport { KcBadLogicException } from './exceptions';\n\nexport interface RunOutsideAngularConfig {\n ngZoneName: string;\n // If true, a single change detection is triggered on resolve of the Promise returned\n // from the function.\n // else, the entire function is run outside of zone.\n // Note that if this is disabled, then change detection is not triggered even if you\n // use async pipes to subscribe to observables on the resulting promise. This is because\n // async pipes only _marks_ a component for change detection, it doesn't actually _trigger_\n // the change detection cycle.\n exceptLastPromise?: boolean;\n // Any method or property you wish to exclude from patch. The methods in EXCLUDE_METHODS are\n // never patched.\n excludeMethods?: string[];\n // If true, patch the setters as well. Settings are some\n // Note that setters do not return any thing. But they can still issue async calls.\n // These async calls are not visible to the wrapper. So we can't issue change detection\n // for setters when they are running outside angular.\n // Note that getters are not patched because getter and setter must use the same type. So if\n // the getter returns a promise, then the setting must alway take a promise. It doesn't make\n // much sense to use getters and setters this way. And if getter returns a value, then there's\n // no need to patch it to run outside angular.\n patchSetters?: boolean;\n}\n\n/**\n * If you wish to change the behaviour of those, you'll need to create a derived\n * class and override the methods.\n * However, can't figure out a way to call the super() in the derived class ctor, error says\n * the super call can't be in tested function.\n */\nexport const EXCLUDE_METHODS = [\n 'constructor',\n 'ngOnChanges',\n 'ngOnInit',\n 'ngDoCheck',\n 'ngAfterContentInit',\n 'ngAfterContentChecked',\n 'ngAfterViewInit',\n 'ngAfterViewChecked',\n 'ngOnDestroy',\n];\n\n// Patch all methods of the class.\n//\n// Note, this will not patch functions in the base class, it only\n// patches the function defined in the current class because it's\n// using getOwnPropertyNames(). You should be using composition for\n// services anyway.\n//\n// Ref: https://stackoverflow.com/a/44409244\n// The above approach might be a bit old. Now that we have ngZone.runOutsideAngular(),\n// we should probably use that and not touch any angular zone internals. But the approach\n// above doesn't require injecting ngZone.\n//\n// Ref: https://github.com/2ng/run-outside-angular/blob/master/src/run-outside-angular.ts\nexport function RunOutsideAngular({\n ngZoneName,\n exceptLastPromise = true,\n excludeMethods = [],\n patchSetters = true,\n}: RunOutsideAngularConfig) {\n return (target: any) => {\n function run(original, args) {\n if (!this[ngZoneName]) {\n throw new KcBadLogicException(\n `RunOutsideAngular decorator requires that ${target.name} inject NgZone as ${ngZoneName}`\n );\n }\n // runOutsideAngular() synchronously runs the callback and returns the result.\n const result = this[ngZoneName].runOutsideAngular(() =>\n original.apply(this, args)\n );\n\n if (exceptLastPromise && result?.then) {\n // Bring back into zone which will trigger change detection properly.\n // If this doesn't work, then we'll have to trigger change detection explicitly.\n return Promise.resolve(result);\n } else {\n return result;\n }\n }\n\n // There should be no reason to run any of the ones in EXCLUDE_METHODS outside angular.\n // So we always exclude them from patching. You can always explicit implement these ones differently.\n excludeMethods = [...excludeMethods, ...EXCLUDE_METHODS];\n\n const methods = Object.getOwnPropertyNames(target.prototype);\n\n methods\n .filter((method) => !excludeMethods.includes(method))\n .forEach((method) => {\n // Patch setters\n // Note that setters do not return any thing. But they can still issue async calls.\n // These async calls are not visible to the wrapper. So we can't issue change detection\n // for setters when they are running outside angular.\n if (\n patchSetters &&\n Object.getOwnPropertyDescriptor(target.prototype, method).set\n ) {\n const original = Object.getOwnPropertyDescriptor(\n target.prototype,\n method\n ).set;\n\n Object.defineProperty(target.prototype, method, {\n set(...args) {\n return run.apply(this, [original, args]);\n },\n });\n }\n\n if (typeof target.prototype[method] === 'function') {\n const original = target.prototype[method];\n\n target.prototype[method] = function (...args) {\n return run.apply(this, [original, args]);\n };\n }\n });\n\n return target;\n };\n}\n","/* eslint-disable @typescript-eslint/no-explicit-any */\nimport { Injectable, NgZone } from '@angular/core';\nimport { KeyGraphService } from '../../key/key-graph.service';\nimport { KcBadLogicException } from '../../_common/exceptions';\nimport { RunOutsideAngular } from '../../_common/run-outside-angular';\nimport { Connection } from '../types';\n\nexport interface ProcessorOptions {\n hasKeys: boolean;\n}\n\nexport const DefaultProcessorOptions: ProcessorOptions = {\n hasKeys: true,\n};\n\n// Sent to each processor for context information\nexport interface ProcessorContext {\n path: ReadonlyArray<string>;\n // processor can set this to false if child fields should\n // not be processed any further\n processChildren: boolean;\n}\n\nexport interface ProcessorCallbackParams<T = any> {\n field: T;\n context: ProcessorContext;\n options: ProcessorOptions;\n}\n\nexport type ProcessorCallback<T = any> = (\n params: ProcessorCallbackParams<T>\n) => T | Promise<T>;\n\ninterface ParseJsonProcessorOptions {\n plainFieldName?: string;\n jsonFieldSuffix?: string;\n}\n\ninterface DecryptionProcessorOptions {\n cipherFieldName?: string;\n clearFieldSuffix?: string;\n getKeyId?: (params: ProcessorCallbackParams) => Promise<string> | string;\n}\n\nexport async function processConnection<Node>(\n field: Connection<Node>,\n processNode: (node: Node) => Node | Promise<Node>\n): Promise<Connection<Node>> {\n return {\n ...field,\n edges: await Promise.all(\n field.edges.map(async (edge) => ({\n ...edge,\n node: await processNode(edge.node),\n }))\n ),\n };\n}\n\n@RunOutsideAngular({\n ngZoneName: 'ngZone',\n})\n@Injectable({\n providedIn: 'root',\n})\nexport class CommonProcessorsService {\n constructor(private ngZone: NgZone, private keyGraph: KeyGraphService) {}\n\n series(processors: ProcessorCallback[]): ProcessorCallback {\n return async ({ field, context, options }) => {\n for (const processor of processors) {\n field = await processor({ field, context, options });\n }\n return field;\n };\n }\n\n makeJsonParseProcessor({\n plainFieldName,\n jsonFieldSuffix = 'Json',\n }: ParseJsonProcessorOptions = {}): ProcessorCallback {\n const jsonFieldName = plainFieldName + jsonFieldSuffix;\n\n return ({ field }) => {\n if (field[plainFieldName] == null || jsonFieldName in field) {\n // if plainFieldName is undefined or null, then don't parse it.\n // if you parse it, then JSON.parse(null) and JSON.parse(\"null\") both return null, so\n // you can't distinguish between the two.\n // If clearFieldName already exists in node as a property, then we don't\n // need to process it again, even if it's value can be undefined or null even.\n return field;\n }\n\n try {\n return {\n ...field,\n [jsonFieldName]: JSON.parse(field[plainFieldName]),\n };\n } catch (error) {\n return field;\n }\n };\n }\n\n makeDecryptionProcessor({\n cipherFieldName,\n clearFieldSuffix = 'ClearJson',\n getKeyId = null,\n }: DecryptionProcessorOptions = {}): ProcessorCallback {\n const clearFieldName = cipherFieldName + clearFieldSuffix;\n\n return async (params) => {\n const { field, context, options } = params;\n\n // Can't decrypt anything if key graph is not returned\n if (!options.hasKeys) {\n return field;\n }\n\n const cipherField = field[cipherFieldName];\n\n // cipherField can be empty string, null or undefined.\n if (!cipherField || clearFieldName in field) {\n return field;\n }\n\n const keyId = getKeyId\n ? await getKeyId(params)\n : field.keyId || field.key?.id;\n\n if (!keyId) {\n const keyIdName = getKeyId ? 'key-id' : 'keyId or key.id';\n throw new KcBadLogicException(\n `Query response does not contain ${keyIdName} field: ${context.path.join(\n '.'\n )}`\n );\n }\n\n return this.keyGraph\n .decryptFromString(keyId, cipherField)\n .then((clear) => ({\n ...field,\n [clearFieldName]: clear,\n }));\n };\n }\n}\n","import { Injectable, NgZone } from '@angular/core';\nimport { KeyGraphService } from '../../key/key-graph.service';\nimport { Key } from '../../key/key.types';\nimport { KcBadRequestException } from '../../_common/exceptions';\nimport { RunOutsideAngular } from '../../_common/run-outside-angular';\nimport {\n ID,\n TpAssemblyApproverNode,\n TpAssemblyNode,\n TpPasswordResetNode,\n TpPasswordResetUser,\n TpPasswordResetUserApprovalNode,\n TpSubAssemblyNode,\n} from '../types';\nimport {\n processConnection,\n ProcessorCallbackParams,\n} from './common-processors.service';\n\n@RunOutsideAngular({\n ngZoneName: 'ngZone',\n})\n@Injectable({\n providedIn: 'root',\n})\nexport class TpPasswordResetProcessorService {\n constructor(private ngZone: NgZone, private keyGraph: KeyGraphService) {}\n\n async processTpPasswordResetUser(\n node: TpPasswordResetUser\n ): Promise<TpPasswordResetUser> {\n const pxk = node.pxk?.id && (await this.keyGraph.getKey(node.pxk.id));\n\n const ret = {\n ...node,\n };\n\n if (pxk && node.approvals) {\n ret.approvals = await Promise.all(\n node.approvals.map((approval) =>\n this.processTpPasswordResetUserApprovalNode(approval, pxk)\n )\n );\n }\n\n return ret;\n }\n\n private async processTpPasswordResetUserApprovalNode(\n approval: TpPasswordResetUserApprovalNode,\n pxk: Key\n ) {\n const ret = {\n ...approval,\n };\n\n if (approval.receiverCipher) {\n ret.receiverCipherClearJson = this.keyGraph.decryptFromString(\n pxk,\n approval.receiverCipher\n );\n }\n\n if (approval.receiverCipherPartialAssemblyKey) {\n ret.receiverCipherPartialAssemblyKeyClearJson =\n await this.keyGraph.decryptFromString(\n pxk,\n approval.receiverCipherPartialAssemblyKey\n );\n }\n return ret;\n }\n\n makeTpPasswordResetNodeProcessor() {\n return async ({\n field,\n }: ProcessorCallbackParams): Promise<TpPasswordResetNode> => {\n const ret = {\n ...field,\n };\n\n if (field.assembly) {\n if (field.applied == null) {\n throw new KcBadRequestException(\n 'If you request for field \"assembly\" in the TpPasswordResetNode, then you must also request the \"applied\" field'\n );\n }\n\n ret.assembly = await this.processTpAssemblyNode(\n field.assembly,\n field.applied\n );\n }\n\n return ret;\n };\n }\n\n private async processTpAssemblyNode(\n assembly: TpAssemblyNode,\n applied: boolean\n ): Promise<TpAssemblyNode> {\n // Subject key is encrypted user the master key. So if reset has been applied, then\n // these keys are not available any more.\n const { subjectKey, assemblyKey, assemblyCipherData, subAssemblies } =\n assembly;\n\n const ret: TpAssemblyNode = {\n ...assembly,\n subAssemblies: await processConnection(subAssemblies, (node) =>\n this.processTpSubAssemblyNode(node, subjectKey.id, applied)\n ),\n };\n\n if (!applied) {\n if (assemblyCipherData) {\n ret.assemblyCipherDataClearJson = await this.keyGraph.decryptFromString(\n assemblyKey.id,\n assemblyCipherData\n );\n }\n }\n\n return ret;\n }\n\n private async processTpSubAssemblyNode(\n subAssembly: TpSubAssemblyNode,\n subjectKeyId: ID,\n applied: boolean\n ): Promise<TpSubAssemblyNode> {\n const { subjectCipherData, approvers } = subAssembly;\n\n // const ret: TpSubAssemblyNode = {\n // ...subAssembly,\n // approvers: {\n // ...approvers,\n // edges: await Promise.all(\n // approvers.edges.map(async (edge) => ({\n // ...edge,\n // node: await this.processTpAssemblyApproverNode(edge.node, applied),\n // }))\n // ),\n // },\n // };\n const ret: TpSubAssemblyNode = {\n ...subAssembly,\n approvers: await processConnection(approvers, (node) =>\n this.processTpAssemblyApproverNode(node, applied)\n ),\n };\n\n if (!applied) {\n if (subjectCipherData) {\n ret.subjectCipherDataClearJson = await this.keyGraph.decryptFromString(\n subjectKeyId,\n subjectCipherData\n );\n }\n }\n\n return ret;\n }\n\n private async processTpAssemblyApproverNode(\n approver: TpAssemblyApproverNode,\n _applied: boolean\n ) {\n return approver;\n }\n}\n","/* eslint-disable @typescript-eslint/no-explicit-any */\nimport { Injectable, NgZone } from '@angular/core';\nimport { KeyService } from '../../key/key.service';\nimport { KcBadLogicException } from '../../_common/exceptions';\nimport { RunOutsideAngular } from '../../_common/run-outside-angular';\nimport { mapValuesMayAsync, promiseAllMayAsync } from '../../_common/utils';\nimport {\n CommonProcessorsService,\n DefaultProcessorOptions,\n // FieldContext,\n ProcessorCallback,\n ProcessorCallbackParams,\n ProcessorContext,\n ProcessorOptions,\n} from './common-processors.service';\nimport { TpPasswordResetProcessorService } from './tp-password-reset-processor.service';\n\nfunction extendPath(context: ProcessorContext, key: string): ProcessorContext {\n return {\n ...context,\n path: [...context.path, key],\n };\n}\n\n@RunOutsideAngular({\n ngZoneName: 'ngZone',\n})\n@Injectable({\n providedIn: 'root',\n})\nexport class QueryProcessorService {\n readonly TYPENAME = '__typename';\n private processors: { [key: string]: ProcessorCallback } = {};\n\n async processQuery(\n fields: { [key: string]: any },\n options: ProcessorOptions\n ) {\n options = {\n ...DefaultProcessorOptions,\n ...options,\n };\n\n // The top level query does not have __typename\n const ret = mapValuesMayAsync(fields, (field, key) =>\n this.processField({\n field,\n context: {\n path: [key],\n processChildren: true,\n },\n options,\n })\n );\n return ret;\n }\n\n // Either returns a Promise, or a value.\n // The Promise<any> type is redundant but it shows that it can return a promise\n // We are not using async on the function because we don't want auto promotion into a Promise, which\n // always defer execution into the event loops. It is costly and unnecessary for objects\n // with only native data types.\n private async processField({\n field,\n context,\n options,\n }: ProcessorCallbackParams) {\n if (field?.then) {\n throw new KcBadLogicException(\n 'processField() should not receive thenable.'\n );\n }\n\n if (field == null) {\n return null;\n }\n\n const newParams: ProcessorCallbackParams = {\n field,\n context: {\n ...context,\n // Processors modifies this field to communicate back to the caller.\n processChildren: true,\n },\n options,\n };\n\n // TODO allow registering processors by field name so we can process primitive fields as well.\n // We have common fields like \"created\", \"modified\" that be processed based on name.\n if (field[this.TYPENAME]) {\n // It's a custom object type\n const processor = this.processors[field[this.TYPENAME]];\n if (processor) {\n // Returns either a value or a promise.\n field = processor(newParams);\n }\n\n const processChildren = (childField) => {\n if (\n context.processChildren &&\n childField !== null &&\n typeof childField === 'object'\n ) {\n return mapValuesMayAsync(childField, (x, key) =>\n this.processField({\n field: x,\n context: extendPath(context, key),\n options,\n })\n );\n } else {\n return childField;\n }\n };\n\n // Keep processing all child fields\n if (field.then) {\n // Wait for field to resolve\n field = field.then((resolvedField) => {\n return processChildren(resolvedField);\n });\n } else {\n // Field is already resolved\n field = processChildren(field);\n }\n } else {\n // Keep processing all child fields\n if (context.processChildren) {\n if (Array.isArray(field)) {\n field = promiseAllMayAsync(\n (field as Array<any>).map((x, i) =>\n this.processField({\n field: x,\n context: extendPath(context, i.toString()),\n options,\n })\n )\n );\n }\n }\n }\n\n return field;\n }\n\n private registerProcessor(name: string, processor: ProcessorCallback) {\n if (this.processors[name]) {\n throw new KcBadLogicException(\n `Processor for field ${name} already exists.`\n );\n }\n this.processors[name] = processor;\n }\n\n constructor(\n private ngZone: NgZone,\n private keyService: KeyService,\n private common: CommonProcessorsService,\n private tpprProcessor: TpPasswordResetProcessorService\n ) {\n this.registerProcessor(\n 'DirectoryNode',\n common.series([\n common.makeJsonParseProcessor({\n plainFieldName: 'plainMeta',\n }),\n common.makeDecryptionProcessor({\n cipherFieldName: 'cipherMeta',\n }),\n ])\n );\n this.registerProcessor(\n 'FileStateNode',\n common.series([\n common.makeJsonParseProcessor({\n plainFieldName: 'plainMeta',\n }),\n common.makeDecryptionProcessor({\n cipherFieldName: 'cipherMeta',\n }),\n ])\n );\n this.registerProcessor(\n 'ContactCardNode',\n common.makeDecryptionProcessor({\n cipherFieldName: 'cipherData',\n })\n );\n this.registerProcessor(\n 'SharedContactCardNode',\n common.series([\n common.makeJsonParseProcessor({\n plainFieldName: 'ownerPlainData',\n }),\n common.makeDecryptionProcessor({\n cipherFieldName: 'ownerCipherData',\n getKeyId: ({ field }) => {\n return field.ownerKey.id;\n },\n }),\n common.makeDecryptionProcessor({\n cipherFieldName: 'receiverCipherData',\n getKeyId: ({ field }) => {\n return field.receiverKey.id;\n },\n }),\n common.makeDecryptionProcessor({\n cipherFieldName: 'sharedCipherData',\n getKeyId: ({ field }) => field.sharedKey.id,\n }),\n ])\n );\n this.registerProcessor(\n 'TpPasswordResetNode',\n this.tpprProcessor.makeTpPasswordResetNodeProcessor()\n );\n this.registerProcessor(\n 'SharedTpClaimApproverNode',\n common.series([\n common.makeDecryptionProcessor({\n cipherFieldName: 'sharedCipherApprovalData',\n getKeyId: ({ field }) => field.sharedKey.id,\n }),\n common.makeDecryptionProcessor({\n cipherFieldName: 'sharedCipherPartialAssemblyKey',\n getKeyId: ({ field }) => field.sharedKey.id,\n }),\n ])\n );\n this.registerProcessor(\n 'TpAssemblyAsApproverNode',\n common.series([\n common.makeDecryptionProcessor({\n cipherFieldName: 'sharedCipherData',\n getKeyId: ({ field }) => field.sharedKey.id,\n }),\n ])\n );\n this.registerProcessor(\n 'ScenarioNode',\n common.series([\n common.makeDecryptionProcessor({\n cipherFieldName: 'subjectCipherData',\n getKeyId: ({ field }) => field.subjectKey.id,\n }),\n ])\n );\n this.registerProcessor(\n 'ScenarioReceiverNode',\n common.series([\n common.makeDecryptionProcessor({\n cipherFieldName: 'sharedCipherData',\n getKeyId: ({ field }) => field.sharedKey.id,\n }),\n ])\n );\n this.registerProcessor(\n 'ScenarioReceiverDirectoryNode',\n common.series([\n common.makeDecryptionProcessor({\n cipherFieldName: 'sharedCipherData',\n getKeyId: ({ field }) => field.sharedKey.id,\n }),\n ])\n );\n this.registerProcessor(\n 'SharedScenarioReceiverDirectoryNode',\n common.series([\n common.makeDecryptionProcessor({\n cipherFieldName: 'sharedCipherData',\n getKeyId: ({ field }) => field.sharedKey.id,\n }),\n ])\n );\n this.registerProcessor(\n 'ScenarioReceiverFileNode',\n common.series([\n common.makeDecryptionProcessor({\n cipherFieldName: 'sharedCipherData',\n getKeyId: ({ field }) => field.sharedKey.id,\n }),\n ])\n );\n this.registerProcessor(\n 'SharedScenarioReceiverFileNode',\n common.series([\n common.makeDecryptionProcessor({\n cipherFieldName: 'sharedCipherData',\n getKeyId: ({ field }) => field.sharedKey.id,\n }),\n ])\n );\n this.registerProcessor(\n 'SharedScenarioReceiverNode',\n common.series([\n common.makeDecryptionProcessor({\n cipherFieldName: 'sharedCipherData',\n getKeyId: ({ field }) => field.sharedKey.id,\n }),\n ])\n );\n this.registerProcessor(\n 'ScenarioApproverAssemblyNode',\n common.series([\n common.makeDecryptionProcessor({\n cipherFieldName: 'assemblyCipherData',\n getKeyId: ({ field }) => field.assemblyKey.id,\n }),\n ])\n );\n this.registerProcessor(\n 'ScenarioApproverSubAssemblyNode',\n common.series([\n common.makeDecryptionProcessor({\n cipherFieldName: 'subjectCipherData',\n getKeyId: ({ field }) => field.subjectKey.id,\n }),\n ])\n );\n this.registerProcessor(\n 'ScenarioApproverNode',\n common.series([\n common.makeDecryptionProcessor({\n cipherFieldName: 'sharedCipherData',\n getKeyId: ({ field }) => field.sharedKey.id,\n }),\n common.makeDecryptionProcessor({\n cipherFieldName: 'sharedCipherApprovalData',\n getKeyId: ({ field }) => field.sharedKey.id,\n }),\n common.makeDecryptionProcessor({\n cipherFieldName: 'sharedCipherPartialAssemblyKey',\n getKeyId: ({ field }) => field.sharedKey.id,\n }),\n ])\n );\n this.registerProcessor(\n 'ScenarioClaimantNode',\n common.series([\n common.makeDecryptionProcessor({\n cipherFieldName: 'sharedCipherData',\n getKeyId: ({ field }) => field.sharedKey.id,\n }),\n ])\n );\n this.registerProcessor(\n 'TpAssemblyNode',\n common.series([\n common.makeDecryptionProcessor({\n cipherFieldName: 'subjectCipherData',\n getKeyId: ({ field }) => field.subjectKey.id,\n }),\n ])\n );\n this.registerProcessor(\n 'TpSubAssemblyNode',\n common.series([\n common.makeDecryptionProcessor({\n cipherFieldName: 'subjectCipherData',\n getKeyId: ({ field }) => field.subjectKey.id,\n }),\n ])\n );\n this.registerProcessor(\n 'NotificationNode',\n common.series([\n common.makeJsonParseProcessor({\n plainFieldName: 'plainMeta',\n }),\n common.makeJsonParseProcessor({\n plainFieldName: 'plainData',\n }),\n ])\n );\n this.registerProcessor(\n 'UserNode',\n common.series([\n common.makeJsonParseProcessor({\n plainFieldName: 'config',\n }),\n ])\n );\n this.registerProcessor(\n 'ReminderNode',\n common.series([\n common.makeJsonParseProcessor({\n plainFieldName: 'plain',\n }),\n ])\n );\n this.registerProcessor(\n 'DirectoryShareNode',\n common.series([\n common.makeJsonParseProcessor({\n plainFieldName: 'plainMeta',\n }),\n ])\n );\n this.registerProcessor(\n 'FileShareNode',\n common.series([\n common.makeJsonParseProcessor({\n plainFieldName: 'plainMeta',\n }),\n ])\n );\n }\n}\n","/* eslint-disable @typescript-eslint/no-explicit-any */\nexport type ResolvePromise<T> = (value?: T | PromiseLike<T>) => void;\nexport type RejectPromise = (reason?: any) => void;\n\nexport class DeferredPromise<T> {\n public readonly promise: Promise<T>;\n /* tslint:disable: variable-name */\n private _resolve: ResolvePromise<T>;\n /* tslint:disable: variable-name */\n private _reject: RejectPromise;\n /* tslint:disable: variable-name */\n private _fulfilled = false;\n\n constructor() {\n this.promise = new Promise<T>((resolve, reject) => {\n this._resolve = resolve;\n this._reject = reject;\n }).finally(() => {\n // finally() simply gets called on both then() and catch(). The promise\n // chain continues on.\n this._fulfilled = true;\n });\n }\n\n get resolve() {\n return this._resolve;\n }\n\n get reject() {\n return this._reject;\n }\n\n get fulfilled() {\n return this._fulfilled;\n }\n}\n","/* eslint-disable @typescript-eslint/no-explicit-any */\nimport { OperationVariables } from '@apollo/client/core';\nimport { FragmentSpreadNode } from 'graphql';\nimport gql from 'graphql-tag';\nimport { getQuery, TypedDocumentNode } from '../../_common/ast';\nimport { DeferredPromise } from '../../_common/deferred-promise';\nimport { KcBadStateException } from '../../_common/exceptions';\n\nexport interface LrMutationData<T, TVariables = OperationVariables> {\n mutation: TypedDocumentNode<T>;\n variables?: TVariables;\n}\n\nexport const fragmentSpreadAstSelection = getQuery(gql`\n query {\n ...FragmentName\n }\n`).selectionSet.selections[0] as FragmentSpreadNode;\n\n// const fragmentSpreadAstSelection = () =>\n// lodash.deepClone(_fragmentSpreadAstSelection) as FragmentSpreadNode;\n\n/**\n * DECISION: LrMutationBase does not provide a convenience method to call lrGraphQL.lrMutate()\n * because this class could be made independent of what lib is used to call the API. If we\n * provided a configurable call back to make the API call, then the typing for that callback\n * needs to be known. But since the API lib (eg. Apollo) has it's own unique return type, so\n * it's not possible to do in general.\n */\nexport abstract class LrMutationBase<T, TVariables = OperationVariables> {\n protected mutation: TypedDocumentNode<T>;\n protected variables?: TVariables;\n /* tslint:disable:variable-name */\n protected _executed = false;\n\n // protected promises: DeferredPromise<T>[] = [];\n public readonly deferredPromise = new DeferredPromise<T>();\n\n get promise(): Promise<T> {\n return this.deferredPromise.promise;\n }\n\n resolve(value: T) {\n this.deferredPromise.resolve(value);\n }\n\n reject(reason?: any) {\n this.deferredPromise.reject(reason);\n }\n\n get lrMutationData(): LrMutationData<T, TVariables> {\n return {\n mutation: this.mutation,\n variables: this.variables,\n };\n }\n\n get executed() {\n return this._executed;\n }\n\n setExecuted() {\n if (this._executed) {\n throw new KcBadStateException('Already executed');\n }\n this._executed = true;\n }\n}\n","/* eslint-disable @typescript-eslint/no-explicit-any */\nimport { OperationVariables } from '@apollo/client/core';\nimport { DocumentNode, FieldNode, FragmentDefinitionNode } from 'graphql';\nimport * as ast from '../../_common/ast';\nimport {\n getAliasOrName,\n getFragments,\n getMutation,\n TypedDocumentNode,\n} from '../../_common/ast';\nimport { lodash } from '../../_common';\nimport {\n fragmentSpreadAstSelection,\n LrMutationBase,\n LrMutationData,\n} from './lr-mutation-base';\n\nexport class LrMutation<\n T extends any,\n TVariables = OperationVariables\n> extends LrMutationBase<T, TVariables> {\n constructor(options: LrMutationData<T, TVariables>) {\n super();\n this.mutation = options.mutation;\n this.variables = options.variables;\n }\n\n /**\n * Select a different set of fields from the mutation. Example usage:\n *\n * interface CreateDirectoryMutationResult {\n * createDirectory: {\n * directory: DirectoryNode;\n * };\n * };\n *\n * const CreateDirectoryMutation = gqlTyped<CreateDirectoryMutationResult>`\n * mutation CreateDirectoryMutation(...) {\n * createDirectory(...) {\n * directory {\n * id\n * }\n * }\n * }\n * `\n * interface CreateDirectoryFragmentResult {\n * createDirectory: {\n * directory: DirectoryNode;\n * };\n * };\n *\n * const CreateDirectoryFragment = gqlTyped<CreateDirectoryFragmentResult>`\n * // Note that the string 'createDirectory' can not be changed.\n * // It must match with the mutation field above.\n * // The 'CreateDirectoryPayload' is the return type of the mutation.\n * fragment createDirectory on CreateDirectoryPayload {\n * directory {\n * plainMeta\n * }\n * }\n * `\n * lrGraphQLService.lrMutate({\n * mutation: CreateDirectoryMutation\n * }).select(CreateDirectoryFragment).createDirectory.directory.plainMeta.\n *\n * @param fragments\n * @returns\n */\n select<TResult>(fragments: TypedDocumentNode<TResult>) {\n // Don't touch the original\n const mutationDoc = lodash.cloneDeep(this.mutation) as DocumentNode;\n const mutationNode = getMutation(mutationDoc);\n\n const fragmentMap = {} as { [key: string]: FragmentDefinitionNode };\n getFragments(fragments).forEach((fragment: FragmentDefinitionNode) => {\n // Using '_' as the delimiter for the dummy suffix which only serves to make fragment names\n // unique since apollo client demands unique fragment names.\n fragmentMap[fragment.name.value.split('_')[0]] = fragment;\n });\n\n const replaceFieldSelection = (selection: FieldNode) => {\n const field = selection as FieldNode;\n const fieldName = getAliasOrName(field);\n const fragment = fragmentMap[fieldName];\n\n if (!fragment) {\n return;\n }\n\n // Make the entire selection of the mutation a spread of\n // a fragment using the same name as the mutation field.\n // We will also rename the fragment to the same name.\n field.selectionSet.selections = [\n {\n ...fragmentSpreadAstSelection,\n name: ast.name(fragment.name.value),\n },\n ];\n };\n\n mutationNode.selectionSet.selections.forEach((selection) => {\n if (selection.kind === 'Field') {\n replaceFieldSelection(selection);\n }\n });\n\n return new LrMutation({\n mutation: {\n ...mutationDoc,\n definitions: [\n // Remove all existing fragments\n ...mutationDoc.definitions.filter(\n (def) => def.kind !== 'FragmentDefinition'\n ),\n ...fragments.definitions,\n ],\n } as TypedDocumentNode<TResult>,\n variables: this.variables,\n });\n }\n}\n","/* eslint-disable @typescript-eslint/no-explicit-any */\nimport {\n ArgumentNode,\n DocumentNode,\n FieldNode,\n FragmentDefinitionNode,\n FragmentSpreadNode,\n SelectionNode,\n SelectionSetNode,\n VariableDefinitionNode,\n} from 'graphql';\nimport { lodash } from '../../_common';\nimport * as ast from '../../_common/ast';\nimport { getAliasOrName, getFragments, getMutation } from '../../_common/ast';\nimport {\n KcBadLogicException,\n KcUnsupportedException,\n} from '../../_common/exceptions';\nimport { LrMutation } from './lr-mutation';\nimport { LrMutationBase } from './lr-mutation-base';\n\nconst lrMergedMutationDoc: DocumentNode = {\n kind: 'Document',\n definitions: [\n {\n kind: 'OperationDefinition',\n operation: 'mutation',\n name: {\n kind: 'Name',\n value: 'lrMergedMutation',\n },\n variableDefinitions: [],\n directives: [],\n selectionSet: {\n kind: 'SelectionSet',\n selections: [],\n },\n },\n ],\n // TODO What to do about these? Serialise and reparse?\n // \"loc\": {\n // \"start\": 0,\n // \"end\": 204\n // }\n};\n\nexport class LrMergedMutation<T> extends LrMutationBase<T> {\n public readonly descendants: Set<LrMutationBase<any>>;\n protected prefixes: string[];\n\n constructor(public readonly lrMutations: LrMutationBase<any>[]) {\n super();\n\n const { mutation, variables, prefixes } = this.merge();\n this.mutation = mutation;\n this.variables = variables;\n this.prefixes = prefixes;\n this.descendants = this.getDescendants();\n }\n\n static create<T1, T2>(\n lrMutations: [\n LrMutationBase<T1> | LrMergedMutation<T1>,\n LrMutationBase<T2> | LrMergedMutation<T2>\n ]\n ): LrMergedMutation<[T1, T2]>;\n\n static create<T1, T2, T3>(\n lrMutations: [\n LrMutationBase<T1> | LrMergedMutation<T1>,\n LrMutationBase<T2> | LrMergedMutation<T2>,\n LrMutationBase<T3> | LrMergedMutation<T3>\n ]\n ): LrMergedMutation<[T1, T2, T3]>;\n\n static create<T1, T2, T3, T4>(\n lrMutations: [\n LrMutationBase<T1> | LrMergedMutation<T1>,\n LrMutationBase<T2> | LrMergedMutation<T2>,\n LrMutationBase<T3> | LrMergedMutation<T3>,\n LrMutationBase<T4> | LrMergedMutation<T4>\n ]\n ): LrMergedMutation<[T1, T2, T3, T4]>;\n\n static create<T1, T2, T3, T4, T5>(\n lrMutations: [\n LrMutationBase<T1> | LrMergedMutation<T1>,\n LrMutationBase<T2> | LrMergedMutation<T2>,\n LrMutationBase<T3> | LrMergedMutation<T3>,\n LrMutationBase<T4> | LrMergedMutation<T4>,\n LrMutationBase<T5> | LrMergedMutation<T5>\n ]\n ): LrMergedMutation<[T1, T2, T3, T4, T5]>;\n\n static create<T>(lrMutations: LrMutationBase<T>[]): LrMergedMutation<T[]>;\n\n static create(lrMutations: LrMutationBase<any>[]): LrMergedMutation<any[]>;\n\n static create(lrMutations: LrMutationBase<any>[]) {\n return new LrMergedMutation(lrMutations);\n }\n\n private getDescendants() {\n const ret = new Set<LrMutationBase<any>>();\n\n const addOrThrow = (item) => {\n if (ret.has(item)) {\n throw new KcBadLogicException(\n 'Classes that are derived from LrMutationBase can not be used more than once in a merged mutation.'\n );\n }\n\n ret.add(item);\n };\n\n this.lrMutations.forEach((lrMutation) => {\n if (lrMutation instanceof LrMutation) {\n addOrThrow(lrMutation);\n } else if (lrMutation instanceof LrMergedMutation) {\n lrMutation.descendants.forEach((t) => addOrThrow(t));\n } else {\n throw new KcUnsupportedException(\n `LrMergeMutation can not handle class: ${lrMutation.constructor.name}`\n );\n }\n });\n\n return ret;\n }\n\n resolve(value: any) {\n // Resolves any promises waiting for the child mutations\n for (let i = 0; i < this.lrMutations.length; ++i) {\n const prefix = this.prefixes[i];\n\n // Remove the prefix and resolve child mutation.\n const res: any = {};\n for (const key2 in value) {\n if (key2.startsWith(prefix)) {\n const originalKey = key2.slice(prefix.length);\n res[originalKey] = value[key2];\n }\n }\n this.lrMutations[i].resolve(res);\n }\n\n // Resolves to the result of children\n Promise.all(this.lrMutations.map((m) => m.promise)).then(\n (childValues: any) => {\n // Resolves any promises waiting for the current merged mutation\n super.resolve(childValues);\n }\n );\n }\n\n reject(reason?: any) {\n super.reject(reason);\n this.lrMutations.forEach((lrMutation) => lrMutation.reject(reason));\n }\n\n setExecuted() {\n super.setExecuted();\n this.lrMutations.forEach((lrMutation) => lrMutation.setExecuted());\n }\n\n private renameVariableDefinition(varDef: VariableDefinitionNode, prefix) {\n return {\n ...varDef,\n variable: {\n ...varDef.variable,\n name: ast.name(prefix + varDef.variable.name.value),\n },\n };\n }\n\n private renameVariableDefinitions(\n varDefs: ReadonlyArray<VariableDefinitionNode>,\n prefix\n ) {\n return varDefs.map((varDef) =>\n this.renameVariableDefinition(varDef, prefix)\n );\n }\n\n private renameArgument(arg: ArgumentNode, prefix) {\n if (arg.value.kind !== 'Variable') {\n return arg;\n }\n\n return {\n ...arg,\n value: {\n ...arg.value,\n name: ast.name(prefix + arg.value.name.value),\n },\n };\n }\n\n private renameField(selection: FieldNode, prefix): FieldNode {\n // Only handling type Field\n if (selection.kind !== 'Field') {\n return selection;\n }\n\n const alias = prefix + getAliasOrName(selection);\n const args = selection.arguments.map((arg) =>\n this.renameArgument(arg, prefix)\n );\n\n return {\n ...selection,\n alias: {\n kind: 'Name',\n value: alias,\n },\n arguments: args,\n };\n }\n\n private renameFragmentSpread(\n selection: FragmentSpreadNode,\n prefix\n ): FragmentSpreadNode {\n return {\n ...selection,\n name: ast.name(prefix + selection.name.value),\n };\n }\n\n private processSelection(selection: SelectionNode, prefix): SelectionNode {\n switch (selection.kind) {\n case 'FragmentSpread':\n return this.renameFragmentSpread(selection, prefix);\n case 'Field':\n // Continue to process children for nested selections.\n if (selection.selectionSet) {\n return {\n ...selection,\n selectionSet: this.processSelectionSet(\n selection.selectionSet,\n prefix\n ),\n };\n } else {\n return selection;\n }\n default:\n return selection;\n }\n }\n\n private processSelectionSet(\n selectionSet: SelectionSetNode,\n prefix\n ): SelectionSetNode {\n return {\n ...selectionSet,\n selections: selectionSet.selections.map((selection) =>\n this.processSelection(selection, prefix)\n ),\n };\n }\n\n private renameSelections(\n selections: ReadonlyArray<SelectionNode>,\n prefix\n ): SelectionNode[] {\n return selections.map((selection) => {\n switch (selection.kind) {\n case 'Field':\n return this.processSelection(\n this.renameField(selection, prefix),\n prefix\n );\n default:\n return selection;\n }\n });\n }\n\n private renameFragmentDefinition(fragment: FragmentDefinitionNode, prefix) {\n const ret = {\n ...fragment,\n name: ast.name(prefix + fragment.name.value),\n };\n\n if (fragment.selectionSet) {\n ret.selectionSet = this.processSelectionSet(\n fragment.selectionSet,\n prefix\n );\n }\n\n return ret;\n }\n\n private renameFragmentDefinitions(\n fragments: FragmentDefinitionNode[],\n prefix\n ) {\n return fragments.map((fragment) =>\n this.renameFragmentDefinition(fragment, prefix)\n );\n }\n\n private merge() {\n let variableDefinitions: VariableDefinitionNode[] = [];\n let selections: SelectionNode[] = [];\n const mergedVariables = {};\n let mergedFragments: FragmentDefinitionNode[] = [];\n\n const prefixes: string[] = [];\n\n // Just wait for everything to resolve because we have to\n // merge the doc synchronously.\n this.lrMutations.forEach((lrMutation, idx) => {\n // Sometimes typing won't catch everything. So need to dynamically check the\n // type to be sure.\n if (!(lrMutation instanceof LrMutationBase)) {\n throw new KcBadLogicException(\n 'An mutation in the array is not of type LrMutationBase.'\n );\n }\n\n const { mutation, variables } = lrMutation.lrMutationData;\n\n const childMutationNode = getMutation(mutation);\n\n // Prefixing all mutation fields so they don't conflict.\n let prefix = `item${idx}_`;\n if (childMutationNode.name) {\n prefix += childMutationNode.name.value + '_';\n }\n\n prefixes.push(prefix);\n\n // Rename and merge variables\n variableDefinitions = [\n ...variableDefinitions,\n ...this.renameVariableDefinitions(\n childMutationNode.variableDefinitions,\n prefix\n ),\n ];\n\n // Rename and merge selections\n selections = [\n ...selections,\n ...this.renameSelections(\n childMutationNode.selectionSet.selections,\n prefix\n ),\n ];\n\n // Rename and merge variables\n for (const key2 of Object.keys(variables)) {\n mergedVariables[prefix + key2] = variables[key2];\n }\n\n // Rename and merge fragments\n const fragments = getFragments(mutation);\n mergedFragments = [\n ...mergedFragments,\n ...this.renameFragmentDefinitions(fragments, prefix),\n ];\n });\n\n const mergedMutation: DocumentNode = lodash.cloneDeep(lrMergedMutationDoc);\n const mutationNode = getMutation(mergedMutation);\n // Add in the mutation selections\n mutationNode.selectionSet.selections = selections;\n // Add in the variables\n // variableDefinitions is readonly property.\n (mutationNode as any).variableDefinitions = variableDefinitions;\n // Add in the fragments\n (mergedMutation as any).definitions = [\n ...mergedMutation.definitions,\n ...mergedFragments,\n ];\n\n return {\n mutation: mergedMutation,\n variables: mergedVariables,\n prefixes,\n };\n }\n}\n","/* eslint-disable @typescript-eslint/no-explicit-any */\nimport { Injectable, NgZone } from '@angular/core';\nimport {\n FetchPolicy,\n MutationOptions,\n OperationVariables,\n QueryOptions,\n} from '@apollo/client/core';\nimport { MutationBaseOptions } from '@apollo/client/core/watchQueryOptions';\nimport { Apollo } from 'apollo-angular';\nimport { FieldNode } from 'graphql';\nimport gql from 'graphql-tag';\nimport * as gqlPrinter from 'graphql/language/printer';\nimport { KeyGraphService } from '../../key/key-graph.service';\nimport { HasKeyGraph } from '../../key/key.types';\nimport { lodash } from '../../_common';\nimport { getMutation, getQuery, TypedDocumentNode } from '../../_common/ast';\nimport {\n handleApolloError,\n KcBadStateException,\n KcUnsupportedException,\n} from '../../_common/exceptions';\nimport { FetchKeyGraphField, KeyGraphField } from '../../_common/queries.gql';\nimport { RunOutsideAngular } from '../../_common/run-outside-angular';\nimport { MayAsync } from '../../_common/types';\nimport { ProcessorOptions, QueryProcessorService } from '../query-processor';\nimport { LrMergedMutation } from './lr-merged-mutation';\nimport { LrMutationBase } from './lr-mutation-base';\n\n// Data structures\n// --------------------------------------------------------------------------\nconst keyGraphFieldAstSelection = getQuery(gql`\nquery {\n ${KeyGraphField}\n}\n`).selectionSet.selections[0] as FieldNode;\n\nconst fetchKeyGraphFieldAstSelection = getQuery(gql`\nquery {\n ${FetchKeyGraphField}\n}\n`).selectionSet.selections[0] as FieldNode;\n\n// const keyGraphFieldAstSelection = () =>\n// lodash.deepClone(_keyGraphFieldAstSelection) as FieldNode;\n// const fetchKeyGraphFieldAstSelection = () =>\n// lodash.deepClone(_fetchKeyGraphFieldAstSelection) as FieldNode;\n\nexport interface LrQueryOptions<T, TVariables>\n extends QueryOptions<TVariables> {\n query: TypedDocumentNode<T>;\n includeKeyGraph?: boolean;\n name?: string;\n processorOptions?: ProcessorOptions;\n}\n\n// Copied from MutationOptions\n// Removed required field \"mutation\". The \"variables\" field is still there\n// but it's dynamically checked.\nexport interface LrMutationOptions<\n T = {\n [key: string]: any;\n },\n TVariables = OperationVariables\n> extends MutationBaseOptions<T, TVariables> {\n context?: any;\n fetchPolicy?: FetchPolicy;\n includeKeyGraph?: boolean;\n name?: string;\n}\n\n// The \"mutation\" and \"variable\" fields are inherited but dynamically prohibited because\n// they are provided by LrMutation. It's a bit unclean but avoids a lot of typing work.\nexport interface LrApolloMutationOptions<T, TVariables = OperationVariables>\n extends MutationOptions<T, TVariables> {\n mutation: TypedDocumentNode<T>;\n includeKeyGraph?: boolean;\n name?: string;\n processorOptions?: ProcessorOptions;\n}\n\ninterface LrGraphQLServiceStats {\n queryCount: number;\n mutationCount: number;\n}\n\n@RunOutsideAngular({\n ngZoneName: 'ngZone',\n})\n@Injectable({\n providedIn: 'root',\n})\nexport class LrGraphQLService {\n private stats: LrGraphQLServiceStats = {\n queryCount: 0,\n mutationCount: 0,\n };\n\n constructor(\n private ngZone: NgZone,\n private apollo: Apollo,\n private keyGraph: KeyGraphService,\n private queryProcessor: QueryProcessorService\n ) {}\n\n async query<T, V = { [key: string]: any }>(\n options: LrQueryOptions<T, V>\n ): Promise<T> {\n // Make copies to avoid side effect.\n options = lodash.cloneDeep(options);\n\n // Append the key graph query\n const includeKeyGraph = this.isIncludeKeyGraph(options.includeKeyGraph);\n if (includeKeyGraph) {\n const operation = getQuery(options.query);\n operation.selectionSet.selections = [\n ...operation.selectionSet.selections,\n keyGraphFieldAstSelection,\n ];\n }\n\n if (options.name) {\n const operation = getQuery(options.query);\n (operation.name as any) = {\n kind: 'Name',\n value: options.name,\n };\n }\n\n const response = await this.apollo.query<T, V>(options).toPromise();\n\n this.stats.queryCount++;\n\n handleApolloError(response.errors);\n\n this.addKeys(response);\n\n const data = await this.queryProcessor.processQuery(\n response.data,\n options.processorOptions\n );\n\n return data;\n }\n\n private async lrMutateImpl(lrMutation, options?) {\n if (options?.variables) {\n throw new KcUnsupportedException(\n 'Unsupported field: \"options.variables\"'\n );\n }\n\n if (lrMutation.executed) {\n throw new KcBadStateException(\n 'LrMutation has already executed. LrMutation can only be used once in a lrMutate() call. Create new instances of LrMutation.'\n );\n }\n\n lrMutation.setExecuted();\n\n return this.apolloMutate({\n ...options,\n ...lrMutation.lrMutationData,\n })\n .then((res) => {\n // Resolve promises set on the lrMutation rather than the lrMutate() call.\n lrMutation.resolve(res);\n // Still need to return value to the promise waiting for the results of lrMutate().\n return res;\n })\n .catch((error) => {\n lrMutation.reject(error);\n throw error;\n });\n }\n\n async apolloMutate<T extends any, TVariables = { [key: string]: any }>(\n options: LrApolloMutationOptions<T, TVariables>\n ): Promise<T> {\n // Make copies to avoid side effect.\n options = {\n ...options,\n mutation: lodash.cloneDeep(options.mutation),\n };\n\n // Append the key graph query\n const includeKeyGraph = this.isIncludeKeyGraph(options.includeKeyGraph);\n\n if (includeKeyGraph) {\n const operation = getMutation(options.mutation);\n operation.selectionSet.selections = [\n ...operation.selectionSet.selections,\n fetchKeyGraphFieldAstSelection,\n ];\n }\n\n if (options.name) {\n const operation = getMutation(options.mutation);\n (operation.name as any) = {\n kind: 'Name',\n value: options.name,\n };\n }\n\n // Format to string and parse again. This allows the \"loc\": { \"start\": ... }\n // part of the DocumentNode to be correctly setup. It's extra processing\n // in serialising and parsing, but probably minimal overhead.\n options.mutation = gql(gqlPrinter.print(options.mutation));\n\n const response = await this.apollo.mutate<T>(options).toPromise();\n\n this.stats.mutationCount++;\n\n handleApolloError(response.errors);\n\n this.addKeys(response);\n\n const data = await this.queryProcessor.processQuery(\n response.data,\n options.processorOptions\n );\n\n return data;\n }\n\n statsSnapshot(): LrGraphQLServiceStats {\n return lodash.cloneDeep(this.stats);\n }\n\n private addKeys(response) {\n if ((response.data as HasKeyGraph).keyGraph) {\n this.keyGraph.addKeys((response.data as HasKeyGraph).keyGraph);\n delete response.data.keyGraph;\n }\n }\n\n private isIncludeKeyGraph(includeKeyGraph) {\n // Default to true when null or undefined.\n return includeKeyGraph == null ? true : false;\n }\n\n async lrMutate<T1, TVariables1, T2, TVariables2>(\n lrMutations: [\n LrMutationMayAsync<T1, TVariables1>,\n LrMutationMayAsync<T2, TVariables2>\n ],\n options?: LrMutationOptions\n ): Promise<[T1, T2]>;\n\n async lrMutate<T1, TVariables1, T2, TVariables2, T3, TVariables3>(\n lrMutations: [\n LrMutationMayAsync<T1, TVariables1>,\n LrMutationMayAsync<T2, TVariables2>,\n LrMutationMayAsync<T3, TVariables3>\n ],\n options?: LrMutationOptions\n ): Promise<[T1, T2, T3]>;\n\n async lrMutate<\n T1,\n TVariables1,\n T2,\n TVariables2,\n T3,\n TVariables3,\n T4,\n TVariables4\n >(\n lrMutations: [\n LrMutationMayAsync<T1, TVariables1>,\n LrMutationMayAsync<T2, TVariables2>,\n LrMutationMayAsync<T3, TVariables3>,\n LrMutationMayAsync<T4, TVariables4>\n ],\n options?: LrMutationOptions\n ): Promise<[T1, T2, T3, T4]>;\n\n async lrMutate<\n T1,\n TVariables1,\n T2,\n TVariables2,\n T3,\n TVariables3,\n T4,\n TVariables4,\n T5,\n TVariables5\n >(\n lrMutations: [\n LrMutationMayAsync<T1, TVariables1>,\n LrMutationMayAsync<T2, TVariables2>,\n LrMutationMayAsync<T3, TVariables3>,\n LrMutationMayAsync<T4, TVariables4>,\n LrMutationMayAsync<T5, TVariables5>\n ],\n options?: LrMutationOptions\n ): Promise<[T1, T2, T3, T4, T5]>;\n\n async lrMutate<T, TVariables = { [key: string]: any }>(\n lrMutation: LrMutationMayAsync<T, TVariables>,\n options?: LrMutationOptions<T, TVariables>\n ): Promise<T>;\n\n async lrMutate<T, TVariables = { [key: string]: any }>(\n lrMutations: LrMutationMayAsync<T, TVariables>[],\n options?: LrMutationOptions\n );\n\n async lrMutate<T, TVariables = { [key: string]: any }>(\n lrMutations:\n | LrMutationMayAsync<T, TVariables>[]\n | LrMutationMayAsync<T, TVariables>,\n options?: LrMutationOptions\n ) {\n if (lrMutations instanceof Array) {\n const merged = LrMergedMutation.create(await Promise.all(lrMutations));\n await this.lrMutateImpl(merged, options);\n return merged.promise;\n } else {\n const resolved = await lrMutations;\n await this.lrMutateImpl(resolved, options);\n return resolved.promise;\n }\n }\n}\n\nexport type LrMutationMayAsync<T, TVariables = OperationVariables> = MayAsync<\n LrMutationBase<T, TVariables>\n>;\n","import { Injector } from '@angular/core';\nimport {\n LrGraphQLService,\n LrMutationOptions,\n LrQueryOptions,\n} from './lr-graphql.service';\nimport { LrMutationBase } from './lr-mutation-base';\n\nexport class LrService {\n protected lrGraphQL: LrGraphQLService;\n\n constructor(injector: Injector) {\n this.lrGraphQL = injector.get(LrGraphQLService);\n }\n\n protected async mutate<T, TVariables>(\n lrMutation:\n | LrMutationBase<T, TVariables>\n | Promise<LrMutationBase<T, TVariables>>,\n options?: LrMutationOptions<T, TVariables>\n ) {\n return this.lrGraphQL.lrMutate(lrMutation, options);\n }\n\n protected async query<T, V>(options: LrQueryOptions<T, V>) {\n return this.lrGraphQL.query(options);\n }\n}\n","// ------------------------------------------------------\n// Basic types\n// ------------------------------------------------------\n// These types map directory to types of the same name in graphql.\n// We use these aliases in case in the future we wish to reify the types and do\n// additional automated conversion.\n\nexport type ID = string;\n// Server requires this to have certain format. But client\n// just treats this as an opaque string.\nexport type LrRelayIdInput = string;\nexport type DateTime = string;\n// This is basically the results of: JSON.stringify(obj)\n// Server validated to make sure it can JSON.parse() this.\nexport type LrJSONString = string;\n// JSONString is a type from graphene. DB JSON fields maps to this type\n// automatically.\n// Where as LrJSONString is out custom implementation for input variables.\nexport type JSONString = string;\n// This avoid triggering linting rule that prohibits using type any.\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport type JSONObject = any;\nexport type LrEmail = string;\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport type GenericScalar = any;\nexport type UUID = string;\n\nexport interface Node {\n id?: string;\n}\n\nexport interface TimeStamped {\n created?: DateTime;\n modified?: DateTime;\n}\n\nexport interface Edge<NodeType extends Node> {\n node?: NodeType;\n cursor?: string;\n}\n\nexport interface Connection<NodeType> {\n pageInfo?: PageInfo;\n edges?: Edge<NodeType>[];\n}\n\nexport interface PageInfo {\n hasNextPage?: boolean;\n hasPreviousPage?: boolean;\n startCursor?: string;\n endCursor?: string;\n}\n","import {\n Connection,\n DateTime,\n GenericScalar,\n ID,\n JSONObject,\n JSONString,\n LrEmail,\n Node,\n TimeStamped,\n} from './graphql.types';\n\nexport function mapEdges<T>(connection: Connection<T>) {\n return connection.edges.map((edge) => edge.node);\n}\n\nexport interface LrNList<T> {\n list?: T[];\n}\n\nexport interface FeaturesNode {\n myVault?: string[];\n tpVault?: string[];\n shareVault?: string[];\n}\n\nexport enum UserDeleteState {\n REQUESTED = 'REQUESTED',\n}\n\nexport interface UserDeleteNode extends Node, TimeStamped {\n state?: UserDeleteState;\n}\n\nexport enum PlanState {\n ENABLED = 'ENABLED',\n DISABLED = 'DISABLED',\n}\n\nexport interface PlanNode extends Node {\n name?: string;\n data?: JSONString;\n state?: PlanState;\n}\n\nexport interface UserPlanStripeNode extends Node, TimeStamped {\n subscriptionId?: string;\n priceId?: string;\n}\n\nexport interface UserPlanNode extends Node, TimeStamped {\n user?: UserNode;\n plan?: PlanNode;\n periodEnd?: DateTime;\n stripe?: UserPlanStripeNode;\n issuer?: UserNode;\n}\n\nexport interface UserStripeNode extends Node, TimeStamped {\n customer?: GenericScalar;\n}\n\nexport interface PassKeyNode extends Node, TimeStamped {\n passKeyParams?: GenericScalar;\n passIdpParams?: GenericScalar;\n wrappedPassIdpVerifierPrk?: GenericScalar;\n}\n\nexport interface CurrentUserKeyNode extends Node, TimeStamped {\n passKeys?: PassKeyNode[];\n passKey?: PassKeyNode;\n rootKey?: KeyNode;\n masterKey?: KeyNode;\n pxk?: KeyNode;\n sigPxk?: KeyNode;\n}\n\n// ------------------------------------------------------\n// Node types\n// ------------------------------------------------------\nexport interface UserNode extends Node {\n username?: string;\n contactCards?: Connection<ContactCardNode>;\n currentUserKey?: CurrentUserKeyNode;\n ownedContactCard?: SharedContactCardNode;\n receivedContactCard?: SharedContactCardNode;\n isCurrentUser?: boolean;\n haveTp?: boolean;\n stripe?: UserStripeNode;\n userPlans?: Connection<UserPlanNode>;\n userDelete?: UserDeleteNode;\n features?: FeaturesNode;\n featureState?: UserFeatureState;\n sessionEncryptionKey?: string;\n plans?: IssuedPlanNode[];\n paymentMethods?: PaymentMethodNode[];\n billingHistory?: BillingField[];\n availablePlans?: AvailablePlanField[];\n config?: JSONString;\n configJson?: JSONObject;\n dateJoined?: string;\n}\n\nexport interface UserFeatureState extends TimeStamped {\n notificationsLastViewed?: DateTime;\n}\n\nexport interface PublicProfile {\n userId?: ID;\n email?: string;\n}\n\nexport interface ServerTime {\n timestamp?: string;\n}\n\nexport interface KeyNode extends Node, TimeStamped {\n pbk?: string;\n}\n\nexport interface ContactCardNode extends Node, TimeStamped {\n owner?: UserNode;\n publicDataSig?: string;\n publicSearchableSig?: string;\n sigPxk?: KeyNode;\n defaultFrom?: DateTime;\n publicData?: string;\n publicSearchable?: string;\n cipherData?: string;\n cipherDataClearJson?: JSONObject;\n key?: KeyNode;\n plainData?: string;\n plainDataSig?: string;\n}\n\nexport interface AccessControlledResource {\n accessRole?: AccessRoleChoice;\n permissions?: PermissionChoice[];\n tpAccessRoles?: AccessRole[];\n allAccessRoles?: AllAccessRole[];\n confidentiality?: ConfidentialResource;\n}\n\nexport interface DirectoryNode\n extends Node,\n TimeStamped,\n AccessControlledResource {\n plainMeta?: JSONString;\n plainMetaJson?: JSONObject;\n cipherMeta?: string;\n cipherMetaClearJson?: JSONObject;\n archived?: boolean;\n keyId?: ID;\n childFileLinks?: Connection<FileLinkNode>;\n childDirectoryLinks?: Connection<DirectoryLinkNode>;\n parentDirectoryLinks?: Connection<DirectoryLinkNode>;\n nParentDirectoryLinks?: LrNList<DirectoryLinkNode>;\n nChildDirectoryLinks?: LrNList<DirectoryLinkNode>;\n nChildFileLinks?: LrNList<FileLinkNode>;\n descendants?: Descendants;\n lock?: LockField;\n lockVersion?: string;\n shares?: Connection<DirectoryShareNode>;\n nShares?: LrNList<DirectoryShareNode>;\n reminder?: ReminderNode;\n}\n\nexport interface FileNode extends Node, TimeStamped, AccessControlledResource {\n currentVersion?: FileVersionNode;\n archived?: boolean;\n versions?: Connection<FileVersionNode>;\n keyId?: ID;\n parentDirectoryLinks?: Connection<FileLinkNode>;\n nParentDirectoryLinks?: LrNList<FileLinkNode>;\n lock?: LockField;\n lockVersion?: string;\n shares?: Connection<FileShareNode>;\n nShares?: LrNList<FileShareNode>;\n}\n\nexport interface DirectoryLinkNode extends Node, TimeStamped {\n parentDirectory?: DirectoryNode;\n childDirectory?: DirectoryNode;\n linkType?: LinkTypeField;\n}\n\nexport interface FileLinkNode extends Node, TimeStamped {\n parentDirectory?: DirectoryNode;\n childFile?: FileNode;\n linkType?: LinkTypeField;\n}\n\nexport enum ShareTypeChoice {\n TP = 'TP',\n DETACHED = 'DETACHED',\n}\n\nexport enum DetachedShareStateChoice {\n IN_PROGRESS = 'IN_PROGRESS',\n COMPLETED = 'COMPLETED',\n}\n\n// Not a generic so we can pick fields from this interface.\nexport interface ItemShareBase extends Node, TimeStamped {\n tp?: TpNode;\n role?: AccessRoleChoice;\n issuer?: PublicProfile;\n isIssuer?: boolean;\n subject?: PublicProfile;\n shareType?: ShareTypeChoice;\n detachedShareState?: DetachedShareStateChoice;\n plainMeta?: JSONString;\n plainMetaJson?: JSONObject;\n}\n\nexport interface ItemShare<ItemType> extends ItemShareBase {\n item?: ItemType;\n}\nexport type DirectoryShareNode = ItemShare<DirectoryNode>;\nexport type FileShareNode = ItemShare<FileNode>;\n\nexport interface Descendants {\n directories?: Connection<DirectoryNode>;\n files?: Connection<FileNode>;\n directoriesCount?: number;\n filesCount?: number;\n}\n\nexport enum AccessRoleChoice {\n READER = 'READER',\n WRITER = 'WRITER',\n ADMIN = 'ADMIN',\n CUSTODIAN = 'CUSTODIAN',\n DENY = 'DENY',\n OWNER = 'OWNER',\n}\n\nexport enum AccessRoleChoiceOrder {\n READER = 0,\n WRITER = 1,\n ADMIN = 2,\n CUSTODIAN = 3,\n DENY = 4,\n CONFIDENTIAL = 5,\n OWNER = 6,\n}\n\nexport enum AccessRoleMethodChoice {\n INHERITED = 'INHERITED',\n DIRECT = 'DIRECT',\n}\n\nexport enum PermissionChoice {\n CREATE = 'CREATE',\n READ = 'READ',\n UPDATE = 'UPDATE',\n DELETE = 'DELETE',\n SHARE = 'SHARE',\n ARCHIVE = 'ARCHIVE',\n ACCESS_ARCHIVED = 'ACCESS_ARCHIVED',\n UNARCHIVE = 'UNARCHIVE',\n SET_CONFIDENTIAL = 'SET_CONFIDENTIAL',\n}\n\nexport interface ConfidentialResource {\n isConfidential?: boolean;\n method?: AccessRoleMethodChoice;\n}\n\nexport interface InheritedRole {\n role?: AccessRoleChoice;\n source?: DirectoryNode;\n}\n\nexport interface AccessRoleBase {\n role?: AccessRoleChoice;\n method?: AccessRoleMethodChoice;\n inheritedRole?: InheritedRole;\n isIssuer?: boolean;\n}\n\nexport interface AccessRole extends AccessRoleBase {\n issuer?: UserNode;\n subject?: UserNode;\n tp?: TpNode;\n}\n\nexport interface AllAccessRole extends AccessRoleBase {\n issuer?: PublicProfile;\n subject?: PublicProfile;\n}\n\nexport enum FileOperationField {\n CREATE = 'CREATE',\n READ = 'READ',\n UPDATE = 'UPDATE',\n REVERT = 'REVERT',\n DELETE = 'DELETE',\n}\n\nexport interface FileVersionNode extends Node, TimeStamped {\n file?: FileNode;\n state?: FileStateNode;\n operation?: FileOperationField;\n author?: UserNode;\n}\nexport interface FileStateNode extends Node, TimeStamped {\n plainMeta?: JSONString;\n plainMetaJson?: JSONObject;\n cipherMeta?: string;\n cipherMetaClearJson?: JSONObject;\n contentResource?: string;\n versions?: Connection<FileVersionNode>;\n keyId?: ID;\n}\n\nexport enum KeyExchangeOtkState {\n OTK_INITIATED = 'OTK_INITIATED',\n OTK_ACCEPTED = 'OTK_ACCEPTED',\n OTK_COMPLETED = 'OTK_COMPLETED',\n}\n\n// These fields are not optional because they are not within the user's control to select in a gql query.\nexport interface ContactCardSharedCipherData {\n // Shared read access between initiator and responder. But only the initiator has write access.\n sharedCipherDataClearJson: JSONObject;\n}\n\n/**\n * The contents of the one-time key cipher\n * These fields are not optional because they are not within the user's control to select in a gql query.\n */\nexport interface OtKeyCipherClearJson2 {\n // Used to confirm to the initiator that the responder has access to the one-time key.\n nonce: string;\n // Data sent from initiator to the responder\n initiator: {\n oneTimePbk: Record<string, JSONObject>; // one-time public encryption key the responder will use to send data back to the initiator\n pbk: Record<string, JSONObject>; // public encryption key\n sigPbk: Record<string, JSONObject>; // public signing key\n message?: JSONObject;\n contactCard?: ContactCardSharedCipherData;\n };\n}\n\nexport interface KeyExchangeOtkNode extends Node, TimeStamped {\n state?: KeyExchangeOtkState;\n sharedKey?: KeyNode;\n mkSharedKey?: KeyNode;\n initiatorSigPxk?: KeyNode;\n responderSigPxk?: KeyNode;\n initiatorOneTimePbkCipher?: string;\n otKeyParams?: string;\n otKeyCipher?: string;\n otKeyCipherClearJson?: OtKeyCipherClearJson2;\n responderPbkCipher?: string;\n}\n\nexport enum KeyExchangeState {\n IN_PROGRESS = 'IN_PROGRESS',\n COMPLETED = 'COMPLETED',\n DECLINED = 'DECLINED',\n CANCELLED = 'CANCELLED',\n DELETED = 'DELETED',\n}\n\nexport enum KeyExchangeMode {\n OTK = 'OTK',\n}\n\nexport interface KeyExchangeNode extends Node, TimeStamped {\n expiryTime?: DateTime;\n token?: string;\n tokenExpiryTime?: DateTime;\n state?: KeyExchangeState;\n mode?: KeyExchangeMode;\n initiator?: UserNode;\n responder?: UserNode;\n initiatorRootKeyCipher?: string;\n responderRootKeyCipher?: string;\n initiatorActionRequired?: boolean;\n responderActionRequired?: boolean;\n createTp?: boolean;\n otk?: KeyExchangeOtkNode;\n isInitiator?: boolean;\n isExpired?: boolean;\n responderEmailAddress?: LrEmail;\n}\n\nexport interface SharedItems {\n descendants: Descendants;\n directories?: Connection<DirectoryNode>;\n files?: Connection<FileNode>;\n}\n\nexport interface SharedContactCardNode extends Node, TimeStamped {\n owner?: UserNode;\n receiver?: UserNode;\n sharedKey?: KeyNode;\n sharedCipherData?: string;\n sharedCipherDataClearJson?: JSONObject;\n sharedCipherDataSig?: string;\n sharedCipherDataSigPxk?: KeyNode;\n ownerCipherData?: string;\n ownerCipherDataClearJson?: JSONObject;\n ownerKey?: KeyNode;\n ownerPlainData?: string;\n ownerPlainDataJson?: JSONObject;\n ownerPlainDataSig?: string;\n receiverCipherData?: string;\n receiverCipherDataClearJson?: JSONObject;\n receiverKey?: KeyNode;\n}\n\nexport interface UserSharedKeyNode extends Node, TimeStamped {\n keyExchange?: KeyExchangeNode;\n user?: UserNode;\n userPrk?: KeyNode;\n userSigPrk?: KeyNode;\n other?: UserNode;\n otherPbk?: KeyNode;\n otherSigPbk?: KeyNode;\n sharedKey?: KeyNode;\n mkSharedKey?: KeyNode;\n mkPxk?: KeyNode;\n mkReshareRequestCipher?: string;\n mkReshareResponseCipher?: string;\n mkReshareRequestCipherClearJson?: JSONObject;\n mkReshareResponseCipherClearJson?: JSONObject;\n mkReshareRequestSent?: boolean;\n mkReshareResponseSent?: boolean;\n}\n\nexport interface CurrentUserSharedKeyNode extends Node, TimeStamped {\n user?: UserNode;\n other?: UserNode;\n userSharedKey?: UserSharedKeyNode;\n}\n\nexport interface TpNode extends Node, TimeStamped {\n user?: UserNode;\n other?: UserNode;\n currentUserSharedKey?: CurrentUserSharedKeyNode;\n isCompleted?: boolean;\n sharedKey?: KeyNode;\n sharedContactCard?: SharedContactCardNode;\n myContactCard?: SharedContactCardNode;\n myItems?: SharedItems;\n theirItems?: SharedItems;\n myScenarios?: Connection<ScenarioNode>;\n sharedScenarios?: Connection<SharedScenarioNode>;\n}\n\nexport enum TpAssemblyState {\n DISABLED = 'DISABLED',\n ENABLED = 'ENABLED',\n CLAIMED = 'CLAIMED',\n APPROVED = 'APPROVED',\n REJECTED = 'REJECTED',\n EXPIRED = 'EXPIRED',\n CANCELLED = 'CANCELLED',\n RESET = 'RESET',\n}\n\nexport enum TpClaimState {\n CLAIMED = 'CLAIMED',\n APPROVED = 'APPROVED',\n REJECTED = 'REJECTED',\n EXPIRED = 'EXPIRED',\n CANCELLED = 'CANCELLED',\n RESET = 'RESET',\n}\n\nexport enum TpClaimApproverState {\n CLAIMED = 'CLAIMED',\n APPROVED = 'APPROVED',\n REJECTED = 'REJECTED',\n}\n\nexport interface TpPasswordResetApproval extends Node, TimeStamped {\n approverEmail?: string;\n receiverCipher?: string;\n receiverCipherClearJson?: JSONObject;\n receiverCipherPartialAssemblyKey?: string;\n receiverCipherPartialAssemblyKeyClearJson?: JSONObject;\n}\n\nexport interface TpPasswordResetUserApprovalNode extends Node, TimeStamped {\n receiverCipher?: string;\n receiverCipherClearJson?: JSONObject;\n receiverCipherPartialAssemblyKey?: string;\n receiverCipherPartialAssemblyKeyClearJson?: JSONObject;\n approverEmail?: string;\n}\n\nexport interface TpPasswordResetUserApprover {\n name?: string;\n email?: string;\n state?: TpClaimApproverState;\n}\n\nexport interface TpPasswordResetUserSubAssembly {\n singleReject?: boolean;\n quorum?: number;\n approvers?: TpPasswordResetUserApprover[];\n}\n\nexport interface TpPasswordResetUserAssembly {\n singleReject?: boolean;\n quorum?: number;\n subAssemblies?: TpPasswordResetUserSubAssembly[];\n}\n\nexport interface TpPasswordResetUser {\n username?: string;\n resetUsername?: string;\n state?: TpClaimState;\n passKey?: PassKeyNode;\n masterKey?: KeyNode;\n pxk?: KeyNode;\n sessionEncryptionKey?: string;\n approvals?: TpPasswordResetUserApprovalNode[];\n assemblyCipherData?: string;\n wrappedAssemblyKeyVerifierPrk?: string;\n assembly?: TpPasswordResetUserAssembly;\n requestAgainAfter?: DateTime;\n}\n\nexport interface TpPasswordResetNode extends Node, TimeStamped {\n assembly?: TpAssemblyNode;\n request?: TpPasswordResetRequestNode;\n applied?: boolean;\n}\n\nexport interface TpPasswordResetRequestNode extends Node, TimeStamped {\n state?: TpClaimState;\n}\n\nexport interface TpAssemblyNode extends Node, TimeStamped {\n id?: ID;\n singleReject?: boolean;\n quorum?: number;\n canMeetQuorum?: boolean;\n subjectKey?: KeyNode;\n subjectCipherData?: string;\n subjectCipherDataClearJson?: JSONObject;\n assemblyKey?: KeyNode;\n assemblyCipherData?: string;\n assemblyCipherDataClearJson?: JSONObject;\n subAssemblies?: Connection<TpSubAssemblyNode>;\n}\n\nexport interface TpSubAssemblyNode extends Node, TimeStamped {\n singleReject?: boolean;\n quorum?: number;\n subjectCipherData?: string;\n subjectCipherDataClearJson?: JSONObject;\n approvers?: Connection<TpAssemblyApproverNode>;\n}\n\nexport interface TpAssemblyApproverNode extends Node, TimeStamped {\n sharedKey?: KeyNode;\n sharedCipherData?: string;\n sharedCipherDataClearJson?: JSONObject;\n sharedCipherApprovalData?: string;\n sharedCipherApprovalDataClearJson?: JSONObject;\n tp?: TpNode;\n}\n\nexport interface SharedTpPasswordResetNode extends Node, TimeStamped {\n assembly?: SharedTpAssemblyNode;\n tp?: TpNode;\n sharedRequest?: SharedTpPasswordResetRequestNode;\n}\n\nexport interface SharedTpAssemblyNode extends Node, TimeStamped {\n asApprovers?: Connection<TpAssemblyAsApproverNode>;\n}\n\nexport interface TpAssemblyAsApproverNode extends Node, TimeStamped {\n sharedKey?: KeyNode;\n sharedCipherData?: string;\n sharedCipherDataClearJson?: JSONObject;\n}\n\nexport interface SharedTpPasswordResetRequestNode extends Node, TimeStamped {\n claim?: SharedTpClaimNode;\n pxk?: KeyNode;\n}\n\nexport interface SharedTpClaimNode extends Node, TimeStamped {\n state?: TpClaimState;\n asClaimApprovers?: Connection<SharedTpClaimApproverNode>;\n}\n\nexport interface SharedTpClaimApproverNode extends Node, TimeStamped {\n state?: TpClaimApproverState;\n sharedKey?: KeyNode;\n sharedCipherApprovalData?: string;\n sharedCipherApprovalDataClearJson?: JSONObject;\n sharedCipherPartialAssemblyKey?: string;\n sharedCipherPartialAssemblyKeyClearJson?: JSONObject;\n receiverApprovals?: Connection<SharedTpClaimReceiverApprovalNode>;\n}\n\nexport interface SharedTpClaimReceiverApprovalNode extends Node, TimeStamped {\n pxk?: KeyNode;\n}\n\nexport enum LockState {\n UNLOCKED = 'UNLOCKED',\n MUTEX_LOCKED = 'MUTEX_LOCKED',\n}\n\nexport enum ScenarioState {\n DISABLED = 'DISABLED',\n ENABLED = 'ENABLED',\n CLAIMED = 'CLAIMED',\n APPROVED = 'APPROVED',\n}\n\nexport enum ClaimState {\n CLAIMED = 'CLAIMED',\n EXPIRED = 'EXPIRED',\n APPROVED = 'APPROVED',\n REJECTED = 'REJECTED',\n CANCELLED = 'CANCELLED',\n RESET = 'RESET',\n}\n\nexport enum ClaimApproverState {\n CLAIMED = 'CLAIMED',\n APPROVED = 'APPROVED',\n REJECTED = 'REJECTED',\n}\n\nexport enum ScenarioLastClaimState {\n CLAIMED = 'CLAIMED',\n APPROVED = 'APPROVED',\n REJECTED = 'REJECTED',\n EXPIRED = 'EXPIRED',\n CANCELLED = 'CANCELLED',\n RESET = 'RESET',\n}\n\nexport interface ScenarioLatestClaim {\n state?: ScenarioLastClaimState;\n created?: DateTime;\n claimAgainAfter?: DateTime;\n}\n\nexport interface ScenarioNode extends Node, TimeStamped {\n subject?: UserNode;\n subjectKey?: KeyNode;\n subjectCipherData?: string;\n subjectCipherDataClearJson?: JSONObject;\n assembly?: TpAssemblyNode;\n state?: ScenarioState;\n claimants?: Connection<ScenarioClaimantNode>;\n receivers?: Connection<ScenarioReceiverNode>;\n claims?: Connection<ScenarioClaimNode>;\n claim?: ScenarioClaimNode;\n assemblyState?: ScenarioAssemblyState;\n latestClaim?: ScenarioLatestClaim;\n inactiveSeconds?: number;\n}\n\nexport interface ScenarioClaimNode extends Node, TimeStamped {\n claimant?: ScenarioClaimantNode;\n state?: ClaimState;\n scenario?: ScenarioNode;\n}\n\nexport interface ScenarioAssemblyState {\n singleReject?: boolean;\n quorum?: number;\n subAssemblyStates?: ScenarioSubAssemblyState[];\n}\n\nexport interface ScenarioSubAssemblyState {\n singleReject?: boolean;\n quorum?: number;\n approverStates?: ScenarioAssemblyApproverState[];\n}\n\nexport interface ScenarioAssemblyApproverState {\n state?: TpClaimApproverState;\n}\n\nexport interface ReceiverItems {\n receiverDirectories?: Connection<ScenarioReceiverDirectoryNode>;\n receiverFiles?: Connection<ScenarioReceiverFileNode>;\n}\n\nexport interface SharedScenarioReceiverItems {\n receiverDirectories?: Connection<SharedScenarioReceiverDirectoryNode>;\n receiverFiles?: Connection<SharedScenarioReceiverFileNode>;\n}\n\nexport interface ScenarioReceiverNodeBase extends Node, TimeStamped {\n sharedKey?: KeyNode;\n sharedCipherData?: string;\n sharedCipherDataClearJson?: JSONObject;\n pbk?: KeyNode;\n tp?: TpNode;\n}\n\n// For now these are the same but they may diverge in the future.\nexport interface ScenarioReceiverNode extends ScenarioReceiverNodeBase {\n receiverItems?: ReceiverItems;\n}\n\nexport interface SharedScenarioReceiverNode extends ScenarioReceiverNodeBase {\n receiverItems?: SharedScenarioReceiverItems;\n}\n\nexport type ReceiverDirectoryAccessRole = AccessRoleChoice;\n\nexport interface ScenarioReceiverItemNode extends Node, TimeStamped {\n sharedKey?: KeyNode;\n sharedCipherData?: string;\n sharedCipherDataClearJson?: JSONObject;\n accessRole?: ReceiverDirectoryAccessRole;\n}\n\nexport interface ScenarioReceiverDirectoryNode\n extends ScenarioReceiverItemNode {\n receiver?: ScenarioReceiverNode;\n directory?: DirectoryNode;\n}\n\nexport interface ScenarioReceiverFileNode extends ScenarioReceiverItemNode {\n receiver?: ScenarioReceiverNode;\n file?: FileNode;\n}\n\nexport interface SharedScenarioReceiverDirectoryNode\n extends ScenarioReceiverItemNode {\n receiver?: SharedScenarioReceiverNode;\n directory?: DirectoryNode;\n}\n\nexport interface SharedScenarioReceiverFileNode\n extends ScenarioReceiverItemNode {\n receiver?: SharedScenarioReceiverNode;\n file?: FileNode;\n}\n\nexport interface ScenarioClaimantNode extends Node, TimeStamped {\n tp?: TpNode;\n sharedKey?: KeyNode;\n sharedCipherData?: string;\n sharedCipherDataClearJson?: JSONObject;\n}\n\nexport interface SharedScenarioNode extends Node, TimeStamped {\n subject?: UserNode;\n state?: ScenarioState;\n tp?: TpNode;\n asClaimant?: ScenarioClaimantNode;\n asReceiver?: ScenarioReceiverNode;\n assembly?: SharedTpAssemblyNode;\n sharedClaim?: SharedScenarioClaimNode;\n assemblyState?: ScenarioAssemblyState;\n latestClaim?: ScenarioLatestClaim;\n}\n\nexport interface SharedScenarioClaimNode extends Node, TimeStamped {\n state?: ClaimState;\n sharedScenario?: SharedScenarioNode;\n isClaimant?: boolean;\n asClaimReceiver?: SharedScenarioClaimReceiverNode;\n claim?: SharedTpClaimNode;\n}\n\nexport interface SharedScenarioClaimApproverNode extends Node, TimeStamped {\n receivers?: Connection<SharedScenarioReceiverNode>;\n state?: ClaimApproverState;\n approver?: TpAssemblyApproverNode;\n}\n\nexport interface SharedScenarioClaimReceiverNode extends Node, TimeStamped {\n received?: DateTime;\n assemblyKeyId?: ID;\n approvals?: Connection<SharedScenarioClaimReceivedApprovalNode>;\n}\n\nexport interface SharedScenarioClaimReceivedApprovalNode\n extends Node,\n TimeStamped {\n receiverCipher?: string;\n receiverCipherPartialAssemblyKey?: string;\n pxk?: KeyNode;\n}\n\nexport interface NotificationNode extends Node, TimeStamped {\n plainData?: JSONString;\n plainMeta?: JSONString;\n timeRead?: DateTime;\n}\n\nexport interface NotificationManagementState extends Node, TimeStamped {\n lastViewed?: DateTime;\n}\n\nexport enum LinkTypeField {\n HARD = 'HARD',\n SOFT = 'SOFT',\n REFERENCE = 'REFERENCE',\n}\n\nexport interface MessageNode extends Node, TimeStamped {\n sender?: UserNode;\n receiver?: UserNode;\n sharedKey?: KeyNode;\n senderSigPbk?: KeyNode;\n plainMessage?: string;\n plainMessageJson?: string;\n signedCipherMessage?: string;\n signedCipherMessageClearJson?: JSONObject;\n}\n\nexport interface LockField {\n created?: DateTime;\n modified?: DateTime;\n expiryTime?: DateTime;\n version?: string;\n state?: LockState;\n}\n\nexport interface ServerConfig {\n relayConnectionMaxLimit?: number;\n}\n\nexport interface AvailablePlanField {\n planName?: string;\n issuerUid?: string;\n planUid?: string;\n name?: string;\n description?: string;\n priceOptions?: PriceOptionField[];\n trial?: TrialPeriodField;\n}\n\nexport interface PriceOptionField {\n priceId?: string;\n planName?: string;\n // name: To be deprecated, replaced by billingPeriod.\n name?: string;\n billingPeriod?: BillingPeriodField;\n description?: string;\n amount?: number;\n currency?: string;\n intervalUnit?: string;\n intervalCount?: number;\n}\n\nexport enum BillingPeriodField {\n MONTHLY = 'MONTHLY',\n ANNUAL = 'ANNUAL',\n}\n\nexport interface TrialPeriodField {\n years?: number;\n months?: number;\n weeks?: number;\n days?: number;\n}\n\nexport interface PaymentCaptureField {\n stripeIntentId?: string;\n stripeClientSecret?: string;\n}\n\nexport interface PaymentMethodNode extends Node, TimeStamped {\n card?: PaymentCardField;\n invoice?: PaymentInvoiceField;\n isDefault?: boolean;\n}\n\nexport interface PaymentCardField {\n brand?: string;\n lastFourDigits?: string;\n expiryYear?: number;\n expiryMonth?: number;\n}\n\nexport interface PaymentInvoiceField {\n email?: string;\n}\n\nexport interface PromotionalCodeField {\n amountOff?: number;\n currency?: string;\n percentOff?: number;\n name?: string;\n duration?: string;\n durationInMonths?: number;\n}\n\nexport interface PeriodField {\n start?: DateTime;\n end?: DateTime;\n}\n\nexport interface IssuedPlanNode extends Node, TimeStamped {\n name?: string;\n description?: string;\n currentStates?: IssuedPlanStateNode[];\n currentPeriod?: PeriodField;\n currentPriceOption?: PriceOptionField;\n upcomingInvoice?: BillingField;\n alternativePriceOptions?: PriceOptionField[];\n scheduledPriceChanges?: PriceChangeField[];\n}\n\nexport interface IssuedPlanStateNode extends Node, TimeStamped {\n periodStart?: DateTime;\n periodEnd?: DateTime;\n state?: PlanStateField;\n}\n\nexport enum PlanStateField {\n TRIALLING = 'TRIALLING',\n ACTIVE = 'ACTIVE',\n CANCELLED = 'CANCELLED',\n EXPIRED = 'EXPIRED',\n}\n\nexport interface BillingField {\n invoiceNumber?: string;\n total?: number;\n amountDue?: number;\n currency?: string;\n documentUrl?: string;\n status?: string;\n periodStart?: DateTime;\n periodEnd?: DateTime;\n finalisedAt?: DateTime;\n paidAt?: DateTime;\n paid?: boolean;\n nextPaymentAttempt?: DateTime;\n}\n\nexport interface PriceChangeField {\n periodStart?: DateTime;\n priceOption?: PriceOptionField;\n}\n\nexport interface ReminderNode extends Node, TimeStamped {\n plain?: JSONString;\n plainJson?: JSONObject;\n firstEvent?: DateTime;\n notifyAheadSeconds?: number;\n notifyAt?: DateTime;\n directory?: DirectoryNode;\n}\n","import { AuthClass } from '@aws-amplify/auth/lib-esm/Auth';\nimport { KcConfig } from '../life-ready.config';\n\nexport function handleCognitoCallback<T>(\n method: (callback: (err?: Error, result?: T) => void) => void\n): Promise<T> {\n return new Promise<T>((resolve, reject) =>\n method((err, result) => (err ? reject(err) : resolve(result)))\n );\n}\n\nexport const awsFetch = (authUrl: string) => {\n const fetch = window.fetch;\n\n return (url, options) => {\n const pass = () => fetch(url, options);\n\n if (!options || !options.headers || !options.headers['X-Amz-Target']) {\n return pass();\n }\n\n const operation = options.headers['X-Amz-Target'].split('.');\n if (\n operation.length < 2 ||\n operation[0] !== 'AWSCognitoIdentityProviderService'\n ) {\n return pass();\n }\n\n const body = JSON.parse(options.body);\n\n if (body && body.ClientMetadata && body.ClientMetadata.noProxy === 'true') {\n return pass();\n }\n\n let custom = false;\n\n if (operation[1] === 'RespondToAuthChallenge') {\n if (body && body.ChallengeName === 'NEW_PASSWORD_REQUIRED') {\n return pass();\n }\n custom = true;\n } else if (operation[1] === 'InitiateAuth') {\n if (body.AuthFlow === 'REFRESH_TOKEN_AUTH') {\n custom = true;\n }\n }\n\n if (!custom) {\n return pass();\n }\n\n return fetch(`${authUrl}auth/proxy/`, {\n ...options,\n credentials: 'include',\n });\n };\n};\n\nexport const configureAmplifyAuth = (\n { authUrl: authUrl, userPoolId, userPoolWebClientId }: KcConfig,\n auth: AuthClass\n) => {\n return () => {\n const tokens = userPoolId.split('_');\n if (tokens.length < 2) {\n throw new Error('userPoolId should have this format: {aws-region}_xxxxx');\n }\n\n window.fetch = awsFetch(authUrl);\n\n auth.configure({\n // REQUIRED - Amazon Cognito Region\n region: tokens[0],\n // OPTIONAL - Amazon Cognito User Pool ID\n userPoolId,\n // OPTIONAL - Amazon Cognito Web Client ID (26-char alphanumeric string)\n userPoolWebClientId,\n // OPTIONAL - Enforce user authentication prior to accessing AWS resources or not\n mandatorySignIn: false,\n });\n };\n};\n","export enum Config {\n TIMEOUT = 0.01, // seconds, min value 0.01, after state is idle, wait for TIMEOUT seconds before taking action\n IDLE = 60 * 20, // seconds, period of inactivity to consider state as idle\n KEEP_ALIVE_INTERVAL = 60 * 1, // seconds, triggered on a regular basis while active (i.e. while not idling)\n}\n\nexport interface KeepaliveResult {\n session: {\n expires_after_seconds: number;\n };\n}\n","import { HttpClient } from '@angular/common/http';\nimport { Inject, Injectable } from '@angular/core';\nimport { AuthClass } from '@aws-amplify/auth/lib-esm/Auth';\nimport { DEFAULT_INTERRUPTSOURCES, Idle } from '@ng-idle/core';\nimport { Keepalive } from '@ng-idle/keepalive';\nimport { KeyService } from '../key/key.service';\nimport { Key } from '../key/key.types';\nimport { httpOptions, KcConfig, KC_CONFIG } from '../life-ready.config';\nimport {\n KcBadArgumentException,\n KcBadStateException,\n} from '../_common/exceptions';\nimport { Config, KeepaliveResult } from './idle.types';\n\n/**\n * onInit: true when onTimeout is called from the init() function. i.e. tab was closed and on reloading the webapp it already timed out.\n */\nexport type IdleServiceOnTimeout = ({\n onInit: boolean,\n}) => void | Promise<void>;\n\nexport type IdleServiceOnKeepalive = () => void | Promise<void>;\n\nexport interface IdleServiceInit {\n // Keep these as callbacks so we can ensure they are called immediately without going into the\n // event loop.\n onTimeout?: IdleServiceOnTimeout;\n onKeepalive?: IdleServiceOnKeepalive;\n idleSec?: number;\n timeoutSec?: number;\n keepAliveIntervalSec?: number;\n}\n\n@Injectable({\n providedIn: 'root',\n})\nexport class IdleService {\n private readonly IDLE_EXPIRY_KEY = 'ng2Idle.main.expiry';\n private readonly IDLING_KEY = 'ng2Idle.main.idling';\n\n private initCalled = false;\n private onTimeout: IdleServiceOnTimeout;\n private onKeepalive: IdleServiceOnKeepalive;\n\n constructor(\n @Inject(KC_CONFIG) private config: KcConfig,\n private http: HttpClient,\n private idle: Idle,\n private keepalive: Keepalive,\n private keyService: KeyService,\n private auth: AuthClass\n ) {}\n\n private assertInit(): void {\n if (!this.initCalled) {\n throw new KcBadStateException('Call IdleService.init() first.');\n }\n }\n\n public async init(params?: IdleServiceInit): Promise<void> {\n if (this.initCalled) {\n throw new KcBadStateException(\n 'IdleService.init() can only be called once. IdleService.start() calls init() with default values if init() has not been called yet.'\n );\n }\n\n this.initCalled = true;\n\n // Defaults\n params = {\n onTimeout: null,\n onKeepalive: null,\n idleSec: Config.IDLE,\n timeoutSec: Config.TIMEOUT,\n keepAliveIntervalSec: Config.KEEP_ALIVE_INTERVAL,\n ...params,\n };\n\n // If timeoutSec == 0 then the onTimeout() callback is never called.\n if (params.timeoutSec < 0.01) {\n throw new KcBadArgumentException(\n 'Minimum value for IdleService.init({ timeoutSec }) is 0.01'\n );\n }\n\n this.onTimeout = params.onTimeout;\n this.onKeepalive = params.onKeepalive;\n\n // ------------------------------------------------------------------------\n // Setup Idle\n // ------------------------------------------------------------------------\n // sets an idle timeout of 5 seconds, for testing purposes.\n this.idle.setIdle(params.idleSec);\n // sets a timeout period of 5 seconds. after 10 seconds of inactivity, the user will be considered timed out.\n this.idle.setTimeout(params.timeoutSec);\n // sets the default interrupts, in this case, things like clicks, scrolls, touches to the document\n this.idle.setInterrupts(DEFAULT_INTERRUPTSOURCES);\n\n this.idle.onIdleEnd.subscribe(() => console.log('Idle stopped'));\n this.idle.onIdleStart.subscribe(() => console.log('Idle started'));\n\n this.idle.onTimeout.subscribe(async () => {\n console.log('Idle timed out');\n this.reset();\n await Promise.resolve(\n this.onTimeout && this.onTimeout({ onInit: false })\n );\n });\n this.idle.onTimeoutWarning.subscribe((countdown) =>\n console.log(`Will timeout in ${countdown} seconds!`)\n );\n\n // ------------------------------------------------------------------------\n // Setup Keepalive\n // ------------------------------------------------------------------------\n // Ref: https://github.com/moribvndvs/ng2-idle#readme\n // ng-idle will instruct @ng-idle/keepalive to ping while the user is active, and stop once\n // they go idle or time out. When the user resumes activity or the idle state is reset, it will\n // ping immediately and then resume pinging.\n this.keepalive.interval(params.keepAliveIntervalSec);\n console.log(\n `Keep alive interval set at: ${Config.KEEP_ALIVE_INTERVAL} seconds`\n );\n\n this.keepalive.onPing.subscribe(() => this.onPing());\n\n // If the browser tab has been closed for a period longer thant the inactivity\n // period, then we should logout right from the start.\n const idleExpiry = localStorage.getItem(this.IDLE_EXPIRY_KEY);\n if (\n idleExpiry &&\n parseInt(idleExpiry, 10) + this.idle.getTimeout() * 1000 < Date.now()\n ) {\n this.reset();\n await Promise.resolve(this.onTimeout && this.onTimeout({ onInit: true }));\n }\n }\n\n public async keepalivePost(): Promise<{\n expiresAfterSeconds: number;\n keepaliveResult: KeepaliveResult;\n }> {\n const keepaliveResult = await this.http\n .post<KeepaliveResult>(\n `${this.config.authUrl}auth/keepalive/`,\n null,\n // /auth/keepalive/ will be extending the sessions cookie.\n await httpOptions(this.auth, this.config)\n )\n .toPromise();\n\n return {\n keepaliveResult,\n expiresAfterSeconds:\n this.idle.getIdle() +\n this.idle.getTimeout() +\n this.keepalive.interval(),\n };\n }\n\n public async persistMasterKey(masterKey: Key): Promise<void> {\n // The keepalive API call extends the server-side session, the session cookie expiry, refresh key cookie\n // expiry, and returns the session expiry.\n // NOTE Use time delta rather than absolute time, since client clock and server clock maybe\n // out of sync. We can't use the serverTime() functionality because the cookie expiry still\n // run on local clock.\n const { expiresAfterSeconds } = await this.keepalivePost();\n\n // Persist the derived passKey\n await this.keyService.persistMasterKey(masterKey, expiresAfterSeconds);\n }\n\n private async onPing(): Promise<void> {\n console.log(\n `Keep alive triggered at time: ${Date.now()}. Interval set at: ${this.keepalive.interval()} seconds`\n );\n\n // Keepalive API will extend the session expiry.\n const { expiresAfterSeconds } = await this.keepalivePost();\n\n // Extend the expiry of the persisted key\n await this.keyService.setMasterKeyExpiresAfterSeconds(expiresAfterSeconds);\n\n await Promise.resolve(this.onKeepalive && this.onKeepalive());\n }\n\n public async start(): Promise<void> {\n if (!this.initCalled) {\n await this.init();\n }\n\n if (this.idle.isRunning()) {\n return;\n }\n\n // Ping does not seem to happen right at the start. So we call it explicitly\n await this.onPing();\n\n this.idle.watch();\n }\n\n public stop(): void {\n this.idle.stop();\n this.reset();\n }\n\n private reset() {\n localStorage.removeItem(this.IDLE_EXPIRY_KEY);\n localStorage.removeItem(this.IDLING_KEY);\n }\n}\n","import { KeyGraphField } from '../_common/queries.gql';\nimport gql from 'graphql-tag';\n\nexport const ContactCardFields = `\nid\npublicData\npublicSearchable\ncipherData\nkey {\n id\n}\n`;\n\nexport const ContactCardQuery = gql`\nquery ContactCardQuery(\n$id: LrRelayIdInput!\n) {\ncontactCard (\n id: $id\n) {\n ${ContactCardFields}\n}\n${KeyGraphField}\n}`;\n\nexport const SearchContactCardQuery = gql`\nquery SearchContactCardQuery(\n $publicSearchable: LrJSONFilter!\n) {\n searchContactCards(\n publicSearchable: $publicSearchable\n orderBy: \"created\"\n ) {\n edges {\n node {\n ${ContactCardFields}\n }\n }\n }\n ${KeyGraphField}\n}`;\n\nexport const ContactCardListQuery = gql`\nquery ContactCardListQuery {\n contactCards(\n orderBy: \"created\"\n ) {\n edges {\n node {\n ${ContactCardFields}\n }\n }\n }\n ${KeyGraphField}\n}`;\n\nexport const CreateContactCardMutation = gql`\nmutation CreateContactCardMutation(\n $input: CreateContactCardInput!\n) {\n createContactCard(input: $input) {\n contactCard {\n ${ContactCardFields}\n }\n }\n}`;\n\nexport const UpdateContactCardMutation = gql`\nmutation UpdateContactCardMutation(\n $input: UpdateContactCardInput!\n) {\n updateContactCard(input: $input) {\n contactCard {\n ${ContactCardFields}\n }\n }\n}`;\n\nexport const DeleteContactCardMutation = gql`\n mutation DeleteContactCardMutation($input: DeleteContactCardInput!) {\n deleteContactCard(input: $input) {\n id\n }\n }\n`;\n","/* eslint-disable @typescript-eslint/no-explicit-any */\nimport { Injectable } from '@angular/core';\nimport { JWK } from 'node-jose';\nimport { LrApolloService } from '../api/lr-apollo.service';\nimport { ID } from '../api/types';\n// import { GetCategoryKeyIdQuery } from '../category/category.gql';\nimport { EncryptionService } from '../encryption/encryption.service';\nimport { gqlTyped } from '../_common/ast';\nimport { KeyFactoryService } from './key-factory.service';\nimport { KeyGraphService } from './key-graph.service';\nimport { KeyService } from './key.service';\n\nexport interface DirectoryKeyQueryResult {\n directory: {\n keyId: ID;\n };\n}\nexport const DirectoryKeyQuery = gqlTyped<DirectoryKeyQueryResult>`\nquery DirectoryKeyQuery($id: LrRelayIdInput!) {\n directory(id: $id) {\n keyId\n }\n}\n`;\n\nexport interface HasCipherMeta {\n keyId: string;\n cipherMeta: string;\n}\n\nexport class WrappedContent {\n key: JWK.Key;\n cipherMeta: string;\n wrappedKeys?: WrappingKey[];\n rootKey?: WrappingKey;\n}\n\nexport class WrappingKey {\n directoryId?: string;\n wrappingKeyId: string;\n wrappedKey: string;\n}\n\n@Injectable({\n providedIn: 'root',\n})\nexport class KeyMetaService {\n constructor(\n private encryptionService: EncryptionService,\n private keyGraph: KeyGraphService,\n private lrApollo: LrApolloService,\n private keyService: KeyService,\n private keyFactory: KeyFactoryService\n ) {}\n\n async decryptMeta<T>(metaHaver: HasCipherMeta): Promise<T> {\n if (metaHaver.cipherMeta) {\n const key = await this.keyGraph.getJwkKey(metaHaver.keyId);\n return (await this.encryptionService.decrypt(\n key,\n JSON.parse(metaHaver.cipherMeta)\n )) as any;\n }\n return null;\n }\n\n async doubleWrapContent(\n secureContent: any,\n categoryIds: string[],\n fileContent?: ArrayBuffer\n ) {\n const key = await this.keyFactory.createKey();\n\n const wrappedContent = await this.wrapContent(\n key.toJSON(true),\n categoryIds\n );\n\n return {\n rootKey: wrappedContent.rootKey,\n wrappedKeys: wrappedContent.wrappedKeys,\n doubleWrappedKey: wrappedContent.cipherMeta,\n cipherMeta: secureContent\n ? JSON.stringify(\n await this.encryptionService.encrypt(key, secureContent)\n )\n : null,\n cipherFileContent: fileContent\n ? JSON.stringify(await this.encryptionService.encrypt(key, fileContent))\n : null,\n };\n }\n\n async reWrapContent(keyId: string, secureContent: any) {\n const key = await this.keyGraph.getJwkKey(keyId);\n const newKey = await this.keyFactory.createKey();\n\n return {\n doubleWrappedKey: JSON.stringify(\n await this.encryptionService.encrypt(key, newKey.toJSON(true))\n ),\n cipherMeta: secureContent\n ? JSON.stringify(\n await this.encryptionService.encrypt(newKey, secureContent)\n )\n : null,\n };\n }\n\n async wrapContent(\n secureContent: any,\n categoryIds?: string[]\n ): Promise<WrappedContent> {\n const key = await this.keyFactory.createKey();\n\n let wrappedKeys: WrappingKey[];\n let rootWrappingKey: WrappingKey;\n\n if (categoryIds && categoryIds.length) {\n wrappedKeys = await Promise.all(\n categoryIds.map(async (categoryId) => {\n const parentKey = await this.getDirectoryKeyId(categoryId);\n const wrappedKey = JSON.stringify(\n await this.encryptionService.encrypt(\n parentKey.key,\n key.toJSON(true)\n )\n );\n return {\n directoryId: categoryId,\n wrappingKeyId: parentKey.keyId,\n wrappedKey,\n };\n })\n );\n } else {\n // Adding to root directory\n const rootKey = this.keyService.currentRootKey;\n const wrappedKey = JSON.stringify(\n await this.encryptionService.encrypt(rootKey.jwk, key.toJSON(true))\n );\n rootWrappingKey = {\n wrappingKeyId: rootKey.id,\n wrappedKey,\n };\n }\n\n return {\n key,\n rootKey: rootWrappingKey,\n wrappedKeys,\n cipherMeta: secureContent\n ? JSON.stringify(\n await this.encryptionService.encrypt(key, secureContent)\n )\n : null,\n };\n }\n\n async wrapContentWithKey(\n secureContent: any,\n keyId: string\n ): Promise<WrappedContent> {\n const key = await this.keyFactory.createKey();\n\n const wrappedKey = await this.keyGraph.encryptToString(\n keyId,\n key.toJSON(true)\n );\n\n return {\n key,\n rootKey: {\n wrappingKeyId: keyId,\n wrappedKey,\n },\n cipherMeta: secureContent\n ? JSON.stringify(\n await this.encryptionService.encrypt(key, secureContent)\n )\n : null,\n };\n }\n\n private async getDirectoryKeyId(\n categoryId: string\n ): Promise<{ keyId: string; key: any }> {\n const { directory } = await this.lrApollo.query<any>({\n query: DirectoryKeyQuery,\n variables: {\n id: categoryId,\n },\n });\n\n return {\n keyId: directory.keyId,\n key: await this.keyGraph.getJwkKey(directory.keyId),\n };\n }\n}\n","import { JWK } from 'node-jose';\nimport {\n Connection,\n DateTime,\n ID,\n JSONObject,\n JSONString,\n LrEmail,\n OtKeyCipherClearJson2,\n} from '../api/types';\nimport { gqlTyped } from '../_common/ast';\n\nexport type KeyExchangeState2 =\n | 'IN_PROGRESS'\n | 'COMPLETED'\n | 'DECLINED'\n | 'CANCELLED'\n | 'DELETED';\n\nexport interface KeyExchangeFieldsResult {\n id: ID;\n token: string;\n state: KeyExchangeState2;\n mode: 'OTK';\n isInitiator: boolean;\n initiator: {\n id: ID;\n username: string;\n config: JSONString;\n configJson: JSONObject;\n };\n responder: {\n id: ID;\n username: string;\n };\n created: DateTime;\n modified: DateTime;\n tokenExpiryTime: DateTime;\n isExpired: boolean;\n initiatorRootKeyCipher: string;\n initiatorRootKeyCipherClearJson: JSONObject;\n initiatorActionRequired: boolean;\n responderActionRequired: boolean;\n responderEmailAddress: LrEmail;\n otk: {\n state: 'OTK_INITIATED' | 'OTK_ACCEPTED' | 'OTK_COMPLETED';\n otKeyParams: string;\n otKeyCipher: string;\n otKey?: JWK.Key;\n otKeyCipherClearJson?: OtKeyCipherClearJson2;\n sharedKey: {\n id: ID;\n };\n mkSharedKey: {\n id: ID;\n };\n initiatorSigPxk: {\n id: ID;\n };\n responderSigPxk: {\n id: ID;\n };\n initiatorOneTimePbkCipher: string;\n initiatorOneTimePbkCipherClearJson: JSONObject;\n responderPbkCipher: string;\n };\n}\n\nexport const KeyExchangeFields = `\n id\n token\n state\n mode\n isInitiator\n initiator {\n id\n username\n config\n }\n responder {\n id\n username\n }\n created\n modified\n tokenExpiryTime\n isExpired\n initiatorRootKeyCipher\n initiatorActionRequired\n responderActionRequired\n responderEmailAddress\n otk {\n state\n otKeyParams\n otKeyCipher\n sharedKey {\n id\n }\n mkSharedKey {\n id\n }\n initiatorSigPxk {\n id\n }\n responderSigPxk {\n id\n }\n initiatorOneTimePbkCipher\n responderPbkCipher\n }\n`;\n\nexport interface UserSharedKeyFieldsResult {\n userSigPrk: {\n id: ID;\n };\n otherSigPbk: {\n id: ID;\n };\n sharedKey: {\n id: ID;\n };\n mkSharedKey: {\n id: ID;\n };\n mkPxk: {\n id: ID;\n pbk: JSONObject;\n };\n mkReshareRequestCipher: string;\n mkReshareResponseCipher: string;\n mkReshareRequestSent: boolean;\n mkReshareResponseSent: boolean;\n}\nexport const UserSharedKeyFields = `\n userSigPrk {\n id\n }\n otherSigPbk {\n id\n }\n sharedKey {\n id\n }\n mkSharedKey {\n id\n }\n mkPxk {\n id\n pbk\n }\n mkReshareRequestCipher\n mkReshareResponseCipher\n mkReshareRequestSent\n mkReshareResponseSent\n`;\n\nexport interface KeyExchangesQuery2 {\n keyExchanges: Connection<KeyExchangeFieldsResult>;\n}\nexport const KeyExchangesQuery2 = gqlTyped<KeyExchangesQuery2>`\nquery KeyExchangesQuery2($state: String) {\n keyExchanges(state: $state) {\n edges {\n node {\n ${KeyExchangeFields}\n }\n }\n }\n}\n`;\n\nexport interface KeyExchangeQuery2 {\n keyExchange: KeyExchangeFieldsResult;\n}\nexport const KeyExchangeQuery2 = gqlTyped<KeyExchangeQuery2>`\nquery KeyExchangeQuery2($id: LrRelayIdInput!) {\n keyExchange(id: $id) {\n ${KeyExchangeFields}\n }\n}\n`;\n\n// Key graph is only available for authenticated users. This query\n// is for unauthenticated users.\nexport interface KeyExchangeTokenQuery2 {\n keyExchange: KeyExchangeFieldsResult;\n}\nexport const KeyExchangeTokenQuery2 = gqlTyped<KeyExchangeTokenQuery2>`\nquery KeyExchangeTokenQuery2($id: LrRelayIdInput!, $token: String) {\n keyExchange(id: $id, token: $token) {\n ${KeyExchangeFields}\n }\n}\n`;\n\nexport interface CancelKeyExchangeMutation {\n cancelKeyExchange: {\n keyExchange: {\n id: ID;\n };\n };\n}\nexport const CancelKeyExchangeMutation = gqlTyped<CancelKeyExchangeMutation>`\nmutation CancelKeyExchangeMutation($input: CancelKeyExchangeInput!) {\n cancelKeyExchange(input: $input) {\n keyExchange {\n id\n }\n }\n}\n`;\n\nexport interface DeclineKeyExchangeMutation {\n declineKeyExchange: {\n keyExchange: {\n id: ID;\n };\n };\n}\nexport const DeclineKeyExchangeMutation = gqlTyped<DeclineKeyExchangeMutation>`\nmutation DeclineKeyExchangeMutation($input: DeclineKeyExchangeInput!) {\n declineKeyExchange(input: $input) {\n keyExchange {\n id\n }\n }\n}\n`;\n\nexport interface InitiateKeyExchangeOtkMutation {\n initiateKeyExchangeOtk: {\n keyExchange: KeyExchangeFieldsResult;\n };\n}\nexport const InitiateKeyExchangeOtkMutation = gqlTyped<InitiateKeyExchangeOtkMutation>`\nmutation InitiateKeyExchangeOtkMutation(\n $input: InitiateKeyExchangeOtkInput!\n) {\n initiateKeyExchangeOtk(input: $input) {\n keyExchange {\n ${KeyExchangeFields}\n }\n }\n}\n`;\n\nexport interface RespondKeyExchangeOtkMutation {\n respondKeyExchangeOtk: {\n keyExchange: KeyExchangeFieldsResult;\n userSharedKey: UserSharedKeyFieldsResult;\n tp: {\n id: ID;\n user: {\n config: unknown;\n };\n };\n };\n}\nexport const RespondKeyExchangeOtkMutation = gqlTyped<RespondKeyExchangeOtkMutation>`\nmutation RespondKeyExchangeOtkMutation($input: RespondKeyExchangeOtkInput!) {\n respondKeyExchangeOtk(input: $input) {\n keyExchange {\n ${KeyExchangeFields}\n }\n userSharedKey {\n ${UserSharedKeyFields}\n }\n tp {\n id\n user {\n config\n }\n }\n }\n}\n`;\n\nexport interface CompleteKeyExchangeOtkMutation {\n completeKeyExchangeOtk: {\n keyExchange: KeyExchangeFieldsResult;\n userSharedKey: UserSharedKeyFieldsResult;\n tp: {\n id: ID;\n user: {\n config: unknown;\n };\n };\n };\n}\nexport const CompleteKeyExchangeOtkMutation = gqlTyped<CompleteKeyExchangeOtkMutation>`\nmutation CompleteKeyExchangeOtkMutation(\n $input: CompleteKeyExchangeOtkInput!\n) {\n completeKeyExchangeOtk(input: $input) {\n keyExchange {\n ${KeyExchangeFields}\n }\n userSharedKey {\n ${UserSharedKeyFields}\n }\n tp {\n id\n user {\n config\n }\n }\n }\n}\n`;\n\nexport interface CurrentUserSharedKeyQuery2 {\n currentUserSharedKey: {\n userSharedKey: UserSharedKeyFieldsResult;\n };\n}\nexport const CurrentUserSharedKeyQuery2 = gqlTyped<CurrentUserSharedKeyQuery2>`\nquery CurrentUserSharedKeyQuery2(\n $username: String\n $userId: LrRelayIdInput\n) {\n currentUserSharedKey(\n username: $username\n userId: $userId\n ) {\n userSharedKey {\n ${UserSharedKeyFields}\n }\n }\n}\n`;\n","/* eslint-disable @typescript-eslint/no-explicit-any */\nimport { DateTime, UserDeleteNode, UserSharedKeyNode } from '../api/types';\nimport { IdKeyPair } from '../item/item.types';\nimport { PassKey } from '../key/key.types';\n\nexport enum FeatureAction {\n // Just the one for now\n ACCESS = 'access',\n}\n\nexport class Features {\n myVault: FeatureAction[];\n tpVault: FeatureAction[];\n shareVault: FeatureAction[];\n}\n\nexport class CurrentUserKey {\n passKey: PassKey;\n masterKey: { id: string };\n rootKey?: { id: string };\n pxk?: { id: string };\n sigPxk?: { id: string };\n}\n\nexport class ApiCurrentUser {\n id: string;\n username: string;\n currentUserKey: CurrentUserKey;\n userDelete: UserDeleteNode;\n features: Features;\n sessionEncryptionKey: string;\n dateJoined: DateTime;\n}\n\nexport class ApiContactCard {\n id: string;\n cipherData: string;\n key: {\n id: string;\n };\n}\n\nexport class ContactCardName {\n name: string;\n title?: string;\n firstName?: string;\n lastName?: string;\n\n constructor(input: any) {\n this.name = input.name;\n this.title = input.title;\n this.firstName = input.firstName;\n this.lastName = input.lastName;\n }\n}\n\nexport class ContactCardAddress {\n fullAddress: string;\n streetAddress: string;\n streetAddress2?: string;\n suburb: string;\n state: string;\n postcode: string;\n country: string;\n countryCode?: string;\n}\n\nexport class MainContactCardProperty<T> {\n value: T;\n hasMultiple: boolean;\n\n values?: { id: string; label: string; value: T }[];\n}\n\nexport class MainContactCardFields {\n name: MainContactCardProperty<ContactCardName>;\n email: MainContactCardProperty<string>;\n image: MainContactCardProperty<string>;\n phone: MainContactCardProperty<string>;\n address: MainContactCardProperty<ContactCardAddress>;\n}\n\nexport interface MainContactCard extends IdKeyPair {\n fields: MainContactCardFields;\n}\n\nexport class MainContactCardPlainFields {\n name: ContactCardName;\n}\n\nexport class TrustedPartyDetails {\n name: ContactCardName;\n email?: string;\n image?: string;\n phones?: { label: string; value: string }[];\n addresses?: {\n label: string;\n value: ContactCardAddress;\n }[];\n}\n\nexport class SharedTrustedPartyDetails extends TrustedPartyDetails {\n id: string;\n ownedKeyId: string;\n sharedKeyId: string;\n}\n\nexport class TPFeatures {\n sharedVault: SharedVaultFeature;\n}\n\nexport class SharedVaultFeature {\n hasAccess: boolean;\n}\n\nexport enum TrustedPartyType {\n User = 'user',\n Organisation = 'organisation',\n}\n\nexport class TrustedParty {\n id: string;\n type: TrustedPartyType;\n name: string;\n\n hasScenarios: boolean;\n hasSharedVault: boolean;\n details: TrustedPartyDetails;\n mySharedDetails: SharedTrustedPartyDetails;\n userSharedKey: UserSharedKeyNode;\n username: string;\n features: TPFeatures;\n}\n","import { Injectable } from '@angular/core';\nimport gql from 'graphql-tag';\nimport { LrApolloService } from '../api/lr-apollo.service';\nimport { JSONObject } from '../api/types';\nimport { EncryptionService } from '../encryption/encryption.service';\nimport { KeyGraphService } from '../key/key-graph.service';\nimport { KeyService } from '../key/key.service';\nimport { Key } from '../key/key.types';\nimport {\n ContactCardName,\n SharedTrustedPartyDetails,\n TrustedPartyDetails,\n} from '../profile/profile.types';\nimport { User } from '../user/user.types';\n\nexport const SharedContactCardFields = `\n id\n owner {\n id\n username\n }\n ownerKey {\n id\n }\n ownerCipherData\n receiver {\n id\n username\n }\n receiverKey {\n id\n }\n receiverCipherData\n sharedKey {\n id\n }\n sharedCipherData\n sharedCipherDataSig\n sharedCipherDataSigPxk {\n id\n }\n`;\n\nconst UpdateOwnedContactCard = gql`\nmutation UpdateOwnedContactCard(\n $input: UpdateOwnedContactCardInput!\n) {\n updateOwnedContactCard(\n input: $input\n ) {\n ownedContactCard {\n ${SharedContactCardFields}\n }\n }\n}`;\n\ninterface UpdateOwnedContactCard {\n updateOwnedContactCard: {\n ownedContactCard: SharedContactCard;\n };\n}\n\nexport interface SharedContactCard {\n id: string;\n owner: User;\n ownerKey: Key;\n ownerCipherData: string;\n receiver: User;\n receiverKey: Key;\n receiverCipherData: string;\n sharedKey: Key;\n sharedCipherData: string;\n // Decrypted\n plainOwnerCipherDataJson: JSONObject;\n plainReceiverCipherDataJson: JSONObject;\n plainSharedCipherDataJson: JSONObject;\n}\n\n@Injectable({\n providedIn: 'root',\n})\nexport class SharedContactCardService {\n constructor(\n private keyService: KeyService,\n private lrApollo: LrApolloService,\n private keyGraph: KeyGraphService,\n private encryptionService: EncryptionService\n ) {}\n\n async decryptSharedTrustedPartyDetails(\n cc: SharedContactCard\n ): Promise<SharedTrustedPartyDetails> {\n const details = await this.decryptTrustedPartyDetails(cc);\n\n return {\n id: cc.id,\n ownedKeyId: cc.ownerKey.id,\n sharedKeyId: cc.sharedKey.id,\n ...details,\n };\n }\n\n async decryptTrustedPartyDetails(\n cc: SharedContactCard\n ): Promise<TrustedPartyDetails> {\n if (cc && cc.sharedKey && cc.sharedCipherData) {\n try {\n return await this.encryptionService.decrypt(\n await this.keyGraph.getJwkKey(cc.sharedKey.id),\n cc.sharedCipherData\n );\n } catch (e) {\n console.error('Cannot decrypt trusted party details', e);\n }\n }\n return null;\n }\n\n async updateMySharedContactCard(\n id: string,\n ownedKeyId: string,\n sharedKeyId: string,\n contactCard: TrustedPartyDetails\n ): Promise<void> {\n const ownerKey = await this.keyGraph.getKey(ownedKeyId);\n const sharedKey = await this.keyGraph.getKey(sharedKeyId);\n const sigPxk = this.keyService.currentSigPxk;\n\n const sharedCipherData = await this.encryptionService.encrypt(\n sharedKey.jwk,\n contactCard\n );\n const sharedCipherDataSig = JSON.stringify(\n await this.encryptionService.sign(sigPxk.jwk, sharedCipherData)\n );\n\n const ownerPlainData = {\n name: new ContactCardName(contactCard.name),\n };\n const ownerPlainDataSig = JSON.stringify(\n await this.encryptionService.sign(sigPxk.jwk, ownerPlainData)\n );\n\n await this.lrApollo.mutate<UpdateOwnedContactCard>({\n mutation: UpdateOwnedContactCard,\n variables: {\n input: {\n id,\n ownerCipherData: '',\n ownerKeyId: ownerKey.id,\n sharedCipherDataSig,\n sharedKeyId: sharedKey.id,\n sigPxkId: sigPxk.id,\n ownerPlainDataSig,\n },\n },\n });\n }\n}\n","/* eslint-disable @typescript-eslint/no-explicit-any */\nimport gql from 'graphql-tag';\nimport { Connection, ContactCardNode, TpNode } from '../api/types';\nimport {\n KeyExchangeFields,\n UserSharedKeyFields,\n} from '../key-exchange/key-exchange.gql';\nimport { HasKeyGraph } from '../key/key.types';\nimport { SharedContactCardFields } from '../shared-contact-card/shared-contact-card.service';\nimport { gqlTyped } from '../_common/ast';\nimport { KeyGraphFragment } from '../_common/queries.gql';\nimport { HasEdges } from './../_common/types';\nimport { ApiContactCard, ApiCurrentUser } from './profile.types';\n\nexport const TrustedPartyProperties = `\n id\n user {\n id\n username\n }\n other{\n id\n username,\n features {\n shareVault\n }\n }\n sharedContactCard {\n ${SharedContactCardFields}\n }\n myContactCard {\n ${SharedContactCardFields}\n }\n sharedScenarios {\n edges {\n node {\n id\n }\n }\n }\n theirItems {\n directories {\n edges {\n node {\n id\n }\n }\n }\n }\n currentUserSharedKey {\n userSharedKey {\n keyExchange {\n ${KeyExchangeFields}\n }\n ${UserSharedKeyFields}\n }\n }`;\n\nexport interface CurrentUserQueryType extends HasKeyGraph {\n currentUser: ApiCurrentUser;\n contactCards: HasEdges<ApiContactCard>;\n userPlans: any[];\n}\n\nexport const CurrentUserQuery = gql`\n query {\n currentUser {\n id\n username\n currentUserKey {\n passKey {\n id\n passKeyParams\n passIdpParams\n wrappedPassIdpVerifierPrk\n created\n }\n masterKey {\n id\n }\n rootKey {\n id\n }\n pxk {\n id\n }\n sigPxk {\n id\n }\n }\n userDelete {\n id\n created\n state\n }\n features {\n myVault\n tpVault\n shareVault\n }\n sessionEncryptionKey\n dateJoined\n }\n userPlans {\n id\n stripe {\n subscriptionId\n }\n plan {\n name\n data\n state\n }\n periodEnd\n }\n contactCards(orderBy: \"created\") {\n edges {\n node {\n id\n key {\n id\n }\n cipherData\n plainData\n }\n }\n }\n keyGraph {\n ...KeyGraphFragment\n }\n }\n ${KeyGraphFragment}\n`;\n\nexport const CreateContactCardMutation = gql`\n mutation CreateContactCardMutation($input: CreateContactCardInput!) {\n createContactCard(input: $input) {\n contactCard {\n id\n key {\n id\n }\n cipherData\n }\n }\n }\n`;\n\nexport const UpdateContactCardMutation = gql`\n mutation UpdateContactCardMutation($input: UpdateContactCardInput!) {\n updateContactCard(input: $input) {\n contactCard {\n id\n key {\n id\n }\n cipherData\n }\n }\n }\n`;\n\nexport interface TrustedPartiesQueryResult {\n tps: Connection<TpNode>;\n}\nexport const TrustedPartiesQuery = gqlTyped<TrustedPartiesQueryResult>`\nquery TrustedPartiesQuery {\n tps {\n edges {\n node {\n ${TrustedPartyProperties}\n }\n }\n }\n}`;\n\nexport interface ContactCardsQueryResult {\n contactCards: Connection<ContactCardNode>;\n}\nexport const ContactCardsQuery = gqlTyped<ContactCardsQueryResult>`\nquery ContactCardsQuery {\n contactCards(orderBy: \"created\") {\n edges {\n node {\n id\n cipherData\n key {\n id\n }\n }\n }\n }\n}\n`;\n","/* eslint-disable @typescript-eslint/no-explicit-any */\nimport { HttpClient } from '@angular/common/http';\nimport { Inject, Injectable } from '@angular/core';\nimport { LrApolloService } from '../api/lr-apollo.service';\nimport {\n ContactCardListQuery,\n DeleteContactCardMutation,\n} from '../contact-card/contact-card.gql';\nimport { ContactCard } from '../contact-card/contact-card.service';\nimport { EncryptionService } from '../encryption/encryption.service';\nimport { KeyGraphService } from '../key/key-graph.service';\nimport { KeyMetaService } from '../key/key-meta.service';\nimport { KeyService } from '../key/key.service';\nimport { KcConfig, KC_CONFIG } from '../life-ready.config';\nimport {\n CreateContactCardMutation,\n CurrentUserQuery,\n CurrentUserQueryType,\n UpdateContactCardMutation,\n} from './profile.gql';\nimport {\n ApiContactCard,\n ApiCurrentUser,\n ContactCardName,\n MainContactCard,\n MainContactCardFields,\n MainContactCardPlainFields,\n} from './profile.types';\n\n@Injectable({\n providedIn: 'root',\n})\nexport class ProfileService {\n constructor(\n @Inject(KC_CONFIG) private config: KcConfig,\n private http: HttpClient,\n private lrApollo: LrApolloService,\n private keyService: KeyService,\n private keyMetaService: KeyMetaService,\n private keyGraph: KeyGraphService,\n private encryptionService: EncryptionService\n ) {}\n\n async getCurrentUser(): Promise<{\n currentUser: ApiCurrentUser;\n contactCard: ApiContactCard;\n }> {\n const { currentUser, contactCards } =\n await this.lrApollo.query<CurrentUserQueryType>({\n query: CurrentUserQuery,\n });\n\n const contactCard = contactCards.edges.map((x) => x.node)[0];\n\n return {\n currentUser,\n contactCard,\n };\n }\n\n async decryptContactCard(\n contactCard: ApiContactCard\n ): Promise<MainContactCard> {\n if (!contactCard) {\n return null;\n }\n\n const details = await this.keyGraph.decryptFromString<any>(\n contactCard.key.id,\n contactCard.cipherData\n );\n\n return {\n id: contactCard.id,\n keyId: contactCard.key.id,\n ...details,\n };\n }\n\n async updateDetails(\n id: string,\n keyId: string,\n fields: MainContactCardFields\n ): Promise<MainContactCard> {\n const res = await (id\n ? this.updateContactCard(id, keyId, fields)\n : this.createContactCard(fields));\n\n return {\n fields,\n id: res.id,\n keyId: res.key.id,\n };\n }\n\n private async prepareContactCardInput(\n contactCard: MainContactCardFields\n ): Promise<any> {\n const sigPxk = this.keyService.currentSigPxk;\n\n const publicDataSig = JSON.stringify(\n await this.encryptionService.sign(sigPxk.jwk, '')\n );\n const publicSearchableSig = JSON.stringify(\n await this.encryptionService.sign(sigPxk.jwk, '')\n );\n\n const plainDataJson: MainContactCardPlainFields = {\n // contactCard.name.value may have additional attributes such as the id of the contact card.\n // So we create a clean version. Otherwise it will fail server checks.\n name: new ContactCardName(contactCard.name.value),\n };\n const plainDataSig = JSON.stringify(\n await this.encryptionService.sign(sigPxk.jwk, plainDataJson)\n );\n\n return {\n sigPxkId: sigPxk.id,\n publicDataSig,\n publicSearchableSig,\n plainDataSig,\n };\n }\n\n private async createContactCard(\n contactCard: MainContactCardFields\n ): Promise<ApiContactCard> {\n const input = await this.prepareContactCardInput(contactCard);\n\n const { rootKey, cipherMeta } = await this.keyMetaService.wrapContent(\n contactCard\n );\n\n const data = await this.lrApollo.mutate<{\n createContactCard: { contactCard: ApiContactCard };\n }>({\n mutation: CreateContactCardMutation,\n variables: {\n input: {\n ...input,\n cipherData: cipherMeta,\n wrappingKeyId: rootKey.wrappingKeyId,\n wrappedKey: rootKey.wrappedKey,\n default: true, // Use this contact card as default contact card.\n },\n },\n });\n return data.createContactCard.contactCard;\n }\n\n private async updateContactCard(\n id: string,\n keyId: string,\n contactCard: MainContactCardFields\n ): Promise<ApiContactCard> {\n const input = await this.prepareContactCardInput(contactCard);\n\n const cipherData = await this.keyGraph.encryptToString(keyId, contactCard);\n\n const data = await this.lrApollo.mutate<{\n updateContactCard: { contactCard: ApiContactCard };\n }>({\n mutation: UpdateContactCardMutation,\n variables: {\n input: {\n ...input,\n id,\n cipherData,\n },\n },\n });\n return data.updateContactCard.contactCard;\n }\n\n async decryptContactCardEdges(edges): Promise<ContactCard[]> {\n return Promise.all(\n edges.map(async (edge: any) => {\n const cc = edge.node as ContactCard;\n return await this.decryptContactCard(cc);\n })\n );\n }\n\n async getContactCards(): Promise<ContactCard[]> {\n const data = await this.lrApollo.query<any>({\n query: ContactCardListQuery,\n });\n\n return await this.decryptContactCardEdges(data.contactCards.edges);\n }\n\n async deleteContactCard(id: string): Promise<string> {\n const data = await this.lrApollo.mutate<any>({\n mutation: DeleteContactCardMutation,\n variables: {\n input: {\n id,\n },\n },\n });\n\n return data.deleteContactCard.id;\n }\n\n async signOut(): Promise<void> {\n await this.http\n .post(`${this.config.authUrl}auth/sign-out/`, null, {\n withCredentials: true,\n responseType: 'text',\n })\n .toPromise();\n }\n}\n","import gql from 'graphql-tag';\n\nexport const PasswordChangeRequestMutation = gql`\n mutation {\n passwordChangeRequest(input: {}) {\n challenge\n }\n }\n`;\n\nexport const PasswordChangeMutation = gql`\n mutation PasswordChange($input: PasswordChangeInput!) {\n passwordChange(input: $input) {\n token\n newPassKey {\n id\n }\n }\n }\n`;\n\nexport const PasswordChangeConfigQuery = gql`\n query PasswordChangeConfigQuery {\n passwordChangeConfig {\n maxAuthAgeSeconds\n authTime\n serverTime\n }\n }\n`;\n","import { HttpClient } from '@angular/common/http';\nimport { Inject, Injectable } from '@angular/core';\nimport { CognitoUser } from '@aws-amplify/auth';\nimport { AuthClass } from '@aws-amplify/auth/lib-esm/Auth';\nimport * as moment_ from 'moment';\nimport { Duration } from 'moment';\nimport { JWK, JWS } from 'node-jose';\nimport { JSONObject } from '../api/types';\nimport { PassKeyBundle } from '../auth/auth.types';\nimport { EncryptionService } from '../encryption/encryption.service';\nimport { KeyFactoryService as KFS } from '../key/key-factory.service';\nimport { KeyGraphService } from '../key/key-graph.service';\nimport { httpOptions, KcConfig, KC_CONFIG } from '../life-ready.config';\nimport { ProfileService } from '../profile/profile.service';\nimport { ApiCurrentUser } from '../profile/profile.types';\nimport { WebCryptoService } from '../web-crypto/web-crypto.service';\nimport { KcAuthException } from '../_common/exceptions';\nimport { LrApolloService } from './../api/lr-apollo.service';\nimport {\n PasswordChangeConfigQuery,\n PasswordChangeMutation,\n PasswordChangeRequestMutation,\n} from './password.gql';\n\n// Ref: https://stackoverflow.com/questions/59735280/angular-8-moment-error-cannot-call-a-namespace-moment\nconst moment = moment_;\n\ninterface PasswordChangeRequestMutation {\n passwordChangeRequest: {\n challenge: {\n serverNonce: string;\n };\n };\n}\n\ninterface PasswordChangeMutation {\n passwordChange: {\n token: string;\n newPassKey: {\n id: string;\n };\n };\n}\n\nexport interface PasswordChangeConfig {\n maxAuthAgeSeconds: number;\n authTime: string | Date;\n serverTime: string | Date;\n}\n\nexport class PasswordCheck {\n length?: number;\n timeToCrack?: Duration;\n passwordExposed?: number;\n}\n\n@Injectable({\n providedIn: 'root',\n})\nexport class PasswordService {\n private readonly CLIENT_NONCE_LENGTH = 32;\n\n constructor(\n @Inject(KC_CONFIG) private config: KcConfig,\n private http: HttpClient,\n private apollo: LrApolloService,\n private auth: AuthClass,\n private profileService: ProfileService,\n private keyFactory: KFS,\n private encryptionService: EncryptionService,\n private keyGraph: KeyGraphService,\n private webCryptoService: WebCryptoService\n ) {}\n\n public async checkPassword(plainPassword: string): Promise<PasswordCheck> {\n const { years } = this.passwordStrength(plainPassword);\n\n return {\n length: plainPassword.length,\n timeToCrack: moment.duration({ years }),\n passwordExposed: await this.getExposureCount(plainPassword),\n };\n }\n\n public async getExposureCount(plainPassword: string): Promise<number> {\n const sha1Password = await this.webCryptoService.stringDigest(\n 'SHA-1',\n plainPassword\n );\n const first5sha1 = sha1Password.substring(0, 5);\n\n const response = await this.http\n .get(`https://api.pwnedpasswords.com/range/${first5sha1}`, {\n responseType: 'text',\n })\n .toPromise();\n\n const results = new RegExp(\n `^(?:${sha1Password.substring(5)}:)(?<count>\\\\d+)$`,\n 'im'\n ).exec(response);\n\n if (results) {\n return +results.groups.count;\n }\n return 0;\n }\n\n public getPassIdpString(passIdp: JWK.Key) {\n return (passIdp.toJSON(true) as JSONObject).k;\n }\n\n public async createPassKeyBundle(\n password: CryptoKey\n ): Promise<PassKeyBundle> {\n const passIdpParams = await this.keyFactory.createPassIdpParams();\n const passIdp = (\n await this.keyFactory.derivePassIdp({\n password,\n ...passIdpParams,\n })\n ).jwk;\n\n const passKeyParams = await this.keyFactory.createPassKeyParams();\n const passKey = (\n await this.keyFactory.derivePassKey({\n password,\n ...passKeyParams,\n })\n ).jwk;\n\n const passIdpVerifier = await this.keyFactory.createPkcSignKey();\n\n const wrappedPassIdpVerifierPrk = await this.encryptionService.encrypt(\n passKey,\n passIdpVerifier.toJSON(true)\n );\n\n // There are two formats that the private key can be represented in JWK:\n // https://tools.ietf.org/html/rfc8017#page-9\n // The second form is an optimization:\n // https://crypto.stackexchange.com/questions/19413/what-are-dp-and-dq-in-encryption-by-rsa-in-c\n\n return {\n passKeyParams,\n passKey,\n passIdpParams,\n passIdp,\n passIdpVerifier,\n wrappedPassIdpVerifierPrk,\n };\n }\n\n /**\n * We need to allow for interruption of the process at any point. Each API call can be considered\n * atomic and either succeeds or fails.\n *\n * The LR server APIs use semaphore tokens for locking critical operations, so concurrent calls will\n * fail.\n *\n * We assume the worst case for IdP API calls. So we use the semaphore token from LR to prevent\n * concurrent calls to IdP APIs, but we have to assume that the IdP API calls will either succeed or\n * fail within a reasonable amount of time.\n *\n * Each location where the server state changes can be a potential point of interruption.\n * Potential points of interruption are marked with: --Potential Failure Point--\n *\n * Places for timeout:\n * - Login age too old at call to: verifyPassword()\n * - Login age too old at call to: changePasswordMutation()\n * - Semaphore token expires at call to: changePasswordComplete()\n *\n * Tests:\n * - Potential Failure Point 1: should be able to restart the process, user remains signed in.\n * - Potential Failure Point 2: should enter recovery flow\n * - Potential Failure Point 3: should enter recovery flow\n * - Potential Failure Point 4: should enter recovery flow\n *\n */\n\n public async isLoginRequired(): Promise<boolean> {\n const changePasswordConfig = await this.getChangePasswordConfig();\n const authTime = moment(changePasswordConfig.authTime);\n const serverTime = moment(changePasswordConfig.serverTime);\n const duration = moment.duration(serverTime.diff(authTime));\n const seconds = duration.asSeconds();\n if (seconds > changePasswordConfig.maxAuthAgeSeconds) {\n return true;\n } else {\n return false;\n }\n }\n\n public async changePassword(password: CryptoKey, newPassword: CryptoKey) {\n const cognitoUser: CognitoUser = await this.auth.currentAuthenticatedUser();\n\n // Not checking that passwords are different. It makes it easier to test.\n const { currentUser } = await this.profileService.getCurrentUser();\n\n const { passIdp, signedChallenge } = await this.verifyPassword(\n password,\n currentUser\n );\n\n // --Potential Failure Point 1--\n // verifyPassword() asks for a current password challenge hence changes server state.\n // Place break points here to test the failure scenarios.\n\n // Generate the new passIdp\n const newPassKey = await this.createPassKeyBundle(newPassword);\n\n // Re-encrypt master key with new key\n const masterKey = await this.keyGraph.getKey(\n currentUser.currentUserKey.masterKey.id\n );\n const newWrappedMasterKey = await this.encryptionService.encrypt(\n newPassKey.passKey,\n masterKey.jwk.toJSON(true)\n );\n\n // If the IdP change password failed, we need to go into recovery mode by forcing\n // a login. We can't logout the user just yet since the IdP password change needs\n // the user to be logged in. We _can_ removed any persisted session values for the IdP\n // but that seems like too much trouble.\n\n const { token } = await this.changePasswordMutation(\n signedChallenge,\n currentUser.currentUserKey.masterKey.id,\n newWrappedMasterKey,\n newPassKey\n );\n\n // --Potential Failure Point 2--\n // changePasswordMutation() uploads new keys and obtains a semaphore lock to prevent any other\n // clients from performing IdP password change.\n\n // Now we can do the IdP password change.\n // todo: Add this back in\n await this.auth.changePassword(\n cognitoUser,\n this.getPassIdpString(passIdp),\n this.getPassIdpString(newPassKey.passIdp)\n );\n\n // --Potential Failure Point 3--\n // IdP password change\n\n // Note that changePassword() could throw an exception for a number of reason. It could throw\n // a network timeout for example. But we don't know if it's the response that timed out and\n // the idp password change was actually carried out. So we have to be extra conservative and\n // only act on a clear success. Otherwise we go into recover mode.\n await this.changePasswordComplete({ useNewPassword: true, token });\n }\n\n public async changePasswordComplete(options: {\n useNewPassword: boolean;\n token?: string;\n }) {\n const { useNewPassword, token } = options;\n return this.http\n .post(\n `${this.config.authUrl}users/password-change-complete/`,\n {\n use_new_password: useNewPassword,\n ...(token && { token }),\n },\n await httpOptions(this.auth, this.config)\n )\n .toPromise();\n }\n\n private async getVerifierPrK(\n passKey: JWK.Key,\n wrappedPrK: Record<string, JSONObject>\n ): Promise<JWK.Key> {\n try {\n const prkJson = await this.encryptionService.decrypt(passKey, wrappedPrK);\n return KFS.asKey(prkJson);\n } catch (error) {\n throw new KcAuthException('Wrong current password');\n }\n }\n\n private async verifyPassword(\n password: CryptoKey,\n currentUser: ApiCurrentUser\n ): Promise<{ passIdp: JWK.Key; signedChallenge: JWS.CreateSignResult }> {\n // Get information from the server to prepare for password change.\n const passwordRequest =\n await this.apollo.mutate<PasswordChangeRequestMutation>({\n mutation: PasswordChangeRequestMutation,\n variables: {},\n });\n\n // Get the old passKey so we can decrypt the old password verifier\n const passKeyResult = await this.keyFactory.derivePassKey({\n password,\n ...currentUser.currentUserKey.passKey.passKeyParams,\n });\n\n const verifierPrK = await this.getVerifierPrK(\n passKeyResult.jwk,\n currentUser.currentUserKey.passKey.wrappedPassIdpVerifierPrk\n );\n\n // Sign the server challenge to prove to the server we can decrypt the password verifier.\n // Generate\n const clientNonce = this.keyFactory.randomString(this.CLIENT_NONCE_LENGTH);\n\n const signedChallenge = await this.encryptionService.sign(verifierPrK, {\n serverNonce: passwordRequest.passwordChangeRequest.challenge.serverNonce,\n clientNonce,\n });\n\n const passIdpResult = await this.keyFactory.derivePassIdp({\n password,\n ...currentUser.currentUserKey.passKey.passIdpParams,\n });\n\n return {\n passIdp: passIdpResult.jwk,\n signedChallenge,\n };\n }\n\n private async changePasswordMutation(\n signedChallenge: JWS.CreateSignResult,\n masterKeyId: string,\n newWrappedMasterKey: Record<string, JSONObject>,\n passKeyBundle: PassKeyBundle\n ): Promise<{ token: string; newPassKeyId: string }> {\n const response = await this.apollo.mutate<PasswordChangeMutation>({\n mutation: PasswordChangeMutation,\n variables: {\n input: {\n signedChallenge: JSON.stringify(signedChallenge),\n masterKeyId,\n newWrappedMasterKey: JSON.stringify(newWrappedMasterKey),\n newPassKey: {\n passIdpParams: JSON.stringify(passKeyBundle.passIdpParams),\n passIdpVerifierPbk: JSON.stringify(\n passKeyBundle.passIdpVerifier.toJSON()\n ),\n wrappedPassIdpVerifierPrk: JSON.stringify(\n passKeyBundle.wrappedPassIdpVerifierPrk\n ),\n passKeyParams: JSON.stringify(passKeyBundle.passKeyParams),\n },\n },\n },\n });\n return {\n token: response.passwordChange.token,\n newPassKeyId: response.passwordChange.newPassKey.id,\n };\n }\n\n async getChangePasswordConfig(): Promise<PasswordChangeConfig> {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const res = await this.apollo.query<any>({\n query: PasswordChangeConfigQuery,\n });\n\n const ret = res.passwordChangeConfig as PasswordChangeConfig;\n\n ret.authTime = new Date(ret.authTime);\n ret.serverTime = new Date(ret.serverTime);\n return ret;\n }\n\n public passwordStrength(password): { years: number; bits: number } {\n const upper = /[A-Z]/g;\n const lower = /[a-z]/g;\n const digit = /[0-9]/g;\n\n const upperChoices = 26;\n const lowerChoices = 26;\n const digitChoices = 10;\n const specialChoices = 30; // /[!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~]/g\n\n function instanceCount(str, re) {\n return ((str || '').match(re) || []).length;\n }\n\n const uppers = instanceCount(password, upper);\n const lowers = instanceCount(password, lower);\n const digits = instanceCount(password, digit);\n const specials = password.length - uppers - lowers - digits;\n\n let choices = 0;\n if (uppers) {\n choices += upperChoices;\n }\n if (lowers) {\n choices += lowerChoices;\n }\n if (digits) {\n choices += digitChoices;\n }\n if (specials) {\n choices += specialChoices;\n }\n\n if (password.length === 0) {\n return {\n years: 0,\n // bits of entropy\n bits: 0,\n };\n }\n\n const permutations = Math.pow(choices, password.length);\n\n const years =\n (54000 * permutations) /\n Math.pow(upperChoices + lowerChoices + digitChoices, 12);\n return {\n years,\n // bits of entropy\n bits: Math.round(Math.log2(permutations)),\n };\n }\n}\n","export const TP_PASSWORD_RESET_CLIENT_NONCE_LENGTH = 32;\nexport const TP_PASSWORD_RESET_SLIP39_PASSPHRASE = 'lifeready';\nexport const TP_PASSWORD_RESET_USERNAME_SUFFIX = '.tp_password_reset';\n","import { Injectable } from '@angular/core';\nimport { Slip39, Slip39Helper } from 'slip39';\n\nexport class SecretShare {\n constructor(\n public assembly: number = 0,\n public subAssembly: number = 0,\n public mnemonics: string = ''\n ) {}\n}\n\nexport class SubAssembly {\n constructor(\n public index: number,\n public threshold: number = 0,\n public size: number = 0\n ) {\n this.clearShares();\n }\n\n shares: SecretShare[];\n\n public clearShares() {\n this.shares = [];\n }\n\n public addShare(share: SecretShare) {\n this.shares.push(share);\n }\n}\n\nexport class Assembly {\n constructor(public threshold: number = 0) {\n this.clearSubAssemblies();\n }\n\n subAssemblies: SubAssembly[];\n\n public size() {\n return this.subAssemblies.length;\n }\n\n public clearSubAssemblies() {\n this.subAssemblies = [];\n }\n\n public addSubAssembly(subAssembly: SubAssembly) {\n this.subAssemblies.push(subAssembly);\n }\n}\n\nexport class SubQuorum {\n shares: string[];\n\n constructor(public subAssemblyIndex: number) {\n this.clearShares();\n }\n\n public clearShares() {\n this.shares = [];\n }\n\n public addShare(share: string) {\n this.shares.push(share);\n }\n}\n\nexport class Quorum {\n subQuora: SubQuorum[];\n\n constructor() {\n this.clearSubQuora();\n }\n\n public clearSubQuora() {\n this.subQuora = [];\n }\n\n public addSubQuorum(subQuorum: SubQuorum) {\n this.subQuora.push(subQuorum);\n }\n\n public serialiseShares() {\n let shares = [];\n\n this.subQuora.forEach((subQuorum) => {\n shares = shares.concat(subQuorum.shares);\n });\n\n return shares;\n }\n}\n\n@Injectable({\n providedIn: 'root',\n})\nexport class Slip39Service {\n public async generateShares(secret, passphrase: string, assembly: Assembly) {\n // Hex-encode secret.\n let ems = btoa(secret);\n ems = Slip39Helper.slip39EncodeHex(ems);\n\n // Construct group specifications\n const groups = [];\n\n for (const sa of assembly.subAssemblies) {\n groups.push([sa.threshold, sa.size]);\n }\n\n // Split!\n const slip = await Slip39.fromArray(ems, {\n passphrase,\n threshold: assembly.threshold,\n groups,\n title: '',\n });\n\n // Extract shares\n assembly.subAssemblies.forEach((sa, isa) => {\n // Remove any existing shares\n sa.clearShares();\n\n for (let im = 0; im < sa.size; im++) {\n // Construct the path to the share, formatted as \"r/<subassembly index>/<member index>\"\n // with <subassembly index> and <member index> being two-digit, zero-padded integers.\n const path =\n 'r/' +\n isa.toString().padStart(2, '0') +\n '/' +\n im.toString().padStart(2, '0');\n const mnemonics = slip.fromPath(path).mnemonics[0];\n const share = new SecretShare(isa, im, mnemonics);\n\n sa.addShare(share);\n }\n });\n }\n\n // Remove all redundant shares. i.e. keep only enough members and groups to satisfy the thresholds.\n private minimalSet(mnemonics: string[]): string[] {\n // Decode the mnemonics and sort then into groups.\n let groupThresh = null;\n const groups = new Map();\n for (const mnemonic of mnemonics) {\n const decoded = Slip39Helper.decodeMnemonic(mnemonic);\n\n if (groupThresh && groupThresh !== decoded.groupThreshold) {\n throw new Error('groupThreshold is different in mnemonics');\n }\n\n groupThresh = decoded.groupThreshold;\n\n // Note that Slip39.recoverSecret() will do all the error checking again. So it's not critical\n // that we error check here. So we just optimistically assume it's all good.\n let g = groups.get(decoded.groupIndex);\n if (g == null) {\n g = {\n memberThreshold: decoded.memberThreshold,\n members: [],\n };\n groups.set(decoded.groupIndex, g);\n }\n\n g.members.push({\n mnemonic,\n decoded,\n });\n }\n\n // Keep the minimum set of groups that meet threshold.\n const mnemonicsMinSet = [];\n let groupCount = 0;\n for (const g of groups.values()) {\n // Keep only groups that meet threshold\n if (g.members.length < g.memberThreshold) {\n continue;\n }\n\n // Keep minimum number of approvals needed for group\n g.members.slice(0, g.memberThreshold).forEach((member) => {\n mnemonicsMinSet.push(member.mnemonic);\n });\n\n ++groupCount;\n if (groupCount >= groupThresh) {\n break;\n }\n }\n\n return mnemonicsMinSet;\n }\n\n public async recoverSecret(shares: string[], passphrase: string) {\n shares = this.minimalSet(shares);\n\n const recovered = await Slip39.recoverSecret(shares, passphrase);\n\n const secret = Slip39Helper.slip39DecodeHex(recovered);\n\n return atob(secret);\n }\n}\n","import { Connection, TpNode } from '../api/types';\nimport { gqlTyped } from '../_common/ast';\n\nexport interface TpsKeysQueryResult {\n tps: Connection<TpNode>;\n}\nexport const TpsKeysQuery = gqlTyped<TpsKeysQueryResult>`\nquery TpsKeysQuery($ids: [ID]) {\n tps(id_In: $ids) {\n edges {\n node {\n id\n currentUserSharedKey {\n userSharedKey {\n sharedKey {\n id\n }\n mkSharedKey {\n id\n }\n }\n }\n }\n }\n }\n}`;\n","import { Injector } from '@angular/core';\nimport { JWK } from 'node-jose';\nimport { LrGraphQLService } from '../api/lr-graphql';\nimport {\n Connection,\n JSONObject,\n mapEdges,\n TpAssemblyNode,\n TpNode,\n TpSubAssemblyNode,\n} from '../api/types';\nimport { EncryptionService } from '../encryption/encryption.service';\nimport { KeyFactoryService } from '../key/key-factory.service';\nimport { KeyGraphService } from '../key/key-graph.service';\nimport { KeyService } from '../key/key.service';\nimport { Key } from '../key/key.types';\nimport * as slip from '../slip39/slip39.service';\nimport {\n KcBadArgumentException,\n KcBadStateException,\n} from '../_common/exceptions';\nimport { TpsKeysQuery } from './tp-assembly.private.gql';\nimport {\n CreateTpAssemblyInput,\n CreateTpSubAssemblyInput,\n PartialAssemblyKey,\n TpAssemblyApproverInput,\n UpdateTpAssemblyInput,\n UpdateTpSubAssemblyInput,\n} from './tp-assembly.types';\n\nexport abstract class TpAssemblyController {\n abstract slip39Passphrase: string;\n\n protected keyFactory: KeyFactoryService;\n protected keyService: KeyService;\n protected encryptionService: EncryptionService;\n protected keyGraph: KeyGraphService;\n protected slip39Service: slip.Slip39Service;\n protected lrGraphQl: LrGraphQLService;\n\n constructor(injector: Injector) {\n this.keyFactory = injector.get(KeyFactoryService);\n this.keyService = injector.get(KeyService);\n this.encryptionService = injector.get(EncryptionService);\n this.keyGraph = injector.get(KeyGraphService);\n this.slip39Service = injector.get(slip.Slip39Service);\n this.lrGraphQl = injector.get(LrGraphQLService);\n }\n\n abstract getTpWrappingKeyId(tp: TpNode): string;\n\n async recoverAssemblyKey(partials: PartialAssemblyKey[]) {\n // Every receiverPbkCipher should contain this and they should all be the same.\n let assemblyKeyParams: Record<string, JSONObject>;\n\n const shares = partials.map((partial) => {\n if (assemblyKeyParams) {\n if (\n JSON.stringify(assemblyKeyParams) !==\n JSON.stringify(partial.assemblyKeyParams)\n ) {\n throw new KcBadStateException(\n 'The assembly key parameters are different between the approvals.'\n );\n }\n } else {\n assemblyKeyParams = partial.assemblyKeyParams;\n }\n return partial.slip39.share.mnemonics;\n });\n\n const rawAssemblyKey = await this.slip39Service.recoverSecret(\n shares,\n this.slip39Passphrase\n );\n\n return await KeyFactoryService.asKey({\n ...assemblyKeyParams,\n k: rawAssemblyKey,\n });\n }\n\n protected async prepareTpWrappingKey(\n tp: TpAssemblyApproverInput\n ): Promise<Key> {\n return this.keyGraph.getKey(tp.wrappingKeyId);\n }\n\n protected async prepareAssembly({\n subjectKey,\n rootKey,\n }: {\n subjectKey: JWK.Key;\n rootKey: JWK.Key;\n }) {\n const assemblyKey = await this.keyFactory.createKey();\n\n const { k: rawAssemblyKey, ...assemblyKeyParams } = assemblyKey.toJSON(\n true\n ) as JSONObject;\n const assemblyKeyVerifierPrk = await this.keyFactory.createPkcSignKey();\n const wrappedAssemblyKeyVerifierPrk =\n await this.encryptionService.encryptToString(\n assemblyKey,\n assemblyKeyVerifierPrk.toJSON(true)\n );\n const assemblyKeyVerifierPbk = JSON.stringify(\n assemblyKeyVerifierPrk.toJSON()\n );\n\n const subjectKeyWrappedAssemblyKey =\n await this.encryptionService.encryptToString(\n subjectKey,\n assemblyKey.toJSON(true)\n );\n\n // Encrypt the rootKey with the assemblyKey\n const assemblyCipherData = await this.encryptionService.encryptToString(\n assemblyKey,\n {\n rootKey: rootKey.toJSON(true),\n }\n );\n\n return {\n assemblyKey,\n rawAssemblyKey,\n assemblyKeyParams,\n subjectKeyWrappedAssemblyKey,\n assemblyCipherData,\n assemblyKeyVerifierPbk,\n wrappedAssemblyKeyVerifierPrk,\n };\n }\n\n protected async prepareCreateSubAssemblies({\n input,\n subjectKey,\n slipSubAssemblies,\n assemblyKeyParams,\n }: {\n input: CreateTpSubAssemblyInput[];\n subjectKey: JWK.Key;\n slipSubAssemblies: slip.SubAssembly[];\n assemblyKeyParams; // TODO type this\n }) {\n return Promise.all(\n input.map(async (sa, saIndex) => {\n const subjectCipherData = await this.encryptionService.encryptToString(\n subjectKey,\n sa.subjectCipherDataClearJson || ''\n );\n\n const createApprovers = await Promise.all(\n sa.approverTps.map(async (approverTp, approverIndex) =>\n this.prepareApprover({\n tp: approverTp,\n approverIndex,\n slipSubAssembly: slipSubAssemblies[saIndex],\n assemblyKeyParams,\n subjectKey,\n })\n )\n );\n\n return {\n singleReject: sa.singleReject,\n quorum: sa.quorum,\n subjectCipherData,\n createApprovers,\n };\n })\n );\n }\n\n protected async prepareUpdateSubAssemblies({\n input,\n subjectKey,\n slipSubAssemblies,\n assemblyKeyParams,\n subAssemblies,\n }: {\n input: UpdateTpSubAssemblyInput[];\n subjectKey: JWK.Key;\n slipSubAssemblies: slip.SubAssembly[];\n assemblyKeyParams; // TODO type this\n subAssemblies: Connection<TpSubAssemblyNode>;\n }) {\n if (slipSubAssemblies.length !== input.length) {\n throw new KcBadArgumentException(\n 'The slipSubAssemblies must be the same length as the input'\n );\n }\n\n return Promise.all(\n input.map(async (sa, saIndex) => {\n const subjectCipherData = await this.encryptionService.encryptToString(\n subjectKey,\n sa.subjectCipherDataClearJson || ''\n );\n\n // Get the existing sub-assembly\n const existingSa = subAssemblies.edges.find(\n (edge) => edge.node.id === sa.id\n ).node;\n\n // Get approvers that do not exist yet\n const createApprovers = [];\n const updateApprovers = [];\n\n sa.approverTps.forEach((tp) => {\n const approver = existingSa.approvers.edges.find(\n (edge) => edge.node.tp.id === tp.tpId\n )?.node;\n if (approver) {\n updateApprovers.push({\n tp,\n approverId: approver.id,\n });\n } else {\n createApprovers.push({\n tp,\n });\n }\n });\n\n const slipSubAssembly = slipSubAssemblies[saIndex];\n\n return {\n subAssemblyId: sa.id,\n singleReject: sa.singleReject,\n quorum: sa.quorum,\n subjectCipherData,\n createApprovers: await Promise.all(\n createApprovers.map(async ({ tp }, approverIndex) =>\n this.prepareApprover({\n tp,\n approverIndex,\n slipSubAssembly,\n assemblyKeyParams,\n subjectKey,\n })\n )\n ),\n updateApprovers: await Promise.all(\n updateApprovers.map(async ({ tp, approverId }, approverIndex) =>\n this.prepareApprover({\n approverId,\n tp,\n approverIndex: approverIndex + createApprovers.length,\n slipSubAssembly,\n assemblyKeyParams,\n subjectKey,\n })\n )\n ),\n };\n })\n );\n }\n\n private fillWrappingKeyId(input: CreateTpSubAssemblyInput[], tps: TpNode[]) {\n // Fill in wrappingKeyId if not present\n input.forEach((sa) => {\n sa.approverTps.forEach((approver) => {\n if (!approver.wrappingKeyId) {\n const tp = tps.find((x) => x.id === approver.tpId);\n approver.wrappingKeyId = this.getTpWrappingKeyId(tp);\n }\n });\n });\n }\n\n private getInputApprovers(input: CreateTpSubAssemblyInput[]) {\n const tpIds: string[] = [];\n input.forEach((sa) => {\n sa.approverTps.forEach((approver) => {\n tpIds.push(approver.tpId);\n });\n });\n return tpIds;\n }\n\n public async prepareCreate(input: CreateTpAssemblyInput) {\n const rootKey = this.keyService.currentRootKey;\n const subjectKey = await this.keyFactory.createKey();\n const rootKeyWrappedSubjectKey = await this.keyGraph.wrapKey(\n rootKey,\n subjectKey\n );\n\n const { assemblyKey, rawAssemblyKey, assemblyKeyParams, ...assemblyInput } =\n await this.prepareAssembly({\n rootKey: rootKey.jwk,\n subjectKey,\n });\n\n const slipAssembly = await this.prepareSlip39(\n input.createSubAssemblies,\n input.quorum,\n rawAssemblyKey\n );\n\n const tpIds = this.getInputApprovers(input.createSubAssemblies);\n\n // This should contain all the TPs that we need to update the assembly.\n const tps = mapEdges(\n (\n await this.lrGraphQl.query({\n query: TpsKeysQuery,\n variables: {\n ids: tpIds,\n },\n })\n ).tps\n );\n\n // Fill in wrappingKeyId if not present\n this.fillWrappingKeyId(input.createSubAssemblies, tps);\n\n const createSubAssemblies = await this.prepareCreateSubAssemblies({\n input: input.createSubAssemblies,\n assemblyKeyParams,\n slipSubAssemblies: slipAssembly.subAssemblies,\n subjectKey,\n });\n\n const subjectCipherData = await this.encryptionService.encryptToString(\n subjectKey,\n input.subjectCipherDataClearJson || ''\n );\n\n return {\n assemblyKey,\n mutationInput: {\n ...assemblyInput,\n singleReject: input.singleReject,\n quorum: input.quorum,\n subjectCipherData,\n createSubAssemblies,\n rootKeyId: rootKey.id,\n rootKeyWrappedSubjectKey,\n },\n };\n }\n\n private getAssemblyApprovers(assembly: TpAssemblyNode) {\n const tpIds: string[] = [];\n\n // Find all TPs that belong to sub-assemblies\n mapEdges(assembly.subAssemblies).map((sa) => {\n mapEdges(sa.approvers).forEach((approver) => tpIds.push(approver.tp.id));\n });\n\n return tpIds;\n }\n\n public async prepareUpdate(\n input: UpdateTpAssemblyInput,\n assembly: TpAssemblyNode // TODO type this to only what we need.\n ) {\n input = {\n createSubAssemblies: [],\n ...input,\n };\n\n const createSubAssembliesInput = input.createSubAssemblies || [];\n const updateSubAssembliesInput = input.updateSubAssemblies || [];\n const deleteSubAssembliesInput = input.deleteSubAssemblies || [];\n\n // Must have at least one.\n if (\n createSubAssembliesInput.length === 0 &&\n updateSubAssembliesInput.length === 0 &&\n deleteSubAssembliesInput.length === 0\n ) {\n throw new KcBadArgumentException(\n 'Must specify at least one of: [createSubAssemblies, updateSubAssemblies, deleteSubAssemblies]'\n );\n }\n\n const rootKey = this.keyService.currentRootKey;\n const subjectKey = await this.keyGraph.getKey(assembly.subjectKey.id);\n\n const { assemblyKey, rawAssemblyKey, assemblyKeyParams, ...assemblyInput } =\n await this.prepareAssembly({\n rootKey: rootKey.jwk,\n subjectKey: subjectKey.jwk,\n });\n\n // Find all the TPs that we need, duplicates are no problem.\n // Existing approvers\n const tpIds = this.getAssemblyApprovers(assembly).concat(\n this.getInputApprovers(createSubAssembliesInput),\n this.getInputApprovers(updateSubAssembliesInput)\n );\n\n // This should contain all the TPs that we need to update the assembly.\n const tps = mapEdges(\n (\n await this.lrGraphQl.query({\n query: TpsKeysQuery,\n variables: {\n ids: tpIds,\n },\n })\n ).tps\n );\n\n // Auto fill the updateSubAssemblies with existing sub assemblies if they are not\n // explicitly deleted.\n mapEdges(assembly.subAssemblies).forEach((existing) => {\n // Deleting existing, don't include it\n if (deleteSubAssembliesInput.includes(existing.id)) {\n return;\n }\n\n // Update already specified in the input\n if (updateSubAssembliesInput.some((sa) => sa.id === existing.id)) {\n return;\n }\n\n const approverTps: TpAssemblyApproverInput[] = mapEdges(\n existing.approvers\n ).map((approver) => {\n return {\n tpId: approver.tp.id,\n sharedCipherDataClearJson: approver.sharedCipherDataClearJson,\n sharedCipherApprovalDataClearJson:\n approver.sharedCipherApprovalDataClearJson,\n };\n });\n\n updateSubAssembliesInput.push({\n id: existing.id,\n quorum: existing.quorum,\n singleReject: existing.singleReject,\n approverTps,\n subjectCipherDataClearJson: existing.subjectCipherDataClearJson,\n });\n });\n\n // Fill in wrappingKeyId if not present\n this.fillWrappingKeyId(createSubAssembliesInput, tps);\n this.fillWrappingKeyId(updateSubAssembliesInput, tps);\n\n let slipAssembly;\n try {\n slipAssembly = await this.prepareSlip39(\n (createSubAssembliesInput || []).concat(updateSubAssembliesInput || []),\n input.quorum,\n rawAssemblyKey\n );\n } catch (error) {\n // TODO this sometimes happens. Maybe missing await.\n console.log('Error while creating slip assembly', error);\n }\n\n const common = {\n assemblyKeyParams,\n subjectKey: subjectKey.jwk,\n };\n\n const createSubAssemblies = await this.prepareCreateSubAssemblies({\n ...common,\n input: createSubAssembliesInput,\n // Need to match the slip sub assemblies to the input\n slipSubAssemblies: slipAssembly.subAssemblies.slice(\n 0,\n createSubAssembliesInput.length\n ),\n });\n\n const updateSubAssemblies = await this.prepareUpdateSubAssemblies({\n ...common,\n input: updateSubAssembliesInput,\n // Add an offset to the sub assemblies to skip the one that are created.\n slipSubAssemblies: slipAssembly.subAssemblies.slice(\n createSubAssembliesInput.length\n ),\n subAssemblies: assembly.subAssemblies,\n });\n\n const subjectCipherData = await this.encryptionService.encryptToString(\n subjectKey.jwk,\n input.subjectCipherDataClearJson ?? assembly.subjectCipherDataClearJson\n );\n\n return {\n assemblyKey,\n mutationInput: {\n ...assemblyInput,\n singleReject: input.singleReject,\n quorum: input.quorum,\n subjectCipherData,\n subjectKeyId: subjectKey.id,\n createSubAssemblies,\n updateSubAssemblies,\n },\n };\n }\n\n private async prepareApprover({\n approverId,\n tp,\n approverIndex,\n slipSubAssembly,\n assemblyKeyParams,\n subjectKey,\n }: {\n approverId?: string; // Given if updating existing approver\n tp: TpAssemblyApproverInput;\n approverIndex: number;\n slipSubAssembly: slip.SubAssembly;\n assemblyKeyParams: Record<string, JSONObject>;\n subjectKey: JWK.Key;\n }) {\n const tpWrappingKey = await this.prepareTpWrappingKey(tp);\n // shared key is rotated every time.\n const sharedKey = await this.keyFactory.createKey();\n\n // For TP to access shared_key\n const tpWrappedSharedKey = await this.encryptionService.encryptToString(\n tpWrappingKey.jwk,\n sharedKey.toJSON(true)\n );\n // For subject to access shared_key\n const subjectKeyWrappedSharedKey =\n await this.encryptionService.encryptToString(\n subjectKey,\n sharedKey.toJSON(true)\n );\n\n // If quorum is 1, then using the same share for every member.\n const share =\n slipSubAssembly.threshold === 1\n ? slipSubAssembly.shares[0]\n : slipSubAssembly.shares[approverIndex];\n\n const partialAssemblyKey: PartialAssemblyKey = {\n slip39: {\n share,\n subAssembly: {\n quorum: slipSubAssembly.threshold,\n size: slipSubAssembly.size,\n },\n },\n assemblyKeyParams,\n };\n\n const sharedCipherData = await this.encryptionService.encryptToString(\n sharedKey,\n tp.sharedCipherDataClearJson || ''\n );\n\n const sharedCipherApprovalData =\n await this.encryptionService.encryptToString(\n sharedKey,\n tp.sharedCipherApprovalDataClearJson || ''\n );\n\n const sharedCipherPartialAssemblyKey =\n await this.encryptionService.encryptToString(\n sharedKey,\n partialAssemblyKey\n );\n\n return {\n tpWrappingKeyId: tpWrappingKey.id,\n tpWrappedSharedKey,\n subjectKeyWrappedSharedKey,\n sharedCipherData,\n sharedCipherApprovalData,\n sharedCipherPartialAssemblyKey,\n approverId: approverId || void 0, // If existing approver\n tpId: approverId ? void 0 : tp.tpId, // else adding new TP\n };\n }\n\n validateApprovers(approvers: TpNode[]): void {\n // Ensure all approvers have mkSharedKey.\n for (const tp of approvers) {\n if (!tp.currentUserSharedKey.userSharedKey.mkSharedKey) {\n const msg = `tp ${tp.other.username} does not have mkSharedKey`;\n console.log(msg);\n throw new KcBadArgumentException(msg);\n }\n }\n }\n\n // Prepare slip39\n protected async prepareSlip39(\n subAssemblies,\n assemblyQuorum: number,\n rawAssemblyKey: string\n ): Promise<slip.Assembly> {\n // Is there enough sub assemblies to meet quorum\n if (subAssemblies.length < assemblyQuorum) {\n throw new KcBadArgumentException(\n 'Not enough sub assemblies to meet quorum'\n );\n }\n\n const slipAssembly = new slip.Assembly(assemblyQuorum);\n\n subAssemblies.forEach((sa, index) => {\n let approverCount = sa.approverTps.length;\n\n // slip39 restricts quorum == 1 to have only 1 member. So we just share the same\n // partial key for all sub assembly members.\n if (sa.quorum === 1) {\n approverCount = 1;\n }\n slipAssembly.addSubAssembly(\n new slip.SubAssembly(index, sa.quorum, approverCount)\n );\n });\n\n await this.slip39Service.generateShares(\n rawAssemblyKey,\n this.slip39Passphrase,\n slipAssembly\n );\n return slipAssembly;\n }\n}\n","import { Injectable, Injector, NgZone } from '@angular/core';\nimport { TpNode } from '../api/types';\nimport { TpAssemblyController } from '../tp-assembly/tp-assembly';\nimport { RunOutsideAngular } from '../_common/run-outside-angular';\nimport { TP_PASSWORD_RESET_SLIP39_PASSPHRASE } from './tp-password-reset.constants';\n\n@RunOutsideAngular({\n ngZoneName: 'ngZone',\n})\n@Injectable({\n providedIn: 'root',\n})\nexport class TpPasswordResetAssemblyController extends TpAssemblyController {\n slip39Passphrase = TP_PASSWORD_RESET_SLIP39_PASSPHRASE;\n\n constructor(private ngZone: NgZone, private injector: Injector) {\n super(injector);\n }\n\n getTpWrappingKeyId(tp: TpNode) {\n return tp.currentUserSharedKey.userSharedKey.mkSharedKey.id;\n }\n}\n","import { ID, JSONObject } from '../api/types';\nimport { gqlTyped } from '../_common/ast';\n\nexport interface CancelTpPasswordResetRequestMutationResult {\n cancelTpPasswordResetRequest: {\n id: ID;\n };\n}\nexport const CancelTpPasswordResetRequestMutation = gqlTyped<CancelTpPasswordResetRequestMutationResult>`\nmutation CancelTpPasswordResetRequestMutation {\n cancelTpPasswordResetRequest(input: {}) {\n id\n }\n}`;\n\nexport interface CreateTpAssemblyKeyChallengeMutationResult {\n createTpAssemblyKeyChallenge: {\n challenge: JSONObject;\n };\n}\nexport const CreateTpAssemblyKeyChallengeMutation = gqlTyped<CreateTpAssemblyKeyChallengeMutationResult>`\nmutation CreateTpAssemblyKeyChallengeMutation(\n $input: CreateTpAssemblyKeyChallengeInput!\n) {\n createTpAssemblyKeyChallenge(input: $input) {\n challenge\n }\n}`;\n\nexport interface PreCompleteTpPasswordResetRequestMutationResult {\n preCompleteTpPasswordResetRequest: {\n idpPassword: string;\n };\n}\nexport const PreCompleteTpPasswordResetRequestMutation = gqlTyped<PreCompleteTpPasswordResetRequestMutationResult>`\nmutation PreCompleteTpPasswordResetRequestMutation(\n $input: PreCompleteTpPasswordResetRequestInput!\n) {\n preCompleteTpPasswordResetRequest(input: $input) {\n idpPassword\n }\n}`;\n\nexport interface CompleteTpPasswordResetRequestMutationResult {\n completeTpPasswordResetRequest: {\n id: ID;\n };\n}\nexport const CompleteTpPasswordResetRequestMutation = gqlTyped<CompleteTpPasswordResetRequestMutationResult>`\nmutation CompleteTpPasswordResetRequestMutation(\n $input: CompleteTpPasswordResetRequestInput!\n) {\n completeTpPasswordResetRequest(input: $input) {\n id\n }\n}`;\n\nexport interface ApproveTpPasswordResetRequestMutationResult {\n approveTpPasswordResetRequest: {\n claimApprover: {\n id: ID;\n };\n };\n}\nexport const ApproveTpPasswordResetRequestMutation = gqlTyped<ApproveTpPasswordResetRequestMutationResult>`\nmutation ApproveTpPasswordResetRequestMutation(\n $input: ApproveTpPasswordResetRequestInput!\n) {\n approveTpPasswordResetRequest(input: $input) {\n claimApprover {\n id\n }\n }\n}`;\n\nexport interface RejectTpPasswordResetRequestMutationResult {\n rejectTpPasswordResetRequest: {\n claimApprover: {\n id: ID;\n };\n };\n}\nexport const RejectTpPasswordResetRequestMutation = gqlTyped<RejectTpPasswordResetRequestMutationResult>`\nmutation RejectTpPasswordResetRequestMutation(\n $input: RejectTpPasswordResetRequestInput!\n) {\n rejectTpPasswordResetRequest(input: $input) {\n claimApprover {\n id\n }\n }\n}`;\n\nexport interface CreateTpPasswordResetMutationResult {\n createTpPasswordReset: {\n tpPasswordReset: {\n id: ID;\n };\n };\n}\nexport const CreateTpPasswordResetMutation = gqlTyped<CreateTpPasswordResetMutationResult>`\nmutation CreateTpPasswordResetMutation($input: CreateTpPasswordResetInput!) {\n createTpPasswordReset(input: $input) {\n tpPasswordReset {\n id\n }\n }\n}`;\n\nexport interface DeleteTpPasswordResetMutationResult {\n deleteTpPasswordReset: {\n id: ID;\n };\n}\nexport const DeleteTpPasswordResetMutation = gqlTyped<DeleteTpPasswordResetMutationResult>`\nmutation DeleteTpPasswordResetMutation {\n deleteTpPasswordReset(input: {}) {\n id\n }\n}`;\n\nexport interface UpdateTpPasswordResetMutationResult {\n updateTpPasswordReset: {\n tpPasswordReset: {\n id: ID;\n };\n };\n}\nexport const UpdateTpPasswordResetMutation = gqlTyped<UpdateTpPasswordResetMutationResult>`\nmutation UpdateTpPasswordResetMutation($input: UpdateTpPasswordResetInput!) {\n updateTpPasswordReset(input: $input) {\n tpPasswordReset {\n id\n }\n }\n}`;\n","export class KeyContainer {\n private timer: NodeJS.Timeout;\n\n constructor(private _key: CryptoKey, timeout: number) {\n this.timer = setTimeout(() => {\n this._key = null;\n }, timeout);\n }\n get key(): CryptoKey {\n return this._key;\n }\n\n /**\n * Clears the reference to the key, clears the timer, return the key.\n * It's important to call this function when the key is no longer needed because\n * the anonymous function in setTimeout() holds a reference to \"this\", and hence\n * keeps the \"this._key\" reference until the timer expired. So if we have used\n * the key before it expired, we should clear the \"this._key\" reference immediately.\n */\n pop(): CryptoKey {\n const ret = this._key;\n this._key = null;\n if (this.timer) {\n clearTimeout(this.timer);\n this.timer = null;\n }\n return ret;\n }\n}\n","import {\n TpPasswordResetUser,\n TpPasswordResetUserApprovalNode,\n TpPasswordResetUserApprover,\n TpPasswordResetUserAssembly,\n TpPasswordResetUserSubAssembly,\n UserNode,\n} from '../api/types';\nimport { UserKeys } from '../key/key.service';\nimport { gqlTyped } from '../_common/ast';\nimport { KeyGraphFragment } from '../_common/queries.gql';\n\nexport interface CurrentUserQueryResult {\n currentUser: Pick<\n Required<UserNode>,\n 'id' | 'username' | 'sessionEncryptionKey'\n > & {\n currentUserKey: UserKeys;\n };\n}\nexport const CurrentUserQuery = gqlTyped<CurrentUserQueryResult>`\nquery {\n currentUser {\n id\n username\n currentUserKey {\n passKey {\n id\n passKeyParams\n passIdpParams\n wrappedPassIdpVerifierPrk\n created\n }\n masterKey {\n id\n }\n rootKey {\n id\n }\n pxk {\n id\n }\n sigPxk {\n id\n }\n }\n sessionEncryptionKey\n }\n keyGraph {\n ...KeyGraphFragment\n }\n}\n${KeyGraphFragment}\n`;\n\nexport interface ResetUserQueryResult {\n tpPasswordResetUser: Pick<\n Required<TpPasswordResetUser>,\n | 'username'\n | 'sessionEncryptionKey'\n | 'state'\n | 'passKey'\n | 'masterKey'\n | 'pxk'\n | 'approvals'\n | 'assemblyCipherData'\n | 'wrappedAssemblyKeyVerifierPrk'\n > & {\n assembly: Pick<\n Required<TpPasswordResetUserAssembly>,\n 'singleReject' | 'quorum'\n > & {\n subAssemblies: (Pick<\n Required<TpPasswordResetUserSubAssembly>,\n 'singleReject' | 'quorum'\n > & {\n approvers: Pick<\n Required<TpPasswordResetUserApprover>,\n 'name' | 'email' | 'state'\n >[];\n })[];\n };\n approvals: Pick<\n Required<TpPasswordResetUserApprovalNode>,\n | 'id'\n | 'modified'\n | 'approverEmail'\n | 'receiverCipher'\n | 'receiverCipherPartialAssemblyKey'\n >;\n };\n}\nexport const ResetUserQuery = gqlTyped<ResetUserQueryResult>`\nquery ResetUserQuery {\n tpPasswordResetUser {\n username\n sessionEncryptionKey\n state\n passKey {\n id\n passKeyParams\n passIdpParams\n }\n masterKey {\n id\n }\n pxk {\n id\n }\n assembly {\n singleReject\n quorum\n subAssemblies {\n singleReject\n quorum\n approvers {\n name\n email\n state\n }\n }\n }\n approvals {\n id\n modified\n approverEmail\n receiverCipher\n receiverCipherPartialAssemblyKey\n }\n assemblyCipherData\n wrappedAssemblyKeyVerifierPrk\n }\n}`;\n\nexport interface SetSessionEncryptionKeyMutation {\n setSessionEncryptionKey: {\n sessionEncryptionKey: string;\n };\n}\nexport const SetSessionEncryptionKeyMutation = gqlTyped<SetSessionEncryptionKeyMutation>`\nmutation SetSessionEncryptionKeyMutation($input: SetSessionEncryptionKeyInput!) {\n setSessionEncryptionKey(input: $input) {\n sessionEncryptionKey\n }\n}\n`;\n","import { CognitoUser } from '@aws-amplify/auth';\nimport { CognitoUserAttribute } from 'amazon-cognito-identity-js';\nimport { JWK } from 'node-jose';\nimport {\n ID,\n JSONObject,\n TpClaimState,\n TpPasswordResetUser,\n TpPasswordResetUserApprovalNode,\n TpPasswordResetUserApprover,\n TpPasswordResetUserAssembly,\n TpPasswordResetUserSubAssembly,\n UserNode,\n} from '../api/types';\nimport { PassIdpParams, PassKeyParams } from '../key/key.types';\n\nexport type AuthUser = Pick<Required<UserNode>, 'username'> & {\n id?: ID; // The reset user does not return an id.\n sub: string;\n loginEmail: string;\n resetUser: null | {\n state: TpClaimState;\n };\n};\n\nexport type LogoutListener = () => void | Promise<void>;\n\nexport interface LoginOptions {\n // If true, complete any TP password reset requests right after login.\n // This is mainly for debugging and testing purposes.\n tpPasswordResetAutoComplete?: boolean;\n}\n\nexport enum RecoveryStatus {\n NONE = 'NONE',\n NEW_PASSWORD = 'NEW_PASSWORD',\n OLD_PASSWORD = 'OLD_PASSWORD',\n}\n\nexport enum PasswordChangeStatus {\n IN_PROGRESS = 'IN_PROGRESS',\n RECOVERY = 'RECOVERY',\n}\n\nexport interface PassIdpResult {\n passwordChangeStatus?: PasswordChangeStatus;\n currentPassIdpParams: PassIdpParams;\n newPassIdpParams: PassIdpParams;\n tpPasswordReset: {\n passIdpParams: PassIdpParams;\n resetUsername: string;\n };\n}\n\nexport enum CognitoChallengeName {\n NEW_PASSWORD_REQUIRED = 'NEW_PASSWORD_REQUIRED',\n SMS_MFA = 'SMS_MFA',\n SOFTWARE_TOKEN_MFA = 'SOFTWARE_TOKEN_MFA',\n MFA_SETUP = 'MFA_SETUP',\n}\n\nexport type LrCognitoUser = CognitoUser & {\n // These are missing types. Bug in the lib basically.\n challengeName: CognitoChallengeName;\n challengeParam: JSONObject;\n};\n\nexport type LrCognitoUserAttribute = CognitoUserAttribute;\n\nexport interface LoginChallenge {\n cognitoUser: LrCognitoUser;\n // In the event a password change process has failed, we need to know\n // if the new or old password was used. This allows us to track it.\n recoveryStatus: RecoveryStatus;\n}\n\nexport interface LoginResult {\n challenge?: LoginChallenge;\n user?: AuthUser;\n}\n\nexport interface PassKeyBundle {\n passKeyParams: PassKeyParams;\n passKey: JWK.Key;\n passIdpParams: PassIdpParams;\n passIdp: JWK.Key;\n passIdpVerifier: JWK.Key;\n wrappedPassIdpVerifierPrk: Record<string, JSONObject>;\n}\n\nexport type ResetUser = Pick<\n Required<TpPasswordResetUser>,\n 'username' | 'state' | 'approvals'\n> & {\n assembly: Pick<\n Required<TpPasswordResetUserAssembly>,\n 'singleReject' | 'quorum'\n > & {\n subAssemblies: (Pick<\n Required<TpPasswordResetUserSubAssembly>,\n 'singleReject' | 'quorum'\n > & {\n approvers: Pick<\n Required<TpPasswordResetUserApprover>,\n 'name' | 'email' | 'state'\n >[];\n })[];\n };\n approvals: Pick<\n Required<TpPasswordResetUserApprovalNode>,\n | 'id'\n | 'modified'\n | 'approverEmail'\n | 'receiverCipher'\n | 'receiverCipherPartialAssemblyKey'\n >;\n};\n","import { HttpClient } from '@angular/common/http';\nimport { Inject, Injectable, Injector, isDevMode, NgZone } from '@angular/core';\nimport { CognitoUser } from '@aws-amplify/auth';\nimport { AuthClass } from '@aws-amplify/auth/lib-esm/Auth';\nimport { Hub } from '@aws-amplify/core';\nimport { CognitoUserAttribute } from 'amazon-cognito-identity-js';\nimport { JWK } from 'node-jose';\nimport { LrGraphQLService, LrMutation, LrService } from '../api/lr-graphql';\nimport { TpClaimState } from '../api/types';\nimport { EncryptionService } from '../encryption/encryption.service';\nimport { IdleService } from '../idle/idle.service';\nimport { KeyFactoryService } from '../key/key-factory.service';\nimport { KeyGraphService } from '../key/key-graph.service';\nimport { KeyService, UserKeys } from '../key/key.service';\nimport { PassIdpParams } from '../key/key.types';\nimport { KcConfig, KC_CONFIG } from '../life-ready.config';\nimport { PasswordService } from '../password/password.service';\nimport { PersistService } from '../persist/persist.service';\nimport {\n TP_PASSWORD_RESET_CLIENT_NONCE_LENGTH,\n TP_PASSWORD_RESET_USERNAME_SUFFIX,\n} from '../tp-password-reset/tp-password-reset.constants';\nimport { TpPasswordResetAssemblyController } from '../tp-password-reset/tp-password-reset.controller';\nimport {\n CompleteTpPasswordResetRequestMutation,\n CreateTpAssemblyKeyChallengeMutation,\n PreCompleteTpPasswordResetRequestMutation,\n} from '../tp-password-reset/tp-password-reset.gql';\nimport {\n KcBadRequestException,\n KcBadStateException,\n KcConcurrentAccessException,\n KcInternalErrorException,\n} from '../_common/exceptions';\nimport { KeyContainer } from '../_common/key';\nimport { RunOutsideAngular } from '../_common/run-outside-angular';\nimport {\n CurrentUserQuery,\n CurrentUserQueryResult,\n ResetUserQuery,\n ResetUserQueryResult,\n SetSessionEncryptionKeyMutation,\n} from './auth.gql.private';\nimport {\n AuthUser,\n CognitoChallengeName,\n LoginChallenge,\n LoginOptions,\n LoginResult,\n LogoutListener,\n LrCognitoUser,\n LrCognitoUserAttribute,\n PassIdpResult,\n PasswordChangeStatus,\n RecoveryStatus,\n} from './auth.types';\n\n@RunOutsideAngular({\n ngZoneName: 'ngZone',\n})\n@Injectable({\n providedIn: 'root',\n})\nexport class AuthService extends LrService {\n static CHALLENGE_TIMEOUT = 1000 * 60 * 5;\n\n // Could use rxjs observables here. But trying to have kc-client use as little angular\n // features as possible. Rxjs is not used anywhere else in kc-client.\n private logoutListeners = new Set<LogoutListener>();\n private user: AuthUser;\n // Stores the password for use after mfa verification to decrypt masterKey.\n private password: KeyContainer = null;\n\n constructor(\n private ngZone: NgZone,\n private injector: Injector,\n private http: HttpClient,\n private cognito: AuthClass,\n private api: LrGraphQLService,\n private keyService: KeyService,\n private keyGraphService: KeyGraphService,\n private keyFactoryService: KeyFactoryService,\n private passwordService: PasswordService,\n private idleService: IdleService,\n private persistService: PersistService,\n private encryptionService: EncryptionService,\n private assemblyController: TpPasswordResetAssemblyController,\n @Inject(KC_CONFIG) private kcConfig: KcConfig\n ) {\n super(injector);\n if (!isDevMode()) {\n if (this.kcConfig.debug != null) {\n throw new KcBadRequestException(\n 'In production mode, \"KcConfig.debug\" must be set to null'\n );\n }\n }\n }\n\n importPassword(plainPassword: string): Promise<CryptoKey> {\n return this.keyFactoryService.importPassword(plainPassword);\n }\n\n async logout(): Promise<void> {\n // Notify all listeners to clean up.\n await Promise.all([...this.logoutListeners].map((callback) => callback()));\n\n this.user = null;\n this.keyService.purgeKeys();\n this.keyGraphService.purgeKeys();\n\n // Sign out on both cognito and kc-server\n await Promise.all([this.cognito.signOut(), this.kcLogout()]);\n\n if (this.kcConfig.debug?.username) {\n this.kcConfig.debug.username = null;\n }\n }\n\n addLogoutListener(callback: LogoutListener) {\n this.logoutListeners.add(callback);\n }\n\n removeLogoutListener(callback: LogoutListener) {\n this.logoutListeners.delete(callback);\n }\n\n async login(\n emailOrPhone: string,\n password: CryptoKey,\n { tpPasswordResetAutoComplete = true }: LoginOptions = {}\n ): Promise<LoginResult> {\n let loginResult: LoginResult = await this.loginImpl(emailOrPhone, password);\n\n // Save the password for use after meeting challenge.\n if (loginResult.challenge) {\n this.password = new KeyContainer(password, AuthService.CHALLENGE_TIMEOUT);\n\n return loginResult;\n }\n\n if (\n tpPasswordResetAutoComplete &&\n loginResult.user.resetUser?.state === TpClaimState.APPROVED\n ) {\n await this.completeResetRequest(password);\n loginResult = await this.loginImpl(emailOrPhone, password);\n }\n\n return loginResult;\n }\n\n async verifyLogin(options: {\n challenge: LoginChallenge;\n code: string;\n rememberMe: boolean;\n }): Promise<LoginResult> {\n const { challenge, code, rememberMe } = options;\n\n const VALID_CHALLENGE_NAMES = [\n CognitoChallengeName.SMS_MFA,\n CognitoChallengeName.SOFTWARE_TOKEN_MFA,\n ];\n\n if (!VALID_CHALLENGE_NAMES.includes(challenge.cognitoUser.challengeName)) {\n throw new KcBadRequestException(\n `challengeName must be one of ${VALID_CHALLENGE_NAMES}`\n );\n }\n\n // TODO: this.auth.confirmSignIn() could return another challenge.\n const cognitoUser = await this.cognito.confirmSignIn(\n challenge.cognitoUser,\n code,\n challenge.cognitoUser.challengeName as\n | CognitoChallengeName.SMS_MFA\n | CognitoChallengeName.SOFTWARE_TOKEN_MFA\n );\n\n await this.handlePostAuth(challenge.recoveryStatus);\n\n const user = await this.loadUser(cognitoUser, this.password.pop());\n\n // This is not strictly necessary since the this.password.pop() already clears the\n // password inside the container. But doesn't hurt either.\n this.password = null;\n\n if (rememberMe) {\n cognitoUser.setDeviceStatusRemembered({\n onSuccess: () => {\n return;\n },\n onFailure: (e) => console.error(e),\n });\n }\n\n return {\n user,\n };\n }\n\n async getUser(): Promise<AuthUser> {\n if (this.user) {\n return this.user;\n }\n\n const cognitoUser = await this.cognito.currentAuthenticatedUser();\n\n return this.loadUser(cognitoUser);\n }\n\n async refreshAccessToken() {\n const cognitoUser: CognitoUser =\n await this.cognito.currentAuthenticatedUser();\n const refreshToken = cognitoUser.getSignInUserSession().getRefreshToken();\n\n console.log('Token refresh...');\n return new Promise((resolve, reject) => {\n cognitoUser.refreshSession(refreshToken, (err) => {\n if (err) {\n console.error('Error refreshing token: ', err);\n reject(err);\n } else {\n console.log('Token refresh complete');\n resolve(0);\n }\n });\n });\n }\n\n // ----------------------------------------------------------------------------------------------------\n // Helpers\n // ----------------------------------------------------------------------------------------------------\n\n private async fetchCurrentUser() {\n return (\n await this.api.query<CurrentUserQueryResult>({\n query: CurrentUserQuery,\n processorOptions: {\n hasKeys: false, // Don't try to decrypt anything because keys have not been setup yet\n },\n })\n ).currentUser;\n }\n\n private async fetchResetUser() {\n return (\n await this.api.query<ResetUserQueryResult>({\n query: ResetUserQuery,\n processorOptions: {\n hasKeys: false, // Don't try to decrypt anything because keys have not been setup yet\n },\n })\n ).tpPasswordResetUser;\n }\n\n private async kcLogout(): Promise<void> {\n await this.http\n .post(`${this.kcConfig.authUrl}auth/sign-out/`, null, {\n withCredentials: true,\n responseType: 'text',\n })\n .toPromise();\n }\n\n private async fetchPassIdpParams(\n emailOrPhone: string\n ): Promise<PassIdpResult> {\n return await this.http\n .get<PassIdpResult>(\n `${\n this.kcConfig.authUrl\n }users/pass-idp-params/?login_name=${encodeURIComponent(emailOrPhone)}`\n )\n .toPromise();\n }\n\n private async loginImpl(\n emailOrPhone: string,\n password: CryptoKey\n ): Promise<LoginResult> {\n await this.logout();\n const loginIdpResult = await this.loginIdp(emailOrPhone, password);\n\n // Can't get the user yet because we still ned to meet MFA challenges\n if (\n [\n CognitoChallengeName.SMS_MFA,\n CognitoChallengeName.SOFTWARE_TOKEN_MFA,\n ].includes(loginIdpResult.cognitoUser.challengeName)\n ) {\n return {\n challenge: {\n cognitoUser: loginIdpResult.cognitoUser,\n recoveryStatus: loginIdpResult.recoveryStatus,\n },\n };\n }\n\n await this.handlePostAuth(loginIdpResult.recoveryStatus);\n // There should be no MFA on the TP reset user.\n const user = await this.loadUser(loginIdpResult.cognitoUser, password);\n\n return {\n user,\n };\n }\n\n private async loginIdp(\n emailOrPhone: string,\n password: CryptoKey\n ): Promise<LoginChallenge> {\n // Download the salt needed to derive the PassIdp\n const passIdpApiResult = await this.fetchPassIdpParams(emailOrPhone);\n\n if (\n passIdpApiResult.passwordChangeStatus === PasswordChangeStatus.IN_PROGRESS\n ) {\n throw new KcConcurrentAccessException('A password change is in progress');\n }\n\n if (\n passIdpApiResult.passwordChangeStatus === PasswordChangeStatus.RECOVERY\n ) {\n console.log('In recovery mode.');\n\n // Let's say we don't know if the password is the new one or the old one. We just have to try both.\n try {\n const user: LoginChallenge = {\n cognitoUser: await this.loginIdpImpl(\n emailOrPhone,\n password,\n passIdpApiResult.newPassIdpParams\n ),\n recoveryStatus: RecoveryStatus.NEW_PASSWORD,\n };\n // New password worked. Let's set to the current password\n\n // --Potential Failure Point 1--\n // if changePasswordComplete() doesn't get called, then it should remain\n\n console.log('New password works!');\n\n return user;\n } catch (error) {\n // Just bubble up any other type of error.\n if (error.code !== 'NotAuthorizedException') {\n throw error;\n }\n // pass, try again assuming it's the old password\n }\n\n // Now assume it's the previous password. Any exception is allowed to bubble up.\n try {\n const user: LoginChallenge = {\n cognitoUser: await this.loginIdpImpl(\n emailOrPhone,\n password,\n passIdpApiResult.currentPassIdpParams\n ),\n recoveryStatus: RecoveryStatus.OLD_PASSWORD,\n };\n // Old password worked.\n console.log('Old password works!');\n\n return user;\n } catch (error) {\n // Just bubble up any other type of error.\n throw error.code === 'NotAuthorizedException'\n ? new KcBadRequestException(\n 'The password change request was interrupted, please try to login with both your new and old password'\n )\n : error;\n }\n }\n\n // Try again as the TP password reset account\n if (passIdpApiResult.tpPasswordReset) {\n try {\n // TP password reset is in process. We need to try the password against both\n // original account and the new reset account.\n const reset = passIdpApiResult.tpPasswordReset;\n const user: LoginChallenge = {\n cognitoUser: await this.loginIdpImpl(\n reset.resetUsername,\n password,\n reset.passIdpParams\n ),\n recoveryStatus: RecoveryStatus.NONE,\n };\n\n return user;\n } catch (err) {\n // continue, try again as regular user.\n }\n }\n\n // Login as regular user\n const user: LoginChallenge = {\n cognitoUser: await this.loginIdpImpl(\n emailOrPhone,\n password,\n passIdpApiResult.currentPassIdpParams\n ),\n recoveryStatus: RecoveryStatus.NONE,\n };\n\n return user;\n }\n\n private async loginIdpImpl(\n emailOrPhone: string,\n password: CryptoKey,\n passIdpParams: PassIdpParams\n ): Promise<LrCognitoUser> {\n const passIdpResult = await this.keyFactoryService.derivePassIdp({\n password,\n ...passIdpParams,\n });\n\n // Use the derived password to signin with cognito\n return this.cognito.signIn(\n emailOrPhone,\n this.passwordService.getPassIdpString(passIdpResult.jwk)\n );\n }\n\n private async handlePostAuth(recoveryStatus: RecoveryStatus) {\n await this.handlePasswordRecovery(recoveryStatus);\n await this.handleSessionEncryptionKey();\n }\n\n private async handlePasswordRecovery(recoveryStatus: RecoveryStatus) {\n if (recoveryStatus !== RecoveryStatus.NONE) {\n await this.passwordService.changePasswordComplete({\n useNewPassword: recoveryStatus === RecoveryStatus.NEW_PASSWORD,\n });\n }\n }\n\n private async handleSessionEncryptionKey() {\n if (this.kcConfig.disableSessionEncryptionKey) {\n if (!isDevMode()) {\n const msg =\n 'You should not set disableSessionEncryptionKey=True in mode prod. It defaults to false.';\n console.error(msg);\n throw new KcInternalErrorException(msg);\n } else {\n console.warn(\n 'You have set disableSessionEncryptionKey=True. Make sure not to do this in prod mode.'\n );\n }\n } else {\n // Set the session key to a new encryption key for this session\n const sessionEncryptionKey = await this.keyFactoryService.createKey();\n await this.lrGraphQL.lrMutate(\n new LrMutation({\n mutation: SetSessionEncryptionKeyMutation,\n variables: {\n input: {\n sessionEncryptionKey: JSON.stringify(\n sessionEncryptionKey.toJSON(true)\n ),\n },\n },\n }),\n {\n includeKeyGraph: false,\n }\n );\n\n this.persistService.setServerSessionEncryptionKey(sessionEncryptionKey);\n }\n }\n\n private getCognitoUserAttribute(\n attributeName: string,\n userAttributes: CognitoUserAttribute[]\n ) {\n const userAttribute = userAttributes.find(\n (x) => x.getName() === attributeName\n );\n\n return userAttribute ? userAttribute.getValue() : null;\n }\n\n private async loadUserKeys(options: {\n userKeys: UserKeys;\n password?: CryptoKey;\n sessionEncryptionKey?: string;\n }) {\n const { userKeys, password, sessionEncryptionKey } = options;\n\n if (sessionEncryptionKey) {\n this.persistService.setServerSessionEncryptionKey(\n await JWK.asKey(sessionEncryptionKey)\n );\n }\n\n // password is not needed if the master key is already persisted.\n if (password) {\n const passKey = (\n await this.keyFactoryService.derivePassKey({\n password,\n ...userKeys.passKey.passKeyParams,\n })\n ).jwk;\n\n await this.idleService.persistMasterKey(\n await this.keyGraphService.unwrapWithPassKey(\n userKeys.passKey.id,\n passKey,\n userKeys.masterKey.id\n )\n );\n }\n }\n\n private async loadUser(\n cognitoUser: CognitoUser,\n password?: CryptoKey\n ): Promise<AuthUser> {\n if (cognitoUser.getUsername().endsWith(TP_PASSWORD_RESET_USERNAME_SUFFIX)) {\n this.user = await this.loadResetUser(cognitoUser, password);\n } else {\n this.user = await this.loadRegularUser(cognitoUser, password);\n }\n\n await this.idleService.start(); // Run idleService whenever user is logged in.\n\n return this.user;\n }\n\n private async loadRegularUser(\n cognitoUser: CognitoUser,\n password?: CryptoKey\n ): Promise<AuthUser> {\n const currentUser = await this.fetchCurrentUser();\n\n await this.loadUserKeys({\n userKeys: currentUser.currentUserKey,\n password,\n sessionEncryptionKey: currentUser.sessionEncryptionKey,\n });\n\n // Regular user populates all keys\n await this.keyGraphService.populateKeys(currentUser.currentUserKey);\n\n const { id, username } = currentUser;\n const userAttributes = await this.cognito.userAttributes(cognitoUser);\n\n return {\n id,\n username,\n sub: this.getCognitoUserAttribute('sub', userAttributes),\n loginEmail: this.getCognitoUserAttribute('email', userAttributes),\n resetUser: null,\n };\n }\n\n private async loadResetUser(\n cognitoUser: CognitoUser,\n password?: CryptoKey\n ): Promise<AuthUser> {\n const resetUser = await this.fetchResetUser();\n\n const userKeys = {\n passKey: {\n id: resetUser.passKey.id,\n passKeyParams: resetUser.passKey.passKeyParams,\n },\n masterKey: {\n id: resetUser.masterKey.id,\n },\n };\n\n await this.loadUserKeys({\n userKeys,\n password,\n sessionEncryptionKey: resetUser.sessionEncryptionKey,\n });\n\n // Reset user only sets a subset of keys\n await this.keyService.setKeys(userKeys);\n\n const { username } = resetUser;\n const userAttributes = await this.cognito.userAttributes(cognitoUser);\n\n return {\n username,\n sub: this.getCognitoUserAttribute('sub', userAttributes),\n loginEmail: this.getCognitoUserAttribute('email', userAttributes),\n resetUser: {\n state: resetUser.state,\n },\n };\n }\n\n private async recoverAssemblyKey(\n resetUser: ResetUserQueryResult['tpPasswordResetUser']\n ): Promise<JWK.Key> {\n const prk = await this.keyGraphService.getKey(resetUser.pxk.id);\n\n const partials = await Promise.all(\n resetUser.approvals\n .filter((approval) => !!approval.receiverCipherPartialAssemblyKey)\n .map((approval) =>\n this.encryptionService.decrypt(\n prk,\n approval.receiverCipherPartialAssemblyKey\n )\n )\n );\n\n return this.assemblyController.recoverAssemblyKey(partials);\n }\n\n async completeResetRequest(newPassword: CryptoKey): Promise<void> {\n const resetUser = await this.fetchResetUser();\n\n if (resetUser.state !== TpClaimState.APPROVED) {\n throw new KcBadStateException(\n 'Password reset request has not been approved.'\n );\n }\n\n // --------------------------------------------------------------\n // Prepare all materials to ensure there are no errors.\n // --------------------------------------------------------------\n const assemblyKey = await this.recoverAssemblyKey(resetUser);\n\n const { rootKey } = await this.encryptionService.decrypt(\n assemblyKey,\n resetUser.assemblyCipherData\n );\n\n // Making sure it's a valid key.\n const rootKeyJwk = await JWK.asKey(rootKey);\n\n const masterKey = await this.keyGraphService.getKey(resetUser.masterKey.id);\n\n const masterKeyWrappedRootKey =\n await this.encryptionService.encryptToString(\n masterKey.jwk,\n rootKeyJwk.toJSON(true)\n );\n\n // The new password\n const newPassIdpResult = await this.keyFactoryService.derivePassIdp({\n password: newPassword,\n ...resetUser.passKey.passIdpParams,\n });\n\n const newIdpPassword = this.passwordService.getPassIdpString(\n newPassIdpResult.jwk\n );\n\n // --------------------------------------------------------------\n // Get assembly key challenge\n // --------------------------------------------------------------\n const challenge = (\n await this.lrGraphQL.lrMutate(\n new LrMutation({\n mutation: CreateTpAssemblyKeyChallengeMutation,\n variables: {\n input: {},\n },\n }),\n {\n includeKeyGraph: false,\n }\n )\n ).createTpAssemblyKeyChallenge.challenge;\n\n // Sign the challenge\n // Generate a client side nonce that's no in the server's control.\n challenge.clientNonce = this.keyFactoryService.randomString(\n TP_PASSWORD_RESET_CLIENT_NONCE_LENGTH\n );\n\n const assemblyKeyVerifierPrk = await this.encryptionService.decrypt(\n assemblyKey,\n resetUser.wrappedAssemblyKeyVerifierPrk\n );\n const signedChallenge = await this.encryptionService.sign(\n assemblyKeyVerifierPrk,\n challenge\n );\n\n // --------------------------------------------------------------\n // Change password for the original user\n // --------------------------------------------------------------\n const tempIdpPassword = (\n await this.lrGraphQL.lrMutate(\n new LrMutation({\n mutation: PreCompleteTpPasswordResetRequestMutation,\n variables: {\n input: {\n signedChallenge: JSON.stringify(signedChallenge),\n },\n },\n }),\n {\n includeKeyGraph: false,\n }\n )\n ).preCompleteTpPasswordResetRequest.idpPassword;\n\n // --------------------------------------------------------------\n // Login as the original user using new temporary password\n // --------------------------------------------------------------\n // At this point, the original account's password has been changed\n // to a temporary password. It is no longer possible for the user\n // to use the original password to login. Any successful login\n // can only be using the temporary password. So it's safe to assume\n // that we want to \"complete\" the password reset.\n\n // There maybe 2FA so we listen for the auth event from Amplify.\n const retPromise = new Promise<void>((resolve) => {\n const listener = async (data) => {\n if (data.payload.event !== 'signIn') {\n return;\n }\n\n Hub.remove('auth', listener);\n\n await this.cognito.signIn(resetUser.username, newIdpPassword);\n\n // Switch over to the new set of keys\n await this.lrGraphQL.lrMutate(\n new LrMutation({\n mutation: CompleteTpPasswordResetRequestMutation,\n variables: {\n input: {\n masterKeyWrappedRootKey,\n masterKeyId: masterKey.id,\n },\n },\n })\n );\n\n resolve();\n };\n\n Hub.listen('auth', listener);\n });\n\n // Signin as the original user. Password has been reset to temporary one. It should return\n // with NEW_PASSWORD_REQUIRED\n let user = await this.cognito.signIn(resetUser.username, tempIdpPassword, {\n noProxy: 'true',\n });\n\n if (user.challengeName !== 'NEW_PASSWORD_REQUIRED') {\n throw new KcInternalErrorException(\n 'Expecting Cognito to have done a password reset after call to PreCompleteTpPasswordResetRequestMutation.'\n );\n }\n\n // Set new password on Idp\n // the awsFetch() function passes NEW_PASSWORD_REQUIRED directly to AWS without\n // going through the proxy.\n user = await this.cognito.completeNewPassword(user, newIdpPassword, {});\n\n return retPromise;\n }\n\n // ------------------------------------------------------\n // Debug utilities\n // ------------------------------------------------------\n async debugLogin(username: string, password: CryptoKey): Promise<AuthUser> {\n // This will fail if debug is null. But when debug is null, this function\n // should not be called.\n this.kcConfig.debug.username = username;\n // Reset it so we don't get surprises.\n this.kcConfig.debug.rbacCacheMode = null;\n\n // This mechanism only works in a browser session because it needs to set cookies etc.\n // But it sets the last_login field for the users which we need in some tests.\n await this.http\n .get(\n `${\n this.kcConfig.authUrl\n }debug_only/users/login/?username=${encodeURIComponent(username)}`\n )\n .toPromise();\n\n return this.debugLoadUser(password);\n }\n\n private async debugLoadUser(password: CryptoKey): Promise<AuthUser> {\n const currentUser = await this.fetchCurrentUser();\n\n const { id, username, currentUserKey } = currentUser;\n\n // Debug mode can not deal with session encryption key yet.\n // NO SESSION ENCRYPTION KEY.\n\n const passKey = (\n await this.keyFactoryService.derivePassKey({\n password,\n ...currentUserKey.passKey.passKeyParams,\n })\n ).jwk;\n\n const masterKey = await this.keyGraphService.unwrapWithPassKey(\n currentUserKey.passKey.id,\n passKey,\n currentUserKey.masterKey.id\n );\n\n await this.idleService.persistMasterKey(masterKey);\n\n await this.keyGraphService.populateKeys(currentUserKey);\n\n this.user = {\n id,\n username,\n resetUser: null,\n sub: 'DEBUG_MODE',\n loginEmail: 'DEBUG_MODE',\n };\n\n return this.user;\n }\n\n /**\n * Clears the caches user. So we can simulate a page refresh and test getUser().\n */\n debugClearUser() {\n this.user = null;\n }\n\n async getCurrentUserAttributes(): Promise<LrCognitoUserAttribute[]> {\n const cognitoUser = await this.cognito.currentAuthenticatedUser();\n const userAttributes = await this.cognito.userAttributes(cognitoUser);\n\n return userAttributes;\n }\n\n debugRetainRbacCache(b: boolean) {\n this.kcConfig.debug.rbacCacheMode = b ? 'retain' : null;\n }\n}\n","import { ID } from '../api/types';\nimport { gqlTyped } from '../_common/ast';\n\nexport interface CreateContactCardMutationResult {\n createContactCard: {\n contactCard: {\n id: ID;\n };\n };\n}\nexport const CreateContactCardMutation = gqlTyped<CreateContactCardMutationResult>`\nmutation CreateContactCardMutation(\n $input: CreateContactCardInput!\n) {\n createContactCard(input: $input) {\n contactCard {\n id\n }\n }\n}\n`;\n\nexport interface UpdateContactCardMutationResult {\n updateContactCard: {\n contactCard: {\n id: ID;\n };\n };\n}\nexport const UpdateContactCardMutation = gqlTyped<UpdateContactCardMutationResult>`\nmutation UpdateContactCardMutation($input: UpdateContactCardInput!) {\n updateContactCard(input: $input) {\n contactCard {\n id\n }\n }\n}\n`;\n\nexport interface DeleteContactCardMutationResult {\n deleteContactCard: {\n deleteContactCard: {\n id: ID;\n };\n };\n}\nexport const DeleteContactCardMutation = gqlTyped<DeleteContactCardMutationResult>`\nmutation DeleteContactCardMutation($input: DeleteContactCardInput!) {\n deleteContactCard(input: $input) {\n id\n }\n}\n`;\n","import { Injectable, NgZone } from '@angular/core';\nimport { LrMutation } from '../api/lr-graphql';\nimport { JSONObject } from '../api/types';\nimport { EncryptionService } from '../encryption/encryption.service';\nimport { KeyFactoryService } from '../key/key-factory.service';\nimport { KeyGraphService } from '../key/key-graph.service';\nimport { KeyMetaService } from '../key/key-meta.service';\nimport { KeyService } from '../key/key.service';\nimport { MainContactCardPlainFields } from '../profile/profile.types';\nimport { RunOutsideAngular } from '../_common/run-outside-angular';\nimport {\n CreateContactCardMutation,\n DeleteContactCardMutation,\n UpdateContactCardMutation,\n} from './contact-card2.gql';\n\nexport interface CreateContactCardInput2 {\n publicDataJson: JSONObject;\n publicSearchableJson: JSONObject;\n plainCipherDataJson: JSONObject;\n plainDataJson: MainContactCardPlainFields;\n}\n\n// These contact name fields are enforced by the server so that it can send out emails with\n// appropriate format.\nexport interface ContactCardName2 {\n name: string;\n title?: string;\n firstName?: string;\n lastName?: string;\n // additional fields are not allowed by the server\n}\n\nexport class OwnerPlainDataJson {\n name: ContactCardName2;\n}\n\nexport interface UpdateContactCardInput2 extends CreateContactCardInput2 {\n id: string;\n keyId: string;\n}\n\n@RunOutsideAngular({\n ngZoneName: 'ngZone',\n})\n@Injectable({\n providedIn: 'root',\n})\nexport class ContactCard2Service {\n constructor(\n private keyFactory: KeyFactoryService,\n private keyService: KeyService,\n private encryptionService: EncryptionService,\n private keyGraph: KeyGraphService,\n private keyMetaService: KeyMetaService,\n private ngZone: NgZone\n ) {}\n\n async createContactCard(input: CreateContactCardInput2) {\n // Get encryption key\n const rootKey = this.keyService.currentRootKey;\n const key = await this.keyFactory.createKey();\n const wrappedKey = await this.keyGraph.encryptToString(\n rootKey.jwk,\n key.toJSON(true)\n );\n const cipherData = await this.keyGraph.encryptToString(\n key,\n input.plainCipherDataJson\n );\n\n const params = await this.prepareContactCardInput(input);\n\n return new LrMutation({\n mutation: CreateContactCardMutation,\n variables: {\n input: {\n ...params,\n wrappingKeyId: rootKey.id,\n wrappedKey,\n cipherData,\n },\n },\n });\n }\n\n async updateContactCard(input: UpdateContactCardInput2) {\n // Get encryption key\n const cipherData = await this.keyGraph.encryptToString(\n input.keyId,\n input.plainCipherDataJson\n );\n\n const params = await this.prepareContactCardInput(input);\n\n return new LrMutation({\n mutation: UpdateContactCardMutation,\n variables: {\n input: {\n ...params,\n id: input.id,\n cipherData,\n },\n },\n });\n }\n\n deleteContactCard(id: string) {\n return new LrMutation({\n mutation: DeleteContactCardMutation,\n variables: {\n input: {\n id,\n },\n },\n });\n }\n\n private async prepareContactCardInput(input: CreateContactCardInput2) {\n const sigPxk = this.keyService.currentSigPxk;\n const publicDataSig = JSON.stringify(\n await this.encryptionService.sign(sigPxk.jwk, input.publicDataJson)\n );\n const publicSearchableSig = JSON.stringify(\n await this.encryptionService.sign(sigPxk.jwk, input.publicSearchableJson)\n );\n const plainDataSig = JSON.stringify(\n await this.encryptionService.sign(sigPxk.jwk, input.plainDataJson)\n );\n\n return {\n sigPxkId: sigPxk.id,\n publicDataSig,\n publicSearchableSig,\n plainDataSig,\n };\n }\n}\n","import { HttpClient } from '@angular/common/http';\nimport { Inject, Injectable } from '@angular/core';\nimport { AuthClass } from '@aws-amplify/auth/lib-esm/Auth';\nimport { JSONObject } from '../api/types';\nimport { httpOptions, KcConfig, KC_CONFIG } from '../life-ready.config';\nimport { UploadEncryptedFileOptions } from './file-upload.types';\n\n@Injectable({\n providedIn: 'root',\n})\nexport class FileUploadService {\n constructor(\n @Inject(KC_CONFIG) private config: KcConfig,\n private http: HttpClient,\n private auth: AuthClass\n ) {}\n\n async downloadEncryptedFileJson(\n fileStateNodeId: string\n ): Promise<JSONObject> {\n return JSON.parse(await this.downloadEncryptedFile(fileStateNodeId));\n }\n\n async downloadEncryptedFile(fileStateNodeId: string): Promise<string> {\n const url = `${this.config.apiUrl}files/download/?file_state_node_id=${fileStateNodeId}`;\n\n const content = await this.http\n .get(url, {\n ...(await httpOptions(this.auth, this.config)),\n responseType: 'text',\n })\n .toPromise();\n\n return content;\n }\n\n async loadFile(file: File | ArrayBuffer): Promise<ArrayBuffer> {\n if (file instanceof ArrayBuffer) {\n return file;\n } else {\n return new Promise<ArrayBuffer>((resolve) => {\n const reader = new FileReader();\n reader.onload = () => {\n // OK to type cast here since we are using readAsArrayBuffer.\n resolve(reader.result as ArrayBuffer);\n };\n reader.readAsArrayBuffer(file);\n });\n }\n }\n\n async uploadEncryptedFile(\n options: UploadEncryptedFileOptions\n ): Promise<string> {\n const { encryptedContent, fileName } = options;\n\n const formData = new FormData();\n formData.append('content', new Blob([encryptedContent]), fileName);\n\n const { content_resource } = await this.http\n .post<{ content_resource }>(\n `${this.config.apiUrl}files/upload/`,\n formData,\n await httpOptions(this.auth, this.config)\n )\n .toPromise();\n\n return content_resource;\n }\n}\n","import { DateTime, ID } from '../api/types';\nimport { gqlTyped } from '../_common/ast';\n\nexport interface CreateDirectoryMutationResult {\n createDirectory: {\n directory: {\n id: ID;\n keyId: ID;\n };\n };\n}\nexport const CreateDirectoryMutation = gqlTyped<CreateDirectoryMutationResult>`\nmutation CreateDirectoryMutation($input: CreateDirectoryInput!) {\n createDirectory(input: $input) {\n directory {\n id\n keyId\n }\n }\n}\n`;\n\nexport interface UpdateDirectoryMutationResult {\n updateDirectory: {\n directory: {\n id: ID;\n modified: DateTime;\n };\n };\n}\nexport const UpdateDirectoryMutation = gqlTyped<UpdateDirectoryMutationResult>`\nmutation UpdateDirectoryMutation($input: UpdateDirectoryInput!) {\n updateDirectory(input: $input) {\n directory {\n id\n modified\n }\n }\n}\n`;\n\nexport interface DeleteDirectoryMutationResult {\n deleteDirectory: {\n id: ID;\n };\n}\nexport const DeleteDirectoryMutation = gqlTyped<DeleteDirectoryMutationResult>`\nmutation DeleteDirectoryMutation($input: DeleteDirectoryInput!) {\n deleteDirectory(input: $input) {\n id\n }\n}\n`;\n\nexport interface CreateFileMutationResult {\n createFile: {\n file: {\n id: ID;\n keyId: ID;\n };\n };\n}\nexport const CreateFileMutation = gqlTyped<CreateFileMutationResult>`\nmutation CreateFileMutation($input: CreateFileInput!) {\n createFile(input: $input) {\n file {\n id\n keyId\n }\n }\n}\n`;\n\nexport interface UpdateFileMutationResult {\n updateFile: {\n file: {\n id: ID;\n };\n };\n}\nexport const UpdateFileMutation = gqlTyped<UpdateFileMutationResult>`\nmutation UpdateFileMutation($input: UpdateFileInput!) {\n updateFile(input: $input) {\n file {\n id\n }\n }\n}\n`;\n\nexport interface RevertFileMutationResult {\n revertFile: {\n file: {\n id: ID;\n };\n };\n}\nexport const RevertFileMutation = gqlTyped<RevertFileMutationResult>`\nmutation RevertFileMutation($input: RevertFileInput!) {\n revertFile(input: $input) {\n file {\n id\n }\n }\n}\n`;\n\nexport interface DeleteFileMutationResult {\n deleteFile: {\n id: ID;\n };\n}\nexport const DeleteFileMutation = gqlTyped<DeleteFileMutationResult>`\nmutation DeleteFileMutation($input: DeleteFileInput!) {\n deleteFile(input: $input) {\n id\n }\n}\n`;\n\nexport interface ArchiveDirectoryMutationResult {\n archiveDirectory: {\n directory: {\n id: ID;\n };\n };\n}\nexport const ArchiveDirectoryMutation = gqlTyped<ArchiveDirectoryMutationResult>`\nmutation ArchiveDirectoryMutation($input: ArchiveDirectoryInput!) {\n archiveDirectory(input: $input) {\n directory {\n id\n }\n }\n}\n`;\n\nexport interface ArchiveFileMutationResult {\n archiveFile: {\n file: {\n id: ID;\n };\n };\n}\nexport const ArchiveFileMutation = gqlTyped<ArchiveFileMutationResult>`\nmutation ArchiveFileMutation($input: ArchiveFileInput!) {\n archiveFile(input: $input) {\n file {\n id\n }\n }\n}\n`;\n\nexport interface UnarchiveDirectoryMutationResult {\n unarchiveDirectory: {\n directory: {\n id: ID;\n };\n };\n}\nexport const UnarchiveDirectoryMutation = gqlTyped<UnarchiveDirectoryMutationResult>`\nmutation UnarchiveDirectoryMutation($input: UnarchiveDirectoryInput!) {\n unarchiveDirectory(input: $input) {\n directory {\n id\n }\n }\n}\n`;\n\nexport interface UnarchiveFileMutationResult {\n unarchiveFile: {\n file: {\n id: ID;\n };\n };\n}\nexport const UnarchiveFileMutation = gqlTyped<UnarchiveFileMutationResult>`\nmutation UnarchiveFileMutation($input: UnarchiveFileInput!) {\n unarchiveFile(input: $input) {\n file {\n id\n }\n }\n}\n`;\n\nexport interface ChangeDirectoryParentsMutationResult {\n changeDirectoryParents: {\n directory: {\n id: ID;\n };\n };\n}\nexport const ChangeDirectoryParentsMutation = gqlTyped<ChangeDirectoryParentsMutationResult>`\nmutation ChangeDirectoryParentsMutation($input: ChangeDirectoryParentsInput!) {\n changeDirectoryParents(input: $input) {\n directory {\n id\n }\n }\n}\n`;\n\nexport interface ChangeFileParentsMutationResult {\n changeFileParents: {\n file: {\n id: ID;\n };\n };\n}\nexport const ChangeFileParentsMutation = gqlTyped<ChangeFileParentsMutationResult>`\nmutation ChangeFileParentsMutation($input: ChangeFileParentsInput!) {\n changeFileParents(input: $input) {\n file {\n id\n }\n }\n}\n`;\n\nexport interface BeginDeleteChildItemLinksWindowMutationResult {\n beginDeleteChildItemLinksWindow: {\n begin: DateTime;\n end: DateTime;\n scheduled: DateTime;\n windowMs: number;\n directory: {\n id: ID;\n };\n };\n}\nexport const BeginDeleteChildItemLinksWindowMutation = gqlTyped<BeginDeleteChildItemLinksWindowMutationResult>`\nmutation BeginDeleteChildItemLinksWindowMutation($input: BeginDeleteChildItemLinksWindowInput!) {\n beginDeleteChildItemLinksWindow(input: $input) {\n begin\n end\n scheduled\n windowMs\n directory {\n id\n }\n }\n}\n`;\n\n// This locks the user\nexport interface TempDirectoryQueryResult {\n rootDirectories: {\n edges: {\n node: {\n id: ID;\n keyId: ID;\n };\n }[];\n };\n lock: {\n version: string;\n };\n}\nexport const TempDirectoryQuery = gqlTyped<TempDirectoryQueryResult>`\nquery TempDirectoryQuery($plainMeta: LrJSONFilter!) {\n rootDirectories(plainMeta: $plainMeta, first: 2, orderBy: \"created\") {\n edges {\n node {\n id\n keyId\n }\n }\n }\n lock {\n version\n }\n}\n`;\n\nexport interface SetFileConfidentialMutationResult {\n setFileConfidential: {\n file: {\n id: ID;\n };\n };\n}\nexport const SetFileConfidentialMutation = gqlTyped<SetFileConfidentialMutationResult>`\nmutation SetFileConfidentialMutation($input: SetFileConfidentialInput!) {\n setFileConfidential(input: $input) {\n file {\n id\n }\n }\n}\n`;\n\nexport interface SetDirectoryConfidentialMutationResult {\n setDirectoryConfidential: {\n directory: {\n id: ID;\n };\n };\n}\nexport const SetDirectoryConfidentialMutation = gqlTyped<SetDirectoryConfidentialMutationResult>`\nmutation SetDirectoryConfidentialMutation($input: SetDirectoryConfidentialInput!) {\n setDirectoryConfidential(input: $input) {\n directory {\n id\n }\n }\n}\n`;\n","import { DateTime, LockState, UUID } from '../api/types';\nimport { gqlTyped } from '../_common/ast';\n\nexport interface LockFragmentResult {\n created: DateTime;\n modified: DateTime;\n version?: UUID;\n expiryTime: DateTime;\n state: LockState;\n}\nexport const LockFragment = gqlTyped<LockFragmentResult>`\nfragment LockFragment on LockField {\n created\n modified\n version\n expiryTime\n state\n}`;\n\nexport interface UpdateLockMutationResult {\n updateLock: {\n lock: LockFragmentResult;\n };\n}\nexport const UpdateLockMutation = gqlTyped<UpdateLockMutationResult>`\nmutation UpdateLockMutation($input: UpdateLockInput!) {\n updateLock(input: $input) {\n lock {\n ...LockFragment\n }\n }\n}\n${LockFragment}\n`;\n\nexport interface AcquireLockMutationResult {\n acquireLock: {\n lock: LockFragmentResult;\n };\n}\nexport const AcquireLockMutation = gqlTyped<AcquireLockMutationResult>`\nmutation AcquireLockMutation($input: AcquireLockInput!) {\n acquireLock(input: $input) {\n lock {\n ...LockFragment\n }\n }\n}\n${LockFragment}\n`;\n\nexport interface ReleaseLockMutationResult {\n releaseLock: {\n lock: LockFragmentResult;\n };\n}\nexport const ReleaseLockMutation = gqlTyped<ReleaseLockMutationResult>`\nmutation ReleaseLockMutation($input: ReleaseLockInput!) {\n releaseLock(input: $input) {\n lock {\n ...LockFragment\n }\n }\n}\n${LockFragment}\n`;\n","import { Injectable, Injector, NgZone } from '@angular/core';\nimport { LrMutation, LrService } from '../api/lr-graphql';\nimport { RunOutsideAngular } from '../_common/run-outside-angular';\nimport {\n AcquireLockMutation,\n ReleaseLockMutation,\n UpdateLockMutation,\n} from './lock.gql';\n\n@RunOutsideAngular({\n ngZoneName: 'ngZone',\n})\n@Injectable({\n providedIn: 'root',\n})\nexport class LockService extends LrService {\n constructor(private ngZone: NgZone, private injector: Injector) {\n super(injector);\n }\n\n // Updating the lock version is always to be down along with another mutation.\n updateLockMutation(options: { resourceId?: string; version: string }) {\n return new LrMutation({\n mutation: UpdateLockMutation,\n variables: {\n input: {\n resourceId: options.resourceId,\n version: options.version,\n },\n },\n });\n }\n\n acquireLockMutation(options: { resourceId?: string; timeoutMs: number }) {\n return new LrMutation({\n mutation: AcquireLockMutation,\n variables: {\n input: {\n resourceId: options.resourceId,\n timeoutMs: options.timeoutMs,\n },\n },\n });\n }\n\n releaseLockMutation(options: { resourceId: string; version: string }) {\n return new LrMutation({\n mutation: ReleaseLockMutation,\n variables: {\n input: {\n resourceId: options.resourceId,\n version: options.version,\n },\n },\n });\n }\n}\n","import { ID } from '../api/types';\nimport { gqlTyped } from '../_common/ast';\n\nexport interface DirectoryKeyQueryResult {\n directory: {\n keyId: ID;\n };\n}\nexport const DirectoryKeyQuery = gqlTyped<DirectoryKeyQueryResult>`\nquery DirectoryKeyQuery($id: LrRelayIdInput!) {\n directory(id: $id) {\n keyId\n }\n}\n`;\n\nexport interface FileKeyQueryResult {\n file: {\n keyId: ID;\n };\n}\nexport const FileKeyQuery = gqlTyped<FileKeyQueryResult>`\nquery FileKeyQuery($id: LrRelayIdInput!) {\n file(id: $id) {\n keyId\n }\n}\n`;\n\nexport interface DirectoryKeyFromDirectoryShareQueryResult {\n directoryShare: {\n item: {\n keyId: ID;\n };\n };\n}\nexport const DirectoryKeyFromDirectoryShareQuery = gqlTyped<DirectoryKeyFromDirectoryShareQueryResult>`\nquery DirectoryKeyFromDirectoryShareQuery($id: LrRelayIdInput!) {\n directoryShare(id: $id) {\n item {\n keyId\n }\n }\n}\n`;\n\nexport interface FileKeyFromFileShareQueryResult {\n fileShare: {\n item: {\n keyId: ID;\n };\n };\n}\nexport const FileKeyFromFileShareQuery = gqlTyped<FileKeyFromFileShareQueryResult>`\nquery FileKeyFromFileShareQuery($id: LrRelayIdInput!) {\n fileShare(id: $id) {\n item {\n keyId\n }\n }\n}\n`;\n\nexport interface FileStateKeyQueryResult {\n fileState: {\n keyId: ID;\n };\n}\nexport const FileStateKeyQuery = gqlTyped<FileStateKeyQueryResult>`\nquery FileStateKeyQuery($id: LrRelayIdInput!) {\n fileState(id: $id) {\n keyId\n }\n}\n`;\n","import { Injectable, Injector, NgZone } from '@angular/core';\nimport { JWK } from 'node-jose';\nimport { LrMutation, LrService } from '../api/lr-graphql';\nimport { ID, JSONObject, LinkTypeField, LrRelayIdInput } from '../api/types';\nimport { AuthService } from '../auth/auth.service';\nimport { FileUploadService } from '../file-upload/file-upload.service';\nimport { KeyFactoryService } from '../key/key-factory.service';\nimport { KeyGraphService } from '../key/key-graph.service';\nimport { KeyService } from '../key/key.service';\nimport { PayloadType } from '../key/key.types';\nimport { LockService } from '../lock/lock.service';\nimport { KcBadArgumentException } from '../_common/exceptions';\nimport { RunOutsideAngular } from '../_common/run-outside-angular';\nimport {\n ArchiveDirectoryMutation,\n ArchiveFileMutation,\n BeginDeleteChildItemLinksWindowMutation,\n ChangeDirectoryParentsMutation,\n ChangeFileParentsMutation,\n CreateDirectoryMutation,\n CreateFileMutation,\n DeleteDirectoryMutation,\n DeleteFileMutation,\n RevertFileMutation,\n SetDirectoryConfidentialMutation,\n SetFileConfidentialMutation,\n TempDirectoryQuery,\n UnarchiveDirectoryMutation,\n UnarchiveFileMutation,\n UpdateDirectoryMutation,\n UpdateFileMutation,\n} from './item.gql';\nimport {\n DirectoryKeyFromDirectoryShareQuery,\n DirectoryKeyQuery,\n FileKeyFromFileShareQuery,\n FileKeyQuery,\n FileStateKeyQuery,\n} from './item.gql.private';\nimport {\n ArchiveDirectoryOptions,\n BeginDeleteChildItemLinksWindowOptions,\n ChangeDirectoryParentsOptions,\n ChangeFileParentsOptions,\n ChangeItemParentsOptions,\n CreateDirectoryOptions,\n CreateDirectoryWithStagingOptions,\n CreateFileOptions,\n CreateFileWithStagingOptions,\n DownloadFileContentOptions,\n IdKeyPair,\n ParentDirectoryInput,\n ParentDirectoryOptions,\n ParentRootDirectoryInput,\n RevertFileOptions,\n SetDirectoryConfidentialOptions,\n SetFileConfidentialOptions,\n UnarchiveDirectoryOptions,\n UpdateDirectoryOptions,\n UpdateFileOptions,\n} from './item.types';\n\n@RunOutsideAngular({\n ngZoneName: 'ngZone',\n})\n@Injectable({\n providedIn: 'root',\n})\nexport class ItemService extends LrService {\n // Caching the temp directory.\n private tempDirectory: IdKeyPair = null;\n\n constructor(\n private ngZone: NgZone,\n private injector: Injector,\n private fileUploadService: FileUploadService,\n private keyService: KeyService,\n private keyFactory: KeyFactoryService,\n private keyGraph: KeyGraphService,\n private lockService: LockService,\n private authService: AuthService\n ) {\n super(injector);\n this.authService.addLogoutListener(() => this.onLogout());\n }\n\n static TEMP_DIRECTORY_PLAIN_META = { kcType: 'temp' };\n static TEMP_DIRECTORY_PLAIN_META_FILTER = JSON.stringify({\n filter: [\n {\n contains: ItemService.TEMP_DIRECTORY_PLAIN_META,\n },\n ],\n });\n\n async downloadFileContent(\n options: DownloadFileContentOptions\n ): Promise<Uint8Array> {\n const fileContent = await this.fileUploadService.downloadEncryptedFile(\n options.fileStateNodeId\n );\n\n const fileStateKey = await this.keyGraph.getKey(\n options.fileStateKeyId,\n () => this.getFileStateKeyId(options.fileStateNodeId)\n );\n\n return this.keyGraph.decryptFromString(fileStateKey, fileContent, {\n payloadType: PayloadType.UINT_8_ARRAY,\n });\n }\n\n async getDirectoryKeyId(directoryId: LrRelayIdInput) {\n return (\n await this.query({\n query: DirectoryKeyQuery,\n variables: {\n id: directoryId,\n },\n })\n ).directory.keyId;\n }\n\n async getFileKeyId(fileId: LrRelayIdInput) {\n return (\n await this.query({\n query: FileKeyQuery,\n variables: {\n id: fileId,\n },\n })\n ).file.keyId;\n }\n\n async getDirectoryKeyIdFromDirectoryShare(directoryShareId: LrRelayIdInput) {\n return (\n await this.query({\n query: DirectoryKeyFromDirectoryShareQuery,\n variables: {\n id: directoryShareId,\n },\n })\n ).directoryShare.item.keyId;\n }\n\n async getFileKeyIdFromFileShare(fileShareId: LrRelayIdInput) {\n return (\n await this.query({\n query: FileKeyFromFileShareQuery,\n variables: {\n id: fileShareId,\n },\n })\n ).fileShare.item.keyId;\n }\n\n async getDirectoryKey(\n directoryId: LrRelayIdInput,\n directoryKeyId?: LrRelayIdInput\n ) {\n return this.keyGraph.getKey(directoryKeyId, () =>\n this.getDirectoryKeyId(directoryId)\n );\n }\n\n async getFileKey(fileId: LrRelayIdInput, fileKeyId?: LrRelayIdInput) {\n return this.keyGraph.getKey(fileKeyId, () => this.getFileKeyId(fileId));\n }\n\n createDirectory(options: CreateDirectoryOptions) {\n return this.mutate(this.createDirectoryMutation(options));\n }\n\n async createDirectoryMutation(options: CreateDirectoryOptions) {\n return new LrMutation({\n mutation: CreateDirectoryMutation,\n variables: {\n input: await this.prepareCreateDirectory(options),\n },\n });\n }\n\n updateDirectory(options: UpdateDirectoryOptions) {\n return this.mutate(this.updateDirectoryMutation(options));\n }\n\n async updateDirectoryMutation(options: UpdateDirectoryOptions) {\n return new LrMutation({\n mutation: UpdateDirectoryMutation,\n variables: {\n input: await this.prepareUpdateDirectory(options),\n },\n });\n }\n\n deleteDirectory(id: ID) {\n return this.mutate(this.deleteDirectoryMutation(id));\n }\n\n deleteDirectoryMutation(id: ID) {\n return new LrMutation({\n mutation: DeleteDirectoryMutation,\n variables: {\n input: {\n directoryId: id,\n },\n },\n });\n }\n\n createFile(options: CreateFileOptions) {\n return this.mutate(this.createFileMutation(options));\n }\n\n async createFileMutation(options: CreateFileOptions) {\n return new LrMutation({\n mutation: CreateFileMutation,\n variables: {\n input: await this.prepareCreateFile(options),\n },\n });\n }\n\n updateFile(options: UpdateFileOptions) {\n return this.mutate(this.updateFileMutation(options));\n }\n\n async updateFileMutation(options: UpdateFileOptions) {\n return new LrMutation({\n mutation: UpdateFileMutation,\n variables: {\n input: await this.prepareUpdateFile(options),\n },\n });\n }\n\n revertFile(options: RevertFileOptions) {\n return this.mutate(this.revertFileMutation(options));\n }\n\n async revertFileMutation(options: RevertFileOptions) {\n return new LrMutation({\n mutation: RevertFileMutation,\n variables: {\n input: options,\n },\n });\n }\n\n deleteFile(id: ID) {\n return this.mutate(this.deleteFileMutation(id));\n }\n\n deleteFileMutation(id: ID) {\n return new LrMutation({\n mutation: DeleteFileMutation,\n variables: {\n input: {\n fileId: id,\n },\n },\n });\n }\n\n archiveDirectory(directoryId: string, options: ArchiveDirectoryOptions) {\n return this.mutate(this.archiveDirectoryMutation(directoryId, options));\n }\n\n archiveDirectoryMutation(\n directoryId: string,\n options: ArchiveDirectoryOptions\n ) {\n return new LrMutation({\n mutation: ArchiveDirectoryMutation,\n variables: {\n input: {\n directoryId,\n recursive: options.recursive,\n },\n },\n });\n }\n\n archiveFile(fileId: string) {\n return this.mutate(this.archiveFileMutation(fileId));\n }\n\n archiveFileMutation(fileId: string) {\n return new LrMutation({\n mutation: ArchiveFileMutation,\n variables: {\n input: {\n fileId,\n },\n },\n });\n }\n\n unarchiveDirectory(directoryId: string, options: UnarchiveDirectoryOptions) {\n return this.mutate(this.unarchiveDirectoryMutation(directoryId, options));\n }\n\n unarchiveDirectoryMutation(\n directoryId: string,\n options: UnarchiveDirectoryOptions\n ) {\n return new LrMutation({\n mutation: UnarchiveDirectoryMutation,\n variables: {\n input: {\n directoryId,\n recursive: options.recursive,\n },\n },\n });\n }\n\n unarchiveFile(fileId: string) {\n return this.mutate(this.unarchiveFileMutation(fileId));\n }\n\n unarchiveFileMutation(fileId: string) {\n return new LrMutation({\n mutation: UnarchiveFileMutation,\n variables: {\n input: {\n fileId,\n },\n },\n });\n }\n\n changeDirectoryParents(options: ChangeDirectoryParentsOptions) {\n return this.mutate(this.changeDirectoryParentsMutation(options));\n }\n\n async changeDirectoryParentsMutation(options: ChangeDirectoryParentsOptions) {\n return new LrMutation({\n mutation: ChangeDirectoryParentsMutation,\n variables: {\n input: await this.prepareChangeDirectoryParents(options),\n },\n });\n }\n\n async changeFileParents(options: ChangeFileParentsOptions) {\n return this.mutate(this.changeFileParentsMutation(options));\n }\n\n async changeFileParentsMutation(options: ChangeFileParentsOptions) {\n return new LrMutation({\n mutation: ChangeFileParentsMutation,\n variables: {\n input: await this.prepareChangeFileParents(options),\n },\n });\n }\n\n beginDeleteChildItemLinksWindow(\n options: BeginDeleteChildItemLinksWindowOptions\n ) {\n return this.mutate(this.beginDeleteChildItemLinksWindowMutation(options));\n }\n\n /**\n * Schedule cleanup of the hard links in a directory.\n * The server will delete all hard link within the directory within a time window: starting from now and\n * ending at requestWindowMs after now.\n * The server decides _when_ it will perform the delete. It's not guaranteed that it will perform\n * the delete at \"now + requestWindowMs\", but it will happen at some time after \"now + requestWindowMs\".\n * This allows multiple overlapping calls to this function and the server allocates enough for each request.\n * The server has a setting that allows for a maximum value on requestWindowMs. If the requested value\n * is larger than this maximum, the call will fail.\n */\n async beginDeleteChildItemLinksWindowMutation(\n options: BeginDeleteChildItemLinksWindowOptions\n ) {\n return new LrMutation({\n mutation: BeginDeleteChildItemLinksWindowMutation,\n variables: {\n input: options,\n },\n });\n }\n\n /**\n *\n * This method may raise VERSION_MISMATCH exception if there is a race condition\n * when multiple clients try to create the temp directory.\n *\n * TODO There is a retry mechanism in graphql with exponential back off but that's internal.\n * But need to use an exponential back off lib if we want to retry here.\n *\n * @returns The ID of the temp directory\n *\n */\n async ensureTempDirectory(): Promise<IdKeyPair> {\n if (this.tempDirectory) {\n return this.tempDirectory;\n }\n\n const existing = await this.query({\n query: TempDirectoryQuery,\n variables: {\n plainMeta: ItemService.TEMP_DIRECTORY_PLAIN_META_FILTER,\n },\n });\n\n if (existing.rootDirectories.edges.length > 1) {\n console.error(\n `There is more than 1 temp directory (plainMeta filter: ${ItemService.TEMP_DIRECTORY_PLAIN_META_FILTER})`\n );\n }\n\n if (existing.rootDirectories.edges.length === 0) {\n // Doesn't exist yet, create it\n const createDirectory = await this.createDirectoryMutation({\n asRootDirectory: true,\n plainMetaJson: ItemService.TEMP_DIRECTORY_PLAIN_META,\n });\n\n // Optimistic lock on the current user.\n const updateLock = this.lockService.updateLockMutation({\n version: existing.lock?.version,\n });\n\n // Because this.mutate() only handles simple types we need to use the more\n // advanced this.lrGraphQL.lrMutate()\n const [createDirectoryResult] = await this.lrGraphQL.lrMutate([\n createDirectory,\n updateLock,\n ]);\n\n const { id, keyId } = createDirectoryResult.createDirectory.directory;\n\n this.tempDirectory = {\n id,\n keyId,\n };\n } else {\n // Return existing temp\n const { id, keyId } = existing.rootDirectories.edges[0].node;\n\n this.tempDirectory = {\n id,\n keyId,\n };\n }\n\n return this.tempDirectory;\n }\n\n async createDirectoryWithStaging(options: CreateDirectoryWithStagingOptions) {\n return this.mutate(this.createDirectoryWithStagingMutation(options));\n }\n\n /**\n * You must run this mutation within the temp directory cleanup window on the\n * server, otherwise the temp directory will get cleaned up.\n *\n */\n async createDirectoryWithStagingMutation(\n options: CreateDirectoryWithStagingOptions\n ) {\n const tempDir = await this.ensureTempDirectory();\n\n // Clear the temp directory of the ones we are about to create.\n // NOTE: this mutation can not be merged into a single mutation with the\n // the createDirectory mutation because it uses the current server time to\n // clean up. So it must successfully complete before the creation of the\n // directories.\n await this.beginDeleteChildItemLinksWindow({\n directoryId: tempDir.id,\n requestWindowMs: options.requestWindowMs,\n });\n\n // Create the directory that has contents\n const directory = (\n await this.createDirectory({\n cipherMetaClearJson: options.cipherMetaClearJson,\n parentDirectories: [\n {\n directoryId: tempDir.id,\n wrappingKeyId: tempDir.keyId,\n },\n ],\n plainMetaJson: options.plainMetaJson,\n })\n ).createDirectory.directory;\n\n // Call back with item that's currently in staging.\n await options.onCreatedInStaging({\n id: directory.id,\n keyId: directory.keyId,\n });\n\n // TODO client-side check for timeout on requestWindowMs\n // TODO return the server time where delete is scheduled. Expirable mutation\n\n // Return the mutation that moves the directory into the dst directories\n return this.changeDirectoryParentsMutation({\n directoryId: directory.id,\n directoryKeyId: directory.keyId,\n parentsToRemove: [tempDir.id],\n parentsToAdd: options.parentDirectories,\n });\n }\n\n async createFileWithStaging(options: CreateFileWithStagingOptions) {\n return this.mutate(this.createFileWithStagingMutation(options));\n }\n\n async createFileWithStagingMutation(options: CreateFileWithStagingOptions) {\n const tempDir = await this.ensureTempDirectory();\n\n // Clear the temp directory of the ones we are about to create.\n // NOTE: this mutation can not be merged into a single mutation with the\n // the createDirectory mutation because it uses the current server time to\n // clean up. So it must successfully complete before the creation of the\n // directories.\n await this.beginDeleteChildItemLinksWindow({\n directoryId: tempDir.id,\n requestWindowMs: options.requestWindowMs,\n });\n\n // Create the file\n const file = (\n await this.createFile({\n ...options,\n parentDirectories: [\n {\n directoryId: tempDir.id,\n wrappingKeyId: tempDir.keyId,\n },\n ],\n })\n ).createFile.file;\n\n // Call back with item that's currently in staging.\n await options.onCreatedInStaging({\n id: file.id,\n keyId: file.keyId,\n });\n\n // TODO client-side check for timeout on requestWindowMs\n // TODO return the server time where delete is scheduled. Expirable mutation\n\n // Return the mutation that moves the directory into the dst directories\n return this.changeFileParentsMutation({\n fileId: file.id,\n fileKeyId: file.keyId,\n parentsToRemove: [tempDir.id],\n parentsToAdd: options.parentDirectories,\n });\n }\n\n async setFileConfidential(options: SetFileConfidentialOptions) {\n return this.mutate(this.setFileConfidentialMutation(options));\n }\n\n async setFileConfidentialMutation(options: SetFileConfidentialOptions) {\n return new LrMutation({\n mutation: SetFileConfidentialMutation,\n variables: {\n input: {\n fileId: options.fileId,\n confidential: options.confidential,\n },\n },\n });\n }\n\n async setDirectoryConfidential(options: SetDirectoryConfidentialOptions) {\n return this.mutate(this.setDirectoryConfidentialMutation(options));\n }\n\n async setDirectoryConfidentialMutation(\n options: SetDirectoryConfidentialOptions\n ) {\n return new LrMutation({\n mutation: SetDirectoryConfidentialMutation,\n variables: {\n input: {\n directoryId: options.directoryId,\n confidential: options.confidential,\n },\n },\n });\n }\n\n // ------------------------------------------------------------------------------\n // ------------------------------------------------------------------------------\n // Helpers\n // ------------------------------------------------------------------------------\n // ------------------------------------------------------------------------------\n\n private async prepareParentDirectory(\n options: ParentDirectoryOptions,\n newKey: JWK.Key\n ): Promise<ParentDirectoryInput> {\n const { directoryId, linkType, wrappingKeyId } = options;\n\n if (linkType == LinkTypeField.REFERENCE) {\n if (wrappingKeyId) {\n throw new KcBadArgumentException(\n 'Do not specify wrappingKeyId when link type is REFERENCE.'\n );\n }\n return {\n directoryId,\n linkType,\n };\n } else {\n // If directory's key is not already in the key graph, then need to\n // fetch the directory's key.\n const wrappingKey = await this.getDirectoryKey(\n directoryId,\n wrappingKeyId\n );\n\n return {\n directoryId,\n wrappingKeyId: wrappingKey.id,\n wrappedKey: await this.keyGraph.wrapKey(wrappingKey, newKey),\n linkType,\n };\n }\n }\n\n private async getFileStateKeyId(fileStateNodeId: LrRelayIdInput) {\n return (\n await this.query({\n query: FileStateKeyQuery,\n variables: {\n id: fileStateNodeId,\n },\n })\n ).fileState.keyId;\n }\n\n private async prepareCreateFileState(\n fileKey: JWK.Key,\n options: CreateFileOptions | UpdateFileOptions\n ) {\n // Each version of the file is encrypted using a new key.\n const fileStateKey = await this.keyFactory.createKey();\n\n const fileContent =\n options.file && (await this.fileUploadService.loadFile(options.file));\n\n let contentResource: string;\n if (fileContent) {\n const cipherFileContent = await this.keyGraph.encryptToString(\n fileStateKey,\n fileContent\n );\n if (options.upload) {\n contentResource = await options.upload(cipherFileContent);\n } else {\n contentResource = await this.fileUploadService.uploadEncryptedFile({\n encryptedContent: cipherFileContent,\n });\n }\n }\n\n return {\n ...(await this.prepareItem(fileStateKey, options)),\n wrappedStateKey: await this.keyGraph.wrapKey(fileKey, fileStateKey),\n contentResource,\n };\n }\n\n private async prepareChangeItemParents(\n options: ChangeItemParentsOptions,\n itemKey: JWK.Key\n ) {\n const parentsToAdd = options.parentsToAdd\n ? await Promise.all(\n options.parentsToAdd.map((t) =>\n this.prepareParentDirectory(t, itemKey)\n )\n )\n : [];\n\n return {\n directoriesToRemove: options.parentsToRemove || [],\n directoriesToAdd: parentsToAdd,\n };\n }\n\n private async prepareItem(\n key: JWK.Key,\n options: { plainMetaJson?: JSONObject; cipherMetaClearJson?: JSONObject }\n ) {\n const { plainMetaJson, cipherMetaClearJson } = options;\n\n return {\n plainMeta: plainMetaJson && JSON.stringify(plainMetaJson),\n cipherMeta:\n cipherMetaClearJson &&\n (await this.keyGraph.encryptToString(key, cipherMetaClearJson)),\n };\n }\n\n private async prepareCreateDirectory(options: CreateDirectoryOptions) {\n const directoryKey = await this.keyFactory.createKey();\n options.parentDirectories = options.parentDirectories || [];\n if (!options.asRootDirectory && !options.parentDirectories?.length) {\n throw new KcBadArgumentException(\n 'A new directory must be either a root directory or a sub-directory. So you must provide either parentDirectories or asRootDirectory parameter.'\n );\n }\n\n if (options.asRootDirectory && options.parentDirectories?.length) {\n throw new KcBadArgumentException(\n 'A new directory must be either a root directory or a sub-directory. So you can only provide either parentDirectories or asRootDirectory parameter.'\n );\n }\n\n const parentDirectories = await Promise.all(\n options.parentDirectories?.map((t) =>\n this.prepareParentDirectory(t, directoryKey)\n )\n );\n\n // TODO this is rather an unfortunate name, change it to asRootDirectory.\n let parentRootDirectory: ParentRootDirectoryInput;\n if (options.asRootDirectory) {\n const rootKey = this.keyService.currentRootKey;\n parentRootDirectory = {\n wrappingKeyId: rootKey.id,\n wrappedKey: await this.keyGraph.wrapKey(rootKey, directoryKey),\n };\n }\n\n const itemInput = await this.prepareItem(directoryKey, options);\n\n return {\n ...itemInput,\n parentDirectories,\n parentRootDirectory,\n };\n }\n\n private async prepareUpdateDirectory(options: UpdateDirectoryOptions) {\n const directoryKey = await this.getDirectoryKey(\n options.directoryId,\n options.directoryKeyId\n );\n\n const itemInput = await this.prepareItem(directoryKey.jwk, options);\n\n return {\n ...itemInput,\n directoryId: options.directoryId,\n };\n }\n\n private async prepareCreateFile(options: CreateFileOptions) {\n const fileKey = await this.keyFactory.createKey();\n\n const parentDirectories = await Promise.all(\n options.parentDirectories.map((t) =>\n this.prepareParentDirectory(t, fileKey)\n )\n );\n\n const input = await this.prepareCreateFileState(fileKey, options);\n\n return {\n ...input,\n parentDirectories,\n };\n }\n\n private async prepareUpdateFile(options: UpdateFileOptions) {\n const fileKey = await this.getFileKey(options.fileId, options.fileKeyId);\n const input = await this.prepareCreateFileState(fileKey.jwk, options);\n\n return {\n ...input,\n fileId: options.fileId,\n };\n }\n\n private async prepareChangeDirectoryParents(\n options: ChangeDirectoryParentsOptions\n ) {\n const directoryKey = await this.getDirectoryKey(\n options.directoryId,\n options.directoryKeyId\n );\n\n const input = await this.prepareChangeItemParents(\n options,\n directoryKey.jwk\n );\n\n return {\n ...input,\n directoryId: options.directoryId,\n };\n }\n\n private async prepareChangeFileParents(options: ChangeFileParentsOptions) {\n const fileKey = await this.getFileKey(options.fileId, options.fileKeyId);\n\n const input = await this.prepareChangeItemParents(options, fileKey.jwk);\n\n return {\n ...input,\n fileId: options.fileId,\n };\n }\n\n private onLogout() {\n // Clear all cached data.\n this.tempDirectory = null;\n }\n}\n","import { Injectable, Injector, NgZone } from '@angular/core';\nimport { JWK } from 'node-jose';\nimport { LrMutation, LrService } from '../api/lr-graphql';\nimport {\n ContactCardSharedCipherData,\n JSONObject,\n OtKeyCipherClearJson2,\n} from '../api/types';\nimport { OwnerPlainDataJson } from '../contact-card/contact-card2.service';\nimport {\n EncryptionService,\n JoseSerialization,\n} from '../encryption/encryption.service';\nimport { KeyFactoryService } from '../key/key-factory.service';\nimport { KeyGraphService } from '../key/key-graph.service';\nimport { KeyService } from '../key/key.service';\nimport { KcCodeMismatchException } from '../_common/exceptions';\nimport { RunOutsideAngular } from '../_common/run-outside-angular';\nimport {\n CancelKeyExchangeMutation,\n CompleteKeyExchangeOtkMutation,\n CurrentUserSharedKeyQuery2,\n DeclineKeyExchangeMutation,\n InitiateKeyExchangeOtkMutation,\n KeyExchangeFieldsResult,\n KeyExchangeQuery2,\n KeyExchangesQuery2,\n KeyExchangeState2,\n KeyExchangeTokenQuery2,\n RespondKeyExchangeOtkMutation,\n} from './key-exchange.gql';\n\n/**\n * The decrypted content of the one-time key cipher;\n * When user supplies this information the lib doesn't need to do another API call\n * to fetch the key exchange node. And since the typical use case is to display\n * some information to the user, the key exchange node would already have been\n * fetched and decrypted.\n */\nexport interface DecryptedOtk2 {\n otKeyCipherClearJson: OtKeyCipherClearJson2;\n otKey: JWK.Key; // The one-time key\n}\n\nexport interface ContactCardReceiverCipherData {\n // The receiver of the contact card keeps a copy\n // of the owner's contact card information, encrypted using the receiver's keys. So that when\n // the owner decides to update their shared contact card at a later date, the receiver can\n // compare against the original contact card sent during key exchange. This way, the owner\n // can't unilaterally update their shared contact card without the receiver knowing about it.\n receiverCipherDataClearJson: JSONObject;\n}\n\nexport interface ContactCardOwnerPlainData {\n // Accessible by the server and the owner. Server side notification emails need to know some\n // information about the owner.\n // The owner could either be the initiator or the responder.\n ownerPlainDataJson: OwnerPlainDataJson;\n}\n\nexport interface ContactCardOwnerCipherData {\n // Owner only access to this data\n ownerCipherDataClearJson: JSONObject;\n}\n\n/**\n * Sending contact card information from the owner to the receiver.\n */\nexport type SendContactCardInput = ContactCardOwnerPlainData &\n ContactCardOwnerCipherData &\n ContactCardSharedCipherData;\n\nexport interface InitiateOtkInput2 {\n // Note that if neither email nor responderUsername are given, the one-time key\n // can still be sent to the responder via OOB\n email?: string;\n message?: JSONObject;\n contactCard?: SendContactCardInput;\n // If True, to upgrade an email invite to an existing user invite if the email\n // is already associated with an existing user.\n upgrade?: boolean;\n}\n\nexport interface RespondOtkInput2 {\n keyExchangeId: string;\n token: string;\n decryptedOtk: DecryptedOtk2;\n message?: JSONObject;\n // The initiator is the owner fo the initiatorContactCard, the responder\n // is the receiver.\n initiatorContactCard?: ContactCardReceiverCipherData;\n responderContactCard?: SendContactCardInput;\n}\n\nexport interface CompleteOtkInput2 {\n keyExchangeId: string;\n // This is a part of the key exchange data. It's encrypted using the root key\n initiatorRootKeyCipher: string;\n // This is a part of the key exchange data. It's encrypted using the one-time key.\n initiatorOneTimePbkCipher: string;\n // The responder is the owner fo the responderContactCard, the initiator\n // is the receiver.\n responderContactCard?: ContactCardReceiverCipherData;\n // The initiator can update the cipher data that are only visible to them. It makes\n // less sense to update the shared data because the responder would have already seen\n // the shared data and accepted that it's legit.\n // But in any case, the initiator can update the shared contact card info at any time.\n initiatorContactCard?: ContactCardOwnerCipherData;\n}\n\nexport interface InitiatorRootKeyCipherClearJson2 {\n nonce: string;\n oneTimePrk: Record<string, JSONObject>; // one-time public encryption key responder use to send data back to initiator\n otKey: Record<string, JSONObject>; // one-time symmetric key that needs to be shared OOB\n initiatorContactCard?: ContactCardOwnerCipherData &\n ContactCardSharedCipherData;\n initiator: {\n message?: JSONObject;\n contactCard?: ContactCardSharedCipherData;\n };\n}\n\nexport interface InitiatorOneTimePbkCipherClearJson {\n nonce: string;\n sharedKey: Record<string, JSONObject>;\n mkSharedKey: Record<string, JSONObject>;\n responder: {\n pbk: Record<string, JSONObject>;\n sigPbk: Record<string, JSONObject>;\n message?: JSONObject;\n contactCard?: ContactCardSharedCipherData & {\n // Note that this is _not_ the same key as the sharedKey. The sharedKey wraps\n // this key in the key graph. But because this key has not been entered into\n // the key graph when the responder calls the API, we pass the JWK directly here.\n sharedCipherKey: Record<string, JSONObject>;\n };\n };\n}\n\nexport interface GetKeyExchangeOptions2 {\n // The otKey as a raw string. i.e. key.toJSON(true).k\n otKeyK?: string;\n // User need the token if they have not responded to the key exchange yet.\n // Once they've responded (hence proven they have the OOB Key) they become\n // the \"responder\" of this exchange, and can access it when signed in.\n token?: string;\n}\n\n@RunOutsideAngular({\n ngZoneName: 'ngZone',\n})\n@Injectable({\n providedIn: 'root',\n})\nexport class KeyExchangeService extends LrService {\n private readonly CLIENT_NONCE_LENGTH = 32;\n\n constructor(\n private ngZone: NgZone,\n private injector: Injector,\n private keyFactory: KeyFactoryService,\n private keyService: KeyService,\n private encryptionService: EncryptionService,\n private keyGraph: KeyGraphService\n ) {\n super(injector);\n }\n\n private async getOtKey(\n keyExchange: KeyExchangeFieldsResult,\n otKeyK?: string\n ): Promise<JWK.Key> {\n if (otKeyK) {\n return await KeyFactoryService.asKey({\n ...JSON.parse(keyExchange.otk.otKeyParams),\n k: otKeyK,\n });\n } else if (\n keyExchange.otk.state === 'OTK_INITIATED' &&\n !keyExchange.isInitiator &&\n keyExchange.otk.responderPbkCipher\n ) {\n // Assuming existing user getting invited where OTK is wrapped in responder's public key.\n const prk = this.keyService.currentPxk;\n const decryptedCipher = await this.encryptionService.decrypt(\n prk.jwk,\n JSON.parse(keyExchange.otk.responderPbkCipher),\n {\n serializations: [JoseSerialization.COMPACT],\n }\n );\n if (decryptedCipher.otKey) {\n return await KeyFactoryService.asKey(decryptedCipher.otKey);\n }\n }\n return null;\n }\n\n private async decryptOtk(\n keyExchange: KeyExchangeFieldsResult,\n otKeyK?: string\n ): Promise<KeyExchangeFieldsResult> {\n const otKey = await this.getOtKey(keyExchange, otKeyK);\n\n let otk = keyExchange.otk;\n\n if (otKey && otk.otKeyCipher) {\n otk = {\n ...otk,\n otKey,\n otKeyCipherClearJson: await this.encryptionService.decrypt(\n otKey,\n keyExchange.otk.otKeyCipher\n ),\n };\n }\n\n return {\n ...keyExchange,\n otk,\n };\n }\n\n private async decryptResponseCipher(\n otKey: JWK.Key,\n otPrk: JWK.Key,\n content: JSONObject\n ): Promise<InitiatorOneTimePbkCipherClearJson> {\n // The response could be wrapped by the OtK in addition to the OtPbk\n try {\n content = await this.encryptionService.decrypt(otKey, content);\n } catch (error) {\n if (error.message !== 'no key found') {\n throw error;\n }\n // Do nothing to support older versions where message is not wrapped with otk.\n }\n\n // The Prk is single-use and only used to send information from the responder back to the initiator.\n return await this.encryptionService.decrypt(otPrk, content);\n }\n\n private async decryptKeyExchangeAsInitiator(\n keyExchange: KeyExchangeFieldsResult\n ): Promise<KeyExchangeFieldsResult> {\n const rootKey = this.keyService.currentRootKey;\n\n // Decrypt using the root key to get the Prk\n const initiatorRootKeyCipherClearJson =\n (await this.encryptionService.decrypt(\n rootKey.jwk,\n keyExchange.initiatorRootKeyCipher\n )) as InitiatorRootKeyCipherClearJson2;\n\n const otKey = await KeyFactoryService.asKey(\n initiatorRootKeyCipherClearJson.otKey\n );\n\n keyExchange = {\n ...keyExchange,\n initiatorRootKeyCipherClearJson,\n };\n\n let otk = keyExchange.otk;\n\n if (otk.initiatorOneTimePbkCipher) {\n otk = {\n ...otk,\n initiatorOneTimePbkCipherClearJson: await this.decryptResponseCipher(\n otKey,\n await KeyFactoryService.asKey(\n initiatorRootKeyCipherClearJson.oneTimePrk\n ),\n otk.initiatorOneTimePbkCipher\n ),\n };\n }\n\n if (otk.otKeyCipher) {\n otk.otKeyCipherClearJson = await this.encryptionService.decrypt(\n otKey,\n otk.otKeyCipher\n );\n }\n\n return {\n ...keyExchange,\n otk,\n };\n }\n\n private async decryptKeyExchangeAsResponder(\n keyExchange: KeyExchangeFieldsResult,\n otKeyK?: string\n ) {\n return this.decryptOtk(keyExchange, otKeyK);\n }\n\n async decryptKeyExchange(\n keyExchange: KeyExchangeFieldsResult,\n otKeyK?: string\n ) {\n if (keyExchange.isInitiator) {\n return this.decryptKeyExchangeAsInitiator(keyExchange);\n } else {\n return this.decryptKeyExchangeAsResponder(keyExchange, otKeyK);\n }\n }\n\n async getKeyExchanges({ state }: { state?: KeyExchangeState2 } = {}) {\n const { keyExchanges } = await this.query({\n query: KeyExchangesQuery2,\n variables: {\n state,\n },\n });\n\n return Promise.all(\n keyExchanges.edges.map((edge) => this.decryptKeyExchange(edge.node))\n );\n }\n\n /**\n * @param id If the current user can responder the key exchange if they are either the initiator or the receiver.\n * @param token If not signed in, or not the initiator or responder, 'token' must be given.\n * @param otKeyK Is the raw one-time key (string). If the responder is explicitly specified at time of initiation, then\n * it's possible to have the otKey wrapped by the public key of the responder. In which case, the otKeyK is not needed.\n */\n async getKeyExchange(\n id: string,\n { otKeyK, token }: GetKeyExchangeOptions2 = {}\n ) {\n const res = await this.query({\n query: token ? KeyExchangeTokenQuery2 : KeyExchangeQuery2,\n variables: {\n id,\n token,\n },\n includeKeyGraph: !token, // if !token then we are post auth, so can fetch keyGraph\n });\n return this.decryptKeyExchange(res.keyExchange, otKeyK);\n }\n\n public async getCurrentUserSharedKey(input: {\n username?: string;\n userId?: string;\n }) {\n return this.query({\n query: CurrentUserSharedKeyQuery2,\n variables: {\n username: input.username,\n userId: input.userId,\n },\n });\n }\n\n cancelKeyExchange(id: string) {\n return this.mutate(this.cancelKeyExchangeMutation(id));\n }\n\n cancelKeyExchangeMutation(id: string) {\n return new LrMutation({\n mutation: CancelKeyExchangeMutation,\n variables: {\n input: {\n id,\n },\n },\n });\n }\n\n declineKeyExchange(id: string, token: string) {\n return this.mutate(this.declineKeyExchangeMutation(id, token));\n }\n\n declineKeyExchangeMutation(id: string, token: string) {\n return new LrMutation({\n mutation: DeclineKeyExchangeMutation,\n variables: {\n input: {\n id,\n token,\n },\n },\n });\n }\n\n async initiateOtk(input: InitiateOtkInput2 = {}) {\n return this.mutate((await this.initiateOtkMutation(input)).lrMutation);\n }\n\n async initiateOtkMutation({\n message,\n email,\n contactCard,\n upgrade,\n }: InitiateOtkInput2 = {}) {\n const otKey = await this.keyFactory.createKey();\n const nonce = this.keyFactory.randomString(this.CLIENT_NONCE_LENGTH);\n\n // New PKC key for encryption. This key is used only once when the responder sends\n // back their signing public key.\n const initiatorOneTimePrk = await this.keyFactory.createPkcKey();\n\n // Option 1: New PKC key for signing\n // const initiatorSigPrk = await this.keyService.createPkcSignKey();\n\n // Option 2: Use the user's global signing key.\n // This key is used to prove the initiator's identity.\n const initiatorPrk = this.keyService.currentPxk;\n const initiatorSigPrk = this.keyService.currentSigPxk;\n\n let initiatorPlainDataSig: string = null;\n\n if (contactCard && contactCard.ownerPlainDataJson) {\n initiatorPlainDataSig = await this.encryptionService.signToString(\n initiatorSigPrk.jwk,\n contactCard.ownerPlainDataJson\n );\n }\n\n const initiator = {\n message,\n contactCard: contactCard && {\n sharedCipherDataClearJson: contactCard.sharedCipherDataClearJson,\n },\n };\n\n // Content to be encrypted using the OTK.\n const plainOtKeyCipher: OtKeyCipherClearJson2 = {\n // TODO Make sure we also put the OOB code in here as well since the OOB code is the\n // _only_ information the KC server does not have access to. The server may have\n // access to OTK and hence the nonce here. It's good to have both the nonce and OOB code\n // since the user may not be using the OOB code. And it's simple to always include\n // the nonce, so why not.\n nonce,\n initiator: {\n ...initiator,\n oneTimePbk: initiatorOneTimePrk.toJSON(), // one-time public encryption key responder use to send data back to initiator\n pbk: initiatorPrk.jwk.toJSON(), // public encryption key\n sigPbk: initiatorSigPrk.jwk.toJSON(), // public signing key\n },\n };\n\n const otKeyCipher = await this.keyGraph.encryptToString(\n otKey,\n plainOtKeyCipher\n );\n\n // Content to be encrypted using the initiator's root key.\n const initiatorRootKeyCipherClearJson: InitiatorRootKeyCipherClearJson2 = {\n nonce,\n oneTimePrk: initiatorOneTimePrk.toJSON(true),\n // Should not need to keep this encrypted since we are using the global signing key.\n // sigPrk: initiatorSigPrk.toJSON(true),\n\n // Save it in case the initiator want to decode the otKeyCipher.\n // Since the otKey is only used once, and that otKeyCipher contains only\n // the public key of the initiator, it's safe just leave the otKey stored here.\n otKey: otKey.toJSON(true),\n // These should be storing information such as how the fields of the shared contact card is\n // derived from the master contact card.\n initiatorContactCard: contactCard,\n initiator,\n };\n\n const rootKey = this.keyService.currentRootKey;\n const initiatorRootKeyCipher = await this.keyGraph.encryptToString(\n rootKey.jwk,\n initiatorRootKeyCipherClearJson\n );\n\n // The raw OTK\n const otKeyK: string = (otKey.toJSON(true) as JSONObject).k;\n\n // API call\n const lrMutation = new LrMutation({\n mutation: InitiateKeyExchangeOtkMutation,\n variables: {\n input: {\n // These will be stored on the server\n initiatorRootKeyCipher,\n initiatorPxkId: initiatorPrk.id,\n initiatorSigPxkId: initiatorSigPrk.id,\n // These will be sent to the responder\n otKeyParams: JSON.stringify(otKey.toJSON()),\n otKeyCipher,\n sendEmail: email && {\n email,\n rawOtKey: otKeyK,\n },\n createTp: true,\n initiatorPlainDataSig,\n upgrade,\n },\n },\n });\n\n return { lrMutation, otKeyK };\n }\n\n respondOtk(input: RespondOtkInput2) {\n return this.mutate(this.respondOtkMutation(input));\n }\n\n async respondOtkMutation({\n keyExchangeId,\n token,\n decryptedOtk,\n message,\n initiatorContactCard,\n responderContactCard,\n }: RespondOtkInput2) {\n const rootKey = this.keyService.currentRootKey;\n\n const masterKey = this.keyService.currentMasterKey;\n\n const sharedKey = await this.keyFactory.createKey();\n const mkSharedKey = await this.keyFactory.createKey();\n\n const rkWrappedSharedKey = await this.encryptionService.encrypt(\n rootKey.jwk,\n sharedKey.toJSON(true)\n );\n const mkWrappedMkSharedKey = await this.encryptionService.encrypt(\n masterKey.jwk,\n mkSharedKey.toJSON(true)\n );\n\n const initiatorOneTimePbk = await KeyFactoryService.asKey(\n decryptedOtk.otKeyCipherClearJson.initiator.oneTimePbk\n );\n\n const initiatorPbk = await KeyFactoryService.asKey(\n decryptedOtk.otKeyCipherClearJson.initiator.pbk\n );\n const initiatorSigPbk = await KeyFactoryService.asKey(\n decryptedOtk.otKeyCipherClearJson.initiator.sigPbk\n );\n\n // Option 1: Using new Prk for each TP pair\n // Create a new public signing key for the responder.\n // const responderSigPrk = await this.keyService.createPkcSignKey()\n // const rkWrappedResponderSigPrk = await this.encrypt(rootKey, responderSigPrk.toJSON(true));\n\n // Option 2: Responder already has a signing Prk\n const responderPrk = this.keyService.currentPxk;\n const responderSigPrk = this.keyService.currentSigPxk;\n\n const signedInitiatorPbk = await this.encryptionService.sign(\n responderSigPrk.jwk,\n initiatorPbk.toJSON()\n );\n const signedInitiatorSigPbk = await this.encryptionService.sign(\n responderSigPrk.jwk,\n initiatorSigPbk.toJSON()\n );\n\n const initiatorOneTimePbkCipherClearJson: InitiatorOneTimePbkCipherClearJson =\n {\n nonce: decryptedOtk.otKeyCipherClearJson.nonce,\n sharedKey: sharedKey.toJSON(true),\n mkSharedKey: mkSharedKey.toJSON(true),\n responder: {\n pbk: responderPrk.jwk.toJSON(), // public key\n sigPbk: responderSigPrk.jwk.toJSON(), // public key\n message,\n },\n };\n\n let receivedCardInput;\n if (decryptedOtk.otKeyCipherClearJson.initiator.contactCard) {\n // Set the info about the initiator to be the ones sent by the initiator. We need th responder to do the encryption here\n // because the initiator does not have the shared key yet, and we want the responder to have a functional contact card after\n // this exchange. The initiator can double check the contact details are correct and sign it when it completes the exchange.\n const sharedCipherDataClearJson =\n decryptedOtk.otKeyCipherClearJson.initiator.contactCard\n .sharedCipherDataClearJson;\n\n // Create keys\n const receiverKey = await this.keyFactory.createKey();\n const ccSharedKey = await this.keyFactory.createKey();\n const sigPxk = this.keyService.currentSigPxk;\n\n receivedCardInput = {\n receiverWrappedKey: JSON.stringify(\n await this.encryptionService.encrypt(\n rootKey.jwk,\n receiverKey.toJSON(true)\n )\n ),\n receiverWrappingKeyId: rootKey.id,\n receiverCipherData: initiatorContactCard\n ? JSON.stringify(\n await this.encryptionService.encrypt(\n receiverKey,\n initiatorContactCard.receiverCipherDataClearJson\n )\n )\n : '',\n sharedWrappedKey: JSON.stringify(\n await this.encryptionService.encrypt(\n sharedKey,\n ccSharedKey.toJSON(true)\n )\n ),\n };\n\n const sharedCipherData = await this.encryptionService.encrypt(\n ccSharedKey,\n sharedCipherDataClearJson\n );\n receivedCardInput.sharedCipherDataSig = JSON.stringify(\n await this.encryptionService.sign(sigPxk.jwk, sharedCipherData)\n );\n receivedCardInput.sigPxkId = sigPxk.id;\n\n initiatorOneTimePbkCipherClearJson.responder.contactCard = {\n ...initiatorOneTimePbkCipherClearJson.responder.contactCard,\n sharedCipherKey: ccSharedKey.toJSON(true),\n };\n }\n\n let responderCardInput;\n if (responderContactCard) {\n // Create keys\n const ownerKey = await this.keyFactory.createKey();\n const ccSharedKey = await this.keyFactory.createKey();\n const sigPxk = this.keyService.currentSigPxk;\n\n responderCardInput = {\n ownerWrappedKey: JSON.stringify(\n await this.encryptionService.encrypt(\n rootKey.jwk,\n ownerKey.toJSON(true)\n )\n ),\n ownerWrappingKeyId: rootKey.id,\n ownerCipherData: responderContactCard.ownerCipherDataClearJson\n ? JSON.stringify(\n await this.encryptionService.encrypt(\n ownerKey,\n responderContactCard.ownerCipherDataClearJson\n )\n )\n : '',\n\n sharedWrappedKey: JSON.stringify(\n await this.encryptionService.encrypt(\n sharedKey,\n ccSharedKey.toJSON(true)\n )\n ),\n };\n\n const sharedCipherData = await this.encryptionService.encrypt(\n ccSharedKey,\n responderContactCard.sharedCipherDataClearJson\n );\n responderCardInput.sharedCipherDataSig = JSON.stringify(\n await this.encryptionService.sign(sigPxk.jwk, sharedCipherData)\n );\n responderCardInput.sigPxkId = sigPxk.id;\n\n if (responderContactCard.ownerPlainDataJson) {\n responderCardInput.ownerPlainDataSig = JSON.stringify(\n await this.encryptionService.sign(\n responderSigPrk.jwk,\n responderContactCard.ownerPlainDataJson\n )\n );\n }\n\n // Contact card info readable by the initiator\n initiatorOneTimePbkCipherClearJson.responder.contactCard = {\n ...initiatorOneTimePbkCipherClearJson.responder.contactCard,\n sharedCipherDataClearJson:\n responderContactCard.sharedCipherDataClearJson,\n };\n }\n\n // Encrypt with one-time public key\n let initiatorOneTimePbkCipher = await this.encryptionService.encrypt(\n initiatorOneTimePbk,\n initiatorOneTimePbkCipherClearJson\n );\n\n // Encrypt with the otk again to keep use of asymmetric keys to a minimum.\n initiatorOneTimePbkCipher = await this.encryptionService.encrypt(\n decryptedOtk.otKey,\n initiatorOneTimePbkCipher\n );\n\n return new LrMutation({\n mutation: RespondKeyExchangeOtkMutation,\n variables: {\n input: {\n keyExchangeId,\n keyExchangeToken: token,\n rootKeyId: rootKey.id,\n masterKeyId: masterKey.id,\n // These will be stored on the server\n responderPxkId: responderPrk.id,\n responderSigPxkId: responderSigPrk.id,\n signedInitiatorPbk: JSON.stringify(signedInitiatorPbk),\n signedInitiatorSigPbk: JSON.stringify(signedInitiatorSigPbk),\n // rkWrappedInitiatorSigPbk: JSON.stringify(rkWrappedInitiatorSigPbk),\n\n // Option 1: Using new Prk for each TP pair\n // rkWrappedResponderSigPrk: JSON.stringify(rkWrappedResponderSigPrk),\n rkWrappedSharedKey: JSON.stringify(rkWrappedSharedKey),\n mkWrappedMkSharedKey: JSON.stringify(mkWrappedMkSharedKey),\n // These will be sent to the initiator\n initiatorOneTimePbkCipher: JSON.stringify(initiatorOneTimePbkCipher),\n initiatorContactCard: receivedCardInput,\n responderContactCard: responderCardInput,\n },\n },\n });\n }\n\n completeOtk(input: CompleteOtkInput2) {\n return this.mutate(this.completeOtkMutation(input));\n }\n\n async completeOtkMutation({\n keyExchangeId,\n initiatorRootKeyCipher,\n initiatorOneTimePbkCipher,\n responderContactCard,\n initiatorContactCard,\n }: CompleteOtkInput2) {\n const rootKey = this.keyService.currentRootKey;\n const masterKey = this.keyService.currentMasterKey;\n\n // Decrypt using the root key to get the Prk\n const initiatorRootKeyCipherClearJson =\n (await this.encryptionService.decrypt(\n rootKey.jwk,\n initiatorRootKeyCipher\n )) as InitiatorRootKeyCipherClearJson2;\n\n // The Prk is single-use and only used to send information from the responder back to the initiator.\n const plainInitiatorOneTimePbkCipher = await this.decryptResponseCipher(\n await KeyFactoryService.asKey(initiatorRootKeyCipherClearJson.otKey),\n await KeyFactoryService.asKey(initiatorRootKeyCipherClearJson.oneTimePrk),\n initiatorOneTimePbkCipher\n );\n\n // Check the nonce match to ensure the responder was the one holding the OTK\n if (\n initiatorRootKeyCipherClearJson.nonce !==\n plainInitiatorOneTimePbkCipher.nonce\n ) {\n throw new KcCodeMismatchException(\n 'The nonce returned by responder does not match with the one created by the initiator.'\n );\n }\n\n // Option 1: Assuming the signing key is unique between users.\n // const initiatorSigPrk = await KFS.asKey(ke.plainInitiatorRootKeyCipher.sigPrk);\n // const rkWrappedInitiatorSigPrk = await this.encrypt(rootKey, initiatorSigPrk.toJSON(true));\n\n // Option 2: Use the user's global signing key.\n // In this case the initiatorSigPrk is already a part of the key graph.\n // So there's nothing to do here.\n\n // Protected the signing public key of the responder.\n const initiatorSigPrk = this.keyService.currentSigPxk;\n const responderSigPbk = await KeyFactoryService.asKey(\n plainInitiatorOneTimePbkCipher.responder.sigPbk\n );\n const responderPbk = await KeyFactoryService.asKey(\n plainInitiatorOneTimePbkCipher.responder.pbk\n );\n\n const signedResponderPbk = await this.encryptionService.sign(\n initiatorSigPrk.jwk,\n responderPbk.toJSON()\n );\n const signedResponderSigPbk = await this.encryptionService.sign(\n initiatorSigPrk.jwk,\n responderSigPbk.toJSON()\n );\n\n const sharedKey = await KeyFactoryService.asKey(\n plainInitiatorOneTimePbkCipher.sharedKey\n );\n const rkWrappedSharedKey = await this.encryptionService.encrypt(\n rootKey.jwk,\n sharedKey.toJSON(true)\n );\n\n const mkSharedKey = await KeyFactoryService.asKey(\n plainInitiatorOneTimePbkCipher.mkSharedKey\n );\n const mkWrappedMkSharedKey = await this.encryptionService.encrypt(\n masterKey.jwk,\n mkSharedKey.toJSON(true)\n );\n\n let responderContactCardCipherInput;\n if (responderContactCard) {\n // Create key\n const receiverKey = await this.keyFactory.createKey();\n\n responderContactCardCipherInput = {\n receiverWrappedKey: JSON.stringify(\n await this.encryptionService.encrypt(\n rootKey.jwk,\n receiverKey.toJSON(true)\n )\n ),\n receiverWrappingKeyId: rootKey.id,\n receiverCipherData: JSON.stringify(\n await this.encryptionService.encrypt(\n receiverKey,\n responderContactCard.receiverCipherDataClearJson\n )\n ),\n };\n }\n\n // Get the data needed from the initiator's cipher data.\n let initiatorContactCardCipherInput;\n let initiatorContactCardSharedCipherInput;\n if (initiatorRootKeyCipherClearJson.initiatorContactCard) {\n // The initiatorContactCard created during the creation of the invite and encrypted using the initiator's\n // root key\n const initiatorContactCardFromInit =\n initiatorRootKeyCipherClearJson.initiatorContactCard;\n const ownerKey = await this.keyFactory.createKey();\n const sharedCipherKey = await KeyFactoryService.asKey(\n plainInitiatorOneTimePbkCipher.responder.contactCard.sharedCipherKey\n );\n\n const ownerWrappedKey = JSON.stringify(\n await this.encryptionService.encrypt(rootKey.jwk, ownerKey.toJSON(true))\n );\n\n // Allow the initiatorContactCard parameter to override\n const ownerCipherDataClearJson =\n initiatorContactCard?.ownerCipherDataClearJson ||\n initiatorContactCardFromInit.ownerCipherDataClearJson;\n\n const ownerCipherData = ownerCipherDataClearJson\n ? await this.keyGraph.encryptToString(\n ownerKey,\n ownerCipherDataClearJson\n )\n : '';\n\n initiatorContactCardCipherInput = {\n ownerWrappedKey,\n ownerWrappingKeyId: rootKey.id,\n ownerCipherData,\n };\n\n initiatorContactCardSharedCipherInput = {\n sigPxkId: initiatorSigPrk.id,\n };\n\n const sharedCipherData = await this.encryptionService.encrypt(\n sharedCipherKey,\n initiatorContactCardFromInit.sharedCipherDataClearJson\n );\n initiatorContactCardSharedCipherInput.sharedCipherDataSig =\n JSON.stringify(\n await this.encryptionService.sign(\n initiatorSigPrk.jwk,\n sharedCipherData\n )\n );\n }\n\n // TODO ideally we update the shared data in the contact card sent to the responder as well since that\n // CC was created by the responder.\n\n return new LrMutation({\n mutation: CompleteKeyExchangeOtkMutation,\n variables: {\n input: {\n keyExchangeId,\n rootKeyId: rootKey.id,\n masterKeyId: masterKey.id,\n initiatorSigPxkId: initiatorSigPrk.id,\n signedResponderPbk: JSON.stringify(signedResponderPbk),\n signedResponderSigPbk: JSON.stringify(signedResponderSigPbk),\n rkWrappedSharedKey: JSON.stringify(rkWrappedSharedKey),\n mkWrappedMkSharedKey: JSON.stringify(mkWrappedMkSharedKey),\n responderContactCardCipher: responderContactCardCipherInput,\n initiatorContactCardCipher: initiatorContactCardCipherInput,\n initiatorContactCardSharedCipher:\n initiatorContactCardSharedCipherInput,\n },\n },\n });\n }\n}\n","/* eslint-disable @typescript-eslint/no-explicit-any */\nimport { HttpClient } from '@angular/common/http';\nimport { Inject, Injectable } from '@angular/core';\nimport { AuthClass } from '@aws-amplify/auth/lib-esm/Auth';\nimport gql from 'graphql-tag';\nimport { JWK } from 'node-jose';\nimport { Slip39Helper } from 'slip39';\nimport { LrApolloService } from '../api/lr-apollo.service';\nimport { EncryptionService } from '../encryption/encryption.service';\nimport { KeyFactoryService as KFS } from '../key/key-factory.service';\nimport { KeyService } from '../key/key.service';\nimport { PassKeyParams } from '../key/key.types';\nimport { KcConfig, KC_CONFIG } from '../life-ready.config';\nimport { PasswordService } from '../password/password.service';\nimport {\n KcBadLogicException,\n KcError,\n KcException,\n KcInternalErrorException,\n} from '../_common/exceptions';\n\nexport const ERROR_SOURCE = 'LBOP';\nexport enum KcLbopErrorCode {\n INVALID_PASSPHRASE = 'INVALID_PASSPHRASE',\n}\n\ninterface SetPasswordApiResult {\n username: string;\n idpPassword: string;\n setPasswordToken: string;\n}\n\nexport interface SetPasswordParams {\n lbopId: string;\n newPassword: CryptoKey;\n verifiedToken: string;\n masterKeyId: string;\n masterKey: JWK.Key;\n}\n\nexport interface VerifyContactParams {\n email?: string;\n phone?: string;\n}\n\nexport interface VerifyContactResult {\n // The claim_id identifies the Email/SMS confirmation\n claimId: string;\n}\n\nexport interface ConfirmContactParams {\n claimId: string;\n vCode: string;\n}\n\nexport interface ConfirmContactResult {\n // The token to prove the client had the correct confirmation code.\n token: string;\n}\n\nexport interface VerifyParams {\n claimId: string;\n claimToken: string;\n lbop: string;\n}\n\nexport interface VerifyResult {\n // userId: string;\n lbopId: string;\n verifiedToken: string;\n masterKeyId: string;\n masterKey: JWK.Key;\n}\n\nexport interface ChallengeResultLbop {\n lbopId: string;\n lbopKeyParams: PassKeyParams;\n wrappedLbopKeyVerifier: any;\n}\n\nexport interface ChallengeResult {\n challenge: {\n serverNonce: string;\n };\n lbops: ChallengeResultLbop[];\n}\n\nexport interface Lbop {\n id: string;\n partial?: string;\n name?: string;\n lbopString?: string;\n}\n\nexport interface CreateLbopParams {\n name?: string;\n}\n\ninterface CreateLbopQuery {\n createLbop: {\n lbop: Lbop;\n };\n}\n\nexport const CreateLbopQuery = gql`\n mutation CreateLbop($input: CreateLbopInput!) {\n createLbop(input: $input) {\n lbop {\n id\n }\n }\n }\n`;\n\ninterface DeleteLbopQuery {\n deleteLbop: Lbop;\n}\n\nexport const DeleteLbopQuery = gql`\n mutation DeleteLbop($input: DeleteLbopInput!) {\n deleteLbop(input: $input) {\n id\n }\n }\n`;\n\nexport interface UpdateLbopParams {\n id: string;\n name: string;\n}\n\ninterface UpdateLbopQuery {\n updateLbop: Lbop;\n}\n\nexport const UpdateLbopQuery = gql`\n mutation UpdateLbop($input: UpdateLbopInput!) {\n updateLbop(input: $input) {\n lbop {\n id\n }\n }\n }\n`;\n\nexport const LbopQuery = gql`\n query Lbop($id: LrRelayIdInput!) {\n lbop(id: $id) {\n id\n cipherMeta\n }\n }\n`;\n\ninterface LbopsQuery {\n lbops: any;\n}\n\nexport const LbopsQuery = gql`\n query Lbops {\n lbops {\n edges {\n node {\n id\n cipherMeta\n }\n }\n }\n }\n`;\n\n@Injectable({\n providedIn: 'root',\n})\nexport class LbopService {\n private readonly CLIENT_NONCE_LENGTH = 32;\n // There are 1024 words (10 bits), so 25 words should give ~256 bits of entropy.\n private readonly LBOP_WORDS = 25;\n\n constructor(\n @Inject(KC_CONFIG) private config: KcConfig,\n private http: HttpClient,\n private lrApollo: LrApolloService,\n private auth: AuthClass,\n private keyFactory: KFS,\n private keyService: KeyService,\n private encryptionService: EncryptionService,\n private passwordService: PasswordService\n ) {}\n\n private getPartial(lbopString: string): string {\n return lbopString.split(' ')[0];\n }\n\n public async remove(id: string): Promise<string> {\n const res = await this.lrApollo.mutate<any>({\n mutation: DeleteLbopQuery,\n variables: {\n input: {\n id,\n },\n },\n });\n\n return res.deleteLbop.id;\n }\n\n public async update({ id, name }: UpdateLbopParams): Promise<Lbop> {\n const lbop = await this.get(id);\n lbop.name = name;\n\n const masterKey = this.keyService.currentMasterKey;\n const cipherMeta = await this.encryptionService.encrypt(\n masterKey.jwk,\n lbop\n );\n\n const res = await this.lrApollo.mutate<UpdateLbopQuery>({\n mutation: UpdateLbopQuery,\n variables: {\n input: {\n id,\n cipherMeta: JSON.stringify(cipherMeta),\n },\n },\n });\n\n return res.updateLbop;\n }\n\n public async get(id: string): Promise<Lbop> {\n const res = await this.lrApollo.query<any>({\n query: LbopQuery,\n variables: {\n id,\n },\n });\n\n const masterKey = this.keyService.currentMasterKey;\n\n const plainCipherMeta = await this.encryptionService.decrypt(\n masterKey.jwk,\n JSON.parse(res.lbop.cipherMeta)\n );\n\n return {\n id: res.id,\n ...plainCipherMeta,\n };\n }\n\n public async list(): Promise<Lbop[]> {\n const res = await this.lrApollo.query<LbopsQuery>({\n query: LbopsQuery,\n });\n\n const masterKey = await this.keyService.currentMasterKey;\n\n return Promise.all(\n res.lbops.edges.map(async (edge) => {\n const plainCipherMeta = await this.encryptionService.decrypt(\n masterKey.jwk,\n JSON.parse(edge.node.cipherMeta)\n );\n return {\n id: edge.node.id,\n ...plainCipherMeta,\n };\n })\n );\n }\n\n public async create({ name }: CreateLbopParams): Promise<Lbop> {\n if (Slip39Helper.WORD_LIST.length !== 1024) {\n throw new KcBadLogicException('Slip39Helper.WORD_LIST.length != 1024');\n }\n\n // Get existing to make sure there are not duplicate first words\n const lbops = await this.list();\n\n // Generate new one\n let lbopString: string;\n // eslint-disable-next-line no-constant-condition\n while (true) {\n lbopString = this.keyFactory\n .randomChoices(Slip39Helper.WORD_LIST, this.LBOP_WORDS)\n .join(' ');\n const partial = this.getPartial(lbopString);\n\n if (!lbops.some((lbop) => lbop.partial === partial)) {\n break;\n }\n }\n\n const lbopKeyParams = await this.keyFactory.createLbopKeyParams();\n const lbopKey = (\n await this.keyFactory.deriveLbopKey({\n password: await this.keyFactory.importPassword(lbopString),\n ...lbopKeyParams,\n })\n ).jwk;\n\n const lbopKeyVerifier = await this.keyFactory.createSignKey();\n const wrappedLbopKeyVerifier = await this.encryptionService.encrypt(\n lbopKey,\n lbopKeyVerifier.toJSON(true)\n );\n\n // Re-encrypt master key with new key\n const masterKey = this.keyService.currentMasterKey;\n const wrappedMasterKey = await this.encryptionService.encrypt(\n lbopKey,\n masterKey.jwk.toJSON(true)\n );\n\n const meta = {\n ...(name && { name }),\n partial: this.getPartial(lbopString),\n };\n const cipherMeta = await this.encryptionService.encrypt(\n masterKey.jwk,\n meta\n );\n\n const res = await this.lrApollo.mutate<CreateLbopQuery>({\n mutation: CreateLbopQuery,\n variables: {\n input: {\n cipherMeta: JSON.stringify(cipherMeta),\n lbopKeyParams: JSON.stringify(lbopKeyParams),\n lbopKeyVerifier: JSON.stringify(lbopKeyVerifier.toJSON(true)),\n wrappedLbopKeyVerifier: JSON.stringify(wrappedLbopKeyVerifier),\n masterKeyId: masterKey.id,\n wrappedMasterKey: JSON.stringify(wrappedMasterKey),\n },\n },\n });\n\n return {\n ...res.createLbop.lbop,\n lbopString,\n };\n }\n\n // --------------------------------------------------------------------------------------------------------------------\n // --------------------------------------------------------------------------------------------------------------------\n // Flow below are for password reset via LBOP\n //\n // --Potential Failure Point xxx--\n //\n // Look for the above and you can test by interrupting at these points.\n //\n // The LBOP reset process can be restarted at any point before the call to \"set-password/\". Once \"set-password/\" has been\n // called, we assume the client has a short period of time to change the Idp password to the one they've chosen. The \"set-password/\"\n // will set the Idp password to a temporary random password. The user can no longer login using their current password. If the Idp\n // password change process does not complete or takes longer than the lockout period, the account will not be accessible and a new\n // LBOP password reset must be carried out.\n // --------------------------------------------------------------------------------------------------------------------\n // --------------------------------------------------------------------------------------------------------------------\n private async verifyLbops(\n challengeResult: ChallengeResult,\n lbopString: string\n ): Promise<{\n lbop: ChallengeResultLbop;\n signedChallenge: any;\n lbopKey: JWK.Key;\n }> {\n const clientNonce = this.keyFactory.randomString(this.CLIENT_NONCE_LENGTH);\n\n for (const lbop of challengeResult.lbops) {\n const lbopKey = (\n await this.keyFactory.deriveLbopKey({\n password: await this.keyFactory.importPassword(lbopString),\n ...lbop.lbopKeyParams,\n })\n ).jwk;\n\n // If decoding successful then it's the correct lbop\n try {\n const lbopKeyVerifier = (await this.encryptionService.decrypt(\n lbopKey,\n lbop.wrappedLbopKeyVerifier\n )) as any;\n\n // Force a bad signature.\n // const serverNonce = challengeResult.challenge.serverNonce + \"1\",\n\n const serverNonce = challengeResult.challenge.serverNonce;\n\n const signedChallenge = await this.encryptionService.sign(\n lbopKeyVerifier,\n {\n serverNonce,\n clientNonce,\n }\n );\n\n return {\n lbop,\n signedChallenge,\n lbopKey,\n };\n } catch (error) {\n continue;\n }\n }\n throw new KcException(\n new KcError({\n source: ERROR_SOURCE,\n code: KcLbopErrorCode.INVALID_PASSPHRASE,\n message: 'Invalid passphrase.',\n })\n );\n }\n\n public async verifyContact(\n params: VerifyContactParams\n ): Promise<VerifyContactResult> {\n const ret = this.http\n .post<VerifyContactResult>(\n `${this.config.authUrl}users/lbop-reset/verify-contact/`,\n params\n )\n .toPromise();\n\n // --Potential Failure Point 1 --\n // The contact verifications are throttled. But otherwise harmless.\n\n return ret;\n }\n\n public async confirmContact(\n params: ConfirmContactParams\n ): Promise<ConfirmContactResult> {\n return this.http\n .post<ConfirmContactResult>(`${this.config.authUrl}cove/respond/`, {\n claim_id: params.claimId,\n v_code: params.vCode,\n })\n .toPromise();\n\n // --Potential Failure Point 2 --\n // A verified claim for a contact does not prevent new ones from being generated. So it should be fine to just start again.\n }\n\n public async verify(params: VerifyParams): Promise<VerifyResult> {\n const challengeResult = await this.http\n .post<ChallengeResult>(\n `${this.config.authUrl}users/lbop-reset/get-challenge/`,\n {\n claimId: params.claimId,\n claimToken: params.claimToken,\n }\n )\n .toPromise();\n\n // --Potential Failure Point 3 --\n // This does not lock anything. A second call to \"get-challenge/\" will create a new challenge amd invalidate the first one.\n const { signedChallenge, lbop, lbopKey } = await this.verifyLbops(\n challengeResult,\n params.lbop\n );\n\n const res = await this.http\n .post<any>(`${this.config.authUrl}users/lbop-reset/verify-challenge/`, {\n lbopId: lbop.lbopId,\n signedChallenge,\n })\n .toPromise();\n\n // --Potential Failure Point 4 --\n // This does not lock anything. So ok to restart.\n\n return {\n lbopId: lbop.lbopId,\n verifiedToken: res.verifiedToken,\n masterKeyId: res.masterKeyId,\n masterKey: await KFS.asKey(\n await this.encryptionService.decrypt(lbopKey, res.wrappedMasterKey)\n ),\n };\n }\n\n public async setPassword(params: SetPasswordParams): Promise<any> {\n // Generate the new password derived keys\n const passKeyBundle = await this.passwordService.createPassKeyBundle(\n params.newPassword\n );\n\n // Re-encrypt master key with new key\n const newWrappedMasterKey = await this.encryptionService.encrypt(\n passKeyBundle.passKey,\n params.masterKey.toJSON(true)\n );\n\n const result = await this.http\n .post<SetPasswordApiResult>(\n `${this.config.authUrl}users/lbop-reset/set-password/`,\n {\n lbopId: params.lbopId,\n verifiedToken: params.verifiedToken,\n masterKeyId: params.masterKeyId,\n newWrappedMasterKey,\n newPassKey: {\n passKeyParams: passKeyBundle.passKeyParams,\n passIdpParams: passKeyBundle.passIdpParams,\n passIdpVerifierPbk: passKeyBundle.passIdpVerifier.toJSON(),\n wrappedPassIdpVerifierPrk: passKeyBundle.wrappedPassIdpVerifierPrk,\n },\n }\n )\n .toPromise();\n\n // --Potential Failure Point 5 --\n // A timed mutex is locked. The Idp password change must occur within a period of time.\n // If interrupted here, the user can not login with their old password again. They must\n // start the whole LBOP password reset process again.\n\n // This call will go through the LR proxy which is OK since the LR server knows\n // the temporary password anyway.\n let user = await this.auth.signIn(result.username, result.idpPassword, {\n noProxy: 'true',\n });\n\n if (user.challengeName !== 'NEW_PASSWORD_REQUIRED') {\n throw new KcInternalErrorException(\n 'Expecting Cognito to have done a password reset.'\n );\n }\n\n // --Potential Failure Point 6 --\n // Must restart the LBOP password reset process again.\n\n // Set new password on Idp\n user = await this.auth.completeNewPassword(\n user,\n this.passwordService.getPassIdpString(passKeyBundle.passIdp),\n {}\n );\n\n // --Potential Failure Point 7 --\n // Must restart the LBOP password reset process again.\n\n await this.auth.signOut();\n\n return await this.http\n .post<any>(`${this.config.authUrl}users/lbop-reset/complete/`, {\n lbopId: params.lbopId,\n setPasswordToken: result.setPasswordToken,\n })\n .toPromise();\n }\n}\n","import { HttpClientModule } from '@angular/common/http';\nimport { APP_INITIALIZER, ModuleWithProviders, NgModule } from '@angular/core';\nimport Auth from '@aws-amplify/auth';\nimport { AuthClass } from '@aws-amplify/auth/lib-esm/Auth';\nimport { NgIdleKeepaliveModule } from '@ng-idle/keepalive';\nimport { APOLLO_OPTIONS } from 'apollo-angular';\nimport { configureAmplifyAuth } from './auth/auth.config';\nimport { configureApollo, KcConfig, KC_CONFIG } from './life-ready.config';\n\n@NgModule({\n imports: [HttpClientModule, NgIdleKeepaliveModule.forRoot()],\n})\nexport class LifeReadyModule {\n public static forRoot(\n config: KcConfig\n ): ModuleWithProviders<LifeReadyModule> {\n return {\n ngModule: LifeReadyModule,\n providers: [\n {\n provide: KC_CONFIG,\n useValue: config,\n },\n {\n provide: AuthClass,\n useValue: Auth,\n },\n {\n provide: APP_INITIALIZER,\n useFactory: configureAmplifyAuth,\n deps: [KC_CONFIG, AuthClass],\n multi: true,\n },\n {\n provide: APOLLO_OPTIONS,\n useFactory: configureApollo,\n deps: [KC_CONFIG, AuthClass],\n },\n ],\n };\n }\n}\n","import { gqlTyped } from '../_common/ast';\nimport { DateTime, ID } from '../api/types';\n\nexport interface UpdateNotificationMutationResult {\n updateNotification: {\n notification: {\n id: ID;\n };\n };\n}\nexport const UpdateNotificationMutation = gqlTyped<UpdateNotificationMutationResult>`\nmutation UpdateNotificationMutation($input: UpdateNotificationInput!) {\n updateNotification(input: $input) {\n notification {\n id\n }\n }\n}\n`;\n\nexport interface UpdateAllNotificationsReadStateMutationResult {\n updateAllNotificationsReadState: {\n count: number;\n };\n}\nexport const UpdateAllNotificationsReadStateMutation = gqlTyped<UpdateAllNotificationsReadStateMutationResult>`\nmutation UpdateAllNotificationsReadStateMutation($input: UpdateAllNotificationsReadStateInput!) {\n updateAllNotificationsReadState(input: $input) {\n count\n }\n}\n`;\n\nexport interface DebugCreateNotificationMutationResult {\n debugCreateNotification: {\n notification: {\n id: ID;\n };\n };\n}\nexport const DebugCreateNotificationMutation = gqlTyped<DebugCreateNotificationMutationResult>`\nmutation DebugCreateNotificationMutation($input: DebugCreateNotificationInput!) {\n debugCreateNotification(input: $input) {\n notification {\n id\n }\n }\n}\n`;\n\nexport interface DebugDeleteAllNotificationsMutationResult {\n debugDeleteAllNotifications: {\n count: number;\n };\n}\nexport const DebugDeleteAllNotificationsMutation = gqlTyped<DebugDeleteAllNotificationsMutationResult>`\nmutation DebugDeleteAllNotificationsMutation($input: DebugDeleteAllNotificationsInput!) {\n debugDeleteAllNotifications(input: $input) {\n count\n }\n}\n`;\n\nexport interface UpdateNotificationFeatureStateMutationResult {\n updateNotificationFeatureState: {\n featureState: {\n notificationsLastViewed: DateTime;\n };\n };\n}\nexport const UpdateNotificationFeatureStateMutation = gqlTyped<UpdateNotificationFeatureStateMutationResult>`\nmutation UpdateNotificationFeatureStateMutation($input: UpdateNotificationFeatureStateInput!) {\n updateNotificationFeatureState(input: $input) {\n featureState {\n notificationsLastViewed\n\t\t}\n }\n}\n`;\n","import { Injectable, Injector, NgZone } from '@angular/core';\nimport { LrMutation, LrService } from '../api/lr-graphql';\nimport { JSONObject } from '../api/types';\nimport { RunOutsideAngular } from '../_common/run-outside-angular';\nimport {\n DebugCreateNotificationMutation,\n DebugDeleteAllNotificationsMutation,\n UpdateAllNotificationsReadStateMutation,\n UpdateNotificationFeatureStateMutation,\n UpdateNotificationMutation,\n} from './notification.gql';\n\nexport interface UpdateNotificationOptions {\n notificationId: string;\n hasBeenRead: boolean;\n}\n\nexport interface UpdateAllNotificationsReadStateOptions {\n hasBeenRead: boolean;\n}\n\nexport interface DebugCreateNotificationOptions {\n receiverId: string;\n plainData?: Record<string, JSONObject>;\n plainMeta?: Record<string, JSONObject>;\n hasBeenRead?: boolean;\n timeRead?: Date;\n}\n\nexport interface DebugDeleteAllNotificationsOptions {\n receiverId: string;\n}\n\nexport interface UpdateNotificationFeatureStateOptions {\n lastViewed: Date | null;\n}\n\n@RunOutsideAngular({\n ngZoneName: 'ngZone',\n})\n@Injectable({\n providedIn: 'root',\n})\nexport class NotificationService extends LrService {\n constructor(private ngZone: NgZone, private injector: Injector) {\n super(injector);\n }\n\n async updateNotification(options: UpdateNotificationOptions) {\n return this.mutate(this.updateNotificationMutation(options));\n }\n\n async updateNotificationMutation(options: UpdateNotificationOptions) {\n return new LrMutation({\n mutation: UpdateNotificationMutation,\n variables: {\n input: {\n ...options,\n },\n },\n });\n }\n\n async updateAllNotificationsReadState(\n options: UpdateAllNotificationsReadStateOptions\n ) {\n return this.mutate(this.updateAllNotificationsReadStateMutation(options));\n }\n\n async updateAllNotificationsReadStateMutation(\n options: UpdateAllNotificationsReadStateOptions\n ) {\n return new LrMutation({\n mutation: UpdateAllNotificationsReadStateMutation,\n variables: {\n input: {\n ...options,\n },\n },\n });\n }\n\n async debugCreateNotification(options: DebugCreateNotificationOptions) {\n return this.mutate(this.debugCreateNotificationMutation(options));\n }\n\n async debugCreateNotificationMutation(\n options: DebugCreateNotificationOptions\n ) {\n return new LrMutation({\n mutation: DebugCreateNotificationMutation,\n variables: {\n input: {\n receiverId: options.receiverId,\n hasBeenRead: options.hasBeenRead,\n timeRead: options.timeRead?.toISOString(),\n plainData: JSON.stringify(options.plainData),\n plainMeta: JSON.stringify(options.plainMeta),\n },\n },\n });\n }\n\n async debugDeleteAllNotifications(\n options: DebugDeleteAllNotificationsOptions\n ) {\n return this.mutate(this.debugDeleteAllNotificationsMutation(options));\n }\n\n async debugDeleteAllNotificationsMutation(\n options: DebugDeleteAllNotificationsOptions\n ) {\n return new LrMutation({\n mutation: DebugDeleteAllNotificationsMutation,\n variables: {\n input: {\n receiverId: options.receiverId,\n },\n },\n });\n }\n\n async updateNotificationFeatureState(\n options: UpdateNotificationFeatureStateOptions\n ) {\n return this.mutate(this.updateNotificationFeatureStateMutation(options));\n }\n\n async updateNotificationFeatureStateMutation(\n options: UpdateNotificationFeatureStateOptions\n ) {\n return new LrMutation({\n mutation: UpdateNotificationFeatureStateMutation,\n variables: {\n input: {\n lastViewed: options.lastViewed?.toISOString(),\n clearLastViewed: options.lastViewed == null || undefined,\n },\n },\n });\n }\n}\n","import {\n ID,\n PaymentCaptureField,\n PaymentCardField,\n PaymentMethodNode,\n} from '../api/types';\nimport { gqlTyped } from '../_common/ast';\n\nexport interface InitiateStripePaymentMethodCaptureMutationResult {\n initiateStripePaymentMethodCapture: {\n paymentCapture: Required<PaymentCaptureField>;\n };\n}\nexport const InitiateStripePaymentMethodCaptureMutation = gqlTyped<InitiateStripePaymentMethodCaptureMutationResult>`\nmutation InitiateStripePaymentMethodCaptureMutation {\n initiateStripePaymentMethodCapture(input: {}) {\n paymentCapture {\n stripeIntentId\n stripeClientSecret\n }\n }\n}\n`;\n\nexport interface CompleteStripePaymentMethodCaptureMutationResult {\n completeStripePaymentMethodCapture: {\n // We don't have a DeepRequired implementation yet, so have to explicitly make\n // the child fields required.\n paymentMethod: Required<Omit<PaymentMethodNode, 'invoice'>> & {\n card: Required<PaymentCardField>;\n };\n };\n}\nexport const CompleteStripePaymentMethodCaptureMutation = gqlTyped<CompleteStripePaymentMethodCaptureMutationResult>`\nmutation CompleteStripePaymentMethodCaptureMutation($input: CompleteStripePaymentMethodCaptureInput!) {\n completeStripePaymentMethodCapture(input: $input) {\n paymentMethod {\n id\n created\n modified\n card {\n brand\n lastFourDigits\n expiryYear\n expiryMonth\n }\n isDefault \n }\n }\n}\n`;\n\nexport interface RemovePaymentMethodMutationResult {\n removePaymentMethod: {\n id: ID;\n };\n}\nexport const RemovePaymentMethodMutation = gqlTyped<RemovePaymentMethodMutationResult>`\nmutation RemovePaymentMethodMutation($input: RemovePaymentMethodInput!) {\n removePaymentMethod(input: $input) {\n id\n }\n}\n`;\n\nexport interface SetDefaultPaymentMethodMutationResult {\n setDefaultPaymentMethod: {\n paymentMethod: {\n id: ID;\n };\n };\n}\nexport const SetDefaultPaymentMethodMutation = gqlTyped<SetDefaultPaymentMethodMutationResult>`\nmutation SetDefaultPaymentMethodMutation($input: SetDefaultPaymentMethodInput!) {\n setDefaultPaymentMethod(input: $input) {\n paymentMethod {\n id\n } \n }\n}\n`;\n\nexport interface RemoveDefaultPaymentMethodMutationResult {\n removeDefaultPaymentMethod: {\n paymentMethod: {\n id: ID;\n };\n };\n}\nexport const RemoveDefaultPaymentMethodMutation = gqlTyped<RemoveDefaultPaymentMethodMutationResult>`\nmutation RemoveDefaultPaymentMethodMutation {\n removeDefaultPaymentMethod(input: {}) {\n paymentMethod {\n id\n } \n }\n}\n`;\n\nexport interface IssuePlanMutationResult {\n issuePlan: {\n plan: {\n id: ID;\n };\n };\n}\nexport const IssuePlanMutation = gqlTyped<IssuePlanMutationResult>`\nmutation IssuePlanMutation($input: IssuePlanInput!) {\n issuePlan(input: $input) {\n plan {\n id\n }\n }\n}\n`;\n\nexport interface CancelPlanMutationResult {\n cancelPlan: {\n plan: {\n id: ID;\n };\n };\n}\nexport const CancelPlanMutation = gqlTyped<CancelPlanMutationResult>`\nmutation CancelPlanMutation($input: CancelPlanInput!) {\n cancelPlan(input: $input) {\n plan {\n id\n } \n }\n}\n`;\n\nexport interface ChangePriceOptionMutationResult {\n changePriceOption: {\n plan: {\n id: ID;\n };\n };\n}\nexport const ChangePriceOptionMutation = gqlTyped<ChangePriceOptionMutationResult>`\nmutation ChangePriceOptionMutation($input: ChangePriceOptionInput!) {\n changePriceOption(input: $input) {\n plan {\n id\n }\n }\n}\n`;\n\nexport interface ReactivatePlanMutationResult {\n reactivatePlan: {\n plan: {\n id: ID;\n };\n };\n}\nexport const ReactivatePlanMutation = gqlTyped<ReactivatePlanMutationResult>`\nmutation ReactivatePlanMutation($input: ReactivatePlanInput!) {\n reactivatePlan(input: $input) {\n plan {\n id\n }\n }\n}\n`;\n","import { Injectable, Injector, NgZone } from '@angular/core';\nimport { LrMutation, LrService } from '../api/lr-graphql';\nimport { LrRelayIdInput } from '../api/types';\nimport { RunOutsideAngular } from '../_common/run-outside-angular';\nimport {\n CancelPlanMutation,\n ChangePriceOptionMutation,\n CompleteStripePaymentMethodCaptureMutation,\n InitiateStripePaymentMethodCaptureMutation,\n IssuePlanMutation,\n ReactivatePlanMutation,\n RemoveDefaultPaymentMethodMutation,\n RemovePaymentMethodMutation,\n SetDefaultPaymentMethodMutation,\n} from './plan.gql';\nimport {\n CancelPlanOptions,\n ChangePriceOptionOptions,\n IssuePlanOptions,\n} from './plan.types';\n\n@RunOutsideAngular({\n ngZoneName: 'ngZone',\n})\n@Injectable({\n providedIn: 'root',\n})\nexport class PlanService extends LrService {\n constructor(private ngZone: NgZone, private injector: Injector) {\n super(injector);\n }\n\n initiateStripePaymentMethodCapture() {\n return this.mutate(this.initiateStripePaymentMethodCaptureMutation());\n }\n\n /**\n * Starts a stripe payment capture intent. On intent can only add one card.\n * @returns Promise that resolves to a mutation\n */\n initiateStripePaymentMethodCaptureMutation() {\n return new LrMutation({\n mutation: InitiateStripePaymentMethodCaptureMutation,\n variables: {\n input: {},\n },\n });\n }\n\n completeStripePaymentMethodCapture(stripeIntentId: string) {\n return this.mutate(\n this.completeStripePaymentMethodCaptureMutation(stripeIntentId)\n );\n }\n\n /**\n * Completes the payment capture intent. Call this after calling stripe.confirmCardSetup.\n *\n * The return result of this mutation can be used to update the UI. Because this is a mutation\n * we always get the most up to date data from the BD.\n *\n * @returns Promise that resolves to a mutation with the just created PaymentMethodNode\n */\n completeStripePaymentMethodCaptureMutation(stripeIntentId: string) {\n return new LrMutation({\n mutation: CompleteStripePaymentMethodCaptureMutation,\n variables: {\n input: { stripeIntentId },\n },\n });\n }\n\n setDefaultPaymentMethod(paymentMethodId: LrRelayIdInput) {\n return this.mutate(this.setDefaultPaymentMethodMutation(paymentMethodId));\n }\n\n /**\n * Mutation that sets the default payment method for the current user.\n *\n * @param paymentMethodId The id from PaymentMethodNode\n * @returns Promise that resolves to a mutation\n */\n setDefaultPaymentMethodMutation(paymentMethodId: LrRelayIdInput) {\n return new LrMutation({\n mutation: SetDefaultPaymentMethodMutation,\n variables: {\n input: {\n paymentMethodId,\n },\n },\n });\n }\n\n removeDefaultPaymentMethod() {\n return this.mutate(this.removeDefaultPaymentMethodMutation());\n }\n\n /**\n * Mutation that removes a the default payment method\n *\n * @returns Promise that resolves to a mutation\n */\n removeDefaultPaymentMethodMutation() {\n return new LrMutation({\n mutation: RemoveDefaultPaymentMethodMutation,\n variables: {\n input: {},\n },\n });\n }\n\n issuePlan(options: IssuePlanOptions) {\n return this.mutate(this.issuePlanMutation(options));\n }\n\n /**\n * Mutation that issues a new plan for the current user.\n *\n * @param options.issuerUid The same issuerUid that is in the AvailablePlanField returned by queries such as availablePublicPlans\n * @param options.planUid The same planUid that is in the AvailablePlanField returned by queries such as availablePublicPlans\n * @param options.priceId The priceId from PriceOptionField (eg. inside AvailablePlanField)\n * @param options.promotionalCode promotion code where applicable\n * @returns Promise that resolves to a mutation\n */\n issuePlanMutation(options: IssuePlanOptions) {\n return new LrMutation({\n mutation: IssuePlanMutation,\n variables: {\n input: options,\n },\n });\n }\n\n removePaymentMethod(paymentMethodId: string) {\n return this.mutate(this.removePaymentMethodMutation(paymentMethodId));\n }\n\n /**\n * Mutation that removes a payment method for the current user\n *\n * @param paymentMethodId The id from PaymentMethodNode\n * @returns Promise that resolves to a mutation\n */\n removePaymentMethodMutation(paymentMethodId: LrRelayIdInput) {\n return new LrMutation({\n mutation: RemovePaymentMethodMutation,\n variables: {\n input: {\n paymentMethodId,\n },\n },\n });\n }\n\n cancelPlan(options: CancelPlanOptions) {\n return this.mutate(this.cancelPlanMutation(options));\n }\n\n /**\n * Mutation that removes a payment method for the current user\n *\n * @param options.planId The id from IssuedPlanNode\n * @param options.immediate If true, cancel plan effective immediately. Default false.\n * @returns Promise that resolves to a mutation\n */\n cancelPlanMutation(options: CancelPlanOptions) {\n return new LrMutation({\n mutation: CancelPlanMutation,\n variables: {\n input: options,\n },\n });\n }\n\n changePriceOption(options: ChangePriceOptionOptions) {\n return this.mutate(this.changePriceOptionMutation(options));\n }\n\n /**\n * Change the price option for a plan.\n *\n * @param options.planId The id from IssuedPlanNode\n * @param options.priceId The priceId from PriceOptionField (eg. inside AvailablePlanField)\n * @returns Promise that resolves to a mutation\n */\n changePriceOptionMutation(options: ChangePriceOptionOptions) {\n return new LrMutation({\n mutation: ChangePriceOptionMutation,\n variables: {\n input: options,\n },\n });\n }\n\n reactivatePlan(planId: LrRelayIdInput) {\n return this.mutate(this.reactivatePlanMutation(planId));\n }\n\n /**\n * Reactivate a cancelled plan with a specified price option.\n *\n * @param options.planId The id from IssuedPlanNode\n * @returns Promise that resolves to a mutation\n */\n reactivatePlanMutation(planId: LrRelayIdInput) {\n return new LrMutation({\n mutation: ReactivatePlanMutation,\n variables: {\n input: { planId },\n },\n });\n }\n}\n","/* eslint-disable @typescript-eslint/no-explicit-any */\nimport { Injectable } from '@angular/core';\nimport { LrGraphQLService } from '../api/lr-graphql';\nimport { mapEdges, TpNode } from '../api/types';\nimport { SharedContactCardService } from '../shared-contact-card/shared-contact-card.service';\nimport { lodash } from '../_common';\nimport { ContactCardsQuery, TrustedPartiesQuery } from './profile.gql';\nimport { ProfileService } from './profile.service';\nimport {\n MainContactCard,\n MainContactCardFields,\n MainContactCardProperty,\n SharedTrustedPartyDetails,\n TrustedParty,\n TrustedPartyDetails,\n TrustedPartyType,\n} from './profile.types';\n\nenum ContactFields {\n Name = 'name',\n Email = 'email',\n Image = 'image',\n Phone = 'phone',\n Address = 'address',\n}\n\nconst FieldNames = [\n ContactFields.Name,\n ContactFields.Email,\n ContactFields.Image,\n ContactFields.Phone,\n ContactFields.Address,\n];\n\ninterface FieldChange {\n field: string;\n id: string;\n label: string;\n oldValue?: any;\n newValue?: any;\n}\n\n@Injectable({\n providedIn: 'root',\n})\nexport class ProfileDetailsService {\n constructor(\n private sharedContactCardService: SharedContactCardService,\n private profileService: ProfileService,\n private api: LrGraphQLService\n ) {}\n\n async updateDetails(fields: MainContactCardFields): Promise<MainContactCard> {\n console.log('updateDetails()');\n const mainContactCard = await this.fetchMainContactCard();\n\n const updatedMainContactCard = await this.profileService.updateDetails(\n mainContactCard?.id,\n mainContactCard?.keyId,\n fields\n );\n\n await this.synchronizeContactCards(fields, mainContactCard?.fields);\n\n return updatedMainContactCard;\n }\n\n async updateTrustedPartyDetails(details: SharedTrustedPartyDetails) {\n const { id, ownedKeyId, sharedKeyId, ...contactCard } = details;\n\n await this.sharedContactCardService.updateMySharedContactCard(\n id,\n ownedKeyId,\n sharedKeyId,\n contactCard\n );\n\n await this.synchronizeSharedDetails(details);\n }\n\n async synchronizeSharedDetails(details: TrustedPartyDetails) {\n let hasNewValues = false;\n\n // Used to be a getCurrentUser() call which returns a caches version of the contact card.\n // Now we just make an API call. So ok to modify the returned value.\n const mainContactCard = await this.fetchMainContactCard();\n\n if (details.name) {\n const property = this.checkField(\n details.name,\n mainContactCard.fields.name\n );\n\n if (property) {\n mainContactCard.fields.name = property;\n hasNewValues = true;\n }\n }\n\n if (details.email) {\n const property = this.checkField(\n details.email,\n mainContactCard.fields.email\n );\n\n if (property) {\n mainContactCard.fields.email = property;\n hasNewValues = true;\n }\n }\n\n if (details.image) {\n const property = this.checkField(\n details.image,\n mainContactCard.fields.image\n );\n\n if (property) {\n mainContactCard.fields.image = property;\n hasNewValues = true;\n }\n }\n\n if (details.phones && details.phones.length) {\n for (const phone of details.phones) {\n const property = this.checkField(\n phone.value,\n mainContactCard.fields.phone,\n phone.label\n );\n\n if (property) {\n mainContactCard.fields.phone = property;\n hasNewValues = true;\n }\n }\n }\n\n if (details.addresses && details.addresses.length) {\n for (const address of details.addresses) {\n const property = this.checkField(\n address.value,\n mainContactCard.fields.address,\n address.label\n );\n\n if (property) {\n mainContactCard.fields.address = property;\n hasNewValues = true;\n }\n }\n }\n\n if (hasNewValues) {\n await this.profileService.updateDetails(\n mainContactCard.id,\n mainContactCard.keyId,\n mainContactCard.fields\n );\n }\n }\n\n // ------------------------------------------------------------------\n // Helpers\n // ------------------------------------------------------------------\n private async fetchMainContactCard(): Promise<MainContactCard | null> {\n const mainContactCard = (await this.api.query({ query: ContactCardsQuery }))\n .contactCards.edges[0]?.node;\n\n return mainContactCard\n ? {\n id: mainContactCard.id,\n keyId: mainContactCard.key.id,\n fields: mainContactCard.cipherDataClearJson as MainContactCardFields,\n }\n : null;\n }\n\n private async getTrustedParties(): Promise<TrustedParty[]> {\n const { tps } = await this.api.query({\n query: TrustedPartiesQuery,\n });\n\n return mapEdges(tps).map((tp) => this.mapTrustedParty(tp));\n }\n\n private mapTrustedParty(tp: TpNode): TrustedParty {\n const tpDetails: TrustedPartyDetails =\n tp.sharedContactCard.sharedCipherDataClearJson;\n\n const myDetails: SharedTrustedPartyDetails = {\n ...tp.myContactCard.sharedCipherDataClearJson,\n id: tp.myContactCard.id,\n ownedKeyId: tp.myContactCard.ownerKey.id,\n sharedKeyId: tp.myContactCard.sharedKey.id,\n };\n\n return {\n id: tp.id,\n type: TrustedPartyType.User,\n hasScenarios: !!tp.sharedScenarios.edges.length,\n hasSharedVault: !!tp.theirItems.directories.edges.length,\n name: tpDetails?.name?.name,\n details: tpDetails,\n mySharedDetails: myDetails,\n userSharedKey: tp.currentUserSharedKey.userSharedKey,\n username: tp.other.username,\n features: {\n sharedVault: {\n hasAccess:\n (tp.other.features?.shareVault || ['noaccess'])[0] === 'access',\n },\n },\n };\n }\n\n private async synchronizeContactCards(\n newFields: MainContactCardFields,\n oldFields: MainContactCardFields\n ): Promise<void> {\n if (!oldFields) return;\n\n const changes = this.getChanges(newFields, oldFields);\n\n if (changes.length === 0) return;\n\n const trustedParties = await this.getTrustedParties();\n\n if (trustedParties.length === 0) return;\n\n for (const details of trustedParties.map((x) => x.mySharedDetails)) {\n await this.synchronizeSharedContactCard(details, changes);\n }\n }\n\n private getChanges(\n newFields: MainContactCardFields,\n oldFields: MainContactCardFields\n ): FieldChange[] {\n const changes: FieldChange[] = [];\n\n for (const field of FieldNames) {\n const oldField = oldFields[field];\n if (oldField && oldField.values) {\n for (const oldValue of oldField.values) {\n const newValue = (newFields[field].values as any[])?.find(\n (x) => x.id === oldValue.id\n );\n\n if (!newValue) {\n changes.push({\n field,\n id: oldValue.id,\n label: oldValue.label,\n oldValue: oldValue.value,\n });\n } else if (!lodash.isEqual(newValue.value, oldValue.value)) {\n changes.push({\n field,\n id: oldValue.id,\n label: oldValue.label,\n oldValue: oldValue.value,\n newValue: newValue.value,\n });\n }\n }\n }\n }\n return changes;\n }\n\n private async synchronizeSharedContactCard(\n details: SharedTrustedPartyDetails,\n changes: FieldChange[]\n ): Promise<void> {\n let hasChanged = false;\n for (const change of changes) {\n switch (change.field) {\n case ContactFields.Phone:\n {\n const value =\n details.phones &&\n details.phones.find((x) => x.label === change.label);\n\n if (value) {\n hasChanged = true;\n value.value = change.newValue;\n }\n }\n break;\n case ContactFields.Address:\n {\n const value =\n details.addresses &&\n details.addresses.find((x) => x.label === change.label);\n\n if (value) {\n hasChanged = true;\n value.value = change.newValue;\n }\n }\n break;\n default: {\n const value = details[change.field];\n\n if (lodash.isEqual(value, change.oldValue)) {\n hasChanged = true;\n details[change.field] = change.newValue;\n }\n }\n }\n }\n if (hasChanged) {\n const { id, ownedKeyId, sharedKeyId, ...contactCard } = details;\n\n await this.sharedContactCardService.updateMySharedContactCard(\n id,\n ownedKeyId,\n sharedKeyId,\n contactCard\n );\n }\n }\n\n private checkField<T>(\n field: T,\n property: MainContactCardProperty<T>,\n label: string = null\n ) {\n property = property || { value: field, hasMultiple: false };\n property.values = property.values || [];\n\n if (\n property.values.length === 0 ||\n property.values.every((x) => !lodash.isEqual(field, x.value))\n ) {\n property.values.push({\n id: `${label}-${new Date().getTime()}`,\n label,\n value: field,\n });\n property.hasMultiple = property.values.length > 1;\n property.value = property.value || field;\n return property;\n }\n return null;\n }\n}\n","import { HttpClient } from '@angular/common/http';\nimport { Inject, Injectable } from '@angular/core';\nimport { AuthClass } from '@aws-amplify/auth/lib-esm/Auth';\nimport { JSONObject } from '../api/types';\nimport { EncryptionService } from '../encryption/encryption.service';\nimport { KeyFactoryService } from '../key/key-factory.service';\nimport { KcConfig, KC_CONFIG } from '../life-ready.config';\nimport { PasswordService } from '../password/password.service';\nimport { RegisterResult } from './register.types';\n\n@Injectable({\n providedIn: 'root',\n})\nexport class RegisterService {\n constructor(\n @Inject(KC_CONFIG) private config: KcConfig,\n private auth: AuthClass,\n private http: HttpClient,\n private keyFactory: KeyFactoryService,\n private encryptionService: EncryptionService,\n private passwordService: PasswordService\n ) {}\n\n /**\n * Request a verification code to be sent out to an email.\n * @return Info needed to be submitted along with the verification code\n */\n public async verifyEmail(email: string): Promise<string> {\n const { claim_id } = await this.http\n .post<{ claim_id }>(`${this.config.authUrl}cove/claim/email/`, {\n address: email,\n context: 'signup',\n })\n .toPromise();\n return claim_id;\n }\n\n public async verifyPhone(phoneNumber: string): Promise<string> {\n const { claim_id } = await this.http\n .post<{ claim_id }>(`${this.config.authUrl}cove/claim/sms/`, {\n address: phoneNumber,\n context: 'signup',\n })\n .toPromise();\n return claim_id;\n }\n\n public async confirmVerificationCode(\n verificationId: string,\n verificationCode: string\n ): Promise<string> {\n const { token } = await this.http\n .post<{ token }>(`${this.config.authUrl}cove/respond/`, {\n claim_id: verificationId,\n v_code: verificationCode,\n })\n .toPromise();\n return token;\n }\n\n public async register(\n email: string,\n password: CryptoKey,\n verificationId: string,\n verificationToken: string,\n verificationType: 'email' | 'phone' = 'email'\n ): Promise<RegisterResult> {\n // Generate the key material needed for PassIdp which will be the password used for Cognito.\n const passKeyBundle = await this.passwordService.createPassKeyBundle(\n password\n );\n\n const masterKey = await this.keyFactory.createKey();\n const wrappedMasterKey = await this.encryptionService.encrypt(\n passKeyBundle.passKey,\n masterKey.toJSON(true)\n );\n\n const rootKey = await this.keyFactory.createKey();\n const wrappedRootKey = await this.encryptionService.encrypt(\n masterKey,\n rootKey.toJSON(true)\n );\n\n // Encryption PKC key\n const prk = await this.keyFactory.createPkcKey();\n const wrappedPrk = await this.encryptionService.encrypt(\n rootKey,\n prk.toJSON(true)\n );\n\n // Signing PKC key\n const sigPrk = await this.keyFactory.createPkcSignKey();\n const wrappedSigPrk = await this.encryptionService.encrypt(\n rootKey,\n sigPrk.toJSON(true)\n );\n\n // API call to setup profile\n const user = await this.http\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n .post<any>(`${this.config.authUrl}users/`, {\n claims: [\n {\n type: verificationType,\n token: verificationToken,\n claim_id: verificationId,\n },\n ],\n pass_idp_params: passKeyBundle.passIdpParams,\n pass_idp_verifier_pbk: passKeyBundle.passIdpVerifier.toJSON(),\n wrapped_pass_idp_verifier_prk: passKeyBundle.wrappedPassIdpVerifierPrk,\n pass_key_params: passKeyBundle.passKeyParams,\n wrapped_master_key: wrappedMasterKey,\n wrapped_root_key: wrappedRootKey,\n pbk: prk.toJSON(), // public encryption key\n wrapped_prk: wrappedPrk,\n sig_pbk: sigPrk.toJSON(), // public signing key\n wrapped_sig_prk: wrappedSigPrk,\n })\n .toPromise();\n\n // API call to create user on cognito\n const attributes = {};\n user.claims.forEach((claim) => {\n attributes[claim.type] = claim.value;\n });\n\n // Random suffix for uniqueness. If there's a duplicate, then used just needs to\n // sign up again. But chances of collision is low.\n const suffix = this.keyFactory.randomDigitsNoZeros(4);\n\n const cognitoUser = await this.auth.signUp({\n username: `${email.split('@')[0]}.${suffix}`,\n password: this.passwordService.getPassIdpString(passKeyBundle.passIdp),\n attributes,\n // Unfortunately, validationData is not passed to the post\n // confirmation cognito trigger. So can can't do the association there.\n // The current workflow will create a new user on LR before signing up\n // with Cognito. Then Cognito can use the user.id and user.pre_sign_up_token to\n // do the validation of the attributes.\n // validationData: [\n // new CognitoUserAttribute({\n // Name: \"user_id\",\n // Value: String(user.id)\n // }),\n // new CognitoUserAttribute({\n // Name: \"user_pre_sign_up_token\",\n // Value: user.pre_sign_up_token\n // })\n // ]\n clientMetadata: {\n user_id: String(user.id),\n user_pre_sign_up_token: String(user.pre_sign_up_token),\n },\n });\n\n return {\n username: cognitoUser.user.getUsername(),\n userId: user.id,\n preSignUpToken: user.pre_sign_up_token,\n userSub: cognitoUser.userSub,\n };\n }\n\n public async hibpBreachedAccounts(account: string) {\n // The account is just the email\n try {\n const response = await this.http\n .get<JSONObject>(\n `${this.config.authUrl}users/hibp/breachedaccount/${account}/?truncateResponse=false`\n )\n .toPromise();\n return response;\n } catch (error) {\n if (error.status === 404) {\n return null;\n } else {\n throw error;\n }\n }\n }\n}\n","export class RegisterResult {\n username: string;\n userId: string;\n preSignUpToken: string;\n userSub: string;\n}\n","import { ID } from '../api/types';\nimport { gqlTyped } from '../_common/ast';\n\nexport interface CreateReminderMutationResult {\n createReminder: {\n reminder: {\n id: ID;\n };\n };\n}\nexport const CreateReminderMutation = gqlTyped<CreateReminderMutationResult>`\nmutation CreateReminderMutation($input: CreateReminderInput!) {\n createReminder(input: $input) {\n reminder {\n id\n }\n }\n}\n`;\n\nexport interface UpdateReminderMutationResult {\n updateReminder: {\n reminder: {\n id: ID;\n };\n };\n}\nexport const UpdateReminderMutation = gqlTyped<UpdateReminderMutationResult>`\nmutation UpdateReminderMutation($input: UpdateReminderInput!) {\n updateReminder(input: $input) {\n reminder {\n id\n }\n }\n}\n`;\n\nexport interface DeleteReminderMutationResult {\n deleteReminder: {\n id: ID;\n };\n}\nexport const DeleteReminderMutation = gqlTyped<DeleteReminderMutationResult>`\nmutation DeleteReminderMutation($input: DeleteReminderInput!) {\n deleteReminder(input: $input) {\n id\n }\n}\n`;\n","import { Injectable, Injector, NgZone } from '@angular/core';\nimport { LrMutation, LrService } from '../api/lr-graphql';\nimport { LrRelayIdInput } from '../api/types';\nimport { RunOutsideAngular } from '../_common/run-outside-angular';\nimport {\n CreateReminderMutation,\n DeleteReminderMutation,\n UpdateReminderMutation,\n} from './reminder.gql';\nimport { CreateReminderOptions, UpdateReminderOptions } from './reminder.types';\n\n@RunOutsideAngular({\n ngZoneName: 'ngZone',\n})\n@Injectable({\n providedIn: 'root',\n})\nexport class ReminderService extends LrService {\n constructor(private ngZone: NgZone, private injector: Injector) {\n super(injector);\n }\n\n createReminder(options: CreateReminderOptions) {\n return this.mutate(this.createReminderMutation(options));\n }\n\n async createReminderMutation(options: CreateReminderOptions) {\n return new LrMutation({\n mutation: CreateReminderMutation,\n variables: {\n input: {\n directoryId: options.directoryId,\n firstEvent: options.firstEvent.toISOString(),\n plain: JSON.stringify(options.plainJson),\n notifyAheadSeconds: options.notifyAheadSeconds ?? 0,\n },\n },\n });\n }\n\n updateReminder(options: UpdateReminderOptions) {\n return this.mutate(this.updateReminderMutation(options));\n }\n\n async updateReminderMutation(options: UpdateReminderOptions) {\n return new LrMutation({\n mutation: UpdateReminderMutation,\n variables: {\n input: {\n id: options.id,\n firstEvent: options.firstEvent?.toISOString(),\n // Ok to use undefined in side JSON.stringify: JSON.stringify(undefined) === undefined\n // Passing in undefined to plain means don't update the plain field.\n plain: JSON.stringify(options.plainJson ?? undefined),\n notifyAheadSeconds: options.notifyAheadSeconds,\n },\n },\n });\n }\n\n deleteReminder(id: LrRelayIdInput) {\n return this.mutate(this.deleteReminderMutation(id));\n }\n\n async deleteReminderMutation(id: LrRelayIdInput) {\n return new LrMutation({\n mutation: DeleteReminderMutation,\n variables: {\n input: {\n id,\n },\n },\n });\n }\n}\n","import { gqlTyped } from '../_common/ast';\n\nexport interface CreateScenarioMutationResult {\n createScenario: {\n scenario: {\n id: string;\n };\n };\n}\nexport const CreateScenarioMutation = gqlTyped<CreateScenarioMutationResult>`\nmutation CreateScenarioMutation($input: CreateScenarioInput!) {\n createScenario(input: $input) {\n scenario {\n id\n }\n }\n}\n`;\n\nexport interface UpdateScenarioMutationResult {\n updateScenario: {\n scenario: {\n id: string;\n };\n };\n}\nexport const UpdateScenarioMutation = gqlTyped<UpdateScenarioMutationResult>`\nmutation UpdateScenarioMutation($input: UpdateScenarioInput!) {\n updateScenario(input: $input) {\n scenario {\n id\n }\n }\n}\n`;\n\nexport interface DeleteScenarioMutationResult {\n deleteScenario: {\n id: string;\n };\n}\nexport const DeleteScenarioMutation = gqlTyped<DeleteScenarioMutationResult>`\nmutation DeleteScenarioMutation($input: DeleteScenarioInput!) {\n deleteScenario(input: $input) {\n id\n }\n}\n`;\n\nexport interface CreateScenarioClaimMutationResult {\n createScenarioClaim: {\n sharedClaim: {\n id: string;\n };\n };\n}\nexport const CreateScenarioClaimMutation = gqlTyped<CreateScenarioClaimMutationResult>`\nmutation CreateScenarioClaimMutation($input: CreateScenarioClaimInput!) {\n createScenarioClaim(input: $input) {\n sharedClaim {\n id\n }\n }\n}\n`;\n\nexport interface CancelScenarioClaimMutationResult {\n cancelScenarioClaim: {\n sharedClaim: {\n id: string;\n };\n };\n}\nexport const CancelScenarioClaimMutation = gqlTyped<CancelScenarioClaimMutationResult>`\nmutation CancelScenarioClaimMutation($input: CancelScenarioClaimInput!) {\n cancelScenarioClaim(input: $input) {\n sharedClaim {\n id\n }\n }\n}\n`;\n\nexport interface RejectScenarioClaimMutationResult {\n rejectScenarioClaim: {\n claimApprover: {\n id: string;\n };\n };\n}\nexport const RejectScenarioClaimMutation = gqlTyped<RejectScenarioClaimMutationResult>`\nmutation RejectScenarioClaimMutation($input: RejectScenarioClaimInput!) {\n rejectScenarioClaim(input: $input) {\n claimApprover {\n id\n }\n }\n}\n`;\n\nexport interface ApproveScenarioClaimMutationResult {\n approveScenarioClaim: {\n claimApprover: {\n id: string;\n };\n };\n}\nexport const ApproveScenarioClaimMutation = gqlTyped<ApproveScenarioClaimMutationResult>`\nmutation ApproveScenarioClaimMutation($input: ApproveScenarioClaimInput!) {\n approveScenarioClaim(input: $input) {\n claimApprover {\n id\n }\n }\n}\n`;\n\nexport interface ReceiveScenarioClaimMutationResult {\n receiveScenarioClaim2: {\n sharedClaim: {\n id: string;\n };\n };\n}\nexport const ReceiveScenarioClaimMutation = gqlTyped<ReceiveScenarioClaimMutationResult>`\nmutation ReceiveScenarioClaimMutation($input: ReceiveScenarioClaimInput!) {\n receiveScenarioClaim(input: $input) {\n sharedClaim {\n id\n }\n }\n}\n`;\n\nexport interface DebugExpireScenarioClaimMutationResult {\n debugExpireScenarioClaim: {\n scenarioClaim: {\n id: string;\n };\n };\n}\nexport const DebugExpireScenarioClaimMutation = gqlTyped<DebugExpireScenarioClaimMutationResult>`\nmutation DebugExpireScenarioClaimMutation($input: DebugExpireScenarioClaimInput!) {\n debugExpireScenarioClaim(input: $input) {\n scenarioClaim {\n id\n }\n }\n}\n`;\n\nexport interface DebugExpireTpPasswordResetRequestMutationResult {\n debugExpireTpPasswordResetRequest: {\n passwordResetRequest: {\n id: string;\n };\n };\n}\nexport const DebugExpireTpPasswordResetRequestMutation = gqlTyped<DebugExpireTpPasswordResetRequestMutationResult>`\nmutation DebugExpireTpPasswordResetRequestMutation($input: DebugExpireTpPasswordResetRequestInput!) {\n debugExpireTpPasswordResetRequest(input: $input) {\n passwordResetRequest {\n id\n }\n }\n}\n`;\n","export const SCENARIO_SLIP39_PASSPHRASE = 'lifeready';\n","import { Injectable, Injector, NgZone } from '@angular/core';\nimport { TpNode } from '../api/types';\nimport { TpAssemblyController } from '../tp-assembly/tp-assembly';\nimport { RunOutsideAngular } from '../_common/run-outside-angular';\nimport { SCENARIO_SLIP39_PASSPHRASE } from './scenario.constants';\n\n@RunOutsideAngular({\n ngZoneName: 'ngZone',\n})\n@Injectable({\n providedIn: 'root',\n})\nexport class ScenarioAssemblyController extends TpAssemblyController {\n slip39Passphrase = SCENARIO_SLIP39_PASSPHRASE;\n\n constructor(private ngZone: NgZone, private injector: Injector) {\n super(injector);\n }\n\n getTpWrappingKeyId(tp: TpNode) {\n return tp.currentUserSharedKey.userSharedKey.sharedKey.id;\n }\n}\n","import { ScenarioNode, SharedScenarioNode } from '../api/types';\nimport { gqlTyped } from '../_common/ast';\n\n/**\n * This is a query that is used internally by the services for mutations. It\n * contains the minimum amount of information for the information the services\n * need. You'll probably want to write your own query to your liking if you\n * want to retrieve a scenario. For example, there a separate query in the\n * scenario.service.spec.ts\n */\nexport interface ScenarioQueryResult {\n scenario: ScenarioNode;\n}\nexport const ScenarioQuery = gqlTyped<ScenarioQueryResult>`\nquery ScenarioQuery(\n $scenarioId: LrRelayIdInput!\n) {\n scenario(id: $scenarioId) {\n id\n state\n assembly {\n quorum\n singleReject\n assemblyKey {\n id\n }\n subjectKey {\n id\n }\n subjectCipherData\n subAssemblies {\n edges {\n node {\n id\n subjectKey {\n id\n }\n subjectCipherData\n quorum\n singleReject\n approvers {\n edges {\n node {\n id\n tp {\n id\n }\n sharedKey {\n id\n }\n }\n }\n }\n }\n }\n }\n }\n claimants {\n edges {\n node {\n tp {\n id\n }\n sharedKey {\n id\n }\n }\n }\n }\n receivers {\n edges {\n node {\n tp {\n id\n }\n sharedKey {\n id\n }\n sharedCipherData\n receiverItems {\n receiverDirectories {\n edges {\n node {\n id\n sharedCipherData\n sharedKey {\n id\n }\n accessRole\n directory {\n id\n keyId\n }\n }\n }\n }\n receiverFiles {\n edges {\n node {\n id\n sharedCipherData\n sharedKey {\n id\n }\n accessRole\n file {\n id\n keyId\n }\n }\n }\n }\n }\n }\n }\n }\n }\n}`;\n\nexport interface SharedScenarioQueryResult {\n sharedScenario: SharedScenarioNode;\n}\nexport const SharedScenarioQuery = gqlTyped<SharedScenarioQueryResult>`\nquery SharedScenarioQuery($scenarioId: LrRelayIdInput!) {\n sharedScenario(id: $scenarioId) {\n id\n state\n tp {\n id\n }\n asClaimant {\n sharedKey {\n id\n }\n sharedCipherData\n }\n asReceiver {\n sharedKey {\n id\n }\n sharedCipherData\n pbk {\n id\n }\n receiverItems {\n receiverDirectories {\n edges {\n node {\n id\n }\n }\n }\n }\n }\n assembly {\n asApprovers {\n edges {\n node {\n id\n sharedKey {\n id\n }\n sharedCipherData\n }\n }\n }\n }\n sharedClaim {\n\t \t\tid\n isClaimant\n claim {\n state\n asClaimApprovers {\n edges {\n node {\n id\n state\n sharedKey {\n id\n }\n sharedCipherApprovalData\n sharedCipherPartialAssemblyKey\n receiverApprovals {\n edges {\n node {\n id\n pxk {\n id\n }\n }\n }\n }\n }\n }\n }\n }\n asClaimReceiver {\n received\n assemblyKeyId\n approvals {\n edges {\n node {\n receiverCipher\n receiverCipherPartialAssemblyKey\n pxk {\n id\n }\n }\n }\n }\n }\n }\n }\n}\n`;\n","import { Injectable, Injector, NgZone } from '@angular/core';\nimport { JWK } from 'node-jose';\nimport { LrMergedMutation, LrMutation, LrService } from '../api/lr-graphql';\nimport {\n AccessRoleChoice,\n JSONObject,\n mapEdges,\n ScenarioNode,\n ScenarioReceiverNode,\n ScenarioState,\n SharedScenarioClaimReceivedApprovalNode,\n SharedTpClaimApproverNode,\n TpClaimApproverState,\n TpNode\n} from '../api/types';\nimport { EncryptionService } from '../encryption/encryption.service';\nimport { ItemService } from '../item/item.service';\nimport { IdKeyPair } from '../item/item.types';\nimport { KeyGraphService } from '../key/key-graph.service';\nimport { TpsKeysQuery } from '../tp-assembly/tp-assembly.private.gql';\nimport { PartialAssemblyKey } from '../tp-assembly/tp-assembly.types';\nimport {\n KcBadArgumentException,\n KcBadStateException\n} from '../_common/exceptions';\nimport { RunOutsideAngular } from '../_common/run-outside-angular';\nimport { assert_xor } from '../_common/utils';\nimport { ScenarioAssemblyController } from './scenario.controller';\nimport {\n ApproveScenarioClaimMutation,\n CancelScenarioClaimMutation,\n CreateScenarioClaimMutation,\n CreateScenarioMutation,\n DebugExpireScenarioClaimMutation,\n DeleteScenarioMutation,\n ReceiveScenarioClaimMutation,\n RejectScenarioClaimMutation,\n UpdateScenarioMutation\n} from './scenario.gql';\nimport { ScenarioQuery, SharedScenarioQuery } from './scenario.private.gql';\nimport {\n CreateClaimantOptions,\n CreateParticipantOptions,\n CreateReceiverOptions,\n CreateScenarioOptions,\n ParticipantOptions,\n ReceiverDirectoryOptions,\n ReceiverFileOptions,\n ReceiverItemOptions,\n ResetScenarioOptions,\n UpdateClaimantOptions,\n UpdateReceiverOptions,\n UpdateScenarioOptions\n} from './scenario.types';\n\nexport function throwClaimIdMismatch() {\n throw new KcBadArgumentException(\n 'claimId does not match with the current claimId of the scenario'\n );\n}\n\nexport function throwClaimNotApproved() {\n throw new KcBadStateException('Scenario claim has not been approved');\n}\n\n@RunOutsideAngular({\n ngZoneName: 'ngZone',\n})\n@Injectable({\n providedIn: 'root',\n})\nexport class ScenarioService extends LrService {\n constructor(\n private ngZone: NgZone,\n private injector: Injector,\n private keyGraph: KeyGraphService,\n private itemService: ItemService,\n private assemblyController: ScenarioAssemblyController,\n private encryptionService: EncryptionService\n ) {\n super(injector);\n }\n public static SLIP39_PASSPHRASE = 'lifeready';\n\n private prepareAddReceiverDirectory = this.prepareReceiverDirectory;\n private prepareUpdateReceiverDirectory = this.prepareReceiverDirectory;\n\n private prepareAddReceiverFile = this.prepareReceiverFile;\n private prepareUpdateReceiverFile = this.prepareReceiverFile;\n\n // Scenarios\n async createScenario(options: CreateScenarioOptions) {\n return this.mutate(this.createScenarioMutation(options));\n }\n\n async createScenarioMutation(options: CreateScenarioOptions) {\n const input = await this.prepareCreateScenarioMutation(options);\n return new LrMutation({\n mutation: CreateScenarioMutation,\n variables: {\n input,\n },\n });\n }\n\n async updateScenario(options: UpdateScenarioOptions) {\n return this.mutate(this.updateScenarioMutation(options));\n }\n\n async updateScenarioMutation(options: UpdateScenarioOptions) {\n const scenario = (await this.getScenario(options.scenarioId)).scenario;\n const input = await this.prepareUpdateScenario(options, scenario);\n return new LrMutation({\n mutation: UpdateScenarioMutation,\n variables: {\n input,\n },\n });\n }\n\n async resetScenario(options: ResetScenarioOptions) {\n return this.mutate(this.resetScenarioMutation(options));\n }\n\n async resetScenarioMutation(options: ResetScenarioOptions) {\n const scenario = (await this.getScenario(options.scenarioId)).scenario;\n\n const { assembly } = scenario;\n\n // Just need to do an update without changing approvers. This will recreate\n // all assembly keys.\n const updateSubAssemblies = mapEdges(assembly.subAssemblies).map((sa) => {\n const approverTps = mapEdges(sa.approvers).map((approver) => ({\n tpId: approver.tp.id,\n }));\n\n return {\n id: sa.id,\n quorum: sa.quorum,\n singleReject: sa.singleReject,\n subjectCipherDataClearJson: sa.subjectCipherDataClearJson,\n approverTps,\n };\n });\n\n const input = await this.prepareUpdateScenario(\n {\n scenarioId: options.scenarioId,\n enabled: options.enabled,\n updateAssembly: {\n quorum: assembly.quorum,\n singleReject: assembly.singleReject,\n updateSubAssemblies,\n },\n },\n scenario\n );\n\n return new LrMutation({\n mutation: UpdateScenarioMutation, // updating scenario resets it\n variables: {\n input,\n },\n });\n }\n\n async deleteScenario(scenarioId: string) {\n return this.lrGraphQL.lrMutate(this.deleteScenarioMutation(scenarioId));\n }\n\n async deleteScenarioMutation(scenarioId: string) {\n return new LrMutation({\n mutation: DeleteScenarioMutation,\n variables: { input: { scenarioId } },\n });\n }\n\n // Claims\n async createClaim(scenarioId: string) {\n return this.mutate(this.createClaimMutation(scenarioId));\n }\n\n async createClaimMutation(scenarioId: string) {\n return new LrMutation({\n mutation: CreateScenarioClaimMutation,\n variables: { input: { scenarioId } },\n });\n }\n\n async cancelClaim(claimId: string) {\n return this.mutate(this.cancelClaimMutation(claimId));\n }\n\n async cancelClaimMutation(claimId: string) {\n return new LrMutation({\n mutation: CancelScenarioClaimMutation,\n variables: { input: { claimId } },\n });\n }\n\n async rejectClaim(sharedScenarioId: string, claimId: string) {\n return this.mutate(this.rejectClaimMutation(sharedScenarioId, claimId));\n }\n\n async rejectClaimMutation(sharedScenarioId: string, claimId: string) {\n const mutations = await this.prepareRejectClaimMutations(\n sharedScenarioId,\n claimId\n );\n return LrMergedMutation.create(await Promise.all(mutations));\n }\n\n async approveClaim(sharedScenarioId: string, sharedClaimId: string) {\n // TODO this needs a cast so the result is not ANY.\n return this.mutate(\n this.approveClaimMutation(sharedScenarioId, sharedClaimId)\n );\n }\n\n async approveClaimMutation(sharedScenarioId: string, sharedClaimId: string) {\n const mutations = await this.prepareApproveClaimMutations(\n sharedScenarioId,\n sharedClaimId\n );\n return LrMergedMutation.create(await Promise.all(mutations));\n }\n\n async receiveClaim(scenarioId: string, sharedClaimId: string) {\n return this.mutate(this.receiveClaim2Mutation(scenarioId, sharedClaimId));\n }\n\n async receiveClaim2Mutation(scenarioId: string, sharedClaimId: string) {\n return new LrMutation({\n mutation: ReceiveScenarioClaimMutation,\n variables: {\n input: await this.prepareReceiveClaim2(scenarioId, sharedClaimId),\n },\n });\n }\n\n async debugExpireClaim(scenarioId: string) {\n return this.mutate(this.debugExpireClaimMutation(scenarioId));\n }\n\n async debugExpireClaimMutation(scenarioId: string) {\n return new LrMutation({\n mutation: DebugExpireScenarioClaimMutation,\n variables: {\n input: { scenarioId },\n },\n });\n }\n\n // --------------------------------------------------------------------------------\n // --------------------------------------------------------------------------------\n // Helpers\n // --------------------------------------------------------------------------------\n // --------------------------------------------------------------------------------\n private async getScenario(scenarioId: string) {\n return this.query({\n query: ScenarioQuery,\n variables: { scenarioId },\n });\n }\n\n private async getSharedScenario(scenarioId: string, claimId?: string) {\n const ret = await this.query({\n query: SharedScenarioQuery,\n variables: {\n scenarioId,\n },\n });\n\n if (claimId && ret.sharedScenario.sharedClaim.id !== claimId) {\n throwClaimIdMismatch();\n }\n\n return ret;\n }\n\n private async getParticipantTpsKeys(options: CreateParticipantOptions[]) {\n const tpIds = options.map((x) => x.tpId);\n\n // This should contain all the TPs that we need to update the assembly.\n const tps = mapEdges(\n (\n await this.lrGraphQL.query({\n query: TpsKeysQuery,\n variables: {\n ids: tpIds,\n },\n })\n ).tps\n );\n\n return tps;\n }\n\n private fillTpSharedKeyId(\n options: CreateParticipantOptions[],\n tps: TpNode[]\n ) {\n options.forEach((participant) => {\n if (!participant.tpSharedKeyId) {\n const tp = tps.find((x) => x.id === participant.tpId);\n participant.tpSharedKeyId =\n tp.currentUserSharedKey.userSharedKey.sharedKey.id;\n }\n });\n }\n\n private async prepareCreateScenarioMutation(options: CreateScenarioOptions) {\n const { assemblyKey, mutationInput: createAssembly } =\n await this.assemblyController.prepareCreate(options.createAssembly);\n\n const createReceiversOptions = options.createReceivers || [];\n const createClaimantsOptions = options.createClaimants || [];\n\n // Fetch all the TPs so we don't have to pass in tpSharedKeyId\n const creatParticipantsOptions = createReceiversOptions.concat(\n createClaimantsOptions\n );\n\n const tps = await this.getParticipantTpsKeys(creatParticipantsOptions);\n\n this.fillTpSharedKeyId(creatParticipantsOptions, tps);\n\n const createReceivers = await Promise.all(\n createReceiversOptions.map((receiver) =>\n this.prepareCreateReceiver(receiver, assemblyKey)\n )\n );\n\n const createClaimants = await Promise.all(\n createClaimantsOptions.map((x) => this.prepareCreateClaimant(x))\n );\n\n return {\n enabled: options.enabled,\n inactiveSeconds: options.inactiveSeconds,\n createAssembly,\n createReceivers,\n createClaimants,\n };\n }\n\n private async prepareUpdateScenario(\n options: UpdateScenarioOptions,\n scenario: ScenarioNode\n ) {\n let assemblyKey = await this.keyGraph.getJwkKey(\n scenario.assembly.assemblyKey.id\n );\n\n const updateAssembly = options.updateAssembly\n ? await (async () => {\n // Assembly key is always rotated when updating assembly.\n const result = await this.assemblyController.prepareUpdate(\n options.updateAssembly,\n scenario.assembly\n );\n // Use new assembly key.\n assemblyKey = result.assemblyKey;\n return result.mutationInput;\n })()\n : undefined;\n\n const createReceiversOptions = options.createReceivers || [];\n const createClaimantsOptions = options.createClaimants || [];\n\n // Fetch all the TPs so we don't have to pass in tpSharedKeyId\n const creatParticipantsOptions = createReceiversOptions.concat(\n createClaimantsOptions\n );\n\n const tps = await this.getParticipantTpsKeys(creatParticipantsOptions);\n\n this.fillTpSharedKeyId(creatParticipantsOptions, tps);\n\n const createReceivers =\n options.createReceivers &&\n (await Promise.all(\n options.createReceivers.map((x) =>\n this.prepareCreateReceiver(x, assemblyKey)\n )\n ));\n\n const existingReceivers = mapEdges(scenario.receivers);\n let updateReceivers = options.updateReceivers\n ? await Promise.all(\n options.updateReceivers.map((updateReceiver) => {\n // Find the receiver we are updating\n const existingReceiver = existingReceivers.find(\n (x) => x.tp.id === updateReceiver.tpId\n );\n\n return this.prepareUpdateReceiver(\n updateReceiver,\n assemblyKey,\n existingReceiver\n );\n })\n )\n : [];\n\n // Fill in any missing receivers when updating assembly.\n if (options.updateAssembly) {\n // Filter out the receivers that will be deleted or already updated.\n const existing = existingReceivers.filter(\n (existingReceiver) =>\n !(options.deleteReceivers || []).includes(existingReceiver.tp.id) &&\n !updateReceivers.some(\n (updateReceiver) => updateReceiver.tpId === existingReceiver.tp.id\n )\n );\n updateReceivers = updateReceivers.concat(\n await this.prepareExistingReceivers(existing, assemblyKey)\n );\n }\n\n const createClaimants =\n options.createClaimants &&\n (await Promise.all(\n options.createClaimants.map((x) => this.prepareCreateClaimant(x))\n ));\n\n const existingClaimants = mapEdges(scenario.claimants);\n const updateClaimants =\n options.updateClaimants &&\n (await Promise.all(\n options.updateClaimants.map((x) => {\n // Find the claimant we are updating\n const claimant = existingClaimants.find(\n (existingClaimant) => existingClaimant.tp.id === x.tpId\n );\n return this.prepareUpdateClaimant(x, claimant.sharedKey.id);\n })\n ));\n\n return {\n scenarioId: options.scenarioId,\n enabled: options.enabled,\n inactiveSeconds: options.inactiveSeconds,\n updateAssembly,\n createReceivers,\n updateReceivers,\n deleteReceivers: options.deleteReceivers,\n createClaimants,\n updateClaimants,\n deleteClaimants: options.deleteClaimants,\n };\n }\n\n private async prepareReceiverItem(options: {\n receiverItemOptions: ReceiverItemOptions;\n receiverSharedKey: JWK.Key;\n assemblyKey: JWK.Key;\n directory?: IdKeyPair;\n file?: IdKeyPair;\n }) {\n const {\n receiverItemOptions,\n receiverSharedKey,\n assemblyKey,\n directory,\n file,\n } = options;\n\n assert_xor({ directory, file });\n\n const { accessRole } = receiverItemOptions;\n\n if (accessRole == AccessRoleChoice.DENY) {\n const ret = {\n accessRole,\n itemKeyId: null,\n wrappedItemKey: null,\n sharedCipherData: null,\n };\n\n if (directory) {\n // Cryptographic access to item is not required.\n return {\n ...ret,\n directoryId: directory.id,\n };\n } else {\n return {\n ...ret,\n fileId: file.id,\n };\n }\n } else {\n // TODO this should be batched\n let itemKey;\n if (directory) {\n itemKey = await this.itemService.getDirectoryKey(\n directory.id,\n directory.keyId\n );\n } else {\n itemKey = await this.itemService.getFileKey(file.id, file.keyId);\n }\n\n let wrappedItemKey = await this.keyGraph.encryptToString(\n receiverSharedKey,\n itemKey.jwk.toJSON(true)\n );\n\n const sharedCipherData = await this.keyGraph.encryptToString(\n receiverSharedKey,\n receiverItemOptions.sharedCipherDataClearJson || ''\n );\n\n wrappedItemKey = await this.keyGraph.encryptToString(\n assemblyKey,\n wrappedItemKey\n );\n\n const ret = {\n accessRole,\n itemKeyId: itemKey.id,\n wrappedItemKey,\n sharedCipherData,\n };\n\n if (directory) {\n return {\n ...ret,\n directoryId: directory.id,\n };\n } else {\n return {\n ...ret,\n fileId: file.id,\n };\n }\n }\n }\n\n private async prepareReceiverDirectory(\n options: ReceiverDirectoryOptions,\n receiverSharedKey: JWK.Key,\n assemblyKey: JWK.Key\n ) {\n return this.prepareReceiverItem({\n receiverItemOptions: options,\n receiverSharedKey,\n assemblyKey,\n directory: {\n id: options.directoryId,\n keyId: options.directoryKeyId,\n },\n });\n }\n\n private async prepareReceiverFile(\n options: ReceiverFileOptions,\n receiverSharedKey: JWK.Key,\n assemblyKey: JWK.Key\n ) {\n return this.prepareReceiverItem({\n receiverItemOptions: options,\n receiverSharedKey,\n assemblyKey,\n file: {\n id: options.fileId,\n keyId: options.fileKeyId,\n },\n });\n }\n\n private async prepareCreateReceiver(\n options: CreateReceiverOptions,\n assemblyKey: JWK.Key\n ) {\n const { sharedKey, mutationInput } = await this.prepareCreateParticipant(\n options\n );\n\n const addDirectories =\n options.addDirectories &&\n (await Promise.all(\n options.addDirectories.map((x) =>\n this.prepareAddReceiverDirectory(x, sharedKey.key, assemblyKey)\n )\n ));\n\n const addFiles =\n options.addFiles &&\n (await Promise.all(\n options.addFiles.map((x) =>\n this.prepareAddReceiverFile(x, sharedKey.key, assemblyKey)\n )\n ));\n\n return {\n ...mutationInput,\n addDirectories,\n addFiles,\n };\n }\n\n private async prepareUpdateReceiver(\n options: UpdateReceiverOptions,\n assemblyKey: JWK.Key,\n existingReceiver: ScenarioReceiverNode\n ) {\n const sharedKeyId = existingReceiver.sharedKey.id;\n\n const deleteDirectoriesOptions = options.deleteDirectories || [];\n const updateDirectoriesOptions = options.updateDirectories || [];\n\n const deleteFilesOptions = options.deleteFiles || [];\n const updateFilesOptions = options.updateFiles || [];\n\n // Fill in any missing update directories\n mapEdges(existingReceiver.receiverItems.receiverDirectories).forEach(\n (existingDirectory) => {\n if (deleteDirectoriesOptions.includes(existingDirectory.directory.id)) {\n return;\n }\n\n if (\n updateDirectoriesOptions.find(\n (x) => x.directoryId === existingDirectory.directory.id\n )\n ) {\n return;\n }\n\n updateDirectoriesOptions.push({\n accessRole: existingDirectory.accessRole,\n directoryId: existingDirectory.directory.id,\n directoryKeyId: existingDirectory.directory.keyId,\n sharedCipherDataClearJson:\n existingDirectory.sharedCipherDataClearJson,\n });\n }\n );\n\n // Fill in any missing update files\n mapEdges(existingReceiver.receiverItems.receiverFiles).forEach(\n (existingFile) => {\n if (deleteFilesOptions.includes(existingFile.file.id)) {\n return;\n }\n\n if (updateFilesOptions.find((x) => x.fileId === existingFile.file.id)) {\n return;\n }\n\n updateFilesOptions.push({\n accessRole: existingFile.accessRole,\n fileId: existingFile.file.id,\n fileKeyId: existingFile.file.keyId,\n sharedCipherDataClearJson: existingFile.sharedCipherDataClearJson,\n });\n }\n );\n\n const { sharedKey, mutationInput } = await this.prepareUpdateParticipant(\n options,\n sharedKeyId\n );\n\n const addDirectories =\n options.addDirectories &&\n (await Promise.all(\n options.addDirectories.map((x) =>\n this.prepareAddReceiverDirectory(x, sharedKey, assemblyKey)\n )\n ));\n\n const addFiles =\n options.addFiles &&\n (await Promise.all(\n options.addFiles.map((x) =>\n this.prepareAddReceiverFile(x, sharedKey, assemblyKey)\n )\n ));\n\n const updateDirectories = await Promise.all(\n updateDirectoriesOptions.map((x) =>\n this.prepareUpdateReceiverDirectory(x, sharedKey, assemblyKey)\n )\n );\n\n const updateFiles = await Promise.all(\n updateFilesOptions.map((x) =>\n this.prepareUpdateReceiverFile(x, sharedKey, assemblyKey)\n )\n );\n\n return {\n ...mutationInput,\n addDirectories,\n addFiles,\n updateDirectories,\n updateFiles,\n deleteDirectories: options.deleteDirectories,\n deleteFiles: options.deleteFiles,\n };\n }\n\n private async prepareExistingReceiver(\n existingReceiver: ScenarioReceiverNode,\n assemblyKey: JWK.Key\n ) {\n const updateDirectories = mapEdges(\n existingReceiver.receiverItems.receiverDirectories\n ).map(({ accessRole, sharedCipherDataClearJson, directory }) => ({\n accessRole,\n sharedCipherDataClearJson,\n directoryId: directory.id,\n directoryKeyId: directory.keyId,\n }));\n\n const updateFiles = mapEdges(\n existingReceiver.receiverItems.receiverFiles\n ).map(({ accessRole, sharedCipherDataClearJson, file }) => ({\n accessRole,\n sharedCipherDataClearJson,\n fileId: file.id,\n fileKeyId: file.keyId,\n }));\n\n // Fill it in with existing receiver.\n return this.prepareUpdateReceiver(\n {\n tpId: existingReceiver.tp.id,\n sharedCipherDataClearJson: existingReceiver.sharedCipherDataClearJson,\n updateDirectories,\n updateFiles,\n },\n assemblyKey,\n existingReceiver\n );\n }\n\n private async prepareExistingReceivers(\n existingReceivers: ScenarioReceiverNode[],\n assemblyKey: JWK.Key\n ) {\n return Promise.all(\n existingReceivers.map((existingReceiver) =>\n this.prepareExistingReceiver(existingReceiver, assemblyKey)\n )\n );\n }\n\n private async prepareCreateParticipant(options: CreateParticipantOptions) {\n const sharedKey = await this.keyGraph.encryptWithNewKey(\n options.tpSharedKeyId,\n options.sharedCipherDataClearJson || ''\n );\n return {\n sharedKey,\n mutationInput: {\n tpId: options.tpId,\n tpSharedKeyId: options.tpSharedKeyId,\n tpSharedKeyWrappedSharedKey: sharedKey.wrappedKey,\n sharedCipherData: sharedKey.cipher,\n },\n };\n }\n\n private async prepareUpdateParticipant(\n options: ParticipantOptions,\n sharedKeyId: string\n ) {\n const sharedKey = await this.keyGraph.getJwkKey(sharedKeyId);\n\n const sharedCipherData = await this.keyGraph.encryptToString(\n sharedKey,\n options.sharedCipherDataClearJson || ''\n );\n\n return {\n sharedKey,\n mutationInput: {\n tpId: options.tpId,\n sharedKeyId,\n sharedCipherData,\n },\n };\n }\n\n private async prepareCreateClaimant(options: CreateClaimantOptions) {\n const { mutationInput } = await this.prepareCreateParticipant(options);\n return mutationInput;\n }\n\n private async prepareUpdateClaimant(\n options: UpdateClaimantOptions,\n sharedKeyId: string\n ) {\n const { mutationInput } = await this.prepareUpdateParticipant(\n options,\n sharedKeyId\n );\n\n return mutationInput;\n }\n\n async prepareReceiveClaim2(scenarioId: string, sharedClaimId: string) {\n // Get all the shared items\n const sharedScenario = (\n await this.getSharedScenario(scenarioId, sharedClaimId)\n ).sharedScenario;\n\n if (sharedScenario.state !== ScenarioState.APPROVED) {\n throwClaimNotApproved();\n }\n\n const approvals = mapEdges(\n sharedScenario.sharedClaim.asClaimReceiver.approvals\n );\n\n const assemblyKey = await this.recoverAssemblyKey(approvals);\n\n // Wrap assembly key with shared key.\n //???\n // This sharedKey is created just for this scenario. It's wrapped by the tpSharedKey.\n const sharedKey = await this.keyGraph.getKey(\n sharedScenario.asReceiver.sharedKey.id\n );\n\n const sharedKeyWrappedAssemblyKey = await this.keyGraph.encryptToString(\n sharedKey,\n assemblyKey.toJSON(true)\n );\n\n return {\n scenarioClaimId: sharedClaimId,\n sharedKeyWrappedAssemblyKey,\n sharedKeyId: sharedKey.id,\n assemblyKeyId: sharedScenario.sharedClaim.asClaimReceiver.assemblyKeyId,\n };\n }\n\n // async prepareReceiveClaim(scenarioId: string, sharedClaimId: string) {\n // // Get all the shared items\n // const sharedScenario = (\n // await this.getSharedScenario(scenarioId, sharedClaimId)\n // ).sharedScenario;\n\n // if (sharedScenario.state !== ScenarioState.APPROVED) {\n // throwClaimNotApproved();\n // }\n\n // const approvals = mapEdges(\n // sharedScenario.sharedClaim.asClaimReceiver.approvals\n // );\n\n // const assemblyKey = await this.recoverAssemblyKey(approvals);\n\n // // Decrypt all items\n // const receiverDirectories = await Promise.all(\n // sharedScenario.asReceiver.receiverItems.receiverDirectories.edges\n // .map((edge) => edge.node)\n // .map(async (receiverDirectory) => {\n // const wrappedItemKey = await this.encryptionService.decrypt(\n // assemblyKey,\n // receiverDirectory.wrappedItemKey\n // );\n\n // return {\n // receiverDirectoryId: receiverDirectory.id,\n // // Looks like receiverDirectory.wrappedItemKey has no other content in side it except a wrapped key.\n // // So we can turn this in to a doubly wrapped key and just release the assembly key.\n\n // receiverSharedKeyWrappedItemKey: wrappedItemKey, // the wrappedItemKey is already wrapped by receiverSharedKey\n // };\n // })\n // );\n\n // return {\n // scenarioClaimId: sharedClaimId,\n // receiverDirectories,\n // };\n // }\n\n private async recoverAssemblyKey(\n approvals: SharedScenarioClaimReceivedApprovalNode[]\n ) {\n const partials = await Promise.all(\n approvals.map((approval) =>\n this.keyGraph.decryptFromString<PartialAssemblyKey>(\n approval.pxk.id,\n approval.receiverCipherPartialAssemblyKey\n )\n )\n );\n\n return this.assemblyController.recoverAssemblyKey(partials);\n }\n\n private async asClaimApprovers(\n sharedScenarioId,\n claimId,\n state: TpClaimApproverState\n ) {\n const sharedScenario = (\n await this.getSharedScenario(sharedScenarioId, claimId)\n ).sharedScenario;\n\n return mapEdges(sharedScenario.sharedClaim.claim.asClaimApprovers).filter(\n (asClaimApprover) => asClaimApprover.state === state\n );\n }\n\n private async prepareApproveClaimMutations(\n sharedScenarioId: string,\n claimId: string\n ) {\n // The current user may be acting as approvers in multiple sub-assemblies so\n // we approve them all.\n const asClaimApprovers = await this.asClaimApprovers(\n sharedScenarioId,\n claimId,\n TpClaimApproverState.CLAIMED\n );\n\n return asClaimApprovers.map(\n async (asClaimApprover) =>\n new LrMutation({\n mutation: ApproveScenarioClaimMutation,\n variables: {\n input: await this.prepareApproveClaim(asClaimApprover),\n },\n })\n );\n }\n\n private async prepareApproveClaim(\n asClaimApprover: SharedTpClaimApproverNode\n ) {\n const receiverApprovals = await Promise.all(\n mapEdges(asClaimApprover.receiverApprovals).map((receiverApproval) =>\n this.prepareReceiverApproval({\n receiverApprovalId: receiverApproval.id,\n receiverApprovalPxkId: receiverApproval.pxk.id,\n sharedCipherPartialAssemblyKeyClearJson:\n asClaimApprover.sharedCipherPartialAssemblyKeyClearJson,\n })\n )\n );\n\n return {\n claimApproverId: asClaimApprover.id,\n receiverApprovals,\n };\n }\n\n private async prepareReceiverApproval(options: {\n receiverApprovalId: string;\n receiverApprovalPxkId: string;\n sharedCipherPartialAssemblyKeyClearJson: JSONObject;\n }) {\n return {\n receiverApprovalId: options.receiverApprovalId,\n // TODO allow sending of messages to receiver.\n receiverCipher: '',\n receiverCipherPartialAssemblyKey: await this.keyGraph.encryptToString(\n options.receiverApprovalPxkId,\n options.sharedCipherPartialAssemblyKeyClearJson\n ),\n };\n }\n\n private async prepareRejectClaimMutations(\n sharedScenarioId: string,\n claimId: string\n ) {\n // The current user may be acting as approvers in multiple sub-assemblies so\n // we reject them all.\n const asClaimApprovers = await this.asClaimApprovers(\n sharedScenarioId,\n claimId,\n TpClaimApproverState.CLAIMED\n );\n\n return asClaimApprovers.map(\n async (asClaimApprover) =>\n new LrMutation({\n mutation: RejectScenarioClaimMutation,\n variables: {\n input: { claimApproverId: asClaimApprover.id },\n },\n })\n );\n }\n}\n","import { ServerConfig } from '../api/types';\nimport { gqlTyped } from '../_common/ast';\n\nexport interface ServerConfigQueryResult {\n serverConfig: Pick<Required<ServerConfig>, 'relayConnectionMaxLimit'>;\n}\nexport const ServerConfigQuery = gqlTyped<ServerConfigQueryResult>`\nquery ServerConfigQuery {\n serverConfig {\n relayConnectionMaxLimit\n }\n}\n`;\n","import { Injectable, Injector, NgZone } from '@angular/core';\nimport { LrService } from '../api/lr-graphql';\nimport { RunOutsideAngular } from '../_common/run-outside-angular';\nimport {\n ServerConfigQuery,\n ServerConfigQueryResult,\n} from './server-config.gql';\n\n@RunOutsideAngular({\n ngZoneName: 'ngZone',\n})\n@Injectable({\n providedIn: 'root',\n})\nexport class ServerConfigService extends LrService {\n private serverConfig: ServerConfigQueryResult['serverConfig']; // cache\n\n constructor(private ngZone: NgZone, private injector: Injector) {\n super(injector);\n }\n\n async getConfig() {\n if (this.serverConfig == null) {\n this.serverConfig = (\n await this.query({\n query: ServerConfigQuery,\n includeKeyGraph: false,\n })\n ).serverConfig;\n }\n\n return this.serverConfig;\n }\n}\n","import { ID } from '../api/types';\nimport { gqlTyped } from '../_common/ast';\n\nexport interface UpdateOwnedContactCardMutation {\n updateOwnedContactCard: {\n ownedContactCard: {\n id: ID;\n };\n };\n}\nexport const UpdateOwnedContactCardMutation = gqlTyped<UpdateOwnedContactCardMutation>`\nmutation UpdateOwnedContactCardMutation(\n $input: UpdateOwnedContactCardInput!\n) {\n updateOwnedContactCard(input: $input) {\n ownedContactCard {\n id\n }\n }\n}`;\n\nexport interface UpdateReceivedContactCardMutation {\n updateReceivedContactCard: {\n receivedContactCard: {\n id: ID;\n };\n };\n}\nexport const UpdateReceivedContactCardMutation = gqlTyped<UpdateReceivedContactCardMutation>`\nmutation UpdateReceivedContactCardMutation(\n $input: UpdateReceivedContactCardInput!\n) {\n updateReceivedContactCard(input: $input) {\n receivedContactCard {\n id\n }\n }\n}`;\n\nexport interface GetOwnedContactCardKeyIdsQuery {\n ownedContactCard: {\n sharedKey: {\n id: ID;\n };\n ownerKey: {\n id: ID;\n };\n };\n}\nexport const GetOwnedContactCardKeyIdsQuery = gqlTyped<GetOwnedContactCardKeyIdsQuery>`\nquery GetOwnedContactCardKeyIdsQuery($id: LrRelayIdInput!) {\n ownedContactCard(id: $id) {\n sharedKey {\n id\n }\n ownerKey {\n id\n }\n }\n}`;\n\nexport interface GetReceivedContactCardKeyIdQuery {\n receivedContactCard: {\n receiverKey: {\n id: ID;\n };\n };\n}\nexport const GetReceivedContactCardKeyIdQuery = gqlTyped<GetReceivedContactCardKeyIdQuery>`\nquery GetReceivedContactCardKeyIdQuery($id: LrRelayIdInput!) {\n receivedContactCard(id: $id) {\n receiverKey {\n id\n }\n }\n}`;\n","import { Injectable, NgZone } from '@angular/core';\nimport { LrGraphQLService, LrMutation } from '../api/lr-graphql';\nimport { LrRelayIdInput } from '../api/types';\nimport { EncryptionService } from '../encryption/encryption.service';\nimport {\n ContactCardReceiverCipherData,\n SendContactCardInput,\n} from '../key-exchange/key-exchange.service';\nimport { KeyGraphService } from '../key/key-graph.service';\nimport { KeyService } from '../key/key.service';\nimport { Key } from '../key/key.types';\nimport { RunOutsideAngular } from '../_common/run-outside-angular';\nimport {\n GetOwnedContactCardKeyIdsQuery,\n GetReceivedContactCardKeyIdQuery,\n UpdateOwnedContactCardMutation,\n UpdateReceivedContactCardMutation,\n} from './shared-contact-card2.gql';\n\nexport interface UpdateOwnedContactCardInput extends SendContactCardInput {\n id: LrRelayIdInput;\n ownerKeyId?: LrRelayIdInput;\n sharedKeyId?: LrRelayIdInput;\n}\n\nexport interface UpdateReceivedContactCardInput\n extends ContactCardReceiverCipherData {\n id: LrRelayIdInput;\n receiverKeyId?: LrRelayIdInput;\n}\n\n@RunOutsideAngular({\n ngZoneName: 'ngZone',\n})\n@Injectable({\n providedIn: 'root',\n})\nexport class SharedContactCard2Service {\n constructor(\n private ngZone: NgZone,\n private keyService: KeyService,\n private keyGraph: KeyGraphService,\n private encryptionService: EncryptionService,\n private lrGraphQL: LrGraphQLService\n ) {}\n\n private async getOwnedContactCardKeyIds(id: LrRelayIdInput) {\n const { ownedContactCard: cc } = await this.lrGraphQL.query({\n query: GetOwnedContactCardKeyIdsQuery,\n variables: {\n id,\n },\n });\n\n return {\n sharedKeyId: cc.sharedKey.id,\n ownerKeyId: cc.ownerKey.id,\n };\n }\n\n private async getReceivedContactCardKeyId(id: LrRelayIdInput) {\n return (\n await this.lrGraphQL.query({\n query: GetReceivedContactCardKeyIdQuery,\n variables: {\n id,\n },\n })\n ).receivedContactCard.receiverKey.id;\n }\n\n async updateOwnedContactCard({\n id,\n ownerKeyId,\n sharedKeyId,\n ownerPlainDataJson,\n ownerCipherDataClearJson,\n sharedCipherDataClearJson,\n }: UpdateOwnedContactCardInput) {\n let ownerKey: Key;\n let sharedKey: Key;\n\n try {\n ownerKey = await this.keyGraph.getKey(ownerKeyId);\n sharedKey = await this.keyGraph.getKey(sharedKeyId);\n } catch (error) {\n const keys = await this.getOwnedContactCardKeyIds(id);\n\n // try again\n ownerKey = await this.keyGraph.getKey(keys.ownerKeyId);\n sharedKey = await this.keyGraph.getKey(keys.sharedKeyId);\n }\n\n const sigPxk = this.keyService.currentSigPxk;\n\n const sharedCipherData = await this.encryptionService.encrypt(\n sharedKey.jwk,\n sharedCipherDataClearJson\n );\n const sharedCipherDataSig = JSON.stringify(\n await this.encryptionService.sign(sigPxk.jwk, sharedCipherData)\n );\n\n const ownerPlainDataSig = JSON.stringify(\n await this.encryptionService.sign(sigPxk.jwk, ownerPlainDataJson)\n );\n\n const ownerCipherData = await this.encryptionService.encryptToString(\n ownerKey.jwk,\n ownerCipherDataClearJson\n );\n\n return new LrMutation({\n mutation: UpdateOwnedContactCardMutation,\n variables: {\n input: {\n id,\n ownerCipherData,\n ownerKeyId: ownerKey.id,\n sharedCipherDataSig,\n sharedKeyId: sharedKey.id,\n sigPxkId: sigPxk.id,\n ownerPlainDataSig,\n },\n },\n });\n }\n\n async updateReceivedContactCard({\n id,\n receiverKeyId,\n receiverCipherDataClearJson,\n }: UpdateReceivedContactCardInput) {\n const receiverKey = await this.keyGraph.getKey(receiverKeyId, () =>\n this.getReceivedContactCardKeyId(id)\n );\n\n const receiverCipherData = await this.encryptionService.encryptToString(\n receiverKey.jwk,\n receiverCipherDataClearJson\n );\n\n return new LrMutation({\n mutation: UpdateReceivedContactCardMutation,\n variables: {\n input: {\n id,\n receiverCipherData,\n receiverKeyId: receiverKey.id,\n },\n },\n });\n }\n}\n","import { GenericScalar, ID } from '../api/types';\nimport { DateTime, JSONObject } from '../api/types/graphql.types';\nimport {\n TpClaimApproverState,\n TpClaimState,\n} from '../api/types/lr-graphql.types';\nimport { gqlTyped } from '../_common/ast';\n\nexport interface SharedTpPasswordResetFragmentResult {\n id: ID;\n tp: {\n id: ID;\n other: {\n username: string;\n };\n };\n assembly: {\n asApprovers: {\n edges: {\n node: {\n id: ID;\n sharedKey: {\n id: ID;\n };\n sharedCipherData: string;\n sharedCipherDataClearJson: JSONObject;\n };\n }[];\n };\n };\n sharedRequest: {\n id: ID;\n pxk: {\n id: ID;\n pbk: string;\n };\n claim: {\n id: ID;\n state: TpClaimState;\n asClaimApprovers: {\n edges: {\n node: {\n id: ID;\n state: TpClaimApproverState;\n sharedKey: {\n id: ID;\n };\n sharedCipherApprovalData: string;\n sharedCipherApprovalDataClearJson: JSONObject;\n sharedCipherPartialAssemblyKey: string;\n sharedCipherPartialAssemblyKeyClearJson: JSONObject;\n receiverApprovals: {\n edges: {\n node: {\n id: ID;\n };\n }[];\n };\n };\n }[];\n };\n };\n };\n}\nconst SharedTpPasswordResetFragment = gqlTyped<SharedTpPasswordResetFragmentResult>`\nfragment SharedTpPasswordResetFragment on SharedTpPasswordResetNode {\n id\n tp {\n id\n other {\n username\n }\n }\n assembly {\n asApprovers {\n edges {\n node {\n id\n sharedKey {\n id\n }\n sharedCipherData\n }\n }\n }\n }\n sharedRequest {\n id\n pxk {\n id\n pbk\n }\n claim {\n id\n state\n asClaimApprovers {\n edges {\n node {\n id\n state\n sharedKey {\n id\n }\n sharedCipherApprovalData\n sharedCipherPartialAssemblyKey\n receiverApprovals {\n edges {\n node {\n id\n }\n }\n }\n }\n }\n }\n }\n }\n}`;\n\nexport interface SharedTpPasswordResetsQueryResult {\n sharedTpPasswordResets: {\n edges: {\n node: SharedTpPasswordResetFragmentResult;\n }[];\n };\n}\nexport const SharedTpPasswordResetsQuery = gqlTyped<SharedTpPasswordResetsQueryResult>`\nquery SharedTpPasswordResetsQuery {\n sharedTpPasswordResets {\n edges {\n node {\n ...SharedTpPasswordResetFragment\n }\n }\n }\n}\n${SharedTpPasswordResetFragment}\n`;\n\nexport interface SharedTpPasswordResetQueryResult {\n sharedTpPasswordReset: SharedTpPasswordResetFragmentResult;\n}\nexport const SharedTpPasswordResetQuery = gqlTyped<SharedTpPasswordResetQueryResult>`\nquery SharedTpPasswordResetQuery($id: LrRelayIdInput!) {\n sharedTpPasswordReset(id: $id) {\n ...SharedTpPasswordResetFragment\n }\n}\n${SharedTpPasswordResetFragment}\n`;\n\nexport interface TpPasswordResetUserQueryResult {\n tpPasswordResetUser: {\n username: string;\n resetUsername: string;\n state: TpClaimState;\n passKey: {\n id: ID;\n passKeyParams: GenericScalar;\n passIdpParams: GenericScalar;\n };\n masterKey: {\n id: ID;\n };\n pxk: {\n id: ID;\n };\n sessionEncryptionKey: string;\n assembly: {\n singleReject: boolean;\n quorum: number;\n subAssemblies: {\n singleReject: boolean;\n quorum: number;\n approvers: {\n name: string;\n email: string;\n state: TpClaimApproverState;\n }[];\n }[];\n };\n approvals: {\n id: ID;\n modified: DateTime;\n approverEmail: string;\n receiverCipher: string;\n receiverCipherPartialAssemblyKey: string;\n }[];\n assemblyCipherData: string;\n wrappedAssemblyKeyVerifierPrk: string;\n requestAgainAfter: DateTime;\n };\n}\nexport const TpPasswordResetUserQuery = gqlTyped<TpPasswordResetUserQueryResult>`\nquery TpPasswordResetUserQuery {\n tpPasswordResetUser {\n username\n resetUsername\n state\n passKey {\n id\n passKeyParams\n passIdpParams\n }\n masterKey {\n id\n }\n pxk {\n id\n }\n sessionEncryptionKey\n assembly {\n singleReject\n quorum\n subAssemblies {\n singleReject\n quorum\n approvers {\n name\n email\n state\n }\n }\n }\n approvals {\n id\n modified\n approverEmail\n receiverCipher\n receiverCipherPartialAssemblyKey\n }\n assemblyCipherData\n wrappedAssemblyKeyVerifierPrk\n requestAgainAfter\n }\n}`;\n\nexport interface TpPasswordResetQueryResult {\n tpPasswordReset: {\n id: ID;\n applied: boolean;\n assembly: {\n singleReject: boolean;\n quorum: number;\n canMeetQuorum: boolean;\n subjectCipherData: string;\n subjectCipherDataClearJson: JSONObject;\n subjectKey: {\n id: ID;\n };\n assemblyKey: {\n id: ID;\n };\n assemblyCipherData: string;\n subAssemblies: {\n edges: {\n node: {\n id: ID;\n singleReject: boolean;\n quorum: number;\n subjectCipherData: string;\n subjectCipherDataClearJson: JSONObject;\n subjectKey: {\n id: ID;\n };\n approvers: {\n edges: {\n node: {\n id: ID;\n tp: {\n id: ID;\n };\n sharedKey: {\n id: ID;\n };\n sharedCipherData: string;\n };\n }[];\n };\n };\n }[];\n };\n };\n };\n}\nexport const TpPasswordResetQuery = gqlTyped<TpPasswordResetQueryResult>`\nquery TpPasswordResetQuery {\n tpPasswordReset {\n id\n applied\n assembly {\n singleReject\n quorum\n canMeetQuorum\n subjectCipherData\n subjectKey {\n id\n }\n assemblyKey {\n id\n }\n assemblyCipherData\n subAssemblies {\n edges {\n node {\n id\n singleReject\n quorum\n subjectCipherData\n subjectKey {\n id\n }\n approvers {\n edges {\n node {\n id\n tp {\n id\n }\n sharedKey {\n id\n }\n sharedCipherData\n }\n }\n }\n }\n }\n }\n }\n }\n}`;\n","import { Injectable, Injector, NgZone } from '@angular/core';\nimport { LrService } from '../api/lr-graphql';\nimport { RunOutsideAngular } from '../_common/run-outside-angular';\nimport {\n SharedTpPasswordResetQuery,\n SharedTpPasswordResetsQuery,\n TpPasswordResetQuery,\n} from './tp-password-reset.private.gql';\n\n@RunOutsideAngular({\n ngZoneName: 'ngZone',\n})\n@Injectable({\n providedIn: 'root',\n})\nexport class TpPasswordResetPrivateService extends LrService {\n constructor(private ngZone: NgZone, private injector: Injector) {\n super(injector);\n }\n\n async getReset() {\n return (\n await this.query({\n query: TpPasswordResetQuery,\n })\n ).tpPasswordReset;\n }\n\n async getSharedResets() {\n return (\n await this.query({\n query: SharedTpPasswordResetsQuery,\n })\n ).sharedTpPasswordResets;\n }\n\n async getSharedReset(id) {\n return (\n await this.query({\n query: SharedTpPasswordResetQuery,\n variables: {\n id,\n },\n })\n ).sharedTpPasswordReset;\n }\n}\n","import { Injectable, Injector, NgZone } from '@angular/core';\nimport { JWK } from 'node-jose';\nimport { LrMergedMutation, LrMutation, LrService } from '../api/lr-graphql';\nimport { TpAssemblyState, TpClaimApproverState } from '../api/types';\nimport { EncryptionService } from '../encryption/encryption.service';\nimport { KcBadStateException } from '../_common/exceptions';\nimport { RunOutsideAngular } from '../_common/run-outside-angular';\nimport {\n ApproveTpPasswordResetRequestMutation,\n RejectTpPasswordResetRequestMutation,\n} from './tp-password-reset.gql';\nimport { TpPasswordResetPrivateService } from './tp-password-reset.private.service';\n\n@RunOutsideAngular({\n ngZoneName: 'ngZone',\n})\n@Injectable({\n providedIn: 'root',\n})\nexport class TpPasswordResetRequestService extends LrService {\n constructor(\n private ngZone: NgZone,\n private injector: Injector,\n private encryptionService: EncryptionService,\n private privateService: TpPasswordResetPrivateService\n ) {\n super(injector);\n }\n\n private activeRequestOrRaise(sharedReset): void {\n const state = sharedReset.sharedRequest.claim.state;\n if (state !== TpAssemblyState.CLAIMED) {\n throw new KcBadStateException(`Claim is already in ${state} state.`);\n }\n }\n\n rejectRequest(sharedResetId: string) {\n return this.mutate(this.rejectRequestMutation(sharedResetId));\n }\n\n async rejectRequestMutation(sharedResetId: string) {\n const sharedReset = await this.privateService.getSharedReset(sharedResetId);\n\n this.activeRequestOrRaise(sharedReset);\n\n return LrMergedMutation.create(\n sharedReset.sharedRequest.claim.asClaimApprovers.edges\n .filter((edge) => edge.node.state === TpClaimApproverState.CLAIMED)\n .map(\n (edge) =>\n new LrMutation({\n mutation: RejectTpPasswordResetRequestMutation,\n variables: { input: { claimApproverId: edge.node.id } },\n })\n )\n );\n }\n\n async approveRequest(sharedResetId: string, pbkFingerPrint?: string) {\n return this.lrGraphQL.lrMutate(\n await this.approveRequestMutation(sharedResetId, pbkFingerPrint)\n );\n }\n\n async approveRequestMutation(\n sharedResetId: string,\n _pbkFingerPrint?: string\n ) {\n const sharedReset = await this.privateService.getSharedReset(sharedResetId);\n\n this.activeRequestOrRaise(sharedReset);\n\n const pbk = await JWK.asKey(JSON.parse(sharedReset.sharedRequest.pxk.pbk));\n\n // TODO <AZ> Verify pbk against pbkFingerPrint\n\n const claimApprovers =\n sharedReset.sharedRequest.claim.asClaimApprovers.edges.filter(\n (edge) => edge.node.state === TpClaimApproverState.CLAIMED\n );\n\n // A single approver may belong to multiple sub-assemblies. We approve them all here in a single\n // transaction.\n return LrMergedMutation.create(\n await Promise.all(\n claimApprovers.map(async (approverEdge) => {\n const ca = approverEdge.node;\n const input = {\n claimApproverId: ca.id,\n receiverApprovals: await Promise.all(\n ca.receiverApprovals.edges.map(async (receiverEdge) => {\n const ra = receiverEdge.node;\n return {\n receiverApprovalId: ra.id,\n receiverCipher: '',\n receiverCipherPartialAssemblyKey:\n await this.encryptionService.encryptToString(\n pbk,\n ca.sharedCipherPartialAssemblyKeyClearJson\n ),\n };\n })\n ),\n };\n\n return new LrMutation({\n mutation: ApproveTpPasswordResetRequestMutation,\n variables: {\n input,\n },\n });\n })\n )\n );\n }\n}\n","import { KcBadArgumentException } from './exceptions';\n\nconst COGNITO_LOCALSTORAGE_PREFIX = 'CognitoIdentityServiceProvider';\n\n/**\n * Remove all keys in localstorage with matching prefix.\n * A prefix must be specified. If you want to remove everything, then just use localStorage.clear().\n *\n * @param prefix Keys with this prefix will be removed.\n */\nexport function clearLocalStorage(prefix: string) {\n if (!prefix) {\n throw new KcBadArgumentException('You must specify a non empty prefix.');\n }\n\n // Remove all persisted session variables\n Object.keys(localStorage).forEach((key) => {\n if (key.startsWith(prefix)) {\n localStorage.removeItem(key);\n }\n });\n}\n\n/**\n * Clear all items related to cognito in localstorage.\n * The remember device function sometimes interferes with creating new users\n * on TP based password reset.\n */\nexport function clearCognitoLocalStorage() {\n clearLocalStorage(COGNITO_LOCALSTORAGE_PREFIX);\n}\n","import { HttpClient } from '@angular/common/http';\nimport { Inject, Injectable, Injector, NgZone } from '@angular/core';\nimport { AuthClass } from '@aws-amplify/auth/lib-esm/Auth';\nimport { ISignUpResult } from 'amazon-cognito-identity-js';\nimport { LrService } from '../api/lr-graphql';\nimport { EncryptionService } from '../encryption/encryption.service';\nimport { KeyFactoryService } from '../key/key-factory.service';\nimport { KcConfig, KC_CONFIG } from '../life-ready.config';\nimport { PasswordService } from '../password/password.service';\nimport { RunOutsideAngular } from '../_common/run-outside-angular';\nimport { clearCognitoLocalStorage } from '../_common/storage';\nimport { RequestResetResult } from './tp-password-reset.types';\n\n@RunOutsideAngular({\n ngZoneName: 'ngZone',\n})\n@Injectable({\n providedIn: 'root',\n})\nexport class TpPasswordResetUserService extends LrService {\n constructor(\n private ngZone: NgZone,\n private injector: Injector,\n @Inject(KC_CONFIG) private config: KcConfig,\n private keyFactory: KeyFactoryService,\n private encryptionService: EncryptionService,\n private passwordService: PasswordService,\n private http: HttpClient,\n private auth: AuthClass\n ) {\n super(injector);\n }\n\n async verifyEmailContact(email): Promise<{ claimId: string }> {\n const params = {\n email,\n };\n return (\n this.http\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n .post<any>(\n `${this.config.authUrl}tp/password-reset/verify-contact/`,\n params\n )\n .toPromise()\n );\n }\n\n async verifyContactRespond(\n claimId: string,\n claimCode: string\n ): Promise<string> {\n const { token } = await this.http\n .post<{ token }>(`${this.config.authUrl}cove/respond/`, {\n claim_id: claimId,\n v_code: claimCode,\n })\n .toPromise();\n return token;\n }\n\n async requestReset(\n password: CryptoKey,\n claimId: string,\n claimToken: string\n ): Promise<{\n requestResetResult: RequestResetResult;\n signUpResult: ISignUpResult;\n }> {\n // Clearing all localstorage data because cognito has the \"remember device\" functionality which sometimes\n // does not work properly. Clearing localstorage seems to solve this issue.\n clearCognitoLocalStorage();\n\n // Generate the key materials\n const passKeyBundle = await this.passwordService.createPassKeyBundle(\n password\n );\n\n const masterKey = await this.keyFactory.createKey();\n const wrappedMasterKey = await this.encryptionService.encrypt(\n passKeyBundle.passKey,\n masterKey.toJSON(true)\n );\n\n // Ephemeral PKC key\n const prk = await this.keyFactory.createPkcKey();\n const masterKeyWrappedPrk = await this.encryptionService.encrypt(\n masterKey,\n prk.toJSON(true)\n );\n\n // API call to setup reset request\n const requestResetResult = await this.http\n .post<RequestResetResult>(\n `${this.config.authUrl}tp/password-reset/request/`,\n {\n claimId,\n claimToken,\n pass_key_params: passKeyBundle.passKeyParams,\n pass_idp_params: passKeyBundle.passIdpParams,\n pass_idp_verifier_pbk: passKeyBundle.passIdpVerifier.toJSON(), // public key\n wrapped_pass_idp_verifier_prk:\n passKeyBundle.wrappedPassIdpVerifierPrk,\n wrapped_master_key: wrappedMasterKey,\n pbk: prk.toJSON(), // ephemeral public key\n master_key_wrapped_prk: masterKeyWrappedPrk,\n }\n )\n .toPromise();\n\n console.log('Using new password');\n\n // API call to create user on cognito\n const signUpResult = await this.auth.signUp({\n username: requestResetResult.reset_username,\n password: this.passwordService.getPassIdpString(passKeyBundle.passIdp),\n clientMetadata: {\n tp_password_reset_request: JSON.stringify({\n id: requestResetResult.id,\n associate_reset_user_token:\n requestResetResult.associate_reset_user_token,\n }),\n },\n });\n\n console.log('requestRest done');\n\n return {\n requestResetResult,\n signUpResult,\n };\n }\n}\n","import { Injectable, Injector, NgZone } from '@angular/core';\nimport { LrMutation, LrService } from '../api/lr-graphql';\nimport { TpNode } from '../api/types';\nimport { DebugExpireTpPasswordResetRequestMutation } from '../scenario/scenario.gql';\nimport {\n CreateTpAssemblyInput,\n UpdateTpAssemblyInput,\n} from '../tp-assembly/tp-assembly.types';\nimport { RunOutsideAngular } from '../_common/run-outside-angular';\nimport { TP_PASSWORD_RESET_SLIP39_PASSPHRASE } from './tp-password-reset.constants';\nimport { TpPasswordResetAssemblyController } from './tp-password-reset.controller';\nimport {\n CancelTpPasswordResetRequestMutation,\n CreateTpPasswordResetMutation,\n DeleteTpPasswordResetMutation,\n UpdateTpPasswordResetMutation,\n} from './tp-password-reset.gql';\nimport { TpPasswordResetPrivateService } from './tp-password-reset.private.service';\n\n@RunOutsideAngular({\n ngZoneName: 'ngZone',\n})\n@Injectable({\n providedIn: 'root',\n})\nexport class TpPasswordResetService extends LrService {\n slip39Passphrase = TP_PASSWORD_RESET_SLIP39_PASSPHRASE;\n\n constructor(\n private ngZone: NgZone,\n private injector: Injector,\n private privateService: TpPasswordResetPrivateService,\n private assemblyController: TpPasswordResetAssemblyController\n ) {\n super(injector);\n }\n\n cancelResetRequest() {\n return this.mutate(this.cancelResetRequestMutation());\n }\n\n cancelResetRequestMutation() {\n return new LrMutation({\n mutation: CancelTpPasswordResetRequestMutation,\n });\n }\n\n deleteReset() {\n return this.mutate(this.deleteResetMutation());\n }\n\n deleteResetMutation() {\n return new LrMutation({\n mutation: DeleteTpPasswordResetMutation,\n });\n }\n\n validateApprovers(approvers: TpNode[]): void {\n return this.assemblyController.validateApprovers(approvers);\n }\n\n createReset(input: CreateTpAssemblyInput) {\n return this.mutate(this.createResetMutation(input));\n }\n\n async createResetMutation(input: CreateTpAssemblyInput) {\n const { mutationInput } = await this.assemblyController.prepareCreate(\n input\n );\n\n return new LrMutation({\n mutation: CreateTpPasswordResetMutation,\n variables: {\n input: {\n assembly: {\n ...mutationInput,\n },\n },\n },\n });\n }\n\n updateReset(input: UpdateTpAssemblyInput) {\n return this.mutate(this.updateResetMutation(input));\n }\n\n async updateResetMutation(input: UpdateTpAssemblyInput) {\n const passwordReset = await this.privateService.getReset();\n\n const { mutationInput } = await this.assemblyController.prepareUpdate(\n input,\n passwordReset.assembly\n );\n\n return new LrMutation({\n mutation: UpdateTpPasswordResetMutation,\n variables: {\n input: {\n assembly: {\n ...mutationInput,\n },\n },\n },\n });\n }\n\n debugExpireResetRequest(username: string) {\n return this.mutate(this.debugExpireResetRequestMutation(username), {\n includeKeyGraph: false,\n });\n }\n\n async debugExpireResetRequestMutation(username: string) {\n return new LrMutation({\n mutation: DebugExpireTpPasswordResetRequestMutation,\n variables: {\n input: {\n username,\n },\n },\n });\n }\n}\n","import { ID } from '../api/types';\nimport { gqlTyped } from '../_common/ast';\n\nexport interface DeleteTpMutation {\n deleteTp: {\n id: ID;\n };\n}\nexport const DeleteTpMutation = gqlTyped<DeleteTpMutation>`\nmutation DeleteTpMutation($input: DeleteTpInput!) {\n deleteTp(input: $input) {\n id\n }\n}\n`;\n\nexport interface CreateDirectoryShareMutationResult {\n createDirectoryShare: {\n directoryShare: {\n id: ID;\n };\n };\n}\nexport const CreateDirectoryShareMutation = gqlTyped<CreateDirectoryShareMutationResult>`\nmutation CreateDirectoryShareMutation($input: CreateDirectoryShareInput!) {\n createDirectoryShare(input: $input) {\n directoryShare {\n id\n }\n }\n}\n`;\n\nexport interface CreateFileShareMutationResult {\n createFileShare: {\n fileShare: {\n id: ID;\n };\n };\n}\nexport const CreateFileShareMutation = gqlTyped<CreateFileShareMutationResult>`\nmutation CreateFileShareMutation($input: CreateFileShareInput!) {\n createFileShare(input: $input) {\n fileShare {\n id\n }\n }\n}\n`;\n\nexport interface UpdateDirectoryShareMutationResult {\n updateDirectoryShare: {\n directoryShare: {\n id: ID;\n };\n };\n}\nexport const UpdateDirectoryShareMutation = gqlTyped<UpdateDirectoryShareMutationResult>`\nmutation UpdateDirectoryShareMutation($input: UpdateDirectoryShareInput!) {\n updateDirectoryShare(input: $input) {\n directoryShare {\n id\n }\n }\n}\n`;\n\nexport interface UpdateFileShareMutationResult {\n updateFileShare: {\n fileShare: {\n id: ID;\n };\n };\n}\nexport const UpdateFileShareMutation = gqlTyped<UpdateFileShareMutationResult>`\nmutation UpdateFileShareMutation($input: UpdateFileShareInput!) {\n updateFileShare(input: $input) {\n fileShare {\n id\n }\n }\n}\n`;\n\nexport interface DeleteDirectoryShareMutationResult {\n deleteDirectoryShare: {\n id: ID;\n };\n}\nexport const DeleteDirectoryShareMutation = gqlTyped<DeleteDirectoryShareMutationResult>`\nmutation DeleteDirectoryShareMutation($input: DeleteDirectoryShareInput!) {\n deleteDirectoryShare(input: $input) {\n id\n }\n}\n`;\n\nexport interface DeleteFileShareMutationResult {\n deleteFileShare: {\n id: ID;\n };\n}\nexport const DeleteFileShareMutation = gqlTyped<DeleteFileShareMutationResult>`\nmutation DeleteFileShareMutation($input: DeleteFileShareInput!) {\n deleteFileShare(input: $input) {\n id\n }\n}\n`;\n\nexport interface CompleteDetachedDirectoryShareMutationResult {\n completeDetachedDirectoryShare: {\n directoryShare: {\n id: ID;\n };\n };\n}\nexport const CompleteDetachedDirectoryShareMutation = gqlTyped<CompleteDetachedDirectoryShareMutationResult>`\nmutation CompleteDetachedDirectoryShareMutation($input: CompleteDetachedDirectoryShareInput!) {\n completeDetachedDirectoryShare(input: $input) {\n directoryShare {\n id\n }\n }\n}\n`;\n\nexport interface CompleteDetachedFileShareMutationResult {\n completeDetachedDirectoryShare: {\n directoryShare: {\n id: ID;\n };\n };\n}\nexport const CompleteDetachedFileShareMutation = gqlTyped<CompleteDetachedFileShareMutationResult>`\nmutation CompleteDetachedFileShareMutation($input: CompleteDetachedFileShareInput!) {\n completeDetachedFileShare(input: $input) {\n fileShare {\n id\n }\n }\n}\n`;\n\nexport interface RequestTpMkReshareMutation {\n requestTpMkReshare: {\n id: ID;\n };\n}\nexport const RequestTpMkReshareMutation = gqlTyped<RequestTpMkReshareMutation>`\nmutation RequestTpMkReshareMutation($input: RequestTpMkReshareInput!) {\n requestTpMkReshare(input: $input) {\n id\n }\n}`;\n\nexport interface RespondTpMkReshareMutation {\n respondTpMkReshare: {\n id: ID;\n };\n}\nexport const RespondTpMkReshareMutation = gqlTyped<RespondTpMkReshareMutation>`\n mutation RespondTpMkReshareMutation($input: RespondTpMkReshareInput!) {\n respondTpMkReshare(input: $input) {\n id\n }\n }\n`;\n\nexport interface CompleteTpMkReshareMutation {\n completeTpMkReshare: {\n id: ID;\n };\n}\nexport const CompleteTpMkReshareMutation = gqlTyped<CompleteTpMkReshareMutation>`\nmutation CompleteTpMkReshareMutation($input: CompleteTpMkReshareInput!) {\n completeTpMkReshare(input: $input) {\n id\n }\n}`;\n","import { ID, ShareTypeChoice } from '../api/types';\nimport { gqlTyped } from '../_common/ast';\n\nexport interface TpCurrentUserSharedKeyQuery {\n tp: {\n currentUserSharedKey: {\n userSharedKey: {\n sharedKey: {\n id: ID;\n };\n mkSharedKey: {\n id: ID;\n };\n mkPxk: {\n id: ID;\n };\n mkReshareRequestCipher: string;\n mkReshareRequestSent: boolean;\n mkReshareResponseCipher: string;\n mkReshareResponseSent: boolean;\n };\n };\n };\n}\nexport const TpCurrentUserSharedKeyQuery = gqlTyped<TpCurrentUserSharedKeyQuery>`\nquery TpCurrentUserSharedKeyQuery($id: LrRelayIdInput!) {\n tp(id: $id){\n currentUserSharedKey {\n userSharedKey {\n sharedKey {\n id\n }\n mkSharedKey {\n id\n }\n mkPxk {\n id\n }\n mkReshareRequestCipher\n mkReshareRequestSent\n mkReshareResponseCipher\n mkReshareResponseSent\n }\n }\n }\n}\n`;\n\nexport interface ItemShareQueryResult {\n item: {\n id: string;\n };\n tp: {\n id: string;\n };\n shareType: ShareTypeChoice;\n}\n\nexport interface DirectoryShareQueryResult {\n directoryShare: ItemShareQueryResult;\n}\nexport const DirectoryShareQuery = gqlTyped<DirectoryShareQueryResult>`\nquery DirectoryShareQuery($id: LrRelayIdInput!) {\n directoryShare(id: $id) {\n item {\n id\n }\n tp {\n id\n }\n shareType\n }\n}\n`;\n\nexport interface FileShareQueryResult {\n fileShare: ItemShareQueryResult;\n}\nexport const FileShareQuery = gqlTyped<FileShareQueryResult>`\nquery FileShareItemIdQuery($id: LrRelayIdInput!) {\n fileShare(id: $id) {\n item {\n id\n }\n tp {\n id\n }\n shareType\n }\n}\n`;\n","import { Injectable, Injector, NgZone } from '@angular/core';\nimport { JWK } from 'node-jose';\nimport { LrMutation, LrService } from '../api/lr-graphql';\nimport {\n AccessRoleChoice,\n LrRelayIdInput,\n ShareTypeChoice,\n} from '../api/types';\nimport { EncryptionService } from '../encryption/encryption.service';\nimport { ItemService } from '../item/item.service';\nimport { KeyFactoryService } from '../key/key-factory.service';\nimport { KeyGraphService } from '../key/key-graph.service';\nimport { KeyService } from '../key/key.service';\nimport { Key } from '../key/key.types';\nimport {\n KcBadArgumentException,\n KcBadStateException,\n} from '../_common/exceptions';\nimport { RunOutsideAngular } from '../_common/run-outside-angular';\nimport {\n CompleteDetachedDirectoryShareMutation,\n CompleteDetachedFileShareMutation,\n CompleteTpMkReshareMutation,\n CreateDirectoryShareMutation,\n CreateFileShareMutation,\n DeleteDirectoryShareMutation,\n DeleteFileShareMutation,\n DeleteTpMutation,\n RequestTpMkReshareMutation,\n RespondTpMkReshareMutation,\n UpdateDirectoryShareMutation,\n UpdateFileShareMutation,\n} from './trusted-party.gql';\nimport {\n DirectoryShareQuery,\n DirectoryShareQueryResult,\n FileShareQuery,\n FileShareQueryResult,\n ItemShareQueryResult,\n TpCurrentUserSharedKeyQuery,\n} from './trusted-party.gql.private';\nimport {\n CompleteDetachedItemShareOptions,\n CreateItemShareOptions,\n UpdateDetachedItemShareOptions,\n UpdateItemShareOptions,\n} from './trusted-party.types';\n\n@RunOutsideAngular({\n ngZoneName: 'ngZone',\n})\n@Injectable({\n providedIn: 'root',\n})\nexport class TrustedPartyService extends LrService {\n constructor(\n private ngZone: NgZone,\n private injector: Injector,\n private keyGraph: KeyGraphService,\n private itemService: ItemService,\n private keyService: KeyService,\n private keyFactory: KeyFactoryService,\n private encryptionService: EncryptionService\n ) {\n super(injector);\n }\n\n deleteTp(tpId: LrRelayIdInput) {\n return this.mutate(this.deleteTpMutation(tpId));\n }\n\n deleteTpMutation(tpId: LrRelayIdInput) {\n return new LrMutation({\n mutation: DeleteTpMutation,\n variables: {\n input: {\n id: tpId,\n },\n },\n });\n }\n\n async createDirectoryShare(options: CreateItemShareOptions) {\n return this.mutate(this.createDirectoryShareMutation(options));\n }\n\n async createDirectoryShareMutation(options: CreateItemShareOptions) {\n return new LrMutation({\n mutation: CreateDirectoryShareMutation,\n variables: await this.prepareCreateItemShareMutation({\n ...options,\n isDirectory: true,\n }),\n });\n }\n\n async createFileShare(options: CreateItemShareOptions) {\n return this.mutate(this.createFileShareMutation(options));\n }\n\n async createFileShareMutation(options: CreateItemShareOptions) {\n return new LrMutation({\n mutation: CreateFileShareMutation,\n variables: await this.prepareCreateItemShareMutation({\n ...options,\n isDirectory: false,\n }),\n });\n }\n\n private async prepareCreateItemShareMutation(\n options: CreateItemShareOptions & { isDirectory: boolean }\n ) {\n const {\n itemId,\n itemKeyId,\n tpId,\n tpSharedKeyId,\n accessRole,\n isDirectory,\n shareType,\n plainMetaJson,\n } = options;\n\n const plainMeta = plainMetaJson && JSON.stringify(plainMetaJson);\n\n if (accessRole == AccessRoleChoice.DENY) {\n if (itemKeyId || tpSharedKeyId) {\n throw new KcBadArgumentException(\n 'If accessRole is AccessRoleChoice.DENY, must not specify any of itemId, itemKeyId, or tpSharedKeyId parameters'\n );\n }\n\n return {\n input: {\n itemId,\n tpId,\n accessRole,\n itemKeyId: null,\n wrappingKeyId: null,\n wrappedItemKey: null,\n shareType,\n plainMeta,\n },\n };\n }\n\n const itemKey = await this.keyGraph.getKey(itemKeyId, () =>\n isDirectory\n ? this.itemService.getDirectoryKeyId(itemId)\n : this.itemService.getFileKeyId(itemId)\n );\n\n const wrappingKey = await this.keyGraph.getKey(tpSharedKeyId, () =>\n this.getTpCurrentUserSharedKey(tpId).then((res) => res.sharedKey.id)\n );\n const wrappedItemKey = await this.keyGraph.wrapKey(\n wrappingKey,\n itemKey.jwk\n );\n\n return {\n input: {\n itemId,\n tpId,\n accessRole,\n itemKeyId: itemKey.id,\n wrappingKeyId: wrappingKey.id,\n wrappedItemKey,\n shareType,\n plainMeta,\n },\n };\n }\n\n async updateDirectoryShare(options: UpdateItemShareOptions) {\n return this.mutate(this.updateDirectoryShareMutation(options));\n }\n\n async updateDirectoryShareMutation(options: UpdateItemShareOptions) {\n return new LrMutation({\n mutation: UpdateDirectoryShareMutation,\n variables: await this.prepareUpdateItemShareMutation({\n ...options,\n isDirectory: true,\n }),\n });\n }\n\n async updateDetachedDirectoryShare(options: UpdateDetachedItemShareOptions) {\n return this.mutate(this.updateDetachedDirectoryShareMutation(options));\n }\n\n async updateDetachedDirectoryShareMutation(\n options: UpdateDetachedItemShareOptions\n ) {\n return new LrMutation({\n mutation: UpdateDirectoryShareMutation,\n variables: await this.prepareUpdateDetachedItemShareMutation(options),\n });\n }\n\n async updateFileShare(options: UpdateItemShareOptions) {\n return this.mutate(this.updateFileShareMutation(options));\n }\n\n async updateFileShareMutation(options: UpdateItemShareOptions) {\n return new LrMutation({\n mutation: UpdateFileShareMutation,\n variables: await this.prepareUpdateItemShareMutation({\n ...options,\n isDirectory: false,\n }),\n });\n }\n\n async updateDetachedFileShare(options: UpdateDetachedItemShareOptions) {\n return this.mutate(this.updateDetachedFileShareMutation(options));\n }\n\n async updateDetachedFileShareMutation(\n options: UpdateDetachedItemShareOptions\n ) {\n return new LrMutation({\n mutation: UpdateFileShareMutation,\n variables: await this.prepareUpdateDetachedItemShareMutation(options),\n });\n }\n\n private getDirectoryShare(\n itemShareId: string\n ): Promise<DirectoryShareQueryResult> {\n return this.lrGraphQL.query({\n query: DirectoryShareQuery,\n variables: {\n id: itemShareId,\n },\n });\n }\n\n private getFileShare(itemShareId: string): Promise<FileShareQueryResult> {\n return this.lrGraphQL.query({\n query: FileShareQuery,\n variables: {\n id: itemShareId,\n },\n });\n }\n\n private async prepareUpdateItemShareMutation(\n options: UpdateItemShareOptions & { isDirectory: boolean }\n ) {\n const {\n itemShareId,\n accessRole,\n isDirectory,\n itemId,\n itemKeyId,\n tpId,\n tpSharedKeyId,\n plainMetaJson,\n } = options;\n\n // If plainMetaJson is undefined, then plainMeta is undefined\n // If plainMetaJson is null, then plainMeta is null\n // If plainMetaJson has value, then plainMeta is JSON.stringify(plainMetaJson)\n const plainMeta = plainMetaJson && JSON.stringify(plainMetaJson);\n\n // If not updating access role or updating to DENY role, then we don't need any key material.\n if (accessRole == null || accessRole == AccessRoleChoice.DENY) {\n if (itemId || itemKeyId || tpId || tpSharedKeyId) {\n throw new KcBadArgumentException(\n 'If accessRole is AccessRoleChoice.DENY, must not specify any of itemId, itemKeyId, tpId, or tpSharedKeyId parameters'\n );\n }\n\n return {\n input: {\n id: itemShareId,\n accessRole,\n plainMeta,\n },\n };\n }\n\n // Caching the result so we only need one call.\n let itemShare: ItemShareQueryResult;\n\n const getItemShare = async (): Promise<ItemShareQueryResult> => {\n if (!itemShare) {\n if (isDirectory) {\n itemShare = (await this.getDirectoryShare(itemShareId))\n .directoryShare;\n } else {\n itemShare = (await this.getFileShare(itemShareId)).fileShare;\n }\n\n if (itemShare.shareType == ShareTypeChoice.DETACHED) {\n throw new KcBadArgumentException(\n 'Use updateDetachedDirectoryShare() or updateDetachedFileShare() to updated DETACHED shares.'\n );\n }\n }\n\n return itemShare;\n };\n\n const itemKey = await this.keyGraph.getKey(\n itemKeyId,\n async (): Promise<string> => {\n const itemId_ = itemId || (await getItemShare()).item.id;\n if (isDirectory) {\n return this.itemService.getDirectoryKeyId(itemId_);\n } else {\n return this.itemService.getFileKeyId(itemId_);\n }\n }\n );\n\n const wrappingKey = await this.keyGraph.getKey(\n tpSharedKeyId,\n async (): Promise<string> => {\n const tpId_ = tpId || (await getItemShare()).tp.id;\n return (await this.getTpCurrentUserSharedKey(tpId_)).sharedKey.id;\n }\n );\n\n const wrappedItemKey = await this.keyGraph.wrapKey(\n wrappingKey,\n itemKey.jwk\n );\n\n return {\n input: {\n id: itemShareId,\n accessRole,\n itemKeyId: itemKey.id,\n wrappingKeyId: wrappingKey.id,\n wrappedItemKey,\n plainMeta,\n },\n };\n }\n\n private async prepareUpdateDetachedItemShareMutation(\n options: UpdateDetachedItemShareOptions\n ) {\n const { itemShareId, accessRole, plainMetaJson } = options;\n\n return {\n input: {\n id: itemShareId,\n accessRole,\n plainMeta: plainMetaJson && JSON.stringify(plainMetaJson),\n },\n };\n }\n\n async deleteDirectoryShare(id: string) {\n return this.mutate(this.deleteDirectoryShareMutation(id));\n }\n\n async deleteDirectoryShareMutation(id: string) {\n return new LrMutation({\n mutation: DeleteDirectoryShareMutation,\n variables: {\n input: {\n id,\n },\n },\n });\n }\n\n async deleteFileShare(id: string) {\n return this.mutate(this.deleteFileShareMutation(id));\n }\n\n async deleteFileShareMutation(id: string) {\n return new LrMutation({\n mutation: DeleteFileShareMutation,\n variables: {\n input: {\n id,\n },\n },\n });\n }\n\n async completeDetachedDirectoryShare(\n options: CompleteDetachedItemShareOptions\n ) {\n return this.mutate(this.completeDetachedDirectoryShareMutation(options));\n }\n\n async completeDetachedDirectoryShareMutation(\n options: CompleteDetachedItemShareOptions\n ) {\n return new LrMutation({\n mutation: CompleteDetachedDirectoryShareMutation,\n variables: await this.prepareCompleteDetachedItemShareMutation({\n ...options,\n isDirectory: true,\n }),\n });\n }\n\n async completeDetachedFileShare(options: CompleteDetachedItemShareOptions) {\n return this.mutate(this.completeDetachedFileShareMutation(options));\n }\n\n async completeDetachedFileShareMutation(\n options: CompleteDetachedItemShareOptions\n ) {\n return new LrMutation({\n mutation: CompleteDetachedFileShareMutation,\n variables: await this.prepareCompleteDetachedItemShareMutation({\n ...options,\n isDirectory: false,\n }),\n });\n }\n\n private async prepareCompleteDetachedItemShareMutation(\n options: CompleteDetachedItemShareOptions & { isDirectory: boolean }\n ) {\n const { itemShareId, itemKeyId, isDirectory } = options;\n\n const itemKey = await this.keyGraph.getKey(itemKeyId, () =>\n isDirectory\n ? this.itemService.getDirectoryKeyIdFromDirectoryShare(itemShareId)\n : this.itemService.getFileKeyIdFromFileShare(itemShareId)\n );\n\n const rootKey = this.keyService.currentRootKey;\n\n const wrappedKey = await this.keyGraph.wrapKey(rootKey, itemKey.jwk);\n\n return {\n input: {\n id: itemShareId,\n keyId: itemKey.id,\n wrappingKeyId: rootKey.id,\n wrappedKey,\n },\n };\n }\n\n async requestMkReshareMutation(tpId: LrRelayIdInput) {\n const userSharedKey = await this.getTpCurrentUserSharedKey(tpId);\n\n if (userSharedKey.mkSharedKey) {\n throw new KcBadStateException('TP already has mkSharedKey');\n }\n\n const masterKey = this.keyService.currentMasterKey;\n const prk = await this.keyFactory.createPkcKey();\n const mkWrappedMkPrk = await this.encryptionService.encryptToString(\n masterKey.jwk,\n prk.toJSON(true)\n );\n\n const sharedKey = await this.keyGraph.getKey(userSharedKey.sharedKey.id);\n const mkReshareRequestCipher = await this.encryptionService.encryptToString(\n sharedKey.jwk,\n {\n pbk: prk.toJSON(),\n }\n );\n\n return await new LrMutation({\n mutation: RequestTpMkReshareMutation,\n variables: {\n input: {\n tpId,\n masterKeyId: masterKey.id,\n mkPbk: JSON.stringify(prk.toJSON()),\n mkWrappedMkPrk,\n sharedKeyId: sharedKey.id,\n mkReshareRequestCipher,\n },\n },\n });\n }\n\n async respondMkReshare(tpId: LrRelayIdInput) {\n const userSharedKey = await this.getTpCurrentUserSharedKey(tpId);\n\n if (!userSharedKey.mkSharedKey) {\n throw new KcBadStateException(\n 'No access to the mkSharedKey so cannot reshare it with TP'\n );\n }\n\n const sharedKey = await this.keyGraph.getKey(userSharedKey.sharedKey.id);\n const plainMkReshareRequestCipher = await this.encryptionService.decrypt(\n sharedKey,\n userSharedKey.mkReshareRequestCipher\n );\n const pbk = await JWK.asKey(plainMkReshareRequestCipher.pbk);\n const mkSharedKey = await this.keyGraph.getKey(\n userSharedKey.mkSharedKey.id\n );\n\n const plainMkReshareResponseCipher = {\n mkSharedKey: {\n id: mkSharedKey.id,\n jwk: mkSharedKey.jwk.toJSON(true),\n },\n };\n\n // Wrap with sharedKey then again with Pbk\n const mkReshareResponseCipher =\n await this.encryptionService.encryptToString(\n pbk,\n await this.encryptionService.encryptToString(\n sharedKey.jwk,\n plainMkReshareResponseCipher\n )\n );\n\n return new LrMutation({\n mutation: RespondTpMkReshareMutation,\n variables: {\n input: {\n tpId,\n mkSharedKeyId: mkSharedKey.id,\n mkReshareResponseCipher,\n },\n },\n });\n }\n\n async completeMkReshare(tpId: LrRelayIdInput) {\n const userSharedKey = await this.getTpCurrentUserSharedKey(tpId);\n\n const sharedKey = await this.keyGraph.getKey(userSharedKey.sharedKey.id);\n const prk = await this.keyGraph.getKey(userSharedKey.mkPxk.id);\n const plainMkReshareResponseCipher = await this.encryptionService.decrypt(\n sharedKey,\n await this.encryptionService.decrypt(\n prk,\n userSharedKey.mkReshareResponseCipher\n )\n );\n\n // Double check it's a valid key.\n const mkSharedKey: Key = {\n id: plainMkReshareResponseCipher.mkSharedKey.id,\n jwk: await JWK.asKey(plainMkReshareResponseCipher.mkSharedKey.jwk),\n };\n\n const masterKey = this.keyService.currentMasterKey;\n const mkWrappedMkSharedKey = await this.encryptionService.encryptToString(\n masterKey.jwk,\n mkSharedKey.jwk.toJSON(true)\n );\n\n return new LrMutation({\n mutation: CompleteTpMkReshareMutation,\n variables: {\n input: {\n tpId,\n masterKeyId: masterKey.id,\n mkSharedKeyId: mkSharedKey.id,\n mkWrappedMkSharedKey,\n },\n },\n });\n }\n\n // ------------------------------------------------------------------------------------\n // ------------------------------------------------------------------------------------\n // Helpers\n // ------------------------------------------------------------------------------------\n // ------------------------------------------------------------------------------------\n private async getTpCurrentUserSharedKey(tpId: LrRelayIdInput) {\n return (\n await this.lrGraphQL.query({\n query: TpCurrentUserSharedKeyQuery,\n variables: {\n id: tpId,\n },\n })\n ).tp.currentUserSharedKey.userSharedKey;\n }\n}\n","import { Injectable } from '@angular/core';\nimport { CognitoUser } from '@aws-amplify/auth';\nimport { AuthClass } from '@aws-amplify/auth/lib-esm/Auth';\nimport { KcBadArgumentException } from '../_common/exceptions';\n\n@Injectable({\n providedIn: 'root',\n})\nexport class TwoFactorService {\n constructor(private auth: AuthClass) {}\n\n public async getPreferredMFA(): Promise<string> {\n const cognitoUser: CognitoUser = await this.auth.currentAuthenticatedUser();\n\n return await this.auth.getPreferredMFA(cognitoUser);\n }\n\n public async setPreferredMFA(\n method: 'TOTP' | 'SMS' | 'NOMFA'\n ): Promise<void> {\n const cognitoUser: CognitoUser = await this.auth.currentAuthenticatedUser();\n\n await this.auth.setPreferredMFA(cognitoUser, method);\n }\n\n public async setPhoneNumber(phone): Promise<void> {\n const cognitoUser: CognitoUser = await this.auth.currentAuthenticatedUser();\n\n await this.auth.updateUserAttributes(cognitoUser, {\n phone_number: phone,\n });\n }\n\n public async getSMSCode() {\n await this.auth.verifyCurrentUserAttribute('phone_number');\n }\n\n public async verifySMSCode(verificationCode: string) {\n await this.auth.verifyCurrentUserAttributeSubmit(\n 'phone_number',\n verificationCode\n );\n }\n\n public async getSoftwareToken(): Promise<{ code: string; codeUri: string }> {\n const [cognitoUser, userInfo] = await Promise.all([\n this.auth.currentAuthenticatedUser(),\n this.auth.currentUserInfo(),\n ]);\n\n const code = await this.auth.setupTOTP(cognitoUser);\n\n const email = userInfo.attributes.email;\n if (!email) {\n throw new KcBadArgumentException('No email associated with user.');\n }\n\n return {\n code,\n codeUri: `otpauth://totp/${email}?secret=${code}&issuer=LifeReady`,\n };\n }\n\n public async verifySoftwareToken(totpCode: string): Promise<void> {\n const cognitoUser: CognitoUser = await this.auth.currentAuthenticatedUser();\n\n await this.auth.verifyTotpToken(cognitoUser, totpCode);\n }\n}\n","import gql from 'graphql-tag';\nimport { HasKeyGraph } from '../key/key.types';\nimport { User } from './user.types';\n\nexport interface UserQueryType extends HasKeyGraph {\n user: User;\n}\n\nexport const RequestUserDeleteMutation = gql`\n mutation RequestUserDelete($input: RequestUserDeleteInput!) {\n requestUserDelete(input: $input) {\n userDelete {\n state\n created\n }\n }\n }\n`;\n\nexport const CancelUserDeleteMutation = gql`\n mutation CancelUserDelete($input: CancelUserDeleteInput!) {\n cancelUserDelete(input: $input) {\n id\n }\n }\n`;\n\nexport const LoginHistoryQuery = gql`\n query LoginHistory($first: Int, $after: String) {\n loginHistory(first: $first, after: $after) {\n pageInfo {\n hasNextPage\n hasPreviousPage\n startCursor\n endCursor\n }\n events\n }\n }\n`;\n","/* eslint-disable @typescript-eslint/no-explicit-any */\nimport { Injectable } from '@angular/core';\nimport { LrApolloService } from '../api/lr-apollo.service';\nimport { UserDeleteNode } from '../api/types';\nimport {\n CancelUserDeleteMutation,\n LoginHistoryQuery,\n RequestUserDeleteMutation,\n} from './user.gql';\n\n@Injectable({\n providedIn: 'root',\n})\nexport class UserService {\n constructor(private lrApollo: LrApolloService) {}\n\n async requestUserDelete(): Promise<UserDeleteNode> {\n const res = await this.lrApollo.mutate<{ requestUserDelete: any }>({\n mutation: RequestUserDeleteMutation,\n variables: {\n input: {},\n },\n });\n\n return res.requestUserDelete.userDelete;\n }\n\n async cancelUserDelete(): Promise<string> {\n const res = await this.lrApollo.mutate<{ cancelUserDelete: any }>({\n mutation: CancelUserDeleteMutation,\n variables: {\n input: {},\n },\n });\n\n return res.cancelUserDelete.id;\n }\n\n async loginHistory(first: number = null, after: string = null): Promise<any> {\n // first: return first n entries\n // after: pass in the pageInfo.endCursor to paginate\n const res = await this.lrApollo.query<{ loginHistory: any }>({\n query: LoginHistoryQuery,\n variables: {\n first,\n after,\n },\n });\n\n return res.loginHistory;\n }\n}\n","/*\n * Public API Surface of lr-auth\n */\n\nexport * from './lib/api/lr-apollo.service';\nexport * from './lib/api/lr-graphql';\nexport * from './lib/api/query-processor';\nexport * from './lib/api/types';\nexport * from './lib/auth/auth.config';\nexport * from './lib/auth/auth.service';\nexport * from './lib/auth/auth.types';\nexport * from './lib/contact-card/contact-card2.service';\nexport * from './lib/file-upload/file-upload.service';\nexport * from './lib/idle/idle.service';\nexport * from './lib/idle/idle.types';\nexport * from './lib/item/item.gql';\nexport * from './lib/item/item.service';\nexport * from './lib/item/item.types';\nexport * from './lib/key-exchange/key-exchange.gql';\nexport * from './lib/key-exchange/key-exchange.service';\nexport * from './lib/lbop/lbop.service';\nexport * from './lib/life-ready.config';\nexport * from './lib/life-ready.module';\nexport * from './lib/lock/lock.service';\nexport * from './lib/notification/notification.service';\nexport * from './lib/password/password.service';\nexport * from './lib/persist/persist.service';\nexport * from './lib/plan/plan.service';\nexport * from './lib/plan/plan.types';\nexport * from './lib/profile/profile-details.service';\nexport * from './lib/profile/profile.gql';\nexport * from './lib/profile/profile.service';\nexport * from './lib/profile/profile.types';\nexport * from './lib/register/register.service';\nexport * from './lib/register/register.types';\nexport * from './lib/reminder/reminder.service';\nexport * from './lib/reminder/reminder.types';\nexport * from './lib/scenario/scenario.gql';\nexport * from './lib/scenario/scenario.service';\nexport * from './lib/scenario/scenario.types';\nexport * from './lib/server-config/server-config.service';\nexport * from './lib/shared-contact-card/shared-contact-card2.gql';\nexport * from './lib/shared-contact-card/shared-contact-card2.service';\nexport * from './lib/time/time.service';\nexport * from './lib/tp-assembly/tp-assembly.types';\nexport * from './lib/tp-password-reset/tp-password-reset-request.service';\nexport * from './lib/tp-password-reset/tp-password-reset-user.service';\nexport * from './lib/tp-password-reset/tp-password-reset.gql';\nexport * from './lib/tp-password-reset/tp-password-reset.service';\nexport * from './lib/tp-password-reset/tp-password-reset.types';\nexport * from './lib/trusted-party/trusted-party.service';\nexport * from './lib/trusted-party/trusted-party.types';\nexport * from './lib/two-factor/two-factor.service';\nexport * from './lib/user/user.gql';\nexport * from './lib/user/user.service';\nexport * from './lib/user/user.types';\nexport * from './lib/web-crypto/web-crypto.service';\nexport { gqlTyped } from './lib/_common/ast';\nexport * from './lib/_common/exceptions';\nexport * from './lib/_common/queries.gql';\n","/**\n * Generated bundle index. Do not edit.\n */\n\nexport * from './public-api';\n\nexport {RunOutsideAngular as ɵf} from './lib/_common/run-outside-angular';\nexport {LrGraphQLService as ɵg,LrService as ɵe} from './lib/api/lr-graphql';\nexport {EncryptionService as ɵb} from './lib/encryption/encryption.service';\nexport {KeyFactoryService as ɵd} from './lib/key/key-factory.service';\nexport {KeyGraphService as ɵa} from './lib/key/key-graph.service';\nexport {KeyMetaService as ɵh} from './lib/key/key-meta.service';\nexport {KeyService as ɵc} from './lib/key/key.service';\nexport {ScenarioAssemblyController as ɵm} from './lib/scenario/scenario.controller';\nexport {SharedContactCardFields as ɵk,SharedContactCardService as ɵl} from './lib/shared-contact-card/shared-contact-card.service';\nexport {TpAssemblyController as ɵj} from './lib/tp-assembly/tp-assembly';\nexport {TpPasswordResetAssemblyController as ɵi} from './lib/tp-password-reset/tp-password-reset.controller';\nexport {TpPasswordResetPrivateService as ɵn} from './lib/tp-password-reset/tp-password-reset.private.service';"],"names":["lodash.omit","KFS","lodash.cloneDeep","ast.name","gqlPrinter.print","CreateContactCardMutation","UpdateContactCardMutation","moment","slip.Slip39Service","slip.Assembly","slip.SubAssembly","CurrentUserQuery","DeleteContactCardMutation","DirectoryKeyQuery","lodash.isEqual"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AAoDA,IAAY,gBAGX;AAHD,WAAY,gBAAgB;IAC1B,+BAAW,CAAA;IACX,uCAAmB,CAAA;AACrB,CAAC,EAHW,gBAAgB,KAAhB,gBAAgB,QAG3B;AAOD,IAAY,gBAGX;AAHD,WAAY,gBAAgB;IAC1B,uCAAmB,CAAA;IACnB,+CAA2B,CAAA;AAC7B,CAAC,EAHW,gBAAgB,KAAhB,gBAAgB,QAG3B;AAmBD,IAAY,WAGX;AAHD,WAAY,WAAW;IACrB,4BAAa,CAAA;IACb,4CAA6B,CAAA;AAC/B,CAAC,EAHW,WAAW,KAAX,WAAW;;ACpFvB;;SCIgB,iBAAiB,CAAC,MAAmC;IACnE,IAAI,CAAC,MAAM,IAAI,CAAC,MAAM,CAAC,MAAM;QAAE,OAAO;IAEtC,MAAM,QAAQ,GAAG,MAAM,CAAC,GAAG,CAAC,CAAC,CAAC;QAC5B,OAAO,IAAI,OAAO,CAAC;YACjB,IAAI,EAAE,CAAC,CAAC,UAAU,IAAI,CAAC,CAAC,UAAU,CAAC,IAAI;YACvC,MAAM,EAAE,CAAC,CAAC,UAAU,IAAI,CAAC,CAAC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