From 5ad8d0886a78751fc82519c1bdb9ae4b3786908b Mon Sep 17 00:00:00 2001 From: Pavel Grigorenko Date: Tue, 27 Oct 2026 16:11:42 +0100 Subject: [PATCH] Own the library surface instead of shipping one by accident MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `src/lib/index.ts` was a blanket `export *` over all seven lib modules, wired into the `exports` map since the first commit. It published 43 names, internals among them: adding a symbol to any module widened the public API and renaming one broke consumers, neither producing a diff that looked like an API change. Importing anything also pulled in the aggregator client, so verification — which needs no gateway, no API key and no filesystem — could not be used without them. Two explicit entry points replace it. `@unicitylabs/proof-cli/verify` carries offline verification: 80 modules, no transport, no `node:` import. The package root adds stamping. Both list every name they export. Making the verification entry point independent of the gateway: - `TimestampClient.ts` keeps stamping; `describeToken`, `verificationFailure`, `verify` and the result types move to `TimestampVerification.ts`, which does not import `AggregatorClient`. - `loadTrustBase` moves to `src/config.ts` along with `INetworkSelection`, leaving `src/lib/` free of filesystem access. `resolveNetwork` takes a parsed `trustBase` instead of a path, and is now synchronous. `PublicApiTest` pins both export lists, asserts a deep import is refused, and walks each built module graph: no module in this package may import from `node:`, and nothing reachable from `/verify` may be the aggregator client or its transport. Each guard was confirmed to fail on the drift it exists to catch. The build now removes `lib/` before compiling, so the deleted barrel stops shipping from working trees that built before its removal. Narrowing drops names 0.2.0 exported: `TIMESTAMP_BURN_REASON`, `TIMESTAMP_RECIPIENT_ENCODED`, `createUnicityCertificateVerifier`, `errorMessage`, `NO_PAYLOAD_MESSAGE`, `DEFAULT_POLL_INTERVAL_MS`, `certifyMintTransaction`, `TrustBaseSource`, `ITrustBaseChoice` and `loadTrustBase`. All remain available inside the package. Refs #14 --- README.md | 41 +++++ package.json | 10 +- src/commands/inspect.ts | 2 +- src/commands/stamp.ts | 3 +- src/commands/verify.ts | 7 +- src/config.ts | 39 ++++- src/index.ts | 20 +++ src/lib/TimestampClient.ts | 161 +------------------ src/lib/TimestampVerification.ts | 163 +++++++++++++++++++ src/lib/index.ts | 7 - src/lib/networks.ts | 38 ++--- src/output.ts | 2 +- src/verify.ts | 26 +++ tests/unit/ConfigTest.ts | 16 ++ tests/unit/OutputTest.ts | 3 +- tests/unit/PublicApiTest.ts | 221 ++++++++++++++++++++++++++ tests/unit/lib/NetworksTest.ts | 22 +-- tests/unit/lib/TimestampClientTest.ts | 3 +- 18 files changed, 566 insertions(+), 218 deletions(-) create mode 100644 src/index.ts create mode 100644 src/lib/TimestampVerification.ts delete mode 100644 src/lib/index.ts create mode 100644 src/verify.ts create mode 100644 tests/unit/PublicApiTest.ts diff --git a/README.md b/README.md index 8cc6dbf..3125b50 100644 --- a/README.md +++ b/README.md @@ -187,6 +187,47 @@ unicity-proof stamp --file document.pdf --gateway http://localhost:3000 --allow- The testnet2 key above is the shared public demo key published in the [sphere-sdk README](https://github.com/unicity-sphere/sphere-sdk/blob/main/README.md#api-key), where it is documented as public rather than secret; capacity is shared, so get your own key for sustained use. Trust bases for mainnet and testnet2 ship inside the package. The CLI never downloads a trust base at run time. +### Library + +The package is importable as well as runnable. Verification has its own entry +point that cannot reach a gateway: no aggregator client, no JSON-RPC transport, +and no `node:` import anywhere in its module graph — 80 modules against the 137 +behind the package root, and nothing that can open a socket or read a file, which +is what a browser bundle needs. + +```js +import { readFile } from 'node:fs/promises'; + +import { Token } from '@unicitylabs/state-transition-sdk/lib/transaction/Token.js'; +import { bundledTrustBase, networkNameForId, verify } from '@unicitylabs/proof-cli/verify'; + +const token = await Token.fromCBOR(new Uint8Array(await readFile('document.cbor'))); +const network = networkNameForId(token.networkId.id); +if (network === undefined) { + throw new Error(`No bundled trust base for network ${token.networkId.id}.`); +} + +// digest is the document's own SHA-256. Without it the result says only that +// some hash was certified, not that it was yours. +const result = await verify(token, bundledTrustBase(network), { expectedDigest: digest }); +console.log(result.status, result.reason, result.referenceTime); +``` + +Stamping needs a gateway and an API key, so it lives at the package root, which +re-exports everything above: + +```js +import { resolveNetwork, stamp } from '@unicitylabs/proof-cli'; + +const token = await stamp(digest, resolveNetwork({ network: 'testnet2' }), process.env.UNICITY_API_KEY); +``` + +Those two entry points are the whole public API; Node refuses deep imports into +the implementation. Anything they do not export is internal and may change in any +release. `tests/unit/PublicApiTest.ts` pins both export lists, and fails if a +module in this package starts importing from `node:` or if the verification entry +point gains a path to the aggregator. + ## What a stamp proves A verified token shows that a transaction containing your hash was certified by the Unicity Network in a specific round, and records the round's reference time, which is at or before the consensus-signed round timestamp. If the stamp is signed, it also shows that the holder of the printed key signed the hash, and that this signature existed no later than the certified time. diff --git a/package.json b/package.json index b486c1a..40e77be 100644 --- a/package.json +++ b/package.json @@ -8,8 +8,12 @@ }, "exports": { ".": { - "types": "./lib/lib/index.d.ts", - "default": "./lib/lib/index.js" + "types": "./lib/index.d.ts", + "default": "./lib/index.js" + }, + "./verify": { + "types": "./lib/verify.d.ts", + "default": "./lib/verify.js" } }, "files": [ @@ -19,7 +23,7 @@ "README.md" ], "scripts": { - "build": "tsc --project tsconfig.build.json", + "build": "node -e \"require('node:fs').rmSync('lib', { force: true, recursive: true })\" && tsc --project tsconfig.build.json", "build:check": "tsc --noEmit", "lint": "eslint \"src/**/*\" \"tests/**/*\"", "lint:fix": "eslint \"src/**/*\" \"tests/**/*\" --fix", diff --git a/src/commands/inspect.ts b/src/commands/inspect.ts index 7deaad1..22c3494 100644 --- a/src/commands/inspect.ts +++ b/src/commands/inspect.ts @@ -1,7 +1,7 @@ import { ICommandContext } from './context.js'; import { decodeToken, readTokenInput, reportNotAToken } from './tokenInput.js'; import { EXIT_OK } from '../errors.js'; -import { describeToken } from '../lib/TimestampClient.js'; +import { describeToken } from '../lib/TimestampVerification.js'; import { inspectJson, inspectText, toJsonLine } from '../output.js'; /** diff --git a/src/commands/stamp.ts b/src/commands/stamp.ts index d91c93c..5abbe46 100644 --- a/src/commands/stamp.ts +++ b/src/commands/stamp.ts @@ -4,7 +4,8 @@ import path from 'node:path'; import { ICommandContext } from './context.js'; import { IStampFlags, resolveStampConfig } from '../config.js'; import { EXIT_OK } from '../errors.js'; -import { describeToken, stamp } from '../lib/TimestampClient.js'; +import { stamp } from '../lib/TimestampClient.js'; +import { describeToken } from '../lib/TimestampVerification.js'; import { recoveryLines, stampJson, stampText, toJsonLine, warningLine } from '../output.js'; /** diff --git a/src/commands/verify.ts b/src/commands/verify.ts index fa55bb7..e263100 100644 --- a/src/commands/verify.ts +++ b/src/commands/verify.ts @@ -3,7 +3,12 @@ import { decodeToken, readTokenInput, reportNotAToken } from './tokenInput.js'; import { assertOneDigestSource, INetworkFlags, resolveDigest, resolveTrustBaseOverride } from '../config.js'; import { EXIT_OK, EXIT_VERIFICATION_FAILED } from '../errors.js'; import { bundledTrustBase, ITrustBaseChoice, networkNameForId, TrustBaseSource } from '../lib/networks.js'; -import { describeToken, ITimestampVerificationResult, verificationFailure, verify } from '../lib/TimestampClient.js'; +import { + describeToken, + ITimestampVerificationResult, + verificationFailure, + verify, +} from '../lib/TimestampVerification.js'; import { toJsonLine, verifyJson, verifyText } from '../output.js'; export interface IVerifyFlags extends INetworkFlags { diff --git a/src/config.ts b/src/config.ts index ab16c21..28e688b 100644 --- a/src/config.ts +++ b/src/config.ts @@ -4,17 +4,16 @@ import { access, readFile } from 'node:fs/promises'; import path from 'node:path'; import { pipeline } from 'node:stream/promises'; +import { RootTrustBase } from '@unicitylabs/state-transition-sdk/lib/api/bft/RootTrustBase.js'; import { SigningService } from '@unicitylabs/state-transition-sdk/lib/crypto/secp256k1/SigningService.js'; import { HexConverter } from '@unicitylabs/state-transition-sdk/lib/util/HexConverter.js'; import { usageError } from './errors.js'; import { bundledTrustBase, - INetworkSelection, isNetworkName, ITimestampNetwork, ITrustBaseChoice, - loadTrustBase, NETWORK_NAMES, NetworkName, resolveNetwork, @@ -34,6 +33,20 @@ export interface INetworkFlags { readonly trustBase?: string; } +/** + * A network choice as the command line expresses it, with the trust base still a + * path. The library takes a parsed trust base instead, so {@link loadTrustBase} + * sits between this and {@link resolveNetwork}. + */ +export interface INetworkSelection { + /** Overrides the preset gateway. */ + readonly gatewayUrl?: string; + /** Defaults to mainnet. */ + readonly network?: NetworkName; + /** Path to a trust base JSON file that replaces the bundled one. */ + readonly trustBasePath?: string; +} + export interface IStampFlags extends INetworkFlags { readonly allowInsecure?: boolean; readonly anonymous?: boolean; @@ -189,6 +202,21 @@ export async function resolveDigest( return file === undefined ? undefined : await hashFile(file); } +/** + * Read and parse a trust base file. + * + * The library reads no files, so this lives here: a `--trust-base` path is a + * command-line concept, and keeping the read in the CLI leaves the verification + * path able to run where there is no filesystem. + * + * @param {string} file Path to a trust base JSON file. + * @returns {Promise} Parsed trust base. + * @throws {Error} If the file cannot be read or is not a trust base. + */ +export async function loadTrustBase(file: string): Promise { + return RootTrustBase.fromJSON(JSON.parse(await readFile(file, 'utf8'))); +} + /** * Network selection for stamping: flags, then environment, then the mainnet default. * @@ -384,7 +412,12 @@ export async function resolveStampConfig( throw usageError('No API key. Set UNICITY_API_KEY in the environment or .env, or pass --api-key.'); } - const network = await resolveNetwork(resolveNetworkSelection(flags, env)); + const selection = resolveNetworkSelection(flags, env); + const network = resolveNetwork({ + gatewayUrl: selection.gatewayUrl, + network: selection.network, + trustBase: selection.trustBasePath === undefined ? undefined : await loadTrustBase(selection.trustBasePath), + }); const allowInsecure = flags.allowInsecure ?? false; if (new URL(network.gatewayUrl).protocol !== 'https:' && !allowInsecure) { throw usageError( diff --git a/src/index.ts b/src/index.ts new file mode 100644 index 0000000..638f2b1 --- /dev/null +++ b/src/index.ts @@ -0,0 +1,20 @@ +/** + * The library: offline verification, plus stamping through a gateway. + * + * Verification on its own is available from `@unicitylabs/proof-cli/verify`, whose + * module graph cannot reach the aggregator client. Prefer that entry point in code + * that only checks proofs — importing this one pulls in the gateway stack a + * verifier never calls. + * + * Every name here is listed deliberately. A symbol added to a module under + * `src/lib/` is internal until it appears in this file or in `src/verify.ts`. + */ + +export * from './verify.js'; + +export { TIMESTAMP_RECIPIENT } from './lib/constants.js'; +export { StampError } from './lib/errors.js'; +export { resolveNetwork } from './lib/networks.js'; +export type { INetworkOverrides, ITimestampNetwork } from './lib/networks.js'; +export { DEFAULT_TIMEOUT_MS, stamp, stampWith } from './lib/TimestampClient.js'; +export type { ICertifyOptions, IStampOptions } from './lib/TimestampClient.js'; diff --git a/src/lib/TimestampClient.ts b/src/lib/TimestampClient.ts index d5d389f..1201a35 100644 --- a/src/lib/TimestampClient.ts +++ b/src/lib/TimestampClient.ts @@ -2,25 +2,18 @@ import { AggregatorClient } from '@unicitylabs/state-transition-sdk/lib/api/Aggr import { RootTrustBase } from '@unicitylabs/state-transition-sdk/lib/api/bft/RootTrustBase.js'; import { CertificationData } from '@unicitylabs/state-transition-sdk/lib/api/CertificationData.js'; import { CertificationStatus } from '@unicitylabs/state-transition-sdk/lib/api/CertificationResponse.js'; -import { NetworkId } from '@unicitylabs/state-transition-sdk/lib/api/NetworkId.js'; import { SigningService } from '@unicitylabs/state-transition-sdk/lib/crypto/secp256k1/SigningService.js'; -import { EncodedPredicate } from '@unicitylabs/state-transition-sdk/lib/predicate/EncodedPredicate.js'; import { StateTransitionClient } from '@unicitylabs/state-transition-sdk/lib/StateTransitionClient.js'; import { CertifiedMintTransaction } from '@unicitylabs/state-transition-sdk/lib/transaction/CertifiedMintTransaction.js'; import { MintTransaction } from '@unicitylabs/state-transition-sdk/lib/transaction/MintTransaction.js'; import { Token } from '@unicitylabs/state-transition-sdk/lib/transaction/Token.js'; -import { TokenId } from '@unicitylabs/state-transition-sdk/lib/transaction/TokenId.js'; import { VerificationContext } from '@unicitylabs/state-transition-sdk/lib/transaction/verification/VerificationContext.js'; -import { HexConverter } from '@unicitylabs/state-transition-sdk/lib/util/HexConverter.js'; import { waitInclusionProof } from '@unicitylabs/state-transition-sdk/lib/util/InclusionProofUtils.js'; -import { areUint8ArraysEqual } from '@unicitylabs/state-transition-sdk/lib/util/TypedArrayUtils.js'; -import { VerificationResult } from '@unicitylabs/state-transition-sdk/lib/verification/VerificationResult.js'; -import { VerificationStatus } from '@unicitylabs/state-transition-sdk/lib/verification/VerificationStatus.js'; -import { TIMESTAMP_RECIPIENT, TIMESTAMP_RECIPIENT_ENCODED, TIMESTAMP_TOKEN_TYPE } from './constants.js'; +import { TIMESTAMP_RECIPIENT, TIMESTAMP_TOKEN_TYPE } from './constants.js'; import { StampError } from './errors.js'; import { ITimestampNetwork } from './networks.js'; -import { decodePayload, TimestampPayload } from './TimestampPayload.js'; +import { TimestampPayload } from './TimestampPayload.js'; import { createVerificationContext } from './verification.js'; export const DEFAULT_TIMEOUT_MS = 60_000; @@ -44,37 +37,6 @@ export interface IStampOptions extends ICertifyOptions { readonly signer?: SigningService; } -export interface ITimestampVerifyOptions { - /** Digest the token is expected to carry. */ - readonly expectedDigest?: Uint8Array; -} - -/** Everything that can be read off a token without verifying it. */ -export interface ITimestampDescription { - readonly epoch: bigint; - readonly networkId: NetworkId; - readonly payload: TimestampPayload | null; - readonly payloadError: string | null; - readonly recipientIsTimestampBurn: boolean; - /** Unix seconds; the certified time of the stamp. */ - readonly referenceTime: bigint; - readonly roundNumber: bigint; - /** Unix seconds; consensus-signed upper bound of the reference time. */ - readonly roundTimestamp: bigint; - readonly tokenId: TokenId; - readonly tokenTypeIsTimestamp: boolean; - readonly transferCount: number; -} - -export interface ITimestampVerificationResult extends ITimestampDescription { - /** SDK result tree, or null when verification was not reached. */ - readonly details: VerificationResult | null; - /** Null when no expected digest was given or the comparison was not reached. */ - readonly expectedDigestMatches: boolean | null; - readonly reason: string | null; - readonly status: 'FAIL' | 'OK'; -} - const KNOWN_STATUSES: readonly string[] = Object.values(CertificationStatus); const SUCCESS_STATUS: string = CertificationStatus.SUCCESS; @@ -176,122 +138,3 @@ export async function stampWith( const context = createVerificationContext(trustBase); return Token.mint(await certifyMintTransaction(client, context, transaction, options), context); } - -/** - * Read the timestamp fields off a token without verifying anything. - * - * @param {Token} token Any SDK token. - * @returns {ITimestampDescription} What the token claims. - */ -export function describeToken(token: Token): ITimestampDescription { - const genesis = token.genesis; - const certificate = genesis.inclusionProof.unicityCertificate; - const { error: payloadError, payload } = decodePayload(genesis.data); - - return { - epoch: certificate.unicitySeal.epoch, - networkId: token.networkId, - payload, - payloadError, - recipientIsTimestampBurn: EncodedPredicate.equals(genesis.recipient, TIMESTAMP_RECIPIENT_ENCODED), - referenceTime: genesis.referenceTime, - roundNumber: certificate.inputRecord.roundNumber, - roundTimestamp: certificate.inputRecord.timestamp, - tokenId: token.id, - tokenTypeIsTimestamp: areUint8ArraysEqual(token.type.bytes, TIMESTAMP_TOKEN_TYPE.bytes), - transferCount: token.transactions.length, - }; -} - -/** - * Build a failed verification result around a token description. - * - * @param {ITimestampDescription} description Fields read off the token. - * @param {string} reason Why verification failed. - * @param {VerificationResult|null} details SDK result tree, if verification ran. - * @param {boolean|null} expectedDigestMatches Digest comparison outcome, if one was requested. - * @returns {ITimestampVerificationResult} Failed result. - */ -export function verificationFailure( - description: ITimestampDescription, - reason: string, - details: VerificationResult | null = null, - expectedDigestMatches: boolean | null = null, -): ITimestampVerificationResult { - return { ...description, details, expectedDigestMatches, reason, status: 'FAIL' }; -} - -/** - * Verify a timestamp token offline against a trust base. - * - * @param {Token} token Token to verify. - * @param {RootTrustBase} trustBase Trust base of the network the token claims. - * @param {ITimestampVerifyOptions} options Expected digest. - * @returns {Promise} Outcome with the SDK result tree. - */ -export async function verify( - token: Token, - trustBase: RootTrustBase, - options: ITimestampVerifyOptions = {}, -): Promise { - const description = describeToken(token); - if (description.transferCount > 0) { - return verificationFailure( - description, - `Timestamp tokens carry no transfers; this one has ${description.transferCount}.`, - ); - } - if (!description.tokenTypeIsTimestamp) { - return verificationFailure( - description, - `Not a timestamp token: token type ${HexConverter.encode(token.type.bytes)}.`, - ); - } - - const details = await token.verify(createVerificationContext(trustBase)); - if (details.status !== VerificationStatus.OK) { - return verificationFailure(description, explainFailure(details, description, trustBase), details); - } - if (options.expectedDigest === undefined) { - return { ...description, details, expectedDigestMatches: null, reason: null, status: 'OK' }; - } - // Not dead code, and not a pass: reachable only if `describeToken` and the - // issuance verifier disagree about the payload, which is exactly the case that - // must not report OK with the caller's comparison quietly skipped. - if (description.payload === null) { - return verificationFailure( - description, - `Cannot check the expected hash: the payload could not be read (${description.payloadError ?? 'no payload'}).`, - details, - ); - } - if (!areUint8ArraysEqual(description.payload.digest, options.expectedDigest)) { - return verificationFailure(description, 'Hash mismatch: the token certifies a different digest.', details, false); - } - return { ...description, details, expectedDigestMatches: true, reason: null, status: 'OK' }; -} - -/** - * Pick the message a user needs out of a failed verification: the deepest failing - * rule that carries one, followed by the trust-base network when it is not the token's. - */ -function explainFailure( - details: VerificationResult, - description: ITimestampDescription, - trustBase: RootTrustBase, -): string { - const failures = collectFailures(details); - const explained = failures.filter((result) => result.message !== '').at(-1) ?? failures.at(-1) ?? details; - const reason = explained.message !== '' ? explained.message : `Verification rule ${explained.rule} failed.`; - if (description.networkId.id !== trustBase.networkId.id) { - return `${reason} The token is for network ${description.networkId.id} and the trust base for network ${trustBase.networkId.id}; select the matching network or trust base.`; - } - return reason; -} - -function collectFailures(result: VerificationResult): VerificationResult[] { - if (result.status === VerificationStatus.OK) { - return []; - } - return [result, ...result.results.flatMap((child) => collectFailures(child))]; -} diff --git a/src/lib/TimestampVerification.ts b/src/lib/TimestampVerification.ts new file mode 100644 index 0000000..26e3416 --- /dev/null +++ b/src/lib/TimestampVerification.ts @@ -0,0 +1,163 @@ +import { RootTrustBase } from '@unicitylabs/state-transition-sdk/lib/api/bft/RootTrustBase.js'; +import { NetworkId } from '@unicitylabs/state-transition-sdk/lib/api/NetworkId.js'; +import { EncodedPredicate } from '@unicitylabs/state-transition-sdk/lib/predicate/EncodedPredicate.js'; +import { Token } from '@unicitylabs/state-transition-sdk/lib/transaction/Token.js'; +import { TokenId } from '@unicitylabs/state-transition-sdk/lib/transaction/TokenId.js'; +import { HexConverter } from '@unicitylabs/state-transition-sdk/lib/util/HexConverter.js'; +import { areUint8ArraysEqual } from '@unicitylabs/state-transition-sdk/lib/util/TypedArrayUtils.js'; +import { VerificationResult } from '@unicitylabs/state-transition-sdk/lib/verification/VerificationResult.js'; +import { VerificationStatus } from '@unicitylabs/state-transition-sdk/lib/verification/VerificationStatus.js'; + +import { TIMESTAMP_RECIPIENT_ENCODED, TIMESTAMP_TOKEN_TYPE } from './constants.js'; +import { decodePayload, TimestampPayload } from './TimestampPayload.js'; +import { createVerificationContext } from './verification.js'; + +export interface ITimestampVerifyOptions { + /** Digest the token is expected to carry. */ + readonly expectedDigest?: Uint8Array; +} + +/** Everything that can be read off a token without verifying it. */ +export interface ITimestampDescription { + readonly epoch: bigint; + readonly networkId: NetworkId; + readonly payload: TimestampPayload | null; + readonly payloadError: string | null; + readonly recipientIsTimestampBurn: boolean; + /** Unix seconds; the certified time of the stamp. */ + readonly referenceTime: bigint; + readonly roundNumber: bigint; + /** Unix seconds; consensus-signed upper bound of the reference time. */ + readonly roundTimestamp: bigint; + readonly tokenId: TokenId; + readonly tokenTypeIsTimestamp: boolean; + readonly transferCount: number; +} + +export interface ITimestampVerificationResult extends ITimestampDescription { + /** SDK result tree, or null when verification was not reached. */ + readonly details: VerificationResult | null; + /** Null when no expected digest was given or the comparison was not reached. */ + readonly expectedDigestMatches: boolean | null; + readonly reason: string | null; + readonly status: 'FAIL' | 'OK'; +} + +/** + * Read the timestamp fields off a token without verifying anything. + * + * @param {Token} token Any SDK token. + * @returns {ITimestampDescription} What the token claims. + */ +export function describeToken(token: Token): ITimestampDescription { + const genesis = token.genesis; + const certificate = genesis.inclusionProof.unicityCertificate; + const { error: payloadError, payload } = decodePayload(genesis.data); + + return { + epoch: certificate.unicitySeal.epoch, + networkId: token.networkId, + payload, + payloadError, + recipientIsTimestampBurn: EncodedPredicate.equals(genesis.recipient, TIMESTAMP_RECIPIENT_ENCODED), + referenceTime: genesis.referenceTime, + roundNumber: certificate.inputRecord.roundNumber, + roundTimestamp: certificate.inputRecord.timestamp, + tokenId: token.id, + tokenTypeIsTimestamp: areUint8ArraysEqual(token.type.bytes, TIMESTAMP_TOKEN_TYPE.bytes), + transferCount: token.transactions.length, + }; +} + +/** + * Build a failed verification result around a token description. + * + * @param {ITimestampDescription} description Fields read off the token. + * @param {string} reason Why verification failed. + * @param {VerificationResult|null} details SDK result tree, if verification ran. + * @param {boolean|null} expectedDigestMatches Digest comparison outcome, if one was requested. + * @returns {ITimestampVerificationResult} Failed result. + */ +export function verificationFailure( + description: ITimestampDescription, + reason: string, + details: VerificationResult | null = null, + expectedDigestMatches: boolean | null = null, +): ITimestampVerificationResult { + return { ...description, details, expectedDigestMatches, reason, status: 'FAIL' }; +} + +/** + * Verify a timestamp token offline against a trust base. + * + * @param {Token} token Token to verify. + * @param {RootTrustBase} trustBase Trust base of the network the token claims. + * @param {ITimestampVerifyOptions} options Expected digest. + * @returns {Promise} Outcome with the SDK result tree. + */ +export async function verify( + token: Token, + trustBase: RootTrustBase, + options: ITimestampVerifyOptions = {}, +): Promise { + const description = describeToken(token); + if (description.transferCount > 0) { + return verificationFailure( + description, + `Timestamp tokens carry no transfers; this one has ${description.transferCount}.`, + ); + } + if (!description.tokenTypeIsTimestamp) { + return verificationFailure( + description, + `Not a timestamp token: token type ${HexConverter.encode(token.type.bytes)}.`, + ); + } + + const details = await token.verify(createVerificationContext(trustBase)); + if (details.status !== VerificationStatus.OK) { + return verificationFailure(description, explainFailure(details, description, trustBase), details); + } + if (options.expectedDigest === undefined) { + return { ...description, details, expectedDigestMatches: null, reason: null, status: 'OK' }; + } + // Not dead code, and not a pass: reachable only if `describeToken` and the + // issuance verifier disagree about the payload, which is exactly the case that + // must not report OK with the caller's comparison quietly skipped. + if (description.payload === null) { + return verificationFailure( + description, + `Cannot check the expected hash: the payload could not be read (${description.payloadError ?? 'no payload'}).`, + details, + ); + } + if (!areUint8ArraysEqual(description.payload.digest, options.expectedDigest)) { + return verificationFailure(description, 'Hash mismatch: the token certifies a different digest.', details, false); + } + return { ...description, details, expectedDigestMatches: true, reason: null, status: 'OK' }; +} + +/** + * Pick the message a user needs out of a failed verification: the deepest failing + * rule that carries one, followed by the trust-base network when it is not the token's. + */ +function explainFailure( + details: VerificationResult, + description: ITimestampDescription, + trustBase: RootTrustBase, +): string { + const failures = collectFailures(details); + const explained = failures.filter((result) => result.message !== '').at(-1) ?? failures.at(-1) ?? details; + const reason = explained.message !== '' ? explained.message : `Verification rule ${explained.rule} failed.`; + if (description.networkId.id !== trustBase.networkId.id) { + return `${reason} The token is for network ${description.networkId.id} and the trust base for network ${trustBase.networkId.id}; select the matching network or trust base.`; + } + return reason; +} + +function collectFailures(result: VerificationResult): VerificationResult[] { + if (result.status === VerificationStatus.OK) { + return []; + } + return [result, ...result.results.flatMap((child) => collectFailures(child))]; +} diff --git a/src/lib/index.ts b/src/lib/index.ts deleted file mode 100644 index 8d31287..0000000 --- a/src/lib/index.ts +++ /dev/null @@ -1,7 +0,0 @@ -export * from './constants.js'; -export * from './errors.js'; -export * from './networks.js'; -export * from './TimestampClient.js'; -export * from './TimestampIssuanceVerifier.js'; -export * from './TimestampPayload.js'; -export * from './verification.js'; diff --git a/src/lib/networks.ts b/src/lib/networks.ts index 10f2765..ac724f1 100644 --- a/src/lib/networks.ts +++ b/src/lib/networks.ts @@ -1,5 +1,3 @@ -import { readFile } from 'node:fs/promises'; - import { RootTrustBase } from '@unicitylabs/state-transition-sdk/lib/api/bft/RootTrustBase.js'; import mainnetTrustBase from '../trust-bases/bft-trustbase.mainnet.json' with { type: 'json' }; @@ -37,13 +35,20 @@ export interface ITimestampNetwork { readonly trustBase: RootTrustBase; } -export interface INetworkSelection { +/** + * Overrides for {@link resolveNetwork}. + * + * A replacement trust base arrives already parsed. This module reads no files, so + * the verification path can run where there is no filesystem; turning a + * `--trust-base` path into a trust base is the CLI's job. + */ +export interface INetworkOverrides { /** Overrides the preset gateway. */ readonly gatewayUrl?: string; /** Defaults to mainnet. */ readonly network?: NetworkName; - /** Path to a trust base JSON file that replaces the bundled one. */ - readonly trustBasePath?: string; + /** Replaces the bundled trust base. */ + readonly trustBase?: RootTrustBase; } /** @@ -84,28 +89,17 @@ export function bundledTrustBase(name: NetworkName): RootTrustBase { return RootTrustBase.fromJSON(NETWORKS[name].trustBaseJson); } -/** - * Read and parse a trust base file. - * - * @param {string} path File path. - * @returns {Promise} Parsed trust base. - * @throws {Error} If the file cannot be read or is not a trust base. - */ -export async function loadTrustBase(path: string): Promise { - return RootTrustBase.fromJSON(JSON.parse(await readFile(path, 'utf8'))); -} - /** * Resolve gateway and trust base from a preset plus optional overrides. * - * @param {INetworkSelection} selection Preset and overrides. - * @returns {Promise} Resolved network. + * @param {INetworkOverrides} overrides Gateway, preset and trust base overrides. + * @returns {ITimestampNetwork} Resolved network. */ -export async function resolveNetwork(selection: INetworkSelection = {}): Promise { - const name = selection.network ?? 'mainnet'; +export function resolveNetwork(overrides: INetworkOverrides = {}): ITimestampNetwork { + const name = overrides.network ?? 'mainnet'; return { - gatewayUrl: selection.gatewayUrl ?? NETWORKS[name].gatewayUrl, + gatewayUrl: overrides.gatewayUrl ?? NETWORKS[name].gatewayUrl, preset: name, - trustBase: selection.trustBasePath ? await loadTrustBase(selection.trustBasePath) : bundledTrustBase(name), + trustBase: overrides.trustBase ?? bundledTrustBase(name), }; } diff --git a/src/output.ts b/src/output.ts index 0cb72c3..15a7e95 100644 --- a/src/output.ts +++ b/src/output.ts @@ -2,7 +2,7 @@ import { HexConverter } from '@unicitylabs/state-transition-sdk/lib/util/HexConv import { VerificationResult } from '@unicitylabs/state-transition-sdk/lib/verification/VerificationResult.js'; import { networkNameForId, TrustBaseSource } from './lib/networks.js'; -import { ITimestampDescription, ITimestampVerificationResult } from './lib/TimestampClient.js'; +import { ITimestampDescription, ITimestampVerificationResult } from './lib/TimestampVerification.js'; /** Minimal sink the commands write to; process.stdout and process.stderr satisfy it. */ export interface IWriter { diff --git a/src/verify.ts b/src/verify.ts new file mode 100644 index 0000000..9f3d732 --- /dev/null +++ b/src/verify.ts @@ -0,0 +1,26 @@ +/** + * Offline verification: everything needed to check a proof, and nothing that can + * reach a gateway. + * + * The module graph behind this entry point contains no aggregator client, no + * JSON-RPC transport and no Node builtin, which is what makes "offline" a property + * of the import rather than a promise in the documentation. `PublicApiTest` + * enforces it. + * + * Every name here is listed deliberately. A symbol added to a module under + * `src/lib/` is internal until it appears in this file or in `src/index.ts`. + */ + +export { PAYLOAD_VERSION, TIMESTAMP_TAG, TIMESTAMP_TOKEN_TYPE, TIMESTAMP_TOKEN_TYPE_HEX } from './lib/constants.js'; +export { bundledTrustBase, isNetworkName, NETWORK_NAMES, NETWORKS, networkNameForId } from './lib/networks.js'; +export type { INetworkPreset, NetworkName } from './lib/networks.js'; +export { TimestampIssuanceVerifier } from './lib/TimestampIssuanceVerifier.js'; +export { decodePayload, TimestampPayload, TimestampPayloadError } from './lib/TimestampPayload.js'; +export type { DecodedPayload } from './lib/TimestampPayload.js'; +export { describeToken, verificationFailure, verify } from './lib/TimestampVerification.js'; +export type { + ITimestampDescription, + ITimestampVerificationResult, + ITimestampVerifyOptions, +} from './lib/TimestampVerification.js'; +export { createVerificationContext } from './lib/verification.js'; diff --git a/tests/unit/ConfigTest.ts b/tests/unit/ConfigTest.ts index 7881638..63595c7 100644 --- a/tests/unit/ConfigTest.ts +++ b/tests/unit/ConfigTest.ts @@ -6,6 +6,7 @@ import { HexConverter } from '@unicitylabs/state-transition-sdk/lib/util/HexConv import { hashFile, loadEnvironment, + loadTrustBase, parseDigest, parseNetworkName, parsePrivateKey, @@ -116,6 +117,21 @@ describe('resolveNetworkSelection', () => { }); }); +describe('loadTrustBase', () => { + it('parses a trust base file', async () => { + const file = path.join(await tempDir(), 'trust-base.json'); + await writeFile(file, JSON.stringify(NETWORKS.testnet2.trustBaseJson)); + expect((await loadTrustBase(file)).networkId.id).toBe(4); + }); + + it('surfaces unreadable and malformed files', async () => { + await expect(loadTrustBase('/nonexistent/trust-base.json')).rejects.toMatchObject({ code: 'ENOENT' }); + const file = path.join(await tempDir(), 'broken.json'); + await writeFile(file, '{"version": "1"}'); + await expect(loadTrustBase(file)).rejects.toThrow(); + }); +}); + describe('resolveTrustBaseOverride', () => { it('returns nothing without flags, so the token decides', async () => { await expect(resolveTrustBaseOverride({}, {})).resolves.toBeUndefined(); diff --git a/tests/unit/OutputTest.ts b/tests/unit/OutputTest.ts index b5dc739..a015160 100644 --- a/tests/unit/OutputTest.ts +++ b/tests/unit/OutputTest.ts @@ -3,7 +3,8 @@ import { HexConverter } from '@unicitylabs/state-transition-sdk/lib/util/HexConv import { VerificationResult } from '@unicitylabs/state-transition-sdk/lib/verification/VerificationResult.js'; import { VerificationStatus } from '@unicitylabs/state-transition-sdk/lib/verification/VerificationStatus.js'; -import { describeToken, stampWith, verify } from '../../src/lib/TimestampClient.js'; +import { stampWith } from '../../src/lib/TimestampClient.js'; +import { describeToken, verify } from '../../src/lib/TimestampVerification.js'; import { descriptionJson, formatIso, diff --git a/tests/unit/PublicApiTest.ts b/tests/unit/PublicApiTest.ts new file mode 100644 index 0000000..f4c660b --- /dev/null +++ b/tests/unit/PublicApiTest.ts @@ -0,0 +1,221 @@ +import { execFile } from 'node:child_process'; +import { readFile } from 'node:fs/promises'; +import { createRequire } from 'node:module'; +import path from 'node:path'; +import { pathToFileURL } from 'node:url'; +import { promisify } from 'node:util'; + +const execFileAsync = promisify(execFile); + +const PACKAGE_NAME = '@unicitylabs/proof-cli'; +/** Subpath in the `exports` map to the built file it resolves to. */ +const ENTRY_POINTS = { + '.': 'lib/index.js', + './verify': 'lib/verify.js', +} as const; +/** Trailing slash so the prefix test cannot match a sibling directory. */ +const PACKAGE_ROOT = pathToFileURL(`${path.resolve('.')}/`).href; + +/** + * Names `@unicitylabs/proof-cli/verify` publishes. Every one of them works with no + * gateway, no API key and no filesystem; adding anything else to this list is a + * claim that the name belongs in a browser. + */ +const VERIFY_EXPORTS: readonly string[] = [ + 'NETWORKS', + 'NETWORK_NAMES', + 'PAYLOAD_VERSION', + 'TIMESTAMP_TAG', + 'TIMESTAMP_TOKEN_TYPE', + 'TIMESTAMP_TOKEN_TYPE_HEX', + 'TimestampIssuanceVerifier', + 'TimestampPayload', + 'TimestampPayloadError', + 'bundledTrustBase', + 'createVerificationContext', + 'decodePayload', + 'describeToken', + 'isNetworkName', + 'networkNameForId', + 'verificationFailure', + 'verify', +]; + +/** What the package root adds on top of {@link VERIFY_EXPORTS}: stamping needs a gateway. */ +const STAMPING_EXPORTS: readonly string[] = [ + 'DEFAULT_TIMEOUT_MS', + 'StampError', + 'TIMESTAMP_RECIPIENT', + 'resolveNetwork', + 'stamp', + 'stampWith', +]; + +const VERIFY_TYPE_EXPORTS: readonly string[] = [ + 'DecodedPayload', + 'INetworkPreset', + 'ITimestampDescription', + 'ITimestampVerificationResult', + 'ITimestampVerifyOptions', + 'NetworkName', +]; + +const STAMPING_TYPE_EXPORTS: readonly string[] = [ + 'ICertifyOptions', + 'INetworkOverrides', + 'IStampOptions', + 'ITimestampNetwork', +]; + +interface IModuleGraph { + /** Node builtin specifier to the modules importing it. */ + readonly builtins: Map; + /** Every module reachable from the entry point, as a file URL. */ + readonly modules: Set; +} + +/** `import x from 'y'` and `export { x } from 'y'`, across line breaks. */ +const REEXPORT = /(?:^|[\s;}])(?:import|export)[\s\S]*?from\s*['"]([^'"]+)['"]/g; +/** Side-effect imports and dynamic ones, which carry no `from`. */ +const DIRECT_IMPORT = /(?:^|[\s;}])import\s*(?:\(\s*)?['"]([^'"]+)['"]/g; + +/** + * Walk a built entry point's module graph the way a bundler would, recording what + * it reaches and every Node builtin it imports on the way. + * + * Resolution uses the Node condition, so a dependency shipping separate Node and + * browser builds is seen through its Node build — the pessimistic choice. + * + * @param {string} entry Path to a built module. + * @returns {Promise} Reachable modules and the builtins they import. + */ +async function moduleGraph(entry: string): Promise { + const builtins = new Map(); + const modules = new Set(); + + async function walk(url: string): Promise { + if (modules.has(url) || !url.endsWith('.js')) { + return; + } + modules.add(url); + const source = await readFile(new URL(url), 'utf8'); + const specifiers = [...source.matchAll(REEXPORT), ...source.matchAll(DIRECT_IMPORT)].map((match) => match[1]); + for (const specifier of new Set(specifiers)) { + if (specifier.startsWith('node:')) { + builtins.set(specifier, [...(builtins.get(specifier) ?? []), url]); + continue; + } + await walk( + specifier.startsWith('.') + ? new URL(specifier, url).href + : pathToFileURL(createRequire(url).resolve(specifier)).href, + ); + } + } + + await walk(pathToFileURL(path.resolve(entry)).href); + return { builtins, modules }; +} + +/** True for modules written in this repository, as opposed to dependencies. */ +function isOwnModule(url: string): boolean { + return url.startsWith(PACKAGE_ROOT) && !url.includes('/node_modules/'); +} + +/** + * Import a specifier in a child process and list its exports. + * + * The package is imported by name, which Node resolves through its own `exports` + * map, so this sees exactly what a consumer sees. Jest's CJS runtime cannot import + * the built ESM directly, hence the child. + * + * @param {string} specifier Module specifier to import. + * @returns {Promise} Exported names, sorted. + */ +async function publishedExports(specifier: string): Promise { + const { stdout } = await execFileAsync( + process.execPath, + [ + '--input-type=module', + '-e', + `const module = await import(${JSON.stringify(specifier)}); + console.log(JSON.stringify(Object.keys(module).sort()));`, + ], + { cwd: path.resolve('.') }, + ); + return JSON.parse(stdout) as string[]; +} + +function exportedTypes(source: string): string[] { + return [...source.matchAll(/export type \{([^}]*)\}/g)] + .flatMap((match) => match[1].split(',')) + .map((name) => name.trim()) + .filter((name) => name !== '') + .sort(); +} + +describe('public library surface', () => { + it('publishes exactly the offline names from /verify', async () => { + expect(await publishedExports(`${PACKAGE_NAME}/verify`)).toEqual([...VERIFY_EXPORTS].sort()); + }); + + it('publishes verification plus stamping from the package root', async () => { + expect(await publishedExports(PACKAGE_NAME)).toEqual([...VERIFY_EXPORTS, ...STAMPING_EXPORTS].sort()); + }); + + it('pins the exported types of both entry points', async () => { + expect(exportedTypes(await readFile(path.resolve('src/verify.ts'), 'utf8'))).toEqual( + [...VERIFY_TYPE_EXPORTS].sort(), + ); + expect(exportedTypes(await readFile(path.resolve('src/index.ts'), 'utf8'))).toEqual( + [...STAMPING_TYPE_EXPORTS].sort(), + ); + }); + + it('lists every public name instead of re-exporting modules wholesale', async () => { + const verifySource = await readFile(path.resolve('src/verify.ts'), 'utf8'); + const indexSource = await readFile(path.resolve('src/index.ts'), 'utf8'); + expect(verifySource).not.toMatch(/export \*/); + expect([...indexSource.matchAll(/export \* from '([^']+)'/g)].map((match) => match[1])).toEqual(['./verify.js']); + }); + + it('blocks deep imports, so the entry points are the whole surface', async () => { + await expect(publishedExports(`${PACKAGE_NAME}/lib/lib/networks.js`)).rejects.toThrow( + /ERR_PACKAGE_PATH_NOT_EXPORTED/, + ); + }); + + it('ships both entry points with their declarations', async () => { + const manifest = JSON.parse(await readFile(path.resolve('package.json'), 'utf8')) as { + exports: Record; + files: string[]; + }; + expect(Object.keys(manifest.exports).sort()).toEqual(Object.keys(ENTRY_POINTS).sort()); + expect(manifest.files).toContain('lib/**/*'); + for (const [subpath, built] of Object.entries(ENTRY_POINTS)) { + expect(manifest.exports[subpath].default).toEqual(`./${built}`); + expect(manifest.exports[subpath].types).toEqual(`./${built.replace(/\.js$/, '.d.ts')}`); + await expect(readFile(path.resolve(built), 'utf8')).resolves.toContain('export'); + await expect(readFile(path.resolve(built.replace(/\.js$/, '.d.ts')), 'utf8')).resolves.toContain('export'); + } + }); + + it('keeps the gateway and the filesystem out of /verify', async () => { + const graph = await moduleGraph(ENTRY_POINTS['./verify']); + // Guards the guard: a regex that matched nothing would make every assertion + // below pass on an empty graph. + expect([...graph.modules].some((url) => url.includes('RootTrustBase'))).toBe(true); + expect([...graph.builtins.keys()]).toEqual([]); + expect([...graph.modules].filter((url) => /AggregatorClient|JsonRpc|\/uuid\//.test(url))).toEqual([]); + }); + + it('imports no Node builtin from any module in this package', async () => { + const graph = await moduleGraph(ENTRY_POINTS['.']); + expect([...graph.modules].filter(isOwnModule).length).toBeGreaterThan(5); + expect( + [...graph.builtins].flatMap(([builtin, importers]) => + importers.filter(isOwnModule).map((url) => `${builtin} <- ${url.slice(PACKAGE_ROOT.length)}`), + ), + ).toEqual([]); + }); +}); diff --git a/tests/unit/lib/NetworksTest.ts b/tests/unit/lib/NetworksTest.ts index c2db211..9d0fcc1 100644 --- a/tests/unit/lib/NetworksTest.ts +++ b/tests/unit/lib/NetworksTest.ts @@ -1,16 +1,11 @@ -import { writeFile } from 'node:fs/promises'; -import path from 'node:path'; - import { bundledTrustBase, isNetworkName, - loadTrustBase, NETWORK_NAMES, networkNameForId, NETWORKS, resolveNetwork, } from '../../../src/lib/networks.js'; -import { tempDir } from '../../support/fixtures.js'; describe('networks', () => { it('knows mainnet and testnet2 with the documented gateways and ids', () => { @@ -41,28 +36,19 @@ describe('networks', () => { expect(isNetworkName('')).toBe(false); }); - it('resolves mainnet by default and applies overrides', async () => { - const byDefault = await resolveNetwork(); + it('resolves mainnet by default and applies overrides', () => { + const byDefault = resolveNetwork(); expect(byDefault.preset).toEqual('mainnet'); expect(byDefault.gatewayUrl).toEqual(NETWORKS.mainnet.gatewayUrl); expect(byDefault.trustBase.networkId.id).toBe(1); - const file = path.join(await tempDir(), 'trust-base.json'); - await writeFile(file, JSON.stringify(NETWORKS.testnet2.trustBaseJson)); - const overridden = await resolveNetwork({ + const overridden = resolveNetwork({ gatewayUrl: 'http://localhost:3000', network: 'mainnet', - trustBasePath: file, + trustBase: bundledTrustBase('testnet2'), }); expect(overridden.preset).toEqual('mainnet'); expect(overridden.gatewayUrl).toEqual('http://localhost:3000'); expect(overridden.trustBase.networkId.id).toBe(4); }); - - it('surfaces unreadable and malformed trust base files', async () => { - await expect(loadTrustBase('/nonexistent/trust-base.json')).rejects.toMatchObject({ code: 'ENOENT' }); - const file = path.join(await tempDir(), 'broken.json'); - await writeFile(file, '{"version": "1"}'); - await expect(loadTrustBase(file)).rejects.toThrow(); - }); }); diff --git a/tests/unit/lib/TimestampClientTest.ts b/tests/unit/lib/TimestampClientTest.ts index 5b86a77..05a5494 100644 --- a/tests/unit/lib/TimestampClientTest.ts +++ b/tests/unit/lib/TimestampClientTest.ts @@ -15,7 +15,8 @@ import { VerificationStatus } from '@unicitylabs/state-transition-sdk/lib/verifi import { StampError } from '../../../src/lib/errors.js'; import { bundledTrustBase } from '../../../src/lib/networks.js'; -import { describeToken, stampWith, verificationFailure, verify } from '../../../src/lib/TimestampClient.js'; +import { stampWith } from '../../../src/lib/TimestampClient.js'; +import { describeToken, verificationFailure, verify } from '../../../src/lib/TimestampVerification.js'; import { OTHER_DIGEST, TEST_DIGEST, TEST_DIGEST_HEX } from '../../support/fixtures.js'; import { TestAggregatorClient } from '../../support/TestAggregatorClient.js';