identity: the SD-JWT form of an AERE hybrid identity is judged on its ML-DSA-65 half by default, the Ed25519 half only on explicit request, and every verdict says postQuantum (rule sdjwt.hybrid-half); pq-pki: the signature algorithm a certificate or a revocation list declares must be its issuer key's (ALG_KEY, CRL_ALG_KEY); agents: an equivocation proof requires the agent's ML-DSA-65 key; pq-gateway: the status names the path to the backend and hybrid-only refuses a plain-HTTP backend; conformance 241 rules, 631 vectors

This commit is contained in:
Aere Network committed 2026-10-19 05:19:21 +03:00
1 parent 3ff21f7758
commit 0c8f1de3fd
122 files changed
+1205 -262

No files matched your search

+48 -15
View File
@@ -168,17 +168,40 @@ import { issueSdJwt, presentSdJwt, verifySdJwt } from './sdjwt.mjs';
// issuer: an issuer-signed JWT (digests of the disclosable claims in _sd, list elements as {"...": digest}, _sd_alg sha-256, the holder's
// key in cnf.jwk) followed by the disclosures, joined by ~
const { sdJwt } = issueSdJwt({ issuer, holder: holderPublicJwkOrKeys, claims, disclosable: ['given_name', 'age_over_18'],
arrayDisclosable: ['nationalities'], iss: 'https://issuer.example', exp, alg: 'EdDSA' }); // or alg: 'ML-DSA-65'
arrayDisclosable: ['nationalities'], iss: 'https://issuer.example', exp }); // AERE keys: ML-DSA-65 (alg: 'EdDSA' needs classicalHalf: true)
// holder: keep only the chosen disclosures and add a Key Binding JWT (typ kb+jwt, aud, nonce, iat, sd_hash) signed with the holder key
// a name reveals a top-level claim; { element, in } an element of the top-level list named (only that list)
const shown = presentSdJwt({ sdJwt, reveal: ['age_over_18', { element: 'RO', in: 'nationalities' }], holder, audience, nonce });
// verifier: the steps of RFC 9901 sections 7.1 and 7.3, with the issuer key the verifier chose (never one taken from the token);
// its audience and nonce are required, exp is required, the token must be explicitly typed ...+sd-jwt (expectedTyp to change it)
const r = verifySdJwt(shown, { issuerKey, audience, nonce, expectedIssuer: 'https://issuer.example' }); // { valid, reason, payload, disclosed, keyBinding }
const r = verifySdJwt(shown, { issuerKey, audience, nonce, expectedIssuer: 'https://issuer.example' });
// { valid, rule, reason, payload, disclosed, alg, postQuantum, keyBinding }
```
From the command line (the issuer key a public JWK, or the output of `pub`): `node identity-cli.mjs verify-sdjwt --sd-jwt token.txt --issuer-key issuer.pub.json
--issuer-alg EdDSA --audience A --nonce N [--expected-issuer I] [--at T] [--json]`; Aere Cloud runs it behind `POST /v1/identity/sd-jwt/verify`.
[--issuer-alg A] [--classical-half] --audience A --nonce N [--expected-issuer I] [--at T] [--json]`; Aere Cloud runs it behind
`POST /v1/identity/sd-jwt/verify` (fields `issuerAlg` and `classicalHalf`; the response carries `postQuantum`).
**The post-quantum half of an AERE identity (since 2026-10-19; AIP-25, finding C1).** The keys of an AERE identity are an Ed25519 key
AND an ML-DSA-65 key, and its own credentials need both signatures. An SD-JWT carries one JWS signature. Until 2026-10-19 the issuer,
the holder's `cnf.jwk` and the verifier used the Ed25519 half by default, so a token signed with the issuer's Ed25519 key alone, which
someone who broke only that classical key could make, verified against the issuer's whole hybrid identity, on the command line and
on the public route alike. Since then, with AERE keys (the key pair, or the public keys `{alg, ed25519, mldsa65}`):
- issuing, the holder key bound in `cnf.jwk`, the Key Binding JWT and the Token Status List (below) use the ML-DSA-65 half by default;
- the verifier requires the ML-DSA-65 half by default; a token signed with the Ed25519 half is refused by the rule `hybrid-half`, and
naming `issuerAlg: 'EdDSA'` alone is refused the same way;
- the Ed25519 half is used, and judged, only when the caller asks for it: `classicalHalf: true` (`--classical-half` on the command line,
`classicalHalf` on the route), for classical interoperation with a library that does not know RFC 9964; the verifier then takes the
half the token is signed with, EdDSA or ML-DSA-65;
- every verdict says `postQuantum`: true only when every signature it judged (the issuer's and the Key Binding JWT, and for an SD-JWT VC
the status list) is ML-DSA-65; false on every refusal.
A plain JWK (a key of another issuer, ES256 or EdDSA; the tokens of `@sd-jwt/core` and of European wallets) is judged as before, since
there is no post-quantum half to lose, and the verdict says `postQuantum: false` for it too. Someone who turns AERE keys into a plain
Ed25519 JWK (`publicJwk(keys, 'EdDSA', { classicalHalf: true })`) has asked for the classical half, and the verdict says so. Tokens
issued with EdDSA by AERE identities before this date stop verifying against their hybrid keys unless the verifier asks for the
classical half.
Checked against the standard's own vectors (`fixturi-rfc9901.json`, extracted from RFC 9901 Section 5 and Appendix A.5; IETF code
components, Revised BSD License): the digest of each of the ten example disclosures; the example SD-JWT, signed ES256 by someone
@@ -191,7 +214,8 @@ type AKP (`alg` `ML-DSA-65`, parameters `pub` and `priv`), the names and key for
`draft-ietf-cose-dilithium`, which this file quoted as not yet a standard). Measured 2026-10-18 on Node.js 24.14.1: jose 6.2.12 signs
and verifies ML-DSA-65 JWS through Node's WebCrypto (which prints an experimental-feature warning), its signatures and ours verify
each other, and `@sd-jwt/core` 0.23.0 accepts an ML-DSA-65 SD-JWT and KB-JWT through its injected verifier; a library that does not
know RFC 9964 rejects such a token, so for it issue with EdDSA. A hybrid (two signatures in one token) would need the general JWS JSON
know RFC 9964 rejects such a token, so for it issue with EdDSA (with AERE keys, since 2026-10-19, `alg: 'EdDSA', classicalHalf: true`,
and the verdict says the token is not post-quantum). A hybrid (two signatures in one token) would need the general JWS JSON
serialization and is not done here. The algorithm must match the key the verifier gives (no `none`, no algorithm confusion); a
disclosure not bound to a digest, a digest seen twice, a disclosure naming `_sd`, `...`, `_sd_alg` or `__proto__`, or one that
overwrites a claim, or a claim named `__proto__` anywhere, is refused; `_sd_alg` below the top level of the payload is refused (RFC
@@ -223,7 +247,10 @@ rest to policy): kept, measured as our refusal of their `sha-384` token. Nested
claim; the RFC's MUST NOT decided it, repaired here. The salt of their default helper, `generateSalt(16)` of `@sd-jwt/crypto-nodejs`,
is 16 hexadecimal characters, 64 bits, under the 128 bits Section 9.3 recommends; ours is 16 random bytes; theirs, and the generator
is injectable. Disclosures are ordered by the presentation frame there and by issuance order here; the RFC orders them not at all.
An AKP JWK without `alg` is refused by Node's `crypto` and by jose alike (RFC 9964 Section 3 requires it).
An AKP JWK without `alg` is refused by Node's `crypto` and by jose alike (RFC 9964 Section 3 requires it). These rows were measured on
2026-10-18, when the Ed25519 half of AERE keys was the default; since 2026-10-19 the interop scripts ask for it explicitly
(`classicalHalf: true`), and they have not been run again since (the foreign libraries are not installed here): not measured after
the change. Their recorded fixtures carry plain JWKs and are judged offline as before.
## SD-JWT VC (`sdjwt-vc.mjs`)
@@ -238,9 +265,14 @@ const { sdJwt } = issueSdJwtVc({ issuer, holder, vct: 'urn:eudi:pid:1', iss, cla
const shown = presentSdJwtVc({ sdJwt, reveal: ['birthdate'], holder, audience, nonce });
const list = issueStatusListJwt({ issuer, uri, statuses: [0, 0, 0, 0, 0, 1], bits: 1, exp }); // typ statuslist+jwt, sub = uri, iat, status_list { bits, lst }
const r = verifySdJwtVc(shown, { issuerKey, audience, nonce, expectedVct: 'urn:eudi:pid:1', statusListJwt: list });
// r: { valid, reason, payload, disclosed, keyBinding, vct, status: { present, judged, uri, idx, value, name } }
// r: { valid, reason, payload, disclosed, keyBinding, postQuantum, vct, status: { present, judged, uri, idx, value, name } }
```
Since 2026-10-19 (AIP-25 C1) the Status List Token of an AERE issuer is signed and judged with the ML-DSA-65 half by default, as the
credential is: a list signed with the Ed25519 half alone, which could "unrevoke" a credential for someone who broke only that key, is
refused (`status-list`, naming the Ed25519 half) unless the verifier asks for the classical half (`classicalHalf`), and `postQuantum`
of a VC verdict is true only when the list judged is ML-DSA-65 too.
What the verifier requires beyond RFC 9901: the header type `dc+sd-jwt` (Section 2.2.1); a `vct` in the payload equal to one the
verifier names (`expectedVct` is required: a verifier that does not say which credential type it expects would accept any); none of
`iss`, `nbf`, `exp`, `cnf`, `vct`, `vct#integrity`, `aka_vcts`, `status` selectively disclosed (Section 2.2.2.3; the issuer refuses to
@@ -254,7 +286,7 @@ not judged); one that names no status is judged without a list. Nothing is fetch
JWT VC Issuer Metadata, `x5c`) or taken from the token.
From the command line: `node identity-cli.mjs verify-sdjwt-vc --sd-jwt token.txt --issuer-key issuer.pub.json --audience A --nonce N
--expected-vct urn:eudi:pid:1 [--status-list list.txt [--status-list-key k.json]] [--status-not-required] [--expected-issuer I]
--expected-vct urn:eudi:pid:1 [--status-list list.txt [--status-list-key k.json]] [--status-not-required] [--classical-half] [--expected-issuer I]
[--at T] [--json]`; 0 VALID, 1 INVALID, 2 a usage error.
**Interoperability, measured 2026-10-18** (`interop/interop-sdjwt-vc.mjs`; `@sd-jwt/sd-jwt-vc` 0.23.0, `@owf/token-status-list` 0.5.0,
@@ -309,13 +341,14 @@ no row failed, also when rows were not judged; a caller that needs "nothing left
With these ids the presentation verifier is enrolled in the conformance suite beside this folder (`conformance/`: 38 rules,
69 vectors of the artifact kind `identity-presentation`, four of them for `request` since 2026-10-18, each rule taken out of a copy of the verifier in turn). Since 2026-10-18 the
SD-JWT verifier and the SD-JWT VC profile are enrolled there too: `verifySdJwt` names the rule of its refusal (`rule`, one of the 23 of
`REGULI` in `sdjwt.mjs`: `form`, `alg`, `typ`, `crit`, `key`, `signature`, `issuer`, `sd-alg`, `disclosure-form`, `disclosure-twice`,
SD-JWT verifier and the SD-JWT VC profile are enrolled there too: `verifySdJwt` names the rule of its refusal (`rule`, one of the 24 of
`REGULI` in `sdjwt.mjs`: `form`, `alg`, `typ`, `crit`, `key`, `hybrid-half` (since 2026-10-19), `signature`, `issuer`, `sd-alg`, `disclosure-form`, `disclosure-twice`,
`digest-twice`, `disclosure-name`, `claim-conflict`, `unreferenced`, `time`, `kb-context`, `kb-required`, `kb-cnf`, `kb-claims`,
`kb-audience`, `kb-nonce`, `kb-freshness`, `kb-sd-hash`), and `verifySdJwtVc` one of those or one of its own 9 (`vct-expected`, `vct`,
`vct-mismatch`, `disclosed-protected`, `form`, `status-list`, `status-index`, `status-revoked`, `status-unjudged`); both stop at their
first refusal. The suite holds 54 vectors of the kind `sdjwt-presentation` (the RFC 9901 example, the tokens of `@sd-jwt/core` from the
interop fixtures, and tokens issued with AERE keys) and 32 of `sdjwt-vc-presentation` (ours with their status lists, and the credentials
first refusal. The suite holds 59 vectors of the kind `sdjwt-presentation` (the RFC 9901 example, the tokens of `@sd-jwt/core` from the
interop fixtures, and tokens issued with AERE keys; since 2026-10-19 five judged against the AERE hybrid keys, three of them refused by
`hybrid-half`) and 32 of `sdjwt-vc-presentation` (ours with their status lists, and the credentials
and lists of `@sd-jwt/sd-jwt-vc` and `@owf/token-status-list`); a VC whose status was waived and not judged is `PARTIAL` there, never
`VALID`.
@@ -362,10 +395,10 @@ node proba-conformitate.mjs # 18: compliance policies judged on real pr
node control-negativ-conformitate.mjs # on a copy, each of 17 guards removed -> its own named test turns red
node proba-travel-rule.mjs # 20: two VASPs with registry credentials, the whole exchange, and each attack of the review
node control-negativ-travel-rule.mjs # on a copy, each of 20 guards removed -> its own named test turns red
node proba-sdjwt.mjs # 25: the RFC 9901 vectors, SD-JWTs issued with AERE keys (EdDSA and ML-DSA-65), each attack, the fixtures of @sd-jwt/core
node control-negativ-sdjwt.mjs # on a copy, each of 31 guards removed -> its own named test turns red
node proba-sdjwt-vc.mjs # 10: the SD-JWT VC profile, the status list, the fixtures of @sd-jwt/sd-jwt-vc and @owf/token-status-list, the command line
node control-negativ-sdjwt-vc.mjs # on a copy, each of 16 guards removed -> its own named test turns red
node proba-sdjwt.mjs # 31: the RFC 9901 vectors, SD-JWTs issued with AERE keys (ML-DSA-65 by default, EdDSA on request), each attack, the post-quantum half (AIP-25 C1), the fixtures of @sd-jwt/core
node control-negativ-sdjwt.mjs # on a copy, each of 39 guards removed -> its own named test turns red
node proba-sdjwt-vc.mjs # 11: the SD-JWT VC profile, the status list (and its post-quantum half), the fixtures of @sd-jwt/sd-jwt-vc and @owf/token-status-list, the command line
node control-negativ-sdjwt-vc.mjs # on a copy, each of 20 guards removed -> its own named test turns red
node interop/interop-sdjwt.mjs --lab <folder> # the measurement itself, with the foreign libraries installed in <folder>, outside this repository
node interop/interop-sdjwt-vc.mjs --lab <folder> # (npm: @sd-jwt/core, @sd-jwt/sd-jwt-vc, @sd-jwt/crypto-nodejs, jose); --scrie rewrites the fixtures
```
+6 -1
View File
@@ -24,10 +24,15 @@ const PLANTARI = [
['impachetarea bitilor citita de la bitul cel mai semnificativ (ordinea gresita)', '(octeti[Math.floor(idx * bits / 8)] >> ((idx * bits) % 8)) & ((1 << bits) - 1)', '(octeti[Math.floor(idx * bits / 8)] >> (8 - bits - ((idx * bits) % 8))) & ((1 << bits) - 1)', 'STARE: revocat'],
['sub-ul listei nu se mai compara cu uri-ul din jeton', 'if (!(corp.sub === uri /*PAZA:status-list*/)) return nu(', 'if (false) return nu(', 'STARE: lista pentru alt uri'],
['lista expirata primita', 'if (!(corp.exp === undefined || (Number.isFinite(corp.exp) && acum < corp.exp) /*PAZA:status-list*/)) return nu(', 'if (false) return nu(', 'STARE: lista pentru alt uri'],
['typ-ul statuslist+jwt al listei nu se mai cere', "verifyJws(jwt, publicJwk(key, alg), { typ: TYP_STATUS_LIST })", "verifyJws(jwt, publicJwk(key, alg), { typ: null })", 'STARE: lista pentru alt uri'],
['typ-ul statuslist+jwt al listei nu se mai cere', "headerAlg: headerAlgOf(jwt) }), { typ: TYP_STATUS_LIST })", "headerAlg: headerAlgOf(jwt) }), { typ: null })", 'STARE: lista pentru alt uri'],
['iat-ul listei nu se mai cere', "if (!(Number.isFinite(corp.iat) /*PAZA:status-list*/)) return nu('iat is required", "if (false) return nu('iat is required", 'STARE: lista pentru alt uri'],
['indexul dincolo de lista citit ca 0', 'if (!(v !== null /*PAZA:status-index*/)) return refuz(', 'if (false) return refuz(', 'STARE: lista pentru alt uri'],
// fixturile straine: cu impachetarea gresita, listele @owf/token-status-list pe 1 bit cu indexul 5 = 1 ar fi citite altfel
// 2026-10-19 (AIP-25 C1, D-535): lista de stare a unui emitent AERE pe jumatatea ML-DSA-65; paznicii noi si forma de dinainte
['AIP-25 C1: lista de stare emisa implicit cu jumatatea Ed25519 (forma de dinainte)', 'const algL = alg ?? defaultAlg(issuer);', "const algL = alg ?? 'EdDSA'; classicalHalf = true;", 'AIP-25 C1: lista de stare'],
['AIP-25 C1: lista de stare judecata implicit pe jumatatea Ed25519 (forma de dinainte)', 'judgedJwk(key, alg, { classicalHalf, headerAlg: headerAlgOf(jwt) })', "judgedJwk(key, alg ?? 'EdDSA', { classicalHalf: true, headerAlg: headerAlgOf(jwt) })", 'AIP-25 C1: lista de stare'],
['AIP-25 C1: verdictul VC post-cuantic si cu o lista semnata Ed25519', "pqLista = l.alg === 'ML-DSA-65';", 'pqLista = true;', 'AIP-25 C1: lista de stare'],
['AIP-25 C1: classicalHalf netransmis listei de stare', 'classicalHalf: o.classicalHalf, uri: ref.uri', 'classicalHalf: false, uri: ref.uri', 'AIP-25 C1: lista de stare'],
['fixturile straine: lista LOR revocata citita cu ordinea gresita a bitilor', 'const statusAt = (idx) => (Number.isInteger(idx) && idx >= 0 && idx < entries ?', 'const statusAt = (idx) => (false && Number.isInteger(idx) && idx >= 0 && idx < entries ?', 'INTEROP'],
];
function copie() {
+13 -4
View File
@@ -13,7 +13,7 @@ import { fileURLToPath } from 'node:url';
const AICI = path.dirname(fileURLToPath(import.meta.url));
const S = 'sdjwt.mjs';
const PLANTARI = [
// [nume, tipar, inlocuire, proba (inceputul numelui ei)]
// [nume, tipar, inlocuire, proba (inceputul numelui ei), fisierul plantat (implicit sdjwt.mjs; din 2026-10-19 si linia de comanda)]
['alg none primit', "if (!(ALGS.includes(antet.alg) /*PAZA:alg*/)) throw", "if (antet.alg === 'nimic') throw", 'ATAC: alg none'],
['algoritmul nu mai trebuie sa fie al cheii (confuzia)', 'if (!(potriveste(antet.alg, key) /*PAZA:key*/)) throw', 'if (false) throw', 'ATAC: alg none'],
['o dezvaluire nelegata de niciun digest primita', 'if (!(folosite.size === dupaDigest.size /*PAZA:unreferenced*/)) return', 'if (false) return', 'ATAC: o dezvaluire cu valoarea schimbata'],
@@ -47,7 +47,16 @@ const PLANTARI = [
['emiterea nu mai cere un typ explicit de SD-JWT', "if (!tipBun(typ, undefined)) throw new Error('sd-jwt: typ must be", "if (false) throw new Error('sd-jwt: typ must be", 'INTEROP: _sd_alg imbricat'],
['cheia publica Node nu mai e primita', "(k.type === 'public' ? k : crypto.createPublicKey(k))", 'crypto.createPublicKey(k)', 'REVIZUIRE: cheia emitentului'],
['o afirmatie __proto__ primita (prototipul schimbat)', "if (!(!Object.hasOwn(x, '__proto__') /*PAZA:disclosure-name*/)) throw", 'if (false) throw', 'ATAC: o afirmatie numita __proto__'],
['elementele de lista nedezvaluite pastrate', 'if (!c) continue; // nedezvaluit: elementul se scoate', "if (!c) { out.push(e); continue; }", 'AERE -> SD-JWT (EdDSA'],
['elementele de lista nedezvaluite pastrate', 'if (!c) continue; // nedezvaluit: elementul se scoate', "if (!c) { out.push(e); continue; }", 'AERE -> SD-JWT (implicit'],
// 2026-10-19 (AIP-25 C1, D-535): jumatatea clasica a unei identitati hibride; fiecare paznic nou si forma de dinainte a reparatiei
['AIP-25 C1: jetonul doar-Ed25519 contra cheilor AERE nu mai e numit (cade pe key)', "if (!(!(a === 'ML-DSA-65' && CLASIC.includes(headerAlg)) /*PAZA:hybrid-half*/)) throw", 'if (false) throw', 'AIP-25 C1: un SD-JWT semnat NUMAI'],
['AIP-25 C1: jumatatea Ed25519 a cheilor AERE data fara classicalHalf', 'if (!(classicalHalf === true /*PAZA:hybrid-half*/)) throw', 'if (false) throw', 'AIP-25 C1: jumatatea clasica se judeca NUMAI'],
['AIP-25 C1: forma de dinainte: cheile AERE judecate implicit pe jumatatea Ed25519, fara cerere', 'if (!esteAere(k)) return publicJwk(k, alg);', "if (true) return publicJwk(k, alg ?? 'EdDSA', { classicalHalf: true });", 'AIP-25 C1: un SD-JWT semnat NUMAI'],
['AIP-25 C1: postQuantum spus adevarat pentru orice semnatura a emitentului', "const pqEmitent = antet.alg === 'ML-DSA-65';", 'const pqEmitent = true;', 'AIP-25 C1: un JWK simplu ramane'],
['AIP-25 C1: Key Binding-ul clasic nu mai coboara postQuantum', "postQuantum: rez.postQuantum && k.antet.alg === 'ML-DSA-65',", 'postQuantum: rez.postQuantum,', 'AIP-25 C1: un JWK simplu ramane'],
['AIP-25 C1: emiterea implicita cu chei AERE pe Ed25519 (forma de dinainte)', 'const algE = alg ?? defaultAlg(issuer), algH = holderAlg ?? defaultAlg(holder);', "const algE = alg ?? 'EdDSA', algH = holderAlg ?? 'EdDSA'; classicalHalf = true;", 'AIP-25 C1: emiterea implicita'],
['AIP-25 C1: linia de comanda ignora --classical-half', "const classicalHalf = are('--classical-half');", 'const classicalHalf = false;', 'linia de comanda AIP-25 C1', 'identity-cli.mjs'],
['AIP-25 C1: linia de comanda cere implicit EdDSA (forma de dinainte)', "issuerAlg: algDat ?? (aere(cheie) ? undefined : 'EdDSA'),", "issuerAlg: algDat ?? 'EdDSA',", 'linia de comanda AIP-25 C1', 'identity-cli.mjs'],
];
function copie() {
const t = fs.mkdtempSync(path.join(os.tmpdir(), 'aere-sdjwt-ctl-'));
@@ -64,10 +73,10 @@ function ruleaza(t) {
c.on('close', (cod) => { clearTimeout(ceas); resolve({ cod, rulat: /aere-sd-jwt: \d+\/\d+/.test(out), rosii: out.split('\n').filter((l) => l.startsWith(' RAU ')) }); });
});
}
async function planteaza([nume, din, inl, tinta]) {
async function planteaza([nume, din, inl, tinta, fis = S]) {
const t = copie();
try {
const f = path.join(t, S); const src = fs.readFileSync(f, 'utf8');
const f = path.join(t, fis); const src = fs.readFileSync(f, 'utf8');
if (src.split(din).length !== 2) return [false, ` STRICAT ${nume}: tiparul apare de ${src.split(din).length - 1} ori`];
fs.writeFileSync(f, src.replace(din, inl));
const r = await ruleaza(t);
+30 -17
View File
@@ -15,10 +15,11 @@
// comply --presentation p.json --policy policy.json --audience A --nonce N [--status-list l.json ...] [--revocation r.json ...]
// [--record record.json] [--pseudonym-key-file k] a compliance policy judged; the record carries no personal data
// [--json [--with-record]] [--at T] the whole result as one JSON object (with the record inside)
// verify-sdjwt --sd-jwt f.txt --issuer-key k.json [--issuer-alg EdDSA|ML-DSA-65|ES256] --audience A --nonce N
// verify-sdjwt --sd-jwt f.txt --issuer-key k.json [--issuer-alg EdDSA|ML-DSA-65|ES256] [--classical-half] --audience A --nonce N
// [--expected-issuer I] [--expected-typ T] [--max-age S] [--at T] [--json] an SD-JWT+KB (IETF RFC 9901), sdjwt.mjs;
// the issuer key is a public JWK or the public keys of an AERE identity (the output of pub)
// verify-sdjwt-vc --sd-jwt f.txt --issuer-key k.json [--issuer-alg A] --audience A --nonce N --expected-vct V [--expected-vct V2 ...]
// the issuer key is a public JWK or the public keys of an AERE identity (the output of pub). With AERE keys the ML-DSA-65
// half is judged; the Ed25519 half only with --classical-half (2026-10-19, AIP-25 C1), and then the verdict says postQuantum false
// verify-sdjwt-vc --sd-jwt f.txt --issuer-key k.json [--issuer-alg A] [--classical-half] --audience A --nonce N --expected-vct V [--expected-vct V2 ...]
// [--status-list f.txt [--status-list-key k.json] [--status-list-alg A]] [--status-not-required] [--expected-issuer I]
// [--max-age S] [--at T] [--json] an SD-JWT VC (draft-ietf-oauth-sd-jwt-vc), sdjwt-vc.mjs; the status list is the Token
// Status List JWT the verifier fetched from the uri the credential names (without it a credential with `status` is INVALID)
@@ -139,32 +140,42 @@ async function main() {
const { verifySdJwt, publicJwk } = await import('./sdjwt.mjs');
const vc = cmd === 'verify-sdjwt-vc';
let jeton; try { jeton = fs.readFileSync(cere('--sd-jwt'), 'utf8').trim(); } catch (e) { throw new Folosire(`cannot read --sd-jwt: ${e.message}`); }
// 2026-10-19 (AIP-25 C1, D-535): cu cheile publice ale unei identitati AERE (iesirea lui `pub`), fara --issuer-alg se judeca jumatatea
// ML-DSA-65; jumatatea Ed25519 numai cu --classical-half (si verdictul spune postQuantum false). Pana atunci implicitul era EdDSA, deci
// jumatatea clasica singura. Pentru un JWK simplu, --issuer-alg ramane cum era (implicit EdDSA, verificat contra cheii).
const classicalHalf = are('--classical-half');
const aere = (k) => !!k && typeof k === 'object' && k.alg === I.ALG;
// revizuirea din 30 sept: cheia emitentului e intrarea VERIFICATORULUI; una care nu se citeste, e privata sau nu e a algoritmului cerut e o
// greseala a lui (cod 2, cu motivul), nu un credential INVALID (cheile stricate ieseau INVALID cu mesajul Node)
// greseala a lui (cod 2, cu motivul), nu un credential INVALID (cheile stricate ieseau INVALID cu mesajul Node). Pentru chei AERE se
// citesc jumatatile pe care verificarea le poate folosi; cererea jumatatii Ed25519 fara --classical-half nu e o greseala de intrare, ci
// un refuz al verificatorului (INVALID, regula hybrid-half), ca jetonul doar-Ed25519
const cheiePublicaBuna = (optiune, cheie, alg) => {
if (!['EdDSA', 'Ed25519', 'ES256', 'ML-DSA-65'].includes(alg)) throw new Folosire(`${optiune}-alg is EdDSA, ES256 or ML-DSA-65`);
try {
const jwk = publicJwk(cheie, alg);
if ('d' in jwk || 'priv' in jwk) throw new Error('a private JWK was given where a public key belongs');
const k = crypto.createPublicKey({ key: jwk, format: 'jwk' });
const buna = alg === 'ES256' ? k.asymmetricKeyType === 'ec' && k.asymmetricKeyDetails.namedCurve === 'prime256v1' : alg === 'ML-DSA-65' ? k.asymmetricKeyType === 'ml-dsa-65' : k.asymmetricKeyType === 'ed25519';
if (!buna) throw new Error(`the key is a ${k.asymmetricKeyType} key, not one for ${alg}`);
} catch (e) { if (e instanceof Folosire) throw e; throw new Folosire(`${optiune}: ` + String(e.message || e).replace(/^sd-jwt: /, '').slice(0, 160)); }
if (alg != null && !['EdDSA', 'Ed25519', 'ES256', 'ML-DSA-65'].includes(alg)) throw new Folosire(`${optiune}-alg is EdDSA, ES256 or ML-DSA-65`);
const deCitit = !aere(cheie) ? [alg ?? 'EdDSA'] : alg != null ? (['EdDSA', 'Ed25519'].includes(alg) && !classicalHalf ? [] : [alg]) : (classicalHalf ? ['ML-DSA-65', 'EdDSA'] : ['ML-DSA-65']);
for (const a of deCitit) {
try {
const jwk = publicJwk(cheie, a, { classicalHalf: true });
if ('d' in jwk || 'priv' in jwk) throw new Error('a private JWK was given where a public key belongs');
const k = crypto.createPublicKey({ key: jwk, format: 'jwk' });
const buna = a === 'ES256' ? k.asymmetricKeyType === 'ec' && k.asymmetricKeyDetails.namedCurve === 'prime256v1' : a === 'ML-DSA-65' ? k.asymmetricKeyType === 'ml-dsa-65' : k.asymmetricKeyType === 'ed25519';
if (!buna) throw new Error(`the key is a ${k.asymmetricKeyType} key, not one for ${a}`);
} catch (e) { if (e instanceof Folosire) throw e; throw new Folosire(`${optiune}: ` + String(e.message || e).replace(/^sd-jwt: /, '').slice(0, 160)); }
}
};
const cheie = citeste(cere('--issuer-key'));
const alg = get('--issuer-alg') ?? 'EdDSA';
cheiePublicaBuna('--issuer-key', cheie, alg);
const algDat = get('--issuer-alg');
cheiePublicaBuna('--issuer-key', cheie, algDat);
const maxAgeS = Number(get('--max-age') ?? 300);
if (!Number.isInteger(maxAgeS) || maxAgeS < 1 || maxAgeS > 3600) throw new Folosire('--max-age is a number of seconds, 1..3600');
const tip = get('--expected-typ');
const comune = { issuerKey: cheie, issuerAlg: alg, audience: cere('--audience'), nonce: cere('--nonce'), expectedIssuer: get('--expected-issuer'), maxAgeS, now: momentul(), ...(tip != null ? { expectedTyp: tip } : {}) };
const comune = { issuerKey: cheie, issuerAlg: algDat ?? (aere(cheie) ? undefined : 'EdDSA'), classicalHalf, audience: cere('--audience'), nonce: cere('--nonce'), expectedIssuer: get('--expected-issuer'), maxAgeS, now: momentul(), ...(tip != null ? { expectedTyp: tip } : {}) };
let r;
if (!vc) r = verifySdJwt(jeton, comune);
else {
const { verifySdJwtVc } = await import('./sdjwt-vc.mjs');
const vcts = toate('--expected-vct'); if (!vcts.length) throw new Folosire('verify-sdjwt-vc needs --expected-vct <vct> (the credential type the verifier expects; may be repeated)');
let statusListJwt = null; if (get('--status-list')) { try { statusListJwt = fs.readFileSync(get('--status-list'), 'utf8').trim(); } catch (e) { throw new Folosire(`cannot read --status-list: ${e.message}`); } }
const statusListKey = get('--status-list-key') ? citeste(get('--status-list-key')) : null, statusListAlg = get('--status-list-alg') ?? alg;
const statusListKey = get('--status-list-key') ? citeste(get('--status-list-key')) : null, statusListAlg = get('--status-list-alg') ?? algDat ?? undefined;
if (statusListKey) cheiePublicaBuna('--status-list-key', statusListKey, statusListAlg);
r = verifySdJwtVc(jeton, { ...comune, expectedVct: vcts, statusListJwt, statusListKey, statusListAlg, requireStatus: !are('--status-not-required') });
}
@@ -173,7 +184,9 @@ async function main() {
else if (!r.valid) console.log('INVALID: ' + r.reason);
else {
const stare = !vc ? '' : '; status ' + (r.status.judged ? `${r.status.value} (${r.status.name}) in ${r.status.uri} at ${r.status.idx}` : r.status.present ? `not judged (${r.status.uri ?? r.status.mechanism})` : 'none');
console.log(`VALID: issued by ${r.issuer}${r.issuerChecked ? '' : ' (not checked against an expected issuer)'}${vc ? `; vct ${r.vct}` : ''}; disclosed: ${r.disclosed.join(', ') || 'nothing'}${stare}`);
// AIP-25 C1: textul spune si daca fiecare semnatura judecata e post-cuantica (in --json: postQuantum)
const pq = r.postQuantum ? '; post-quantum: every signature judged is ML-DSA-65' : `; NOT post-quantum: the issuer signed ${r.alg}${r.keyBinding ? ', the key binding ' + r.keyBinding.alg : ''}${vc && r.status && r.status.judged ? ' (or the status list is not ML-DSA-65)' : ''}`;
console.log(`VALID: issued by ${r.issuer}${r.issuerChecked ? '' : ' (not checked against an expected issuer)'}${vc ? `; vct ${r.vct}` : ''}; disclosed: ${r.disclosed.join(', ') || 'nothing'}${stare}${pq}`);
}
return r.valid ? 0 : 1;
}
+6 -5
View File
@@ -60,14 +60,15 @@ async function main() {
// ---------------------------------------------------------------- partea NOASTRA
function cheiNoi(alg) {
if (alg === 'ES256') { const k = crypto.generateKeyPairSync('ec', { namedCurve: 'P-256' }); return { priv: k.privateKey, pub: k.publicKey, jwk: J.publicJwk(k.publicKey), alg }; }
const k = I.generateKeys(); return { priv: k, pub: k.public, jwk: J.publicJwk(k, alg), alg };
const k = I.generateKeys(); return { priv: k, pub: k.public, jwk: J.publicJwk(k, alg, { classicalHalf: true }), alg };
}
const CL = { given_name: 'Ana', family_name: 'Pop', birthdate: '1990-01-01', age_over_18: true, nationalities: ['RO', 'DE'], address: { locality: 'Cluj', country: 'RO' }, issuing_authority: 'Example Authority', issuing_country: 'RO' };
// status: null = credential FARA status (un `undefined` ar lua valoarea implicita a parametrului)
const noiEmite = ({ iss, hol, alg, status = { status_list: { idx: IDX, uri: URI } }, extra = {} }) => V.issueSdJwtVc({ issuer: iss.priv, holder: hol.pub, vct: VCT, claims: CL, disclosable: ['given_name', 'family_name', 'birthdate', 'age_over_18', 'address'], arrayDisclosable: ['nationalities'], iss: 'https://issuer.aere.example', iat: CEAS, nbf: CEAS, exp: CEAS + 365 * 86400, alg, holderAlg: hol.alg, decoys: 2, ...(status !== null ? { status } : {}), ...extra });
const noiPrezinta = (sd, reveal, hol, extra = {}) => V.presentSdJwtVc({ sdJwt: sd, reveal, holder: hol.priv, holderAlg: hol.alg, audience: AUD, nonce: NONCE, iat: CEAS, ...extra });
// 2026-10-19 (AIP-25 C1): jumatatea Ed25519 a cheilor AERE se cere explicit (classicalHalf); masuratoarea EdDSA din 18 oct o folosea implicit
const noiEmite = ({ iss, hol, alg, status = { status_list: { idx: IDX, uri: URI } }, extra = {} }) => V.issueSdJwtVc({ classicalHalf: true, issuer: iss.priv, holder: hol.pub, vct: VCT, claims: CL, disclosable: ['given_name', 'family_name', 'birthdate', 'age_over_18', 'address'], arrayDisclosable: ['nationalities'], iss: 'https://issuer.aere.example', iat: CEAS, nbf: CEAS, exp: CEAS + 365 * 86400, alg, holderAlg: hol.alg, decoys: 2, ...(status !== null ? { status } : {}), ...extra });
const noiPrezinta = (sd, reveal, hol, extra = {}) => V.presentSdJwtVc({ classicalHalf: true, sdJwt: sd, reveal, holder: hol.priv, holderAlg: hol.alg, audience: AUD, nonce: NONCE, iat: CEAS, ...extra });
const noiVerifica = (sd, { issuerKey, alg, statusListJwt = null, optiuni = {} }) => V.verifySdJwtVc(sd, { issuerKey, issuerAlg: alg, audience: AUD, nonce: NONCE, now: LA, expectedVct: VCT, ...(statusListJwt != null ? { statusListJwt } : {}), ...optiuni });
const listaNoi = (iss, statuses, bits = 1, extra = {}) => V.issueStatusListJwt({ issuer: iss.priv, alg: iss.alg, uri: URI, statuses, bits, iat: CEAS, exp: CEAS + 3600, ...extra });
const listaNoi = (iss, statuses, bits = 1, extra = {}) => V.issueStatusListJwt({ classicalHalf: true, issuer: iss.priv, alg: iss.alg, uri: URI, statuses, bits, iat: CEAS, exp: CEAS + 3600, ...extra });
const toateValide = new Array(N).fill(0);
const revocat = toateValide.map((_, i) => (i === IDX ? 1 : 0));
const suspendat = toateValide.map((_, i) => (i === IDX ? 2 : 0));
@@ -170,7 +171,7 @@ async function main() {
const citit = V.readStatusListJwt(lAmestec, { key: iss.jwk, alg: 'EdDSA', uri: URI, now: LA });
const citite = citit.ok ? amestec.map((_, i) => citit.statusAt(i)) : null;
rand({ sens: 'lor->noi', caz: 'IMPACHETARE: lista LOR pe 2 biti cu 12 stari amestecate, citite de noi index cu index', noi: { valid: citit.ok && egal(citite, amestec), reason: citit.ok ? 'citit ' + JSON.stringify(citite) : citit.reason }, lor: { valid: true }, asteptat: { noi: 'VALID', lor: 'VALID' }, nota: 'citit: ' + JSON.stringify(citite) + ' = scris: ' + JSON.stringify(amestec) });
const lNoiAmestec = V.issueStatusListJwt({ issuer: cheiNoi('EdDSA').priv, uri: URI, statuses: amestec, bits: 2, iat: CEAS });
const lNoiAmestec = V.issueStatusListJwt({ issuer: cheiNoi('EdDSA').priv, alg: 'EdDSA', classicalHalf: true, uri: URI, statuses: amestec, bits: 2, iat: CEAS });
const lorCitit = amestec.map((_, i) => tsl.getListFromStatusListJWT(lNoiAmestec).getStatus(i));
rand({ sens: 'noi->lor', caz: 'IMPACHETARE: lista NOASTRA pe 2 biti cu 12 stari amestecate, citite de ei index cu index', noi: { valid: true }, lor: { valid: egal(lorCitit, amestec), reason: 'citit ' + JSON.stringify(lorCitit) }, asteptat: { noi: 'VALID', lor: 'VALID' }, nota: 'citit: ' + JSON.stringify(lorCitit) + ' = scris: ' + JSON.stringify(amestec) });
await neg('NEGATIV: lista LOR pentru ALT uri (sub != uri-ul din jeton)', { lista: await listaLor(iss, toateValide, 1, { uri: URI + '-alta' }), motivNoi: /sub .* is not the uri/, motivLor: /sub|uri|Status List/i });
+4 -3
View File
@@ -76,10 +76,11 @@ async function main() {
const CL = { given_name: 'Ana', family_name: 'Pop', age_over_18: true, nationalities: ['RO', 'DE'], address: { street_address: 'Str. Lunga 1', locality: 'Cluj', country: 'RO' } };
function cheiNoi(alg) {
if (alg === 'ES256') { const k = crypto.generateKeyPairSync('ec', { namedCurve: 'P-256' }); return { priv: k.privateKey, pub: k.publicKey, jwk: J.publicJwk(k.publicKey), alg }; }
const k = I.generateKeys(); return { priv: k, pub: k.public, jwk: J.publicJwk(k, alg), alg };
const k = I.generateKeys(); return { priv: k, pub: k.public, jwk: J.publicJwk(k, alg, { classicalHalf: true }), alg };
}
const noiEmite = ({ iss, hol, alg, extra = {} }) => J.issueSdJwt({ issuer: iss.priv, holder: hol.pub, claims: CL, disclosable: ['given_name', 'family_name', 'age_over_18'], arrayDisclosable: ['nationalities'], iss: 'https://issuer.aere.example', iat: CEAS, exp: CEAS + 365 * 86400, alg, holderAlg: hol.alg, decoys: 2, ...extra });
const noiPrezinta = (sd, reveal, hol, extra = {}) => J.presentSdJwt({ sdJwt: sd, reveal, holder: hol.priv, holderAlg: hol.alg, audience: AUD, nonce: NONCE, iat: CEAS, ...extra });
// 2026-10-19 (AIP-25 C1): jumatatea Ed25519 a cheilor AERE se cere explicit (classicalHalf); masuratoarea EdDSA din 18 oct o folosea implicit
const noiEmite = ({ iss, hol, alg, extra = {} }) => J.issueSdJwt({ classicalHalf: true, issuer: iss.priv, holder: hol.pub, claims: CL, disclosable: ['given_name', 'family_name', 'age_over_18'], arrayDisclosable: ['nationalities'], iss: 'https://issuer.aere.example', iat: CEAS, exp: CEAS + 365 * 86400, alg, holderAlg: hol.alg, decoys: 2, ...extra });
const noiPrezinta = (sd, reveal, hol, extra = {}) => J.presentSdJwt({ classicalHalf: true, sdJwt: sd, reveal, holder: hol.priv, holderAlg: hol.alg, audience: AUD, nonce: NONCE, iat: CEAS, ...extra });
const jwtDin = (antet, corp, k) => { const cap = b64u(JSON.stringify(antet)) + '.' + b64u(JSON.stringify(corp)); const date = Buffer.from(cap, 'ascii'); return cap + '.' + b64u(antet.alg === 'ES256' ? crypto.sign('sha256', date, { key: k, dsaEncoding: 'ieee-p1363' }) : crypto.sign(null, date, k)); };
const sha = (d) => crypto.createHash('sha256').update(d).digest('base64url');
+25 -9
View File
@@ -31,17 +31,33 @@ const arata = (sd, reveal, o = {}) => V.presentSdJwtVc({ sdJwt: sd, reveal, hold
const judeca = (p, o = {}) => V.verifySdJwtVc(p, { issuerKey: iss, audience: AUD, nonce: NONCE, now: LA, expectedVct: VCT, ...o });
const lista = (statuses, bits = 1, o = {}) => V.issueStatusListJwt({ issuer: iss, uri: URI, statuses, bits, iat: NOW, exp: NOW + 3600, ...o });
const TOATE0 = new Array(16).fill(0), REVOCAT = TOATE0.map((_, i) => (i === IDX ? 1 : 0)), SUSPENDAT = TOATE0.map((_, i) => (i === IDX ? 2 : 0));
// 2026-10-19 (AIP-25 C1): cu chei AERE, jetonul si lista de stare se semneaza si se judeca implicit cu jumatatea ML-DSA-65; cele facute de
// mana mai jos sunt semnate cu ea (cu jumatatea Ed25519 singura ar cadea pe hybrid-half inaintea regulii masurate)
const PQ = 'ML-DSA-65', EM = iss.privat.mldsa65;
const jwtDin = (antet, corp, cheie) => { const cap = b64u(JSON.stringify(antet)) + '.' + b64u(JSON.stringify(corp)); return cap + '.' + b64u(crypto.sign(null, Buffer.from(cap), cheie)); };
const E = emite(), P = arata(E.sdJwt, ['birthdate', 'age_over_18', { element: 'RO', in: 'nationalities' }]);
test('PROFIL: emitere SD-JWT VC (typ dc+sd-jwt, vct, iss, cnf, nbf/exp, status) si verificare cu lista de stare (toate 0): VALID, starea judecata 0, numai ce s-a aratat', () => {
const h = JSON.parse(Buffer.from(E.sdJwt.split('.')[0], 'base64url').toString('utf8')); cere(h.typ === 'dc+sd-jwt' && h.alg === 'EdDSA', JSON.stringify(h));
const h = JSON.parse(Buffer.from(E.sdJwt.split('.')[0], 'base64url').toString('utf8')); cere(h.typ === 'dc+sd-jwt' && h.alg === PQ, JSON.stringify(h));
const r = judeca(P, { statusListJwt: lista(TOATE0) });
cere(r.valid, r.reason);
cere(r.vct === VCT && r.payload.vct === VCT && r.payload.iss === 'https://issuer.example' && r.payload.cnf && r.payload.nbf === NOW && r.payload.exp === NOW + 365 * 86400, JSON.stringify(Object.keys(r.payload)));
cere(r.payload.birthdate === '1990-01-01' && r.payload.age_over_18 === true && !('given_name' in r.payload) && !('address' in r.payload) && egal(r.payload.nationalities, ['RO']) && r.payload.issuing_country === 'RO', JSON.stringify(r.payload));
cere(egal(r.status, { present: true, judged: true, mechanism: 'status_list', uri: URI, idx: IDX, value: 0, name: 'VALID' }), JSON.stringify(r.status));
cere(r.keyBinding && r.keyBinding.aud === AUD && r.keyBinding.nonce === NONCE, JSON.stringify(r.keyBinding));
// AIP-25 C1: credentialul, Key Binding-ul si lista de stare implicite ale unor chei AERE sunt toate ML-DSA-65
cere(r.postQuantum === true && r.alg === PQ && r.keyBinding.alg === PQ, 'postQuantum=' + r.postQuantum + ' ' + r.alg + '/' + r.keyBinding.alg);
});
test('AIP-25 C1: lista de stare a unui emitent AERE e semnata implicit ML-DSA-65; una semnata NUMAI cu jumatatea Ed25519 (cine a spart doar cheia clasica "dezrevoca" credentialul) -> refuzata implicit (Ed25519 half); cu classicalHalf -> primita, dar verdictul VC e postQuantum false; un credential doar-Ed25519 -> hybrid-half', () => {
const lp = lista(TOATE0); cere(JSON.parse(Buffer.from(lp.split('.')[0], 'base64url').toString('utf8')).alg === PQ, 'lista implicita nu e ML-DSA-65');
const corp = JSON.parse(Buffer.from(lp.split('.')[1], 'base64url').toString('utf8'));
const clasica = jwtDin({ alg: 'EdDSA', typ: 'statuslist+jwt' }, corp, iss.privat.ed25519);
const a = judeca(P, { statusListJwt: clasica }); cere(!a.valid && a.rule === 'status-list' && /Ed25519 half/.test(a.reason) && a.postQuantum === false, 'lista doar-Ed25519, implicit: ' + (a.valid ? 'VALID' : a.rule + ': ' + a.reason));
const b = judeca(P, { statusListJwt: clasica, classicalHalf: true }); cere(b.valid && b.status.judged && b.alg === PQ && b.postQuantum === false, 'lista doar-Ed25519 cu classicalHalf: ' + (b.valid ? 'pq=' + b.postQuantum : b.reason));
cere(/classicalHalf/.test((() => { try { V.issueStatusListJwt({ issuer: iss, alg: 'EdDSA', uri: URI, statuses: TOATE0, iat: NOW }); return ''; } catch (e) { return e.message; } })()), 'lista EdDSA emisa fara classicalHalf');
const corpC = JSON.parse(Buffer.from(E.sdJwt.split('~')[0].split('.')[1], 'base64url').toString('utf8'));
const c1 = jwtDin({ alg: 'EdDSA', typ: 'dc+sd-jwt' }, corpC, iss.privat.ed25519) + '~' + E.sdJwt.split('~').slice(1).join('~');
const c = judeca(arata(c1, ['birthdate']), { statusListJwt: lp }); cere(!c.valid && c.rule === 'hybrid-half', 'credentialul doar-Ed25519: ' + (c.valid ? 'VALID' : c.rule));
});
test('PROFIL vct: verificatorul fara expectedVct -> refuzat; alt vct asteptat -> refuzat; lista de vct-uri acceptate -> primit; jeton fara vct -> refuzat (s.2.2.2.3 REQUIRED)', () => {
cere(refuz(V.verifySdJwtVc(P, { issuerKey: iss, audience: AUD, nonce: NONCE, now: LA, statusListJwt: lista(TOATE0) }), /must name the vct/), 'fara expectedVct a trecut');
@@ -66,10 +82,10 @@ test('PROFIL s.2.2.2.3: emitentul refuza vct/status/iss/exp/cnf dezvaluibile, vc
cere(incearca({ disclosable: ['sub'] }) === null, 'sub dezvaluibil refuzat (s.2.2.2.3 il lasa)');
// verificatorul: o dezvaluire numita status / vct, facuta de mana si semnata de emitent
const fa = (nume, val) => { const d = b64u(JSON.stringify(['s1', nume, val])); const dg = crypto.createHash('sha256').update(d).digest('base64url');
return jwtDin({ alg: 'EdDSA', typ: 'dc+sd-jwt' }, { vct: VCT, iss: 'x', exp: NOW + 100, _sd_alg: 'sha-256', _sd: [dg] }, iss.privat.ed25519) + '~' + d + '~'; };
return jwtDin({ alg: PQ, typ: 'dc+sd-jwt' }, { vct: VCT, iss: 'x', exp: NOW + 100, _sd_alg: 'sha-256', _sd: [dg] }, EM) + '~' + d + '~'; };
cere(refuz(judeca(fa('status', { status_list: { idx: 1, uri: URI } }), { requireKeyBinding: false }), /status was selectively disclosed/), 'status dezvaluit a trecut');
const dv = b64u(JSON.stringify(['s1', 'nationalities', ['RO']])), dgv = crypto.createHash('sha256').update(dv).digest('base64url');
const bun = jwtDin({ alg: 'EdDSA', typ: 'dc+sd-jwt' }, { vct: VCT, iss: 'x', exp: NOW + 100, _sd_alg: 'sha-256', _sd: [dgv] }, iss.privat.ed25519) + '~' + dv + '~';
const bun = jwtDin({ alg: PQ, typ: 'dc+sd-jwt' }, { vct: VCT, iss: 'x', exp: NOW + 100, _sd_alg: 'sha-256', _sd: [dgv] }, EM) + '~' + dv + '~';
cere(judeca(bun, { requireKeyBinding: false }).valid, 'martorul (o dezvaluire obisnuita) refuzat');
});
test('STARE: lista lipsa -> refuzat implicit (requireStatus, cu uri-ul de adus in motiv); requireStatus:false -> VALID cu starea prezenta si nejudecata; credential fara status -> VALID fara lista', () => {
@@ -77,7 +93,7 @@ test('STARE: lista lipsa -> refuzat implicit (requireStatus, cu uri-ul de adus i
const r2 = judeca(P, { requireStatus: false }); cere(r2.valid && egal(r2.status, { present: true, judged: false, mechanism: 'status_list', uri: URI, idx: IDX }), r2.reason + ' ' + JSON.stringify(r2.status));
const F = emite({ status: undefined }); const r3 = judeca(arata(F.sdJwt, ['birthdate'])); cere(r3.valid && egal(r3.status, { present: false, judged: false }), r3.reason + ' ' + JSON.stringify(r3.status));
// un mecanism de stare pe care nu il stim: prezent, nejudecat
const alt = jwtDin({ alg: 'EdDSA', typ: 'dc+sd-jwt' }, { vct: VCT, iss: 'x', exp: NOW + 100, status: { identifier_list: { id: '1', uri: URI } } }, iss.privat.ed25519) + '~';
const alt = jwtDin({ alg: PQ, typ: 'dc+sd-jwt' }, { vct: VCT, iss: 'x', exp: NOW + 100, status: { identifier_list: { id: '1', uri: URI } } }, EM) + '~';
const r4 = judeca(alt, { requireKeyBinding: false }); cere(refuz(r4, /was not judged/) && r4.status.mechanism === 'identifier_list', r4.reason);
cere(judeca(alt, { requireKeyBinding: false, requireStatus: false }).valid, 'mecanismul necunoscut cu requireStatus:false refuzat');
});
@@ -102,11 +118,11 @@ test('STARE: lista pentru alt uri (sub), expirata, semnata de alta cheie, cu typ
cere(refuz(judeca(P, { statusListJwt: V.issueStatusListJwt({ issuer: strain, uri: URI, statuses: TOATE0, iat: NOW }) }), /status list: the signature does not verify/), 'alta cheie a trecut');
cere(judeca(P, { statusListJwt: V.issueStatusListJwt({ issuer: strain, uri: URI, statuses: TOATE0, iat: NOW }), statusListKey: strain }).valid, 'cheia listei data separat refuzata');
const corp = JSON.parse(Buffer.from(lista(TOATE0).split('.')[1], 'base64url').toString('utf8'));
cere(refuz(judeca(P, { statusListJwt: jwtDin({ alg: 'EdDSA', typ: 'JWT' }, corp, iss.privat.ed25519) }), /status list: typ/), 'typ JWT a trecut');
cere(refuz(judeca(P, { statusListJwt: jwtDin({ alg: PQ, typ: 'JWT' }, corp, EM) }), /status list: typ/), 'typ JWT a trecut');
const { iat: _i, ...faraIat } = corp;
cere(refuz(judeca(P, { statusListJwt: jwtDin({ alg: 'EdDSA', typ: 'statuslist+jwt' }, faraIat, iss.privat.ed25519) }), /status list: iat is required/), 'fara iat a trecut');
cere(refuz(judeca(P, { statusListJwt: jwtDin({ alg: 'EdDSA', typ: 'statuslist+jwt' }, { ...corp, status_list: { ...corp.status_list, bits: 3 } }, iss.privat.ed25519) }), /status list: status_list must be/), 'bits 3 a trecut');
cere(refuz(judeca(P, { statusListJwt: jwtDin({ alg: 'EdDSA', typ: 'statuslist+jwt' }, { ...corp, iat: NOW + 600 }, iss.privat.ed25519) }), /status list: issued in the future/), 'iat in viitor a trecut');
cere(refuz(judeca(P, { statusListJwt: jwtDin({ alg: PQ, typ: 'statuslist+jwt' }, faraIat, EM) }), /status list: iat is required/), 'fara iat a trecut');
cere(refuz(judeca(P, { statusListJwt: jwtDin({ alg: PQ, typ: 'statuslist+jwt' }, { ...corp, status_list: { ...corp.status_list, bits: 3 } }, EM) }), /status list: status_list must be/), 'bits 3 a trecut');
cere(refuz(judeca(P, { statusListJwt: jwtDin({ alg: PQ, typ: 'statuslist+jwt' }, { ...corp, iat: NOW + 600 }, EM) }), /status list: issued in the future/), 'iat in viitor a trecut');
const scurta = V.issueStatusListJwt({ issuer: iss, uri: URI, statuses: [0, 0, 0, 0], bits: 8, iat: NOW });
cere(refuz(judeca(P, { statusListJwt: scurta }), /index 5 is beyond the list \(4 entries\)/), 'index dincolo a trecut');
let m = null; try { V.issueStatusListJwt({ issuer: iss, uri: URI, statuses: [0, 2], bits: 1, iat: NOW }); } catch (e) { m = e.message; } cere(/below 2\^1/.test(m || ''), 'starea 2 pe 1 bit emisa');
@@ -116,7 +132,7 @@ test('POST-CUANTIC: credential ML-DSA-65 cu lista de stare semnata ML-DSA-65 ->
const p = arata(M.sdJwt, ['birthdate'], { holderAlg: 'ML-DSA-65' });
const l = V.issueStatusListJwt({ issuer: iss, alg: 'ML-DSA-65', uri: URI, statuses: TOATE0, iat: NOW });
const r = judeca(p, { issuerAlg: 'ML-DSA-65', statusListJwt: l }); cere(r.valid && r.alg === 'ML-DSA-65' && r.status.judged, r.reason);
cere(refuz(judeca(p, { issuerAlg: 'ML-DSA-65', statusListJwt: l, statusListAlg: 'EdDSA' }), /status list: .*does not match|status list: signed with/), 'lista ML-DSA-65 judecata cu Ed25519 a trecut');
cere(refuz(judeca(p, { issuerAlg: 'ML-DSA-65', statusListJwt: l, statusListAlg: 'EdDSA' }), /status list: .*does not match|status list: signed with|status list: .*Ed25519 half/), 'lista ML-DSA-65 judecata cu Ed25519 a trecut');
});
const FX = path.join(AICI, 'interop', 'fixturi-interop-sdjwt-vc.json');
const F = fs.existsSync(FX) ? JSON.parse(fs.readFileSync(FX, 'utf8')) : null;
+120 -25
View File
@@ -57,32 +57,38 @@ test('RFC 9901: o dezvaluire scoasa din prezentare dupa semnarea KB (sd_hash) sa
});
// ---------------------------------------------------------------- jetoane emise cu chei AERE
// 2026-10-19 (AIP-25 C1, D-535): cu chei AERE (Ed25519 SI ML-DSA-65), emiterea, cnf-ul detinatorului si verificarea folosesc IMPLICIT jumatatea
// post-cuantica, ML-DSA-65; jumatatea Ed25519 numai la cerere (classicalHalf), cu verdictul postQuantum false. Probele de mai jos o masoara
// pe calea implicita; jetoanele facute de mana sunt semnate cu jumatatea ML-DSA-65 (cu cea Ed25519 singura ar cadea pe hybrid-half inaintea
// regulii pe care o masoara proba).
const NOW = Math.floor(Date.parse('2026-09-30T08:00:00Z') / 1000), LA = new Date(NOW * 1000);
const iss = I.generateKeys(), hol = I.generateKeys(), strain = I.generateKeys();
const PQ = 'ML-DSA-65', EM = iss.privat.mldsa65, HM = hol.privat.mldsa65;
const CL = { given_name: 'Ana', family_name: 'Pop', age_over_18: true, nationalities: ['RO', 'DE'], employer: 'Example Ltd' };
const emite = (o = {}) => J.issueSdJwt({ issuer: iss, holder: hol, claims: CL, disclosable: ['given_name', 'family_name', 'age_over_18'], arrayDisclosable: ['nationalities'], iss: 'https://issuer.aere.example', iat: NOW, exp: NOW + 86400, decoys: 2, ...o });
const AUD = 'https://verifier.example', NONCE = 'n-' + crypto.randomBytes(4).toString('hex');
const arata = (sd, reveal, o = {}) => J.presentSdJwt({ sdJwt: sd, reveal, holder: hol, audience: AUD, nonce: NONCE, iat: NOW, ...o });
const judeca = (p, o = {}) => J.verifySdJwt(p, { issuerKey: iss, audience: AUD, nonce: NONCE, now: LA, ...o });
const E = emite();
test('AERE -> SD-JWT (EdDSA, cheia Ed25519 a emitentului AERE): detinatorul arata age_over_18 si RO, verificatorul vede numai atat plus afirmatiile in clar', () => {
test('AERE -> SD-JWT (implicit ML-DSA-65, jumatatea post-cuantica a emitentului AERE): detinatorul arata age_over_18 si RO, verificatorul vede numai atat plus afirmatiile in clar, postQuantum true', () => {
const r = judeca(arata(E.sdJwt, ['age_over_18', { element: 'RO', in: 'nationalities' }]));
cere(r.valid, r.reason);
cere(r.payload.age_over_18 === true && !('given_name' in r.payload) && egal(r.payload.nationalities, ['RO']) && r.payload.employer === 'Example Ltd' && r.alg === 'EdDSA', JSON.stringify(r.payload));
cere(r.payload.age_over_18 === true && !('given_name' in r.payload) && egal(r.payload.nationalities, ['RO']) && r.payload.employer === 'Example Ltd' && r.alg === PQ && r.postQuantum === true, JSON.stringify(r.payload) + ' alg=' + r.alg + ' pq=' + r.postQuantum);
});
test('AERE -> SD-JWT in forma standardului: typ explicit, _sd sortat (cu momeli), _sd_alg sha-256, cnf.jwk = cheia Ed25519 a detinatorului, dezvaluiri [sare, nume, valoare]', () => {
test('AERE -> SD-JWT in forma standardului: typ explicit, _sd sortat (cu momeli), _sd_alg sha-256, cnf.jwk = cheia ML-DSA-65 (AKP, RFC 9964) a detinatorului, dezvaluiri [sare, nume, valoare]', () => {
const [h, p] = E.sdJwt.split('~')[0].split('.').slice(0, 2).map((x) => JSON.parse(Buffer.from(x, 'base64url').toString('utf8')));
cere(h.alg === 'EdDSA' && h.typ === J.TYP, JSON.stringify(h));
cere(h.alg === PQ && h.typ === J.TYP, JSON.stringify(h));
cere(Array.isArray(p._sd) && p._sd.length === 5 && egal([...p._sd].sort(), p._sd) && p._sd_alg === 'sha-256', JSON.stringify(p._sd));
cere(p.cnf.jwk.kty === 'OKP' && p.cnf.jwk.crv === 'Ed25519' && p.cnf.jwk.x === J.publicJwk(hol).x && !('d' in p.cnf.jwk), JSON.stringify(p.cnf));
cere(p.cnf.jwk.kty === 'AKP' && p.cnf.jwk.alg === PQ && p.cnf.jwk.pub === J.publicJwk(hol).pub && !('priv' in p.cnf.jwk), JSON.stringify(p.cnf).slice(0, 120));
const c = JSON.parse(Buffer.from(E.disclosures[0].disclosure, 'base64url').toString('utf8'));
cere(c.length === 3 && typeof c[0] === 'string' && c[0].length >= 22 && c[1] === 'given_name', JSON.stringify(c));
});
test('AERE -> SD-JWT post-cuantic (ML-DSA-65, cheia AKP): verifica cu cheia ML-DSA-65 a emitentului, nu cu cea Ed25519; detinatorul poate semna KB tot cu ML-DSA-65', () => {
const M = emite({ alg: 'ML-DSA-65', holderAlg: 'ML-DSA-65' });
const p = arata(M.sdJwt, ['age_over_18'], { holderAlg: 'ML-DSA-65' });
const r = judeca(p, { issuerAlg: 'ML-DSA-65' }); cere(r.valid && r.alg === 'ML-DSA-65' && r.keyBinding.alg === 'ML-DSA-65', r.reason);
cere(refuz(judeca(p, { issuerAlg: 'EdDSA' }), /does not match/), 'cheia Ed25519 a primit un jeton ML-DSA-65');
test('AERE -> SD-JWT post-cuantic numit explicit (alg ML-DSA-65): verifica cu jumatatea ML-DSA-65 a emitentului; issuerAlg EdDSA fara classicalHalf -> hybrid-half; cu classicalHalf, cheia Ed25519 nu primeste un jeton ML-DSA-65', () => {
const M = emite({ alg: PQ, holderAlg: PQ });
const p = arata(M.sdJwt, ['age_over_18'], { holderAlg: PQ });
const r = judeca(p, { issuerAlg: PQ }); cere(r.valid && r.alg === PQ && r.keyBinding.alg === PQ && r.postQuantum === true, r.reason);
const e = judeca(p, { issuerAlg: 'EdDSA' }); cere(!e.valid && e.rule === 'hybrid-half', 'issuerAlg EdDSA fara classicalHalf: ' + (e.valid ? 'VALID' : e.rule + ' ' + e.reason));
cere(refuz(judeca(p, { issuerAlg: 'EdDSA', classicalHalf: true }), /does not match/), 'cheia Ed25519 a primit un jeton ML-DSA-65');
});
// ---------------------------------------------------------------- atacuri
@@ -105,14 +111,14 @@ test('ATAC: o dezvaluire cu valoarea schimbata (alt digest, nelegata) -> refuzat
});
test('ATAC: un emitent care pune in _sd o dezvaluire cu numele "_sd", una care acopera o afirmatie in clar, sau acelasi digest de doua ori -> refuzat', () => {
const faci = (dezvaluiri, extra = {}) => { const ds = dezvaluiri.map((x) => b64u(JSON.stringify(x))); const sd = ds.map((d) => crypto.createHash('sha256').update(d).digest('base64url'));
return jwtDin({ alg: 'EdDSA', typ: J.TYP }, { _sd: extra.dublu ? [...sd, sd[0]] : sd, _sd_alg: 'sha-256', iss: 'x', ...(extra.clar || {}) }, iss.privat.ed25519) + '~' + ds.map((d) => d + '~').join(''); };
return jwtDin({ alg: PQ, typ: J.TYP }, { _sd: extra.dublu ? [...sd, sd[0]] : sd, _sd_alg: 'sha-256', iss: 'x', ...(extra.clar || {}) }, EM) + '~' + ds.map((d) => d + '~').join(''); };
cere(refuz(J.verifySdJwt(faci([['s1', '_sd', ['x']]]), { issuerKey: iss, requireKeyBinding: false, now: LA }), /may not name _sd/), '_sd a trecut');
cere(refuz(J.verifySdJwt(faci([['s1', 'role', 'admin']], { clar: { role: 'user' } }), { issuerKey: iss, requireKeyBinding: false, now: LA }), /already exists/), 'coliziunea a trecut');
cere(refuz(J.verifySdJwt(faci([['s1', 'a', 1]], { dublu: true }), { issuerKey: iss, requireKeyBinding: false, now: LA }), /more than once/), 'digestul dublu a trecut');
cere(refuz(J.verifySdJwt(faci([['s1', '__proto__', { admin: true }]]), { issuerKey: iss, requireKeyBinding: false, now: LA }), /may not name __proto__/), '__proto__ a trecut');
});
test('ATAC: o afirmatie numita __proto__ in clar sau intr-o valoare dezvaluita (prototipul payload-ului schimbat) -> refuzata', () => {
const cap = (corp) => jwtDin({ alg: 'EdDSA', typ: J.TYP }, corp, iss.privat.ed25519);
const cap = (corp) => jwtDin({ alg: PQ, typ: J.TYP }, corp, EM);
const clar = JSON.parse('{"iss":"x","_sd_alg":"sha-256","__proto__":{"admin":true}}');
cere(refuz(J.verifySdJwt(cap(clar) + '~', { issuerKey: iss, requireKeyBinding: false, now: LA }), /__proto__/), 'in clar a trecut');
const d = b64u('["s1","profil",' + '{"__proto__":{"admin":true}}' + ']');
@@ -124,9 +130,9 @@ test('ATAC: KB semnat de alta cheie decat cnf.jwk, KB cu typ gresit, KB fara non
cere(refuz(judeca(alt), /key binding: the signature does not verify/), 'cheia straina a trecut');
const baza = arata(E.sdJwt, ['age_over_18']).split('~').slice(0, -1).join('~') + '~';
const sh = crypto.createHash('sha256').update(Buffer.from(baza, 'ascii')).digest('base64url');
const tip = jwtDin({ alg: 'EdDSA', typ: 'JWT' }, { iat: NOW, aud: AUD, nonce: NONCE, sd_hash: sh }, hol.privat.ed25519);
const tip = jwtDin({ alg: PQ, typ: 'JWT' }, { iat: NOW, aud: AUD, nonce: NONCE, sd_hash: sh }, HM);
cere(refuz(judeca(baza + tip), /typ/), 'typ gresit a trecut');
const faraNonce = jwtDin({ alg: 'EdDSA', typ: 'kb+jwt' }, { iat: NOW, aud: AUD, sd_hash: sh }, hol.privat.ed25519);
const faraNonce = jwtDin({ alg: PQ, typ: 'kb+jwt' }, { iat: NOW, aud: AUD, sd_hash: sh }, HM);
cere(refuz(judeca(baza + faraNonce), /required/), 'fara nonce a trecut');
});
test('timpul: exp trecut -> refuzat (fara toleranta); nbf peste 30 s -> admis (toleranta de ceas), peste 90 s -> refuzat', () => {
@@ -154,24 +160,27 @@ test('REVIZUIRE: prezentarea arata elementul NUMAI din lista numita (acelasi RO
let m = null; try { arata(D.sdJwt, [{ element: 'IT', in: 'nationalities' }]); } catch (e) { m = e.message; } cere(/nothing to reveal/.test(m || ''), 'alegerea fara corespondent a tacut');
});
test('REVIZUIRE: cheia emitentului data ca KeyObject public sau ca identitate AERE publica (keys.public) e primita; detinatorul dat ca cheie publica', () => {
const pubKO = crypto.createPublicKey(iss.privat.ed25519);
const pubKO = crypto.createPublicKey(EM);
const D = J.issueSdJwt({ issuer: iss, holder: crypto.createPublicKey(hol.privat.ed25519), claims: { age_over_18: true }, disclosable: ['age_over_18'], iss: 'x', iat: NOW });
const p = arata(D.sdJwt, ['age_over_18']);
cere(J.verifySdJwt(p, { issuerKey: pubKO, audience: AUD, nonce: NONCE, now: LA }).valid, 'KeyObject public refuzat');
cere(J.verifySdJwt(p, { issuerKey: iss.public, audience: AUD, nonce: NONCE, now: LA }).valid, 'identitatea AERE publica refuzata');
const r = J.verifySdJwt(p, { issuerKey: iss.public, audience: AUD, nonce: NONCE, now: LA });
cere(r.valid, 'identitatea AERE publica refuzata');
// detinatorul legat cu o cheie Ed25519 (KeyObject dat la emitere): Key Binding-ul e clasic, deci verdictul nu e post-cuantic (AIP-25 C1)
cere(r.keyBinding && r.keyBinding.alg === 'EdDSA' && r.postQuantum === false, 'KB Ed25519: ' + JSON.stringify(r.keyBinding) + ' pq=' + r.postQuantum);
});
test('REVIZUIRE: exp cerut implicit (un exp dezvaluibil si retinut de detinator nu mai lasa jetonul fara expirare); requireExp:false il lasa', () => {
const dExp = b64u(JSON.stringify(['s', 'exp', NOW - 10]));
const corp = { _sd: [crypto.createHash('sha256').update(dExp).digest('base64url')], _sd_alg: 'sha-256', iss: 'x' };
const jwt = jwtDin({ alg: 'EdDSA', typ: J.TYP }, corp, iss.privat.ed25519);
const jwt = jwtDin({ alg: PQ, typ: J.TYP }, corp, EM);
cere(refuz(J.verifySdJwt(jwt + '~', { issuerKey: iss, requireKeyBinding: false, now: LA }), /exp is required/), 'fara exp a trecut');
cere(refuz(J.verifySdJwt(jwt + '~' + dExp + '~', { issuerKey: iss, requireKeyBinding: false, now: LA }), /expired/), 'exp dezvaluit si trecut a trecut');
cere(J.verifySdJwt(jwt + '~', { issuerKey: iss, requireKeyBinding: false, requireExp: false, now: LA }).valid, 'requireExp:false a refuzat');
});
test('REVIZUIRE: tipul jetonului: un KB-JWT sau un JWT cu typ JWT dat drept jeton de emitent -> refuzat implicit; expectedIssuer altul -> refuzat', () => {
const corp = { iss: 'https://issuer.aere.example', exp: NOW + 100, _sd_alg: 'sha-256' };
cere(refuz(J.verifySdJwt(jwtDin({ alg: 'EdDSA', typ: 'kb+jwt' }, corp, iss.privat.ed25519) + '~', { issuerKey: iss, requireKeyBinding: false, now: LA }), /typ/), 'kb+jwt drept emitent a trecut');
const simplu = jwtDin({ alg: 'EdDSA', typ: 'JWT' }, corp, iss.privat.ed25519) + '~';
cere(refuz(J.verifySdJwt(jwtDin({ alg: PQ, typ: 'kb+jwt' }, corp, EM) + '~', { issuerKey: iss, requireKeyBinding: false, now: LA }), /typ/), 'kb+jwt drept emitent a trecut');
const simplu = jwtDin({ alg: PQ, typ: 'JWT' }, corp, EM) + '~';
cere(refuz(J.verifySdJwt(simplu, { issuerKey: iss, requireKeyBinding: false, now: LA }), /typ/), 'typ JWT a trecut implicit');
cere(J.verifySdJwt(simplu, { issuerKey: iss, requireKeyBinding: false, expectedTyp: null, now: LA }).valid, 'expectedTyp:null a refuzat un JWT simplu');
const bun = J.verifySdJwt(arata(E.sdJwt, ['age_over_18']), { issuerKey: iss, audience: AUD, nonce: NONCE, now: LA, expectedIssuer: 'https://issuer.aere.example' });
@@ -180,22 +189,24 @@ test('REVIZUIRE: tipul jetonului: un KB-JWT sau un JWT cu typ JWT dat drept jeto
});
test('REVIZUIRE: crit (orice forma), base64url necanonic al semnaturii, KB expirat sau inca nevalabil (nbf) -> refuzate', () => {
const corp = { iss: 'x', exp: NOW + 100, _sd_alg: 'sha-256', meta: { note: 1 } };
for (const crit of [[], 'b64', ['b64']]) cere(refuz(J.verifySdJwt(jwtDin({ alg: 'EdDSA', typ: J.TYP, crit, b64: false }, corp, iss.privat.ed25519) + '~', { issuerKey: iss, requireKeyBinding: false, now: LA }), /crit/), 'crit ' + JSON.stringify(crit));
for (const crit of [[], 'b64', ['b64']]) cere(refuz(J.verifySdJwt(jwtDin({ alg: PQ, typ: J.TYP, crit, b64: false }, corp, EM) + '~', { issuerKey: iss, requireKeyBinding: false, now: LA }), /crit/), 'crit ' + JSON.stringify(crit));
// base64url necanonic: o semnatura Ed25519 (64 de octeti) are doi biti nefolositi in ultimul caracter; una ML-DSA-65 (3309 = 3 x 1103
// octeti) nu are niciunul, deci proba ramane pe jumatatea clasica, ceruta explicit (AIP-25 C1)
const j = jwtDin({ alg: 'EdDSA', typ: J.TYP }, corp, iss.privat.ed25519);
const r = J.verifySdJwt(j + '~', { issuerKey: iss, requireKeyBinding: false, now: LA });
const r = J.verifySdJwt(j + '~', { issuerKey: iss, classicalHalf: true, requireKeyBinding: false, now: LA });
cere(r.valid && r.payload.meta.note === 1 && !('_sd_alg' in r.payload), 'martorul: ' + JSON.stringify(r.payload));
const ALF = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_';
const u = j[j.length - 1], alt = ALF[ALF.indexOf(u) ^ 1];
const nec = j.slice(0, -1) + alt;
cere(Buffer.from(nec.split('.')[2], 'base64url').equals(Buffer.from(j.split('.')[2], 'base64url')), 'proba: scrierea alternativa trebuie sa dea aceiasi octeti');
cere(refuz(J.verifySdJwt(nec + '~', { issuerKey: iss, requireKeyBinding: false, now: LA }), /canonical/), 'semnatura necanonica a trecut');
cere(refuz(J.verifySdJwt(nec + '~', { issuerKey: iss, classicalHalf: true, requireKeyBinding: false, now: LA }), /canonical/), 'semnatura necanonica a trecut');
const baza = arata(E.sdJwt, ['age_over_18']).split('~').slice(0, -1).join('~') + '~';
const sh = crypto.createHash('sha256').update(Buffer.from(baza, 'ascii')).digest('base64url');
const kbExp = jwtDin({ alg: 'EdDSA', typ: 'kb+jwt' }, { iat: NOW, aud: AUD, nonce: NONCE, sd_hash: sh, exp: NOW - 100 }, hol.privat.ed25519);
const kbExp = jwtDin({ alg: PQ, typ: 'kb+jwt' }, { iat: NOW, aud: AUD, nonce: NONCE, sd_hash: sh, exp: NOW - 100 }, HM);
cere(refuz(judeca(baza + kbExp), /key binding: expired/), 'KB expirat a trecut');
// 2026-10-01: nbf-ul KB (a doua jumatate a reparatiei "exp/nbf ale KB" din B-32) nu avea proba: paznicul scos lasa proba 23/23.
// Martorul aceluiasi KB facut de mana, cu nbf in toleranta de ceas, e VALID: refuzul de mai jos e al nbf-ului, nu al constructiei.
const kbNbf = (nbf) => jwtDin({ alg: 'EdDSA', typ: 'kb+jwt' }, { iat: NOW, aud: AUD, nonce: NONCE, sd_hash: sh, nbf }, hol.privat.ed25519);
const kbNbf = (nbf) => jwtDin({ alg: PQ, typ: 'kb+jwt' }, { iat: NOW, aud: AUD, nonce: NONCE, sd_hash: sh, nbf }, HM);
const rNbfBun = judeca(baza + kbNbf(NOW + 30));
cere(rNbfBun.valid, 'martorul: KB cu nbf in toleranta (30 s) trebuie sa fie VALID: ' + rNbfBun.reason);
cere(refuz(judeca(baza + kbNbf(NOW + 600)), /key binding: not valid before/), 'KB inca nevalabil (nbf peste 10 minute) a trecut');
@@ -205,7 +216,7 @@ test('REVIZUIRE: crit (orice forma), base64url necanonic al semnaturii, KB expir
// 2026-10-18, din interoperarea cu @sd-jwt/core 0.23.0 (care refuza _sd_alg imbricat): RFC 9901 s.4.1.1 "It MUST NOT be used in any object
// nested within the payload"; pana atunci il pastram ca afirmatie. Si RFC 7515 s.4.1.9: typ-ul "application/x+sd-jwt" e acelasi cu "x+sd-jwt".
test('INTEROP: _sd_alg imbricat (in clar sau intr-o valoare dezvaluita) -> refuzat (RFC 9901 s.4.1.1); o dezvaluire numita _sd_alg -> refuzata; typ cu prefixul application/ -> acelasi tip (RFC 7515 s.4.1.9)', () => {
const cap = (corp, typ = J.TYP) => jwtDin({ alg: 'EdDSA', typ }, corp, iss.privat.ed25519);
const cap = (corp, typ = J.TYP) => jwtDin({ alg: PQ, typ }, corp, EM);
const o = { issuerKey: iss, requireKeyBinding: false, now: LA };
cere(refuz(J.verifySdJwt(cap({ iss: 'x', exp: NOW + 100, _sd_alg: 'sha-256', meta: { _sd_alg: 'x', note: 1 } }) + '~', o), /_sd_alg below the top level/), 'imbricat in clar a trecut');
const dIm = b64u(JSON.stringify(['s1', 'meta', { _sd_alg: 'sha-256', note: 1 }])), dgIm = crypto.createHash('sha256').update(dIm).digest('base64url');
@@ -234,6 +245,8 @@ test(`INTEROP (fixturi @sd-jwt/core ${F2 ? F2.biblioteci['@sd-jwt/core'] : '?'}
cere(r.valid, c.nume + ': ' + r.reason);
cere(egal(r.payload, c.asteptat.payload) && egal([...r.disclosed].sort(), c.asteptat.disclosed), c.nume + ': rezultatul difera de cel inregistrat: ' + JSON.stringify(r.payload).slice(0, 200));
cere(r.payload.address && r.payload.address.locality === 'Cluj' && !('street_address' in r.payload.address) && egal(r.payload.nationalities, ['RO']) && !('given_name' in r.payload), c.nume + ': dezvaluirile imbricate/de lista nu sunt cele asteptate');
// AIP-25 C1: cheia lor e un JWK simplu (nicio jumatate de pierdut); verdictul spune daca fiecare semnatura judecata e post-cuantica
cere(r.postQuantum === (r.alg === PQ && (!r.keyBinding || r.keyBinding.alg === PQ)), c.nume + ': postQuantum=' + r.postQuantum + ' pentru ' + r.alg + '/' + (r.keyBinding && r.keyBinding.alg));
valide++;
} else { cere(refuz(r, new RegExp(c.asteptat.motiv)), c.nume + ': asteptat refuz /' + c.asteptat.motiv + '/, primit ' + (r.valid ? 'VALID' : r.reason)); refuzate++; }
}
@@ -244,6 +257,73 @@ test(`INTEROP (fixturi @sd-jwt/core ${F2 ? F2.biblioteci['@sd-jwt/core'] : '?'}
cere(faraTyp && refuz(J.verifySdJwt(faraTyp.prezentare, { issuerKey: faraTyp.issuerJwk, issuerAlg: faraTyp.alg, audience: F2.audience, nonce: F2.nonce, now: la }), /typ/), 'jetonul lor fara typ a trecut de tipul implicit');
});
// ---------------------------------------------------------------- AIP-25 C1 (D-535, 2026-10-19): jumatatea clasica a unei identitati hibride
// Cheile unei identitati AERE sunt Ed25519 SI ML-DSA-65 (identity.mjs cere amandoua semnaturile). Pana pe 19 oct verificatorul SD-JWT alegea
// IMPLICIT jumatatea Ed25519, deci cine spargea NUMAI cheia clasica a emitentului facea credentiale primite contra identitatii lui intregi.
const corpE = corpDe(E.sdJwt);
const dezvE = E.sdJwt.split('~').slice(1).join('~'); // dezvaluirile lui E, fiecare urmata de ~
// ce poate face cine are NUMAI cheia Ed25519 a emitentului: aceleasi afirmatii, semnate cu ea
const doarClasic = (alg = 'EdDSA', corp = corpE, cheie = iss.privat.ed25519) => jwtDin({ alg, typ: J.TYP }, corp, cheie) + '~' + dezvE;
const nuArunca = (f) => { try { f(); return null; } catch (e) { return String(e.message || e); } };
test('AIP-25 C1: un SD-JWT semnat NUMAI cu jumatatea Ed25519 a emitentului AERE (ce face cine a spart doar cheia clasica), judecat implicit contra cheilor AERE -> REFUZAT pe regula hybrid-half, postQuantum false; acelasi credential cinstit -> VALID, postQuantum true', () => {
const atac = judeca(arata(doarClasic(), ['age_over_18']));
cere(!atac.valid && atac.rule === 'hybrid-half' && atac.postQuantum === false, 'jetonul doar-Ed25519, cheile AERE private: ' + (atac.valid ? 'VALID' : atac.rule + ': ' + atac.reason));
const pub = judeca(arata(doarClasic(), ['age_over_18']), { issuerKey: iss.public });
cere(!pub.valid && pub.rule === 'hybrid-half' && /Ed25519 half/.test(pub.reason), 'contra identitatii AERE PUBLICE (keys.public): ' + (pub.valid ? 'VALID' : pub.rule));
const plin = judeca(arata(doarClasic('Ed25519'), ['age_over_18']));
cere(!plin.valid && plin.rule === 'hybrid-half', 'antetul Ed25519 (numele complet din RFC 9864): ' + (plin.valid ? 'VALID' : plin.rule));
const bun = judeca(arata(E.sdJwt, ['age_over_18']));
cere(bun.valid && bun.alg === PQ && bun.postQuantum === true, 'credentialul cinstit: ' + (bun.valid ? bun.alg + ' pq=' + bun.postQuantum : bun.reason));
});
test('AIP-25 C1: jumatatea clasica se judeca NUMAI la cerere: issuerAlg EdDSA fara classicalHalf -> hybrid-half; classicalHalf:true -> VALID cu postQuantum false (verdictul o spune); classicalHalf primeste si jetonul ML-DSA-65, cu postQuantum true; classicalHalf + issuerAlg ML-DSA-65 pe jetonul clasic -> hybrid-half', () => {
const p = arata(doarClasic(), ['age_over_18']);
const a = judeca(p, { issuerAlg: 'EdDSA' }); cere(!a.valid && a.rule === 'hybrid-half', 'issuerAlg EdDSA fara classicalHalf: ' + (a.valid ? 'VALID' : a.rule));
const b = judeca(p, { classicalHalf: true }); cere(b.valid && b.alg === 'EdDSA' && b.postQuantum === false, 'classicalHalf: ' + (b.valid ? 'pq=' + b.postQuantum : b.reason));
const c = judeca(p, { classicalHalf: true, issuerAlg: 'EdDSA' }); cere(c.valid && c.postQuantum === false, 'classicalHalf + issuerAlg EdDSA: ' + (c.valid ? 'pq=' + c.postQuantum : c.reason));
const d = judeca(arata(E.sdJwt, ['age_over_18']), { classicalHalf: true }); cere(d.valid && d.alg === PQ && d.postQuantum === true, 'classicalHalf pe jetonul post-cuantic: ' + (d.valid ? d.alg + ' pq=' + d.postQuantum : d.reason));
const e = judeca(p, { classicalHalf: true, issuerAlg: PQ }); cere(!e.valid && e.rule === 'hybrid-half', 'classicalHalf + issuerAlg ML-DSA-65 pe jetonul clasic: ' + (e.valid ? 'VALID' : e.rule));
});
test('AIP-25 C1: emiterea implicita cu chei AERE e post-cuantica (antet ML-DSA-65, cnf.jwk AKP ML-DSA-65, KB ML-DSA-65); EdDSA la emitere sau in cnf cere classicalHalf; publicJwk(chei AERE) = jumatatea ML-DSA-65, cea Ed25519 numai cu { classicalHalf: true }, ES256 deloc', () => {
const h = JSON.parse(Buffer.from(E.sdJwt.split('.')[0], 'base64url').toString('utf8'));
cere(h.alg === PQ && corpE.cnf.jwk.kty === 'AKP' && corpE.cnf.jwk.alg === PQ, 'emiterea implicita: ' + JSON.stringify(h) + ' cnf ' + (corpE.cnf.jwk.kty + '/' + corpE.cnf.jwk.alg));
const kb = arata(E.sdJwt, ['age_over_18']).split('~').pop(); const hk = JSON.parse(Buffer.from(kb.split('.')[0], 'base64url').toString('utf8'));
cere(hk.alg === PQ, 'Key Binding-ul implicit: ' + JSON.stringify(hk));
cere(/classicalHalf/.test(nuArunca(() => emite({ alg: 'EdDSA' })) || ''), 'emiterea EdDSA fara classicalHalf a tacut');
cere(/classicalHalf/.test(nuArunca(() => emite({ holderAlg: 'EdDSA' })) || ''), 'cnf Ed25519 fara classicalHalf a tacut');
const C = emite({ alg: 'EdDSA', holderAlg: 'EdDSA', classicalHalf: true });
const rc = judeca(arata(C.sdJwt, ['age_over_18']), { classicalHalf: true });
cere(rc.valid && rc.alg === 'EdDSA' && rc.keyBinding.alg === 'EdDSA' && rc.postQuantum === false, 'emiterea clasica ceruta: ' + (rc.valid ? 'pq=' + rc.postQuantum : rc.reason));
cere(J.publicJwk(iss).kty === 'AKP' && J.publicJwk(iss.public).kty === 'AKP' && J.publicJwk(iss.public, PQ).pub === J.publicJwk(iss).pub, 'publicJwk implicit');
cere(/classicalHalf/.test(nuArunca(() => J.publicJwk(iss, 'EdDSA')) || '') && /classicalHalf/.test(nuArunca(() => J.publicJwk(iss.public, 'Ed25519')) || ''), 'publicJwk EdDSA/Ed25519 fara classicalHalf a tacut');
cere(J.publicJwk(iss, 'EdDSA', { classicalHalf: true }).crv === 'Ed25519', 'publicJwk EdDSA cu classicalHalf');
cere(/no ES256 key/.test(nuArunca(() => J.publicJwk(iss, 'ES256')) || ''), 'publicJwk ES256 pe chei AERE a dat o cheie');
});
test('AIP-25 C1: un JWK simplu ramane cum e (nicio jumatate de pierdut), iar verdictul spune postQuantum: Ed25519 OKP -> VALID postQuantum false; AKP ML-DSA-65 -> VALID postQuantum true; ES256 al standardului -> postQuantum false; un Key Binding clasic peste un emitent ML-DSA-65 -> postQuantum false', () => {
const okp = judeca(arata(doarClasic(), ['age_over_18']), { issuerKey: J.publicJwk(iss, 'EdDSA', { classicalHalf: true }) });
cere(okp.valid && okp.alg === 'EdDSA' && okp.postQuantum === false, 'OKP simplu: ' + (okp.valid ? 'pq=' + okp.postQuantum : okp.reason));
const akp = judeca(arata(E.sdJwt, ['age_over_18']), { issuerKey: J.publicJwk(iss) });
cere(akp.valid && akp.postQuantum === true, 'AKP simplu: ' + (akp.valid ? 'pq=' + akp.postQuantum : akp.reason));
const rfc = J.verifySdJwt(F.presentation, { issuerKey: F.issuerJwk, audience: KB.aud, nonce: KB.nonce, now: LA_KB });
cere(rfc.valid && rfc.alg === 'ES256' && rfc.postQuantum === false, 'ES256 al standardului: ' + (rfc.valid ? 'pq=' + rfc.postQuantum : rfc.reason));
const K = emite({ holderAlg: 'EdDSA', classicalHalf: true }); const rk = judeca(arata(K.sdJwt, ['age_over_18']));
cere(rk.valid && rk.alg === PQ && rk.keyBinding.alg === 'EdDSA' && rk.postQuantum === false, 'KB clasic peste emitent ML-DSA-65: ' + (rk.valid ? rk.alg + '/' + rk.keyBinding.alg + ' pq=' + rk.postQuantum : rk.reason));
const refuzat = judeca(arata(doarClasic(), ['age_over_18']), { audience: 'https://alt.example' });
cere(!refuzat.valid && refuzat.postQuantum === false, 'un refuz nu spune postQuantum true: ' + refuzat.postQuantum);
});
test('AIP-25 C1 ATAC: alg none sau ES256 contra cheilor AERE (si cu classicalHalf) -> refuzate pe alg / key; chei AERE amestecate (Ed25519 al strainului langa ML-DSA-65 al emitentului) nu primesc implicit jetonul doar-Ed25519 al strainului; chei AERE fara jumatatea ML-DSA-65 -> key, nu o cadere si nu jumatatea Ed25519', () => {
const none = b64u(JSON.stringify({ alg: 'none', typ: J.TYP })) + '.' + b64u(JSON.stringify(corpE)) + '.~' + dezvE;
for (const ch of [false, true]) {
const n = J.verifySdJwt(none, { issuerKey: iss, requireKeyBinding: false, classicalHalf: ch, now: LA }); cere(!n.valid && n.rule === 'alg', 'none, classicalHalf ' + ch + ': ' + (n.valid ? 'VALID' : n.rule));
const es = J.verifySdJwt(doarClasic('ES256'), { issuerKey: iss, requireKeyBinding: false, classicalHalf: ch, now: LA }); cere(!es.valid && es.rule === 'key', 'ES256 cu cheia Ed25519, classicalHalf ' + ch + ': ' + (es.valid ? 'VALID' : es.rule));
}
const amestec = { alg: iss.public.alg, ed25519: strain.public.ed25519, mldsa65: iss.public.mldsa65 };
const s = J.verifySdJwt(doarClasic('EdDSA', corpE, strain.privat.ed25519), { issuerKey: amestec, requireKeyBinding: false, now: LA });
cere(!s.valid && s.rule === 'hybrid-half', 'chei amestecate, implicit: ' + (s.valid ? 'VALID' : s.rule));
const faraMl = { alg: iss.public.alg, ed25519: iss.public.ed25519 };
const fm = J.verifySdJwt(arata(E.sdJwt, ['age_over_18']), { issuerKey: faraMl, audience: AUD, nonce: NONCE, now: LA });
cere(!fm.valid && fm.rule === 'key', 'chei AERE fara ML-DSA-65: ' + (fm.valid ? 'VALID (pe jumatatea Ed25519)' : fm.rule + ': ' + fm.reason));
});
test('linia de comanda: verify-sdjwt pe prezentarea RFC 9901 s.5.2 -> 0 VALID la momentul ei (--at), 1 INVALID acum (KB vechi); o cheie privata -> 2', () => {
const T = fs.mkdtempSync(path.join(os.tmpdir(), 'aere-sdjwt-cli-'));
try {
@@ -255,6 +335,21 @@ test('linia de comanda: verify-sdjwt pe prezentarea RFC 9901 s.5.2 -> 0 VALID la
const c = run(); cere(c.status === 2 && /private JWK/.test(c.stderr), 'cheia privata: ' + c.status + ' ' + c.stderr);
} finally { fs.rmSync(T, { recursive: true, force: true }); }
});
test('linia de comanda AIP-25 C1: verify-sdjwt cu cheile AERE publice ale emitentului: jetonul doar-Ed25519 -> 1 INVALID (hybrid-half), si cu --issuer-alg EdDSA fara --classical-half; cu --classical-half -> 0 VALID, postQuantum false in --json si "NOT post-quantum" in text; jetonul implicit -> 0, postQuantum true', () => {
const T = fs.mkdtempSync(path.join(os.tmpdir(), 'aere-sdjwt-cli-c1-'));
try {
fs.writeFileSync(path.join(T, 'clasic.txt'), arata(doarClasic(), ['age_over_18'])); fs.writeFileSync(path.join(T, 'pq.txt'), arata(E.sdJwt, ['age_over_18']));
fs.writeFileSync(path.join(T, 'k.json'), JSON.stringify(iss.public));
const run = (f, ...a) => spawnSync(process.execPath, [path.join(AICI, 'identity-cli.mjs'), 'verify-sdjwt', '--sd-jwt', f, '--issuer-key', 'k.json', '--audience', AUD, '--nonce', NONCE, '--at', LA.toISOString(), ...a], { cwd: T, encoding: 'utf8' });
const j = (r) => { try { return JSON.parse(r.stdout); } catch { return {}; } };
const a = run('clasic.txt', '--json'); cere(a.status === 1 && j(a).rule === 'hybrid-half' && j(a).postQuantum === false, 'doar-Ed25519 implicit: ' + a.status + ' ' + (a.stdout + a.stderr).slice(0, 200));
const b = run('clasic.txt', '--issuer-alg', 'EdDSA', '--json'); cere(b.status === 1 && j(b).rule === 'hybrid-half', '--issuer-alg EdDSA fara --classical-half: ' + b.status + ' ' + (b.stdout + b.stderr).slice(0, 200));
const c = run('clasic.txt', '--classical-half', '--json'); cere(c.status === 0 && j(c).valid === true && j(c).postQuantum === false, '--classical-half: ' + c.status + ' ' + (c.stdout + c.stderr).slice(0, 200));
const d = run('clasic.txt', '--classical-half'); cere(d.status === 0 && /NOT post-quantum/.test(d.stdout), 'textul cu --classical-half: ' + d.stdout.slice(0, 200));
const e = run('pq.txt', '--json'); cere(e.status === 0 && j(e).postQuantum === true && j(e).alg === PQ, 'jetonul implicit: ' + e.status + ' ' + (e.stdout + e.stderr).slice(0, 200));
const g = run('pq.txt'); cere(g.status === 0 && /post-quantum/.test(g.stdout) && !/NOT post-quantum/.test(g.stdout), 'textul pe jetonul implicit: ' + g.stdout.slice(0, 200));
} finally { fs.rmSync(T, { recursive: true, force: true }); }
});
console.log(`\naere-sd-jwt: ${treceri}/${treceri + esecuri.length} cum trebuia`);
process.exitCode = esecuri.length ? 1 : 0;
+25 -15
View File
@@ -18,8 +18,12 @@
// CE NU FACE: nu aduce nimic de pe internet (nici metadatele de tip ale lui `vct`, s.5, nici lista de stare: verificatorul le aduce si le da,
// ca `--status-list` la credentialul AERE); nu rezolva cheia emitentului din `iss` (s.2.5: JWT VC Issuer Metadata sau x5c): cheia e intrarea
// verificatorului, niciodata din jeton; nu e mdoc (ISO/IEC 18013-5, CBOR/COSE): formatul de proximitate al ARF e alt format, nefacut aici.
//
// AIP-25 C1 (2026-10-19, D-535): lista de stare a unui emitent AERE se semneaza si se judeca implicit cu jumatatea ML-DSA-65 a cheilor lui,
// ca jetonul (sdjwt.mjs); jumatatea Ed25519 numai cu classicalHalf: true. Altfel cine spargea numai cheia clasica putea "dezrevoca" un
// credential cu o lista semnata de ea. `postQuantum` al verdictului VC e true numai daca si lista judecata e ML-DSA-65.
import zlib from 'node:zlib';
import { issueSdJwt, presentSdJwt, verifySdJwt, publicJwk, verifyJws, signJws, privateKeyOf, ALGS } from './sdjwt.mjs';
import { issueSdJwt, presentSdJwt, verifySdJwt, verifyJws, signJws, privateKeyOf, judgedJwk, headerAlgOf, defaultAlg, ALGS } from './sdjwt.mjs';
export const TYP_VC = 'dc+sd-jwt';
export const TYP_STATUS_LIST = 'statuslist+jwt';
@@ -66,8 +70,9 @@ export function issueSdJwtVc({ vct, vctIntegrity, status, claims = {}, disclosab
* fiecare sub 2^bits; bits din {1, 2, 4, 8}. Impachetarea (s.4.1): indexul i sta la octetul floor(i*bits/8), de la bitul (i*bits) mod 8, adica
* de la bitul cel mai putin semnificativ catre cel mai semnificativ. lst = base64url(ZLIB(DEFLATE(octeti))).
*/
export function issueStatusListJwt({ issuer, alg = 'EdDSA', uri, statuses, bits = 1, iat = Math.floor(Date.now() / 1000), exp, ttl, aggregationUri }) {
if (!ALGS.includes(alg)) throw new Error('status-list: unknown alg');
export function issueStatusListJwt({ issuer, alg, classicalHalf = false, uri, statuses, bits = 1, iat = Math.floor(Date.now() / 1000), exp, ttl, aggregationUri }) {
const algL = alg ?? defaultAlg(issuer); // AIP-25 C1: ML-DSA-65 pentru chei AERE
if (!ALGS.includes(algL)) throw new Error('status-list: unknown alg');
if (typeof uri !== 'string' || !uri) throw new Error('status-list: uri (the sub of the token) is required');
if (![1, 2, 4, 8].includes(bits)) throw new Error('status-list: bits is 1, 2, 4 or 8');
if (!Array.isArray(statuses) || !statuses.length || !statuses.every((s) => Number.isInteger(s) && s >= 0 && s < 2 ** bits)) throw new Error(`status-list: statuses is a non-empty list of integers below 2^${bits}`);
@@ -75,20 +80,22 @@ export function issueStatusListJwt({ issuer, alg = 'EdDSA', uri, statuses, bits
statuses.forEach((s, i) => { octeti[Math.floor(i * bits / 8)] |= s << ((i * bits) % 8); });
const lst = b64u(zlib.deflateSync(octeti, { level: 9 }));
const corp = { sub: uri, iat, ...(exp != null ? { exp } : {}), ...(ttl != null ? { ttl } : {}), status_list: { bits, lst, ...(aggregationUri ? { aggregation_uri: aggregationUri } : {}) } };
return signJws({ alg, typ: TYP_STATUS_LIST }, corp, privateKeyOf(issuer, alg));
return signJws({ alg: algL, typ: TYP_STATUS_LIST }, corp, privateKeyOf(issuer, algL, classicalHalf));
}
/**
* Citeste si verifica un Status List Token JWT cu cheia DATA (a emitentului listei; de obicei emitentul credentialului), pentru URI-ul cerut.
* Intoarce { ok, reason, entries, bits, statusAt(idx) -> 0..2^bits-1 sau null (dincolo de lista), payload }. Toate verificarile de aici
* Cu chei AERE se judeca implicit jumatatea ML-DSA-65; jumatatea Ed25519 numai cu classicalHalf (AIP-25 C1).
* Intoarce { ok, reason, entries, bits, statusAt(idx) -> 0..2^bits-1 sau null (dincolo de lista), payload, alg }. Toate verificarile de aici
* sunt regula `status-list` a profilului.
*/
export function readStatusListJwt(jwt, { key, alg = 'EdDSA', uri, now = new Date(), clockSkewS = 60 } = {}) {
const nu = (reason) => ({ ok: false, reason, entries: 0, bits: 0, statusAt: () => null, payload: null });
export function readStatusListJwt(jwt, { key, alg, classicalHalf = false, uri, now = new Date(), clockSkewS = 60 } = {}) {
const nu = (reason) => ({ ok: false, reason, entries: 0, bits: 0, statusAt: () => null, payload: null, alg: null });
const motiv = (e) => String((e && e.message) || e).replace(/^sd-jwt: /, '');
// semnatura, typ-ul si potrivirea alg/cheie le judeca verifyJws (o lista semnata ML-DSA-65 judecata cu cheia Ed25519 cade acolo: "does not match")
let corp = {};
try { ({ corp } = verifyJws(jwt, publicJwk(key, alg), { typ: TYP_STATUS_LIST })); } catch (e) { if (!(false /*PAZA:status-list*/)) return nu(motiv(e)); }
// semnatura, typ-ul si potrivirea alg/cheie le judeca verifyJws (o lista semnata ML-DSA-65 judecata cu cheia Ed25519 cade acolo: "does not match");
// jumatatea cheilor AERE o alege judgedJwk (o lista semnata numai cu jumatatea Ed25519 cade acolo, "Ed25519 half", fara classicalHalf)
let corp = {}, antet = {};
try { ({ antet, corp } = verifyJws(jwt, judgedJwk(key, alg, { classicalHalf, headerAlg: headerAlgOf(jwt) }), { typ: TYP_STATUS_LIST })); } catch (e) { if (!(false /*PAZA:status-list*/)) return nu(motiv(e)); }
if (!(typeof uri === 'string' && !!uri /*PAZA:status-list*/)) return nu('the verifier must give the uri the list was fetched for');
if (!(corp.sub === uri /*PAZA:status-list*/)) return nu(`sub ${JSON.stringify(corp.sub)} is not the uri referenced (${uri})`);
const acum = Math.floor(new Date(now).getTime() / 1000);
@@ -104,7 +111,7 @@ export function readStatusListJwt(jwt, { key, alg = 'EdDSA', uri, now = new Date
} catch (e) { if (!(false /*PAZA:status-list*/)) return nu('lst cannot be inflated: ' + String(e.message || e).slice(0, 80)); }
const bits = obiect(sl) && [1, 2, 4, 8].includes(sl.bits) ? sl.bits : 1, entries = Math.floor(octeti.length * 8 / bits);
const statusAt = (idx) => (Number.isInteger(idx) && idx >= 0 && idx < entries ? (octeti[Math.floor(idx * bits / 8)] >> ((idx * bits) % 8)) & ((1 << bits) - 1) : null);
return { ok: true, reason: '', entries, bits, statusAt, payload: corp };
return { ok: true, reason: '', entries, bits, statusAt, payload: corp, alg: antet.alg };
}
/**
@@ -116,7 +123,7 @@ export function readStatusListJwt(jwt, { key, alg = 'EdDSA', uri, now = new Date
* regula care a refuzat (a profilului sau a lui sdjwt.mjs), null cand e valid.
*/
export function verifySdJwtVc(token, { expectedVct, statusListJwt = null, statusListKey = null, statusListAlg = null, requireStatus = true, expectedTyp = TYP_VC, ...o } = {}) {
const refuz = (rule, reason, extra = {}) => ({ valid: false, rule, reason, payload: null, disclosed: [], keyBinding: null, vct: null, status: null, ...extra });
const refuz = (rule, reason, extra = {}) => ({ valid: false, rule, reason, payload: null, disclosed: [], keyBinding: null, postQuantum: false, vct: null, status: null, ...extra });
const vcts = Array.isArray(expectedVct) ? expectedVct : expectedVct == null ? null : [expectedVct];
if (!(Array.isArray(vcts) && vcts.length > 0 && vcts.every((v) => typeof v === 'string' && !!v) /*PAZA:vct-expected*/)) return refuz('vct-expected', 'the verifier must name the vct it expects (expectedVct)');
const tipuri = Array.isArray(vcts) ? vcts : [];
@@ -128,7 +135,7 @@ export function verifySdJwtVc(token, { expectedVct, statusListJwt = null, status
const dez = r.disclosed.filter((n) => NEDEZVALUIBILE.includes(n));
if (!(dez.length === 0 /*PAZA:disclosed-protected*/)) return refuz('disclosed-protected', `${dez[0]} was selectively disclosed; an SD-JWT VC carries it in the clear (s.2.2.2.3)`);
if (!(p['vct#integrity'] === undefined || typeof p['vct#integrity'] === 'string' /*PAZA:form*/)) return refuz('form', 'vct#integrity is not a string');
let status = { present: false, judged: false };
let status = { present: false, judged: false }, pqLista = true;
if (p.status !== undefined) {
if (!(obiect(p.status) /*PAZA:form*/)) return refuz('form', 'status is not an object');
const ref = obiect(p.status) ? p.status.status_list : undefined;
@@ -138,7 +145,9 @@ export function verifySdJwtVc(token, { expectedVct, statusListJwt = null, status
if (!(e === null /*PAZA:form*/)) return refuz('form', 'status.status_list: ' + e);
status.uri = ref.uri; status.idx = ref.idx;
if (statusListJwt != null) {
const l = readStatusListJwt(statusListJwt, { key: statusListKey ?? o.issuerKey, alg: statusListAlg ?? o.issuerAlg ?? 'EdDSA', uri: ref.uri, now: o.now, clockSkewS: o.clockSkewS });
// AIP-25 C1: fara statusListAlg, o lista a unei chei AERE se judeca pe jumatatea ML-DSA-65 (Ed25519 numai cu classicalHalf)
const l = readStatusListJwt(statusListJwt, { key: statusListKey ?? o.issuerKey, alg: statusListAlg ?? o.issuerAlg, classicalHalf: o.classicalHalf, uri: ref.uri, now: o.now, clockSkewS: o.clockSkewS });
pqLista = l.alg === 'ML-DSA-65';
if (!(l.ok /*PAZA:status-list*/)) return refuz('status-list', 'status list: ' + l.reason, { vct: p.vct, status });
const v = l.statusAt(ref.idx);
if (!(v !== null /*PAZA:status-index*/)) return refuz('status-index', `status list: index ${ref.idx} is beyond the list (${l.entries} entries)`, { vct: p.vct, status });
@@ -148,5 +157,6 @@ export function verifySdJwtVc(token, { expectedVct, statusListJwt = null, status
}
if (!(status.judged || !requireStatus /*PAZA:status-unjudged*/)) return refuz('status-unjudged', `the credential names a status (${status.mechanism}) that was not judged: give statusListJwt fetched from ${status.uri ?? 'the issuer'}, or set requireStatus:false`, { vct: p.vct, status });
}
return { ...r, vct: p.vct, status };
// AIP-25 C1: post-cuantic numai daca si lista de stare judecata (cand a fost judecata) e semnata ML-DSA-65
return { ...r, postQuantum: r.postQuantum && pqLista, vct: p.vct, status };
}
+92 -26
View File
@@ -11,9 +11,20 @@
// nonce-ul lui CERUTE cand exista (sau se cere) Key Binding, cu `exp` cerut, cu tipul explicit al jetonului verificat
//
// ALGORITMII (JWS): ES256 (P-256, cel din exemplele RFC 9901), EdDSA / Ed25519 (RFC 8037) si ML-DSA-65 (post-cuantic; numele si forma
// cheii JWK "AKP" din RFC 9964, mai 2026). Un emitent AERE semneaza cu cheia lui Ed25519 (algoritm cunoscut tuturor bibliotecilor JOSE)
// sau cu cheia ML-DSA-65 (masurat 2026-10-18: jose 6.2.12 pe Node 24 o semneaza si o verifica); o semnatura hibrida in acelasi jeton ar
// cere serializarea JSON generala a JWS si nu e facuta aici.
// cheii JWK "AKP" din RFC 9964, mai 2026). O semnatura hibrida in acelasi jeton ar cere serializarea JSON generala a JWS si nu e facuta aici.
//
// JUMATATEA POST-CUANTICA (2026-10-19, AIP-25 constatarea C1, D-535): cheile unei identitati AERE sunt Ed25519 SI ML-DSA-65 (identity.mjs
// cere amandoua semnaturile). Un JWS poarta UNA. Pana pe 19 oct emiterea, cnf-ul detinatorului si verificarea alegeau implicit jumatatea
// Ed25519, deci cine spargea NUMAI cheia clasica a emitentului facea credentiale primite contra identitatii lui intregi (masurat de
// aips/aip25-inventar/masoara-constatari.mjs). De atunci, cu chei AERE (perechea privata, sau cheile publice {alg, ed25519, mldsa65}):
// - emiterea (alg), cnf-ul detinatorului (holderAlg), Key Binding-ul si lista de stare (sdjwt-vc.mjs) folosesc implicit ML-DSA-65;
// - verificarea cere implicit jumatatea ML-DSA-65; un jeton semnat cu jumatatea Ed25519 e refuzat pe regula `hybrid-half`;
// - jumatatea Ed25519 se foloseste si se judeca NUMAI la cererea explicita a apelantului (`classicalHalf: true`, pentru interoperarea
// clasica), si atunci verificatorul primeste jumatatea pe care o numeste jetonul (EdDSA sau ML-DSA-65);
// - verdictul spune `postQuantum`: true numai cand FIECARE semnatura judecata (a emitentului si, daca exista, Key Binding-ul) e ML-DSA-65.
// Un JWK simplu (o cheie straina, ES256 sau EdDSA, @sd-jwt/core, portofelele europene) ramane cum era: nu exista o jumatate post-cuantica
// de pierdut, iar verdictul spune la fel postQuantum false. Cine isi transforma singur cheile AERE intr-un JWK Ed25519 simplu
// (publicJwk(chei, 'EdDSA', { classicalHalf: true })) a cerut jumatatea clasica, si verdictul o spune.
//
// Revizuirea adversariala din 2026-09-30 (inainte de publicare) a gasit si s-au reparat: emitentul semna structura SD-JWT venita in valorile
// afirmatiilor (`_sd`, `{"...": d}`), deci detinatorul putea dezvalui afirmatii pe care emitentul nu le-a vazut; prezentarea arata un element
@@ -34,8 +45,10 @@ export const ALGS = ['ES256', 'EdDSA', 'Ed25519', 'ML-DSA-65'];
export const TYP = 'aere+sd-jwt';
const AERE_ALG = 'ed25519+ml-dsa-65';
/** regulile pe care le poate numi un refuz al lui verifySdJwt (ordinea e cea a verificarii; `form` si pentru ceasul verificatorului) */
export const REGULI = ['form', 'alg', 'typ', 'crit', 'key', 'signature', 'issuer', 'sd-alg', 'disclosure-form', 'disclosure-twice', 'digest-twice',
export const REGULI = ['form', 'alg', 'typ', 'crit', 'key', 'hybrid-half', 'signature', 'issuer', 'sd-alg', 'disclosure-form', 'disclosure-twice', 'digest-twice',
'disclosure-name', 'claim-conflict', 'unreferenced', 'time', 'kb-context', 'kb-required', 'kb-cnf', 'kb-claims', 'kb-audience', 'kb-nonce', 'kb-freshness', 'kb-sd-hash'];
// numele JOSE ale semnaturii Ed25519: EdDSA (RFC 8037) si Ed25519 (numele complet, RFC 9864)
const CLASIC = ['EdDSA', 'Ed25519'];
class Refuz extends Error { constructor(rule, message) { super(message); this.rule = rule; } }
const nu = (rule, msg) => { if (!REGULI.includes(rule)) throw new Error('sd-jwt: undeclared rule ' + rule); return new Refuz(rule, 'sd-jwt: ' + msg); };
// base64url CANONIC: decodat si recodat trebuie sa dea acelasi text (altfel aceeasi semnatura are mai multe scrieri, si un depozit de
@@ -51,18 +64,54 @@ const sha256b64u = (s) => crypto.createHash('sha256').update(Buffer.from(s, 'asc
const obiect = (x) => x !== null && typeof x === 'object' && !Array.isArray(x);
// ---------------------------------------------------------------- chei JWK si semnaturi JWS
/** Chei AERE: perechea (identity.mjs, cu `privat`) sau cheile publice ale unei identitati ({alg: 'ed25519+ml-dsa-65', ed25519, mldsa65}). */
const esteAere = (k) => !!k && !(k instanceof crypto.KeyObject) && (obiect(k.privat) || (obiect(k) && k.alg === AERE_ALG));
/** Algoritmul implicit al unei chei la EMITERE: ML-DSA-65 pentru chei AERE (AIP-25 C1), EdDSA altfel (ca pana acum). */
export const defaultAlg = (k) => (esteAere(k) ? 'ML-DSA-65' : 'EdDSA');
/**
* Jumatatea unei chei AERE ceruta de `alg` (implicit ML-DSA-65). Jumatatea Ed25519 NUMAI cu `classicalHalf` (AIP-25 C1): altfel refuz
* `hybrid-half`. Un algoritm pe care o identitate AERE nu il are (ES256) e refuz `key`, nu cheia Ed25519 data in tacere (pana pe 19 oct).
*/
function jumatateaAere(alg, classicalHalf) {
const a = alg == null ? 'ML-DSA-65' : alg;
if (a === 'ML-DSA-65') return 'mldsa65';
if (!CLASIC.includes(a)) throw nu('key', `an AERE hybrid identity has an Ed25519 and an ML-DSA-65 key, no ${a} key`);
if (!(classicalHalf === true /*PAZA:hybrid-half*/)) throw nu('hybrid-half', `${a} names the Ed25519 half of an AERE hybrid identity (Ed25519 + ML-DSA-65); that half alone is not post-quantum and is used only when the caller asks for it (classicalHalf: true); the post-quantum half is ML-DSA-65, the default`);
return 'ed25519';
}
/**
* Cheia PUBLICA ca JWK, din: o pereche de chei AERE (identity.mjs; `privat`), cheile publice ale unei identitati AERE ({alg, ed25519,
* mldsa65}), un KeyObject public sau privat, sau un JWK public. `alg` alege cheia AERE: 'EdDSA' (Ed25519) sau 'ML-DSA-65'.
* mldsa65}), un KeyObject public sau privat, sau un JWK public. Pentru chei AERE, `alg` alege jumatatea: implicit 'ML-DSA-65'; 'EdDSA' /
* 'Ed25519' (jumatatea clasica) numai cu { classicalHalf: true } (AIP-25 C1). Pentru celelalte chei `alg` nu conteaza (cheia e cea data).
*/
export function publicJwk(k, alg = 'EdDSA') {
const ml = alg === 'ML-DSA-65';
if (k && k.privat) k = ml ? k.privat.mldsa65 : k.privat.ed25519;
else if (obiect(k) && k.alg === AERE_ALG && typeof k.ed25519 === 'string') k = crypto.createPublicKey({ key: Buffer.from(ml ? k.mldsa65 : k.ed25519, 'base64'), format: 'der', type: 'spki' });
export function publicJwk(k, alg, { classicalHalf = false } = {}) {
if (esteAere(k)) {
const j = jumatateaAere(alg, classicalHalf);
let x = null;
try { x = k.privat ? k.privat[j] : crypto.createPublicKey({ key: Buffer.from(k[j], 'base64'), format: 'der', type: 'spki' }); } catch { x = null; }
if (!(x instanceof crypto.KeyObject)) throw nu('key', `the ${j === 'mldsa65' ? 'ML-DSA-65' : 'Ed25519'} half of the AERE identity keys cannot be read`);
k = x;
}
if (k instanceof crypto.KeyObject) return (k.type === 'public' ? k : crypto.createPublicKey(k)).export({ format: 'jwk' });
if (obiect(k) && k.kty) return k;
throw nu('key', 'not a key (a JWK, a Node key object, or AERE identity keys)');
}
/**
* Cheia cu care se judeca un JWS semnat de cheia `k` a emitentului (sau a listei de stare), data de verificator (AIP-25 C1, 2026-10-19).
* O cheie care nu e AERE: ea insasi, ca pana acum. Chei AERE: jumatatea `alg` daca verificatorul o numeste; altfel ML-DSA-65, sau, numai
* cu `classicalHalf`, jumatatea pe care o numeste antetul (EdDSA / Ed25519; verdictul spune atunci postQuantum false). Un jeton semnat cu
* jumatatea Ed25519, judecat de un verificator care cere jumatatea ML-DSA-65, e refuzat pe NUMELE lui (`hybrid-half`), nu ca "alta cheie".
*/
export function judgedJwk(k, alg, { classicalHalf = false, headerAlg } = {}) {
if (!esteAere(k)) return publicJwk(k, alg);
const a = alg != null ? alg : classicalHalf === true && CLASIC.includes(headerAlg) ? headerAlg : 'ML-DSA-65';
if (!(!(a === 'ML-DSA-65' && CLASIC.includes(headerAlg)) /*PAZA:hybrid-half*/)) throw nu('hybrid-half', `the JWS is signed ${headerAlg} with the Ed25519 half of an AERE hybrid identity alone (Ed25519 + ML-DSA-65): that half is not post-quantum, so it is judged only when the verifier asks for it (classicalHalf: true); by default the ML-DSA-65 half is required`);
return publicJwk(k, a, { classicalHalf });
}
/** Algoritmul din antetul unui JWS compact, citit fara sa fie crezut (numai ca sa se numeasca un refuz); undefined daca nu se citeste. */
export function headerAlgOf(jws) {
try { const h = jsonB64u(String(jws).split('.')[0], 'the JWS header'); return obiect(h) && typeof h.alg === 'string' ? h.alg : undefined; } catch { return undefined; }
}
function cheiePublica(jwk) {
if (!(obiect(jwk) && ['EC', 'OKP', 'AKP'].includes(jwk.kty) /*PAZA:key*/)) throw nu('key', 'the key is not an EC, OKP or AKP JWK');
if (!(!('d' in jwk) && !('priv' in jwk) /*PAZA:key*/)) throw nu('key', 'a private JWK was given where a public key belongs');
@@ -109,8 +158,14 @@ function semneazaJws(antet, corp, priv) {
const sig = antet.alg === 'ES256' ? crypto.sign('sha256', date, { key: priv, dsaEncoding: 'ieee-p1363' }) : crypto.sign(null, date, priv);
return cap + '.' + b64u(sig);
}
const cheiePrivata = (k, alg) => (k && k.privat ? (alg === 'ML-DSA-65' ? k.privat.mldsa65 : k.privat.ed25519) : k);
// pentru profilurile de deasupra (sdjwt-vc.mjs: Status List Token), ca semnatura JWS sa se faca intr-un singur loc
// cheia privata care semneaza: pentru chei AERE jumatatea numita de alg (Ed25519 numai cu classicalHalf, AIP-25 C1); altfel cheia data
function cheiePrivata(k, alg, classicalHalf = false) {
if (!(k && k.privat)) return k;
const j = jumatateaAere(alg, classicalHalf);
if (!k.privat[j]) throw new Error(`sd-jwt: these AERE keys have no private ${j === 'mldsa65' ? 'ML-DSA-65' : 'Ed25519'} half`);
return k.privat[j];
}
// pentru profilurile de deasupra (sdjwt-vc.mjs: Status List Token), ca semnatura JWS si alegerea jumatatii AERE sa se faca intr-un singur loc
export { verificaJws as verifyJws, semneazaJws as signJws, cheiePrivata as privateKeyOf };
// structura SD-JWT intr-o valoare: o cheie `_sd`/`_sd_alg` intr-un obiect sau un element {"...": x} intr-o lista, oriunde in adancime
function areStructuraSd(v) {
@@ -130,12 +185,14 @@ function areStructuraSd(v) {
* issuer: chei AERE sau KeyObject privat. holder: cheia PUBLICA a detinatorului (sau cheile lui AERE). disclosable: numele afirmatiilor de
* sus dezvaluibile; arrayDisclosable: listele de sus ale caror ELEMENTE sunt dezvaluibile una cate una. exp implicit: un an de la iat
* (null: fara exp, pe care verifySdJwt il refuza implicit). typ: tipul explicit al jetonului (implicit TYP; un profil ca SD-JWT VC isi
* pune al lui, "dc+sd-jwt"; RFC 9901 s.9.11). Intoarce { sdJwt, disclosures:[{name, value, disclosure}] }.
* pune al lui, "dc+sd-jwt"; RFC 9901 s.9.11). alg / holderAlg: implicit ML-DSA-65 pentru chei AERE, EdDSA pentru celelalte; jumatatea
* Ed25519 a unor chei AERE (emitent sau detinator) numai cu classicalHalf: true (AIP-25 C1). Intoarce { sdJwt, disclosures:[{name, value, disclosure}] }.
*/
export function issueSdJwt({ issuer, claims, disclosable = [], arrayDisclosable = [], holder, iss, iat = Math.floor(Date.now() / 1000), exp, nbf, alg = 'EdDSA', holderAlg = 'EdDSA', decoys = 0, typ = TYP }) {
export function issueSdJwt({ issuer, claims, disclosable = [], arrayDisclosable = [], holder, iss, iat = Math.floor(Date.now() / 1000), exp, nbf, alg, holderAlg, classicalHalf = false, decoys = 0, typ = TYP }) {
if (!obiect(claims)) throw new Error('sd-jwt: claims must be an object');
if (typeof iss !== 'string' || !iss) throw new Error('sd-jwt: iss is required');
if (!ALGS.includes(alg) || !ALGS.includes(holderAlg)) throw new Error('sd-jwt: unknown alg');
const algE = alg ?? defaultAlg(issuer), algH = holderAlg ?? defaultAlg(holder);
if (!ALGS.includes(algE) || !ALGS.includes(algH)) throw new Error('sd-jwt: unknown alg');
if (!tipBun(typ, undefined)) throw new Error('sd-jwt: typ must be an explicit SD-JWT type ("...+sd-jwt", RFC 9901 s.9.11)');
// RFC 9901 s.4.1 (regula 7 a emitentului): emitentul nu semneaza digesturi pe care nu le-a facut el; o valoare care poarta deja `_sd`,
// `_sd_alg` sau un element {"...": d} ar lasa detinatorul sa dezvaluie afirmatii nevazute de emitent
@@ -155,8 +212,8 @@ export function issueSdJwt({ issuer, claims, disclosable = [], arrayDisclosable
corp.iss = iss; corp.iat = iat;
const e = exp === undefined ? iat + 365 * 86400 : exp; if (e != null) corp.exp = e;
if (nbf != null) corp.nbf = nbf;
corp.cnf = { jwk: publicJwk(holder, holderAlg) };
const jwt = semneazaJws({ alg, typ }, corp, cheiePrivata(issuer, alg));
corp.cnf = { jwk: publicJwk(holder, algH, { classicalHalf }) };
const jwt = semneazaJws({ alg: algE, typ }, corp, cheiePrivata(issuer, algE, classicalHalf));
return { sdJwt: jwt + '~' + dez.map((x) => x.disclosure + '~').join(''), disclosures: dez };
}
@@ -164,12 +221,17 @@ export function issueSdJwt({ issuer, claims, disclosable = [], arrayDisclosable
* Detinatorul pastreaza numai dezvaluirile alese si leaga prezentarea de verificator. reveal: un sir = afirmatia de SUS cu acel nume;
* { element, in } = elementul cu acea valoare din lista de SUS `in` (numai din ea). O alegere care nu gaseste nimic e o eroare, nu o tacere.
*/
export function presentSdJwt({ sdJwt, reveal = [], holder, holderAlg = 'EdDSA', audience, nonce, iat = Math.floor(Date.now() / 1000) }) {
export function presentSdJwt({ sdJwt, reveal = [], holder, holderAlg, classicalHalf = false, audience, nonce, iat = Math.floor(Date.now() / 1000) }) {
if (typeof audience !== 'string' || !audience || typeof nonce !== 'string' || !nonce) throw new Error('sd-jwt: a presentation needs the verifier\'s audience and nonce');
const parti = String(sdJwt).split('~');
if (parti[parti.length - 1] !== '') throw new Error('sd-jwt: this SD-JWT already ends with a key binding JWT');
const jwt = parti[0], dez = parti.slice(1, -1);
const corp = jsonB64u(jwt.split('.')[1] || '', 'the issuer-signed JWT payload');
// AIP-25 C1 (2026-10-19): un detinator AERE semneaza Key Binding-ul cu jumatatea pe care emitentul a legat-o in cnf.jwk (ML-DSA-65 implicit;
// o cheie OKP in cnf inseamna ca emitentul a cerut jumatatea Ed25519, iar verdictul spune postQuantum false); un holderAlg dat castiga
const cnfKty = obiect(corp.cnf) && obiect(corp.cnf.jwk) ? corp.cnf.jwk.kty : null;
const urmeazaCnf = holderAlg == null && esteAere(holder) && cnfKty === 'OKP';
const algH = holderAlg ?? (urmeazaCnf ? 'EdDSA' : defaultAlg(holder));
// unde sta fiecare digest in JWT-ul emitentului: proprietate de sus, sau element al unei liste de sus (cu numele listei)
const loc = new Map();
for (const dg of Array.isArray(corp._sd) ? corp._sd : []) loc.set(dg, { tip: 'prop' });
@@ -189,7 +251,7 @@ export function presentSdJwt({ sdJwt, reveal = [], holder, holderAlg = 'EdDSA',
const lipsa = reveal.filter((_, i) => !gasite.has(i));
if (lipsa.length) throw new Error('sd-jwt: nothing to reveal for ' + JSON.stringify(lipsa) + ' (a name reveals a top-level claim; {element, in} an element of the top-level list named)');
const baza = jwt + '~' + alese.map((d) => d + '~').join('');
const kb = semneazaJws({ alg: holderAlg, typ: 'kb+jwt' }, { iat, aud: audience, nonce, sd_hash: sha256b64u(baza) }, cheiePrivata(holder, holderAlg));
const kb = semneazaJws({ alg: algH, typ: 'kb+jwt' }, { iat, aud: audience, nonce, sd_hash: sha256b64u(baza) }, cheiePrivata(holder, algH, classicalHalf || urmeazaCnf));
return baza + kb;
}
@@ -200,11 +262,13 @@ export function presentSdJwt({ sdJwt, reveal = [], holder, holderAlg = 'EdDSA',
* now?:Date, maxAgeS?:number, clockSkewS?:number, expectedTyp?:string|null}} o
* issuerKey: cheia EMITENTULUI data de verificator (JWK, KeyObject, cheile AERE ale emitentului); niciodata din jeton. audience si nonce
* sunt ale verificatorului si se CER cand exista (sau se cere) Key Binding. expectedTyp: implicit orice tip explicit "...+sd-jwt".
* Intoarce { valid, rule, reason, payload, disclosed:[nume], issuer, issuerChecked, keyBinding:{aud, nonce, iat, alg}|null }; `rule` e
* regula (din REGULI) care a refuzat, null cand e valid.
* Cu chei AERE (AIP-25 C1): implicit se cere jumatatea ML-DSA-65 (issuerAlg o poate numi); jumatatea Ed25519 numai cu classicalHalf: true.
* Intoarce { valid, rule, reason, payload, disclosed:[nume], issuer, issuerChecked, alg, postQuantum, keyBinding:{aud, nonce, iat, alg}|null };
* `rule` e regula (din REGULI) care a refuzat, null cand e valid; `postQuantum` e true numai cand fiecare semnatura judecata (a emitentului
* si Key Binding-ul, daca exista) e ML-DSA-65, si false pe orice refuz.
*/
export function verifySdJwt(sdJwt, { issuerKey, issuerAlg = 'EdDSA', expectedIssuer = null, audience = null, nonce = null, requireKeyBinding = true, requireExp = true, now = new Date(), maxAgeS = 300, clockSkewS = 60, expectedTyp } = {}) {
const refuz = (rule, reason) => ({ valid: false, rule, reason, payload: null, disclosed: [], keyBinding: null });
export function verifySdJwt(sdJwt, { issuerKey, issuerAlg, classicalHalf = false, expectedIssuer = null, audience = null, nonce = null, requireKeyBinding = true, requireExp = true, now = new Date(), maxAgeS = 300, clockSkewS = 60, expectedTyp } = {}) {
const refuz = (rule, reason) => ({ valid: false, rule, reason, payload: null, disclosed: [], keyBinding: null, postQuantum: false });
const motiv = (e) => String((e && e.message) || e).replace(/^sd-jwt: /, '');
const regula = (e) => (e instanceof Refuz ? e.rule : 'form');
try {
@@ -218,8 +282,8 @@ export function verifySdJwt(sdJwt, { issuerKey, issuerAlg = 'EdDSA', expectedIss
// RFC 9901 s.7.3 pasul 5: publicul si nonce-ul verificatorului se compara; fara ele, o prezentare facuta pentru altul ar trece
const context = typeof audience === 'string' && !!audience && typeof nonce === 'string' && !!nonce;
if (!(!(requireKeyBinding || kb !== '') || context /*PAZA:kb-context*/)) return refuz('kb-context', 'the verifier must give its audience and nonce to judge a key binding (RFC 9901 s.7.3)');
// 2. JWT-ul emitentului
const { antet, corp } = verificaJws(jwt, publicJwk(issuerKey, issuerAlg), { typ: expectedTyp });
// 2. JWT-ul emitentului, cu jumatatea ceruta a unor chei AERE (AIP-25 C1: implicit ML-DSA-65; Ed25519 numai cu classicalHalf)
const { antet, corp } = verificaJws(jwt, judgedJwk(issuerKey, issuerAlg, { classicalHalf, headerAlg: headerAlgOf(jwt) }), { typ: expectedTyp });
if (!(expectedIssuer == null || corp.iss === expectedIssuer /*PAZA:issuer*/)) return refuz('issuer', `issued by ${JSON.stringify(corp.iss)}, not ${expectedIssuer}`);
const alg = corp._sd_alg === undefined ? 'sha-256' : corp._sd_alg;
if (!(alg === 'sha-256' /*PAZA:sd-alg*/)) return refuz('sd-alg', `_sd_alg ${JSON.stringify(corp._sd_alg)} is not understood (only sha-256)`);
@@ -288,7 +352,9 @@ export function verifySdJwt(sdJwt, { issuerKey, issuerAlg = 'EdDSA', expectedIss
if (!(payload.exp === undefined || acum < payload.exp /*PAZA:time*/)) return refuz('time', `expired at ${payload.exp}`);
if (!(payload.nbf === undefined || payload.nbf - clockSkewS <= acum /*PAZA:time*/)) return refuz('time', `not valid before ${payload.nbf}`);
if (!(payload.iat === undefined || payload.iat - clockSkewS <= acum /*PAZA:time*/)) return refuz('time', `issued in the future (${payload.iat})`);
const rez = { valid: true, rule: null, reason: '', payload, disclosed, issuer: corp.iss, issuerChecked: expectedIssuer != null, alg: antet.alg };
// AIP-25 C1: verdictul spune daca semnatura emitentului judecata e post-cuantica (Key Binding-ul o poate cobori, mai jos)
const pqEmitent = antet.alg === 'ML-DSA-65';
const rez = { valid: true, rule: null, reason: '', payload, disclosed, issuer: corp.iss, issuerChecked: expectedIssuer != null, alg: antet.alg, postQuantum: pqEmitent };
// s.7.3: Key Binding JWT
if (kb === '') {
if (!(!requireKeyBinding /*PAZA:kb-required*/)) return refuz('kb-required', 'key binding is required and the SD-JWT has none (it ends with ~)');
@@ -307,6 +373,6 @@ export function verifySdJwt(sdJwt, { issuerKey, issuerAlg = 'EdDSA', expectedIss
if (!(K.nbf === undefined || (Number.isFinite(K.nbf) && K.nbf - clockSkewS <= acum) /*PAZA:kb-freshness*/)) return refuz('kb-freshness', `key binding: not valid before ${K.nbf}`);
const baza = sdJwt.slice(0, sdJwt.length - kb.length);
if (!(sha256b64u(baza) === K.sd_hash /*PAZA:kb-sd-hash*/)) return refuz('kb-sd-hash', 'key binding: sd_hash is not the hash of what was presented');
return { ...rez, keyBinding: { aud: K.aud, nonce: K.nonce, iat: K.iat, alg: k.antet.alg } };
return { ...rez, postQuantum: rez.postQuantum && k.antet.alg === 'ML-DSA-65', keyBinding: { aud: K.aud, nonce: K.nonce, iat: K.iat, alg: k.antet.alg } };
} catch (e) { return refuz(regula(e), motiv(e)); }
}