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kB,CAChB,CACE,KAAM,aACN,GAAI,KAAK,QAGb,UAAWD,EACX,iBAAkB,aAErB,EAEGC,EAAO,0BAA4B,OACrC,KAAK,wBAA0BA,EAAO,yBAGxC,IAAMJ,EAAWI,EAAO,SAElBC,EAAO/B,EAAK,OAChB,IAAIA,EAAK,OAAO,MAAO,CACrB,mBAAoB,IAAI,WAAW0B,EAAS,iBAAiB,EAC7D,iBAAkB,IAAI,YAAW,EAAG,OAAOA,EAAS,cAAc,EAClE,UAAW,IAAI,WAAWA,EAAS,SAAS,EAC7C,CAAC,EAEJ,GAAI,CAACK,EACH,MAAM,IAAI,MAAM,uBAAuB,EAEzC,OAAOA,EAAK,MACd,CAKO,QAAM,CACX,MAAO,CACL,UAAWhC,EAAM,KAAK,WAAW,QAAO,CAAE,EAC1C,MAAOA,EAAM,KAAK,KAAK,EAE3B,GCjPF,OAAS,WAAAiC,GAAS,aAAAC,GAAW,gBAAAC,GAAc,eAAAC,OAAmB,2GAKxD,IAAOC,EAAP,KAA2B,CAC/B,aAAA,CACE,MAAM,IAAI,MACR,gFAAgF,CAEpF","names":["bufEquals","SignIdentity","uint8ToBuf","ED25519_OID","unwrapDER","wrapDER","fromHex","toHex","bufFromBufLike","ed25519","isObject","value","Ed25519PublicKey","_Ed25519PublicKey","key","_Ed25519PublicKey_rawKey","_Ed25519PublicKey_derKey","__classPrivateFieldSet","maybeKey","view","rawKey","derKey","publicKey","unwrapped","__classPrivateFieldGet","Ed25519KeyIdentity","_Ed25519KeyIdentity","privateKey","_Ed25519KeyIdentity_publicKey","_Ed25519KeyIdentity_privateKey","seed","sk","pk","obj","publicKeyDer","privateKeyRaw","json","parsed","secretKey","challenge","blob","signature","sig","msg","message","x","SignIdentity","CryptoError","_CryptoError","message","_getEffectiveCrypto","subtleCrypto","ECDSAKeyIdentity","_ECDSAKeyIdentity","keyPair","derKey","options","extractable","keyUsages","effectiveCrypto","key","challenge","params","fromHex","requestIdOf","SignIdentity","toHex","Principal","cbor","Principal","PartialIdentity","inner","_PartialIdentity_inner","__classPrivateFieldSet","__classPrivateFieldGet","domainSeparator","requestDomainSeparator","_parseBlob","value","fromHex","Delegation","pubkey","expiration","targets","t","toHex","p","_createSingleDelegation","from","to","delegation","challenge","requestIdOf","signature","DelegationChain","_DelegationChain","delegations","publicKey","options","_a","_b","json","parsedDelegations","signedDelegation","Principal","DelegationIdentity","SignIdentity","_inner","_delegation","key","blob","request","body","fields","__rest","requestId","PartialDelegationIdentity","_PartialDelegationIdentity","PartialIdentity","inner","_PartialDelegationIdentity_delegation","__classPrivateFieldSet","__classPrivateFieldGet","isDelegationValid","chain","checks","scopes","maybeScope","s","scope","none","target","SignIdentity","wrapDER","DER_COSE_OID","fromHex","toHex","borc","randomBytes","bufFromBufLike","_coseToDerEncodedBlob","cose","_authDataToCose","authData","dataView","idLenBytes","v","i","credentialIdLength","CosePublicKey","_cose","_createChallengeBuffer","challenge","c","_createCredential","credentialCreationOptions","creds","PubKeyCoseAlgo","WebAuthnIdentity","rawId","authenticatorAttachment","json","publicKey","response","attObject","_a","blob","result","cbor","wrapDER","unwrapDER","DER_COSE_OID","ED25519_OID","Secp256k1KeyIdentity"],"sources":["../esm/npm/@dfinity/identity@1.4.0/node_modules/@dfinity/identity/src/identity/ed25519.ts","../esm/npm/@dfinity/identity@1.4.0/node_modules/@dfinity/identity/src/identity/ecdsa.ts","../esm/npm/@dfinity/identity@1.4.0/node_modules/@dfinity/identity/src/identity/delegation.ts","../esm/npm/@dfinity/identity@1.4.0/node_modules/@dfinity/identity/src/identity/partial.ts","../esm/npm/@dfinity/identity@1.4.0/node_modules/@dfinity/identity/src/identity/webauthn.ts","../esm/npm/@dfinity/identity@1.4.0/node_modules/@dfinity/identity/src/index.ts"],"sourcesContent":["import { bufEquals } from '@dfinity/agent';\nimport {\n  DerEncodedPublicKey,\n  KeyPair,\n  PublicKey,\n  Signature,\n  SignIdentity,\n  uint8ToBuf,\n  ED25519_OID,\n  unwrapDER,\n  wrapDER,\n  fromHex,\n  toHex,\n  bufFromBufLike,\n} from '@dfinity/agent';\nimport { ed25519 } from '@noble/curves/ed25519';\n\ndeclare type KeyLike = PublicKey | DerEncodedPublicKey | ArrayBuffer | ArrayBufferView;\n\nfunction isObject(value: unknown) {\n  return value !== null \u0026\u0026 typeof value === 'object';\n}\n\nexport class Ed25519PublicKey implements PublicKey {\n  /**\n   * Construct Ed25519PublicKey from an existing PublicKey\n   * @param {unknown} maybeKey - existing PublicKey, ArrayBuffer, DerEncodedPublicKey, or hex string\n   * @returns {Ed25519PublicKey} Instance of Ed25519PublicKey\n   */\n  public static from(maybeKey: unknown): Ed25519PublicKey {\n    if (typeof maybeKey === 'string') {\n      const key = fromHex(maybeKey);\n      return this.fromRaw(key);\n    } else if (isObject(maybeKey)) {\n      const key = maybeKey as KeyLike;\n      if (isObject(key) \u0026\u0026 Object.hasOwnProperty.call(key, '__derEncodedPublicKey__')) {\n        return this.fromDer(key as DerEncodedPublicKey);\n      } else if (ArrayBuffer.isView(key)) {\n        const view = key as ArrayBufferView;\n        return this.fromRaw(bufFromBufLike(view.buffer));\n      } else if (key instanceof ArrayBuffer) {\n        return this.fromRaw(key);\n      } else if ('rawKey' in key) {\n        return this.fromRaw(key.rawKey as ArrayBuffer);\n      } else if ('derKey' in key) {\n        return this.fromDer(key.derKey as DerEncodedPublicKey);\n      } else if ('toDer' in key) {\n        return this.fromDer(key.toDer() as ArrayBuffer);\n      }\n    }\n    throw new Error('Cannot construct Ed25519PublicKey from the provided key.');\n  }\n\n  public static fromRaw(rawKey: ArrayBuffer): Ed25519PublicKey {\n    return new Ed25519PublicKey(rawKey);\n  }\n\n  public static fromDer(derKey: DerEncodedPublicKey): Ed25519PublicKey {\n    return new Ed25519PublicKey(this.derDecode(derKey));\n  }\n\n  // The length of Ed25519 public keys is always 32 bytes.\n  private static RAW_KEY_LENGTH = 32;\n\n  private static derEncode(publicKey: ArrayBuffer): DerEncodedPublicKey {\n    const key = wrapDER(publicKey, ED25519_OID).buffer as DerEncodedPublicKey;\n    key.__derEncodedPublicKey__ = undefined;\n    return key;\n  }\n\n  private static derDecode(key: DerEncodedPublicKey): ArrayBuffer {\n    const unwrapped = unwrapDER(key, ED25519_OID);\n    if (unwrapped.length !== this.RAW_KEY_LENGTH) {\n      throw new Error('An Ed25519 public key must be exactly 32bytes long');\n    }\n    return unwrapped;\n  }\n\n  #rawKey: ArrayBuffer;\n\n  public get rawKey(): ArrayBuffer {\n    return this.#rawKey;\n  }\n\n  #derKey: DerEncodedPublicKey;\n\n  public get derKey(): DerEncodedPublicKey {\n    return this.#derKey;\n  }\n\n  // `fromRaw` and `fromDer` should be used for instantiation, not this constructor.\n  private constructor(key: ArrayBuffer) {\n    if (key.byteLength !== Ed25519PublicKey.RAW_KEY_LENGTH) {\n      throw new Error('An Ed25519 public key must be exactly 32bytes long');\n    }\n    this.#rawKey = key;\n    this.#derKey = Ed25519PublicKey.derEncode(key);\n  }\n\n  public toDer(): DerEncodedPublicKey {\n    return this.derKey;\n  }\n\n  public toRaw(): ArrayBuffer {\n    return this.rawKey;\n  }\n}\n\n/**\n * Ed25519KeyIdentity is an implementation of SignIdentity that uses Ed25519 keys. This class is used to sign and verify messages for an agent.\n */\nexport class Ed25519KeyIdentity extends SignIdentity {\n  /**\n   * Generate a new Ed25519KeyIdentity.\n   * @param seed a 32-byte seed for the private key. If not provided, a random seed will be generated.\n   * @returns Ed25519KeyIdentity\n   */\n  public static generate(seed?: Uint8Array): Ed25519KeyIdentity {\n\n    if (seed \u0026\u0026 seed.length !== 32) {\n      throw new Error('Ed25519 Seed needs to be 32 bytes long.');\n    }\n    if (!seed) seed = ed25519.utils.randomPrivateKey();\n    // Check if the seed is all zeros\n    if(bufEquals(seed, new Uint8Array(new Array(32).fill(0)))) {\n      console.warn('Seed is all zeros. This is not a secure seed. Please provide a seed with sufficient entropy if this is a production environment.');\n    }\n    const sk = new Uint8Array(32);\n    for (let i = 0; i \u003c 32; i++) sk[i] = new Uint8Array(seed)[i];\n\n    const pk = ed25519.getPublicKey(sk);\n    return Ed25519KeyIdentity.fromKeyPair(pk, sk);\n  }\n\n  public static fromParsedJson(obj: JsonnableEd25519KeyIdentity): Ed25519KeyIdentity {\n    const [publicKeyDer, privateKeyRaw] = obj;\n    return new Ed25519KeyIdentity(\n      Ed25519PublicKey.fromDer(fromHex(publicKeyDer) as DerEncodedPublicKey),\n      fromHex(privateKeyRaw),\n    );\n  }\n\n  public static fromJSON(json: string): Ed25519KeyIdentity {\n    const parsed = JSON.parse(json);\n    if (Array.isArray(parsed)) {\n      if (typeof parsed[0] === 'string' \u0026\u0026 typeof parsed[1] === 'string') {\n        return this.fromParsedJson([parsed[0], parsed[1]]);\n      } else {\n        throw new Error('Deserialization error: JSON must have at least 2 items.');\n      }\n    }\n    throw new Error(`Deserialization error: Invalid JSON type for string: ${JSON.stringify(json)}`);\n  }\n\n  public static fromKeyPair(publicKey: ArrayBuffer, privateKey: ArrayBuffer): Ed25519KeyIdentity {\n    return new Ed25519KeyIdentity(Ed25519PublicKey.fromRaw(publicKey), privateKey);\n  }\n\n  public static fromSecretKey(secretKey: ArrayBuffer): Ed25519KeyIdentity {\n    const publicKey = ed25519.getPublicKey(new Uint8Array(secretKey));\n    return Ed25519KeyIdentity.fromKeyPair(publicKey, secretKey);\n  }\n\n  #publicKey: Ed25519PublicKey;\n  #privateKey: Uint8Array;\n\n  // `fromRaw` and `fromDer` should be used for instantiation, not this constructor.\n  protected constructor(publicKey: PublicKey, privateKey: ArrayBuffer) {\n    super();\n    this.#publicKey = Ed25519PublicKey.from(publicKey);\n    this.#privateKey = new Uint8Array(privateKey);\n  }\n\n  /**\n   * Serialize this key to JSON.\n   */\n  public toJSON(): JsonnableEd25519KeyIdentity {\n    return [toHex(this.#publicKey.toDer()), toHex(this.#privateKey)];\n  }\n\n  /**\n   * Return a copy of the key pair.\n   */\n  public getKeyPair(): KeyPair {\n    return {\n      secretKey: this.#privateKey,\n      publicKey: this.#publicKey,\n    };\n  }\n\n  /**\n   * Return the public key.\n   */\n  public getPublicKey(): Required\u003cPublicKey\u003e {\n    return this.#publicKey;\n  }\n\n  /**\n   * Signs a blob of data, with this identity's private key.\n   * @param challenge - challenge to sign with this identity's secretKey, producing a signature\n   */\n  public async sign(challenge: ArrayBuffer): Promise\u003cSignature\u003e {\n    const blob = new Uint8Array(challenge);\n    // Some implementations of Ed25519 private keys append a public key to the end of the private key. We only want the private key.\n    const signature = uint8ToBuf(ed25519.sign(blob, this.#privateKey.slice(0, 32)));\n    // add { __signature__: void; } to the signature to make it compatible with the agent\n\n    Object.defineProperty(signature, '__signature__', {\n      enumerable: false,\n      value: undefined,\n    });\n\n    return signature as Signature;\n  }\n\n  /**\n   * Verify\n   * @param sig - signature to verify\n   * @param msg - message to verify\n   * @param pk - public key\n   * @returns - true if the signature is valid, false otherwise\n   */\n  public static verify(\n    sig: ArrayBuffer | Uint8Array | string,\n    msg: ArrayBuffer | Uint8Array | string,\n    pk: ArrayBuffer | Uint8Array | string,\n  ) {\n    const [signature, message, publicKey] = [sig, msg, pk].map(x =\u003e {\n      if (typeof x === 'string') {\n        x = fromHex(x);\n      }\n      if (x instanceof Uint8Array) {\n        x = x.buffer;\n      }\n      return new Uint8Array(x);\n    });\n    return ed25519.verify(message, signature, publicKey);\n  }\n}\n\ntype PublicKeyHex = string;\ntype SecretKeyHex = string;\nexport type JsonnableEd25519KeyIdentity = [PublicKeyHex, SecretKeyHex];\n","import { DerEncodedPublicKey, PublicKey, Signature, SignIdentity } from '@dfinity/agent';\n\n/**\n * Options used in a {@link ECDSAKeyIdentity}\n */\nexport type CryptoKeyOptions = {\n  extractable?: boolean;\n  keyUsages?: KeyUsage[];\n  subtleCrypto?: SubtleCrypto;\n};\n\nexport class CryptoError extends Error {\n  constructor(public readonly message: string) {\n    super(message);\n    Object.setPrototypeOf(this, CryptoError.prototype);\n  }\n}\n\nexport interface DerCryptoKey extends CryptoKey {\n  toDer: () =\u003e DerEncodedPublicKey;\n}\n\n/**\n * Utility method to ensure that a subtleCrypto implementation is provided or is available in the global context\n * @param subtleCrypto SubtleCrypto implementation\n * @returns subleCrypto\n */\nfunction _getEffectiveCrypto(subtleCrypto: CryptoKeyOptions['subtleCrypto']): SubtleCrypto {\n  if (typeof global !== 'undefined' \u0026\u0026 global['crypto'] \u0026\u0026 global['crypto']['subtle']) {\n    return global['crypto']['subtle'];\n  }\n  if (subtleCrypto) {\n    return subtleCrypto;\n  } else if (typeof crypto !== 'undefined' \u0026\u0026 crypto['subtle']) {\n    return crypto.subtle;\n  } else {\n    throw new CryptoError(\n      'Global crypto was not available and none was provided. Please inlcude a SubtleCrypto implementation. See https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto',\n    );\n  }\n}\n\n/**\n * An identity interface that wraps an ECDSA keypair using the P-256 named curve. Supports DER-encoding and decoding for agent calls\n */\nexport class ECDSAKeyIdentity extends SignIdentity {\n  /**\n   * Generates a randomly generated identity for use in calls to the Internet Computer.\n   * @param {CryptoKeyOptions} options optional settings\n   * @param {CryptoKeyOptions['extractable']} options.extractable - whether the key should allow itself to be used. Set to false for maximum security.\n   * @param {CryptoKeyOptions['keyUsages']} options.keyUsages - a list of key usages that the key can be used for\n   * @param {CryptoKeyOptions['subtleCrypto']} options.subtleCrypto interface\n   * @constructs ECDSAKeyIdentity\n   * @returns a {@link ECDSAKeyIdentity}\n   */\n  public static async generate(options?: CryptoKeyOptions): Promise\u003cECDSAKeyIdentity\u003e {\n    const { extractable = false, keyUsages = ['sign', 'verify'], subtleCrypto } = options ?? {};\n    const effectiveCrypto = _getEffectiveCrypto(subtleCrypto);\n    const keyPair = await effectiveCrypto.generateKey(\n      {\n        name: 'ECDSA',\n        namedCurve: 'P-256',\n      },\n      extractable,\n      keyUsages,\n    );\n    const derKey = (await effectiveCrypto.exportKey(\n      'spki',\n      keyPair.publicKey,\n    )) as DerEncodedPublicKey;\n\n    return new this(keyPair, derKey, effectiveCrypto);\n  }\n\n  /**\n   * generates an identity from a public and private key. Please ensure that you are generating these keys securely and protect the user's private key\n   * @param keyPair a CryptoKeyPair\n   * @param subtleCrypto - a SubtleCrypto interface in case one is not available globally\n   * @returns an {@link ECDSAKeyIdentity}\n   */\n  public static async fromKeyPair(\n    keyPair: CryptoKeyPair | { privateKey: CryptoKey; publicKey: CryptoKey },\n    subtleCrypto?: SubtleCrypto,\n  ): Promise\u003cECDSAKeyIdentity\u003e {\n    const effectiveCrypto = _getEffectiveCrypto(subtleCrypto);\n    const derKey = (await effectiveCrypto.exportKey(\n      'spki',\n      keyPair.publicKey,\n    )) as DerEncodedPublicKey;\n    return new ECDSAKeyIdentity(keyPair, derKey, effectiveCrypto);\n  }\n\n  protected _derKey: DerEncodedPublicKey;\n  protected _keyPair: CryptoKeyPair;\n  protected _subtleCrypto: SubtleCrypto;\n\n  // `fromKeyPair` and `generate` should be used for instantiation, not this constructor.\n  protected constructor(\n    keyPair: CryptoKeyPair,\n    derKey: DerEncodedPublicKey,\n    subtleCrypto: SubtleCrypto,\n  ) {\n    super();\n    this._keyPair = keyPair;\n    this._derKey = derKey;\n    this._subtleCrypto = subtleCrypto;\n  }\n\n  /**\n   * Return the internally-used key pair.\n   * @returns a CryptoKeyPair\n   */\n  public getKeyPair(): CryptoKeyPair {\n    return this._keyPair;\n  }\n\n  /**\n   * Return the public key.\n   * @returns an {@link PublicKey \u0026 DerCryptoKey}\n   */\n  public getPublicKey(): PublicKey \u0026 DerCryptoKey {\n    const derKey = this._derKey;\n    const key: DerCryptoKey = Object.create(this._keyPair.publicKey);\n    key.toDer = function () {\n      return derKey;\n    };\n\n    return key;\n  }\n\n  /**\n   * Signs a blob of data, with this identity's private key.\n   * @param {ArrayBuffer} challenge - challenge to sign with this identity's secretKey, producing a signature\n   * @returns {Promise\u003cSignature\u003e} signature\n   */\n  public async sign(challenge: ArrayBuffer): Promise\u003cSignature\u003e {\n    const params: EcdsaParams = {\n      name: 'ECDSA',\n      hash: { name: 'SHA-256' },\n    };\n    this._keyPair.privateKey;\n    const signature = await this._subtleCrypto.sign(params, this._keyPair.privateKey, challenge);\n\n    return signature as Signature;\n  }\n}\n\nexport default ECDSAKeyIdentity;\n","import {\n  DerEncodedPublicKey,\n  fromHex,\n  HttpAgentRequest,\n  PublicKey,\n  requestIdOf,\n  Signature,\n  SignIdentity,\n  toHex,\n} from '@dfinity/agent';\nimport { Principal } from '@dfinity/principal';\nimport * as cbor from 'simple-cbor';\nimport { PartialIdentity } from './partial';\n\nconst domainSeparator = new TextEncoder().encode('\\x1Aic-request-auth-delegation');\nconst requestDomainSeparator = new TextEncoder().encode('\\x0Aic-request');\n\nfunction _parseBlob(value: unknown): ArrayBuffer {\n  if (typeof value !== 'string' || value.length \u003c 64) {\n    throw new Error('Invalid public key.');\n  }\n\n  return fromHex(value);\n}\n\n/**\n * A single delegation object that is signed by a private key. This is constructed by\n * `DelegationChain.create()`.\n *\n * {@see DelegationChain}\n */\nexport class Delegation {\n  constructor(\n    public readonly pubkey: ArrayBuffer,\n    public readonly expiration: bigint,\n    public readonly targets?: Principal[],\n  ) {}\n\n  public toCBOR(): cbor.CborValue {\n    // Expiration field needs to be encoded as a u64 specifically.\n    return cbor.value.map({\n      pubkey: cbor.value.bytes(this.pubkey),\n      expiration: cbor.value.u64(this.expiration.toString(16), 16),\n      ...(this.targets \u0026\u0026 {\n        targets: cbor.value.array(this.targets.map(t =\u003e cbor.value.bytes(t.toUint8Array()))),\n      }),\n    });\n  }\n\n  public toJSON(): JsonnableDelegation {\n    // every string should be hex and once-de-hexed,\n    // discoverable what it is (e.g. de-hex to get JSON with a 'type' property, or de-hex to DER\n    // with an OID). After de-hex, if it's not obvious what it is, it's an ArrayBuffer.\n    return {\n      expiration: this.expiration.toString(16),\n      pubkey: toHex(this.pubkey),\n      ...(this.targets \u0026\u0026 { targets: this.targets.map(p =\u003e p.toHex()) }),\n    };\n  }\n}\n\n/**\n * Type of ReturnType\u003cDelegation.toJSON\u003e.\n * The goal here is to stringify all non-JSON-compatible types to some bytes representation we can\n * stringify as hex.\n * (Hex shouldn't be ambiguous ever, because you can encode as DER with semantic OIDs).\n */\ninterface JsonnableDelegation {\n  // A BigInt of Nanoseconds since epoch as hex\n  expiration: string;\n  // Hexadecimal representation of the DER public key.\n  pubkey: string;\n  // Array of strings, where each string is hex of principal blob (*NOT* textual representation).\n  targets?: string[];\n}\n\n/**\n * A signed delegation, which lends its identity to the public key in the delegation\n * object. This is constructed by `DelegationChain.create()`.\n *\n * {@see DelegationChain}\n */\nexport interface SignedDelegation {\n  delegation: Delegation;\n  signature: Signature;\n}\n\n/**\n * Sign a single delegation object for a period of time.\n * @param from The identity that lends its delegation.\n * @param to The identity that receives the delegation.\n * @param expiration An expiration date for this delegation.\n * @param targets Limit this delegation to the target principals.\n */\nasync function _createSingleDelegation(\n  from: SignIdentity,\n  to: PublicKey,\n  expiration: Date,\n  targets?: Principal[],\n): Promise\u003cSignedDelegation\u003e {\n  const delegation: Delegation = new Delegation(\n    to.toDer(),\n    BigInt(+expiration) * BigInt(1000000), // In nanoseconds.\n    targets,\n  );\n  // The signature is calculated by signing the concatenation of the domain separator\n  // and the message.\n  // Note: To ensure Safari treats this as a user gesture, ensure to not use async methods\n  // besides the actualy webauthn functionality (such as `sign`). Safari will de-register\n  // a user gesture if you await an async call thats not fetch, xhr, or setTimeout.\n  const challenge = new Uint8Array([\n    ...domainSeparator,\n    ...new Uint8Array(requestIdOf(delegation)),\n  ]);\n  const signature = await from.sign(challenge);\n\n  return {\n    delegation,\n    signature,\n  };\n}\n\nexport interface JsonnableDelegationChain {\n  publicKey: string;\n  delegations: Array\u003c{\n    signature: string;\n    delegation: {\n      pubkey: string;\n      expiration: string;\n      targets?: string[];\n    };\n  }\u003e;\n}\n\n/**\n * A chain of delegations. This is JSON Serializable.\n * This is the object to serialize and pass to a DelegationIdentity. It does not keep any\n * private keys.\n */\nexport class DelegationChain {\n  /**\n   * Create a delegation chain between two (or more) keys. By default, the expiration time\n   * will be very short (15 minutes).\n   *\n   * To build a chain of more than 2 identities, this function needs to be called multiple times,\n   * passing the previous delegation chain into the options argument. For example:\n   * @example\n   * const rootKey = createKey();\n   * const middleKey = createKey();\n   * const bottomeKey = createKey();\n   *\n   * const rootToMiddle = await DelegationChain.create(\n   *   root, middle.getPublicKey(), Date.parse('2100-01-01'),\n   * );\n   * const middleToBottom = await DelegationChain.create(\n   *   middle, bottom.getPublicKey(), Date.parse('2100-01-01'), { previous: rootToMiddle },\n   * );\n   *\n   * // We can now use a delegation identity that uses the delegation above:\n   * const identity = DelegationIdentity.fromDelegation(bottomKey, middleToBottom);\n   * @param from The identity that will delegate.\n   * @param to The identity that gets delegated. It can now sign messages as if it was the\n   *           identity above.\n   * @param expiration The length the delegation is valid. By default, 15 minutes from calling\n   *                   this function.\n   * @param options A set of options for this delegation. expiration and previous\n   * @param options.previous - Another DelegationChain that this chain should start with.\n   * @param options.targets - targets that scope the delegation (e.g. Canister Principals)\n   */\n  public static async create(\n    from: SignIdentity,\n    to: PublicKey,\n    expiration: Date = new Date(Date.now() + 15 * 60 * 1000),\n    options: {\n      previous?: DelegationChain;\n      targets?: Principal[];\n    } = {},\n  ): Promise\u003cDelegationChain\u003e {\n    const delegation = await _createSingleDelegation(from, to, expiration, options.targets);\n    return new DelegationChain(\n      [...(options.previous?.delegations || []), delegation],\n      options.previous?.publicKey || from.getPublicKey().toDer(),\n    );\n  }\n\n  /**\n   * Creates a DelegationChain object from a JSON string.\n   * @param json The JSON string to parse.\n   */\n  public static fromJSON(json: string | JsonnableDelegationChain): DelegationChain {\n    const { publicKey, delegations } = typeof json === 'string' ? JSON.parse(json) : json;\n    if (!Array.isArray(delegations)) {\n      throw new Error('Invalid delegations.');\n    }\n\n    const parsedDelegations: SignedDelegation[] = delegations.map(signedDelegation =\u003e {\n      const { delegation, signature } = signedDelegation;\n      const { pubkey, expiration, targets } = delegation;\n      if (targets !== undefined \u0026\u0026 !Array.isArray(targets)) {\n        throw new Error('Invalid targets.');\n      }\n\n      return {\n        delegation: new Delegation(\n          _parseBlob(pubkey),\n          BigInt('0x' + expiration), // expiration in JSON is an hexa string (See toJSON() below).\n          targets \u0026\u0026\n            targets.map((t: unknown) =\u003e {\n              if (typeof t !== 'string') {\n                throw new Error('Invalid target.');\n              }\n              return Principal.fromHex(t);\n            }),\n        ),\n        signature: _parseBlob(signature) as Signature,\n      };\n    });\n\n    return new this(parsedDelegations, _parseBlob(publicKey) as DerEncodedPublicKey);\n  }\n\n  /**\n   * Creates a DelegationChain object from a list of delegations and a DER-encoded public key.\n   * @param delegations The list of delegations.\n   * @param publicKey The DER-encoded public key of the key-pair signing the first delegation.\n   */\n  public static fromDelegations(\n    delegations: SignedDelegation[],\n    publicKey: DerEncodedPublicKey,\n  ): DelegationChain {\n    return new this(delegations, publicKey);\n  }\n\n  protected constructor(\n    public readonly delegations: SignedDelegation[],\n    public readonly publicKey: DerEncodedPublicKey,\n  ) {}\n\n  public toJSON(): JsonnableDelegationChain {\n    return {\n      delegations: this.delegations.map(signedDelegation =\u003e {\n        const { delegation, signature } = signedDelegation;\n        const { targets } = delegation;\n        return {\n          delegation: {\n            expiration: delegation.expiration.toString(16),\n            pubkey: toHex(delegation.pubkey),\n            ...(targets \u0026\u0026 {\n              targets: targets.map(t =\u003e t.toHex()),\n            }),\n          },\n          signature: toHex(signature),\n        };\n      }),\n      publicKey: toHex(this.publicKey),\n    };\n  }\n}\n\n/**\n * An Identity that adds delegation to a request. Everywhere in this class, the name\n * innerKey refers to the SignIdentity that is being used to sign the requests, while\n * originalKey is the identity that is being borrowed. More identities can be used\n * in the middle to delegate.\n */\nexport class DelegationIdentity extends SignIdentity {\n  /**\n   * Create a delegation without having access to delegateKey.\n   * @param key The key used to sign the reqyests.\n   * @param delegation A delegation object created using `createDelegation`.\n   */\n  public static fromDelegation(\n    key: Pick\u003cSignIdentity, 'sign'\u003e,\n    delegation: DelegationChain,\n  ): DelegationIdentity {\n    return new this(key, delegation);\n  }\n\n  protected constructor(\n    private _inner: Pick\u003cSignIdentity, 'sign'\u003e,\n    private _delegation: DelegationChain,\n  ) {\n    super();\n  }\n\n  public getDelegation(): DelegationChain {\n    return this._delegation;\n  }\n\n  public getPublicKey(): PublicKey {\n    return {\n      derKey: this._delegation.publicKey,\n      toDer: () =\u003e this._delegation.publicKey,\n    };\n  }\n  public sign(blob: ArrayBuffer): Promise\u003cSignature\u003e {\n    return this._inner.sign(blob);\n  }\n\n  public async transformRequest(request: HttpAgentRequest): Promise\u003cunknown\u003e {\n    const { body, ...fields } = request;\n    const requestId = await requestIdOf(body);\n    return {\n      ...fields,\n      body: {\n        content: body,\n        sender_sig: await this.sign(\n          new Uint8Array([...requestDomainSeparator, ...new Uint8Array(requestId)]),\n        ),\n        sender_delegation: this._delegation.delegations,\n        sender_pubkey: this._delegation.publicKey,\n      },\n    };\n  }\n}\n\n/**\n * A partial delegated identity, representing a delegation chain and the public key that it targets\n */\nexport class PartialDelegationIdentity extends PartialIdentity {\n  #delegation: DelegationChain;\n\n  /**\n   * The Delegation Chain of this identity.\n   */\n  get delegation(): DelegationChain {\n    return this.#delegation;\n  }\n\n  private constructor(inner: PublicKey, delegation: DelegationChain) {\n    super(inner);\n    this.#delegation = delegation;\n  }\n\n  /**\n   * Create a {@link PartialDelegationIdentity} from a {@link PublicKey} and a {@link DelegationChain}.\n   * @param key The {@link PublicKey} to delegate to.\n   * @param delegation a {@link DelegationChain} targeting the inner key.\n   * @constructs PartialDelegationIdentity\n   */\n  public static fromDelegation(key: PublicKey, delegation: DelegationChain) {\n    return new PartialDelegationIdentity(key, delegation);\n  }\n}\n\n/**\n * List of things to check for a delegation chain validity.\n */\nexport interface DelegationValidChecks {\n  /**\n   * Check that the scope is amongst the scopes that this delegation has access to.\n   */\n  scope?: Principal | string | Array\u003cPrincipal | string\u003e;\n}\n\n/**\n * Analyze a DelegationChain and validate that it's valid, ie. not expired and apply to the\n * scope.\n * @param chain The chain to validate.\n * @param checks Various checks to validate on the chain.\n */\nexport function isDelegationValid(chain: DelegationChain, checks?: DelegationValidChecks): boolean {\n  // Verify that the no delegation is expired. If any are in the chain, returns false.\n  for (const { delegation } of chain.delegations) {\n    // prettier-ignore\n    if (+new Date(Number(delegation.expiration / BigInt(1000000))) \u003c= +Date.now()) {\n      return false;\n    }\n  }\n\n  // Check the scopes.\n  const scopes: Principal[] = [];\n  const maybeScope = checks?.scope;\n  if (maybeScope) {\n    if (Array.isArray(maybeScope)) {\n      scopes.push(...maybeScope.map(s =\u003e (typeof s === 'string' ? Principal.fromText(s) : s)));\n    } else {\n      scopes.push(typeof maybeScope === 'string' ? Principal.fromText(maybeScope) : maybeScope);\n    }\n  }\n\n  for (const s of scopes) {\n    const scope = s.toText();\n    for (const { delegation } of chain.delegations) {\n      if (delegation.targets === undefined) {\n        continue;\n      }\n\n      let none = true;\n      for (const target of delegation.targets) {\n        if (target.toText() === scope) {\n          none = false;\n          break;\n        }\n      }\n      if (none) {\n        return false;\n      }\n    }\n  }\n\n  return true;\n}\n","import { Identity, PublicKey } from '@dfinity/agent';\nimport { Principal } from '@dfinity/principal';\n\n/**\n * A partial delegated identity, representing a delegation chain and the public key that it targets\n */\nexport class PartialIdentity implements Identity {\n  #inner: PublicKey;\n\n  /**\n   * The raw public key of this identity.\n   */\n  get rawKey(): ArrayBuffer | undefined {\n    return this.#inner.rawKey;\n  }\n\n  /**\n   * The DER-encoded public key of this identity.\n   */\n  get derKey(): ArrayBuffer | undefined {\n    return this.#inner.derKey;\n  }\n\n  /**\n   * The DER-encoded public key of this identity.\n   */\n  public toDer(): ArrayBuffer {\n    return this.#inner.toDer();\n  }\n\n  /**\n   * The inner {@link PublicKey} used by this identity.\n   */\n  public getPublicKey(): PublicKey {\n    return this.#inner;\n  }\n\n  /**\n   * The {@link Principal} of this identity.\n   */\n  public getPrincipal(): Principal {\n    return Principal.from(this.#inner.rawKey);\n  }\n\n  /**\n   * Required for the Identity interface, but cannot implemented for just a public key.\n   */\n  public transformRequest(): Promise\u003cnever\u003e {\n    return Promise.reject(\n      'Not implemented. You are attempting to use a partial identity to sign calls, but this identity only has access to the public key.To sign calls, use a DelegationIdentity instead.',\n    );\n  }\n\n  constructor(inner: PublicKey) {\n    this.#inner = inner;\n  }\n}\n","import {\n  DerEncodedPublicKey,\n  PublicKey,\n  Signature,\n  SignIdentity,\n  wrapDER,\n  DER_COSE_OID,\n  fromHex,\n  toHex,\n} from '@dfinity/agent';\nimport borc from 'borc';\nimport { randomBytes } from '@noble/hashes/utils';\nimport { bufFromBufLike } from '@dfinity/candid';\n\nfunction _coseToDerEncodedBlob(cose: ArrayBuffer): DerEncodedPublicKey {\n  return wrapDER(cose, DER_COSE_OID).buffer as DerEncodedPublicKey;\n}\n\ntype PublicKeyCredentialWithAttachment = PublicKeyCredential \u0026 {\n  // Extends `PublicKeyCredential` with an optional field introduced in the WebAuthn level 3 spec:\n  // https://w3c.github.io/webauthn/#dom-publickeycredential-authenticatorattachment\n  // Already supported by Chrome, Safari and Edge\n  // Note: `null` is included here as a possible value because Edge set this value to null in the\n  // past.\n  authenticatorAttachment: AuthenticatorAttachment | undefined | null;\n};\n\n/**\n * From the documentation;\n * The authData is a byte array described in the spec. Parsing it will involve slicing bytes from\n * the array and converting them into usable objects.\n *\n * See https://webauthn.guide/#registration (subsection \"Example: Parsing the authenticator data\").\n * @param authData The authData field of the attestation response.\n * @returns The COSE key of the authData.\n */\nfunction _authDataToCose(authData: ArrayBuffer): ArrayBuffer {\n  const dataView = new DataView(new ArrayBuffer(2));\n  const idLenBytes = authData.slice(53, 55);\n  [...new Uint8Array(idLenBytes)].forEach((v, i) =\u003e dataView.setUint8(i, v));\n  const credentialIdLength = dataView.getUint16(0);\n\n  // Get the public key object.\n  return authData.slice(55 + credentialIdLength);\n}\n\nexport class CosePublicKey implements PublicKey {\n  protected _encodedKey: DerEncodedPublicKey;\n\n  public constructor(protected _cose: ArrayBuffer) {\n    this._encodedKey = _coseToDerEncodedBlob(_cose);\n  }\n\n  public toDer(): DerEncodedPublicKey {\n    return this._encodedKey;\n  }\n\n  public getCose(): ArrayBuffer {\n    return this._cose;\n  }\n}\n\n/**\n * Create a challenge from a string or array. The default challenge is always the same\n * because we don't need to verify the authenticity of the key on the server (we don't\n * register our keys with the IC). Any challenge would do, even one per key, randomly\n * generated.\n * @param challenge The challenge to transform into a byte array. By default a hard\n *        coded string.\n */\nfunction _createChallengeBuffer(challenge: string | Uint8Array = '\u003cic0.app\u003e'): Uint8Array {\n  if (typeof challenge === 'string') {\n    return Uint8Array.from(challenge, c =\u003e c.charCodeAt(0));\n  } else {\n    return challenge;\n  }\n}\n\n/**\n * Create a credentials to authenticate with a server. This is necessary in order in\n * WebAuthn to get credentials IDs (which give us the public key and allow us to\n * sign), but in the case of the Internet Computer, we don't actually need to register\n * it, so we don't.\n * @param credentialCreationOptions an optional CredentialCreationOptions object\n */\nasync function _createCredential(\n  credentialCreationOptions?: CredentialCreationOptions,\n): Promise\u003cPublicKeyCredentialWithAttachment | null\u003e {\n  const creds = (await navigator.credentials.create(\n    credentialCreationOptions ?? {\n      publicKey: {\n        authenticatorSelection: {\n          userVerification: 'preferred',\n        },\n        attestation: 'direct',\n        challenge: _createChallengeBuffer(),\n        pubKeyCredParams: [{ type: 'public-key', alg: PubKeyCoseAlgo.ECDSA_WITH_SHA256 }],\n        rp: {\n          name: 'Internet Identity Service',\n        },\n        user: {\n          id: randomBytes(16),\n          name: 'Internet Identity',\n          displayName: 'Internet Identity',\n        },\n      },\n    },\n  )) as PublicKeyCredentialWithAttachment | null;\n\n  if (creds === null) {\n    return null;\n  }\n\n  return {\n    // do _not_ use ...creds here, as creds is not enumerable in all cases\n    id: creds.id,\n    response: creds.response,\n    type: creds.type,\n    authenticatorAttachment: creds.authenticatorAttachment,\n    getClientExtensionResults: creds.getClientExtensionResults,\n    // Some password managers will return a Uint8Array, so we ensure we return an ArrayBuffer.\n    rawId: bufFromBufLike(creds.rawId),\n  };\n}\n\n// See https://www.iana.org/assignments/cose/cose.xhtml#algorithms for a complete\n// list of these algorithms. We only list the ones we support here.\nenum PubKeyCoseAlgo {\n  ECDSA_WITH_SHA256 = -7,\n}\n\n/**\n * A SignIdentity that uses `navigator.credentials`. See https://webauthn.guide/ for\n * more information about WebAuthentication.\n */\nexport class WebAuthnIdentity extends SignIdentity {\n  /**\n   * Create an identity from a JSON serialization.\n   * @param json - json to parse\n   */\n  public static fromJSON(json: string): WebAuthnIdentity {\n    const { publicKey, rawId } = JSON.parse(json);\n\n    if (typeof publicKey !== 'string' || typeof rawId !== 'string') {\n      throw new Error('Invalid JSON string.');\n    }\n\n    return new this(fromHex(rawId), fromHex(publicKey), undefined);\n  }\n\n  /**\n   * Create an identity.\n   * @param credentialCreationOptions an optional CredentialCreationOptions Challenge\n   */\n  public static async create(\n    credentialCreationOptions?: CredentialCreationOptions,\n  ): Promise\u003cWebAuthnIdentity\u003e {\n    const creds = await _createCredential(credentialCreationOptions);\n\n    if (!creds || creds.type !== 'public-key') {\n      throw new Error('Could not create credentials.');\n    }\n\n    const response = creds.response as AuthenticatorAttestationResponse;\n    if (response.attestationObject === undefined) {\n      throw new Error('Was expecting an attestation response.');\n    }\n\n    // Parse the attestationObject as CBOR.\n    const attObject = borc.decodeFirst(new Uint8Array(response.attestationObject));\n\n    return new this(\n      creds.rawId,\n      _authDataToCose(attObject.authData),\n      creds.authenticatorAttachment ?? undefined,\n    );\n  }\n\n  protected _publicKey: CosePublicKey;\n\n  public constructor(\n    public readonly rawId: ArrayBuffer,\n    cose: ArrayBuffer,\n    protected authenticatorAttachment: AuthenticatorAttachment | undefined,\n  ) {\n    super();\n    this._publicKey = new CosePublicKey(cose);\n  }\n\n  public getPublicKey(): PublicKey {\n    return this._publicKey;\n  }\n\n  /**\n   * WebAuthn level 3 spec introduces a new attribute on successful WebAuthn interactions,\n   * see https://w3c.github.io/webauthn/#dom-publickeycredential-authenticatorattachment.\n   * This attribute is already implemented for Chrome, Safari and Edge.\n   *\n   * Given the attribute is only available after a successful interaction, the information is\n   * provided opportunistically and might also be `undefined`.\n   */\n  public getAuthenticatorAttachment(): AuthenticatorAttachment | undefined {\n    return this.authenticatorAttachment;\n  }\n\n  public async sign(blob: ArrayBuffer): Promise\u003cSignature\u003e {\n    const result = (await navigator.credentials.get({\n      publicKey: {\n        allowCredentials: [\n          {\n            type: 'public-key',\n            id: this.rawId,\n          },\n        ],\n        challenge: blob,\n        userVerification: 'preferred',\n      },\n    })) as PublicKeyCredentialWithAttachment;\n\n    if (result.authenticatorAttachment !== null) {\n      this.authenticatorAttachment = result.authenticatorAttachment;\n    }\n\n    const response = result.response as AuthenticatorAssertionResponse;\n\n    const cbor = borc.encode(\n      new borc.Tagged(55799, {\n        authenticator_data: new Uint8Array(response.authenticatorData),\n        client_data_json: new TextDecoder().decode(response.clientDataJSON),\n        signature: new Uint8Array(response.signature),\n      }),\n    );\n    if (!cbor) {\n      throw new Error('failed to encode cbor');\n    }\n    return cbor.buffer as Signature;\n  }\n\n  /**\n   * Allow for JSON serialization of all information needed to reuse this identity.\n   */\n  public toJSON(): JsonnableWebAuthnIdentity {\n    return {\n      publicKey: toHex(this._publicKey.getCose()),\n      rawId: toHex(this.rawId),\n    };\n  }\n}\n\n/**\n * ReturnType\u003cWebAuthnIdentity.toJSON\u003e\n */\nexport interface JsonnableWebAuthnIdentity {\n  // The hexadecimal representation of the DER encoded public key.\n  publicKey: string;\n  // The string representation of the local WebAuthn Credential.id (base64url encoded).\n  rawId: string;\n}\n","export { Ed25519KeyIdentity, Ed25519PublicKey } from './identity/ed25519';\nexport * from './identity/ecdsa';\nexport * from './identity/delegation';\nexport * from './identity/partial';\nexport { WebAuthnIdentity } from './identity/webauthn';\nexport { wrapDER, unwrapDER, DER_COSE_OID, ED25519_OID } from '@dfinity/agent';\n\n/**\n * @deprecated due to size of dependencies. Use `@dfinity/identity-secp256k1` instead.\n */\nexport class Secp256k1KeyIdentity {\n  constructor() {\n    throw new Error(\n      'Secp256k1KeyIdentity has been moved to a new repo: @dfinity/identity-secp256k1',\n    );\n  }\n}\n"],"version":3}
