plenipo 0.6.0 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -88,7 +88,7 @@ npm run example:gateway # a bank's HTTP API behind the Plenipo gateway
88
88
  cd sandbox && docker compose up --build # a bank, a wallet, an agent platform and a live dashboard
89
89
  ```
90
90
 
91
- The [sandbox](sandbox/README.md) also runs with Node, has 17 scripted scenarios and an MCP bridge
91
+ The [sandbox](sandbox/README.md) also runs with Node, has 21 scripted scenarios and an MCP bridge
92
92
  that lets Claude Desktop or Claude Code act as the agent. More in [examples/](examples/README.md).
93
93
 
94
94
  The demo prints:
@@ -190,11 +190,10 @@ See [ROADMAP.md](ROADMAP.md). Changes by version are in [CHANGELOG.md](CHANGELOG
190
190
 
191
191
  ## Limits
192
192
 
193
- - One third-party wallet so far: walt.id Wallet API 2, a server-side wallet, approved a
194
- `plenipo_mandate` and a TS12 e-mandate bound to the PID, with a test PID from the sandbox, and the
195
- sandbox bank enforced them ([docs/interop.md](docs/interop.md)). No phone wallet yet: the EUDI
196
- reference wallet core declares accepted types since release 0.31.0; IT-Wallet does not accept
197
- custom types.
193
+ - Wallets so far: walt.id Wallet API 2 (server-side) and the EUDI reference wallet on Android and iOS,
194
+ through forks that show the mandate, with test PIDs ([docs/interop.md](docs/interop.md)). IT-Wallet:
195
+ profiles `it-wallet-1` (specification 1.4.7) and `it-wallet-2` (1.5.0, EUDIW path) are ready, not yet
196
+ run against an Italian wallet ([docs/it-wallet.md](docs/it-wallet.md)).
198
197
  - With TS12, the e-mandate is approved with a bank's SCA attestation, not the PID. Tying that
199
198
  attestation to the PID holder needs the same holder key or identity claims the bank includes;
200
199
  see [docs/root.md](docs/root.md).
@@ -13,3 +13,4 @@ export { checkAttestationCertificates, checkAttestationStatus, SCA_QUERY_ID, typ
13
13
  export { currencyMinorDigits, NON_DECIMAL_CURRENCY_EXPONENTS, decodeCanonical, describeMandate, emandateViolations, encodeEmandateTransactionData, mandateToEmandate, parseDateTime, toMajorUnits, toMinorUnits, type EmandateCheckOptions, type EmandateMappingOptions, type EmandatePayee, type EmandatePayload, type EmandatePaymentPayload, type EmandateTransactionData, type EmandateViolation, } from './ts12.js';
14
14
  export { checkRepresentation, createLegalMandate, legalPrincipalProblems, representationClaimsProblems, representationQuery, rolePowerViolations, RepresentationError, REPRESENTATION_QUERY_ID, type RepresentationClaims, type RepresentationVerifyOptions, type VerifiedRepresentation, } from './legal.js';
15
15
  export { verifyAttestationPresentation, disclosedProtectedClaims, PresentationError, PROTECTED_CLAIMS, type VerifiedPresentation, } from './presentation.js';
16
+ export { IT_WALLET_PROFILE, IT_WALLET_EUDIW_PROFILE, IT_WALLET_PID_VCT, IT_WALLET_PID_VCT_TRANSITIONAL, IT_WALLET_EUDIW_SCHEME, IT_WALLET_CLIENT_ID_PREFIXES, IT_WALLET_DEFAULT_CLAIMS, IT_WALLET_REGISTRAR_DATASET_MEMBERS, IT_WALLET_PRINCIPAL_ID_CLAIMS, itWalletRequestOptions, itWalletVerifyDefaults, itWalletRequestProblems, itWalletIdentityMatch, type ItWalletProfile, type ItWalletRequestInput, type ItWalletIdentityMatch, type TrustedAuthority, type VerifierInfo, } from './itwallet.js';
@@ -15,3 +15,6 @@ export { checkAttestationCertificates, checkAttestationStatus, SCA_QUERY_ID, } f
15
15
  export { currencyMinorDigits, NON_DECIMAL_CURRENCY_EXPONENTS, decodeCanonical, describeMandate, emandateViolations, encodeEmandateTransactionData, mandateToEmandate, parseDateTime, toMajorUnits, toMinorUnits, } from './ts12.js';
16
16
  export { checkRepresentation, createLegalMandate, legalPrincipalProblems, representationClaimsProblems, representationQuery, rolePowerViolations, RepresentationError, REPRESENTATION_QUERY_ID, } from './legal.js';
17
17
  export { verifyAttestationPresentation, disclosedProtectedClaims, PresentationError, PROTECTED_CLAIMS, } from './presentation.js';
18
+ // IT-Wallet profiles it-wallet-1 (specification 1.4.7) and it-wallet-2 (1.5.0, EUDIW path);
19
+ // not yet run against an Italian wallet
20
+ export { IT_WALLET_PROFILE, IT_WALLET_EUDIW_PROFILE, IT_WALLET_PID_VCT, IT_WALLET_PID_VCT_TRANSITIONAL, IT_WALLET_EUDIW_SCHEME, IT_WALLET_CLIENT_ID_PREFIXES, IT_WALLET_DEFAULT_CLAIMS, IT_WALLET_REGISTRAR_DATASET_MEMBERS, IT_WALLET_PRINCIPAL_ID_CLAIMS, itWalletRequestOptions, itWalletVerifyDefaults, itWalletRequestProblems, itWalletIdentityMatch, } from './itwallet.js';
package/dist/index.d.ts CHANGED
@@ -10,7 +10,7 @@ export { InMemoryNonceStore, InMemoryRevocationRegistry, InMemorySpendingLedger,
10
10
  export { canonicalize, mandateHash, sha256 } from './encoding.js';
11
11
  export { resolveSigningKey, verifyX5c, TrustError, type TrustConfig, type ResolvedKey } from './trust.js';
12
12
  export { checkStatus, StatusUnavailableError, defaultStatusFetcher, StatusListCache, StatusListPublisher, DEFAULT_STATUS_TTL_SECONDS, STATUS_INVALID, STATUS_SUSPENDED, STATUS_VALID, type StatusFetcher, type StatusReference, } from './status.js';
13
- export { createMandateRequest, handleMandateResponse, authorizationRequestUrl, PID_QUERY_ID, type MandateRequest, type MandateRequestOptions, type MandateRequestSession, type MandateResponseOptions, type MandateResponseResult, } from './openid4vp.js';
13
+ export { createMandateRequest, handleMandateResponse, authorizationRequestUrl, x509HashClientId, signMandateRequestObject, SELF_ISSUED_AUDIENCE, DEFAULT_CLAIM_PURPOSES, PID_QUERY_ID, type ClaimDisclosure, type MandateRequest, type MandateRequestOptions, type TrustedAuthority, type VerifierInfo, type MandateRequestSession, type MandateResponseOptions, type MandateResponseResult, } from './openid4vp.js';
14
14
  export { checkPidStatus, decodeMandateTransactionData, type RootOptions } from './root.js';
15
15
  export { httpsOrigin, isStatusReference } from './status.js';
16
16
  export type { DelegationFormat } from './delegate-sdjwt.js';
package/dist/index.js CHANGED
@@ -10,7 +10,7 @@ export { InMemoryNonceStore, InMemoryRevocationRegistry, InMemorySpendingLedger,
10
10
  export { canonicalize, mandateHash, sha256 } from './encoding.js';
11
11
  export { resolveSigningKey, verifyX5c, TrustError } from './trust.js';
12
12
  export { checkStatus, StatusUnavailableError, defaultStatusFetcher, StatusListCache, StatusListPublisher, DEFAULT_STATUS_TTL_SECONDS, STATUS_INVALID, STATUS_SUSPENDED, STATUS_VALID, } from './status.js';
13
- export { createMandateRequest, handleMandateResponse, authorizationRequestUrl, PID_QUERY_ID, } from './openid4vp.js';
13
+ export { createMandateRequest, handleMandateResponse, authorizationRequestUrl, x509HashClientId, signMandateRequestObject, SELF_ISSUED_AUDIENCE, DEFAULT_CLAIM_PURPOSES, PID_QUERY_ID, } from './openid4vp.js';
14
14
  export { checkPidStatus, decodeMandateTransactionData } from './root.js';
15
15
  export { httpsOrigin, isStatusReference } from './status.js';
16
16
  // stores
@@ -0,0 +1,86 @@
1
+ import { type MandateRequestOptions, type TrustedAuthority, type VerifierInfo } from './openid4vp.js';
2
+ import type { SigningKey } from './signer.js';
3
+ import type { Mandate } from './types.js';
4
+ export type { TrustedAuthority, VerifierInfo } from './openid4vp.js';
5
+ export declare const IT_WALLET_PROFILE = "it-wallet-1";
6
+ /** Profile for the EUDIW path of the IT-Wallet specification 1.5.0. */
7
+ export declare const IT_WALLET_EUDIW_PROFILE = "it-wallet-2";
8
+ export type ItWalletProfile = typeof IT_WALLET_PROFILE | typeof IT_WALLET_EUDIW_PROFILE;
9
+ /** PID type of the IT-Wallet specification (1.4.7 and 1.5.0). Not yet confirmed against an issued PID. */
10
+ export declare const IT_WALLET_PID_VCT = "urn:eudi:pid:it:1";
11
+ /** PID type that 1.5.0 allows national implementations to use before full EUDIW operability. */
12
+ export declare const IT_WALLET_PID_VCT_TRANSITIONAL = "urn:it-wallet:pid:1";
13
+ /** Invocation scheme of the EUDIW path when the wallet publishes no HTTPS authorization endpoint (1.5.0). */
14
+ export declare const IT_WALLET_EUDIW_SCHEME = "eu-eaap://";
15
+ /** Client identifier prefixes the IT-Wallet specification allows for relying parties. */
16
+ export declare const IT_WALLET_CLIENT_ID_PREFIXES: readonly string[];
17
+ /** Claims asked by default: the names for the record and a stable identifier for the principal. */
18
+ export declare const IT_WALLET_DEFAULT_CLAIMS: readonly string[];
19
+ /**
20
+ * Claims for `principal_id` under these profiles, in order of preference: the IT-Wallet specification 1.5.0
21
+ * makes `personal_administrative_number` or `tax_id_code` the primary identity matching key. Pass as
22
+ * `idClaims` to `principalIdentity`, `AuditLog` or `toOpaInput`.
23
+ */
24
+ export declare const IT_WALLET_PRINCIPAL_ID_CLAIMS: readonly string[];
25
+ /** Members the registrar dataset of `verifier_info` must carry on the EUDIW path (1.5.0). */
26
+ export declare const IT_WALLET_REGISTRAR_DATASET_MEMBERS: readonly string[];
27
+ export interface ItWalletRequestInput {
28
+ /** `it-wallet-1` (specification 1.4.7, default) or `it-wallet-2` (1.5.0, EUDIW path). */
29
+ profile?: ItWalletProfile;
30
+ mandate: Mandate;
31
+ /** Where the wallet posts its response. */
32
+ responseUri: string;
33
+ /** Signs the request object. The client identifier is the x509_hash of `x5c[0]`; under it-wallet-2 that is the WRPAC. */
34
+ signer: {
35
+ key: SigningKey;
36
+ x5c: string[];
37
+ };
38
+ /** PID claims to request. Default `IT_WALLET_DEFAULT_CLAIMS`. Each needs a purpose. */
39
+ disclose?: string[];
40
+ /** Purposes for claims beyond those Plenipo relies on. */
41
+ claimPurposes?: Record<string, string>;
42
+ /** Accepted PID types. Default `[IT_WALLET_PID_VCT]`. */
43
+ pidVcts?: string[];
44
+ lifetimeSeconds?: number;
45
+ /** it-wallet-2: the registrar dataset and the registration certificate (WRPRC), as `verifier_info`. */
46
+ verifierInfo?: VerifierInfo[];
47
+ /** it-wallet-2: the ETSI trusted lists the PID must chain to, as DCQL `trusted_authorities`. */
48
+ trustedAuthorities?: TrustedAuthority[];
49
+ }
50
+ /**
51
+ * Options for `createMandateRequest` under an IT-Wallet profile: x509_hash client identifier from the
52
+ * signing certificate, encrypted response, the Italian PID type, and a stated purpose for every claim.
53
+ * Under it-wallet-2 also `verifier_info` and `trusted_authorities`, which it refuses to leave out.
54
+ */
55
+ export declare function itWalletRequestOptions(input: ItWalletRequestInput): MandateRequestOptions;
56
+ /** Verifier settings matching the profiles: accept the Italian PID type. */
57
+ export declare function itWalletVerifyDefaults(pidVcts?: string[]): {
58
+ acceptedPidVcts: string[];
59
+ acceptedVcts: string[];
60
+ };
61
+ /**
62
+ * Checks built request parameters, and the signed request object, against the rules of the Italian remote
63
+ * flow that the profile knows. Returns the problems found; empty means none of these rules is broken, not
64
+ * that a wallet will accept the request.
65
+ */
66
+ export declare function itWalletRequestProblems(params: Record<string, unknown>, requestObject?: string, opts?: {
67
+ profile?: ItWalletProfile;
68
+ }): string[];
69
+ /** How a relying party ties the presented identity attributes to one natural person (1.5.0, identity matching). */
70
+ export interface ItWalletIdentityMatch {
71
+ /** `unique_identifier`: a national identifier was presented. `attributes`: attribute-based binding. */
72
+ method: 'unique_identifier' | 'attributes';
73
+ /** The claim used, for `unique_identifier`. */
74
+ claim?: 'personal_administrative_number' | 'tax_id_code';
75
+ /** The matching key: the identifier itself, or a hash of the normalised minimum attribute set. */
76
+ key: string;
77
+ }
78
+ /**
79
+ * The identity matching key of the IT-Wallet specification 1.5.0 for a PID or an IT-Wallet ID, from the
80
+ * claims presented. With `personal_administrative_number` or `tax_id_code`, that identifier (in this order
81
+ * of preference). Without one, attribute-based binding over `family_name`, `given_name`, the date of birth
82
+ * (`birth_date` or `birthdate`, ISO 8601) and `place_of_birth`, after normalising case, whitespace and
83
+ * diacritics. Returns null when that minimum set is incomplete: a subset of it must not be treated as a
84
+ * match. Use the key to find a stored user record; a key that matches more than one record is not a match.
85
+ */
86
+ export declare function itWalletIdentityMatch(claims: Record<string, unknown>): ItWalletIdentityMatch | null;
@@ -0,0 +1,269 @@
1
+ /**
2
+ * IT-Wallet profiles (experimental): mandate requests shaped for the Italian IT-Wallet System.
3
+ *
4
+ * `it-wallet-1` follows the IT-Wallet technical specification 1.4.7 (September 2026), the version in use:
5
+ * - remote flow on OpenID4VP 1.0 with a signed request object, a DCQL query and response_mode
6
+ * direct_post.jwt, the response encrypted with ECDH-ES on P-256 and AES-GCM;
7
+ * - client identifier prefixes `openid_federation` and `x509_hash`; these profiles build `x509_hash`,
8
+ * `openid_federation` needs a federation entity and is not implemented yet;
9
+ * - transaction_data as an optional request parameter, its hashes in `transaction_data_hashes` of the
10
+ * SD-JWT VC key binding JWT, which is how a `plenipo_mandate` is already bound;
11
+ * - PID as SD-JWT VC of type `urn:eudi:pid:it:1`.
12
+ *
13
+ * `it-wallet-2` follows the EUDIW path of version 1.5.0 (pre-release, November 2026), the baseline for
14
+ * notifying IT-Wallet as a European Digital Identity Wallet. On top of `it-wallet-1`, from the remote flow
15
+ * of 1.5.0 and ETSI TS 119 472-2: `iss` equal to the client identifier, a nonce of at least 32
16
+ * characters, A128GCM and A256GCM both listed, `verifier_info` with the registrar dataset and the
17
+ * registration certificate (WRPRC), `trusted_authorities` of type `etsi_tl` in every DCQL query, and the
18
+ * `eu-eaap://` invocation scheme. The signing certificate must be the access certificate (WRPAC), with its
19
+ * chain up to and excluding the trust anchor.
20
+ *
21
+ * What is not known: whether an IT-Wallet app shows a `plenipo_mandate` to the person and signs it, or
22
+ * refuses the request. Nothing in these profiles has run against an Italian wallet. Under 1.5.0 a PID is
23
+ * issued only once the wallet is notified; until then national identification uses the IT-Wallet ID on the
24
+ * `openid_federation` path, which these profiles do not cover.
25
+ */
26
+ import { createHash } from 'node:crypto';
27
+ import { decodeJwt, decodeProtectedHeader } from 'jose';
28
+ import { X509Certificate } from 'node:crypto';
29
+ import { DEFAULT_CLAIM_PURPOSES, x509HashClientId } from './openid4vp.js';
30
+ export const IT_WALLET_PROFILE = 'it-wallet-1';
31
+ /** Profile for the EUDIW path of the IT-Wallet specification 1.5.0. */
32
+ export const IT_WALLET_EUDIW_PROFILE = 'it-wallet-2';
33
+ /** PID type of the IT-Wallet specification (1.4.7 and 1.5.0). Not yet confirmed against an issued PID. */
34
+ export const IT_WALLET_PID_VCT = 'urn:eudi:pid:it:1';
35
+ /** PID type that 1.5.0 allows national implementations to use before full EUDIW operability. */
36
+ export const IT_WALLET_PID_VCT_TRANSITIONAL = 'urn:it-wallet:pid:1';
37
+ /** Invocation scheme of the EUDIW path when the wallet publishes no HTTPS authorization endpoint (1.5.0). */
38
+ export const IT_WALLET_EUDIW_SCHEME = 'eu-eaap://';
39
+ /** Client identifier prefixes the IT-Wallet specification allows for relying parties. */
40
+ export const IT_WALLET_CLIENT_ID_PREFIXES = Object.freeze(['openid_federation', 'x509_hash']);
41
+ /** Claims asked by default: the names for the record and a stable identifier for the principal. */
42
+ export const IT_WALLET_DEFAULT_CLAIMS = Object.freeze(['given_name', 'family_name', 'personal_administrative_number']);
43
+ /**
44
+ * Claims for `principal_id` under these profiles, in order of preference: the IT-Wallet specification 1.5.0
45
+ * makes `personal_administrative_number` or `tax_id_code` the primary identity matching key. Pass as
46
+ * `idClaims` to `principalIdentity`, `AuditLog` or `toOpaInput`.
47
+ */
48
+ export const IT_WALLET_PRINCIPAL_ID_CLAIMS = Object.freeze(['personal_administrative_number', 'tax_id_code']);
49
+ /** Members the registrar dataset of `verifier_info` must carry on the EUDIW path (1.5.0). */
50
+ export const IT_WALLET_REGISTRAR_DATASET_MEMBERS = Object.freeze([
51
+ 'identifier',
52
+ 'srvDescription',
53
+ 'registryURI',
54
+ 'intendedUseIdentifier',
55
+ 'purpose',
56
+ 'policyURI',
57
+ ]);
58
+ /**
59
+ * Options for `createMandateRequest` under an IT-Wallet profile: x509_hash client identifier from the
60
+ * signing certificate, encrypted response, the Italian PID type, and a stated purpose for every claim.
61
+ * Under it-wallet-2 also `verifier_info` and `trusted_authorities`, which it refuses to leave out.
62
+ */
63
+ export function itWalletRequestOptions(input) {
64
+ const profile = input.profile ?? IT_WALLET_PROFILE;
65
+ if (profile !== IT_WALLET_PROFILE && profile !== IT_WALLET_EUDIW_PROFILE)
66
+ throw new Error(`unknown IT-Wallet profile ${String(profile)}`);
67
+ const leaf = input.signer?.x5c?.[0];
68
+ if (!leaf)
69
+ throw new Error(`profile ${profile} needs a signer with its certificate in x5c`);
70
+ if (profile === IT_WALLET_EUDIW_PROFILE) {
71
+ const problems = verifierInfoProblems(input.verifierInfo);
72
+ if (problems.length)
73
+ throw new Error(`profile it-wallet-2 needs verifierInfo: ${problems.join('; ')}`);
74
+ if (!input.trustedAuthorities?.some((t) => t?.type === 'etsi_tl' && Array.isArray(t.values) && t.values.length > 0)) {
75
+ throw new Error('profile it-wallet-2 needs trustedAuthorities with an etsi_tl entry');
76
+ }
77
+ }
78
+ return {
79
+ mandate: input.mandate,
80
+ clientId: x509HashClientId(leaf),
81
+ responseUri: input.responseUri,
82
+ signer: input.signer,
83
+ encryptResponse: true,
84
+ transactionDataType: 'plenipo_mandate',
85
+ pidVcts: input.pidVcts ?? [IT_WALLET_PID_VCT],
86
+ disclose: input.disclose ?? [...IT_WALLET_DEFAULT_CLAIMS],
87
+ claimPurposes: { ...DEFAULT_CLAIM_PURPOSES, ...(input.claimPurposes ?? {}) },
88
+ requireClaimPurposes: true,
89
+ ...(input.lifetimeSeconds !== undefined ? { lifetimeSeconds: input.lifetimeSeconds } : {}),
90
+ ...(profile === IT_WALLET_EUDIW_PROFILE ? { verifierInfo: input.verifierInfo, trustedAuthorities: input.trustedAuthorities } : {}),
91
+ };
92
+ }
93
+ /** Verifier settings matching the profiles: accept the Italian PID type. */
94
+ export function itWalletVerifyDefaults(pidVcts = [IT_WALLET_PID_VCT]) {
95
+ return { acceptedPidVcts: [...pidVcts], acceptedVcts: [...pidVcts] };
96
+ }
97
+ function isMultiLangString(v) {
98
+ return (Array.isArray(v) &&
99
+ v.length > 0 &&
100
+ v.every((e) => typeof e === 'object' && e !== null && typeof e.lang === 'string' && typeof e.value === 'string' && e.value.length > 0));
101
+ }
102
+ function verifierInfoProblems(list) {
103
+ if (!Array.isArray(list) || list.length === 0)
104
+ return ['verifier_info is missing'];
105
+ const problems = [];
106
+ const dataset = list.filter((v) => v?.format === 'registrar_dataset');
107
+ const cert = list.filter((v) => v?.format === 'registration_cert');
108
+ if (dataset.length !== 1)
109
+ problems.push('verifier_info needs exactly one registrar_dataset');
110
+ else {
111
+ const data = dataset[0].data;
112
+ if (typeof data !== 'object' || data === null || Array.isArray(data))
113
+ problems.push('registrar_dataset data must be an object');
114
+ else {
115
+ for (const m of IT_WALLET_REGISTRAR_DATASET_MEMBERS)
116
+ if (data[m] === undefined)
117
+ problems.push(`registrar_dataset lacks ${m}`);
118
+ for (const m of ['srvDescription', 'purpose']) {
119
+ const v = data[m];
120
+ if (v !== undefined && !isMultiLangString(v))
121
+ problems.push(`registrar_dataset ${m} must be a MultiLangString list`);
122
+ }
123
+ }
124
+ }
125
+ if (cert.length !== 1)
126
+ problems.push('verifier_info needs exactly one registration_cert');
127
+ else if (typeof cert[0].data !== 'string' || !/^[A-Za-z0-9_.~-]+$/.test(cert[0].data))
128
+ problems.push('registration_cert data must be the base64url WRPRC');
129
+ if (list.some((v) => v && typeof v === 'object' && 'credential_ids' in v))
130
+ problems.push('verifier_info must not contain credential_ids');
131
+ return problems;
132
+ }
133
+ function isSelfSigned(b64) {
134
+ try {
135
+ const c = new X509Certificate(Buffer.from(b64, 'base64'));
136
+ return c.subject === c.issuer && c.verify(c.publicKey);
137
+ }
138
+ catch {
139
+ return false;
140
+ }
141
+ }
142
+ /**
143
+ * Checks built request parameters, and the signed request object, against the rules of the Italian remote
144
+ * flow that the profile knows. Returns the problems found; empty means none of these rules is broken, not
145
+ * that a wallet will accept the request.
146
+ */
147
+ export function itWalletRequestProblems(params, requestObject, opts = {}) {
148
+ const profile = opts.profile ?? IT_WALLET_PROFILE;
149
+ const problems = [];
150
+ const clientId = params.client_id;
151
+ const prefix = typeof clientId === 'string' ? clientId.slice(0, Math.max(0, clientId.indexOf(':'))) : '';
152
+ if (!IT_WALLET_CLIENT_ID_PREFIXES.includes(prefix))
153
+ problems.push(`client_id prefix must be one of ${IT_WALLET_CLIENT_ID_PREFIXES.join(', ')}`);
154
+ if (params.response_mode !== 'direct_post.jwt')
155
+ problems.push('response_mode must be direct_post.jwt');
156
+ if (params.response_type !== 'vp_token')
157
+ problems.push('response_type must be vp_token');
158
+ const dcql = params.dcql_query;
159
+ const queries = dcql && Array.isArray(dcql.credentials) ? dcql.credentials : [];
160
+ if (queries.length === 0)
161
+ problems.push('a DCQL query is required');
162
+ else if (queries.some((c) => c?.format !== 'dc+sd-jwt'))
163
+ problems.push('every credential query must ask for dc+sd-jwt');
164
+ const minNonce = profile === IT_WALLET_EUDIW_PROFILE ? 32 : 16;
165
+ if (typeof params.nonce !== 'string' || params.nonce.length < minNonce)
166
+ problems.push(`nonce must be a string of at least ${minNonce} characters`);
167
+ if (!Array.isArray(params.transaction_data) || params.transaction_data.length === 0)
168
+ problems.push('transaction_data is missing');
169
+ else if (params.transaction_data.some((t) => typeof t !== 'string' || !/^[A-Za-z0-9_-]+$/.test(t)))
170
+ problems.push('transaction_data entries must be base64url strings');
171
+ const signed = typeof requestObject === 'string' && requestObject.split('.').length === 3;
172
+ if (!signed)
173
+ problems.push('the request object must be signed');
174
+ if (profile !== IT_WALLET_EUDIW_PROFILE)
175
+ return problems;
176
+ if (prefix !== 'x509_hash')
177
+ problems.push('the EUDIW path uses the x509_hash client identifier prefix');
178
+ for (const p of verifierInfoProblems(params.verifier_info))
179
+ problems.push(p);
180
+ if (queries.length && queries.some((q) => !Array.isArray(q?.trusted_authorities) || !q.trusted_authorities.some((t) => t?.type === 'etsi_tl' && Array.isArray(t.values) && t.values.length > 0))) {
181
+ problems.push('every DCQL query needs trusted_authorities of type etsi_tl');
182
+ }
183
+ const cm = params.client_metadata;
184
+ const keys = cm?.jwks?.keys ?? [];
185
+ if (keys.length === 0)
186
+ problems.push('client_metadata.jwks must carry the response encryption key');
187
+ if (keys.some((k) => typeof k.kid !== 'string' || typeof k.use !== 'string'))
188
+ problems.push('every client_metadata key needs kid and use');
189
+ if (new Set(keys.map((k) => k.kid)).size !== keys.length)
190
+ problems.push('client_metadata key ids must be unique');
191
+ const enc = Array.isArray(cm?.encrypted_response_enc_values_supported) ? cm.encrypted_response_enc_values_supported : [];
192
+ if (!['A128GCM', 'A256GCM'].every((e) => enc.includes(e)))
193
+ problems.push('client_metadata must list both A128GCM and A256GCM');
194
+ if (signed) {
195
+ try {
196
+ const h = decodeProtectedHeader(requestObject);
197
+ const p = decodeJwt(requestObject);
198
+ if (h.alg !== 'ES256')
199
+ problems.push('the request object must be signed with ES256');
200
+ if (h.typ !== 'oauth-authz-req+jwt')
201
+ problems.push('the request object typ must be oauth-authz-req+jwt');
202
+ if (!Array.isArray(h.x5c) || h.x5c.length === 0)
203
+ problems.push('the request object needs x5c with the WRPAC first');
204
+ else {
205
+ if (typeof clientId === 'string' && x509HashClientId(h.x5c[0]) !== clientId)
206
+ problems.push('client_id is not the hash of the first x5c certificate');
207
+ if (h.x5c.length > 1 && isSelfSigned(h.x5c[h.x5c.length - 1]))
208
+ problems.push('x5c must not include the trust anchor');
209
+ }
210
+ if (p.iss !== clientId)
211
+ problems.push('iss must equal the prefix-qualified client_id');
212
+ if (p.client_id !== clientId)
213
+ problems.push('the request object client_id differs from the request');
214
+ if (typeof p.aud !== 'string' || p.aud.length === 0)
215
+ problems.push('the request object needs aud');
216
+ if (typeof p.iat !== 'number')
217
+ problems.push('the request object needs iat');
218
+ if (typeof p.exp !== 'number' || (typeof p.iat === 'number' && p.exp <= p.iat))
219
+ problems.push('the request object needs an exp after iat');
220
+ }
221
+ catch {
222
+ problems.push('the request object cannot be decoded');
223
+ }
224
+ }
225
+ return problems;
226
+ }
227
+ function normalise(s) {
228
+ return s
229
+ .normalize('NFD')
230
+ .replace(/\p{M}/gu, '')
231
+ .toLowerCase()
232
+ .replace(/\s+/g, ' ')
233
+ .trim();
234
+ }
235
+ /**
236
+ * The identity matching key of the IT-Wallet specification 1.5.0 for a PID or an IT-Wallet ID, from the
237
+ * claims presented. With `personal_administrative_number` or `tax_id_code`, that identifier (in this order
238
+ * of preference). Without one, attribute-based binding over `family_name`, `given_name`, the date of birth
239
+ * (`birth_date` or `birthdate`, ISO 8601) and `place_of_birth`, after normalising case, whitespace and
240
+ * diacritics. Returns null when that minimum set is incomplete: a subset of it must not be treated as a
241
+ * match. Use the key to find a stored user record; a key that matches more than one record is not a match.
242
+ */
243
+ export function itWalletIdentityMatch(claims) {
244
+ for (const claim of ['personal_administrative_number', 'tax_id_code']) {
245
+ const v = claims[claim];
246
+ if (typeof v === 'string' && v.trim().length > 0)
247
+ return { method: 'unique_identifier', claim, key: v.trim() };
248
+ }
249
+ const given = claims.given_name;
250
+ const family = claims.family_name;
251
+ const birth = claims.birth_date ?? claims.birthdate;
252
+ const place = claims.place_of_birth;
253
+ if (typeof given !== 'string' || typeof family !== 'string' || !normalise(given) || !normalise(family))
254
+ return null;
255
+ if (typeof birth !== 'string' || !/^\d{4}-\d{2}-\d{2}$/.test(birth) || Number.isNaN(Date.parse(`${birth}T00:00:00Z`)))
256
+ return null;
257
+ if (typeof place !== 'object' || place === null || Array.isArray(place))
258
+ return null;
259
+ const p = {};
260
+ for (const m of ['country', 'region', 'locality']) {
261
+ const v = place[m];
262
+ if (typeof v === 'string' && normalise(v))
263
+ p[m] = normalise(v);
264
+ }
265
+ if (Object.keys(p).length === 0)
266
+ return null;
267
+ const canonical = JSON.stringify([normalise(family), normalise(given), birth, p.country ?? '', p.region ?? '', p.locality ?? '']);
268
+ return { method: 'attributes', key: createHash('sha256').update(canonical).digest('base64url') };
269
+ }
@@ -22,6 +22,16 @@ export interface MandateRequestOptions {
22
22
  responseUri: string;
23
23
  /** PID claims to request. Default given_name and family_name. */
24
24
  disclose?: string[];
25
+ /** PID types to ask for in the DCQL query (`vct_values`). Default `['urn:eudi:pid:1']`. */
26
+ pidVcts?: string[];
27
+ /**
28
+ * Why each requested claim is needed, by claim name: reported in `MandateRequest.disclosure`, so a relying
29
+ * party can show that it asks only for what the mandate needs. Claims Plenipo itself relies on have a
30
+ * default reason (`DEFAULT_CLAIM_PURPOSES`).
31
+ */
32
+ claimPurposes?: Record<string, string>;
33
+ /** Refuse to build a request that asks for a claim with no stated purpose. Default false. */
34
+ requireClaimPurposes?: boolean;
25
35
  /** Encrypt the wallet response to this platform. Default true. */
26
36
  encryptResponse?: boolean;
27
37
  /** Signs the request object. Required by most wallets for x509_san_dns client identifiers. */
@@ -57,6 +67,20 @@ export interface MandateRequestOptions {
57
67
  vcts?: string[];
58
68
  identityClaims?: string[];
59
69
  };
70
+ /**
71
+ * Authorities whose trust lists the requested credentials must chain to, added to every DCQL credential
72
+ * query as `trusted_authorities` (OpenID4VP 1.0, section 6.1.1). The EUDIW path of the IT-Wallet
73
+ * specification 1.5.0 requires `{ type: 'etsi_tl', values: [<trusted list URL>] }`.
74
+ */
75
+ trustedAuthorities?: TrustedAuthority[];
76
+ /**
77
+ * `verifier_info` for the request object (OpenID4VP 1.0, section 5.1): attestations about the verifier,
78
+ * such as the registrar dataset and the registration certificate that ETSI TS 119 472-2 requires.
79
+ * Plenipo carries them as given and does not check their content.
80
+ */
81
+ verifierInfo?: VerifierInfo[];
82
+ /** `aud` of the signed request object. Default `https://self-issued.me/v2` (OpenID4VP 1.0, section 5.8). */
83
+ requestAudience?: string;
60
84
  /**
61
85
  * How long the request can be answered, in seconds. Default 600, the default `maxAgeSeconds` of
62
86
  * `handleMandateResponse`. The signed request object carries it as `exp`, so a wallet that checks it
@@ -64,6 +88,18 @@ export interface MandateRequestOptions {
64
88
  */
65
89
  lifetimeSeconds?: number;
66
90
  }
