@myfield/sdk 0.9.2 → 0.9.3
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/CHANGELOG.md +7 -0
- package/README.md +30 -9
- package/dist/index.js +467 -366
- package/package.json +15 -8
- package/types/index.d.ts +395 -137
- package/docs/API.md +0 -298
- package/docs/BUCKET-SPEC.md +0 -173
- package/src/auth/authorization.ts +0 -254
- package/src/auth/flow.ts +0 -93
- package/src/auth/identifiers.ts +0 -46
- package/src/auth/index.ts +0 -17
- package/src/auth/instance.ts +0 -395
- package/src/auth/keys.ts +0 -73
- package/src/auth/proof.ts +0 -26
- package/src/auth/session.ts +0 -16
- package/src/auth/store.ts +0 -90
- package/src/auth/types.ts +0 -47
- package/src/bucket/binary.ts +0 -253
- package/src/bucket/client.ts +0 -426
- package/src/bucket/crypto.ts +0 -58
- package/src/bucket/format.ts +0 -324
- package/src/bucket/index.ts +0 -40
- package/src/bucket/keys.ts +0 -104
- package/src/bucket/store.ts +0 -190
- package/src/bucket/transport.ts +0 -249
- package/src/errors.ts +0 -40
- package/src/facade.ts +0 -698
- package/src/index.ts +0 -29
- package/src/internal/encoding.ts +0 -95
- package/src/remote/bucket.ts +0 -180
- package/src/remote/client.ts +0 -38
- package/src/remote/connection.ts +0 -529
- package/src/remote/feed.ts +0 -80
- package/src/remote/http.ts +0 -78
- package/src/remote/session.ts +0 -31
package/dist/index.js
CHANGED
|
@@ -1111,8 +1111,9 @@ function memoryAdapterOver(map) {
|
|
|
1111
1111
|
async removePrefix(prefix) {
|
|
1112
1112
|
for (const key of map.keys()) if (key.startsWith(prefix)) map.delete(key);
|
|
1113
1113
|
},
|
|
1114
|
-
async insertIfEmpty(prefix, entries) {
|
|
1114
|
+
async insertIfEmpty(prefix, entries, condition) {
|
|
1115
1115
|
if ([...map.keys()].some((key) => key.startsWith(prefix))) return false;
|
|
1116
|
+
if (condition && !condition.matches(map.get(condition.key))) return false;
|
|
1116
1117
|
const cloned = entries.map(({ key, value }) => ({ key, value: structuredClone(value) }));
|
|
1117
1118
|
for (const { key, value } of cloned) map.set(key, value);
|
|
1118
1119
|
return true;
|
|
@@ -1143,12 +1144,11 @@ function createIndexedDbStorageAdapter(options) {
|
|
|
1143
1144
|
tx.oncomplete = () => resolve();
|
|
1144
1145
|
tx.onabort = tx.onerror = () => reject(tx.error || new Error("Atomic removal failed"));
|
|
1145
1146
|
})),
|
|
1146
|
-
insertIfEmpty: (prefix, entries) => withIdb(dbName, storeName, (db) => new Promise((resolve, reject) => {
|
|
1147
|
+
insertIfEmpty: (prefix, entries, condition) => withIdb(dbName, storeName, (db) => new Promise((resolve, reject) => {
|
|
1147
1148
|
const tx = db.transaction(storeName, "readwrite"), store = tx.objectStore(storeName);
|
|
1148
1149
|
let inserted = false;
|
|
1149
1150
|
const count = store.count(IDBKeyRange.bound(prefix, `${prefix}\uFFFF`));
|
|
1150
|
-
|
|
1151
|
-
if (count.result) return;
|
|
1151
|
+
const insert = () => {
|
|
1152
1152
|
try {
|
|
1153
1153
|
for (const { key, value } of entries) store.put(value, key);
|
|
1154
1154
|
inserted = true;
|
|
@@ -1157,6 +1157,17 @@ function createIndexedDbStorageAdapter(options) {
|
|
|
1157
1157
|
reject(error);
|
|
1158
1158
|
}
|
|
1159
1159
|
};
|
|
1160
|
+
count.onsuccess = () => {
|
|
1161
|
+
if (count.result) return;
|
|
1162
|
+
if (!condition) {
|
|
1163
|
+
insert();
|
|
1164
|
+
return;
|
|
1165
|
+
}
|
|
1166
|
+
const current = store.get(condition.key);
|
|
1167
|
+
current.onsuccess = () => {
|
|
1168
|
+
if (condition.matches(current.result)) insert();
|
|
1169
|
+
};
|
|
1170
|
+
};
|
|
1160
1171
|
tx.oncomplete = () => resolve(inserted);
|
|
1161
1172
|
tx.onabort = tx.onerror = () => reject(tx.error || new Error("Atomic write failed"));
|
|
1162
1173
|
})),
|
|
@@ -1305,6 +1316,345 @@ function resolveAppId(value) {
|
|
|
1305
1316
|
return appId;
|
|
1306
1317
|
}
|
|
1307
1318
|
|
|
1319
|
+
// src/remote/http.ts
|
|
1320
|
+
function isRecord2(value) {
|
|
1321
|
+
return value !== null && typeof value === "object" && !Array.isArray(value);
|
|
1322
|
+
}
|
|
1323
|
+
function requireString(value, name) {
|
|
1324
|
+
if (typeof value !== "string" || !value.trim()) {
|
|
1325
|
+
throw new ClientError("INVALID_INPUT", `${name} must be a non-empty string`);
|
|
1326
|
+
}
|
|
1327
|
+
}
|
|
1328
|
+
function invalidResponse(response, message = "Invalid protocol response", cause) {
|
|
1329
|
+
return new ClientError("INVALID_RESPONSE", message, {
|
|
1330
|
+
status: response.status,
|
|
1331
|
+
requestId: response.headers.get("x-request-id") ?? void 0,
|
|
1332
|
+
cause
|
|
1333
|
+
});
|
|
1334
|
+
}
|
|
1335
|
+
function networkError(cause, signal) {
|
|
1336
|
+
signal?.throwIfAborted();
|
|
1337
|
+
throw new ClientError("NETWORK_ERROR", "Network request failed", { retryable: true, cause });
|
|
1338
|
+
}
|
|
1339
|
+
async function readJson(response, signal) {
|
|
1340
|
+
let value;
|
|
1341
|
+
try {
|
|
1342
|
+
value = await response.json();
|
|
1343
|
+
} catch (cause) {
|
|
1344
|
+
signal?.throwIfAborted();
|
|
1345
|
+
if (!(cause instanceof SyntaxError)) return networkError(cause, signal);
|
|
1346
|
+
throw invalidResponse(response, "Invalid JSON response", cause);
|
|
1347
|
+
}
|
|
1348
|
+
signal?.throwIfAborted();
|
|
1349
|
+
if (!isRecord2(value)) throw invalidResponse(response);
|
|
1350
|
+
return value;
|
|
1351
|
+
}
|
|
1352
|
+
function createHttpRequest(options) {
|
|
1353
|
+
requireString(options.apiBase, "apiBase");
|
|
1354
|
+
let base;
|
|
1355
|
+
try {
|
|
1356
|
+
base = new URL(options.apiBase);
|
|
1357
|
+
} catch (cause) {
|
|
1358
|
+
throw new ClientError("INVALID_INPUT", "apiBase must be an HTTP(S) origin", { cause });
|
|
1359
|
+
}
|
|
1360
|
+
if (!["http:", "https:"].includes(base.protocol) || base.pathname !== "/" || base.search || base.hash || base.username || base.password) {
|
|
1361
|
+
throw new ClientError("INVALID_INPUT", "apiBase must be an HTTP(S) origin without a path, query, fragment or credentials");
|
|
1362
|
+
}
|
|
1363
|
+
const fetch2 = options.fetch ?? globalThis.fetch.bind(globalThis);
|
|
1364
|
+
if (typeof fetch2 !== "function") throw new ClientError("INVALID_INPUT", "fetch must be a function");
|
|
1365
|
+
return async (path, init) => {
|
|
1366
|
+
init.signal?.throwIfAborted();
|
|
1367
|
+
let response;
|
|
1368
|
+
try {
|
|
1369
|
+
response = await fetch2(new URL(path, base).href, { ...init, credentials: "omit" });
|
|
1370
|
+
} catch (cause) {
|
|
1371
|
+
return networkError(cause, init.signal);
|
|
1372
|
+
}
|
|
1373
|
+
if (response.ok) return response;
|
|
1374
|
+
let body = {};
|
|
1375
|
+
try {
|
|
1376
|
+
const value = await response.json();
|
|
1377
|
+
if (isRecord2(value)) body = value;
|
|
1378
|
+
} catch {
|
|
1379
|
+
init.signal?.throwIfAborted();
|
|
1380
|
+
}
|
|
1381
|
+
const details = isRecord2(body.details) ? body.details : {};
|
|
1382
|
+
const retry = response.headers.get("retry-after");
|
|
1383
|
+
const seconds = retry !== null && /^\d+(?:\.\d+)?$/.test(retry.trim()) ? Number(retry) : NaN;
|
|
1384
|
+
const date = retry === null ? NaN : Date.parse(retry);
|
|
1385
|
+
const retryAfterMs = Number.isFinite(seconds) ? seconds * 1e3 : Number.isFinite(date) ? Math.max(0, date - Date.now()) : void 0;
|
|
1386
|
+
throw new ClientError(
|
|
1387
|
+
typeof body.code === "string" && body.code ? body.code : "HTTP_ERROR",
|
|
1388
|
+
typeof body.message === "string" && body.message ? body.message : typeof body.error === "string" && body.error ? body.error : `HTTP ${response.status}`,
|
|
1389
|
+
{
|
|
1390
|
+
status: response.status,
|
|
1391
|
+
requestId: typeof body.requestId === "string" ? body.requestId : response.headers.get("x-request-id") ?? void 0,
|
|
1392
|
+
retryable: typeof details.retryable === "boolean" ? details.retryable : response.status === 408 || response.status === 429 || response.status >= 500,
|
|
1393
|
+
retryAfterMs,
|
|
1394
|
+
maxBytes: typeof details.maxBytes === "number" ? details.maxBytes : void 0
|
|
1395
|
+
}
|
|
1396
|
+
);
|
|
1397
|
+
};
|
|
1398
|
+
}
|
|
1399
|
+
|
|
1400
|
+
// src/remote/feed.ts
|
|
1401
|
+
function isFeedHint(value) {
|
|
1402
|
+
return isRecord2(value) && typeof value.objectId === "string" && value.objectId.length > 0 && typeof value.versionId === "string" && value.versionId.length > 0;
|
|
1403
|
+
}
|
|
1404
|
+
var MIN_POLL_MS = 6e4;
|
|
1405
|
+
var MAX_POLL_MS = 60 * MIN_POLL_MS;
|
|
1406
|
+
function waitForPoll(delay, signal) {
|
|
1407
|
+
signal.throwIfAborted();
|
|
1408
|
+
if (!delay) return Promise.resolve();
|
|
1409
|
+
return new Promise((resolve, reject) => {
|
|
1410
|
+
const timer = setTimeout(() => {
|
|
1411
|
+
signal.removeEventListener("abort", onAbort);
|
|
1412
|
+
resolve();
|
|
1413
|
+
}, delay);
|
|
1414
|
+
const onAbort = () => {
|
|
1415
|
+
clearTimeout(timer);
|
|
1416
|
+
reject(signal.reason);
|
|
1417
|
+
};
|
|
1418
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
1419
|
+
});
|
|
1420
|
+
}
|
|
1421
|
+
async function watchHttpFeed(bucket, ...sources) {
|
|
1422
|
+
const controller = new AbortController();
|
|
1423
|
+
const { signal } = controller;
|
|
1424
|
+
const listeners = sources.filter((source) => source !== void 0).map((source) => {
|
|
1425
|
+
const abort = () => controller.abort(source.reason);
|
|
1426
|
+
if (source.aborted) abort();
|
|
1427
|
+
else if (!signal.aborted) source.addEventListener("abort", abort, { once: true });
|
|
1428
|
+
return () => source.removeEventListener("abort", abort);
|
|
1429
|
+
});
|
|
1430
|
+
const cleanup = () => listeners.forEach((remove) => remove());
|
|
1431
|
+
signal.addEventListener("abort", cleanup, { once: true });
|
|
1432
|
+
let interval = MIN_POLL_MS;
|
|
1433
|
+
const lengthenInterval = () => {
|
|
1434
|
+
interval = Math.min(interval * 2, MAX_POLL_MS);
|
|
1435
|
+
};
|
|
1436
|
+
const retryDelay = (error) => {
|
|
1437
|
+
signal.throwIfAborted();
|
|
1438
|
+
if (!(error instanceof ClientError) || !error.retryable) throw error;
|
|
1439
|
+
const delay = Math.max(interval, error.retryAfterMs ?? 0);
|
|
1440
|
+
lengthenInterval();
|
|
1441
|
+
return delay;
|
|
1442
|
+
};
|
|
1443
|
+
let cursor;
|
|
1444
|
+
async function readCursor() {
|
|
1445
|
+
for (; ; ) {
|
|
1446
|
+
signal.throwIfAborted();
|
|
1447
|
+
try {
|
|
1448
|
+
return (await bucket.getIndex({ signal })).feedCursor;
|
|
1449
|
+
} catch (error) {
|
|
1450
|
+
await waitForPoll(retryDelay(error), signal);
|
|
1451
|
+
}
|
|
1452
|
+
}
|
|
1453
|
+
}
|
|
1454
|
+
try {
|
|
1455
|
+
cursor = await readCursor();
|
|
1456
|
+
} catch (error) {
|
|
1457
|
+
cleanup();
|
|
1458
|
+
throw error;
|
|
1459
|
+
}
|
|
1460
|
+
let closed = false;
|
|
1461
|
+
async function* hints() {
|
|
1462
|
+
let delay = 0;
|
|
1463
|
+
interval = MIN_POLL_MS;
|
|
1464
|
+
try {
|
|
1465
|
+
for (; ; ) {
|
|
1466
|
+
await waitForPoll(delay, signal);
|
|
1467
|
+
let page;
|
|
1468
|
+
try {
|
|
1469
|
+
page = await bucket.listFeed({ cursor, signal });
|
|
1470
|
+
} catch (error) {
|
|
1471
|
+
delay = retryDelay(error);
|
|
1472
|
+
continue;
|
|
1473
|
+
}
|
|
1474
|
+
signal.throwIfAborted();
|
|
1475
|
+
if ((page.hasMore || page.entries.length) && (!page.cursor || page.cursor === cursor)) {
|
|
1476
|
+
throw new ClientError("INVALID_RESPONSE", "Feed cursor did not advance");
|
|
1477
|
+
}
|
|
1478
|
+
cursor = page.cursor;
|
|
1479
|
+
const latest = new Map(page.entries.map(({ objectId, versionId }) => [objectId, { objectId, versionId }]));
|
|
1480
|
+
if (page.hasMore || latest.size) interval = MIN_POLL_MS;
|
|
1481
|
+
delay = interval;
|
|
1482
|
+
if (!page.hasMore && !latest.size) lengthenInterval();
|
|
1483
|
+
for (const hint of latest.values()) {
|
|
1484
|
+
signal.throwIfAborted();
|
|
1485
|
+
yield hint;
|
|
1486
|
+
}
|
|
1487
|
+
}
|
|
1488
|
+
} catch (error) {
|
|
1489
|
+
if (!closed) throw error;
|
|
1490
|
+
} finally {
|
|
1491
|
+
cleanup();
|
|
1492
|
+
}
|
|
1493
|
+
}
|
|
1494
|
+
const stream = hints();
|
|
1495
|
+
const close = () => {
|
|
1496
|
+
closed = true;
|
|
1497
|
+
controller.abort();
|
|
1498
|
+
cleanup();
|
|
1499
|
+
};
|
|
1500
|
+
const watched = {
|
|
1501
|
+
next: () => stream.next(),
|
|
1502
|
+
return(value) {
|
|
1503
|
+
close();
|
|
1504
|
+
return stream.return(value);
|
|
1505
|
+
},
|
|
1506
|
+
throw(error) {
|
|
1507
|
+
close();
|
|
1508
|
+
return stream.throw(error);
|
|
1509
|
+
},
|
|
1510
|
+
[Symbol.asyncIterator]() {
|
|
1511
|
+
return watched;
|
|
1512
|
+
}
|
|
1513
|
+
};
|
|
1514
|
+
const asyncDispose = Reflect.get(Symbol, "asyncDispose");
|
|
1515
|
+
if (typeof asyncDispose === "symbol") {
|
|
1516
|
+
Object.defineProperty(watched, asyncDispose, { value: async () => {
|
|
1517
|
+
await watched.return(void 0);
|
|
1518
|
+
} });
|
|
1519
|
+
}
|
|
1520
|
+
return watched;
|
|
1521
|
+
}
|
|
1522
|
+
|
|
1523
|
+
// src/auth/authorization.ts
|
|
1524
|
+
var AUTH_CALLBACK_FRAGMENT_PARAM = "mf_auth_result";
|
|
1525
|
+
function buildAuthRequestFragment(request) {
|
|
1526
|
+
if (!request.requestId || !request.state) throw new Error("auth request state required");
|
|
1527
|
+
if (!isValidInstanceId(request.instanceId)) throw new Error("invalid instanceId");
|
|
1528
|
+
if (!isPublicP256EcJwk(request.instanceSigningPublicJwk)) throw new Error("instanceSigningPublicJwk required");
|
|
1529
|
+
if (!isPublicP256EcJwk(request.instanceWrappingPublicJwk)) throw new Error("instanceWrappingPublicJwk required");
|
|
1530
|
+
const redirect = new URL(request.redirectUri);
|
|
1531
|
+
const origin = new URL(request.origin);
|
|
1532
|
+
if (redirect.origin !== origin.origin) throw new Error("redirectUri origin mismatch");
|
|
1533
|
+
const wire = {
|
|
1534
|
+
response_type: "code",
|
|
1535
|
+
client_id: request.clientId,
|
|
1536
|
+
redirect_uri: request.redirectUri,
|
|
1537
|
+
state: request.state,
|
|
1538
|
+
scope: request.capabilities.join(" "),
|
|
1539
|
+
resource_id: request.resourceId,
|
|
1540
|
+
mf_v: 1,
|
|
1541
|
+
mf_auth_mode: "v1",
|
|
1542
|
+
mf_request_id: request.requestId,
|
|
1543
|
+
mf_instance_id: request.instanceId,
|
|
1544
|
+
mf_instance_signing_jwk: request.instanceSigningPublicJwk,
|
|
1545
|
+
mf_instance_wrapping_jwk: request.instanceWrappingPublicJwk,
|
|
1546
|
+
mf_issued_at: request.createdAt
|
|
1547
|
+
};
|
|
1548
|
+
return `#authRequest=${bytesToB64url(utf8Encode(stableStringify(wire)))}`;
|
|
1549
|
+
}
|
|
1550
|
+
function parseEncryptedAuthAuthorizationResultFragment(fragmentOrUrl) {
|
|
1551
|
+
const input = String(fragmentOrUrl || "");
|
|
1552
|
+
const rawFragment = input.includes("#") ? input.slice(input.indexOf("#") + 1) : input.replace(/^#/, "");
|
|
1553
|
+
if (!rawFragment) return null;
|
|
1554
|
+
const encoded = new URLSearchParams(rawFragment).get(AUTH_CALLBACK_FRAGMENT_PARAM);
|
|
1555
|
+
if (!encoded) return null;
|
|
1556
|
+
const envelope = JSON.parse(new TextDecoder().decode(b64urlToBytes(encoded)));
|
|
1557
|
+
if (!envelope || envelope.v !== 1 || envelope.typ !== "auth.authorization-result.envelope.v1" || envelope.alg !== "ECDH-HKDF-SHA-256/AES-GCM-256" || typeof envelope.requestId !== "string" || typeof envelope.state !== "string" || !parseBucketResourceId(envelope.resourceId) || !isValidInstanceId(envelope.instanceId || "") || !isPublicP256EcJwk(envelope.ephemeralPublicJwk) || typeof envelope.salt !== "string" || typeof envelope.iv !== "string" || typeof envelope.aad !== "string" || typeof envelope.ciphertext !== "string") {
|
|
1558
|
+
throw new Error("auth callback result fragment invalid");
|
|
1559
|
+
}
|
|
1560
|
+
return envelope;
|
|
1561
|
+
}
|
|
1562
|
+
async function decryptEncryptedAuthAuthorizationResult(input) {
|
|
1563
|
+
const { envelope } = input;
|
|
1564
|
+
if (input.expectedRequestId && envelope.requestId !== input.expectedRequestId || input.expectedState && envelope.state !== input.expectedState || input.expectedResourceId && envelope.resourceId !== input.expectedResourceId || input.expectedInstanceId && envelope.instanceId !== input.expectedInstanceId) {
|
|
1565
|
+
throw new Error("auth callback result mismatch");
|
|
1566
|
+
}
|
|
1567
|
+
const ephemeralPublic = await crypto.subtle.importKey("jwk", envelope.ephemeralPublicJwk, { name: "ECDH", namedCurve: "P-256" }, false, []);
|
|
1568
|
+
const sharedBits = await crypto.subtle.deriveBits({ name: "ECDH", public: ephemeralPublic }, input.instanceWrappingPrivateKey, 256);
|
|
1569
|
+
const material = await crypto.subtle.importKey("raw", sharedBits, "HKDF", false, ["deriveKey"]);
|
|
1570
|
+
const wrappingKey = await crypto.subtle.deriveKey(
|
|
1571
|
+
{ name: "HKDF", hash: "SHA-256", salt: b64urlToBytes(envelope.salt), info: utf8Encode(envelope.aad) },
|
|
1572
|
+
material,
|
|
1573
|
+
{ name: "AES-GCM", length: 256 },
|
|
1574
|
+
false,
|
|
1575
|
+
["decrypt"]
|
|
1576
|
+
);
|
|
1577
|
+
const plaintext = await crypto.subtle.decrypt(
|
|
1578
|
+
{ name: "AES-GCM", iv: b64urlToBytes(envelope.iv), additionalData: utf8Encode(envelope.aad) },
|
|
1579
|
+
wrappingKey,
|
|
1580
|
+
b64urlToBytes(envelope.ciphertext)
|
|
1581
|
+
);
|
|
1582
|
+
const result = normalizeAuthAuthorizationResult(JSON.parse(new TextDecoder().decode(plaintext)), envelope.requestId);
|
|
1583
|
+
if (!result || result.state !== envelope.state || result.resourceId !== envelope.resourceId || result.instanceId !== envelope.instanceId || input.expectedState && result.state !== input.expectedState || input.expectedResourceId && result.resourceId !== input.expectedResourceId || input.expectedInstanceId && result.instanceId !== input.expectedInstanceId) {
|
|
1584
|
+
throw new Error("auth callback result mismatch");
|
|
1585
|
+
}
|
|
1586
|
+
return result;
|
|
1587
|
+
}
|
|
1588
|
+
function normalizeAuthAuthorizationResult(value, expectedRequestId) {
|
|
1589
|
+
const row = value;
|
|
1590
|
+
if (!row || row.v !== 1 || row.result !== "approved" || typeof row.requestId !== "string" || expectedRequestId && row.requestId !== expectedRequestId || typeof row.state !== "string" || !isValidMfid(row.mfid || "") || !parseBucketResourceId(row.resourceId) || !isValidInstanceId(row.instanceId || "") || typeof row.createdAt !== "string") {
|
|
1591
|
+
return null;
|
|
1592
|
+
}
|
|
1593
|
+
if (row.expiresAt !== void 0) {
|
|
1594
|
+
const expiresAt = Date.parse(String(row.expiresAt));
|
|
1595
|
+
if (!Number.isFinite(expiresAt) || expiresAt <= Date.now()) return null;
|
|
1596
|
+
}
|
|
1597
|
+
const resource = parseBucketResourceId(row.resourceId);
|
|
1598
|
+
if (!resource) return null;
|
|
1599
|
+
const bucketAccessGrant = normalizeBucketGrant(row.bucketAccessGrant);
|
|
1600
|
+
if (!bucketAccessGrant) return null;
|
|
1601
|
+
if (bucketAccessGrant.mfid !== row.mfid || !parseBucketResourceId(bucketAccessGrant.resourceId) || bucketAccessGrant.instanceId !== row.instanceId) {
|
|
1602
|
+
return null;
|
|
1603
|
+
}
|
|
1604
|
+
return {
|
|
1605
|
+
v: 1,
|
|
1606
|
+
requestId: row.requestId,
|
|
1607
|
+
state: row.state,
|
|
1608
|
+
result: "approved",
|
|
1609
|
+
mfid: row.mfid,
|
|
1610
|
+
resourceId: resource.resourceId,
|
|
1611
|
+
instanceId: row.instanceId,
|
|
1612
|
+
createdAt: row.createdAt,
|
|
1613
|
+
...typeof row.resourceApiUrl === "string" && row.resourceApiUrl.trim() ? { resourceApiUrl: row.resourceApiUrl.trim() } : {},
|
|
1614
|
+
bucketAccessGrant,
|
|
1615
|
+
...row.expiresAt ? { expiresAt: row.expiresAt } : {}
|
|
1616
|
+
};
|
|
1617
|
+
}
|
|
1618
|
+
function normalizeBucketGrant(value) {
|
|
1619
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) return null;
|
|
1620
|
+
const row = value;
|
|
1621
|
+
const resource = parseBucketResourceId(row.resourceId);
|
|
1622
|
+
const capabilities = normalizeCapabilities(row.capabilities);
|
|
1623
|
+
if (row.v !== 1 || !/^ar_[a-f0-9]{32}$/.test(String(row.grantRecordId || "")) || !isValidMfid(row.mfid) || !resource || !isValidInstanceId(row.instanceId) || !/^bk_[a-f0-9]{32}$/.test(String(row.keyId || "")) || capabilities.length < 1 || !isValidBucketKeyGrantEnvelope(row.envelope, row.instanceId, row.keyId)) {
|
|
1624
|
+
return null;
|
|
1625
|
+
}
|
|
1626
|
+
return {
|
|
1627
|
+
v: 1,
|
|
1628
|
+
grantRecordId: row.grantRecordId,
|
|
1629
|
+
mfid: row.mfid,
|
|
1630
|
+
resourceId: resource.resourceId,
|
|
1631
|
+
instanceId: row.instanceId,
|
|
1632
|
+
issuedAt: String(row.issuedAt || ""),
|
|
1633
|
+
keyId: row.keyId,
|
|
1634
|
+
capabilities,
|
|
1635
|
+
envelope: row.envelope
|
|
1636
|
+
};
|
|
1637
|
+
}
|
|
1638
|
+
function isValidBucketKeyGrantEnvelope(value, instanceId, keyId) {
|
|
1639
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) return false;
|
|
1640
|
+
const row = value;
|
|
1641
|
+
if (row.kind !== "bucket-key" || !isValidBucketId(row.bucketId) || !/^bk_[a-f0-9]{32}$/.test(String(row.keyId || "")) || !isValidInstanceId(row.targetInstanceId) || row.wrapAlg !== "ECDH-HKDF-SHA-256/AES-GCM-256" || !isPublicP256EcJwk(row.targetWrappingPublicJwk) || !isPublicP256EcJwk(row.ephemeralPublicJwk) || typeof row.salt !== "string" || typeof row.iv !== "string" || typeof row.aad !== "string" || typeof row.ciphertext !== "string") {
|
|
1642
|
+
return false;
|
|
1643
|
+
}
|
|
1644
|
+
if (instanceId && row.targetInstanceId !== instanceId) return false;
|
|
1645
|
+
if (keyId && row.keyId !== keyId) return false;
|
|
1646
|
+
return true;
|
|
1647
|
+
}
|
|
1648
|
+
function normalizeCapabilities(input) {
|
|
1649
|
+
if (!Array.isArray(input)) return [];
|
|
1650
|
+
const allowed = /* @__PURE__ */ new Set(["read", "write"]);
|
|
1651
|
+
const result = [];
|
|
1652
|
+
for (const item of input) {
|
|
1653
|
+
if (allowed.has(item) && !result.includes(item)) result.push(item);
|
|
1654
|
+
}
|
|
1655
|
+
return result.sort();
|
|
1656
|
+
}
|
|
1657
|
+
|
|
1308
1658
|
// src/auth/keys.ts
|
|
1309
1659
|
async function createInstanceKey() {
|
|
1310
1660
|
const signing = await crypto.subtle.generateKey({ name: "ECDSA", namedCurve: "P-256" }, false, ["sign", "verify"]);
|
|
@@ -1412,13 +1762,14 @@ function createInstanceKeyStore(storage, appId) {
|
|
|
1412
1762
|
if (!value) throw new ClientError("INVALID_INSTANCE_KEY", "Stored instance key is missing");
|
|
1413
1763
|
return value;
|
|
1414
1764
|
}
|
|
1415
|
-
async function insert(instance) {
|
|
1765
|
+
async function insert(instance, extra) {
|
|
1416
1766
|
if (await storage.get(keys.active) !== null) return false;
|
|
1417
1767
|
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
1418
1768
|
const entries = [
|
|
1419
1769
|
{ key: keys.key(instance.instanceId), value: { ...instance, updatedAt: now } },
|
|
1420
1770
|
{ key: keys.active, value: { v: 1, instanceId: instance.instanceId, updatedAt: now } }
|
|
1421
1771
|
];
|
|
1772
|
+
if (extra) entries.push(extra);
|
|
1422
1773
|
if (storage.insertIfEmpty) return storage.insertIfEmpty(keys.keyPrefix, entries);
|
|
1423
1774
|
if ((await storage.keys(keys.keyPrefix)).length) return false;
|
|
1424
1775
|
const written = [];
|
|
@@ -1434,8 +1785,8 @@ function createInstanceKeyStore(storage, appId) {
|
|
|
1434
1785
|
return true;
|
|
1435
1786
|
}
|
|
1436
1787
|
let ensuring;
|
|
1437
|
-
async function save(instance) {
|
|
1438
|
-
if (!await insert(instance)) throw new ClientError("KEY_EXISTS", "An instance key already exists for this appId");
|
|
1788
|
+
async function save(instance, extra) {
|
|
1789
|
+
if (!await insert(instance, extra)) throw new ClientError("KEY_EXISTS", "An instance key already exists for this appId");
|
|
1439
1790
|
}
|
|
1440
1791
|
async function create(beforeWrite = () => {
|
|
1441
1792
|
}) {
|
|
@@ -1601,81 +1952,13 @@ async function deriveBucketKeysFromRaw(bucketId, keyId, rawKey) {
|
|
|
1601
1952
|
const mac = new Uint8Array(await crypto.subtle.sign("HMAC", idKey, utf8Encode(safe)));
|
|
1602
1953
|
const wireId = `${WIRE_ID_PREFIX}${bytesToHex(mac).slice(0, WIRE_ID_HEX_LENGTH)}`;
|
|
1603
1954
|
wireIdCache.set(safe, wireId);
|
|
1604
|
-
return wireId;
|
|
1605
|
-
}
|
|
1606
|
-
};
|
|
1607
|
-
}
|
|
1608
|
-
async function unwrapBucketKeys(envelope, instanceWrappingPrivateKey) {
|
|
1609
|
-
const ephemeralPublic = await crypto.subtle.importKey("jwk", envelope.ephemeralPublicJwk, { name: "ECDH", namedCurve: "P-256" }, false, []);
|
|
1610
|
-
const sharedBits = await crypto.subtle.deriveBits({ name: "ECDH", public: ephemeralPublic }, instanceWrappingPrivateKey, 256);
|
|
1611
|
-
const material = await crypto.subtle.importKey("raw", sharedBits, "HKDF", false, ["deriveKey"]);
|
|
1612
|
-
const wrappingKey = await crypto.subtle.deriveKey(
|
|
1613
|
-
{ name: "HKDF", hash: "SHA-256", salt: b64urlToBytes(envelope.salt), info: utf8Encode(envelope.aad) },
|
|
1614
|
-
material,
|
|
1615
|
-
{ name: "AES-GCM", length: 256 },
|
|
1616
|
-
false,
|
|
1617
|
-
["decrypt"]
|
|
1618
|
-
);
|
|
1619
|
-
const raw = new Uint8Array(
|
|
1620
|
-
await crypto.subtle.decrypt(
|
|
1621
|
-
{ name: "AES-GCM", iv: b64urlToBytes(envelope.iv), additionalData: utf8Encode(envelope.aad) },
|
|
1622
|
-
wrappingKey,
|
|
1623
|
-
b64urlToBytes(envelope.ciphertext)
|
|
1624
|
-
)
|
|
1625
|
-
);
|
|
1626
|
-
try {
|
|
1627
|
-
return await deriveBucketKeysFromRaw(envelope.bucketId, envelope.keyId, raw);
|
|
1628
|
-
} finally {
|
|
1629
|
-
raw.fill(0);
|
|
1630
|
-
}
|
|
1631
|
-
}
|
|
1632
|
-
|
|
1633
|
-
// src/auth/authorization.ts
|
|
1634
|
-
var AUTH_CALLBACK_FRAGMENT_PARAM = "mf_auth_result";
|
|
1635
|
-
function buildAuthRequestFragment(request) {
|
|
1636
|
-
if (!request.requestId || !request.state) throw new Error("auth request state required");
|
|
1637
|
-
if (!isValidInstanceId(request.instanceId)) throw new Error("invalid instanceId");
|
|
1638
|
-
if (!isPublicP256EcJwk(request.instanceSigningPublicJwk)) throw new Error("instanceSigningPublicJwk required");
|
|
1639
|
-
if (!isPublicP256EcJwk(request.instanceWrappingPublicJwk)) throw new Error("instanceWrappingPublicJwk required");
|
|
1640
|
-
const redirect = new URL(request.redirectUri);
|
|
1641
|
-
const origin = new URL(request.origin);
|
|
1642
|
-
if (redirect.origin !== origin.origin) throw new Error("redirectUri origin mismatch");
|
|
1643
|
-
const wire = {
|
|
1644
|
-
response_type: "code",
|
|
1645
|
-
client_id: request.clientId,
|
|
1646
|
-
redirect_uri: request.redirectUri,
|
|
1647
|
-
state: request.state,
|
|
1648
|
-
scope: request.capabilities.join(" "),
|
|
1649
|
-
resource_id: request.resourceId,
|
|
1650
|
-
mf_v: 1,
|
|
1651
|
-
mf_auth_mode: "v1",
|
|
1652
|
-
mf_request_id: request.requestId,
|
|
1653
|
-
mf_instance_id: request.instanceId,
|
|
1654
|
-
mf_instance_signing_jwk: request.instanceSigningPublicJwk,
|
|
1655
|
-
mf_instance_wrapping_jwk: request.instanceWrappingPublicJwk,
|
|
1656
|
-
mf_issued_at: request.createdAt
|
|
1955
|
+
return wireId;
|
|
1956
|
+
}
|
|
1657
1957
|
};
|
|
1658
|
-
return `#authRequest=${bytesToB64url(utf8Encode(stableStringify(wire)))}`;
|
|
1659
|
-
}
|
|
1660
|
-
function parseEncryptedAuthAuthorizationResultFragment(fragmentOrUrl) {
|
|
1661
|
-
const input = String(fragmentOrUrl || "");
|
|
1662
|
-
const rawFragment = input.includes("#") ? input.slice(input.indexOf("#") + 1) : input.replace(/^#/, "");
|
|
1663
|
-
if (!rawFragment) return null;
|
|
1664
|
-
const encoded = new URLSearchParams(rawFragment).get(AUTH_CALLBACK_FRAGMENT_PARAM);
|
|
1665
|
-
if (!encoded) return null;
|
|
1666
|
-
const envelope = JSON.parse(new TextDecoder().decode(b64urlToBytes(encoded)));
|
|
1667
|
-
if (!envelope || envelope.v !== 1 || envelope.typ !== "auth.authorization-result.envelope.v1" || envelope.alg !== "ECDH-HKDF-SHA-256/AES-GCM-256" || typeof envelope.requestId !== "string" || typeof envelope.state !== "string" || !parseBucketResourceId(envelope.resourceId) || !isValidInstanceId(envelope.instanceId || "") || !isPublicP256EcJwk(envelope.ephemeralPublicJwk) || typeof envelope.salt !== "string" || typeof envelope.iv !== "string" || typeof envelope.aad !== "string" || typeof envelope.ciphertext !== "string") {
|
|
1668
|
-
throw new Error("auth callback result fragment invalid");
|
|
1669
|
-
}
|
|
1670
|
-
return envelope;
|
|
1671
1958
|
}
|
|
1672
|
-
async function
|
|
1673
|
-
const { envelope } = input;
|
|
1674
|
-
if (input.expectedRequestId && envelope.requestId !== input.expectedRequestId || input.expectedState && envelope.state !== input.expectedState || input.expectedResourceId && envelope.resourceId !== input.expectedResourceId || input.expectedInstanceId && envelope.instanceId !== input.expectedInstanceId) {
|
|
1675
|
-
throw new Error("auth callback result mismatch");
|
|
1676
|
-
}
|
|
1959
|
+
async function unwrapBucketKeys(envelope, instanceWrappingPrivateKey) {
|
|
1677
1960
|
const ephemeralPublic = await crypto.subtle.importKey("jwk", envelope.ephemeralPublicJwk, { name: "ECDH", namedCurve: "P-256" }, false, []);
|
|
1678
|
-
const sharedBits = await crypto.subtle.deriveBits({ name: "ECDH", public: ephemeralPublic },
|
|
1961
|
+
const sharedBits = await crypto.subtle.deriveBits({ name: "ECDH", public: ephemeralPublic }, instanceWrappingPrivateKey, 256);
|
|
1679
1962
|
const material = await crypto.subtle.importKey("raw", sharedBits, "HKDF", false, ["deriveKey"]);
|
|
1680
1963
|
const wrappingKey = await crypto.subtle.deriveKey(
|
|
1681
1964
|
{ name: "HKDF", hash: "SHA-256", salt: b64urlToBytes(envelope.salt), info: utf8Encode(envelope.aad) },
|
|
@@ -1684,85 +1967,18 @@ async function decryptEncryptedAuthAuthorizationResult(input) {
|
|
|
1684
1967
|
false,
|
|
1685
1968
|
["decrypt"]
|
|
1686
1969
|
);
|
|
1687
|
-
const
|
|
1688
|
-
|
|
1689
|
-
|
|
1690
|
-
|
|
1970
|
+
const raw = new Uint8Array(
|
|
1971
|
+
await crypto.subtle.decrypt(
|
|
1972
|
+
{ name: "AES-GCM", iv: b64urlToBytes(envelope.iv), additionalData: utf8Encode(envelope.aad) },
|
|
1973
|
+
wrappingKey,
|
|
1974
|
+
b64urlToBytes(envelope.ciphertext)
|
|
1975
|
+
)
|
|
1691
1976
|
);
|
|
1692
|
-
|
|
1693
|
-
|
|
1694
|
-
|
|
1695
|
-
|
|
1696
|
-
return result;
|
|
1697
|
-
}
|
|
1698
|
-
function normalizeAuthAuthorizationResult(value, expectedRequestId) {
|
|
1699
|
-
const row = value;
|
|
1700
|
-
if (!row || row.v !== 1 || row.result !== "approved" || typeof row.requestId !== "string" || expectedRequestId && row.requestId !== expectedRequestId || typeof row.state !== "string" || !isValidMfid(row.mfid || "") || !parseBucketResourceId(row.resourceId) || !isValidInstanceId(row.instanceId || "") || typeof row.createdAt !== "string") {
|
|
1701
|
-
return null;
|
|
1702
|
-
}
|
|
1703
|
-
if (row.expiresAt !== void 0) {
|
|
1704
|
-
const expiresAt = Date.parse(String(row.expiresAt));
|
|
1705
|
-
if (!Number.isFinite(expiresAt) || expiresAt <= Date.now()) return null;
|
|
1706
|
-
}
|
|
1707
|
-
const resource = parseBucketResourceId(row.resourceId);
|
|
1708
|
-
if (!resource) return null;
|
|
1709
|
-
const bucketAccessGrant = normalizeBucketAccessGrant(row.bucketAccessGrant);
|
|
1710
|
-
if (!bucketAccessGrant) return null;
|
|
1711
|
-
if (bucketAccessGrant.mfid !== row.mfid || !parseBucketResourceId(bucketAccessGrant.resourceId) || bucketAccessGrant.instanceId !== row.instanceId) {
|
|
1712
|
-
return null;
|
|
1713
|
-
}
|
|
1714
|
-
return {
|
|
1715
|
-
v: 1,
|
|
1716
|
-
requestId: row.requestId,
|
|
1717
|
-
state: row.state,
|
|
1718
|
-
result: "approved",
|
|
1719
|
-
mfid: row.mfid,
|
|
1720
|
-
resourceId: resource.resourceId,
|
|
1721
|
-
instanceId: row.instanceId,
|
|
1722
|
-
createdAt: row.createdAt,
|
|
1723
|
-
...typeof row.resourceApiUrl === "string" && row.resourceApiUrl.trim() ? { resourceApiUrl: row.resourceApiUrl.trim() } : {},
|
|
1724
|
-
bucketAccessGrant,
|
|
1725
|
-
...row.expiresAt ? { expiresAt: row.expiresAt } : {}
|
|
1726
|
-
};
|
|
1727
|
-
}
|
|
1728
|
-
function normalizeBucketAccessGrant(value) {
|
|
1729
|
-
if (!value || typeof value !== "object" || Array.isArray(value)) return null;
|
|
1730
|
-
const row = value;
|
|
1731
|
-
const resource = parseBucketResourceId(row.resourceId);
|
|
1732
|
-
const capabilities = normalizeCapabilities(row.capabilities);
|
|
1733
|
-
if (row.v !== 1 || !/^ar_[a-f0-9]{32}$/.test(String(row.grantRecordId || "")) || !isValidMfid(row.mfid) || !resource || !isValidInstanceId(row.instanceId) || !/^bk_[a-f0-9]{32}$/.test(String(row.keyId || "")) || capabilities.length < 1 || !isValidBucketKeyGrantEnvelope(row.envelope, row.instanceId, row.keyId)) {
|
|
1734
|
-
return null;
|
|
1735
|
-
}
|
|
1736
|
-
return {
|
|
1737
|
-
v: 1,
|
|
1738
|
-
grantRecordId: row.grantRecordId,
|
|
1739
|
-
mfid: row.mfid,
|
|
1740
|
-
resourceId: resource.resourceId,
|
|
1741
|
-
instanceId: row.instanceId,
|
|
1742
|
-
issuedAt: String(row.issuedAt || ""),
|
|
1743
|
-
keyId: row.keyId,
|
|
1744
|
-
capabilities,
|
|
1745
|
-
envelope: row.envelope
|
|
1746
|
-
};
|
|
1747
|
-
}
|
|
1748
|
-
function isValidBucketKeyGrantEnvelope(value, instanceId, keyId) {
|
|
1749
|
-
if (!value || typeof value !== "object" || Array.isArray(value)) return false;
|
|
1750
|
-
const row = value;
|
|
1751
|
-
if (row.kind !== "bucket-key" || !isValidBucketId(row.bucketId) || !/^bk_[a-f0-9]{32}$/.test(String(row.keyId || "")) || !isValidInstanceId(row.targetInstanceId) || row.wrapAlg !== "ECDH-HKDF-SHA-256/AES-GCM-256" || !isPublicP256EcJwk(row.targetWrappingPublicJwk) || !isPublicP256EcJwk(row.ephemeralPublicJwk) || typeof row.salt !== "string" || typeof row.iv !== "string" || typeof row.aad !== "string" || typeof row.ciphertext !== "string") {
|
|
1752
|
-
return false;
|
|
1753
|
-
}
|
|
1754
|
-
if (instanceId && row.targetInstanceId !== instanceId) return false;
|
|
1755
|
-
if (keyId && row.keyId !== keyId) return false;
|
|
1756
|
-
return true;
|
|
1757
|
-
}
|
|
1758
|
-
function normalizeCapabilities(input) {
|
|
1759
|
-
if (!Array.isArray(input)) return [];
|
|
1760
|
-
const allowed = /* @__PURE__ */ new Set(["read", "write"]);
|
|
1761
|
-
const result = [];
|
|
1762
|
-
for (const item of input) {
|
|
1763
|
-
if (allowed.has(item) && !result.includes(item)) result.push(item);
|
|
1977
|
+
try {
|
|
1978
|
+
return await deriveBucketKeysFromRaw(envelope.bucketId, envelope.keyId, raw);
|
|
1979
|
+
} finally {
|
|
1980
|
+
raw.fill(0);
|
|
1764
1981
|
}
|
|
1765
|
-
return result.sort();
|
|
1766
1982
|
}
|
|
1767
1983
|
|
|
1768
1984
|
// src/remote/session.ts
|
|
@@ -2023,7 +2239,7 @@ function createInstanceAuthClient(options = {}) {
|
|
|
2023
2239
|
const cacheKey = `${mfid}:${safeBucketId}:${authInstance.instanceId}`;
|
|
2024
2240
|
const cached = bucketAccessCache.get(cacheKey);
|
|
2025
2241
|
if (cached && cached.expiresAt > Date.now()) return cached.access;
|
|
2026
|
-
const grant =
|
|
2242
|
+
const grant = normalizeBucketGrant(context.bucketAccessGrant);
|
|
2027
2243
|
const remoteResourceId = context.remoteResourceId || resourceId;
|
|
2028
2244
|
if (!grant || grant.mfid !== mfid || grant.instanceId !== authInstance.instanceId || grant.resourceId !== remoteResourceId) {
|
|
2029
2245
|
throw new Error("bucket access grant unavailable; reauthorize required");
|
|
@@ -2096,169 +2312,6 @@ function browserLocationOrigin() {
|
|
|
2096
2312
|
return window.location.origin;
|
|
2097
2313
|
}
|
|
2098
2314
|
|
|
2099
|
-
// src/remote/http.ts
|
|
2100
|
-
function isRecord2(value) {
|
|
2101
|
-
return value !== null && typeof value === "object" && !Array.isArray(value);
|
|
2102
|
-
}
|
|
2103
|
-
function requireString(value, name) {
|
|
2104
|
-
if (typeof value !== "string" || !value.trim()) {
|
|
2105
|
-
throw new ClientError("INVALID_INPUT", `${name} must be a non-empty string`);
|
|
2106
|
-
}
|
|
2107
|
-
}
|
|
2108
|
-
function invalidResponse(response, message = "Invalid protocol response", cause) {
|
|
2109
|
-
return new ClientError("INVALID_RESPONSE", message, {
|
|
2110
|
-
status: response.status,
|
|
2111
|
-
requestId: response.headers.get("x-request-id") ?? void 0,
|
|
2112
|
-
cause
|
|
2113
|
-
});
|
|
2114
|
-
}
|
|
2115
|
-
function networkError(cause, signal) {
|
|
2116
|
-
signal?.throwIfAborted();
|
|
2117
|
-
throw new ClientError("NETWORK_ERROR", "Network request failed", { retryable: true, cause });
|
|
2118
|
-
}
|
|
2119
|
-
async function readJson(response, signal) {
|
|
2120
|
-
let value;
|
|
2121
|
-
try {
|
|
2122
|
-
value = await response.json();
|
|
2123
|
-
} catch (cause) {
|
|
2124
|
-
signal?.throwIfAborted();
|
|
2125
|
-
if (!(cause instanceof SyntaxError)) return networkError(cause, signal);
|
|
2126
|
-
throw invalidResponse(response, "Invalid JSON response", cause);
|
|
2127
|
-
}
|
|
2128
|
-
signal?.throwIfAborted();
|
|
2129
|
-
if (!isRecord2(value)) throw invalidResponse(response);
|
|
2130
|
-
return value;
|
|
2131
|
-
}
|
|
2132
|
-
function createHttpRequest(options) {
|
|
2133
|
-
requireString(options.apiBase, "apiBase");
|
|
2134
|
-
let base;
|
|
2135
|
-
try {
|
|
2136
|
-
base = new URL(options.apiBase);
|
|
2137
|
-
} catch (cause) {
|
|
2138
|
-
throw new ClientError("INVALID_INPUT", "apiBase must be an HTTP(S) origin", { cause });
|
|
2139
|
-
}
|
|
2140
|
-
if (!["http:", "https:"].includes(base.protocol) || base.pathname !== "/" || base.search || base.hash || base.username || base.password) {
|
|
2141
|
-
throw new ClientError("INVALID_INPUT", "apiBase must be an HTTP(S) origin without a path, query, fragment or credentials");
|
|
2142
|
-
}
|
|
2143
|
-
const fetch2 = options.fetch ?? globalThis.fetch.bind(globalThis);
|
|
2144
|
-
if (typeof fetch2 !== "function") throw new ClientError("INVALID_INPUT", "fetch must be a function");
|
|
2145
|
-
return async (path, init) => {
|
|
2146
|
-
init.signal?.throwIfAborted();
|
|
2147
|
-
let response;
|
|
2148
|
-
try {
|
|
2149
|
-
response = await fetch2(new URL(path, base).href, { ...init, credentials: "omit" });
|
|
2150
|
-
} catch (cause) {
|
|
2151
|
-
return networkError(cause, init.signal);
|
|
2152
|
-
}
|
|
2153
|
-
if (response.ok) return response;
|
|
2154
|
-
let body = {};
|
|
2155
|
-
try {
|
|
2156
|
-
const value = await response.json();
|
|
2157
|
-
if (isRecord2(value)) body = value;
|
|
2158
|
-
} catch {
|
|
2159
|
-
init.signal?.throwIfAborted();
|
|
2160
|
-
}
|
|
2161
|
-
const details = isRecord2(body.details) ? body.details : {};
|
|
2162
|
-
const retry = response.headers.get("retry-after");
|
|
2163
|
-
const seconds = retry !== null && /^\d+(?:\.\d+)?$/.test(retry.trim()) ? Number(retry) : NaN;
|
|
2164
|
-
const date = retry === null ? NaN : Date.parse(retry);
|
|
2165
|
-
const retryAfterMs = Number.isFinite(seconds) ? seconds * 1e3 : Number.isFinite(date) ? Math.max(0, date - Date.now()) : void 0;
|
|
2166
|
-
throw new ClientError(
|
|
2167
|
-
typeof body.code === "string" && body.code ? body.code : "HTTP_ERROR",
|
|
2168
|
-
typeof body.message === "string" && body.message ? body.message : typeof body.error === "string" && body.error ? body.error : `HTTP ${response.status}`,
|
|
2169
|
-
{
|
|
2170
|
-
status: response.status,
|
|
2171
|
-
requestId: typeof body.requestId === "string" ? body.requestId : response.headers.get("x-request-id") ?? void 0,
|
|
2172
|
-
retryable: typeof details.retryable === "boolean" ? details.retryable : response.status === 408 || response.status === 429 || response.status >= 500,
|
|
2173
|
-
retryAfterMs,
|
|
2174
|
-
maxBytes: typeof details.maxBytes === "number" ? details.maxBytes : void 0
|
|
2175
|
-
}
|
|
2176
|
-
);
|
|
2177
|
-
};
|
|
2178
|
-
}
|
|
2179
|
-
|
|
2180
|
-
// src/remote/feed.ts
|
|
2181
|
-
function isFeedHint(value) {
|
|
2182
|
-
return isRecord2(value) && typeof value.objectId === "string" && value.objectId.length > 0 && typeof value.versionId === "string" && value.versionId.length > 0;
|
|
2183
|
-
}
|
|
2184
|
-
async function openFeedStream(response, signal) {
|
|
2185
|
-
const stream = readFeedStream(response, signal);
|
|
2186
|
-
await stream.next();
|
|
2187
|
-
return stream;
|
|
2188
|
-
}
|
|
2189
|
-
async function* readFeedStream(response, signal) {
|
|
2190
|
-
if (!response.body || response.headers.get("content-type")?.split(";", 1)[0]?.trim().toLowerCase() !== "text/event-stream") {
|
|
2191
|
-
await response.body?.cancel().catch(() => {
|
|
2192
|
-
});
|
|
2193
|
-
throw invalidResponse(response, "Expected an event stream");
|
|
2194
|
-
}
|
|
2195
|
-
const reader = response.body.getReader();
|
|
2196
|
-
const decoder = new TextDecoder();
|
|
2197
|
-
const cancel = () => {
|
|
2198
|
-
void reader.cancel(signal?.reason).catch(() => {
|
|
2199
|
-
});
|
|
2200
|
-
};
|
|
2201
|
-
signal?.addEventListener("abort", cancel, { once: true });
|
|
2202
|
-
let buffer = "", event = "", data = [], ready = false;
|
|
2203
|
-
try {
|
|
2204
|
-
signal?.throwIfAborted();
|
|
2205
|
-
for (; ; ) {
|
|
2206
|
-
let chunk;
|
|
2207
|
-
try {
|
|
2208
|
-
chunk = await reader.read();
|
|
2209
|
-
} catch (cause) {
|
|
2210
|
-
signal?.throwIfAborted();
|
|
2211
|
-
throw new ClientError("NETWORK_ERROR", "Feed stream interrupted", { retryable: true, cause });
|
|
2212
|
-
}
|
|
2213
|
-
signal?.throwIfAborted();
|
|
2214
|
-
buffer += decoder.decode(chunk.value, { stream: !chunk.done });
|
|
2215
|
-
let match;
|
|
2216
|
-
while ((match = /\r\n|\r|\n/.exec(buffer)) !== null) {
|
|
2217
|
-
if (!chunk.done && match.index === buffer.length - 1 && match[0] === "\r") break;
|
|
2218
|
-
const line = buffer.slice(0, match.index);
|
|
2219
|
-
buffer = buffer.slice(match.index + match[0].length);
|
|
2220
|
-
if (line === "") {
|
|
2221
|
-
if (event === "sync-ready" && data.length && !ready) {
|
|
2222
|
-
ready = true;
|
|
2223
|
-
yield void 0;
|
|
2224
|
-
} else if (event === "sync-feed" && data.length) {
|
|
2225
|
-
if (!ready) throw invalidResponse(response, "Feed change received before readiness");
|
|
2226
|
-
let value;
|
|
2227
|
-
try {
|
|
2228
|
-
value = JSON.parse(data.join("\n"));
|
|
2229
|
-
} catch (cause) {
|
|
2230
|
-
throw invalidResponse(response, "Invalid feed event", cause);
|
|
2231
|
-
}
|
|
2232
|
-
const entries = isRecord2(value) && Array.isArray(value.entries) ? value.entries : [value];
|
|
2233
|
-
if (!entries.every(isFeedHint)) throw invalidResponse(response, "Invalid feed hint");
|
|
2234
|
-
for (const entry of entries) {
|
|
2235
|
-
signal?.throwIfAborted();
|
|
2236
|
-
if (isFeedHint(entry)) yield { objectId: entry.objectId, versionId: entry.versionId };
|
|
2237
|
-
}
|
|
2238
|
-
}
|
|
2239
|
-
event = "";
|
|
2240
|
-
data = [];
|
|
2241
|
-
} else if (!line.startsWith(":")) {
|
|
2242
|
-
const colon = line.indexOf(":");
|
|
2243
|
-
const field = colon < 0 ? line : line.slice(0, colon);
|
|
2244
|
-
const value = colon < 0 ? "" : line.slice(colon + 1).replace(/^ /, "");
|
|
2245
|
-
if (field === "event") event = value;
|
|
2246
|
-
if (field === "data") data.push(value);
|
|
2247
|
-
}
|
|
2248
|
-
}
|
|
2249
|
-
if (chunk.done) {
|
|
2250
|
-
if (!ready) throw invalidResponse(response, "Feed ended before readiness");
|
|
2251
|
-
break;
|
|
2252
|
-
}
|
|
2253
|
-
}
|
|
2254
|
-
} finally {
|
|
2255
|
-
signal?.removeEventListener("abort", cancel);
|
|
2256
|
-
await reader.cancel().catch(() => {
|
|
2257
|
-
});
|
|
2258
|
-
reader.releaseLock();
|
|
2259
|
-
}
|
|
2260
|
-
}
|
|
2261
|
-
|
|
2262
2315
|
// src/remote/bucket.ts
|
|
2263
2316
|
function isHistory(value) {
|
|
2264
2317
|
return Array.isArray(value) && value.every((id) => typeof id === "string" && id.length > 0) && new Set(value).size === value.length;
|
|
@@ -2300,7 +2353,7 @@ function createBucketClient(request, bucketId) {
|
|
|
2300
2353
|
if (!isVersionMeta(body, objectId, versionId)) throw invalidResponse(response);
|
|
2301
2354
|
return body;
|
|
2302
2355
|
}
|
|
2303
|
-
|
|
2356
|
+
const bucket = {
|
|
2304
2357
|
async getCurrent(objectId, options = {}) {
|
|
2305
2358
|
const query = new URLSearchParams({ miss: "null" });
|
|
2306
2359
|
if (options.knownVersionId != null) {
|
|
@@ -2336,10 +2389,7 @@ function createBucketClient(request, bucketId) {
|
|
|
2336
2389
|
if (!Array.isArray(body.entries) || !body.entries.every(isFeedHint) || typeof body.cursor !== "string" || typeof body.hasMore !== "boolean") throw invalidResponse(response);
|
|
2337
2390
|
return body;
|
|
2338
2391
|
},
|
|
2339
|
-
|
|
2340
|
-
const response = await request(`${root}/feed/stream`, { headers: { accept: "text/event-stream" }, signal: options.signal });
|
|
2341
|
-
return openFeedStream(response, options.signal);
|
|
2342
|
-
},
|
|
2392
|
+
watchFeed: (options) => watchHttpFeed(bucket, options?.signal),
|
|
2343
2393
|
async getPayload(objectId, versionId, options = {}) {
|
|
2344
2394
|
return request(`${versionPath(objectId, versionId)}/payload`, { signal: options.signal });
|
|
2345
2395
|
},
|
|
@@ -2386,6 +2436,7 @@ function createBucketClient(request, bucketId) {
|
|
|
2386
2436
|
throw invalidResponse(response, "Invalid commit result");
|
|
2387
2437
|
}
|
|
2388
2438
|
};
|
|
2439
|
+
return bucket;
|
|
2389
2440
|
}
|
|
2390
2441
|
|
|
2391
2442
|
// src/remote/client.ts
|
|
@@ -2416,6 +2467,9 @@ function createRemoteClient(options) {
|
|
|
2416
2467
|
|
|
2417
2468
|
// src/remote/connection.ts
|
|
2418
2469
|
var DEFAULT_AUTH_URL = "https://myfield.one/auth/";
|
|
2470
|
+
function samePublicKey(a, b) {
|
|
2471
|
+
return a.kty === b.kty && a.crv === b.crv && a.x === b.x && a.y === b.y;
|
|
2472
|
+
}
|
|
2419
2473
|
function notAuthorized2(message, cause) {
|
|
2420
2474
|
return new ClientError("NOT_AUTHORIZED", message, {
|
|
2421
2475
|
cause,
|
|
@@ -2539,7 +2593,7 @@ function createInstanceConnection(deps) {
|
|
|
2539
2593
|
const keys = authRecordKeys(appId);
|
|
2540
2594
|
const prefix = keys.prefix;
|
|
2541
2595
|
return {
|
|
2542
|
-
...deps.auth.insertIfEmpty ? { insertIfEmpty: (prefix2, entries) => queue(signal, () => deps.auth.insertIfEmpty(prefix2, entries)) } : {},
|
|
2596
|
+
...deps.auth.insertIfEmpty ? { insertIfEmpty: (prefix2, entries, condition) => queue(signal, () => deps.auth.insertIfEmpty(prefix2, entries, condition)) } : {},
|
|
2543
2597
|
get: (key) => queue(signal, () => deps.auth.get(key)),
|
|
2544
2598
|
keys: (prefix2) => queue(signal, () => deps.auth.keys(prefix2)),
|
|
2545
2599
|
remove: (key) => queue(signal, () => deps.auth.remove(key)),
|
|
@@ -2805,40 +2859,11 @@ function createInstanceConnection(deps) {
|
|
|
2805
2859
|
listVersions: (...args) => invoke((bucket) => bucket.listVersions(...args)),
|
|
2806
2860
|
async watchFeed(options) {
|
|
2807
2861
|
const { client, controller } = requireConnection();
|
|
2808
|
-
const
|
|
2809
|
-
|
|
2810
|
-
|
|
2811
|
-
|
|
2812
|
-
|
|
2813
|
-
await stream.return(void 0);
|
|
2814
|
-
controller.signal.throwIfAborted();
|
|
2815
|
-
}
|
|
2816
|
-
const watched = {
|
|
2817
|
-
async next() {
|
|
2818
|
-
try {
|
|
2819
|
-
controller.signal.throwIfAborted();
|
|
2820
|
-
const next = await handleOperation(controller, () => stream.next());
|
|
2821
|
-
controller.signal.throwIfAborted();
|
|
2822
|
-
return next;
|
|
2823
|
-
} catch (error) {
|
|
2824
|
-
await stream.return(void 0);
|
|
2825
|
-
controller.signal.throwIfAborted();
|
|
2826
|
-
throw error;
|
|
2827
|
-
}
|
|
2828
|
-
},
|
|
2829
|
-
return: (value) => stream.return(value),
|
|
2830
|
-
throw: (error) => stream.throw(error),
|
|
2831
|
-
[Symbol.asyncIterator]() {
|
|
2832
|
-
return watched;
|
|
2833
|
-
}
|
|
2834
|
-
};
|
|
2835
|
-
const asyncDispose = Reflect.get(Symbol, "asyncDispose");
|
|
2836
|
-
if (typeof asyncDispose === "symbol") {
|
|
2837
|
-
Object.defineProperty(watched, asyncDispose, { value: async () => {
|
|
2838
|
-
await stream.return(void 0);
|
|
2839
|
-
} });
|
|
2840
|
-
}
|
|
2841
|
-
return watched;
|
|
2862
|
+
const bucket = client.getBucket();
|
|
2863
|
+
return watchHttpFeed({
|
|
2864
|
+
getIndex: (request) => handleOperation(controller, () => bucket.getIndex(request)),
|
|
2865
|
+
listFeed: (request) => handleOperation(controller, () => bucket.listFeed(request))
|
|
2866
|
+
}, options?.signal, controller.signal);
|
|
2842
2867
|
}
|
|
2843
2868
|
};
|
|
2844
2869
|
function start(prompt, args) {
|
|
@@ -2939,11 +2964,83 @@ function createInstanceConnection(deps) {
|
|
|
2939
2964
|
return key ? toInstanceKey(key) : null;
|
|
2940
2965
|
},
|
|
2941
2966
|
createKey: () => changeKey(async (store) => toInstanceKey(await store.create(assertKeyMutable))),
|
|
2942
|
-
importKey
|
|
2943
|
-
const
|
|
2944
|
-
|
|
2945
|
-
|
|
2946
|
-
|
|
2967
|
+
importKey(key, options) {
|
|
2968
|
+
const revision = generation;
|
|
2969
|
+
return changeKey(async (store) => {
|
|
2970
|
+
if (options !== void 0 && (!options || typeof options !== "object" || Array.isArray(options) || !options.bucketGrant || typeof options.apiUrl !== "string" || Object.keys(options).some(
|
|
2971
|
+
(name) => name !== "bucketGrant" && name !== "apiUrl"
|
|
2972
|
+
))) {
|
|
2973
|
+
throw new ClientError("INVALID_INPUT", "Key import options require bucketGrant and apiUrl");
|
|
2974
|
+
}
|
|
2975
|
+
const identity = await validateInstanceKey(key);
|
|
2976
|
+
assertKeyMutable();
|
|
2977
|
+
if (options === void 0) return store.import(identity);
|
|
2978
|
+
const checkRuntime = () => {
|
|
2979
|
+
if (revision !== generation) throw new DOMException("Key import cancelled", "AbortError");
|
|
2980
|
+
assertKeyMutable();
|
|
2981
|
+
};
|
|
2982
|
+
checkRuntime();
|
|
2983
|
+
assertUsable();
|
|
2984
|
+
const contextKey = store.keys.context(resourceId, identity.instanceId);
|
|
2985
|
+
const matchesIdentity = (active2) => active2.instanceId === identity.instanceId && samePublicKey(active2.signingPublicJwk, identity.signingPublicJwk) && samePublicKey(active2.wrappingPublicJwk, identity.wrappingPublicJwk);
|
|
2986
|
+
const requireMatchingIdentity = (active2) => {
|
|
2987
|
+
if (!matchesIdentity(active2)) throw new ClientError("KEY_EXISTS", "A different instance key already exists for this appId");
|
|
2988
|
+
};
|
|
2989
|
+
let active = await store.active();
|
|
2990
|
+
if (active) {
|
|
2991
|
+
requireMatchingIdentity(active);
|
|
2992
|
+
if (await deps.auth.get(contextKey)) return;
|
|
2993
|
+
}
|
|
2994
|
+
const grant = normalizeBucketGrant(options.bucketGrant);
|
|
2995
|
+
if (!grant || grant.instanceId !== identity.instanceId || grant.resourceId !== resourceId || grant.envelope.bucketId !== bucketId || !samePublicKey(grant.envelope.targetWrappingPublicJwk, identity.wrappingPublicJwk)) {
|
|
2996
|
+
throw notAuthorized2("Grant does not match the instance and default bucket");
|
|
2997
|
+
}
|
|
2998
|
+
const resourceApiUrl = apiOrigin(options.apiUrl);
|
|
2999
|
+
try {
|
|
3000
|
+
await unwrapBucketKeys(grant.envelope, identity.wrappingPrivateKey);
|
|
3001
|
+
} catch (error) {
|
|
3002
|
+
throw notAuthorized2("Cannot unwrap the imported bucket key", error);
|
|
3003
|
+
}
|
|
3004
|
+
const context = {
|
|
3005
|
+
v: 1,
|
|
3006
|
+
mfid: grant.mfid,
|
|
3007
|
+
instanceId: identity.instanceId,
|
|
3008
|
+
resourceId,
|
|
3009
|
+
resourceApiUrl,
|
|
3010
|
+
requestId: grant.grantRecordId,
|
|
3011
|
+
authorizedAt: grant.issuedAt,
|
|
3012
|
+
bucketAccessGrant: grant
|
|
3013
|
+
};
|
|
3014
|
+
checkRuntime();
|
|
3015
|
+
const entry = { key: contextKey, value: context };
|
|
3016
|
+
const write = (async () => {
|
|
3017
|
+
if (!active) {
|
|
3018
|
+
try {
|
|
3019
|
+
await store.import(identity, entry);
|
|
3020
|
+
return;
|
|
3021
|
+
} catch (error) {
|
|
3022
|
+
if (!(error instanceof ClientError) || error.code !== "KEY_EXISTS") throw error;
|
|
3023
|
+
}
|
|
3024
|
+
active = await store.active();
|
|
3025
|
+
if (!active) throw new ClientError("INVALID_STATE", "The instance key changed during import");
|
|
3026
|
+
requireMatchingIdentity(active);
|
|
3027
|
+
}
|
|
3028
|
+
const inserted = await deps.auth.insertIfEmpty(contextKey, [entry], {
|
|
3029
|
+
key: store.keys.key(identity.instanceId),
|
|
3030
|
+
matches: (value) => {
|
|
3031
|
+
const saved = value;
|
|
3032
|
+
return Boolean(saved && matchesIdentity(saved));
|
|
3033
|
+
}
|
|
3034
|
+
});
|
|
3035
|
+
if (!inserted && !await deps.auth.get(contextKey)) {
|
|
3036
|
+
throw new ClientError("INVALID_STATE", "The instance key changed during import");
|
|
3037
|
+
}
|
|
3038
|
+
})();
|
|
3039
|
+
storageQueue = write.catch(() => {
|
|
3040
|
+
});
|
|
3041
|
+
await write;
|
|
3042
|
+
});
|
|
3043
|
+
},
|
|
2947
3044
|
removeKey: () => changeKey((store) => store.remove()),
|
|
2948
3045
|
resume: (...args) => start(false, args),
|
|
2949
3046
|
connect: (...args) => start(true, args),
|
|
@@ -3504,7 +3601,11 @@ function normalizeNamespace(value) {
|
|
|
3504
3601
|
function prefixedAdapter(adapter, prefix) {
|
|
3505
3602
|
return {
|
|
3506
3603
|
...adapter.removePrefix ? { removePrefix: (keyPrefix) => adapter.removePrefix(`${prefix}${keyPrefix}`) } : {},
|
|
3507
|
-
...adapter.insertIfEmpty ? { insertIfEmpty: (keyPrefix, entries) => adapter.insertIfEmpty(
|
|
3604
|
+
...adapter.insertIfEmpty ? { insertIfEmpty: (keyPrefix, entries, condition) => adapter.insertIfEmpty(
|
|
3605
|
+
`${prefix}${keyPrefix}`,
|
|
3606
|
+
entries.map((entry) => ({ ...entry, key: `${prefix}${entry.key}` })),
|
|
3607
|
+
condition && { ...condition, key: `${prefix}${condition.key}` }
|
|
3608
|
+
) } : {},
|
|
3508
3609
|
get: (key) => adapter.get(`${prefix}${key}`),
|
|
3509
3610
|
set: (key, value) => adapter.set(`${prefix}${key}`, value),
|
|
3510
3611
|
remove: (key) => adapter.remove(`${prefix}${key}`),
|