@vdatacloud/cx-commons 0.1.9 → 0.2.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 +17 -3
- package/package.json +1 -1
- package/src/components/LanguageSwitcher.astro +44 -0
- package/src/sdk/agreement-sig.ts +278 -0
- package/src/sdk/cx-messages.ts +14 -0
- package/src/sdk/dialogs.ts +178 -0
package/README.md
CHANGED
|
@@ -41,8 +41,8 @@ This repository publishes `@vdatacloud/cx-commons` with modular export entry poi
|
|
|
41
41
|
@vdatacloud/cx-commons
|
|
42
42
|
├── (default) --> exports index.ts (Astro integration plugin `cxCommons()`)
|
|
43
43
|
├── /styles/global.css --> exports canonical LNF design system tokens & Tailwind rules
|
|
44
|
-
├── /components/* --> exports shared Astro UI components (Nav, Footer, StatusBadge, EyebrowLabel, ApiErrorNotice, CantonId)
|
|
45
|
-
├── /sdk/* --> exports browser SDK helpers (i18n, cx-messages, api-error, api-error-notice, canton-id, canton-id-view, status-colors)
|
|
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, 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
|
|
|
@@ -104,6 +113,11 @@ Korean are catalog work, not a rewrite). Vocabulary follows daml-escrow's `docs/
|
|
|
104
113
|
`en`). `StatusBadge` shows `cx.status.<STATUS>` (e.g. `FUNDED` -> "Funds committed"); `ApiErrorNotice` /
|
|
105
114
|
`renderApiErrorNotice` translate `errors.<CODE>.message|hint` and `stages.<stage>` when the app registers them,
|
|
106
115
|
keeping the server's original message in the details.
|
|
116
|
+
- **Language switcher:** `components/LanguageSwitcher` -- sets the `locale` cookie and reloads; pass the app's
|
|
117
|
+
`locales`.
|
|
118
|
+
- **Dialogs:** `sdk/dialogs` -- `confirmDialog`, `promptDialog`, `formDialog`, `acknowledge`, `notifyError`,
|
|
119
|
+
`showErrorIn`, `notifyInfo` replace `window.confirm`/`prompt`/`alert` in the page's language (see
|
|
120
|
+
`docs/COMPONENTS.md`).
|
|
107
121
|
- **CJK:** elements that uppercase/letter-space carry `.cx-caps`, switched off under `:lang(ja|zh|ko)`.
|
|
108
122
|
|
|
109
123
|
## 5. Quick Start & Integration Guide
|
package/package.json
CHANGED
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
---
|
|
2
|
+
// Language choice: remembered in the locale cookie (sdk/i18n chooseLocale)
|
|
3
|
+
// and applied by reloading, so server-rendered text follows. No URL prefix.
|
|
4
|
+
// Works for signed-out visitors too. Each language is named in itself
|
|
5
|
+
// (cx.language.<code>), so a reader can always find their own.
|
|
6
|
+
import { getTranslator } from '../sdk/i18n';
|
|
7
|
+
import { CX_LOCALES } from '../sdk/cx-messages';
|
|
8
|
+
|
|
9
|
+
interface Props {
|
|
10
|
+
/** The page's locale (default: Astro.locals.locale, else 'en'). */
|
|
11
|
+
locale?: string;
|
|
12
|
+
/** The locales to offer (default: every locale cx-commons ships strings for). */
|
|
13
|
+
locales?: readonly string[];
|
|
14
|
+
/** Extra classes for the wrapper. */
|
|
15
|
+
class?: string;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
const locale = Astro.props.locale ?? (Astro.locals as { locale?: string }).locale ?? Astro.currentLocale ?? 'en';
|
|
19
|
+
const locales = Astro.props.locales ?? CX_LOCALES;
|
|
20
|
+
const { t } = getTranslator(locale);
|
|
21
|
+
const lang = locale.split('-')[0];
|
|
22
|
+
---
|
|
23
|
+
|
|
24
|
+
<label class:list={['relative inline-flex items-center normal-case tracking-normal', Astro.props.class]}>
|
|
25
|
+
<span class="sr-only">{t('cx.language.choose')}</span>
|
|
26
|
+
<select
|
|
27
|
+
data-cx-language-switcher
|
|
28
|
+
class="appearance-none cursor-pointer rounded-xl border border-slate-200 bg-transparent py-1.5 pl-2.5 pr-6 text-[11px] font-bold text-slate-600 hover:border-brand-400 dark:border-slate-700 dark:text-slate-300"
|
|
29
|
+
title={t('cx.language.label')}
|
|
30
|
+
>
|
|
31
|
+
{locales.map((l) => (
|
|
32
|
+
<option value={l} selected={l === lang} lang={l}>{getTranslator(l).maybe(`cx.language.${l}`) ?? l}</option>
|
|
33
|
+
))}
|
|
34
|
+
</select>
|
|
35
|
+
<svg class="pointer-events-none absolute right-1.5 h-3 w-3 text-slate-400" viewBox="0 0 20 20" fill="currentColor" aria-hidden="true"><path fill-rule="evenodd" d="M5.293 7.293a1 1 0 011.414 0L10 10.586l3.293-3.293a1 1 0 111.414 1.414l-4 4a1 1 0 01-1.414 0l-4-4a1 1 0 010-1.414z" clip-rule="evenodd" /></svg>
|
|
36
|
+
</label>
|
|
37
|
+
|
|
38
|
+
<script>
|
|
39
|
+
import { chooseLocale } from '../sdk/i18n';
|
|
40
|
+
|
|
41
|
+
document.querySelectorAll<HTMLSelectElement>('select[data-cx-language-switcher]').forEach((s) => {
|
|
42
|
+
s.addEventListener('change', () => chooseLocale(s.value));
|
|
43
|
+
});
|
|
44
|
+
</script>
|
|
@@ -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
|
+
}
|
package/src/sdk/cx-messages.ts
CHANGED
|
@@ -59,8 +59,15 @@ export const cxMessages = {
|
|
|
59
59
|
FIAT_PENDING: 'Fiat payment pending',
|
|
60
60
|
LAPSED: 'Lapsed',
|
|
61
61
|
},
|
|
62
|
+
dialog: {
|
|
63
|
+
confirm: 'Confirm',
|
|
64
|
+
cancel: 'Cancel',
|
|
65
|
+
ok: 'OK',
|
|
66
|
+
close: 'Close',
|
|
67
|
+
},
|
|
62
68
|
language: {
|
|
63
69
|
label: 'Language',
|
|
70
|
+
choose: 'Choose language',
|
|
64
71
|
en: 'English',
|
|
65
72
|
fr: 'Français',
|
|
66
73
|
},
|
|
@@ -118,8 +125,15 @@ export const cxMessages = {
|
|
|
118
125
|
FIAT_PENDING: 'Paiement fiat en attente',
|
|
119
126
|
LAPSED: 'Expiré',
|
|
120
127
|
},
|
|
128
|
+
dialog: {
|
|
129
|
+
confirm: 'Confirmer',
|
|
130
|
+
cancel: 'Annuler',
|
|
131
|
+
ok: 'OK',
|
|
132
|
+
close: 'Fermer',
|
|
133
|
+
},
|
|
121
134
|
language: {
|
|
122
135
|
label: 'Langue',
|
|
136
|
+
choose: 'Choisir la langue',
|
|
123
137
|
en: 'English',
|
|
124
138
|
fr: 'Français',
|
|
125
139
|
},
|
|
@@ -0,0 +1,178 @@
|
|
|
1
|
+
// In-page replacements for window.confirm / prompt / alert (promoted from
|
|
2
|
+
// daml-escrow's frontend, PLAN.md Phase 71). The browser's own dialogs block the page, can't be
|
|
3
|
+
// styled, ignore the page's language for their buttons, and lose an error's
|
|
4
|
+
// code and request id. These render a <dialog> (or, for errors, the
|
|
5
|
+
// cx-commons error notice) in the page's language.
|
|
6
|
+
//
|
|
7
|
+
// Built with DOM APIs and textContent only -- messages often carry values
|
|
8
|
+
// from the server or other parties and must never become markup.
|
|
9
|
+
|
|
10
|
+
// Button labels are cx.dialog.* (sdk/cx-messages); an app overrides them by
|
|
11
|
+
// registering the same keys. Styling uses the design system's tokens
|
|
12
|
+
// (brand-*, status-*), so it follows white-labeling.
|
|
13
|
+
|
|
14
|
+
import { mountApiErrorNotice } from './api-error-notice';
|
|
15
|
+
import { apiErrorFromUnknown, isApiError, type ApiError } from './api-error';
|
|
16
|
+
import { getTranslator } from './i18n';
|
|
17
|
+
import './cx-messages';
|
|
18
|
+
|
|
19
|
+
const BUTTON = 'rounded-lg px-4 py-2 text-sm font-bold cursor-pointer';
|
|
20
|
+
const SECONDARY = `${BUTTON} border border-slate-200 text-slate-700 hover:bg-slate-100 dark:border-slate-700 dark:text-slate-200 dark:hover:bg-slate-800`;
|
|
21
|
+
const PRIMARY = `${BUTTON} bg-brand-600 text-white hover:bg-brand-700 border-none`;
|
|
22
|
+
const DANGER = `${BUTTON} bg-status-disputed text-white hover:opacity-90 border-none`;
|
|
23
|
+
const INPUT = 'w-full rounded-xl border border-slate-200 bg-slate-50 px-3 py-2 text-sm text-slate-900 dark:border-slate-700 dark:bg-slate-800 dark:text-white';
|
|
24
|
+
|
|
25
|
+
function el<K extends keyof HTMLElementTagNameMap>(tag: K, className = '', text?: string): HTMLElementTagNameMap[K] {
|
|
26
|
+
const n = document.createElement(tag);
|
|
27
|
+
if (className) n.className = className;
|
|
28
|
+
if (text !== undefined) n.textContent = text;
|
|
29
|
+
return n;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export interface Field {
|
|
33
|
+
name: string;
|
|
34
|
+
label: string;
|
|
35
|
+
defaultValue?: string;
|
|
36
|
+
placeholder?: string;
|
|
37
|
+
required?: boolean;
|
|
38
|
+
type?: 'text' | 'number';
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
interface DialogSpec {
|
|
42
|
+
title?: string;
|
|
43
|
+
message: string;
|
|
44
|
+
fields?: Field[];
|
|
45
|
+
confirmLabel?: string;
|
|
46
|
+
cancelLabel?: string;
|
|
47
|
+
danger?: boolean;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
// open renders a modal and resolves with the field values on confirm, or
|
|
51
|
+
// null on cancel / Escape / close. The safe choice (Cancel) has focus unless
|
|
52
|
+
// there are fields to fill.
|
|
53
|
+
function open(spec: DialogSpec): Promise<Record<string, string> | null> {
|
|
54
|
+
const { t } = getTranslator();
|
|
55
|
+
return new Promise((resolve) => {
|
|
56
|
+
const dialog = el('dialog', 'm-auto w-full max-w-md rounded-2xl border border-slate-200 bg-white p-6 shadow-xl backdrop:bg-slate-900/50 dark:border-slate-700 dark:bg-slate-900');
|
|
57
|
+
dialog.dataset.appDialog = '';
|
|
58
|
+
const form = el('form', 'space-y-4');
|
|
59
|
+
form.method = 'dialog';
|
|
60
|
+
if (spec.title) form.append(el('h2', 'text-lg font-bold text-slate-900 dark:text-white', spec.title));
|
|
61
|
+
form.append(el('p', 'text-sm text-slate-700 dark:text-slate-200 whitespace-pre-line', spec.message));
|
|
62
|
+
const inputs: HTMLInputElement[] = [];
|
|
63
|
+
for (const f of spec.fields ?? []) {
|
|
64
|
+
const label = el('label', 'block space-y-1');
|
|
65
|
+
label.append(el('span', 'text-xs font-semibold text-slate-500 dark:text-slate-400', f.label));
|
|
66
|
+
const input = el('input', INPUT);
|
|
67
|
+
input.name = f.name;
|
|
68
|
+
input.type = f.type ?? 'text';
|
|
69
|
+
if (f.type === 'number') input.step = 'any';
|
|
70
|
+
input.value = f.defaultValue ?? '';
|
|
71
|
+
if (f.placeholder) input.placeholder = f.placeholder;
|
|
72
|
+
input.required = !!f.required;
|
|
73
|
+
label.append(input);
|
|
74
|
+
form.append(label);
|
|
75
|
+
inputs.push(input);
|
|
76
|
+
}
|
|
77
|
+
const actions = el('div', 'flex justify-end gap-2 pt-2');
|
|
78
|
+
const cancel = el('button', SECONDARY, spec.cancelLabel || t('cx.dialog.cancel'));
|
|
79
|
+
cancel.type = 'button';
|
|
80
|
+
// An empty cancelLabel means a single-button (acknowledge) dialog.
|
|
81
|
+
if (spec.cancelLabel === '') cancel.hidden = true;
|
|
82
|
+
const ok = el('button', spec.danger ? DANGER : PRIMARY, spec.confirmLabel ?? t('cx.dialog.confirm'));
|
|
83
|
+
ok.type = 'submit';
|
|
84
|
+
actions.append(cancel, ok);
|
|
85
|
+
form.append(actions);
|
|
86
|
+
dialog.append(form);
|
|
87
|
+
|
|
88
|
+
let settled = false;
|
|
89
|
+
const finish = (value: Record<string, string> | null) => {
|
|
90
|
+
if (settled) return;
|
|
91
|
+
settled = true;
|
|
92
|
+
dialog.close();
|
|
93
|
+
dialog.remove();
|
|
94
|
+
resolve(value);
|
|
95
|
+
};
|
|
96
|
+
form.addEventListener('submit', (e) => {
|
|
97
|
+
e.preventDefault();
|
|
98
|
+
if (!form.reportValidity()) return;
|
|
99
|
+
finish(Object.fromEntries(inputs.map((i) => [i.name, i.value.trim()])));
|
|
100
|
+
});
|
|
101
|
+
cancel.addEventListener('click', () => finish(null));
|
|
102
|
+
dialog.addEventListener('close', () => finish(null));
|
|
103
|
+
document.body.append(dialog);
|
|
104
|
+
dialog.showModal();
|
|
105
|
+
(inputs[0] ?? (cancel.hidden ? ok : cancel)).focus();
|
|
106
|
+
});
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/** Asks a yes/no question; resolves true only on an explicit confirm. */
|
|
110
|
+
export async function confirmDialog(message: string, opts: Omit<DialogSpec, 'message' | 'fields'> = {}): Promise<boolean> {
|
|
111
|
+
return (await open({ ...opts, message })) !== null;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/** Shows a message that needs reading before the page moves on (e.g. before a reload). */
|
|
115
|
+
export async function acknowledge(message: string, opts: { title?: string } = {}): Promise<void> {
|
|
116
|
+
const { t } = getTranslator();
|
|
117
|
+
await open({ ...opts, message, confirmLabel: t('cx.dialog.ok'), cancelLabel: '' });
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/** Asks for one value; resolves the trimmed value, or null when cancelled. */
|
|
121
|
+
export async function promptDialog(message: string, field: Omit<Field, 'name'> & { name?: string }, opts: Omit<DialogSpec, 'message' | 'fields'> = {}): Promise<string | null> {
|
|
122
|
+
const name = field.name ?? 'value';
|
|
123
|
+
const values = await open({ ...opts, message, fields: [{ ...field, name }] });
|
|
124
|
+
return values ? values[name] : null;
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
/** Asks for several values; resolves them by field name, or null when cancelled. */
|
|
128
|
+
export function formDialog(message: string, fields: Field[], opts: Omit<DialogSpec, 'message' | 'fields'> = {}): Promise<Record<string, string> | null> {
|
|
129
|
+
return open({ ...opts, message, fields });
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
// Notices stack in one fixed region, top right, newest first.
|
|
133
|
+
function region(): HTMLElement {
|
|
134
|
+
let r = document.getElementById('app-notices');
|
|
135
|
+
if (!r) {
|
|
136
|
+
r = el('div', 'fixed right-4 top-20 z-[200] flex w-full max-w-md flex-col gap-3');
|
|
137
|
+
r.id = 'app-notices';
|
|
138
|
+
r.setAttribute('aria-live', 'polite');
|
|
139
|
+
document.body.append(r);
|
|
140
|
+
}
|
|
141
|
+
return r;
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
/**
|
|
145
|
+
* Shows a failure with the platform error notice (code, stage, hint, request
|
|
146
|
+
* id, details), in the page's language. Anything carrying the error envelope
|
|
147
|
+
* (ApiRequestError, wallet errors) shows as-is; anything else is normalized.
|
|
148
|
+
*/
|
|
149
|
+
export function notifyError(err: unknown, stage?: string): ApiError {
|
|
150
|
+
const carried = (err as { apiError?: unknown } | null)?.apiError;
|
|
151
|
+
const e = isApiError(carried) ? carried : apiErrorFromUnknown(err, { stage });
|
|
152
|
+
const host = el('div', 'shadow-xl rounded-2xl bg-white dark:bg-slate-900');
|
|
153
|
+
region().prepend(host);
|
|
154
|
+
mountApiErrorNotice(host, e, { onDismiss: () => host.remove() });
|
|
155
|
+
return e;
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
/** Renders a failure into host (e.g. a modal's status area) with the platform error notice. */
|
|
159
|
+
export function showErrorIn(host: HTMLElement | null, err: unknown, stage?: string): void {
|
|
160
|
+
if (!host) return;
|
|
161
|
+
const carried = (err as { apiError?: unknown } | null)?.apiError;
|
|
162
|
+
mountApiErrorNotice(host, isApiError(carried) ? carried : apiErrorFromUnknown(err, { stage }));
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
/** Shows a short confirmation that dismisses itself. */
|
|
166
|
+
export function notifyInfo(message: string, ms = 6000): HTMLElement {
|
|
167
|
+
const { t } = getTranslator();
|
|
168
|
+
const host = el('div', 'flex items-start gap-3 rounded-2xl border border-slate-200 bg-white p-4 text-sm text-slate-800 shadow-xl dark:border-slate-700 dark:bg-slate-900 dark:text-slate-100');
|
|
169
|
+
host.setAttribute('role', 'status');
|
|
170
|
+
host.append(el('p', 'flex-1', message));
|
|
171
|
+
const close = el('button', 'text-xs font-bold text-slate-400 hover:text-slate-600 border-none bg-transparent cursor-pointer', t('cx.dialog.close'));
|
|
172
|
+
close.type = 'button';
|
|
173
|
+
close.addEventListener('click', () => host.remove());
|
|
174
|
+
host.append(close);
|
|
175
|
+
region().prepend(host);
|
|
176
|
+
if (ms > 0) setTimeout(() => host.remove(), ms);
|
|
177
|
+
return host;
|
|
178
|
+
}
|