@open-charging-cloud/chargy-gui 0.0.0-stage → 0.1.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.
Files changed (170) hide show
  1. package/CHANGELOG.md +87 -0
  2. package/LICENSE +661 -0
  3. package/README.md +48 -2
  4. package/SECURITY.md +21 -0
  5. package/dist/anchorKeyTrust.d.ts +9 -0
  6. package/dist/anchorKeyTrust.d.ts.map +1 -0
  7. package/dist/anchorKeyTrust.js +24 -0
  8. package/dist/anchorKeyTrust.js.map +1 -0
  9. package/dist/anchorKeyTrustView.d.ts +14 -0
  10. package/dist/anchorKeyTrustView.d.ts.map +1 -0
  11. package/dist/anchorKeyTrustView.js +95 -0
  12. package/dist/anchorKeyTrustView.js.map +1 -0
  13. package/dist/browserFiles.d.ts +5 -0
  14. package/dist/browserFiles.d.ts.map +1 -0
  15. package/dist/browserFiles.js +100 -0
  16. package/dist/browserFiles.js.map +1 -0
  17. package/dist/core/i18n.json +1518 -0
  18. package/dist/core/package.json +119 -0
  19. package/dist/core/validationRules.json +8 -0
  20. package/dist/domHelpers.d.ts +25 -0
  21. package/dist/domHelpers.d.ts.map +1 -0
  22. package/dist/domHelpers.js +212 -0
  23. package/dist/domHelpers.js.map +1 -0
  24. package/dist/historicalSessionPanel.d.ts +24 -0
  25. package/dist/historicalSessionPanel.d.ts.map +1 -0
  26. package/dist/historicalSessionPanel.js +108 -0
  27. package/dist/historicalSessionPanel.js.map +1 -0
  28. package/dist/index.d.ts +40 -0
  29. package/dist/index.d.ts.map +1 -0
  30. package/dist/index.js +56 -0
  31. package/dist/index.js.map +1 -0
  32. package/dist/liveLinkTrust.d.ts +208 -0
  33. package/dist/liveLinkTrust.d.ts.map +1 -0
  34. package/dist/liveLinkTrust.js +452 -0
  35. package/dist/liveLinkTrust.js.map +1 -0
  36. package/dist/livePOISession.d.ts +38 -0
  37. package/dist/livePOISession.d.ts.map +1 -0
  38. package/dist/livePOISession.js +193 -0
  39. package/dist/livePOISession.js.map +1 -0
  40. package/dist/measurementDetailsRenderer.d.ts +25 -0
  41. package/dist/measurementDetailsRenderer.d.ts.map +1 -0
  42. package/dist/measurementDetailsRenderer.js +343 -0
  43. package/dist/measurementDetailsRenderer.js.map +1 -0
  44. package/dist/poiConsistencyView.d.ts +3 -0
  45. package/dist/poiConsistencyView.d.ts.map +1 -0
  46. package/dist/poiConsistencyView.js +14 -0
  47. package/dist/poiConsistencyView.js.map +1 -0
  48. package/dist/poiObservedHistory.d.ts +49 -0
  49. package/dist/poiObservedHistory.d.ts.map +1 -0
  50. package/dist/poiObservedHistory.js +205 -0
  51. package/dist/poiObservedHistory.js.map +1 -0
  52. package/dist/poiTransport.d.ts +12 -0
  53. package/dist/poiTransport.d.ts.map +1 -0
  54. package/dist/poiTransport.js +74 -0
  55. package/dist/poiTransport.js.map +1 -0
  56. package/dist/poiTrustContext.d.ts +134 -0
  57. package/dist/poiTrustContext.d.ts.map +1 -0
  58. package/dist/poiTrustContext.js +243 -0
  59. package/dist/poiTrustContext.js.map +1 -0
  60. package/dist/poiTrustLineage.d.ts +10 -0
  61. package/dist/poiTrustLineage.d.ts.map +1 -0
  62. package/dist/poiTrustLineage.js +47 -0
  63. package/dist/poiTrustLineage.js.map +1 -0
  64. package/dist/poiURLs.d.ts +5 -0
  65. package/dist/poiURLs.d.ts.map +1 -0
  66. package/dist/poiURLs.js +24 -0
  67. package/dist/poiURLs.js.map +1 -0
  68. package/dist/poiWitnessManagement.d.ts +3 -0
  69. package/dist/poiWitnessManagement.d.ts.map +1 -0
  70. package/dist/poiWitnessManagement.js +127 -0
  71. package/dist/poiWitnessManagement.js.map +1 -0
  72. package/dist/poiWitnessTrust.d.ts +26 -0
  73. package/dist/poiWitnessTrust.d.ts.map +1 -0
  74. package/dist/poiWitnessTrust.js +90 -0
  75. package/dist/poiWitnessTrust.js.map +1 -0
  76. package/dist/pricePublicationData.d.ts +19 -0
  77. package/dist/pricePublicationData.d.ts.map +1 -0
  78. package/dist/pricePublicationData.js +83 -0
  79. package/dist/pricePublicationData.js.map +1 -0
  80. package/dist/roamingNetworks.d.ts +14 -0
  81. package/dist/roamingNetworks.d.ts.map +1 -0
  82. package/dist/roamingNetworks.js +33 -0
  83. package/dist/roamingNetworks.js.map +1 -0
  84. package/dist/securityFingerprint.d.ts +16 -0
  85. package/dist/securityFingerprint.d.ts.map +1 -0
  86. package/dist/securityFingerprint.js +36 -0
  87. package/dist/securityFingerprint.js.map +1 -0
  88. package/dist/securityFingerprintView.d.ts +3 -0
  89. package/dist/securityFingerprintView.d.ts.map +1 -0
  90. package/dist/securityFingerprintView.js +61 -0
  91. package/dist/securityFingerprintView.js.map +1 -0
  92. package/dist/sessionEvidenceStore.d.ts +23 -0
  93. package/dist/sessionEvidenceStore.d.ts.map +1 -0
  94. package/dist/sessionEvidenceStore.js +81 -0
  95. package/dist/sessionEvidenceStore.js.map +1 -0
  96. package/dist/sessionMeterKeyView.d.ts +9 -0
  97. package/dist/sessionMeterKeyView.d.ts.map +1 -0
  98. package/dist/sessionMeterKeyView.js +55 -0
  99. package/dist/sessionMeterKeyView.js.map +1 -0
  100. package/dist/sessionPOIData.d.ts +49 -0
  101. package/dist/sessionPOIData.d.ts.map +1 -0
  102. package/dist/sessionPOIData.js +161 -0
  103. package/dist/sessionPOIData.js.map +1 -0
  104. package/dist/sessionPOIPanel.d.ts +50 -0
  105. package/dist/sessionPOIPanel.d.ts.map +1 -0
  106. package/dist/sessionPOIPanel.js +288 -0
  107. package/dist/sessionPOIPanel.js.map +1 -0
  108. package/dist/sessionPriceData.d.ts +17 -0
  109. package/dist/sessionPriceData.d.ts.map +1 -0
  110. package/dist/sessionPriceData.js +51 -0
  111. package/dist/sessionPriceData.js.map +1 -0
  112. package/dist/sessionPricePanel.d.ts +31 -0
  113. package/dist/sessionPricePanel.d.ts.map +1 -0
  114. package/dist/sessionPricePanel.js +222 -0
  115. package/dist/sessionPricePanel.js.map +1 -0
  116. package/dist/sessionUIState.d.ts +12 -0
  117. package/dist/sessionUIState.d.ts.map +1 -0
  118. package/dist/sessionUIState.js +33 -0
  119. package/dist/sessionUIState.js.map +1 -0
  120. package/dist/stationProofData.d.ts +38 -0
  121. package/dist/stationProofData.d.ts.map +1 -0
  122. package/dist/stationProofData.js +83 -0
  123. package/dist/stationProofData.js.map +1 -0
  124. package/dist/stationProofPanel.d.ts +44 -0
  125. package/dist/stationProofPanel.d.ts.map +1 -0
  126. package/dist/stationProofPanel.js +304 -0
  127. package/dist/stationProofPanel.js.map +1 -0
  128. package/dist/stationProofView.d.ts +9 -0
  129. package/dist/stationProofView.d.ts.map +1 -0
  130. package/dist/stationProofView.js +186 -0
  131. package/dist/stationProofView.js.map +1 -0
  132. package/dist/trustAnchorData.d.ts +40 -0
  133. package/dist/trustAnchorData.d.ts.map +1 -0
  134. package/dist/trustAnchorData.js +91 -0
  135. package/dist/trustAnchorData.js.map +1 -0
  136. package/dist/trustAnchorDataView.d.ts +13 -0
  137. package/dist/trustAnchorDataView.d.ts.map +1 -0
  138. package/dist/trustAnchorDataView.js +69 -0
  139. package/dist/trustAnchorDataView.js.map +1 -0
  140. package/dist/trustAnchorImport.d.ts +5 -0
  141. package/dist/trustAnchorImport.d.ts.map +1 -0
  142. package/dist/trustAnchorImport.js +34 -0
  143. package/dist/trustAnchorImport.js.map +1 -0
  144. package/dist/trustAnchorPreview.d.ts +37 -0
  145. package/dist/trustAnchorPreview.d.ts.map +1 -0
  146. package/dist/trustAnchorPreview.js +180 -0
  147. package/dist/trustAnchorPreview.js.map +1 -0
  148. package/dist/trustManagement.d.ts +34 -0
  149. package/dist/trustManagement.d.ts.map +1 -0
  150. package/dist/trustManagement.js +405 -0
  151. package/dist/trustManagement.js.map +1 -0
  152. package/dist/trustStore.d.ts +75 -0
  153. package/dist/trustStore.d.ts.map +1 -0
  154. package/dist/trustStore.js +408 -0
  155. package/dist/trustStore.js.map +1 -0
  156. package/dist/trustTransitionView.d.ts +5 -0
  157. package/dist/trustTransitionView.d.ts.map +1 -0
  158. package/dist/trustTransitionView.js +110 -0
  159. package/dist/trustTransitionView.js.map +1 -0
  160. package/dist/trustedPublicKeys.d.ts +4 -0
  161. package/dist/trustedPublicKeys.d.ts.map +1 -0
  162. package/dist/trustedPublicKeys.js +25 -0
  163. package/dist/trustedPublicKeys.js.map +1 -0
  164. package/dist/wwcpPoi.d.ts +2 -0
  165. package/dist/wwcpPoi.d.ts.map +1 -0
  166. package/dist/wwcpPoi.js +2 -0
  167. package/dist/wwcpPoi.js.map +1 -0
  168. package/documentation/AUDIT.md +262 -0
  169. package/images/NGI0_tag.svg +149 -0
  170. package/package.json +75 -4
