@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,452 @@
1
+ /*
2
+ * Copyright (c) 2018-2026 GraphDefined GmbH <achim.friedland@graphdefined.com>
3
+ * This file is part of Chargy WebApp <https://github.com/OpenChargingCloud/ChargyWebApp>
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
+ // A charge transparency live link names the URLs its live data can be fetched
18
+ // from, and the document comes from outside - so those URLs are a trust
19
+ // question, not a configuration detail. The installation may pre-answer it in
20
+ // externalURLs.conf; for everything else the user is asked once per origin and
21
+ // the answer is remembered: trust on first use.
22
+ //
23
+ // This module holds the parts of that which are plain functions - the shape of
24
+ // the remembered decisions and the structural rules a poll target has to
25
+ // satisfy before a user is even asked. The dialog and the store live in the
26
+ // application.
27
+ import { hmac } from '@noble/hashes/hmac.js';
28
+ import { sha256 } from '@noble/hashes/sha2.js';
29
+ /**
30
+ * The two bounds below are this application's policy, not the format's: how
31
+ * often an https transport is asked when a document does not say is the
32
+ * format's own default, and ChargyCore states it as defaultRefreshSeconds.
33
+ * Duplicating the number here would give it two sources of truth.
34
+ */
35
+ /**
36
+ * A reloading client can hammer a server no faster than this, whatever the
37
+ * document says: a viral QR code must not turn every phone that scans it
38
+ * into a flood.
39
+ */
40
+ export const minimumRefreshSeconds = 5;
41
+ /**
42
+ * And no slower than this. The refresh period is a document-controlled number
43
+ * with no upper bound of its own, and a value large enough to overflow the
44
+ * timer delay wraps back to firing immediately - so a document could turn its
45
+ * own "poll rarely" into "poll as fast as the network answers" through the far
46
+ * end of the range. One day is longer than any charging session and safely
47
+ * inside the timer's integer range.
48
+ */
49
+ export const maximumRefreshSeconds = 24 * 60 * 60;
50
+ /**
51
+ * How much a poll answer may weigh when the origin was approved by the user
52
+ * rather than by externalURLs.conf, which states a limit per prefix.
53
+ */
54
+ export const defaultTrustedPayloadBytes = 1024 * 1024;
55
+ //#region The remembered decisions
56
+ /** How long decisions are kept when the user has not said otherwise. */
57
+ export const defaultRetentionMonths = 6;
58
+ export const minimumRetentionMonths = 1;
59
+ export const maximumRetentionMonths = 120;
60
+ // The algorithms this version can compute, and the one new entries use. The
61
+ // salt length follows the digest length, as OpenSSH's does. Switching to a
62
+ // stronger algorithm later means adding it here and changing the current one -
63
+ // existing entries keep matching with the algorithm they were written with.
64
+ const trustHashAlgorithms = {
65
+ "HMAC-SHA-256": { hash: sha256, saltLength: 32 }
66
+ };
67
+ export const currentTrustHashAlgorithm = "HMAC-SHA-256";
68
+ //#region Base64 and hashing
69
+ function bytesToBase64(bytes) {
70
+ let binary = "";
71
+ for (const byte of bytes)
72
+ binary += String.fromCharCode(byte);
73
+ return btoa(binary);
74
+ }
75
+ function base64ToBytes(value) {
76
+ const binary = atob(value);
77
+ const bytes = new Uint8Array(binary.length);
78
+ for (let index = 0; index < binary.length; index++)
79
+ bytes[index] = binary.charCodeAt(index);
80
+ return bytes;
81
+ }
82
+ // The keyed hash of an origin: the salt is the key, the origin the message.
83
+ // The salt is no secret - it sits right next to the hash - its job is to make
84
+ // precomputation and cross-entry correlation impossible, not to hide.
85
+ function hashOrigin(algorithm, saltBytes, origin) {
86
+ // Own properties only: the algorithm string comes from a stored entry, and
87
+ // "__proto__" or "toString" must be an unknown algorithm, not an inherited
88
+ // object that slips past the check below.
89
+ const suite = Object.hasOwn(trustHashAlgorithms, algorithm)
90
+ ? trustHashAlgorithms[algorithm]
91
+ : undefined;
92
+ if (suite === undefined)
93
+ return null;
94
+ return hmac(suite.hash, saltBytes, new TextEncoder().encode(origin));
95
+ }
96
+ /** Whether this entry is the remembered decision for the given origin. */
97
+ export function matchesTrustedOrigin(entry, origin) {
98
+ try {
99
+ const expected = base64ToBytes(entry.hash);
100
+ const computed = hashOrigin(entry.algorithm, base64ToBytes(entry.salt), origin);
101
+ if (computed?.length !== expected.length)
102
+ return false;
103
+ // Compared without an early exit; in this setting timing hardly
104
+ // matters, but a comparison of hashes should simply look like this.
105
+ let difference = 0;
106
+ for (let index = 0; index < computed.length; index++)
107
+ difference |= (computed[index] ?? 0) ^ (expected[index] ?? 0);
108
+ return difference === 0;
109
+ }
110
+ catch {
111
+ // Unparsable base64 is an entry that matches nothing.
112
+ return false;
113
+ }
114
+ }
115
+ //#endregion
116
+ /** The remembered decision for an origin, when there is one. */
117
+ export function findTrustedOrigin(store, origin) {
118
+ return store.origins.find(entry => matchesTrustedOrigin(entry, origin));
119
+ }
120
+ /**
121
+ * Remembers a decision for an origin, replacing whatever was remembered
122
+ * before. The entry gets a fresh salt on every write; when the decision
123
+ * itself has not changed, its original date is kept, so reconsidering
124
+ * without changing anything does not reset "trusted since".
125
+ * Returns the entry as written.
126
+ */
127
+ export function upsertTrustedOrigin(store, origin, decision, label, nowISO) {
128
+ const existing = findTrustedOrigin(store, origin);
129
+ const since = existing?.decision === decision && existing.since !== ""
130
+ ? existing.since
131
+ : nowISO;
132
+ store.origins = store.origins.filter(entry => !matchesTrustedOrigin(entry, origin));
133
+ const suite = trustHashAlgorithms[currentTrustHashAlgorithm];
134
+ const saltBytes = crypto.getRandomValues(new Uint8Array(suite?.saltLength ?? 32));
135
+ const hashBytes = hashOrigin(currentTrustHashAlgorithm, saltBytes, origin);
136
+ if (hashBytes === null)
137
+ throw new Error("The current trust hash algorithm is unknown to itself!");
138
+ const entry = {
139
+ algorithm: currentTrustHashAlgorithm,
140
+ salt: bytesToBase64(saltBytes),
141
+ hash: bytesToBase64(hashBytes),
142
+ label: sanitizeTrustLabel(label),
143
+ decision: decision,
144
+ since: since,
145
+ lastUsed: nowISO
146
+ };
147
+ store.origins.push(entry);
148
+ return entry;
149
+ }
150
+ /**
151
+ * How much newer a use has to be before it is worth persisting: the expiry is
152
+ * measured in months, so refreshing lastUsed more often than hourly would be
153
+ * pure storage churn for a live link that reloads every few seconds.
154
+ */
155
+ export const lastUsedGranularityMs = 60 * 60 * 1000;
156
+ /**
157
+ * Records that the remembered decision for this origin was actually applied -
158
+ * an allowed origin polled, a denied one blocked. Every use restarts the idle
159
+ * expiry clock. Returns whether anything changed and is worth saving.
160
+ */
161
+ export function touchTrustedOrigin(store, origin, now) {
162
+ const entry = findTrustedOrigin(store, origin);
163
+ if (entry === undefined)
164
+ return false;
165
+ const lastUsed = new Date(entry.lastUsed);
166
+ if (!Number.isNaN(lastUsed.valueOf()) &&
167
+ now.valueOf() - lastUsed.valueOf() < lastUsedGranularityMs) {
168
+ return false;
169
+ }
170
+ entry.lastUsed = now.toISOString();
171
+ return true;
172
+ }
173
+ /** Forgets the remembered decision for an origin. Returns whether one existed. */
174
+ export function removeTrustedOrigin(store, origin) {
175
+ const before = store.origins.length;
176
+ store.origins = store.origins.filter(entry => !matchesTrustedOrigin(entry, origin));
177
+ return store.origins.length !== before;
178
+ }
179
+ /**
180
+ * The label an entry is shown under: the operator name the user saw when
181
+ * consenting. Document text from outside, so control and format characters -
182
+ * newlines, zero-width characters, bidi overrides - are stripped, the rest is
183
+ * trimmed and capped. Rendering must additionally treat it as text, never as
184
+ * markup.
185
+ */
186
+ export function sanitizeTrustLabel(value) {
187
+ if (typeof value !== "string")
188
+ return "";
189
+ return value.replace(/[\p{Cc}\p{Cf}]/gu, "").trim().substring(0, 100);
190
+ }
191
+ /**
192
+ * The label to actually store for a given origin. A label that contains the
193
+ * origin's host would smuggle the very plaintext back into storage that the
194
+ * hashing keeps out, so such a label is dropped - the entry then shows as an
195
+ * unknown operator, which is the honest price of a hostname-shaped name.
196
+ */
197
+ export function trustLabelForOrigin(label, origin) {
198
+ try {
199
+ const hostname = new URL(origin).hostname.toLowerCase();
200
+ if (hostname !== "" && label.toLowerCase().includes(hostname))
201
+ return "";
202
+ }
203
+ catch {
204
+ // An unparsable origin is never stored anyway.
205
+ }
206
+ return label;
207
+ }
208
+ /**
209
+ * The retention setting, tolerantly: null means "keep indefinitely", numbers
210
+ * are clamped into [1, 120] months, and anything unusable falls back to the
211
+ * default rather than to "keep forever".
212
+ */
213
+ export function sanitizeRetentionMonths(value) {
214
+ if (value === null)
215
+ return null;
216
+ if (typeof value === "number" && Number.isFinite(value))
217
+ return Math.min(Math.max(Math.round(value), minimumRetentionMonths), maximumRetentionMonths);
218
+ return defaultRetentionMonths;
219
+ }
220
+ /**
221
+ * When an entry expires, or null when decisions are kept indefinitely.
222
+ * Measured from the last use, not from the decision: using a decision
223
+ * restarts its clock, so only what lies unused actually runs out.
224
+ */
225
+ export function trustedOriginExpiry(entry, retentionMonths) {
226
+ if (retentionMonths === null)
227
+ return null;
228
+ const since = new Date(entry.lastUsed !== "" ? entry.lastUsed : entry.since);
229
+ if (Number.isNaN(since.valueOf()))
230
+ return null;
231
+ // Calendar months, without JavaScript's day overflow: a decision from
232
+ // August 31st plus six months expires on February 28th, not on March 3rd
233
+ // via a "February 31st" that never existed.
234
+ const expiry = new Date(since);
235
+ const dayOfMonth = expiry.getUTCDate();
236
+ expiry.setUTCDate(1);
237
+ expiry.setUTCMonth(expiry.getUTCMonth() + retentionMonths);
238
+ const daysInMonth = new Date(Date.UTC(expiry.getUTCFullYear(), expiry.getUTCMonth() + 1, 0)).getUTCDate();
239
+ expiry.setUTCDate(Math.min(dayOfMonth, daysInMonth));
240
+ return expiry;
241
+ }
242
+ /**
243
+ * Drops every entry whose time is up. An entry whose date cannot be read
244
+ * counts as expired rather than immortal: with retention active, nothing may
245
+ * be un-forgettable. Returns whether anything changed.
246
+ */
247
+ export function pruneExpiredTrustedOrigins(store, now) {
248
+ if (store.retentionMonths === null)
249
+ return false;
250
+ const before = store.origins.length;
251
+ store.origins = store.origins.filter(entry => {
252
+ const expiry = trustedOriginExpiry(entry, store.retentionMonths);
253
+ return expiry !== null && now.valueOf() < expiry.valueOf();
254
+ });
255
+ return store.origins.length !== before;
256
+ }
257
+ export function emptyTrustedOriginsStore() {
258
+ return { retentionMonths: defaultRetentionMonths, origins: [] };
259
+ }
260
+ /**
261
+ * The stored decisions, tolerantly: anything that is not exactly an entry with
262
+ * a salt, a hash, an algorithm and a valid decision is dropped rather than
263
+ * trusted by accident, and a store that cannot be parsed at all counts as
264
+ * empty - the user is simply asked again. Entries with an algorithm this
265
+ * version does not know are kept: they never match here, but a newer version
266
+ * may still understand them.
267
+ */
268
+ export function parseTrustedOriginsStore(json) {
269
+ const store = emptyTrustedOriginsStore();
270
+ if (json == null || json === "")
271
+ return store;
272
+ let parsed;
273
+ try {
274
+ parsed = JSON.parse(json);
275
+ }
276
+ catch {
277
+ return store;
278
+ }
279
+ if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed))
280
+ return store;
281
+ const parsedStore = parsed;
282
+ store.retentionMonths = sanitizeRetentionMonths(parsedStore["retentionMonths"]);
283
+ const origins = parsedStore["origins"];
284
+ if (!Array.isArray(origins))
285
+ return store;
286
+ for (const candidate of origins) {
287
+ if (candidate === null || typeof candidate !== "object")
288
+ continue;
289
+ const entry = candidate;
290
+ const algorithm = entry["algorithm"];
291
+ const salt = entry["salt"];
292
+ const hash = entry["hash"];
293
+ const decision = entry["decision"];
294
+ const since = entry["since"];
295
+ if (typeof algorithm !== "string" || algorithm === "" ||
296
+ typeof salt !== "string" || salt === "" ||
297
+ typeof hash !== "string" || hash === "") {
298
+ continue;
299
+ }
300
+ if (decision !== "allow" && decision !== "deny")
301
+ continue;
302
+ const sinceText = typeof since === "string" ? since : "";
303
+ const lastUsed = entry["lastUsed"];
304
+ store.origins.push({
305
+ algorithm: algorithm,
306
+ salt: salt,
307
+ hash: hash,
308
+ label: sanitizeTrustLabel(entry["label"]),
309
+ decision: decision,
310
+ since: sinceText,
311
+ // An entry that never recorded a use counts as used when it was
312
+ // decided - the least surprising reading, and the one that keeps
313
+ // it prunable.
314
+ lastUsed: typeof lastUsed === "string" && lastUsed !== "" ? lastUsed : sinceText
315
+ });
316
+ }
317
+ return store;
318
+ }
319
+ export function serializeTrustedOriginsStore(store) {
320
+ return JSON.stringify(store);
321
+ }
322
+ //#endregion
323
+ //#region The structural rules
324
+ function ipv4Octets(hostname) {
325
+ const match = /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/.exec(hostname);
326
+ if (match === null)
327
+ return null;
328
+ const octets = match.slice(1).map(Number);
329
+ return octets.every(octet => octet <= 255)
330
+ ? octets
331
+ : null;
332
+ }
333
+ /**
334
+ * The dotted-quad an IPv4-carrying IPv6 literal embeds, or null.
335
+ *
336
+ * An IPv4 address hidden inside IPv6 still reaches the same IPv4 host at the
337
+ * socket layer, so it has to be classified as that host, not waved through as
338
+ * an opaque IPv6 address. The WHATWG URL parser serializes the embedded IPv4
339
+ * in hex - "[::ffff:127.0.0.1]" arrives here as "[::ffff:7f00:1]" - so the two
340
+ * trailing hextets are decoded back into octets. Covered forms: IPv4-mapped
341
+ * (::ffff:0:0/96), the deprecated IPv4-compatible (::/96) and NAT64
342
+ * (64:ff9b::/96).
343
+ */
344
+ function embeddedIPv4(hostname) {
345
+ if (!hostname.startsWith("[") || !hostname.endsWith("]"))
346
+ return null;
347
+ const address = hostname.slice(1, -1).toLowerCase();
348
+ // A dotted tail can survive when the leading field is non-zero; take it.
349
+ const dotted = /:((?:\d{1,3}\.){3}\d{1,3})$/.exec(address);
350
+ if (dotted !== null)
351
+ return ipv4Octets(dotted[1]);
352
+ const hex = /^(?:::ffff:|::|64:ff9b::)([0-9a-f]{1,4}):([0-9a-f]{1,4})$/.exec(address);
353
+ if (hex === null)
354
+ return null;
355
+ const high = parseInt(hex[1], 16);
356
+ const low = parseInt(hex[2], 16);
357
+ return [(high >> 8) & 0xff, high & 0xff, (low >> 8) & 0xff, low & 0xff];
358
+ }
359
+ /** The host of the machine itself. The WHATWG URL parser has already
360
+ * normalized IPv4 notations, so "127.1" arrives here as "127.0.0.1". */
361
+ export function isLoopbackHost(hostname) {
362
+ const host = hostname.toLowerCase();
363
+ if (host === "localhost" || host.endsWith(".localhost"))
364
+ return true;
365
+ if (host === "[::1]" || host === "::1" || host === "0.0.0.0")
366
+ return true;
367
+ const octets = ipv4Octets(host) ?? embeddedIPv4(host);
368
+ return octets !== null && octets[0] === 127;
369
+ }
370
+ /**
371
+ * A host that is not on the public internet: loopback, RFC 1918, link-local
372
+ * and IPv6 unique-local addresses. A public web application must not let a
373
+ * document turn the user's browser into a probe for the network behind their
374
+ * router.
375
+ */
376
+ export function isPrivateNetworkHost(hostname) {
377
+ if (isLoopbackHost(hostname))
378
+ return true;
379
+ const host = hostname.toLowerCase();
380
+ const octets = ipv4Octets(host) ?? embeddedIPv4(host);
381
+ if (octets !== null) {
382
+ const [first, second] = octets;
383
+ return first === 10 ||
384
+ (first === 172 && second >= 16 && second <= 31) ||
385
+ (first === 192 && second === 168) ||
386
+ (first === 169 && second === 254);
387
+ }
388
+ if (host.startsWith("[") && host.endsWith("]")) {
389
+ const address = host.slice(1, -1);
390
+ // fc00::/7 (unique local) and fe80::/10 (link local).
391
+ return address.startsWith("fc") ||
392
+ address.startsWith("fd") ||
393
+ address.startsWith("fe8") ||
394
+ address.startsWith("fe9") ||
395
+ address.startsWith("fea") ||
396
+ address.startsWith("feb");
397
+ }
398
+ return false;
399
+ }
400
+ /**
401
+ * Why this URL's scheme must not be used, or null if it may be.
402
+ *
403
+ * Encrypted schemes - https and wss - are always fine, their plaintext
404
+ * counterparts only in a build that was told to allow them, and everything
405
+ * else never. This is the rule that no trust decision may waive: what a
406
+ * consent tier can decide is whether an origin may be asked at all, not
407
+ * whether a request may travel in the clear, so it is asked before the tiers
408
+ * rather than after them.
409
+ *
410
+ * ws and wss are listed although nothing here opens a websocket yet: the rule
411
+ * belongs to the scheme, not to the code that happens to exist.
412
+ *
413
+ * An application served from loopback is a developer's, and a developer talks
414
+ * to their own machine: for them the rule is waived, as the others are.
415
+ */
416
+ export function transportProtocolProblem(url, appIsLoopback, allowances = {}) {
417
+ if (appIsLoopback && isLoopbackHost(url.hostname))
418
+ return null;
419
+ if (url.protocol === "https:" || url.protocol === "wss:")
420
+ return null;
421
+ if (url.protocol === "http:" || url.protocol === "ws:") {
422
+ return allowances.insecureTransports === true
423
+ ? null
424
+ : "unencrypted " + url.protocol.replace(":", "") + " is used only by a build that allows it";
425
+ }
426
+ return "only encrypted transports are used, not " + url.protocol.replace(":", "");
427
+ }
428
+ /**
429
+ * Why this URL must not be polled, or null if it may be - subject to the
430
+ * user's consent, which is the next gate, not this one.
431
+ *
432
+ * An application served from loopback is a developer's, and a developer polls
433
+ * their own machine: for them every rule is waived.
434
+ */
435
+ export function pollTargetProblem(url, appIsLoopback, allowances = {}) {
436
+ const protocolProblem = transportProtocolProblem(url, appIsLoopback, allowances);
437
+ if (protocolProblem !== null)
438
+ return protocolProblem;
439
+ if (appIsLoopback && isLoopbackHost(url.hostname))
440
+ return null;
441
+ // A poll is an http request. A scheme another transport may use is
442
+ // therefore still not one to ask over.
443
+ if (url.protocol !== "https:" && url.protocol !== "http:")
444
+ return "a poll asks over https, not " + url.protocol.replace(":", "");
445
+ if (isPrivateNetworkHost(url.hostname) &&
446
+ allowances.privateNetworkTransports !== true) {
447
+ return "the host is not on the public internet";
448
+ }
449
+ return null;
450
+ }
451
+ //#endregion
452
+ //# sourceMappingURL=liveLinkTrust.js.map
@@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AAK,IAAI;YAClC,CAAC,CAAC,IAAI;YACN,CAAC,CAAC,cAAc,GAAG,GAAG,CAAC,QAAQ,CAAC,OAAO,CAAC,GAAG,EAAE,EAAE,CAAC,GAAG,yCAAyC,CAAC;IAC5G,CAAC;IAED,OAAO,0CAA0C,GAAG,GAAG,CAAC,QAAQ,CAAC,OAAO,CAAC,GAAG,EAAE,EAAE,CAAC,CAAC;AAEtF,CAAC;AAED;;;;;;GAMG;AACH,MAAM,UAAU,iBAAiB,CAAC,GAAmB,EACnB,aAAuB,EACvB,aAAuC,EAAE;IAEvE,MAAM,eAAe,GAAG,wBAAwB,CAAC,GAAG,EAAE,aAAa,EAAE,UAAU,CAAC,CAAC;IAEjF,IAAI,eAAe,KAAK,IAAI;QACxB,OAAO,eAAe,CAAC;IAE3B,IAAI,aAAa,IAAI,cAAc,CAAC,GAAG,CAAC,QAAQ,CAAC;QAC7C,OAAO,IAAI,CAAC;IAEhB,mEAAmE;IACnE,uCAAuC;IACvC,IAAI,GAAG,CAAC,QAAQ,KAAK,QAAQ,IAAI,GAAG,CAAC,QAAQ,KAAK,OAAO;QACrD,OAAO,8BAA8B,GAAG,GAAG,CAAC,QAAQ,CAAC,OAAO,CAAC,GAAG,EAAE,EAAE,CAAC,CAAC;IAE1E,IAAI,oBAAoB,CAAC,GAAG,CAAC,QAAQ,CAAC;QAClC,UAAU,CAAC,wBAAwB,KAAK,IAAI,EAChD,CAAC;QACG,OAAO,wCAAwC,CAAC;IACpD,CAAC;IAED,OAAO,IAAI,CAAC;AAEhB,CAAC;AAED,YAAY","sourcesContent":["/*\n * Copyright (c) 2018-2026 GraphDefined GmbH <achim.friedland@graphdefined.com>\n * This file is part of Chargy WebApp <https://github.com/OpenChargingCloud/ChargyWebApp>\n *\n * Licensed under the Affero GPL license, Version 3.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.gnu.org/licenses/agpl.html\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n// A charge transparency live link names the URLs its live data can be fetched\n// from, and the document comes from outside - so those URLs are a trust\n// question, not a configuration detail. The installation may pre-answer it in\n// externalURLs.conf; for everything else the user is asked once per origin and\n// the answer is remembered: trust on first use.\n//\n// This module holds the parts of that which are plain functions - the shape of\n// the remembered decisions and the structural rules a poll target has to\n// satisfy before a user is even asked. The dialog and the store live in the\n// application.\n\nimport { hmac } from '@noble/hashes/hmac.js';\nimport { sha256 } from '@noble/hashes/sha2.js';\n\nexport type TrustDecision = \"allow\" | \"deny\";\n\n/**\n * One remembered decision.\n *\n * The origin itself is not stored. Like OpenSSH's hashed known_hosts, each\n * entry keeps a fresh random salt and the keyed hash of the origin instead:\n * the store can still answer \"have I seen this origin?\" - the candidate\n * arrives in plain text with every live link - but a copy of the store\n * answers little on its own. What that buys, and what it does not:\n *\n * - A snapshot of the store (a synced browser profile, a backup, a moment of\n * access to the machine) no longer reveals where its owner charges - which\n * is a movement profile - nor does it hand over a ready-made list of CPO\n * live-data endpoints to probe.\n * - The per-entry salt prevents precomputed tables and correlation: the same\n * origin hashes differently in every entry and every installation, so two\n * stores cannot be matched against each other.\n * - The honest limit, same as OpenSSH's: publicly known endpoints can still\n * be tested against each entry, one guess at a time. The protection is for\n * what is not on a public list - and it makes the store worthless as a\n * harvesting target rather than unreadable in principle.\n *\n * The algorithm is stored per entry, so a future switch (say, to HMAC-SHA512)\n * needs no migration: new entries simply use the new algorithm, old ones keep\n * matching with theirs. An entry whose algorithm this version does not know is\n * preserved but never matches - a newer version may still understand it.\n *\n * The label is the operator name the user saw in the consent dialog, kept so\n * the settings screen can say \"GraphDefined GmbH\" instead of a hash - or an\n * unhelpful cloud hostname. It names the operator, not the server: the\n * topology stays hashed.\n */\nexport interface ITrustedOrigin {\n algorithm: string;\n salt: string;\n hash: string;\n label: string;\n decision: TrustDecision;\n since: string;\n lastUsed: string;\n}\n\n/** The remembered decisions, plus how long an unused one is kept. */\nexport interface ITrustedOriginsStore {\n\n /**\n * After how many months WITHOUT USE a decision expires and is asked again,\n * or null to keep decisions indefinitely. Every time a decision actually\n * decides something - an allowed origin is polled, a denied one is blocked\n * - its clock restarts, so an entry in regular use never expires. What\n * fades is what stopped being used: a stale \"always\" whose server no\n * longer appears in any document, entries for endpoints an operator has\n * long since retired. Idle expiry, not forced re-consent.\n */\n retentionMonths: number | null;\n\n origins: Array<ITrustedOrigin>;\n\n}\n\n/**\n * The two bounds below are this application's policy, not the format's: how\n * often an https transport is asked when a document does not say is the\n * format's own default, and ChargyCore states it as defaultRefreshSeconds.\n * Duplicating the number here would give it two sources of truth.\n */\n\n/**\n * A reloading client can hammer a server no faster than this, whatever the\n * document says: a viral QR code must not turn every phone that scans it\n * into a flood.\n */\nexport const minimumRefreshSeconds = 5;\n\n/**\n * And no slower than this. The refresh period is a document-controlled number\n * with no upper bound of its own, and a value large enough to overflow the\n * timer delay wraps back to firing immediately - so a document could turn its\n * own \"poll rarely\" into \"poll as fast as the network answers\" through the far\n * end of the range. One day is longer than any charging session and safely\n * inside the timer's integer range.\n */\nexport const maximumRefreshSeconds = 24 * 60 * 60;\n\n/**\n * How much a poll answer may weigh when the origin was approved by the user\n * rather than by externalURLs.conf, which states a limit per prefix.\n */\nexport const defaultTrustedPayloadBytes = 1024 * 1024;\n\n//#region The remembered decisions\n\n/** How long decisions are kept when the user has not said otherwise. */\nexport const defaultRetentionMonths = 6;\nexport const minimumRetentionMonths = 1;\nexport const maximumRetentionMonths = 120;\n\n// The algorithms this version can compute, and the one new entries use. The\n// salt length follows the digest length, as OpenSSH's does. Switching to a\n// stronger algorithm later means adding it here and changing the current one -\n// existing entries keep matching with the algorithm they were written with.\nconst trustHashAlgorithms: Record<string, { hash: typeof sha256, saltLength: number }> = {\n \"HMAC-SHA-256\": { hash: sha256, saltLength: 32 }\n};\n\nexport const currentTrustHashAlgorithm = \"HMAC-SHA-256\";\n\n//#region Base64 and hashing\n\nfunction bytesToBase64(bytes: Uint8Array): string {\n\n let binary = \"\";\n\n for (const byte of bytes)\n binary += String.fromCharCode(byte);\n\n return btoa(binary);\n\n}\n\nfunction base64ToBytes(value: string): Uint8Array {\n\n const binary = atob(value);\n const bytes = new Uint8Array(binary.length);\n\n for (let index = 0; index < binary.length; index++)\n bytes[index] = binary.charCodeAt(index);\n\n return bytes;\n\n}\n\n// The keyed hash of an origin: the salt is the key, the origin the message.\n// The salt is no secret - it sits right next to the hash - its job is to make\n// precomputation and cross-entry correlation impossible, not to hide.\nfunction hashOrigin(algorithm: string,\n saltBytes: Uint8Array,\n origin: string): Uint8Array | null {\n\n // Own properties only: the algorithm string comes from a stored entry, and\n // \"__proto__\" or \"toString\" must be an unknown algorithm, not an inherited\n // object that slips past the check below.\n const suite = Object.hasOwn(trustHashAlgorithms, algorithm)\n ? trustHashAlgorithms[algorithm]\n : undefined;\n\n if (suite === undefined)\n return null;\n\n return hmac(suite.hash, saltBytes, new TextEncoder().encode(origin));\n\n}\n\n/** Whether this entry is the remembered decision for the given origin. */\nexport function matchesTrustedOrigin(entry: ITrustedOrigin,\n origin: string): boolean {\n\n try\n {\n\n const expected = base64ToBytes(entry.hash);\n const computed = hashOrigin(entry.algorithm, base64ToBytes(entry.salt), origin);\n\n if (computed?.length !== expected.length)\n return false;\n\n // Compared without an early exit; in this setting timing hardly\n // matters, but a comparison of hashes should simply look like this.\n let difference = 0;\n\n for (let index = 0; index < computed.length; index++)\n difference |= (computed[index] ?? 0) ^ (expected[index] ?? 0);\n\n return difference === 0;\n\n }\n catch\n {\n // Unparsable base64 is an entry that matches nothing.\n return false;\n }\n\n}\n\n//#endregion\n\n/** The remembered decision for an origin, when there is one. */\nexport function findTrustedOrigin(store: ITrustedOriginsStore,\n origin: string): ITrustedOrigin | undefined {\n return store.origins.find(entry => matchesTrustedOrigin(entry, origin));\n}\n\n/**\n * Remembers a decision for an origin, replacing whatever was remembered\n * before. The entry gets a fresh salt on every write; when the decision\n * itself has not changed, its original date is kept, so reconsidering\n * without changing anything does not reset \"trusted since\".\n * Returns the entry as written.\n */\nexport function upsertTrustedOrigin(store: ITrustedOriginsStore,\n origin: string,\n decision: TrustDecision,\n label: string,\n nowISO: string): ITrustedOrigin {\n\n const existing = findTrustedOrigin(store, origin);\n const since = existing?.decision === decision && existing.since !== \"\"\n ? existing.since\n : nowISO;\n\n store.origins = store.origins.filter(entry => !matchesTrustedOrigin(entry, origin));\n\n const suite = trustHashAlgorithms[currentTrustHashAlgorithm];\n const saltBytes = crypto.getRandomValues(new Uint8Array(suite?.saltLength ?? 32));\n const hashBytes = hashOrigin(currentTrustHashAlgorithm, saltBytes, origin);\n\n if (hashBytes === null)\n throw new Error(\"The current trust hash algorithm is unknown to itself!\");\n\n const entry: ITrustedOrigin = {\n algorithm: currentTrustHashAlgorithm,\n salt: bytesToBase64(saltBytes),\n hash: bytesToBase64(hashBytes),\n label: sanitizeTrustLabel(label),\n decision: decision,\n since: since,\n lastUsed: nowISO\n };\n\n store.origins.push(entry);\n\n return entry;\n\n}\n\n/**\n * How much newer a use has to be before it is worth persisting: the expiry is\n * measured in months, so refreshing lastUsed more often than hourly would be\n * pure storage churn for a live link that reloads every few seconds.\n */\nexport const lastUsedGranularityMs = 60 * 60 * 1000;\n\n/**\n * Records that the remembered decision for this origin was actually applied -\n * an allowed origin polled, a denied one blocked. Every use restarts the idle\n * expiry clock. Returns whether anything changed and is worth saving.\n */\nexport function touchTrustedOrigin(store: ITrustedOriginsStore,\n origin: string,\n now: Date): boolean {\n\n const entry = findTrustedOrigin(store, origin);\n\n if (entry === undefined)\n return false;\n\n const lastUsed = new Date(entry.lastUsed);\n\n if (!Number.isNaN(lastUsed.valueOf()) &&\n now.valueOf() - lastUsed.valueOf() < lastUsedGranularityMs)\n {\n return false;\n }\n\n entry.lastUsed = now.toISOString();\n\n return true;\n\n}\n\n/** Forgets the remembered decision for an origin. Returns whether one existed. */\nexport function removeTrustedOrigin(store: ITrustedOriginsStore,\n origin: string): boolean {\n\n const before = store.origins.length;\n store.origins = store.origins.filter(entry => !matchesTrustedOrigin(entry, origin));\n\n return store.origins.length !== before;\n\n}\n\n/**\n * The label an entry is shown under: the operator name the user saw when\n * consenting. Document text from outside, so control and format characters -\n * newlines, zero-width characters, bidi overrides - are stripped, the rest is\n * trimmed and capped. Rendering must additionally treat it as text, never as\n * markup.\n */\nexport function sanitizeTrustLabel(value: unknown): string {\n\n if (typeof value !== \"string\")\n return \"\";\n\n return value.replace(/[\\p{Cc}\\p{Cf}]/gu, \"\").trim().substring(0, 100);\n\n}\n\n/**\n * The label to actually store for a given origin. A label that contains the\n * origin's host would smuggle the very plaintext back into storage that the\n * hashing keeps out, so such a label is dropped - the entry then shows as an\n * unknown operator, which is the honest price of a hostname-shaped name.\n */\nexport function trustLabelForOrigin(label: string,\n origin: string): string {\n\n try\n {\n\n const hostname = new URL(origin).hostname.toLowerCase();\n\n if (hostname !== \"\" && label.toLowerCase().includes(hostname))\n return \"\";\n\n }\n catch\n {\n // An unparsable origin is never stored anyway.\n }\n\n return label;\n\n}\n\n/**\n * The retention setting, tolerantly: null means \"keep indefinitely\", numbers\n * are clamped into [1, 120] months, and anything unusable falls back to the\n * default rather than to \"keep forever\".\n */\nexport function sanitizeRetentionMonths(value: unknown): number | null {\n\n if (value === null)\n return null;\n\n if (typeof value === \"number\" && Number.isFinite(value))\n return Math.min(Math.max(Math.round(value), minimumRetentionMonths), maximumRetentionMonths);\n\n return defaultRetentionMonths;\n\n}\n\n/**\n * When an entry expires, or null when decisions are kept indefinitely.\n * Measured from the last use, not from the decision: using a decision\n * restarts its clock, so only what lies unused actually runs out.\n */\nexport function trustedOriginExpiry(entry: ITrustedOrigin,\n retentionMonths: number | null): Date | null {\n\n if (retentionMonths === null)\n return null;\n\n const since = new Date(entry.lastUsed !== \"\" ? entry.lastUsed : entry.since);\n\n if (Number.isNaN(since.valueOf()))\n return null;\n\n // Calendar months, without JavaScript's day overflow: a decision from\n // August 31st plus six months expires on February 28th, not on March 3rd\n // via a \"February 31st\" that never existed.\n const expiry = new Date(since);\n const dayOfMonth = expiry.getUTCDate();\n\n expiry.setUTCDate(1);\n expiry.setUTCMonth(expiry.getUTCMonth() + retentionMonths);\n\n const daysInMonth = new Date(Date.UTC(expiry.getUTCFullYear(), expiry.getUTCMonth() + 1, 0)).getUTCDate();\n\n expiry.setUTCDate(Math.min(dayOfMonth, daysInMonth));\n\n return expiry;\n\n}\n\n/**\n * Drops every entry whose time is up. An entry whose date cannot be read\n * counts as expired rather than immortal: with retention active, nothing may\n * be un-forgettable. Returns whether anything changed.\n */\nexport function pruneExpiredTrustedOrigins(store: ITrustedOriginsStore,\n now: Date): boolean {\n\n if (store.retentionMonths === null)\n return false;\n\n const before = store.origins.length;\n\n store.origins = store.origins.filter(entry => {\n const expiry = trustedOriginExpiry(entry, store.retentionMonths);\n return expiry !== null && now.valueOf() < expiry.valueOf();\n });\n\n return store.origins.length !== before;\n\n}\n\nexport function emptyTrustedOriginsStore(): ITrustedOriginsStore {\n return { retentionMonths: defaultRetentionMonths, origins: [] };\n}\n\n/**\n * The stored decisions, tolerantly: anything that is not exactly an entry with\n * a salt, a hash, an algorithm and a valid decision is dropped rather than\n * trusted by accident, and a store that cannot be parsed at all counts as\n * empty - the user is simply asked again. Entries with an algorithm this\n * version does not know are kept: they never match here, but a newer version\n * may still understand them.\n */\nexport function parseTrustedOriginsStore(json: string | null): ITrustedOriginsStore {\n\n const store = emptyTrustedOriginsStore();\n\n if (json == null || json === \"\")\n return store;\n\n let parsed: unknown;\n\n try\n {\n parsed = JSON.parse(json);\n }\n catch\n {\n return store;\n }\n\n if (parsed === null || typeof parsed !== \"object\" || Array.isArray(parsed))\n return store;\n\n const parsedStore = parsed as Record<string, unknown>;\n store.retentionMonths = sanitizeRetentionMonths(parsedStore[\"retentionMonths\"]);\n\n const origins = parsedStore[\"origins\"];\n\n if (!Array.isArray(origins))\n return store;\n\n for (const candidate of origins)\n {\n\n if (candidate === null || typeof candidate !== \"object\")\n continue;\n\n const entry = candidate as Record<string, unknown>;\n const algorithm = entry[\"algorithm\"];\n const salt = entry[\"salt\"];\n const hash = entry[\"hash\"];\n const decision = entry[\"decision\"];\n const since = entry[\"since\"];\n\n if (typeof algorithm !== \"string\" || algorithm === \"\" ||\n typeof salt !== \"string\" || salt === \"\" ||\n typeof hash !== \"string\" || hash === \"\")\n {\n continue;\n }\n\n if (decision !== \"allow\" && decision !== \"deny\")\n continue;\n\n const sinceText = typeof since === \"string\" ? since : \"\";\n const lastUsed = entry[\"lastUsed\"];\n\n store.origins.push({\n algorithm: algorithm,\n salt: salt,\n hash: hash,\n label: sanitizeTrustLabel(entry[\"label\"]),\n decision: decision,\n since: sinceText,\n // An entry that never recorded a use counts as used when it was\n // decided - the least surprising reading, and the one that keeps\n // it prunable.\n lastUsed: typeof lastUsed === \"string\" && lastUsed !== \"\" ? lastUsed : sinceText\n });\n\n }\n\n return store;\n\n}\n\nexport function serializeTrustedOriginsStore(store: ITrustedOriginsStore): string {\n return JSON.stringify(store);\n}\n\n//#endregion\n\n//#region The structural rules\n\nfunction ipv4Octets(hostname: string): number[] | null {\n\n const match = /^(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})$/.exec(hostname);\n\n if (match === null)\n return null;\n\n const octets = match.slice(1).map(Number);\n\n return octets.every(octet => octet <= 255)\n ? octets\n : null;\n\n}\n\n/**\n * The dotted-quad an IPv4-carrying IPv6 literal embeds, or null.\n *\n * An IPv4 address hidden inside IPv6 still reaches the same IPv4 host at the\n * socket layer, so it has to be classified as that host, not waved through as\n * an opaque IPv6 address. The WHATWG URL parser serializes the embedded IPv4\n * in hex - \"[::ffff:127.0.0.1]\" arrives here as \"[::ffff:7f00:1]\" - so the two\n * trailing hextets are decoded back into octets. Covered forms: IPv4-mapped\n * (::ffff:0:0/96), the deprecated IPv4-compatible (::/96) and NAT64\n * (64:ff9b::/96).\n */\nfunction embeddedIPv4(hostname: string): number[] | null {\n\n if (!hostname.startsWith(\"[\") || !hostname.endsWith(\"]\"))\n return null;\n\n const address = hostname.slice(1, -1).toLowerCase();\n\n // A dotted tail can survive when the leading field is non-zero; take it.\n const dotted = /:((?:\\d{1,3}\\.){3}\\d{1,3})$/.exec(address);\n\n if (dotted !== null)\n return ipv4Octets(dotted[1] as string);\n\n const hex = /^(?:::ffff:|::|64:ff9b::)([0-9a-f]{1,4}):([0-9a-f]{1,4})$/.exec(address);\n\n if (hex === null)\n return null;\n\n const high = parseInt(hex[1] as string, 16);\n const low = parseInt(hex[2] as string, 16);\n\n return [ (high >> 8) & 0xff, high & 0xff, (low >> 8) & 0xff, low & 0xff ];\n\n}\n\n/** The host of the machine itself. The WHATWG URL parser has already\n * normalized IPv4 notations, so \"127.1\" arrives here as \"127.0.0.1\". */\nexport function isLoopbackHost(hostname: string): boolean {\n\n const host = hostname.toLowerCase();\n\n if (host === \"localhost\" || host.endsWith(\".localhost\"))\n return true;\n\n if (host === \"[::1]\" || host === \"::1\" || host === \"0.0.0.0\")\n return true;\n\n const octets = ipv4Octets(host) ?? embeddedIPv4(host);\n\n return octets !== null && octets[0] === 127;\n\n}\n\n/**\n * A host that is not on the public internet: loopback, RFC 1918, link-local\n * and IPv6 unique-local addresses. A public web application must not let a\n * document turn the user's browser into a probe for the network behind their\n * router.\n */\nexport function isPrivateNetworkHost(hostname: string): boolean {\n\n if (isLoopbackHost(hostname))\n return true;\n\n const host = hostname.toLowerCase();\n const octets = ipv4Octets(host) ?? embeddedIPv4(host);\n\n if (octets !== null)\n {\n\n const [ first, second ] = octets as [ number, number, number, number ];\n\n return first === 10 ||\n (first === 172 && second >= 16 && second <= 31) ||\n (first === 192 && second === 168) ||\n (first === 169 && second === 254);\n\n }\n\n if (host.startsWith(\"[\") && host.endsWith(\"]\"))\n {\n\n const address = host.slice(1, -1);\n\n // fc00::/7 (unique local) and fe80::/10 (link local).\n return address.startsWith(\"fc\") ||\n address.startsWith(\"fd\") ||\n address.startsWith(\"fe8\") ||\n address.startsWith(\"fe9\") ||\n address.startsWith(\"fea\") ||\n address.startsWith(\"feb\");\n\n }\n\n return false;\n\n}\n\n/**\n * What a build allows beyond the rules that hold everywhere. Both are off\n * unless a development build was explicitly told to allow them - the defaults\n * here say so, so a caller that passes nothing gets the strict rules.\n *\n * The values come from compile-time constants (see buildFlags.ts), never from\n * the document, a setting or anything else a user could be talked into\n * changing. They are passed in rather than read here so that this module stays\n * a set of plain functions, and so that both answers can be tested.\n */\nexport interface ITransportAllowances {\n\n /** Whether http:// and ws:// URLs may be used at all. */\n insecureTransports?: boolean;\n\n /** Whether hosts on the local network may be reached. */\n privateNetworkTransports?: boolean;\n\n}\n\n/**\n * Why this URL's scheme must not be used, or null if it may be.\n *\n * Encrypted schemes - https and wss - are always fine, their plaintext\n * counterparts only in a build that was told to allow them, and everything\n * else never. This is the rule that no trust decision may waive: what a\n * consent tier can decide is whether an origin may be asked at all, not\n * whether a request may travel in the clear, so it is asked before the tiers\n * rather than after them.\n *\n * ws and wss are listed although nothing here opens a websocket yet: the rule\n * belongs to the scheme, not to the code that happens to exist.\n *\n * An application served from loopback is a developer's, and a developer talks\n * to their own machine: for them the rule is waived, as the others are.\n */\nexport function transportProtocolProblem(url: URL,\n appIsLoopback: boolean,\n allowances: ITransportAllowances = {}): string | null {\n\n if (appIsLoopback && isLoopbackHost(url.hostname))\n return null;\n\n if (url.protocol === \"https:\" || url.protocol === \"wss:\")\n return null;\n\n if (url.protocol === \"http:\" || url.protocol === \"ws:\")\n {\n return allowances.insecureTransports === true\n ? null\n : \"unencrypted \" + url.protocol.replace(\":\", \"\") + \" is used only by a build that allows it\";\n }\n\n return \"only encrypted transports are used, not \" + url.protocol.replace(\":\", \"\");\n\n}\n\n/**\n * Why this URL must not be polled, or null if it may be - subject to the\n * user's consent, which is the next gate, not this one.\n *\n * An application served from loopback is a developer's, and a developer polls\n * their own machine: for them every rule is waived.\n */\nexport function pollTargetProblem(url: URL,\n appIsLoopback: boolean,\n allowances: ITransportAllowances = {}): string | null {\n\n const protocolProblem = transportProtocolProblem(url, appIsLoopback, allowances);\n\n if (protocolProblem !== null)\n return protocolProblem;\n\n if (appIsLoopback && isLoopbackHost(url.hostname))\n return null;\n\n // A poll is an http request. A scheme another transport may use is\n // therefore still not one to ask over.\n if (url.protocol !== \"https:\" && url.protocol !== \"http:\")\n return \"a poll asks over https, not \" + url.protocol.replace(\":\", \"\");\n\n if (isPrivateNetworkHost(url.hostname) &&\n allowances.privateNetworkTransports !== true)\n {\n return \"the host is not on the public internet\";\n }\n\n return null;\n\n}\n\n//#endregion\n\n"]}
@@ -0,0 +1,38 @@
1
+ import type { Chargy, IChargingSession, ChargyInterfaces } from '@open-charging-cloud/chargy-core';
2
+ import type { SessionPriceVerification } from '@open-charging-cloud/wwcp-poi';
3
+ import type { SessionPOIEvidence } from './sessionPOIData.js';
4
+ import type { POITrustService } from './poiTrustContext.js';
5
+ export interface LivePOIState {
6
+ readonly id: string;
7
+ readonly evseId: string;
8
+ readonly meterSerialNumber: string;
9
+ readonly originals: readonly string[];
10
+ readonly readingCount: number;
11
+ readonly priceChanged: boolean;
12
+ readonly authorityProofs: readonly (string | undefined)[];
13
+ evidence: readonly SessionPOIEvidence[];
14
+ policyId: string;
15
+ /** Remembers the selected fixed version, never an authorization lease. */
16
+ pricePinned: boolean;
17
+ expectedHistoryGeneration?: string;
18
+ }
19
+ export interface LivePOICheck {
20
+ readonly stage: 'waiting' | 'start' | 'charging' | 'complete';
21
+ readonly readingCount: number;
22
+ readonly price?: SessionPriceVerification;
23
+ readonly cpo: {
24
+ readonly operatorId: string;
25
+ readonly documents: number;
26
+ readonly keyIds: readonly string[];
27
+ };
28
+ }
29
+ export declare function originalLiveInput(input: string | ChargyInterfaces.IFileInfo | readonly ChargyInterfaces.IFileInfo[]): string | undefined;
30
+ /** Retain equivocation even when continuity rejects the candidate before meter parsing. Never advance the accepted live head. */
31
+ export declare function observeRejectedLiveCandidate(service: POITrustService, state: LivePOIState, text: string, signal: AbortSignal): Promise<void>;
32
+ /** Merge evidence by field. An omitted block never removes the selected original fixed-price evidence. */
33
+ export declare function prepareLivePOIState(text: string, incoming: readonly SessionPOIEvidence[], previous?: LivePOIState, now?: number): LivePOIState;
34
+ /** UI/download orchestration only; the shared libraries authenticate every original document and price. */
35
+ export declare function checkLivePOISession(chargy: Chargy, service: POITrustService, state: LivePOIState, session: IChargingSession | undefined, signal: AbortSignal): Promise<LivePOICheck>;
36
+ /** Restore public evidence and revalidate the original chain; local key permission is supplied afresh by the caller. */
37
+ export declare function restoreObservedLive(originals: readonly string[], evidenceText: string, policyId: string): LivePOIState;
38
+ //# sourceMappingURL=livePOISession.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"livePOISession.d.ts","sourceRoot":"","sources":["../src/livePOISession.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAC,MAAM,EAAC,gBAAgB,EAAC,gBAAgB,EAAC,MAAM,kCAAkC,CAAC;AAE/F,OAAO,KAAK,EAAoB,wBAAwB,EAAC,MAAM,+BAA+B,CAAC;AAC/F,OAAO,KAAK,EAAC,kBAAkB,EAAC,MAAM,qBAAqB,CAAC;AAG5D,OAAO,KAAK,EAAC,eAAe,EAAC,MAAM,sBAAsB,CAAC;AAE1D,MAAM,WAAW,YAAY;IACzB,QAAQ,CAAC,EAAE,EAAC,MAAM,CAAC;IAAA,QAAQ,CAAC,MAAM,EAAC,MAAM,CAAC;IAAA,QAAQ,CAAC,iBAAiB,EAAC,MAAM,CAAC;IAC5E,QAAQ,CAAC,SAAS,EAAC,SAAS,MAAM,EAAE,CAAC;IAAA,QAAQ,CAAC,YAAY,EAAC,MAAM,CAAC;IAAA,QAAQ,CAAC,YAAY,EAAC,OAAO,CAAC;IAChG,QAAQ,CAAC,eAAe,EAAC,SAAS,CAAC,MAAM,GAAC,SAAS,CAAC,EAAE,CAAC;IACvD,QAAQ,EAAC,SAAS,kBAAkB,EAAE,CAA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