@abraca/resend 2.34.0 → 2.35.1

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.
@@ -1,15 +1,10 @@
1
1
  #!/usr/bin/env node
2
- import { AbracadabraClient, AbracadabraProvider, Kind, SERVER_ROOT_ID, WebSocketStatus, makeEntryMap, patchEntry, toPlain } from "@abraca/dabra";
3
- import * as Y from "yjs";
2
+ import { AbracadabraClient, Kind, SERVER_ROOT_ID, WebSocketStatus, loadOrCreateKeyFile, loginOrRegisterWithKey, makeChallengeSigner, makeEntryMap, openSyncedProvider, patchEntry, readEntries, toPlain, waitForSync } from "@abraca/dabra";
4
3
  import { populateYDocFromMarkdown, yjsToHtml } from "@abraca/convert";
5
4
  import { createHmac, timingSafeEqual } from "node:crypto";
6
5
  import { createServer } from "node:http";
7
6
  import { Resend } from "resend";
8
- import * as ed from "@noble/ed25519";
9
- import { existsSync } from "node:fs";
10
- import { mkdir, readFile, writeFile } from "node:fs/promises";
11
- import { homedir } from "node:os";
12
- import { dirname, join } from "node:path";
7
+ import "yjs";
13
8
 
14
9
  //#region packages/resend/src/bootstrap.ts
15
10
  /**
@@ -27,22 +22,6 @@ const OUTBOX_COLUMNS = [
27
22
  "Sent",
28
23
  "Failed"
29
24
  ];
30
- function readEntries(treeMap, selfId) {
31
- const entries = [];
32
- treeMap.forEach((raw, id) => {
33
- if (selfId && id === selfId) return;
34
- const value = toPlain(raw);
35
- if (typeof value !== "object" || value === null) return;
36
- entries.push({
37
- id,
38
- label: typeof value.label === "string" ? value.label : "Untitled",
39
- parentId: value.parentId ?? null,
40
- order: typeof value.order === "number" ? value.order : 0,
41
- type: typeof value.type === "string" ? value.type : void 0
42
- });
43
- });
44
- return entries;
45
- }
46
25
  async function createDoc(server, opts) {
47
26
  const treeMap = server.getTreeMap();
48
27
  const rootDoc = server.rootDocument;
@@ -127,31 +106,6 @@ async function bootstrap(server) {
127
106
  };
128
107
  }
129
108
 
130
- //#endregion
131
- //#region packages/resend/src/utils.ts
132
- /**
133
- * Wait for a provider's `synced` event with a timeout.
134
- *
135
- * The `isSynced` short-circuit is load-bearing: providers that already synced
136
- * (e.g. cached child providers returned from `loadChild`) won't re-emit
137
- * `synced`, so without the short-circuit every later op on that doc times out.
138
- */
139
- function waitForSync(provider, timeoutMs = 15e3) {
140
- if (provider.isSynced) return Promise.resolve();
141
- return new Promise((resolve, reject) => {
142
- const timer = setTimeout(() => {
143
- provider.off("synced", handler);
144
- reject(/* @__PURE__ */ new Error(`Sync timed out after ${timeoutMs}ms`));
145
- }, timeoutMs);
146
- function handler() {
147
- clearTimeout(timer);
148
- provider.off("synced", handler);
149
- resolve();
150
- }
151
- provider.on("synced", handler);
152
- });
153
- }
154
-
155
109
  //#endregion
156
110
  //#region packages/resend/src/inbound-server.ts
