@majikah/majik-signature
v1.6.0
Published
Hybrid post-quantum content signing and verification for the Majikah ecosystem, combining Ed25519 and ML-DSA-87 (FIPS 204) with file embedding, detached envelopes, and batch manifests.
Downloads
1,994
Maintainers
Readme
Majik Signature
Majik Signature is a hybrid post-quantum content signing and verification library for the Majikah ecosystem. Built on top of Majik Key, it produces tamper-evident, forgery-resistant digital signatures for any content — plaintext, JSON, PDFs, audio, video, Office documents, or raw binary — using a dual-algorithm architecture that combines classical Ed25519 with post-quantum ML-DSA-87 (FIPS-204).
Beyond signing raw bytes, Majik Signature can embed signatures directly into a file's native format or produce detached envelopes that travel independently of the file. Envelopes can be represented as JSON, the existing Base64 serialization format, CBOR bytes, or a dedicated self-describing binary container (.mjksig). The current .mjksig writer uses version 2 with CBOR, while the reader retains support for legacy version 1 JSON containers. Newly embedded envelopes use a version-marked, Base64-wrapped CBOR representation, while existing files with legacy JSON-encoded embedded envelopes remain readable. New .mjksmap containers use version 2 with CBOR-native byte strings for content hashes and nested envelope cryptographic fields; the reader continues to accept legacy version 1 JSON manifests. The SDK also supports multi-party signing, signing allowlists, envelope sealing, trusted timestamps (TSA), batch/folder signing via the .mjksmap manifest format, chronological signing-order verification, and blockchain anchor registration.
Table of Contents
- Majik Signature
- Table of Contents
- Why Majik Signature
- Security Architecture
- Overview
- Features
- Installation
- Command-Line Interface
- Quick Start
- API Reference
- Content Signing (bytes/strings)
MajikSignature.sign(content, key, options?)MajikSignature.verify(content, signature, publicKeys)MajikSignature.verifyWithKey(content, signature, key)MajikSignature.publicKeysFromMajikKey(key)signature.extractPublicKeys()(instance method)signature.validate()/signature.isValid()MajikSignature.fromJSON(json)/MajikSignature.deserialize(base64)
- File Embedding API
- Detached Signing & MajikSignatureEnvelope API
- Multi-Signature & Allowlist API
MajikSignature.expectedSignerFromKey(key)MajikSignature.getAllowlist(file, options?)MajikSignature.canSign(file, key, options?)MajikSignature.getSignatories(file, options?, filter?)MajikSignature.getIssuer(file, options?)MajikSignature.getEnvelopeInfo(file, options?)MajikSignature.isMultiSig(file, options?)
- Sealing API
- Trusted Timestamps API
- SignRoom Session-Bound Signing
- Batch Signing & MajikSignatureMap API
- Resource and untrusted-input limits
- Signature Order Verification API
- Chain Anchoring API (Experimental)
- File Versioning API
- Image Stamping (Experimental)
- Serialization
signature.toJSON()/MajikSignature.fromJSON(json)signature.serialize()/MajikSignature.deserialize(base64)envelope.toJSON()/MajikSignatureEnvelope.fromJSON(json)envelope.serialize()/MajikSignatureEnvelope.deserialize(base64)envelope.toMJKSIG()/MajikSignatureEnvelope.fromMJKSIG(input)signature.toCBOR()/MajikSignature.fromCBOR(bytes)envelope.toCBOR()/MajikSignatureEnvelope.fromCBOR(bytes)
- Content Signing (bytes/strings)
- Supported File Formats
- Signature & Envelope Structure
- Binary Container Formats (MJKSIG / MJKSMAP)
- Error Handling
- Security Considerations
- The Majikah Ecosystem
- Related Projects
- Contributing
- License
- Author
- Contact
Why Majik Signature
Most "digital signature" libraries only sign raw bytes and leave you to figure out storage, transport, and file compatibility yourself. Majik Signature is built to be dropped into a real application:
- Hybrid post-quantum by default — every signature is Ed25519 + ML-DSA-87, not an opt-in extra.
- Signatures live inside the file, or travel detached — embed directly into the file's native format, or produce a portable envelope as JSON, Base64, raw CBOR bytes, or a versioned
.mjksigbinary container. Legacy JSON representations remain supported for backward compatibility. - Multi-party signing is a first-class concept — not bolted on. Allowlists, sealing, issuer semantics, and chronological order verification are part of the core envelope model.
- Batch-aware — sign or verify an entire folder or zip's contents against a single manifest (
.mjksmap) instead of tracking one signature file per asset. - Deterministic by design — canonical payload construction is deterministic for the same signer and signed metadata (including timestamp and optional policy fields) (see Signature & Envelope Structure).
- TypeScript-first API — core workflows use JavaScript/TypeScript dependencies and Web-standard binary APIs; no native add-on is required for the core signing path.
cbor-xmay use optional platform-specific acceleration when available. The CLI runs on Node.js 22.12+.
Security Architecture
flowchart TD
A[12/24-word BIP-39 Seed Phrase] --> B[Majik Key]
%% Signing branch
B --> S[Signing]
S --> S1[Ed25519]
S --> S2[ML-DSA-87]
%% Identity branch
B --> I[Identity]
I --> I1[BIP-39]
I --> I2[X25519]
%% Products (fan-in)
S1 --> P1[Majik Signature]
S2 --> P11. Hybrid Dual-Algorithm Signing
Every Majik Signature is produced by two independent signing algorithms over the same canonical payload:
- Ed25519 — classical elliptic curve signature (128-bit security, 64-byte signature)
- ML-DSA-87 (FIPS-204) — post-quantum lattice-based signature (NIST Category 5, ~4627-byte signature)
Verification requires both to pass. This means:
- A classical attacker breaking Ed25519 still cannot forge the ML-DSA-87 signature.
- A quantum attacker breaking ML-DSA-87 still cannot forge the Ed25519 signature.
- No single algorithmic break is sufficient to forge a valid signature.
2. Canonical Payload Binding
Both signatures cover a domain-separated canonical payload:
"majik-signature-v1:" + JSON({ v, id, ts, ct, hash[, alh][, vu][, vch][, sch] })| Field | Description |
| ------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| v | Envelope version |
| id | Signer fingerprint (MajikKey identity) |
| ts | ISO 8601 timestamp |
| ct | Content type (advisory, or null) |
| hash | SHA-256 of the original content, base64 |
| alh | SHA-256 of the canonical allowlist, base64 — present only when this signer is establishing an allowlist |
| vu | Optional ISO 8601 expiry. When present, verify() treats the signature as invalid once the current time is past this value. Absent = never expires (matches all pre-existing signatures — fully backward compatible). Covered by the canonical signing payload when present, so it cannot be stripped or extended post-hoc without breaking both signatures. |
| vch | SHA-256 of the fileVersions revision chain, Base64 — present only when file versioning is in use; commits the signer to the chain state at their turn. |
| sch | SHA-256 commitment to a SignRoom session, one-time challenge, and immutable policy snapshot; present only for session-bound signing. |
alh is omitted entirely (not set to null) on every signature that isn't establishing an allowlist. This is a deliberate backward-compatibility guarantee: every signature produced before multi-sig support existed still verifies today, because its payload bytes are unchanged.
This binding means a valid signature cannot be reused on different content, transferred to a different signer, replayed with a modified timestamp, or forged without both private keys.
Serialization compatibility note: CBOR is used for encoding and transporting signature and envelope data; it does not replace or redefine the canonical payload used by the signing algorithms. The canonical signing payload remains domain-separated using majik-signature-v1: and the established canonical JSON representation. Container versions describe the serialization of the stored envelope, not a change to the underlying signing algorithms or signature schema. This separation allows the SDK to adopt CBOR while retaining verification compatibility with existing signatures.
3. Content-Agnostic Hashing
Content is never embedded in the envelope — only its SHA-256 hash is signed. Hashing remains linear in the number of input bytes. Once the SHA-256 digest is available, the hybrid signature operation works on that fixed-size digest, so its cryptographic cost does not grow with the original file size. Use the streaming APIs to bound memory while hashing large inputs.
4. File Embedding & Detachment Integrity
When a signature is embedded into a file, it always covers the original file bytes before embedding. Verification strips the embedded envelope before re-hashing, so the round-trip is always:
sign(originalBytes) → embed into file → extract → strip → verify(originalBytes)The same guarantee applies to detached signing: signFileDetached() signs the clean, stripped bytes and returns them alongside the envelope — the envelope and the file travel separately, but verification always strips the file first, so an accidentally-still-embedded envelope never double-counts or corrupts the hash.
Re-signing (or re-embedding) the same file is always safe — the existing envelope is stripped before the new one is written, so signatures never stack or corrupt each other.
5. Multi-Party Signing, Allowlists & Sealing
Files don't hold a single signature — they hold a MultiSigEnvelope (modeled at runtime by the MajikSignatureEnvelope class): an array of per-signer envelopes, plus optional allowlist, seal, and chain-anchor metadata.
- Open signing (default): anyone with a
MajikKeycan add a signature. - Restricted signing: the first signer may supply an
expectedSignersallowlist. That allowlist is cryptographically committed to viaallowlistHashin the issuer's own canonical payload — tampering with the allowlist after the fact breaks the issuer's signature. Non-listed signers are rejected before any cryptographic operation runs. - Sealing: the issuer (and only the issuer) can seal an envelope, computing a SHA3-512 hash over every current signatory plus a seal timestamp, domain-separated with
"majik-seal-v1:". A sealed envelope rejects all further signing attempts — including from the issuer.
6. File Versioning for Visually-Mutating Multi-Sig Workflows
Ordinary multi-sig assumes every signer signs the same underlying bytes. That breaks when signing also means visually stamping the document — each signer's stamp changes the file's content, so the next signer is working from different bytes than the one before them.
signFile()'s priorSignedFile option handles this: pass the file as it was received (carrying the prior signer's envelope), and the library verifies that prior envelope is genuinely valid before extending it with a new FileVersion revision entry, cryptographically bound via versionChainHash — see File Versioning & Multi-Sig Revisions.
7. Trusted Timestamps (TSA)
A MajikSignature can optionally carry a MajikTimestamp signed by a timestamp authority over the majikah-tsa-v-1: canonical payload, which binds a digest, nonce, and TSA timestamp. Legacy/content-scoped tokens attest to the document contentHash; signature-scoped tokens use buildTSARequestPayload("signature") to attest to the specific unsigned signer record, including its keys and signed metadata. The TSA token is itself a hybrid Majik Signature. When TSA provenance matters, pass an independently trusted TSA public-key bundle to addTSA() and verifyTSA(); verification against the token's embedded key alone proves internal consistency, not authoritative TSA identity. TSA timestamps can support attested signing-order verification.
8. Chain Anchoring
A sealed envelope's seal hash can be committed to an external blockchain (handled by a companion product, e.g. majik-notary) and the resulting confirmed anchor registered back into the envelope via MajikChainAnchor records. The SDK does not talk to any chain itself — it only builds the canonical memo to anchor (buildChainAnchorMemo()) and embeds/reads already-confirmed anchors. Anchoring requires the envelope to already be sealed.
Overview
What is a Majik Signature?
A Majik Signature is cryptographic evidence that a specific content digest was signed by the private keys corresponding to a specific Majik Key. It combines Ed25519 with the NIST-standardized post-quantum ML-DSA-87 algorithm. This hybrid design is intended to retain forgery resistance if one algorithm is weakened, provided the other remains secure; it cannot guarantee security against every future cryptanalytic advance.
Verification is fully public — anyone with the signer's public keys can verify. No private key is ever needed for verification.
Use Cases
- Content Provenance — prove that music, art, a document, or a dataset was produced by a specific identity.
- File Integrity — detect any tampering or modification to distributed files.
- API Payload Signing — sign JSON requests/responses for non-repudiation.
- Document Authentication — certify contracts, legal records, or invoices, with support for multiple independent signers, chronological approval order, and a final seal.
- Media Certification — stamp audio, video, or image files as authentic originals, with the signature embedded directly in the file.
- Software Distribution — sign release artifacts to prove they come from the original author.
- Identity-Bound Messaging — bind signed content to a verifiable identity across the Majikah ecosystem.
- Batch Asset Signing — sign every file in a folder, project export, or zip archive against a single manifest, resilient to files being renamed or relocated afterward.
- Approval Workflows — verify not just who signed a contract, but that they signed it in the required order (e.g. legal before finance, requester before approver).
Features
Security & Post-Quantum Readiness
- Hybrid signatures — Ed25519 (classical) + ML-DSA-87 (post-quantum, FIPS-204, Category 5); both must verify
- Tamper detection — SHA-256 content hash is bound inside the signed payload; any byte change invalidates both signatures
- Domain separation — distinct prefixes for signing (
majik-signature-v1:), sealing (majik-seal-v1:), TSA payloads (majikah-tsa-v-1:), signature-scoped TSA digests (majik-signature-attestation-v1:), SignRoom context hashes (majik-signature-session-context-v1:), and chain anchoring (majik-notary-v-1:) separate protocol purposes - Signer & timestamp binding — both are part of the signed payload; neither can be altered or transferred after signing
- No private key for verification — pure public-key verification, safe to run anywhere
Multi-Party Signing
- Multi-signature envelopes — any number of independent signers on one file, modeled by the immutable
MajikSignatureEnvelopeclass - Signing allowlists — restrict who may sign, enforced before any cryptographic operation
- Cryptographically committed allowlists — tampering with the allowlist invalidates the issuer's signature
- Sealing — the issuer can permanently lock an envelope against further signatures
- Chronological order verification — verify that signers signed in a required sequence, with TSA-attested timestamps preferred over self-reported ones, and a strict mode to reject unexpected extra signers
- Status queries —
getSignatories(),getIssuer(),getEnvelopeInfo(),canSign()for building signing-status UI without manually walking the envelope
Detached Signing & Batch Workflows
- Detached envelopes — sign a file and receive the envelope separately, for external verification pipelines where payload and signature travel independently
- Self-describing binary containers —
.mjksigfor a single detached envelope,.mjksmapfor a manifest covering an entire batch, each with magic bytes, a version header, and a length-prefixed payload - Batch signing — sign every file in a folder or zip in one call, packaged as one
.mjksmapmanifest or as separate.mjksigfiles per asset - Relocation-tolerant batch verification — a file renamed or moved after signing is still found and verified by content hash, not just by its original path
- Per-file batch verification reporting —
verified/invalid/tampered/not_in_mapstatus per file, plus a one-glance summary
Content Format Support
- Plain text, JSON, binary —
Uint8Arrayorstring - PDF — signature appended as a spec-compliant binary trailer after the file's
%%EOF - PNG — embedded in an
iTXtmetadata chunk - WAV — embedded in a RIFF
LIST INFOchunk - MP3 — embedded in an ID3v2
TXXXframe - MP4, MOV, M4A, M4V — embedded in the
moov/udtabox, custommajkbox type - DOCX, XLSX, PPTX, ODT, ODS, ODP — embedded as a dedicated entry inside the ZIP container
- MKV, WebM — embedded via a custom Matroska metadata tag
- JPEG, FLAC — native format metadata, same round-trip guarantees as other handlers
- HTML, Markdown, JSON, plain text, source code — embedded as an appended, format-appropriate metadata block
- Any other format — universal binary trailer:
[original bytes][version-marked embedded-envelope payload][8-byte length][8-byte magic]. New writes use the embedded CBOR codec; legacy JSON payloads remain supported when reading existing files.
See Supported File Formats for the full handler table.
Developer Experience
- First-class TypeScript support — full type definitions for every interface and class
- Simple core API —
sign()/verify()for bytes and strings;signFile()/verifyFile()for embedded files;signFileDetached()/verifyFileDetached()for detached workflows - One-liner file signing —
MajikSignature.signFile(blob, key)signs and embeds in a single call - Format auto-detection — MIME type and magic-byte sniffing, no manual format hints required in most cases
- Idempotent re-signing — safely re-sign or re-embed any file without accumulating stacked or orphaned envelopes
- Immutable envelope model —
MajikSignatureEnvelopeandMajikSignatureMapare both immutable; every mutation returns a new instance - Typed error hierarchy — precise, catchable error classes instead of generic exceptions
- Modern JavaScript runtimes — the core APIs use standard byte/binary and Web APIs. Automated CI validates Node.js 22 and 24; browser, Tauri, Deno, and Bun integrations should be tested in their target host. No native binding is required for the core API; CBOR acceleration packages may be used optionally when available.
Serialization & Portability
- JSON serialization —
toJSON()/fromJSON()remain supported for signatures and envelopes, including legacy envelope shapes. - Base64 serialization —
serialize()/deserialize()remain available for the SDK's existing Base64 transport format. - CBOR serialization —
toCBOR()/fromCBOR()provide binary CBOR serialization for signatures and envelopes. - File-embedded envelopes — newly written embedded envelopes use a version-marked, Base64-wrapped CBOR payload through the existing file-format handlers. Legacy JSON-encoded embedded envelopes remain readable.
- Versioned
.mjksigcontainers — new containers use version 2 with CBOR; version 1 JSON containers remain supported for backward compatibility. - CBOR
.mjksmapmanifests — new batch containers use version 2 and store SHA-256 hashes, public keys, signatures, and other binary envelope fields as raw CBOR byte strings; version 1 JSON manifests remain readable. - Self-contained envelopes — envelopes carry the signer's public keys so verification can run without a separate key registry.
- Portable binary containers —
.mjksigand.mjksmapsupport detached-envelope and batch-manifest storage as standalone files.
Installation
npm install @majikah/majik-signature
# Optional: add this only when your application imports Majik Key directly
npm install @majikah/majik-keyThe core API targets modern JavaScript runtimes that provide the standard binary and Web APIs used by the selected feature. The CLI is Node.js-only and requires Node.js 22.12 or newer. The CI matrix validates Node.js 22 and 24.
Command-Line Interface
mjksig — Sign, Verify, Seal, Inspect
Majik Signature includes a full-featured CLI for working with signed files directly from your terminal.
The mjksig CLI supports:
- Embedded and detached signing
- MJKSMAP folder signing and verification
- Multi-signature allowlists and co-signing
- Envelope sealing
- Signing-permission checks
- Signature inspection
- Batch workflows
- Machine-readable
--jsonoutput - Interactive and non-interactive signing-key passphrases
Run with npx
No global installation required:
npx @majikah/majik-signature --helpSign a file:
npx @majikah/majik-signature sign report.pdf --key alice.jsonVerify a file:
npx @majikah/majik-signature verify report.pdfOr install globally and use the mjksig command directly:
npm install -g @majikah/majik-signaturemjksig --helpFor automation and CI environments, signing-key passphrases can be supplied through MAJIK_KEY_PASSPHRASE.
CLI Documentation
For the complete command reference, workflow combinations, options, compatibility rules, examples, exit codes, automation guidance, and npx usage, see:
Quick Start
Signing Raw Content
import { MajikKey } from '@majikah/majik-key';
import { MajikSignature, CONTENT_TYPES } from '@majikah/majik-signature';
// Step 1 — create and unlock a MajikKey
const mnemonic = MajikKey.generateMnemonic();
const key = await MajikKey.create(mnemonic, 'my-passphrase', 'My Signing Key');
// Step 2 — sign content
const document = 'This is the original content of my document.';
const signature = await MajikSignature.sign(document, key, {
contentType: CONTENT_TYPES.TEXT,
});
console.log('Signer ID:', signature.signerId);
console.log('Content Hash:', signature.contentHash);
console.log('Timestamp:', signature.timestamp);
// Step 3 — serialize for storage or transport
const serialized = signature.serialize(); // base64 string
// Step 4 — verify (no private key needed)
const publicKeys = MajikSignature.publicKeysFromMajikKey(key);
const result = MajikSignature.verify(document, signature, publicKeys);
console.log('Valid:', result.valid);
// Shorthand — verify directly against a MajikKey (works even if locked)
const result2 = MajikSignature.verifyWithKey(document, signature, key);File Embedding
import { MajikSignature } from '@majikah/majik-signature';
// Sign a file and embed the signature into it
const { blob: signedBlob } = await MajikSignature.signFile(file, key);
// signedBlob is the same format as file — PDF stays PDF, WAV stays WAV, etc.
// Verify — returns one VerificationResult PER SIGNER
const results = await MajikSignature.verifyFile(signedBlob, key);
const allValid = results.every((r) => r.valid);
console.log('All signatures valid:', allValid);
console.log('Signed by:', results.map((r) => r.signerId));
// Check if a file is signed, without verifying
const signed = await MajikSignature.isSigned(file);
// Extract embedded signatures as typed instances — always an array
const sigs = await MajikSignature.extractFrom(signedBlob);
for (const sig of sigs) {
console.log(sig.signerId, sig.timestamp, sig.contentHash);
}
// Get the original clean file back (signature removed)
const originalBlob = await MajikSignature.stripFrom(signedBlob);Note:
verifyFile()andextractFrom()return arrays, not single values — a file may carry more than one signature. Legacy single-signature files still return a one-item array, so existing call sites that only readresults[0]continue to work.
Detached Signing
Use detached signing when the signature envelope needs to travel independently of the file — for example, storing envelopes in a database while files sit in blob storage, or verification pipelines that never touch the original file storage layer.
import { MajikSignature } from '@majikah/majik-signature';
// Sign — returns the clean file bytes AND the envelope, separately
const { blob, envelope, signature } = await MajikSignature.signFileDetached(file, aliceKey);
// The envelope can be stored/transported however you like:
const envelopeJson = envelope.toJSON();
const envelopeB64 = envelope.serialize();
const envelopeBinary = envelope.toMJKSIG(); // a portable .mjksig Blob
// Verify later, against the same clean file bytes + the detached envelope
const results = await MajikSignature.verifyFileDetached(blob, envelope, aliceKey);
console.log('Valid:', results.every((r) => r.valid));
// Multiple signers can be added to the same detached envelope before it's ever embedded
const { envelope: envelope2 } = await MajikSignature.signFileDetached(blob, bobKey, {
existingEnvelope: envelope, // continue from Alice's envelope
});You can attach a Trusted Timestamp to a detached signature in the same call:
const { envelope, signature } = await MajikSignature.signFileDetached(file, aliceKey, {
tsa: myTsaTimestamp,
});
console.log(signature.hasTSA); // trueMulti-Signature Files & Allowlists
import { MajikSignature } from '@majikah/majik-signature';
// Alice signs first and restricts who else may sign
const { blob: step1 } = await MajikSignature.signFile(file, aliceKey, {
expectedSigners: [
MajikSignature.expectedSignerFromKey(aliceKey),
MajikSignature.expectedSignerFromKey(bobKey),
],
});
// Bob signs — allowed, he's on the allowlist
const { blob: step2 } = await MajikSignature.signFile(step1, bobKey);
// Someone not on the allowlist — rejected before any crypto runs
try {
await MajikSignature.signFile(step2, eveKey);
} catch (err) {
// MajikSignatureAllowlistError
}
// Check status without signing
const { permitted, reason } = await MajikSignature.canSign(step2, eveKey);
// Inspect who has signed and who is still pending
const { signed, pending } = await MajikSignature.getSignatories(step2);
console.log('Pending:', pending.map((s) => s.signerId));Sealing an Envelope
Only the issuer (the signer who established the allowlist) can seal a file, and only once every intended signer's status is where you want it to be.
import { MajikSignature } from '@majikah/majik-signature';
// Alice (the issuer) seals the file — no further signatures accepted after this
const { blob: sealed, sealInfo } = await MajikSignature.seal(step2, aliceKey);
console.log('Sealed at:', sealInfo.sealTimestamp);
// Anyone can verify the seal itself (structural — not the individual signatures)
const sealResult = await MajikSignature.verifySeal(sealed);
console.log('Seal valid:', sealResult.valid, 'sealed by:', sealResult.sealedBy);
// Still verify the underlying cryptographic signatures separately
const sigResults = await MajikSignature.verifyFile(sealed, aliceKey);Trusted Timestamps (TSA)
TSA support works at the signature-object level, independent of file embedding. A TSA server signs a canonical payload binding either the document digest (legacy/content scope) or the canonical unsigned signer record (signature scope) to a nonce and TSA timestamp; you attach the resulting MajikTimestamp to your own signature.
import { MajikSignature } from '@majikah/majik-signature';
// Client side — build the request payload from an existing signature
const signature = await MajikSignature.sign(document, key);
// Choose "signature" to bind this TSA token to the complete signer record.
const tsaRequest = signature.buildTSARequestPayload("signature");
// Send tsaRequest to your TSA server, receive back a MajikTimestamp...
// (server side, using a TSA-controlled MajikKey)
const timestamp = await MajikSignature.signTSA(
tsaRequest,
tsaKey,
{ id: 'tsa.majikah.solutions', signerFingerprint: tsaKey.fingerprint },
);
// Client pins the TSA to an independently trusted key before attaching it
const trustedTsaPublicKeys = MajikSignature.publicKeysFromMajikKey(tsaKey);
signature.addTSA(timestamp, trustedTsaPublicKeys); // checks token/digest and expected TSA fingerprint
console.log('Has TSA:', signature.hasTSA);
console.log('TSA still valid:', signature.verifyTSA().valid);Batch Signing a Folder
Sign every file in a folder, project export, or zip's contents in one call, packaged as a single manifest.
import { MajikSignature } from '@majikah/majik-signature';
const result = await MajikSignature.signBatchDetached(
[
{ path: 'docs/report.pdf', blob: reportBlob },
{ path: 'docs/appendix.pdf', blob: appendixBlob },
{ path: 'assets/cover.png', blob: coverBlob },
],
aliceKey,
);
if (result.mode === 'map') {
// result.map is a MajikSignatureMap instance; result.mapBlob is a ready-to-store .mjksmap Blob
zip.file('signatures.mjksmap', await result.mapBlob.arrayBuffer());
}
// Later — verify an extracted batch against the manifest
const map = await MajikSignatureMap.fromMJKSMAP(mapBlob);
const results = await MajikSignature.verifyFilesFromMjksMap(
map,
extractedFiles, // { path, blob }[]
publicKeys,
);
const summary = MajikSignature.summarizeBatchVerification(results);
console.log(`${summary.verified}/${summary.total} verified`);
if (!summary.allValid) {
for (const r of results) {
if (r.status !== 'verified') console.log(r.path, r.status, r.reason);
}
}A batch-verified file that was renamed or moved after signing is still resolved correctly — matched by content hash and reported with relocatedFrom set to its original path, rather than showing up as missing.
Verifying Signing Order
Beyond confirming who signed a file, you can confirm they signed in a required sequence — e.g. "Bob must sign before Dave." TSA-attested timestamps are preferred automatically when present; self-reported timestamps are used as a fallback and flagged accordingly.
import { MajikSignature } from '@majikah/majik-signature';
// expectedOrder accepts MajikKey instances and/or ExpectedSigner objects, mixed freely
const result = await MajikSignature.verifyFileOrder(signedBlob, [bobKey, daveKey]);
if (!result.allExpectedSigned) {
console.log('Still pending:', result.pendingSigners);
} else if (!result.allValid) {
console.log('Invalid/tampered signature(s):', result.invalidSigners);
} else if (!result.orderRespected) {
console.log('Signed out of order:', result.violations);
} else if (result.softTieWarnings.length > 0) {
console.log('Valid, but note:', result.reason); // identical timestamps — order indistinguishable
} else {
console.log('Signed in the expected order — all valid.');
}
if (result.usesUnattestedTimestamp) {
console.log('Note: order relied on at least one self-reported (non-TSA) timestamp.');
}
// Strict mode — fail if anyone outside expectedOrder signed at all
const strictResult = await MajikSignature.verifyFileOrder(
signedBlob,
[bobKey, daveKey],
{ strict: true },
);The same check works against a detached envelope via verifyFileDetachedOrder(file, envelope, expectedOrder, options?).
Chain Anchoring
Chain anchoring is a two-step handoff: this SDK prepares and reads anchor data; a separate chain-integration layer (e.g. majik-notary) is responsible for actually submitting and confirming the transaction.
import { MajikSignature } from '@majikah/majik-signature';
// 1. File must be sealed first
const { permitted, reason } = await MajikSignature.canAnchor(sealedBlob);
// 2. Build the canonical memo to submit on-chain (elsewhere, e.g. via majik-notary)
const memo = MajikSignature.buildChainAnchorMemo(sealInfo.sealHash);
// 3. Once the external chain integration confirms the transaction, register the anchor
const blob = await MajikSignature.registerChainAnchor(sealedBlob, confirmedAnchor);
// 4. Read anchors back later
const anchors = await MajikSignature.getChainAnchors(blob);File Versioning & Multi-Sig Revisions
Use this when signing also means visually stamping the file (drawn signatures, watermark overlays) — so each signer's turn changes the bytes, not just adds a detached signature.
import { MajikSignature } from '@majikah/majik-signature';
// Issuer signs first — same as a normal first signature.
const { blob: signedV1 } = await MajikSignature.signFile(originalFile, aliceKey, {
expectedSigners: [
MajikSignature.expectedSignerFromKey(aliceKey),
MajikSignature.expectedSignerFromKey(bobKey),
],
});
// Bob visually stamps the file (application-specific), THEN signs — passing
// priorSignedFile so the new revision correctly chains onto Alice's.
const stampedByBob = await applyVisualStamp(signedV1, bobKey);
const { blob: signedV2 } = await MajikSignature.signFile(stampedByBob, bobKey, {
priorSignedFile: signedV1,
message: 'Approved pending final review',
});
// Tier 1 — self-contained verification, no archived revisions needed.
// Proves every signer's commitment is genuine and the chain hasn't been
// rewritten, using only the final file.
const chainResult = await MajikSignature.verifyFileChain(signedV2);
console.log('Chain valid:', chainResult.chainValid);
console.log('Latest signer valid:', chainResult.latest.valid);
// Tier 2 — archive-assisted, full proof against retained revision bytes.
// Accepts Blob, File, Uint8Array, or ArrayBuffer for each prior revision.
const revisionResult = await MajikSignature.verifyFileRevisions(
signedV2,
[originalFile, signedV1],
);
console.log('All revisions valid:', revisionResult.allValid);
console.log('Complete set supplied:', revisionResult.isCompleteSet);API Reference
Content Signing (bytes/strings)
MajikSignature.sign(content, key, options?)
Sign raw bytes or a string with an unlocked MajikKey.
content: Uint8Array | string— content to sign; strings are UTF-8 encoded before hashingkey: MajikKey— an unlocked key with signing keys presentoptions?: SignOptionscontentType?: string— advisory label (seeCONTENT_TYPES)timestamp?: string— ISO 8601 override (defaults tonew Date().toISOString())expectedSigners?: ExpectedSigner[]— accepted at the type level for allowlist-establishing flows; ignored by the baresign()call itself (only meaningful via the file-level allowlist APIs)
Returns: Promise<MajikSignature>
Throws: MajikSignatureKeyError if the key is locked or has no signing keys.
MajikSignature.verify(content, signature, publicKeys)
Verify a signature against content and the signer's public keys. Both Ed25519 and ML-DSA-87 must pass.
Returns: VerificationResult
{
valid: boolean;
signerId?: string;
contentHash?: string;
timestamp: string;
contentType?: string;
handler?: string; // present when result came from a file-level verify
reason?: string; // present when valid is false
}MajikSignature.verifyWithKey(content, signature, key)
Convenience wrapper — verifies directly against a MajikKey instance. Works even if the key is locked, since only public keys are needed.
MajikSignature.publicKeysFromMajikKey(key)
Extracts { signerId, edPublicKey, mlDsaPublicKey } from a MajikKey for use with verify(). Works on locked keys.
signature.extractPublicKeys() (instance method)
Extracts { signerId, edPublicKey, mlDsaPublicKey } from the signature envelope itself, rather than from a MajikKey. Useful when you only have a serialized signature and need its embedded public keys — for example, to independently verify a TSA token via verifyTSA(). Validates key lengths before returning.
⚠️ Keys extracted this way are self-asserted by the envelope — always cross-check the returned
signerIdagainst a trusted source before relying on the result. See Security Considerations.
signature.validate() / signature.isValid()
validate() re-runs structural validation on the signature's own JSON shape and throws on failure; isValid() is the non-throwing boolean wrapper. Useful as a cheap sanity check after deserializing from untrusted storage, before running full cryptographic verification.
MajikSignature.fromJSON(json) / MajikSignature.deserialize(base64)
Reconstruct a MajikSignature instance from stored JSON or a base64 string.
File Embedding API
These methods sign or verify files with the signature envelope embedded directly in the file. Format is auto-detected from magic bytes and MIME type.
MajikSignature.signFile(file, key, options?)
Sign a file and embed the signature in one call. Strips any existing envelope first, so re-signing is always safe.
file: Blobkey: MajikKeyoptions?contentType?: stringtimestamp?: stringmimeType?: string— override auto-detected MIME typeexpectedSigners?: ExpectedSigner[]— only honored on the first signature; establishes a signing allowlist
Returns: Promise<{ blob: Blob; signature: MajikSignature; envelope: MajikSignatureEnvelope; handler: string; mimeType: string }>
MajikSignature.verifyFile(file, keyOrPublicKeys, options?)
Verify every signature embedded in a file. Accepts a MajikKey or raw MajikSignerPublicKeys.
options?.expectedSignerId?: string— verify only one specific signeroptions?.mimeType?: string
Returns: Promise<VerificationResult[]> — one result per signer in the envelope; legacy single-sig files return a one-item array.
signature.embedIn(file, options?) (instance method)
Embed an already-computed MajikSignature into a file. The signature must have been created from the file's original bytes before embedding — use signFile() if you want signing and embedding together in one step.
Returns: Promise<Blob>
MajikSignature.extractFrom(file, options?)
Extract every embedded signature as typed MajikSignature instances.
Returns: Promise<MajikSignature[]> — empty array if the file has no envelope.
MajikSignature.stripFrom(file, options?)
Return a clean copy of the file with the embedded envelope removed — exactly the bytes that were originally signed.
Returns: Promise<Blob>
MajikSignature.isSigned(file, options?)
Structural presence check — does the file contain an envelope at all? Does not verify. Use as a fast guard before calling verifyFile().
Returns: Promise<boolean>
Detached Signing & MajikSignatureEnvelope API
MajikSignature.signFileDetached(file, key, options?)
Sign a file and return the resulting envelope detached — the returned blob is the clean, stripped file; the envelope travels separately.
options?.existingEnvelope?: MajikSignatureEnvelope | MajikSignatureEnvelopeJSON | Uint8Array | Blob— continue signing an envelope that started out-of-band (any of: an instance, its JSON shape, raw.mjksigbytes, or a.mjksigBlob)options?.expectedSigners?: ExpectedSigner[]— same allowlist-establishing semantics assignFile()options?.tsa?: MajikTimestamp— attach a Trusted Timestamp to this signer's entry before it's added to the envelope
Returns: Promise<{ blob: Blob; envelope: MajikSignatureEnvelope; signature: MajikSignature; handler: string; mimeType: string }>
MajikSignature.verifyFileDetached(file, envelope, keyOrPublicKeys, options?)
Verify a file against a detached envelope (instance, JSON, .mjksig bytes, or Blob — accepted via the same flexible shape as existingEnvelope above). Strips the file first, in case it also happens to carry an embedded envelope.
Returns: Promise<VerificationResult[]>
MajikSignatureEnvelope
The behavior-rich, immutable in-memory counterpart to the wire-format MultiSigEnvelope JSON. Every with* method returns a new instance — the receiver is never mutated. This is the class returned by signFileDetached(), accepted by verifyFileDetached(), and underlying every multi-sig query method.
State predicates: isSealed(), hasAllowlist(), isFirstSigner(), isMultiSig(), hasMultipleSignatories(), isIssuer(keyOrFingerprint)
Lookup: findSignature(signerId), get signatures, get allowlist, get chainAnchors
Allowlist enforcement: checkAllowlist(key), assertCanSign(key) (throws), canSign(key) (non-throwing), verifyAllowlistIntegrity()
Builders (immutable): withSignature(sig), withAllowlist(allowlist, signerId), withSeal(sealedBy, timestamp?), withChainAnchor(anchor)
Seal queries: verifySeal(), getSealInfo(), canAnchor()
Signatory resolution: resolveIssuer(), getSignatories(filter?), getEnvelopeInfo()
Serialization: toJSON(), serialize() / MajikSignatureEnvelope.deserialize(base64), toMJKSIG() / toMJKSIGBytes() / MajikSignatureEnvelope.fromMJKSIG(input), MajikSignatureEnvelope.isMJKSIG(input), MajikSignatureEnvelope.getMJKSIGVersion(input), toCBOR() / MajikSignatureEnvelope.fromCBOR(bytes)
Creation / parsing: MajikSignatureEnvelope.empty(), MajikSignatureEnvelope.fromJSON(json) (also transparently promotes legacy bare single-sig JSON), MajikSignatureEnvelope.from(input) (accepts an instance, JSON, .mjksig bytes, or Blob — the universal entry point used internally by every detached-envelope-accepting method)
Validation: validate() (throws), isValid() (boolean)
See Binary Container Formats for details on .mjksig.
Multi-Signature & Allowlist API
MajikSignature.expectedSignerFromKey(key)
Builds an ExpectedSigner entry ({ signerId, edPublicKey, mlDsaPublicKey }) from a MajikKey, for use in signFile()'s / signFileDetached()'s expectedSigners option. The key does not need to be unlocked.
MajikSignature.getAllowlist(file, options?)
Returns: Promise<ExpectedSigner[] | null> — null for open-signing or unsigned files.
MajikSignature.canSign(file, key, options?)
Checks whether a key is permitted to add a signature — accounts for seal status and full three-field allowlist membership (signerId + both public keys).
Returns: Promise<{ permitted: boolean; reason?: string }>
MajikSignature.getSignatories(file, options?, filter?)
Returns the full signing-status breakdown of a file. filter narrows which slice of the result is populated, but the full SignatoriesResult shape is always returned.
Returns: Promise<SignatoriesResult | null>
{
all: SignatoryInfo[];
signed: SignatoryInfo[];
pending: SignatoryInfo[];
}Convenience aliases: getSignedSignatories(), getPendingSignatories(), getAllSignatories().
MajikSignature.getIssuer(file, options?)
Returns the signatory who established the allowlist (or, for open-signing files, the first signer). Returns: Promise<SignatoryInfo | null>
MajikSignature.getEnvelopeInfo(file, options?)
One call, full picture — isMultiSig, isSealed, issuer, signatories, allowlist, signatureCount, and sealInfo when sealed. Built for rendering a signing-status UI without multiple round trips.
Returns: Promise<EnvelopeInfo | null>
MajikSignature.isMultiSig(file, options?)
true only when the file has a restricted multi-sig envelope (an allowlist with more than one expected signer). false for unsigned, open-signing, or single-signer files.
Sealing API
MajikSignature.seal(file, key, options?)
Only the issuer may seal, and only once. Computes a SHA3-512 hash over all current signatories plus a seal timestamp — this is a hash-based integrity lock, not a new cryptographic signature.
Returns: Promise<{ blob: Blob; sealInfo: SealInfo; handler: string; mimeType: string }>
MajikSignature.verifySeal(file, options?)
Recomputes and compares the seal hash. Does not verify individual signer signatures — call verifyFile() for that.
Returns: Promise<SealVerificationResult>
MajikSignature.getSealInfo(file, options?)
Returns: Promise<SealInfo | null> — { sealHash, sealTimestamp, sealedBy }, without performing verification.
MajikSignature.isSealed(file, options?)
Structural check only. Returns: Promise<boolean>
Trusted Timestamps API
signature.buildTSARequestPayload()
Builds a MajikTSARequest from an existing signature. The default content scope retains legacy behavior; the signature scope hashes the canonical unsigned signer record, including both hybrid signatures and signed metadata, while excluding the TSA property itself.
MajikSignature.signTSA(request, key, tsa, options?)
Server-side. Signs a TSA payload and returns a complete MajikTimestamp, including a server-generated nonce and timestamp.
signature.addTSA(timestamp)
Attaches and validates a MajikTimestamp on an existing signature instance. Signature-scoped timestamps are checked against the canonical unsigned signature record. When supplied, trustedTsaPublicKeys validates the attestation against the authoritative TSA signer identity and both public keys. A TSA, once attached, cannot be replaced.
signature.verifyTSA()
Re-verifies the attached TSA's digest and hybrid signature. Supply MajikSignature.publicKeysFromMajikKey(trustedTsaKey) to pin verification to the authoritative TSA public keys.
signature.hasTSA
boolean getter.
SignRoom Session-Bound Signing
SignRoom can bind each participant to a session ID, a server-issued one-time challenge ID, and an immutable policy hash. For detached document workflows, prefer the session-aware file APIs below: they build the context commitment internally and preserve the normal detached envelope and revision-chain behavior.
MajikSignature.signSessionFile(file, key, options)
Sign one detached document for a SignRoom participant. A session context is required; the method computes its canonical commitment and includes it in both the Ed25519 and ML-DSA-87 signing payloads.
const sessionContext = {
sessionId,
challengeId,
policyHash, // base64 SHA-256 digest of the immutable session policy
};
const signed = await MajikSignature.signSessionFile(
documentBlob,
unlockedMajikKey,
{
sessionContext,
contentType: "application/pdf",
expectedSigners, // optional; used when this signer establishes the allowlist
},
);
// The document is detached and clean. Store/send the sidecar separately.
const document = signed.blob;
const envelope = signed.envelope;
const sidecar = signed.mjksig; // binary .mjksig BlobFor subsequent participants, pass the existing envelope. When a participant adds a visual stamp, pass the exact next fileVersion entry. The SDK validates that it follows the existing envelope, matches the signer and signed content, appends it to the returned envelope, and commits its chain hash. A signer who does not add a new revision is automatically bound to the current chain:
const next = await MajikSignature.signSessionFile(stampedDocument, participantKey, {
sessionContext: participantSessionContext, // that participant's own challenge
existingEnvelope: previous.envelope,
fileVersion: {
version: previous.envelope.lastFileVersion!.version + 1,
timestamp: new Date().toISOString(),
contentHash: stampedContentHash,
previousVersionHash: MajikSignatureEnvelope.hashFileVersionEntry(
previous.envelope.lastFileVersion!,
),
createdBy: participantKey.fingerprint,
message: "Participant added a visual stamp",
},
contentType: "application/pdf",
});The returned mjksig contains the envelope as it exists when this call returns. If a server later attaches an official TSA token, serialize the updated envelope again with updatedEnvelope.toMJKSIG() so the sidecar includes that attestation.
MajikSignature.verifySessionFile(file, envelope, options)
Verify the detached document and every participant's session-bound signature. Verification fails closed unless callers supply both the authoritative session context and trusted signing public keys for every signer. The maps are keyed by signer fingerprint because each participant has a distinct one-time challenge.
const verification = await MajikSignature.verifySessionFile(
documentBlob,
sidecar, // .mjksig Blob, envelope JSON, or MajikSignatureEnvelope
{
expectedSessionContexts: {
[issuerKey.fingerprint]: issuerSessionContext,
[participantKey.fingerprint]: participantSessionContext,
},
expectedSignerPublicKeys: {
[issuerKey.fingerprint]: MajikSignature.publicKeysFromMajikKey(issuerKey),
[participantKey.fingerprint]: MajikSignature.publicKeysFromMajikKey(participantKey),
},
trustedTsaPublicKeys, // optional: pins TSA verification to this key
requireTSA: true,
requireTrustedTSA: true,
},
);
if (!verification.valid) {
console.error(verification.reason, verification.results);
}The result includes one cryptographic/session verification result per participant, TSA status per signature, and revision-chain details when present. When requireTrustedTSA is enabled, trustedTsaPublicKeys is mandatory and every signer must have a valid attestation pinned to that TSA identity. Without a pinned TSA key, a present token is checked for internal consistency but is not reported as trusted.
The SDK validates signatures, signer keys, session commitments, allowlist integrity, sealing, revision chains, and any TSA records. It does not authorize participants, issue or consume one-time challenges, or decide whether a challenge is still active; those remain application-server responsibilities.
buildSessionContextHash(context)
The lower-level helper remains available when applications need to construct or compare the canonical context commitment directly:
import {
buildSessionContextHash,
hashContent,
bytesToBase64,
} from "@majikah/majik-signature";
const policyHash = bytesToBase64(hashContent(canonicalPolicyBytes));
const sessionContextHash = buildSessionContextHash({
sessionId,
challengeId,
policyHash,
});MajikSignature.verifyDigest(hash, signature, publicKeys, options?)
For digest-only workflows where the application has independently established the trusted document hash, verifyDigest() remains available. For detached file verification, prefer verifySessionFile() because it can recompute the digest from the supplied document bytes and verify all participants in the envelope.
Signature-scoped TSA digests are domain-separated and exclude the TSA field to avoid circular hashing. In SignRoom, the API should verify the participant signature first, generate the TSA token server-side, verify it against the trusted TSA public keys, attach it, and persist the timestamped envelope. TSA issuance and billing policy belong to the application service, not this library.
Batch Signing & MajikSignatureMap API
MajikSignature.signBatchDetached(files, key, options?)
Sign a batch of files (e.g. a folder or zip's contents) as detached envelopes.
files: { path: string; blob: Blob }[]— every path must be unique within the batchoptions?.mode?: "map" | "separate"—"map"(default) produces oneMajikSignatureMapcovering the whole batch;"separate"produces one.mjksigBlob per fileoptions?.continueOnError?: boolean— defaultfalse(abort the whole batch on the first failure); settrueto collect failures per-file and continue
Returns:
