@vdatacloud/cx-commons 0.1.10 → 0.2.1
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 +11 -2
- package/package.json +3 -2
- package/src/sdk/agreement-sig.ts +278 -0
package/README.md
CHANGED
|
@@ -42,7 +42,7 @@ This repository publishes `@vdatacloud/cx-commons` with modular export entry poi
|
|
|
42
42
|
├── (default) --> exports index.ts (Astro integration plugin `cxCommons()`)
|
|
43
43
|
├── /styles/global.css --> exports canonical LNF design system tokens & Tailwind rules
|
|
44
44
|
├── /components/* --> exports shared Astro UI components (Nav, Footer, StatusBadge, EyebrowLabel, ApiErrorNotice, CantonId, LanguageSwitcher)
|
|
45
|
-
├── /sdk/* --> exports browser SDK helpers (i18n, cx-messages, dialogs, api-error, api-error-notice, canton-id, canton-id-view, status-colors)
|
|
45
|
+
├── /sdk/* --> exports browser SDK helpers (i18n, cx-messages, dialogs, api-error, api-error-notice, canton-id, canton-id-view, agreement-sig, status-colors)
|
|
46
46
|
└── /schema/api-error.json --> the canonical API error JSON Schema
|
|
47
47
|
```
|
|
48
48
|
|
|
@@ -79,7 +79,16 @@ There are three kinds of Canton id. Each has one parser and one short form, mirr
|
|
|
79
79
|
- `parsePartyId`, `classifyCantonId`, `shortCantonId`, `isFingerprint` and `partyControlledBy` are the helpers. `api-error`'s `shortId` is `shortCantonId`.
|
|
80
80
|
- `renderCantonId(value, {label, copy})` / `<CantonId value={…} label="Joey Depositor" />` give one display everywhere: the short form or a label, the full value on hover, and a copy button that copies the full value. Prefer a T1 `label` over a raw party id in UX. The error notice shows every id this way.
|
|
81
81
|
|
|
82
|
-
|
|
82
|
+
### Agreement signing (`sdk/agreement-sig`)
|
|
83
|
+
|
|
84
|
+
How a party signs one version of an agreement, mirroring daml-escrow-commons `agreementsig` byte for byte (daml-escrow PLAN.md Phase 81). A page recomputes the hash of the content it shows, never trusting a server's copy, before a wallet signs.
|
|
85
|
+
|
|
86
|
+
- `agreementHash(version)` / `agreementCanonical` / `validateAgreementVersion`: `tripart.agreement-version/1`. Terms are a JSON object with safe-integer numbers only; money is a decimal string.
|
|
87
|
+
- `agreementMessage(version, hash, signer)`: the exact text a signer signs, naming their own ledger identity.
|
|
88
|
+
- `verifySignature(alg, publicKey, message, signature)`: `ed25519` (wallets) or `ecdsa-p256-sha256` (KMS keys such as the custodian's; strict DER, low s), through WebCrypto.
|
|
89
|
+
- `draftHash` / `draftMessage`: the frozen `tripart.draft-version/1` (Phase 77 drafts).
|
|
90
|
+
|
|
91
|
+
`test/fixtures/api-error`, `test/fixtures/canton-id` and `test/fixtures/agreement-sig` hold copies of the Go goldens, from the commit in `SOURCE`. After changing the Go package, run `npm run sync:api-error-fixtures`; CI fails if the copies drift.
|
|
83
92
|
|
|
84
93
|
---
|
|
85
94
|
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@vdatacloud/cx-commons",
|
|
3
|
-
"version": "0.1
|
|
3
|
+
"version": "0.2.1",
|
|
4
4
|
"description": "Product CX Commons - Shared design system, UI components, and Astro integration for Data Cloud web applications",
|
|
5
5
|
"repository": {
|
|
6
6
|
"type": "git",
|
|
@@ -45,7 +45,8 @@
|
|
|
45
45
|
"vitest": "^5.0.3"
|
|
46
46
|
},
|
|
47
47
|
"overrides": {
|
|
48
|
-
"nanoid": "3.3.18"
|
|
48
|
+
"nanoid": "3.3.18",
|
|
49
|
+
"postcss-selector-parser": "7.1.6"
|
|
49
50
|
},
|
|
50
51
|
"keywords": [
|
|
51
52
|
"astro",
|
|
@@ -0,0 +1,278 @@
|
|
|
1
|
+
// Signing one version of an agreement -- the TypeScript mirror of
|
|
2
|
+
// daml-escrow-commons `agreementsig` (Go), held to it byte for byte by
|
|
3
|
+
// test/fixtures/agreement-sig (daml-escrow PLAN.md Phase 81).
|
|
4
|
+
//
|
|
5
|
+
// A browser recomputes the version hash from the content it shows -- never
|
|
6
|
+
// trusting a server's copy -- before asking a wallet to sign the message,
|
|
7
|
+
// and can check any recorded signature offline.
|
|
8
|
+
//
|
|
9
|
+
// tripart.draft-version/1 one off-chain escrow draft version (Phase 77)
|
|
10
|
+
// tripart.agreement-version/1 one version of an agreement or amendment
|
|
11
|
+
//
|
|
12
|
+
// Both schemas are frozen: a change is a new schema, never an edit.
|
|
13
|
+
// Signatures name their algorithm: 'ed25519' (wallets) or
|
|
14
|
+
// 'ecdsa-p256-sha256' (KMS-held keys such as the custodian's; strict DER,
|
|
15
|
+
// low s).
|
|
16
|
+
|
|
17
|
+
export const DRAFT_SCHEMA = 'tripart.draft-version/1';
|
|
18
|
+
export const AGREEMENT_SCHEMA = 'tripart.agreement-version/1';
|
|
19
|
+
|
|
20
|
+
export type SignatureAlgorithm = 'ed25519' | 'ecdsa-p256-sha256';
|
|
21
|
+
|
|
22
|
+
/** Why something was refused: matches the Go errors (ErrInvalid, ErrBadSignature, ...). */
|
|
23
|
+
export type AgreementSigReason = 'invalid' | 'bad' | 'noncanonical' | 'unsupported' | 'key';
|
|
24
|
+
|
|
25
|
+
export class AgreementSigError extends Error {
|
|
26
|
+
constructor(readonly reason: AgreementSigReason, message: string) {
|
|
27
|
+
super(message);
|
|
28
|
+
this.name = 'AgreementSigError';
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
const invalid = (msg: string) => new AgreementSigError('invalid', `agreementsig: invalid agreement version: ${msg}`);
|
|
33
|
+
|
|
34
|
+
// --- canonical JSON ---
|
|
35
|
+
|
|
36
|
+
type NumberMode = 'any' | 'integers';
|
|
37
|
+
|
|
38
|
+
// Keys sorted by UTF-16 code units (JavaScript's default sort, as Go sorts);
|
|
39
|
+
// strings and numbers as JSON.stringify writes them; no whitespace.
|
|
40
|
+
function canon(v: unknown, mode: NumberMode): string {
|
|
41
|
+
if (v === null || v === undefined) return 'null';
|
|
42
|
+
if (typeof v === 'number') {
|
|
43
|
+
if (!Number.isFinite(v)) throw invalid('number out of range');
|
|
44
|
+
if (mode === 'integers' && !Number.isSafeInteger(v)) throw invalid(`${v} is not a safe integer (write decimals as strings)`);
|
|
45
|
+
return JSON.stringify(v);
|
|
46
|
+
}
|
|
47
|
+
if (typeof v === 'string' || typeof v === 'boolean') return JSON.stringify(v);
|
|
48
|
+
if (Array.isArray(v)) return '[' + v.map((e) => canon(e, mode)).join(',') + ']';
|
|
49
|
+
if (typeof v === 'object') {
|
|
50
|
+
const o = v as Record<string, unknown>;
|
|
51
|
+
return '{' + Object.keys(o).sort().map((k) => JSON.stringify(k) + ':' + canon(o[k], mode)).join(',') + '}';
|
|
52
|
+
}
|
|
53
|
+
throw invalid(`unsupported value ${typeof v}`);
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
async function sha256Hex(text: string): Promise<string> {
|
|
57
|
+
const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(text));
|
|
58
|
+
return [...new Uint8Array(digest)].map((b) => b.toString(16).padStart(2, '0')).join('');
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
// --- tripart.draft-version/1 ---
|
|
62
|
+
|
|
63
|
+
/** The draft fields a version hash covers, as the API serves them. */
|
|
64
|
+
export interface DraftVersionContent {
|
|
65
|
+
rootId: string;
|
|
66
|
+
version: number;
|
|
67
|
+
contractType: string;
|
|
68
|
+
amount: number;
|
|
69
|
+
currency: string;
|
|
70
|
+
depositorId?: string;
|
|
71
|
+
beneficiaryEmail?: string;
|
|
72
|
+
mediatorId?: string;
|
|
73
|
+
terms?: unknown;
|
|
74
|
+
metadata?: unknown;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/** The canonical document for a draft version. */
|
|
78
|
+
export function draftCanonical(d: DraftVersionContent): string {
|
|
79
|
+
return canon({
|
|
80
|
+
schema: DRAFT_SCHEMA,
|
|
81
|
+
rootId: d.rootId,
|
|
82
|
+
version: d.version,
|
|
83
|
+
contractType: d.contractType ?? '',
|
|
84
|
+
amount: d.amount,
|
|
85
|
+
currency: d.currency ?? '',
|
|
86
|
+
depositorId: d.depositorId ?? '',
|
|
87
|
+
beneficiaryEmail: d.beneficiaryEmail ?? '',
|
|
88
|
+
mediatorId: d.mediatorId ?? '',
|
|
89
|
+
terms: d.terms ?? null,
|
|
90
|
+
metadata: d.metadata ?? null,
|
|
91
|
+
}, 'any');
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/** Lowercase hex SHA-256 of the draft's canonical document. */
|
|
95
|
+
export function draftHash(d: DraftVersionContent): Promise<string> {
|
|
96
|
+
return sha256Hex(draftCanonical(d));
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/** The exact text a wallet signs to approve a draft version. */
|
|
100
|
+
export function draftMessage(rootId: string, version: number, versionHash: string): string {
|
|
101
|
+
return `Tripart\nI approve version ${version} of escrow draft ${rootId}.\nVersion hash: sha256:${versionHash}`;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
// --- tripart.agreement-version/1 ---
|
|
105
|
+
|
|
106
|
+
export type AgreementKind = 'agreement' | 'amendment';
|
|
107
|
+
|
|
108
|
+
/** One version of an agreement or amendment, in its JSON wire form. */
|
|
109
|
+
export interface AgreementVersion {
|
|
110
|
+
agreementId: string;
|
|
111
|
+
/** Counts from 1; each later version names its parent's hash. */
|
|
112
|
+
version: number;
|
|
113
|
+
parentHash?: string | null;
|
|
114
|
+
kind: AgreementKind;
|
|
115
|
+
/** Set for an amendment: the original's id and every ratified hash, oldest first. */
|
|
116
|
+
amends?: { agreementId: string; ratifiedHashes: string[] } | null;
|
|
117
|
+
/** The rendered document, by content only -- never where it is stored. */
|
|
118
|
+
document: { sha256: string; mediaType: string; sourceSha256: string; sourceMediaType: string };
|
|
119
|
+
termsSchema: string;
|
|
120
|
+
/** A JSON object; numbers must be safe integers, money a decimal string. */
|
|
121
|
+
terms: Record<string, unknown>;
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
const HEX_SHA256 = /^[0-9a-f]{64}$/;
|
|
125
|
+
const MAX_ID_BYTES = 256;
|
|
126
|
+
// Control characters (as Go's unicode.IsControl) and the line/paragraph
|
|
127
|
+
// separators: identifiers appear verbatim in signed messages.
|
|
128
|
+
const CONTROL = new RegExp("[\\u0000-\\u001f\\u007f-\\u009f\\u2028\\u2029]");
|
|
129
|
+
|
|
130
|
+
function checkId(what: string, s: unknown): void {
|
|
131
|
+
if (typeof s !== 'string' || s === '') throw invalid(`${what} is empty`);
|
|
132
|
+
if (new TextEncoder().encode(s).length > MAX_ID_BYTES) throw invalid(`${what} is longer than ${MAX_ID_BYTES} bytes`);
|
|
133
|
+
if (CONTROL.test(s)) throw invalid(`${what} contains a control character`);
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
/** Throws AgreementSigError('invalid') unless v is well formed. */
|
|
137
|
+
export function validateAgreementVersion(v: AgreementVersion): void {
|
|
138
|
+
checkId('agreement id', v.agreementId);
|
|
139
|
+
if (!Number.isSafeInteger(v.version) || v.version < 1) throw invalid('version must be 1 or more');
|
|
140
|
+
const parent = v.parentHash ?? '';
|
|
141
|
+
if (v.version === 1 && parent !== '') throw invalid('version 1 has no parent');
|
|
142
|
+
if (v.version > 1 && !HEX_SHA256.test(parent)) throw invalid(`version ${v.version} needs its parent's hash (64 lowercase hex)`);
|
|
143
|
+
if (v.kind === 'agreement') {
|
|
144
|
+
if (v.amends) throw invalid('an agreement amends nothing');
|
|
145
|
+
} else if (v.kind === 'amendment') {
|
|
146
|
+
if (!v.amends) throw invalid('an amendment names what it amends');
|
|
147
|
+
checkId('amended agreement id', v.amends.agreementId);
|
|
148
|
+
if (v.amends.agreementId === v.agreementId) throw invalid("an amendment has its own id, not the agreement's");
|
|
149
|
+
if (!v.amends.ratifiedHashes?.length) throw invalid("an amendment names at least the ratified agreement's hash");
|
|
150
|
+
for (const h of v.amends.ratifiedHashes) if (!HEX_SHA256.test(h)) throw invalid(`ratified hash ${JSON.stringify(h)} is not 64 lowercase hex`);
|
|
151
|
+
} else {
|
|
152
|
+
throw invalid('kind must be "agreement" or "amendment"');
|
|
153
|
+
}
|
|
154
|
+
const d = v.document;
|
|
155
|
+
if (!d || !HEX_SHA256.test(d.sha256) || !HEX_SHA256.test(d.sourceSha256)) throw invalid('document hashes must be 64 lowercase hex');
|
|
156
|
+
checkId('document media type', d.mediaType);
|
|
157
|
+
checkId('source media type', d.sourceMediaType);
|
|
158
|
+
checkId('terms schema', v.termsSchema);
|
|
159
|
+
if (v.terms === null || typeof v.terms !== 'object' || Array.isArray(v.terms)) throw invalid('terms must be a JSON object');
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
/** The canonical document for an agreement version (validates first). */
|
|
163
|
+
export function agreementCanonical(v: AgreementVersion): string {
|
|
164
|
+
validateAgreementVersion(v);
|
|
165
|
+
return canon({
|
|
166
|
+
schema: AGREEMENT_SCHEMA,
|
|
167
|
+
agreementId: v.agreementId,
|
|
168
|
+
version: v.version,
|
|
169
|
+
parentHash: v.parentHash || null,
|
|
170
|
+
kind: v.kind,
|
|
171
|
+
amends: v.amends ? { agreementId: v.amends.agreementId, ratifiedHashes: v.amends.ratifiedHashes } : null,
|
|
172
|
+
document: {
|
|
173
|
+
sha256: v.document.sha256,
|
|
174
|
+
mediaType: v.document.mediaType,
|
|
175
|
+
sourceSha256: v.document.sourceSha256,
|
|
176
|
+
sourceMediaType: v.document.sourceMediaType,
|
|
177
|
+
},
|
|
178
|
+
termsSchema: v.termsSchema,
|
|
179
|
+
terms: v.terms,
|
|
180
|
+
}, 'integers');
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
/** Lowercase hex SHA-256 of the version's canonical document. */
|
|
184
|
+
export function agreementHash(v: AgreementVersion): Promise<string> {
|
|
185
|
+
return sha256Hex(agreementCanonical(v));
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
/**
|
|
189
|
+
* The exact text `signer` (their own ledger identity) signs to approve
|
|
190
|
+
* version v with hash versionHash. Fixed English; the page explains it.
|
|
191
|
+
*/
|
|
192
|
+
export function agreementMessage(v: AgreementVersion, versionHash: string, signer: string): string {
|
|
193
|
+
checkId('signer', signer);
|
|
194
|
+
if (!HEX_SHA256.test(versionHash)) throw invalid('version hash must be 64 lowercase hex');
|
|
195
|
+
validateAgreementVersion(v);
|
|
196
|
+
const what = v.kind === 'amendment'
|
|
197
|
+
? `amendment ${v.agreementId} to agreement ${v.amends!.agreementId}`
|
|
198
|
+
: `agreement ${v.agreementId}`;
|
|
199
|
+
return `Tripart\nI, ${signer}, approve version ${v.version} of ${what}.\nVersion hash: sha256:${versionHash}`;
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
// --- signatures ---
|
|
203
|
+
|
|
204
|
+
// P-256 group order n, and n/2: a canonical signature has s <= n/2.
|
|
205
|
+
const P256_N = 0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551n;
|
|
206
|
+
const P256_HALF_N = P256_N >> 1n;
|
|
207
|
+
|
|
208
|
+
function bytesToBigInt(b: Uint8Array): bigint {
|
|
209
|
+
let n = 0n;
|
|
210
|
+
for (const x of b) n = (n << 8n) | BigInt(x);
|
|
211
|
+
return n;
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
// Reads one strictly-DER INTEGER at off: short-form length, minimal,
|
|
215
|
+
// positive. Returns its value bytes (without the sign pad) and the next
|
|
216
|
+
// offset.
|
|
217
|
+
function derInteger(der: Uint8Array, off: number): [Uint8Array, number] {
|
|
218
|
+
if (der[off] !== 0x02) throw new AgreementSigError('bad', 'not a DER (r, s) sequence');
|
|
219
|
+
const len = der[off + 1];
|
|
220
|
+
if (len === undefined || len === 0 || len > 0x7f || off + 2 + len > der.length) throw new AgreementSigError('bad', 'not a DER (r, s) sequence');
|
|
221
|
+
let v = der.subarray(off + 2, off + 2 + len);
|
|
222
|
+
if (v[0] & 0x80) throw new AgreementSigError('bad', 'negative ECDSA component');
|
|
223
|
+
if (v[0] === 0 && (len === 1 || !(v[1] & 0x80))) throw new AgreementSigError('bad', 'non-minimal DER integer');
|
|
224
|
+
if (v[0] === 0) v = v.subarray(1);
|
|
225
|
+
return [v, off + 2 + len];
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
// Strict DER (r, s) with low s -> the 64-byte r||s WebCrypto verifies.
|
|
229
|
+
function p256RawFromDER(der: Uint8Array): Uint8Array {
|
|
230
|
+
if (der.length < 8 || der[0] !== 0x30) throw new AgreementSigError('bad', 'not a DER (r, s) sequence');
|
|
231
|
+
// A P-256 signature is under 128 bytes: the long length form is loose DER.
|
|
232
|
+
if (der[1] & 0x80 || der[1] !== der.length - 2) throw new AgreementSigError('bad', 'not a DER (r, s) sequence');
|
|
233
|
+
const [r, next] = derInteger(der, 2);
|
|
234
|
+
const [s, end] = derInteger(der, next);
|
|
235
|
+
if (end !== der.length) throw new AgreementSigError('bad', 'not a DER (r, s) sequence');
|
|
236
|
+
if (r.length > 32 || s.length > 32) throw new AgreementSigError('bad', 'ECDSA component too long for P-256');
|
|
237
|
+
const sv = bytesToBigInt(s);
|
|
238
|
+
if (bytesToBigInt(r) === 0n || sv === 0n) throw new AgreementSigError('bad', 'zero ECDSA component');
|
|
239
|
+
if (sv > P256_HALF_N) throw new AgreementSigError('noncanonical', 'ECDSA signature is not in canonical low-s DER form');
|
|
240
|
+
const raw = new Uint8Array(64);
|
|
241
|
+
raw.set(r, 32 - r.length);
|
|
242
|
+
raw.set(s, 64 - s.length);
|
|
243
|
+
return raw;
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
async function importKey(format: 'raw' | 'spki', key: Uint8Array, algorithm: AlgorithmIdentifier | EcKeyImportParams): Promise<CryptoKey> {
|
|
247
|
+
try {
|
|
248
|
+
return await crypto.subtle.importKey(format, key as BufferSource, algorithm, false, ['verify']);
|
|
249
|
+
} catch (err) {
|
|
250
|
+
throw new AgreementSigError('key', `agreementsig: unusable public key: ${(err as Error).message}`);
|
|
251
|
+
}
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
/**
|
|
255
|
+
* Checks that signature is publicKey's signature over message under alg.
|
|
256
|
+
* Resolves on success; rejects with an AgreementSigError ('bad',
|
|
257
|
+
* 'noncanonical', 'unsupported' or 'key') otherwise.
|
|
258
|
+
*
|
|
259
|
+
* Ed25519 keys: raw 32 bytes or DER SubjectPublicKeyInfo; signature 64
|
|
260
|
+
* bytes. P-256 keys: DER SubjectPublicKeyInfo; signature strict DER, low s,
|
|
261
|
+
* over SHA-256 of the message.
|
|
262
|
+
*/
|
|
263
|
+
export async function verifySignature(alg: SignatureAlgorithm, publicKey: Uint8Array, message: string, signature: Uint8Array): Promise<void> {
|
|
264
|
+
const data = new TextEncoder().encode(message);
|
|
265
|
+
let ok: boolean;
|
|
266
|
+
if (alg === 'ed25519') {
|
|
267
|
+
const key = await importKey(publicKey.length === 32 ? 'raw' : 'spki', publicKey, { name: 'Ed25519' });
|
|
268
|
+
if (signature.length !== 64) throw new AgreementSigError('bad', 'agreementsig: the signature does not match this message and key');
|
|
269
|
+
ok = await crypto.subtle.verify({ name: 'Ed25519' }, key, signature as BufferSource, data);
|
|
270
|
+
} else if (alg === 'ecdsa-p256-sha256') {
|
|
271
|
+
const key = await importKey('spki', publicKey, { name: 'ECDSA', namedCurve: 'P-256' });
|
|
272
|
+
const raw = p256RawFromDER(signature);
|
|
273
|
+
ok = await crypto.subtle.verify({ name: 'ECDSA', hash: 'SHA-256' }, key, raw as BufferSource, data);
|
|
274
|
+
} else {
|
|
275
|
+
throw new AgreementSigError('unsupported', `agreementsig: unsupported signature algorithm ${JSON.stringify(alg)}`);
|
|
276
|
+
}
|
|
277
|
+
if (!ok) throw new AgreementSigError('bad', 'agreementsig: the signature does not match this message and key');
|
|
278
|
+
}
|