@keetanetwork/anchor 0.0.79 → 0.0.80
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/lib/anchor-external.d.ts +94 -1
- package/lib/anchor-external.d.ts.map +1 -1
- package/lib/anchor-external.generated.js +52 -3
- package/lib/anchor-external.generated.js.map +1 -1
- package/lib/anchor-external.js +126 -3
- package/lib/anchor-external.js.map +1 -1
- package/lib/anchor-metadata-server.d.ts +15 -2
- package/lib/anchor-metadata-server.d.ts.map +1 -1
- package/lib/anchor-metadata-server.js +54 -0
- package/lib/anchor-metadata-server.js.map +1 -1
- package/lib/anchor-status.d.ts +149 -0
- package/lib/anchor-status.d.ts.map +1 -0
- package/lib/anchor-status.js +93 -0
- package/lib/anchor-status.js.map +1 -0
- package/lib/chaining.d.ts +2 -1
- package/lib/chaining.d.ts.map +1 -1
- package/lib/chaining.js +67 -8
- package/lib/chaining.js.map +1 -1
- package/lib/history.d.ts +405 -0
- package/lib/history.d.ts.map +1 -0
- package/lib/history.js +723 -0
- package/lib/history.js.map +1 -0
- package/lib/http-server/index.d.ts +1 -0
- package/lib/http-server/index.d.ts.map +1 -1
- package/lib/http-server/index.js +1 -0
- package/lib/http-server/index.js.map +1 -1
- package/lib/index.d.ts +6 -1
- package/lib/index.d.ts.map +1 -1
- package/lib/index.js +3 -1
- package/lib/index.js.map +1 -1
- package/lib/metadata.types.d.ts +3 -0
- package/lib/metadata.types.d.ts.map +1 -1
- package/lib/metadata.types.js.map +1 -1
- package/lib/resolver.d.ts +28 -7
- package/lib/resolver.d.ts.map +1 -1
- package/lib/resolver.generated.js +528 -453
- package/lib/resolver.generated.js.map +1 -1
- package/lib/resolver.js +67 -8
- package/lib/resolver.js.map +1 -1
- package/lib/utils/brand.d.ts +5 -0
- package/lib/utils/brand.d.ts.map +1 -1
- package/lib/utils/brand.js +4 -1
- package/lib/utils/brand.js.map +1 -1
- package/npm-shrinkwrap.json +10 -17
- package/package.json +2 -2
- package/services/asset-movement/client.d.ts +7 -1
- package/services/asset-movement/client.d.ts.map +1 -1
- package/services/asset-movement/client.js +70 -15
- package/services/asset-movement/client.js.map +1 -1
- package/services/asset-movement/lib/location.d.ts.map +1 -1
- package/services/asset-movement/lib/location.js +1 -0
- package/services/asset-movement/lib/location.js.map +1 -1
- package/services/asset-movement/server.d.ts +1 -1
- package/services/asset-movement/server.d.ts.map +1 -1
- package/services/asset-movement/server.js +1 -1
- package/services/asset-movement/server.js.map +1 -1
- package/services/asset-movement/status-source.d.ts +32 -0
- package/services/asset-movement/status-source.d.ts.map +1 -0
- package/services/asset-movement/status-source.js +77 -0
- package/services/asset-movement/status-source.js.map +1 -0
- package/services/fx/server.d.ts +2 -2
- package/services/fx/server.d.ts.map +1 -1
- package/services/fx/server.js +2 -1
- package/services/fx/server.js.map +1 -1
- package/services/kyc/server.d.ts +1 -1
- package/services/kyc/server.d.ts.map +1 -1
- package/services/kyc/server.js +1 -1
- package/services/kyc/server.js.map +1 -1
- package/services/notification/client.js +50 -6
- package/services/notification/client.js.map +1 -1
- package/services/notification/server.d.ts.map +1 -1
- package/services/notification/server.js +4 -1
- package/services/notification/server.js.map +1 -1
- package/services/storage/client.js +50 -6
- package/services/storage/client.js.map +1 -1
- package/services/storage/clients/contacts.d.ts +5 -0
- package/services/storage/clients/contacts.d.ts.map +1 -1
- package/services/storage/clients/contacts.js +20 -9
- package/services/storage/clients/contacts.js.map +1 -1
- package/services/storage/server.d.ts +1 -1
- package/services/storage/server.d.ts.map +1 -1
- package/services/storage/server.js +2 -2
- package/services/storage/server.js.map +1 -1
- package/services/username/client.js +50 -6
- package/services/username/client.js.map +1 -1
- package/services/username/server.d.ts.map +1 -1
- package/services/username/server.js +4 -1
- package/services/username/server.js.map +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"anchor-external.js","sourceRoot":"","sources":["../../src/lib/anchor-external.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,qCAAqC,EAAE,MA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AC,KAAK,CAAC,EAAE,CAAC;gBAC/C,MAAK,CAAC,IAAI,mBAAmB,CAAC,eAAe,EAAE,kCAAkC,KAAK,CAAC,IAAI,EAAE,CAAC,CAAC,CAAC;YACjG,CAAC;YAED,MAAK,CAAC,KAAK,CAAC,CAAC;QACd,CAAC;QAED,IAAI,CAAC,KAAK,EAAE,CAAC;YACZ,MAAK,CAAC,IAAI,mBAAmB,CAAC,eAAe,EAAE,0DAA0D,CAAC,CAAC,CAAC;QAC7G,CAAC;QAED,MAAM,MAAM,GAAG,SAAS,CAAC,iBAAiB,EAAE,CAAC;QAC7C,IAAI,MAAM,KAAK,SAAS,EAAE,CAAC;YAC1B,MAAK,CAAC,IAAI,mBAAmB,CAAC,eAAe,EAAE,4DAA4D,CAAC,CAAC,CAAC;QAC/G,CAAC;QAED,IAAI,CAAC,YAAY,CAAC,QAAQ,EAAE,MAAM,CAAC,EAAE,CAAC;YACrC,MAAK,CAAC,IAAI,mBAAmB,CAAC,mBAAmB,EAAE,mDAAmD,CAAC,CAAC,CAAC;QAC1G,CAAC;QAED,OAAM,CAAC,EAAE,MAAM,EAAE,CAAC,CAAC;IACpB,CAAC","sourcesContent":["import type { lib as KeetaNetLib } from '@keetanetwork/keetanet-client';\n\nimport { assertEncodedAnchorExternalEnvelopeV1 } from './anchor-external.generated.js';\nimport { EncryptedContainer, EncryptedContainerError } from './encrypted-container.js';\nimport { KeetaAnchorError, KeetaAnchorUserError, KeetaAnchorUserValidationError } from './error.js';\nimport { canonicalizeJson } from './utils/signing.js';\nimport { Buffer, arrayBufferToBuffer, decodeBase64Strict } from './utils/buffer.js';\n\ntype Account = InstanceType<typeof KeetaNetLib.Account>;\n\n/**\n * Upper bound on inflated container plaintext, before JSON parsing.\n *\n * Prevents an attacker from forcing a large allocation via a\n * high-ratio gzip payload.\n */\nconst MAX_PLAINTEXT_BYTES = 4096;\n\n/**\n * Current envelope format version.\n */\nexport const ANCHOR_EXTERNAL_VERSION = 1;\n\n// #region Public types\n\n/**\n * Per-anchor entry.\n */\nexport type AnchorExternalEntry =\n\t| {\n\t\t/**\n\t\t * Transaction id at the anchor.\n\t\t */\n\t\ttransactionId: string;\n\t}\n\t| {\n\t\t/**\n\t\t * Persistent forwarding id at the anchor.\n\t\t */\n\t\tpersistentForwardingId: string;\n\t}\n\t| {\n\t\t/**\n\t\t * Opaque destination data interpreted by the anchor (e.g. an EVM\n\t\t * address for an EVM anchor).\n\t\t */\n\t\tdestination: string;\n\t};\n\n/**\n * Replay-protection binding for a signed envelope.\n *\n * Pins the signature to a specific position on the signer's account\n * chain so the same signed envelope cannot be reused on a different\n * operation or block.\n */\nexport type AnchorExternalBinding = {\n\t/**\n\t * Block hash that the signer's account had as its head when the\n\t * SEND carrying this envelope was constructed.\n\t */\n\tpreviousBlockHash: string;\n\t/**\n\t * Index of the SEND operation within its block.\n\t */\n\toperationIndex: number;\n};\n\n/**\n * Decoded anchor-external envelope as exposed to callers.\n */\nexport type AnchorExternalEnvelope = {\n\t/**\n\t * Envelope format version.\n\t */\n\tversion: typeof ANCHOR_EXTERNAL_VERSION;\n\t/**\n\t * Per-anchor entries keyed by `Account.publicKeyString.get()`.\n\t */\n\tanchors: { [anchorPublicKey: string]: AnchorExternalEntry };\n\t/**\n\t * Signature binding. Present if the envelope is signed.\n\t */\n\tbinding?: AnchorExternalBinding;\n};\n\n/**\n * Authenticity record attached to a verified signed envelope. Present only\n * when the signature was verified and the signer appears in\n * {@link AnchorExternalEnvelope.anchors}.\n */\nexport type AnchorExternalSigned = {\n\tsigner: Account;\n};\n\n/**\n * Shape inspection result from {@link AnchorExternal.peek}.\n */\nexport type AnchorExternalPeekResult = {\n\tencrypted: boolean;\n\tsigned: boolean;\n};\n\n// #endregion\n\n// #region Encoded form types (module-internal, exported for tests)\n\n/**\n * Per-anchor entry as it appears in the encoded envelope.\n *\n * `t` = transaction id, `p` = persistent forwarding id, `d` = destination.\n *\n * Note: Single-letter keys keep the envelope smaller.\n */\nexport type EncodedAnchorExternalEntryV1 =\n\t| { t: string }\n\t| { p: string }\n\t| { d: string };\n\n/**\n * Replay-protection binding as it appears in the encoded envelope.\n *\n * `p` = previous block hash, `o` = operation index.\n */\nexport type EncodedAnchorExternalBindingV1 = {\n\tp: string;\n\to: number;\n};\n\n/**\n * Anchor-external envelope as it appears inside the encoded blob.\n *\n * `v` = envelope version, `a` = anchors, `b` = binding.\n */\nexport type EncodedAnchorExternalEnvelopeV1 = {\n\tv: typeof ANCHOR_EXTERNAL_VERSION;\n\ta: { [anchorPublicKey: string]: EncodedAnchorExternalEntryV1 };\n\tb?: EncodedAnchorExternalBindingV1;\n};\n\n// #endregion\n\n// #region Error Handling\n\n/**\n * Error codes for anchor-external envelope operations.\n */\nexport const AnchorExternalErrorCodes = [\n\t/*\n\t * Parsing\n\t */\n\t'BAD_BASE64',\n\t'NOT_AN_ENVELOPE',\n\t'UNSUPPORTED_VERSION',\n\t'NON_CANONICAL',\n\t'PLAINTEXT_TOO_LARGE',\n\n\t/*\n\t * Non-repudiation\n\t */\n\t'BAD_SIGNATURE',\n\t'SIGNER_NOT_LISTED',\n\t'MISSING_BINDING',\n\t'UNEXPECTED_BINDING',\n\n\t/*\n\t * Confidentiality\n\t */\n\t'EXPECTED_PLAIN',\n\t'EXPECTED_ENCRYPTED',\n\n\t/*\n\t * Caller-declared budget\n\t */\n\t'OUTPUT_TOO_LARGE'\n] as const;\n\nexport type AnchorExternalErrorCode = typeof AnchorExternalErrorCodes[number];\n\nconst anchorExternalErrorCodeSet: ReadonlySet<string> = new Set(AnchorExternalErrorCodes);\n\n/**\n * Error raised by anchor-external decode failures.\n */\nexport class AnchorExternalError extends KeetaAnchorUserError {\n\tstatic override readonly name: string = 'AnchorExternalError';\n\n\tprivate readonly anchorExternalErrorObjectTypeID!: string;\n\tprivate static readonly anchorExternalErrorObjectTypeID = '2db22831-216b-4b3e-952a-5f9860f0790b';\n\n\treadonly code: AnchorExternalErrorCode;\n\n\t/**\n\t * Type-narrow an arbitrary string to {@link AnchorExternalErrorCode}.\n\t */\n\tstatic isValidCode(code: string): code is AnchorExternalErrorCode {\n\t\treturn(anchorExternalErrorCodeSet.has(code));\n\t}\n\n\tconstructor(code: AnchorExternalErrorCode, message: string) {\n\t\tsuper(message);\n\t\tthis.code = code;\n\n\t\tObject.defineProperty(this, 'anchorExternalErrorObjectTypeID', {\n\t\t\tvalue: AnchorExternalError.anchorExternalErrorObjectTypeID,\n\t\t\tenumerable: false\n\t\t});\n\t}\n\n\tstatic override isInstance(input: unknown): input is AnchorExternalError {\n\t\treturn(this.hasPropWithValue(input, 'anchorExternalErrorObjectTypeID', AnchorExternalError.anchorExternalErrorObjectTypeID));\n\t}\n\n\toverride toJSON(): ReturnType<KeetaAnchorUserError['toJSON']> & { code: AnchorExternalErrorCode } {\n\t\treturn({\n\t\t\t...super.toJSON(),\n\t\t\tcode: this.code\n\t\t});\n\t}\n\n\tstatic override async fromJSON(input: unknown): Promise<AnchorExternalError> {\n\t\tconst { message, other } = this.extractErrorProperties(input, this);\n\n\t\tif (!('code' in other) || typeof other.code !== 'string') {\n\t\t\tthrow(new Error('Invalid AnchorExternalError JSON: missing code property'));\n\t\t}\n\n\t\tconst code = other.code;\n\t\tif (!this.isValidCode(code)) {\n\t\t\tthrow(new Error(`Invalid AnchorExternalError JSON: unknown code ${code}`));\n\t\t}\n\n\t\tconst error = new this(code, message);\n\t\terror.restoreFromJSON(other);\n\t\treturn(error);\n\t}\n}\n\n// #endregion\n\n// #region Encoded <-> Public mappers\n\n/**\n * Convert a public entry to an encoded entry.\n */\nfunction entryToEncoded(entry: AnchorExternalEntry): EncodedAnchorExternalEntryV1 {\n\tif ('transactionId' in entry) {\n\t\treturn({ t: entry.transactionId });\n\t}\n\tif ('persistentForwardingId' in entry) {\n\t\treturn({ p: entry.persistentForwardingId });\n\t}\n\n\treturn({ d: entry.destination });\n}\n\n/**\n * Convert an encoded entry to a public entry.\n */\nfunction entryFromEncoded(entry: EncodedAnchorExternalEntryV1): AnchorExternalEntry {\n\tif ('t' in entry) {\n\t\treturn({ transactionId: entry.t });\n\t}\n\tif ('p' in entry) {\n\t\treturn({ persistentForwardingId: entry.p });\n\t}\n\n\treturn({ destination: entry.d });\n}\n\n/**\n * Convert a public envelope to an encoded envelope.\n */\nfunction envelopeToEncoded(envelope: AnchorExternalEnvelope): EncodedAnchorExternalEnvelopeV1 {\n\tconst encodedAnchors: { [anchorPublicKey: string]: EncodedAnchorExternalEntryV1 } = {};\n\tfor (const [pk, entry] of Object.entries(envelope.anchors)) {\n\t\tencodedAnchors[pk] = entryToEncoded(entry);\n\t}\n\n\tconst result: EncodedAnchorExternalEnvelopeV1 = {\n\t\tv: ANCHOR_EXTERNAL_VERSION,\n\t\ta: encodedAnchors\n\t};\n\tif (envelope.binding !== undefined) {\n\t\tresult.b = { p: envelope.binding.previousBlockHash, o: envelope.binding.operationIndex };\n\t}\n\n\treturn(result);\n}\n\n/**\n * Convert an encoded envelope to a public envelope.\n */\nfunction envelopeFromEncoded(encoded: EncodedAnchorExternalEnvelopeV1): AnchorExternalEnvelope {\n\tconst anchors: { [anchorPublicKey: string]: AnchorExternalEntry } = {};\n\tfor (const [pk, entry] of Object.entries(encoded.a)) {\n\t\tanchors[pk] = entryFromEncoded(entry);\n\t}\n\n\tconst result: AnchorExternalEnvelope = {\n\t\tversion: ANCHOR_EXTERNAL_VERSION,\n\t\tanchors\n\t};\n\tif (encoded.b !== undefined) {\n\t\tresult.binding = { previousBlockHash: encoded.b.p, operationIndex: encoded.b.o };\n\t}\n\n\treturn(result);\n}\n\n/**\n * Parse an encoded envelope.\n */\nfunction parseEncodedEnvelope(value: unknown): EncodedAnchorExternalEnvelopeV1 {\n\ttry {\n\t\treturn(assertEncodedAnchorExternalEnvelopeV1(value));\n\t} catch (error) {\n\t\tif (KeetaAnchorUserValidationError.isTypeGuardErrorLike(error)) {\n\t\t\tif (error.path === '$input.v') {\n\t\t\t\tthrow(new AnchorExternalError('UNSUPPORTED_VERSION', `Unsupported envelope version at ${error.path}: ${String(error.value)}`));\n\t\t\t}\n\n\t\t\tthrow(new AnchorExternalError('NOT_AN_ENVELOPE', `Envelope failed shape check at ${error.path ?? '$input'}: expected ${error.expected}`));\n\t\t}\n\n\t\tthrow(error);\n\t}\n}\n\n/**\n * Check if a signer is listed in the envelope.anchors.\n */\nfunction signerListed(envelope: AnchorExternalEnvelope, signer: Account): boolean {\n\tconst signerKey = signer.publicKeyString.get();\n\treturn(signerKey in envelope.anchors);\n}\n\n/**\n * Validate the shape of a {@link AnchorExternalBinding}.\n *\n * @returns `undefined` if valid, or an error message.\n */\nfunction validateBindingShape(binding: AnchorExternalBinding): string | undefined {\n\tif (typeof binding.previousBlockHash !== 'string' || binding.previousBlockHash.length === 0) {\n\t\treturn('binding.previousBlockHash must be a non-empty string');\n\t}\n\tif (!Number.isInteger(binding.operationIndex) || binding.operationIndex < 0) {\n\t\treturn(`binding.operationIndex must be a non-negative integer, got ${binding.operationIndex}`);\n\t}\n\n\treturn(undefined);\n}\n\n/**\n * Decode the base64-encoded string.\n */\nfunction decodeExternal(external: string): Buffer {\n\tconst decoded = decodeBase64Strict(external);\n\tif (decoded === undefined) {\n\t\tthrow(new AnchorExternalError('BAD_BASE64', 'External string is not valid base64 or decoded to zero bytes'));\n\t}\n\n\treturn(decoded);\n}\n\n// #endregion\n\n// #region AnchorExternalBuilder\n\n/**\n * Fluent builder for constructing an anchor-external envelope and producing\n * its encoded SEND.external string.\n */\nexport class AnchorExternalBuilder {\n\treadonly #anchors: { [anchorPublicKey: string]: AnchorExternalEntry } = {};\n\t#signer: Account | undefined;\n\t#principals: Account[] | undefined;\n\t#maxLength: number | undefined;\n\t#binding: AnchorExternalBinding | undefined;\n\n\t/**\n\t * Set the entry for a given anchor, replacing any prior entry\n\t * for the same anchor.\n\t */\n\tsetAnchor(anchor: Account, entry: AnchorExternalEntry): this {\n\t\tthis.#anchors[anchor.publicKeyString.get()] = entry;\n\t\treturn(this);\n\t}\n\n\t/**\n\t * Sign the produced envelope with the given account.\n\t */\n\twithSigner(signer: Account): this {\n\t\tthis.#signer = signer;\n\t\treturn(this);\n\t}\n\n\t/**\n\t * Encrypt the produced envelope so each listed principal can decrypt\n\t * it. Omit to leave the envelope as plaintext.\n\t */\n\twithPrincipals(principals: Account[]): this {\n\t\tthis.#principals = principals;\n\t\treturn(this);\n\t}\n\n\t/**\n\t * Bind the produced signature to a position on the signer's\n\t * account chain. Required whenever {@link withSigner} is used.\n\t *\n\t * @param previousBlockHash Block hash of the signer's current head.\n\t * @param operationIndex Index of the SEND operation within its block.\n\t */\n\twithBinding(previousBlockHash: string, operationIndex: number): this {\n\t\tconst candidate: AnchorExternalBinding = { previousBlockHash, operationIndex };\n\t\tconst error = validateBindingShape(candidate);\n\t\tif (error !== undefined) {\n\t\t\tthrow(new KeetaAnchorError(`withBinding: ${error}`));\n\t\t}\n\n\t\tthis.#binding = candidate;\n\t\treturn(this);\n\t}\n\n\t/**\n\t * Set an upper bound on the encoded output length. {@link build}\n\t * throws if the produced string would exceed this length.\n\t */\n\twithMaxLength(maxLength: number): this {\n\t\tif (!Number.isInteger(maxLength) || maxLength <= 0) {\n\t\t\tthrow(new KeetaAnchorError(`withMaxLength requires a positive integer, got ${maxLength}`));\n\t\t}\n\n\t\tthis.#maxLength = maxLength;\n\t\treturn(this);\n\t}\n\n\t/**\n\t * Snapshot of the envelope as it would be encoded right now.\n\t */\n\ttoEnvelope(): AnchorExternalEnvelope {\n\t\tconst result: AnchorExternalEnvelope = {\n\t\t\tversion: ANCHOR_EXTERNAL_VERSION,\n\t\t\tanchors: { ...this.#anchors }\n\t\t};\n\n\t\tif (this.#binding !== undefined) {\n\t\t\tresult.binding = { ...this.#binding };\n\t\t}\n\n\t\treturn(result);\n\t}\n\n\t/**\n\t * Produce the encoded SEND.external string.\n\t *\n\t * @throws {@link KeetaAnchorError} on caller misuse.\n\t */\n\tasync build(): Promise<string> {\n\t\tconst envelope = this.toEnvelope();\n\n\t\tif (this.#signer !== undefined && !signerListed(envelope, this.#signer)) {\n\t\t\tthrow(new KeetaAnchorError('Signer is not listed in envelope.anchors'));\n\t\t}\n\t\tif (this.#signer !== undefined && this.#binding === undefined) {\n\t\t\tthrow(new KeetaAnchorError('Signed envelopes require withBinding(previousBlockHash, operationIndex) for replay protection'));\n\t\t}\n\t\tif (this.#signer === undefined && this.#binding !== undefined) {\n\t\t\tthrow(new KeetaAnchorError('withBinding is only valid for signed envelopes'));\n\t\t}\n\n\t\tconst encoded = envelopeToEncoded(envelope);\n\t\tconst canonical = canonicalizeJson(encoded);\n\t\tconst plaintext = Buffer.from(canonical, 'utf-8');\n\n\t\tconst principals = this.#principals ?? null;\n\t\tlet containerOptions: { signer: Account } | undefined;\n\t\tif (this.#signer !== undefined) {\n\t\t\tcontainerOptions = { signer: this.#signer };\n\t\t}\n\n\t\tconst container = EncryptedContainer.fromPlaintext(plaintext, principals, containerOptions);\n\t\tconst containerBuffer = arrayBufferToBuffer(await container.getEncodedBuffer());\n\t\tconst external = containerBuffer.toString('base64');\n\n\t\tif (this.#maxLength !== undefined && external.length > this.#maxLength) {\n\t\t\tthrow(new KeetaAnchorError(`Encoded external length ${external.length} exceeds caller maxLength ${this.#maxLength}`));\n\t\t}\n\n\t\treturn(external);\n\t}\n}\n\n// #endregion\n\n// #region AnchorExternal\n\n/**\n * Immutable, verified view of a parsed SEND.external envelope.\n */\nexport class AnchorExternal {\n\tstatic readonly Builder: typeof AnchorExternalBuilder = AnchorExternalBuilder;\n\n\treadonly #envelope: AnchorExternalEnvelope;\n\treadonly #encrypted: boolean;\n\treadonly #signed: AnchorExternalSigned | undefined;\n\n\tprivate constructor(envelope: AnchorExternalEnvelope, encrypted: boolean, signed: AnchorExternalSigned | undefined) {\n\t\tthis.#envelope = envelope;\n\t\tthis.#encrypted = encrypted;\n\t\tthis.#signed = signed;\n\t}\n\n\t/**\n\t * Decoded envelope.\n\t */\n\tget envelope(): AnchorExternalEnvelope {\n\t\treturn(this.#envelope);\n\t}\n\n\t/**\n\t * `true` if the source blob was encrypted.\n\t */\n\tget encrypted(): boolean {\n\t\treturn(this.#encrypted);\n\t}\n\n\t/**\n\t * Authenticity record for a verified signed envelope, or `undefined`\n\t * if the envelope was not signed.\n\t */\n\tget signed(): AnchorExternalSigned | undefined {\n\t\treturn(this.#signed);\n\t}\n\n\t/**\n\t * Decode an external string asserted to be plaintext.\n\t *\n\t * @throws {@link AnchorExternalError} `EXPECTED_PLAIN` if the source blob is encrypted.\n\t */\n\tstatic async fromPlainExternal(external: string): Promise<AnchorExternal> {\n\t\tconst buffer = decodeExternal(external);\n\n\t\tlet container: EncryptedContainer;\n\t\ttry {\n\t\t\tcontainer = EncryptedContainer.fromEncodedBuffer(buffer, null);\n\t\t} catch (error) {\n\t\t\tif (EncryptedContainerError.isInstance(error)) {\n\t\t\t\tif (error.code === 'INVALID_PRINCIPALS') {\n\t\t\t\t\tthrow(new AnchorExternalError('EXPECTED_PLAIN', 'Blob is encrypted but plaintext was expected'));\n\t\t\t\t}\n\t\t\t\tthrow(new AnchorExternalError('NOT_AN_ENVELOPE', `Container parse failed: ${error.code}`));\n\t\t\t}\n\t\t\tthrow(error);\n\t\t}\n\n\t\tif (container.encrypted) {\n\t\t\tthrow(new AnchorExternalError('EXPECTED_PLAIN', 'Blob is encrypted but plaintext was expected'));\n\t\t}\n\n\t\tconst result = await AnchorExternal.fromContainer(container, false);\n\t\treturn(result);\n\t}\n\n\t/**\n\t * Decode an external string asserted to be encrypted under one of the\n\t * supplied principals.\n\t *\n\t * @throws {@link AnchorExternalError} `EXPECTED_ENCRYPTED` if the source blob is plaintext.\n\t * @throws {@link KeetaAnchorError} if `principals` is empty.\n\t */\n\tstatic async fromEncryptedExternal(external: string, principals: Account[]): Promise<AnchorExternal> {\n\t\tif (principals.length === 0) {\n\t\t\tthrow(new KeetaAnchorError('AnchorExternal.fromEncryptedExternal requires at least one principal'));\n\t\t}\n\n\t\tconst buffer = decodeExternal(external);\n\t\tlet container: EncryptedContainer;\n\t\ttry {\n\t\t\tcontainer = EncryptedContainer.fromEncryptedBuffer(buffer, principals);\n\t\t} catch (error) {\n\t\t\tif (EncryptedContainerError.isInstance(error)) {\n\t\t\t\tif (error.code === 'ENCRYPTION_REQUIRED') {\n\t\t\t\t\tthrow(new AnchorExternalError('EXPECTED_ENCRYPTED', 'Blob is plaintext but encrypted was expected'));\n\t\t\t\t}\n\n\t\t\t\tthrow(new AnchorExternalError('NOT_AN_ENVELOPE', `Container parse failed: ${error.code}`));\n\t\t\t}\n\n\t\t\tthrow(error);\n\t\t}\n\n\t\tif (!container.encrypted) {\n\t\t\tthrow(new AnchorExternalError('EXPECTED_ENCRYPTED', 'Blob is plaintext but encrypted was expected'));\n\t\t}\n\n\t\tconst result = await AnchorExternal.fromContainer(container, true);\n\t\treturn(result);\n\t}\n\n\t/**\n\t * Inspect encrypted/signed flags of a candidate external string\n\t * without reading plaintext or requiring a decryption key.\n\t */\n\tstatic async peek(external: string): Promise<AnchorExternalPeekResult> {\n\t\tconst buffer = decodeExternal(external);\n\t\tlet container: EncryptedContainer;\n\t\ttry {\n\t\t\tcontainer = EncryptedContainer.fromEncodedBuffer(buffer, []);\n\t\t} catch (error) {\n\t\t\tif (EncryptedContainerError.isInstance(error)) {\n\t\t\t\tthrow(new AnchorExternalError('NOT_AN_ENVELOPE', `Container parse failed: ${error.code}`));\n\t\t\t}\n\n\t\t\tthrow(error);\n\t\t}\n\n\t\treturn({\n\t\t\tencrypted: container.encrypted,\n\t\t\tsigned: container.isSigned\n\t\t});\n\t}\n\n\t/**\n\t * Create an {@link AnchorExternal} from a container.\n\t */\n\tprivate static async fromContainer(container: EncryptedContainer, encrypted: boolean): Promise<AnchorExternal> {\n\t\tconst envelope = await AnchorExternal.readEnvelope(container);\n\t\tconst signed = await AnchorExternal.readSigned(container, envelope);\n\t\tconst result = new AnchorExternal(envelope, encrypted, signed);\n\t\treturn(result);\n\t}\n\n\t/**\n\t * Read the envelope from a container.\n\t */\n\tprivate static async readEnvelope(container: EncryptedContainer): Promise<AnchorExternalEnvelope> {\n\t\tlet plaintextArrayBuffer: ArrayBuffer;\n\t\ttry {\n\t\t\tplaintextArrayBuffer = await container.getPlaintext();\n\t\t} catch (error) {\n\t\t\tif (EncryptedContainerError.isInstance(error)) {\n\t\t\t\tthrow(new AnchorExternalError('NOT_AN_ENVELOPE', `Container plaintext unavailable: ${error.code}`));\n\t\t\t}\n\t\t\tthrow(error);\n\t\t}\n\n\t\tif (plaintextArrayBuffer.byteLength > MAX_PLAINTEXT_BYTES) {\n\t\t\tthrow(new AnchorExternalError('PLAINTEXT_TOO_LARGE', `Container plaintext exceeds ${MAX_PLAINTEXT_BYTES} bytes`));\n\t\t}\n\n\t\tconst plaintextBuffer = arrayBufferToBuffer(plaintextArrayBuffer);\n\t\tconst plaintextString = plaintextBuffer.toString('utf-8');\n\n\t\tlet parsed: unknown;\n\t\ttry {\n\t\t\tparsed = JSON.parse(plaintextString);\n\t\t} catch {\n\t\t\tthrow(new AnchorExternalError('NOT_AN_ENVELOPE', 'Container plaintext is not valid JSON'));\n\t\t}\n\n\t\tconst encoded = parseEncodedEnvelope(parsed);\n\n\t\t/*\n\t\t * Reject non-canonical encodings: an attacker could otherwise\n\t\t * mutate the JSON shape under a still-valid signature on the\n\t\t * original bytes.\n\t\t */\n\t\tconst reCanonical = canonicalizeJson(encoded);\n\t\tif (reCanonical !== plaintextString) {\n\t\t\tthrow(new AnchorExternalError('NON_CANONICAL', 'Container plaintext is not JCS-canonical'));\n\t\t}\n\n\t\tconst result = envelopeFromEncoded(encoded);\n\t\treturn(result);\n\t}\n\n\t/**\n\t * Read the signed record from a container.\n\t */\n\tprivate static async readSigned(container: EncryptedContainer, envelope: AnchorExternalEnvelope): Promise<AnchorExternalSigned | undefined> {\n\t\tif (!container.isSigned) {\n\t\t\tif (envelope.binding !== undefined) {\n\t\t\t\tthrow(new AnchorExternalError('UNEXPECTED_BINDING', 'Unsigned envelope carries a binding'));\n\t\t\t}\n\n\t\t\treturn(undefined);\n\t\t}\n\n\t\tif (envelope.binding === undefined) {\n\t\t\tthrow(new AnchorExternalError('MISSING_BINDING', 'Signed envelope is missing required binding'));\n\t\t}\n\n\t\tlet valid: boolean;\n\t\ttry {\n\t\t\tvalid = await container.verifySignature();\n\t\t} catch (error) {\n\t\t\tif (EncryptedContainerError.isInstance(error)) {\n\t\t\t\tthrow(new AnchorExternalError('BAD_SIGNATURE', `Signature verification failed: ${error.code}`));\n\t\t\t}\n\n\t\t\tthrow(error);\n\t\t}\n\n\t\tif (!valid) {\n\t\t\tthrow(new AnchorExternalError('BAD_SIGNATURE', 'Signature did not verify against the contained plaintext'));\n\t\t}\n\n\t\tconst signer = container.getSigningAccount();\n\t\tif (signer === undefined) {\n\t\t\tthrow(new AnchorExternalError('BAD_SIGNATURE', 'Container is signed but the signing account is unavailable'));\n\t\t}\n\n\t\tif (!signerListed(envelope, signer)) {\n\t\t\tthrow(new AnchorExternalError('SIGNER_NOT_LISTED', 'Signing account is not listed in envelope.anchors'));\n\t\t}\n\n\t\treturn({ signer });\n\t}\n}\n\n// #endregion\n"]}
|
|
1
|
+
{"version":3,"file":"anchor-external.js","sourceRoot":"","sources":["../../src/lib/anchor-external.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,qCAAqC,EAAE,MAAM,gCAAgC,CAAC;AACvF,OAAO,EAAE,kBAAkB,EAAE,uBAAuB,EAAE,MAAM,0BAA0B,CAAC;AACvF,OAAO,EAAE,gBAAgB,EAAE,oBAAoB,EAAE,8BAA8B,EAAE,MAAM,YAAY,CAAC;AACpG,OAAO,EAAE,gBAAgB,EAAE,MAAM,oBAAoB,CAAC;AACtD,OAAO,EAAE,MAAM,EAAE,mBAAmB,EAAE,kBAAkB,EAAE,MAAM,mBAAmB,CAAC;AAIpF;;;;;GAKG;AACH,MAAM,mBAAmB,GAAG,IAAI,CAAC;AAEjC;;GAEG;AACH,MAAM,CAAC,MAAM,uBAAuB,GAAG,CAAC,CAAC;AAEzC;;;GAGG;AACH,MAAM,mBAAmB,GAA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AK,SAAS,EAAE,CAAC;YAC1B,MAAK,CAAC,IAAI,mBAAmB,CAAC,eAAe,EAAE,4DAA4D,CAAC,CAAC,CAAC;QAC/G,CAAC;QAED,IAAI,CAAC,YAAY,CAAC,QAAQ,EAAE,MAAM,CAAC,EAAE,CAAC;YACrC,MAAK,CAAC,IAAI,mBAAmB,CAAC,mBAAmB,EAAE,mDAAmD,CAAC,CAAC,CAAC;QAC1G,CAAC;QAED,OAAM,CAAC,EAAE,MAAM,EAAE,CAAC,CAAC;IACpB,CAAC","sourcesContent":["import type { lib as KeetaNetLib } from '@keetanetwork/keetanet-client';\n\nimport { assertEncodedAnchorExternalEnvelopeV1 } from './anchor-external.generated.js';\nimport { EncryptedContainer, EncryptedContainerError } from './encrypted-container.js';\nimport { KeetaAnchorError, KeetaAnchorUserError, KeetaAnchorUserValidationError } from './error.js';\nimport { canonicalizeJson } from './utils/signing.js';\nimport { Buffer, arrayBufferToBuffer, decodeBase64Strict } from './utils/buffer.js';\n\ntype Account = InstanceType<typeof KeetaNetLib.Account>;\n\n/**\n * Upper bound on inflated container plaintext, before JSON parsing.\n *\n * Prevents an attacker from forcing a large allocation via a\n * high-ratio gzip payload.\n */\nconst MAX_PLAINTEXT_BYTES = 4096;\n\n/**\n * Current envelope format version.\n */\nexport const ANCHOR_EXTERNAL_VERSION = 1;\n\n/**\n * Largest valid operation index, matching the 32-bit bound used for\n * operation indexes elsewhere in the protocol.\n */\nconst MAX_OPERATION_INDEX = 2 ** 32 - 1;\n\n// #region Public types\n\n/**\n * Per-anchor entry.\n */\nexport type AnchorExternalEntry =\n\t| {\n\t\t/**\n\t\t * Transaction id at the anchor.\n\t\t */\n\t\ttransactionId: string;\n\t}\n\t| {\n\t\t/**\n\t\t * Persistent forwarding id at the anchor.\n\t\t */\n\t\tpersistentForwardingId: string;\n\t}\n\t| {\n\t\t/**\n\t\t * Opaque destination data interpreted by the anchor (e.g. an EVM\n\t\t * address for an EVM anchor).\n\t\t */\n\t\tdestination: string;\n\t};\n\n/**\n * Replay-protection binding for a signed envelope.\n *\n * Pins the signature to a specific position on the signer's account\n * chain so the same signed envelope cannot be reused on a different\n * operation or block.\n */\nexport type AnchorExternalBinding = {\n\t/**\n\t * Block hash that the signer's account had as its head when the\n\t * SEND carrying this envelope was constructed.\n\t */\n\tpreviousBlockHash: string;\n\t/**\n\t * Index of the SEND operation within its block.\n\t *\n\t * Valid range: `0` to `2^32 - 1` inclusive.\n\t */\n\toperationIndex: number;\n};\n\n/**\n * Reference to a prior on-chain operation that is relevant to the\n * transfer this envelope describes.\n *\n * Inputs are backward links: an envelope can only reference operations\n * whose block hashes are already known when the carrying SEND is\n * constructed.\n *\n * When the envelope is signed, inputs are part of the signed plaintext\n * and the signer cannot later repudiate the claimed relevance.\n */\nexport type AnchorExternalInput = {\n\t/**\n\t * Hash of the block carrying the referenced operation.\n\t */\n\tblockHash: string;\n\t/**\n\t * Index of the referenced operation within its block. Omit to\n\t * reference the block as a whole.\n\t *\n\t * Valid range: `0` to `2^32 - 1` inclusive.\n\t */\n\toperationIndex?: number;\n};\n\n/**\n * Decoded anchor-external envelope as exposed to callers.\n */\nexport type AnchorExternalEnvelope = {\n\t/**\n\t * Envelope format version.\n\t */\n\tversion: typeof ANCHOR_EXTERNAL_VERSION;\n\t/**\n\t * Per-anchor entries keyed by `Account.publicKeyString.get()`.\n\t */\n\tanchors: { [anchorPublicKey: string]: AnchorExternalEntry };\n\t/**\n\t * Signature binding. Present if the envelope is signed.\n\t */\n\tbinding?: AnchorExternalBinding;\n\t/**\n\t * References to prior on-chain operations relevant to this transfer,\n\t * in the order they were added. Present only when non-empty.\n\t */\n\tinputs?: AnchorExternalInput[];\n};\n\n/**\n * Authenticity record attached to a verified signed envelope. Present only\n * when the signature was verified and the signer appears in\n * {@link AnchorExternalEnvelope.anchors}.\n */\nexport type AnchorExternalSigned = {\n\tsigner: Account;\n};\n\n/**\n * Shape inspection result from {@link AnchorExternal.peek}.\n */\nexport type AnchorExternalPeekResult = {\n\tencrypted: boolean;\n\tsigned: boolean;\n};\n\n// #endregion\n\n// #region Encoded form types (module-internal, exported for tests)\n\n/**\n * Per-anchor entry as it appears in the encoded envelope.\n *\n * `t` = transaction id, `p` = persistent forwarding id, `d` = destination.\n *\n * Note: Single-letter keys keep the envelope smaller.\n */\nexport type EncodedAnchorExternalEntryV1 =\n\t| { t: string }\n\t| { p: string }\n\t| { d: string };\n\n/**\n * Replay-protection binding as it appears in the encoded envelope.\n *\n * `p` = previous block hash, `o` = operation index.\n */\nexport type EncodedAnchorExternalBindingV1 = {\n\tp: string;\n\to: number;\n};\n\n/**\n * Input reference as it appears in the encoded envelope.\n *\n * `h` = block hash, `o` = operation index.\n */\nexport type EncodedAnchorExternalInputV1 = {\n\th: string;\n\to?: number;\n};\n\n/**\n * Anchor-external envelope as it appears inside the encoded blob.\n *\n * `v` = envelope version, `a` = anchors, `b` = binding, `i` = inputs.\n */\nexport type EncodedAnchorExternalEnvelopeV1 = {\n\tv: typeof ANCHOR_EXTERNAL_VERSION;\n\ta: { [anchorPublicKey: string]: EncodedAnchorExternalEntryV1 };\n\tb?: EncodedAnchorExternalBindingV1;\n\ti?: EncodedAnchorExternalInputV1[];\n};\n\n// #endregion\n\n// #region Error Handling\n\n/**\n * Error codes for anchor-external envelope operations.\n */\nexport const AnchorExternalErrorCodes = [\n\t/*\n\t * Parsing\n\t */\n\t'BAD_BASE64',\n\t'NOT_AN_ENVELOPE',\n\t'UNSUPPORTED_VERSION',\n\t'NON_CANONICAL',\n\t'PLAINTEXT_TOO_LARGE',\n\n\t/*\n\t * Non-repudiation\n\t */\n\t'BAD_SIGNATURE',\n\t'SIGNER_NOT_LISTED',\n\t'MISSING_BINDING',\n\t'UNEXPECTED_BINDING',\n\n\t/*\n\t * Confidentiality\n\t */\n\t'EXPECTED_PLAIN',\n\t'EXPECTED_ENCRYPTED',\n\n\t/*\n\t * Caller-declared budget\n\t */\n\t'OUTPUT_TOO_LARGE'\n] as const;\n\nexport type AnchorExternalErrorCode = typeof AnchorExternalErrorCodes[number];\n\nconst anchorExternalErrorCodeSet: ReadonlySet<string> = new Set(AnchorExternalErrorCodes);\n\n/**\n * Error raised by anchor-external decode failures.\n */\nexport class AnchorExternalError extends KeetaAnchorUserError {\n\tstatic override readonly name: string = 'AnchorExternalError';\n\n\tprivate readonly anchorExternalErrorObjectTypeID!: string;\n\tprivate static readonly anchorExternalErrorObjectTypeID = '2db22831-216b-4b3e-952a-5f9860f0790b';\n\n\treadonly code: AnchorExternalErrorCode;\n\n\t/**\n\t * Type-narrow an arbitrary string to {@link AnchorExternalErrorCode}.\n\t */\n\tstatic isValidCode(code: string): code is AnchorExternalErrorCode {\n\t\treturn(anchorExternalErrorCodeSet.has(code));\n\t}\n\n\tconstructor(code: AnchorExternalErrorCode, message: string) {\n\t\tsuper(message);\n\t\tthis.code = code;\n\n\t\tObject.defineProperty(this, 'anchorExternalErrorObjectTypeID', {\n\t\t\tvalue: AnchorExternalError.anchorExternalErrorObjectTypeID,\n\t\t\tenumerable: false\n\t\t});\n\t}\n\n\tstatic override isInstance(input: unknown): input is AnchorExternalError {\n\t\treturn(this.hasPropWithValue(input, 'anchorExternalErrorObjectTypeID', AnchorExternalError.anchorExternalErrorObjectTypeID));\n\t}\n\n\toverride toJSON(): ReturnType<KeetaAnchorUserError['toJSON']> & { code: AnchorExternalErrorCode } {\n\t\treturn({\n\t\t\t...super.toJSON(),\n\t\t\tcode: this.code\n\t\t});\n\t}\n\n\tstatic override async fromJSON(input: unknown): Promise<AnchorExternalError> {\n\t\tconst { message, other } = this.extractErrorProperties(input, this);\n\n\t\tif (!('code' in other) || typeof other.code !== 'string') {\n\t\t\tthrow(new Error('Invalid AnchorExternalError JSON: missing code property'));\n\t\t}\n\n\t\tconst code = other.code;\n\t\tif (!this.isValidCode(code)) {\n\t\t\tthrow(new Error(`Invalid AnchorExternalError JSON: unknown code ${code}`));\n\t\t}\n\n\t\tconst error = new this(code, message);\n\t\terror.restoreFromJSON(other);\n\t\treturn(error);\n\t}\n}\n\n// #endregion\n\n// #region Encoded <-> Public mappers\n\n/**\n * Convert a public entry to an encoded entry.\n */\nfunction entryToEncoded(entry: AnchorExternalEntry): EncodedAnchorExternalEntryV1 {\n\tif ('transactionId' in entry) {\n\t\treturn({ t: entry.transactionId });\n\t}\n\tif ('persistentForwardingId' in entry) {\n\t\treturn({ p: entry.persistentForwardingId });\n\t}\n\n\treturn({ d: entry.destination });\n}\n\n/**\n * Convert an encoded entry to a public entry.\n */\nfunction entryFromEncoded(entry: EncodedAnchorExternalEntryV1): AnchorExternalEntry {\n\tif ('t' in entry) {\n\t\treturn({ transactionId: entry.t });\n\t}\n\tif ('p' in entry) {\n\t\treturn({ persistentForwardingId: entry.p });\n\t}\n\n\treturn({ destination: entry.d });\n}\n\n/**\n * Convert a public input reference to an encoded input reference.\n */\nfunction inputToEncoded(input: AnchorExternalInput): EncodedAnchorExternalInputV1 {\n\tconst result: EncodedAnchorExternalInputV1 = { h: input.blockHash };\n\tif (input.operationIndex !== undefined) {\n\t\tresult.o = input.operationIndex;\n\t}\n\n\treturn(result);\n}\n\n/**\n * Convert an encoded input reference to a public input reference.\n */\nfunction inputFromEncoded(input: EncodedAnchorExternalInputV1): AnchorExternalInput {\n\tconst result: AnchorExternalInput = { blockHash: input.h };\n\tif (input.o !== undefined) {\n\t\tresult.operationIndex = input.o;\n\t}\n\n\treturn(result);\n}\n\n/**\n * Convert a public envelope to an encoded envelope.\n */\nfunction envelopeToEncoded(envelope: AnchorExternalEnvelope): EncodedAnchorExternalEnvelopeV1 {\n\tconst encodedAnchors: { [anchorPublicKey: string]: EncodedAnchorExternalEntryV1 } = {};\n\tfor (const [pk, entry] of Object.entries(envelope.anchors)) {\n\t\tencodedAnchors[pk] = entryToEncoded(entry);\n\t}\n\n\tconst result: EncodedAnchorExternalEnvelopeV1 = {\n\t\tv: ANCHOR_EXTERNAL_VERSION,\n\t\ta: encodedAnchors\n\t};\n\tif (envelope.binding !== undefined) {\n\t\tresult.b = { p: envelope.binding.previousBlockHash, o: envelope.binding.operationIndex };\n\t}\n\n\tif (envelope.inputs !== undefined) {\n\t\tresult.i = envelope.inputs.map(inputToEncoded);\n\t}\n\n\treturn(result);\n}\n\n/**\n * Convert an encoded envelope to a public envelope.\n */\nfunction envelopeFromEncoded(encoded: EncodedAnchorExternalEnvelopeV1): AnchorExternalEnvelope {\n\tconst anchors: { [anchorPublicKey: string]: AnchorExternalEntry } = {};\n\tfor (const [pk, entry] of Object.entries(encoded.a)) {\n\t\tanchors[pk] = entryFromEncoded(entry);\n\t}\n\n\tconst result: AnchorExternalEnvelope = {\n\t\tversion: ANCHOR_EXTERNAL_VERSION,\n\t\tanchors\n\t};\n\tif (encoded.b !== undefined) {\n\t\tresult.binding = { previousBlockHash: encoded.b.p, operationIndex: encoded.b.o };\n\t}\n\n\tif (encoded.i !== undefined) {\n\t\tresult.inputs = encoded.i.map(inputFromEncoded);\n\t}\n\n\treturn(result);\n}\n\n/**\n * Parse an encoded envelope.\n */\nfunction parseEncodedEnvelope(value: unknown): EncodedAnchorExternalEnvelopeV1 {\n\ttry {\n\t\treturn(assertEncodedAnchorExternalEnvelopeV1(value));\n\t} catch (error) {\n\t\tif (KeetaAnchorUserValidationError.isTypeGuardErrorLike(error)) {\n\t\t\tif (error.path === '$input.v') {\n\t\t\t\tthrow(new AnchorExternalError('UNSUPPORTED_VERSION', `Unsupported envelope version at ${error.path}: ${String(error.value)}`));\n\t\t\t}\n\n\t\t\tthrow(new AnchorExternalError('NOT_AN_ENVELOPE', `Envelope failed shape check at ${error.path ?? '$input'}: expected ${error.expected}`));\n\t\t}\n\n\t\tthrow(error);\n\t}\n}\n\n/**\n * Check if a signer is listed in the envelope.anchors.\n */\nfunction signerListed(envelope: AnchorExternalEnvelope, signer: Account): boolean {\n\tconst signerKey = signer.publicKeyString.get();\n\treturn(signerKey in envelope.anchors);\n}\n\n/**\n * Validate an operation index against its valid range of `0` to\n * `2^32 - 1` inclusive.\n *\n * @returns `undefined` if valid, or an error message.\n */\nfunction validateOperationIndex(label: string, value: number): string | undefined {\n\tif (!Number.isSafeInteger(value)) {\n\t\treturn(`${label} must be an integer, got ${value}`);\n\t}\n\n\tif (value < 0) {\n\t\treturn(`${label} must not be negative, got ${value}`);\n\t}\n\n\tif (value > MAX_OPERATION_INDEX) {\n\t\treturn(`${label} must not exceed ${MAX_OPERATION_INDEX}, got ${value}`);\n\t}\n\n\treturn(undefined);\n}\n\n/**\n * Validate the shape of a {@link AnchorExternalBinding}.\n *\n * @returns `undefined` if valid, or an error message.\n */\nfunction validateBindingShape(binding: AnchorExternalBinding): string | undefined {\n\tif (typeof binding.previousBlockHash !== 'string' || binding.previousBlockHash.length === 0) {\n\t\treturn('binding.previousBlockHash must be a non-empty string');\n\t}\n\n\treturn(validateOperationIndex('binding.operationIndex', binding.operationIndex));\n}\n\n/**\n * Validate the shape of an {@link AnchorExternalInput}.\n *\n * @returns `undefined` if valid, or an error message.\n */\nfunction validateInputShape(input: AnchorExternalInput): string | undefined {\n\tif (typeof input.blockHash !== 'string' || input.blockHash.length === 0) {\n\t\treturn('input.blockHash must be a non-empty string');\n\t}\n\n\tif (input.operationIndex === undefined) {\n\t\treturn(undefined);\n\t}\n\n\treturn(validateOperationIndex('input.operationIndex', input.operationIndex));\n}\n\n/**\n * Decode the base64-encoded string.\n */\nfunction decodeExternal(external: string): Buffer {\n\tconst decoded = decodeBase64Strict(external);\n\tif (decoded === undefined) {\n\t\tthrow(new AnchorExternalError('BAD_BASE64', 'External string is not valid base64 or decoded to zero bytes'));\n\t}\n\n\treturn(decoded);\n}\n\n// #endregion\n\n// #region AnchorExternalBuilder\n\n/**\n * Fluent builder for constructing an anchor-external envelope and producing\n * its encoded SEND.external string.\n */\nexport class AnchorExternalBuilder {\n\treadonly #anchors: { [anchorPublicKey: string]: AnchorExternalEntry } = {};\n\treadonly #inputs: AnchorExternalInput[] = [];\n\t#signer: Account | undefined;\n\t#principals: Account[] | undefined;\n\t#maxLength: number | undefined;\n\t#binding: AnchorExternalBinding | undefined;\n\n\t/**\n\t * Set the entry for a given anchor, replacing any prior entry\n\t * for the same anchor.\n\t */\n\tsetAnchor(anchor: Account, entry: AnchorExternalEntry): this {\n\t\tthis.#anchors[anchor.publicKeyString.get()] = entry;\n\t\treturn(this);\n\t}\n\n\t/**\n\t * Append a reference to a prior on-chain operation relevant to this\n\t * transfer. Order of addition is preserved in the envelope.\n\t *\n\t * @param blockHash Hash of the block carrying the referenced operation.\n\t * @param operationIndex Index of the operation within its block. Omit to\n\t * reference the block as a whole.\n\t */\n\taddInput(blockHash: string, operationIndex?: number): this {\n\t\tconst candidate: AnchorExternalInput = { blockHash };\n\t\tif (operationIndex !== undefined) {\n\t\t\tcandidate.operationIndex = operationIndex;\n\t\t}\n\n\t\tconst error = validateInputShape(candidate);\n\t\tif (error !== undefined) {\n\t\t\tthrow(new KeetaAnchorError(`addInput: ${error}`));\n\t\t}\n\n\t\tthis.#inputs.push(candidate);\n\t\treturn(this);\n\t}\n\n\t/**\n\t * Sign the produced envelope with the given account.\n\t */\n\twithSigner(signer: Account): this {\n\t\tthis.#signer = signer;\n\t\treturn(this);\n\t}\n\n\t/**\n\t * Encrypt the produced envelope so each listed principal can decrypt\n\t * it. Omit to leave the envelope as plaintext.\n\t */\n\twithPrincipals(principals: Account[]): this {\n\t\tthis.#principals = principals;\n\t\treturn(this);\n\t}\n\n\t/**\n\t * Bind the produced signature to a position on the signer's\n\t * account chain. Required whenever {@link withSigner} is used.\n\t *\n\t * @param previousBlockHash Block hash of the signer's current head.\n\t * @param operationIndex Index of the SEND operation within its block.\n\t */\n\twithBinding(previousBlockHash: string, operationIndex: number): this {\n\t\tconst candidate: AnchorExternalBinding = { previousBlockHash, operationIndex };\n\t\tconst error = validateBindingShape(candidate);\n\t\tif (error !== undefined) {\n\t\t\tthrow(new KeetaAnchorError(`withBinding: ${error}`));\n\t\t}\n\n\t\tthis.#binding = candidate;\n\t\treturn(this);\n\t}\n\n\t/**\n\t * Set an upper bound on the encoded output length. {@link build}\n\t * throws if the produced string would exceed this length.\n\t */\n\twithMaxLength(maxLength: number): this {\n\t\tif (!Number.isInteger(maxLength) || maxLength <= 0) {\n\t\t\tthrow(new KeetaAnchorError(`withMaxLength requires a positive integer, got ${maxLength}`));\n\t\t}\n\n\t\tthis.#maxLength = maxLength;\n\t\treturn(this);\n\t}\n\n\t/**\n\t * Snapshot of the envelope as it would be encoded right now.\n\t */\n\ttoEnvelope(): AnchorExternalEnvelope {\n\t\tconst result: AnchorExternalEnvelope = {\n\t\t\tversion: ANCHOR_EXTERNAL_VERSION,\n\t\t\tanchors: { ...this.#anchors }\n\t\t};\n\n\t\tif (this.#binding !== undefined) {\n\t\t\tresult.binding = { ...this.#binding };\n\t\t}\n\n\t\tif (this.#inputs.length > 0) {\n\t\t\tresult.inputs = this.#inputs.map(function(input) {\n\t\t\t\treturn({ ...input });\n\t\t\t});\n\t\t}\n\n\t\treturn(result);\n\t}\n\n\t/**\n\t * Produce the encoded SEND.external string.\n\t *\n\t * @throws {@link KeetaAnchorError} on caller misuse.\n\t */\n\tasync build(): Promise<string> {\n\t\tconst envelope = this.toEnvelope();\n\n\t\tif (this.#signer !== undefined && !signerListed(envelope, this.#signer)) {\n\t\t\tthrow(new KeetaAnchorError('Signer is not listed in envelope.anchors'));\n\t\t}\n\t\tif (this.#signer !== undefined && this.#binding === undefined) {\n\t\t\tthrow(new KeetaAnchorError('Signed envelopes require withBinding(previousBlockHash, operationIndex) for replay protection'));\n\t\t}\n\t\tif (this.#signer === undefined && this.#binding !== undefined) {\n\t\t\tthrow(new KeetaAnchorError('withBinding is only valid for signed envelopes'));\n\t\t}\n\n\t\tconst encoded = envelopeToEncoded(envelope);\n\t\tconst canonical = canonicalizeJson(encoded);\n\t\tconst plaintext = Buffer.from(canonical, 'utf-8');\n\n\t\tconst principals = this.#principals ?? null;\n\t\tlet containerOptions: { signer: Account } | undefined;\n\t\tif (this.#signer !== undefined) {\n\t\t\tcontainerOptions = { signer: this.#signer };\n\t\t}\n\n\t\tconst container = EncryptedContainer.fromPlaintext(plaintext, principals, containerOptions);\n\t\tconst containerBuffer = arrayBufferToBuffer(await container.getEncodedBuffer());\n\t\tconst external = containerBuffer.toString('base64');\n\n\t\tif (this.#maxLength !== undefined && external.length > this.#maxLength) {\n\t\t\tthrow(new KeetaAnchorError(`Encoded external length ${external.length} exceeds caller maxLength ${this.#maxLength}`));\n\t\t}\n\n\t\treturn(external);\n\t}\n}\n\n// #endregion\n\n// #region Signed external helper\n\n/**\n * Inputs to {@link buildSignedAnchorExternal}.\n */\nexport type AnchorPayoutExternalOptions = {\n\t/**\n\t * Anchor signing account; also the envelope's anchor entry key.\n\t */\n\tanchor: Account;\n\t/**\n\t * Service-scoped transfer/transaction id to correlate.\n\t */\n\ttransactionID: string;\n\t/**\n\t * On-chain operations feeding this payout in relevance order.\n\t */\n\tinputs?: AnchorExternalInput[];\n\t/**\n\t * Binding coordinates of the block about to be published.\n\t */\n\tbinding: AnchorExternalBinding;\n\t/**\n\t * Encrypt the envelope to these recipients.\n\t */\n\tencryptTo?: Account[];\n};\n\n/**\n * Build the signed, encoded SEND.external string an anchor attaches to a\n * payout (anchor-to-user) SEND.\n *\n * @throws {@link KeetaAnchorError} on caller misuse (invalid binding or inputs).\n */\nexport async function buildSignedAnchorExternal(options: AnchorPayoutExternalOptions): Promise<string> {\n\tconst builder = new AnchorExternalBuilder();\n\tbuilder.setAnchor(options.anchor, { transactionId: options.transactionID });\n\tbuilder.withSigner(options.anchor);\n\tbuilder.withBinding(options.binding.previousBlockHash, options.binding.operationIndex);\n\n\tfor (const input of options.inputs ?? []) {\n\t\tbuilder.addInput(input.blockHash, input.operationIndex);\n\t}\n\n\tif (options.encryptTo !== undefined) {\n\t\tbuilder.withPrincipals(options.encryptTo);\n\t}\n\n\tconst external = await builder.build();\n\treturn(external);\n}\n\n// #endregion\n\n// #region AnchorExternal\n\n/**\n * Immutable, verified view of a parsed SEND.external envelope.\n */\nexport class AnchorExternal {\n\tstatic readonly Builder: typeof AnchorExternalBuilder = AnchorExternalBuilder;\n\n\treadonly #envelope: AnchorExternalEnvelope;\n\treadonly #encrypted: boolean;\n\treadonly #signed: AnchorExternalSigned | undefined;\n\n\tprivate constructor(envelope: AnchorExternalEnvelope, encrypted: boolean, signed: AnchorExternalSigned | undefined) {\n\t\tthis.#envelope = envelope;\n\t\tthis.#encrypted = encrypted;\n\t\tthis.#signed = signed;\n\t}\n\n\t/**\n\t * Decoded envelope.\n\t */\n\tget envelope(): AnchorExternalEnvelope {\n\t\treturn(this.#envelope);\n\t}\n\n\t/**\n\t * `true` if the source blob was encrypted.\n\t */\n\tget encrypted(): boolean {\n\t\treturn(this.#encrypted);\n\t}\n\n\t/**\n\t * Authenticity record for a verified signed envelope, or `undefined`\n\t * if the envelope was not signed.\n\t */\n\tget signed(): AnchorExternalSigned | undefined {\n\t\treturn(this.#signed);\n\t}\n\n\t/**\n\t * Decode an external string asserted to be plaintext.\n\t *\n\t * @throws {@link AnchorExternalError} `EXPECTED_PLAIN` if the source blob is encrypted.\n\t */\n\tstatic async fromPlainExternal(external: string): Promise<AnchorExternal> {\n\t\tconst buffer = decodeExternal(external);\n\n\t\tlet container: EncryptedContainer;\n\t\ttry {\n\t\t\tcontainer = EncryptedContainer.fromEncodedBuffer(buffer, null);\n\t\t} catch (error) {\n\t\t\tif (EncryptedContainerError.isInstance(error)) {\n\t\t\t\tif (error.code === 'INVALID_PRINCIPALS') {\n\t\t\t\t\tthrow(new AnchorExternalError('EXPECTED_PLAIN', 'Blob is encrypted but plaintext was expected'));\n\t\t\t\t}\n\t\t\t\tthrow(new AnchorExternalError('NOT_AN_ENVELOPE', `Container parse failed: ${error.code}`));\n\t\t\t}\n\t\t\tthrow(error);\n\t\t}\n\n\t\tif (container.encrypted) {\n\t\t\tthrow(new AnchorExternalError('EXPECTED_PLAIN', 'Blob is encrypted but plaintext was expected'));\n\t\t}\n\n\t\tconst result = await AnchorExternal.fromContainer(container, false);\n\t\treturn(result);\n\t}\n\n\t/**\n\t * Decode an external string asserted to be encrypted under one of the\n\t * supplied principals.\n\t *\n\t * @throws {@link AnchorExternalError} `EXPECTED_ENCRYPTED` if the source blob is plaintext.\n\t * @throws {@link KeetaAnchorError} if `principals` is empty.\n\t */\n\tstatic async fromEncryptedExternal(external: string, principals: Account[]): Promise<AnchorExternal> {\n\t\tif (principals.length === 0) {\n\t\t\tthrow(new KeetaAnchorError('AnchorExternal.fromEncryptedExternal requires at least one principal'));\n\t\t}\n\n\t\tconst buffer = decodeExternal(external);\n\t\tlet container: EncryptedContainer;\n\t\ttry {\n\t\t\tcontainer = EncryptedContainer.fromEncryptedBuffer(buffer, principals);\n\t\t} catch (error) {\n\t\t\tif (EncryptedContainerError.isInstance(error)) {\n\t\t\t\tif (error.code === 'ENCRYPTION_REQUIRED') {\n\t\t\t\t\tthrow(new AnchorExternalError('EXPECTED_ENCRYPTED', 'Blob is plaintext but encrypted was expected'));\n\t\t\t\t}\n\n\t\t\t\tthrow(new AnchorExternalError('NOT_AN_ENVELOPE', `Container parse failed: ${error.code}`));\n\t\t\t}\n\n\t\t\tthrow(error);\n\t\t}\n\n\t\tif (!container.encrypted) {\n\t\t\tthrow(new AnchorExternalError('EXPECTED_ENCRYPTED', 'Blob is plaintext but encrypted was expected'));\n\t\t}\n\n\t\tconst result = await AnchorExternal.fromContainer(container, true);\n\t\treturn(result);\n\t}\n\n\t/**\n\t * Decode an external string, dispatching on whether the blob is encrypted.\n\t *\n\t * Encrypted blobs are decrypted with the supplied decryption keys.\n\t * Plaintext blobs ignore them.\n\t *\n\t * @throws {@link AnchorExternalError} on decode failure.\n\t */\n\tstatic async fromExternal(external: string, options?: { decryptionKeys?: Account[] }): Promise<AnchorExternal> {\n\t\tconst peeked = await AnchorExternal.peek(external);\n\t\tif (peeked.encrypted) {\n\t\t\tconst encryptedResult = await AnchorExternal.fromEncryptedExternal(external, options?.decryptionKeys ?? []);\n\t\t\treturn(encryptedResult);\n\t\t}\n\n\t\tconst plainResult = await AnchorExternal.fromPlainExternal(external);\n\t\treturn(plainResult);\n\t}\n\n\t/**\n\t * Inspect encrypted/signed flags of a candidate external string\n\t * without reading plaintext or requiring a decryption key.\n\t */\n\tstatic async peek(external: string): Promise<AnchorExternalPeekResult> {\n\t\tconst buffer = decodeExternal(external);\n\t\tlet container: EncryptedContainer;\n\t\ttry {\n\t\t\tcontainer = EncryptedContainer.fromEncodedBuffer(buffer, []);\n\t\t} catch (error) {\n\t\t\tif (EncryptedContainerError.isInstance(error)) {\n\t\t\t\tthrow(new AnchorExternalError('NOT_AN_ENVELOPE', `Container parse failed: ${error.code}`));\n\t\t\t}\n\n\t\t\tthrow(error);\n\t\t}\n\n\t\treturn({\n\t\t\tencrypted: container.encrypted,\n\t\t\tsigned: container.isSigned\n\t\t});\n\t}\n\n\t/**\n\t * Create an {@link AnchorExternal} from a container.\n\t */\n\tprivate static async fromContainer(container: EncryptedContainer, encrypted: boolean): Promise<AnchorExternal> {\n\t\tconst envelope = await AnchorExternal.readEnvelope(container);\n\t\tconst signed = await AnchorExternal.readSigned(container, envelope);\n\t\tconst result = new AnchorExternal(envelope, encrypted, signed);\n\t\treturn(result);\n\t}\n\n\t/**\n\t * Read the envelope from a container.\n\t */\n\tprivate static async readEnvelope(container: EncryptedContainer): Promise<AnchorExternalEnvelope> {\n\t\tlet plaintextArrayBuffer: ArrayBuffer;\n\t\ttry {\n\t\t\tplaintextArrayBuffer = await container.getPlaintext();\n\t\t} catch (error) {\n\t\t\tif (EncryptedContainerError.isInstance(error)) {\n\t\t\t\tthrow(new AnchorExternalError('NOT_AN_ENVELOPE', `Container plaintext unavailable: ${error.code}`));\n\t\t\t}\n\t\t\tthrow(error);\n\t\t}\n\n\t\tif (plaintextArrayBuffer.byteLength > MAX_PLAINTEXT_BYTES) {\n\t\t\tthrow(new AnchorExternalError('PLAINTEXT_TOO_LARGE', `Container plaintext exceeds ${MAX_PLAINTEXT_BYTES} bytes`));\n\t\t}\n\n\t\tconst plaintextBuffer = arrayBufferToBuffer(plaintextArrayBuffer);\n\t\tconst plaintextString = plaintextBuffer.toString('utf-8');\n\n\t\tlet parsed: unknown;\n\t\ttry {\n\t\t\tparsed = JSON.parse(plaintextString);\n\t\t} catch {\n\t\t\tthrow(new AnchorExternalError('NOT_AN_ENVELOPE', 'Container plaintext is not valid JSON'));\n\t\t}\n\n\t\tconst encoded = parseEncodedEnvelope(parsed);\n\n\t\t/*\n\t\t * Reject non-canonical encodings: an attacker could otherwise\n\t\t * mutate the JSON shape under a still-valid signature on the\n\t\t * original bytes.\n\t\t */\n\t\tconst reCanonical = canonicalizeJson(encoded);\n\t\tif (reCanonical !== plaintextString) {\n\t\t\tthrow(new AnchorExternalError('NON_CANONICAL', 'Container plaintext is not JCS-canonical'));\n\t\t}\n\n\t\tconst result = envelopeFromEncoded(encoded);\n\t\treturn(result);\n\t}\n\n\t/**\n\t * Read the signed record from a container.\n\t */\n\tprivate static async readSigned(container: EncryptedContainer, envelope: AnchorExternalEnvelope): Promise<AnchorExternalSigned | undefined> {\n\t\tif (!container.isSigned) {\n\t\t\tif (envelope.binding !== undefined) {\n\t\t\t\tthrow(new AnchorExternalError('UNEXPECTED_BINDING', 'Unsigned envelope carries a binding'));\n\t\t\t}\n\n\t\t\treturn(undefined);\n\t\t}\n\n\t\tif (envelope.binding === undefined) {\n\t\t\tthrow(new AnchorExternalError('MISSING_BINDING', 'Signed envelope is missing required binding'));\n\t\t}\n\n\t\tlet valid: boolean;\n\t\ttry {\n\t\t\tvalid = await container.verifySignature();\n\t\t} catch (error) {\n\t\t\tif (EncryptedContainerError.isInstance(error)) {\n\t\t\t\tthrow(new AnchorExternalError('BAD_SIGNATURE', `Signature verification failed: ${error.code}`));\n\t\t\t}\n\n\t\t\tthrow(error);\n\t\t}\n\n\t\tif (!valid) {\n\t\t\tthrow(new AnchorExternalError('BAD_SIGNATURE', 'Signature did not verify against the contained plaintext'));\n\t\t}\n\n\t\tconst signer = container.getSigningAccount();\n\t\tif (signer === undefined) {\n\t\t\tthrow(new AnchorExternalError('BAD_SIGNATURE', 'Container is signed but the signing account is unavailable'));\n\t\t}\n\n\t\tif (!signerListed(envelope, signer)) {\n\t\t\tthrow(new AnchorExternalError('SIGNER_NOT_LISTED', 'Signing account is not listed in envelope.anchors'));\n\t\t}\n\n\t\treturn({ signer });\n\t}\n}\n\n// #endregion\n"]}
|
|
@@ -1,8 +1,9 @@
|
|
|
1
|
-
import type { KeetaAnchorHTTPServerConfig } from './http-server/index.js';
|
|
2
|
-
import type
|
|
1
|
+
import type { KeetaAnchorHTTPServerConfig, Routes } from './http-server/index.js';
|
|
2
|
+
import { type HTTPSignedField } from './http-server/common.js';
|
|
3
3
|
import type { SignableAccount, VerifiableAccount } from './utils/signing.js';
|
|
4
4
|
import type { ServiceMetadataEndpoint, SharedAnchorMetadataLegalExtension, SharedAnchorMetadataSignedExtension } from './metadata.types.js';
|
|
5
5
|
import { KeetaNetAnchorHTTPServer } from './http-server/index.js';
|
|
6
|
+
import type { Account, GenericAccount } from '@keetanetwork/keetanet-client/lib/account.js';
|
|
6
7
|
/**
|
|
7
8
|
* Namespace tag bound into every service metadata signature.
|
|
8
9
|
*/
|
|
@@ -29,6 +30,17 @@ export type SignedServiceMetadataFields = {
|
|
|
29
30
|
export interface KeetaAnchorMetadataServerConfig extends KeetaAnchorHTTPServerConfig {
|
|
30
31
|
/** Signs the published metadata. Omit for unsigned metadata. */
|
|
31
32
|
metadataSigner?: SignableAccount | undefined;
|
|
33
|
+
serviceMetadataEndpoint?: {
|
|
34
|
+
expose: false;
|
|
35
|
+
} | {
|
|
36
|
+
expose: true;
|
|
37
|
+
authentication?: {
|
|
38
|
+
required: false;
|
|
39
|
+
} | {
|
|
40
|
+
required: true;
|
|
41
|
+
allowAccount: InstanceType<typeof Account.Set> | ((account: GenericAccount) => Promise<boolean>);
|
|
42
|
+
};
|
|
43
|
+
};
|
|
32
44
|
}
|
|
33
45
|
/**
|
|
34
46
|
* Extracts the subset of `metadata` that is covered by the signature.
|
|
@@ -48,6 +60,7 @@ export declare abstract class KeetaAnchorMetadataServer<Built extends SignableSe
|
|
|
48
60
|
#private;
|
|
49
61
|
constructor(config: C);
|
|
50
62
|
get metadataSigner(): SignableAccount | undefined;
|
|
63
|
+
protected initRoutes(config: C): Promise<Routes>;
|
|
51
64
|
protected abstract buildServiceMetadata(): Promise<Built>;
|
|
52
65
|
serviceMetadata(): Promise<Built & SharedAnchorMetadataSignedExtension>;
|
|
53
66
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"anchor-metadata-server.d.ts","sourceRoot":"","sources":["../../src/lib/anchor-metadata-server.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,2BAA2B,EAAE,MAAM,wBAAwB,CAAC;
|
|
1
|
+
{"version":3,"file":"anchor-metadata-server.d.ts","sourceRoot":"","sources":["../../src/lib/anchor-metadata-server.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,2BAA2B,EAAE,MAAM,EAAE,MAAM,wBAAwB,CAAC;AAClF,OAAO,EAAyB,KAAK,eAAe,EAAE,MAAM,yBAAyB,CAAC;AACtF,OAAO,KAAK,EAAE,eAAe,EAAE,iBAAiB,EAAE,MAAM,oBAAoB,CAAC;AAC7E,OAAO,KAAK,EAAE,uBAAuB,EAAE,kCAAkC,EAAE,mCAAmC,EAAE,MAAM,qBAAqB,CAAC;AAC5I,OAAO,EAAE,wBAAwB,EAAE,MAAM,wBAAwB,CAAC;AAElE,OAAO,KAAK,EAAE,OAAO,EAAE,cAAc,EAAE,MAAM,8CAA8C,CAAC;AAK5F;;GAEG;AACH,eAAO,MAAM,4BAA4B,wCAAwC,CAAC;AAElF;;;GAGG;AACH,MAAM,MAAM,uBAAuB,GAAG,kCAAkC,GAAG;IAC1E,UAAU,EAAE;QAAE,CAAC,aAAa,EAAE,MAAM,GAAG,uBAAuB,GAAG,SAAS,CAAA;KAAE,CAAC;CAC7E,CAAC;AAEF;;;GAGG;AACH,MAAM,MAAM,2BA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,QAAQ,CAAC,oBAAoB,IAAI,OAAO,CAAC,KAAK,CAAC;IAEnD,eAAe,IAAI,OAAO,CAAC,KAAK,GAAG,mCAAmC,CAAC;CAmB7E"}
|
|
@@ -1,5 +1,9 @@
|
|
|
1
|
+
import { parseSignatureFromURL } from './http-server/common.js';
|
|
1
2
|
import { KeetaNetAnchorHTTPServer } from './http-server/index.js';
|
|
2
3
|
import { SignData, VerifySignedData, objectToSignable } from './utils/signing.js';
|
|
4
|
+
import { KeetaAnchorUserValidationError } from './error.js';
|
|
5
|
+
import Resolver from './resolver.js';
|
|
6
|
+
import { KeetaNet } from '../client/index.js';
|
|
3
7
|
/**
|
|
4
8
|
* Namespace tag bound into every service metadata signature.
|
|
5
9
|
*/
|
|
@@ -42,6 +46,56 @@ export class KeetaAnchorMetadataServer extends KeetaNetAnchorHTTPServer {
|
|
|
42
46
|
get metadataSigner() {
|
|
43
47
|
return (this.#metadataSigner);
|
|
44
48
|
}
|
|
49
|
+
async initRoutes(config) {
|
|
50
|
+
const routes = {};
|
|
51
|
+
if (config.serviceMetadataEndpoint?.expose) {
|
|
52
|
+
const endpointConfig = config.serviceMetadataEndpoint;
|
|
53
|
+
routes['GET /serviceMetadata'] = {
|
|
54
|
+
bodyType: 'none',
|
|
55
|
+
handler: async (_ignore_params, _ignore_data, _ignore_headers, url) => {
|
|
56
|
+
if (endpointConfig.authentication?.required) {
|
|
57
|
+
const signature = parseSignatureFromURL(url);
|
|
58
|
+
try {
|
|
59
|
+
if (!signature.account || !signature.signedField) {
|
|
60
|
+
throw (new KeetaAnchorUserValidationError({ fields: [] }, 'Missing signature fields in request URL'));
|
|
61
|
+
}
|
|
62
|
+
const signable = Resolver.getExternalURLSignable(url);
|
|
63
|
+
const verified = await VerifySignedData(signature.account, signable, signature.signedField);
|
|
64
|
+
if (!verified) {
|
|
65
|
+
throw (new KeetaAnchorUserValidationError({ fields: [] }, 'Invalid signature in request URL'));
|
|
66
|
+
}
|
|
67
|
+
let allowAccount = false;
|
|
68
|
+
if (typeof endpointConfig.authentication.allowAccount === 'function') {
|
|
69
|
+
allowAccount = await endpointConfig.authentication.allowAccount(signature.account);
|
|
70
|
+
}
|
|
71
|
+
else {
|
|
72
|
+
allowAccount = endpointConfig.authentication.allowAccount.has(signature.account);
|
|
73
|
+
}
|
|
74
|
+
if (!allowAccount) {
|
|
75
|
+
throw (new KeetaAnchorUserValidationError({ fields: [] }, 'Account not allowed to access this endpoint'));
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
catch (error) {
|
|
79
|
+
this.logger?.debug('KeetaAnchorMetadataServer: serviceMetadata endpoint authentication failed:', error);
|
|
80
|
+
return ({
|
|
81
|
+
statusCode: 404,
|
|
82
|
+
headers: { 'Content-Type': 'text/plain' },
|
|
83
|
+
output: 'Not Found'
|
|
84
|
+
});
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
const serviceMetadata = await this.serviceMetadata();
|
|
88
|
+
const serializable = KeetaNet.lib.Utils.Conversion.toJSONSerializable(serviceMetadata);
|
|
89
|
+
return ({
|
|
90
|
+
output: JSON.stringify(serializable),
|
|
91
|
+
headers: { 'Content-Type': 'application/json' },
|
|
92
|
+
statusCode: 200
|
|
93
|
+
});
|
|
94
|
+
}
|
|
95
|
+
};
|
|
96
|
+
}
|
|
97
|
+
return (routes);
|
|
98
|
+
}
|
|
45
99
|
async serviceMetadata() {
|
|
46
100
|
const built = await this.buildServiceMetadata();
|
|
47
101
|
const signer = this.#metadataSigner;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"anchor-metadata-server.js","sourceRoot":"","sources":["../../src/lib/anchor-metadata-server.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,wBAAwB,EAAE,MAAM,wBAAwB,CAAC;AAClE,OAAO,EAAE,QAAQ,EAAE,gBAAgB,EAAE,gBAAgB,EAAE,MAAM,oBAAoB,CAAC;AAElF;;GAEG;AACH,MAAM,CAAC,MAAM,4BAA4B,GAAG,qCAAqC,CA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,KAAK,SAAS,EAAE,CAAC;YAC1B,OAAM,CAAC,KAAK,CAAC,CAAC;QACf,CAAC;QAED,MAAM,OAAO,GAAG,MAAM,CAAC,eAAe,CAAC,GAAG,EAAE,CAAC;QAC7C,MAAM,YAAY,GAAG,mBAAmB,CAAC,OAAO,EAAE,KAAK,CAAC,CAAC;QACzD,MAAM,QAAQ,GAAG,gBAAgB,CAAC,YAAY,CAAC,CAAC;QAChD,MAAM,MAAM,GAAG,MAAM,QAAQ,CAAC,MAAM,EAAE,QAAQ,CAAC,CAAC;QAEhD,OAAM,CAAC;YACN,GAAG,KAAK;YACR,OAAO;YACP,MAAM;SACN,CAAC,CAAC;IACJ,CAAC;CACD","sourcesContent":["import type { KeetaAnchorHTTPServerConfig } from './http-server/index.js';\nimport type { HTTPSignedField } from './http-server/common.js';\nimport type { SignableAccount, VerifiableAccount } from './utils/signing.js';\nimport type { ServiceMetadataEndpoint, SharedAnchorMetadataLegalExtension, SharedAnchorMetadataSignedExtension } from './metadata.types.js';\nimport { KeetaNetAnchorHTTPServer } from './http-server/index.js';\nimport { SignData, VerifySignedData, objectToSignable } from './utils/signing.js';\n\n/**\n * Namespace tag bound into every service metadata signature.\n */\nexport const METADATA_SIGNATURE_NAMESPACE = 'keetanet/anchor/service-metadata/v1';\n\n/**\n * Service metadata shape whose signed fields can be authenticated\n * by {@link KeetaAnchorMetadataServer}.\n */\nexport type SignableServiceMetadata = SharedAnchorMetadataLegalExtension & {\n\toperations: { [operationName: string]: ServiceMetadataEndpoint | undefined };\n};\n\n/**\n * Canonical fields covered by the metadata signature. `namespace` scopes\n * the signature to this protocol/version.\n */\nexport type SignedServiceMetadataFields = {\n\tnamespace: typeof METADATA_SIGNATURE_NAMESPACE;\n\taccount: string;\n\toperations: SignableServiceMetadata['operations'];\n\tlegal?: SignableServiceMetadata['legal'];\n};\n\nexport interface KeetaAnchorMetadataServerConfig extends KeetaAnchorHTTPServerConfig {\n\t/** Signs the published metadata. Omit for unsigned metadata. */\n\tmetadataSigner?: SignableAccount | undefined;\n}\n\n/**\n * Extracts the subset of `metadata` that is covered by the signature.\n * `account` is the public-key string of the claimed signer.\n */\nexport function extractSignedFields(account: string, metadata: SignableServiceMetadata): SignedServiceMetadataFields {\n\tconst fields: SignedServiceMetadataFields = {\n\t\tnamespace: METADATA_SIGNATURE_NAMESPACE,\n\t\taccount: account,\n\t\toperations: metadata.operations\n\t};\n\tif (metadata.legal !== undefined) {\n\t\tfields.legal = metadata.legal;\n\t}\n\n\treturn(fields);\n}\n\n/**\n * Verifies that `signed` was produced by `account` over the signed\n * fields of `metadata` (see {@link extractSignedFields}).\n */\nexport async function verifyMetadataSignature(account: VerifiableAccount, metadata: SignableServiceMetadata, signed: HTTPSignedField): Promise<boolean> {\n\tconst signedFields = extractSignedFields(account.publicKeyString.get(), metadata);\n\tconst signable = objectToSignable(signedFields);\n\tconst verifyOptions = { maxSkewMs: Number.POSITIVE_INFINITY };\n\n\treturn(await VerifySignedData(account, signable, signed, verifyOptions));\n}\n\n/**\n * Publishes anchor service metadata, optionally signed by `metadataSigner`.\n * Subclasses implement {@link buildServiceMetadata}.\n */\nexport abstract class KeetaAnchorMetadataServer<\n\tBuilt extends SignableServiceMetadata,\n\tC extends KeetaAnchorMetadataServerConfig = KeetaAnchorMetadataServerConfig\n> extends KeetaNetAnchorHTTPServer<C> {\n\treadonly #metadataSigner: SignableAccount | undefined;\n\n\tconstructor(config: C) {\n\t\tsuper(config);\n\t\tthis.#metadataSigner = config.metadataSigner;\n\t}\n\n\tget metadataSigner(): SignableAccount | undefined {\n\t\treturn(this.#metadataSigner);\n\t}\n\n\tprotected abstract buildServiceMetadata(): Promise<Built>;\n\n\tasync serviceMetadata(): Promise<Built & SharedAnchorMetadataSignedExtension> {\n\t\tconst built = await this.buildServiceMetadata();\n\n\t\tconst signer = this.#metadataSigner;\n\t\tif (signer === undefined) {\n\t\t\treturn(built);\n\t\t}\n\n\t\tconst account = signer.publicKeyString.get();\n\t\tconst signedFields = extractSignedFields(account, built);\n\t\tconst signable = objectToSignable(signedFields);\n\t\tconst signed = await SignData(signer, signable);\n\n\t\treturn({\n\t\t\t...built,\n\t\t\taccount,\n\t\t\tsigned\n\t\t});\n\t}\n}\n"]}
|
|
1
|
+
{"version":3,"file":"anchor-metadata-server.js","sourceRoot":"","sources":["../../src/lib/anchor-metadata-server.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,qBAAqB,EAAwB,MAAM,yBAAyB,CAAC;AAGtF,OAAO,EAAE,wBAAwB,EAAE,MAAM,wBAAwB,CAAC;AAClE,OAAO,EAAE,QAAQ,EAAE,gBAAgB,EAAE,gBAAgB,EAAE,MAAM,oBAAoB,CAAC;AAElF,OAAO,EAAE,8BAA8B,EAAE,MAAM,YAAY,CAAC;AAC5D,OAAO,QAAQ,MAAM,eAAe,CAAC;AACrC,OAAO,EAAE,QAAQ,EAAE,MAAM,oBAAoB,CAAC;AAE9C;;GAEG;AACH,MAAM,CAAC,MAAM,4BAA4B,GAAG,qCAAqC,CAAC;AAuClF;;;GAGG;AACH,MAAM,UAAU,mBAAmB,CAAC,OAAe,EAAE,QAAiC;IACrF,MAAM,MAAM,GAAgC;QAC3C,SAAS,EAAE,4BAA4B;QACvC,OAAO,EAAE,OAAO;QAChB,UAAU,EAAE,QAAQ,CAAC,UAAU;KAC/B,CAAC;IACF,IAAI,QAAQ,CAAC,KAAK,KAAK,SAAS,EAAE,CAAC;QAClC,MAAM,CAAC,KAAK,GAAG,QAAQ,CAAC,KAAK,CAAC;IAC/B,CAAC;IAED,OAAM,CAAC,MAAM,CAAC,CAAC;AAChB,CAAC;AAED;;;GAGG;AACH,MAAM,CAAC,KAAK,UAAU,uBAAuB,CAAC,OAA0B,EAAE,QAAiC,EAAE,MAAuB;IACnI,MAAM,YAAY,GAAG,mBAAmB,CAAC,OAAO,CAAC,eAAe,CAAC,GAAG,EAAE,EAAE,QAAQ,CAAC,CAAC;IAClF,MAAM,QAAQ,GAAG,gBAAgB,CAAC,YAAY,CAA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,SAAS,CAAC,YAAY,CAAC;wBACpC,OAAO,EAAE,EAAE,cAAc,EAAE,kBAAkB,EAAE;wBAC/C,UAAU,EAAE,GAAG;qBACf,CAAC,CAAA;gBACH,CAAC;aACD,CAAA;QACF,CAAC;QAED,OAAM,CAAC,MAAM,CAAC,CAAC;IAChB,CAAC;IAID,KAAK,CAAC,eAAe;QACpB,MAAM,KAAK,GAAG,MAAM,IAAI,CAAC,oBAAoB,EAAE,CAAC;QAEhD,MAAM,MAAM,GAAG,IAAI,CAAC,eAAe,CAAC;QACpC,IAAI,MAAM,KAAK,SAAS,EAAE,CAAC;YAC1B,OAAM,CAAC,KAAK,CAAC,CAAC;QACf,CAAC;QAED,MAAM,OAAO,GAAG,MAAM,CAAC,eAAe,CAAC,GAAG,EAAE,CAAC;QAC7C,MAAM,YAAY,GAAG,mBAAmB,CAAC,OAAO,EAAE,KAAK,CAAC,CAAC;QACzD,MAAM,QAAQ,GAAG,gBAAgB,CAAC,YAAY,CAAC,CAAC;QAChD,MAAM,MAAM,GAAG,MAAM,QAAQ,CAAC,MAAM,EAAE,QAAQ,CAAC,CAAC;QAEhD,OAAM,CAAC;YACN,GAAG,KAAK;YACR,OAAO;YACP,MAAM;SACN,CAAC,CAAC;IACJ,CAAC;CACD","sourcesContent":["import type { KeetaAnchorHTTPServerConfig, Routes } from './http-server/index.js';\nimport { parseSignatureFromURL, type HTTPSignedField } from './http-server/common.js';\nimport type { SignableAccount, VerifiableAccount } from './utils/signing.js';\nimport type { ServiceMetadataEndpoint, SharedAnchorMetadataLegalExtension, SharedAnchorMetadataSignedExtension } from './metadata.types.js';\nimport { KeetaNetAnchorHTTPServer } from './http-server/index.js';\nimport { SignData, VerifySignedData, objectToSignable } from './utils/signing.js';\nimport type { Account, GenericAccount } from '@keetanetwork/keetanet-client/lib/account.js';\nimport { KeetaAnchorUserValidationError } from './error.js';\nimport Resolver from './resolver.js';\nimport { KeetaNet } from '../client/index.js';\n\n/**\n * Namespace tag bound into every service metadata signature.\n */\nexport const METADATA_SIGNATURE_NAMESPACE = 'keetanet/anchor/service-metadata/v1';\n\n/**\n * Service metadata shape whose signed fields can be authenticated\n * by {@link KeetaAnchorMetadataServer}.\n */\nexport type SignableServiceMetadata = SharedAnchorMetadataLegalExtension & {\n\toperations: { [operationName: string]: ServiceMetadataEndpoint | undefined };\n};\n\n/**\n * Canonical fields covered by the metadata signature. `namespace` scopes\n * the signature to this protocol/version.\n */\nexport type SignedServiceMetadataFields = {\n\tnamespace: typeof METADATA_SIGNATURE_NAMESPACE;\n\taccount: string;\n\toperations: SignableServiceMetadata['operations'];\n\tlegal?: SignableServiceMetadata['legal'];\n};\n\nexport interface KeetaAnchorMetadataServerConfig extends KeetaAnchorHTTPServerConfig {\n\t/** Signs the published metadata. Omit for unsigned metadata. */\n\tmetadataSigner?: SignableAccount | undefined;\n\n\tserviceMetadataEndpoint?: {\n\t\texpose: false;\n\t} | {\n\t\texpose: true;\n\n\t\tauthentication?: {\n\t\t\trequired: false;\n\t\t} | {\n\t\t\trequired: true;\n\t\t\tallowAccount: InstanceType<typeof Account.Set> | ((account: GenericAccount) => Promise<boolean>);\n\t\t}\n\t}\n}\n\n/**\n * Extracts the subset of `metadata` that is covered by the signature.\n * `account` is the public-key string of the claimed signer.\n */\nexport function extractSignedFields(account: string, metadata: SignableServiceMetadata): SignedServiceMetadataFields {\n\tconst fields: SignedServiceMetadataFields = {\n\t\tnamespace: METADATA_SIGNATURE_NAMESPACE,\n\t\taccount: account,\n\t\toperations: metadata.operations\n\t};\n\tif (metadata.legal !== undefined) {\n\t\tfields.legal = metadata.legal;\n\t}\n\n\treturn(fields);\n}\n\n/**\n * Verifies that `signed` was produced by `account` over the signed\n * fields of `metadata` (see {@link extractSignedFields}).\n */\nexport async function verifyMetadataSignature(account: VerifiableAccount, metadata: SignableServiceMetadata, signed: HTTPSignedField): Promise<boolean> {\n\tconst signedFields = extractSignedFields(account.publicKeyString.get(), metadata);\n\tconst signable = objectToSignable(signedFields);\n\tconst verifyOptions = { maxSkewMs: Number.POSITIVE_INFINITY };\n\n\treturn(await VerifySignedData(account, signable, signed, verifyOptions));\n}\n\n/**\n * Publishes anchor service metadata, optionally signed by `metadataSigner`.\n * Subclasses implement {@link buildServiceMetadata}.\n */\nexport abstract class KeetaAnchorMetadataServer<\n\tBuilt extends SignableServiceMetadata,\n\tC extends KeetaAnchorMetadataServerConfig = KeetaAnchorMetadataServerConfig\n> extends KeetaNetAnchorHTTPServer<C> {\n\treadonly #metadataSigner: SignableAccount | undefined;\n\n\tconstructor(config: C) {\n\t\tsuper(config);\n\t\tthis.#metadataSigner = config.metadataSigner;\n\t}\n\n\tget metadataSigner(): SignableAccount | undefined {\n\t\treturn(this.#metadataSigner);\n\t}\n\n\tprotected async initRoutes(config: C): Promise<Routes> {\n\t\tconst routes: Routes = {};\n\n\t\tif (config.serviceMetadataEndpoint?.expose) {\n\t\t\tconst endpointConfig = config.serviceMetadataEndpoint;\n\t\t\troutes['GET /serviceMetadata'] = {\n\t\t\t\tbodyType: 'none',\n\t\t\t\thandler: async (_ignore_params, _ignore_data, _ignore_headers, url: URL) => {\n\t\t\t\t\tif (endpointConfig.authentication?.required) {\n\t\t\t\t\t\tconst signature = parseSignatureFromURL(url);\n\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tif (!signature.account || !signature.signedField) {\n\t\t\t\t\t\t\t\tthrow(new KeetaAnchorUserValidationError({ fields: [] }, 'Missing signature fields in request URL'));\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tconst signable = Resolver.getExternalURLSignable(url);\n\t\t\t\t\t\t\tconst verified = await VerifySignedData(signature.account, signable, signature.signedField);\n\n\t\t\t\t\t\t\tif (!verified) {\n\t\t\t\t\t\t\t\tthrow(new KeetaAnchorUserValidationError({ fields: [] }, 'Invalid signature in request URL'));\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tlet allowAccount = false;\n\t\t\t\t\t\t\tif (typeof endpointConfig.authentication.allowAccount === 'function') {\n\t\t\t\t\t\t\t\tallowAccount = await endpointConfig.authentication.allowAccount(signature.account);\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\tallowAccount = endpointConfig.authentication.allowAccount.has(signature.account);\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tif (!allowAccount) {\n\t\t\t\t\t\t\t\tthrow(new KeetaAnchorUserValidationError({ fields: [] }, 'Account not allowed to access this endpoint'));\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\t\tthis.logger?.debug('KeetaAnchorMetadataServer: serviceMetadata endpoint authentication failed:', error);\n\n\t\t\t\t\t\t\treturn({\n\t\t\t\t\t\t\t\tstatusCode: 404,\n\t\t\t\t\t\t\t\theaders: { 'Content-Type': 'text/plain' },\n\t\t\t\t\t\t\t\toutput: 'Not Found'\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tconst serviceMetadata = await this.serviceMetadata();\n\t\t\t\t\tconst serializable = KeetaNet.lib.Utils.Conversion.toJSONSerializable(serviceMetadata);\n\n\t\t\t\t\treturn({\n\t\t\t\t\t\toutput: JSON.stringify(serializable),\n\t\t\t\t\t\theaders: { 'Content-Type': 'application/json' },\n\t\t\t\t\t\tstatusCode: 200\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn(routes);\n\t}\n\n\tprotected abstract buildServiceMetadata(): Promise<Built>;\n\n\tasync serviceMetadata(): Promise<Built & SharedAnchorMetadataSignedExtension> {\n\t\tconst built = await this.buildServiceMetadata();\n\n\t\tconst signer = this.#metadataSigner;\n\t\tif (signer === undefined) {\n\t\t\treturn(built);\n\t\t}\n\n\t\tconst account = signer.publicKeyString.get();\n\t\tconst signedFields = extractSignedFields(account, built);\n\t\tconst signable = objectToSignable(signedFields);\n\t\tconst signed = await SignData(signer, signable);\n\n\t\treturn({\n\t\t\t...built,\n\t\t\taccount,\n\t\t\tsigned\n\t\t});\n\t}\n}\n"]}
|
|
@@ -0,0 +1,149 @@
|
|
|
1
|
+
import type { AccountPublicKeyString } from '@keetanetwork/keetanet-client/lib/account.js';
|
|
2
|
+
import type { KeetaNetAccount } from './asset.js';
|
|
3
|
+
import type { VerifiableAccount } from './utils/signing.js';
|
|
4
|
+
/**
|
|
5
|
+
* An anchor reference accepted when resolving a provider.
|
|
6
|
+
*/
|
|
7
|
+
export type AnchorReference = AccountPublicKeyString | VerifiableAccount;
|
|
8
|
+
/**
|
|
9
|
+
* Provider-independent, standardized view of an anchor transfer's status.
|
|
10
|
+
*/
|
|
11
|
+
export type StandardizedTransferStatus<Transaction = unknown> = {
|
|
12
|
+
/**
|
|
13
|
+
* Provider wire lifecycle state. Only `COMPLETE` is standardized.
|
|
14
|
+
*/
|
|
15
|
+
status: string;
|
|
16
|
+
/**
|
|
17
|
+
* Anchor-scoped transaction id the status was read for.
|
|
18
|
+
*/
|
|
19
|
+
transactionID: string;
|
|
20
|
+
/**
|
|
21
|
+
* Full source transaction record backing the status.
|
|
22
|
+
*/
|
|
23
|
+
transaction: Transaction;
|
|
24
|
+
};
|
|
25
|
+
/**
|
|
26
|
+
* Per-call options for {@link AnchorTransactionStatus.getStatus}.
|
|
27
|
+
*/
|
|
28
|
+
export type AnchorGetTransactionStatusOptions = {
|
|
29
|
+
/**
|
|
30
|
+
* Account to authenticate the status request with, for anchors that
|
|
31
|
+
* require (or scope) authentication on status reads.
|
|
32
|
+
*/
|
|
33
|
+
requesterAccount?: KeetaNetAccount;
|
|
34
|
+
};
|
|
35
|
+
/**
|
|
36
|
+
* Per-call options for {@link AnchorTransactionStatus.getStatusesFromExternal}.
|
|
37
|
+
*/
|
|
38
|
+
export type AnchorExternalTransactionStatusOptions = AnchorGetTransactionStatusOptions & {
|
|
39
|
+
/**
|
|
40
|
+
* Accounts whose keys may decrypt an encrypted envelope.
|
|
41
|
+
*/
|
|
42
|
+
decryptionKeys?: VerifiableAccount[];
|
|
43
|
+
};
|
|
44
|
+
/**
|
|
45
|
+
* Per-anchor outcome from {@link AnchorTransactionStatus.getStatusesFromExternal}.
|
|
46
|
+
*/
|
|
47
|
+
export type AnchorTransactionStatusResult<Transaction = unknown> = {
|
|
48
|
+
/**
|
|
49
|
+
* A status was read for the anchor.
|
|
50
|
+
*/
|
|
51
|
+
kind: 'status';
|
|
52
|
+
status: StandardizedTransferStatus<Transaction>;
|
|
53
|
+
} | {
|
|
54
|
+
/**
|
|
55
|
+
* Entry carries no transaction id (opaque, persistent-forwarding,
|
|
56
|
+
* or destination), so no transfer status applies.
|
|
57
|
+
*/
|
|
58
|
+
kind: 'unavailable';
|
|
59
|
+
} | {
|
|
60
|
+
/**
|
|
61
|
+
* The anchor's provider could not be resolved.
|
|
62
|
+
*/
|
|
63
|
+
kind: 'unresolved';
|
|
64
|
+
} | {
|
|
65
|
+
/**
|
|
66
|
+
* Reading the status failed; the captured error is provided.
|
|
67
|
+
*/
|
|
68
|
+
kind: 'error';
|
|
69
|
+
error: unknown;
|
|
70
|
+
};
|
|
71
|
+
/**
|
|
72
|
+
* On-chain coordinates of a Keeta operation, used to reverse-lookup the
|
|
73
|
+
* anchor transfer it belongs to when the operation carries no decodable
|
|
74
|
+
* transaction id (e.g. a deposit mint observed as a RECEIVE).
|
|
75
|
+
*/
|
|
76
|
+
export type AnchorOnChainReference = {
|
|
77
|
+
/**
|
|
78
|
+
* Network id of the Keeta chain the operation was observed on.
|
|
79
|
+
*/
|
|
80
|
+
keetaNetworkID: bigint;
|
|
81
|
+
/**
|
|
82
|
+
* Hash of the block carrying the operation.
|
|
83
|
+
*/
|
|
84
|
+
blockHash: string;
|
|
85
|
+
/**
|
|
86
|
+
* Index of the operation within its block.
|
|
87
|
+
*/
|
|
88
|
+
operationIndex: number;
|
|
89
|
+
};
|
|
90
|
+
/**
|
|
91
|
+
* Reads the status of a single transaction at one resolved anchor.
|
|
92
|
+
*/
|
|
93
|
+
export interface AnchorTransferReader<Transaction = unknown> {
|
|
94
|
+
/**
|
|
95
|
+
* Read the standardized status of one transaction at this anchor.
|
|
96
|
+
*/
|
|
97
|
+
getTransferStatus(transactionID: string, options?: AnchorGetTransactionStatusOptions): Promise<StandardizedTransferStatus<Transaction>>;
|
|
98
|
+
/**
|
|
99
|
+
* Reverse-lookup the transfer an on-chain operation belongs to, for
|
|
100
|
+
* operations that carry no transaction id of their own.
|
|
101
|
+
*/
|
|
102
|
+
findByOnChain?(reference: AnchorOnChainReference, options?: AnchorGetTransactionStatusOptions): Promise<StandardizedTransferStatus<Transaction> | null>;
|
|
103
|
+
}
|
|
104
|
+
/**
|
|
105
|
+
* Resolves an anchor account to a transfer-status reader.
|
|
106
|
+
*/
|
|
107
|
+
export interface AnchorStatusSource<Transaction = unknown> {
|
|
108
|
+
/**
|
|
109
|
+
* Resolve the reader for an anchor account, or `null` if no provider
|
|
110
|
+
* serves it.
|
|
111
|
+
*/
|
|
112
|
+
getReader(anchor: AnchorReference): Promise<AnchorTransferReader<Transaction> | null>;
|
|
113
|
+
}
|
|
114
|
+
/**
|
|
115
|
+
* Is `true` once a transfer has settled.
|
|
116
|
+
*
|
|
117
|
+
* Other states are provider-specific and cannot be classified here.
|
|
118
|
+
*/
|
|
119
|
+
export declare function isCompletedTransferStatus(status: string): boolean;
|
|
120
|
+
/**
|
|
121
|
+
* Reads anchor transfer status through a single, provider-independent
|
|
122
|
+
* surface backed by an injected {@link AnchorStatusSource}.
|
|
123
|
+
*/
|
|
124
|
+
export declare class AnchorTransactionStatus<Transaction = unknown> {
|
|
125
|
+
#private;
|
|
126
|
+
constructor(source: AnchorStatusSource<Transaction>);
|
|
127
|
+
/**
|
|
128
|
+
* Resolve the transfer-status reader an anchor account is filed under.
|
|
129
|
+
*
|
|
130
|
+
* @returns The reader, or `null` if none resolves for the anchor.
|
|
131
|
+
*/
|
|
132
|
+
getReader(anchor: AnchorReference): Promise<AnchorTransferReader<Transaction> | null>;
|
|
133
|
+
/**
|
|
134
|
+
* Read the standardized status of a single anchor transaction.
|
|
135
|
+
*
|
|
136
|
+
* @returns The standardized status, or `null` if the anchor's provider
|
|
137
|
+
* could not be resolved.
|
|
138
|
+
*/
|
|
139
|
+
getStatus(anchor: AnchorReference, transactionID: string, options?: AnchorGetTransactionStatusOptions): Promise<StandardizedTransferStatus<Transaction> | null>;
|
|
140
|
+
/**
|
|
141
|
+
* Read the standardized status of every anchor referenced by an encoded
|
|
142
|
+
* external field.
|
|
143
|
+
*/
|
|
144
|
+
getStatusesFromExternal(external: string, options?: AnchorExternalTransactionStatusOptions): Promise<{
|
|
145
|
+
[anchorID: string]: AnchorTransactionStatusResult<Transaction>;
|
|
146
|
+
}>;
|
|
147
|
+
}
|
|
148
|
+
export default AnchorTransactionStatus;
|
|
149
|
+
//# sourceMappingURL=anchor-status.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"anchor-status.d.ts","sourceRoot":"","sources":["../../src/lib/anchor-status.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,sBAAsB,EAAE,MAAM,8CAA8C,CAAC;AAI3F,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,YAAY,CAAC;AAClD,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,oBAAoB,CAAC;AAE5D;;GAEG;AACH,MAAM,MAAM,eAAe,GAAG,sBAAsB,GAAG,iBAAiB,CAAC;AAEzE;;GAEG;AACH,MAAM,MAAM,0BAA0B,CAAC,WAAW,GAAG,OAAO,IAAI;IAC/D;;OAEG;IACH,MAAM,EAAE,MAAM,CAAC;IACf;;OAEG;IACH,aAAa,EAAE,MAAM,CAAC;IACtB;;OAEG;IACH,WAAW,EAAE,WAAW,CAAC;CACzB,CAAC;AAEF;;GAEG;AACH,MAAM,MAAM,iCAAiC,GAAG;IAC/C;;;OAGG;IACH,gBAAgB,CAAC,EAAE,eAAe,CAAC;CACnC,CAAC;AAEF;;GAEG;AACH,MAAM,MAAM,sCAAsC,GAAG,iCAAiC,GAAG;IACxF;;OAEG;I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AED;;;GAGG;AACH,qBAAa,uBAAuB,CAAC,WAAW,GAAG,OAAO;;gBAG7C,MAAM,EAAE,kBAAkB,CAAC,WAAW,CAAC;IAInD;;;;OAIG;IACG,SAAS,CAAC,MAAM,EAAE,eAAe,GAAG,OAAO,CAAC,oBAAoB,CAAC,WAAW,CAAC,GAAG,IAAI,CAAC;IAK3F;;;;;OAKG;IACG,SAAS,CAAC,MAAM,EAAE,eAAe,EAAE,aAAa,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,iCAAiC,GAAG,OAAO,CAAC,0BAA0B,CAAC,WAAW,CAAC,GAAG,IAAI,CAAC;IAUrK;;;OAGG;IACG,uBAAuB,CAAC,QAAQ,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,sCAAsC,GAAG,OAAO,CAAC;QAAE,CAAC,QAAQ,EAAE,MAAM,GAAG,6BAA6B,CAAC,WAAW,CAAC,CAAA;KAAE,CAAC;CAkD9K;AAED,eAAe,uBAAuB,CAAC"}
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
import { lib as KeetaNetLib } from '@keetanetwork/keetanet-client';
|
|
2
|
+
import { AnchorExternal } from './anchor-external.js';
|
|
3
|
+
/**
|
|
4
|
+
* Is `true` once a transfer has settled.
|
|
5
|
+
*
|
|
6
|
+
* Other states are provider-specific and cannot be classified here.
|
|
7
|
+
*/
|
|
8
|
+
export function isCompletedTransferStatus(status) {
|
|
9
|
+
return (status === 'COMPLETE');
|
|
10
|
+
}
|
|
11
|
+
/**
|
|
12
|
+
* Reads anchor transfer status through a single, provider-independent
|
|
13
|
+
* surface backed by an injected {@link AnchorStatusSource}.
|
|
14
|
+
*/
|
|
15
|
+
export class AnchorTransactionStatus {
|
|
16
|
+
#source;
|
|
17
|
+
constructor(source) {
|
|
18
|
+
this.#source = source;
|
|
19
|
+
}
|
|
20
|
+
/**
|
|
21
|
+
* Resolve the transfer-status reader an anchor account is filed under.
|
|
22
|
+
*
|
|
23
|
+
* @returns The reader, or `null` if none resolves for the anchor.
|
|
24
|
+
*/
|
|
25
|
+
async getReader(anchor) {
|
|
26
|
+
const reader = await this.#source.getReader(anchor);
|
|
27
|
+
return (reader);
|
|
28
|
+
}
|
|
29
|
+
/**
|
|
30
|
+
* Read the standardized status of a single anchor transaction.
|
|
31
|
+
*
|
|
32
|
+
* @returns The standardized status, or `null` if the anchor's provider
|
|
33
|
+
* could not be resolved.
|
|
34
|
+
*/
|
|
35
|
+
async getStatus(anchor, transactionID, options) {
|
|
36
|
+
const reader = await this.getReader(anchor);
|
|
37
|
+
if (reader === null) {
|
|
38
|
+
return (null);
|
|
39
|
+
}
|
|
40
|
+
const status = await reader.getTransferStatus(transactionID, options);
|
|
41
|
+
return (status);
|
|
42
|
+
}
|
|
43
|
+
/**
|
|
44
|
+
* Read the standardized status of every anchor referenced by an encoded
|
|
45
|
+
* external field.
|
|
46
|
+
*/
|
|
47
|
+
async getStatusesFromExternal(external, options) {
|
|
48
|
+
const statusOptions = {};
|
|
49
|
+
if (options?.requesterAccount !== undefined) {
|
|
50
|
+
statusOptions.requesterAccount = options.requesterAccount;
|
|
51
|
+
}
|
|
52
|
+
const decodeOptions = {};
|
|
53
|
+
if (options?.decryptionKeys !== undefined) {
|
|
54
|
+
decodeOptions.decryptionKeys = options.decryptionKeys;
|
|
55
|
+
}
|
|
56
|
+
const decoded = await AnchorExternal.fromExternal(external, decodeOptions);
|
|
57
|
+
const entries = Object.entries(decoded.envelope.anchors);
|
|
58
|
+
const settled = await Promise.all(entries.map(async ([anchorID, entry]) => {
|
|
59
|
+
let anchor;
|
|
60
|
+
try {
|
|
61
|
+
anchor = KeetaNetLib.Account.fromPublicKeyString(anchorID);
|
|
62
|
+
}
|
|
63
|
+
catch (error) {
|
|
64
|
+
return ([anchorID, { kind: 'error', error: error }]);
|
|
65
|
+
}
|
|
66
|
+
const result = await this.#readEntryStatus(anchor, entry, statusOptions);
|
|
67
|
+
return ([anchorID, result]);
|
|
68
|
+
}));
|
|
69
|
+
const results = Object.fromEntries(settled);
|
|
70
|
+
return (results);
|
|
71
|
+
}
|
|
72
|
+
/**
|
|
73
|
+
* Resolve a single decoded per-anchor entry to its outcome.
|
|
74
|
+
*/
|
|
75
|
+
async #readEntryStatus(anchor, entry, options) {
|
|
76
|
+
if (!('transactionId' in entry)) {
|
|
77
|
+
return ({ kind: 'unavailable' });
|
|
78
|
+
}
|
|
79
|
+
let status;
|
|
80
|
+
try {
|
|
81
|
+
status = await this.getStatus(anchor, entry.transactionId, options);
|
|
82
|
+
}
|
|
83
|
+
catch (error) {
|
|
84
|
+
return ({ kind: 'error', error: error });
|
|
85
|
+
}
|
|
86
|
+
if (status === null) {
|
|
87
|
+
return ({ kind: 'unresolved' });
|
|
88
|
+
}
|
|
89
|
+
return ({ kind: 'status', status: status });
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
export default AnchorTransactionStatus;
|
|
93
|
+
//# sourceMappingURL=anchor-status.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"anchor-status.js","sourceRoot":"","sources":["../../src/lib/anchor-status.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,IAAI,WAAW,EAAE,MAAM,+BAA+B,CAAC;AAGnE,OAAO,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAC;AA+HtD;;;;GAIG;AACH,MAAM,UAAU,yBAAyB,CAAC,MAAc;IACvD,OAAM,CAAC,MAAM,KAAK,UAAU,CAAC,CAAC;AAC/B,CAAC;AAED;;;GAGG;AACH,MAAM,OAAO,uBAAuB;IAC1B,OAAO,CAAkC;IAElD,YAAY,MAAuC;QAClD,IAAI,CAAC,OAAO,GAAG,MAAM,CAAC;IACvB,CAAC;IAED;;;;OAIG;IACH,KAAK,CAAC,SAAS,CAAC,MAAuB;QACtC,MAAM,MAAM,GAAG,MAAM,IAAI,CAAC,OAAO,CAAC,SAAS,CAAC,MAAM,CAAC,CAAC;QACpD,OAAM,CAAC,MAAM,CAAC,CAAC;IAChB,CAAC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ccountPublicKeyString } from '@keetanetwork/keetanet-client/lib/account.js';\n\nimport { AnchorExternal } from './anchor-external.js';\nimport type { AnchorExternalEntry } from './anchor-external.js';\nimport type { KeetaNetAccount } from './asset.js';\nimport type { VerifiableAccount } from './utils/signing.js';\n\n/**\n * An anchor reference accepted when resolving a provider.\n */\nexport type AnchorReference = AccountPublicKeyString | VerifiableAccount;\n\n/**\n * Provider-independent, standardized view of an anchor transfer's status.\n */\nexport type StandardizedTransferStatus<Transaction = unknown> = {\n\t/**\n\t * Provider wire lifecycle state. Only `COMPLETE` is standardized.\n\t */\n\tstatus: string;\n\t/**\n\t * Anchor-scoped transaction id the status was read for.\n\t */\n\ttransactionID: string;\n\t/**\n\t * Full source transaction record backing the status.\n\t */\n\ttransaction: Transaction;\n};\n\n/**\n * Per-call options for {@link AnchorTransactionStatus.getStatus}.\n */\nexport type AnchorGetTransactionStatusOptions = {\n\t/**\n\t * Account to authenticate the status request with, for anchors that\n\t * require (or scope) authentication on status reads.\n\t */\n\trequesterAccount?: KeetaNetAccount;\n};\n\n/**\n * Per-call options for {@link AnchorTransactionStatus.getStatusesFromExternal}.\n */\nexport type AnchorExternalTransactionStatusOptions = AnchorGetTransactionStatusOptions & {\n\t/**\n\t * Accounts whose keys may decrypt an encrypted envelope.\n\t */\n\tdecryptionKeys?: VerifiableAccount[];\n};\n\n/**\n * Per-anchor outcome from {@link AnchorTransactionStatus.getStatusesFromExternal}.\n */\nexport type AnchorTransactionStatusResult<Transaction = unknown> =\n\t| {\n\t\t/**\n\t\t * A status was read for the anchor.\n\t\t */\n\t\tkind: 'status';\n\t\tstatus: StandardizedTransferStatus<Transaction>;\n\t}\n\t| {\n\t\t/**\n\t\t * Entry carries no transaction id (opaque, persistent-forwarding,\n\t\t * or destination), so no transfer status applies.\n\t\t */\n\t\tkind: 'unavailable';\n\t}\n\t| {\n\t\t/**\n\t\t * The anchor's provider could not be resolved.\n\t\t */\n\t\tkind: 'unresolved';\n\t}\n\t| {\n\t\t/**\n\t\t * Reading the status failed; the captured error is provided.\n\t\t */\n\t\tkind: 'error';\n\t\terror: unknown;\n\t};\n\n/**\n * On-chain coordinates of a Keeta operation, used to reverse-lookup the\n * anchor transfer it belongs to when the operation carries no decodable\n * transaction id (e.g. a deposit mint observed as a RECEIVE).\n */\nexport type AnchorOnChainReference = {\n\t/**\n\t * Network id of the Keeta chain the operation was observed on.\n\t */\n\tkeetaNetworkID: bigint;\n\t/**\n\t * Hash of the block carrying the operation.\n\t */\n\tblockHash: string;\n\t/**\n\t * Index of the operation within its block.\n\t */\n\toperationIndex: number;\n};\n\n/**\n * Reads the status of a single transaction at one resolved anchor.\n */\nexport interface AnchorTransferReader<Transaction = unknown> {\n\t/**\n\t * Read the standardized status of one transaction at this anchor.\n\t */\n\tgetTransferStatus(transactionID: string, options?: AnchorGetTransactionStatusOptions): Promise<StandardizedTransferStatus<Transaction>>;\n\t/**\n\t * Reverse-lookup the transfer an on-chain operation belongs to, for\n\t * operations that carry no transaction id of their own.\n\t */\n\tfindByOnChain?(reference: AnchorOnChainReference, options?: AnchorGetTransactionStatusOptions): Promise<StandardizedTransferStatus<Transaction> | null>;\n}\n\n/**\n * Resolves an anchor account to a transfer-status reader.\n */\nexport interface AnchorStatusSource<Transaction = unknown> {\n\t/**\n\t * Resolve the reader for an anchor account, or `null` if no provider\n\t * serves it.\n\t */\n\tgetReader(anchor: AnchorReference): Promise<AnchorTransferReader<Transaction> | null>;\n}\n\n/**\n * Is `true` once a transfer has settled.\n *\n * Other states are provider-specific and cannot be classified here.\n */\nexport function isCompletedTransferStatus(status: string): boolean {\n\treturn(status === 'COMPLETE');\n}\n\n/**\n * Reads anchor transfer status through a single, provider-independent\n * surface backed by an injected {@link AnchorStatusSource}.\n */\nexport class AnchorTransactionStatus<Transaction = unknown> {\n\treadonly #source: AnchorStatusSource<Transaction>;\n\n\tconstructor(source: AnchorStatusSource<Transaction>) {\n\t\tthis.#source = source;\n\t}\n\n\t/**\n\t * Resolve the transfer-status reader an anchor account is filed under.\n\t *\n\t * @returns The reader, or `null` if none resolves for the anchor.\n\t */\n\tasync getReader(anchor: AnchorReference): Promise<AnchorTransferReader<Transaction> | null> {\n\t\tconst reader = await this.#source.getReader(anchor);\n\t\treturn(reader);\n\t}\n\n\t/**\n\t * Read the standardized status of a single anchor transaction.\n\t *\n\t * @returns The standardized status, or `null` if the anchor's provider\n\t * could not be resolved.\n\t */\n\tasync getStatus(anchor: AnchorReference, transactionID: string, options?: AnchorGetTransactionStatusOptions): Promise<StandardizedTransferStatus<Transaction> | null> {\n\t\tconst reader = await this.getReader(anchor);\n\t\tif (reader === null) {\n\t\t\treturn(null);\n\t\t}\n\n\t\tconst status = await reader.getTransferStatus(transactionID, options);\n\t\treturn(status);\n\t}\n\n\t/**\n\t * Read the standardized status of every anchor referenced by an encoded\n\t * external field.\n\t */\n\tasync getStatusesFromExternal(external: string, options?: AnchorExternalTransactionStatusOptions): Promise<{ [anchorID: string]: AnchorTransactionStatusResult<Transaction> }> {\n\t\tconst statusOptions: AnchorGetTransactionStatusOptions = {};\n\t\tif (options?.requesterAccount !== undefined) {\n\t\t\tstatusOptions.requesterAccount = options.requesterAccount;\n\t\t}\n\n\t\tconst decodeOptions: { decryptionKeys?: VerifiableAccount[] } = {};\n\t\tif (options?.decryptionKeys !== undefined) {\n\t\t\tdecodeOptions.decryptionKeys = options.decryptionKeys;\n\t\t}\n\n\t\tconst decoded = await AnchorExternal.fromExternal(external, decodeOptions);\n\t\tconst entries = Object.entries(decoded.envelope.anchors);\n\t\tconst settled = await Promise.all(entries.map(async ([anchorID, entry]): Promise<[string, AnchorTransactionStatusResult<Transaction>]> => {\n\t\t\tlet anchor: KeetaNetAccount;\n\t\t\ttry {\n\t\t\t\tanchor = KeetaNetLib.Account.fromPublicKeyString(anchorID);\n\t\t\t} catch (error) {\n\t\t\t\treturn([anchorID, { kind: 'error', error: error }]);\n\t\t\t}\n\n\t\t\tconst result = await this.#readEntryStatus(anchor, entry, statusOptions);\n\t\t\treturn([anchorID, result]);\n\t\t}));\n\n\t\tconst results = Object.fromEntries(settled);\n\t\treturn(results);\n\t}\n\n\t/**\n\t * Resolve a single decoded per-anchor entry to its outcome.\n\t */\n\tasync #readEntryStatus(anchor: KeetaNetAccount, entry: AnchorExternalEntry, options: AnchorGetTransactionStatusOptions): Promise<AnchorTransactionStatusResult<Transaction>> {\n\t\tif (!('transactionId' in entry)) {\n\t\t\treturn({ kind: 'unavailable' });\n\t\t}\n\n\t\tlet status: StandardizedTransferStatus<Transaction> | null;\n\t\ttry {\n\t\t\tstatus = await this.getStatus(anchor, entry.transactionId, options);\n\t\t} catch (error) {\n\t\t\treturn({ kind: 'error', error: error });\n\t\t}\n\n\t\tif (status === null) {\n\t\t\treturn({ kind: 'unresolved' });\n\t\t}\n\n\t\treturn({ kind: 'status', status: status });\n\t}\n}\n\nexport default AnchorTransactionStatus;\n"]}
|