@muhkoo/connect 0.15.0-alpha.10 → 0.15.0-alpha.12

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.
@@ -2570,6 +2570,19 @@ class HttpError extends Error {
2570
2570
  * `requiresPaidTier` or `freeTierFull` — has no `code`, and stays a plain
2571
2571
  * `HttpError`, as before.
2572
2572
  */
2573
+ const CODES = new Set([
2574
+ "user_plan_required",
2575
+ "user_payment_past_due",
2576
+ "owner_payment_past_due",
2577
+ ]);
2578
+ /** True for one of the three {@link PaymentRequiredCode}s. */
2579
+ function isPaymentRequiredCode(value) {
2580
+ return typeof value === "string" && CODES.has(value);
2581
+ }
2582
+ /** `url` when it is an absolute http(s) URL, else undefined: an app may put it straight into a link. */
2583
+ function absoluteHttpUrl(url) {
2584
+ return typeof url === "string" && /^https?:\/\/[^/]/i.test(url) ? url : undefined;
2585
+ }
2573
2586
  /** Thrown for a 402 whose body carries one of the three {@link PaymentRequiredCode}s. */
2574
2587
  class PaymentRequiredError extends HttpError {
2575
2588
  /** Why the write was refused. */
@@ -2589,6 +2602,317 @@ class PaymentRequiredError extends HttpError {
2589
2602
  this.upgradeUrl = upgradeUrl;
2590
2603
  }
2591
2604
  }
2605
+ /**
2606
+ * The error to throw for a refused response: a {@link PaymentRequiredError}
2607
+ * for a 402 whose body carries one of the three codes, and null for anything
2608
+ * else, so the caller throws what it threw before. `body` is the parsed JSON,
2609
+ * or the raw text of the response, which is parsed here.
2610
+ */
2611
+ function paymentRequiredFrom(status, body) {
2612
+ if (status !== 402)
2613
+ return null;
2614
+ let parsed = body;
2615
+ if (typeof parsed === "string") {
2616
+ try {
2617
+ parsed = JSON.parse(parsed);
2618
+ }
2619
+ catch {
2620
+ return null;
2621
+ }
2622
+ }
2623
+ if (!parsed || typeof parsed !== "object")
2624
+ return null;
2625
+ const { code, error, upgradeUrl } = parsed;
2626
+ if (!isPaymentRequiredCode(code))
2627
+ return null;
2628
+ const message = typeof error === "string" && error ? error : `Payment required (${code})`;
2629
+ return new PaymentRequiredError(message, code, parsed, absoluteHttpUrl(upgradeUrl));
2630
+ }
2631
+
2632
+ /**
2633
+ * Typed refusals from the shares API. Each extends {@link HttpError}, so code that only knows `HttpError` still
2634
+ * sees the status and body. Codes are the accelerator's wire contract.
2635
+ */
2636
+ /** 402 `share_full`: the share is at its storage cap. */
2637
+ class ShareFullError extends HttpError {
2638
+ limitBytes;
2639
+ usedBytes;
2640
+ refused;
2641
+ constructor(message, limitBytes, usedBytes,
2642
+ /**
2643
+ * How many items of a `Share.writeMany` were not written (the refused one and every one after it). The
2644
+ * server's body has no such field, so it is 0 on an error straight from the wire.
2645
+ */
2646
+ refused, body) {
2647
+ super(message, 402, body);
2648
+ this.limitBytes = limitBytes;
2649
+ this.usedBytes = usedBytes;
2650
+ this.refused = refused;
2651
+ this.name = "ShareFullError";
2652
+ }
2653
+ }
2654
+ /** 409 `share_closed`: the share was rotated; use `successor` instead. */
2655
+ class ShareClosedError extends HttpError {
2656
+ successor;
2657
+ constructor(message, successor, body) {
2658
+ super(message, 409, body);
2659
+ this.successor = successor;
2660
+ this.name = "ShareClosedError";
2661
+ }
2662
+ }
2663
+ /** 403 `share_password`: wrong password. */
2664
+ class SharePasswordError extends HttpError {
2665
+ constructor(message, body) {
2666
+ super(message, 403, body);
2667
+ this.name = "SharePasswordError";
2668
+ }
2669
+ }
2670
+ /** 429 `share_password_rate`: too many wrong passwords. */
2671
+ class SharePasswordRateError extends HttpError {
2672
+ retryAfterSeconds;
2673
+ constructor(message, retryAfterSeconds, body) {
2674
+ super(message, 429, body);
2675
+ this.retryAfterSeconds = retryAfterSeconds;
2676
+ this.name = "SharePasswordRateError";
2677
+ }
2678
+ }
2679
+ /** 403 `share_member_limit`: the share holds as many members as it allows. */
2680
+ class ShareMemberLimitError extends HttpError {
2681
+ constructor(message, body) {
2682
+ super(message, 403, body);
2683
+ this.name = "ShareMemberLimitError";
2684
+ }
2685
+ }
2686
+ /** 409 `share_space_not_empty`: only an empty Space can become a share. */
2687
+ class ShareSpaceNotEmptyError extends HttpError {
2688
+ constructor(message, body) {
2689
+ super(message, 409, body);
2690
+ this.name = "ShareSpaceNotEmptyError";
2691
+ }
2692
+ }
2693
+ /** 409 `share_space_not_ready`: the Space has no `/metadata` yet; create the Space before making it a share. */
2694
+ class ShareSpaceNotReadyError extends HttpError {
2695
+ constructor(message, body) {
2696
+ super(message, 409, body);
2697
+ this.name = "ShareSpaceNotReadyError";
2698
+ }
2699
+ }
2700
+ /** 409 `rotation_mismatch`: a retried rotation asked for other settings than the one in progress. */
2701
+ class RotationMismatchError extends HttpError {
2702
+ constructor(message, body) {
2703
+ super(message, 409, body);
2704
+ this.name = "RotationMismatchError";
2705
+ }
2706
+ }
2707
+ /** 409 `rotation_in_progress`: another rotation of this share won; `successor` is its new Space. */
2708
+ class RotationInProgressError extends HttpError {
2709
+ successor;
2710
+ constructor(message, successor, body) {
2711
+ super(message, 409, body);
2712
+ this.successor = successor;
2713
+ this.name = "RotationInProgressError";
2714
+ }
2715
+ }
2716
+ /**
2717
+ * A rotation (`changePassword` / `removeMember`) claimed `newSpaceId` but its adopt did not finish (network failure
2718
+ * or server error, retried). It is kept on this device: call the same rotation again, or `shares.resumeRotation`,
2719
+ * to finish it into the SAME Space. No other rotation of this share starts until it does.
2720
+ */
2721
+ class RotationIncompleteError extends Error {
2722
+ from;
2723
+ newSpaceId;
2724
+ cause;
2725
+ constructor(from, newSpaceId, cause) {
2726
+ super(`Moving the share ${from} to ${newSpaceId} did not finish; try again to finish it.`);
2727
+ this.from = from;
2728
+ this.newSpaceId = newSpaceId;
2729
+ this.cause = cause;
2730
+ this.name = "RotationIncompleteError";
2731
+ }
2732
+ }
2733
+ /** A guest recovery code that does not parse (expected `<username>:<words>`). */
2734
+ class InvalidRecoveryCodeError extends Error {
2735
+ constructor(message = "That is not a recovery code: expected <username>:<words>.") {
2736
+ super(message);
2737
+ this.name = "InvalidRecoveryCodeError";
2738
+ }
2739
+ }
2740
+ /** `restoreGuest` would replace another guest's login kept on this device; pass `{ replace: true }` to do so. */
2741
+ class GuestLoginConflictError extends Error {
2742
+ existing;
2743
+ constructor(existing) {
2744
+ super(`This device is signed in as the guest ${existing}; replace it to restore another guest.`);
2745
+ this.existing = existing;
2746
+ this.name = "GuestLoginConflictError";
2747
+ }
2748
+ }
2749
+ const num = (v) => (typeof v === "number" && Number.isFinite(v) ? v : 0);
2750
+ const str = (v) => (typeof v === "string" ? v : "");
2751
+ /**
2752
+ * The typed error for a refused response, or null when it is not a share refusal (the caller then throws what it
2753
+ * threw before). `body` is the parsed JSON or the raw response text. `retryAfterSeconds` is the `Retry-After`
2754
+ * header, used for a 429.
2755
+ */
2756
+ function shareErrorFrom(status, body, retryAfterSeconds) {
2757
+ let parsed = body;
2758
+ if (typeof parsed === "string") {
2759
+ try {
2760
+ parsed = JSON.parse(parsed);
2761
+ }
2762
+ catch {
2763
+ return null;
2764
+ }
2765
+ }
2766
+ if (!parsed || typeof parsed !== "object")
2767
+ return null;
2768
+ const b = parsed;
2769
+ const code = b.code;
2770
+ const msg = (fallback) => (typeof b.error === "string" && b.error ? b.error : fallback);
2771
+ if (status === 402 && code === "share_full") {
2772
+ return new ShareFullError(msg("Share is full"), num(b.limitBytes), num(b.usedBytes), num(b.refused), parsed);
2773
+ }
2774
+ if (status === 403) {
2775
+ if (code === "share_password")
2776
+ return new SharePasswordError(msg("Wrong password"), parsed);
2777
+ if (code === "share_member_limit")
2778
+ return new ShareMemberLimitError(msg("Share member limit reached"), parsed);
2779
+ }
2780
+ if (status === 429 && code === "share_password_rate") {
2781
+ const wait = retryAfterSeconds !== undefined && Number.isFinite(retryAfterSeconds) ? retryAfterSeconds : 1;
2782
+ return new SharePasswordRateError(msg("Too many wrong passwords"), wait, parsed);
2783
+ }
2784
+ if (status === 409) {
2785
+ if (code === "share_closed")
2786
+ return new ShareClosedError(msg("Share is closed"), str(b.successor), parsed);
2787
+ if (code === "share_space_not_ready")
2788
+ return new ShareSpaceNotReadyError(msg("Space is not ready"), parsed);
2789
+ if (code === "share_space_not_empty")
2790
+ return new ShareSpaceNotEmptyError(msg("Space is not empty"), parsed);
2791
+ if (code === "rotation_mismatch")
2792
+ return new RotationMismatchError(msg("Rotation settings differ"), parsed);
2793
+ if (code === "rotation_in_progress") {
2794
+ return new RotationInProgressError(msg("Share is being rotated"), str(b.successor), parsed);
2795
+ }
2796
+ }
2797
+ return null;
2798
+ }
2799
+
2800
+ /**
2801
+ * `SharesClient` — the thin HTTP layer over the accelerator's `/api/shares` routes. It owns paths, verbs and error
2802
+ * mapping and nothing else; the `Share` object and `client.shares` build on it.
2803
+ *
2804
+ * Every call but `publicInfo` carries the app key and the signed-in session (with the usual stale-session recovery),
2805
+ * including `admit`: a public share's guest is an ordinary account. `publicInfo` needs only the app key and never
2806
+ * sends a session.
2807
+ */
2808
+ class SharesClient {
2809
+ http;
2810
+ keyOnlyHttp;
2811
+ constructor(http) {
2812
+ this.http = http;
2813
+ this.keyOnlyHttp = http.withoutSession();
2814
+ }
2815
+ create(body) {
2816
+ return this.send(this.http, "POST", "/api/shares", body);
2817
+ }
2818
+ async list() {
2819
+ const res = await this.send(this.http, "GET", "/api/shares");
2820
+ return res.shares ?? [];
2821
+ }
2822
+ info(spaceId) {
2823
+ return this.send(this.http, "GET", `/api/shares/${enc$1(spaceId)}`);
2824
+ }
2825
+ update(spaceId, patch) {
2826
+ return this.send(this.http, "PATCH", `/api/shares/${enc$1(spaceId)}`, patch);
2827
+ }
2828
+ /** A public share's name, owner and password salt, read before admission. Publishable key only; never the verifier. */
2829
+ publicInfo(spaceId) {
2830
+ return this.send(this.keyOnlyHttp, "GET", `/api/shares/${enc$1(spaceId)}/public`);
2831
+ }
2832
+ /**
2833
+ * Admit the signed-in account to a public share by proving its password. Afterwards the account is a member:
2834
+ * it sends its own `/keyring/join-request`. Re-admitting the same account only updates its name.
2835
+ */
2836
+ async admit(spaceId, body) {
2837
+ await this.send(this.http, "POST", `/api/shares/${enc$1(spaceId)}/admit`, body);
2838
+ }
2839
+ async removeMember(spaceId, username) {
2840
+ await this.send(this.http, "DELETE", `/api/shares/${enc$1(spaceId)}/members/${enc$1(username)}`);
2841
+ }
2842
+ /** Rotate: `from` is the old share, `newSpaceId` the Space the client made and seeded. */
2843
+ adopt(newSpaceId, body) {
2844
+ return this.send(this.http, "POST", `/api/shares/${enc$1(newSpaceId)}/adopt`, body);
2845
+ }
2846
+ async send(http, method, path, body) {
2847
+ const init = { method };
2848
+ if (body !== undefined) {
2849
+ init.headers = { "Content-Type": "application/json" };
2850
+ init.body = JSON.stringify(body);
2851
+ }
2852
+ const res = await http.fetchWithRecovery(`${http.baseUrl}${path}`, init);
2853
+ let parsed = null;
2854
+ try {
2855
+ parsed = await res.json();
2856
+ }
2857
+ catch {
2858
+ // Non-JSON body: fall through with null.
2859
+ }
2860
+ if (res.ok)
2861
+ return parsed;
2862
+ const retry = Number(res.headers.get("Retry-After"));
2863
+ const typed = shareErrorFrom(res.status, parsed, Number.isFinite(retry) && retry > 0 ? retry : undefined);
2864
+ if (typed)
2865
+ throw typed;
2866
+ const msg = parsed && typeof parsed === "object" && "error" in parsed
2867
+ ? String(parsed.error)
2868
+ : `${res.status} ${res.statusText}`;
2869
+ throw paymentRequiredFrom(res.status, parsed) ?? new HttpError(msg, res.status, parsed);
2870
+ }
2871
+ }
2872
+ /** A path segment. Space ids are `[A-Za-z0-9_-]` so this is a no-op for them; usernames may need it. */
2873
+ function enc$1(segment) {
2874
+ return encodeURIComponent(segment);
2875
+ }
2876
+
2877
+ const SHARE_PASSWORD_ITERATIONS = 310_000;
2878
+ const enc = new TextEncoder();
2879
+ function b64(bytes) {
2880
+ let s = "";
2881
+ for (let i = 0; i < bytes.length; i++)
2882
+ s += String.fromCharCode(bytes[i]);
2883
+ return btoa(s);
2884
+ }
2885
+ function unb64(s) {
2886
+ const bin = atob(s);
2887
+ const out = new Uint8Array(bin.length);
2888
+ for (let i = 0; i < bin.length; i++)
2889
+ out[i] = bin.charCodeAt(i);
2890
+ return out;
2891
+ }
2892
+ const MIN_ITERATIONS = 100_000;
2893
+ const MAX_ITERATIONS = 2_000_000;
2894
+ async function proofBytes(password, salt, iterations) {
2895
+ if (!Number.isInteger(iterations) || iterations < MIN_ITERATIONS || iterations > MAX_ITERATIONS) {
2896
+ throw new Error(`Share password iterations must be between ${MIN_ITERATIONS} and ${MAX_ITERATIONS}`);
2897
+ }
2898
+ const key = await crypto.subtle.importKey("raw", enc.encode(password.normalize("NFC")), { name: "PBKDF2" }, false, [
2899
+ "deriveBits",
2900
+ ]);
2901
+ const bits = await crypto.subtle.deriveBits({ name: "PBKDF2", hash: "SHA-256", salt: enc.encode(salt), iterations }, key, 256);
2902
+ return new Uint8Array(bits);
2903
+ }
2904
+ /** What a guest sends to prove it knows the password. */
2905
+ async function passwordProof(password, salt, iterations) {
2906
+ return b64(await proofBytes(password, salt, iterations));
2907
+ }
2908
+ /** What the share owner registers at creation: a fresh salt and the verifier for `password`. */
2909
+ async function newPasswordVerifier(password) {
2910
+ const salt = b64(crypto.getRandomValues(new Uint8Array(16)));
2911
+ const iterations = SHARE_PASSWORD_ITERATIONS;
2912
+ const proof = await passwordProof(password, salt, iterations);
2913
+ const digest = new Uint8Array(await crypto.subtle.digest("SHA-256", unb64(proof)));
2914
+ return { salt, iterations, verifier: b64(digest) };
2915
+ }
2592
2916
 
2593
2917
  function _loadWasmModule (sync, filepath, src, imports) {
2594
2918
  function _instantiateOrCompile(source, imports, stream) {
@@ -2876,5 +3200,5 @@ function alloc(u32, size) {
2876
3200
  return ptr;
2877
3201
  }
2878
3202
 
2879
- export { AES_GCM_IV_BYTES, AES_GCM_KEY_BYTES, AES_GCM_TAG_BYTES, BroadcastChannel, BroadcastChannelEvents, ChunkCipher, DoubleRatchet, EncryptedSession, EventCore, EventCoreEvents, KeyStore, Message, Message as MessageDefault, PBKDF2_DEFAULT_ITERATIONS, PREIMAGE_POK_VERIFICATION_KEY, Packet, PaymentRequiredError, SerializeMessage, WSTransport, decorators, decryptAesGcm, deriveAesKeyFromPassphrase, deriveBitsHkdf, encryptAesGcm, getSubtle, initBn128Wasm, randomBytes, unwrapWithPassphrase, verifyGroth16, wrapWithPassphrase };
3203
+ export { AES_GCM_IV_BYTES, AES_GCM_KEY_BYTES, AES_GCM_TAG_BYTES, BroadcastChannel, BroadcastChannelEvents, ChunkCipher, DoubleRatchet, EncryptedSession, EventCore, EventCoreEvents, GuestLoginConflictError, InvalidRecoveryCodeError, KeyStore, Message, Message as MessageDefault, PBKDF2_DEFAULT_ITERATIONS, PREIMAGE_POK_VERIFICATION_KEY, Packet, PaymentRequiredError, RotationInProgressError, RotationIncompleteError, RotationMismatchError, SHARE_PASSWORD_ITERATIONS, SerializeMessage, ShareClosedError, ShareFullError, ShareMemberLimitError, SharePasswordError, SharePasswordRateError, ShareSpaceNotEmptyError, ShareSpaceNotReadyError, SharesClient, WSTransport, decorators, decryptAesGcm, deriveAesKeyFromPassphrase, deriveBitsHkdf, encryptAesGcm, getSubtle, initBn128Wasm, newPasswordVerifier, passwordProof, randomBytes, shareErrorFrom, unwrapWithPassphrase, verifyGroth16, wrapWithPassphrase };
2880
3204
  //# sourceMappingURL=index.js.map