@abraca/resend 2.34.0 → 2.35.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/bootstrap.ts CHANGED
@@ -5,8 +5,7 @@
5
5
  * as-is — the user is allowed to rename, recolor, or restructure these docs
6
6
  * after they're created. Missing columns under the Outbox kanban are filled in.
7
7
  */
8
- import { makeEntryMap, toPlain } from "@abraca/dabra";
9
- import * as Y from "yjs";
8
+ import { makeEntryMap, readEntries } from "@abraca/dabra";
10
9
  import type { AbracadabraResendServer } from "./server.ts";
11
10
 
12
11
  export const INBOX_LABEL = "Inbox";
@@ -21,34 +20,6 @@ export interface BootstrapResult {
21
20
  columns: Record<OutboxColumn, string>;
22
21
  }
23
22
 
24
- interface TreeEntry {
25
- id: string;
26
- label: string;
27
- parentId: string | null;
28
- order: number;
29
- type?: string;
30
- }
31
-
32
- function readEntries(
33
- treeMap: Y.Map<any>,
34
- selfId: string | null,
35
- ): TreeEntry[] {
36
- const entries: TreeEntry[] = [];
37
- treeMap.forEach((raw: any, id: string) => {
38
- if (selfId && id === selfId) return;
39
- const value = toPlain(raw) as any;
40
- if (typeof value !== "object" || value === null) return;
41
- entries.push({
42
- id,
43
- label: typeof value.label === "string" ? value.label : "Untitled",
44
- parentId: value.parentId ?? null,
45
- order: typeof value.order === "number" ? value.order : 0,
46
- type: typeof value.type === "string" ? value.type : undefined,
47
- });
48
- });
49
- return entries;
50
- }
51
-
52
23
  async function createDoc(
53
24
  server: AbracadabraResendServer,
54
25
  opts: {
package/src/server.ts CHANGED
@@ -11,11 +11,14 @@ import {
11
11
  AbracadabraClient,
12
12
  AbracadabraProvider,
13
13
  Kind,
14
+ loadOrCreateKeyFile,
15
+ loginOrRegisterWithKey,
16
+ makeChallengeSigner,
17
+ openSyncedProvider,
14
18
  SERVER_ROOT_ID,
15
19
  WebSocketStatus,
16
20
  } from "@abraca/dabra";
17
21
  import * as Y from "yjs";
18
- import { loadOrCreateKeypair, signChallenge } from "./crypto.ts";
19
22
  import { waitForSync } from "./utils.ts";
20
23
 
21
24
  export interface ResendServerConfig {
@@ -91,35 +94,27 @@ export class AbracadabraResendServer {
91
94
 
92
95
  /** Authenticate, discover spaces, connect to the configured (or first) space. */
93
96
  async connect(): Promise<void> {
94
- const keypair = await loadOrCreateKeypair(this.config.keyFile);
97
+ const keypair = await loadOrCreateKeyFile(this.config.keyFile, {
98
+ defaultFileName: "resend.key",
99
+ onCreate: ({ path, publicKeyB64 }) => {
100
+ console.error(
101
+ `[abracadabra-resend] Generated new agent keypair at ${path}`,
102
+ );
103
+ console.error(`[abracadabra-resend] Public key: ${publicKeyB64}`);
104
+ },
105
+ });
95
106
  this._userId = keypair.publicKeyB64;
96
- const signFn = (challenge: string) =>
97
- Promise.resolve(signChallenge(challenge, keypair.privateKey));
98
- this._signFn = signFn;
99
-
100
- try {
101
- await this.client.loginWithKey(keypair.publicKeyB64, signFn);
102
- } catch (err: any) {
103
- const status = err?.status ?? err?.response?.status;
104
- const msg = String(err?.message ?? "").toLowerCase();
105
- const notRegistered =
106
- status === 404 ||
107
- status === 422 ||
108
- (status === 401 &&
109
- /not registered|user not found|no such user/.test(msg));
110
- if (!notRegistered) throw err;
111
- console.error(
112
- "[abracadabra-resend] Key not registered, creating new account...",
113
- );
114
- await this.client.registerWithKey({
115
- publicKey: keypair.publicKeyB64,
116
- username: this.agentName.replace(/\s+/g, "-").toLowerCase(),
117
- displayName: this.agentName,
118
- deviceName: "Resend Bridge",
119
- inviteCode: this.config.inviteCode,
120
- });
121
- await this.client.loginWithKey(keypair.publicKeyB64, signFn);
122
- }
107
+ this._signFn = makeChallengeSigner(keypair);
108
+
109
+ await loginOrRegisterWithKey(this.client, keypair, {
110
+ displayName: this.agentName,
111
+ deviceName: "Resend Bridge",
112
+ inviteCode: this.config.inviteCode,
113
+ onRegister: () =>
114
+ console.error(
115
+ "[abracadabra-resend] Key not registered, creating new account...",
116
+ ),
117
+ });
123
118
  console.error(
124
119
  `[abracadabra-resend] Authenticated as ${this.agentName} (pubkey=${keypair.publicKeyB64})`,
125
120
  );
@@ -171,16 +166,7 @@ export class AbracadabraResendServer {
171
166
  await this.client.loginWithKey(this._userId, this._signFn);
172
167
  }
173
168
 
174
- const doc = new Y.Doc({ guid: docId });
175
- const provider = new AbracadabraProvider({
176
- name: docId,
177
- document: doc,
178
- client: this.client,
179
- disableOfflineStore: true,
180
- subdocLoading: "lazy",
181
- });
182
-
183
- await waitForSync(provider);
169
+ const { doc, provider } = await openSyncedProvider({ client: this.client, docId });
184
170
 
185
171
  provider.awareness?.setLocalStateField("user", {
186
172
  name: this.agentName,
package/src/utils.ts CHANGED
@@ -1,32 +1,6 @@
1
1
  /**
2
- * Wait for a provider's `synced` event with a timeout.
3
- *
4
- * The `isSynced` short-circuit is load-bearing: providers that already synced
5
- * (e.g. cached child providers returned from `loadChild`) won't re-emit
6
- * `synced`, so without the short-circuit every later op on that doc times out.
2
+ * Re-export of the shared provider sync utility. The implementation lives in
3
+ * `@abraca/dabra` (`DocUtils.waitForSync`) — kept here as a stable local import
4
+ * path for `server.ts` / `inbound-server.ts`.
7
5
  */
8
- export function waitForSync(
9
- provider: {
10
- isSynced?: boolean;
11
- on(event: string, cb: () => void): void;
12
- off(event: string, cb: () => void): void;
13
- },
14
- timeoutMs = 15000,
15
- ): Promise<void> {
16
- if (provider.isSynced) return Promise.resolve();
17
-
18
- return new Promise<void>((resolve, reject) => {
19
- const timer = setTimeout(() => {
20
- provider.off("synced", handler);
21
- reject(new Error(`Sync timed out after ${timeoutMs}ms`));
22
- }, timeoutMs);
23
-
24
- function handler() {
25
- clearTimeout(timer);
26
- provider.off("synced", handler);
27
- resolve();
28
- }
29
-
30
- provider.on("synced", handler);
31
- });
32
- }
6
+ export { waitForSync } from "@abraca/dabra";
package/src/crypto.ts DELETED
@@ -1,72 +0,0 @@
1
- /**
2
- * Ed25519 key generation, persistence, and challenge signing for the Resend bridge.
3
- * Same shape as @abraca/mcp's crypto module; intentionally vendored so this package
4
- * doesn't depend on @abraca/mcp.
5
- */
6
- import * as ed from "@noble/ed25519";
7
- import { sha512 } from "@noble/hashes/sha2.js";
8
- import { existsSync } from "node:fs";
9
- import { mkdir, readFile, writeFile } from "node:fs/promises";
10
- import { homedir } from "node:os";
11
- import { dirname, join } from "node:path";
12
-
13
- ed.hashes.sha512 = sha512;
14
- ed.hashes.sha512Async = (m: Uint8Array) => Promise.resolve(sha512(m));
15
-
16
- const DEFAULT_KEY_PATH = join(homedir(), ".abracadabra", "resend.key");
17
-
18
- function toBase64url(bytes: Uint8Array): string {
19
- return Buffer.from(bytes).toString("base64url");
20
- }
21
-
22
- function fromBase64url(b64: string): Uint8Array {
23
- return new Uint8Array(Buffer.from(b64, "base64url"));
24
- }
25
-
26
- export interface AgentKeypair {
27
- privateKey: Uint8Array;
28
- publicKeyB64: string;
29
- }
30
-
31
- export async function loadOrCreateKeypair(
32
- keyPath?: string,
33
- ): Promise<AgentKeypair> {
34
- const path = keyPath || DEFAULT_KEY_PATH;
35
-
36
- if (existsSync(path)) {
37
- const seed = await readFile(path);
38
- if (seed.length !== 32) {
39
- throw new Error(
40
- `Invalid key file at ${path}: expected 32 bytes, got ${seed.length}`,
41
- );
42
- }
43
- const privateKey = new Uint8Array(seed);
44
- const publicKey = ed.getPublicKey(privateKey);
45
- return { privateKey, publicKeyB64: toBase64url(publicKey) };
46
- }
47
-
48
- const privateKey = ed.utils.randomSecretKey();
49
- const publicKey = ed.getPublicKey(privateKey);
50
-
51
- const dir = dirname(path);
52
- if (!existsSync(dir)) {
53
- await mkdir(dir, { recursive: true, mode: 0o700 });
54
- }
55
- await writeFile(path, Buffer.from(privateKey), { mode: 0o600 });
56
-
57
- console.error(`[abracadabra-resend] Generated new agent keypair at ${path}`);
58
- console.error(
59
- `[abracadabra-resend] Public key: ${toBase64url(publicKey)}`,
60
- );
61
-
62
- return { privateKey, publicKeyB64: toBase64url(publicKey) };
63
- }
64
-
65
- export function signChallenge(
66
- challengeB64: string,
67
- privateKey: Uint8Array,
68
- ): string {
69
- const challenge = fromBase64url(challengeB64);
70
- const sig = ed.sign(challenge, privateKey);
71
- return toBase64url(sig);
72
- }