var didJwt = require('did-jwt'); var sha256 = require('@noble/hashes/sha256'); var zklogin = require('@mysten/sui/zklogin'); var secp256r1 = require('@mysten/sui/keypairs/secp256r1'); var utils = require('@mysten/sui/utils'); var zklogin$1 = require('@mysten/zklogin'); var bcs = require('@mysten/sui/bcs'); var cryptography = require('@mysten/sui/cryptography'); var graphql = require('@mysten/sui/graphql'); var didResolver = require('did-resolver'); var canonicalizeData = require('canonicalize'); function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; } var canonicalizeData__default = /*#__PURE__*/_interopDefaultLegacy(canonicalizeData); const SUPPORTED_PUBLIC_KEY_TYPES = { zkLogin: ['zkLoginSignatureVerification'] }; const NBF_SKEW = 300; const resolveAuthenticator = function (resolver, alg, issuer, proofPurpose) { try { const types = SUPPORTED_PUBLIC_KEY_TYPES[alg]; if (!types || types.length === 0) { throw new Error(`${didJwt.JWT_ERROR.NOT_SUPPORTED}: No supported signature types for algorithm ${alg}`); } let didResult; return Promise.resolve(resolver.resolve(issuer, { accept: DID_JSON })).then(function (result) { // support legacy resolvers that do not produce DIDResolutionResult if (Object.getOwnPropertyNames(result).indexOf('didDocument') === -1) { didResult = { didDocument: result, didDocumentMetadata: {}, didResolutionMetadata: { contentType: DID_JSON } }; } else { didResult = result; } if (didResult.didResolutionMetadata?.error || didResult.didDocument == null) { const { error, message } = didResult.didResolutionMetadata; throw new Error(`${didJwt.JWT_ERROR.RESOLVER_ERROR}: Unable to resolve DID document for ${issuer}: ${error}, ${message || ''}`); } const getPublicKeyById = (verificationMethods, pubid) => { const filtered = verificationMethods.filter(({ id }) => pubid === id); return filtered.length > 0 ? filtered[0] : null; }; let publicKeysToCheck = [...(didResult?.didDocument?.verificationMethod || []), ...(didResult?.didDocument?.publicKey || [])]; if (typeof proofPurpose === 'string') { // support legacy DID Documents that do not list assertionMethod if (proofPurpose.startsWith('assertion') && !Object.getOwnPropertyNames(didResult?.didDocument).includes('assertionMethod')) { didResult.didDocument = { ...didResult.didDocument }; didResult.didDocument.assertionMethod = [...publicKeysToCheck.map(pk => pk.id)]; } publicKeysToCheck = (didResult.didDocument[proofPurpose] || []).map(verificationMethod => { if (typeof verificationMethod === 'string') { return getPublicKeyById(publicKeysToCheck, verificationMethod); } else if (typeof verificationMethod.publicKey === 'string') { // this is a legacy format return getPublicKeyById(publicKeysToCheck, verificationMethod.publicKey); } else { return verificationMethod; } }).filter(key => key != null); } const authenticators = publicKeysToCheck.filter(({ type }) => types.find(supported => supported === type)); if (typeof proofPurpose === 'string' && (!authenticators || authenticators.length === 0)) { throw new Error(`${didJwt.JWT_ERROR.NO_SUITABLE_KEYS}: DID document for ${issuer} does not have public keys suitable for ${alg} with ${proofPurpose} purpose`); } if (!authenticators || authenticators.length === 0) { throw new Error(`${didJwt.JWT_ERROR.NO_SUITABLE_KEYS}: DID document for ${issuer} does not have public keys for ${alg}`); } return { authenticators, issuer, didResolutionResult: didResult }; }); } catch (e) { return Promise.reject(e); } }; const DID_JSON = 'application/did+json'; function _catch$3(body, recover) { try { var result = body(); } catch (e) { return recover(e); } if (result && result.then) { return result.then(void 0, recover); } return result; } const verifierZkLogin = function (data, signature, authenticators) { try { function _temp3() { if (!signer) throw new Error('invalid_signature: Signature invalid for JWT'); return signer; } let signer = undefined; const _temp2 = function () { if (authenticators[0]) { const _temp = _catch$3(function () { const { keyBytes } = didJwt.extractPublicKeyBytes(authenticators[0]); const parsed = authenticators[0].controller.split(':'); const network = parsed.length === 3 ? 'mainnet' : parsed[2]; const client = new graphql.SuiGraphQLClient({ url: `https://sui-${network}.mystenlabs.com/graphql` }); const zkLoginPublicIdentifier = new zklogin.ZkLoginPublicIdentifier(keyBytes, { client }); const bytes = didJwt.base64ToBytes(signature); return Promise.resolve(zkLoginPublicIdentifier.verifyPersonalMessage(sha256.sha256(new TextEncoder().encode(data)), bytes)).then(function (result) { if (result) { signer = authenticators[0]; } }); }, function (error) { console.error(error); }); if (_temp && _temp.then) return _temp.then(function () {}); } }(); return Promise.resolve(_temp2 && _temp2.then ? _temp2.then(_temp3) : _temp3(_temp2)); } catch (e) { return Promise.reject(e); } }; const algorithms$1 = { zkLogin: verifierZkLogin }; function toSignatureObject(signature, recoverable = false) { const rawSig = didJwt.base64ToBytes(signature); if (rawSig.length !== (recoverable ? 65 : 64)) { throw new Error('wrong signature length'); } const r = didJwt.bytesToHex(rawSig.slice(0, 32)); const s = didJwt.bytesToHex(rawSig.slice(32, 64)); const sigObj = { r, s }; if (recoverable) { sigObj.recoveryParam = rawSig[64]; } return sigObj; } function VerifierAlgorithm(alg) { const impl = algorithms$1[alg]; if (!impl) throw new Error(`not_supported: Unsupported algorithm ${alg}`); return impl; } VerifierAlgorithm.toSignatureObject = toSignatureObject; const verifyJWTDecoded = function ({ header, payload, data, signature }, pubKeys) { try { if (!Array.isArray(pubKeys)) pubKeys = [pubKeys]; const iss = payload.iss; let recurse = true; do { if (iss !== payload.iss) throw new Error(`${didJwt.JWT_ERROR.INVALID_JWT}: multiple issuers`); try { const result = VerifierAlgorithm(header.alg)(data, signature, pubKeys); return Promise.resolve(result); } catch (e) { if (!e.message.startsWith(didJwt.JWT_ERROR.INVALID_SIGNATURE)) throw e; } // TODO probably best to create copy objects than replace reference objects if (header.cty !== 'JWT') { recurse = false; } else { ; ({ payload, header, signature, data } = didJwt.decodeJWT(payload.jwt, false)); } } while (recurse); throw new Error(`${didJwt.JWT_ERROR.INVALID_SIGNATURE}: no matching public key found`); } catch (e) { return Promise.reject(e); } }; function _catch$2(body, recover) { try { var result = body(); } catch (e) { return recover(e); } if (result && result.then) { return result.then(void 0, recover); } return result; } const _iteratorSymbol = typeof Symbol !== "undefined" ? Symbol.iterator || (Symbol.iterator = Symbol("Symbol.iterator")) : "@@iterator"; function _settle$1(pact, state, value) { if (!pact.s) { if (value instanceof _Pact$1) { if (value.s) { if (state & 1) { state = value.s; } value = value.v; } else { value.o = _settle$1.bind(null, pact, state); return; } } if (value && value.then) { value.then(_settle$1.bind(null, pact, state), _settle$1.bind(null, pact, 2)); return; } pact.s = state; pact.v = value; const observer = pact.o; if (observer) { observer(pact); } } } const _Pact$1 = /*#__PURE__*/function () { function _Pact() {} _Pact.prototype.then = function (onFulfilled, onRejected) { const result = new _Pact(); const state = this.s; if (state) { const callback = state & 1 ? onFulfilled : onRejected; if (callback) { try { _settle$1(result, 1, callback(this.v)); } catch (e) { _settle$1(result, 2, e); } return result; } else { return this; } } this.o = function (_this) { try { const value = _this.v; if (_this.s & 1) { _settle$1(result, 1, onFulfilled ? onFulfilled(value) : value); } else if (onRejected) { _settle$1(result, 1, onRejected(value)); } else { _settle$1(result, 2, value); } } catch (e) { _settle$1(result, 2, e); } }; return result; }; return _Pact; }(); function _isSettledPact$1(thenable) { return thenable instanceof _Pact$1 && thenable.s & 1; } function _forTo(array, body, check) { var i = -1, pact, reject; function _cycle(result) { try { while (++i < array.length && (!check || !check())) { result = body(i); if (result && result.then) { if (_isSettledPact$1(result)) { result = result.v; } else { result.then(_cycle, reject || (reject = _settle$1.bind(null, pact = new _Pact$1(), 2))); return; } } } if (pact) { _settle$1(pact, 1, result); } else { pact = result; } } catch (e) { _settle$1(pact || (pact = new _Pact$1()), 2, e); } } _cycle(); return pact; } function _forOf(target, body, check) { if (typeof target[_iteratorSymbol] === "function") { var iterator = target[_iteratorSymbol](), step, pact, reject; function _cycle(result) { try { while (!(step = iterator.next()).done && (!check || !check())) { result = body(step.value); if (result && result.then) { if (_isSettledPact$1(result)) { result = result.v; } else { result.then(_cycle, reject || (reject = _settle$1.bind(null, pact = new _Pact$1(), 2))); return; } } } if (pact) { _settle$1(pact, 1, result); } else { pact = result; } } catch (e) { _settle$1(pact || (pact = new _Pact$1()), 2, e); } } _cycle(); if (iterator.return) { var _fixup = function (value) { try { if (!step.done) { iterator.return(); } } catch (e) {} return value; }; if (pact && pact.then) { return pact.then(_fixup, function (e) { throw _fixup(e); }); } _fixup(); } return pact; } // No support for Symbol.iterator if (!("length" in target)) { throw new TypeError("Object is not iterable"); } // Handle live collections properly var values = []; for (var i = 0; i < target.length; i++) { values.push(target[i]); } return _forTo(values, function (i) { return body(values[i]); }, check); } const verifyConditionDelegated = function (jwt, { header, payload, data, signature }, authenticator, options) { try { if (!authenticator.conditionDelegated) { throw new Error('Expected conditionDelegated'); } if (!options.resolver) { throw new Error('Expected resolver'); } let foundSigner; const issuer = authenticator.conditionDelegated; return Promise.resolve(resolveAuthenticator(options.resolver, header.alg, issuer, options.proofPurpose)).then(function (didAuthenticator) { let _exit2; function _temp6(_result4) { if (_exit2) ; if (foundSigner) { return authenticator; } throw new Error(`${didJwt.JWT_ERROR.INVALID_SIGNATURE}: condition for authenticator ${authenticator.id} is not met.`); } const didResolutionResult = didAuthenticator.didResolutionResult; if (!didResolutionResult?.didDocument) { throw new Error(`${didJwt.JWT_ERROR.RESOLVER_ERROR}: Could not resolve delegated DID ${issuer}.`); } const delegatedAuthenticator = didAuthenticator.authenticators.find(authenticator => authenticator.id === issuer); if (!delegatedAuthenticator) { throw new Error(`${didJwt.JWT_ERROR.NO_SUITABLE_KEYS}: Could not find delegated authenticator ${issuer} in it's DID Document`); } const _temp5 = function () { if (delegatedAuthenticator.type === CONDITIONAL_PROOF_2022) { return Promise.resolve(didJwt.verifyJWT(jwt, { ...options, ...{ didAuthenticator: { didResolutionResult, authenticators: [delegatedAuthenticator], issuer: delegatedAuthenticator.id } } })).then(function ({ verified }) { if (verified) { foundSigner = delegatedAuthenticator; } }); } else { return _catch$2(function () { return Promise.resolve(verifyJWTDecoded({ header, payload, data, signature }, delegatedAuthenticator)).then(function (_verifyJWTDecoded2) { foundSigner = _verifyJWTDecoded2; }); }, function (e) { if (!e.message.startsWith('invalid_signature:')) throw e; }); } }(); return _temp5 && _temp5.then ? _temp5.then(_temp6) : _temp6(_temp5); }); } catch (e) { return Promise.reject(e); } }; const verifyConditionWeightedThreshold = function (jwt, { header, payload, data, signature }, authenticator, options) { try { let _exit; function _temp4(_result3) { if (_exit) return _result3; throw new Error(`${didJwt.JWT_ERROR.INVALID_SIGNATURE}: condition for authenticator ${authenticator.id} is not met.`); } if (!authenticator.conditionWeightedThreshold || !authenticator.threshold) { throw new Error('Expected conditionWeightedThreshold and threshold'); } const issuers = []; const threshold = authenticator.threshold; let weightCount = 0; const _temp3 = _forOf(authenticator.conditionWeightedThreshold, function (weightedCondition) { function _temp2(_result2) { if (_exit) return _result2; if (foundSigner && !issuers.includes(foundSigner.id)) { issuers.push(foundSigner.id); weightCount += weightedCondition.weight; if (weightCount >= threshold) { _exit = 1; return authenticator; } } } const currentCondition = weightedCondition.condition; let foundSigner; const _temp = _catch$2(function () { if (currentCondition.type === CONDITIONAL_PROOF_2022) { if (!options.didAuthenticator) { throw new Error('Expected didAuthenticator'); } const newOptions = { ...options, didAuthenticator: { didResolutionResult: options.didAuthenticator?.didResolutionResult, authenticators: [currentCondition], issuer: currentCondition.id } }; return Promise.resolve(didJwt.verifyJWT(jwt, newOptions)).then(function ({ verified }) { if (verified) { foundSigner = currentCondition; } }); } else { return Promise.resolve(verifyJWTDecoded({ header, payload, data, signature }, currentCondition)).then(function (_verifyJWTDecoded) { foundSigner = _verifyJWTDecoded; }); } }, function (e) { if (!e.message.startsWith(didJwt.JWT_ERROR.INVALID_SIGNATURE)) throw e; }); return _temp && _temp.then ? _temp.then(_temp2) : _temp2(_temp); }, function () { return _exit; }); return Promise.resolve(_temp3 && _temp3.then ? _temp3.then(_temp4) : _temp4(_temp3)); } catch (e) { return Promise.reject(e); } }; const verifyConditionalProof = function (jwt, { header, payload, signature, data }, authenticator, options) { try { // Validate the condition according to its condition property if (authenticator.conditionWeightedThreshold) { return verifyConditionWeightedThreshold(jwt, { header, payload, data, signature }, authenticator, options); } else if (authenticator.conditionDelegated) { return verifyConditionDelegated(jwt, { header, payload, data, signature }, authenticator, options); } // TODO other conditions throw new Error(`${didJwt.JWT_ERROR.INVALID_JWT}: conditional proof type did not find condition for authenticator ${authenticator.id}.`); } catch (e) { return Promise.reject(e); } }; const verifyProof = function (jwt, { header, payload, signature, data }, authenticator, options) { try { if (authenticator.type === CONDITIONAL_PROOF_2022) { return verifyConditionalProof(jwt, { payload, header, signature, data }, authenticator, options); } else { return Promise.resolve(verifyJWTDecoded({ header, payload, data, signature }, [authenticator])); } } catch (e) { return Promise.reject(e); } }; const CONDITIONAL_PROOF_2022 = 'ConditionalProof2022'; function asUint8Array(buf) { if (globalThis.Buffer != null) { return new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength); } return buf; } function allocUnsafe(size = 0) { if (globalThis.Buffer != null && globalThis.Buffer.allocUnsafe != null) { return asUint8Array(globalThis.Buffer.allocUnsafe(size)); } return new Uint8Array(size); } function concat(arrays, length) { if (!length) { length = arrays.reduce((acc, curr) => acc + curr.length, 0); } const output = allocUnsafe(length); let offset = 0; for (const arr of arrays) { output.set(arr, offset); offset += arr.length; } return asUint8Array(output); } function base(ALPHABET, name) { if (ALPHABET.length >= 255) { throw new TypeError('Alphabet too long'); } var BASE_MAP = new Uint8Array(256); for (var j = 0; j < BASE_MAP.length; j++) { BASE_MAP[j] = 255; } for (var i = 0; i < ALPHABET.length; i++) { var x = ALPHABET.charAt(i); var xc = x.charCodeAt(0); if (BASE_MAP[xc] !== 255) { throw new TypeError(x + ' is ambiguous'); } BASE_MAP[xc] = i; } var BASE = ALPHABET.length; var LEADER = ALPHABET.charAt(0); var FACTOR = Math.log(BASE) / Math.log(256); var iFACTOR = Math.log(256) / Math.log(BASE); function encode(source) { if (source instanceof Uint8Array); else if (ArrayBuffer.isView(source)) { source = new Uint8Array(source.buffer, source.byteOffset, source.byteLength); } else if (Array.isArray(source)) { source = Uint8Array.from(source); } if (!(source instanceof Uint8Array)) { throw new TypeError('Expected Uint8Array'); } if (source.length === 0) { return ''; } var zeroes = 0; var length = 0; var pbegin = 0; var pend = source.length; while (pbegin !== pend && source[pbegin] === 0) { pbegin++; zeroes++; } var size = (pend - pbegin) * iFACTOR + 1 >>> 0; var b58 = new Uint8Array(size); while (pbegin !== pend) { var carry = source[pbegin]; var i = 0; for (var it1 = size - 1; (carry !== 0 || i < length) && it1 !== -1; it1--, i++) { carry += 256 * b58[it1] >>> 0; b58[it1] = carry % BASE >>> 0; carry = carry / BASE >>> 0; } if (carry !== 0) { throw new Error('Non-zero carry'); } length = i; pbegin++; } var it2 = size - length; while (it2 !== size && b58[it2] === 0) { it2++; } var str = LEADER.repeat(zeroes); for (; it2 < size; ++it2) { str += ALPHABET.charAt(b58[it2]); } return str; } function decodeUnsafe(source) { if (typeof source !== 'string') { throw new TypeError('Expected String'); } if (source.length === 0) { return new Uint8Array(); } var psz = 0; if (source[psz] === ' ') { return; } var zeroes = 0; var length = 0; while (source[psz] === LEADER) { zeroes++; psz++; } var size = (source.length - psz) * FACTOR + 1 >>> 0; var b256 = new Uint8Array(size); while (source[psz]) { var carry = BASE_MAP[source.charCodeAt(psz)]; if (carry === 255) { return; } var i = 0; for (var it3 = size - 1; (carry !== 0 || i < length) && it3 !== -1; it3--, i++) { carry += BASE * b256[it3] >>> 0; b256[it3] = carry % 256 >>> 0; carry = carry / 256 >>> 0; } if (carry !== 0) { throw new Error('Non-zero carry'); } length = i; psz++; } if (source[psz] === ' ') { return; } var it4 = size - length; while (it4 !== size && b256[it4] === 0) { it4++; } var vch = new Uint8Array(zeroes + (size - it4)); var j = zeroes; while (it4 !== size) { vch[j++] = b256[it4++]; } return vch; } function decode(string) { var buffer = decodeUnsafe(string); if (buffer) { return buffer; } throw new Error(`Non-${ name } character`); } return { encode: encode, decodeUnsafe: decodeUnsafe, decode: decode }; } var src = base; var _brrp__multiformats_scope_baseX = src; const coerce = o => { if (o instanceof Uint8Array && o.constructor.name === 'Uint8Array') return o; if (o instanceof ArrayBuffer) return new Uint8Array(o); if (ArrayBuffer.isView(o)) { return new Uint8Array(o.buffer, o.byteOffset, o.byteLength); } throw new Error('Unknown type, must be binary type'); }; const fromString$1 = str => new TextEncoder().encode(str); const toString$1 = b => new TextDecoder().decode(b); class Encoder { constructor(name, prefix, baseEncode) { this.name = name; this.prefix = prefix; this.baseEncode = baseEncode; } encode(bytes) { if (bytes instanceof Uint8Array) { return `${ this.prefix }${ this.baseEncode(bytes) }`; } else { throw Error('Unknown type, must be binary type'); } } } class Decoder { constructor(name, prefix, baseDecode) { this.name = name; this.prefix = prefix; if (prefix.codePointAt(0) === undefined) { throw new Error('Invalid prefix character'); } this.prefixCodePoint = prefix.codePointAt(0); this.baseDecode = baseDecode; } decode(text) { if (typeof text === 'string') { if (text.codePointAt(0) !== this.prefixCodePoint) { throw Error(`Unable to decode multibase string ${ JSON.stringify(text) }, ${ this.name } decoder only supports inputs prefixed with ${ this.prefix }`); } return this.baseDecode(text.slice(this.prefix.length)); } else { throw Error('Can only multibase decode strings'); } } or(decoder) { return or(this, decoder); } } class ComposedDecoder { constructor(decoders) { this.decoders = decoders; } or(decoder) { return or(this, decoder); } decode(input) { const prefix = input[0]; const decoder = this.decoders[prefix]; if (decoder) { return decoder.decode(input); } else { throw RangeError(`Unable to decode multibase string ${ JSON.stringify(input) }, only inputs prefixed with ${ Object.keys(this.decoders) } are supported`); } } } const or = (left, right) => new ComposedDecoder({ ...left.decoders || { [left.prefix]: left }, ...right.decoders || { [right.prefix]: right } }); class Codec { constructor(name, prefix, baseEncode, baseDecode) { this.name = name; this.prefix = prefix; this.baseEncode = baseEncode; this.baseDecode = baseDecode; this.encoder = new Encoder(name, prefix, baseEncode); this.decoder = new Decoder(name, prefix, baseDecode); } encode(input) { return this.encoder.encode(input); } decode(input) { return this.decoder.decode(input); } } const from = ({name, prefix, encode, decode}) => new Codec(name, prefix, encode, decode); const baseX = ({prefix, name, alphabet}) => { const {encode, decode} = _brrp__multiformats_scope_baseX(alphabet, name); return from({ prefix, name, encode, decode: text => coerce(decode(text)) }); }; const decode$1 = (string, alphabet, bitsPerChar, name) => { const codes = {}; for (let i = 0; i < alphabet.length; ++i) { codes[alphabet[i]] = i; } let end = string.length; while (string[end - 1] === '=') { --end; } const out = new Uint8Array(end * bitsPerChar / 8 | 0); let bits = 0; let buffer = 0; let written = 0; for (let i = 0; i < end; ++i) { const value = codes[string[i]]; if (value === undefined) { throw new SyntaxError(`Non-${ name } character`); } buffer = buffer << bitsPerChar | value; bits += bitsPerChar; if (bits >= 8) { bits -= 8; out[written++] = 255 & buffer >> bits; } } if (bits >= bitsPerChar || 255 & buffer << 8 - bits) { throw new SyntaxError('Unexpected end of data'); } return out; }; const encode$1 = (data, alphabet, bitsPerChar) => { const pad = alphabet[alphabet.length - 1] === '='; const mask = (1 << bitsPerChar) - 1; let out = ''; let bits = 0; let buffer = 0; for (let i = 0; i < data.length; ++i) { buffer = buffer << 8 | data[i]; bits += 8; while (bits > bitsPerChar) { bits -= bitsPerChar; out += alphabet[mask & buffer >> bits]; } } if (bits) { out += alphabet[mask & buffer << bitsPerChar - bits]; } if (pad) { while (out.length * bitsPerChar & 7) { out += '='; } } return out; }; const rfc4648 = ({name, prefix, bitsPerChar, alphabet}) => { return from({ prefix, name, encode(input) { return encode$1(input, alphabet, bitsPerChar); }, decode(input) { return decode$1(input, alphabet, bitsPerChar, name); } }); }; const identity = from({ prefix: '\0', name: 'identity', encode: buf => toString$1(buf), decode: str => fromString$1(str) }); var identityBase = { __proto__: null, identity: identity }; const base2 = rfc4648({ prefix: '0', name: 'base2', alphabet: '01', bitsPerChar: 1 }); var base2$1 = { __proto__: null, base2: base2 }; const base8 = rfc4648({ prefix: '7', name: 'base8', alphabet: '01234567', bitsPerChar: 3 }); var base8$1 = { __proto__: null, base8: base8 }; const base10 = baseX({ prefix: '9', name: 'base10', alphabet: '0123456789' }); var base10$1 = { __proto__: null, base10: base10 }; const base16 = rfc4648({ prefix: 'f', name: 'base16', alphabet: '0123456789abcdef', bitsPerChar: 4 }); const base16upper = rfc4648({ prefix: 'F', name: 'base16upper', alphabet: '0123456789ABCDEF', bitsPerChar: 4 }); var base16$1 = { __proto__: null, base16: base16, base16upper: base16upper }; const base32 = rfc4648({ prefix: 'b', name: 'base32', alphabet: 'abcdefghijklmnopqrstuvwxyz234567', bitsPerChar: 5 }); const base32upper = rfc4648({ prefix: 'B', name: 'base32upper', alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567', bitsPerChar: 5 }); const base32pad = rfc4648({ prefix: 'c', name: 'base32pad', alphabet: 'abcdefghijklmnopqrstuvwxyz234567=', bitsPerChar: 5 }); const base32padupper = rfc4648({ prefix: 'C', name: 'base32padupper', alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=', bitsPerChar: 5 }); const base32hex = rfc4648({ prefix: 'v', name: 'base32hex', alphabet: '0123456789abcdefghijklmnopqrstuv', bitsPerChar: 5 }); const base32hexupper = rfc4648({ prefix: 'V', name: 'base32hexupper', alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUV', bitsPerChar: 5 }); const base32hexpad = rfc4648({ prefix: 't', name: 'base32hexpad', alphabet: '0123456789abcdefghijklmnopqrstuv=', bitsPerChar: 5 }); const base32hexpadupper = rfc4648({ prefix: 'T', name: 'base32hexpadupper', alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUV=', bitsPerChar: 5 }); const base32z = rfc4648({ prefix: 'h', name: 'base32z', alphabet: 'ybndrfg8ejkmcpqxot1uwisza345h769', bitsPerChar: 5 }); var base32$1 = { __proto__: null, base32: base32, base32upper: base32upper, base32pad: base32pad, base32padupper: base32padupper, base32hex: base32hex, base32hexupper: base32hexupper, base32hexpad: base32hexpad, base32hexpadupper: base32hexpadupper, base32z: base32z }; const base36 = baseX({ prefix: 'k', name: 'base36', alphabet: '0123456789abcdefghijklmnopqrstuvwxyz' }); const base36upper = baseX({ prefix: 'K', name: 'base36upper', alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ' }); var base36$1 = { __proto__: null, base36: base36, base36upper: base36upper }; const base58btc = baseX({ name: 'base58btc', prefix: 'z', alphabet: '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz' }); const base58flickr = baseX({ name: 'base58flickr', prefix: 'Z', alphabet: '123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ' }); var base58 = { __proto__: null, base58btc: base58btc, base58flickr: base58flickr }; const base64 = rfc4648({ prefix: 'm', name: 'base64', alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/', bitsPerChar: 6 }); const base64pad = rfc4648({ prefix: 'M', name: 'base64pad', alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=', bitsPerChar: 6 }); const base64url = rfc4648({ prefix: 'u', name: 'base64url', alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_', bitsPerChar: 6 }); const base64urlpad = rfc4648({ prefix: 'U', name: 'base64urlpad', alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=', bitsPerChar: 6 }); var base64$1 = { __proto__: null, base64: base64, base64pad: base64pad, base64url: base64url, base64urlpad: base64urlpad }; const alphabet = Array.from('\uD83D\uDE80\uD83E\uDE90\u2604\uD83D\uDEF0\uD83C\uDF0C\uD83C\uDF11\uD83C\uDF12\uD83C\uDF13\uD83C\uDF14\uD83C\uDF15\uD83C\uDF16\uD83C\uDF17\uD83C\uDF18\uD83C\uDF0D\uD83C\uDF0F\uD83C\uDF0E\uD83D\uDC09\u2600\uD83D\uDCBB\uD83D\uDDA5\uD83D\uDCBE\uD83D\uDCBF\uD83D\uDE02\u2764\uD83D\uDE0D\uD83E\uDD23\uD83D\uDE0A\uD83D\uDE4F\uD83D\uDC95\uD83D\uDE2D\uD83D\uDE18\uD83D\uDC4D\uD83D\uDE05\uD83D\uDC4F\uD83D\uDE01\uD83D\uDD25\uD83E\uDD70\uD83D\uDC94\uD83D\uDC96\uD83D\uDC99\uD83D\uDE22\uD83E\uDD14\uD83D\uDE06\uD83D\uDE44\uD83D\uDCAA\uD83D\uDE09\u263A\uD83D\uDC4C\uD83E\uDD17\uD83D\uDC9C\uD83D\uDE14\uD83D\uDE0E\uD83D\uDE07\uD83C\uDF39\uD83E\uDD26\uD83C\uDF89\uD83D\uDC9E\u270C\u2728\uD83E\uDD37\uD83D\uDE31\uD83D\uDE0C\uD83C\uDF38\uD83D\uDE4C\uD83D\uDE0B\uD83D\uDC97\uD83D\uDC9A\uD83D\uDE0F\uD83D\uDC9B\uD83D\uDE42\uD83D\uDC93\uD83E\uDD29\uD83D\uDE04\uD83D\uDE00\uD83D\uDDA4\uD83D\uDE03\uD83D\uDCAF\uD83D\uDE48\uD83D\uDC47\uD83C\uDFB6\uD83D\uDE12\uD83E\uDD2D\u2763\uD83D\uDE1C\uD83D\uDC8B\uD83D\uDC40\uD83D\uDE2A\uD83D\uDE11\uD83D\uDCA5\uD83D\uDE4B\uD83D\uDE1E\uD83D\uDE29\uD83D\uDE21\uD83E\uDD2A\uD83D\uDC4A\uD83E\uDD73\uD83D\uDE25\uD83E\uDD24\uD83D\uDC49\uD83D\uDC83\uD83D\uDE33\u270B\uD83D\uDE1A\uD83D\uDE1D\uD83D\uDE34\uD83C\uDF1F\uD83D\uDE2C\uD83D\uDE43\uD83C\uDF40\uD83C\uDF37\uD83D\uDE3B\uD83D\uDE13\u2B50\u2705\uD83E\uDD7A\uD83C\uDF08\uD83D\uDE08\uD83E\uDD18\uD83D\uDCA6\u2714\uD83D\uDE23\uD83C\uDFC3\uD83D\uDC90\u2639\uD83C\uDF8A\uD83D\uDC98\uD83D\uDE20\u261D\uD83D\uDE15\uD83C\uDF3A\uD83C\uDF82\uD83C\uDF3B\uD83D\uDE10\uD83D\uDD95\uD83D\uDC9D\uD83D\uDE4A\uD83D\uDE39\uD83D\uDDE3\uD83D\uDCAB\uD83D\uDC80\uD83D\uDC51\uD83C\uDFB5\uD83E\uDD1E\uD83D\uDE1B\uD83D\uDD34\uD83D\uDE24\uD83C\uDF3C\uD83D\uDE2B\u26BD\uD83E\uDD19\u2615\uD83C\uDFC6\uD83E\uDD2B\uD83D\uDC48\uD83D\uDE2E\uD83D\uDE46\uD83C\uDF7B\uD83C\uDF43\uD83D\uDC36\uD83D\uDC81\uD83D\uDE32\uD83C\uDF3F\uD83E\uDDE1\uD83C\uDF81\u26A1\uD83C\uDF1E\uD83C\uDF88\u274C\u270A\uD83D\uDC4B\uD83D\uDE30\uD83E\uDD28\uD83D\uDE36\uD83E\uDD1D\uD83D\uDEB6\uD83D\uDCB0\uD83C\uDF53\uD83D\uDCA2\uD83E\uDD1F\uD83D\uDE41\uD83D\uDEA8\uD83D\uDCA8\uD83E\uDD2C\u2708\uD83C\uDF80\uD83C\uDF7A\uD83E\uDD13\uD83D\uDE19\uD83D\uDC9F\uD83C\uDF31\uD83D\uDE16\uD83D\uDC76\uD83E\uDD74\u25B6\u27A1\u2753\uD83D\uDC8E\uD83D\uDCB8\u2B07\uD83D\uDE28\uD83C\uDF1A\uD83E\uDD8B\uD83D\uDE37\uD83D\uDD7A\u26A0\uD83D\uDE45\uD83D\uDE1F\uD83D\uDE35\uD83D\uDC4E\uD83E\uDD32\uD83E\uDD20\uD83E\uDD27\uD83D\uDCCC\uD83D\uDD35\uD83D\uDC85\uD83E\uDDD0\uD83D\uDC3E\uD83C\uDF52\uD83D\uDE17\uD83E\uDD11\uD83C\uDF0A\uD83E\uDD2F\uD83D\uDC37\u260E\uD83D\uDCA7\uD83D\uDE2F\uD83D\uDC86\uD83D\uDC46\uD83C\uDFA4\uD83D\uDE47\uD83C\uDF51\u2744\uD83C\uDF34\uD83D\uDCA3\uD83D\uDC38\uD83D\uDC8C\uD83D\uDCCD\uD83E\uDD40\uD83E\uDD22\uD83D\uDC45\uD83D\uDCA1\uD83D\uDCA9\uD83D\uDC50\uD83D\uDCF8\uD83D\uDC7B\uD83E\uDD10\uD83E\uDD2E\uD83C\uDFBC\uD83E\uDD75\uD83D\uDEA9\uD83C\uDF4E\uD83C\uDF4A\uD83D\uDC7C\uD83D\uDC8D\uD83D\uDCE3\uD83E\uDD42'); const alphabetBytesToChars = alphabet.reduce((p, c, i) => { p[i] = c; return p; }, []); const alphabetCharsToBytes = alphabet.reduce((p, c, i) => { p[c.codePointAt(0)] = i; return p; }, []); function encode(data) { return data.reduce((p, c) => { p += alphabetBytesToChars[c]; return p; }, ''); } function decode(str) { const byts = []; for (const char of str) { const byt = alphabetCharsToBytes[char.codePointAt(0)]; if (byt === undefined) { throw new Error(`Non-base256emoji character: ${ char }`); } byts.push(byt); } return new Uint8Array(byts); } const base256emoji = from({ prefix: '\uD83D\uDE80', name: 'base256emoji', encode, decode }); var base256emoji$1 = { __proto__: null, base256emoji: base256emoji }; new TextEncoder(); new TextDecoder(); const bases = { ...identityBase, ...base2$1, ...base8$1, ...base10$1, ...base16$1, ...base32$1, ...base36$1, ...base58, ...base64$1, ...base256emoji$1 }; function createCodec(name, prefix, encode, decode) { return { name, prefix, encoder: { name, prefix, encode }, decoder: { decode } }; } const string = createCodec('utf8', 'u', buf => { const decoder = new TextDecoder('utf8'); return 'u' + decoder.decode(buf); }, str => { const encoder = new TextEncoder(); return encoder.encode(str.substring(1)); }); const ascii = createCodec('ascii', 'a', buf => { let string = 'a'; for (let i = 0; i < buf.length; i++) { string += String.fromCharCode(buf[i]); } return string; }, str => { str = str.substring(1); const buf = allocUnsafe(str.length); for (let i = 0; i < str.length; i++) { buf[i] = str.charCodeAt(i); } return buf; }); const BASES = { utf8: string, 'utf-8': string, hex: bases.base16, latin1: ascii, ascii: ascii, binary: ascii, ...bases }; function fromString(string, encoding = 'utf8') { const base = BASES[encoding]; if (!base) { throw new Error(`Unsupported encoding "${ encoding }"`); } if ((encoding === 'utf8' || encoding === 'utf-8') && globalThis.Buffer != null && globalThis.Buffer.from != null) { return asUint8Array(globalThis.Buffer.from(string, 'utf-8')); } return base.decoder.decode(`${ base.prefix }${ string }`); } function toString(array, encoding = 'utf8') { const base = BASES[encoding]; if (!base) { throw new Error(`Unsupported encoding "${ encoding }"`); } if ((encoding === 'utf8' || encoding === 'utf-8') && globalThis.Buffer != null && globalThis.Buffer.from != null) { return globalThis.Buffer.from(array.buffer, array.byteOffset, array.byteLength).toString('utf8'); } return base.encoder.encode(array).substring(1); } const u8a = { toString, fromString, concat }; function encodeBase64url(s) { return didJwt.bytesToBase64url(u8a.fromString(s)); } function encodeSection(data, shouldCanonicalize = false) { if (shouldCanonicalize) { return encodeBase64url(canonicalizeData__default["default"](data)); } else { return encodeBase64url(JSON.stringify(data)); } } // eslint-disable-next-line @typescript-eslint/no-explicit-any function instanceOfEcdsaSignature(object) { return typeof object === 'object' && 'r' in object && 's' in object; } function ZkLoginSignerAlg() { return function sign(payload, signer) { try { return Promise.resolve(signer(payload)).then(function (signature) { if (!instanceOfEcdsaSignature(signature)) { return signature; } else { throw new Error('invalid_config: expected a signer function that returns a string instead of signature object'); } }); } catch (e) { return Promise.reject(e); } }; } const algorithms = { zkLogin: ZkLoginSignerAlg() }; function SignerAlg(alg) { const impl = algorithms[alg]; if (!impl) throw new Error(`not_supported: Unsupported algorithm ${alg}`); return impl; } const createJWS = function (payload, signer, header = {}, options = {}) { try { if (!header.alg) header.alg = 'zkLogin'; const encodedPayload = typeof payload === 'string' ? payload : encodeSection(payload, options.canonicalize); const signingInput = [encodeSection(header, options.canonicalize), encodedPayload].join('.'); const jwtSigner = SignerAlg(header.alg); return Promise.resolve(jwtSigner(signingInput, signer)).then(function (signature) { // JWS Compact Serialization // https://www.rfc-editor.org/rfc/rfc7515#section-7.1 return [signingInput, signature].join('.'); }); } catch (e) { return Promise.reject(e); } }; function _catch$1(body, recover) { try { var result = body(); } catch (e) { return recover(e); } if (result && result.then) { return result.then(void 0, recover); } return result; } function _settle(pact, state, value) { if (!pact.s) { if (value instanceof _Pact) { if (value.s) { if (state & 1) { state = value.s; } value = value.v; } else { value.o = _settle.bind(null, pact, state); return; } } if (value && value.then) { value.then(_settle.bind(null, pact, state), _settle.bind(null, pact, 2)); return; } pact.s = state; pact.v = value; const observer = pact.o; if (observer) { observer(pact); } } } const _Pact = /*#__PURE__*/function () { function _Pact() {} _Pact.prototype.then = function (onFulfilled, onRejected) { const result = new _Pact(); const state = this.s; if (state) { const callback = state & 1 ? onFulfilled : onRejected; if (callback) { try { _settle(result, 1, callback(this.v)); } catch (e) { _settle(result, 2, e); } return result; } else { return this; } } this.o = function (_this) { try { const value = _this.v; if (_this.s & 1) { _settle(result, 1, onFulfilled ? onFulfilled(value) : value); } else if (onRejected) { _settle(result, 1, onRejected(value)); } else { _settle(result, 2, value); } } catch (e) { _settle(result, 2, e); } }; return result; }; return _Pact; }(); function _isSettledPact(thenable) { return thenable instanceof _Pact && thenable.s & 1; } function _for(test, update, body) { var stage; for (;;) { var shouldContinue = test(); if (_isSettledPact(shouldContinue)) { shouldContinue = shouldContinue.v; } if (!shouldContinue) { return result; } if (shouldContinue.then) { stage = 0; break; } var result = body(); if (result && result.then) { if (_isSettledPact(result)) { result = result.s; } else { stage = 1; break; } } if (update) { var updateValue = update(); if (updateValue && updateValue.then && !_isSettledPact(updateValue)) { stage = 2; break; } } } var pact = new _Pact(); var reject = _settle.bind(null, pact, 2); (stage === 0 ? shouldContinue.then(_resumeAfterTest) : stage === 1 ? result.then(_resumeAfterBody) : updateValue.then(_resumeAfterUpdate)).then(void 0, reject); return pact; function _resumeAfterBody(value) { result = value; do { if (update) { updateValue = update(); if (updateValue && updateValue.then && !_isSettledPact(updateValue)) { updateValue.then(_resumeAfterUpdate).then(void 0, reject); return; } } shouldContinue = test(); if (!shouldContinue || _isSettledPact(shouldContinue) && !shouldContinue.v) { _settle(pact, 1, result); return; } if (shouldContinue.then) { shouldContinue.then(_resumeAfterTest).then(void 0, reject); return; } result = body(); if (_isSettledPact(result)) { result = result.v; } } while (!result || !result.then); result.then(_resumeAfterBody).then(void 0, reject); } function _resumeAfterTest(shouldContinue) { if (shouldContinue) { result = body(); if (result && result.then) { result.then(_resumeAfterBody).then(void 0, reject); } else { _resumeAfterBody(result); } } else { _settle(pact, 1, result); } } function _resumeAfterUpdate() { if (shouldContinue = test()) { if (shouldContinue.then) { shouldContinue.then(_resumeAfterTest).then(void 0, reject); } else { _resumeAfterTest(shouldContinue); } } else { _settle(pact, 1, result); } } } const createZkLoginJWT = function (payload, { issuer, signer, alg, expiresIn, canonicalize }, header = {}) { try { if (!signer) throw new Error('missing_signer: No Signer functionality has been configured'); if (!issuer) throw new Error('missing_issuer: No issuing DID has been configured'); if (!header.typ) header.typ = 'JWT'; if (!header.alg) header.alg = alg; const timestamps = { iat: Math.floor(Date.now() / 1000), exp: undefined }; if (expiresIn) { if (typeof expiresIn === 'number') { timestamps.exp = (payload.nbf || timestamps.iat) + Math.floor(expiresIn); } else { throw new Error('invalid_argument: JWT expiresIn is not a number'); } } const fullPayload = { ...timestamps, ...payload, iss: issuer }; return Promise.resolve(createJWS(fullPayload, signer, header, { canonicalize })); } catch (e) { return Promise.reject(e); } }; const verifyZkLoginJWT = function (jwt, options) { try { function _temp6() { let _exit; function _temp4(_result) { if (_exit) ; if (signer) { const now = typeof options.policies?.now === 'number' ? options.policies.now : Math.floor(Date.now() / 1000); const skewTime = typeof options.skewTime !== 'undefined' && options.skewTime >= 0 ? options.skewTime : NBF_SKEW; const nowSkewed = now + skewTime; if (options.policies?.nbf !== false && payload.nbf) { if (payload.nbf > nowSkewed) { throw new Error(`${didJwt.JWT_ERROR.INVALID_JWT}: JWT not valid before nbf: ${payload.nbf}`); } } else if (options.policies?.iat !== false && payload.iat && payload.iat > nowSkewed) { throw new Error(`${didJwt.JWT_ERROR.INVALID_JWT}: JWT not valid yet (issued in the future) iat: ${payload.iat}`); } if (options.policies?.exp !== false && payload.exp && payload.exp <= now - skewTime) { throw new Error(`${didJwt.JWT_ERROR.INVALID_JWT}: JWT has expired: exp: ${payload.exp} < now: ${now}`); } if (options.policies?.aud !== false && payload.aud) { if (!options.audience && !options.callbackUrl) { throw new Error(`${didJwt.JWT_ERROR.INVALID_AUDIENCE}: JWT audience is required but your app address has not been configured`); } const audArray = Array.isArray(payload.aud) ? payload.aud : [payload.aud]; const matchedAudience = audArray.find(item => options.audience === item || options.callbackUrl === item); if (typeof matchedAudience === 'undefined') { throw new Error(`${didJwt.JWT_ERROR.INVALID_AUDIENCE}: JWT audience does not match your DID or callback url`); } } return { verified: true, payload, didResolutionResult, issuer, signer, jwt, policies: options.policies }; } throw new Error(`${didJwt.JWT_ERROR.INVALID_SIGNATURE}: JWT not valid. issuer DID document does not contain a verificationMethod that matches the signature.`); } const { did } = didResolver.parse(didUrl); let signer = null; const _temp3 = function () { if (did !== didUrl) { const authenticator = authenticators.find(auth => auth.id === didUrl); if (!authenticator) { throw new Error(`${didJwt.JWT_ERROR.INVALID_JWT}: No authenticator found for did URL ${didUrl}`); } return Promise.resolve(verifyProof(jwt, { payload, header, signature, data }, authenticator, options)).then(function (_verifyProof) { signer = _verifyProof; }); } else { let i = 0; return _for(function () { return !_exit && !signer && i < authenticators.length; }, void 0, function () { function _temp2(_result2) { if (_exit) ; i++; } const authenticator = authenticators[i]; const _temp = _catch$1(function () { return Promise.resolve(verifyProof(jwt, { payload, header, signature, data }, authenticator, options)).then(function (_verifyProof2) { signer = _verifyProof2; }); }, function (e) { if (!e.message.includes(didJwt.JWT_ERROR.INVALID_SIGNATURE) || i === authenticators.length - 1) throw e; }); return _temp && _temp.then ? _temp.then(_temp2) : _temp2(_temp); }); } }(); return _temp3 && _temp3.then ? _temp3.then(_temp4) : _temp4(_temp3); } if (!options.resolver) throw new Error('missing_resolver: No DID resolver has been configured'); const { payload, header, signature, data } = didJwt.decodeJWT(jwt, false); const proofPurpose = Object.prototype.hasOwnProperty.call(options, 'auth') ? options.auth ? 'authentication' : undefined : options.proofPurpose; let didUrl; if (!payload.iss && !payload.client_id) { throw new Error(`${didJwt.JWT_ERROR.INVALID_JWT}: JWT iss or client_id are required`); } if (options.didAuthenticator) { didUrl = options.didAuthenticator.issuer; } else if (!payload.iss && payload.scope === 'openid' && payload.redirect_uri) { // SIOP Request payload // https://identity.foundation/jwt-vc-presentation-profile/#self-issued-op-request-object if (!payload.client_id) { throw new Error(`${didJwt.JWT_ERROR.INVALID_JWT}: JWT client_id is required`); } didUrl = payload.client_id; } else { didUrl = payload.iss; } if (!didUrl) { throw new Error(`${didJwt.JWT_ERROR.INVALID_JWT}: No DID has been found in the JWT`); } let authenticators; let issuer; let didResolutionResult; const _temp5 = function () { if (options.didAuthenticator) { ({ didResolutionResult, authenticators, issuer } = options.didAuthenticator); } else { return Promise.resolve(resolveAuthenticator(options.resolver, header.alg, didUrl, proofPurpose)).then(function (_resolveAuthenticator) { ({ didResolutionResult, authenticators, issuer } = _resolveAuthenticator); // Add to options object for recursive reference options.didAuthenticator = { didResolutionResult, authenticators, issuer }; }); } }(); return Promise.resolve(_temp5 && _temp5.then ? _temp5.then(_temp6) : _temp6(_temp5)); } catch (e) { return Promise.reject(e); } }; function _catch(body, recover) { try { var result = body(); } catch (e) { return recover(e); } if (result && result.then) { return result.then(void 0, recover); } return result; } class WalrusDID { constructor(signer) { this.alg = void 0; this.signer = void 0; this.publicKey = void 0; this.alg = signer.zkLogin ? 'zkLogin' : 'ES256'; this.publicKey = signer.zkLogin ? zklogin.toZkLoginPublicIdentifier(BigInt(signer.zkLogin.addressSeed), signer.zkLogin.iss).toSuiPublicKey() : secp256r1.Secp256r1Keypair.fromSecretKey(utils.fromB64(signer.privateKey)).getPublicKey().toSuiPublicKey(); this.signer = signer.zkLogin ? function (data) { try { return Promise.resolve(secp256r1.Secp256r1Keypair.fromSecretKey(utils.fromB64(signer.privateKey)).signPersonalMessage(sha256.sha256(typeof data === 'string' ? new TextEncoder().encode(data) : data))).then(function ({ signature }) { const zkLoginSignature = zklogin$1.getZkLoginSignature({ inputs: { ...JSON.parse(signer.zkLogin.proof), addressSeed: signer.zkLogin?.addressSeed }, maxEpoch: signer.zkLogin.maxEpoch, userSignature: signature }); return didJwt.bytesToBase64url(utils.fromB64(zkLoginSignature)); }); } catch (e) { return Promise.reject(e); } } : function (data) { try { return Promise.resolve(secp256r1.Secp256r1Keypair.fromSecretKey(utils.fromB64(signer.privateKey)).sign(typeof data === 'string' ? new TextEncoder().encode(data) : data)).then(didJwt.bytesToBase64url); } catch (e) { return Promise.reject(e); } }; } getPublicKey() { return this.publicKey; } sign(data) { try { const _this = this; if (_this.signer) { return Promise.resolve(_this.signer(data)); } throw new Error('signer error'); return Promise.resolve(); } catch (e) { return Promise.reject(e); } } signJWT(did, payload, expiresIn) { try { const _this2 = this; if (_this2.signer) { const options = { signer: _this2.signer, alg: _this2.alg, issuer: did }; if (expiresIn) options['expiresIn'] = expiresIn; if (_this2.alg === 'zkLogin') { return Promise.resolve(createZkLoginJWT(payload, options)); } return Promise.resolve(didJwt.createJWT(payload, options)); } throw new Error('signer error'); return Promise.resolve(); } catch (e) { return Promise.reject(e); } } static verifyJWT(jwt, resolver, audience) { try { const decoded = didJwt.decodeJWT(jwt); if (decoded.header.alg === 'zkLogin') { return Promise.resolve(verifyZkLoginJWT(jwt, { resolver, audience })); } return Promise.resolve(didJwt.verifyJWT(jwt, { resolver, audience })); } catch (e) { return Promise.reject(e); } } static VerifyMetaData(verified, issuer) { let _exit; return Promise.resolve(_catch(function () { function _temp7(_result) { let _exit2; if (_exit) return _result; const _temp5 = function () { if (signatureScheme === 'Secp256r1') { function _temp4(_temp) { _exit2 = 1; return _temp; } const pubKey = new secp256r1.Secp256r1PublicKey(utils.fromB64(publicKey).slice(1)); const _temp3 = utils.toB64(utils.fromB64(publicKey).slice(1)) === verified.signer.publicKeyBase64; return _temp3 ? Promise.resolve(pubKey.verify(utils.fromB64(data), utils.fromB64(signature))).then(_temp4) : _temp4(_temp3); } else return function () { if (signatureScheme === 'ZkLogin') { const parsed = verified.issuer.split(':'); const network = parsed.length === 3 ? 'mainnet' : parsed[2]; const client = new graphql.SuiGraphQLClient({ url: `https://sui-${network}.mystenlabs.com/graphql` }); const zkLoginPublicIdentifier = new zklogin.ZkLoginPublicIdentifier(utils.fromB64(publicKey), { client }); const bytes = didJwt.base64ToBytes(signature); return Promise.resolve(zkLoginPublicIdentifier.verifyPersonalMessage(sha256.sha256(utils.fromB64(data)), bytes)).then(function (verifySubject) { const split = verified.jwt.split('.'); return Promise.resolve(zkLoginPublicIdentifier.verifyPersonalMessage(sha256.sha256(new TextEncoder().encode(`${split[0]}.${split[1]}`)), didJwt.base64ToBytes(split[2]))).then(function (verifyJwt) { const _temp2 = verifySubject && verifyJwt; _exit2 = 1; return _temp2; }); }); } }(); }(); return _temp5 && _temp5.then ? _temp5.then(function (_result2) { return _exit2 ? _result2 : false; }) : _exit2 ? _temp5 : false; } const { walrus } = verified.didResolutionResult.didDocumentMetadata; const Serializer = bcs.bcs.struct('SigData', { data: bcs.bcs.string(), publicKey: bcs.bcs.string(), signature: bcs.bcs.string() }); const parsed = Serializer.fromBase64(walrus); const { data, publicKey, signature } = Serializer.fromBase64(parsed.data); const signatureScheme = cryptography.SIGNATURE_FLAG_TO_SCHEME[utils.fromB64(publicKey)[0]]; const _temp6 = function () { if (issuer) { const pubKey = new secp256r1.Secp256r1PublicKey(utils.fromB64(issuer)); return Promise.resolve(pubKey.verify(utils.fromB64(parsed.data), utils.fromB64(parsed.signature))).then(function (verify) { if (!verify || issuer !== parsed.publicKey) { _exit = 1; return false; } }); } }(); return _temp6 && _temp6.then ? _temp6.then(_temp7) : _temp7(_temp6); }, function () { return false; })); } } exports.WalrusDID = WalrusDID; //# sourceMappingURL=index.cjs.map