91
+ /** An entry of DCQL `trusted_authorities`. */
92
+ export interface TrustedAuthority {
93
+ type: string;
94
+ values: string[];
95
+ }
96
+ /** An entry of `verifier_info`: a format name and its data. */
97
+ export interface VerifierInfo {
98
+ format: string;
99
+ data: unknown;
100
+ credential_ids?: string[];
101
+ }
102
+ export declare const SELF_ISSUED_AUDIENCE = "https://self-issued.me/v2";
67
103
  /** What the platform keeps between the request and the response. Contains a private key: keep it server-side. */
68
104
  export interface MandateRequestSession {
69
105
  clientId: string;
@@ -81,17 +117,47 @@ export interface MandateRequestSession {
81
117
  /** DCQL query ids besides `pid` whose presentations the response must contain. */
82
118
  extraQueries?: string[];
83
119
  }
120
+ /** One claim a request asks for, and why. */
121
+ export interface ClaimDisclosure {
122
+ /** DCQL credential query id: `pid`, `sca` or `representation`. */
123
+ credential: string;
124
+ claim: string;
125
+ /** Why the claim is needed; absent when nobody stated it. */
126
+ purpose?: string;
127
+ }
128
+ /** Reasons for the claims Plenipo itself relies on. */
129
+ export declare const DEFAULT_CLAIM_PURPOSES: Readonly<Record<string, string>>;
84
130
  export interface MandateRequest {
85
131
  /** Authorization request parameters, as JSON. */
86
132
  params: Record<string, unknown>;
133
+ /** Every claim the request asks for, by credential, with its purpose: the data minimisation record. */
134
+ disclosure: ClaimDisclosure[];
87
135
  /** Signed request object, when a signer was given: serve it at the request_uri until `expiresAt`. */
88
136
  requestObject?: string;
89
137
  /** When the request expires, in seconds since the epoch: show it to the person, stop serving the request object after it. */
90
138
  expiresAt: number;
139
+ /** `aud` of the signed request object, kept so `signMandateRequestObject` can sign it again. */
140
+ requestAudience: string;
91
141
  session: MandateRequestSession;
92
142
  }
93
143
  /** Builds the OpenID4VP authorization request for a mandate. */
94
144
  export declare function createMandateRequest(opts: MandateRequestOptions): Promise<MandateRequest>;
145
+ /**
146
+ * Signs the request object again with the `wallet_nonce` a wallet sent when it fetched the request with
147
+ * `request_uri_method=post` (OpenID4VP 1.0, section 5.10). Everything else, nonce, state, expiry and the
148
+ * response key, stays as in the original request, so the session does not change.
149
+ */
150
+ export declare function signMandateRequestObject(request: MandateRequest, signer: {
151
+ key: SigningKey;
152
+ x5c?: string[];
153
+ }, opts?: {
154
+ walletNonce?: string;
155
+ }): Promise<string>;
156
+ /**
157
+ * The `x509_hash` client identifier for a certificate (OpenID4VP 1.0, section 5.9.3): the base64url
158
+ * SHA-256 of its DER encoding. Accepts an x5c entry (base64 DER) or a PEM certificate.
159
+ */
160
+ export declare function x509HashClientId(certificate: string): string;
95
161
  /** The URL to put in a QR code or a link, for a request object served at `requestUri`. */
96
162
  export declare function authorizationRequestUrl(clientId: string, requestUri: string, scheme?: string): string;
97
163
  export interface MandateResponseResult {
package/dist/openid4vp.js CHANGED
@@ -7,7 +7,7 @@
7
7
  * Responses are encrypted to the platform by default (response_mode direct_post.jwt), as HAIP requires.
8
8
  */
9
9
  import { signCompactJwt } from './signer.js';
10
- import { randomBytes, randomUUID } from 'node:crypto';
10
+ import { createHash, randomBytes, randomUUID, X509Certificate } from 'node:crypto';
11
11
  import { compactDecrypt, exportJWK, generateKeyPair, } from 'jose';
12
12
  import { REPRESENTATION_QUERY_ID, representationQuery } from './legal.js';
13
13
  import { encodeMandateTransactionData } from './mandate.js';
@@ -17,9 +17,17 @@ import { encodeEmandateTransactionData, mandateToEmandate } from './ts12.js';
17
17
  import { EMANDATE_TX_DATA_TYPE, PID_VCT } from './types.js';
18
18
  export const PID_QUERY_ID = 'pid';
19
19
  export const REQUEST_OBJECT_TYP = 'oauth-authz-req+jwt';
20
+ export const SELF_ISSUED_AUDIENCE = 'https://self-issued.me/v2';
21
+ /** Reasons for the claims Plenipo itself relies on. */
22
+ export const DEFAULT_CLAIM_PURPOSES = Object.freeze({
23
+ given_name: 'Names the person who approves the mandate, in the decision and in the audit log.',
24
+ family_name: 'Names the person who approves the mandate, in the decision and in the audit log.',
25
+ personal_administrative_number: 'Identifies the person stably across mandates (principal_id), so limits, revocations and audit records refer to the same person.',
26
+ });
20
27
  /** Builds the OpenID4VP authorization request for a mandate. */
21
28
  export async function createMandateRequest(opts) {
22
- const nonce = randomBytes(16).toString('base64url');
29
+ // 32 bytes, 43 characters: the IT-Wallet specification 1.5.0 asks for at least 32 (RPR-93).
30
+ const nonce = randomBytes(32).toString('base64url');
23
31
  const state = randomUUID();
24
32
  const lifetime = opts.lifetimeSeconds ?? 600;
25
33
  if (!Number.isSafeInteger(lifetime) || lifetime <= 0)
@@ -37,20 +45,53 @@ export async function createMandateRequest(opts) {
37
45
  type: em.type ?? EMANDATE_TX_DATA_TYPE,
38
46
  })
39
47
  : encodeMandateTransactionData(opts.mandate, PID_QUERY_ID);
48
+ checkClientId(opts.clientId, opts.signer);
49
+ const pidVcts = opts.pidVcts ?? [PID_VCT];
50
+ if (!Array.isArray(pidVcts) || pidVcts.length === 0 || pidVcts.some((v) => typeof v !== 'string' || v.length === 0)) {
51
+ throw new Error('pidVcts must be a non-empty list of credential types');
52
+ }
40
53
  const extraQueries = [];
54
+ const purposes = { ...DEFAULT_CLAIM_PURPOSES, ...(opts.claimPurposes ?? {}) };
55
+ const scaBindingPurpose = 'Ties the SCA attestation to the PID holder (scaIdentityClaims).';
56
+ const representationBindingPurpose = 'Ties the representation attestation to the PID holder.';
41
57
  // Identity claims compared with another credential must be disclosed by the PID too.
42
58
  const pidClaims = new Set(opts.disclose ?? ['given_name', 'family_name']);
59
+ const pidPurpose = new Map();
43
60
  if (emandate && bindTo === SCA_QUERY_ID)
44
- for (const c of em.scaIdentityClaims ?? [])
61
+ for (const c of em.scaIdentityClaims ?? []) {
45
62
  pidClaims.add(c);
63
+ pidPurpose.set(c, purposes[c] ?? scaBindingPurpose);
64
+ }
46
65
  if (opts.mandate.principal)
47
- for (const c of opts.representation?.identityClaims ?? [])
66
+ for (const c of opts.representation?.identityClaims ?? []) {
48
67
  pidClaims.add(c);
68
+ if (!pidPurpose.has(c))
69
+ pidPurpose.set(c, purposes[c] ?? representationBindingPurpose);
70
+ }
71
+ const disclosure = [...pidClaims].map((claim) => {
72
+ const purpose = Object.hasOwn(purposes, claim) ? purposes[claim] : pidPurpose.get(claim);
73
+ return { credential: PID_QUERY_ID, claim, ...(purpose ? { purpose } : {}) };
74
+ });
75
+ for (const c of em.scaIdentityClaims ?? []) {
76
+ if (emandate && bindTo === SCA_QUERY_ID)
77
+ disclosure.push({ credential: SCA_QUERY_ID, claim: c, purpose: scaBindingPurpose });
78
+ }
79
+ if (opts.mandate.principal) {
80
+ for (const c of opts.representation?.identityClaims ?? [])
81
+ disclosure.push({ credential: REPRESENTATION_QUERY_ID, claim: c, purpose: representationBindingPurpose });
82
+ }
83
+ const trustedAuthorities = checkTrustedAuthorities(opts.trustedAuthorities);
84
+ const verifierInfo = checkVerifierInfo(opts.verifierInfo);
85
+ if (opts.requireClaimPurposes) {
86
+ const missing = disclosure.filter((d) => !d.purpose).map((d) => d.claim);
87
+ if (missing.length)
88
+ throw new Error(`no purpose stated for the requested claims: ${missing.join(', ')}`);
89
+ }
49
90
  const queries = [
50
91
  {
51
92
  id: PID_QUERY_ID,
52
93
  format: 'dc+sd-jwt',
53
- meta: { vct_values: [PID_VCT] },
94
+ meta: { vct_values: [...pidVcts] },
54
95
  claims: [...pidClaims].map((c) => ({ path: [c] })),
55
96
  },
56
97
  ];
@@ -67,6 +108,9 @@ export async function createMandateRequest(opts) {
67
108
  extraQueries.push(REPRESENTATION_QUERY_ID);
68
109
  queries.push(representationQuery(opts.representation));
69
110
  }
111
+ if (trustedAuthorities)
112
+ for (const q of queries)
113
+ q.trusted_authorities = trustedAuthorities.map((t) => ({ type: t.type, values: [...t.values] }));
70
114
  const encrypt = opts.encryptResponse ?? true;
71
115
  let decryptionKey;
72
116
  let encJwk;
@@ -87,17 +131,30 @@ export async function createMandateRequest(opts) {
87
131
  transaction_data: [transactionData],
88
132
  client_metadata: {
89
133
  vp_formats_supported: { 'dc+sd-jwt': { 'sd-jwt_alg_values': ['ES256'], 'kb-jwt_alg_values': ['ES256'] } },
90
- ...(encJwk ? { jwks: { keys: [encJwk] }, encrypted_response_enc_values_supported: ['A128GCM'] } : {}),
134
+ ...(encJwk
135
+ ? {
136
+ jwks: { keys: [encJwk] },
137
+ encrypted_response_alg_values_supported: ['ECDH-ES'],
138
+ // Both are accepted by handleMandateResponse; ETSI TS 119 472-2 asks verifiers to list both.
139
+ encrypted_response_enc_values_supported: ['A128GCM', 'A256GCM'],
140
+ }
141
+ : {}),
91
142
  },
143
+ ...(verifierInfo ? { verifier_info: verifierInfo } : {}),
92
144
  };
145
+ const requestAudience = opts.requestAudience ?? SELF_ISSUED_AUDIENCE;
146
+ if (typeof requestAudience !== 'string' || requestAudience.length === 0)
147
+ throw new Error('requestAudience must be a non-empty string');
93
148
  let requestObject;
94
149
  if (opts.signer) {
95
- requestObject = await signCompactJwt({ ...params, aud: 'https://self-issued.me/v2', iat: createdAt, exp: expiresAt }, { alg: 'ES256', typ: REQUEST_OBJECT_TYP, ...(opts.signer.x5c ? { x5c: opts.signer.x5c } : {}) }, opts.signer.key);
150
+ requestObject = await signRequestObject(params, opts.signer, { aud: requestAudience, iat: createdAt, exp: expiresAt });
96
151
  }
97
152
  return {
98
153
  params,
154
+ disclosure,
99
155
  requestObject,
100
156
  expiresAt,
157
+ requestAudience,
101
158
  session: {
102
159
  clientId: opts.clientId,
103
160
  nonce,
@@ -113,6 +170,87 @@ export async function createMandateRequest(opts) {
113
170
  },
114
171
  };
115
172
  }
173
+ async function signRequestObject(params, signer, claims) {
174
+ // iss is the client identifier with its prefix (RFC 9101; required by the IT-Wallet specification 1.5.0).
175
+ return signCompactJwt({ ...params, iss: params.client_id, ...claims }, { alg: 'ES256', typ: REQUEST_OBJECT_TYP, ...(signer.x5c ? { x5c: signer.x5c } : {}) }, signer.key);
176
+ }
177
+ /**
178
+ * Signs the request object again with the `wallet_nonce` a wallet sent when it fetched the request with
179
+ * `request_uri_method=post` (OpenID4VP 1.0, section 5.10). Everything else, nonce, state, expiry and the
180
+ * response key, stays as in the original request, so the session does not change.
181
+ */
182
+ export async function signMandateRequestObject(request, signer, opts = {}) {
183
+ checkClientId(String(request.params.client_id), signer);
184
+ if (opts.walletNonce !== undefined && (typeof opts.walletNonce !== 'string' || opts.walletNonce.length === 0 || opts.walletNonce.length > 512)) {
185
+ throw new Error('wallet_nonce must be a non-empty string of at most 512 characters');
186
+ }
187
+ return signRequestObject(request.params, signer, {
188
+ aud: request.requestAudience,
189
+ iat: request.session.createdAt,
190
+ exp: request.expiresAt,
191
+ ...(opts.walletNonce !== undefined ? { wallet_nonce: opts.walletNonce } : {}),
192
+ });
193
+ }
194
+ function checkTrustedAuthorities(list) {
195
+ if (list === undefined)
196
+ return undefined;
197
+ if (!Array.isArray(list) || list.length === 0)
198
+ throw new Error('trustedAuthorities must be a non-empty list');
199
+ for (const t of list) {
200
+ if (typeof t?.type !== 'string' || t.type.length === 0)
201
+ throw new Error('every trusted authority needs a type');
202
+ if (!Array.isArray(t.values) || t.values.length === 0 || t.values.some((v) => typeof v !== 'string' || v.length === 0)) {
203
+ throw new Error('every trusted authority needs a non-empty list of values');
204
+ }
205
+ }
206
+ return list;
207
+ }
208
+ function checkVerifierInfo(list) {
209
+ if (list === undefined)
210
+ return undefined;
211
+ if (!Array.isArray(list) || list.length === 0)
212
+ throw new Error('verifierInfo must be a non-empty list');
213
+ for (const v of list) {
214
+ if (typeof v?.format !== 'string' || v.format.length === 0)
215
+ throw new Error('every verifier_info entry needs a format');
216
+ if (v.data === undefined || v.data === null)
217
+ throw new Error('every verifier_info entry needs data');
218
+ }
219
+ return structuredClone(list);
220
+ }
221
+ /**
222
+ * The `x509_hash` client identifier for a certificate (OpenID4VP 1.0, section 5.9.3): the base64url
223
+ * SHA-256 of its DER encoding. Accepts an x5c entry (base64 DER) or a PEM certificate.
224
+ */
225
+ export function x509HashClientId(certificate) {
226
+ return `x509_hash:${certificateHash(certificate)}`;
227
+ }
228
+ function certificateHash(certificate) {
229
+ const der = certificate.includes('-----BEGIN')
230
+ ? new X509Certificate(certificate).raw
231
+ : Buffer.from(certificate.replace(/\s+/g, ''), 'base64');
232
+ if (der.length === 0)
233
+ throw new Error('certificate is empty');
234
+ // Parse it, so that a value that is not a certificate is refused rather than hashed.
235
+ new X509Certificate(der);
236
+ return createHash('sha256').update(der).digest('base64url');
237
+ }
238
+ /**
239
+ * A request under an `x509_hash` client identifier must be signed with the key of the certificate it
240
+ * names, carried first in x5c (OpenID4VP 1.0, section 5.9.3). Checked here so a platform cannot build a
241
+ * request that every wallet would refuse.
242
+ */
243
+ function checkClientId(clientId, signer) {
244
+ if (typeof clientId !== 'string' || clientId.length === 0)
245
+ throw new Error('clientId is required');
246
+ if (!clientId.startsWith('x509_hash:'))
247
+ return;
248
+ const leaf = signer?.x5c?.[0];
249
+ if (!leaf)
250
+ throw new Error('an x509_hash client identifier needs a signer with the certificate in x5c');
251
+ if (clientId !== x509HashClientId(leaf))
252
+ throw new Error('the x509_hash client identifier does not match the signing certificate');
253
+ }
116
254
  /** The URL to put in a QR code or a link, for a request object served at `requestUri`. */
117
255
  export function authorizationRequestUrl(clientId, requestUri, scheme = 'openid4vp://') {
118
256
  const q = new URLSearchParams({ client_id: clientId, request_uri: requestUri });
@@ -2,7 +2,7 @@
2
2
  * Verification of an SD-JWT VC presentation other than the PID, presented in the same wallet response:
3
3
  * the SCA attestation a TS12 e-mandate is bound to, or a representation attestation for a legal person.
4
4
  */
5
- import { SDJwtVcInstance } from '@sd-jwt/sd-jwt-vc';
5
+ import { SdJwtVcInstance } from '@sd-jwt/sd-jwt-vc';
6
6
  import { ES256, digest } from '@sd-jwt/crypto-nodejs';
7
7
  import { decodeJwt, decodeProtectedHeader } from 'jose';
8
8
  import { fromBase64url } from './encoding.js';
@@ -105,7 +105,7 @@ export async function verifyAttestationPresentation(presentation, opts) {
105
105
  throw new PresentationError('untrusted', `${label} issuer not trusted`, e.message);
106
106
  throw e;
107
107
  }
108
- const sdjwt = new SDJwtVcInstance({
108
+ const sdjwt = new SdJwtVcInstance({
109
109
  hasher: digest,
110
110
  hashAlg: 'sha-256',
111
111
  verifier: await ES256.getVerifier(key.jwk),
package/dist/root.js CHANGED
@@ -1,4 +1,4 @@
1
- import { SDJwtVcInstance } from '@sd-jwt/sd-jwt-vc';
1
+ import { SdJwtVcInstance } from '@sd-jwt/sd-jwt-vc';
2
2
  import { ES256, digest } from '@sd-jwt/crypto-nodejs';
3
3
  import { decodeJwt, decodeProtectedHeader } from 'jose';
4
4
  import { canonicalize, fromBase64url, sha256 } from './encoding.js';
@@ -127,7 +127,7 @@ export async function verifyRoot(root, opts) {
127
127
  if (typeof kbNonce !== 'string' || kbNonce.length === 0) {
128
128
  throw new RootError('ROOT_INVALID', 'presentation has no key binding JWT');
129
129
  }
130
- const sdjwt = new SDJwtVcInstance({
130
+ const sdjwt = new SdJwtVcInstance({
131
131
  hasher: digest,
132
132
  hashAlg: 'sha-256',
133
133
  verifier: await ES256.getVerifier(key.jwk),
package/dist/status.js CHANGED
@@ -5,11 +5,11 @@
5
5
  */
6
6
  import { signCompactJwt } from './signer.js';
7
7
  import { decodeProtectedHeader, importJWK, jwtVerify } from 'jose';
8
- import { StatusList, createHeaderAndPayload, verifyStatusListJwtClaims, verifyStatusListJwtHeader } from '@owf/token-status-list';
8
+ import { StatusList, verifyStatusListJwtClaims, zStatusListJwtHeader } from '@owf/token-status-list';
9
9
  import { randomInt } from 'node:crypto';
10
10
  import { inflateSync } from 'node:zlib';
11
11
  import { resolveSigningKeyAsync } from './trust.js';
12
- import { canonicalize, sha256 } from './encoding.js';
12
+ import { base64url, canonicalize, sha256 } from './encoding.js';
13
13
  const MAX_TOKEN_BYTES = 1_000_000;
14
14
  export const defaultStatusFetcher = async (uri, opts) => {
15
15
  if (new URL(uri).protocol !== 'https:')
@@ -214,7 +214,8 @@ export async function checkStatus(ref, opts) {
214
214
  throw new StatusUnavailableError(e?.message ?? String(e));
215
215
  }
216
216
  const header = decodeProtectedHeader(token);
217
- verifyStatusListJwtHeader(header);
217
+ // typ must be statuslist+jwt (or application/statuslist+jwt): a JWT signed for another purpose is not a list.
218
+ zStatusListJwtHeader.parse(header);
218
219
  if (header.alg !== 'ES256')
219
220
  throw new Error('status list token must use ES256');
220
221
  const signingKey = await resolveStatusSigner(header, opts);
@@ -222,7 +223,8 @@ export async function checkStatus(ref, opts) {
222
223
  algorithms: ['ES256'],
223
224
  currentDate: new Date(opts.now * 1000),
224
225
  });
225
- verifyStatusListJwtClaims(payload, { uri, now: new Date(opts.now * 1000), requireExpirationTime: true });
226
+ // sub must equal the uri; sub, iat and exp are required; exp, nbf and iat are checked with 30 s of skew.
227
+ verifyStatusListJwtClaims(payload, { uri, now: new Date(opts.now * 1000), requiredClaims: ['sub', 'iat', 'exp'] });
226
228
  list = decodeStatusList(payload.status_list, maxBytes);
227
229
  if (opts.cache) {
228
230
  const ttl = typeof payload.ttl === 'number' && payload.ttl >= 0 ? payload.ttl : opts.cache.maxAge;
@@ -280,13 +282,15 @@ export class StatusListPublisher {
280
282
  }
281
283
  /** Signs the current list as a status list token. */
282
284
  async token(now = Math.floor(Date.now() / 1000)) {
283
- const { header, payload } = createHeaderAndPayload(this.list, {
285
+ const header = { alg: 'ES256', typ: 'statuslist+jwt', ...(this.opts.x5c ? { x5c: this.opts.x5c } : {}) };
286
+ const payload = {
284
287
  sub: this.opts.uri,
285
288
  iat: now,
286
289
  exp: now + (this.opts.lifetimeSeconds ?? 3600),
287
290
  ttl: this.opts.ttlSeconds ?? DEFAULT_STATUS_TTL_SECONDS,
288
291
  ...(this.opts.iss ? { iss: this.opts.iss } : {}),
289
- }, { alg: 'ES256', typ: 'statuslist+jwt', ...(this.opts.x5c ? { x5c: this.opts.x5c } : {}) });
292
+ status_list: { bits: this.list.getBitsPerStatus(), lst: base64url(this.list.compressStatusListToBytes()) },
293
+ };
290
294
  return signCompactJwt(payload, header, this.opts.signingKey);
291
295
  }
292
296
  }
package/dist/testing.d.ts CHANGED
@@ -120,6 +120,7 @@ export interface TestPidProvider {
120
120
  issuePid(holderJwk: JWK, claims: PidClaims, opts?: {
121
121
  exp?: number;
122
122
  omitIss?: boolean;
123
+ vct?: string;
123
124
  }): Promise<string>;
124
125
  /** Signs a status list token with this provider's key, for any URI (negative tests). */
125
126
  signStatusList(publisher: {
@@ -134,6 +135,7 @@ export declare function createTestPidProvider(iss?: string, opts?: {
134
135
  statusList?: boolean;
135
136
  ca?: TestCertificateAuthority;
136
137
  leaf?: TestLeafOptions;
138
+ vct?: string;
137
139
  }): Promise<TestPidProvider>;
138
140
  /** An issuer of SD-JWT VC attestations other than the PID: a business register, a bank. */
139
141
  export interface TestAttestationIssuer {
@@ -196,6 +198,8 @@ export interface WalletRequestPolicy {
196
198
  approveTransaction?: (transactionData: Record<string, unknown>) => boolean;
197
199
  /** Test hook: changes a key binding JWT payload before signing, to simulate a misbehaving wallet. */
198
200
  tamperKeyBinding?: (queryId: string, payload: Record<string, unknown>) => void;
201
+ /** Content encryption of an encrypted response; default A128GCM. */
202
+ enc?: 'A128GCM' | 'A256GCM';
199
203
  }
200
204
  export interface TestWalletOptions {
201
205
  /**
@@ -203,6 +207,16 @@ export interface TestWalletOptions {
203
207
  * metadata lists the type, which is the default behaviour.
204
208
  */
205
209
  emandateOnPid?: boolean;
210
+ /**
211
+ * Client identifier prefixes the wallet accepts, as a wallet profile restricts them (the IT-Wallet
212
+ * specification allows `openid_federation` and `x509_hash`). Default any.
213
+ */
214
+ clientIdPrefixes?: string[];
215
+ /**
216
+ * Check an `x509_hash` client identifier against the certificate of the signed request object, as
217
+ * OpenID4VP 1.0 requires. Needs the request object, not the bare parameters. Default false.
218
+ */
219
+ checkX509Hash?: boolean;
206
220
  }
207
221
  export interface TestWallet {
208
222
  holderJwk: JWK;
package/dist/testing.js CHANGED
@@ -9,9 +9,9 @@ import * as x509 from '@peculiar/x509';
9
9
  import { AsnConvert, OctetString } from '@peculiar/asn1-schema';
10
10
  import { AlgorithmIdentifier, Certificate, Extension } from '@peculiar/asn1-x509';
11
11
  import { BasicOCSPResponse, CertID, CertStatus, OCSPResponse, OCSPResponseStatus, ResponderID, ResponseBytes, ResponseData, RevokedInfo, SingleResponse, id_kp_OCSPSigning, id_pkix_ocsp_basic, id_pkix_ocsp_nonce, } from '@peculiar/asn1-ocsp';
12
- import { SDJwtVcInstance } from '@sd-jwt/sd-jwt-vc';
12
+ import { SdJwtVcInstance } from '@sd-jwt/sd-jwt-vc';
13
13
  import { ES256, digest, generateSalt } from '@sd-jwt/crypto-nodejs';
14
- import { calculateJwkThumbprint, CompactEncrypt, decodeJwt, importJWK } from 'jose';
14
+ import { calculateJwkThumbprint, CompactEncrypt, decodeJwt, decodeProtectedHeader, importJWK } from 'jose';
15
15
  import { sha256 } from './encoding.js';
16
16
  import { encodeMandateTransactionData, nowSeconds } from './mandate.js';
17
17
  import { StatusListPublisher } from './status.js';
@@ -220,7 +220,7 @@ export async function createTestPidProvider(iss = 'https://pid-provider.test', o
220
220
  const statusList = opts.statusList
221
221
  ? new StatusListPublisher({ uri: statusUri, signingKey, iss, ...(x5c ? { x5c } : {}) })
222
222
  : undefined;
223
- const sdjwt = new SDJwtVcInstance({
223
+ const sdjwt = new SdJwtVcInstance({
224
224
  signer: await ES256.getSigner(privateJwk),
225
225
  signAlg: 'ES256',
226
226
  hasher: digest,
@@ -246,7 +246,7 @@ export async function createTestPidProvider(iss = 'https://pid-provider.test', o
246
246
  ...(o.omitIss ? {} : { iss }),
247
247
  iat,
248
248
  exp: o.exp ?? iat + 365 * 24 * 3600,
249
- vct: PID_VCT,
249
+ vct: o.vct ?? opts.vct ?? PID_VCT,
250
250
  cnf: { jwk: holderJwk },
251
251
  ...(status ? { status } : {}),
252
252
  ...claims,
@@ -283,7 +283,7 @@ export async function createTestAttestationIssuer(iss, vct, opts = {}) {
283
283
  }
284
284
  const statusUri = `${iss}/status/1`;
285
285
  const statusList = opts.statusList ? new StatusListPublisher({ uri: statusUri, signingKey, iss, ...(x5c ? { x5c } : {}) }) : undefined;
286
- const sdjwt = new SDJwtVcInstance({
286
+ const sdjwt = new SdJwtVcInstance({
287
287
  signer: await ES256.getSigner(privateJwk),
288
288
  signAlg: 'ES256',
289
289
  hasher: digest,
@@ -397,7 +397,7 @@ export async function createTestWallet(walletOpts = {}) {
397
397
  let pid;
398
398
  const others = [];
399
399
  async function presentWith(sdjwtCred, privateJwk, frame, kb) {
400
- const instance = new SDJwtVcInstance({
400
+ const instance = new SdJwtVcInstance({
401
401
  hasher: digest,
402
402
  hashAlg: 'sha-256',
403
403
  kbSigner: await ES256.getSigner(privateJwk),
@@ -452,16 +452,29 @@ export async function createTestWallet(walletOpts = {}) {
452
452
  async respond(request, policy = {}) {
453
453
  const params = (typeof request === 'string' ? decodeJwt(request) : request);
454
454
  const state = params.state;
455
+ const clientId = String(params.client_id ?? '');
456
+ const prefix = clientId.includes(':') ? clientId.slice(0, clientId.indexOf(':')) : '';
457
+ if (walletOpts.clientIdPrefixes && !walletOpts.clientIdPrefixes.includes(prefix))
458
+ return { error: 'invalid_client', state };
459
+ if (walletOpts.checkX509Hash && prefix === 'x509_hash') {
460
+ if (typeof request !== 'string')
461
+ return { error: 'invalid_request', state };
462
+ const leaf = decodeProtectedHeader(request).x5c?.[0];
463
+ const hash = leaf ? createHash('sha256').update(Buffer.from(leaf, 'base64')).digest('base64url') : undefined;
464
+ if (clientId !== `x509_hash:${hash}`)
465
+ return { error: 'invalid_client', state };
466
+ }
467
+ const pidVct = pid ? String(decodeJwt(pid.split('~')[0]).vct) : PID_VCT;
455
468
  const queries = params.dcql_query?.credentials;
456
469
  const first = Array.isArray(queries) ? queries[0] : undefined;
457
- if (!first || first.format !== 'dc+sd-jwt' || !first.meta?.vct_values?.includes(PID_VCT)) {
470
+ if (!first || first.format !== 'dc+sd-jwt' || !first.meta?.vct_values?.includes(pidVct)) {
458
471
  return { error: 'invalid_request', state };
459
472
  }
460
473
  if (!pid)
461
474
  return { error: 'access_denied', state };
462
475
  // Match every credential query against what the wallet holds.
463
476
  const held = new Map();
464
- held.set(first.id, { sdjwt: pid, vct: PID_VCT, privateJwk: holder.privateKey, transactionDataTypes: [] });
477
+ held.set(first.id, { sdjwt: pid, vct: pidVct, privateJwk: holder.privateKey, transactionDataTypes: [] });
465
478
  for (const q of queries.slice(1)) {
466
479
  if (q?.format !== 'dc+sd-jwt' || typeof q.id !== 'string' || held.has(q.id))
467
480
  return { error: 'invalid_request', state };
@@ -535,7 +548,7 @@ export async function createTestWallet(walletOpts = {}) {
535
548
  return { error: 'invalid_request', state };
536
549
  const key = await importJWK(encJwk, 'ECDH-ES');
537
550
  const jwe = await new CompactEncrypt(new TextEncoder().encode(JSON.stringify(result)))
538
- .setProtectedHeader({ alg: 'ECDH-ES', enc: 'A128GCM', kid: encJwk.kid })
551
+ .setProtectedHeader({ alg: 'ECDH-ES', enc: policy.enc ?? 'A128GCM', kid: encJwk.kid })
539
552
  .encrypt(key);
540
553
  return { response: jwe };
541
554
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "plenipo",
3
- "version": "0.6.0",
3
+ "version": "0.8.0",
4
4
  "description": "Wallet-anchored mandates for AI agents: EUDI Wallet PID as root, enforced attenuation, expiry and revocation, MCP guard.",
5
5
  "keywords": [
6
6
  "eudi-wallet",
@@ -69,32 +69,32 @@
69
69
  "example:gateway": "tsx examples/bank-gateway.ts"
70
70
  },
71
71
  "dependencies": {
72
- "@owf/token-status-list": "^0.7.0",
73
- "@peculiar/asn1-ocsp": "^3.0.0",
74
- "@peculiar/asn1-schema": "^3.0.0",
75
- "@peculiar/asn1-x509": "^3.0.0",
72
+ "@owf/token-status-list": "^0.9.0",
73
+ "@peculiar/asn1-ocsp": "^3.1.0",
74
+ "@peculiar/asn1-schema": "^3.1.0",
75
+ "@peculiar/asn1-x509": "^3.1.0",
76
76
  "@peculiar/x509": "^3.1.0",
77
77
  "@sd-jwt/crypto-nodejs": "^0.19.0",
78
- "@sd-jwt/sd-jwt-vc": "^0.24.3",
78
+ "@sd-jwt/sd-jwt-vc": "^0.25.0",
79
79
  "canonicalize": "^5.1.0",
80
- "jose": "^6.2.12",
80
+ "jose": "^6.2.18",
81
81
  "reflect-metadata": "^0.2.2",
82
82
  "zod": "^4.6.7"
83
83
  },
84
84
  "devDependencies": {
85
- "@electric-sql/pglite": "^0.5.10",
85
+ "@electric-sql/pglite": "^0.6.0",
86
86
  "@modelcontextprotocol/sdk": "^1.32.1",
87
- "@owf/eudi-lote": "^0.6.0",
87
+ "@owf/eudi-lote": "^0.8.0",
88
88
  "@types/express": "^5.0.3",
89
- "@types/node": "^26.6.5",
89
+ "@types/node": "^26.6.10",
90
90
  "@types/pg": "^8.23.1",
91
91
  "express": "^5.1.0",
92
- "fast-check": "^4.10.2",
93
- "ioredis": "^6.0.0",
92
+ "fast-check": "^4.11.0",
93
+ "ioredis": "^6.1.0",
94
94
  "pg": "^8.23.1",
95
- "redis": "^6.3.0",
95
+ "redis": "^6.4.0",
96
96
  "tsx": "^4.23.15",
97
97
  "typescript": "^7.0.2",
98
- "vitest": "^5.0.5"
98
+ "vitest": "^5.1.2"
99
99
  }
100
100
  }