diff --git a/README.md b/README.md index 3c1d6db..63709a0 100644 --- a/README.md +++ b/README.md @@ -11,9 +11,9 @@ writer semantics independently in TypeScript. ## Version and Core release -The package asset binding is `0.0.2`, built against the published -`malt-core v0.0.9` release at commit -`e389418cf6715ae58a97255196833b410b0962d1`. +The package asset binding is `0.0.3-rc.1`, built against the published +`malt-core v0.0.10-rc.1` release at commit +`933ef9824d5d852f819bdc91b244ce7b7e800706`. [`malt-core.lock.json`](./malt-core.lock.json) binds that tag, commit, Go module checksums. The `malt.ts-core-lock/v2` lock binds Core source only; Core WASM assets are not required. This repository exclusively owns WASM entrypoints, @@ -100,10 +100,13 @@ from committing source. ## Authentication API `verifyAuthenticationLocally({request, result, ...options})` verifies the -caller-selected Root, typed steps and binding/range operation through Core. -`malt.authentication/1` also authenticates early path absence. Typed inputs -preserve base64 bytes and decimal uint64 strings; JavaScript performs no -input hashing or application path normalization. +caller-selected Root, label steps and binding/range operation through Core. +`malt.authentication/3` also authenticates early path absence. Labels are +base64-encoded opaque bytes. `encodeIndexLabel(bigint)` serializes Direct +indices as eight unsigned big-endian bytes, and `encodeKeyLabel(Uint8Array)` +serializes Direct 32-byte keys. `deriveCoordinate({profile, label})` executes +Core derivation in the verifier Worker and returns a key or a bigint index. +JavaScript performs no label hashing or application path normalization. `prepareAuthentication(backend, stateJSON)` builds a complete candidate. `updateAuthentication(backend, candidateJSON, stateJSON)` verifies a complete @@ -161,7 +164,7 @@ session snapshot compatibility APIs. Worker readiness requires the complete current ABI. There are no forwarding aliases or optional old-runtime exports. The `malt-core.lock.json` and packaged binary assets identify the published -Core `v0.0.9` release. Its current host and batch APIs are bound to the +Core `v0.0.10-rc.1` release. Its current host and batch APIs are bound to the exact release tag, source commit, and module checksums. Source integration checks remain separate from this published release binding. diff --git a/assets/verifier/PROVENANCE.json b/assets/verifier/PROVENANCE.json index c6f443a..1f0fff2 100644 --- a/assets/verifier/PROVENANCE.json +++ b/assets/verifier/PROVENANCE.json @@ -1,18 +1,19 @@ { "schema": "malt.ts-verifier.provenance/v1", "source_repository": "https://github.com/DeWebProtocol/malt-ts.git", - "build_inputs_sha256": "f6d894fa39215a1c87a1a35ee6afa1af59d79191dcb2aadd9c1eeb4331044fc0", + "build_inputs_sha256": "a09908180f8fb79c4e6136c24f46deabc93a54dca0bfe106ecf82e8384f4af8f", "core": { "module_path": "github.com/dewebprotocol/malt-core", - "module_version": "v0.0.9", + "module_version": "v0.0.10-rc.1", "source_repository": "https://github.com/DeWebProtocol/malt-core.git", - "source_commit": "e389418cf6715ae58a97255196833b410b0962d1", - "module_sum": "h1:e4jNMhZ0dkaiFFLfg/8xxUFAP7JK//8KLxqp78s2nso=", + "source_commit": "933ef9824d5d852f819bdc91b244ce7b7e800706", + "module_sum": "h1:bZl8z4y0Uug6H79KAUBjwJ28RjOQouONTlF9Ede57sc=", "go_mod_sum": "h1:o6L8K9vJp5hyrVo3fUtSsj0rvNpcboOcOb3nQwnR/gs=" }, "target": "js/wasm", "exports": [ - "maltVerifyAuthentication" + "maltVerifyAuthentication", + "maltDeriveCoordinate" ], "go_version": "go1.26.0", "go_toolchain": "go version go1.26.0 linux/amd64", diff --git a/assets/verifier/SHA256SUMS b/assets/verifier/SHA256SUMS index 06763a6..e9b000d 100644 --- a/assets/verifier/SHA256SUMS +++ b/assets/verifier/SHA256SUMS @@ -1,3 +1,3 @@ -9f284de8b16efe4d2b941c966840199a325b4587cb9cee295fbcfa9c36ab9a5d malt-verifier.wasm +f920f17dfd846afb90e30c04919a97d9a936a1cd21ba78deba9c468a9bcd372d malt-verifier.wasm 0c949f4996f9a89698e4b5c586de32249c3b69b7baadb64d220073cc04acba14 wasm_exec.js -37428609c8e71a9986a3df0181359f076cd3c1f54293e2529369bc8a6db72e89 PROVENANCE.json +96666561a87b1ecd5a099d4de3f2f7a79f7b0432e80066a9248f36bd4d1fd8b9 PROVENANCE.json diff --git a/assets/verifier/malt-verifier.wasm b/assets/verifier/malt-verifier.wasm index 65ee1cc..748cb62 100644 Binary files a/assets/verifier/malt-verifier.wasm and b/assets/verifier/malt-verifier.wasm differ diff --git a/assets/writer/PROVENANCE.json b/assets/writer/PROVENANCE.json index c5a8de8..f0e6183 100644 --- a/assets/writer/PROVENANCE.json +++ b/assets/writer/PROVENANCE.json @@ -1,13 +1,13 @@ { "schema": "malt.ts-writer.provenance/v1", "source_repository": "https://github.com/DeWebProtocol/malt-ts.git", - "build_inputs_sha256": "f6d894fa39215a1c87a1a35ee6afa1af59d79191dcb2aadd9c1eeb4331044fc0", + "build_inputs_sha256": "a09908180f8fb79c4e6136c24f46deabc93a54dca0bfe106ecf82e8384f4af8f", "core": { "module_path": "github.com/dewebprotocol/malt-core", - "module_version": "v0.0.9", + "module_version": "v0.0.10-rc.1", "source_repository": "https://github.com/DeWebProtocol/malt-core.git", - "source_commit": "e389418cf6715ae58a97255196833b410b0962d1", - "module_sum": "h1:e4jNMhZ0dkaiFFLfg/8xxUFAP7JK//8KLxqp78s2nso=", + "source_commit": "933ef9824d5d852f819bdc91b244ce7b7e800706", + "module_sum": "h1:bZl8z4y0Uug6H79KAUBjwJ28RjOQouONTlF9Ede57sc=", "go_mod_sum": "h1:o6L8K9vJp5hyrVo3fUtSsj0rvNpcboOcOb3nQwnR/gs=" }, "target": "js/wasm", diff --git a/assets/writer/SHA256SUMS b/assets/writer/SHA256SUMS index 5c2f450..f3eab81 100644 --- a/assets/writer/SHA256SUMS +++ b/assets/writer/SHA256SUMS @@ -1,8 +1,8 @@ -82a734f8cf71608a21fcf5d8cd1ed213096373dd479a833e66eac53f62bad09d malt-writer-kzg.wasm -222a66d912f6498474353297c5ef21eb72103dbdaa9cf9e58062218dd6fdc66a malt-writer-ipa-direct.wasm -3a9bda0d5f5c889ae9be2ef9e179c9848e5d48ab4d194360f5c84f85fec49f7f malt-writer-ipa-compact.wasm -cd23cceeb13c8765a6ff8e318dca4d37cf596a851af1641fd082f8e49222f3c5 malt-writer-ipa-fast.wasm +32f533363304bd92e9198d1f5642a55a1c809a75e19bfbde18259d99b4fc5ce0 malt-writer-kzg.wasm +49d24f768c0b7361bb42c2629408ed55a05faf20301fa075f9e8db9c170c2719 malt-writer-ipa-direct.wasm +fb0326b4a47a80b9d79a40068a34a8f96e01507d004473ccfc80c696d2c432cc malt-writer-ipa-compact.wasm +190c5d081a7ac10b4bee48771b103096d9096d49e14caf8a418f844161d31a7f malt-writer-ipa-fast.wasm 6311876a80f3c9333f20e6a8ae8b55b7235b1f7411d6ae2224bc90b55fe779a2 malt-writer-worker.mjs 968657d9a8818feb23b6463aca609478c81423a93a8b0dc453705ad009214db0 malt-writer-workers.mjs 0c949f4996f9a89698e4b5c586de32249c3b69b7baadb64d220073cc04acba14 wasm_exec.js -4f2a89091cc594deb2f6e5a432b115081dcd0ee00af18d56a26974524ae9909d PROVENANCE.json +35ce4aad116eedbfacc44f8c49632c6f969a27ff94187f9cf3939943fc2276fe PROVENANCE.json diff --git a/assets/writer/malt-writer-ipa-compact.wasm b/assets/writer/malt-writer-ipa-compact.wasm index 95fc591..975fb8d 100644 Binary files a/assets/writer/malt-writer-ipa-compact.wasm and b/assets/writer/malt-writer-ipa-compact.wasm differ diff --git a/assets/writer/malt-writer-ipa-direct.wasm b/assets/writer/malt-writer-ipa-direct.wasm index 73ae086..f7f026e 100644 Binary files a/assets/writer/malt-writer-ipa-direct.wasm and b/assets/writer/malt-writer-ipa-direct.wasm differ diff --git a/assets/writer/malt-writer-ipa-fast.wasm b/assets/writer/malt-writer-ipa-fast.wasm index d71eeac..d068bed 100644 Binary files a/assets/writer/malt-writer-ipa-fast.wasm and b/assets/writer/malt-writer-ipa-fast.wasm differ diff --git a/assets/writer/malt-writer-kzg.wasm b/assets/writer/malt-writer-kzg.wasm index 5808cea..0e73a52 100644 Binary files a/assets/writer/malt-writer-kzg.wasm and b/assets/writer/malt-writer-kzg.wasm differ diff --git a/cmd/malt-verifier-wasm/authentication.go b/cmd/malt-verifier-wasm/authentication.go index 5cedf66..95667c8 100644 --- a/cmd/malt-verifier-wasm/authentication.go +++ b/cmd/malt-verifier-wasm/authentication.go @@ -23,7 +23,7 @@ func registerAuthenticationVerifier(backend string) error { default: return fmt.Errorf("unsupported verifier backend %q", backend) } - verifier, initErr := authbuiltin.NewVerifier(nil, profiles...) + verifier, initErr := authbuiltin.NewVerifier(profiles...) if initErr != nil { return initErr } diff --git a/cmd/malt-verifier-wasm/coordinate.go b/cmd/malt-verifier-wasm/coordinate.go new file mode 100644 index 0000000..75fcbe0 --- /dev/null +++ b/cmd/malt-verifier-wasm/coordinate.go @@ -0,0 +1,49 @@ +//go:build js && wasm + +package main + +import ( + "encoding/json" + "strconv" + "syscall/js" + + "github.com/dewebprotocol/malt-core/auth/coordinate" + "github.com/dewebprotocol/malt-core/derivation" +) + +func registerCoordinateDerivation() { + js.Global().Set("maltDeriveCoordinate", js.FuncOf(func(_ js.Value, args []js.Value) any { + fail := func(message string) string { + raw, _ := json.Marshal(map[string]string{"error": message}) + return string(raw) + } + if len(args) != 2 || args[0].Type() != js.TypeNumber || args[1].Type() != js.TypeObject || !args[1].InstanceOf(js.Global().Get("Uint8Array")) { + return fail("derive expects a profile ID and Uint8Array label") + } + number := args[0].Float() + if number < 0 || number > 255 || number != float64(uint8(number)) { + return fail("invalid derivation profile ID") + } + length := args[1].Get("byteLength").Int() + if length > 96<<20 { + return fail("label exceeds size limit") + } + label := make([]byte, length) + js.CopyBytesToGo(label, args[1]) + value, err := derivation.Derive(derivation.ProfileID(uint8(number)), label) + if err != nil { + return fail(err.Error()) + } + result := map[string]any{"kind": string(value.Kind)} + if value.Kind == coordinate.Index { + result["index"] = strconv.FormatUint(value.Index, 10) + } else { + result["key"] = coordinate.EncodeKey(value.Key) + } + raw, err := json.Marshal(result) + if err != nil { + return fail(err.Error()) + } + return string(raw) + })) +} diff --git a/cmd/malt-verifier-wasm/main.go b/cmd/malt-verifier-wasm/main.go index 37c1496..cd7b52c 100644 --- a/cmd/malt-verifier-wasm/main.go +++ b/cmd/malt-verifier-wasm/main.go @@ -12,6 +12,7 @@ import ( ) func main() { + registerCoordinateDerivation() backend := requestedBackend() if err := registerAuthenticationVerifier(backend); err != nil { js.Global().Set("maltVerifierInitError", err.Error()) diff --git a/go.mod b/go.mod index 650fa1e..1986fd9 100644 --- a/go.mod +++ b/go.mod @@ -2,7 +2,7 @@ module github.com/dewebprotocol/malt-ts go 1.26.0 -require github.com/dewebprotocol/malt-core v0.0.9 +require github.com/dewebprotocol/malt-core v0.0.10-rc.1 require ( github.com/bits-and-blooms/bitset v1.24.6 // indirect diff --git a/go.sum b/go.sum index 1d42541..52b6757 100644 --- a/go.sum +++ b/go.sum @@ -6,8 +6,8 @@ github.com/crate-crypto/go-kzg-4844 v1.1.0 h1:EN/u9k2TF6OWSHrCCDBBU6GLNMq88OspHH github.com/crate-crypto/go-kzg-4844 v1.1.0/go.mod h1:JolLjpSff1tCCJKaJx4psrlEdlXuJEC996PL3tTAFks= github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= -github.com/dewebprotocol/malt-core v0.0.9 h1:e4jNMhZ0dkaiFFLfg/8xxUFAP7JK//8KLxqp78s2nso= -github.com/dewebprotocol/malt-core v0.0.9/go.mod h1:o6L8K9vJp5hyrVo3fUtSsj0rvNpcboOcOb3nQwnR/gs= +github.com/dewebprotocol/malt-core v0.0.10-rc.1 h1:bZl8z4y0Uug6H79KAUBjwJ28RjOQouONTlF9Ede57sc= +github.com/dewebprotocol/malt-core v0.0.10-rc.1/go.mod h1:o6L8K9vJp5hyrVo3fUtSsj0rvNpcboOcOb3nQwnR/gs= github.com/ipfs/go-cid v0.6.2 h1:VuGwJd+KJTaMJ4S4d5EEf9SXc17YUblS5axCbocn9YE= github.com/ipfs/go-cid v0.6.2/go.mod h1:Xhwg8NzHeK9xPCEZkCw4idzPiuNMpX3fARuI5Iwj1Lo= github.com/klauspost/cpuid/v2 v2.3.0 h1:S4CRMLnYUhGeDFDqkGriYKdfoFlDnMtqTiI/sFzhA9Y= diff --git a/malt-core.lock.json b/malt-core.lock.json index b3920db..28464a8 100644 --- a/malt-core.lock.json +++ b/malt-core.lock.json @@ -1,9 +1,9 @@ { "schema": "malt.ts-core-lock/v2", "module_path": "github.com/dewebprotocol/malt-core", - "module_version": "v0.0.9", + "module_version": "v0.0.10-rc.1", "source_repository": "https://github.com/DeWebProtocol/malt-core.git", - "source_commit": "e389418cf6715ae58a97255196833b410b0962d1", - "module_sum": "h1:e4jNMhZ0dkaiFFLfg/8xxUFAP7JK//8KLxqp78s2nso=", + "source_commit": "933ef9824d5d852f819bdc91b244ce7b7e800706", + "module_sum": "h1:bZl8z4y0Uug6H79KAUBjwJ28RjOQouONTlF9Ede57sc=", "go_mod_sum": "h1:o6L8K9vJp5hyrVo3fUtSsj0rvNpcboOcOb3nQwnR/gs=" } diff --git a/node-tests/malt-writer-workers.mjs b/node-tests/malt-writer-workers.mjs index ff86f4b..638dbbf 100644 --- a/node-tests/malt-writer-workers.mjs +++ b/node-tests/malt-writer-workers.mjs @@ -139,8 +139,8 @@ test("request errors keep the selected Worker alive", async () => { const bootstrap = writer.createAuthentication("kzg", new Uint8Array([1])); const bootstrapRequest = await worker.nextRequest(); assert.equal(bootstrapRequest.method, "createAuthentication"); - worker.respond(bootstrapRequest, { result: '{"profile":"malt.authentication/0"}' }); - assert.equal(await bootstrap, '{"profile":"malt.authentication/0"}'); + worker.respond(bootstrapRequest, { result: '{"profile":"malt.authentication/2"}' }); + assert.equal(await bootstrap, '{"profile":"malt.authentication/2"}'); const invalidLoad = writer.importAuthentication("kzg", new Uint8Array([1])); const invalidRequest = await worker.nextRequest(); diff --git a/package-lock.json b/package-lock.json index 8706258..cb67160 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "@dewebprotocol/malt", - "version": "0.0.2", + "version": "0.0.3-rc.1", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@dewebprotocol/malt", - "version": "0.0.2", + "version": "0.0.3-rc.1", "license": "Apache-2.0", "devDependencies": { "happy-dom": "20.11.1", diff --git a/package.json b/package.json index 15749d0..591cfdd 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@dewebprotocol/malt", - "version": "0.0.2", + "version": "0.0.3-rc.1", "description": "Stable TypeScript and browser WASM SDK for MALT", "type": "module", "license": "Apache-2.0", diff --git a/scripts/build-wasm-release.sh b/scripts/build-wasm-release.sh index 7dac411..ee2546c 100755 --- a/scripts/build-wasm-release.sh +++ b/scripts/build-wasm-release.sh @@ -65,7 +65,7 @@ cp "${temporary}/assets/verifier/"* "${verifier_staging}/" cp "${temporary}/assets/writer/"* "${writer_staging}/" pin="$("${build_source}/scripts/resolve-core.sh")" IFS=$'\t' read -r _ _ core_module_dir _ _ <<<"${pin}" -authentication_corpus_sha256="$(sha256sum "${core_module_dir}/conformance/authentication-v1.json" | awk '{print $1}')" +authentication_corpus_sha256="$(sha256sum "${core_module_dir}/conformance/authentication-v2.json" | awk '{print $1}')" chmod 0644 "${verifier_staging}/"* "${writer_staging}/"* ( @@ -136,7 +136,7 @@ MANIFEST_PATH="${temporary}/WASM-RELEASE.json" node -e ' target: "js/wasm", archive_format: "ustar+gzip", conformance_corpora: { - authentication: {schema: "malt.conformance.authentication/1", sha256: process.env.AUTHENTICATION_CORPUS_SHA256}, + authentication: {schema: "malt.conformance.authentication/2", sha256: process.env.AUTHENTICATION_CORPUS_SHA256}, }, codegen_environment: {CGO_ENABLED: "0", GOEXPERIMENT: "none", GOWASM: "", GOFIPS140: "off"}, components: {verifier: component("VERIFIER"), writer: component("WRITER")} diff --git a/scripts/build-wasm.sh b/scripts/build-wasm.sh index 6e452e5..55a8b49 100755 --- a/scripts/build-wasm.sh +++ b/scripts/build-wasm.sh @@ -166,7 +166,8 @@ PROVENANCE_PATH="${verifier_staging}/PROVENANCE.json" node -e ' }, target: "js/wasm", exports: [ - "maltVerifyAuthentication" + "maltVerifyAuthentication", + "maltDeriveCoordinate" ], go_version: process.env.GO_VERSION, go_toolchain: process.env.GO_TOOLCHAIN, diff --git a/scripts/check-verifier.sh b/scripts/check-verifier.sh index 7950e6f..a14c141 100755 --- a/scripts/check-verifier.sh +++ b/scripts/check-verifier.sh @@ -78,7 +78,8 @@ MALT_SUM="${malt_module_sum}" MALT_GO_MOD_SUM="${malt_go_mod_sum}" \ CGO_ENABLED: "0", GOEXPERIMENT: "none", GOWASM: "", GOFIPS140: "off" } const expectedExports = [ - "maltVerifyAuthentication" + "maltVerifyAuthentication", + "maltDeriveCoordinate" ] if ( provenance.schema !== "malt.ts-verifier.provenance/v1" || diff --git a/scripts/check-wasm-release.sh b/scripts/check-wasm-release.sh index 240aa78..15442b9 100755 --- a/scripts/check-wasm-release.sh +++ b/scripts/check-wasm-release.sh @@ -27,7 +27,7 @@ fi expected_go_version="go${go_directive}" pin="$("${repo_root}/scripts/resolve-core.sh")" IFS=$'\t' read -r _ _ core_module_dir _ _ <<<"${pin}" -expected_authentication_corpus_sha256="$(sha256sum "${core_module_dir}/conformance/authentication-v1.json" | awk '{print $1}')" +expected_authentication_corpus_sha256="$(sha256sum "${core_module_dir}/conformance/authentication-v2.json" | awk '{print $1}')" expected_commit="$(git -C "${repo_root}" rev-parse HEAD)" expected_epoch="$(git -C "${repo_root}" show -s --format=%ct HEAD)" expected_build_inputs="$("${repo_root}/scripts/build-wasm.sh" --print-source-digest)" @@ -84,7 +84,7 @@ AUTHENTICATION_CORPUS_SHA256="${expected_authentication_corpus_sha256}" node -e const version = /^v[0-9]+\.[0-9]+\.[0-9]+(?:[.-][0-9A-Za-z.-]+)?$/ const expectedCodegen = {CGO_ENABLED: "0", GOEXPERIMENT: "none", GOWASM: "", GOFIPS140: "off"} const expectedCorpora = { - authentication: {schema: "malt.conformance.authentication/1", sha256: process.env.AUTHENTICATION_CORPUS_SHA256}, + authentication: {schema: "malt.conformance.authentication/2", sha256: process.env.AUTHENTICATION_CORPUS_SHA256}, } const toolchain = /^go version (go[0-9]+\.[0-9]+\.[0-9]+) ([a-z0-9]+)\/([a-z0-9]+)$/.exec(manifest.go_toolchain || "") if (manifest.schema !== "malt.ts-wasm-release/v1" || diff --git a/scripts/run-authentication-batch-wasm.mjs b/scripts/run-authentication-batch-wasm.mjs index 6f3d3af..c497cd9 100644 --- a/scripts/run-authentication-batch-wasm.mjs +++ b/scripts/run-authentication-batch-wasm.mjs @@ -23,27 +23,27 @@ assert.equal(globalThis.maltWriterLoadedBackend, backend) assert.equal(globalThis.maltWriterLoadedProfile, profile) for (const name of ['maltComputeClientRootV1', 'maltWriterBootstrapSessionV1', 'maltWriterLoadSessionV1', 'maltWriterPrepareSessionV1', 'maltWriterValidateReceiptV1']) assert.equal(globalThis[name], undefined) const json = value => new TextEncoder().encode(JSON.stringify(value)) -const state = { descriptor: { layout: 1, input_rule: 1, vc_profile: backend === 'ipa' ? 2 : 1 }, entries: [] } +const state = { descriptor: { layout: 1, derivation_profile: 4, vc_profile: backend === 'ipa' ? 2 : 1 }, entries: [] } const base = JSON.parse(await globalThis.maltPrepareAuthentication(json(state))) -state.entries.push({ input: { kind: 'label', data: 'ZmlsZQ==' }, target: { '/': 'bafkqaaa' } }) +state.entries.push({ label: 'ZmlsZQ==', target: { '/': 'bafkqaaa' } }) const next = JSON.parse(await globalThis.maltUpdateAuthentication(json(base), json(state))) // Both complete and retained no-op updates must stay materializable. const unchanged = JSON.parse(await globalThis.maltUpdateAuthentication(json(next), json(state))) const retained = JSON.parse(await globalThis.maltImportAuthentication(json(next))) -const noOpHandle = JSON.parse(await globalThis.maltApplyAuthentication(new TextEncoder().encode(retained.handle), json({ profile: 'malt.authentication-delta/0', changes: [] }))) +const noOpHandle = JSON.parse(await globalThis.maltApplyAuthentication(new TextEncoder().encode(retained.handle), json({ profile: 'malt.authentication-delta/1', changes: [] }))) const noOp = JSON.parse(await globalThis.maltExportAuthentication(new TextEncoder().encode(noOpHandle.handle))) for (const candidate of [unchanged, noOp]) { assert.equal(candidate.root, next.root) assert.equal(candidate.previous, next.previous) - const noOpBatch = { profile: 'malt.authentication-batch/0', transaction_id: 'no-op', base: next.root, root: next.root, candidates: [candidate] } + const noOpBatch = { profile: 'malt.authentication-batch/1', transaction_id: 'no-op', base: next.root, root: next.root, candidates: [candidate] } const noOpDigest = await globalThis.maltValidateAuthenticationBatch(json(noOpBatch)) - assert.equal(await globalThis.maltValidateAuthenticationReceipt(json(noOpBatch), json({ profile: 'malt.authentication-receipt/0', transaction_id: noOpBatch.transaction_id, base: next.root, root: next.root, digest: noOpDigest, durable_boundary: 'wasm-test/no-op' })), next.root) + assert.equal(await globalThis.maltValidateAuthenticationReceipt(json(noOpBatch), json({ profile: 'malt.authentication-receipt/1', transaction_id: noOpBatch.transaction_id, base: next.root, root: next.root, digest: noOpDigest, durable_boundary: 'wasm-test/no-op' })), next.root) } await globalThis.maltCloseAuthentication() -const batch = { profile: 'malt.authentication-batch/0', transaction_id: 'wasm-batch', base: base.root, root: next.root, candidates: [base, next] } +const batch = { profile: 'malt.authentication-batch/1', transaction_id: 'wasm-batch', base: base.root, root: next.root, candidates: [base, next] } const digest = await globalThis.maltValidateAuthenticationBatch(json(batch)) assert.match(digest, /^[a-f0-9]{64}$/) -const receipt = { profile: 'malt.authentication-receipt/0', transaction_id: batch.transaction_id, base: batch.base, root: batch.root, digest, durable_boundary: 'wasm-test/0' } +const receipt = { profile: 'malt.authentication-receipt/1', transaction_id: batch.transaction_id, base: batch.base, root: batch.root, digest, durable_boundary: 'wasm-test/0' } assert.equal(await globalThis.maltValidateAuthenticationReceipt(json(batch), json(receipt)), next.root) for (const field of ['transaction_id', 'base', 'root', 'digest', 'durable_boundary']) { await assert.rejects(() => globalThis.maltValidateAuthenticationReceipt(json(batch), json({ ...receipt, [field]: '' }))) diff --git a/scripts/run-authentication-router-smoke.mjs b/scripts/run-authentication-router-smoke.mjs index 5345564..560d6ad 100644 --- a/scripts/run-authentication-router-smoke.mjs +++ b/scripts/run-authentication-router-smoke.mjs @@ -1,3 +1,4 @@ +import { encodeIndexLabel } from '../src/coordinate.mjs' import assert from 'node:assert/strict' import { readFile } from 'node:fs/promises' import { Worker as NodeWorker } from 'node:worker_threads' @@ -32,14 +33,14 @@ const writer = await createBrowserMaltWriter({ const bytes = value => new TextEncoder().encode(value) const json = value => bytes(JSON.stringify(value)) const state = { - descriptor: { layout: 2, input_rule: 0, vc_profile: 2 }, - entries: [{ input: { kind: 'index', number: '0' }, target: { '/': 'bafkqaaa' } }] + descriptor: { layout: 2, derivation_profile: 3, vc_profile: 2 }, + entries: [{ label: encodeIndexLabel('0'), target: { '/': 'bafkqaaa' } }] } try { const base = JSON.parse(await writer.createAuthentication('ipa', json(state))) const next = JSON.parse(await writer.applyAuthentication('ipa', bytes(base.handle), json({ - profile: 'malt.authentication-delta/0', - changes: [{ input: { kind: 'index', number: '0' }, before: 'bafkqaaa', after: 'bafkreigh2akiscaildcw4535x7k5vfhq56bqddhziq3p4mwfmlz4vfu2ta' }] + profile: 'malt.authentication-delta/1', + changes: [{ label: encodeIndexLabel('0'), before: 'bafkqaaa', after: 'bafkreigh2akiscaildcw4535x7k5vfhq56bqddhziq3p4mwfmlz4vfu2ta' }] }))) assert.notEqual(next.root, base.root) const exported = JSON.parse(await writer.exportAuthentication('ipa', bytes(next.handle))) diff --git a/scripts/run-authentication-wasm.mjs b/scripts/run-authentication-wasm.mjs index f615223..75e3803 100644 --- a/scripts/run-authentication-wasm.mjs +++ b/scripts/run-authentication-wasm.mjs @@ -22,8 +22,19 @@ while (typeof globalThis[name] !== 'function') { await new Promise(resolve => setTimeout(resolve, 10)) } const corpus = JSON.parse(await readFile(corpusPath, 'utf8')) -assert.equal(corpus.schema, 'malt.conformance.authentication/1') +assert.equal(corpus.schema, 'malt.conformance.authentication/2') if (kind === 'verifier') { + const derive = (profile, bytes) => JSON.parse(globalThis.maltDeriveCoordinate(profile, bytes)) + for (const index of [0n, 42n, 9007199254740993n, 18446744073709551615n]) { + const label = new Uint8Array(8) + new DataView(label.buffer).setBigUint64(0, index, false) + assert.deepEqual(derive(3, label), {kind: 'index', index: String(index)}) + } + const key = Uint8Array.from({length: 32}, (_, i) => i) + assert.deepEqual(derive(3, key), {kind:'key', key: Buffer.from(key).toString('base64')}) + assert.deepEqual(derive(4, new TextEncoder().encode('@payload')), {kind:'key', key: 'WG2RKG7FVDG1oDI45hXWKHCvy9y+sUC28l0lMcxB8kc='}) + for (const id of [0, 1, 2, 255]) assert(derive(id, key).error) + for (const bytes of [new Uint8Array(), new TextEncoder().encode('42'), new Uint8Array(33)]) assert(derive(3, bytes).error) for (const vector of corpus.vectors) { const result = JSON.parse(globalThis[name](JSON.stringify(vector.verification))) assert.equal(result.profile, vector.verification.request.profile, vector.id) @@ -37,17 +48,17 @@ if (kind === 'verifier') { console.log(`V0 WASM verifier ${backend} passed: ${corpus.vectors.length} vectors`) } else { const id = backend === 'ipa' ? 2 : 1 - const state = { descriptor: { layout: 1, input_rule: 1, vc_profile: id }, entries: [ - { input: { kind: 'label', data: 'YS9i' }, target: { '/': 'bafkqaaa' } }, - { input: { kind: 'system', number: '1' }, target: { '/': 'bafkqaaa' } } + const state = { descriptor: { layout: 1, derivation_profile: 4, vc_profile: id }, entries: [ + { label: 'YS9i', target: { '/': 'bafkqaaa' } }, + { label: 'QHBheWxvYWQ=', target: { '/': 'bafkqaaa' } } ] } const candidate = JSON.parse(await globalThis[name](new TextEncoder().encode(JSON.stringify(state)))) const expected = corpus.vectors.find(v => v.id === `profile-${id}.opaque-label`) assert.equal(candidate.root, expected.verification.request.root) - assert.equal(candidate.profile, 'malt.authentication/0') + assert.equal(candidate.profile, 'malt.authentication/2') assert(candidate.nodes.length > 0) await assert.rejects(() => globalThis[name]('{}')) - state.descriptor.input_rule = 255 + state.descriptor.derivation_profile = 255 await assert.rejects(() => globalThis[name](new TextEncoder().encode(JSON.stringify(state)))) console.log(`V0 WASM writer ${backend}: exact native Root and rejection checks passed`) } diff --git a/scripts/run-retained-writer-wasm.mjs b/scripts/run-retained-writer-wasm.mjs index c927cfb..6a66a81 100644 --- a/scripts/run-retained-writer-wasm.mjs +++ b/scripts/run-retained-writer-wasm.mjs @@ -1,3 +1,4 @@ +import { encodeIndexLabel } from '../src/coordinate.mjs' import assert from 'node:assert/strict' import { webcrypto } from 'node:crypto' import { readFile } from 'node:fs/promises' @@ -29,17 +30,17 @@ const json = value => text(JSON.stringify(value)) const first = 'bafkqaaa' const second = 'bafkreigh2akiscaildcw4535x7k5vfhq56bqddhziq3p4mwfmlz4vfu2ta' const state = { - descriptor: { layout: 2, input_rule: 0, vc_profile: backend === 'ipa' ? 2 : 1 }, + descriptor: { layout: 2, derivation_profile: 3, vc_profile: backend === 'ipa' ? 2 : 1 }, entries: Array.from({ length: 256 }, (_, i) => ({ - input: { kind: 'index', number: String(i) }, target: { '/': first } + label: encodeIndexLabel(String(i)), target: { '/': first } })) } const base = JSON.parse(await globalThis.maltCreateAuthentication(json(state))) assert.equal(typeof base.handle, 'string') assert.equal(base.nodes, undefined) const delta = { - profile: 'malt.authentication-delta/0', - changes: [{ input: { kind: 'index', number: '255' }, before: first, after: second }] + profile: 'malt.authentication-delta/1', + changes: [{ label: encodeIndexLabel('255'), before: first, after: second }] } const next = JSON.parse(await globalThis.maltApplyAuthentication(text(base.handle), json(delta))) assert.notEqual(next.root, base.root) diff --git a/scripts/run-verifier-conformance.sh b/scripts/run-verifier-conformance.sh index bb0b7db..e3474e2 100755 --- a/scripts/run-verifier-conformance.sh +++ b/scripts/run-verifier-conformance.sh @@ -22,6 +22,6 @@ fi for backend in all kzg ipa; do node "${repo_root}/scripts/run-authentication-wasm.mjs" verifier \ "${verifier_root}/malt-verifier.wasm" "${verifier_root}/wasm_exec.js" \ - "${malt_module_dir}/conformance/authentication-v1.json" "${backend}" + "${malt_module_dir}/conformance/authentication-v2.json" "${backend}" done printf 'malt-ts verifier passes the MALT %s conformance corpus.\n' "${malt_version}" diff --git a/scripts/run-writer-conformance.sh b/scripts/run-writer-conformance.sh index cf91fbb..0d5995f 100755 --- a/scripts/run-writer-conformance.sh +++ b/scripts/run-writer-conformance.sh @@ -31,7 +31,7 @@ for profile in kzg direct compact fast; do wasm="${writer_root}/malt-writer-ipa-${profile}.wasm" profile_arg="${profile}" if [[ "${profile}" == kzg ]]; then backend=kzg; wasm="${writer_root}/malt-writer-kzg.wasm"; profile_arg=; fi - node "${repo_root}/scripts/run-authentication-wasm.mjs" writer "${wasm}" "${writer_root}/wasm_exec.js" "${malt_module_dir}/conformance/authentication-v1.json" "${backend}" + node "${repo_root}/scripts/run-authentication-wasm.mjs" writer "${wasm}" "${writer_root}/wasm_exec.js" "${malt_module_dir}/conformance/authentication-v2.json" "${backend}" node "${repo_root}/scripts/run-retained-writer-wasm.mjs" "${wasm}" "${writer_root}/wasm_exec.js" "${backend}" "${profile_arg}" node "${repo_root}/scripts/run-authentication-batch-wasm.mjs" "${wasm}" "${writer_root}/wasm_exec.js" "${backend}" "${profile_arg}" done diff --git a/scripts/run-writer-worker-smoke.mjs b/scripts/run-writer-worker-smoke.mjs index 2e5236c..fd59e9f 100644 --- a/scripts/run-writer-worker-smoke.mjs +++ b/scripts/run-writer-worker-smoke.mjs @@ -58,18 +58,18 @@ try { const bytes = value => new TextEncoder().encode(value); const json = value => bytes(JSON.stringify(value)); - const state = { descriptor: { layout: 1, input_rule: 1, vc_profile: backend === 'ipa' ? 2 : 1 }, entries: [] }; + const state = { descriptor: { layout: 1, derivation_profile: 4, vc_profile: backend === 'ipa' ? 2 : 1 }, entries: [] }; const base = JSON.parse(await writer.createAuthentication(backend, json(state))); const next = JSON.parse(await writer.applyAuthentication(backend, bytes(base.handle), json({ - profile: 'malt.authentication-delta/0', changes: [{ input: { kind: 'label', data: 'ZmlsZQ==' }, after: 'bafkqaaa' }] + profile: 'malt.authentication-delta/1', changes: [{ label: 'ZmlsZQ==', after: 'bafkqaaa' }] }))); assert.notEqual(next.root, base.root); const exported = JSON.parse(await writer.exportAuthentication(backend, bytes(next.handle))); const imported = JSON.parse(await writer.importAuthentication(backend, json(exported))); assert.equal(imported.root, next.root); - const batch = { profile: 'malt.authentication-batch/0', transaction_id: 'worker-smoke', base: base.root, root: next.root, candidates: [exported] }; + const batch = { profile: 'malt.authentication-batch/1', transaction_id: 'worker-smoke', base: base.root, root: next.root, candidates: [exported] }; const digest = await writer.validateAuthenticationBatch(backend, json(batch)); - const receipt = { profile: 'malt.authentication-receipt/0', transaction_id: batch.transaction_id, base: batch.base, root: batch.root, digest, durable_boundary: 'worker-smoke/0' }; + const receipt = { profile: 'malt.authentication-receipt/1', transaction_id: batch.transaction_id, base: batch.base, root: batch.root, digest, durable_boundary: 'worker-smoke/0' }; assert.equal(await writer.validateAuthenticationReceipt(backend, json(batch), json(receipt)), next.root); await assert.rejects(writer.validateAuthenticationReceipt(backend, json(batch), json({ ...receipt, root: base.root }))); // Queued export completes before close invalidates every retained handle. diff --git a/scripts/test-core-source.sh b/scripts/test-core-source.sh index ef8a7e2..74cce27 100755 --- a/scripts/test-core-source.sh +++ b/scripts/test-core-source.sh @@ -41,14 +41,14 @@ cp "${go_root}/lib/wasm/wasm_exec.js" "${output}/writer/wasm_exec.js" cp "${go_root}/lib/wasm/wasm_exec.js" "${output}/verifier/wasm_exec.js" cp "${repo_root}/assets/writer/malt-writer-worker.mjs" "${repo_root}/assets/writer/malt-writer-workers.mjs" "${output}/writer/" node "${repo_root}/scripts/run-authentication-wasm.mjs" verifier "${output}/verifier/malt-verifier.wasm" \ - "${output}/verifier/wasm_exec.js" "${core_root}/conformance/authentication-v1.json" all + "${output}/verifier/wasm_exec.js" "${core_root}/conformance/authentication-v2.json" all for profile in kzg direct compact fast; do backend=ipa wasm="${output}/writer/malt-writer-ipa-${profile}.wasm" profile_arg="${profile}" if [[ "${profile}" == kzg ]]; then backend=kzg; wasm="${output}/writer/malt-writer-kzg.wasm"; profile_arg=; fi node "${repo_root}/scripts/run-authentication-wasm.mjs" writer "${wasm}" "${output}/writer/wasm_exec.js" \ - "${core_root}/conformance/authentication-v1.json" "${backend}" + "${core_root}/conformance/authentication-v2.json" "${backend}" node "${repo_root}/scripts/run-retained-writer-wasm.mjs" "${wasm}" "${output}/writer/wasm_exec.js" "${backend}" "${profile_arg}" node "${repo_root}/scripts/run-authentication-batch-wasm.mjs" "${wasm}" "${output}/writer/wasm_exec.js" "${backend}" "${profile_arg}" done diff --git a/src/coordinate.mjs b/src/coordinate.mjs new file mode 100644 index 0000000..a360264 --- /dev/null +++ b/src/coordinate.mjs @@ -0,0 +1,38 @@ +import { loadBrowserVerifier } from './verifier.mjs' +// Label serialization helpers. Coordinate derivation itself executes in Core/WASM. +const base64 = (bytes) => btoa(String.fromCharCode(...bytes)) + +/** Encode a uint64 as the canonical eight-byte big-endian Direct label. */ +export function encodeIndexLabel(index) { + if (typeof index === 'number' && !Number.isSafeInteger(index)) throw new TypeError('index number must be a safe integer; use bigint or a decimal string') + if (typeof index !== 'number' && typeof index !== 'bigint' && !(typeof index === 'string' && /^(0|[1-9][0-9]*)$/.test(index))) throw new TypeError('index must be an unsigned integer') + const value = BigInt(index) + if (value < 0n || value > 0xffffffffffffffffn) throw new RangeError('index exceeds uint64') + const bytes = new Uint8Array(8) + new DataView(bytes.buffer).setBigUint64(0, value, false) + return base64(bytes) +} + +/** Encode a precomputed 32-byte key as a Direct label. */ +export function encodeKeyLabel(key) { + if (!(key instanceof Uint8Array) || key.byteLength !== 32) throw new TypeError('key must contain exactly 32 bytes') + return base64(key) +} + +/** Execute the selected public derivation profile in the locked Core/WASM. */ +export async function deriveCoordinate({ profile, label, provider, signal, ...loadOptions }) { + if (!(label instanceof Uint8Array)) throw new TypeError('label must be Uint8Array') + if (!Number.isInteger(profile) || profile < 0 || profile > 255) throw new TypeError('invalid derivation profile ID') + let encoded = '' + for (let i=0;ic.charCodeAt(0)) + if (key.length === 32 && btoa(String.fromCharCode(...key)) === result.key) return {kind:'key',key} + } + throw new Error('invalid coordinate returned by Core/WASM') +} diff --git a/src/index.mjs b/src/index.mjs index b88dea5..47ceb75 100644 --- a/src/index.mjs +++ b/src/index.mjs @@ -1,3 +1,5 @@ export * from './release.mjs' export * from './verifier.mjs' export * from './writer.mjs' + +export * from './coordinate.mjs' diff --git a/src/malt-verifier.worker.mjs b/src/malt-verifier.worker.mjs index 4a0274a..1ad2876 100644 --- a/src/malt-verifier.worker.mjs +++ b/src/malt-verifier.worker.mjs @@ -98,6 +98,8 @@ async function verify({ id, kind, json }) { function selectVerifier(kind) { switch (kind) { + case 'derive': + return (json) => { const { profile, label } = JSON.parse(json); return globalThis.maltDeriveCoordinate(profile, Uint8Array.from(atob(label), (c) => c.charCodeAt(0))) } case 'authentication': return globalThis.maltVerifyAuthentication default: @@ -115,7 +117,7 @@ async function waitForProvider() { if (Date.now() >= deadline) throw new Error('local verifier initialization timed out') await new Promise((resolve) => setTimeout(resolve, 10)) } - for (const name of ['maltVerifyAuthentication']) { + for (const name of ['maltVerifyAuthentication', 'maltDeriveCoordinate']) { if (typeof globalThis[name] !== 'function') throw new Error(`local verifier did not register ${name}`) } diff --git a/src/release.mjs b/src/release.mjs index 4ab0e9b..e1215b6 100644 --- a/src/release.mjs +++ b/src/release.mjs @@ -1,8 +1,8 @@ -export const maltTSVersion = '0.0.2' +export const maltTSVersion = '0.0.3-rc.1' export const maltCoreRelease = Object.freeze({ - version: 'v0.0.9', - commit: 'e389418cf6715ae58a97255196833b410b0962d1', - moduleSum: 'h1:e4jNMhZ0dkaiFFLfg/8xxUFAP7JK//8KLxqp78s2nso=', + version: 'v0.0.10-rc.1', + commit: '933ef9824d5d852f819bdc91b244ce7b7e800706', + moduleSum: 'h1:bZl8z4y0Uug6H79KAUBjwJ28RjOQouONTlF9Ede57sc=', goModSum: 'h1:o6L8K9vJp5hyrVo3fUtSsj0rvNpcboOcOb3nQwnR/gs=' }) diff --git a/src/verifier.mjs b/src/verifier.mjs index 4f4571a..c19d08c 100644 --- a/src/verifier.mjs +++ b/src/verifier.mjs @@ -1,4 +1,4 @@ -export const authenticationPathVerifierProfile = "malt.authentication/1" +export const authenticationPathVerifierProfile = "malt.authentication/3" export const defaultVerifierRuntimeURL = '/verifier/wasm_exec.js' export const defaultVerifierWASMURL = '/verifier/malt-verifier.wasm' @@ -160,6 +160,10 @@ class BrowserVerifierProvider { await this.waitForWorker(this.workerSlot) } + derive(json, signal) { + return this.verify("derive", json, signal) + } + authentication(json, signal) { return this.verify("authentication", json, signal) } diff --git a/test/authentication.test.mjs b/test/authentication.test.mjs index d086a2e..a9a1df1 100644 --- a/test/authentication.test.mjs +++ b/test/authentication.test.mjs @@ -1,14 +1,15 @@ +import { encodeIndexLabel } from '../src/coordinate.mjs' import { describe, it, expect } from 'vitest' import { createAuthenticationVerification, verifyAuthenticationLocally } from '../src/index.mjs' -const profile = 'malt.authentication/1' +const profile = 'malt.authentication/3' const request = { profile, root: 'caller-root', operation: 'binding', steps: [], - input: { kind: 'index', number: '18446744073709551615' } } + label: encodeIndexLabel('18446744073709551615') } const result = { profile, resolved: 'caller-root', traversal: { steps: [] } } describe('typed authentication bridge', () => { it('preserves caller steps, opaque bytes and uint64 strings', async () => { - const source = { request: { ...request, steps: [{ kind: 'label', data: 'YS9iAA==' }] }, result } + const source = { request: { ...request, steps: ['YS9iAA=='] }, result } let received const provider = { authentication: async (json) => { received = JSON.parse(json) @@ -36,23 +37,23 @@ describe('typed authentication bridge', () => { }) it('binds path absence to the new request profile without reinterpreting steps', async () => { - const profile = 'malt.authentication/1' - const q = { ...request, profile, operation: 'resolve', input: undefined, - steps: [{ kind: 'label', data: 'bWlzc2luZw==' }] } + const profile = 'malt.authentication/3' + const q = { ...request, profile, operation: 'resolve', label: undefined, + steps: ['bWlzc2luZw=='] } const proof = { profile, resolved: '', absent_step: '0', traversal: { results: [] } } const provider = { authentication: async (json) => { expect(JSON.parse(json).request.profile).toBe(profile) return JSON.stringify({ profile, valid: true }) } } expect((await verifyAuthenticationLocally({ request: q, result: proof, provider })).valid).toBe(true) - expect((await verifyAuthenticationLocally({ request: q, result: { ...result, profile: 'malt.authentication/0' }, provider })).valid).toBe(false) + expect((await verifyAuthenticationLocally({ request: q, result: { ...result, profile: 'malt.authentication/2' }, provider })).valid).toBe(false) }) it('rejects the retired query profile before calling WASM', async () => { let called = false const checked = await verifyAuthenticationLocally({ - request: { ...request, profile: 'malt.authentication/0' }, - result: { ...result, profile: 'malt.authentication/0' }, + request: { ...request, profile: 'malt.authentication/2' }, + result: { ...result, profile: 'malt.authentication/2' }, provider: { authentication() { called = true; throw new Error('unexpected call') } } }) expect(checked.valid).toBe(false) diff --git a/test/coordinate.test.mjs b/test/coordinate.test.mjs new file mode 100644 index 0000000..d3f4c78 --- /dev/null +++ b/test/coordinate.test.mjs @@ -0,0 +1,48 @@ +import { describe, it, expect, vi } from 'vitest' +import * as verifier from '../src/verifier.mjs' +import { deriveCoordinate, encodeIndexLabel, encodeKeyLabel } from '../src/index.mjs' + +describe('client-facing coordinate derivation', () => { + it('encodes Direct indices losslessly as eight big-endian bytes', () => { + expect(encodeIndexLabel(42)).toBe('AAAAAAAAACo=') + expect(encodeIndexLabel(0n)).toBe('AAAAAAAAAAA=') + expect(encodeIndexLabel('18446744073709551615')).toBe('//////////8=') + for (const value of [-1, 1.5, NaN, 9007199254740992, '01', '1.0', true, 18446744073709551616n]) { + expect(() => encodeIndexLabel(value)).toThrow() + } + }) + it('accepts only exact Direct keys without mutating the input', () => { + const key = new Uint8Array(32).fill(7), encoded = encodeKeyLabel(key) + key[0] = 0 + expect(Uint8Array.from(atob(encoded), c => c.charCodeAt(0))).toEqual(new Uint8Array(32).fill(7)) + expect(() => encodeKeyLabel(new Uint8Array(31))).toThrow() + }) + it('delegates opaque labels to Core and preserves uint64 output', async () => { + const label = Uint8Array.from([255, 0, 47]), signal = new AbortController().signal + const provider = { derive: vi.fn(async () => '{"kind":"index","index":"18446744073709551615"}') } + expect(await deriveCoordinate({profile:3,label,signal,provider})).toEqual({kind:'index',index:18446744073709551615n}) + expect(provider.derive).toHaveBeenCalledWith('{"profile":3,"label":"/wAv"}',signal) + }) + it('captures each label before asynchronous verifier initialization', async () => { + let ready + const initialization = new Promise(resolve => { ready = resolve }) + const load = vi.spyOn(verifier, 'loadBrowserVerifier').mockReturnValue(initialization) + try { + const label = new Uint8Array(8) + const zero = deriveCoordinate({ profile: 3, label }) + label[7] = 1 + const one = deriveCoordinate({ profile: 3, label }) + label[7] = 2 + ready({ derive: async request => { + const bytes = Uint8Array.from(atob(JSON.parse(request).label), c => c.charCodeAt(0)) + return JSON.stringify({ kind: 'index', index: new DataView(bytes.buffer).getBigUint64(0, false).toString() }) + } }) + expect(await Promise.all([zero, one])).toEqual([{ kind: 'index', index: 0n }, { kind: 'index', index: 1n }]) + } finally { load.mockRestore() } + }) + it('rejects malformed Core replies and unsupported profiles', async () => { + for (const response of [{kind:'index',index:42},{kind:'index',index:'01'},{kind:'index',index:'18446744073709551616'},{kind:'key',key:'AA=='},{error:'unsupported profile'}]) { + await expect(deriveCoordinate({profile:3,label:new Uint8Array(8),provider:{derive:async()=>JSON.stringify(response)}})).rejects.toThrow() + } + }) +}) diff --git a/test/fixtures/portable-verifier-runtime.mjs b/test/fixtures/portable-verifier-runtime.mjs index 5badaf0..ab9dca4 100644 --- a/test/fixtures/portable-verifier-runtime.mjs +++ b/test/fixtures/portable-verifier-runtime.mjs @@ -4,7 +4,8 @@ globalThis.Go = class { importObject = {} run() { globalThis.maltVerifierLoadedBackend = 'all' - globalThis.maltVerifyAuthentication = () => '{"profile":"malt.authentication/1","valid":true}' + globalThis.maltDeriveCoordinate = () => '{"kind":"index","index":"0"}' + globalThis.maltVerifyAuthentication = () => '{"profile":"malt.authentication/3","valid":true}' globalThis.maltVerifierReady = true return new Promise(() => {}) } diff --git a/test/public-api.ts b/test/public-api.ts index dbc8a08..b0e0034 100644 --- a/test/public-api.ts +++ b/test/public-api.ts @@ -16,7 +16,7 @@ void maltWasmAssetsDirectory() void versionedWasmAssetsPlugin() const lease = createBrowserVerifierLease() void loadBrowserVerifier({ lease }).then(() => releaseBrowserVerifier(lease)) -void verifyAuthenticationLocally({ request: { profile: 'malt.authentication/1', root: 'root', operation: 'resolve', steps: [] }, result: {} }) +void verifyAuthenticationLocally({ request: { profile: 'malt.authentication/3', root: 'root', operation: 'resolve', steps: [] }, result: {} }) void createBrowserMaltWriter({ ipaPreference: 'auto' }) void createBrowserMaltWriter({}).then(async writer => { @@ -34,5 +34,5 @@ void createBrowserMaltWriter({}).then(async writer => { }) // @ts-expect-error retired query profiles are not accepted by the public verifier -const retiredQuery: import("../types/verifier").AuthenticationRequest = { profile: "malt.authentication/0", root: "root", operation: "resolve", steps: [] } +const retiredQuery: import("../types/verifier").AuthenticationRequest = { profile: "malt.authentication/2", root: "root", operation: "resolve", steps: [] } void retiredQuery diff --git a/test/verifier-worker.test.mjs b/test/verifier-worker.test.mjs index 2cbe60f..57344e6 100644 --- a/test/verifier-worker.test.mjs +++ b/test/verifier-worker.test.mjs @@ -26,7 +26,7 @@ it('starts with only typed exports and rejects the retired artifact operation', worker.postMessage({ type: 'verify', id: 2, kind: 'authentication', json: '{}' }) expect((await current)[0]).toEqual({ type: 'result', id: 2, - result: '{"profile":"malt.authentication/1","valid":true}' + result: '{"profile":"malt.authentication/3","valid":true}' }) } finally { await worker.terminate() diff --git a/test/verifier.test.mjs b/test/verifier.test.mjs index 0cc76cc..4d2f994 100644 --- a/test/verifier.test.mjs +++ b/test/verifier.test.mjs @@ -9,12 +9,12 @@ function typedRoot(codec, size) { function verification(from) { return JSON.stringify({ request: { - profile: 'malt.authentication/1', + profile: 'malt.authentication/3', root: from, - operation: 'resolve', steps: [{ kind: 'label', data: 'ZG9jcw==' }] + operation: 'resolve', steps: ['ZG9jcw=='] }, result: { - profile: 'malt.authentication/1', + profile: 'malt.authentication/3', resolved: from, traversal: { results: [] } } }) @@ -173,14 +173,14 @@ describe('browser verifier workers', () => { wasmURL: '/verifier/verifier-workers-b.wasm' }) const [portableWorker] = FakeVerifierWorker.instances - const kzgRoot = typedRoot(0x300101, 48) + const kzgRoot = typedRoot(0x300104, 48) const kzgResult = await verifyAuthenticationLocally({ ...JSON.parse(verification(kzgRoot)), provider }) expect(kzgResult.valid).toBe(true) - const ipaRoot = typedRoot(0x300101, 32) + const ipaRoot = typedRoot(0x300104, 32) const mixedInput = JSON.parse(verification(kzgRoot)) mixedInput.result.resolved = ipaRoot const mixed = JSON.stringify(mixedInput) @@ -295,7 +295,7 @@ describe('browser verifier workers', () => { releaseBrowserVerifier(secondOldLease) expect(replacementWorkers.every((worker) => !worker.terminated)).toBe(true) - await expect(replacement.authentication(verification(typedRoot(0x300101, 48)))) + await expect(replacement.authentication(verification(typedRoot(0x300104, 48)))) .resolves.toContain('"valid":true') releaseBrowserVerifier(replacementLease) @@ -304,7 +304,7 @@ describe('browser verifier workers', () => { it('passes an absent typed binding and the unchanged selected input to Core', async () => { const { verifyAuthenticationLocally } = await import('../src/verifier.mjs') - const q = { profile: 'malt.authentication/1', root: typedRoot(0x300101, 48), steps: [], operation: 'binding', input: { kind: 'label', data: 'bWlzc2luZw==' } } + const q = { profile: 'malt.authentication/3', root: typedRoot(0x300104, 48), steps: [], operation: 'binding', label: 'bWlzc2luZw==' } const result = { profile: q.profile, resolved: q.root, binding: { present: false }, traversal: { results: [] } } const provider = { authentication: vi.fn(async (json) => { expect(JSON.parse(json)).toEqual({ request: q, result }) @@ -316,11 +316,11 @@ describe('browser verifier workers', () => { it('keeps function providers receiver-free', async () => { const { verifyAuthenticationLocally } = await import('../src/verifier.mjs') - const root = typedRoot(0x300101, 48) + const root = typedRoot(0x300104, 48) let receiver = 'not-called' function provider() { receiver = this - return JSON.stringify({ profile: 'malt.authentication/1', valid: true }) + return JSON.stringify({ profile: 'malt.authentication/3', valid: true }) } const result = await verifyAuthenticationLocally({ @@ -410,12 +410,12 @@ describe('browser verifier workers', () => { firstPortable.emit({ type: 'runtime-error', error: 'simulated runtime failure' }) expect(firstPortable.terminated).toBe(true) - const kzgRoot = typedRoot(0x300101, 48) + const kzgRoot = typedRoot(0x300104, 48) await expect(provider.authentication(verification(kzgRoot))) .resolves.toContain('"valid":true') expect(FakeVerifierWorker.instances[1].backend).toBe('all') - const ipaRoot = typedRoot(0x300101, 32) + const ipaRoot = typedRoot(0x300104, 32) await expect(provider.authentication(verification(ipaRoot))) .resolves.toContain('"valid":true') expect(FakeVerifierWorker.instances).toHaveLength(2) @@ -434,11 +434,11 @@ describe('browser verifier workers', () => { .rejects.toThrow('simulated verification result error') const controller = new AbortController() controller.abort() - await expect(provider.authentication(verification(typedRoot(0x300101, 48)), controller.signal)) + await expect(provider.authentication(verification(typedRoot(0x300104, 48)), controller.signal)) .rejects.toMatchObject({ name: 'AbortError' }) await vi.waitFor(() => expect(FakeVerifierWorker.instances).toHaveLength(1)) - await expect(provider.authentication(verification(typedRoot(0x300101, 32)))) + await expect(provider.authentication(verification(typedRoot(0x300104, 32)))) .resolves.toContain('"valid":true') expect(FakeVerifierWorker.instances).toHaveLength(1) }) @@ -457,10 +457,10 @@ describe('browser verifier workers', () => { expect(FakeVerifierWorker.instances.every((worker) => worker.terminated)).toBe(true) const provider = await loadBrowserVerifier(options) - const kzgRoot = typedRoot(0x300101, 48) + const kzgRoot = typedRoot(0x300104, 48) await expect(provider.authentication(verification(kzgRoot))) .resolves.toContain('"valid":true') - const ipaRoot = typedRoot(0x300101, 32) + const ipaRoot = typedRoot(0x300104, 32) await expect(provider.authentication(verification(ipaRoot))) .resolves.toContain('"valid":true') expect(FakeVerifierWorker.instances).toHaveLength(3) @@ -487,7 +487,7 @@ describe('browser verifier workers', () => { error: 'simulated runtime failure' }) await vi.waitFor(() => expect(beforeWorkerStart).toHaveBeenCalledTimes(2)) - await expect(provider.authentication(verification(typedRoot(0x300101, 48)))) + await expect(provider.authentication(verification(typedRoot(0x300104, 48)))) .rejects.toBe(releaseChanged) await Promise.resolve() diff --git a/test/writer.test.mjs b/test/writer.test.mjs index 904b9d5..6457848 100644 --- a/test/writer.test.mjs +++ b/test/writer.test.mjs @@ -696,7 +696,7 @@ it('routes retained authentication operations without sending a complete base ag }) const state = new TextEncoder().encode('{}') const internalHandle = new TextEncoder().encode('1') - const delta = new TextEncoder().encode('{"profile":"malt.authentication-delta/0","changes":[]}') + const delta = new TextEncoder().encode('{"profile":"malt.authentication-delta/1","changes":[]}') const created = JSON.parse(await writer.createAuthentication('kzg', state)) const handle = new TextEncoder().encode(created.handle) await writer.applyAuthentication('kzg', handle, delta) diff --git a/types/coordinate.d.ts b/types/coordinate.d.ts new file mode 100644 index 0000000..d1eb9e0 --- /dev/null +++ b/types/coordinate.d.ts @@ -0,0 +1,9 @@ +/** Canonical base64 label for a Direct uint64 coordinate. */ +export declare function encodeIndexLabel(index: bigint | number | string): string +/** Canonical base64 label for a Direct 32-byte coordinate. */ +export declare function encodeKeyLabel(key: Uint8Array): string + +export type Coordinate = { kind: 'key'; key: Uint8Array } | { kind: 'index'; index: bigint } +export declare function deriveCoordinate(options: import('./verifier.js').VerifierLoadOptions & { + profile: number; label: Uint8Array; provider?: import('./verifier.js').BrowserVerifierProvider +}): Promise diff --git a/types/index.d.ts b/types/index.d.ts index 59f992a..688dcb1 100644 --- a/types/index.d.ts +++ b/types/index.d.ts @@ -1,3 +1,5 @@ export * from './release.js' export * from './verifier.js' export * from './writer.js' + +export * from './coordinate.js' diff --git a/types/release.d.ts b/types/release.d.ts index 1e28c02..f76eab7 100644 --- a/types/release.d.ts +++ b/types/release.d.ts @@ -1,8 +1,8 @@ -export declare const maltTSVersion: '0.0.2' +export declare const maltTSVersion: '0.0.3-rc.1' export interface MaltCoreRelease { - readonly version: 'v0.0.9' - readonly commit: 'e389418cf6715ae58a97255196833b410b0962d1' + readonly version: 'v0.0.10-rc.1' + readonly commit: '933ef9824d5d852f819bdc91b244ce7b7e800706' readonly moduleSum: string readonly goModSum: string } diff --git a/types/verifier.d.ts b/types/verifier.d.ts index ab78bbe..4eb8f99 100644 --- a/types/verifier.d.ts +++ b/types/verifier.d.ts @@ -8,6 +8,7 @@ export interface VerificationResult extends JSONRecord { } export interface BrowserVerifierProvider { + derive(json: string, signal?: AbortSignal): Promise authentication(json: string, signal?: AbortSignal): Promise terminate(): void } @@ -40,21 +41,17 @@ export declare function loadBrowserVerifier(options?: VerifierLoadOptions): Prom export declare function releaseBrowserVerifier(lease: VerifierLease): void /** uint64 decimal strings and base64 bytes follow the normative Core schema. */ -export type AuthenticationInput = - | { kind: 'index'; number: string } - | { kind: 'system'; number: string } - | { kind: 'key'; data: string } - | { kind: 'label'; data: string } +export type AuthenticationLabel = string export interface AuthenticationRequest extends JSONRecord { - profile: 'malt.authentication/1' + profile: 'malt.authentication/3' root: string - steps?: AuthenticationInput[] | null + steps?: AuthenticationLabel[] | null operation: 'resolve' | 'binding' | 'range' - input?: AuthenticationInput + label?: AuthenticationLabel start?: string end?: string } -export declare const authenticationPathVerifierProfile: 'malt.authentication/1' +export declare const authenticationPathVerifierProfile: 'malt.authentication/3' export declare function createAuthenticationVerification(options: { request: AuthenticationRequest; result: JSONRecord }): JSONRecord