@calimero-network/mero-react 9.11.4 → 9.12.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 +159 -1339
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +37 -778
- package/dist/index.d.ts +37 -778
- package/dist/index.js +31 -1284
- package/dist/index.js.map +1 -1
- package/package.json +2 -3
package/dist/index.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { createContext, useMemo, useState, useRef, useCallback, useEffect, useContext } from 'react';
|
|
2
|
-
import {
|
|
2
|
+
import { LocalStorageTokenStore, readDelegatedSession, parseAuthCallback, MeroJs, buildAuthLoginUrl, saveDelegatedSession, saveDelegatedCredential, clearDelegatedSession, clearDelegatedCredential, relayForContext, buildDelegatedClient, readPinnedRelayNodeKey, learnRelayNodeKey, resolveApplicationIdFromRegistry, listDelegatedContexts, createAccountAdmin, createNodeAdmin, readEnrolmentCallback, completeDeviceEnrolment, CloudClient, deviceEnrolmentUrl, DEFAULT_LOCAL_NODE_PORTS, discoverLocalNodes, nodeEndpoint, createDelegatedContext, createDelegatedPrivateContext, governRoot, memberJoinedOpenOp, signerFromSecret, compareSemver, readDelegatedCredential, bootstrapFromInvitation, rememberRelay, carryExecutorAccount, listDelegatedNamespaces, AuthRevokedError, HTTPError, foundDelegatedNamespace, joinAsAccount, classifyError } from '@calimero-network/mero-js';
|
|
3
3
|
export * from '@calimero-network/mero-js';
|
|
4
|
-
export { CAPABILITIES, DEFAULT_LOCAL_NODE_PORTS, discoverLocalNodes, hasCap, localNodeUrl, nodeEndpoint, probeNodeHealth, withCap, withoutCap } from '@calimero-network/mero-js';
|
|
4
|
+
export { CAPABILITIES, DEFAULT_LOCAL_NODE_PORTS, HA_ACCOUNT_NOT_LINKED_MESSAGE, HA_REFUSAL_MESSAGES, InvitationNotClaimableError, NoRelayError, NotForAccountError, applicationIdForBundle, bootstrapFromInvitation, clearDelegatedCredential, createAccountAdmin, createDelegatedContext, createNodeAdmin, discoverLocalNodes, hasCap, joinWithNode, listDelegatedContexts, localNodeUrl, nodeEndpoint, normaliseAccount, pinRelayNodeKey, probeNodeHealth, readDelegatedCredential, readPinnedRelayNodeKey, readRelayMap, relayForContext, rememberRelay, resolveApplicationIdFromRegistry, resolveRelayFromInvitation, saveDelegatedCredential, selectLatestBundle, withCap, withoutCap } from '@calimero-network/mero-js';
|
|
5
5
|
import { jsx, jsxs, Fragment } from 'react/jsx-runtime';
|
|
6
6
|
import { createPortal } from 'react-dom';
|
|
7
7
|
|
|
@@ -44,1271 +44,6 @@ var ConnectionType = /* @__PURE__ */ ((ConnectionType2) => {
|
|
|
44
44
|
ConnectionType2["Custom"] = "custom";
|
|
45
45
|
return ConnectionType2;
|
|
46
46
|
})(ConnectionType || {});
|
|
47
|
-
var KEY = "calimero.delegated.connection";
|
|
48
|
-
var CREDENTIAL_KEY = "calimero.delegated.credential";
|
|
49
|
-
function readDelegatedSession() {
|
|
50
|
-
if (typeof sessionStorage === "undefined") return null;
|
|
51
|
-
try {
|
|
52
|
-
const raw = sessionStorage.getItem(KEY);
|
|
53
|
-
return raw ? JSON.parse(raw) : null;
|
|
54
|
-
} catch {
|
|
55
|
-
return null;
|
|
56
|
-
}
|
|
57
|
-
}
|
|
58
|
-
function saveDelegatedSession(s) {
|
|
59
|
-
try {
|
|
60
|
-
sessionStorage.setItem(KEY, JSON.stringify(s));
|
|
61
|
-
} catch {
|
|
62
|
-
}
|
|
63
|
-
}
|
|
64
|
-
function clearDelegatedSession() {
|
|
65
|
-
try {
|
|
66
|
-
sessionStorage.removeItem(KEY);
|
|
67
|
-
} catch {
|
|
68
|
-
}
|
|
69
|
-
}
|
|
70
|
-
function readDelegatedCredential() {
|
|
71
|
-
const session = readDelegatedSession();
|
|
72
|
-
if (session) {
|
|
73
|
-
const { account, credential, deviceSecret } = session;
|
|
74
|
-
return { account, credential, deviceSecret };
|
|
75
|
-
}
|
|
76
|
-
if (typeof sessionStorage === "undefined") return null;
|
|
77
|
-
try {
|
|
78
|
-
const raw = sessionStorage.getItem(CREDENTIAL_KEY);
|
|
79
|
-
if (!raw) return null;
|
|
80
|
-
const parsed = JSON.parse(raw);
|
|
81
|
-
if (!parsed.account || !parsed.credential || !parsed.deviceSecret) return null;
|
|
82
|
-
return parsed;
|
|
83
|
-
} catch {
|
|
84
|
-
return null;
|
|
85
|
-
}
|
|
86
|
-
}
|
|
87
|
-
function saveDelegatedCredential(c) {
|
|
88
|
-
try {
|
|
89
|
-
sessionStorage.setItem(CREDENTIAL_KEY, JSON.stringify(c));
|
|
90
|
-
} catch {
|
|
91
|
-
}
|
|
92
|
-
}
|
|
93
|
-
function clearDelegatedCredential() {
|
|
94
|
-
try {
|
|
95
|
-
sessionStorage.removeItem(CREDENTIAL_KEY);
|
|
96
|
-
} catch {
|
|
97
|
-
}
|
|
98
|
-
}
|
|
99
|
-
function persistedNonces(relayUrl) {
|
|
100
|
-
const key = nonceKey(relayUrl);
|
|
101
|
-
return {
|
|
102
|
-
next: async () => {
|
|
103
|
-
let n = 0n;
|
|
104
|
-
try {
|
|
105
|
-
n = readNonceFloor(relayUrl);
|
|
106
|
-
} catch {
|
|
107
|
-
n = 0n;
|
|
108
|
-
}
|
|
109
|
-
try {
|
|
110
|
-
localStorage.setItem(key, String(n + 1n));
|
|
111
|
-
} catch {
|
|
112
|
-
}
|
|
113
|
-
return n;
|
|
114
|
-
}
|
|
115
|
-
};
|
|
116
|
-
}
|
|
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) {
|
|
134
|
-
try {
|
|
135
|
-
if (readNonceFloor(relayUrl) <= nonce) localStorage.setItem(nonceKey(relayUrl), String(nonce + 1n));
|
|
136
|
-
} catch {
|
|
137
|
-
}
|
|
138
|
-
}
|
|
139
|
-
var RELAY_NODE_KEY_PREFIX = "calimero.delegated.relay-node-key.";
|
|
140
|
-
function relayOrigin(relayUrl) {
|
|
141
|
-
return relayUrl.replace(/\/+$/, "");
|
|
142
|
-
}
|
|
143
|
-
function pinRelayNodeKey(relayUrl, nodeKey) {
|
|
144
|
-
localStorage.setItem(RELAY_NODE_KEY_PREFIX + relayOrigin(relayUrl), nodeKey.trim().toLowerCase());
|
|
145
|
-
}
|
|
146
|
-
function readPinnedRelayNodeKey(relayUrl) {
|
|
147
|
-
try {
|
|
148
|
-
const v = localStorage.getItem(RELAY_NODE_KEY_PREFIX + relayOrigin(relayUrl));
|
|
149
|
-
return v && /^[0-9a-f]{64}$/.test(v) ? v : null;
|
|
150
|
-
} catch {
|
|
151
|
-
return null;
|
|
152
|
-
}
|
|
153
|
-
}
|
|
154
|
-
function isLoopback(relayUrl) {
|
|
155
|
-
try {
|
|
156
|
-
const { hostname } = new URL(relayUrl);
|
|
157
|
-
return hostname === "localhost" || hostname === "127.0.0.1" || hostname === "[::1]";
|
|
158
|
-
} catch {
|
|
159
|
-
return false;
|
|
160
|
-
}
|
|
161
|
-
}
|
|
162
|
-
var TRUSTED_RELAY_PROFILE = "locked-read-only";
|
|
163
|
-
var MIN_RELAY_RELEASE = "2.3.99";
|
|
164
|
-
var loadedDcap;
|
|
165
|
-
function dcapVerifyFrom(mod) {
|
|
166
|
-
const ns = mod;
|
|
167
|
-
const verify = typeof ns.verify === "function" ? ns.verify : ns.default?.verify;
|
|
168
|
-
if (typeof verify !== "function") {
|
|
169
|
-
throw new TypeError("@phala/dcap-qvl loaded without a verify function");
|
|
170
|
-
}
|
|
171
|
-
return verify;
|
|
172
|
-
}
|
|
173
|
-
var RelayKeyTransportError = class extends Error {
|
|
174
|
-
constructor(step, cause) {
|
|
175
|
-
super(`${step}: ${cause instanceof Error ? cause.message : String(cause)}`);
|
|
176
|
-
this.step = step;
|
|
177
|
-
this.cause = cause;
|
|
178
|
-
this.name = "RelayKeyTransportError";
|
|
179
|
-
}
|
|
180
|
-
};
|
|
181
|
-
async function transport(step, run) {
|
|
182
|
-
try {
|
|
183
|
-
return await run();
|
|
184
|
-
} catch (e) {
|
|
185
|
-
throw e instanceof RelayKeyTransportError ? e : new RelayKeyTransportError(step, e);
|
|
186
|
-
}
|
|
187
|
-
}
|
|
188
|
-
function relayFetch(marked) {
|
|
189
|
-
return async (input, init) => {
|
|
190
|
-
let response;
|
|
191
|
-
try {
|
|
192
|
-
response = await globalThis.fetch(input, init);
|
|
193
|
-
} catch (e) {
|
|
194
|
-
marked.failure = e;
|
|
195
|
-
throw new RelayKeyTransportError(`reaching ${String(input)}`, e);
|
|
196
|
-
}
|
|
197
|
-
if (!response.ok) marked.failure ?? (marked.failure = new Error(`${String(input)} answered HTTP ${response.status}`));
|
|
198
|
-
return response;
|
|
199
|
-
};
|
|
200
|
-
}
|
|
201
|
-
function relayQuoteVerifier(relayUrl, fetchRelay) {
|
|
202
|
-
const verify = async (attestation) => {
|
|
203
|
-
const dcapVerify = await transport("loading the quote verifier", () => {
|
|
204
|
-
loadedDcap ?? (loadedDcap = import('@phala/dcap-qvl').then(
|
|
205
|
-
(mod) => dcapVerifyFrom(mod),
|
|
206
|
-
(error) => {
|
|
207
|
-
loadedDcap = void 0;
|
|
208
|
-
throw error;
|
|
209
|
-
}
|
|
210
|
-
));
|
|
211
|
-
return loadedDcap;
|
|
212
|
-
});
|
|
213
|
-
return createSignedReleaseVerifier({
|
|
214
|
-
dcapVerify,
|
|
215
|
-
// Fetched only. Its signature, its version and the quote's registers are
|
|
216
|
-
// all checked by the verifier after this returns, and none of that is a
|
|
217
|
-
// transport question.
|
|
218
|
-
release: () => transport(
|
|
219
|
-
"fetching the release the relay runs",
|
|
220
|
-
async () => fetchNodeRelease(
|
|
221
|
-
cloudNodeReleaseUrl(DEFAULT_RELEASE_MIRROR, await fetchNodeReleaseVersion(relayUrl, { fetch: fetchRelay }))
|
|
222
|
-
)
|
|
223
|
-
),
|
|
224
|
-
profile: TRUSTED_RELAY_PROFILE,
|
|
225
|
-
minReleaseVersion: MIN_RELAY_RELEASE
|
|
226
|
-
})(attestation);
|
|
227
|
-
};
|
|
228
|
-
return Object.assign(verify, { includeCollateral: true });
|
|
229
|
-
}
|
|
230
|
-
async function attemptRelayNodeKey(relayUrl) {
|
|
231
|
-
const pinned = readPinnedRelayNodeKey(relayUrl);
|
|
232
|
-
if (pinned) return { kind: "learned", nodeKey: pinned };
|
|
233
|
-
const marked = { failure: null };
|
|
234
|
-
const fetchRelay = relayFetch(marked);
|
|
235
|
-
try {
|
|
236
|
-
const local = isLoopback(relayUrl);
|
|
237
|
-
const { nodeKey } = await attestRelayNodeKey({
|
|
238
|
-
relayUrl,
|
|
239
|
-
allowMock: local,
|
|
240
|
-
fetch: fetchRelay,
|
|
241
|
-
...local ? {} : { verify: relayQuoteVerifier(relayUrl, fetchRelay) }
|
|
242
|
-
});
|
|
243
|
-
pinRelayNodeKey(relayUrl, nodeKey);
|
|
244
|
-
return { kind: "learned", nodeKey };
|
|
245
|
-
} catch (e) {
|
|
246
|
-
if (e instanceof RelayKeyTransportError || marked.failure) return { kind: "unavailable", error: e };
|
|
247
|
-
return { kind: "refused", error: e };
|
|
248
|
-
}
|
|
249
|
-
}
|
|
250
|
-
async function resolveRelayNodeKey(relayUrl) {
|
|
251
|
-
const attempt = await attemptRelayNodeKey(relayUrl);
|
|
252
|
-
if (attempt.kind === "learned") return attempt.nodeKey;
|
|
253
|
-
console.warn("[mero-react] could not learn the relay node key from its attestation", attempt.error);
|
|
254
|
-
return null;
|
|
255
|
-
}
|
|
256
|
-
var RELAY_NODE_KEY_RETRY_MS = [1e3, 2e3, 5e3, 1e4, 3e4];
|
|
257
|
-
function pause(ms, signal) {
|
|
258
|
-
return new Promise((resolve) => {
|
|
259
|
-
if (signal?.aborted) return resolve();
|
|
260
|
-
const timer = setTimeout(done, ms);
|
|
261
|
-
function done() {
|
|
262
|
-
clearTimeout(timer);
|
|
263
|
-
signal?.removeEventListener("abort", done);
|
|
264
|
-
resolve();
|
|
265
|
-
}
|
|
266
|
-
signal?.addEventListener("abort", done);
|
|
267
|
-
});
|
|
268
|
-
}
|
|
269
|
-
async function learnRelayNodeKey(relayUrl, options = {}) {
|
|
270
|
-
const { signal } = options;
|
|
271
|
-
for (let failures = 0; !signal?.aborted; failures += 1) {
|
|
272
|
-
const attempt = await attemptRelayNodeKey(relayUrl);
|
|
273
|
-
if (attempt.kind === "learned") return attempt.nodeKey;
|
|
274
|
-
if (attempt.kind === "refused") {
|
|
275
|
-
console.warn("[mero-react] refusing the relay's attestation; its node key stays unknown", attempt.error);
|
|
276
|
-
return null;
|
|
277
|
-
}
|
|
278
|
-
const wait = RELAY_NODE_KEY_RETRY_MS[Math.min(failures, RELAY_NODE_KEY_RETRY_MS.length - 1)];
|
|
279
|
-
console.warn(
|
|
280
|
-
`[mero-react] could not reach what proves the relay's node key; retrying in ${wait / 1e3} s`,
|
|
281
|
-
attempt.error
|
|
282
|
-
);
|
|
283
|
-
await pause(wait, signal);
|
|
284
|
-
}
|
|
285
|
-
return null;
|
|
286
|
-
}
|
|
287
|
-
function jwtExpiryMs(token) {
|
|
288
|
-
try {
|
|
289
|
-
const payload = JSON.parse(atob(token.split(".")[1].replace(/-/g, "+").replace(/_/g, "/")));
|
|
290
|
-
return typeof payload.exp === "number" ? payload.exp * 1e3 : null;
|
|
291
|
-
} catch {
|
|
292
|
-
return null;
|
|
293
|
-
}
|
|
294
|
-
}
|
|
295
|
-
function relaySession(s, nodeKey) {
|
|
296
|
-
let token = null;
|
|
297
|
-
let inflight = null;
|
|
298
|
-
return async () => {
|
|
299
|
-
const exp = token ? jwtExpiryMs(token) : null;
|
|
300
|
-
if (token && (exp === null || exp - Date.now() > 3e4)) return token;
|
|
301
|
-
if (!inflight) {
|
|
302
|
-
inflight = login({
|
|
303
|
-
nodeUrl: s.relayUrl,
|
|
304
|
-
node: nodeKey,
|
|
305
|
-
deviceSecret: s.deviceSecret,
|
|
306
|
-
accountProof: s.credential,
|
|
307
|
-
audience: defaultAudience()
|
|
308
|
-
}).then((minted) => {
|
|
309
|
-
token = minted.accessToken;
|
|
310
|
-
return token;
|
|
311
|
-
}).catch((e) => {
|
|
312
|
-
console.warn("[mero-react] relay login failed", e);
|
|
313
|
-
token = null;
|
|
314
|
-
return void 0;
|
|
315
|
-
}).finally(() => {
|
|
316
|
-
inflight = null;
|
|
317
|
-
});
|
|
318
|
-
}
|
|
319
|
-
return inflight;
|
|
320
|
-
};
|
|
321
|
-
}
|
|
322
|
-
var methodKinds = /* @__PURE__ */ new Map();
|
|
323
|
-
function isNotAView(e) {
|
|
324
|
-
return typeof e === "object" && e !== null && e.status === 409;
|
|
325
|
-
}
|
|
326
|
-
function readsThroughQuery(client2, relayUrl) {
|
|
327
|
-
const inner = client2.rpc;
|
|
328
|
-
const origin2 = relayOrigin(relayUrl);
|
|
329
|
-
const run = async (params) => {
|
|
330
|
-
const key = `${origin2}|${params.contextId}|${params.method}`;
|
|
331
|
-
if (methodKinds.get(key) !== "write") {
|
|
332
|
-
try {
|
|
333
|
-
const { returns } = await client2.admin.queryContext(params.contextId, {
|
|
334
|
-
method: params.method,
|
|
335
|
-
// The node defaults a warrant's missing `argsJson` to `{}`; the same here.
|
|
336
|
-
argsJson: params.argsJson ?? {}
|
|
337
|
-
});
|
|
338
|
-
methodKinds.set(key, "read");
|
|
339
|
-
return { returns, transport: "relay" };
|
|
340
|
-
} catch (e) {
|
|
341
|
-
if (isNotAView(e)) methodKinds.set(key, "write");
|
|
342
|
-
}
|
|
343
|
-
}
|
|
344
|
-
return inner.executeWithMetadata(params);
|
|
345
|
-
};
|
|
346
|
-
return {
|
|
347
|
-
get kind() {
|
|
348
|
-
return inner.kind;
|
|
349
|
-
},
|
|
350
|
-
get canSubscribe() {
|
|
351
|
-
return inner.canSubscribe;
|
|
352
|
-
},
|
|
353
|
-
execute: async (params) => (await run(params)).returns,
|
|
354
|
-
executeWithMetadata: run,
|
|
355
|
-
migrateMyEntries: (contextId) => inner.migrateMyEntries(contextId),
|
|
356
|
-
countMyPending: (contextId) => inner.countMyPending(contextId)
|
|
357
|
-
};
|
|
358
|
-
}
|
|
359
|
-
function dormantEvents(relayUrl) {
|
|
360
|
-
return new SseClient({
|
|
361
|
-
baseUrl: relayUrl,
|
|
362
|
-
authorize: async () => ({}),
|
|
363
|
-
fetch: (_url, init) => new Promise((_, reject) => {
|
|
364
|
-
const abort = () => reject(Object.assign(new Error("the stream was closed before the relay was attested"), { name: "AbortError" }));
|
|
365
|
-
if (init?.signal?.aborted) return abort();
|
|
366
|
-
init?.signal?.addEventListener("abort", abort, { once: true });
|
|
367
|
-
})
|
|
368
|
-
});
|
|
369
|
-
}
|
|
370
|
-
function delegatedClient(client2, opts) {
|
|
371
|
-
const rpc = opts.session ? readsThroughQuery(client2, opts.relayUrl) : null;
|
|
372
|
-
let dormant = null;
|
|
373
|
-
return new Proxy(client2, {
|
|
374
|
-
get(target, prop) {
|
|
375
|
-
if (prop === "rpc" && rpc) return rpc;
|
|
376
|
-
if (!opts.attested) {
|
|
377
|
-
if (prop === "canSubscribe") return false;
|
|
378
|
-
if (prop === "events") return dormant ?? (dormant = dormantEvents(opts.relayUrl));
|
|
379
|
-
if (prop === "close") {
|
|
380
|
-
return () => {
|
|
381
|
-
dormant?.close();
|
|
382
|
-
target.close();
|
|
383
|
-
};
|
|
384
|
-
}
|
|
385
|
-
}
|
|
386
|
-
const value = Reflect.get(target, prop, target);
|
|
387
|
-
return typeof value === "function" ? value.bind(target) : value;
|
|
388
|
-
}
|
|
389
|
-
});
|
|
390
|
-
}
|
|
391
|
-
function buildDelegatedClient(s, _contextId) {
|
|
392
|
-
if (!s.relayUrl) return null;
|
|
393
|
-
const nodeKey = readPinnedRelayNodeKey(s.relayUrl);
|
|
394
|
-
const client2 = createMeroClient({
|
|
395
|
-
transport: "relay",
|
|
396
|
-
relay: {
|
|
397
|
-
relayUrl: s.relayUrl,
|
|
398
|
-
authorAccount: s.account,
|
|
399
|
-
authorProof: s.credential,
|
|
400
|
-
deviceSecret: s.deviceSecret,
|
|
401
|
-
// One sequence per relay, whatever context is chosen: `execute` takes a
|
|
402
|
-
// context per call, so the nonce source must not depend on this one.
|
|
403
|
-
nonces: persistedNonces(s.relayUrl)
|
|
404
|
-
},
|
|
405
|
-
// The certificate authenticates the requests too, not just the writes.
|
|
406
|
-
//
|
|
407
|
-
// This is the whole of what reads and events need: the device key signs each
|
|
408
|
-
// request, and the node verifies it against the account's certificate with no
|
|
409
|
-
// store read and no prior relationship. Measured against a node built from
|
|
410
|
-
// core `aecba573b`: `listNamespaces` and `getContexts` answer `200` and are
|
|
411
|
-
// caller-scoped, `/sse` answers `200`, and a real write arrives on the stream
|
|
412
|
-
// as a `StateMutation` frame.
|
|
413
|
-
//
|
|
414
|
-
// What this replaces is a session minted by `login()` plus the relay node's
|
|
415
|
-
// signing key learned out of band — two inputs, one of which the cloud does
|
|
416
|
-
// not publish, for an answer the certificate already gives.
|
|
417
|
-
proof: { credential: s.credential, deviceSecret: s.deviceSecret },
|
|
418
|
-
// A session, when this relay's node key is pinned. A hosted relay's
|
|
419
|
-
// forward-auth accepts a Bearer token and not the proof above, so without
|
|
420
|
-
// one every admin read there is a 401. Given a session the client uses it
|
|
421
|
-
// for every admin call; a relay with no pinned key keeps the proof path.
|
|
422
|
-
session: nodeKey ? relaySession({ ...s, relayUrl: s.relayUrl }, nodeKey) : void 0,
|
|
423
|
-
// Events too. `/sse` on a relay sits behind the same forward-auth, so the
|
|
424
|
-
// proof above gets a 401 there; with the node key the client observes
|
|
425
|
-
// through its own device-certificate login instead.
|
|
426
|
-
observe: nodeKey ? { nodeKey } : void 0
|
|
427
|
-
});
|
|
428
|
-
return delegatedClient(client2, {
|
|
429
|
-
relayUrl: s.relayUrl,
|
|
430
|
-
session: nodeKey !== null,
|
|
431
|
-
attested: nodeKey !== null || isLoopback(s.relayUrl)
|
|
432
|
-
});
|
|
433
|
-
}
|
|
434
|
-
var RELAY_MAP_PREFIX = "calimero.delegated.relays.";
|
|
435
|
-
function readRelayMap(account) {
|
|
436
|
-
try {
|
|
437
|
-
const raw = localStorage.getItem(RELAY_MAP_PREFIX + account);
|
|
438
|
-
const parsed = raw ? JSON.parse(raw) : {};
|
|
439
|
-
return { namespaces: parsed.namespaces ?? {}, contexts: parsed.contexts ?? {} };
|
|
440
|
-
} catch {
|
|
441
|
-
return { namespaces: {}, contexts: {} };
|
|
442
|
-
}
|
|
443
|
-
}
|
|
444
|
-
function writeRelayMap(account, map) {
|
|
445
|
-
try {
|
|
446
|
-
localStorage.setItem(RELAY_MAP_PREFIX + account, JSON.stringify(map));
|
|
447
|
-
} catch {
|
|
448
|
-
}
|
|
449
|
-
}
|
|
450
|
-
function rememberRelay(account, relayUrl, at) {
|
|
451
|
-
const map = readRelayMap(account);
|
|
452
|
-
const url = relayOrigin(relayUrl);
|
|
453
|
-
if (at.namespaceId) map.namespaces[at.namespaceId] = url;
|
|
454
|
-
if (at.contextId) map.contexts[at.contextId] = url;
|
|
455
|
-
writeRelayMap(account, map);
|
|
456
|
-
}
|
|
457
|
-
function relayForContext(account, contextId) {
|
|
458
|
-
return readRelayMap(account).contexts[contextId] ?? null;
|
|
459
|
-
}
|
|
460
|
-
function carryExecutorAccount(prev, next) {
|
|
461
|
-
if (next.executorAccount || !prev?.executorAccount || !prev.relayUrl || !next.relayUrl) return next;
|
|
462
|
-
if (relayOrigin(prev.relayUrl) !== relayOrigin(next.relayUrl)) return next;
|
|
463
|
-
return { ...next, executorAccount: prev.executorAccount };
|
|
464
|
-
}
|
|
465
|
-
function knownRelays(s) {
|
|
466
|
-
const map = readRelayMap(s.account);
|
|
467
|
-
const all = [s.relayUrl, ...Object.values(map.namespaces), ...Object.values(map.contexts)].filter((u) => typeof u === "string" && u.length > 0).map(relayOrigin);
|
|
468
|
-
return [...new Set(all)];
|
|
469
|
-
}
|
|
470
|
-
async function listDelegatedContexts(s) {
|
|
471
|
-
const out = [];
|
|
472
|
-
const map = readRelayMap(s.account);
|
|
473
|
-
for (const relayUrl of knownRelays(s)) {
|
|
474
|
-
try {
|
|
475
|
-
if (!await resolveRelayNodeKey(relayUrl)) continue;
|
|
476
|
-
const client2 = buildDelegatedClient({ ...s, relayUrl }, null);
|
|
477
|
-
if (!client2) continue;
|
|
478
|
-
const { contexts } = await client2.admin.getContexts();
|
|
479
|
-
for (const c of contexts ?? []) {
|
|
480
|
-
out.push({ ...c, relayUrl });
|
|
481
|
-
map.contexts[c.id] = relayUrl;
|
|
482
|
-
}
|
|
483
|
-
} catch (e) {
|
|
484
|
-
console.warn(`[mero-react] could not list contexts on ${relayUrl}`, e);
|
|
485
|
-
}
|
|
486
|
-
}
|
|
487
|
-
writeRelayMap(s.account, map);
|
|
488
|
-
return out;
|
|
489
|
-
}
|
|
490
|
-
async function listDelegatedNamespaces(s) {
|
|
491
|
-
var _a, _b;
|
|
492
|
-
const out = [];
|
|
493
|
-
const seen = /* @__PURE__ */ new Set();
|
|
494
|
-
const map = readRelayMap(s.account);
|
|
495
|
-
for (const relayUrl of knownRelays(s)) {
|
|
496
|
-
try {
|
|
497
|
-
if (!await resolveRelayNodeKey(relayUrl)) continue;
|
|
498
|
-
const client2 = buildDelegatedClient({ ...s, relayUrl }, null);
|
|
499
|
-
if (!client2) continue;
|
|
500
|
-
for (const ns of await client2.admin.listNamespaces()) {
|
|
501
|
-
if (seen.has(ns.namespaceId)) continue;
|
|
502
|
-
seen.add(ns.namespaceId);
|
|
503
|
-
out.push({ ...ns, relayUrl });
|
|
504
|
-
(_a = map.namespaces)[_b = ns.namespaceId] ?? (_a[_b] = relayUrl);
|
|
505
|
-
}
|
|
506
|
-
} catch (e) {
|
|
507
|
-
console.warn(`[mero-react] could not list namespaces on ${relayUrl}`, e);
|
|
508
|
-
}
|
|
509
|
-
}
|
|
510
|
-
writeRelayMap(s.account, map);
|
|
511
|
-
return out;
|
|
512
|
-
}
|
|
513
|
-
|
|
514
|
-
// src/delegated/application-id.ts
|
|
515
|
-
function borshString(s) {
|
|
516
|
-
const bytes = new TextEncoder().encode(s);
|
|
517
|
-
const out = new Uint8Array(4 + bytes.length);
|
|
518
|
-
new DataView(out.buffer).setUint32(0, bytes.length, true);
|
|
519
|
-
out.set(bytes, 4);
|
|
520
|
-
return out;
|
|
521
|
-
}
|
|
522
|
-
async function applicationIdForBundle(pkg, signerId) {
|
|
523
|
-
const a = borshString(pkg);
|
|
524
|
-
const b = borshString(signerId);
|
|
525
|
-
const tuple = new Uint8Array(a.length + b.length);
|
|
526
|
-
tuple.set(a, 0);
|
|
527
|
-
tuple.set(b, a.length);
|
|
528
|
-
const digest = await crypto.subtle.digest("SHA-256", tuple);
|
|
529
|
-
return Array.from(new Uint8Array(digest), (x) => x.toString(16).padStart(2, "0")).join("");
|
|
530
|
-
}
|
|
531
|
-
function newer(a, b) {
|
|
532
|
-
const [x, y] = [a, b].map((v) => v.split(/[.-]/).map((n) => Number.parseInt(n, 10) || 0));
|
|
533
|
-
for (let i = 0; i < Math.max(x.length, y.length); i++) {
|
|
534
|
-
if ((x[i] ?? 0) !== (y[i] ?? 0)) return (x[i] ?? 0) > (y[i] ?? 0);
|
|
535
|
-
}
|
|
536
|
-
return false;
|
|
537
|
-
}
|
|
538
|
-
function selectLatestBundle(bundles) {
|
|
539
|
-
return bundles.filter((b) => !b.yanked && typeof b.appVersion === "string" && b.appVersion.length > 0).reduce((best, b) => !best || newer(b.appVersion, best.appVersion) ? b : best, void 0);
|
|
540
|
-
}
|
|
541
|
-
async function fetchRegistryBundles(registryUrl, pkg, fetchFn = globalThis.fetch) {
|
|
542
|
-
const url = `${registryUrl.replace(/\/+$/, "")}/api/v2/bundles?package=${encodeURIComponent(pkg)}`;
|
|
543
|
-
const response = await fetchFn(url, { headers: { Accept: "application/json" } });
|
|
544
|
-
if (!response.ok) throw new Error(`the registry has no ${pkg} (HTTP ${response.status})`);
|
|
545
|
-
const body = await response.json();
|
|
546
|
-
return Array.isArray(body) ? body : [];
|
|
547
|
-
}
|
|
548
|
-
async function resolveApplicationIdFromRegistry(registryUrl, pkg, deps = {}) {
|
|
549
|
-
const bundles = await fetchRegistryBundles(registryUrl, pkg, deps.fetch);
|
|
550
|
-
const live = bundles.filter((b) => !b.yanked);
|
|
551
|
-
const signers = [...new Set(live.map((b) => b.signerId).filter((s) => typeof s === "string" && s.length > 0))];
|
|
552
|
-
if (signers.length > 1) {
|
|
553
|
-
throw new Error(
|
|
554
|
-
`the registry lists ${pkg} under more than one publisher (${signers.join(", ")}): refusing to guess which application it is`
|
|
555
|
-
);
|
|
556
|
-
}
|
|
557
|
-
const latest = selectLatestBundle(live);
|
|
558
|
-
if (!latest) throw new Error(`the registry lists no version of ${pkg}`);
|
|
559
|
-
const signerId = latest.signerId;
|
|
560
|
-
if (!signerId) throw new Error(`the registry names no publisher for ${pkg} ${latest.appVersion}`);
|
|
561
|
-
return { applicationId: await applicationIdForBundle(pkg, signerId), signerId, version: latest.appVersion };
|
|
562
|
-
}
|
|
563
|
-
|
|
564
|
-
// src/delegated/create-context.ts
|
|
565
|
-
function governanceNonce(relay, group) {
|
|
566
|
-
return { next: async () => nextGovernanceNonce(relay, group) };
|
|
567
|
-
}
|
|
568
|
-
function nextGovernanceNonce(relay, group) {
|
|
569
|
-
const key = `calimero.governance-nonce.${relay}.${group}`;
|
|
570
|
-
let last = 0n;
|
|
571
|
-
try {
|
|
572
|
-
last = BigInt(localStorage.getItem(key) ?? "0");
|
|
573
|
-
} catch {
|
|
574
|
-
}
|
|
575
|
-
const next = [last + 1n, BigInt(Date.now())].reduce((a, b) => a > b ? a : b);
|
|
576
|
-
try {
|
|
577
|
-
localStorage.setItem(key, String(next));
|
|
578
|
-
} catch {
|
|
579
|
-
}
|
|
580
|
-
return next;
|
|
581
|
-
}
|
|
582
|
-
function relayFor(s, namespaceId) {
|
|
583
|
-
const url = readRelayMap(s.account).namespaces[namespaceId] ?? s.relayUrl;
|
|
584
|
-
if (!url) throw new Error("no relay is known for this namespace, so there is nowhere to send this");
|
|
585
|
-
return url.replace(/\/+$/, "");
|
|
586
|
-
}
|
|
587
|
-
function initArgsOf(params) {
|
|
588
|
-
if (!params || params.length === 0) return {};
|
|
589
|
-
return JSON.parse(new TextDecoder().decode(Uint8Array.from(params)));
|
|
590
|
-
}
|
|
591
|
-
function client(s, relayUrl, nonces, fetch2) {
|
|
592
|
-
return new RelayClient({
|
|
593
|
-
relayUrl,
|
|
594
|
-
authorAccount: s.account,
|
|
595
|
-
authorProof: s.credential,
|
|
596
|
-
deviceSecret: s.deviceSecret,
|
|
597
|
-
nonces,
|
|
598
|
-
fetch: fetch2
|
|
599
|
-
});
|
|
600
|
-
}
|
|
601
|
-
async function createDelegatedContext(s, req, deps = {}) {
|
|
602
|
-
const relay = relayFor(s, req.namespaceId);
|
|
603
|
-
const creationNonce = 0n;
|
|
604
|
-
const created = await client(s, relay, { next: async () => creationNonce }, deps.fetch).createContext({
|
|
605
|
-
groupId: req.groupId ?? req.namespaceId,
|
|
606
|
-
applicationId: req.applicationId,
|
|
607
|
-
serviceName: req.serviceName,
|
|
608
|
-
seed: req.contextSeed,
|
|
609
|
-
initArgs: initArgsOf(req.initializationParams),
|
|
610
|
-
name: req.name
|
|
611
|
-
});
|
|
612
|
-
markContextNonceSpent(relay, created.contextId, creationNonce);
|
|
613
|
-
rememberRelay(s.account, relay, { namespaceId: req.namespaceId, contextId: created.contextId });
|
|
614
|
-
return { contextId: created.contextId };
|
|
615
|
-
}
|
|
616
|
-
async function delegatedGovernance(s, req, deps = {}) {
|
|
617
|
-
const relay = relayFor(s, req.namespaceId);
|
|
618
|
-
return client(s, relay, governanceNonce(relay, req.group), deps.fetch).govern({ groupId: req.group, op: req.op });
|
|
619
|
-
}
|
|
620
|
-
async function createDelegatedPrivateContext(s, req, deps = {}) {
|
|
621
|
-
const { groupId } = await delegatedGovernance(
|
|
622
|
-
s,
|
|
623
|
-
{
|
|
624
|
-
namespaceId: req.namespaceId,
|
|
625
|
-
group: req.namespaceId,
|
|
626
|
-
// The id is derived from a fresh salt (core#4244); a node refuses any other.
|
|
627
|
-
op: (await subgroupCreation({ parentId: req.namespaceId, restricted: true, admin: s.account })).op
|
|
628
|
-
},
|
|
629
|
-
deps
|
|
630
|
-
);
|
|
631
|
-
for (const member of req.members) {
|
|
632
|
-
await delegatedGovernance(s, { namespaceId: req.namespaceId, group: groupId, op: memberAddedOp(member, "Member") }, deps);
|
|
633
|
-
}
|
|
634
|
-
const { contextId } = await createDelegatedContext(s, { ...req, groupId }, deps);
|
|
635
|
-
return { contextId, groupId };
|
|
636
|
-
}
|
|
637
|
-
async function foundDelegatedNamespace(s, req = {}, deps = {}) {
|
|
638
|
-
const relays = knownRelays(s).map((u) => u.replace(/\/+$/, ""));
|
|
639
|
-
const relay = relays[0];
|
|
640
|
-
if (!relay) throw new Error("no relay is known for this account, so there is nowhere to found a namespace");
|
|
641
|
-
const known = Object.entries(readRelayMap(s.account).namespaces).find(
|
|
642
|
-
([, url]) => url.replace(/\/+$/, "") === relay
|
|
643
|
-
)?.[0];
|
|
644
|
-
const named = s.executorAccount && s.relayUrl && s.relayUrl.replace(/\/+$/, "") === relay ? s.executorAccount : null;
|
|
645
|
-
if (!named && !known) {
|
|
646
|
-
throw new Error(
|
|
647
|
-
"the executor account of this relay is not known: join a namespace on it first, or connect with the relay's executor account (the cloud shows it beside the relay)"
|
|
648
|
-
);
|
|
649
|
-
}
|
|
650
|
-
const executorAccount = named ?? (await client(s, relay, governanceNonce(relay, known), deps.fetch).describeGovernance(known)).executorAccount;
|
|
651
|
-
let next = BigInt(Date.now());
|
|
652
|
-
const founded = await client(s, relay, { next: async () => next++ }, deps.fetch).foundNamespace({
|
|
653
|
-
executorAccount,
|
|
654
|
-
...req.defaultCapabilities !== void 0 ? { defaultCapabilities: req.defaultCapabilities } : {},
|
|
655
|
-
...req.application ? { application: req.application } : {}
|
|
656
|
-
});
|
|
657
|
-
try {
|
|
658
|
-
localStorage.setItem(`calimero.governance-nonce.${relay}.${founded.namespaceId}`, String(next));
|
|
659
|
-
} catch {
|
|
660
|
-
}
|
|
661
|
-
rememberRelay(s.account, relay, { namespaceId: founded.namespaceId });
|
|
662
|
-
if (req.application && founded.applicationSet !== true) {
|
|
663
|
-
throw new Error(
|
|
664
|
-
`founded ${founded.namespaceId} but could not give it its application: ${founded.applicationError ?? "unknown reason"}`
|
|
665
|
-
);
|
|
666
|
-
}
|
|
667
|
-
const ha = founded.teeEnabled ? await enableHaBestEffort(s, founded.namespaceId, founded.salt, relay, deps) : {
|
|
668
|
-
haEnabled: false,
|
|
669
|
-
haError: `the relay did not attest the founding, so no fleet node could be admitted for HA${founded.teeError ? `: ${founded.teeError}` : ""}`
|
|
670
|
-
};
|
|
671
|
-
return { namespaceId: founded.namespaceId, teeEnabled: founded.teeEnabled, ...ha };
|
|
672
|
-
}
|
|
673
|
-
var HA_ACCOUNT_NOT_LINKED_MESSAGE = "link this account to your cloud user in the wallet so invitees can find this namespace";
|
|
674
|
-
var HA_REFUSAL_MESSAGES = {
|
|
675
|
-
account_not_linked: HA_ACCOUNT_NOT_LINKED_MESSAGE,
|
|
676
|
-
account_linked_to_several_users: "this account is linked to more than one cloud user, so the cloud cannot tell whose plan hosts the namespace: unlink it from all but one in the wallet",
|
|
677
|
-
ha_request_pending: "another namespace of this account is still waiting to be hosted; the cloud hosts one new namespace at a time without a cloud sign-in. Sign in to the cloud and turn off hosting for the waiting namespace, or wait until it is hosted",
|
|
678
|
-
unknown_relay: "the cloud does not run the relay this namespace was founded on, so it cannot host it",
|
|
679
|
-
relay_not_dialable: "the relay this namespace was founded on has not reported its address to the cloud yet; try enabling hosting again shortly"
|
|
680
|
-
};
|
|
681
|
-
function blockingNamespace(e) {
|
|
682
|
-
try {
|
|
683
|
-
const body = JSON.parse(e.bodyText ?? "");
|
|
684
|
-
const id = body?.detail?.namespace_id ?? body?.namespace_id;
|
|
685
|
-
return typeof id === "string" && /^[0-9a-f]{64}$/i.test(id) ? id.toLowerCase() : null;
|
|
686
|
-
} catch {
|
|
687
|
-
return null;
|
|
688
|
-
}
|
|
689
|
-
}
|
|
690
|
-
async function enableHaBestEffort(s, namespaceId, salt, relayUrl, deps) {
|
|
691
|
-
try {
|
|
692
|
-
await new CloudClient({ cloudBaseUrl: deps.cloudBaseUrl, fetch: deps.fetch }).enableHaAsAccount({
|
|
693
|
-
namespaceId,
|
|
694
|
-
salt,
|
|
695
|
-
accountId: s.account,
|
|
696
|
-
credential: s.credential,
|
|
697
|
-
deviceSecret: s.deviceSecret,
|
|
698
|
-
// The relay that founded it: the cloud hands it to the fleet node as its
|
|
699
|
-
// admitter, so the node does not have to find it by discovery.
|
|
700
|
-
relayUrl
|
|
701
|
-
});
|
|
702
|
-
return { haEnabled: true };
|
|
703
|
-
} catch (e) {
|
|
704
|
-
if (e instanceof AccountNotLinkedError) return { haEnabled: false, haError: HA_ACCOUNT_NOT_LINKED_MESSAGE };
|
|
705
|
-
if (e instanceof AccountHaRefusedError && HA_REFUSAL_MESSAGES[e.code]) {
|
|
706
|
-
const blocking = e.code === "ha_request_pending" ? blockingNamespace(e) : null;
|
|
707
|
-
const message = HA_REFUSAL_MESSAGES[e.code];
|
|
708
|
-
return { haEnabled: false, haError: blocking ? `${message} (waiting: ${blocking})` : message };
|
|
709
|
-
}
|
|
710
|
-
return { haEnabled: false, haError: e instanceof Error ? e.message : String(e) };
|
|
711
|
-
}
|
|
712
|
-
}
|
|
713
|
-
async function latestPublishedVersion(registryUrl, pkg, fetchFn = globalThis.fetch) {
|
|
714
|
-
const latest = selectLatestBundle(await fetchRegistryBundles(registryUrl, pkg, fetchFn));
|
|
715
|
-
if (!latest) throw new Error(`the registry lists no version of ${pkg}`);
|
|
716
|
-
return latest.appVersion;
|
|
717
|
-
}
|
|
718
|
-
|
|
719
|
-
// src/admin/node-admin.ts
|
|
720
|
-
function createNodeAdmin(input, deps = {}) {
|
|
721
|
-
const { admin, app } = input;
|
|
722
|
-
const latestVersion = deps.latestVersion ?? latestPublishedVersion;
|
|
723
|
-
async function ensureInstalled(applicationId) {
|
|
724
|
-
const { apps } = await admin.listApplications();
|
|
725
|
-
if (apps.some((a) => a.id === applicationId)) return;
|
|
726
|
-
if (!app.packageName) {
|
|
727
|
-
throw new Error(`application ${applicationId} is not installed on this node, and no packageName is set to install it`);
|
|
728
|
-
}
|
|
729
|
-
const version = app.packageVersion ?? await latestVersion(app.registryUrl ?? "https://apps.calimero.network", app.packageName);
|
|
730
|
-
const { applicationId: installed } = await admin.installApplication({ package: app.packageName, version });
|
|
731
|
-
if (installed !== applicationId) {
|
|
732
|
-
throw new Error(`installed ${app.packageName}@${version} as ${installed}, not ${applicationId}`);
|
|
733
|
-
}
|
|
734
|
-
}
|
|
735
|
-
const overrides = {
|
|
736
|
-
async createNamespace(req) {
|
|
737
|
-
await ensureInstalled(req.applicationId);
|
|
738
|
-
return admin.createNamespace(req);
|
|
739
|
-
}
|
|
740
|
-
};
|
|
741
|
-
return new Proxy(admin, {
|
|
742
|
-
get(target, prop, receiver) {
|
|
743
|
-
if (typeof prop === "string" && prop in overrides) return overrides[prop];
|
|
744
|
-
return Reflect.get(target, prop, receiver);
|
|
745
|
-
}
|
|
746
|
-
});
|
|
747
|
-
}
|
|
748
|
-
|
|
749
|
-
// src/delegated/govern.ts
|
|
750
|
-
var GROUP_NAMESPACE_PREFIX = "calimero.delegated.group-namespace.";
|
|
751
|
-
var learned = /* @__PURE__ */ new Map();
|
|
752
|
-
function readGroupNamespaces(account) {
|
|
753
|
-
let stored = {};
|
|
754
|
-
try {
|
|
755
|
-
stored = JSON.parse(localStorage.getItem(GROUP_NAMESPACE_PREFIX + account) ?? "{}");
|
|
756
|
-
} catch {
|
|
757
|
-
}
|
|
758
|
-
return { ...stored, ...learned.get(account) };
|
|
759
|
-
}
|
|
760
|
-
function rememberGroupNamespace(account, groupId, namespaceId) {
|
|
761
|
-
learned.set(account, { ...learned.get(account), [groupId]: namespaceId });
|
|
762
|
-
try {
|
|
763
|
-
const all = readGroupNamespaces(account);
|
|
764
|
-
all[groupId] = namespaceId;
|
|
765
|
-
localStorage.setItem(GROUP_NAMESPACE_PREFIX + account, JSON.stringify(all));
|
|
766
|
-
} catch {
|
|
767
|
-
}
|
|
768
|
-
}
|
|
769
|
-
function namespaceOfGroup(s, groupId) {
|
|
770
|
-
if (readRelayMap(s.account).namespaces[groupId]) return groupId;
|
|
771
|
-
return readGroupNamespaces(s.account)[groupId];
|
|
772
|
-
}
|
|
773
|
-
function requireNamespace(s, groupId) {
|
|
774
|
-
const ns = namespaceOfGroup(s, groupId);
|
|
775
|
-
if (!ns) {
|
|
776
|
-
throw new Error(
|
|
777
|
-
`the namespace of group ${groupId} is not known to this account: it can manage only groups in namespaces it joined or subgroups it created`
|
|
778
|
-
);
|
|
779
|
-
}
|
|
780
|
-
return ns;
|
|
781
|
-
}
|
|
782
|
-
async function governGroup(s, groupId, op) {
|
|
783
|
-
return delegatedGovernance(s, { namespaceId: requireNamespace(s, groupId), group: groupId, op });
|
|
784
|
-
}
|
|
785
|
-
async function governRoot(s, groupId, op) {
|
|
786
|
-
const namespaceId = requireNamespace(s, groupId);
|
|
787
|
-
return delegatedGovernance(s, { namespaceId, group: namespaceId, op });
|
|
788
|
-
}
|
|
789
|
-
|
|
790
|
-
// src/delegated/account-admin.ts
|
|
791
|
-
var NotForAccountError = class extends Error {
|
|
792
|
-
constructor(method) {
|
|
793
|
-
super(`${method} is not available for an account: it needs a node`);
|
|
794
|
-
this.method = method;
|
|
795
|
-
this.name = "NotForAccountError";
|
|
796
|
-
}
|
|
797
|
-
};
|
|
798
|
-
var NoRelayError = class extends Error {
|
|
799
|
-
constructor(method) {
|
|
800
|
-
super(`${method} needs a relay, and this account has none yet: join from an invitation first`);
|
|
801
|
-
this.method = method;
|
|
802
|
-
this.name = "NoRelayError";
|
|
803
|
-
}
|
|
804
|
-
};
|
|
805
|
-
var InvitationNotClaimableError = class extends Error {
|
|
806
|
-
constructor(namespaceId, reason) {
|
|
807
|
-
super(
|
|
808
|
-
reason === "not-hosted" ? `nobody could claim an invitation to ${namespaceId} yet: the namespace is not hosted in the cloud and has no relay in it, so an invitee with no node has no relay to be admitted through. Link this account to your cloud user in the wallet and enable HA for the namespace, then invite.` : `nobody could claim an invitation to ${namespaceId}: the cloud routes to none of the relays or admins it would name as admitters`
|
|
809
|
-
);
|
|
810
|
-
this.namespaceId = namespaceId;
|
|
811
|
-
this.reason = reason;
|
|
812
|
-
this.name = "InvitationNotClaimableError";
|
|
813
|
-
}
|
|
814
|
-
};
|
|
815
|
-
var EMPTY_READS = {
|
|
816
|
-
listNamespaces: async () => [],
|
|
817
|
-
listNamespacesForApplication: async () => [],
|
|
818
|
-
getContexts: async () => ({ contexts: [] })
|
|
819
|
-
};
|
|
820
|
-
var NODE_ONLY = /* @__PURE__ */ new Set([
|
|
821
|
-
"upgradeGroup",
|
|
822
|
-
"retryGroupUpgrade",
|
|
823
|
-
"abortMigration",
|
|
824
|
-
"installApplication",
|
|
825
|
-
"installDevApplication",
|
|
826
|
-
"uninstallApplication",
|
|
827
|
-
"generateContextIdentity",
|
|
828
|
-
"deleteContext",
|
|
829
|
-
// A node's leaveContext is a local opt-out (a tombstone, its own identity rows)
|
|
830
|
-
// and publishes nothing; an account has nothing local to opt out of, and
|
|
831
|
-
// leaving the context's group instead is leaveGroup.
|
|
832
|
-
"leaveContext",
|
|
833
|
-
"createContextAlias",
|
|
834
|
-
"createApplicationAlias",
|
|
835
|
-
"createDeviceAlias",
|
|
836
|
-
"deleteContextAlias",
|
|
837
|
-
"deleteApplicationAlias",
|
|
838
|
-
"deleteDeviceAlias",
|
|
839
|
-
"lookupContextAlias",
|
|
840
|
-
"lookupApplicationAlias",
|
|
841
|
-
"lookupDeviceAlias",
|
|
842
|
-
"listContextAliases",
|
|
843
|
-
"listApplicationAliases",
|
|
844
|
-
"listDeviceAliases",
|
|
845
|
-
"deleteNamespace",
|
|
846
|
-
"createGroupInvitation",
|
|
847
|
-
"joinGroup",
|
|
848
|
-
"setTeeAdmissionPolicy",
|
|
849
|
-
"getTeeAdmissionPolicy",
|
|
850
|
-
"deleteBlob",
|
|
851
|
-
"listAccountDevices",
|
|
852
|
-
"revokeAccountDevice"
|
|
853
|
-
]);
|
|
854
|
-
function isAlreadyDirectMember(e) {
|
|
855
|
-
if (!(e instanceof Error)) return false;
|
|
856
|
-
const status = e.status;
|
|
857
|
-
return (status === void 0 || status === 409) && /signer [0-9a-f]+ is a direct member/i.test(e.message);
|
|
858
|
-
}
|
|
859
|
-
function createAccountAdmin(input, deps = {}) {
|
|
860
|
-
const { session: s, read, app } = input;
|
|
861
|
-
const governGroupOp = deps.govern?.group ?? governGroup;
|
|
862
|
-
const governRootOp = deps.govern?.root ?? governRoot;
|
|
863
|
-
const createContext2 = deps.createContext ?? createDelegatedContext;
|
|
864
|
-
const found = deps.found ?? foundDelegatedNamespace;
|
|
865
|
-
const latestVersion = deps.latestVersion ?? latestPublishedVersion;
|
|
866
|
-
const signInvitation = deps.signInvitation ?? signGroupInvitation;
|
|
867
|
-
const join = deps.join;
|
|
868
|
-
const routing = deps.routing;
|
|
869
|
-
async function joinNamespace(namespaceId, req) {
|
|
870
|
-
if (!join) throw new NotForAccountError("joinNamespace without a join handler");
|
|
871
|
-
return join(namespaceId, req.invitation);
|
|
872
|
-
}
|
|
873
|
-
const relay = () => {
|
|
874
|
-
if (read === null) throw new NoRelayError("this call");
|
|
875
|
-
return read;
|
|
876
|
-
};
|
|
877
|
-
async function knowNamespaceOf(groupId) {
|
|
878
|
-
if (namespaceOfGroup(s, groupId)) return;
|
|
879
|
-
const info = await relay().getGroupInfo(groupId);
|
|
880
|
-
rememberGroupNamespace(s.account, groupId, info.namespaceId ?? groupId);
|
|
881
|
-
}
|
|
882
|
-
const group = async (session, groupId, op) => {
|
|
883
|
-
await knowNamespaceOf(groupId);
|
|
884
|
-
return governGroupOp(session, groupId, op);
|
|
885
|
-
};
|
|
886
|
-
const root = async (session, groupId, op) => {
|
|
887
|
-
await knowNamespaceOf(groupId);
|
|
888
|
-
return governRootOp(session, groupId, op);
|
|
889
|
-
};
|
|
890
|
-
async function joinOpen(groupId) {
|
|
891
|
-
try {
|
|
892
|
-
await root(s, groupId, memberJoinedOpenOp({ member: s.account, groupId, credential: s.credential }));
|
|
893
|
-
return true;
|
|
894
|
-
} catch (e) {
|
|
895
|
-
if (isAlreadyDirectMember(e)) return false;
|
|
896
|
-
throw e;
|
|
897
|
-
}
|
|
898
|
-
}
|
|
899
|
-
async function isMemberOfContextGroup(contextId, knownGroupId) {
|
|
900
|
-
const groupId = String(await relay().getContextGroup(contextId));
|
|
901
|
-
const { members } = await relay().listGroupMembers(groupId);
|
|
902
|
-
return members.some((m) => m.identity.toLowerCase() === s.account.toLowerCase());
|
|
903
|
-
}
|
|
904
|
-
const writes = {
|
|
905
|
-
// The node-wide `for-application` listing is not caller-scoped, so a relay
|
|
906
|
-
// refuses it to an account. Its own scoped list, filtered, is the answer.
|
|
907
|
-
async listNamespacesForApplication(applicationId) {
|
|
908
|
-
return (await relay().listNamespaces()).filter((ns) => ns.targetApplicationId === applicationId);
|
|
909
|
-
},
|
|
910
|
-
async getNodeIdentity() {
|
|
911
|
-
return { accountId: s.account, deviceId: null, publicKey: "", deviceCertified: true };
|
|
912
|
-
},
|
|
913
|
-
async createNamespace(req) {
|
|
914
|
-
if (!app.packageName) throw new NotForAccountError("createNamespace without a packageName");
|
|
915
|
-
const version = app.packageVersion ?? await latestVersion(app.registryUrl ?? "https://apps.calimero.network", app.packageName);
|
|
916
|
-
const { namespaceId, haEnabled, haError } = await found(s, {
|
|
917
|
-
defaultCapabilities: 231,
|
|
918
|
-
application: { applicationId: req.applicationId, package: app.packageName, version }
|
|
919
|
-
});
|
|
920
|
-
if (req.name) await group(s, namespaceId, groupMetadataSetOp({ name: req.name }));
|
|
921
|
-
return { namespaceId, haEnabled, ...haError !== void 0 ? { haError } : {} };
|
|
922
|
-
},
|
|
923
|
-
async createGroupInNamespace(namespaceId, req = {}) {
|
|
924
|
-
const { op } = await subgroupCreation({ parentId: namespaceId, restricted: req.visibility !== "open", admin: s.account });
|
|
925
|
-
const { groupId } = await root(s, namespaceId, op);
|
|
926
|
-
rememberGroupNamespace(s.account, groupId, namespaceId);
|
|
927
|
-
if (req.groupName) await group(s, groupId, groupMetadataSetOp({ name: req.groupName }));
|
|
928
|
-
return { groupId };
|
|
929
|
-
},
|
|
930
|
-
async addGroupMembers(groupId, req) {
|
|
931
|
-
for (const m of req.members) await group(s, groupId, memberAddedOp(m.identity, m.role ?? "Member"));
|
|
932
|
-
},
|
|
933
|
-
async removeGroupMembers(groupId, req) {
|
|
934
|
-
for (const m of req.members) await group(s, groupId, memberRemovedOp(m));
|
|
935
|
-
},
|
|
936
|
-
async setGroupMetadata(groupId, req) {
|
|
937
|
-
await group(s, groupId, groupMetadataSetOp(req));
|
|
938
|
-
},
|
|
939
|
-
async setMemberMetadata(groupId, identity, req) {
|
|
940
|
-
await group(s, groupId, memberMetadataSetOp(identity, req));
|
|
941
|
-
},
|
|
942
|
-
async setContextMetadata(groupId, contextId, req) {
|
|
943
|
-
await group(s, groupId, contextMetadataSetOp(contextId, req));
|
|
944
|
-
},
|
|
945
|
-
async setDefaultCapabilities(groupId, req) {
|
|
946
|
-
await group(s, groupId, defaultCapabilitiesSetOp(req.defaultCapabilities));
|
|
947
|
-
},
|
|
948
|
-
async setSubgroupVisibility(groupId, req) {
|
|
949
|
-
await group(s, groupId, subgroupVisibilitySetOp(req.subgroupVisibility === "open" ? "open" : "restricted"));
|
|
950
|
-
},
|
|
951
|
-
async setMemberCapabilities(groupId, identity, req) {
|
|
952
|
-
await group(s, groupId, memberCapabilitySetOp(identity, req.capabilities));
|
|
953
|
-
},
|
|
954
|
-
async deleteGroup(groupId) {
|
|
955
|
-
await root(s, groupId, groupDeletedOp(groupId));
|
|
956
|
-
return { isDeleted: true };
|
|
957
|
-
},
|
|
958
|
-
async reparentGroup(childGroupId, req) {
|
|
959
|
-
await root(s, childGroupId, groupReparentedOp(childGroupId, req.newParentId));
|
|
960
|
-
return { reparented: true };
|
|
961
|
-
},
|
|
962
|
-
async leaveGroup(groupId) {
|
|
963
|
-
await group(s, groupId, memberLeftOp(s.account));
|
|
964
|
-
},
|
|
965
|
-
async leaveNamespace(namespaceId) {
|
|
966
|
-
await group(s, namespaceId, memberLeftOp(s.account));
|
|
967
|
-
},
|
|
968
|
-
// An account runs as itself in every context it can reach (the relay
|
|
969
|
-
// executes as the account), so its identity there is the account. Owned
|
|
970
|
-
// when its account is a member of the context's group, as on a node a
|
|
971
|
-
// context identity is owned once the node has joined.
|
|
972
|
-
async getContextIdentitiesOwned(contextId) {
|
|
973
|
-
return { identities: await isMemberOfContextGroup(contextId) ? [s.account] : [] };
|
|
974
|
-
},
|
|
975
|
-
async joinContext(contextId) {
|
|
976
|
-
await joinOpen(String(await relay().getContextGroup(contextId)));
|
|
977
|
-
return { contextId, memberPublicKey: s.account };
|
|
978
|
-
},
|
|
979
|
-
async createContext(req) {
|
|
980
|
-
const info = await relay().getGroupInfo(req.groupId);
|
|
981
|
-
const namespaceId = info.namespaceId ?? req.groupId;
|
|
982
|
-
const { contextId } = await createContext2(s, {
|
|
983
|
-
namespaceId,
|
|
984
|
-
groupId: req.groupId,
|
|
985
|
-
applicationId: req.applicationId,
|
|
986
|
-
serviceName: req.serviceName,
|
|
987
|
-
contextSeed: req.contextSeed,
|
|
988
|
-
name: req.name,
|
|
989
|
-
initializationParams: req.initializationParams
|
|
990
|
-
});
|
|
991
|
-
return { contextId, memberPublicKey: s.account, groupId: req.groupId };
|
|
992
|
-
},
|
|
993
|
-
async createNamespaceInvitation(namespaceId) {
|
|
994
|
-
const [{ members }, info] = await Promise.all([relay().listGroupMembers(namespaceId), relay().getGroupInfo(namespaceId)]);
|
|
995
|
-
const relays = members.filter((m) => m.role === "RelayTee").map((m) => m.identity.toLowerCase());
|
|
996
|
-
let admitterAddrs;
|
|
997
|
-
if (routing) {
|
|
998
|
-
const named = new Set(
|
|
999
|
-
relays.length > 0 ? relays : members.filter((m) => m.role === "Admin").map((m) => m.identity.toLowerCase())
|
|
1000
|
-
);
|
|
1001
|
-
let nodes = null;
|
|
1002
|
-
try {
|
|
1003
|
-
nodes = (await routing(namespaceId)).nodes;
|
|
1004
|
-
} catch {
|
|
1005
|
-
}
|
|
1006
|
-
if (nodes !== null) {
|
|
1007
|
-
if (nodes.length === 0) {
|
|
1008
|
-
if (relays.length === 0 || !s.relayUrl) throw new InvitationNotClaimableError(namespaceId, "not-hosted");
|
|
1009
|
-
admitterAddrs = [s.relayUrl];
|
|
1010
|
-
} else if (!nodes.some((n) => n.account !== null && named.has(n.account.toLowerCase()))) {
|
|
1011
|
-
throw new InvitationNotClaimableError(namespaceId, "no-named-node");
|
|
1012
|
-
}
|
|
1013
|
-
}
|
|
1014
|
-
}
|
|
1015
|
-
const invitation = await signInvitation({
|
|
1016
|
-
groupId: namespaceId,
|
|
1017
|
-
inviterAccount: s.account,
|
|
1018
|
-
deviceSecret: s.deviceSecret,
|
|
1019
|
-
...relays.length > 0 ? { admitters: relays } : {},
|
|
1020
|
-
...admitterAddrs ? { admitterAddrs } : {},
|
|
1021
|
-
members,
|
|
1022
|
-
applicationId: info.targetApplicationId,
|
|
1023
|
-
appKey: info.appKey
|
|
1024
|
-
});
|
|
1025
|
-
return { invitation };
|
|
1026
|
-
},
|
|
1027
|
-
// The relay syncs its own view; an account has nothing to pull.
|
|
1028
|
-
async syncGroup(groupId) {
|
|
1029
|
-
return { groupId, synced: true };
|
|
1030
|
-
},
|
|
1031
|
-
async syncContext() {
|
|
1032
|
-
},
|
|
1033
|
-
joinNamespace,
|
|
1034
|
-
async updateMemberRole(groupId, identity, req) {
|
|
1035
|
-
await group(s, groupId, memberRoleSetOp(identity, req.role));
|
|
1036
|
-
},
|
|
1037
|
-
// An open subgroup is joined the way `joinContext` joins one: MemberJoinedOpen
|
|
1038
|
-
// on the subgroup, and nothing to do for a member already in it.
|
|
1039
|
-
async joinSubgroupInheritance(groupId) {
|
|
1040
|
-
return { groupId, memberPublicKey: s.account, wasInherited: await joinOpen(groupId) };
|
|
1041
|
-
},
|
|
1042
|
-
async detachContextFromGroup(groupId, contextId) {
|
|
1043
|
-
await group(s, groupId, contextDetachedOp(contextId));
|
|
1044
|
-
}
|
|
1045
|
-
};
|
|
1046
|
-
if (read === null) {
|
|
1047
|
-
return new Proxy({}, {
|
|
1048
|
-
get(_target, prop) {
|
|
1049
|
-
if (typeof prop !== "string") return void 0;
|
|
1050
|
-
if (prop === "getNodeIdentity") return writes.getNodeIdentity;
|
|
1051
|
-
if (prop === "joinNamespace") return joinNamespace;
|
|
1052
|
-
if (prop in EMPTY_READS) return EMPTY_READS[prop];
|
|
1053
|
-
return async () => {
|
|
1054
|
-
throw new NoRelayError(prop);
|
|
1055
|
-
};
|
|
1056
|
-
}
|
|
1057
|
-
});
|
|
1058
|
-
}
|
|
1059
|
-
return new Proxy(read, {
|
|
1060
|
-
get(target, prop, receiver) {
|
|
1061
|
-
if (typeof prop === "string" && prop in writes) return writes[prop];
|
|
1062
|
-
if (typeof prop === "string" && NODE_ONLY.has(prop)) {
|
|
1063
|
-
return async () => {
|
|
1064
|
-
throw new NotForAccountError(prop);
|
|
1065
|
-
};
|
|
1066
|
-
}
|
|
1067
|
-
return Reflect.get(target, prop, receiver);
|
|
1068
|
-
}
|
|
1069
|
-
});
|
|
1070
|
-
}
|
|
1071
|
-
function explainAdmitFailure(status, body) {
|
|
1072
|
-
const detail = body ? `: ${body}` : "";
|
|
1073
|
-
switch (status) {
|
|
1074
|
-
case 400:
|
|
1075
|
-
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.`;
|
|
1076
|
-
case 403:
|
|
1077
|
-
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.`;
|
|
1078
|
-
case 409:
|
|
1079
|
-
return `That node holds no device of its own, so it cannot endorse anyone (409)${detail}. Another admitter from the same invitation would work.`;
|
|
1080
|
-
default:
|
|
1081
|
-
return `The join was not published (HTTP ${status})${detail}.`;
|
|
1082
|
-
}
|
|
1083
|
-
}
|
|
1084
|
-
function joinNonce(account) {
|
|
1085
|
-
const source = createLocalStorageNonceSource(`calimero.delegated.joinnonce.${account}`);
|
|
1086
|
-
return () => source.next();
|
|
1087
|
-
}
|
|
1088
|
-
function origin(url) {
|
|
1089
|
-
return url.replace(/\/+$/, "");
|
|
1090
|
-
}
|
|
1091
|
-
async function joinWithNode(input) {
|
|
1092
|
-
const { account, credential, deviceSecret } = input.credential;
|
|
1093
|
-
let signedOp;
|
|
1094
|
-
try {
|
|
1095
|
-
signedOp = await signMemberJoinOp({
|
|
1096
|
-
namespaceId: input.namespaceId,
|
|
1097
|
-
member: account,
|
|
1098
|
-
invitation: input.invitation,
|
|
1099
|
-
credential,
|
|
1100
|
-
deviceSecret,
|
|
1101
|
-
nonce: await (input.deps?.nonce ?? joinNonce(account))()
|
|
1102
|
-
});
|
|
1103
|
-
} catch (e) {
|
|
1104
|
-
return {
|
|
1105
|
-
ok: false,
|
|
1106
|
-
step: "sign",
|
|
1107
|
-
reason: `The join op could not be signed, so nothing was sent: ${e instanceof Error ? e.message : String(e)}`
|
|
1108
|
-
};
|
|
1109
|
-
}
|
|
1110
|
-
const body = { invitation: input.invitation, signedOp };
|
|
1111
|
-
const url = input.admitUrl ?? `${origin(input.nodeUrl)}/admin-api/namespaces/${input.namespaceId}/admit`;
|
|
1112
|
-
const doFetch = input.deps?.fetch ?? fetch;
|
|
1113
|
-
let response;
|
|
1114
|
-
try {
|
|
1115
|
-
response = await doFetch(url, {
|
|
1116
|
-
method: "POST",
|
|
1117
|
-
// No Authorization header and no request proof, deliberately: the route is
|
|
1118
|
-
// unauthenticated because the joiner's signature is the authorization.
|
|
1119
|
-
headers: { "Content-Type": "application/json", Accept: "application/json" },
|
|
1120
|
-
body: JSON.stringify(body)
|
|
1121
|
-
});
|
|
1122
|
-
} catch (e) {
|
|
1123
|
-
return {
|
|
1124
|
-
ok: false,
|
|
1125
|
-
step: "admit",
|
|
1126
|
-
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.`
|
|
1127
|
-
};
|
|
1128
|
-
}
|
|
1129
|
-
const text = await response.text();
|
|
1130
|
-
if (!response.ok) {
|
|
1131
|
-
return {
|
|
1132
|
-
ok: false,
|
|
1133
|
-
step: "admit",
|
|
1134
|
-
status: response.status,
|
|
1135
|
-
reason: explainAdmitFailure(response.status, text)
|
|
1136
|
-
};
|
|
1137
|
-
}
|
|
1138
|
-
let published = false;
|
|
1139
|
-
try {
|
|
1140
|
-
const parsed = text ? JSON.parse(text) : {};
|
|
1141
|
-
published = parsed.data?.published === true;
|
|
1142
|
-
} catch {
|
|
1143
|
-
published = false;
|
|
1144
|
-
}
|
|
1145
|
-
return {
|
|
1146
|
-
ok: true,
|
|
1147
|
-
published,
|
|
1148
|
-
session: { relayUrl: origin(input.nodeUrl), account, credential, deviceSecret }
|
|
1149
|
-
};
|
|
1150
|
-
}
|
|
1151
|
-
function normaliseAccount(account) {
|
|
1152
|
-
if (!account) return null;
|
|
1153
|
-
const trimmed = account.trim().toLowerCase();
|
|
1154
|
-
const bare = trimmed.startsWith("0x") ? trimmed.slice(2) : trimmed;
|
|
1155
|
-
return bare.length > 0 ? bare : null;
|
|
1156
|
-
}
|
|
1157
|
-
function httpAdmitterOrigins(addrs) {
|
|
1158
|
-
const out = [];
|
|
1159
|
-
for (const addr of addrs ?? []) {
|
|
1160
|
-
try {
|
|
1161
|
-
const url = new URL(addr);
|
|
1162
|
-
if (url.protocol === "http:" || url.protocol === "https:") out.push(addr.replace(/\/+$/, ""));
|
|
1163
|
-
} catch {
|
|
1164
|
-
}
|
|
1165
|
-
}
|
|
1166
|
-
return out;
|
|
1167
|
-
}
|
|
1168
|
-
function isInvited(node, invited) {
|
|
1169
|
-
if (invited.size === 0) return true;
|
|
1170
|
-
const account = normaliseAccount(node.account);
|
|
1171
|
-
return account !== null && invited.has(account);
|
|
1172
|
-
}
|
|
1173
|
-
async function resolveRelayFromInvitation(input) {
|
|
1174
|
-
const cloud = input.cloud ?? new CloudClient({
|
|
1175
|
-
cloudBaseUrl: input.cloudBaseUrl,
|
|
1176
|
-
routingCredential: { credential: input.credential, deviceSecret: input.deviceSecret }
|
|
1177
|
-
});
|
|
1178
|
-
let nodes;
|
|
1179
|
-
let servable;
|
|
1180
|
-
try {
|
|
1181
|
-
const routing = await cloud.getNamespaceRouting(input.namespaceId);
|
|
1182
|
-
nodes = routing.nodes;
|
|
1183
|
-
servable = routing.servable;
|
|
1184
|
-
} catch (e) {
|
|
1185
|
-
return {
|
|
1186
|
-
ok: false,
|
|
1187
|
-
step: "admitters-lookup",
|
|
1188
|
-
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.`
|
|
1189
|
-
};
|
|
1190
|
-
}
|
|
1191
|
-
if (nodes.length === 0) {
|
|
1192
|
-
const [relayUrl] = httpAdmitterOrigins(input.admitterAddrs);
|
|
1193
|
-
if (relayUrl) {
|
|
1194
|
-
const admitters = (input.admitters ?? []).map(normaliseAccount).filter((a) => a !== null);
|
|
1195
|
-
return {
|
|
1196
|
-
ok: true,
|
|
1197
|
-
relayUrl,
|
|
1198
|
-
admitUrl: `${relayUrl}/admin-api/namespaces/${input.namespaceId}/admit`,
|
|
1199
|
-
admitterAccount: admitters.length === 1 ? admitters[0] : null,
|
|
1200
|
-
peerId: null,
|
|
1201
|
-
// The relay a founder's session runs through executes that founder's
|
|
1202
|
-
// warrants, so it authors on behalf; the node's answer to the first
|
|
1203
|
-
// write is the authoritative one, as for a cloud-routed node.
|
|
1204
|
-
writable: true,
|
|
1205
|
-
stale: false,
|
|
1206
|
-
via: "invitation"
|
|
1207
|
-
};
|
|
1208
|
-
}
|
|
1209
|
-
return {
|
|
1210
|
-
ok: false,
|
|
1211
|
-
step: "no-nodes",
|
|
1212
|
-
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."
|
|
1213
|
-
};
|
|
1214
|
-
}
|
|
1215
|
-
const invited = new Set(
|
|
1216
|
-
(input.admitters ?? []).map(normaliseAccount).filter((a) => a !== null)
|
|
1217
|
-
);
|
|
1218
|
-
const named = nodes.filter((n) => isInvited(n, invited));
|
|
1219
|
-
if (named.length === 0) {
|
|
1220
|
-
return {
|
|
1221
|
-
ok: false,
|
|
1222
|
-
step: "not-invited",
|
|
1223
|
-
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.`
|
|
1224
|
-
};
|
|
1225
|
-
}
|
|
1226
|
-
const usable = named.filter((n) => n.canAdmit);
|
|
1227
|
-
const candidates = usable.length > 0 ? usable : named;
|
|
1228
|
-
const advisory = usable.length === 0 || !servable;
|
|
1229
|
-
const addressable = candidates.filter(
|
|
1230
|
-
(n) => typeof n.relayUrl === "string" && n.relayUrl.length > 0
|
|
1231
|
-
);
|
|
1232
|
-
if (addressable.length === 0) {
|
|
1233
|
-
return {
|
|
1234
|
-
ok: false,
|
|
1235
|
-
step: "no-relay-url",
|
|
1236
|
-
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."
|
|
1237
|
-
};
|
|
1238
|
-
}
|
|
1239
|
-
const chosen = addressable.find((n) => n.canExecute) ?? addressable.find((n) => n.fresh) ?? addressable[0];
|
|
1240
|
-
return {
|
|
1241
|
-
ok: true,
|
|
1242
|
-
relayUrl: chosen.relayUrl,
|
|
1243
|
-
// The cloud's ready-made URL when it gave one, so the path is never rebuilt
|
|
1244
|
-
// from a guess; the fallback is the documented route on the same origin.
|
|
1245
|
-
admitUrl: chosen.admitUrl ?? `${chosen.relayUrl.replace(/\/+$/, "")}/admin-api/namespaces/${input.namespaceId}/admit`,
|
|
1246
|
-
admitterAccount: chosen.account,
|
|
1247
|
-
peerId: chosen.peerId,
|
|
1248
|
-
writable: chosen.canExecute,
|
|
1249
|
-
// Stale when the node's own heartbeat lapsed OR when the cloud's summary
|
|
1250
|
-
// disagrees with trying it at all. Both mean the same thing to a caller:
|
|
1251
|
-
// this was attempted on advisory data, so if the admit fails that is why.
|
|
1252
|
-
stale: !chosen.fresh || advisory,
|
|
1253
|
-
via: "cloud"
|
|
1254
|
-
};
|
|
1255
|
-
}
|
|
1256
|
-
|
|
1257
|
-
// src/delegated/bootstrap-from-invitation.ts
|
|
1258
|
-
async function bootstrapFromInvitation(input) {
|
|
1259
|
-
const resolve = input.deps?.resolve ?? resolveRelayFromInvitation;
|
|
1260
|
-
const join = input.deps?.join ?? joinWithNode;
|
|
1261
|
-
let relay = null;
|
|
1262
|
-
let nodeUrl = input.nodeUrl;
|
|
1263
|
-
let admitUrl;
|
|
1264
|
-
if (!nodeUrl) {
|
|
1265
|
-
const resolved = await resolve({
|
|
1266
|
-
namespaceId: input.namespaceId,
|
|
1267
|
-
// The signed list, read off the invitation itself rather than passed
|
|
1268
|
-
// separately: two sources for one fact is how an intersection ends up
|
|
1269
|
-
// being performed against the wrong list.
|
|
1270
|
-
admitters: input.invitation.invitation.admitters,
|
|
1271
|
-
admitterAddrs: input.invitation.admitter_addrs,
|
|
1272
|
-
credential: input.credential.credential,
|
|
1273
|
-
deviceSecret: input.credential.deviceSecret,
|
|
1274
|
-
cloudBaseUrl: input.cloudBaseUrl
|
|
1275
|
-
});
|
|
1276
|
-
if (!resolved.ok) return resolved;
|
|
1277
|
-
relay = resolved;
|
|
1278
|
-
nodeUrl = resolved.relayUrl;
|
|
1279
|
-
admitUrl = resolved.admitUrl;
|
|
1280
|
-
}
|
|
1281
|
-
const joined = await join({
|
|
1282
|
-
nodeUrl,
|
|
1283
|
-
admitUrl,
|
|
1284
|
-
namespaceId: input.namespaceId,
|
|
1285
|
-
invitation: input.invitation,
|
|
1286
|
-
credential: input.credential,
|
|
1287
|
-
deps: { fetch: input.deps?.fetch, nonce: input.deps?.nonce }
|
|
1288
|
-
});
|
|
1289
|
-
if (!joined.ok) return joined;
|
|
1290
|
-
return { ok: true, published: joined.published, relay, session: joined.session };
|
|
1291
|
-
}
|
|
1292
|
-
|
|
1293
|
-
// src/delegated/join-as-account.ts
|
|
1294
|
-
async function joinAsAccount(session, namespaceId, invitation, opts) {
|
|
1295
|
-
const bootstrap = opts.bootstrap ?? bootstrapFromInvitation;
|
|
1296
|
-
const outcome = await bootstrap({
|
|
1297
|
-
namespaceId,
|
|
1298
|
-
invitation,
|
|
1299
|
-
credential: { account: session.account, credential: session.credential, deviceSecret: session.deviceSecret },
|
|
1300
|
-
cloudBaseUrl: opts.cloudBaseUrl
|
|
1301
|
-
});
|
|
1302
|
-
if (!outcome.ok) {
|
|
1303
|
-
throw Object.assign(new Error(outcome.reason), {
|
|
1304
|
-
step: outcome.step,
|
|
1305
|
-
...outcome.status !== void 0 ? { status: outcome.status } : {}
|
|
1306
|
-
});
|
|
1307
|
-
}
|
|
1308
|
-
if (outcome.session.relayUrl) rememberRelay(session.account, outcome.session.relayUrl, { namespaceId });
|
|
1309
|
-
opts.onJoined(carryExecutorAccount(session, outcome.session));
|
|
1310
|
-
return { namespaceId };
|
|
1311
|
-
}
|
|
1312
47
|
|
|
1313
48
|
// src/auth/node-trust.ts
|
|
1314
49
|
function sameOrigin(a, b) {
|
|
@@ -1693,9 +428,9 @@ function MeroProvider({
|
|
|
1693
428
|
if (!delegated) return;
|
|
1694
429
|
const relayUrl = (contextId ? relayForContext(delegated.account, contextId) : null) ?? delegated.relayUrl;
|
|
1695
430
|
const routed = { ...delegated, relayUrl };
|
|
1696
|
-
const
|
|
1697
|
-
const awaitingKey = Boolean(
|
|
1698
|
-
if (!awaitingKey) setMero(
|
|
431
|
+
const client = buildDelegatedClient(routed, contextId);
|
|
432
|
+
const awaitingKey = Boolean(client && relayUrl && !readPinnedRelayNodeKey(relayUrl));
|
|
433
|
+
if (!awaitingKey) setMero(client);
|
|
1699
434
|
setIsAuthenticated(true);
|
|
1700
435
|
setIsOnline(true);
|
|
1701
436
|
setNodeUrlState(relayUrl);
|
|
@@ -1703,11 +438,11 @@ function MeroProvider({
|
|
|
1703
438
|
let active = true;
|
|
1704
439
|
const stop = new AbortController();
|
|
1705
440
|
(async () => {
|
|
1706
|
-
if (!
|
|
441
|
+
if (!client || !relayUrl) return;
|
|
1707
442
|
if (awaitingKey) {
|
|
1708
443
|
const nodeKey = await learnRelayNodeKey(relayUrl, { signal: stop.signal });
|
|
1709
444
|
if (!active) return;
|
|
1710
|
-
setMero(nodeKey ? buildDelegatedClient(routed) ??
|
|
445
|
+
setMero(nodeKey ? buildDelegatedClient(routed, contextId) ?? client : client);
|
|
1711
446
|
setIsLoading(false);
|
|
1712
447
|
if (!nodeKey) return;
|
|
1713
448
|
}
|
|
@@ -2289,6 +1024,13 @@ function useAccountEnrolment({
|
|
|
2289
1024
|
customWallet: walletOverride !== void 0
|
|
2290
1025
|
};
|
|
2291
1026
|
}
|
|
1027
|
+
|
|
1028
|
+
// src/utils/desktop.ts
|
|
1029
|
+
function isDesktopWindow() {
|
|
1030
|
+
if (typeof window === "undefined") return false;
|
|
1031
|
+
const w = window;
|
|
1032
|
+
return "__TAURI_INTERNALS__" in w || w.__TAURI_FETCH_PROXY_INJECTED__ === true;
|
|
1033
|
+
}
|
|
2292
1034
|
var CUSTOM_SELECTION = "__custom__";
|
|
2293
1035
|
var TABS = [
|
|
2294
1036
|
{ id: "node", label: "Node" },
|
|
@@ -2574,9 +1316,10 @@ function LoginModal({
|
|
|
2574
1316
|
cloud,
|
|
2575
1317
|
initialTab: initialTabProp
|
|
2576
1318
|
}) {
|
|
2577
|
-
const
|
|
1319
|
+
const ownCloud = cloud === void 0 && !isDesktopWindow();
|
|
1320
|
+
const own = useAccountEnrolment({ enabled: ownCloud });
|
|
2578
1321
|
const cloudTab = useMemo(
|
|
2579
|
-
() =>
|
|
1322
|
+
() => ownCloud ? {
|
|
2580
1323
|
onEnrol: () => {
|
|
2581
1324
|
void own.goToWallet();
|
|
2582
1325
|
},
|
|
@@ -2584,9 +1327,9 @@ function LoginModal({
|
|
|
2584
1327
|
walletUrl: own.walletUrl,
|
|
2585
1328
|
customWallet: own.customWallet
|
|
2586
1329
|
} : cloud || null,
|
|
2587
|
-
[cloud, own.goToWallet, own.note, own.walletUrl, own.customWallet]
|
|
1330
|
+
[cloud, ownCloud, own.goToWallet, own.note, own.walletUrl, own.customWallet]
|
|
2588
1331
|
);
|
|
2589
|
-
const initialTab = initialTabProp ?? (
|
|
1332
|
+
const initialTab = initialTabProp ?? (ownCloud && own.returning ? "cloud" : "node");
|
|
2590
1333
|
const [tab, setTab] = useState(initialTab);
|
|
2591
1334
|
useEffect(() => {
|
|
2592
1335
|
if (isOpen) setTab(initialTab);
|
|
@@ -2890,9 +1633,10 @@ function ConnectButton({
|
|
|
2890
1633
|
theme,
|
|
2891
1634
|
logoOnly = false,
|
|
2892
1635
|
label,
|
|
2893
|
-
cloud
|
|
1636
|
+
cloud: cloudProp,
|
|
2894
1637
|
accountDefaults
|
|
2895
1638
|
}) {
|
|
1639
|
+
const cloud = cloudProp ?? !isDesktopWindow();
|
|
2896
1640
|
const { isAuthenticated, connectToNode, logout, nodeUrl, isOnline, isDelegated } = useMero();
|
|
2897
1641
|
const enrolment = useAccountEnrolment({
|
|
2898
1642
|
walletUrl: accountDefaults?.walletUrl,
|
|
@@ -3070,8 +1814,10 @@ function ConnectButtonAccount({
|
|
|
3070
1814
|
className,
|
|
3071
1815
|
style,
|
|
3072
1816
|
theme,
|
|
3073
|
-
defaults = {}
|
|
1817
|
+
defaults = {},
|
|
1818
|
+
cloud: cloudProp
|
|
3074
1819
|
}) {
|
|
1820
|
+
const cloud = cloudProp ?? !isDesktopWindow();
|
|
3075
1821
|
const { isAuthenticated, isOnline, nodeUrl, isDelegated, connectToNode, logout } = useMero();
|
|
3076
1822
|
const [isDropdownOpen, setIsDropdownOpen] = useState(false);
|
|
3077
1823
|
const [isNodeModalOpen, setIsNodeModalOpen] = useState(false);
|
|
@@ -3091,7 +1837,10 @@ function ConnectButtonAccount({
|
|
|
3091
1837
|
document.addEventListener("mousedown", onOutside);
|
|
3092
1838
|
return () => document.removeEventListener("mousedown", onOutside);
|
|
3093
1839
|
}, []);
|
|
3094
|
-
const { goToWallet, note, walletUrl } = useAccountEnrolment({
|
|
1840
|
+
const { goToWallet, note, walletUrl } = useAccountEnrolment({
|
|
1841
|
+
walletUrl: defaults.walletUrl,
|
|
1842
|
+
enabled: cloud
|
|
1843
|
+
});
|
|
3095
1844
|
if (isAuthenticated && !isOnline) {
|
|
3096
1845
|
return /* @__PURE__ */ jsx("div", { className: "mero-connect-container", style: { ...themeVars, display: "inline-block" }, children: /* @__PURE__ */ jsxs(
|
|
3097
1846
|
"button",
|
|
@@ -3170,7 +1919,7 @@ function ConnectButtonAccount({
|
|
|
3170
1919
|
]
|
|
3171
1920
|
}
|
|
3172
1921
|
),
|
|
3173
|
-
/* @__PURE__ */ jsx(
|
|
1922
|
+
cloud && /* @__PURE__ */ jsx(
|
|
3174
1923
|
"button",
|
|
3175
1924
|
{
|
|
3176
1925
|
className: ["mero-connect-button", className].filter(Boolean).join(" "),
|
|
@@ -3180,7 +1929,7 @@ function ConnectButtonAccount({
|
|
|
3180
1929
|
}
|
|
3181
1930
|
)
|
|
3182
1931
|
] }),
|
|
3183
|
-
isAccountOpen && /* @__PURE__ */ jsxs(
|
|
1932
|
+
cloud && isAccountOpen && /* @__PURE__ */ jsxs(
|
|
3184
1933
|
"div",
|
|
3185
1934
|
{
|
|
3186
1935
|
style: {
|
|
@@ -3245,8 +1994,6 @@ function base58ToHex(input) {
|
|
|
3245
1994
|
for (let k = 0; k < input.length && input[k] === "1"; k++) bytes.push(0);
|
|
3246
1995
|
return bytes.reverse().map((b) => b.toString(16).padStart(2, "0")).join("");
|
|
3247
1996
|
}
|
|
3248
|
-
|
|
3249
|
-
// src/hooks/index.ts
|
|
3250
1997
|
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.";
|
|
3251
1998
|
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.";
|
|
3252
1999
|
var REPLAY_RECONCILE_MS = 50;
|
|
@@ -5132,6 +3879,6 @@ function useJoinInvitation() {
|
|
|
5132
3879
|
return { joinInvitation, joining, memberships, invitationRedeemer };
|
|
5133
3880
|
}
|
|
5134
3881
|
|
|
5135
|
-
export { AccountSignInPanel, AppMode, CalimeroLogo, ConnectButton, ConnectButtonAccount, ConnectionType, DEFAULT_MIGRATION_POLL_INTERVAL_MS,
|
|
3882
|
+
export { AccountSignInPanel, AppMode, CalimeroLogo, ConnectButton, ConnectButtonAccount, ConnectionType, DEFAULT_MIGRATION_POLL_INTERVAL_MS, LoginModal, MERO_CSS_VARS, MeroContext, MeroProvider, MigrationAdminPanel, MigrationPendingBanner, clearAllStorage, clearApplicationId, clearContextId, clearContextIdentity, clearNodeUrl, clearTokenNodeUrl, cssVar, defaultMeroTheme, getApplicationId, getContextId, getContextIdentity, getNodeUrl, getTokenNodeUrl, isDesktopWindow, isFinalInvitationError, isReturningFromWallet, localStorageTokenStorage, resolveMeroTheme, setApplicationId, setContextId, setContextIdentity, setNodeUrl, setTokenNodeUrl, themeToCssVars, useAccountEnrolment, 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 };
|
|
5136
3883
|
//# sourceMappingURL=index.js.map
|
|
5137
3884
|
//# sourceMappingURL=index.js.map
|