@abraca/dabra 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.
- package/dist/abracadabra-provider.cjs +417 -163
- package/dist/abracadabra-provider.cjs.map +1 -1
- package/dist/abracadabra-provider.esm.js +410 -164
- package/dist/abracadabra-provider.esm.js.map +1 -1
- package/dist/index.d.ts +170 -1
- package/package.json +2 -2
- package/src/AbracadabraBaseProvider.ts +22 -0
- package/src/DocUtils.ts +41 -0
- package/src/E2EAbracadabraProvider.ts +37 -0
- package/src/NodeConnect.ts +63 -0
- package/src/NodeIdentity.ts +238 -0
- package/src/index.ts +15 -0
|
@@ -0,0 +1,238 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* NodeIdentity — Ed25519 identity helpers for Node-side consumers.
|
|
3
|
+
*
|
|
4
|
+
* The browser identity story lives in {@link CryptoIdentityKeystore} (WebAuthn
|
|
5
|
+
* PRF + IndexedDB). Node CLIs and daemons (`@abraca/mcp`, `@abraca/cli`,
|
|
6
|
+
* `@abraca/orchestrator`, `@abraca/resend`, `@abraca/wiki`) instead use a raw
|
|
7
|
+
* 32-byte Ed25519 seed kept in a key file, and authenticate to the server with
|
|
8
|
+
* the same challenge → sign → verify flow exposed by
|
|
9
|
+
* {@link AbracadabraClient.loginWithKey}.
|
|
10
|
+
*
|
|
11
|
+
* Every one of those packages previously vendored a near-identical `crypto.ts`
|
|
12
|
+
* (key-file load/create + `signChallenge`) plus a copy-pasted
|
|
13
|
+
* "login → register-on-404 → re-login" block. These helpers are the single
|
|
14
|
+
* shared home for both.
|
|
15
|
+
*
|
|
16
|
+
* The signing helpers are environment-agnostic. Only {@link loadOrCreateKeyFile}
|
|
17
|
+
* touches the filesystem, and it does so via dynamic `import("node:…")` so this
|
|
18
|
+
* module stays importable from browser bundles (the fs path simply isn't
|
|
19
|
+
* reachable there).
|
|
20
|
+
*/
|
|
21
|
+
|
|
22
|
+
import * as ed from "@noble/ed25519";
|
|
23
|
+
import { sha512 } from "@noble/hashes/sha2.js";
|
|
24
|
+
|
|
25
|
+
// @noble/ed25519 v3: wire sha512 for the sync sign/getPublicKey paths and an
|
|
26
|
+
// async hook for *Async variants. Idempotent with the same assignment in
|
|
27
|
+
// CryptoIdentityKeystore / MnemonicKeyDerivation — whichever module loads first
|
|
28
|
+
// wins, and the value is identical.
|
|
29
|
+
ed.hashes.sha512 = sha512;
|
|
30
|
+
ed.hashes.sha512Async = (m: Uint8Array) => Promise.resolve(sha512(m));
|
|
31
|
+
|
|
32
|
+
// ── base64url (browser-safe; mirrors CryptoIdentityKeystore) ─────────────────
|
|
33
|
+
|
|
34
|
+
function toBase64url(bytes: Uint8Array): string {
|
|
35
|
+
return btoa(String.fromCharCode(...bytes))
|
|
36
|
+
.replace(/\+/g, "-")
|
|
37
|
+
.replace(/\//g, "_")
|
|
38
|
+
.replace(/=/g, "");
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
function fromBase64url(b64: string): Uint8Array {
|
|
42
|
+
const padded = b64.replace(/-/g, "+").replace(/_/g, "/");
|
|
43
|
+
const padLen = (4 - (padded.length % 4)) % 4;
|
|
44
|
+
return Uint8Array.from(atob(padded + "=".repeat(padLen)), (c) =>
|
|
45
|
+
c.charCodeAt(0),
|
|
46
|
+
);
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
// ── Types ────────────────────────────────────────────────────────────────────
|
|
50
|
+
|
|
51
|
+
/** A raw Node Ed25519 identity: 32-byte seed + base64url public key. */
|
|
52
|
+
export interface NodeKeypair {
|
|
53
|
+
/** 32-byte Ed25519 private-key seed. */
|
|
54
|
+
privateKey: Uint8Array;
|
|
55
|
+
/** base64url-encoded 32-byte Ed25519 public key. */
|
|
56
|
+
publicKeyB64: string;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** Options for {@link loadOrCreateKeyFile}. */
|
|
60
|
+
export interface LoadKeyFileOptions {
|
|
61
|
+
/**
|
|
62
|
+
* File name under `~/.abracadabra/` used when `keyPath` is not given.
|
|
63
|
+
* Lets each consumer keep its own identity slot (e.g. `"cli.key"`,
|
|
64
|
+
* `"agent.key"`). Defaults to `"identity.key"`.
|
|
65
|
+
*/
|
|
66
|
+
defaultFileName?: string;
|
|
67
|
+
/** Invoked once when a brand-new key is generated (for logging). */
|
|
68
|
+
onCreate?: (info: { path: string; publicKeyB64: string }) => void;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/** Minimal client surface needed by {@link loginOrRegisterWithKey}. */
|
|
72
|
+
export interface KeyAuthClient {
|
|
73
|
+
loginWithKey(
|
|
74
|
+
publicKey: string,
|
|
75
|
+
signChallenge: (challenge: string) => Promise<string>,
|
|
76
|
+
): Promise<string>;
|
|
77
|
+
registerWithKey(opts: {
|
|
78
|
+
publicKey: string;
|
|
79
|
+
username?: string;
|
|
80
|
+
displayName?: string;
|
|
81
|
+
deviceName?: string;
|
|
82
|
+
inviteCode?: string;
|
|
83
|
+
}): Promise<unknown>;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/** Options for {@link loginOrRegisterWithKey}. */
|
|
87
|
+
export interface LoginOrRegisterOptions {
|
|
88
|
+
/**
|
|
89
|
+
* Account username. Defaults to a slug of `displayName`
|
|
90
|
+
* (`/\s+/g → "-"`, lowercased) when omitted.
|
|
91
|
+
*/
|
|
92
|
+
username?: string;
|
|
93
|
+
displayName?: string;
|
|
94
|
+
deviceName?: string;
|
|
95
|
+
inviteCode?: string;
|
|
96
|
+
/** Invoked right before auto-registering on first run (for logging). */
|
|
97
|
+
onRegister?: () => void;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
// ── Signing ──────────────────────────────────────────────────────────────────
|
|
101
|
+
|
|
102
|
+
/**
|
|
103
|
+
* Sign a base64url server challenge with a 32-byte Ed25519 seed.
|
|
104
|
+
* Returns a base64url signature suitable for
|
|
105
|
+
* {@link AbracadabraClient.verify}. Synchronous (the sha512 hook is set above).
|
|
106
|
+
*/
|
|
107
|
+
export function signChallengeWithSeed(
|
|
108
|
+
challengeB64: string,
|
|
109
|
+
seed: Uint8Array,
|
|
110
|
+
): string {
|
|
111
|
+
return toBase64url(ed.sign(fromBase64url(challengeB64), seed));
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/**
|
|
115
|
+
* Build the async `signChallenge` callback that
|
|
116
|
+
* {@link AbracadabraClient.loginWithKey} expects, bound to a keypair. Keep the
|
|
117
|
+
* returned function around to re-authenticate after a JWT expires.
|
|
118
|
+
*/
|
|
119
|
+
export function makeChallengeSigner(
|
|
120
|
+
keypair: NodeKeypair,
|
|
121
|
+
): (challenge: string) => Promise<string> {
|
|
122
|
+
return (challenge: string) =>
|
|
123
|
+
Promise.resolve(signChallengeWithSeed(challenge, keypair.privateKey));
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
/**
|
|
127
|
+
* Derive a deterministic keypair from a seed string: the same input always
|
|
128
|
+
* yields the same on-server identity. Used by `@abraca/orchestrator` so a named
|
|
129
|
+
* actor maps to one reproducible account across runs.
|
|
130
|
+
*
|
|
131
|
+
* @param salt domain-separation suffix (default `"orchestrator-salt"`, the
|
|
132
|
+
* historical value — change only if you intend a different identity space).
|
|
133
|
+
*/
|
|
134
|
+
export function deterministicKeypair(
|
|
135
|
+
seed: string,
|
|
136
|
+
salt = "orchestrator-salt",
|
|
137
|
+
): NodeKeypair {
|
|
138
|
+
const privateKey = sha512(
|
|
139
|
+
new TextEncoder().encode(`${seed}:${salt}`),
|
|
140
|
+
).slice(0, 32);
|
|
141
|
+
return { privateKey, publicKeyB64: toBase64url(ed.getPublicKey(privateKey)) };
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
// ── Key file (Node only) ─────────────────────────────────────────────────────
|
|
145
|
+
|
|
146
|
+
/**
|
|
147
|
+
* Load an existing 32-byte Ed25519 seed from `keyPath`, or generate one and
|
|
148
|
+
* persist it with `0o600` (dir `0o700`). When `keyPath` is omitted the file is
|
|
149
|
+
* `~/.abracadabra/<defaultFileName>`.
|
|
150
|
+
*
|
|
151
|
+
* Node-only: filesystem modules are loaded via dynamic import, so importing
|
|
152
|
+
* this symbol in a browser bundle is safe — only *calling* it requires Node.
|
|
153
|
+
*/
|
|
154
|
+
export async function loadOrCreateKeyFile(
|
|
155
|
+
keyPath?: string,
|
|
156
|
+
opts: LoadKeyFileOptions = {},
|
|
157
|
+
): Promise<NodeKeypair> {
|
|
158
|
+
const { existsSync } = await import("node:fs");
|
|
159
|
+
const { readFile, writeFile, mkdir } = await import("node:fs/promises");
|
|
160
|
+
const { homedir } = await import("node:os");
|
|
161
|
+
const { join, dirname } = await import("node:path");
|
|
162
|
+
|
|
163
|
+
const path =
|
|
164
|
+
keyPath ??
|
|
165
|
+
join(homedir(), ".abracadabra", opts.defaultFileName ?? "identity.key");
|
|
166
|
+
|
|
167
|
+
if (existsSync(path)) {
|
|
168
|
+
const seed = await readFile(path);
|
|
169
|
+
if (seed.length !== 32) {
|
|
170
|
+
throw new Error(
|
|
171
|
+
`Invalid key file at ${path}: expected 32 bytes, got ${seed.length}`,
|
|
172
|
+
);
|
|
173
|
+
}
|
|
174
|
+
const privateKey = new Uint8Array(seed);
|
|
175
|
+
return {
|
|
176
|
+
privateKey,
|
|
177
|
+
publicKeyB64: toBase64url(ed.getPublicKey(privateKey)),
|
|
178
|
+
};
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
const privateKey = ed.utils.randomSecretKey();
|
|
182
|
+
const publicKeyB64 = toBase64url(ed.getPublicKey(privateKey));
|
|
183
|
+
|
|
184
|
+
const dir = dirname(path);
|
|
185
|
+
if (!existsSync(dir)) await mkdir(dir, { recursive: true, mode: 0o700 });
|
|
186
|
+
await writeFile(path, privateKey, { mode: 0o600 });
|
|
187
|
+
|
|
188
|
+
opts.onCreate?.({ path, publicKeyB64 });
|
|
189
|
+
return { privateKey, publicKeyB64 };
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
// ── Login / register ─────────────────────────────────────────────────────────
|
|
193
|
+
|
|
194
|
+
/**
|
|
195
|
+
* Authenticate `keypair` against the server, auto-registering on first run.
|
|
196
|
+
*
|
|
197
|
+
* Tries {@link AbracadabraClient.loginWithKey}; if the key isn't registered yet
|
|
198
|
+
* — signalled by HTTP 404/422, or 401 with a "not registered / user not found"
|
|
199
|
+
* message — it calls {@link AbracadabraClient.registerWithKey} and re-logs in.
|
|
200
|
+
* Any other error propagates. Returns the JWT.
|
|
201
|
+
*
|
|
202
|
+
* This is the one shared implementation of the "login → register-on-404 →
|
|
203
|
+
* re-login" dance previously copy-pasted into every Node consumer's connect().
|
|
204
|
+
*/
|
|
205
|
+
export async function loginOrRegisterWithKey(
|
|
206
|
+
client: KeyAuthClient,
|
|
207
|
+
keypair: NodeKeypair,
|
|
208
|
+
opts: LoginOrRegisterOptions = {},
|
|
209
|
+
): Promise<string> {
|
|
210
|
+
const sign = makeChallengeSigner(keypair);
|
|
211
|
+
try {
|
|
212
|
+
return await client.loginWithKey(keypair.publicKeyB64, sign);
|
|
213
|
+
} catch (err: unknown) {
|
|
214
|
+
const e = err as { status?: number; response?: { status?: number }; message?: string };
|
|
215
|
+
const status = e?.status ?? e?.response?.status;
|
|
216
|
+
const msg = String(e?.message ?? "").toLowerCase();
|
|
217
|
+
const notRegistered =
|
|
218
|
+
status === 404 ||
|
|
219
|
+
status === 422 ||
|
|
220
|
+
(status === 401 && /not registered|user not found|no such user/.test(msg));
|
|
221
|
+
if (!notRegistered) throw err;
|
|
222
|
+
|
|
223
|
+
opts.onRegister?.();
|
|
224
|
+
const username =
|
|
225
|
+
opts.username ??
|
|
226
|
+
(opts.displayName
|
|
227
|
+
? opts.displayName.replace(/\s+/g, "-").toLowerCase()
|
|
228
|
+
: undefined);
|
|
229
|
+
await client.registerWithKey({
|
|
230
|
+
publicKey: keypair.publicKeyB64,
|
|
231
|
+
username,
|
|
232
|
+
displayName: opts.displayName,
|
|
233
|
+
deviceName: opts.deviceName,
|
|
234
|
+
inviteCode: opts.inviteCode,
|
|
235
|
+
});
|
|
236
|
+
return await client.loginWithKey(keypair.publicKeyB64, sign);
|
|
237
|
+
}
|
|
238
|
+
}
|
package/src/index.ts
CHANGED
|
@@ -18,6 +18,20 @@ export * from "./CloseEvents.ts";
|
|
|
18
18
|
export * from "./awarenessStatesToArray.ts";
|
|
19
19
|
export { SubdocMessage } from "./OutgoingMessages/SubdocMessage.ts";
|
|
20
20
|
export { CryptoIdentityKeystore } from "./CryptoIdentityKeystore.ts";
|
|
21
|
+
export {
|
|
22
|
+
signChallengeWithSeed,
|
|
23
|
+
makeChallengeSigner,
|
|
24
|
+
deterministicKeypair,
|
|
25
|
+
loadOrCreateKeyFile,
|
|
26
|
+
loginOrRegisterWithKey,
|
|
27
|
+
} from "./NodeIdentity.ts";
|
|
28
|
+
export type {
|
|
29
|
+
NodeKeypair,
|
|
30
|
+
LoadKeyFileOptions,
|
|
31
|
+
LoginOrRegisterOptions,
|
|
32
|
+
KeyAuthClient,
|
|
33
|
+
} from "./NodeIdentity.ts";
|
|
34
|
+
export { openSyncedProvider, pickEntrySpace } from "./NodeConnect.ts";
|
|
21
35
|
export { DocumentCache } from "./DocumentCache.ts";
|
|
22
36
|
export type { DocumentCacheOptions } from "./DocumentCache.ts";
|
|
23
37
|
export { SearchIndex } from "./SearchIndex.ts";
|
|
@@ -153,6 +167,7 @@ export {
|
|
|
153
167
|
withTimeout,
|
|
154
168
|
normalizeRootId,
|
|
155
169
|
toPlain,
|
|
170
|
+
readEntries,
|
|
156
171
|
makeEntryMap,
|
|
157
172
|
patchEntry,
|
|
158
173
|
isPlaceholderLabel,
|