@calimero-network/mero-react 9.3.0 → 9.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs +1020 -699
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +136 -8
- package/dist/index.d.ts +136 -8
- package/dist/index.js +1018 -701
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { createContext, useMemo, useState, useRef, useCallback, useEffect, useContext } from 'react';
|
|
2
|
-
import { LocalStorageTokenStore, parseAuthCallback, MeroJs, buildAuthLoginUrl, DEFAULT_LOCAL_NODE_PORTS, discoverLocalNodes, nodeEndpoint, readEnrolmentCallback, completeDeviceEnrolment,
|
|
2
|
+
import { signGroupInvitation, signMemberJoinOp, CloudClient, LocalStorageTokenStore, parseAuthCallback, MeroJs, buildAuthLoginUrl, DEFAULT_LOCAL_NODE_PORTS, discoverLocalNodes, nodeEndpoint, readEnrolmentCallback, completeDeviceEnrolment, deviceEnrolmentUrl, memberJoinedOpenOp, signerFromSecret, groupDeletedOp, memberAddedOp, memberRemovedOp, subgroupCreation, memberRoleSetOp, defaultCapabilitiesSetOp, subgroupVisibilitySetOp, groupMetadataSetOp, memberMetadataSetOp, contextMetadataSetOp, groupReparentedOp, contextDetachedOp, compareSemver, AuthRevokedError, HTTPError, memberLeftOp, memberCapabilitySetOp, attestRelayNodeKey, createMeroClient, RelayClient, createLocalStorageNonceSource, classifyError, login, defaultAudience, createSignedReleaseVerifier, fetchNodeRelease, cloudNodeReleaseUrl, DEFAULT_RELEASE_MIRROR, fetchNodeReleaseVersion } from '@calimero-network/mero-js';
|
|
3
3
|
export * from '@calimero-network/mero-js';
|
|
4
4
|
export { CAPABILITIES, DEFAULT_LOCAL_NODE_PORTS, discoverLocalNodes, hasCap, localNodeUrl, nodeEndpoint, probeNodeHealth, withCap, withoutCap } from '@calimero-network/mero-js';
|
|
5
5
|
import { jsx, jsxs, Fragment } from 'react/jsx-runtime';
|
|
@@ -44,242 +44,6 @@ var ConnectionType = /* @__PURE__ */ ((ConnectionType2) => {
|
|
|
44
44
|
ConnectionType2["Custom"] = "custom";
|
|
45
45
|
return ConnectionType2;
|
|
46
46
|
})(ConnectionType || {});
|
|
47
|
-
|
|
48
|
-
// src/auth/node-trust.ts
|
|
49
|
-
function sameOrigin(a, b) {
|
|
50
|
-
try {
|
|
51
|
-
return new URL(a).origin === new URL(b).origin;
|
|
52
|
-
} catch {
|
|
53
|
-
return false;
|
|
54
|
-
}
|
|
55
|
-
}
|
|
56
|
-
function resolveTrustedNodeUrl(params) {
|
|
57
|
-
const { candidate, initiated, allowedNodeUrls } = params;
|
|
58
|
-
if (!candidate) {
|
|
59
|
-
return { url: initiated ?? null, rejected: false };
|
|
60
|
-
}
|
|
61
|
-
if (initiated) {
|
|
62
|
-
return sameOrigin(candidate, initiated) ? { url: candidate, rejected: false } : { url: null, rejected: true };
|
|
63
|
-
}
|
|
64
|
-
if (allowedNodeUrls && allowedNodeUrls.length > 0) {
|
|
65
|
-
return allowedNodeUrls.some((u) => sameOrigin(candidate, u)) ? { url: candidate, rejected: false } : { url: null, rejected: true };
|
|
66
|
-
}
|
|
67
|
-
return { url: null, rejected: true };
|
|
68
|
-
}
|
|
69
|
-
|
|
70
|
-
// src/auth/token-adoption.ts
|
|
71
|
-
var HOUR_MS = 36e5;
|
|
72
|
-
function decodeJwtClaims(token) {
|
|
73
|
-
try {
|
|
74
|
-
const parts = token.split(".");
|
|
75
|
-
if (parts.length !== 3) return null;
|
|
76
|
-
let b64 = parts[1].replace(/-/g, "+").replace(/_/g, "/");
|
|
77
|
-
while (b64.length % 4) b64 += "=";
|
|
78
|
-
const payload = JSON.parse(atob(b64));
|
|
79
|
-
if (!payload || typeof payload !== "object") return null;
|
|
80
|
-
const { iat, exp } = payload;
|
|
81
|
-
return {
|
|
82
|
-
iat: typeof iat === "number" && iat > 0 ? iat : void 0,
|
|
83
|
-
exp: typeof exp === "number" && exp > 0 ? exp : void 0
|
|
84
|
-
};
|
|
85
|
-
} catch {
|
|
86
|
-
return null;
|
|
87
|
-
}
|
|
88
|
-
}
|
|
89
|
-
function expiresAtFromJwt(token, fallbackMs = Date.now() + HOUR_MS) {
|
|
90
|
-
const exp = decodeJwtClaims(token)?.exp;
|
|
91
|
-
return exp ? exp * 1e3 : fallbackMs;
|
|
92
|
-
}
|
|
93
|
-
function isCallbackNewer(callbackAccessToken, stored) {
|
|
94
|
-
const incoming = decodeJwtClaims(callbackAccessToken);
|
|
95
|
-
if (!incoming) return false;
|
|
96
|
-
const current = decodeJwtClaims(stored.access_token);
|
|
97
|
-
if (current) {
|
|
98
|
-
if (incoming.iat !== void 0 && current.iat !== void 0 && incoming.iat !== current.iat) {
|
|
99
|
-
return incoming.iat > current.iat;
|
|
100
|
-
}
|
|
101
|
-
if (incoming.exp !== void 0 && current.exp !== void 0 && incoming.exp !== current.exp) {
|
|
102
|
-
return incoming.exp > current.exp;
|
|
103
|
-
}
|
|
104
|
-
return false;
|
|
105
|
-
}
|
|
106
|
-
return incoming.exp !== void 0 && incoming.exp * 1e3 > stored.expires_at;
|
|
107
|
-
}
|
|
108
|
-
function resolveTokenAdoption(params) {
|
|
109
|
-
const { callbackAccessToken, callbackRefreshToken, callbackNodeUrl, stored, storedNodeUrl } = params;
|
|
110
|
-
const bundle = (refreshToken2) => ({
|
|
111
|
-
access_token: callbackAccessToken,
|
|
112
|
-
refresh_token: refreshToken2,
|
|
113
|
-
expires_at: expiresAtFromJwt(callbackAccessToken)
|
|
114
|
-
});
|
|
115
|
-
if (!stored?.access_token) {
|
|
116
|
-
return { adopt: true, tokens: bundle(callbackRefreshToken), reason: "fresh-login" };
|
|
117
|
-
}
|
|
118
|
-
const sameNode = !!storedNodeUrl && sameOrigin(callbackNodeUrl, storedNodeUrl);
|
|
119
|
-
if (!sameNode) {
|
|
120
|
-
return { adopt: true, tokens: bundle(callbackRefreshToken), reason: "node-changed" };
|
|
121
|
-
}
|
|
122
|
-
const refreshToken = callbackRefreshToken || stored.refresh_token;
|
|
123
|
-
if (isCallbackNewer(callbackAccessToken, stored)) {
|
|
124
|
-
return { adopt: true, tokens: bundle(refreshToken), reason: "newer" };
|
|
125
|
-
}
|
|
126
|
-
if (!stored.refresh_token && callbackRefreshToken) {
|
|
127
|
-
return {
|
|
128
|
-
adopt: true,
|
|
129
|
-
tokens: { ...stored, refresh_token: callbackRefreshToken },
|
|
130
|
-
reason: "fill-refresh"
|
|
131
|
-
};
|
|
132
|
-
}
|
|
133
|
-
return { adopt: false, reason: "stale" };
|
|
134
|
-
}
|
|
135
|
-
|
|
136
|
-
// src/storage/index.ts
|
|
137
|
-
var STORAGE_KEYS = {
|
|
138
|
-
ACCESS_TOKEN: "mero:access_token",
|
|
139
|
-
REFRESH_TOKEN: "mero:refresh_token",
|
|
140
|
-
EXPIRES_AT: "mero:expires_at",
|
|
141
|
-
NODE_URL: "mero:node_url",
|
|
142
|
-
// The node the token bundle currently in the TokenStore was issued by. Distinct
|
|
143
|
-
// from NODE_URL, which `connectToNode` overwrites with the *target* node before
|
|
144
|
-
// redirecting to login — so at callback time NODE_URL names where we are going,
|
|
145
|
-
// not who minted the tokens we still hold. Telling those apart is what lets the
|
|
146
|
-
// SSO callback re-seed on a node change without mistaking a different node's
|
|
147
|
-
// bundle for a rotated one (see auth/token-adoption.ts).
|
|
148
|
-
TOKEN_NODE_URL: "mero:token_node_url",
|
|
149
|
-
APPLICATION_ID: "mero:application_id",
|
|
150
|
-
CONTEXT_ID: "mero:context_id",
|
|
151
|
-
CONTEXT_IDENTITY: "mero:context_identity"
|
|
152
|
-
};
|
|
153
|
-
var _storageAvailable = null;
|
|
154
|
-
function isLocalStorageAvailable() {
|
|
155
|
-
if (_storageAvailable !== null) return _storageAvailable;
|
|
156
|
-
try {
|
|
157
|
-
if (typeof window === "undefined" || !window.localStorage) {
|
|
158
|
-
_storageAvailable = false;
|
|
159
|
-
return false;
|
|
160
|
-
}
|
|
161
|
-
const testKey = "__mero_test__";
|
|
162
|
-
localStorage.setItem(testKey, "test");
|
|
163
|
-
localStorage.removeItem(testKey);
|
|
164
|
-
_storageAvailable = true;
|
|
165
|
-
} catch {
|
|
166
|
-
_storageAvailable = false;
|
|
167
|
-
}
|
|
168
|
-
return _storageAvailable;
|
|
169
|
-
}
|
|
170
|
-
var localStorageTokenStorage = {
|
|
171
|
-
async get() {
|
|
172
|
-
if (!isLocalStorageAvailable()) {
|
|
173
|
-
return null;
|
|
174
|
-
}
|
|
175
|
-
try {
|
|
176
|
-
const accessToken = localStorage.getItem(STORAGE_KEYS.ACCESS_TOKEN);
|
|
177
|
-
const refreshToken = localStorage.getItem(STORAGE_KEYS.REFRESH_TOKEN);
|
|
178
|
-
const expiresAt = localStorage.getItem(STORAGE_KEYS.EXPIRES_AT);
|
|
179
|
-
if (!accessToken || !refreshToken) {
|
|
180
|
-
return null;
|
|
181
|
-
}
|
|
182
|
-
return {
|
|
183
|
-
access_token: accessToken,
|
|
184
|
-
refresh_token: refreshToken,
|
|
185
|
-
expires_at: expiresAt ? parseInt(expiresAt, 10) : Date.now() + 36e5
|
|
186
|
-
};
|
|
187
|
-
} catch (e) {
|
|
188
|
-
console.error("[mero-react] Failed to get token from storage:", e);
|
|
189
|
-
return null;
|
|
190
|
-
}
|
|
191
|
-
},
|
|
192
|
-
async set(token) {
|
|
193
|
-
if (!isLocalStorageAvailable()) {
|
|
194
|
-
return;
|
|
195
|
-
}
|
|
196
|
-
try {
|
|
197
|
-
localStorage.setItem(STORAGE_KEYS.ACCESS_TOKEN, token.access_token);
|
|
198
|
-
localStorage.setItem(STORAGE_KEYS.REFRESH_TOKEN, token.refresh_token);
|
|
199
|
-
localStorage.setItem(STORAGE_KEYS.EXPIRES_AT, token.expires_at.toString());
|
|
200
|
-
} catch (e) {
|
|
201
|
-
console.error("[mero-react] Failed to save token to storage:", e);
|
|
202
|
-
}
|
|
203
|
-
},
|
|
204
|
-
async clear() {
|
|
205
|
-
if (!isLocalStorageAvailable()) {
|
|
206
|
-
return;
|
|
207
|
-
}
|
|
208
|
-
try {
|
|
209
|
-
localStorage.removeItem(STORAGE_KEYS.ACCESS_TOKEN);
|
|
210
|
-
localStorage.removeItem(STORAGE_KEYS.REFRESH_TOKEN);
|
|
211
|
-
localStorage.removeItem(STORAGE_KEYS.EXPIRES_AT);
|
|
212
|
-
} catch (e) {
|
|
213
|
-
console.error("[mero-react] Failed to clear token from storage:", e);
|
|
214
|
-
}
|
|
215
|
-
}
|
|
216
|
-
};
|
|
217
|
-
function getNodeUrl() {
|
|
218
|
-
if (!isLocalStorageAvailable()) return null;
|
|
219
|
-
return localStorage.getItem(STORAGE_KEYS.NODE_URL);
|
|
220
|
-
}
|
|
221
|
-
function setNodeUrl(url) {
|
|
222
|
-
if (!isLocalStorageAvailable()) return;
|
|
223
|
-
localStorage.setItem(STORAGE_KEYS.NODE_URL, url);
|
|
224
|
-
}
|
|
225
|
-
function clearNodeUrl() {
|
|
226
|
-
if (!isLocalStorageAvailable()) return;
|
|
227
|
-
localStorage.removeItem(STORAGE_KEYS.NODE_URL);
|
|
228
|
-
}
|
|
229
|
-
function getTokenNodeUrl() {
|
|
230
|
-
if (!isLocalStorageAvailable()) return null;
|
|
231
|
-
return localStorage.getItem(STORAGE_KEYS.TOKEN_NODE_URL);
|
|
232
|
-
}
|
|
233
|
-
function setTokenNodeUrl(url) {
|
|
234
|
-
if (!isLocalStorageAvailable()) return;
|
|
235
|
-
localStorage.setItem(STORAGE_KEYS.TOKEN_NODE_URL, url);
|
|
236
|
-
}
|
|
237
|
-
function clearTokenNodeUrl() {
|
|
238
|
-
if (!isLocalStorageAvailable()) return;
|
|
239
|
-
localStorage.removeItem(STORAGE_KEYS.TOKEN_NODE_URL);
|
|
240
|
-
}
|
|
241
|
-
function getApplicationId() {
|
|
242
|
-
if (!isLocalStorageAvailable()) return null;
|
|
243
|
-
return localStorage.getItem(STORAGE_KEYS.APPLICATION_ID);
|
|
244
|
-
}
|
|
245
|
-
function setApplicationId(id) {
|
|
246
|
-
if (!isLocalStorageAvailable()) return;
|
|
247
|
-
localStorage.setItem(STORAGE_KEYS.APPLICATION_ID, id);
|
|
248
|
-
}
|
|
249
|
-
function clearApplicationId() {
|
|
250
|
-
if (!isLocalStorageAvailable()) return;
|
|
251
|
-
localStorage.removeItem(STORAGE_KEYS.APPLICATION_ID);
|
|
252
|
-
}
|
|
253
|
-
function getContextId() {
|
|
254
|
-
if (!isLocalStorageAvailable()) return null;
|
|
255
|
-
return localStorage.getItem(STORAGE_KEYS.CONTEXT_ID);
|
|
256
|
-
}
|
|
257
|
-
function setContextId(id) {
|
|
258
|
-
if (!isLocalStorageAvailable()) return;
|
|
259
|
-
localStorage.setItem(STORAGE_KEYS.CONTEXT_ID, id);
|
|
260
|
-
}
|
|
261
|
-
function clearContextId() {
|
|
262
|
-
if (!isLocalStorageAvailable()) return;
|
|
263
|
-
localStorage.removeItem(STORAGE_KEYS.CONTEXT_ID);
|
|
264
|
-
}
|
|
265
|
-
function getContextIdentity() {
|
|
266
|
-
if (!isLocalStorageAvailable()) return null;
|
|
267
|
-
return localStorage.getItem(STORAGE_KEYS.CONTEXT_IDENTITY);
|
|
268
|
-
}
|
|
269
|
-
function setContextIdentity(id) {
|
|
270
|
-
if (!isLocalStorageAvailable()) return;
|
|
271
|
-
localStorage.setItem(STORAGE_KEYS.CONTEXT_IDENTITY, id);
|
|
272
|
-
}
|
|
273
|
-
function clearContextIdentity() {
|
|
274
|
-
if (!isLocalStorageAvailable()) return;
|
|
275
|
-
localStorage.removeItem(STORAGE_KEYS.CONTEXT_IDENTITY);
|
|
276
|
-
}
|
|
277
|
-
function clearAllStorage() {
|
|
278
|
-
if (!isLocalStorageAvailable()) return;
|
|
279
|
-
Object.values(STORAGE_KEYS).forEach((key) => {
|
|
280
|
-
localStorage.removeItem(key);
|
|
281
|
-
});
|
|
282
|
-
}
|
|
283
47
|
var KEY = "calimero.delegated.connection";
|
|
284
48
|
var CREDENTIAL_KEY = "calimero.delegated.credential";
|
|
285
49
|
function readDelegatedSession() {
|
|
@@ -332,13 +96,13 @@ function clearDelegatedCredential() {
|
|
|
332
96
|
} catch {
|
|
333
97
|
}
|
|
334
98
|
}
|
|
335
|
-
function persistedNonces(relayUrl
|
|
336
|
-
const key =
|
|
99
|
+
function persistedNonces(relayUrl) {
|
|
100
|
+
const key = nonceKey(relayUrl);
|
|
337
101
|
return {
|
|
338
102
|
next: async () => {
|
|
339
103
|
let n = 0n;
|
|
340
104
|
try {
|
|
341
|
-
n =
|
|
105
|
+
n = readNonceFloor(relayUrl);
|
|
342
106
|
} catch {
|
|
343
107
|
n = 0n;
|
|
344
108
|
}
|
|
@@ -350,11 +114,25 @@ function persistedNonces(relayUrl, contextId) {
|
|
|
350
114
|
}
|
|
351
115
|
};
|
|
352
116
|
}
|
|
353
|
-
function
|
|
354
|
-
|
|
117
|
+
function nonceKey(relayUrl) {
|
|
118
|
+
return `calimero.nonce.${relayUrl}`;
|
|
119
|
+
}
|
|
120
|
+
function readNonceFloor(relayUrl) {
|
|
121
|
+
const own = localStorage.getItem(nonceKey(relayUrl));
|
|
122
|
+
if (own !== null) return BigInt(own);
|
|
123
|
+
const legacy = `${nonceKey(relayUrl)}.`;
|
|
124
|
+
let max = 0n;
|
|
125
|
+
for (let i = 0; i < localStorage.length; i++) {
|
|
126
|
+
const k = localStorage.key(i);
|
|
127
|
+
if (!k?.startsWith(legacy)) continue;
|
|
128
|
+
const v = BigInt(localStorage.getItem(k) ?? "0");
|
|
129
|
+
if (v > max) max = v;
|
|
130
|
+
}
|
|
131
|
+
return max;
|
|
132
|
+
}
|
|
133
|
+
function markContextNonceSpent(relayUrl, _contextId, nonce) {
|
|
355
134
|
try {
|
|
356
|
-
|
|
357
|
-
if (current <= nonce) localStorage.setItem(key, String(nonce + 1n));
|
|
135
|
+
if (readNonceFloor(relayUrl) <= nonce) localStorage.setItem(nonceKey(relayUrl), String(nonce + 1n));
|
|
358
136
|
} catch {
|
|
359
137
|
}
|
|
360
138
|
}
|
|
@@ -454,7 +232,7 @@ function relaySession(s, nodeKey) {
|
|
|
454
232
|
return inflight;
|
|
455
233
|
};
|
|
456
234
|
}
|
|
457
|
-
function buildDelegatedClient(s,
|
|
235
|
+
function buildDelegatedClient(s, _contextId) {
|
|
458
236
|
if (!s.relayUrl) return null;
|
|
459
237
|
const nodeKey = readPinnedRelayNodeKey(s.relayUrl);
|
|
460
238
|
return createMeroClient({
|
|
@@ -464,10 +242,9 @@ function buildDelegatedClient(s, contextId) {
|
|
|
464
242
|
authorAccount: s.account,
|
|
465
243
|
authorProof: s.credential,
|
|
466
244
|
deviceSecret: s.deviceSecret,
|
|
467
|
-
//
|
|
468
|
-
//
|
|
469
|
-
|
|
470
|
-
nonces: persistedNonces(s.relayUrl, contextId)
|
|
245
|
+
// One sequence per relay, whatever context is chosen: `execute` takes a
|
|
246
|
+
// context per call, so the nonce source must not depend on this one.
|
|
247
|
+
nonces: persistedNonces(s.relayUrl)
|
|
471
248
|
},
|
|
472
249
|
// The certificate authenticates the requests too, not just the writes.
|
|
473
250
|
//
|
|
@@ -493,79 +270,940 @@ function buildDelegatedClient(s, contextId) {
|
|
|
493
270
|
observe: nodeKey ? { nodeKey } : void 0
|
|
494
271
|
});
|
|
495
272
|
}
|
|
496
|
-
var RELAY_MAP_PREFIX = "calimero.delegated.relays.";
|
|
497
|
-
function readRelayMap(account) {
|
|
498
|
-
try {
|
|
499
|
-
const raw = localStorage.getItem(RELAY_MAP_PREFIX + account);
|
|
500
|
-
const parsed = raw ? JSON.parse(raw) : {};
|
|
501
|
-
return { namespaces: parsed.namespaces ?? {}, contexts: parsed.contexts ?? {} };
|
|
502
|
-
} catch {
|
|
503
|
-
return { namespaces: {}, contexts: {} };
|
|
504
|
-
}
|
|
273
|
+
var RELAY_MAP_PREFIX = "calimero.delegated.relays.";
|
|
274
|
+
function readRelayMap(account) {
|
|
275
|
+
try {
|
|
276
|
+
const raw = localStorage.getItem(RELAY_MAP_PREFIX + account);
|
|
277
|
+
const parsed = raw ? JSON.parse(raw) : {};
|
|
278
|
+
return { namespaces: parsed.namespaces ?? {}, contexts: parsed.contexts ?? {} };
|
|
279
|
+
} catch {
|
|
280
|
+
return { namespaces: {}, contexts: {} };
|
|
281
|
+
}
|
|
282
|
+
}
|
|
283
|
+
function writeRelayMap(account, map) {
|
|
284
|
+
try {
|
|
285
|
+
localStorage.setItem(RELAY_MAP_PREFIX + account, JSON.stringify(map));
|
|
286
|
+
} catch {
|
|
287
|
+
}
|
|
288
|
+
}
|
|
289
|
+
function rememberRelay(account, relayUrl, at) {
|
|
290
|
+
const map = readRelayMap(account);
|
|
291
|
+
const url = relayOrigin(relayUrl);
|
|
292
|
+
if (at.namespaceId) map.namespaces[at.namespaceId] = url;
|
|
293
|
+
if (at.contextId) map.contexts[at.contextId] = url;
|
|
294
|
+
writeRelayMap(account, map);
|
|
295
|
+
}
|
|
296
|
+
function relayForContext(account, contextId) {
|
|
297
|
+
return readRelayMap(account).contexts[contextId] ?? null;
|
|
298
|
+
}
|
|
299
|
+
function knownRelays(s) {
|
|
300
|
+
const map = readRelayMap(s.account);
|
|
301
|
+
const all = [s.relayUrl, ...Object.values(map.namespaces), ...Object.values(map.contexts)].filter((u) => typeof u === "string" && u.length > 0).map(relayOrigin);
|
|
302
|
+
return [...new Set(all)];
|
|
303
|
+
}
|
|
304
|
+
async function listDelegatedContexts(s) {
|
|
305
|
+
const out = [];
|
|
306
|
+
const map = readRelayMap(s.account);
|
|
307
|
+
for (const relayUrl of knownRelays(s)) {
|
|
308
|
+
try {
|
|
309
|
+
if (!await resolveRelayNodeKey(relayUrl)) continue;
|
|
310
|
+
const client2 = buildDelegatedClient({ ...s, relayUrl }, null);
|
|
311
|
+
if (!client2) continue;
|
|
312
|
+
const { contexts } = await client2.admin.getContexts();
|
|
313
|
+
for (const c of contexts ?? []) {
|
|
314
|
+
out.push({ ...c, relayUrl });
|
|
315
|
+
map.contexts[c.id] = relayUrl;
|
|
316
|
+
}
|
|
317
|
+
} catch (e) {
|
|
318
|
+
console.warn(`[mero-react] could not list contexts on ${relayUrl}`, e);
|
|
319
|
+
}
|
|
320
|
+
}
|
|
321
|
+
writeRelayMap(s.account, map);
|
|
322
|
+
return out;
|
|
323
|
+
}
|
|
324
|
+
async function listDelegatedNamespaces(s) {
|
|
325
|
+
var _a, _b;
|
|
326
|
+
const out = [];
|
|
327
|
+
const seen = /* @__PURE__ */ new Set();
|
|
328
|
+
const map = readRelayMap(s.account);
|
|
329
|
+
for (const relayUrl of knownRelays(s)) {
|
|
330
|
+
try {
|
|
331
|
+
if (!await resolveRelayNodeKey(relayUrl)) continue;
|
|
332
|
+
const client2 = buildDelegatedClient({ ...s, relayUrl }, null);
|
|
333
|
+
if (!client2) continue;
|
|
334
|
+
for (const ns of await client2.admin.listNamespaces()) {
|
|
335
|
+
if (seen.has(ns.namespaceId)) continue;
|
|
336
|
+
seen.add(ns.namespaceId);
|
|
337
|
+
out.push({ ...ns, relayUrl });
|
|
338
|
+
(_a = map.namespaces)[_b = ns.namespaceId] ?? (_a[_b] = relayUrl);
|
|
339
|
+
}
|
|
340
|
+
} catch (e) {
|
|
341
|
+
console.warn(`[mero-react] could not list namespaces on ${relayUrl}`, e);
|
|
342
|
+
}
|
|
343
|
+
}
|
|
344
|
+
writeRelayMap(s.account, map);
|
|
345
|
+
return out;
|
|
346
|
+
}
|
|
347
|
+
|
|
348
|
+
// src/delegated/create-context.ts
|
|
349
|
+
function governanceNonce(relay, group) {
|
|
350
|
+
return { next: async () => nextGovernanceNonce(relay, group) };
|
|
351
|
+
}
|
|
352
|
+
function nextGovernanceNonce(relay, group) {
|
|
353
|
+
const key = `calimero.governance-nonce.${relay}.${group}`;
|
|
354
|
+
let last = 0n;
|
|
355
|
+
try {
|
|
356
|
+
last = BigInt(localStorage.getItem(key) ?? "0");
|
|
357
|
+
} catch {
|
|
358
|
+
}
|
|
359
|
+
const next = [last + 1n, BigInt(Date.now())].reduce((a, b) => a > b ? a : b);
|
|
360
|
+
try {
|
|
361
|
+
localStorage.setItem(key, String(next));
|
|
362
|
+
} catch {
|
|
363
|
+
}
|
|
364
|
+
return next;
|
|
365
|
+
}
|
|
366
|
+
function relayFor(s, namespaceId) {
|
|
367
|
+
const url = readRelayMap(s.account).namespaces[namespaceId] ?? s.relayUrl;
|
|
368
|
+
if (!url) throw new Error("no relay is known for this namespace, so there is nowhere to send this");
|
|
369
|
+
return url.replace(/\/+$/, "");
|
|
370
|
+
}
|
|
371
|
+
function initArgsOf(params) {
|
|
372
|
+
if (!params || params.length === 0) return {};
|
|
373
|
+
return JSON.parse(new TextDecoder().decode(Uint8Array.from(params)));
|
|
374
|
+
}
|
|
375
|
+
function client(s, relayUrl, nonces, fetch2) {
|
|
376
|
+
return new RelayClient({
|
|
377
|
+
relayUrl,
|
|
378
|
+
authorAccount: s.account,
|
|
379
|
+
authorProof: s.credential,
|
|
380
|
+
deviceSecret: s.deviceSecret,
|
|
381
|
+
nonces,
|
|
382
|
+
fetch: fetch2
|
|
383
|
+
});
|
|
384
|
+
}
|
|
385
|
+
async function createDelegatedContext(s, req, deps = {}) {
|
|
386
|
+
const relay = relayFor(s, req.namespaceId);
|
|
387
|
+
const creationNonce = 0n;
|
|
388
|
+
const created = await client(s, relay, { next: async () => creationNonce }, deps.fetch).createContext({
|
|
389
|
+
groupId: req.groupId ?? req.namespaceId,
|
|
390
|
+
applicationId: req.applicationId,
|
|
391
|
+
initArgs: initArgsOf(req.initializationParams),
|
|
392
|
+
name: req.name
|
|
393
|
+
});
|
|
394
|
+
markContextNonceSpent(relay, created.contextId, creationNonce);
|
|
395
|
+
rememberRelay(s.account, relay, { namespaceId: req.namespaceId, contextId: created.contextId });
|
|
396
|
+
return { contextId: created.contextId };
|
|
397
|
+
}
|
|
398
|
+
async function delegatedGovernance(s, req, deps = {}) {
|
|
399
|
+
const relay = relayFor(s, req.namespaceId);
|
|
400
|
+
return client(s, relay, governanceNonce(relay, req.group), deps.fetch).govern({ groupId: req.group, op: req.op });
|
|
401
|
+
}
|
|
402
|
+
async function createDelegatedPrivateContext(s, req, deps = {}) {
|
|
403
|
+
const { groupId } = await delegatedGovernance(
|
|
404
|
+
s,
|
|
405
|
+
{
|
|
406
|
+
namespaceId: req.namespaceId,
|
|
407
|
+
group: req.namespaceId,
|
|
408
|
+
// The id is derived from a fresh salt (core#4244); a node refuses any other.
|
|
409
|
+
op: (await subgroupCreation({ parentId: req.namespaceId, restricted: true, admin: s.account })).op
|
|
410
|
+
},
|
|
411
|
+
deps
|
|
412
|
+
);
|
|
413
|
+
for (const member of req.members) {
|
|
414
|
+
await delegatedGovernance(s, { namespaceId: req.namespaceId, group: groupId, op: memberAddedOp(member, "Member") }, deps);
|
|
415
|
+
}
|
|
416
|
+
const { contextId } = await createDelegatedContext(s, { ...req, groupId }, deps);
|
|
417
|
+
return { contextId, groupId };
|
|
418
|
+
}
|
|
419
|
+
async function foundDelegatedNamespace(s, req = {}, deps = {}) {
|
|
420
|
+
const relays = knownRelays(s).map((u) => u.replace(/\/+$/, ""));
|
|
421
|
+
const relay = relays[0];
|
|
422
|
+
if (!relay) throw new Error("no relay is known for this account, so there is nowhere to found a namespace");
|
|
423
|
+
const known = Object.entries(readRelayMap(s.account).namespaces).find(
|
|
424
|
+
([, url]) => url.replace(/\/+$/, "") === relay
|
|
425
|
+
)?.[0];
|
|
426
|
+
if (!known) {
|
|
427
|
+
throw new Error("join a namespace on this relay first: its executor account is learned from one you are in");
|
|
428
|
+
}
|
|
429
|
+
const { executorAccount } = await client(s, relay, governanceNonce(relay, known), deps.fetch).describeGovernance(known);
|
|
430
|
+
let next = BigInt(Date.now());
|
|
431
|
+
const founded = await client(s, relay, { next: async () => next++ }, deps.fetch).foundNamespace({
|
|
432
|
+
executorAccount,
|
|
433
|
+
...req.defaultCapabilities !== void 0 ? { defaultCapabilities: req.defaultCapabilities } : {},
|
|
434
|
+
...req.application ? { application: req.application } : {}
|
|
435
|
+
});
|
|
436
|
+
try {
|
|
437
|
+
localStorage.setItem(`calimero.governance-nonce.${relay}.${founded.namespaceId}`, String(next));
|
|
438
|
+
} catch {
|
|
439
|
+
}
|
|
440
|
+
rememberRelay(s.account, relay, { namespaceId: founded.namespaceId });
|
|
441
|
+
if (req.application && founded.applicationSet !== true) {
|
|
442
|
+
throw new Error(
|
|
443
|
+
`founded ${founded.namespaceId} but could not give it its application: ${founded.applicationError ?? "unknown reason"}`
|
|
444
|
+
);
|
|
445
|
+
}
|
|
446
|
+
return { namespaceId: founded.namespaceId, teeEnabled: founded.teeEnabled };
|
|
447
|
+
}
|
|
448
|
+
async function latestPublishedVersion(registryUrl, pkg, fetchFn = globalThis.fetch) {
|
|
449
|
+
const url = `${registryUrl.replace(/\/+$/, "")}/api/v2/bundles?package=${encodeURIComponent(pkg)}`;
|
|
450
|
+
const response = await fetchFn(url, { headers: { Accept: "application/json" } });
|
|
451
|
+
if (!response.ok) throw new Error(`the registry has no ${pkg} (HTTP ${response.status})`);
|
|
452
|
+
const bundles = await response.json();
|
|
453
|
+
const newer = (a, b) => {
|
|
454
|
+
const [x, y] = [a, b].map((v) => v.split(/[.-]/).map((n) => Number.parseInt(n, 10) || 0));
|
|
455
|
+
for (let i = 0; i < Math.max(x.length, y.length); i++) {
|
|
456
|
+
if ((x[i] ?? 0) !== (y[i] ?? 0)) return (x[i] ?? 0) > (y[i] ?? 0);
|
|
457
|
+
}
|
|
458
|
+
return false;
|
|
459
|
+
};
|
|
460
|
+
const latest = bundles.map((b) => b.appVersion).filter((v) => typeof v === "string" && v.length > 0).reduce((best, v) => !best || newer(v, best) ? v : best, void 0);
|
|
461
|
+
if (!latest) throw new Error(`the registry lists no version of ${pkg}`);
|
|
462
|
+
return latest;
|
|
463
|
+
}
|
|
464
|
+
|
|
465
|
+
// src/admin/node-admin.ts
|
|
466
|
+
function createNodeAdmin(input, deps = {}) {
|
|
467
|
+
const { admin, app } = input;
|
|
468
|
+
const latestVersion = deps.latestVersion ?? latestPublishedVersion;
|
|
469
|
+
async function ensureInstalled(applicationId) {
|
|
470
|
+
const { apps } = await admin.listApplications();
|
|
471
|
+
if (apps.some((a) => a.id === applicationId)) return;
|
|
472
|
+
if (!app.packageName) {
|
|
473
|
+
throw new Error(`application ${applicationId} is not installed on this node, and no packageName is set to install it`);
|
|
474
|
+
}
|
|
475
|
+
const version = app.packageVersion ?? await latestVersion(app.registryUrl ?? "https://apps.calimero.network", app.packageName);
|
|
476
|
+
const { applicationId: installed } = await admin.installApplication({ package: app.packageName, version });
|
|
477
|
+
if (installed !== applicationId) {
|
|
478
|
+
throw new Error(`installed ${app.packageName}@${version} as ${installed}, not ${applicationId}`);
|
|
479
|
+
}
|
|
480
|
+
}
|
|
481
|
+
const overrides = {
|
|
482
|
+
async createNamespace(req) {
|
|
483
|
+
await ensureInstalled(req.applicationId);
|
|
484
|
+
return admin.createNamespace(req);
|
|
485
|
+
}
|
|
486
|
+
};
|
|
487
|
+
return new Proxy(admin, {
|
|
488
|
+
get(target, prop, receiver) {
|
|
489
|
+
if (typeof prop === "string" && prop in overrides) return overrides[prop];
|
|
490
|
+
return Reflect.get(target, prop, receiver);
|
|
491
|
+
}
|
|
492
|
+
});
|
|
493
|
+
}
|
|
494
|
+
|
|
495
|
+
// src/delegated/govern.ts
|
|
496
|
+
var GROUP_NAMESPACE_PREFIX = "calimero.delegated.group-namespace.";
|
|
497
|
+
function readGroupNamespaces(account) {
|
|
498
|
+
try {
|
|
499
|
+
return JSON.parse(localStorage.getItem(GROUP_NAMESPACE_PREFIX + account) ?? "{}");
|
|
500
|
+
} catch {
|
|
501
|
+
return {};
|
|
502
|
+
}
|
|
503
|
+
}
|
|
504
|
+
function rememberGroupNamespace(account, groupId, namespaceId) {
|
|
505
|
+
try {
|
|
506
|
+
const all = readGroupNamespaces(account);
|
|
507
|
+
all[groupId] = namespaceId;
|
|
508
|
+
localStorage.setItem(GROUP_NAMESPACE_PREFIX + account, JSON.stringify(all));
|
|
509
|
+
} catch {
|
|
510
|
+
}
|
|
511
|
+
}
|
|
512
|
+
function namespaceOfGroup(s, groupId) {
|
|
513
|
+
if (readRelayMap(s.account).namespaces[groupId]) return groupId;
|
|
514
|
+
return readGroupNamespaces(s.account)[groupId];
|
|
515
|
+
}
|
|
516
|
+
function requireNamespace(s, groupId) {
|
|
517
|
+
const ns = namespaceOfGroup(s, groupId);
|
|
518
|
+
if (!ns) {
|
|
519
|
+
throw new Error(
|
|
520
|
+
`the namespace of group ${groupId} is not known to this account: it can manage only groups in namespaces it joined or subgroups it created`
|
|
521
|
+
);
|
|
522
|
+
}
|
|
523
|
+
return ns;
|
|
524
|
+
}
|
|
525
|
+
async function governGroup(s, groupId, op) {
|
|
526
|
+
return delegatedGovernance(s, { namespaceId: requireNamespace(s, groupId), group: groupId, op });
|
|
527
|
+
}
|
|
528
|
+
async function governRoot(s, groupId, op) {
|
|
529
|
+
const namespaceId = requireNamespace(s, groupId);
|
|
530
|
+
return delegatedGovernance(s, { namespaceId, group: namespaceId, op });
|
|
531
|
+
}
|
|
532
|
+
|
|
533
|
+
// src/delegated/account-admin.ts
|
|
534
|
+
var NotForAccountError = class extends Error {
|
|
535
|
+
constructor(method) {
|
|
536
|
+
super(`${method} is not available for an account: it needs a node`);
|
|
537
|
+
this.method = method;
|
|
538
|
+
this.name = "NotForAccountError";
|
|
539
|
+
}
|
|
540
|
+
};
|
|
541
|
+
var NoRelayError = class extends Error {
|
|
542
|
+
constructor(method) {
|
|
543
|
+
super(`${method} needs a relay, and this account has none yet: join from an invitation first`);
|
|
544
|
+
this.method = method;
|
|
545
|
+
this.name = "NoRelayError";
|
|
546
|
+
}
|
|
547
|
+
};
|
|
548
|
+
var EMPTY_READS = {
|
|
549
|
+
listNamespaces: async () => [],
|
|
550
|
+
listNamespacesForApplication: async () => [],
|
|
551
|
+
getContexts: async () => ({ contexts: [] })
|
|
552
|
+
};
|
|
553
|
+
var NODE_ONLY = /* @__PURE__ */ new Set([
|
|
554
|
+
"upgradeGroup",
|
|
555
|
+
"retryGroupUpgrade",
|
|
556
|
+
"abortMigration",
|
|
557
|
+
"installApplication",
|
|
558
|
+
"installDevApplication",
|
|
559
|
+
"uninstallApplication",
|
|
560
|
+
"generateContextIdentity",
|
|
561
|
+
"deleteContext",
|
|
562
|
+
"createContextAlias",
|
|
563
|
+
"createApplicationAlias",
|
|
564
|
+
"createDeviceAlias",
|
|
565
|
+
"deleteContextAlias",
|
|
566
|
+
"deleteApplicationAlias",
|
|
567
|
+
"deleteDeviceAlias",
|
|
568
|
+
"deleteNamespace",
|
|
569
|
+
"createGroupInvitation",
|
|
570
|
+
"joinGroup",
|
|
571
|
+
"setTeeAdmissionPolicy",
|
|
572
|
+
"getTeeAdmissionPolicy",
|
|
573
|
+
"deleteBlob",
|
|
574
|
+
"listAccountDevices",
|
|
575
|
+
"revokeAccountDevice",
|
|
576
|
+
"getGroupUpgradeStatus",
|
|
577
|
+
"getMigrationStatus",
|
|
578
|
+
"getCascadeStatus"
|
|
579
|
+
]);
|
|
580
|
+
function createAccountAdmin(input, deps = {}) {
|
|
581
|
+
const { session: s, read, app } = input;
|
|
582
|
+
const group = deps.govern?.group ?? governGroup;
|
|
583
|
+
const root = deps.govern?.root ?? governRoot;
|
|
584
|
+
const createContext2 = deps.createContext ?? createDelegatedContext;
|
|
585
|
+
const found = deps.found ?? foundDelegatedNamespace;
|
|
586
|
+
const latestVersion = deps.latestVersion ?? latestPublishedVersion;
|
|
587
|
+
const signInvitation = deps.signInvitation ?? signGroupInvitation;
|
|
588
|
+
const join = deps.join;
|
|
589
|
+
async function joinNamespace(namespaceId, req) {
|
|
590
|
+
if (!join) throw new NotForAccountError("joinNamespace without a join handler");
|
|
591
|
+
return join(namespaceId, req.invitation);
|
|
592
|
+
}
|
|
593
|
+
const relay = () => {
|
|
594
|
+
if (read === null) throw new NoRelayError("this call");
|
|
595
|
+
return read;
|
|
596
|
+
};
|
|
597
|
+
async function isMemberOfContextGroup(contextId, knownGroupId) {
|
|
598
|
+
const groupId = knownGroupId ?? String(await relay().getContextGroup(contextId));
|
|
599
|
+
const { members } = await relay().listGroupMembers(groupId);
|
|
600
|
+
return members.some((m) => m.identity.toLowerCase() === s.account.toLowerCase());
|
|
601
|
+
}
|
|
602
|
+
const writes = {
|
|
603
|
+
// The node-wide `for-application` listing is not caller-scoped, so a relay
|
|
604
|
+
// refuses it to an account. Its own scoped list, filtered, is the answer.
|
|
605
|
+
async listNamespacesForApplication(applicationId) {
|
|
606
|
+
return (await relay().listNamespaces()).filter((ns) => ns.targetApplicationId === applicationId);
|
|
607
|
+
},
|
|
608
|
+
async getNodeIdentity() {
|
|
609
|
+
return { accountId: s.account, deviceId: null, publicKey: "", deviceCertified: true };
|
|
610
|
+
},
|
|
611
|
+
async createNamespace(req) {
|
|
612
|
+
if (!app.packageName) throw new NotForAccountError("createNamespace without a packageName");
|
|
613
|
+
const version = app.packageVersion ?? await latestVersion(app.registryUrl ?? "https://apps.calimero.network", app.packageName);
|
|
614
|
+
const { namespaceId } = await found(s, {
|
|
615
|
+
defaultCapabilities: 231,
|
|
616
|
+
application: { applicationId: req.applicationId, package: app.packageName, version }
|
|
617
|
+
});
|
|
618
|
+
if (req.name) await group(s, namespaceId, groupMetadataSetOp({ name: req.name }));
|
|
619
|
+
return { namespaceId };
|
|
620
|
+
},
|
|
621
|
+
async createGroupInNamespace(namespaceId, req = {}) {
|
|
622
|
+
const { op } = await subgroupCreation({ parentId: namespaceId, restricted: req.visibility !== "open", admin: s.account });
|
|
623
|
+
const { groupId } = await root(s, namespaceId, op);
|
|
624
|
+
rememberGroupNamespace(s.account, groupId, namespaceId);
|
|
625
|
+
if (req.groupName) await group(s, groupId, groupMetadataSetOp({ name: req.groupName }));
|
|
626
|
+
return { groupId };
|
|
627
|
+
},
|
|
628
|
+
async addGroupMembers(groupId, req) {
|
|
629
|
+
for (const m of req.members) await group(s, groupId, memberAddedOp(m.identity, m.role ?? "Member"));
|
|
630
|
+
},
|
|
631
|
+
async removeGroupMembers(groupId, req) {
|
|
632
|
+
for (const m of req.members) await group(s, groupId, memberRemovedOp(m));
|
|
633
|
+
},
|
|
634
|
+
async setGroupMetadata(groupId, req) {
|
|
635
|
+
await group(s, groupId, groupMetadataSetOp(req));
|
|
636
|
+
},
|
|
637
|
+
async setMemberMetadata(groupId, identity, req) {
|
|
638
|
+
await group(s, groupId, memberMetadataSetOp(identity, req));
|
|
639
|
+
},
|
|
640
|
+
async setContextMetadata(groupId, contextId, req) {
|
|
641
|
+
await group(s, groupId, contextMetadataSetOp(contextId, req));
|
|
642
|
+
},
|
|
643
|
+
async setDefaultCapabilities(groupId, req) {
|
|
644
|
+
await group(s, groupId, defaultCapabilitiesSetOp(req.defaultCapabilities));
|
|
645
|
+
},
|
|
646
|
+
async setSubgroupVisibility(groupId, req) {
|
|
647
|
+
await group(s, groupId, subgroupVisibilitySetOp(req.subgroupVisibility === "open" ? "open" : "restricted"));
|
|
648
|
+
},
|
|
649
|
+
async setMemberCapabilities(groupId, identity, req) {
|
|
650
|
+
await group(s, groupId, memberCapabilitySetOp(identity, req.capabilities));
|
|
651
|
+
},
|
|
652
|
+
async deleteGroup(groupId) {
|
|
653
|
+
await root(s, groupId, groupDeletedOp(groupId));
|
|
654
|
+
return { isDeleted: true };
|
|
655
|
+
},
|
|
656
|
+
async reparentGroup(childGroupId, req) {
|
|
657
|
+
await root(s, childGroupId, groupReparentedOp(childGroupId, req.newParentId));
|
|
658
|
+
return { reparented: true };
|
|
659
|
+
},
|
|
660
|
+
async leaveGroup(groupId) {
|
|
661
|
+
await group(s, groupId, memberLeftOp(s.account));
|
|
662
|
+
},
|
|
663
|
+
async leaveNamespace(namespaceId) {
|
|
664
|
+
await group(s, namespaceId, memberLeftOp(s.account));
|
|
665
|
+
},
|
|
666
|
+
// An account holds no context identity: leaving a context is leaving its group.
|
|
667
|
+
async leaveContext(contextId) {
|
|
668
|
+
const groupId = await relay().getContextGroup(contextId);
|
|
669
|
+
await group(s, String(groupId), memberLeftOp(s.account));
|
|
670
|
+
},
|
|
671
|
+
// An account runs as itself in every context it can reach (the relay
|
|
672
|
+
// executes as the account), so its identity there is the account. Owned
|
|
673
|
+
// when its account is a member of the context's group, as on a node a
|
|
674
|
+
// context identity is owned once the node has joined.
|
|
675
|
+
async getContextIdentitiesOwned(contextId) {
|
|
676
|
+
return { identities: await isMemberOfContextGroup(contextId) ? [s.account] : [] };
|
|
677
|
+
},
|
|
678
|
+
async joinContext(contextId) {
|
|
679
|
+
const groupId = String(await relay().getContextGroup(contextId));
|
|
680
|
+
if (await isMemberOfContextGroup(contextId, groupId)) {
|
|
681
|
+
return { contextId, memberPublicKey: s.account };
|
|
682
|
+
}
|
|
683
|
+
await root(s, groupId, memberJoinedOpenOp({ member: s.account, groupId, credential: s.credential }));
|
|
684
|
+
return { contextId, memberPublicKey: s.account };
|
|
685
|
+
},
|
|
686
|
+
async createContext(req) {
|
|
687
|
+
const info = await relay().getGroupInfo(req.groupId);
|
|
688
|
+
const namespaceId = info.namespaceId ?? req.groupId;
|
|
689
|
+
const { contextId } = await createContext2(s, {
|
|
690
|
+
namespaceId,
|
|
691
|
+
groupId: req.groupId,
|
|
692
|
+
applicationId: req.applicationId,
|
|
693
|
+
name: req.name,
|
|
694
|
+
initializationParams: req.initializationParams
|
|
695
|
+
});
|
|
696
|
+
return { contextId, memberPublicKey: "", groupId: req.groupId };
|
|
697
|
+
},
|
|
698
|
+
async createNamespaceInvitation(namespaceId) {
|
|
699
|
+
const [{ members }, info] = await Promise.all([relay().listGroupMembers(namespaceId), relay().getGroupInfo(namespaceId)]);
|
|
700
|
+
const relays = members.filter((m) => m.role === "RelayTee").map((m) => m.identity.toLowerCase());
|
|
701
|
+
const invitation = await signInvitation({
|
|
702
|
+
groupId: namespaceId,
|
|
703
|
+
inviterAccount: s.account,
|
|
704
|
+
deviceSecret: s.deviceSecret,
|
|
705
|
+
...relays.length > 0 ? { admitters: relays } : {},
|
|
706
|
+
members,
|
|
707
|
+
applicationId: info.targetApplicationId,
|
|
708
|
+
appKey: info.appKey
|
|
709
|
+
});
|
|
710
|
+
return { invitation };
|
|
711
|
+
},
|
|
712
|
+
// The relay syncs its own view; an account has nothing to pull.
|
|
713
|
+
async syncGroup(groupId) {
|
|
714
|
+
return { groupId, synced: true };
|
|
715
|
+
},
|
|
716
|
+
async syncContext() {
|
|
717
|
+
},
|
|
718
|
+
joinNamespace,
|
|
719
|
+
async updateMemberRole(groupId, identity, req) {
|
|
720
|
+
await group(s, groupId, memberRoleSetOp(identity, req.role));
|
|
721
|
+
},
|
|
722
|
+
// An open subgroup is joined the way `joinContext` joins one: MemberJoinedOpen
|
|
723
|
+
// on the subgroup, and nothing to do for a member already in it.
|
|
724
|
+
async joinSubgroupInheritance(groupId) {
|
|
725
|
+
const { members } = await relay().listGroupMembers(groupId);
|
|
726
|
+
if (members.some((m) => m.identity.toLowerCase() === s.account.toLowerCase())) {
|
|
727
|
+
return { groupId, memberPublicKey: s.account, wasInherited: false };
|
|
728
|
+
}
|
|
729
|
+
await root(s, groupId, memberJoinedOpenOp({ member: s.account, groupId, credential: s.credential }));
|
|
730
|
+
return { groupId, memberPublicKey: s.account, wasInherited: true };
|
|
731
|
+
},
|
|
732
|
+
async detachContextFromGroup(groupId, contextId) {
|
|
733
|
+
await group(s, groupId, contextDetachedOp(contextId));
|
|
734
|
+
}
|
|
735
|
+
};
|
|
736
|
+
if (read === null) {
|
|
737
|
+
return new Proxy({}, {
|
|
738
|
+
get(_target, prop) {
|
|
739
|
+
if (typeof prop !== "string") return void 0;
|
|
740
|
+
if (prop === "getNodeIdentity") return writes.getNodeIdentity;
|
|
741
|
+
if (prop === "joinNamespace") return joinNamespace;
|
|
742
|
+
if (prop in EMPTY_READS) return EMPTY_READS[prop];
|
|
743
|
+
return async () => {
|
|
744
|
+
throw new NoRelayError(prop);
|
|
745
|
+
};
|
|
746
|
+
}
|
|
747
|
+
});
|
|
748
|
+
}
|
|
749
|
+
return new Proxy(read, {
|
|
750
|
+
get(target, prop, receiver) {
|
|
751
|
+
if (typeof prop === "string" && prop in writes) return writes[prop];
|
|
752
|
+
if (typeof prop === "string" && NODE_ONLY.has(prop)) {
|
|
753
|
+
return async () => {
|
|
754
|
+
throw new NotForAccountError(prop);
|
|
755
|
+
};
|
|
756
|
+
}
|
|
757
|
+
return Reflect.get(target, prop, receiver);
|
|
758
|
+
}
|
|
759
|
+
});
|
|
760
|
+
}
|
|
761
|
+
function explainAdmitFailure(status, body) {
|
|
762
|
+
const detail = body ? `: ${body}` : "";
|
|
763
|
+
switch (status) {
|
|
764
|
+
case 400:
|
|
765
|
+
return `The node refused the join as malformed (400)${detail}. The signature covers the invitation exactly as sent, so an edited or re-serialised invitation fails here \u2014 as does a namespace id that is not the invitation's own group.`;
|
|
766
|
+
case 403:
|
|
767
|
+
return `The node refused to carry this join (403)${detail}. Either it is not in the invitation's signed admitters list \u2014 being live and listed by the cloud is not the same thing \u2014 or the invitation itself was rejected as expired or not the inviter\u2019s to issue.`;
|
|
768
|
+
case 409:
|
|
769
|
+
return `That node holds no device of its own, so it cannot endorse anyone (409)${detail}. Another admitter from the same invitation would work.`;
|
|
770
|
+
default:
|
|
771
|
+
return `The join was not published (HTTP ${status})${detail}.`;
|
|
772
|
+
}
|
|
773
|
+
}
|
|
774
|
+
function joinNonce(account) {
|
|
775
|
+
const source = createLocalStorageNonceSource(`calimero.delegated.joinnonce.${account}`);
|
|
776
|
+
return () => source.next();
|
|
777
|
+
}
|
|
778
|
+
function origin(url) {
|
|
779
|
+
return url.replace(/\/+$/, "");
|
|
780
|
+
}
|
|
781
|
+
async function joinWithNode(input) {
|
|
782
|
+
const { account, credential, deviceSecret } = input.credential;
|
|
783
|
+
let signedOp;
|
|
784
|
+
try {
|
|
785
|
+
signedOp = await signMemberJoinOp({
|
|
786
|
+
namespaceId: input.namespaceId,
|
|
787
|
+
member: account,
|
|
788
|
+
invitation: input.invitation,
|
|
789
|
+
credential,
|
|
790
|
+
deviceSecret,
|
|
791
|
+
nonce: await (input.deps?.nonce ?? joinNonce(account))()
|
|
792
|
+
});
|
|
793
|
+
} catch (e) {
|
|
794
|
+
return {
|
|
795
|
+
ok: false,
|
|
796
|
+
step: "sign",
|
|
797
|
+
reason: `The join op could not be signed, so nothing was sent: ${e instanceof Error ? e.message : String(e)}`
|
|
798
|
+
};
|
|
799
|
+
}
|
|
800
|
+
const body = { invitation: input.invitation, signedOp };
|
|
801
|
+
const url = input.admitUrl ?? `${origin(input.nodeUrl)}/admin-api/namespaces/${input.namespaceId}/admit`;
|
|
802
|
+
const doFetch = input.deps?.fetch ?? fetch;
|
|
803
|
+
let response;
|
|
804
|
+
try {
|
|
805
|
+
response = await doFetch(url, {
|
|
806
|
+
method: "POST",
|
|
807
|
+
// No Authorization header and no request proof, deliberately: the route is
|
|
808
|
+
// unauthenticated because the joiner's signature is the authorization.
|
|
809
|
+
headers: { "Content-Type": "application/json", Accept: "application/json" },
|
|
810
|
+
body: JSON.stringify(body)
|
|
811
|
+
});
|
|
812
|
+
} catch (e) {
|
|
813
|
+
return {
|
|
814
|
+
ok: false,
|
|
815
|
+
step: "admit",
|
|
816
|
+
reason: `The admitter at ${input.nodeUrl} could not be reached: ${e instanceof Error ? e.message : String(e)}. The invitation is untouched \u2014 this is the node being unreachable, not a refusal.`
|
|
817
|
+
};
|
|
818
|
+
}
|
|
819
|
+
const text = await response.text();
|
|
820
|
+
if (!response.ok) {
|
|
821
|
+
return {
|
|
822
|
+
ok: false,
|
|
823
|
+
step: "admit",
|
|
824
|
+
status: response.status,
|
|
825
|
+
reason: explainAdmitFailure(response.status, text)
|
|
826
|
+
};
|
|
827
|
+
}
|
|
828
|
+
let published = false;
|
|
829
|
+
try {
|
|
830
|
+
const parsed = text ? JSON.parse(text) : {};
|
|
831
|
+
published = parsed.data?.published === true;
|
|
832
|
+
} catch {
|
|
833
|
+
published = false;
|
|
834
|
+
}
|
|
835
|
+
return {
|
|
836
|
+
ok: true,
|
|
837
|
+
published,
|
|
838
|
+
session: { relayUrl: origin(input.nodeUrl), account, credential, deviceSecret }
|
|
839
|
+
};
|
|
840
|
+
}
|
|
841
|
+
function normaliseAccount(account) {
|
|
842
|
+
if (!account) return null;
|
|
843
|
+
const trimmed = account.trim().toLowerCase();
|
|
844
|
+
const bare = trimmed.startsWith("0x") ? trimmed.slice(2) : trimmed;
|
|
845
|
+
return bare.length > 0 ? bare : null;
|
|
846
|
+
}
|
|
847
|
+
function isInvited(node, invited) {
|
|
848
|
+
if (invited.size === 0) return true;
|
|
849
|
+
const account = normaliseAccount(node.account);
|
|
850
|
+
return account !== null && invited.has(account);
|
|
851
|
+
}
|
|
852
|
+
async function resolveRelayFromInvitation(input) {
|
|
853
|
+
const cloud = input.cloud ?? new CloudClient({
|
|
854
|
+
cloudBaseUrl: input.cloudBaseUrl,
|
|
855
|
+
routingCredential: { credential: input.credential, deviceSecret: input.deviceSecret }
|
|
856
|
+
});
|
|
857
|
+
let nodes;
|
|
858
|
+
let servable;
|
|
859
|
+
try {
|
|
860
|
+
const routing = await cloud.getNamespaceRouting(input.namespaceId);
|
|
861
|
+
nodes = routing.nodes;
|
|
862
|
+
servable = routing.servable;
|
|
863
|
+
} catch (e) {
|
|
864
|
+
return {
|
|
865
|
+
ok: false,
|
|
866
|
+
step: "admitters-lookup",
|
|
867
|
+
reason: `The cloud could not be asked which nodes serve namespace ${input.namespaceId}: ${e instanceof Error ? e.message : String(e)}. Nothing is known about the invitation yet \u2014 this is the lookup failing, not the invitation.`
|
|
868
|
+
};
|
|
869
|
+
}
|
|
870
|
+
if (nodes.length === 0) {
|
|
871
|
+
return {
|
|
872
|
+
ok: false,
|
|
873
|
+
step: "no-nodes",
|
|
874
|
+
reason: "The cloud lists no nodes serving this namespace, so there is no hosted node to be admitted through. The namespace has no fleet assignment \u2014 whoever invited you is running their own node, and admission has to go through a node the cloud routes to."
|
|
875
|
+
};
|
|
876
|
+
}
|
|
877
|
+
const invited = new Set(
|
|
878
|
+
(input.admitters ?? []).map(normaliseAccount).filter((a) => a !== null)
|
|
879
|
+
);
|
|
880
|
+
const named = nodes.filter((n) => isInvited(n, invited));
|
|
881
|
+
if (named.length === 0) {
|
|
882
|
+
return {
|
|
883
|
+
ok: false,
|
|
884
|
+
step: "not-invited",
|
|
885
|
+
reason: `${nodes.length} node${nodes.length === 1 ? "" : "s"} serve this namespace, but your invitation names none of them. The signed admitter list is a snapshot from when the invitation was minted, so a node assigned since is healthy and will still refuse the claim. Ask for a fresh invitation.`
|
|
886
|
+
};
|
|
887
|
+
}
|
|
888
|
+
const usable = named.filter((n) => n.canAdmit);
|
|
889
|
+
const candidates = usable.length > 0 ? usable : named;
|
|
890
|
+
const advisory = usable.length === 0 || !servable;
|
|
891
|
+
const addressable = candidates.filter(
|
|
892
|
+
(n) => typeof n.relayUrl === "string" && n.relayUrl.length > 0
|
|
893
|
+
);
|
|
894
|
+
if (addressable.length === 0) {
|
|
895
|
+
return {
|
|
896
|
+
ok: false,
|
|
897
|
+
step: "no-relay-url",
|
|
898
|
+
reason: "A node your invitation names can admit you, but the cloud knows no address for it yet, so there would be nothing to connect through afterwards. Try again shortly."
|
|
899
|
+
};
|
|
900
|
+
}
|
|
901
|
+
const chosen = addressable.find((n) => n.canExecute) ?? addressable.find((n) => n.fresh) ?? addressable[0];
|
|
902
|
+
return {
|
|
903
|
+
ok: true,
|
|
904
|
+
relayUrl: chosen.relayUrl,
|
|
905
|
+
// The cloud's ready-made URL when it gave one, so the path is never rebuilt
|
|
906
|
+
// from a guess; the fallback is the documented route on the same origin.
|
|
907
|
+
admitUrl: chosen.admitUrl ?? `${chosen.relayUrl.replace(/\/+$/, "")}/admin-api/namespaces/${input.namespaceId}/admit`,
|
|
908
|
+
admitterAccount: chosen.account,
|
|
909
|
+
peerId: chosen.peerId,
|
|
910
|
+
writable: chosen.canExecute,
|
|
911
|
+
// Stale when the node's own heartbeat lapsed OR when the cloud's summary
|
|
912
|
+
// disagrees with trying it at all. Both mean the same thing to a caller:
|
|
913
|
+
// this was attempted on advisory data, so if the admit fails that is why.
|
|
914
|
+
stale: !chosen.fresh || advisory
|
|
915
|
+
};
|
|
916
|
+
}
|
|
917
|
+
|
|
918
|
+
// src/delegated/bootstrap-from-invitation.ts
|
|
919
|
+
async function bootstrapFromInvitation(input) {
|
|
920
|
+
const resolve = input.deps?.resolve ?? resolveRelayFromInvitation;
|
|
921
|
+
const join = input.deps?.join ?? joinWithNode;
|
|
922
|
+
let relay = null;
|
|
923
|
+
let nodeUrl = input.nodeUrl;
|
|
924
|
+
let admitUrl;
|
|
925
|
+
if (!nodeUrl) {
|
|
926
|
+
const resolved = await resolve({
|
|
927
|
+
namespaceId: input.namespaceId,
|
|
928
|
+
// The signed list, read off the invitation itself rather than passed
|
|
929
|
+
// separately: two sources for one fact is how an intersection ends up
|
|
930
|
+
// being performed against the wrong list.
|
|
931
|
+
admitters: input.invitation.invitation.admitters,
|
|
932
|
+
credential: input.credential.credential,
|
|
933
|
+
deviceSecret: input.credential.deviceSecret,
|
|
934
|
+
cloudBaseUrl: input.cloudBaseUrl
|
|
935
|
+
});
|
|
936
|
+
if (!resolved.ok) return resolved;
|
|
937
|
+
relay = resolved;
|
|
938
|
+
nodeUrl = resolved.relayUrl;
|
|
939
|
+
admitUrl = resolved.admitUrl;
|
|
940
|
+
}
|
|
941
|
+
const joined = await join({
|
|
942
|
+
nodeUrl,
|
|
943
|
+
admitUrl,
|
|
944
|
+
namespaceId: input.namespaceId,
|
|
945
|
+
invitation: input.invitation,
|
|
946
|
+
credential: input.credential,
|
|
947
|
+
deps: { fetch: input.deps?.fetch, nonce: input.deps?.nonce }
|
|
948
|
+
});
|
|
949
|
+
if (!joined.ok) return joined;
|
|
950
|
+
return { ok: true, published: joined.published, relay, session: joined.session };
|
|
951
|
+
}
|
|
952
|
+
|
|
953
|
+
// src/delegated/join-as-account.ts
|
|
954
|
+
async function joinAsAccount(session, namespaceId, invitation, opts) {
|
|
955
|
+
const bootstrap = opts.bootstrap ?? bootstrapFromInvitation;
|
|
956
|
+
const outcome = await bootstrap({
|
|
957
|
+
namespaceId,
|
|
958
|
+
invitation,
|
|
959
|
+
credential: { account: session.account, credential: session.credential, deviceSecret: session.deviceSecret },
|
|
960
|
+
cloudBaseUrl: opts.cloudBaseUrl
|
|
961
|
+
});
|
|
962
|
+
if (!outcome.ok) {
|
|
963
|
+
throw Object.assign(new Error(outcome.reason), {
|
|
964
|
+
step: outcome.step,
|
|
965
|
+
...outcome.status !== void 0 ? { status: outcome.status } : {}
|
|
966
|
+
});
|
|
967
|
+
}
|
|
968
|
+
if (outcome.session.relayUrl) rememberRelay(session.account, outcome.session.relayUrl, { namespaceId });
|
|
969
|
+
opts.onJoined(outcome.session);
|
|
970
|
+
return { namespaceId };
|
|
971
|
+
}
|
|
972
|
+
|
|
973
|
+
// src/auth/node-trust.ts
|
|
974
|
+
function sameOrigin(a, b) {
|
|
975
|
+
try {
|
|
976
|
+
return new URL(a).origin === new URL(b).origin;
|
|
977
|
+
} catch {
|
|
978
|
+
return false;
|
|
979
|
+
}
|
|
980
|
+
}
|
|
981
|
+
function resolveTrustedNodeUrl(params) {
|
|
982
|
+
const { candidate, initiated, allowedNodeUrls } = params;
|
|
983
|
+
if (!candidate) {
|
|
984
|
+
return { url: initiated ?? null, rejected: false };
|
|
985
|
+
}
|
|
986
|
+
if (initiated) {
|
|
987
|
+
return sameOrigin(candidate, initiated) ? { url: candidate, rejected: false } : { url: null, rejected: true };
|
|
988
|
+
}
|
|
989
|
+
if (allowedNodeUrls && allowedNodeUrls.length > 0) {
|
|
990
|
+
return allowedNodeUrls.some((u) => sameOrigin(candidate, u)) ? { url: candidate, rejected: false } : { url: null, rejected: true };
|
|
991
|
+
}
|
|
992
|
+
return { url: null, rejected: true };
|
|
993
|
+
}
|
|
994
|
+
|
|
995
|
+
// src/auth/token-adoption.ts
|
|
996
|
+
var HOUR_MS = 36e5;
|
|
997
|
+
function decodeJwtClaims(token) {
|
|
998
|
+
try {
|
|
999
|
+
const parts = token.split(".");
|
|
1000
|
+
if (parts.length !== 3) return null;
|
|
1001
|
+
let b64 = parts[1].replace(/-/g, "+").replace(/_/g, "/");
|
|
1002
|
+
while (b64.length % 4) b64 += "=";
|
|
1003
|
+
const payload = JSON.parse(atob(b64));
|
|
1004
|
+
if (!payload || typeof payload !== "object") return null;
|
|
1005
|
+
const { iat, exp } = payload;
|
|
1006
|
+
return {
|
|
1007
|
+
iat: typeof iat === "number" && iat > 0 ? iat : void 0,
|
|
1008
|
+
exp: typeof exp === "number" && exp > 0 ? exp : void 0
|
|
1009
|
+
};
|
|
1010
|
+
} catch {
|
|
1011
|
+
return null;
|
|
1012
|
+
}
|
|
1013
|
+
}
|
|
1014
|
+
function expiresAtFromJwt(token, fallbackMs = Date.now() + HOUR_MS) {
|
|
1015
|
+
const exp = decodeJwtClaims(token)?.exp;
|
|
1016
|
+
return exp ? exp * 1e3 : fallbackMs;
|
|
1017
|
+
}
|
|
1018
|
+
function isCallbackNewer(callbackAccessToken, stored) {
|
|
1019
|
+
const incoming = decodeJwtClaims(callbackAccessToken);
|
|
1020
|
+
if (!incoming) return false;
|
|
1021
|
+
const current = decodeJwtClaims(stored.access_token);
|
|
1022
|
+
if (current) {
|
|
1023
|
+
if (incoming.iat !== void 0 && current.iat !== void 0 && incoming.iat !== current.iat) {
|
|
1024
|
+
return incoming.iat > current.iat;
|
|
1025
|
+
}
|
|
1026
|
+
if (incoming.exp !== void 0 && current.exp !== void 0 && incoming.exp !== current.exp) {
|
|
1027
|
+
return incoming.exp > current.exp;
|
|
1028
|
+
}
|
|
1029
|
+
return false;
|
|
1030
|
+
}
|
|
1031
|
+
return incoming.exp !== void 0 && incoming.exp * 1e3 > stored.expires_at;
|
|
1032
|
+
}
|
|
1033
|
+
function resolveTokenAdoption(params) {
|
|
1034
|
+
const { callbackAccessToken, callbackRefreshToken, callbackNodeUrl, stored, storedNodeUrl } = params;
|
|
1035
|
+
const bundle = (refreshToken2) => ({
|
|
1036
|
+
access_token: callbackAccessToken,
|
|
1037
|
+
refresh_token: refreshToken2,
|
|
1038
|
+
expires_at: expiresAtFromJwt(callbackAccessToken)
|
|
1039
|
+
});
|
|
1040
|
+
if (!stored?.access_token) {
|
|
1041
|
+
return { adopt: true, tokens: bundle(callbackRefreshToken), reason: "fresh-login" };
|
|
1042
|
+
}
|
|
1043
|
+
const sameNode = !!storedNodeUrl && sameOrigin(callbackNodeUrl, storedNodeUrl);
|
|
1044
|
+
if (!sameNode) {
|
|
1045
|
+
return { adopt: true, tokens: bundle(callbackRefreshToken), reason: "node-changed" };
|
|
1046
|
+
}
|
|
1047
|
+
const refreshToken = callbackRefreshToken || stored.refresh_token;
|
|
1048
|
+
if (isCallbackNewer(callbackAccessToken, stored)) {
|
|
1049
|
+
return { adopt: true, tokens: bundle(refreshToken), reason: "newer" };
|
|
1050
|
+
}
|
|
1051
|
+
if (!stored.refresh_token && callbackRefreshToken) {
|
|
1052
|
+
return {
|
|
1053
|
+
adopt: true,
|
|
1054
|
+
tokens: { ...stored, refresh_token: callbackRefreshToken },
|
|
1055
|
+
reason: "fill-refresh"
|
|
1056
|
+
};
|
|
1057
|
+
}
|
|
1058
|
+
return { adopt: false, reason: "stale" };
|
|
1059
|
+
}
|
|
1060
|
+
|
|
1061
|
+
// src/storage/index.ts
|
|
1062
|
+
var STORAGE_KEYS = {
|
|
1063
|
+
ACCESS_TOKEN: "mero:access_token",
|
|
1064
|
+
REFRESH_TOKEN: "mero:refresh_token",
|
|
1065
|
+
EXPIRES_AT: "mero:expires_at",
|
|
1066
|
+
NODE_URL: "mero:node_url",
|
|
1067
|
+
// The node the token bundle currently in the TokenStore was issued by. Distinct
|
|
1068
|
+
// from NODE_URL, which `connectToNode` overwrites with the *target* node before
|
|
1069
|
+
// redirecting to login — so at callback time NODE_URL names where we are going,
|
|
1070
|
+
// not who minted the tokens we still hold. Telling those apart is what lets the
|
|
1071
|
+
// SSO callback re-seed on a node change without mistaking a different node's
|
|
1072
|
+
// bundle for a rotated one (see auth/token-adoption.ts).
|
|
1073
|
+
TOKEN_NODE_URL: "mero:token_node_url",
|
|
1074
|
+
APPLICATION_ID: "mero:application_id",
|
|
1075
|
+
CONTEXT_ID: "mero:context_id",
|
|
1076
|
+
CONTEXT_IDENTITY: "mero:context_identity"
|
|
1077
|
+
};
|
|
1078
|
+
var _storageAvailable = null;
|
|
1079
|
+
function isLocalStorageAvailable() {
|
|
1080
|
+
if (_storageAvailable !== null) return _storageAvailable;
|
|
1081
|
+
try {
|
|
1082
|
+
if (typeof window === "undefined" || !window.localStorage) {
|
|
1083
|
+
_storageAvailable = false;
|
|
1084
|
+
return false;
|
|
1085
|
+
}
|
|
1086
|
+
const testKey = "__mero_test__";
|
|
1087
|
+
localStorage.setItem(testKey, "test");
|
|
1088
|
+
localStorage.removeItem(testKey);
|
|
1089
|
+
_storageAvailable = true;
|
|
1090
|
+
} catch {
|
|
1091
|
+
_storageAvailable = false;
|
|
1092
|
+
}
|
|
1093
|
+
return _storageAvailable;
|
|
1094
|
+
}
|
|
1095
|
+
var localStorageTokenStorage = {
|
|
1096
|
+
async get() {
|
|
1097
|
+
if (!isLocalStorageAvailable()) {
|
|
1098
|
+
return null;
|
|
1099
|
+
}
|
|
1100
|
+
try {
|
|
1101
|
+
const accessToken = localStorage.getItem(STORAGE_KEYS.ACCESS_TOKEN);
|
|
1102
|
+
const refreshToken = localStorage.getItem(STORAGE_KEYS.REFRESH_TOKEN);
|
|
1103
|
+
const expiresAt = localStorage.getItem(STORAGE_KEYS.EXPIRES_AT);
|
|
1104
|
+
if (!accessToken || !refreshToken) {
|
|
1105
|
+
return null;
|
|
1106
|
+
}
|
|
1107
|
+
return {
|
|
1108
|
+
access_token: accessToken,
|
|
1109
|
+
refresh_token: refreshToken,
|
|
1110
|
+
expires_at: expiresAt ? parseInt(expiresAt, 10) : Date.now() + 36e5
|
|
1111
|
+
};
|
|
1112
|
+
} catch (e) {
|
|
1113
|
+
console.error("[mero-react] Failed to get token from storage:", e);
|
|
1114
|
+
return null;
|
|
1115
|
+
}
|
|
1116
|
+
},
|
|
1117
|
+
async set(token) {
|
|
1118
|
+
if (!isLocalStorageAvailable()) {
|
|
1119
|
+
return;
|
|
1120
|
+
}
|
|
1121
|
+
try {
|
|
1122
|
+
localStorage.setItem(STORAGE_KEYS.ACCESS_TOKEN, token.access_token);
|
|
1123
|
+
localStorage.setItem(STORAGE_KEYS.REFRESH_TOKEN, token.refresh_token);
|
|
1124
|
+
localStorage.setItem(STORAGE_KEYS.EXPIRES_AT, token.expires_at.toString());
|
|
1125
|
+
} catch (e) {
|
|
1126
|
+
console.error("[mero-react] Failed to save token to storage:", e);
|
|
1127
|
+
}
|
|
1128
|
+
},
|
|
1129
|
+
async clear() {
|
|
1130
|
+
if (!isLocalStorageAvailable()) {
|
|
1131
|
+
return;
|
|
1132
|
+
}
|
|
1133
|
+
try {
|
|
1134
|
+
localStorage.removeItem(STORAGE_KEYS.ACCESS_TOKEN);
|
|
1135
|
+
localStorage.removeItem(STORAGE_KEYS.REFRESH_TOKEN);
|
|
1136
|
+
localStorage.removeItem(STORAGE_KEYS.EXPIRES_AT);
|
|
1137
|
+
} catch (e) {
|
|
1138
|
+
console.error("[mero-react] Failed to clear token from storage:", e);
|
|
1139
|
+
}
|
|
1140
|
+
}
|
|
1141
|
+
};
|
|
1142
|
+
function getNodeUrl() {
|
|
1143
|
+
if (!isLocalStorageAvailable()) return null;
|
|
1144
|
+
return localStorage.getItem(STORAGE_KEYS.NODE_URL);
|
|
1145
|
+
}
|
|
1146
|
+
function setNodeUrl(url) {
|
|
1147
|
+
if (!isLocalStorageAvailable()) return;
|
|
1148
|
+
localStorage.setItem(STORAGE_KEYS.NODE_URL, url);
|
|
1149
|
+
}
|
|
1150
|
+
function clearNodeUrl() {
|
|
1151
|
+
if (!isLocalStorageAvailable()) return;
|
|
1152
|
+
localStorage.removeItem(STORAGE_KEYS.NODE_URL);
|
|
1153
|
+
}
|
|
1154
|
+
function getTokenNodeUrl() {
|
|
1155
|
+
if (!isLocalStorageAvailable()) return null;
|
|
1156
|
+
return localStorage.getItem(STORAGE_KEYS.TOKEN_NODE_URL);
|
|
1157
|
+
}
|
|
1158
|
+
function setTokenNodeUrl(url) {
|
|
1159
|
+
if (!isLocalStorageAvailable()) return;
|
|
1160
|
+
localStorage.setItem(STORAGE_KEYS.TOKEN_NODE_URL, url);
|
|
1161
|
+
}
|
|
1162
|
+
function clearTokenNodeUrl() {
|
|
1163
|
+
if (!isLocalStorageAvailable()) return;
|
|
1164
|
+
localStorage.removeItem(STORAGE_KEYS.TOKEN_NODE_URL);
|
|
505
1165
|
}
|
|
506
|
-
function
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
} catch {
|
|
510
|
-
}
|
|
1166
|
+
function getApplicationId() {
|
|
1167
|
+
if (!isLocalStorageAvailable()) return null;
|
|
1168
|
+
return localStorage.getItem(STORAGE_KEYS.APPLICATION_ID);
|
|
511
1169
|
}
|
|
512
|
-
function
|
|
513
|
-
|
|
514
|
-
|
|
515
|
-
if (at.namespaceId) map.namespaces[at.namespaceId] = url;
|
|
516
|
-
if (at.contextId) map.contexts[at.contextId] = url;
|
|
517
|
-
writeRelayMap(account, map);
|
|
1170
|
+
function setApplicationId(id) {
|
|
1171
|
+
if (!isLocalStorageAvailable()) return;
|
|
1172
|
+
localStorage.setItem(STORAGE_KEYS.APPLICATION_ID, id);
|
|
518
1173
|
}
|
|
519
|
-
function
|
|
520
|
-
|
|
1174
|
+
function clearApplicationId() {
|
|
1175
|
+
if (!isLocalStorageAvailable()) return;
|
|
1176
|
+
localStorage.removeItem(STORAGE_KEYS.APPLICATION_ID);
|
|
521
1177
|
}
|
|
522
|
-
function
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
return [...new Set(all)];
|
|
1178
|
+
function getContextId() {
|
|
1179
|
+
if (!isLocalStorageAvailable()) return null;
|
|
1180
|
+
return localStorage.getItem(STORAGE_KEYS.CONTEXT_ID);
|
|
526
1181
|
}
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
for (const relayUrl of knownRelays(s)) {
|
|
531
|
-
try {
|
|
532
|
-
if (!await resolveRelayNodeKey(relayUrl)) continue;
|
|
533
|
-
const client2 = buildDelegatedClient({ ...s, relayUrl }, null);
|
|
534
|
-
if (!client2) continue;
|
|
535
|
-
const { contexts } = await client2.admin.getContexts();
|
|
536
|
-
for (const c of contexts ?? []) {
|
|
537
|
-
out.push({ ...c, relayUrl });
|
|
538
|
-
map.contexts[c.id] = relayUrl;
|
|
539
|
-
}
|
|
540
|
-
} catch (e) {
|
|
541
|
-
console.warn(`[mero-react] could not list contexts on ${relayUrl}`, e);
|
|
542
|
-
}
|
|
543
|
-
}
|
|
544
|
-
writeRelayMap(s.account, map);
|
|
545
|
-
return out;
|
|
1182
|
+
function setContextId(id) {
|
|
1183
|
+
if (!isLocalStorageAvailable()) return;
|
|
1184
|
+
localStorage.setItem(STORAGE_KEYS.CONTEXT_ID, id);
|
|
546
1185
|
}
|
|
547
|
-
|
|
548
|
-
|
|
549
|
-
|
|
550
|
-
|
|
551
|
-
|
|
552
|
-
|
|
553
|
-
|
|
554
|
-
|
|
555
|
-
|
|
556
|
-
|
|
557
|
-
|
|
558
|
-
|
|
559
|
-
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
|
|
563
|
-
|
|
564
|
-
|
|
565
|
-
|
|
566
|
-
|
|
567
|
-
|
|
568
|
-
return out;
|
|
1186
|
+
function clearContextId() {
|
|
1187
|
+
if (!isLocalStorageAvailable()) return;
|
|
1188
|
+
localStorage.removeItem(STORAGE_KEYS.CONTEXT_ID);
|
|
1189
|
+
}
|
|
1190
|
+
function getContextIdentity() {
|
|
1191
|
+
if (!isLocalStorageAvailable()) return null;
|
|
1192
|
+
return localStorage.getItem(STORAGE_KEYS.CONTEXT_IDENTITY);
|
|
1193
|
+
}
|
|
1194
|
+
function setContextIdentity(id) {
|
|
1195
|
+
if (!isLocalStorageAvailable()) return;
|
|
1196
|
+
localStorage.setItem(STORAGE_KEYS.CONTEXT_IDENTITY, id);
|
|
1197
|
+
}
|
|
1198
|
+
function clearContextIdentity() {
|
|
1199
|
+
if (!isLocalStorageAvailable()) return;
|
|
1200
|
+
localStorage.removeItem(STORAGE_KEYS.CONTEXT_IDENTITY);
|
|
1201
|
+
}
|
|
1202
|
+
function clearAllStorage() {
|
|
1203
|
+
if (!isLocalStorageAvailable()) return;
|
|
1204
|
+
Object.values(STORAGE_KEYS).forEach((key) => {
|
|
1205
|
+
localStorage.removeItem(key);
|
|
1206
|
+
});
|
|
569
1207
|
}
|
|
570
1208
|
var MeroContext = createContext(null);
|
|
571
1209
|
var isBrowser = typeof window !== "undefined";
|
|
@@ -604,6 +1242,7 @@ function MeroProvider({
|
|
|
604
1242
|
packageName,
|
|
605
1243
|
packageVersion,
|
|
606
1244
|
registryUrl,
|
|
1245
|
+
cloudBaseUrl,
|
|
607
1246
|
timeoutMs = 3e4,
|
|
608
1247
|
allowedNodeUrls,
|
|
609
1248
|
tokenStore: tokenStoreProp
|
|
@@ -712,7 +1351,7 @@ function MeroProvider({
|
|
|
712
1351
|
if (!delegated) return;
|
|
713
1352
|
const relayUrl = (contextId ? relayForContext(delegated.account, contextId) : null) ?? delegated.relayUrl;
|
|
714
1353
|
const routed = { ...delegated, relayUrl };
|
|
715
|
-
const client2 = buildDelegatedClient(routed
|
|
1354
|
+
const client2 = buildDelegatedClient(routed);
|
|
716
1355
|
const awaitingKey = Boolean(client2 && relayUrl && !readPinnedRelayNodeKey(relayUrl));
|
|
717
1356
|
if (!awaitingKey) setMero(client2);
|
|
718
1357
|
setIsAuthenticated(true);
|
|
@@ -725,7 +1364,7 @@ function MeroProvider({
|
|
|
725
1364
|
if (awaitingKey) {
|
|
726
1365
|
const nodeKey = await resolveRelayNodeKey(relayUrl);
|
|
727
1366
|
if (!active) return;
|
|
728
|
-
setMero(nodeKey ? buildDelegatedClient(routed
|
|
1367
|
+
setMero(nodeKey ? buildDelegatedClient(routed) ?? client2 : client2);
|
|
729
1368
|
setIsLoading(false);
|
|
730
1369
|
if (!nodeKey) return;
|
|
731
1370
|
}
|
|
@@ -880,6 +1519,22 @@ function MeroProvider({
|
|
|
880
1519
|
sse.off("error", onError);
|
|
881
1520
|
};
|
|
882
1521
|
}, [isAuthenticated, mero, checkAuth, logout, delegated]);
|
|
1522
|
+
const admin = useMemo(() => {
|
|
1523
|
+
const app = { packageName, packageVersion, registryUrl };
|
|
1524
|
+
if (delegated !== null) {
|
|
1525
|
+
const deps = {
|
|
1526
|
+
join: (namespaceId, invitation) => joinAsAccount(delegated, namespaceId, invitation, { cloudBaseUrl, onJoined: connectWithAccount })
|
|
1527
|
+
};
|
|
1528
|
+
if (delegated.relayUrl === null) return createAccountAdmin({ session: delegated, read: null, app }, deps);
|
|
1529
|
+
if (!mero) return null;
|
|
1530
|
+
return createAccountAdmin(
|
|
1531
|
+
{ session: delegated, read: mero.admin, app },
|
|
1532
|
+
deps
|
|
1533
|
+
);
|
|
1534
|
+
}
|
|
1535
|
+
const nodeAdmin = mero?.admin;
|
|
1536
|
+
return nodeAdmin ? createNodeAdmin({ admin: nodeAdmin, app }) : null;
|
|
1537
|
+
}, [mero, delegated, packageName, packageVersion, registryUrl, cloudBaseUrl, connectWithAccount]);
|
|
883
1538
|
const contextValue = useMemo(
|
|
884
1539
|
() => ({
|
|
885
1540
|
mero,
|
|
@@ -892,12 +1547,14 @@ function MeroProvider({
|
|
|
892
1547
|
connectToNode,
|
|
893
1548
|
connectWithAccount,
|
|
894
1549
|
isDelegated: delegated !== null,
|
|
895
|
-
|
|
1550
|
+
admin,
|
|
1551
|
+
can: delegated !== null ? { createNamespace: Boolean(packageName), createContext: true, invite: true, upgrade: false } : { createNamespace: true, createContext: true, invite: true, upgrade: true },
|
|
896
1552
|
app: { packageName, packageVersion, registryUrl },
|
|
1553
|
+
cloudBaseUrl,
|
|
897
1554
|
logout,
|
|
898
1555
|
isLoading
|
|
899
1556
|
}),
|
|
900
|
-
[mero, isAuthenticated, isOnline, nodeUrl, applicationId, contextId, contextIdentity, connectToNode, connectWithAccount, delegated, logout, isLoading, packageName, packageVersion, registryUrl]
|
|
1557
|
+
[mero, admin, isAuthenticated, isOnline, nodeUrl, applicationId, contextId, contextIdentity, connectToNode, connectWithAccount, delegated, logout, isLoading, packageName, packageVersion, registryUrl, cloudBaseUrl]
|
|
901
1558
|
);
|
|
902
1559
|
return /* @__PURE__ */ jsx(MeroContext.Provider, { value: contextValue, children });
|
|
903
1560
|
}
|
|
@@ -1694,7 +2351,7 @@ function ConnectButtonAccount({
|
|
|
1694
2351
|
theme,
|
|
1695
2352
|
defaults = {}
|
|
1696
2353
|
}) {
|
|
1697
|
-
const { isAuthenticated, isOnline, nodeUrl, isDelegated, connectToNode, connectWithAccount, logout } = useMero();
|
|
2354
|
+
const { isAuthenticated, isOnline, nodeUrl, isDelegated, connectToNode, connectWithAccount, logout, cloudBaseUrl } = useMero();
|
|
1698
2355
|
const [isDropdownOpen, setIsDropdownOpen] = useState(false);
|
|
1699
2356
|
const [isNodeModalOpen, setIsNodeModalOpen] = useState(false);
|
|
1700
2357
|
const [isAccountOpen, setIsAccountOpen] = useState(false);
|
|
@@ -1768,6 +2425,7 @@ function ConnectButtonAccount({
|
|
|
1768
2425
|
deviceSecret: keys.signSk
|
|
1769
2426
|
});
|
|
1770
2427
|
const cloud = new CloudClient({
|
|
2428
|
+
cloudBaseUrl,
|
|
1771
2429
|
routingCredential: {
|
|
1772
2430
|
credential: enrolled.credential,
|
|
1773
2431
|
deviceSecret: keys.signSk
|
|
@@ -1788,7 +2446,7 @@ function ConnectButtonAccount({
|
|
|
1788
2446
|
return () => {
|
|
1789
2447
|
cancelled = true;
|
|
1790
2448
|
};
|
|
1791
|
-
}, [connectWithAccount]);
|
|
2449
|
+
}, [connectWithAccount, cloudBaseUrl]);
|
|
1792
2450
|
const goToWallet = useCallback(async () => {
|
|
1793
2451
|
const keys = await deviceKeys();
|
|
1794
2452
|
const state = hex(crypto.getRandomValues(new Uint8Array(16)));
|
|
@@ -1926,193 +2584,38 @@ function ConnectButtonAccount({
|
|
|
1926
2584
|
/* @__PURE__ */ jsx(
|
|
1927
2585
|
LoginModal,
|
|
1928
2586
|
{
|
|
1929
|
-
isOpen: isNodeModalOpen,
|
|
1930
|
-
onConnect: (url) => {
|
|
1931
|
-
setIsNodeModalOpen(false);
|
|
1932
|
-
connectToNode(url);
|
|
1933
|
-
},
|
|
1934
|
-
onClose: () => setIsNodeModalOpen(false),
|
|
1935
|
-
theme: resolvedTheme ?? theme
|
|
1936
|
-
}
|
|
1937
|
-
)
|
|
1938
|
-
] });
|
|
1939
|
-
}
|
|
1940
|
-
|
|
1941
|
-
// src/utils/base58.ts
|
|
1942
|
-
var ALPHABET = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
|
|
1943
|
-
function base58ToHex(input) {
|
|
1944
|
-
const bytes = [];
|
|
1945
|
-
for (const char of input) {
|
|
1946
|
-
let carry = ALPHABET.indexOf(char);
|
|
1947
|
-
if (carry === -1) throw new Error(`invalid base58 character: ${char}`);
|
|
1948
|
-
for (let i = 0; i < bytes.length; i++) {
|
|
1949
|
-
carry += bytes[i] * 58;
|
|
1950
|
-
bytes[i] = carry & 255;
|
|
1951
|
-
carry >>= 8;
|
|
1952
|
-
}
|
|
1953
|
-
while (carry > 0) {
|
|
1954
|
-
bytes.push(carry & 255);
|
|
1955
|
-
carry >>= 8;
|
|
1956
|
-
}
|
|
1957
|
-
}
|
|
1958
|
-
for (let k = 0; k < input.length && input[k] === "1"; k++) bytes.push(0);
|
|
1959
|
-
return bytes.reverse().map((b) => b.toString(16).padStart(2, "0")).join("");
|
|
1960
|
-
}
|
|
1961
|
-
function governanceNonce(relay, group) {
|
|
1962
|
-
return { next: async () => nextGovernanceNonce(relay, group) };
|
|
1963
|
-
}
|
|
1964
|
-
function nextGovernanceNonce(relay, group) {
|
|
1965
|
-
const key = `calimero.governance-nonce.${relay}.${group}`;
|
|
1966
|
-
let last = 0n;
|
|
1967
|
-
try {
|
|
1968
|
-
last = BigInt(localStorage.getItem(key) ?? "0");
|
|
1969
|
-
} catch {
|
|
1970
|
-
}
|
|
1971
|
-
const next = [last + 1n, BigInt(Date.now())].reduce((a, b) => a > b ? a : b);
|
|
1972
|
-
try {
|
|
1973
|
-
localStorage.setItem(key, String(next));
|
|
1974
|
-
} catch {
|
|
1975
|
-
}
|
|
1976
|
-
return next;
|
|
1977
|
-
}
|
|
1978
|
-
function relayFor(s, namespaceId) {
|
|
1979
|
-
const url = readRelayMap(s.account).namespaces[namespaceId] ?? s.relayUrl;
|
|
1980
|
-
if (!url) throw new Error("no relay is known for this namespace, so there is nowhere to send this");
|
|
1981
|
-
return url.replace(/\/+$/, "");
|
|
1982
|
-
}
|
|
1983
|
-
function initArgsOf(params) {
|
|
1984
|
-
if (!params || params.length === 0) return {};
|
|
1985
|
-
return JSON.parse(new TextDecoder().decode(Uint8Array.from(params)));
|
|
1986
|
-
}
|
|
1987
|
-
function client(s, relayUrl, nonces, fetch2) {
|
|
1988
|
-
return new RelayClient({
|
|
1989
|
-
relayUrl,
|
|
1990
|
-
authorAccount: s.account,
|
|
1991
|
-
authorProof: s.credential,
|
|
1992
|
-
deviceSecret: s.deviceSecret,
|
|
1993
|
-
nonces,
|
|
1994
|
-
fetch: fetch2
|
|
1995
|
-
});
|
|
1996
|
-
}
|
|
1997
|
-
async function createDelegatedContext(s, req, deps = {}) {
|
|
1998
|
-
const relay = relayFor(s, req.namespaceId);
|
|
1999
|
-
const creationNonce = 0n;
|
|
2000
|
-
const created = await client(s, relay, { next: async () => creationNonce }, deps.fetch).createContext({
|
|
2001
|
-
groupId: req.groupId ?? req.namespaceId,
|
|
2002
|
-
applicationId: req.applicationId,
|
|
2003
|
-
initArgs: initArgsOf(req.initializationParams),
|
|
2004
|
-
name: req.name
|
|
2005
|
-
});
|
|
2006
|
-
markContextNonceSpent(relay, created.contextId, creationNonce);
|
|
2007
|
-
rememberRelay(s.account, relay, { namespaceId: req.namespaceId, contextId: created.contextId });
|
|
2008
|
-
return { contextId: created.contextId };
|
|
2009
|
-
}
|
|
2010
|
-
async function delegatedGovernance(s, req, deps = {}) {
|
|
2011
|
-
const relay = relayFor(s, req.namespaceId);
|
|
2012
|
-
return client(s, relay, governanceNonce(relay, req.group), deps.fetch).govern({ groupId: req.group, op: req.op });
|
|
2013
|
-
}
|
|
2014
|
-
async function createDelegatedPrivateContext(s, req, deps = {}) {
|
|
2015
|
-
const { groupId } = await delegatedGovernance(
|
|
2016
|
-
s,
|
|
2017
|
-
{
|
|
2018
|
-
namespaceId: req.namespaceId,
|
|
2019
|
-
group: req.namespaceId,
|
|
2020
|
-
// The id is derived from a fresh salt (core#4244); a node refuses any other.
|
|
2021
|
-
op: (await subgroupCreation({ parentId: req.namespaceId, restricted: true, admin: s.account })).op
|
|
2022
|
-
},
|
|
2023
|
-
deps
|
|
2024
|
-
);
|
|
2025
|
-
for (const member of req.members) {
|
|
2026
|
-
await delegatedGovernance(s, { namespaceId: req.namespaceId, group: groupId, op: memberAddedOp(member, "Member") }, deps);
|
|
2027
|
-
}
|
|
2028
|
-
const { contextId } = await createDelegatedContext(s, { ...req, groupId }, deps);
|
|
2029
|
-
return { contextId, groupId };
|
|
2030
|
-
}
|
|
2031
|
-
async function foundDelegatedNamespace(s, req = {}, deps = {}) {
|
|
2032
|
-
const relays = knownRelays(s).map((u) => u.replace(/\/+$/, ""));
|
|
2033
|
-
const relay = relays[0];
|
|
2034
|
-
if (!relay) throw new Error("no relay is known for this account, so there is nowhere to found a namespace");
|
|
2035
|
-
const known = Object.entries(readRelayMap(s.account).namespaces).find(
|
|
2036
|
-
([, url]) => url.replace(/\/+$/, "") === relay
|
|
2037
|
-
)?.[0];
|
|
2038
|
-
if (!known) {
|
|
2039
|
-
throw new Error("join a namespace on this relay first: its executor account is learned from one you are in");
|
|
2040
|
-
}
|
|
2041
|
-
const { executorAccount } = await client(s, relay, governanceNonce(relay, known), deps.fetch).describeGovernance(known);
|
|
2042
|
-
let next = BigInt(Date.now());
|
|
2043
|
-
const founded = await client(s, relay, { next: async () => next++ }, deps.fetch).foundNamespace({
|
|
2044
|
-
executorAccount,
|
|
2045
|
-
...req.defaultCapabilities !== void 0 ? { defaultCapabilities: req.defaultCapabilities } : {},
|
|
2046
|
-
...req.application ? { application: req.application } : {}
|
|
2047
|
-
});
|
|
2048
|
-
try {
|
|
2049
|
-
localStorage.setItem(`calimero.governance-nonce.${relay}.${founded.namespaceId}`, String(next));
|
|
2050
|
-
} catch {
|
|
2051
|
-
}
|
|
2052
|
-
rememberRelay(s.account, relay, { namespaceId: founded.namespaceId });
|
|
2053
|
-
if (req.application && founded.applicationSet !== true) {
|
|
2054
|
-
throw new Error(
|
|
2055
|
-
`founded ${founded.namespaceId} but could not give it its application: ${founded.applicationError ?? "unknown reason"}`
|
|
2056
|
-
);
|
|
2057
|
-
}
|
|
2058
|
-
return { namespaceId: founded.namespaceId, teeEnabled: founded.teeEnabled };
|
|
2059
|
-
}
|
|
2060
|
-
async function latestPublishedVersion(registryUrl, pkg, fetchFn = globalThis.fetch) {
|
|
2061
|
-
const url = `${registryUrl.replace(/\/+$/, "")}/api/v2/bundles?package=${encodeURIComponent(pkg)}`;
|
|
2062
|
-
const response = await fetchFn(url, { headers: { Accept: "application/json" } });
|
|
2063
|
-
if (!response.ok) throw new Error(`the registry has no ${pkg} (HTTP ${response.status})`);
|
|
2064
|
-
const bundles = await response.json();
|
|
2065
|
-
const newer = (a, b) => {
|
|
2066
|
-
const [x, y] = [a, b].map((v) => v.split(/[.-]/).map((n) => Number.parseInt(n, 10) || 0));
|
|
2067
|
-
for (let i = 0; i < Math.max(x.length, y.length); i++) {
|
|
2068
|
-
if ((x[i] ?? 0) !== (y[i] ?? 0)) return (x[i] ?? 0) > (y[i] ?? 0);
|
|
2069
|
-
}
|
|
2070
|
-
return false;
|
|
2071
|
-
};
|
|
2072
|
-
const latest = bundles.map((b) => b.appVersion).filter((v) => typeof v === "string" && v.length > 0).reduce((best, v) => !best || newer(v, best) ? v : best, void 0);
|
|
2073
|
-
if (!latest) throw new Error(`the registry lists no version of ${pkg}`);
|
|
2074
|
-
return latest;
|
|
2587
|
+
isOpen: isNodeModalOpen,
|
|
2588
|
+
onConnect: (url) => {
|
|
2589
|
+
setIsNodeModalOpen(false);
|
|
2590
|
+
connectToNode(url);
|
|
2591
|
+
},
|
|
2592
|
+
onClose: () => setIsNodeModalOpen(false),
|
|
2593
|
+
theme: resolvedTheme ?? theme
|
|
2594
|
+
}
|
|
2595
|
+
)
|
|
2596
|
+
] });
|
|
2075
2597
|
}
|
|
2076
2598
|
|
|
2077
|
-
// src/
|
|
2078
|
-
var
|
|
2079
|
-
function
|
|
2080
|
-
|
|
2081
|
-
|
|
2082
|
-
|
|
2083
|
-
|
|
2084
|
-
|
|
2085
|
-
|
|
2086
|
-
|
|
2087
|
-
|
|
2088
|
-
|
|
2089
|
-
|
|
2090
|
-
|
|
2091
|
-
|
|
2092
|
-
|
|
2093
|
-
}
|
|
2094
|
-
function namespaceOfGroup(s, groupId) {
|
|
2095
|
-
if (readRelayMap(s.account).namespaces[groupId]) return groupId;
|
|
2096
|
-
return readGroupNamespaces(s.account)[groupId];
|
|
2097
|
-
}
|
|
2098
|
-
function requireNamespace(s, groupId) {
|
|
2099
|
-
const ns = namespaceOfGroup(s, groupId);
|
|
2100
|
-
if (!ns) {
|
|
2101
|
-
throw new Error(
|
|
2102
|
-
`the namespace of group ${groupId} is not known to this account: it can manage only groups in namespaces it joined or subgroups it created`
|
|
2103
|
-
);
|
|
2599
|
+
// src/utils/base58.ts
|
|
2600
|
+
var ALPHABET = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
|
|
2601
|
+
function base58ToHex(input) {
|
|
2602
|
+
const bytes = [];
|
|
2603
|
+
for (const char of input) {
|
|
2604
|
+
let carry = ALPHABET.indexOf(char);
|
|
2605
|
+
if (carry === -1) throw new Error(`invalid base58 character: ${char}`);
|
|
2606
|
+
for (let i = 0; i < bytes.length; i++) {
|
|
2607
|
+
carry += bytes[i] * 58;
|
|
2608
|
+
bytes[i] = carry & 255;
|
|
2609
|
+
carry >>= 8;
|
|
2610
|
+
}
|
|
2611
|
+
while (carry > 0) {
|
|
2612
|
+
bytes.push(carry & 255);
|
|
2613
|
+
carry >>= 8;
|
|
2614
|
+
}
|
|
2104
2615
|
}
|
|
2105
|
-
|
|
2106
|
-
|
|
2107
|
-
async function governGroup(s, groupId, op) {
|
|
2108
|
-
return delegatedGovernance(s, { namespaceId: requireNamespace(s, groupId), group: groupId, op });
|
|
2109
|
-
}
|
|
2110
|
-
async function governRoot(s, groupId, op) {
|
|
2111
|
-
const namespaceId = requireNamespace(s, groupId);
|
|
2112
|
-
return delegatedGovernance(s, { namespaceId, group: namespaceId, op });
|
|
2616
|
+
for (let k = 0; k < input.length && input[k] === "1"; k++) bytes.push(0);
|
|
2617
|
+
return bytes.reverse().map((b) => b.toString(16).padStart(2, "0")).join("");
|
|
2113
2618
|
}
|
|
2114
|
-
|
|
2115
|
-
// src/hooks/index.ts
|
|
2116
2619
|
var NO_EPHEMERAL_SURFACE_MESSAGE = "useEphemeral: this client has no `mero.ephemeral` surface. Ephemeral presence requires @calimero-network/mero-js >= 9.1.0; upgrade the installed @calimero-network/mero-js (and any lockfile pin) to use it.";
|
|
2117
2620
|
var COULD_NOT_RESOLVE_IDENTITY_MESSAGE = "useEphemeral: could not resolve a local context identity, so your own presence cannot be filtered out. Pass includeSelf: true to accept this.";
|
|
2118
2621
|
var REPLAY_RECONCILE_MS = 50;
|
|
@@ -3927,204 +4430,18 @@ function MigrationAdminPanel({ namespaceId, pollIntervalMs, className }) {
|
|
|
3927
4430
|
] })
|
|
3928
4431
|
] });
|
|
3929
4432
|
}
|
|
3930
|
-
function normaliseAccount(account) {
|
|
3931
|
-
if (!account) return null;
|
|
3932
|
-
const trimmed = account.trim().toLowerCase();
|
|
3933
|
-
const bare = trimmed.startsWith("0x") ? trimmed.slice(2) : trimmed;
|
|
3934
|
-
return bare.length > 0 ? bare : null;
|
|
3935
|
-
}
|
|
3936
|
-
function isInvited(node, invited) {
|
|
3937
|
-
if (invited.size === 0) return true;
|
|
3938
|
-
const account = normaliseAccount(node.account);
|
|
3939
|
-
return account !== null && invited.has(account);
|
|
3940
|
-
}
|
|
3941
|
-
async function resolveRelayFromInvitation(input) {
|
|
3942
|
-
const cloud = input.cloud ?? new CloudClient({
|
|
3943
|
-
cloudBaseUrl: input.cloudBaseUrl,
|
|
3944
|
-
routingCredential: { credential: input.credential, deviceSecret: input.deviceSecret }
|
|
3945
|
-
});
|
|
3946
|
-
let nodes;
|
|
3947
|
-
let servable;
|
|
3948
|
-
try {
|
|
3949
|
-
const routing = await cloud.getNamespaceRouting(input.namespaceId);
|
|
3950
|
-
nodes = routing.nodes;
|
|
3951
|
-
servable = routing.servable;
|
|
3952
|
-
} catch (e) {
|
|
3953
|
-
return {
|
|
3954
|
-
ok: false,
|
|
3955
|
-
step: "admitters-lookup",
|
|
3956
|
-
reason: `The cloud could not be asked which nodes serve namespace ${input.namespaceId}: ${e instanceof Error ? e.message : String(e)}. Nothing is known about the invitation yet \u2014 this is the lookup failing, not the invitation.`
|
|
3957
|
-
};
|
|
3958
|
-
}
|
|
3959
|
-
if (nodes.length === 0) {
|
|
3960
|
-
return {
|
|
3961
|
-
ok: false,
|
|
3962
|
-
step: "no-nodes",
|
|
3963
|
-
reason: "The cloud lists no nodes serving this namespace, so there is no hosted node to be admitted through. The namespace has no fleet assignment \u2014 whoever invited you is running their own node, and admission has to go through a node the cloud routes to."
|
|
3964
|
-
};
|
|
3965
|
-
}
|
|
3966
|
-
const invited = new Set(
|
|
3967
|
-
(input.admitters ?? []).map(normaliseAccount).filter((a) => a !== null)
|
|
3968
|
-
);
|
|
3969
|
-
const named = nodes.filter((n) => isInvited(n, invited));
|
|
3970
|
-
if (named.length === 0) {
|
|
3971
|
-
return {
|
|
3972
|
-
ok: false,
|
|
3973
|
-
step: "not-invited",
|
|
3974
|
-
reason: `${nodes.length} node${nodes.length === 1 ? "" : "s"} serve this namespace, but your invitation names none of them. The signed admitter list is a snapshot from when the invitation was minted, so a node assigned since is healthy and will still refuse the claim. Ask for a fresh invitation.`
|
|
3975
|
-
};
|
|
3976
|
-
}
|
|
3977
|
-
const usable = named.filter((n) => n.canAdmit);
|
|
3978
|
-
const candidates = usable.length > 0 ? usable : named;
|
|
3979
|
-
const advisory = usable.length === 0 || !servable;
|
|
3980
|
-
const addressable = candidates.filter(
|
|
3981
|
-
(n) => typeof n.relayUrl === "string" && n.relayUrl.length > 0
|
|
3982
|
-
);
|
|
3983
|
-
if (addressable.length === 0) {
|
|
3984
|
-
return {
|
|
3985
|
-
ok: false,
|
|
3986
|
-
step: "no-relay-url",
|
|
3987
|
-
reason: "A node your invitation names can admit you, but the cloud knows no address for it yet, so there would be nothing to connect through afterwards. Try again shortly."
|
|
3988
|
-
};
|
|
3989
|
-
}
|
|
3990
|
-
const chosen = addressable.find((n) => n.canExecute) ?? addressable.find((n) => n.fresh) ?? addressable[0];
|
|
3991
|
-
return {
|
|
3992
|
-
ok: true,
|
|
3993
|
-
relayUrl: chosen.relayUrl,
|
|
3994
|
-
// The cloud's ready-made URL when it gave one, so the path is never rebuilt
|
|
3995
|
-
// from a guess; the fallback is the documented route on the same origin.
|
|
3996
|
-
admitUrl: chosen.admitUrl ?? `${chosen.relayUrl.replace(/\/+$/, "")}/admin-api/namespaces/${input.namespaceId}/admit`,
|
|
3997
|
-
admitterAccount: chosen.account,
|
|
3998
|
-
peerId: chosen.peerId,
|
|
3999
|
-
writable: chosen.canExecute,
|
|
4000
|
-
// Stale when the node's own heartbeat lapsed OR when the cloud's summary
|
|
4001
|
-
// disagrees with trying it at all. Both mean the same thing to a caller:
|
|
4002
|
-
// this was attempted on advisory data, so if the admit fails that is why.
|
|
4003
|
-
stale: !chosen.fresh || advisory
|
|
4004
|
-
};
|
|
4005
|
-
}
|
|
4006
|
-
function explainAdmitFailure(status, body) {
|
|
4007
|
-
const detail = body ? `: ${body}` : "";
|
|
4008
|
-
switch (status) {
|
|
4009
|
-
case 400:
|
|
4010
|
-
return `The node refused the join as malformed (400)${detail}. The signature covers the invitation exactly as sent, so an edited or re-serialised invitation fails here \u2014 as does a namespace id that is not the invitation's own group.`;
|
|
4011
|
-
case 403:
|
|
4012
|
-
return `The node refused to carry this join (403)${detail}. Either it is not in the invitation's signed admitters list \u2014 being live and listed by the cloud is not the same thing \u2014 or the invitation itself was rejected as expired or not the inviter\u2019s to issue.`;
|
|
4013
|
-
case 409:
|
|
4014
|
-
return `That node holds no device of its own, so it cannot endorse anyone (409)${detail}. Another admitter from the same invitation would work.`;
|
|
4015
|
-
default:
|
|
4016
|
-
return `The join was not published (HTTP ${status})${detail}.`;
|
|
4017
|
-
}
|
|
4018
|
-
}
|
|
4019
|
-
function joinNonce(account) {
|
|
4020
|
-
const source = createLocalStorageNonceSource(`calimero.delegated.joinnonce.${account}`);
|
|
4021
|
-
return () => source.next();
|
|
4022
|
-
}
|
|
4023
|
-
function origin(url) {
|
|
4024
|
-
return url.replace(/\/+$/, "");
|
|
4025
|
-
}
|
|
4026
|
-
async function joinWithNode(input) {
|
|
4027
|
-
const { account, credential, deviceSecret } = input.credential;
|
|
4028
|
-
let signedOp;
|
|
4029
|
-
try {
|
|
4030
|
-
signedOp = await signMemberJoinOp({
|
|
4031
|
-
namespaceId: input.namespaceId,
|
|
4032
|
-
member: account,
|
|
4033
|
-
invitation: input.invitation,
|
|
4034
|
-
credential,
|
|
4035
|
-
deviceSecret,
|
|
4036
|
-
nonce: await (input.deps?.nonce ?? joinNonce(account))()
|
|
4037
|
-
});
|
|
4038
|
-
} catch (e) {
|
|
4039
|
-
return {
|
|
4040
|
-
ok: false,
|
|
4041
|
-
step: "sign",
|
|
4042
|
-
reason: `The join op could not be signed, so nothing was sent: ${e instanceof Error ? e.message : String(e)}`
|
|
4043
|
-
};
|
|
4044
|
-
}
|
|
4045
|
-
const body = { invitation: input.invitation, signedOp };
|
|
4046
|
-
const url = input.admitUrl ?? `${origin(input.nodeUrl)}/admin-api/namespaces/${input.namespaceId}/admit`;
|
|
4047
|
-
const doFetch = input.deps?.fetch ?? fetch;
|
|
4048
|
-
let response;
|
|
4049
|
-
try {
|
|
4050
|
-
response = await doFetch(url, {
|
|
4051
|
-
method: "POST",
|
|
4052
|
-
// No Authorization header and no request proof, deliberately: the route is
|
|
4053
|
-
// unauthenticated because the joiner's signature is the authorization.
|
|
4054
|
-
headers: { "Content-Type": "application/json", Accept: "application/json" },
|
|
4055
|
-
body: JSON.stringify(body)
|
|
4056
|
-
});
|
|
4057
|
-
} catch (e) {
|
|
4058
|
-
return {
|
|
4059
|
-
ok: false,
|
|
4060
|
-
step: "admit",
|
|
4061
|
-
reason: `The admitter at ${input.nodeUrl} could not be reached: ${e instanceof Error ? e.message : String(e)}. The invitation is untouched \u2014 this is the node being unreachable, not a refusal.`
|
|
4062
|
-
};
|
|
4063
|
-
}
|
|
4064
|
-
const text = await response.text();
|
|
4065
|
-
if (!response.ok) {
|
|
4066
|
-
return {
|
|
4067
|
-
ok: false,
|
|
4068
|
-
step: "admit",
|
|
4069
|
-
status: response.status,
|
|
4070
|
-
reason: explainAdmitFailure(response.status, text)
|
|
4071
|
-
};
|
|
4072
|
-
}
|
|
4073
|
-
let published = false;
|
|
4074
|
-
try {
|
|
4075
|
-
const parsed = text ? JSON.parse(text) : {};
|
|
4076
|
-
published = parsed.data?.published === true;
|
|
4077
|
-
} catch {
|
|
4078
|
-
published = false;
|
|
4079
|
-
}
|
|
4080
|
-
return {
|
|
4081
|
-
ok: true,
|
|
4082
|
-
published,
|
|
4083
|
-
session: { relayUrl: origin(input.nodeUrl), account, credential, deviceSecret }
|
|
4084
|
-
};
|
|
4085
|
-
}
|
|
4086
|
-
|
|
4087
|
-
// src/delegated/bootstrap-from-invitation.ts
|
|
4088
|
-
async function bootstrapFromInvitation(input) {
|
|
4089
|
-
const resolve = input.deps?.resolve ?? resolveRelayFromInvitation;
|
|
4090
|
-
const join = input.deps?.join ?? joinWithNode;
|
|
4091
|
-
let relay = null;
|
|
4092
|
-
let nodeUrl = input.nodeUrl;
|
|
4093
|
-
let admitUrl;
|
|
4094
|
-
if (!nodeUrl) {
|
|
4095
|
-
const resolved = await resolve({
|
|
4096
|
-
namespaceId: input.namespaceId,
|
|
4097
|
-
// The signed list, read off the invitation itself rather than passed
|
|
4098
|
-
// separately: two sources for one fact is how an intersection ends up
|
|
4099
|
-
// being performed against the wrong list.
|
|
4100
|
-
admitters: input.invitation.invitation.admitters,
|
|
4101
|
-
credential: input.credential.credential,
|
|
4102
|
-
deviceSecret: input.credential.deviceSecret,
|
|
4103
|
-
cloudBaseUrl: input.cloudBaseUrl
|
|
4104
|
-
});
|
|
4105
|
-
if (!resolved.ok) return resolved;
|
|
4106
|
-
relay = resolved;
|
|
4107
|
-
nodeUrl = resolved.relayUrl;
|
|
4108
|
-
admitUrl = resolved.admitUrl;
|
|
4109
|
-
}
|
|
4110
|
-
const joined = await join({
|
|
4111
|
-
nodeUrl,
|
|
4112
|
-
admitUrl,
|
|
4113
|
-
namespaceId: input.namespaceId,
|
|
4114
|
-
invitation: input.invitation,
|
|
4115
|
-
credential: input.credential,
|
|
4116
|
-
deps: { fetch: input.deps?.fetch, nonce: input.deps?.nonce }
|
|
4117
|
-
});
|
|
4118
|
-
if (!joined.ok) return joined;
|
|
4119
|
-
return { ok: true, published: joined.published, relay, session: joined.session };
|
|
4120
|
-
}
|
|
4121
4433
|
function useDelegatedBootstrap(options = {}) {
|
|
4122
|
-
const { connectWithAccount } = useMero();
|
|
4434
|
+
const { connectWithAccount, cloudBaseUrl: providerCloud } = useMero();
|
|
4123
4435
|
const [running, setRunning] = useState(false);
|
|
4124
4436
|
const [result, setResult] = useState(null);
|
|
4125
|
-
const
|
|
4437
|
+
const read = readDelegatedCredential();
|
|
4438
|
+
const credential = useMemo(
|
|
4439
|
+
() => read,
|
|
4440
|
+
// Keyed on the contents, not the parsed object.
|
|
4441
|
+
[read?.account, read?.credential, read?.deviceSecret]
|
|
4442
|
+
);
|
|
4126
4443
|
const relayUrl = readDelegatedSession()?.relayUrl ?? null;
|
|
4127
|
-
const
|
|
4444
|
+
const cloudBaseUrl = options.cloudBaseUrl ?? providerCloud;
|
|
4128
4445
|
const bootstrap = useCallback(
|
|
4129
4446
|
async (input) => {
|
|
4130
4447
|
const held = readDelegatedCredential();
|
|
@@ -4238,7 +4555,7 @@ function useJoinInvitation() {
|
|
|
4238
4555
|
return { ok: false, step: "node-join", reason: "Not connected to a node.", final: false };
|
|
4239
4556
|
}
|
|
4240
4557
|
await mero.admin.joinNamespace(input.namespaceId, { invitation: input.invitation });
|
|
4241
|
-
await mero.admin.joinContext(input.contextId);
|
|
4558
|
+
if (input.contextId) await mero.admin.joinContext(input.contextId);
|
|
4242
4559
|
return { ok: true };
|
|
4243
4560
|
} catch (e) {
|
|
4244
4561
|
const reason = e instanceof Error ? e.message : String(e);
|
|
@@ -4281,6 +4598,6 @@ function useJoinInvitation() {
|
|
|
4281
4598
|
return { joinInvitation, joining, memberships, invitationRedeemer };
|
|
4282
4599
|
}
|
|
4283
4600
|
|
|
4284
|
-
export { AppMode, CalimeroLogo, ConnectButton, ConnectButtonAccount, ConnectionType, DEFAULT_MIGRATION_POLL_INTERVAL_MS, LoginModal, MERO_CSS_VARS, MeroContext, MeroProvider, MigrationAdminPanel, MigrationPendingBanner, bootstrapFromInvitation, clearAllStorage, clearApplicationId, clearContextId, clearContextIdentity, clearDelegatedCredential, clearNodeUrl, clearTokenNodeUrl, createDelegatedContext, cssVar, defaultMeroTheme, getApplicationId, getContextId, getContextIdentity, getNodeUrl, getTokenNodeUrl, isFinalInvitationError, joinWithNode, listDelegatedContexts, localStorageTokenStorage, normaliseAccount, pinRelayNodeKey, readDelegatedCredential, readPinnedRelayNodeKey, readRelayMap, relayForContext, rememberRelay, resolveMeroTheme, resolveRelayFromInvitation, saveDelegatedCredential, setApplicationId, setContextId, setContextIdentity, setNodeUrl, setTokenNodeUrl, themeToCssVars, useAddGroupMembers, useAppVersion, useApplicationContexts, useBlobInfo, useBlobUrl, useContextDiscovery, useContextGroup, useContexts, useCreateContext, useCreateGroupInNamespace, useCreateNamespace, useCreateNamespaceInvitation, useCreatePrivateContext, useDefaultCapabilities, useDelegatedBootstrap, useDeleteContext, useDeleteGroup, useDeleteNamespace, useDetachContextFromGroup, useEphemeral, useExecute, useGroupAppVersion, useGroupCapabilities, useGroupContexts, useGroupInfo, useGroupInvitations, useGroupMembers, useGroupMetadata, useGroupUpgradeStatus, useInstallFromRegistry, useJoinContext, useJoinGroup, useJoinInvitation, useJoinNamespace, useJoinSubgroupInheritance, useLatestVersion, useMemberMetadata, useMero, useMigrationEvents, useMigrationStatus, useMyAuthoredMigration, useNamespace, useNamespaceGroups, useNamespaceIdentity, useNamespaces, useNamespacesForApplication, useNodeIdentity, useRedeemInvitation, useRemoveGroupMembers, useReparentGroup, useResyncContext, useRetryGroupUpgrade, useSetContextMetadata, useSetDefaultCapabilities, useSetGroupMetadata, useSetMemberMetadata, useSetSubgroupVisibility, useSetTeeAdmissionPolicy, useSubgroupVisibility, useSubgroups, useSubscription, useSyncGroup, useUpdateMemberRole, useUpgradeGroup, useUploadBlob };
|
|
4601
|
+
export { AppMode, CalimeroLogo, ConnectButton, ConnectButtonAccount, ConnectionType, DEFAULT_MIGRATION_POLL_INTERVAL_MS, LoginModal, MERO_CSS_VARS, MeroContext, MeroProvider, MigrationAdminPanel, MigrationPendingBanner, NoRelayError, NotForAccountError, bootstrapFromInvitation, clearAllStorage, clearApplicationId, clearContextId, clearContextIdentity, clearDelegatedCredential, clearNodeUrl, clearTokenNodeUrl, createAccountAdmin, createDelegatedContext, createNodeAdmin, cssVar, defaultMeroTheme, getApplicationId, getContextId, getContextIdentity, getNodeUrl, getTokenNodeUrl, isFinalInvitationError, joinWithNode, listDelegatedContexts, localStorageTokenStorage, normaliseAccount, pinRelayNodeKey, readDelegatedCredential, readPinnedRelayNodeKey, readRelayMap, relayForContext, rememberRelay, resolveMeroTheme, resolveRelayFromInvitation, saveDelegatedCredential, setApplicationId, setContextId, setContextIdentity, setNodeUrl, setTokenNodeUrl, themeToCssVars, useAddGroupMembers, useAppVersion, useApplicationContexts, useBlobInfo, useBlobUrl, useContextDiscovery, useContextGroup, useContexts, useCreateContext, useCreateGroupInNamespace, useCreateNamespace, useCreateNamespaceInvitation, useCreatePrivateContext, useDefaultCapabilities, useDelegatedBootstrap, useDeleteContext, useDeleteGroup, useDeleteNamespace, useDetachContextFromGroup, useEphemeral, useExecute, useGroupAppVersion, useGroupCapabilities, useGroupContexts, useGroupInfo, useGroupInvitations, useGroupMembers, useGroupMetadata, useGroupUpgradeStatus, useInstallFromRegistry, useJoinContext, useJoinGroup, useJoinInvitation, useJoinNamespace, useJoinSubgroupInheritance, useLatestVersion, useMemberMetadata, useMero, useMigrationEvents, useMigrationStatus, useMyAuthoredMigration, useNamespace, useNamespaceGroups, useNamespaceIdentity, useNamespaces, useNamespacesForApplication, useNodeIdentity, useRedeemInvitation, useRemoveGroupMembers, useReparentGroup, useResyncContext, useRetryGroupUpgrade, useSetContextMetadata, useSetDefaultCapabilities, useSetGroupMetadata, useSetMemberMetadata, useSetSubgroupVisibility, useSetTeeAdmissionPolicy, useSubgroupVisibility, useSubgroups, useSubscription, useSyncGroup, useUpdateMemberRole, useUpgradeGroup, useUploadBlob };
|
|
4285
4602
|
//# sourceMappingURL=index.js.map
|
|
4286
4603
|
//# sourceMappingURL=index.js.map
|