@calimero-network/mero-js 29.14.0 → 29.16.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +36 -1
- package/dist/cloud-v2/approvals.d.ts +39 -2
- package/dist/cloud-v2/approvals.js +5 -1
- package/dist/cloud-v2/client.d.ts +25 -132
- package/dist/cloud-v2/client.js +48 -455
- package/dist/cloud-v2/errors.d.ts +18 -0
- package/dist/cloud-v2/errors.js +16 -0
- package/dist/cloud-v2/index.d.ts +2 -2
- package/dist/cloud-v2/index.js +1 -1
- package/dist/index.browser.mjs +5 -5
- package/dist/index.browser.mjs.map +4 -4
- package/dist/index.cjs +523 -386
- package/dist/index.cjs.map +4 -4
- package/dist/index.d.ts +2 -0
- package/dist/index.js +4 -0
- package/dist/index.mjs +523 -386
- package/dist/index.mjs.map +4 -4
- package/dist/runtime/index.d.ts +10 -0
- package/dist/runtime/index.js +21 -0
- package/dist/runtime/transport.d.ts +311 -0
- package/dist/runtime/transport.js +576 -0
- package/dist/runtime.browser.mjs +67 -0
- package/dist/runtime.cjs +67 -0
- package/dist/runtime.mjs +67 -0
- package/package.json +9 -2
package/dist/index.cjs
CHANGED
|
@@ -46,6 +46,7 @@ __export(index_exports, {
|
|
|
46
46
|
DEFAULT_DIRECTORY: () => DEFAULT_DIRECTORY,
|
|
47
47
|
DEFAULT_ORG_CAPABILITIES: () => DEFAULT_ORG_CAPABILITIES,
|
|
48
48
|
DEFAULT_RELEASE_MIRROR: () => DEFAULT_RELEASE_MIRROR,
|
|
49
|
+
DEFAULT_RETRY: () => DEFAULT_RETRY,
|
|
49
50
|
DirectoryError: () => DirectoryError,
|
|
50
51
|
GITHUB_RELEASES: () => GITHUB_RELEASES,
|
|
51
52
|
HANDSHAKE_PATH: () => HANDSHAKE_PATH,
|
|
@@ -56,6 +57,7 @@ __export(index_exports, {
|
|
|
56
57
|
MAX_REPORT_PAGE: () => MAX_REPORT_PAGE,
|
|
57
58
|
MOCK_QUOTE_HEADER: () => MOCK_QUOTE_HEADER,
|
|
58
59
|
NODE_RELEASE_SIGNER: () => NODE_RELEASE_SIGNER,
|
|
60
|
+
NodeTransport: () => NodeTransport,
|
|
59
61
|
NotFound: () => NotFound,
|
|
60
62
|
NotServing: () => NotServing,
|
|
61
63
|
ORG_CAPABILITIES: () => ORG_CAPABILITIES,
|
|
@@ -68,6 +70,7 @@ __export(index_exports, {
|
|
|
68
70
|
RELEASE_VERIFIER: () => RELEASE_VERIFIER,
|
|
69
71
|
RecoveryNotReady: () => RecoveryNotReady,
|
|
70
72
|
ReleaseDeadlineError: () => ReleaseDeadlineError,
|
|
73
|
+
RuntimeTooOld: () => RuntimeTooOld,
|
|
71
74
|
SEALED_CONTENT_TYPE: () => SEALED_CONTENT_TYPE,
|
|
72
75
|
SEALED_PATH: () => SEALED_PATH,
|
|
73
76
|
SealedTransportError: () => SealedTransportError,
|
|
@@ -92,6 +95,7 @@ __export(index_exports, {
|
|
|
92
95
|
createSealedFetch: () => createSealedFetch,
|
|
93
96
|
createSignedReleaseVerifier: () => createSignedReleaseVerifier,
|
|
94
97
|
deployerKey: () => deployerKey,
|
|
98
|
+
directoryTransport: () => directoryTransport,
|
|
95
99
|
errorFrom: () => errorFrom,
|
|
96
100
|
fetchAttestedKey: () => fetchAttestedKey,
|
|
97
101
|
fetchGithubNodeRelease: () => fetchGithubNodeRelease,
|
|
@@ -100,6 +104,7 @@ __export(index_exports, {
|
|
|
100
104
|
fromB64url: () => fromB64url,
|
|
101
105
|
frontendManifest: () => frontendManifest,
|
|
102
106
|
generateOwnerKey: () => generateOwnerKey,
|
|
107
|
+
newIdempotencyKey: () => newIdempotencyKey,
|
|
103
108
|
newRecoverySeed: () => newRecoverySeed,
|
|
104
109
|
orgCapabilities: () => orgCapabilities,
|
|
105
110
|
ownerPublicKey: () => ownerPublicKey,
|
|
@@ -111,13 +116,18 @@ __export(index_exports, {
|
|
|
111
116
|
provisionInfo: () => provisionInfo,
|
|
112
117
|
publisherBindingBytes: () => publisherBindingBytes,
|
|
113
118
|
publisherBindingMessage: () => publisherBindingMessage,
|
|
119
|
+
queryString: () => queryString,
|
|
114
120
|
recoveryMessage: () => recoveryMessage,
|
|
115
121
|
recoveryPublicKey: () => recoveryPublicKey,
|
|
116
122
|
recoverySeedText: () => recoverySeedText,
|
|
123
|
+
refusal: () => refusal,
|
|
117
124
|
releaseAgent: () => releaseAgent,
|
|
118
125
|
releaseConsent: () => releaseConsent,
|
|
119
126
|
releaseNotesUrl: () => releaseNotesUrl,
|
|
127
|
+
retryDelayMs: () => retryDelayMs,
|
|
128
|
+
routePath: () => routePath,
|
|
120
129
|
signRecovery: () => signRecovery,
|
|
130
|
+
sseFrames: () => sseFrames,
|
|
121
131
|
stalledBy: () => stalledBy,
|
|
122
132
|
transportKeyBinding: () => transportKeyBinding,
|
|
123
133
|
trustSignedRelease: () => trustSignedRelease,
|
|
@@ -1539,6 +1549,14 @@ var ReleaseDeadlineError = class extends CalimeroError {
|
|
|
1539
1549
|
this.after = typeof details.after === "string" ? details.after : "";
|
|
1540
1550
|
}
|
|
1541
1551
|
};
|
|
1552
|
+
var RuntimeTooOld = class extends CalimeroError {
|
|
1553
|
+
constructor(message, details = {}) {
|
|
1554
|
+
super(409, "RUNTIME_TOO_OLD", message, details);
|
|
1555
|
+
this.name = "RuntimeTooOld";
|
|
1556
|
+
this.minRuntimeVersion = typeof details.minRuntimeVersion === "string" ? details.minRuntimeVersion : "";
|
|
1557
|
+
this.nodes = Array.isArray(details.nodes) ? details.nodes : [];
|
|
1558
|
+
}
|
|
1559
|
+
};
|
|
1542
1560
|
var ConsentStale = class extends CalimeroError {
|
|
1543
1561
|
constructor(message, details = {}) {
|
|
1544
1562
|
super(409, "CONSENT_STALE", message, details);
|
|
@@ -1674,6 +1692,8 @@ function errorFrom(status, body, retryAfterHeader) {
|
|
|
1674
1692
|
return new IdempotencyMismatch(message, details);
|
|
1675
1693
|
case "409 RELEASE_DEADLINE":
|
|
1676
1694
|
return new ReleaseDeadlineError(message, details);
|
|
1695
|
+
case "409 RUNTIME_TOO_OLD":
|
|
1696
|
+
return new RuntimeTooOld(message, details);
|
|
1677
1697
|
case "409 CONSENT_STALE":
|
|
1678
1698
|
return new ConsentStale(message, details);
|
|
1679
1699
|
case "403 ORIGIN_NOT_REGISTERED":
|
|
@@ -1792,6 +1812,440 @@ function browserPasskey() {
|
|
|
1792
1812
|
};
|
|
1793
1813
|
}
|
|
1794
1814
|
|
|
1815
|
+
// src/runtime/transport.ts
|
|
1816
|
+
var DEFAULT_RETRY = { retries: 6, baseDelayMs: 200, maxDelayMs: 2e3 };
|
|
1817
|
+
function retryDelayMs(retry, options) {
|
|
1818
|
+
return Math.min(options.baseDelayMs * 2 ** retry, options.maxDelayMs);
|
|
1819
|
+
}
|
|
1820
|
+
function userVerificationOf(named, fallback) {
|
|
1821
|
+
return named === "required" || named === "preferred" || named === "discouraged" ? named : fallback;
|
|
1822
|
+
}
|
|
1823
|
+
function promptFailure(error) {
|
|
1824
|
+
const e = error;
|
|
1825
|
+
const name = e?.name;
|
|
1826
|
+
const message = typeof e?.message === "string" ? e.message : "";
|
|
1827
|
+
if (name === "InvalidStateError" || /not focused|already pending/i.test(message)) {
|
|
1828
|
+
return new ConfirmPromptBlocked(error);
|
|
1829
|
+
}
|
|
1830
|
+
if (name === "NotAllowedError" || name === "AbortError") return new ConfirmCancelled(error);
|
|
1831
|
+
return error;
|
|
1832
|
+
}
|
|
1833
|
+
function sealedError(error) {
|
|
1834
|
+
if (error instanceof SealedTransportError && error.status === 413) {
|
|
1835
|
+
return errorFrom(413, {
|
|
1836
|
+
error: "TOO_LARGE",
|
|
1837
|
+
message: error.message.replace(/^Sealed request refused: /, "")
|
|
1838
|
+
});
|
|
1839
|
+
}
|
|
1840
|
+
return error;
|
|
1841
|
+
}
|
|
1842
|
+
async function refusal(response) {
|
|
1843
|
+
const text = await response.text().catch(() => "");
|
|
1844
|
+
let body = {};
|
|
1845
|
+
try {
|
|
1846
|
+
body = text ? JSON.parse(text) : {};
|
|
1847
|
+
} catch {
|
|
1848
|
+
body = { message: text };
|
|
1849
|
+
}
|
|
1850
|
+
return errorFrom(response.status, body, response.headers.get("retry-after"));
|
|
1851
|
+
}
|
|
1852
|
+
async function* sseFrames(body) {
|
|
1853
|
+
const reader = body.getReader();
|
|
1854
|
+
const decoder = new TextDecoder();
|
|
1855
|
+
let buffer = "";
|
|
1856
|
+
for (; ; ) {
|
|
1857
|
+
const { value, done } = await reader.read();
|
|
1858
|
+
if (done) return;
|
|
1859
|
+
buffer += decoder.decode(value, { stream: true });
|
|
1860
|
+
let cut;
|
|
1861
|
+
while ((cut = buffer.indexOf("\n\n")) >= 0) {
|
|
1862
|
+
const frame = buffer.slice(0, cut);
|
|
1863
|
+
buffer = buffer.slice(cut + 2);
|
|
1864
|
+
let id = "";
|
|
1865
|
+
let kind = "";
|
|
1866
|
+
let data = "";
|
|
1867
|
+
for (const line of frame.split("\n")) {
|
|
1868
|
+
if (line.startsWith("id:")) id = line.slice(3).trim();
|
|
1869
|
+
else if (line.startsWith("event:")) kind = line.slice(6).trim();
|
|
1870
|
+
else if (line.startsWith("data:")) data += line.slice(5).trim();
|
|
1871
|
+
}
|
|
1872
|
+
if (!kind && !data) continue;
|
|
1873
|
+
let parsed = data;
|
|
1874
|
+
try {
|
|
1875
|
+
parsed = JSON.parse(data);
|
|
1876
|
+
} catch {
|
|
1877
|
+
}
|
|
1878
|
+
yield { id, kind, data: parsed };
|
|
1879
|
+
}
|
|
1880
|
+
}
|
|
1881
|
+
}
|
|
1882
|
+
function newIdempotencyKey() {
|
|
1883
|
+
return `node:c-${b64url(crypto.getRandomValues(new Uint8Array(16)))}`;
|
|
1884
|
+
}
|
|
1885
|
+
function routePath(template, params = {}) {
|
|
1886
|
+
return template.replace(/\{([^}]+)\}/g, (_, name) => {
|
|
1887
|
+
const value = params[name];
|
|
1888
|
+
if (value === void 0) throw new Error(`no value for path parameter ${name} of ${template}`);
|
|
1889
|
+
return encodeURIComponent(String(value));
|
|
1890
|
+
});
|
|
1891
|
+
}
|
|
1892
|
+
function queryString(query) {
|
|
1893
|
+
if (!query) return "";
|
|
1894
|
+
const search = new URLSearchParams();
|
|
1895
|
+
for (const [name, value] of Object.entries(query)) {
|
|
1896
|
+
for (const one of Array.isArray(value) ? value : [value]) {
|
|
1897
|
+
if (one !== void 0 && one !== null) search.append(name, String(one));
|
|
1898
|
+
}
|
|
1899
|
+
}
|
|
1900
|
+
const text = search.toString();
|
|
1901
|
+
return text ? `?${text}` : "";
|
|
1902
|
+
}
|
|
1903
|
+
function ceremony(path) {
|
|
1904
|
+
return path === "auth/refresh" || path.startsWith("auth/passkey/") || RECOVERY_CEREMONIES.has(path);
|
|
1905
|
+
}
|
|
1906
|
+
var RECOVERY_CEREMONIES = /* @__PURE__ */ new Set(["auth/recovery/begin", "auth/recovery/start", "auth/recovery/finish"]);
|
|
1907
|
+
function relative(path) {
|
|
1908
|
+
return path.replace(/^\/+/, "");
|
|
1909
|
+
}
|
|
1910
|
+
var NodeTransport = class {
|
|
1911
|
+
constructor(options) {
|
|
1912
|
+
/** The one in use: an index into {@link nodeUrls}. */
|
|
1913
|
+
this.at = 0;
|
|
1914
|
+
/** A sealed fetch per node, each attesting its own node on first use. */
|
|
1915
|
+
this.channels = /* @__PURE__ */ new Map();
|
|
1916
|
+
/** Rejections of the underlying `fetch` itself: the node could not be reached or dropped the connection. */
|
|
1917
|
+
this.networkFailures = /* @__PURE__ */ new WeakSet();
|
|
1918
|
+
const trim = (url2) => url2.replace(/\/+$/, "");
|
|
1919
|
+
this.nodeUrls = [...new Set([options.baseUrl, ...options.nodes ?? []].map(trim))];
|
|
1920
|
+
this.policy = options.policy;
|
|
1921
|
+
this.retry = { ...DEFAULT_RETRY, ...options.retry };
|
|
1922
|
+
const given = options.fetch ?? ((input, init) => fetch(input, init));
|
|
1923
|
+
const raw = async (input, init) => {
|
|
1924
|
+
try {
|
|
1925
|
+
return await given(input, init);
|
|
1926
|
+
} catch (error) {
|
|
1927
|
+
if (error instanceof TypeError) this.networkFailures.add(error);
|
|
1928
|
+
throw error;
|
|
1929
|
+
}
|
|
1930
|
+
};
|
|
1931
|
+
this.raw = raw;
|
|
1932
|
+
}
|
|
1933
|
+
/** Re-read the node list from `source` when it is due, and after a failover. */
|
|
1934
|
+
useDirectory(source) {
|
|
1935
|
+
this.source = source;
|
|
1936
|
+
}
|
|
1937
|
+
/** The node requests go to now: `baseUrl`, until a `421 WRONG_NODE` or a failover moved on. */
|
|
1938
|
+
get nodeUrl() {
|
|
1939
|
+
return this.nodeUrls[this.at];
|
|
1940
|
+
}
|
|
1941
|
+
/** Every node this transport may use, in the order it moves through them. */
|
|
1942
|
+
get nodes() {
|
|
1943
|
+
return [...this.nodeUrls];
|
|
1944
|
+
}
|
|
1945
|
+
/** Authenticate every request with an API key. */
|
|
1946
|
+
useApiKey(key) {
|
|
1947
|
+
this.auth = key;
|
|
1948
|
+
this.current = void 0;
|
|
1949
|
+
}
|
|
1950
|
+
/** Authenticate every request with `session`, refreshed when a node answers `401` to it. */
|
|
1951
|
+
useSession(session) {
|
|
1952
|
+
this.auth = session.sessionToken;
|
|
1953
|
+
this.current = session;
|
|
1954
|
+
}
|
|
1955
|
+
/** Drop the credential: no request after this carries it. */
|
|
1956
|
+
signOut() {
|
|
1957
|
+
this.auth = void 0;
|
|
1958
|
+
this.current = void 0;
|
|
1959
|
+
}
|
|
1960
|
+
get session() {
|
|
1961
|
+
return this.current;
|
|
1962
|
+
}
|
|
1963
|
+
/** The sealed channel to `url`, attested under the policy before its first request. */
|
|
1964
|
+
channel(url2) {
|
|
1965
|
+
let sealed = this.channels.get(url2);
|
|
1966
|
+
if (!sealed) {
|
|
1967
|
+
sealed = createSealedFetch({
|
|
1968
|
+
baseUrl: url2,
|
|
1969
|
+
transportPublicKey: () => fetchAttestedKey(url2, this.policy, this.raw),
|
|
1970
|
+
fetch: this.raw
|
|
1971
|
+
});
|
|
1972
|
+
this.channels.set(url2, sealed);
|
|
1973
|
+
}
|
|
1974
|
+
return sealed;
|
|
1975
|
+
}
|
|
1976
|
+
/**
|
|
1977
|
+
* Move on from node `from` (the one that answered `421 WRONG_NODE`) to the
|
|
1978
|
+
* next one. False when there is no other. A request that saw the same node
|
|
1979
|
+
* refuse after another request moved on already does not move again.
|
|
1980
|
+
*/
|
|
1981
|
+
moveOn(from) {
|
|
1982
|
+
if (this.nodeUrls.length < 2) return false;
|
|
1983
|
+
if (this.nodeUrl === from) this.at = (this.at + 1) % this.nodeUrls.length;
|
|
1984
|
+
return true;
|
|
1985
|
+
}
|
|
1986
|
+
/**
|
|
1987
|
+
* Fail over from node `from`, where a request's retries ran out, to the next
|
|
1988
|
+
* node it has not `tried`. False when it has tried them all. A request whose
|
|
1989
|
+
* node another request moved away from already goes to that node, if untried.
|
|
1990
|
+
*/
|
|
1991
|
+
failOver(from, tried) {
|
|
1992
|
+
if (this.nodeUrl !== from && !tried.has(this.nodeUrl)) return true;
|
|
1993
|
+
const count = this.nodeUrls.length;
|
|
1994
|
+
for (let step = 1; step < count; step++) {
|
|
1995
|
+
const next = (this.at + step) % count;
|
|
1996
|
+
if (!tried.has(this.nodeUrls[next])) {
|
|
1997
|
+
this.at = next;
|
|
1998
|
+
this.reread();
|
|
1999
|
+
return true;
|
|
2000
|
+
}
|
|
2001
|
+
}
|
|
2002
|
+
return false;
|
|
2003
|
+
}
|
|
2004
|
+
/**
|
|
2005
|
+
* Read the node list again from the directory, in the background: the node
|
|
2006
|
+
* in use stays first, then the directory's order; a node no longer listed is
|
|
2007
|
+
* dropped. A failed read is ignored. One read at a time.
|
|
2008
|
+
*/
|
|
2009
|
+
reread() {
|
|
2010
|
+
const source = this.source;
|
|
2011
|
+
if (!source || source.reading) return;
|
|
2012
|
+
source.reading = readDirectory(source.directory, source.cluster, this.raw).then((listing) => {
|
|
2013
|
+
const current = this.nodeUrl;
|
|
2014
|
+
const listed = orderNodes(listing.nodes, source.zone, source.random);
|
|
2015
|
+
this.nodeUrls = [current, ...listed.filter((url2) => url2 !== current)];
|
|
2016
|
+
this.at = 0;
|
|
2017
|
+
source.due = Date.now() + listing.refreshAfterSeconds * 1e3;
|
|
2018
|
+
}).catch(() => void 0).finally(() => {
|
|
2019
|
+
source.reading = void 0;
|
|
2020
|
+
});
|
|
2021
|
+
}
|
|
2022
|
+
/**
|
|
2023
|
+
* Send one request to the node in use, with the credential held now, and
|
|
2024
|
+
* answer the response, whatever its status. {@link send} judges it.
|
|
2025
|
+
*/
|
|
2026
|
+
async once(method, path, options) {
|
|
2027
|
+
const headers = {};
|
|
2028
|
+
if (this.auth) headers.authorization = `Bearer ${this.auth}`;
|
|
2029
|
+
let payload;
|
|
2030
|
+
if (options.bytes) {
|
|
2031
|
+
headers["content-type"] = options.contentType ?? "application/wasm";
|
|
2032
|
+
payload = options.bytes;
|
|
2033
|
+
} else if (options.body !== void 0) {
|
|
2034
|
+
headers["content-type"] = "application/json";
|
|
2035
|
+
payload = JSON.stringify(options.body);
|
|
2036
|
+
}
|
|
2037
|
+
if (this.source && Date.now() >= this.source.due) this.reread();
|
|
2038
|
+
const url2 = this.nodeUrl;
|
|
2039
|
+
try {
|
|
2040
|
+
return await this.channel(url2)(`${url2}/${path}${queryString(options.query)}`, {
|
|
2041
|
+
method,
|
|
2042
|
+
headers,
|
|
2043
|
+
body: payload,
|
|
2044
|
+
signal: options.signal
|
|
2045
|
+
});
|
|
2046
|
+
} catch (error) {
|
|
2047
|
+
throw sealedError(error);
|
|
2048
|
+
}
|
|
2049
|
+
}
|
|
2050
|
+
/**
|
|
2051
|
+
* {@link once}, answering what a lost issuing node or a node on the wrong
|
|
2052
|
+
* release does to a session: a successful response, or the refusal as a
|
|
2053
|
+
* typed error ({@link errorFrom}).
|
|
2054
|
+
*
|
|
2055
|
+
* - `401 UNAUTHENTICATED` to a request that carried a session: the node that
|
|
2056
|
+
* signed the session may be gone, replaced, or out of reach of the node
|
|
2057
|
+
* asked, which any node of the cluster answers with a refresh. The
|
|
2058
|
+
* transport refreshes once, shared by every request that needs it at the
|
|
2059
|
+
* same time ({@link refresh}), and repeats the request once. A refresh that
|
|
2060
|
+
* is refused surfaces as {@link LoginRequired}.
|
|
2061
|
+
* - `421 WRONG_NODE`: this node's release may not serve the account. The
|
|
2062
|
+
* transport moves to the next node it knows and repeats the request once;
|
|
2063
|
+
* with none, the {@link WrongNode} reaches the caller.
|
|
2064
|
+
*
|
|
2065
|
+
* Repeating is safe even for a request that is not idempotent: the node
|
|
2066
|
+
* answers `401` and `421` when it judges the credential, before it reads what
|
|
2067
|
+
* the request asks, so the first attempt ran nothing. The exceptions are the
|
|
2068
|
+
* ceremonies that mint a session ({@link ceremony}), never repeated here.
|
|
2069
|
+
*/
|
|
2070
|
+
async send(method, path, options) {
|
|
2071
|
+
let refreshed = false;
|
|
2072
|
+
let moved = false;
|
|
2073
|
+
for (; ; ) {
|
|
2074
|
+
const [token, at] = [this.auth, this.nodeUrl];
|
|
2075
|
+
const response = await this.once(method, path, options);
|
|
2076
|
+
if (response.ok) return response;
|
|
2077
|
+
const error = await refusal(response);
|
|
2078
|
+
if (error instanceof WrongNode && !moved) {
|
|
2079
|
+
moved = true;
|
|
2080
|
+
if (this.moveOn(at) && !ceremony(path)) continue;
|
|
2081
|
+
} else if (error instanceof LoginRequired && !refreshed && this.mayRefresh(token, path)) {
|
|
2082
|
+
refreshed = true;
|
|
2083
|
+
await this.renew(token);
|
|
2084
|
+
continue;
|
|
2085
|
+
}
|
|
2086
|
+
throw error;
|
|
2087
|
+
}
|
|
2088
|
+
}
|
|
2089
|
+
/** Whether a `401` to a request sent with `token` is one a refresh may answer. */
|
|
2090
|
+
mayRefresh(token, path) {
|
|
2091
|
+
return token !== void 0 && this.current !== void 0 && !ceremony(path);
|
|
2092
|
+
}
|
|
2093
|
+
/**
|
|
2094
|
+
* A fresh session in place of the one `token` belonged to: by the refresh
|
|
2095
|
+
* another request already made, or by one this request starts.
|
|
2096
|
+
*/
|
|
2097
|
+
async renew(token) {
|
|
2098
|
+
if (this.auth !== token) return;
|
|
2099
|
+
await this.refresh();
|
|
2100
|
+
}
|
|
2101
|
+
async read(method, path, options) {
|
|
2102
|
+
const response = await this.send(method, path, options);
|
|
2103
|
+
const text = await response.text();
|
|
2104
|
+
return text ? JSON.parse(text) : {};
|
|
2105
|
+
}
|
|
2106
|
+
/**
|
|
2107
|
+
* {@link read} for a call or a view (D70): while the node answers 503 or
|
|
2108
|
+
* cannot be reached, the same request, with the same idempotency key, is sent
|
|
2109
|
+
* again after {@link retryDelayMs} (or the pause the node asked for, if
|
|
2110
|
+
* longer), at most `retries` times. Every other answer is final.
|
|
2111
|
+
*
|
|
2112
|
+
* When a node's retries run out, the request fails over to the next node the
|
|
2113
|
+
* transport knows and its retries start again there, with the same key: the
|
|
2114
|
+
* key is kept in the app's replicated log, so the cluster answers it once
|
|
2115
|
+
* whichever node it reaches. Each node is tried once per request. The last
|
|
2116
|
+
* failure surfaces as {@link UnavailableError}: the node's 503, or reason
|
|
2117
|
+
* `network` for a connection that failed, whose `committed` is `'unknown'`.
|
|
2118
|
+
*
|
|
2119
|
+
* `once` sends the request exactly once, to the node in use (a confirmed
|
|
2120
|
+
* attempt, whose challenge is single-use).
|
|
2121
|
+
*/
|
|
2122
|
+
async retried(method, path, options, once) {
|
|
2123
|
+
const retries = once ? 0 : this.retry.retries;
|
|
2124
|
+
const tried = /* @__PURE__ */ new Set();
|
|
2125
|
+
for (; ; ) {
|
|
2126
|
+
let unavailable;
|
|
2127
|
+
let node = this.nodeUrl;
|
|
2128
|
+
for (let attempt = 0; ; attempt++) {
|
|
2129
|
+
node = this.nodeUrl;
|
|
2130
|
+
tried.add(node);
|
|
2131
|
+
try {
|
|
2132
|
+
return await this.read(method, path, options);
|
|
2133
|
+
} catch (error) {
|
|
2134
|
+
if (error instanceof UnavailableError) unavailable = error;
|
|
2135
|
+
else if (error instanceof TypeError && this.networkFailures.has(error)) {
|
|
2136
|
+
unavailable = new UnavailableError("NETWORK", `the node could not be reached: ${error.message}`, {}, void 0, error);
|
|
2137
|
+
} else throw error;
|
|
2138
|
+
}
|
|
2139
|
+
if (attempt >= retries) break;
|
|
2140
|
+
const backoff = retryDelayMs(attempt, this.retry);
|
|
2141
|
+
await new Promise((resolve) => setTimeout(resolve, Math.max(backoff, (unavailable.retryAfter ?? 0) * 1e3)));
|
|
2142
|
+
}
|
|
2143
|
+
if (once || !this.failOver(node, tried)) throw unavailable;
|
|
2144
|
+
}
|
|
2145
|
+
}
|
|
2146
|
+
/**
|
|
2147
|
+
* One JSON request, retried as `options.retry` says. The confirmed attempt
|
|
2148
|
+
* of a step-up (`body.confirm` set) goes out exactly once.
|
|
2149
|
+
*/
|
|
2150
|
+
attempt(method, path, options) {
|
|
2151
|
+
if (!options.retry) return this.read(method, path, options);
|
|
2152
|
+
const confirming = options.body?.confirm !== void 0;
|
|
2153
|
+
return this.retried(method, path, options, options.retry === "once" || confirming);
|
|
2154
|
+
}
|
|
2155
|
+
/**
|
|
2156
|
+
* {@link attempt}, answering a `412 CONFIRM_REQUIRED` with `passkey`'s
|
|
2157
|
+
* assertion over the node's challenge: the same body again, with `confirm`.
|
|
2158
|
+
* Without a passkey the `412` reaches the caller as {@link ConfirmRequired}.
|
|
2159
|
+
*/
|
|
2160
|
+
async confirmed(method, path, options) {
|
|
2161
|
+
const { passkey } = options;
|
|
2162
|
+
const signal = options.promptSignal ?? options.signal;
|
|
2163
|
+
try {
|
|
2164
|
+
return await this.attempt(method, path, options);
|
|
2165
|
+
} catch (error) {
|
|
2166
|
+
if (!(error instanceof ConfirmRequired) || !passkey) throw error;
|
|
2167
|
+
const d = error.details;
|
|
2168
|
+
let assertion;
|
|
2169
|
+
try {
|
|
2170
|
+
assertion = await passkey.get(fromB64url(d.challenge), d.rpId, d.allowCredentials, {
|
|
2171
|
+
userVerification: userVerificationOf(d.userVerification, options.userVerification ?? "required"),
|
|
2172
|
+
...signal ? { signal } : {}
|
|
2173
|
+
});
|
|
2174
|
+
} catch (declined) {
|
|
2175
|
+
throw promptFailure(declined);
|
|
2176
|
+
}
|
|
2177
|
+
const body = { ...options.body, confirm: { challengeId: d.challengeId, assertion } };
|
|
2178
|
+
return this.attempt(method, path, { ...options, body });
|
|
2179
|
+
}
|
|
2180
|
+
}
|
|
2181
|
+
request(method, path, options = {}) {
|
|
2182
|
+
return this.send(method, relative(path), options);
|
|
2183
|
+
}
|
|
2184
|
+
json(method, path, options = {}) {
|
|
2185
|
+
return this.confirmed(method, relative(path), options);
|
|
2186
|
+
}
|
|
2187
|
+
async *events(path, options = {}) {
|
|
2188
|
+
const response = await this.send("GET", relative(path), options);
|
|
2189
|
+
if (!response.body) throw new CalimeroError(response.status, "EVENTS", "the event stream has no body");
|
|
2190
|
+
yield* sseFrames(response.body);
|
|
2191
|
+
}
|
|
2192
|
+
/**
|
|
2193
|
+
* `GET path` in the clear, from the node in use: only for the route a node
|
|
2194
|
+
* serves unsealed (`attestation`), and never with the credential.
|
|
2195
|
+
*/
|
|
2196
|
+
async unsealed(path, options = {}) {
|
|
2197
|
+
const response = await this.raw(`${this.nodeUrl}/${relative(path)}${queryString(options.query)}`);
|
|
2198
|
+
if (!response.ok) throw await refusal(response);
|
|
2199
|
+
return response;
|
|
2200
|
+
}
|
|
2201
|
+
/**
|
|
2202
|
+
* Swap the refresh token for a new session, on whichever node the transport
|
|
2203
|
+
* uses: any node of the cluster takes it. A refresh token is used once, so
|
|
2204
|
+
* requests made while one refresh is under way share it rather than sending
|
|
2205
|
+
* the same token again (which would revoke the session).
|
|
2206
|
+
*/
|
|
2207
|
+
refresh() {
|
|
2208
|
+
if (!this.refreshing) {
|
|
2209
|
+
const pending = this.exchangeRefresh();
|
|
2210
|
+
this.refreshing = pending;
|
|
2211
|
+
const clear = () => {
|
|
2212
|
+
if (this.refreshing === pending) this.refreshing = void 0;
|
|
2213
|
+
};
|
|
2214
|
+
pending.then(clear, clear);
|
|
2215
|
+
}
|
|
2216
|
+
return this.refreshing;
|
|
2217
|
+
}
|
|
2218
|
+
async exchangeRefresh() {
|
|
2219
|
+
const current = this.current;
|
|
2220
|
+
if (!current) throw new Error("no session to refresh");
|
|
2221
|
+
let session;
|
|
2222
|
+
for (let tried = 1; session === void 0; tried++) {
|
|
2223
|
+
try {
|
|
2224
|
+
session = await this.json("POST", "auth/refresh", { body: { refreshToken: current.refreshToken } });
|
|
2225
|
+
} catch (error) {
|
|
2226
|
+
if (!(error instanceof WrongNode) || tried >= this.nodeUrls.length) throw error;
|
|
2227
|
+
}
|
|
2228
|
+
}
|
|
2229
|
+
if (this.current === current) this.useSession(session);
|
|
2230
|
+
return session;
|
|
2231
|
+
}
|
|
2232
|
+
};
|
|
2233
|
+
async function directoryTransport(options) {
|
|
2234
|
+
const random = options.random ?? Math.random;
|
|
2235
|
+
const fetcher = options.fetch ?? ((input, init) => fetch(input, init));
|
|
2236
|
+
const listing = await readDirectory(options.directory, options.cluster, fetcher);
|
|
2237
|
+
const [baseUrl, ...nodes] = orderNodes(listing.nodes, options.zone, random);
|
|
2238
|
+
const transport = new NodeTransport({ baseUrl, nodes, policy: options.policy, fetch: options.fetch, retry: options.retry });
|
|
2239
|
+
transport.useDirectory({
|
|
2240
|
+
directory: options.directory,
|
|
2241
|
+
cluster: options.cluster,
|
|
2242
|
+
zone: options.zone,
|
|
2243
|
+
random,
|
|
2244
|
+
due: Date.now() + listing.refreshAfterSeconds * 1e3
|
|
2245
|
+
});
|
|
2246
|
+
return transport;
|
|
2247
|
+
}
|
|
2248
|
+
|
|
1795
2249
|
// src/cloud-v2/recovery.ts
|
|
1796
2250
|
var RECOVERY_DOMAIN = "calimero.org-recovery.v1\0";
|
|
1797
2251
|
var MAX_RECOVERY_NONCE_BYTES = 64;
|
|
@@ -1941,12 +2395,16 @@ function pendingApprovalsFrom(report, rules, now = Date.now() / 1e3) {
|
|
|
1941
2395
|
for (const a of report.apps) {
|
|
1942
2396
|
const available = a.availableVersions ?? [];
|
|
1943
2397
|
if (a.package === null || available.length === 0) continue;
|
|
2398
|
+
const latest = available[available.length - 1];
|
|
2399
|
+
const reachable = a.latestReachable === void 0 ? latest : a.latestReachable;
|
|
1944
2400
|
upgrades.push({
|
|
1945
2401
|
app: a.app,
|
|
1946
2402
|
name: a.name ?? null,
|
|
1947
2403
|
package: a.package.package,
|
|
1948
2404
|
from: a.package.version,
|
|
1949
|
-
to:
|
|
2405
|
+
to: reachable ?? latest,
|
|
2406
|
+
reachable: reachable !== null,
|
|
2407
|
+
blocked: a.latestBlocked ?? null,
|
|
1950
2408
|
available,
|
|
1951
2409
|
actionable: upgradesActionable
|
|
1952
2410
|
});
|
|
@@ -1976,114 +2434,36 @@ function upgradeConsent(app, toVersion, returnTo) {
|
|
|
1976
2434
|
return { kind: "upgrade", subject: { app, toVersion }, returnTo };
|
|
1977
2435
|
}
|
|
1978
2436
|
|
|
1979
|
-
// src/cloud-v2/client.ts
|
|
1980
|
-
function deployerKey(deployer) {
|
|
1981
|
-
return "account" in deployer ? `account:${deployer.account}` : `org:${deployer.org}`;
|
|
1982
|
-
}
|
|
1983
|
-
async function frontendManifest(origin, fetcher = fetch) {
|
|
1984
|
-
const base = origin ?? globalThis.location?.origin;
|
|
1985
|
-
if (!base) throw new Error("no page origin to read the frontend manifest from; pass `origin`");
|
|
1986
|
-
const response = await fetcher(new URL("/.well-known/calimero.json", base).toString());
|
|
1987
|
-
if (!response.ok) throw await refusal(response);
|
|
1988
|
-
const manifest = await response.json();
|
|
1989
|
-
return { ...manifest, deployments: manifest.deployments ?? [] };
|
|
1990
|
-
}
|
|
1991
|
-
function pageDeployment(href) {
|
|
1992
|
-
const at = href ?? globalThis.location?.href;
|
|
1993
|
-
if (!at) return null;
|
|
1994
|
-
try {
|
|
1995
|
-
return new URL(at).searchParams.get("deployment") || null;
|
|
1996
|
-
} catch {
|
|
1997
|
-
return null;
|
|
1998
|
-
}
|
|
1999
|
-
}
|
|
2000
|
-
function userVerificationOf(named, fallback) {
|
|
2001
|
-
return named === "required" || named === "preferred" || named === "discouraged" ? named : fallback;
|
|
2002
|
-
}
|
|
2003
|
-
function promptFailure(error) {
|
|
2004
|
-
const e = error;
|
|
2005
|
-
const name = e?.name;
|
|
2006
|
-
const message = typeof e?.message === "string" ? e.message : "";
|
|
2007
|
-
if (name === "InvalidStateError" || /not focused|already pending/i.test(message)) {
|
|
2008
|
-
return new ConfirmPromptBlocked(error);
|
|
2009
|
-
}
|
|
2010
|
-
if (name === "NotAllowedError" || name === "AbortError") return new ConfirmCancelled(error);
|
|
2011
|
-
return error;
|
|
2012
|
-
}
|
|
2013
|
-
function seg(value) {
|
|
2014
|
-
return encodeURIComponent(value);
|
|
2015
|
-
}
|
|
2016
|
-
function sealedError(error) {
|
|
2017
|
-
if (error instanceof SealedTransportError && error.status === 413) {
|
|
2018
|
-
return errorFrom(413, {
|
|
2019
|
-
error: "TOO_LARGE",
|
|
2020
|
-
message: error.message.replace(/^Sealed request refused: /, "")
|
|
2021
|
-
});
|
|
2022
|
-
}
|
|
2023
|
-
return error;
|
|
2024
|
-
}
|
|
2025
|
-
async function refusal(response) {
|
|
2026
|
-
const text = await response.text().catch(() => "");
|
|
2027
|
-
let body = {};
|
|
2028
|
-
try {
|
|
2029
|
-
body = text ? JSON.parse(text) : {};
|
|
2030
|
-
} catch {
|
|
2031
|
-
body = { message: text };
|
|
2032
|
-
}
|
|
2033
|
-
return errorFrom(response.status, body, response.headers.get("retry-after"));
|
|
2034
|
-
}
|
|
2035
|
-
async function* sseFrames(body) {
|
|
2036
|
-
const reader = body.getReader();
|
|
2037
|
-
const decoder = new TextDecoder();
|
|
2038
|
-
let buffer = "";
|
|
2039
|
-
for (; ; ) {
|
|
2040
|
-
const { value, done } = await reader.read();
|
|
2041
|
-
if (done) return;
|
|
2042
|
-
buffer += decoder.decode(value, { stream: true });
|
|
2043
|
-
let cut;
|
|
2044
|
-
while ((cut = buffer.indexOf("\n\n")) >= 0) {
|
|
2045
|
-
const frame = buffer.slice(0, cut);
|
|
2046
|
-
buffer = buffer.slice(cut + 2);
|
|
2047
|
-
let id = "";
|
|
2048
|
-
let kind = "";
|
|
2049
|
-
let data = "";
|
|
2050
|
-
for (const line of frame.split("\n")) {
|
|
2051
|
-
if (line.startsWith("id:")) id = line.slice(3).trim();
|
|
2052
|
-
else if (line.startsWith("event:")) kind = line.slice(6).trim();
|
|
2053
|
-
else if (line.startsWith("data:")) data += line.slice(5).trim();
|
|
2054
|
-
}
|
|
2055
|
-
if (!kind && !data) continue;
|
|
2056
|
-
let parsed = data;
|
|
2057
|
-
try {
|
|
2058
|
-
parsed = JSON.parse(data);
|
|
2059
|
-
} catch {
|
|
2060
|
-
}
|
|
2061
|
-
yield { id, kind, data: parsed };
|
|
2062
|
-
}
|
|
2063
|
-
}
|
|
2437
|
+
// src/cloud-v2/client.ts
|
|
2438
|
+
function deployerKey(deployer) {
|
|
2439
|
+
return "account" in deployer ? `account:${deployer.account}` : `org:${deployer.org}`;
|
|
2064
2440
|
}
|
|
2065
|
-
function
|
|
2066
|
-
|
|
2441
|
+
async function frontendManifest(origin, fetcher = fetch) {
|
|
2442
|
+
const base = origin ?? globalThis.location?.origin;
|
|
2443
|
+
if (!base) throw new Error("no page origin to read the frontend manifest from; pass `origin`");
|
|
2444
|
+
const response = await fetcher(new URL("/.well-known/calimero.json", base).toString());
|
|
2445
|
+
if (!response.ok) throw await refusal(response);
|
|
2446
|
+
const manifest = await response.json();
|
|
2447
|
+
return { ...manifest, deployments: manifest.deployments ?? [] };
|
|
2067
2448
|
}
|
|
2068
|
-
function
|
|
2069
|
-
|
|
2449
|
+
function pageDeployment(href) {
|
|
2450
|
+
const at = href ?? globalThis.location?.href;
|
|
2451
|
+
if (!at) return null;
|
|
2452
|
+
try {
|
|
2453
|
+
return new URL(at).searchParams.get("deployment") || null;
|
|
2454
|
+
} catch {
|
|
2455
|
+
return null;
|
|
2456
|
+
}
|
|
2070
2457
|
}
|
|
2071
|
-
|
|
2072
|
-
|
|
2073
|
-
return Math.min(options.baseDelayMs * 2 ** retry, options.maxDelayMs);
|
|
2458
|
+
function seg(value) {
|
|
2459
|
+
return encodeURIComponent(value);
|
|
2074
2460
|
}
|
|
2075
|
-
function
|
|
2076
|
-
return
|
|
2461
|
+
function toHex(bytes) {
|
|
2462
|
+
return Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("");
|
|
2077
2463
|
}
|
|
2078
|
-
var RECOVERY_CEREMONIES = /* @__PURE__ */ new Set(["auth/recovery/begin", "auth/recovery/start", "auth/recovery/finish"]);
|
|
2079
2464
|
var CalimeroClient = class _CalimeroClient {
|
|
2465
|
+
/** A client of the nodes `options` names, or one sending through an existing `transport`. */
|
|
2080
2466
|
constructor(options) {
|
|
2081
|
-
/** The one in use: an index into {@link nodeUrls}. */
|
|
2082
|
-
this.at = 0;
|
|
2083
|
-
/** A sealed fetch per node, each attesting its own node on first use. */
|
|
2084
|
-
this.channels = /* @__PURE__ */ new Map();
|
|
2085
|
-
/** Rejections of the underlying `fetch` itself: the node could not be reached or dropped the connection. */
|
|
2086
|
-
this.networkFailures = /* @__PURE__ */ new WeakSet();
|
|
2087
2467
|
// ---------------------------------------------------------------- package origins
|
|
2088
2468
|
/**
|
|
2089
2469
|
* The web origins `{package}`'s managers registered so a frontend they host
|
|
@@ -2109,20 +2489,7 @@ var CalimeroClient = class _CalimeroClient {
|
|
|
2109
2489
|
),
|
|
2110
2490
|
remove: (pkg, origin, passkey) => this.confirmed("DELETE", `package-origins/${seg(pkg)}`, { origin }, passkey)
|
|
2111
2491
|
};
|
|
2112
|
-
|
|
2113
|
-
this.nodeUrls = [...new Set([options.baseUrl, ...options.nodes ?? []].map(trim))];
|
|
2114
|
-
this.policy = options.policy;
|
|
2115
|
-
this.retry = { ...DEFAULT_RETRY, ...options.retry };
|
|
2116
|
-
const given = options.fetch ?? ((input, init) => fetch(input, init));
|
|
2117
|
-
const raw = async (input, init) => {
|
|
2118
|
-
try {
|
|
2119
|
-
return await given(input, init);
|
|
2120
|
-
} catch (error) {
|
|
2121
|
-
if (error instanceof TypeError) this.networkFailures.add(error);
|
|
2122
|
-
throw error;
|
|
2123
|
-
}
|
|
2124
|
-
};
|
|
2125
|
-
this.raw = raw;
|
|
2492
|
+
this.transport = options instanceof NodeTransport ? options : new NodeTransport(options);
|
|
2126
2493
|
}
|
|
2127
2494
|
/**
|
|
2128
2495
|
* A client for the Calimero Cloud cluster named `cluster`: its node list read
|
|
@@ -2135,219 +2502,31 @@ var CalimeroClient = class _CalimeroClient {
|
|
|
2135
2502
|
* first request once the directory's `refreshAfterSeconds` has passed.
|
|
2136
2503
|
*/
|
|
2137
2504
|
static async connect(options) {
|
|
2138
|
-
const
|
|
2139
|
-
|
|
2140
|
-
const fetcher = options.fetch ?? ((input, init) => fetch(input, init));
|
|
2141
|
-
const listing = await readDirectory(directory, options.cluster, fetcher);
|
|
2142
|
-
const [baseUrl, ...nodes] = orderNodes(listing.nodes, options.zone, random);
|
|
2143
|
-
const client = new _CalimeroClient({ baseUrl, nodes, policy: options.policy, fetch: options.fetch, retry: options.retry });
|
|
2144
|
-
client.source = {
|
|
2145
|
-
directory,
|
|
2146
|
-
cluster: options.cluster,
|
|
2147
|
-
zone: options.zone,
|
|
2148
|
-
random,
|
|
2149
|
-
due: Date.now() + listing.refreshAfterSeconds * 1e3
|
|
2150
|
-
};
|
|
2151
|
-
return client;
|
|
2505
|
+
const transport = await directoryTransport({ ...options, directory: options.directory ?? DEFAULT_DIRECTORY });
|
|
2506
|
+
return new _CalimeroClient(transport);
|
|
2152
2507
|
}
|
|
2153
2508
|
/** The node requests go to now: `baseUrl`, until a `421 WRONG_NODE` or a failover moved the client on. */
|
|
2154
2509
|
get nodeUrl() {
|
|
2155
|
-
return this.
|
|
2510
|
+
return this.transport.nodeUrl;
|
|
2156
2511
|
}
|
|
2157
2512
|
/** Every node this client may use, in the order it moves through them. */
|
|
2158
2513
|
get nodes() {
|
|
2159
|
-
return
|
|
2160
|
-
}
|
|
2161
|
-
/** The sealed channel to `url`, attested under the client's policy before its first request. */
|
|
2162
|
-
channel(url2) {
|
|
2163
|
-
let sealed = this.channels.get(url2);
|
|
2164
|
-
if (!sealed) {
|
|
2165
|
-
sealed = createSealedFetch({
|
|
2166
|
-
baseUrl: url2,
|
|
2167
|
-
transportPublicKey: () => fetchAttestedKey(url2, this.policy, this.raw),
|
|
2168
|
-
fetch: this.raw
|
|
2169
|
-
});
|
|
2170
|
-
this.channels.set(url2, sealed);
|
|
2171
|
-
}
|
|
2172
|
-
return sealed;
|
|
2173
|
-
}
|
|
2174
|
-
/**
|
|
2175
|
-
* Move on from node `from` (the one that answered `421 WRONG_NODE`) to the
|
|
2176
|
-
* next one. False when there is no other. A request that saw the same node
|
|
2177
|
-
* refuse after another request moved on already does not move again.
|
|
2178
|
-
*/
|
|
2179
|
-
moveOn(from) {
|
|
2180
|
-
if (this.nodeUrls.length < 2) return false;
|
|
2181
|
-
if (this.nodeUrl === from) this.at = (this.at + 1) % this.nodeUrls.length;
|
|
2182
|
-
return true;
|
|
2183
|
-
}
|
|
2184
|
-
/**
|
|
2185
|
-
* Fail over from node `from`, where a request's retries ran out, to the next
|
|
2186
|
-
* node it has not `tried`. False when it has tried them all. A request whose
|
|
2187
|
-
* node another request moved away from already goes to that node, if untried.
|
|
2188
|
-
*/
|
|
2189
|
-
failOver(from, tried) {
|
|
2190
|
-
if (this.nodeUrl !== from && !tried.has(this.nodeUrl)) return true;
|
|
2191
|
-
const count = this.nodeUrls.length;
|
|
2192
|
-
for (let step = 1; step < count; step++) {
|
|
2193
|
-
const next = (this.at + step) % count;
|
|
2194
|
-
if (!tried.has(this.nodeUrls[next])) {
|
|
2195
|
-
this.at = next;
|
|
2196
|
-
this.reread();
|
|
2197
|
-
return true;
|
|
2198
|
-
}
|
|
2199
|
-
}
|
|
2200
|
-
return false;
|
|
2201
|
-
}
|
|
2202
|
-
/**
|
|
2203
|
-
* Read the node list again from the directory, in the background, for a
|
|
2204
|
-
* client made by {@link connect}: the node in use stays first, then the
|
|
2205
|
-
* directory's order; a node no longer listed is dropped. A failed read is
|
|
2206
|
-
* ignored. One read at a time.
|
|
2207
|
-
*/
|
|
2208
|
-
reread() {
|
|
2209
|
-
const source = this.source;
|
|
2210
|
-
if (!source || source.reading) return;
|
|
2211
|
-
source.reading = readDirectory(source.directory, source.cluster, this.raw).then((listing) => {
|
|
2212
|
-
const current = this.nodeUrl;
|
|
2213
|
-
const listed = orderNodes(listing.nodes, source.zone, source.random);
|
|
2214
|
-
this.nodeUrls = [current, ...listed.filter((url2) => url2 !== current)];
|
|
2215
|
-
this.at = 0;
|
|
2216
|
-
source.due = Date.now() + listing.refreshAfterSeconds * 1e3;
|
|
2217
|
-
}).catch(() => void 0).finally(() => {
|
|
2218
|
-
source.reading = void 0;
|
|
2219
|
-
});
|
|
2514
|
+
return this.transport.nodes;
|
|
2220
2515
|
}
|
|
2221
2516
|
/** Authenticate every request with an API key. */
|
|
2222
2517
|
useApiKey(key) {
|
|
2223
|
-
this.
|
|
2224
|
-
this.current = void 0;
|
|
2518
|
+
this.transport.useApiKey(key);
|
|
2225
2519
|
}
|
|
2226
2520
|
useSession(session) {
|
|
2227
|
-
this.
|
|
2228
|
-
this.current = session;
|
|
2521
|
+
this.transport.useSession(session);
|
|
2229
2522
|
}
|
|
2230
2523
|
get session() {
|
|
2231
|
-
return this.
|
|
2232
|
-
}
|
|
2233
|
-
/**
|
|
2234
|
-
* Send one request to the node in use, with the credential held now, and
|
|
2235
|
-
* answer the response, whatever its status. {@link send} judges it.
|
|
2236
|
-
*/
|
|
2237
|
-
async request(method, path, body, raw, contentType = "application/wasm", signal) {
|
|
2238
|
-
const headers = {};
|
|
2239
|
-
if (this.auth) headers.authorization = `Bearer ${this.auth}`;
|
|
2240
|
-
let payload;
|
|
2241
|
-
if (raw) {
|
|
2242
|
-
headers["content-type"] = contentType;
|
|
2243
|
-
payload = raw;
|
|
2244
|
-
} else if (body !== void 0) {
|
|
2245
|
-
headers["content-type"] = "application/json";
|
|
2246
|
-
payload = JSON.stringify(body);
|
|
2247
|
-
}
|
|
2248
|
-
if (this.source && Date.now() >= this.source.due) this.reread();
|
|
2249
|
-
const url2 = this.nodeUrl;
|
|
2250
|
-
try {
|
|
2251
|
-
return await this.channel(url2)(`${url2}/${path}`, { method, headers, body: payload, signal });
|
|
2252
|
-
} catch (error) {
|
|
2253
|
-
throw sealedError(error);
|
|
2254
|
-
}
|
|
2255
|
-
}
|
|
2256
|
-
/**
|
|
2257
|
-
* {@link request}, answering what a lost issuing node or a node on the
|
|
2258
|
-
* wrong release does to a session: a successful response, or the refusal as a
|
|
2259
|
-
* typed error ({@link errorFrom}).
|
|
2260
|
-
*
|
|
2261
|
-
* - `401 UNAUTHENTICATED` to a request that carried a session: the node that
|
|
2262
|
-
* signed the session may be gone, replaced, or out of reach of the node
|
|
2263
|
-
* asked, which any node of the cluster answers with a refresh. The client
|
|
2264
|
-
* refreshes once, shared by every request that needs it at the same time
|
|
2265
|
-
* ({@link refresh}), and repeats the request once. A refresh that is
|
|
2266
|
-
* refused surfaces as {@link LoginRequired}.
|
|
2267
|
-
* - `421 WRONG_NODE`: this node's release may not serve the account. The
|
|
2268
|
-
* client moves to the next node it knows and repeats the request once; with
|
|
2269
|
-
* none, the {@link WrongNode} reaches the caller.
|
|
2270
|
-
*
|
|
2271
|
-
* Repeating is safe even for a request that is not idempotent: the node
|
|
2272
|
-
* answers `401` and `421` when it judges the credential, before it reads what
|
|
2273
|
-
* the request asks, so the first attempt ran nothing. The exceptions are the
|
|
2274
|
-
* ceremonies that mint a session ({@link ceremony}), never repeated here.
|
|
2275
|
-
*/
|
|
2276
|
-
async send(method, path, body, raw, contentType, signal) {
|
|
2277
|
-
let refreshed = false;
|
|
2278
|
-
let moved = false;
|
|
2279
|
-
for (; ; ) {
|
|
2280
|
-
const [token, at] = [this.auth, this.nodeUrl];
|
|
2281
|
-
const response = await this.request(method, path, body, raw, contentType, signal);
|
|
2282
|
-
if (response.ok) return response;
|
|
2283
|
-
const error = await refusal(response);
|
|
2284
|
-
if (error instanceof WrongNode && !moved) {
|
|
2285
|
-
moved = true;
|
|
2286
|
-
if (this.moveOn(at) && !ceremony(path)) continue;
|
|
2287
|
-
} else if (error instanceof LoginRequired && !refreshed && this.mayRefresh(token, path)) {
|
|
2288
|
-
refreshed = true;
|
|
2289
|
-
await this.renew(token);
|
|
2290
|
-
continue;
|
|
2291
|
-
}
|
|
2292
|
-
throw error;
|
|
2293
|
-
}
|
|
2524
|
+
return this.transport.session;
|
|
2294
2525
|
}
|
|
2295
|
-
/**
|
|
2296
|
-
|
|
2297
|
-
|
|
2298
|
-
|
|
2299
|
-
/**
|
|
2300
|
-
* A fresh session in place of the one `token` belonged to: by the refresh
|
|
2301
|
-
* another request already made, or by one this request starts.
|
|
2302
|
-
*/
|
|
2303
|
-
async renew(token) {
|
|
2304
|
-
if (this.auth !== token) return;
|
|
2305
|
-
await this.refresh();
|
|
2306
|
-
}
|
|
2307
|
-
async json(method, path, body, raw, contentType) {
|
|
2308
|
-
const response = await this.send(method, path, body, raw, contentType);
|
|
2309
|
-
const text = await response.text();
|
|
2310
|
-
return text ? JSON.parse(text) : {};
|
|
2311
|
-
}
|
|
2312
|
-
/**
|
|
2313
|
-
* {@link json} for a call or a view (D70): while the node answers 503 or
|
|
2314
|
-
* cannot be reached, the same request, with the same idempotency key, is sent
|
|
2315
|
-
* again after {@link retryDelayMs} (or the pause the node asked for, if
|
|
2316
|
-
* longer), at most `retries` times. Every other answer is final.
|
|
2317
|
-
*
|
|
2318
|
-
* When a node's retries run out, the request fails over to the next node the
|
|
2319
|
-
* client knows and its retries start again there, with the same key: the
|
|
2320
|
-
* key is kept in the app's replicated log, so the cluster answers it once
|
|
2321
|
-
* whichever node it reaches. Each node is tried once per request. The last
|
|
2322
|
-
* failure surfaces as {@link UnavailableError}: the node's 503, or reason
|
|
2323
|
-
* `network` for a connection that failed, whose `committed` is `'unknown'`.
|
|
2324
|
-
*
|
|
2325
|
-
* `once` sends the request exactly once, to the node in use (the confirmed
|
|
2326
|
-
* attempt of {@link callConfirmed}, whose challenge is single-use).
|
|
2327
|
-
*/
|
|
2328
|
-
async retried(method, path, body, once = false) {
|
|
2329
|
-
const retries = once ? 0 : this.retry.retries;
|
|
2330
|
-
const tried = /* @__PURE__ */ new Set();
|
|
2331
|
-
for (; ; ) {
|
|
2332
|
-
let unavailable;
|
|
2333
|
-
let node = this.nodeUrl;
|
|
2334
|
-
for (let attempt = 0; ; attempt++) {
|
|
2335
|
-
node = this.nodeUrl;
|
|
2336
|
-
tried.add(node);
|
|
2337
|
-
try {
|
|
2338
|
-
return await this.json(method, path, body);
|
|
2339
|
-
} catch (error) {
|
|
2340
|
-
if (error instanceof UnavailableError) unavailable = error;
|
|
2341
|
-
else if (error instanceof TypeError && this.networkFailures.has(error)) {
|
|
2342
|
-
unavailable = new UnavailableError("NETWORK", `the node could not be reached: ${error.message}`, {}, void 0, error);
|
|
2343
|
-
} else throw error;
|
|
2344
|
-
}
|
|
2345
|
-
if (attempt >= retries) break;
|
|
2346
|
-
const backoff = retryDelayMs(attempt, this.retry);
|
|
2347
|
-
await new Promise((resolve) => setTimeout(resolve, Math.max(backoff, (unavailable.retryAfter ?? 0) * 1e3)));
|
|
2348
|
-
}
|
|
2349
|
-
if (once || !this.failOver(node, tried)) throw unavailable;
|
|
2350
|
-
}
|
|
2526
|
+
/** A JSON request, or a raw one when `raw` is given (as `contentType`, the transport's default when absent). */
|
|
2527
|
+
json(method, path, body, raw, contentType) {
|
|
2528
|
+
const options = raw ? { bytes: raw, ...contentType === void 0 ? {} : { contentType } } : { body };
|
|
2529
|
+
return this.transport.json(method, path, options);
|
|
2351
2530
|
}
|
|
2352
2531
|
post(path, body = {}) {
|
|
2353
2532
|
return this.json("POST", path, body);
|
|
@@ -2391,7 +2570,6 @@ var CalimeroClient = class _CalimeroClient {
|
|
|
2391
2570
|
"auth/passkey/register/finish",
|
|
2392
2571
|
{ challengeId: begin.challengeId, registration, ...invite },
|
|
2393
2572
|
passkey,
|
|
2394
|
-
void 0,
|
|
2395
2573
|
"preferred",
|
|
2396
2574
|
signal
|
|
2397
2575
|
);
|
|
@@ -2432,7 +2610,7 @@ var CalimeroClient = class _CalimeroClient {
|
|
|
2432
2610
|
const page = globalThis.location?.origin;
|
|
2433
2611
|
if (!page || page === "null") return void 0;
|
|
2434
2612
|
const nodes = new Set(
|
|
2435
|
-
this.
|
|
2613
|
+
this.transport.nodes.map((url2) => {
|
|
2436
2614
|
try {
|
|
2437
2615
|
return new URL(url2).origin;
|
|
2438
2616
|
} catch {
|
|
@@ -2460,29 +2638,7 @@ var CalimeroClient = class _CalimeroClient {
|
|
|
2460
2638
|
* same token again (which would revoke the session).
|
|
2461
2639
|
*/
|
|
2462
2640
|
refresh() {
|
|
2463
|
-
|
|
2464
|
-
const pending = this.exchangeRefresh();
|
|
2465
|
-
this.refreshing = pending;
|
|
2466
|
-
const clear = () => {
|
|
2467
|
-
if (this.refreshing === pending) this.refreshing = void 0;
|
|
2468
|
-
};
|
|
2469
|
-
pending.then(clear, clear);
|
|
2470
|
-
}
|
|
2471
|
-
return this.refreshing;
|
|
2472
|
-
}
|
|
2473
|
-
async exchangeRefresh() {
|
|
2474
|
-
const current = this.current;
|
|
2475
|
-
if (!current) throw new Error("no session to refresh");
|
|
2476
|
-
let session;
|
|
2477
|
-
for (let tried = 1; session === void 0; tried++) {
|
|
2478
|
-
try {
|
|
2479
|
-
session = await this.post("auth/refresh", { refreshToken: current.refreshToken });
|
|
2480
|
-
} catch (error) {
|
|
2481
|
-
if (!(error instanceof WrongNode) || tried >= this.nodeUrls.length) throw error;
|
|
2482
|
-
}
|
|
2483
|
-
}
|
|
2484
|
-
if (this.current === current) this.useSession(session);
|
|
2485
|
-
return session;
|
|
2641
|
+
return this.transport.refresh();
|
|
2486
2642
|
}
|
|
2487
2643
|
/**
|
|
2488
2644
|
* End this session. The client is signed out whether or not the node
|
|
@@ -2542,8 +2698,7 @@ var CalimeroClient = class _CalimeroClient {
|
|
|
2542
2698
|
try {
|
|
2543
2699
|
await this.post(path);
|
|
2544
2700
|
} finally {
|
|
2545
|
-
this.
|
|
2546
|
-
this.current = void 0;
|
|
2701
|
+
this.transport.signOut();
|
|
2547
2702
|
}
|
|
2548
2703
|
}
|
|
2549
2704
|
/** Who the credential is: the account, how it signed in, and the package (`app`) and `origin` a session is bound to. */
|
|
@@ -2649,8 +2804,7 @@ var CalimeroClient = class _CalimeroClient {
|
|
|
2649
2804
|
*/
|
|
2650
2805
|
async attestation() {
|
|
2651
2806
|
const nonce2 = toHex(crypto.getRandomValues(new Uint8Array(32)));
|
|
2652
|
-
const response = await this.
|
|
2653
|
-
if (!response.ok) throw await refusal(response);
|
|
2807
|
+
const response = await this.transport.unsealed("attestation", { query: { nonce: nonce2 } });
|
|
2654
2808
|
return await response.json();
|
|
2655
2809
|
}
|
|
2656
2810
|
/** The account's API keys (never the keys themselves). */
|
|
@@ -2711,8 +2865,9 @@ var CalimeroClient = class _CalimeroClient {
|
|
|
2711
2865
|
* app; `application/octet-stream` otherwise.
|
|
2712
2866
|
*/
|
|
2713
2867
|
async blobContent(app, id, options = {}) {
|
|
2714
|
-
const
|
|
2715
|
-
|
|
2868
|
+
const response = await this.transport.request("GET", `apps/${seg(app)}/blobs/${seg(id)}`, {
|
|
2869
|
+
query: { grant: options.grant }
|
|
2870
|
+
});
|
|
2716
2871
|
return {
|
|
2717
2872
|
data: new Uint8Array(await response.arrayBuffer()),
|
|
2718
2873
|
contentType: response.headers.get("content-type") ?? "application/octet-stream"
|
|
@@ -2823,8 +2978,10 @@ var CalimeroClient = class _CalimeroClient {
|
|
|
2823
2978
|
}
|
|
2824
2979
|
/**
|
|
2825
2980
|
* Move an app to another release of its package (`{ version }`), another
|
|
2826
|
-
* package, or a bundle hash
|
|
2827
|
-
*
|
|
2981
|
+
* package, or a bundle hash. An upgrade is code only: the app moves to any
|
|
2982
|
+
* newer release in one step. Answers the upgrade's entry; one the app's
|
|
2983
|
+
* group refuses rejects with code `UPGRADE_FAILED` (422), and one a
|
|
2984
|
+
* replica's node is too old to run with {@link RuntimeTooOld} (409).
|
|
2828
2985
|
* Where owners hold app upgrades, the node asks for the approval of
|
|
2829
2986
|
* whoever the package's manifest names (`412 CONFIRM_REQUIRED`), which
|
|
2830
2987
|
* `passkey` gives. Refused (`403`) to a session opened on an app's
|
|
@@ -2855,23 +3012,12 @@ var CalimeroClient = class _CalimeroClient {
|
|
|
2855
3012
|
deleteConfirmed(path, passkey, body = {}) {
|
|
2856
3013
|
return this.confirmed("DELETE", path, body, passkey);
|
|
2857
3014
|
}
|
|
2858
|
-
|
|
2859
|
-
|
|
2860
|
-
|
|
2861
|
-
|
|
2862
|
-
|
|
2863
|
-
|
|
2864
|
-
let assertion;
|
|
2865
|
-
try {
|
|
2866
|
-
assertion = await passkey.get(fromB64url(d.challenge), d.rpId, d.allowCredentials, {
|
|
2867
|
-
userVerification: userVerificationOf(d.userVerification, userVerification),
|
|
2868
|
-
...signal ? { signal } : {}
|
|
2869
|
-
});
|
|
2870
|
-
} catch (declined) {
|
|
2871
|
-
throw promptFailure(declined);
|
|
2872
|
-
}
|
|
2873
|
-
return send({ ...body, confirm: { challengeId: d.challengeId, assertion } });
|
|
2874
|
-
}
|
|
3015
|
+
/**
|
|
3016
|
+
* `body` to `path`, answering a `412 CONFIRM_REQUIRED` with `passkey` when one
|
|
3017
|
+
* is given; `signal` aborts only the passkey prompt.
|
|
3018
|
+
*/
|
|
3019
|
+
confirmed(method, path, body, passkey, userVerification, signal) {
|
|
3020
|
+
return this.transport.json(method, path, { body, passkey, userVerification, promptSignal: signal });
|
|
2875
3021
|
}
|
|
2876
3022
|
/**
|
|
2877
3023
|
* Create an app instance from a bundle hash, or from a package release
|
|
@@ -2895,7 +3041,7 @@ var CalimeroClient = class _CalimeroClient {
|
|
|
2895
3041
|
*/
|
|
2896
3042
|
call(app, method, args = {}, idempotencyKey) {
|
|
2897
3043
|
const key = idempotencyKey ?? newIdempotencyKey();
|
|
2898
|
-
return this.
|
|
3044
|
+
return this.transport.json("POST", `apps/${seg(app)}/intents`, { body: { method, args, idempotencyKey: key }, retry: true });
|
|
2899
3045
|
}
|
|
2900
3046
|
/**
|
|
2901
3047
|
* Call a method that needs the account holder's approval: the node returns a
|
|
@@ -2905,32 +3051,23 @@ var CalimeroClient = class _CalimeroClient {
|
|
|
2905
3051
|
async callConfirmed(app, method, args, passkey, idempotencyKey) {
|
|
2906
3052
|
const path = `apps/${seg(app)}/intents`;
|
|
2907
3053
|
const key = idempotencyKey ?? newIdempotencyKey();
|
|
2908
|
-
return this.
|
|
2909
|
-
"POST",
|
|
2910
|
-
path,
|
|
2911
|
-
{ method, args, idempotencyKey: key },
|
|
2912
|
-
passkey,
|
|
2913
|
-
(body) => this.retried("POST", path, body, body.confirm !== void 0)
|
|
2914
|
-
);
|
|
3054
|
+
return this.transport.json("POST", path, { body: { method, args, idempotencyKey: key }, passkey, retry: true });
|
|
2915
3055
|
}
|
|
2916
3056
|
/** Run a read-only method: strong by default, or stale from any replica. */
|
|
2917
3057
|
view(app, method, args = {}, options = {}) {
|
|
2918
|
-
return this.
|
|
2919
|
-
|
|
2920
|
-
|
|
2921
|
-
|
|
2922
|
-
|
|
3058
|
+
return this.transport.json("POST", `apps/${seg(app)}/views`, {
|
|
3059
|
+
body: {
|
|
3060
|
+
method,
|
|
3061
|
+
args,
|
|
3062
|
+
consistency: options.stale ? "stale" : "strong",
|
|
3063
|
+
minIndex: options.minIndex ?? 0
|
|
3064
|
+
},
|
|
3065
|
+
retry: true
|
|
2923
3066
|
});
|
|
2924
3067
|
}
|
|
2925
3068
|
/** Committed events from index `from`, then live, until `signal` aborts. */
|
|
2926
3069
|
events(app, from = 0, signal) {
|
|
2927
|
-
return this.
|
|
2928
|
-
}
|
|
2929
|
-
/** A server-sent event stream on `path`, sealed like every other answer. */
|
|
2930
|
-
async *stream(path, signal) {
|
|
2931
|
-
const response = await this.send("GET", path, void 0, void 0, void 0, signal);
|
|
2932
|
-
if (!response.body) throw new CalimeroError(response.status, "EVENTS", "the event stream has no body");
|
|
2933
|
-
yield* sseFrames(response.body);
|
|
3070
|
+
return this.transport.events(`apps/${seg(app)}/events`, { query: { from }, signal });
|
|
2934
3071
|
}
|
|
2935
3072
|
// ---------------------------------------------------------------- presence
|
|
2936
3073
|
/**
|
|
@@ -2951,7 +3088,7 @@ var CalimeroClient = class _CalimeroClient {
|
|
|
2951
3088
|
* entries present), then a `presence` event (`data` one entry) per change.
|
|
2952
3089
|
*/
|
|
2953
3090
|
presenceStream(app, signal) {
|
|
2954
|
-
return this.
|
|
3091
|
+
return this.transport.events(`apps/${seg(app)}/presence/stream`, { signal });
|
|
2955
3092
|
}
|
|
2956
3093
|
// ---------------------------------------------------------------- aliases
|
|
2957
3094
|
/** Name an app (its id or context id) for this account. */
|