157
111
  /**
@@ -731,636 +685,6 @@ var ResendClient = class {
731
685
  }
732
686
  };
733
687
 
734
- //#endregion
735
- //#region node_modules/@noble/hashes/utils.js
736
- /**
737
- * Checks if something is Uint8Array. Be careful: nodejs Buffer will return true.
738
- * @param a - value to test
739
- * @returns `true` when the value is a Uint8Array-compatible view.
740
- * @example
741
- * Check whether a value is a Uint8Array-compatible view.
742
- * ```ts
743
- * isBytes(new Uint8Array([1, 2, 3]));
744
- * ```
745
- */
746
- function isBytes(a) {
747
- return a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array" && "BYTES_PER_ELEMENT" in a && a.BYTES_PER_ELEMENT === 1;
748
- }
749
- /**
750
- * Asserts something is Uint8Array.
751
- * @param value - value to validate
752
- * @param length - optional exact length constraint
753
- * @param title - label included in thrown errors
754
- * @returns The validated byte array.
755
- * @throws On wrong argument types. {@link TypeError}
756
- * @throws On wrong argument ranges or values. {@link RangeError}
757
- * @example
758
- * Validate that a value is a byte array.
759
- * ```ts
760
- * abytes(new Uint8Array([1, 2, 3]));
761
- * ```
762
- */
763
- function abytes(value, length, title = "") {
764
- const bytes = isBytes(value);
765
- const len = value?.length;
766
- const needsLen = length !== void 0;
767
- if (!bytes || needsLen && len !== length) {
768
- const prefix = title && `"${title}" `;
769
- const ofLen = needsLen ? ` of length ${length}` : "";
770
- const got = bytes ? `length=${len}` : `type=${typeof value}`;
771
- const message = prefix + "expected Uint8Array" + ofLen + ", got " + got;
772
- if (!bytes) throw new TypeError(message);
773
- throw new RangeError(message);
774
- }
775
- return value;
776
- }
777
- /**
778
- * Asserts a hash instance has not been destroyed or finished.
779
- * @param instance - hash instance to validate
780
- * @param checkFinished - whether to reject finalized instances
781
- * @throws If the hash instance has already been destroyed or finalized. {@link Error}
782
- * @example
783
- * Validate that a hash instance is still usable.
784
- * ```ts
785
- * import { aexists } from '@noble/hashes/utils.js';
786
- * import { sha256 } from '@noble/hashes/sha2.js';
787
- * const hash = sha256.create();
788
- * aexists(hash);
789
- * ```
790
- */
791
- function aexists(instance, checkFinished = true) {
792
- if (instance.destroyed) throw new Error("Hash instance has been destroyed");
793
- if (checkFinished && instance.finished) throw new Error("Hash#digest() has already been called");
794
- }
795
- /**
796
- * Asserts output is a sufficiently-sized byte array.
797
- * @param out - destination buffer
798
- * @param instance - hash instance providing output length
799
- * Oversized buffers are allowed; downstream code only promises to fill the first `outputLen` bytes.
800
- * @throws On wrong argument types. {@link TypeError}
801
- * @throws On wrong argument ranges or values. {@link RangeError}
802
- * @example
803
- * Validate a caller-provided digest buffer.
804
- * ```ts
805
- * import { aoutput } from '@noble/hashes/utils.js';
806
- * import { sha256 } from '@noble/hashes/sha2.js';
807
- * const hash = sha256.create();
808
- * aoutput(new Uint8Array(hash.outputLen), hash);
809
- * ```
810
- */
811
- function aoutput(out, instance) {
812
- abytes(out, void 0, "digestInto() output");
813
- const min = instance.outputLen;
814
- if (out.length < min) throw new RangeError("\"digestInto() output\" expected to be of length >=" + min);
815
- }
816
- /**
817
- * Zeroizes typed arrays in place. Warning: JS provides no guarantees.
818
- * @param arrays - arrays to overwrite with zeros
819
- * @example
820
- * Zeroize sensitive buffers in place.
821
- * ```ts
822
- * clean(new Uint8Array([1, 2, 3]));
823
- * ```
824
- */
825
- function clean(...arrays) {
826
- for (let i = 0; i < arrays.length; i++) arrays[i].fill(0);
827
- }
828
- /**
829
- * Creates a DataView for byte-level manipulation.
830
- * @param arr - source typed array
831
- * @returns DataView over the same buffer region.
832
- * @example
833
- * Create a DataView over an existing buffer.
834
- * ```ts
835
- * createView(new Uint8Array(4));
836
- * ```
837
- */
838
- function createView(arr) {
839
- return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);
840
- }
841
- /** Whether the current platform is little-endian. */
842
- const isLE = new Uint8Array(new Uint32Array([287454020]).buffer)[0] === 68;
843
- const hasHexBuiltin = typeof Uint8Array.from([]).toHex === "function" && typeof Uint8Array.fromHex === "function";
844
- /**
845
- * Creates a callable hash function from a stateful class constructor.
846
- * @param hashCons - hash constructor or factory
847
- * @param info - optional metadata such as DER OID
848
- * @returns Frozen callable hash wrapper with `.create()`.
849
- * Wrapper construction eagerly calls `hashCons(undefined)` once to read
850
- * `outputLen` / `blockLen`, so constructor side effects happen at module
851
- * init time.
852
- * @example
853
- * Wrap a stateful hash constructor into a callable helper.
854
- * ```ts
855
- * import { createHasher } from '@noble/hashes/utils.js';
856
- * import { sha256 } from '@noble/hashes/sha2.js';
857
- * const wrapped = createHasher(sha256.create, { oid: sha256.oid });
858
- * wrapped(new Uint8Array([1]));
859
- * ```
860
- */
861
- function createHasher(hashCons, info = {}) {
862
- const hashC = (msg, opts) => hashCons(opts).update(msg).digest();
863
- const tmp = hashCons(void 0);
864
- hashC.outputLen = tmp.outputLen;
865
- hashC.blockLen = tmp.blockLen;
866
- hashC.canXOF = tmp.canXOF;
867
- hashC.create = (opts) => hashCons(opts);
868
- Object.assign(hashC, info);
869
- return Object.freeze(hashC);
870
- }
871
- /**
872
- * Creates OID metadata for NIST hashes with prefix `06 09 60 86 48 01 65 03 04 02`.
873
- * @param suffix - final OID byte for the selected hash.
874
- * The helper accepts any byte even though only the documented NIST hash
875
- * suffixes are meaningful downstream.
876
- * @returns Object containing the DER-encoded OID.
877
- * @example
878
- * Build OID metadata for a NIST hash.
879
- * ```ts
880
- * oidNist(0x01);
881
- * ```
882
- */
883
- const oidNist = (suffix) => ({ oid: Uint8Array.from([
884
- 6,
885
- 9,
886
- 96,
887
- 134,
888
- 72,
889
- 1,
890
- 101,
891
- 3,
892
- 4,
893
- 2,
894
- suffix
895
- ]) });
896
-
897
- //#endregion
898
- //#region node_modules/@noble/hashes/_md.js
899
- /**
900
- * Internal Merkle-Damgard hash utils.
901
- * @module
902
- */
903
- /**
904
- * Merkle-Damgard hash construction base class.
905
- * Could be used to create MD5, RIPEMD, SHA1, SHA2.
906
- * Accepts only byte-aligned `Uint8Array` input, even when the underlying spec describes bit
907
- * strings with partial-byte tails.
908
- * @param blockLen - internal block size in bytes
909
- * @param outputLen - digest size in bytes
910
- * @param padOffset - trailing length field size in bytes
911
- * @param isLE - whether length and state words are encoded in little-endian
912
- * @example
913
- * Use a concrete subclass to get the shared Merkle-Damgard update/digest flow.
914
- * ```ts
915
- * import { _SHA1 } from '@noble/hashes/legacy.js';
916
- * const hash = new _SHA1();
917
- * hash.update(new Uint8Array([97, 98, 99]));
918
- * hash.digest();
919
- * ```
920
- */
921
- var HashMD = class {
922
- blockLen;
923
- outputLen;
924
- canXOF = false;
925
- padOffset;
926
- isLE;
927
- buffer;
928
- view;
929
- finished = false;
930
- length = 0;
931
- pos = 0;
932
- destroyed = false;
933
- constructor(blockLen, outputLen, padOffset, isLE) {
934
- this.blockLen = blockLen;
935
- this.outputLen = outputLen;
936
- this.padOffset = padOffset;
937
- this.isLE = isLE;
938
- this.buffer = new Uint8Array(blockLen);
939
- this.view = createView(this.buffer);
940
- }
941
- update(data) {
942
- aexists(this);
943
- abytes(data);
944
- const { view, buffer, blockLen } = this;
945
- const len = data.length;
946
- for (let pos = 0; pos < len;) {
947
- const take = Math.min(blockLen - this.pos, len - pos);
948
- if (take === blockLen) {
949
- const dataView = createView(data);
950
- for (; blockLen <= len - pos; pos += blockLen) this.process(dataView, pos);
951
- continue;
952
- }
953
- buffer.set(data.subarray(pos, pos + take), this.pos);
954
- this.pos += take;
955
- pos += take;
956
- if (this.pos === blockLen) {
957
- this.process(view, 0);
958
- this.pos = 0;
959
- }
960
- }
961
- this.length += data.length;
962
- this.roundClean();
963
- return this;
964
- }
965
- digestInto(out) {
966
- aexists(this);
967
- aoutput(out, this);
968
- this.finished = true;
969
- const { buffer, view, blockLen, isLE } = this;
970
- let { pos } = this;
971
- buffer[pos++] = 128;
972
- clean(this.buffer.subarray(pos));
973
- if (this.padOffset > blockLen - pos) {
974
- this.process(view, 0);
975
- pos = 0;
976
- }
977
- for (let i = pos; i < blockLen; i++) buffer[i] = 0;
978
- view.setBigUint64(blockLen - 8, BigInt(this.length * 8), isLE);
979
- this.process(view, 0);
980
- const oview = createView(out);
981
- const len = this.outputLen;
982
- if (len % 4) throw new Error("_sha2: outputLen must be aligned to 32bit");
983
- const outLen = len / 4;
984
- const state = this.get();
985
- if (outLen > state.length) throw new Error("_sha2: outputLen bigger than state");
986
- for (let i = 0; i < outLen; i++) oview.setUint32(4 * i, state[i], isLE);
987
- }
988
- digest() {
989
- const { buffer, outputLen } = this;
990
- this.digestInto(buffer);
991
- const res = buffer.slice(0, outputLen);
992
- this.destroy();
993
- return res;
994
- }
995
- _cloneInto(to) {
996
- to ||= new this.constructor();
997
- to.set(...this.get());
998
- const { blockLen, buffer, length, finished, destroyed, pos } = this;
999
- to.destroyed = destroyed;
1000
- to.finished = finished;
1001
- to.length = length;
1002
- to.pos = pos;
1003
- if (length % blockLen) to.buffer.set(buffer);
1004
- return to;
1005
- }
1006
- clone() {
1007
- return this._cloneInto();
1008
- }
1009
- };
1010
- /** Initial SHA512 state from RFC 6234 §6.3: eight RFC 64-bit `H(0)` words stored as sixteen
1011
- * big-endian 32-bit halves. Derived from the fractional parts of the square roots of the first
1012
- * eight prime numbers. Exported as a shared table; callers must treat it as read-only because
1013
- * constructors copy halves from it by index. */
1014
- const SHA512_IV = /* @__PURE__ */ Uint32Array.from([
1015
- 1779033703,
1016
- 4089235720,
1017
- 3144134277,
1018
- 2227873595,
1019
- 1013904242,
1020
- 4271175723,
1021
- 2773480762,
1022
- 1595750129,
1023
- 1359893119,
1024
- 2917565137,
1025
- 2600822924,
1026
- 725511199,
1027
- 528734635,
1028
- 4215389547,
1029
- 1541459225,
1030
- 327033209
1031
- ]);
1032
-
1033
- //#endregion
1034
- //#region node_modules/@noble/hashes/_u64.js
1035
- const U32_MASK64 = /* @__PURE__ */ BigInt(2 ** 32 - 1);
1036
- const _32n = /* @__PURE__ */ BigInt(32);
1037
- function fromBig(n, le = false) {
1038
- if (le) return {
1039
- h: Number(n & U32_MASK64),
1040
- l: Number(n >> _32n & U32_MASK64)
1041
- };
1042
- return {
1043
- h: Number(n >> _32n & U32_MASK64) | 0,
1044
- l: Number(n & U32_MASK64) | 0
1045
- };
1046
- }
1047
- function split(lst, le = false) {
1048
- const len = lst.length;
1049
- let Ah = new Uint32Array(len);
1050
- let Al = new Uint32Array(len);
1051
- for (let i = 0; i < len; i++) {
1052
- const { h, l } = fromBig(lst[i], le);
1053
- [Ah[i], Al[i]] = [h, l];
1054
- }
1055
- return [Ah, Al];
1056
- }
1057
- const shrSH = (h, _l, s) => h >>> s;
1058
- const shrSL = (h, l, s) => h << 32 - s | l >>> s;
1059
- const rotrSH = (h, l, s) => h >>> s | l << 32 - s;
1060
- const rotrSL = (h, l, s) => h << 32 - s | l >>> s;
1061
- const rotrBH = (h, l, s) => h << 64 - s | l >>> s - 32;
1062
- const rotrBL = (h, l, s) => h >>> s - 32 | l << 64 - s;
1063
- function add(Ah, Al, Bh, Bl) {
1064
- const l = (Al >>> 0) + (Bl >>> 0);
1065
- return {
1066
- h: Ah + Bh + (l / 2 ** 32 | 0) | 0,
1067
- l: l | 0
1068
- };
1069
- }
1070
- const add3L = (Al, Bl, Cl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0);
1071
- const add3H = (low, Ah, Bh, Ch) => Ah + Bh + Ch + (low / 2 ** 32 | 0) | 0;
1072
- const add4L = (Al, Bl, Cl, Dl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0);
1073
- const add4H = (low, Ah, Bh, Ch, Dh) => Ah + Bh + Ch + Dh + (low / 2 ** 32 | 0) | 0;
1074
- const add5L = (Al, Bl, Cl, Dl, El) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0);
1075
- const add5H = (low, Ah, Bh, Ch, Dh, Eh) => Ah + Bh + Ch + Dh + Eh + (low / 2 ** 32 | 0) | 0;
1076
-
1077
- //#endregion
1078
- //#region node_modules/@noble/hashes/sha2.js
1079
- /**
1080
- * SHA2 hash function. A.k.a. sha256, sha384, sha512, sha512_224, sha512_256.
1081
- * SHA256 is the fastest hash implementable in JS, even faster than Blake3.
1082
- * Check out {@link https://www.rfc-editor.org/rfc/rfc4634 | RFC 4634} and
1083
- * {@link https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf | FIPS 180-4}.
1084
- * @module
1085
- */
1086
- const K512 = split([
1087
- "0x428a2f98d728ae22",
1088
- "0x7137449123ef65cd",
1089
- "0xb5c0fbcfec4d3b2f",
1090
- "0xe9b5dba58189dbbc",
1091
- "0x3956c25bf348b538",
1092
- "0x59f111f1b605d019",
1093
- "0x923f82a4af194f9b",
1094
- "0xab1c5ed5da6d8118",
1095
- "0xd807aa98a3030242",
1096
- "0x12835b0145706fbe",
1097
- "0x243185be4ee4b28c",
1098
- "0x550c7dc3d5ffb4e2",
1099
- "0x72be5d74f27b896f",
1100
- "0x80deb1fe3b1696b1",
1101
- "0x9bdc06a725c71235",
1102
- "0xc19bf174cf692694",
1103
- "0xe49b69c19ef14ad2",
1104
- "0xefbe4786384f25e3",
1105
- "0x0fc19dc68b8cd5b5",
1106
- "0x240ca1cc77ac9c65",
1107
- "0x2de92c6f592b0275",
1108
- "0x4a7484aa6ea6e483",
1109
- "0x5cb0a9dcbd41fbd4",
1110
- "0x76f988da831153b5",
1111
- "0x983e5152ee66dfab",
1112
- "0xa831c66d2db43210",
1113
- "0xb00327c898fb213f",
1114
- "0xbf597fc7beef0ee4",
1115
- "0xc6e00bf33da88fc2",
1116
- "0xd5a79147930aa725",
1117
- "0x06ca6351e003826f",
1118
- "0x142929670a0e6e70",
1119
- "0x27b70a8546d22ffc",
1120
- "0x2e1b21385c26c926",
1121
- "0x4d2c6dfc5ac42aed",
1122
- "0x53380d139d95b3df",
1123
- "0x650a73548baf63de",
1124
- "0x766a0abb3c77b2a8",
1125
- "0x81c2c92e47edaee6",
1126
- "0x92722c851482353b",
1127
- "0xa2bfe8a14cf10364",
1128
- "0xa81a664bbc423001",
1129
- "0xc24b8b70d0f89791",
1130
- "0xc76c51a30654be30",
1131
- "0xd192e819d6ef5218",
1132
- "0xd69906245565a910",
1133
- "0xf40e35855771202a",
1134
- "0x106aa07032bbd1b8",
1135
- "0x19a4c116b8d2d0c8",
1136
- "0x1e376c085141ab53",
1137
- "0x2748774cdf8eeb99",
1138
- "0x34b0bcb5e19b48a8",
1139
- "0x391c0cb3c5c95a63",
1140
- "0x4ed8aa4ae3418acb",
1141
- "0x5b9cca4f7763e373",
1142
- "0x682e6ff3d6b2b8a3",
1143
- "0x748f82ee5defb2fc",
1144
- "0x78a5636f43172f60",
1145
- "0x84c87814a1f0ab72",
1146
- "0x8cc702081a6439ec",
1147
- "0x90befffa23631e28",
1148
- "0xa4506cebde82bde9",
1149
- "0xbef9a3f7b2c67915",
1150
- "0xc67178f2e372532b",
1151
- "0xca273eceea26619c",
1152
- "0xd186b8c721c0c207",
1153
- "0xeada7dd6cde0eb1e",
1154
- "0xf57d4f7fee6ed178",
1155
- "0x06f067aa72176fba",
1156
- "0x0a637dc5a2c898a6",
1157
- "0x113f9804bef90dae",
1158
- "0x1b710b35131c471b",
1159
- "0x28db77f523047d84",
1160
- "0x32caab7b40c72493",
1161
- "0x3c9ebe0a15c9bebc",
1162
- "0x431d67c49c100d4c",
1163
- "0x4cc5d4becb3e42b6",
1164
- "0x597f299cfc657e2a",
1165
- "0x5fcb6fab3ad6faec",
1166
- "0x6c44198c4a475817"
1167
- ].map((n) => BigInt(n)));
1168
- const SHA512_Kh = K512[0];
1169
- const SHA512_Kl = K512[1];
1170
- const SHA512_W_H = /* @__PURE__ */ new Uint32Array(80);
1171
- const SHA512_W_L = /* @__PURE__ */ new Uint32Array(80);
1172
- /** Internal SHA-384 / SHA-512 compression engine from RFC 6234 §6.4. */
1173
- var SHA2_64B = class extends HashMD {
1174
- constructor(outputLen) {
1175
- super(128, outputLen, 16, false);
1176
- }
1177
- get() {
1178
- const { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;
1179
- return [
1180
- Ah,
1181
- Al,
1182
- Bh,
1183
- Bl,
1184
- Ch,
1185
- Cl,
1186
- Dh,
1187
- Dl,
1188
- Eh,
1189
- El,
1190
- Fh,
1191
- Fl,
1192
- Gh,
1193
- Gl,
1194
- Hh,
1195
- Hl
1196
- ];
1197
- }
1198
- set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl) {
1199
- this.Ah = Ah | 0;
1200
- this.Al = Al | 0;
1201
- this.Bh = Bh | 0;
1202
- this.Bl = Bl | 0;
1203
- this.Ch = Ch | 0;
1204
- this.Cl = Cl | 0;
1205
- this.Dh = Dh | 0;
1206
- this.Dl = Dl | 0;
1207
- this.Eh = Eh | 0;
1208
- this.El = El | 0;
1209
- this.Fh = Fh | 0;
1210
- this.Fl = Fl | 0;
1211
- this.Gh = Gh | 0;
1212
- this.Gl = Gl | 0;
1213
- this.Hh = Hh | 0;
1214
- this.Hl = Hl | 0;
1215
- }
1216
- process(view, offset) {
1217
- for (let i = 0; i < 16; i++, offset += 4) {
1218
- SHA512_W_H[i] = view.getUint32(offset);
1219
- SHA512_W_L[i] = view.getUint32(offset += 4);
1220
- }
1221
- for (let i = 16; i < 80; i++) {
1222
- const W15h = SHA512_W_H[i - 15] | 0;
1223
- const W15l = SHA512_W_L[i - 15] | 0;
1224
- const s0h = rotrSH(W15h, W15l, 1) ^ rotrSH(W15h, W15l, 8) ^ shrSH(W15h, W15l, 7);
1225
- const s0l = rotrSL(W15h, W15l, 1) ^ rotrSL(W15h, W15l, 8) ^ shrSL(W15h, W15l, 7);
1226
- const W2h = SHA512_W_H[i - 2] | 0;
1227
- const W2l = SHA512_W_L[i - 2] | 0;
1228
- const s1h = rotrSH(W2h, W2l, 19) ^ rotrBH(W2h, W2l, 61) ^ shrSH(W2h, W2l, 6);
1229
- const s1l = rotrSL(W2h, W2l, 19) ^ rotrBL(W2h, W2l, 61) ^ shrSL(W2h, W2l, 6);
1230
- const SUMl = add4L(s0l, s1l, SHA512_W_L[i - 7], SHA512_W_L[i - 16]);
1231
- SHA512_W_H[i] = add4H(SUMl, s0h, s1h, SHA512_W_H[i - 7], SHA512_W_H[i - 16]) | 0;
1232
- SHA512_W_L[i] = SUMl | 0;
1233
- }
1234
- let { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;
1235
- for (let i = 0; i < 80; i++) {
1236
- const sigma1h = rotrSH(Eh, El, 14) ^ rotrSH(Eh, El, 18) ^ rotrBH(Eh, El, 41);
1237
- const sigma1l = rotrSL(Eh, El, 14) ^ rotrSL(Eh, El, 18) ^ rotrBL(Eh, El, 41);
1238
- const CHIh = Eh & Fh ^ ~Eh & Gh;
1239
- const CHIl = El & Fl ^ ~El & Gl;
1240
- const T1ll = add5L(Hl, sigma1l, CHIl, SHA512_Kl[i], SHA512_W_L[i]);
1241
- const T1h = add5H(T1ll, Hh, sigma1h, CHIh, SHA512_Kh[i], SHA512_W_H[i]);
1242
- const T1l = T1ll | 0;
1243
- const sigma0h = rotrSH(Ah, Al, 28) ^ rotrBH(Ah, Al, 34) ^ rotrBH(Ah, Al, 39);
1244
- const sigma0l = rotrSL(Ah, Al, 28) ^ rotrBL(Ah, Al, 34) ^ rotrBL(Ah, Al, 39);
1245
- const MAJh = Ah & Bh ^ Ah & Ch ^ Bh & Ch;
1246
- const MAJl = Al & Bl ^ Al & Cl ^ Bl & Cl;
1247
- Hh = Gh | 0;
1248
- Hl = Gl | 0;
1249
- Gh = Fh | 0;
1250
- Gl = Fl | 0;
1251
- Fh = Eh | 0;
1252
- Fl = El | 0;
1253
- ({h: Eh, l: El} = add(Dh | 0, Dl | 0, T1h | 0, T1l | 0));
1254
- Dh = Ch | 0;
1255
- Dl = Cl | 0;
1256
- Ch = Bh | 0;
1257
- Cl = Bl | 0;
1258
- Bh = Ah | 0;
1259
- Bl = Al | 0;
1260
- const All = add3L(T1l, sigma0l, MAJl);
1261
- Ah = add3H(All, T1h, sigma0h, MAJh);
1262
- Al = All | 0;
1263
- }
1264
- ({h: Ah, l: Al} = add(this.Ah | 0, this.Al | 0, Ah | 0, Al | 0));
1265
- ({h: Bh, l: Bl} = add(this.Bh | 0, this.Bl | 0, Bh | 0, Bl | 0));
1266
- ({h: Ch, l: Cl} = add(this.Ch | 0, this.Cl | 0, Ch | 0, Cl | 0));
1267
- ({h: Dh, l: Dl} = add(this.Dh | 0, this.Dl | 0, Dh | 0, Dl | 0));
1268
- ({h: Eh, l: El} = add(this.Eh | 0, this.El | 0, Eh | 0, El | 0));
1269
- ({h: Fh, l: Fl} = add(this.Fh | 0, this.Fl | 0, Fh | 0, Fl | 0));
1270
- ({h: Gh, l: Gl} = add(this.Gh | 0, this.Gl | 0, Gh | 0, Gl | 0));
1271
- ({h: Hh, l: Hl} = add(this.Hh | 0, this.Hl | 0, Hh | 0, Hl | 0));
1272
- this.set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl);
1273
- }
1274
- roundClean() {
1275
- clean(SHA512_W_H, SHA512_W_L);
1276
- }
1277
- destroy() {
1278
- this.destroyed = true;
1279
- clean(this.buffer);
1280
- this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
1281
- }
1282
- };
1283
- /** Internal SHA-512 hash class grounded in RFC 6234 §6.3 and §6.4. */
1284
- var _SHA512 = class extends SHA2_64B {
1285
- Ah = SHA512_IV[0] | 0;
1286
- Al = SHA512_IV[1] | 0;
1287
- Bh = SHA512_IV[2] | 0;
1288
- Bl = SHA512_IV[3] | 0;
1289
- Ch = SHA512_IV[4] | 0;
1290
- Cl = SHA512_IV[5] | 0;
1291
- Dh = SHA512_IV[6] | 0;
1292
- Dl = SHA512_IV[7] | 0;
1293
- Eh = SHA512_IV[8] | 0;
1294
- El = SHA512_IV[9] | 0;
1295
- Fh = SHA512_IV[10] | 0;
1296
- Fl = SHA512_IV[11] | 0;
1297
- Gh = SHA512_IV[12] | 0;
1298
- Gl = SHA512_IV[13] | 0;
1299
- Hh = SHA512_IV[14] | 0;
1300
- Hl = SHA512_IV[15] | 0;
1301
- constructor() {
1302
- super(64);
1303
- }
1304
- };
1305
- /**
1306
- * SHA2-512 hash function from RFC 4634.
1307
- * @param msg - message bytes to hash
1308
- * @returns Digest bytes.
1309
- * @example
1310
- * Hash a message with SHA2-512.
1311
- * ```ts
1312
- * sha512(new Uint8Array([97, 98, 99]));
1313
- * ```
1314
- */
1315
- const sha512 = /* @__PURE__ */ createHasher(() => new _SHA512(), /* @__PURE__ */ oidNist(3));
1316
-
1317
- //#endregion
1318
- //#region packages/resend/src/crypto.ts
1319
- /**
1320
- * Ed25519 key generation, persistence, and challenge signing for the Resend bridge.
1321
- * Same shape as @abraca/mcp's crypto module; intentionally vendored so this package
1322
- * doesn't depend on @abraca/mcp.
1323
- */
1324
- ed.hashes.sha512 = sha512;
1325
- ed.hashes.sha512Async = (m) => Promise.resolve(sha512(m));
1326
- const DEFAULT_KEY_PATH = join(homedir(), ".abracadabra", "resend.key");
1327
- function toBase64url(bytes) {
1328
- return Buffer.from(bytes).toString("base64url");
1329
- }
1330
- function fromBase64url(b64) {
1331
- return new Uint8Array(Buffer.from(b64, "base64url"));
1332
- }
1333
- async function loadOrCreateKeypair(keyPath) {
1334
- const path = keyPath || DEFAULT_KEY_PATH;
1335
- if (existsSync(path)) {
1336
- const seed = await readFile(path);
1337
- if (seed.length !== 32) throw new Error(`Invalid key file at ${path}: expected 32 bytes, got ${seed.length}`);
1338
- const privateKey = new Uint8Array(seed);
1339
- return {
1340
- privateKey,
1341
- publicKeyB64: toBase64url(ed.getPublicKey(privateKey))
1342
- };
1343
- }
1344
- const privateKey = ed.utils.randomSecretKey();
1345
- const publicKey = ed.getPublicKey(privateKey);
1346
- const dir = dirname(path);
1347
- if (!existsSync(dir)) await mkdir(dir, {
1348
- recursive: true,
1349
- mode: 448
1350
- });
1351
- await writeFile(path, Buffer.from(privateKey), { mode: 384 });
1352
- console.error(`[abracadabra-resend] Generated new agent keypair at ${path}`);
1353
- console.error(`[abracadabra-resend] Public key: ${toBase64url(publicKey)}`);
1354
- return {
1355
- privateKey,
1356
- publicKeyB64: toBase64url(publicKey)
1357
- };
1358
- }
1359
- function signChallenge(challengeB64, privateKey) {
1360
- const challenge = fromBase64url(challengeB64);
1361
- return toBase64url(ed.sign(challenge, privateKey));
1362
- }
1363
-
1364
688
  //#endregion