@@ -0,0 +1,193 @@
1
+ import { verifyLiveSessionAuthority, readLiveSessionDocument, verifyLiveSessionTransition, verifyHistoricalOCMFSession, readOCMFSessionPriceContext, compareOCMFPriceRates, collectDocumentPublicKeys, verifyDocumentSignaturesWithKeys } from '@open-charging-cloud/chargy-core';
2
+ import { prettyJSON, isObject, compareObservedVersions, toHex, hash, parseJSON, canonicalJSONBytes, HISTORICAL_METER_EVIDENCE_CONTEXT, parseHistoricalMeterEvidence } from '@open-charging-cloud/wwcp-poi';
3
+ import { exportSessionPOIEvidence, readSessionPOIEvidence } from './sessionPOIData.js';
4
+ import { trustAnchorStorageId } from './trustStore.js';
5
+ export function originalLiveInput(input) {
6
+ const files = typeof input === 'string' ? [input] : Array.isArray(input) ? input : [input];
7
+ for (const file of files) {
8
+ let text;
9
+ if (typeof file === 'string')
10
+ text = file;
11
+ else if (file.data !== undefined && file.error === undefined) {
12
+ try {
13
+ text = new TextDecoder('utf-8', { fatal: true }).decode(file.data);
14
+ }
15
+ catch {
16
+ continue;
17
+ }
18
+ }
19
+ if (text?.trimStart().startsWith('{') !== true)
20
+ continue;
21
+ let parsed;
22
+ try {
23
+ parsed = JSON.parse(text);
24
+ }
25
+ catch {
26
+ continue;
27
+ }
28
+ if (parsed !== null && typeof parsed === 'object' && parsed['@context'] === 'https://open.charging.cloud/contexts/chargeTransparency/live/link/1.0')
29
+ return text;
30
+ }
31
+ return undefined;
32
+ }
33
+ function sameJSON(left, right) {
34
+ return new TextDecoder().decode(canonicalJSONBytes(parseJSON(left))) === new TextDecoder().decode(canonicalJSONBytes(parseJSON(right)));
35
+ }
36
+ function sameSelectedPrice(left, right) {
37
+ const content = (text) => { const json = parseJSON(text); if (!isObject(json))
38
+ throw new Error('Invalid pinned price evidence'); const { publicationReceipts: _, witnessCandidates: __, ...price } = json; return prettyJSON(price); };
39
+ return sameJSON(content(left), content(right));
40
+ }
41
+ function liveObservation(original, pinned) {
42
+ const parsed = readLiveSessionDocument(original), json = parsed.json, cpo = json['chargingStationOperator'];
43
+ const signatures = json['signatures'];
44
+ const immutable = (value) => JSON.stringify([value.id, value.evseId, value.meterSerialNumber, value.json['chargingStationOperator']['@id'], value.json['created'], value.json['chargingSessionId']]);
45
+ const identity = pinned?.identity !== undefined && immutable(readLiveSessionDocument(pinned.original)) === immutable(parsed) ? pinned.identity : toHex(hash('sha256', canonicalJSONBytes({ evseId: parsed.evseId, meter: parsed.meterSerialNumber, cpo: cpo['@id'],
46
+ created: typeof json['created'] === 'string' ? json['created'] : null, sessionId: typeof json['chargingSessionId'] === 'string' ? json['chargingSessionId'] : null, keys: signatures.map(item => item.keyId.toLowerCase()).sort() })));
47
+ return { kind: 'live', chain: parsed.id, epoch: '', position: Date.parse(typeof json['lastUpdated'] === 'string' ? json['lastUpdated'] : ''), digest: parsed.reference, identity,
48
+ ...(typeof json['updates'] === 'string' ? { previous: json['updates'].toLowerCase() } : {}), original };
49
+ }
50
+ /** Retain equivocation even when continuity rejects the candidate before meter parsing. Never advance the accepted live head. */
51
+ export async function observeRejectedLiveCandidate(service, state, text, signal) {
52
+ if (state.policyId === '')
53
+ return;
54
+ const ticket = await service.beginObservations(state.policyId, true, signal), head = ticket.observed.heads[JSON.stringify(['live', state.id])];
55
+ const pinned = ticket.observed.points.find(point => point.kind === 'live' && point.chain === state.id && point.digest === head?.digest);
56
+ if (pinned === undefined)
57
+ return;
58
+ const previous = readLiveSessionDocument(pinned.original), incoming = readLiveSessionDocument(text);
59
+ if (incoming.id !== state.id)
60
+ return;
61
+ // A self-signed replacement key must never poison the journal. Authenticate with previously accepted keys.
62
+ const keys = collectDocumentPublicKeys({ chargingStationOperator: previous.json['chargingStationOperator'] }).filter(key => key.keyUsage.includes('signCTRs'));
63
+ if (verifyDocumentSignaturesWithKeys(incoming.json, keys).status !== 'allValid')
64
+ return;
65
+ const point = liveObservation(text, pinned), comparison = compareObservedVersions(ticket.observed, [point], 'historical', ticket.context.evaluatedAt);
66
+ if (comparison.issues.some(issue => ['fork', 'identity', 'link'].includes(issue.code)))
67
+ await service.recordObservations(ticket, [point], 'historical', { signal });
68
+ }
69
+ /** Merge evidence by field. An omitted block never removes the selected original fixed-price evidence. */
70
+ export function prepareLivePOIState(text, incoming, previous, now = Date.now()) {
71
+ const parsed = previous === undefined ? readLiveSessionDocument(text, now) : verifyLiveSessionTransition(previous.originals.at(-1) ?? '', text, now, { structureOnly: true });
72
+ if (previous !== undefined && (previous.id !== parsed.id || previous.evseId !== parsed.evseId))
73
+ throw new Error('Live POI identity changed');
74
+ if (incoming.length > 1 || incoming.some(item => item.error !== undefined || item.evseId !== parsed.evseId))
75
+ throw new Error('Invalid or competing live POI evidence');
76
+ const old = previous?.evidence[0], next = incoming[0];
77
+ let priceChanged = previous?.priceChanged ?? false;
78
+ if (old?.bootstrap !== undefined && next?.bootstrap !== undefined && trustAnchorStorageId(old.bootstrap.anchor) !== trustAnchorStorageId(next.bootstrap.anchor))
79
+ throw new Error('Live trust policy changed');
80
+ if (old?.historicalEvidence !== undefined && next?.historicalEvidence !== undefined && !sameJSON(old.historicalEvidence, next.historicalEvidence)) {
81
+ const before = parseHistoricalMeterEvidence(parseJSON(old.historicalEvidence)), after = parseHistoricalMeterEvidence(parseJSON(next.historicalEvidence));
82
+ const normalized = (version) => prettyJSON({ chargingStationProof: version.proof, ...(version.commitProof === undefined ? {} : { commitProof: version.commitProof }), checkpoints: version.checkpoints.map(entry => ({ checkpoint: entry.checkpoint, operator: entry.operator })) });
83
+ if (after.evseId !== before.evseId || after.versions.length < before.versions.length || before.versions.some((version, index) => after.versions[index] === undefined || !sameJSON(normalized(version), normalized(after.versions[index]))))
84
+ throw new Error('Historical station evidence must retain every previous original version');
85
+ }
86
+ if (previous?.pricePinned === true && old?.priceEvidence !== undefined && next?.priceEvidence !== undefined && !sameSelectedPrice(old.priceEvidence, next.priceEvidence))
87
+ priceChanged = true;
88
+ const originals = [...(previous?.originals ?? []), text];
89
+ if (new TextEncoder().encode(JSON.stringify(originals)).length > 4 * 1024 * 1024)
90
+ throw new Error('Live evidence archive limit reached; original history was retained');
91
+ const merged = old === undefined ? next : next === undefined ? old : { ...old, ...next,
92
+ ...(old.bootstrap === undefined ? {} : { bootstrap: old.bootstrap }),
93
+ ...(previous?.pricePinned !== true || old.priceEvidence === undefined ? {} : { priceEvidence: old.priceEvidence, priceSource: old.priceSource }) };
94
+ if (merged === undefined)
95
+ throw new Error('No live POI evidence');
96
+ return { id: parsed.id, evseId: parsed.evseId, meterSerialNumber: parsed.meterSerialNumber, originals, authorityProofs: [...previous?.authorityProofs ?? [], next?.document?.text ?? old?.document?.text], readingCount: parsed.readings.length, priceChanged,
97
+ policyId: previous?.policyId ?? '', pricePinned: previous?.pricePinned ?? false, evidence: [{ ...merged, liveDocuments: originals }] };
98
+ }
99
+ /** UI/download orchestration only; the shared libraries authenticate every original document and price. */
100
+ export async function checkLivePOISession(chargy, service, state, session, signal) {
101
+ if (state.policyId === '')
102
+ throw new Error('Select and authorize a local trust policy before accepting POI live updates');
103
+ const evidence = state.evidence[0];
104
+ if (evidence === undefined)
105
+ throw new Error('Missing live evidence');
106
+ const ticket = await service.beginObservations(state.policyId, true, signal), before = ticket.context;
107
+ if (state.expectedHistoryGeneration !== undefined && state.expectedHistoryGeneration !== ticket.generation)
108
+ throw new Error('Version history was reset before reopening');
109
+ signal.throwIfAborted();
110
+ const knownHead = ticket.observed.heads[JSON.stringify(['live', state.id])], known = ticket.observed.points.find(point => point.kind === 'live' && point.chain === state.id && point.digest === knownHead?.digest);
111
+ if (known !== undefined && !state.originals.some(original => readLiveSessionDocument(original).reference === known.digest) && Date.parse(String(readLiveSessionDocument(state.originals.at(-1) ?? '').json['lastUpdated'])) > known.position)
112
+ throw new Error('Reopen the last observed live originals before continuing this known session; its selected fixed price must be retained');
113
+ const cpoKeys = new Set();
114
+ let operatorId = '';
115
+ for (const [index, original] of state.originals.entries()) {
116
+ const parsed = readLiveSessionDocument(original), cpo = parsed.json['chargingStationOperator'], proof = state.authorityProofs[index] ?? evidence.document?.text;
117
+ if (proof === undefined || typeof cpo['@id'] !== 'string')
118
+ throw new Error('A station proof is required to authorize the live envelope CPO');
119
+ const authority = await service.verifyLiveDocumentKeys(state.policyId, parseJSON(proof), { evseId: state.evseId, operatorId: cpo['@id'], at: Date.parse(String(parsed.json['lastUpdated'])) }, signal);
120
+ verifyLiveSessionAuthority(original, authority, state.originals[index - 1]);
121
+ operatorId = authority.operatorId;
122
+ for (const key of authority.keys)
123
+ cpoKeys.add(key.id);
124
+ }
125
+ let price, publicationPolicyRevision, stage = 'waiting';
126
+ if (session === undefined) {
127
+ if (state.readingCount !== 0 || evidence.document === undefined)
128
+ throw new Error('No usable station proof for live preparation');
129
+ await service.verifyMeterKey(state.policyId, parseJSON(evidence.document.text), { evseId: state.evseId, meterSerialNumber: state.meterSerialNumber, keyFormat: 'spki-der' }, signal);
130
+ }
131
+ else {
132
+ if (session.EVSEId !== state.evseId)
133
+ throw new Error('Original reading EVSE differs from the live link');
134
+ const subject = await readOCMFSessionPriceContext(chargy, session);
135
+ if (subject.meterSerialNumber !== state.meterSerialNumber)
136
+ throw new Error('Original reading meter differs from the live link');
137
+ const material = evidence.historicalEvidence === undefined ? { '@context': HISTORICAL_METER_EVIDENCE_CONTEXT, EVSEId: state.evseId, versions: [{ chargingStationProof: parseJSON(evidence.document?.text ?? 'null') }] } : parseJSON(evidence.historicalEvidence);
138
+ const times = (session.measurements ?? []).flatMap(measurement => measurement.values.map(value => Date.parse(value.timestamp)));
139
+ const historical = await service.verifyHistoricalMeterEvidence(state.policyId, material, { evseId: state.evseId, meterSerialNumber: state.meterSerialNumber, measurementTimes: times, keyFormat: 'spki-der' }, signal);
140
+ if (!historical.consistency.accepted)
141
+ throw new Error('Historical evidence contradicts locally observed versions');
142
+ const readings = await verifyHistoricalOCMFSession(chargy, session, historical.evidence.bindings, { signal });
143
+ if (readings.status !== 'verified' || !readings.signaturesValid || readings.signatureCount !== state.readingCount)
144
+ throw new Error('An original live reading or its historical meter-key association is not valid');
145
+ if (evidence.priceEvidence !== undefined) {
146
+ const related = parseHistoricalMeterEvidence(material).versions.flatMap(version => version.checkpoints);
147
+ const priced = await service.verifySessionPriceEvidence(state.policyId, parseJSON(evidence.priceEvidence), subject, related, signal);
148
+ publicationPolicyRevision = priced.publicationPolicyRevision;
149
+ if (!priced.consistency.accepted)
150
+ throw new Error('Price evidence contradicts locally observed versions');
151
+ price = priced.price;
152
+ if (price.signatures !== 'valid' || price.applicability !== 'bound' || price.publication === 'invalid')
153
+ throw new Error('The fixed session price could not be verified');
154
+ const rates = compareOCMFPriceRates({ ...subject, tariffTexts: subject.allTariffTexts ?? subject.tariffTexts }, price.selected?.rates);
155
+ if (rates.status !== 'rates-match')
156
+ throw new Error('A signed live tariff text conflicts with the selected fixed gross rates or needs another profile');
157
+ }
158
+ const transactions = readings.checks.flatMap(check => (check.record?.chargingSessions ?? []).flatMap(item => (item.measurements ?? []).flatMap(measurement => measurement.values.map(value => value.transaction))));
159
+ stage = transactions.includes('E') ? 'complete' : state.readingCount === 1 ? 'start' : 'charging';
160
+ }
161
+ const after = await service.resolveHistorical(state.policyId);
162
+ signal.throwIfAborted();
163
+ if (before.keyStatementDigest !== after.keyStatementDigest || before.requiredConsensus !== after.requiredConsensus || JSON.stringify(before.authorizedHolders) !== JSON.stringify(after.authorizedHolders) || after.evaluatedAt > before.validUntil)
164
+ throw new Error('Live authorization changed during verification');
165
+ const pin = ticket.observed.points.find(point => point.kind === 'live' && point.chain === state.id) ?? liveObservation(state.originals[0] ?? '');
166
+ const points = state.originals.map(original => liveObservation(original, pin));
167
+ const { liveDocuments: _, ...snapshot } = evidence;
168
+ const report = await service.recordObservations(ticket, points, 'current', { signal, live: { chain: state.id, evidence: JSON.stringify(exportSessionPOIEvidence(snapshot)) } });
169
+ if (!report.accepted)
170
+ throw new Error('Local live-version history rejected: ' + report.issues.map(issue => issue.code + ': ' + issue.detail).join('; '));
171
+ if (publicationPolicyRevision !== undefined)
172
+ await service.assertPublicationPolicy(publicationPolicyRevision);
173
+ signal.throwIfAborted();
174
+ if (price?.applicability === 'bound')
175
+ state.pricePinned = true;
176
+ return { stage, readingCount: state.readingCount, cpo: { operatorId, documents: state.originals.length, keyIds: [...cpoKeys] }, ...(price === undefined ? {} : { price }) };
177
+ }
178
+ /** Restore public evidence and revalidate the original chain; local key permission is supplied afresh by the caller. */
179
+ export function restoreObservedLive(originals, evidenceText, policyId) {
180
+ const source = readSessionPOIEvidence(JSON.stringify({ poiEvidence: JSON.parse(evidenceText) }));
181
+ let state, priceChanged = false;
182
+ const selected = source[0]?.priceEvidence;
183
+ for (const original of originals) {
184
+ const own = readSessionPOIEvidence(original);
185
+ if ((state?.readingCount ?? 0) > 0 && selected !== undefined && own[0]?.priceEvidence !== undefined && !sameSelectedPrice(selected, own[0].priceEvidence))
186
+ priceChanged = true;
187
+ state = prepareLivePOIState(original, state === undefined && own.length === 0 ? source : own, state);
188
+ }
189
+ if (state === undefined)
190
+ throw new Error('No saved live originals');
191
+ return { ...state, evidence: source, policyId, priceChanged: state.priceChanged || priceChanged };
192
+ }
193
+ //# sourceMappingURL=livePOISession.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"livePOISession.js","sourceRoot":"","sources":["../src/livePOISession.ts"],"names":[],"mappings":"AAAA,OAAO,EAAC,0BAA0B,EAAC,uBAAuB,EAAC,2BAA2B,EAAC,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CAAC;IAC5F,KAAI,MAAM,QAAQ,IAAI,SAAS,EAAC,CAAC;QAC7B,MAAM,GAAG,GAAC,sBAAsB,CAAC,QAAQ,CAAC,CAAC;QAC3C,IAAG,CAAC,KAAK,EAAE,YAAY,IAAE,CAAC,CAAC,GAAC,CAAC,IAAE,QAAQ,KAAG,SAAS,IAAE,GAAG,CAAC,CAAC,CAAC,EAAE,aAAa,KAAG,SAAS,IAAE,CAAC,iBAAiB,CAAC,QAAQ,EAAC,GAAG,CAAC,CAAC,CAAC,CAAC,aAAa,CAAC;YAAC,YAAY,GAAC,IAAI,CAAC;QAC5J,KAAK,GAAC,mBAAmB,CAAC,QAAQ,EAAC,KAAK,KAAG,SAAS,IAAE,GAAG,CAAC,MAAM,KAAG,CAAC,CAAA,CAAC,CAAA,MAAM,CAAA,CAAC,CAAA,GAAG,EAAC,KAAK,CAAC,CAAC;IAC3F,CAAC;IACD,IAAG,KAAK,KAAG,SAAS;QAAC,MAAM,IAAI,KAAK,CAAC,yBAAyB,CAAC,CAAC;IAAA,OAAO,EAAC,GAAG,KAAK,EAAC,QAAQ,EAAC,MAAM,EAAC,QAAQ,EAAC,YAAY,EAAC,KAAK,CAAC,YAAY,IAAE,YAAY,EAAC,CAAC;AAC7J,CAAC","sourcesContent":["import {verifyLiveSessionAuthority,readLiveSessionDocument,verifyLiveSessionTransition,verifyHistoricalOCMFSession,readOCMFSessionPriceContext,compareOCMFPriceRates,collectDocumentPublicKeys,verifyDocumentSignaturesWithKeys} from '@open-charging-cloud/chargy-core';\nimport type {Chargy,IChargingSession,ChargyInterfaces} from '@open-charging-cloud/chargy-core';\nimport {prettyJSON,isObject,compareObservedVersions,toHex,hash,parseJSON,canonicalJSONBytes,HISTORICAL_METER_EVIDENCE_CONTEXT,parseHistoricalMeterEvidence} from '@open-charging-cloud/wwcp-poi';\nimport type {VersionObservation,SessionPriceVerification} from '@open-charging-cloud/wwcp-poi';\nimport type {SessionPOIEvidence} from './sessionPOIData.js';\nimport {exportSessionPOIEvidence,readSessionPOIEvidence} from './sessionPOIData.js';\nimport {trustAnchorStorageId} from './trustStore.js';\nimport type {POITrustService} from './poiTrustContext.js';\n\nexport interface LivePOIState {\n readonly id:string;readonly evseId:string;readonly meterSerialNumber:string;\n readonly originals:readonly string[];readonly readingCount:number;readonly priceChanged:boolean;\n readonly authorityProofs:readonly (string|undefined)[];\n evidence:readonly SessionPOIEvidence[];\n policyId:string;\n /** Remembers the selected fixed version, never an authorization lease. */\n pricePinned:boolean;\n expectedHistoryGeneration?:string;\n}\nexport interface LivePOICheck {readonly stage:'waiting'|'start'|'charging'|'complete';readonly readingCount:number;readonly price?:SessionPriceVerification;readonly cpo:{readonly operatorId:string;readonly documents:number;readonly keyIds:readonly string[]};}\nexport function originalLiveInput(input:string|ChargyInterfaces.IFileInfo|readonly ChargyInterfaces.IFileInfo[]):string|undefined {\n const files:readonly (string|ChargyInterfaces.IFileInfo)[]=typeof input==='string'?[input]:Array.isArray(input)?input as readonly ChargyInterfaces.IFileInfo[]:[input as ChargyInterfaces.IFileInfo];\n for(const file of files){\n let text:string|undefined;\n if(typeof file==='string')text=file;\n else if(file.data!==undefined&&file.error===undefined){\n try{text=new TextDecoder('utf-8',{fatal:true}).decode(file.data);}\n catch{continue;}\n }\n if(text?.trimStart().startsWith('{')!==true)continue;\n let parsed:unknown;try{parsed=JSON.parse(text) as unknown;}catch{continue;}\n if(parsed!==null&&typeof parsed==='object'&&(parsed as Record<string,unknown>)['@context']==='https://open.charging.cloud/contexts/chargeTransparency/live/link/1.0')return text;\n }\n return undefined;\n}\nfunction sameJSON(left:string,right:string):boolean {\n return new TextDecoder().decode(canonicalJSONBytes(parseJSON(left)))===new TextDecoder().decode(canonicalJSONBytes(parseJSON(right)));\n}\nfunction sameSelectedPrice(left:string,right:string):boolean {\n const content=(text:string):string=>{const json=parseJSON(text);if(!isObject(json))throw new Error('Invalid pinned price evidence');const {publicationReceipts:_,witnessCandidates:__,...price}=json;return prettyJSON(price);};\n return sameJSON(content(left),content(right));\n}\nfunction liveObservation(original:string,pinned?:VersionObservation):VersionObservation {\n const parsed=readLiveSessionDocument(original),json=parsed.json,cpo=json['chargingStationOperator'] as Record<string,unknown>;\n const signatures=json['signatures'] as {keyId:string}[];\n const immutable=(value:ReturnType<typeof readLiveSessionDocument>):string=>JSON.stringify([value.id,value.evseId,value.meterSerialNumber,(value.json['chargingStationOperator'] as Record<string,unknown>)['@id'],value.json['created'],value.json['chargingSessionId']]);\n const identity=pinned?.identity!==undefined&&immutable(readLiveSessionDocument(pinned.original))===immutable(parsed)?pinned.identity:toHex(hash('sha256',canonicalJSONBytes({evseId:parsed.evseId,meter:parsed.meterSerialNumber,cpo:cpo['@id'] as string,\n created:typeof json['created']==='string'?json['created']:null,sessionId:typeof json['chargingSessionId']==='string'?json['chargingSessionId']:null,keys:signatures.map(item=>item.keyId.toLowerCase()).sort()})));\n return {kind:'live',chain:parsed.id,epoch:'',position:Date.parse(typeof json['lastUpdated']==='string'?json['lastUpdated']:''),digest:parsed.reference,identity,\n ...(typeof json['updates']==='string'?{previous:json['updates'].toLowerCase()}:{}),original};\n}\n/** Retain equivocation even when continuity rejects the candidate before meter parsing. Never advance the accepted live head. */\nexport async function observeRejectedLiveCandidate(service:POITrustService,state:LivePOIState,text:string,signal:AbortSignal):Promise<void> {\n if(state.policyId==='')return;\n const ticket=await service.beginObservations(state.policyId,true,signal),head=ticket.observed.heads[JSON.stringify(['live',state.id])];\n const pinned=ticket.observed.points.find(point=>point.kind==='live'&&point.chain===state.id&&point.digest===head?.digest);\n if(pinned===undefined)return;\n const previous=readLiveSessionDocument(pinned.original),incoming=readLiveSessionDocument(text);\n if(incoming.id!==state.id)return;\n // A self-signed replacement key must never poison the journal. Authenticate with previously accepted keys.\n const keys=collectDocumentPublicKeys({chargingStationOperator:previous.json['chargingStationOperator']}).filter(key=>key.keyUsage.includes('signCTRs'));\n if(verifyDocumentSignaturesWithKeys(incoming.json,keys).status!=='allValid')return;\n const point=liveObservation(text,pinned),comparison=compareObservedVersions(ticket.observed,[point],'historical',ticket.context.evaluatedAt);\n if(comparison.issues.some(issue=>['fork','identity','link'].includes(issue.code)))await service.recordObservations(ticket,[point],'historical',{signal});\n}\n/** Merge evidence by field. An omitted block never removes the selected original fixed-price evidence. */\nexport function prepareLivePOIState(text:string,incoming:readonly SessionPOIEvidence[],previous?:LivePOIState,now:number=Date.now()):LivePOIState {\n const parsed=previous===undefined?readLiveSessionDocument(text,now):verifyLiveSessionTransition(previous.originals.at(-1)??'',text,now,{structureOnly:true});\n if(previous!==undefined&&(previous.id!==parsed.id||previous.evseId!==parsed.evseId))throw new Error('Live POI identity changed');\n if(incoming.length>1||incoming.some(item=>item.error!==undefined||item.evseId!==parsed.evseId))throw new Error('Invalid or competing live POI evidence');\n const old=previous?.evidence[0],next=incoming[0];let priceChanged=previous?.priceChanged??false;\n if(old?.bootstrap!==undefined&&next?.bootstrap!==undefined&&trustAnchorStorageId(old.bootstrap.anchor)!==trustAnchorStorageId(next.bootstrap.anchor))throw new Error('Live trust policy changed');\n if(old?.historicalEvidence!==undefined&&next?.historicalEvidence!==undefined&&!sameJSON(old.historicalEvidence,next.historicalEvidence)){\n const before=parseHistoricalMeterEvidence(parseJSON(old.historicalEvidence)),after=parseHistoricalMeterEvidence(parseJSON(next.historicalEvidence));\n const normalized=(version:typeof before.versions[number]):string=>prettyJSON({chargingStationProof:version.proof,...(version.commitProof===undefined?{}:{commitProof:version.commitProof}),checkpoints:version.checkpoints.map(entry=>({checkpoint:entry.checkpoint,operator:entry.operator}))});\n if(after.evseId!==before.evseId||after.versions.length<before.versions.length||before.versions.some((version,index)=>after.versions[index]===undefined||!sameJSON(normalized(version),normalized(after.versions[index]))))throw new Error('Historical station evidence must retain every previous original version');\n }\n if(previous?.pricePinned===true&&old?.priceEvidence!==undefined&&next?.priceEvidence!==undefined&&!sameSelectedPrice(old.priceEvidence,next.priceEvidence))priceChanged=true;\n const originals=[...(previous?.originals??[]),text];\n if(new TextEncoder().encode(JSON.stringify(originals)).length>4*1024*1024)throw new Error('Live evidence archive limit reached; original history was retained');\n const merged:SessionPOIEvidence|undefined=old===undefined?next:next===undefined?old:{...old,...next,\n ...(old.bootstrap===undefined?{}:{bootstrap:old.bootstrap}),\n ...(previous?.pricePinned!==true||old.priceEvidence===undefined?{}:{priceEvidence:old.priceEvidence,priceSource:old.priceSource})};\n if(merged===undefined)throw new Error('No live POI evidence');\n return {id:parsed.id,evseId:parsed.evseId,meterSerialNumber:parsed.meterSerialNumber,originals,authorityProofs:[...previous?.authorityProofs??[],next?.document?.text??old?.document?.text],readingCount:parsed.readings.length,priceChanged,\n policyId:previous?.policyId??'',pricePinned:previous?.pricePinned??false,evidence:[{...merged,liveDocuments:originals}]};\n}\n\n/** UI/download orchestration only; the shared libraries authenticate every original document and price. */\nexport async function checkLivePOISession(chargy:Chargy,service:POITrustService,state:LivePOIState,session:IChargingSession|undefined,signal:AbortSignal):Promise<LivePOICheck> {\n if(state.policyId==='')throw new Error('Select and authorize a local trust policy before accepting POI live updates');\n const evidence=state.evidence[0];if(evidence===undefined)throw new Error('Missing live evidence');\n const ticket=await service.beginObservations(state.policyId,true,signal),before=ticket.context;\n if(state.expectedHistoryGeneration!==undefined&&state.expectedHistoryGeneration!==ticket.generation)throw new Error('Version history was reset before reopening');signal.throwIfAborted();\n const knownHead=ticket.observed.heads[JSON.stringify(['live',state.id])],known=ticket.observed.points.find(point=>point.kind==='live'&&point.chain===state.id&&point.digest===knownHead?.digest);\n if(known!==undefined&&!state.originals.some(original=>readLiveSessionDocument(original).reference===known.digest)&&Date.parse(String(readLiveSessionDocument(state.originals.at(-1)??'').json['lastUpdated']))>known.position)\n throw new Error('Reopen the last observed live originals before continuing this known session; its selected fixed price must be retained');\n const cpoKeys=new Set<string>();let operatorId='';\n for(const [index,original]of state.originals.entries()){\n const parsed=readLiveSessionDocument(original),cpo=parsed.json['chargingStationOperator'] as Record<string,unknown>,proof=state.authorityProofs[index]??evidence.document?.text;\n if(proof===undefined||typeof cpo['@id']!=='string')throw new Error('A station proof is required to authorize the live envelope CPO');\n const authority=await service.verifyLiveDocumentKeys(state.policyId,parseJSON(proof),{evseId:state.evseId,operatorId:cpo['@id'],at:Date.parse(String(parsed.json['lastUpdated']))},signal);\n verifyLiveSessionAuthority(original,authority,state.originals[index-1]);operatorId=authority.operatorId;for(const key of authority.keys)cpoKeys.add(key.id);\n }\n let price:SessionPriceVerification|undefined,publicationPolicyRevision:string|undefined,stage:LivePOICheck['stage']='waiting';\n if(session===undefined){\n if(state.readingCount!==0||evidence.document===undefined)throw new Error('No usable station proof for live preparation');\n await service.verifyMeterKey(state.policyId,parseJSON(evidence.document.text),{evseId:state.evseId,meterSerialNumber:state.meterSerialNumber,keyFormat:'spki-der'},signal);\n }else{\n if(session.EVSEId!==state.evseId)throw new Error('Original reading EVSE differs from the live link');\n const subject=await readOCMFSessionPriceContext(chargy,session);\n if(subject.meterSerialNumber!==state.meterSerialNumber)throw new Error('Original reading meter differs from the live link');\n const material=evidence.historicalEvidence===undefined?{'@context':HISTORICAL_METER_EVIDENCE_CONTEXT,EVSEId:state.evseId,versions:[{chargingStationProof:parseJSON(evidence.document?.text??'null') }]}:parseJSON(evidence.historicalEvidence);\n const times=(session.measurements??[]).flatMap(measurement=>measurement.values.map(value=>Date.parse(value.timestamp)));\n const historical=await service.verifyHistoricalMeterEvidence(state.policyId,material,{evseId:state.evseId,meterSerialNumber:state.meterSerialNumber,measurementTimes:times,keyFormat:'spki-der'},signal);\n if(!historical.consistency.accepted)throw new Error('Historical evidence contradicts locally observed versions');\n const readings=await verifyHistoricalOCMFSession(chargy,session,historical.evidence.bindings,{signal});\n if(readings.status!=='verified'||!readings.signaturesValid||readings.signatureCount!==state.readingCount)throw new Error('An original live reading or its historical meter-key association is not valid');\n if(evidence.priceEvidence!==undefined){\n const related=parseHistoricalMeterEvidence(material).versions.flatMap(version=>version.checkpoints);\n const priced=await service.verifySessionPriceEvidence(state.policyId,parseJSON(evidence.priceEvidence),subject,related,signal);\n publicationPolicyRevision=priced.publicationPolicyRevision;\n if(!priced.consistency.accepted)throw new Error('Price evidence contradicts locally observed versions');price=priced.price;\n if(price.signatures!=='valid'||price.applicability!=='bound'||price.publication==='invalid')throw new Error('The fixed session price could not be verified');\n const rates=compareOCMFPriceRates({...subject,tariffTexts:subject.allTariffTexts??subject.tariffTexts},price.selected?.rates);\n if(rates.status!=='rates-match')throw new Error('A signed live tariff text conflicts with the selected fixed gross rates or needs another profile');\n }\n const transactions=readings.checks.flatMap(check=>(check.record?.chargingSessions??[]).flatMap(item=>(item.measurements??[]).flatMap(measurement=>measurement.values.map(value=>(value as {transaction?:string}).transaction))));\n stage=transactions.includes('E')?'complete':state.readingCount===1?'start':'charging';\n }\n const after=await service.resolveHistorical(state.policyId);signal.throwIfAborted();\n if(before.keyStatementDigest!==after.keyStatementDigest||before.requiredConsensus!==after.requiredConsensus||JSON.stringify(before.authorizedHolders)!==JSON.stringify(after.authorizedHolders)||after.evaluatedAt>before.validUntil)throw new Error('Live authorization changed during verification');\n const pin=ticket.observed.points.find(point=>point.kind==='live'&&point.chain===state.id)??liveObservation(state.originals[0]??'');\n const points=state.originals.map(original=>liveObservation(original,pin));\n const {liveDocuments:_,...snapshot}=evidence;\n const report=await service.recordObservations(ticket,points,'current',{signal,live:{chain:state.id,evidence:JSON.stringify(exportSessionPOIEvidence(snapshot))}});\n if(!report.accepted)throw new Error('Local live-version history rejected: '+report.issues.map(issue=>issue.code+': '+issue.detail).join('; '));\n if(publicationPolicyRevision!==undefined)await service.assertPublicationPolicy(publicationPolicyRevision);signal.throwIfAborted();\n if(price?.applicability==='bound')state.pricePinned=true;\n return {stage,readingCount:state.readingCount,cpo:{operatorId,documents:state.originals.length,keyIds:[...cpoKeys]},...(price===undefined?{}:{price})};\n}\n\n/** Restore public evidence and revalidate the original chain; local key permission is supplied afresh by the caller. */\nexport function restoreObservedLive(originals:readonly string[],evidenceText:string,policyId:string):LivePOIState {\n const source=readSessionPOIEvidence(JSON.stringify({poiEvidence:JSON.parse(evidenceText) as unknown}));\n let state:LivePOIState|undefined,priceChanged=false;const selected=source[0]?.priceEvidence;\n for(const original of originals){\n const own=readSessionPOIEvidence(original);\n if((state?.readingCount??0)>0&&selected!==undefined&&own[0]?.priceEvidence!==undefined&&!sameSelectedPrice(selected,own[0].priceEvidence))priceChanged=true;\n state=prepareLivePOIState(original,state===undefined&&own.length===0?source:own,state);\n }\n if(state===undefined)throw new Error('No saved live originals');return {...state,evidence:source,policyId,priceChanged:state.priceChanged||priceChanged};\n}\n"]}
@@ -0,0 +1,25 @@
1
+ import type { IMeasurementDetailModel, IMeasurementValue } from "@open-charging-cloud/chargy-core";
2
+ export interface IMeasurementDetailsTargets {
3
+ readonly errorDiv: HTMLDivElement;
4
+ readonly introDiv: HTMLDivElement;
5
+ readonly infoDiv: HTMLDivElement;
6
+ readonly bufferValue: HTMLDivElement;
7
+ readonly hashedBufferValue: HTMLDivElement;
8
+ readonly publicKeyValue: HTMLDivElement;
9
+ readonly signatureExpectedValue: HTMLDivElement;
10
+ readonly signatureCheckValue: HTMLDivElement;
11
+ }
12
+ export interface IMeasurementDetailsRenderOptions {
13
+ readonly onShowPKIDetails?: (pkiData: unknown) => void;
14
+ }
15
+ /**
16
+ * Renders a DOM-free IMeasurementDetailModel produced by ChargyCore into the
17
+ * caller-provided measurement details dialog elements using safe DOM APIs only.
18
+ */
19
+ export declare function renderMeasurementDetails(model: IMeasurementDetailModel, targets: IMeasurementDetailsTargets, options?: IMeasurementDetailsRenderOptions): void;
20
+ /**
21
+ * Builds the verification detail model via ChargyCore and renders it into the
22
+ * given DOM targets. Returns an Error if the measurement could not be rendered.
23
+ */
24
+ export declare function renderMeasurementValueDetails(measurementValue: IMeasurementValue, targets: IMeasurementDetailsTargets, options?: IMeasurementDetailsRenderOptions): Promise<Error | undefined>;
25
+ //# sourceMappingURL=measurementDetailsRenderer.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"measurementDetailsRenderer.d.ts","sourceRoot":"","sources":["../src/measurementDetailsRenderer.ts"],"names":[],"mappings":"AAiBA,OAAO,KAAK,EAER,uBAAuB,EACvB,iBAAiB,EACpB,MAAM,kCAAkC,CAAC;AAG1C,MAAM,WAAW,0BAA0B;IACvC,QAAQ,CAAC,QAAQ,EAAgB,cAAc,CAAC;IAChD,QAAQ,CAAC,QAAQ,EAAgB,cAAc,CAAC;IAChD,QAAQ,CAAC,OAAO,EAAiB,cAAc,CAAC;IAChD,QAAQ,CAAC,WAAW,EAAa,cAAc,CAAC;IAChD,QAAQ,CAAC,iBAAiB,EAAO,cAAc,CAAC;IAChD,QAAQ,CAAC,cAAc,EAAU,cAAc,CAAC;IAChD,QAAQ,CAAC,sBAAsB,EAAE,cAAc,CAAC;IAChD,QAAQ,CAAC,mBAAmB,EAAK,cAAc,CAAC;CACnD;AAED,MAAM,WAAW,gCAAgC;IAC7C,QAAQ,CAAC,gBAAgB,CAAC,EAAE,CAAC,OAAO,EAAE,OAAO,KAAK,IAAI,CAAC;CAC1D;AA6XD;;;GAGG;AACH,wBAAgB,wBAAwB,CAAC,KAAK,EAAK,uBAAuB,EACjC,OAAO,EAAG,0BAA0B,EACpC,OAAO,CAAC,EAAE,gCAAgC,GAAG,IAAI,CAkDzF;AAED;;;GAGG;AACH,wBAAsB,6BAA6B,CAAC,gBAAgB,EAAE,iBAAiB,EACnC,OAAO,EAAW,0BAA0B,EAC5C,OAAO,CAAC,EAAU,gCAAgC,GAAG,OAAO,CAAC,KAAK,GAAG,SAAS,CAAC,CAYlI"}
@@ -0,0 +1,343 @@
1
+ /*
2
+ * Copyright (c) 2018-2026 GraphDefined GmbH <achim.friedland@graphdefined.com>
3
+ * This file is part of ChargyGUI <https://github.com/OpenChargingCloud/ChargyGUI.TS>
4
+ *
5
+ * Licensed under the Affero GPL license, Version 3.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.gnu.org/licenses/agpl.html
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */
17
+ import { clearElement, createDiv, renderPrettyJSON } from "./domHelpers.js";
18
+ function setElementStyle(element, styles) {
19
+ const style = element.style;
20
+ if (style === undefined)
21
+ return;
22
+ if (styles.display !== undefined)
23
+ style.display = styles.display;
24
+ if (styles.fontFamily !== undefined)
25
+ style.fontFamily = styles.fontFamily;
26
+ if (styles.maxHeight !== undefined)
27
+ style.maxHeight = styles.maxHeight;
28
+ if (styles.overflowY !== undefined)
29
+ style.overflowY = styles.overflowY;
30
+ if (styles.whiteSpace !== undefined)
31
+ style.whiteSpace = styles.whiteSpace;
32
+ }
33
+ function getDirectElementChild(parent, index) {
34
+ if (parent === null)
35
+ return undefined;
36
+ let currentIndex = 0;
37
+ for (let child = parent.firstChild; child !== null; child = child.nextSibling) {
38
+ if (child.nodeType === 1) {
39
+ if (currentIndex === index)
40
+ return child;
41
+ currentIndex++;
42
+ }
43
+ }
44
+ return undefined;
45
+ }
46
+ function setParentHeader(valueElement, header) {
47
+ if (header === undefined)
48
+ return;
49
+ const firstChild = getDirectElementChild(valueElement.parentElement, 0);
50
+ if (firstChild !== undefined)
51
+ firstChild.textContent = header;
52
+ }
53
+ function renderIntro(introDiv, intro) {
54
+ const doc = introDiv.ownerDocument;
55
+ const substitute = (text) => text.replace("{methodName}", intro.methodName)
56
+ .replace("{cryptoAlgorithm}", intro.cryptoAlgorithm);
57
+ clearElement(introDiv);
58
+ const importantTag = /<span class="important">([^<]*)<\/span>/g;
59
+ let lastIndex = 0;
60
+ let match;
61
+ while ((match = importantTag.exec(intro.template)) !== null) {
62
+ if (match.index > lastIndex)
63
+ introDiv.appendChild(doc.createTextNode(substitute(intro.template.slice(lastIndex, match.index))));
64
+ const span = doc.createElement("span");
65
+ span.className = "important";
66
+ span.textContent = substitute(match[1] ?? "");
67
+ introDiv.appendChild(span);
68
+ lastIndex = match.index + match[0].length;
69
+ }
70
+ if (lastIndex < intro.template.length)
71
+ introDiv.appendChild(doc.createTextNode(substitute(intro.template.slice(lastIndex))));
72
+ }
73
+ function addVisualBufferLink(hexSlice, bufferDiv, lineDiv) {
74
+ const entry = createDiv(bufferDiv, "entry", hexSlice);
75
+ const lineId = getDirectElementChild(lineDiv, 0);
76
+ const lineVal = getDirectElementChild(lineDiv, 1);
77
+ entry.onmouseenter = () => {
78
+ lineId?.classList.add("overEntry");
79
+ lineVal?.classList.add("overEntry");
80
+ };
81
+ entry.onmouseleave = () => {
82
+ lineId?.classList.remove("overEntry");
83
+ lineVal?.classList.remove("overEntry");
84
+ };
85
+ lineDiv.onmouseenter = () => {
86
+ entry.classList.add("overEntry");
87
+ };
88
+ lineDiv.onmouseleave = () => {
89
+ entry.classList.remove("overEntry");
90
+ };
91
+ }
92
+ function renderFieldRow(row, infoDiv, bufferDiv) {
93
+ const doc = infoDiv.ownerDocument;
94
+ const lineDiv = createDiv(infoDiv, "row");
95
+ createDiv(lineDiv, "id", row.label);
96
+ const valueDiv = createDiv(lineDiv, "value");
97
+ if (row.lines !== undefined) {
98
+ row.lines.forEach((item, index) => {
99
+ if (index > 0)
100
+ valueDiv.appendChild(doc.createElement("br"));
101
+ valueDiv.appendChild(doc.createTextNode(item));
102
+ });
103
+ }
104
+ else {
105
+ const headline = row.value ?? "";
106
+ if (headline.length > 0)
107
+ valueDiv.appendChild(doc.createTextNode(headline));
108
+ if (row.statusItems !== undefined && row.statusItems.length > 0) {
109
+ if (headline.length > 0)
110
+ valueDiv.appendChild(doc.createElement("br"));
111
+ const statusSpan = doc.createElement("span");
112
+ statusSpan.className = "statusInfos";
113
+ row.statusItems.forEach((item, index) => {
114
+ if (index > 0)
115
+ statusSpan.appendChild(doc.createElement("br"));
116
+ statusSpan.appendChild(doc.createTextNode(item));
117
+ });
118
+ valueDiv.appendChild(statusSpan);
119
+ }
120
+ }
121
+ addVisualBufferLink(row.hexSlice, bufferDiv, lineDiv);
122
+ }
123
+ function renderOCMFPlainText(plainTextDiv, model) {
124
+ const doc = plainTextDiv.ownerDocument;
125
+ clearElement(plainTextDiv);
126
+ const compactDiv = doc.createElement("div");
127
+ compactDiv.className = "compactValue";
128
+ plainTextDiv.appendChild(compactDiv);
129
+ const ocmfPrefix = doc.createElement("span");
130
+ ocmfPrefix.className = "ocmfHighlight";
131
+ ocmfPrefix.textContent = "OCMF";
132
+ compactDiv.appendChild(ocmfPrefix);
133
+ const rawBody = model.raw.substring(4);
134
+ const firstIndex = rawBody.indexOf("|");
135
+ const lastIndex = rawBody.lastIndexOf("|");
136
+ if (firstIndex !== -1 && lastIndex !== -1 && lastIndex !== firstIndex) {
137
+ if (firstIndex > 0)
138
+ compactDiv.appendChild(doc.createTextNode(rawBody.substring(0, firstIndex)));
139
+ const firstSep = doc.createElement("span");
140
+ firstSep.className = "ocmfSeparator";
141
+ firstSep.textContent = "|";
142
+ compactDiv.appendChild(firstSep);
143
+ compactDiv.appendChild(doc.createTextNode(rawBody.substring(firstIndex + 1, lastIndex)));
144
+ const lastSep = doc.createElement("span");
145
+ lastSep.className = "ocmfSeparator";
146
+ lastSep.textContent = "|";
147
+ compactDiv.appendChild(lastSep);
148
+ const sigSpan = doc.createElement("span");
149
+ sigSpan.className = "ocmfHighlight";
150
+ sigSpan.textContent = rawBody.substring(lastIndex + 1);
151
+ compactDiv.appendChild(sigSpan);
152
+ }
153
+ else if (firstIndex !== -1) {
154
+ if (firstIndex > 0)
155
+ compactDiv.appendChild(doc.createTextNode(rawBody.substring(0, firstIndex)));
156
+ const firstSep = doc.createElement("span");
157
+ firstSep.className = "ocmfSeparator";
158
+ firstSep.textContent = "|";
159
+ compactDiv.appendChild(firstSep);
160
+ compactDiv.appendChild(doc.createTextNode(rawBody.substring(firstIndex + 1)));
161
+ }
162
+ else if (rawBody.length > 0) {
163
+ compactDiv.appendChild(doc.createTextNode(rawBody));
164
+ }
165
+ setElementStyle(compactDiv, {
166
+ fontFamily: "monospace",
167
+ maxHeight: "25vh",
168
+ overflowY: "scroll"
169
+ });
170
+ const prettyDiv = doc.createElement("div");
171
+ prettyDiv.className = "prettyValue";
172
+ plainTextDiv.appendChild(prettyDiv);
173
+ const prettyPrefix = doc.createElement("span");
174
+ prettyPrefix.className = "ocmfHighlight";
175
+ prettyPrefix.textContent = "OCMF";
176
+ prettyDiv.appendChild(prettyPrefix);
177
+ const prettySep1 = doc.createElement("span");
178
+ prettySep1.className = "ocmfSeparator";
179
+ prettySep1.textContent = "|";
180
+ prettyDiv.appendChild(prettySep1);
181
+ prettyDiv.appendChild(doc.createElement("br"));
182
+ renderPrettyJSON(prettyDiv, model.payload, model.payloadLabelResolver);
183
+ const prettySep2 = doc.createElement("span");
184
+ prettySep2.className = "ocmfSeparator";
185
+ prettySep2.textContent = "|";
186
+ prettyDiv.appendChild(prettySep2);
187
+ prettyDiv.appendChild(doc.createElement("br"));
188
+ renderPrettyJSON(prettyDiv, model.signature, model.signatureLabelResolver);
189
+ compactDiv.onclick = () => {
190
+ setElementStyle(compactDiv, { display: "none" });
191
+ setElementStyle(prettyDiv, { display: "block" });
192
+ };
193
+ prettyDiv.onclick = () => {
194
+ setElementStyle(compactDiv, { display: "block" });
195
+ setElementStyle(prettyDiv, { display: "none" });
196
+ };
197
+ }
198
+ function renderPublicKey(publicKeyDiv, model, options) {
199
+ const doc = publicKeyDiv.ownerDocument;
200
+ setParentHeader(publicKeyDiv, model.header);
201
+ switch (model.kind) {
202
+ case "plain":
203
+ if (model.value.length > 0)
204
+ publicKeyDiv.textContent = model.value;
205
+ break;
206
+ case "leadingFour":
207
+ clearElement(publicKeyDiv);
208
+ if (model.value.startsWith("04")) {
209
+ const leadingSpan = doc.createElement("span");
210
+ leadingSpan.className = "leadingFour";
211
+ leadingSpan.textContent = "04";
212
+ publicKeyDiv.appendChild(leadingSpan);
213
+ publicKeyDiv.appendChild(doc.createTextNode(" " + (model.value.substring(2).match(/.{1,8}/g)?.join(" ") ?? (model.fallback ?? ""))));
214
+ }
215
+ else {
216
+ publicKeyDiv.textContent = model.value.match(/.{1,8}/g)?.join(" ") ?? (model.fallback ?? "");
217
+ }
218
+ break;
219
+ case "derXY":
220
+ clearElement(publicKeyDiv);
221
+ publicKeyDiv.appendChild(doc.createTextNode("der: " + model.value));
222
+ publicKeyDiv.appendChild(doc.createElement("br"));
223
+ publicKeyDiv.appendChild(doc.createElement("br"));
224
+ publicKeyDiv.appendChild(doc.createTextNode("x:\u00A0\u00A0 " + (model.x ?? "-")));
225
+ publicKeyDiv.appendChild(doc.createElement("br"));
226
+ publicKeyDiv.appendChild(doc.createTextNode("y:\u00A0\u00A0 " + (model.y ?? "-")));
227
+ break;
228
+ }
229
+ const signatureContainer = getDirectElementChild(publicKeyDiv.parentElement, 3);
230
+ if (signatureContainer !== undefined) {
231
+ clearElement(signatureContainer);
232
+ if (model.signatures !== undefined) {
233
+ for (const sig of model.signatures) {
234
+ const sigDiv = doc.createElement("div");
235
+ if (sig.clickable === true)
236
+ sigDiv.classList.add("signature");
237
+ const icon = doc.createElement("i");
238
+ icon.className = sig.valid ? "fas fa-check-circle" : "fas fa-times-circle";
239
+ sigDiv.appendChild(icon);
240
+ sigDiv.appendChild(doc.createTextNode(sig.signer));
241
+ if (sig.clickable === true && options?.onShowPKIDetails !== undefined) {
242
+ const onShowPKIDetails = options.onShowPKIDetails;
243
+ sigDiv.onclick = () => {
244
+ onShowPKIDetails({});
245
+ };
246
+ }
247
+ signatureContainer.appendChild(sigDiv);
248
+ }
249
+ }
250
+ }
251
+ }
252
+ function renderExpectedSignature(signatureDiv, model) {
253
+ const doc = signatureDiv.ownerDocument;
254
+ setParentHeader(signatureDiv, model.header);
255
+ switch (model.kind) {
256
+ case "plain":
257
+ signatureDiv.textContent = model.value ?? "";
258
+ break;
259
+ case "rs":
260
+ clearElement(signatureDiv);
261
+ signatureDiv.appendChild(doc.createTextNode((model.prefixR ?? "r: ") + (model.r ?? "")));
262
+ signatureDiv.appendChild(doc.createElement("br"));
263
+ signatureDiv.appendChild(doc.createTextNode((model.prefixS ?? "s: ") + (model.s ?? "")));
264
+ break;
265
+ case "derRS":
266
+ clearElement(signatureDiv);
267
+ signatureDiv.appendChild(doc.createTextNode((model.valueLabel ?? "der") + ": " + (model.value ?? "-")));
268
+ signatureDiv.appendChild(doc.createElement("br"));
269
+ signatureDiv.appendChild(doc.createElement("br"));
270
+ signatureDiv.appendChild(doc.createTextNode("R:\u00A0\u00A0 " + (model.r ?? "-")));
271
+ signatureDiv.appendChild(doc.createElement("br"));
272
+ signatureDiv.appendChild(doc.createTextNode("S:\u00A0\u00A0 " + (model.s ?? "-")));
273
+ break;
274
+ }
275
+ }
276
+ function renderVerificationBadge(container, valid, text) {
277
+ const doc = container.ownerDocument;
278
+ clearElement(container);
279
+ const icon = doc.createElement("i");
280
+ icon.className = valid ? "fas fa-check-circle" : "fas fa-times-circle";
281
+ const description = doc.createElement("div");
282
+ description.id = "description";
283
+ description.textContent = text;
284
+ container.appendChild(icon);
285
+ container.appendChild(description);
286
+ }
287
+ /**
288
+ * Renders a DOM-free IMeasurementDetailModel produced by ChargyCore into the
289
+ * caller-provided measurement details dialog elements using safe DOM APIs only.
290
+ */
291
+ export function renderMeasurementDetails(model, targets, options) {
292
+ renderIntro(targets.introDiv, model.intro);
293
+ setParentHeader(targets.bufferValue, model.plainText.header);
294
+ switch (model.plainText.kind) {
295
+ case "fields":
296
+ setElementStyle(targets.bufferValue, {
297
+ fontFamily: "",
298
+ whiteSpace: "",
299
+ maxHeight: "",
300
+ overflowY: ""
301
+ });
302
+ for (const row of model.plainText.rows)
303
+ renderFieldRow(row, targets.infoDiv, targets.bufferValue);
304
+ break;
305
+ case "ocmf":
306
+ renderOCMFPlainText(targets.bufferValue, model.plainText);
307
+ break;
308
+ case "preformatted":
309
+ targets.bufferValue.textContent = model.plainText.text;
310
+ setElementStyle(targets.bufferValue, {
311
+ fontFamily: "monospace",
312
+ whiteSpace: "pre",
313
+ maxHeight: "25vh",
314
+ overflowY: "scroll"
315
+ });
316
+ break;
317
+ case "text":
318
+ targets.bufferValue.textContent = model.plainText.text;
319
+ break;
320
+ }
321
+ setParentHeader(targets.hashedBufferValue, model.hashedPlainText.header);
322
+ targets.hashedBufferValue.textContent = model.hashedPlainText.value;
323
+ if (model.publicKey !== undefined)
324
+ renderPublicKey(targets.publicKeyValue, model.publicKey, options);
325
+ if (model.expectedSignature !== undefined)
326
+ renderExpectedSignature(targets.signatureExpectedValue, model.expectedSignature);
327
+ if (model.signatureCheck !== undefined)
328
+ renderVerificationBadge(targets.signatureCheckValue, model.signatureCheck.valid, model.signatureCheck.text);
329
+ }
330
+ /**
331
+ * Builds the verification detail model via ChargyCore and renders it into the
332
+ * given DOM targets. Returns an Error if the measurement could not be rendered.
333
+ */
334
+ export async function renderMeasurementValueDetails(measurementValue, targets, options) {
335
+ if (measurementValue.method == null)
336
+ return new Error("Missing measurement verification method!");
337
+ const modelOrError = await measurementValue.method.BuildMeasurementDetails(measurementValue);
338
+ if (modelOrError instanceof Error)
339
+ return modelOrError;
340
+ renderMeasurementDetails(modelOrError, targets, options);
341
+ return undefined;
342
+ }
343
+ //# sourceMappingURL=measurementDetailsRenderer.js.map