1365
689
  //#region packages/resend/src/server.ts
1366
690
  const IDLE_TIMEOUT_MS = 300 * 1e3;
@@ -1404,26 +728,21 @@ var AbracadabraResendServer = class {
1404
728
  }
1405
729
  /** Authenticate, discover spaces, connect to the configured (or first) space. */
1406
730
  async connect() {
1407
- const keypair = await loadOrCreateKeypair(this.config.keyFile);
731
+ const keypair = await loadOrCreateKeyFile(this.config.keyFile, {
732
+ defaultFileName: "resend.key",
733
+ onCreate: ({ path, publicKeyB64 }) => {
734
+ console.error(`[abracadabra-resend] Generated new agent keypair at ${path}`);
735
+ console.error(`[abracadabra-resend] Public key: ${publicKeyB64}`);
736
+ }
737
+ });
1408
738
  this._userId = keypair.publicKeyB64;
1409
- const signFn = (challenge) => Promise.resolve(signChallenge(challenge, keypair.privateKey));
1410
- this._signFn = signFn;
1411
- try {
1412
- await this.client.loginWithKey(keypair.publicKeyB64, signFn);
1413
- } catch (err) {
1414
- const status = err?.status ?? err?.response?.status;
1415
- const msg = String(err?.message ?? "").toLowerCase();
1416
- if (!(status === 404 || status === 422 || status === 401 && /not registered|user not found|no such user/.test(msg))) throw err;
1417
- console.error("[abracadabra-resend] Key not registered, creating new account...");
1418
- await this.client.registerWithKey({
1419
- publicKey: keypair.publicKeyB64,
1420
- username: this.agentName.replace(/\s+/g, "-").toLowerCase(),
1421
- displayName: this.agentName,
1422
- deviceName: "Resend Bridge",
1423
- inviteCode: this.config.inviteCode
1424
- });
1425
- await this.client.loginWithKey(keypair.publicKeyB64, signFn);
1426
- }
739
+ this._signFn = makeChallengeSigner(keypair);
740
+ await loginOrRegisterWithKey(this.client, keypair, {
741
+ displayName: this.agentName,
742
+ deviceName: "Resend Bridge",
743
+ inviteCode: this.config.inviteCode,
744
+ onRegister: () => console.error("[abracadabra-resend] Key not registered, creating new account...")
745
+ });
1427
746
  console.error(`[abracadabra-resend] Authenticated as ${this.agentName} (pubkey=${keypair.publicKeyB64})`);
1428
747
  this._serverInfo = await this.client.serverInfo();
1429
748
  const roots = await this.client.listChildren();
@@ -1448,15 +767,10 @@ var AbracadabraResendServer = class {
1448
767
  console.error("[abracadabra-resend] JWT expired, re-authenticating...");
1449
768
  await this.client.loginWithKey(this._userId, this._signFn);
1450
769
  }
1451
- const doc = new Y.Doc({ guid: docId });
1452
- const provider = new AbracadabraProvider({
1453
- name: docId,
1454
- document: doc,
770
+ const { doc, provider } = await openSyncedProvider({
1455
771
  client: this.client,
1456
- disableOfflineStore: true,
1457
- subdocLoading: "lazy"
772
+ docId
1458
773
  });
1459
- await waitForSync(provider);
1460
774
  provider.awareness?.setLocalStateField("user", {
1461
775
  name: this.agentName,
1462
776
  color: "hsl(170, 70%, 45%)",