@abraca/nuxt 2.85.0 → 2.86.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/dist/module.json CHANGED
@@ -4,7 +4,7 @@
4
4
  "compatibility": {
5
5
  "nuxt": ">=4.0.0"
6
6
  },
7
- "version": "2.85.0",
7
+ "version": "2.86.0",
8
8
  "builder": {
9
9
  "@nuxt/module-builder": "1.0.2",
10
10
  "unbuild": "3.6.1"
@@ -36,10 +36,10 @@ declare const __VLS_base: import("vue").DefineComponent<__VLS_Props, {}, {}, {},
36
36
  name: string;
37
37
  color: string;
38
38
  online: boolean | null;
39
+ isFollowing: boolean;
39
40
  currentDocId: string | null;
40
41
  isSelf: boolean;
41
42
  avatarStyle: string;
42
- isFollowing: boolean;
43
43
  showFollow: boolean;
44
44
  currentDocLabel: string | null;
45
45
  currentDocIcon: string;
@@ -36,10 +36,10 @@ declare const __VLS_base: import("vue").DefineComponent<__VLS_Props, {}, {}, {},
36
36
  name: string;
37
37
  color: string;
38
38
  online: boolean | null;
39
+ isFollowing: boolean;
39
40
  currentDocId: string | null;
40
41
  isSelf: boolean;
41
42
  avatarStyle: string;
42
- isFollowing: boolean;
43
43
  showFollow: boolean;
44
44
  currentDocLabel: string | null;
45
45
  currentDocIcon: string;
@@ -34,7 +34,7 @@ export function useAAFollowPeer(options = {}) {
34
34
  return followingUserCache.value;
35
35
  });
36
36
  watch(followingUser, (user) => {
37
- if (user) followingUserCache.value = { ...user };
37
+ if (user && user !== followingUserCache.value) followingUserCache.value = { ...user };
38
38
  }, { flush: "post" });
39
39
  watch(isFollowing, (active) => {
40
40
  if (!active) followingUserCache.value = null;
@@ -8,6 +8,7 @@ import { buildServerSchemaValidator } from "../utils/schemaServerSupport.js";
8
8
  import { createDocCacheAPI } from "../utils/docCache.js";
9
9
  import { docTreeCacheRunner } from "../runners/doc-tree-cache.js";
10
10
  import { initSlugMap, loadPersistedSlugMap } from "../utils/slugMap.js";
11
+ import { loginWithKeyRetrying, waitForBackendReady } from "../utils/authRetry.js";
11
12
  function fromBase64Url(str) {
12
13
  const b = atob(str.replace(/-/g, "+").replace(/_/g, "/").padEnd(str.length + (4 - str.length % 4) % 4, "="));
13
14
  const a = new Uint8Array(b.length);
@@ -53,7 +54,7 @@ async function loadOrCreateAutoIdentity(opts) {
53
54
  const pk = await opts.ed.getPublicKey(sk);
54
55
  const publicKey = toBase64Url(pk);
55
56
  const privateKey = toBase64Url(sk);
56
- const username = `runner-${publicKey.replace(/[^a-zA-Z0-9]/g, "").slice(0, 16).toLowerCase()}`;
57
+ const username = `runner-${publicKey.replace(/[^a-z0-9]/gi, "").slice(0, 16).toLowerCase()}`;
57
58
  console.log(`[abracadabra-service] auto-registering ${username} on ${opts.serverUrl}\u2026`);
58
59
  const res = await fetch(`${opts.serverUrl}/auth/register`, {
59
60
  method: "POST",
@@ -187,57 +188,64 @@ export default defineNitroPlugin(async (nitroApp) => {
187
188
  return;
188
189
  }
189
190
  let wsp = null;
190
- try {
191
- const [
192
- { AbracadabraClient, AbracadabraProvider, AbracadabraWS },
193
- edModule,
194
- { sha512 },
195
- Y,
196
- wsModule
197
- ] = await Promise.all([
198
- import("@abraca/dabra"),
199
- import("@noble/ed25519"),
200
- import("@noble/hashes/sha2.js"),
201
- import("yjs"),
202
- import("ws")
203
- ]);
204
- const ed = edModule.default ?? edModule;
205
- const WSImpl = wsModule.WebSocket ?? wsModule.default;
206
- if (typeof globalThis.WebSocket === "undefined" && WSImpl) {
207
- ;
208
- globalThis.WebSocket = WSImpl;
209
- }
210
- if (!ed.hashes) {
211
- throw new Error("@noble/ed25519 v3: `hashes` export missing \u2014 check Vite optimizeDeps");
212
- }
213
- ed.hashes.sha512 = sha512;
214
- ed.hashes.sha512Async = (m) => Promise.resolve(sha512(m));
215
- let pubKeyB64 = explicitPubKey;
216
- let privKeyB64 = explicitPrivKey;
217
- if (!pubKeyB64 || !privKeyB64) {
218
- const cachePath = join(process.cwd(), ".data", "abracadabra-runner-identity.json");
219
- const id = await loadOrCreateAutoIdentity({ serverUrl, cachePath, ed });
220
- if (!id) {
221
- return;
191
+ const INIT_BACKOFF_CAP_MS = 3e4;
192
+ for (let initAttempt = 1; ; initAttempt++) {
193
+ try {
194
+ const [
195
+ { AbracadabraClient, AbracadabraProvider, AbracadabraWS },
196
+ edModule,
197
+ { sha512 },
198
+ Y,
199
+ wsModule
200
+ ] = await Promise.all([
201
+ import("@abraca/dabra"),
202
+ import("@noble/ed25519"),
203
+ import("@noble/hashes/sha2.js"),
204
+ import("yjs"),
205
+ import("ws")
206
+ ]);
207
+ const ed = edModule.default ?? edModule;
208
+ const WSImpl = wsModule.WebSocket ?? wsModule.default;
209
+ if (typeof globalThis.WebSocket === "undefined" && WSImpl) {
210
+ ;
211
+ globalThis.WebSocket = WSImpl;
222
212
  }
223
- pubKeyB64 = id.publicKey;
224
- privKeyB64 = id.privateKey;
225
- }
226
- const privKey = fromBase64Url(privKeyB64);
227
- const client = new AbracadabraClient({
228
- url: serverUrl,
229
- persistAuth: false
230
- });
231
- await client.loginWithKey(pubKeyB64, async (challenge) => {
232
- const sig = await ed.sign(fromBase64Url(challenge), privKey);
233
- return toBase64Url(sig);
234
- });
235
- const actualRole = await resolveActualRole(serverUrl, client.token);
236
- console.log(
237
- `[abracadabra-service] authenticated \u2014 role: ${actualRole ?? "unknown"}`
238
- );
239
- if (actualRole !== "service") {
240
- const detail = `[abracadabra-service] this runner is "${actualRole ?? "unknown"}", not "service".
213
+ if (!ed.hashes) {
214
+ throw new Error("@noble/ed25519 v3: `hashes` export missing \u2014 check Vite optimizeDeps");
215
+ }
216
+ ed.hashes.sha512 = sha512;
217
+ ed.hashes.sha512Async = (m) => Promise.resolve(sha512(m));
218
+ let pubKeyB64 = explicitPubKey;
219
+ let privKeyB64 = explicitPrivKey;
220
+ if (!pubKeyB64 || !privKeyB64) {
221
+ const cachePath = join(process.cwd(), ".data", "abracadabra-runner-identity.json");
222
+ const id = await loadOrCreateAutoIdentity({ serverUrl, cachePath, ed });
223
+ if (!id) {
224
+ return;
225
+ }
226
+ pubKeyB64 = id.publicKey;
227
+ privKeyB64 = id.privateKey;
228
+ }
229
+ const privKey = fromBase64Url(privKeyB64);
230
+ const client = new AbracadabraClient({
231
+ url: serverUrl,
232
+ persistAuth: false
233
+ });
234
+ await waitForBackendReady({ serverUrl });
235
+ await loginWithKeyRetrying({
236
+ client,
237
+ publicKey: pubKeyB64,
238
+ sign: async (challenge) => {
239
+ const sig = await ed.sign(fromBase64Url(challenge), privKey);
240
+ return toBase64Url(sig);
241
+ }
242
+ });
243
+ const actualRole = await resolveActualRole(serverUrl, client.token);
244
+ console.log(
245
+ `[abracadabra-service] authenticated \u2014 role: ${actualRole ?? "unknown"}`
246
+ );
247
+ if (actualRole !== "service") {
248
+ const detail = `[abracadabra-service] this runner is "${actualRole ?? "unknown"}", not "service".
241
249
  Consequence: writes are refused ON THE WIRE with no thrown error \u2014 seeding,
242
250
  the SSR doc cache and RPC handlers will appear to run and change nothing.
243
251
  Runner public key: ${pubKeyB64}
@@ -247,183 +255,197 @@ export default defineNitroPlugin(async (nitroApp) => {
247
255
  password = "<rotate-me>"
248
256
  public_key = "${pubKeyB64}"
249
257
  (env equivalent: ABRA_USERS_SYSTEM_USERS='[{"username":"app-runner","password":"<rotate-me>","public_key":"${pubKeyB64}"}]')`;
250
- if (requireServiceRole) {
251
- console.error(detail);
252
- console.error(
253
- "[abracadabra-service] refusing to boot runners (service.requireServiceRole). A runner that cannot write is worse than none: it looks healthy and does nothing."
254
- );
258
+ if (requireServiceRole) {
259
+ console.error(detail);
260
+ console.error(
261
+ "[abracadabra-service] refusing to boot runners (service.requireServiceRole). A runner that cannot write is worse than none: it looks healthy and does nothing."
262
+ );
263
+ return;
264
+ }
265
+ console.warn(detail);
266
+ }
267
+ const wsUrl = client.wsUrl;
268
+ wsp = new AbracadabraWS({
269
+ url: wsUrl,
270
+ delay: 1e3,
271
+ minDelay: 1e3,
272
+ maxDelay: 3e4,
273
+ factor: 2,
274
+ jitter: true,
275
+ maxAttempts: 50,
276
+ WebSocketPolyfill: WSImpl
277
+ });
278
+ let rootDocId = rootDocIdOverride;
279
+ let rootDocFromSentinel = false;
280
+ if (!rootDocId) {
281
+ try {
282
+ const info = await $fetch(`${serverUrl}/info`);
283
+ rootDocId = info?.root_doc_id ?? "";
284
+ rootDocFromSentinel = !!rootDocId;
285
+ } catch {
286
+ }
287
+ }
288
+ if (!rootDocId) {
289
+ console.warn("[abracadabra-service] Could not determine root doc ID. Set service.rootDocId in module options.");
290
+ wsp.destroy?.();
255
291
  return;
256
292
  }
257
- console.warn(detail);
258
- }
259
- const wsUrl = client.wsUrl;
260
- wsp = new AbracadabraWS({
261
- url: wsUrl,
262
- delay: 1e3,
263
- minDelay: 1e3,
264
- maxDelay: 3e4,
265
- factor: 2,
266
- jitter: true,
267
- maxAttempts: 50,
268
- WebSocketPolyfill: WSImpl
269
- });
270
- let rootDocId = rootDocIdOverride;
271
- let rootDocFromSentinel = false;
272
- if (!rootDocId) {
273
- try {
274
- const info = await $fetch(`${serverUrl}/info`);
275
- rootDocId = info?.root_doc_id ?? "";
276
- rootDocFromSentinel = !!rootDocId;
277
- } catch {
293
+ if (rootDocFromSentinel) {
294
+ console.warn(
295
+ `[abracadabra-service] no service.rootDocId / entryDocId configured \u2014 falling back to the server's reserved root (${rootDocId}). That is a shared sentinel, not this app's space: expect an empty doc tree and no SSR content. Set abracadabra.entryDocId (or service.rootDocId) to your space's id.`
296
+ );
278
297
  }
279
- }
280
- if (!rootDocId) {
281
- console.warn("[abracadabra-service] Could not determine root doc ID. Set service.rootDocId in module options.");
282
- wsp.destroy?.();
283
- return;
284
- }
285
- if (rootDocFromSentinel) {
286
- console.warn(
287
- `[abracadabra-service] no service.rootDocId / entryDocId configured \u2014 falling back to the server's reserved root (${rootDocId}). That is a shared sentinel, not this app's space: expect an empty doc tree and no SSR content. Set abracadabra.entryDocId (or service.rootDocId) to your space's id.`
288
- );
289
- }
290
- const rootReady = await ensureRootDocument({
291
- serverUrl,
292
- rootDocId,
293
- token: client.token,
294
- role: actualRole,
295
- label: rootDocLabel,
296
- publicAccess: rootDocPublicAccess,
297
- // Never auto-create the shared sentinel: it always exists, and creating
298
- // "the root" is not what an operator who forgot to set an id wants.
299
- enabled: ensureRootDoc && !rootDocFromSentinel
300
- });
301
- if (!rootReady) {
302
- wsp.destroy?.();
303
- return;
304
- }
305
- const rootDoc = new Y.Doc();
306
- const rootProvider = new AbracadabraProvider({
307
- client,
308
- document: rootDoc,
309
- name: rootDocId,
310
- websocketProvider: wsp,
311
- disableOfflineStore: true,
312
- cryptoIdentity: { publicKey: pubKeyB64 },
313
- signChallenge: async (challenge) => {
314
- const sig = await ed.sign(fromBase64Url(challenge), privKey);
315
- return toBase64Url(sig);
298
+ const rootReady = await ensureRootDocument({
299
+ serverUrl,
300
+ rootDocId,
301
+ token: client.token,
302
+ role: actualRole,
303
+ label: rootDocLabel,
304
+ publicAccess: rootDocPublicAccess,
305
+ // Never auto-create the shared sentinel: it always exists, and creating
306
+ // "the root" is not what an operator who forgot to set an id wants.
307
+ enabled: ensureRootDoc && !rootDocFromSentinel
308
+ });
309
+ if (!rootReady) {
310
+ wsp.destroy?.();
311
+ return;
316
312
  }
317
- });
318
- rootProvider.on("writeRejected", ({ documentName, reason, kind }) => {
319
- console.error(
320
- `[abracadabra-service] server REFUSED a write to ${documentName} (${kind}): ${reason}. This runner's changes are not being persisted.`
321
- );
322
- });
323
- rootProvider.attach();
324
- const SYNC_ATTEMPTS = 3;
325
- const SYNC_TIMEOUT_MS = 3e4;
326
- const waitForSync = () => Promise.race([
327
- new Promise((resolve) => {
328
- if (rootProvider.isSynced) {
329
- resolve();
330
- return;
313
+ const rootDoc = new Y.Doc();
314
+ const rootProvider = new AbracadabraProvider({
315
+ client,
316
+ document: rootDoc,
317
+ name: rootDocId,
318
+ websocketProvider: wsp,
319
+ disableOfflineStore: true,
320
+ cryptoIdentity: { publicKey: pubKeyB64 },
321
+ signChallenge: async (challenge) => {
322
+ const sig = await ed.sign(fromBase64Url(challenge), privKey);
323
+ return toBase64Url(sig);
331
324
  }
332
- const handler = ({ state }) => {
333
- if (state) {
334
- rootProvider.off("synced", handler);
325
+ });
326
+ rootProvider.on("writeRejected", ({ documentName, reason, kind }) => {
327
+ console.error(
328
+ `[abracadabra-service] server REFUSED a write to ${documentName} (${kind}): ${reason}. This runner's changes are not being persisted.`
329
+ );
330
+ });
331
+ rootProvider.attach();
332
+ const SYNC_ATTEMPTS = 3;
333
+ const SYNC_TIMEOUT_MS = 3e4;
334
+ const waitForSync = () => Promise.race([
335
+ new Promise((resolve) => {
336
+ if (rootProvider.isSynced) {
335
337
  resolve();
338
+ return;
336
339
  }
337
- };
338
- rootProvider.on("synced", handler);
339
- }),
340
- new Promise(
341
- (_, reject) => setTimeout(() => reject(new Error("sync timeout")), SYNC_TIMEOUT_MS)
342
- )
343
- ]);
344
- let synced = false;
345
- for (let attempt = 1; attempt <= SYNC_ATTEMPTS && !synced; attempt++) {
346
- try {
347
- await waitForSync();
348
- synced = true;
349
- } catch {
350
- let restStatus = "unreachable";
340
+ const handler = ({ state }) => {
341
+ if (state) {
342
+ rootProvider.off("synced", handler);
343
+ resolve();
344
+ }
345
+ };
346
+ rootProvider.on("synced", handler);
347
+ }),
348
+ new Promise(
349
+ (_, reject) => setTimeout(() => reject(new Error("sync timeout")), SYNC_TIMEOUT_MS)
350
+ )
351
+ ]);
352
+ let synced = false;
353
+ for (let attempt = 1; attempt <= SYNC_ATTEMPTS && !synced; attempt++) {
351
354
  try {
352
- await $fetch(`${serverUrl}/docs/${rootDocId}`, {
353
- headers: client.token ? { Authorization: `Bearer ${client.token}` } : void 0
354
- });
355
- restStatus = "exists over REST";
356
- } catch (e) {
357
- const status = e?.status ?? e?.statusCode;
358
- restStatus = status === 404 ? "DOES NOT EXIST (404)" : `REST error ${status ?? "?"}`;
355
+ await waitForSync();
356
+ synced = true;
357
+ } catch {
358
+ let restStatus = "unreachable";
359
+ try {
360
+ await $fetch(`${serverUrl}/docs/${rootDocId}`, {
361
+ headers: client.token ? { Authorization: `Bearer ${client.token}` } : void 0
362
+ });
363
+ restStatus = "exists over REST";
364
+ } catch (e) {
365
+ const status = e?.status ?? e?.statusCode;
366
+ restStatus = status === 404 ? "DOES NOT EXIST (404)" : `REST error ${status ?? "?"}`;
367
+ }
368
+ console.warn(
369
+ `[abracadabra-service] root doc ${rootDocId} did not sync within ${SYNC_TIMEOUT_MS}ms (attempt ${attempt}/${SYNC_ATTEMPTS}) \u2014 document: ${restStatus}; role: ${actualRole ?? "unknown"}; socket: ${rootProvider.connectionStatus ?? "unknown"}`
370
+ );
359
371
  }
360
- console.warn(
361
- `[abracadabra-service] root doc ${rootDocId} did not sync within ${SYNC_TIMEOUT_MS}ms (attempt ${attempt}/${SYNC_ATTEMPTS}) \u2014 document: ${restStatus}; role: ${actualRole ?? "unknown"}; socket: ${rootProvider.connectionStatus ?? "unknown"}`
372
+ }
373
+ if (!synced) {
374
+ console.error(
375
+ `[abracadabra-service] giving up on the initial sync of ${rootDocId}. Runners will boot anyway and recover as sync lands \u2014 SSR content will be missing until then.`
362
376
  );
377
+ } else {
378
+ console.log("[abracadabra-service] Root doc synced");
363
379
  }
364
- }
365
- if (!synced) {
366
- console.error(
367
- `[abracadabra-service] giving up on the initial sync of ${rootDocId}. Runners will boot anyway and recover as sync lands \u2014 SSR content will be missing until then.`
368
- );
369
- } else {
370
- console.log("[abracadabra-service] Root doc synced");
371
- }
372
- const storage2 = useStorage();
373
- const ctx = {
374
- client,
375
- wsp,
376
- rootDoc,
377
- rootDocId,
378
- rootProvider,
379
- storage: storage2,
380
- docCache: createDocCacheAPI(rootDoc)
381
- };
382
- const publicConfig = config.public?.abracadabra;
383
- if (publicConfig?.features?.serverCache !== false) {
384
- const coreServerPlugin = {
385
- name: "abracadabra:core-server",
386
- serverRunners: [docTreeCacheRunner]
380
+ const storage2 = useStorage();
381
+ const ctx = {
382
+ client,
383
+ wsp,
384
+ rootDoc,
385
+ rootDocId,
386
+ rootProvider,
387
+ storage: storage2,
388
+ docCache: createDocCacheAPI(rootDoc)
387
389
  };
388
- registerServerPlugin(coreServerPlugin);
389
- }
390
- const attachedSchemas = [];
391
- const schemaCfg = publicConfig?.schema ?? {};
392
- if (schemaCfg.bundleDir) {
393
- console.log(
394
- `[abracadabra-service] schema bundle_dir advertised: ${schemaCfg.bundleDir} (server-side bundle_dir = same path; informational only \u2014 server is authoritative)`
395
- );
396
- }
397
- Object.assign(ctx, {
398
- attachSchema: (registry) => {
399
- if (!registry || typeof registry !== "object") return;
400
- if (typeof registry.validateMeta !== "function") {
401
- console.warn("[abracadabra-service] attachSchema received a value missing validateMeta() \u2014 skipping");
402
- return;
390
+ const publicConfig = config.public?.abracadabra;
391
+ if (publicConfig?.features?.serverCache !== false) {
392
+ const coreServerPlugin = {
393
+ name: "abracadabra:core-server",
394
+ serverRunners: [docTreeCacheRunner]
395
+ };
396
+ registerServerPlugin(coreServerPlugin);
397
+ }
398
+ const attachedSchemas = [];
399
+ const schemaCfg = publicConfig?.schema ?? {};
400
+ if (schemaCfg.bundleDir) {
401
+ console.log(
402
+ `[abracadabra-service] schema bundle_dir advertised: ${schemaCfg.bundleDir} (server-side bundle_dir = same path; informational only \u2014 server is authoritative)`
403
+ );
404
+ }
405
+ Object.assign(ctx, {
406
+ attachSchema: (registry) => {
407
+ if (!registry || typeof registry !== "object") return;
408
+ if (typeof registry.validateMeta !== "function") {
409
+ console.warn("[abracadabra-service] attachSchema received a value missing validateMeta() \u2014 skipping");
410
+ return;
411
+ }
412
+ attachedSchemas.push(registry);
403
413
  }
404
- attachedSchemas.push(registry);
414
+ });
415
+ await nitroApp.hooks.callHook("abracadabra:before-runners", ctx);
416
+ delete ctx.attachSchema;
417
+ if (attachedSchemas.length > 0) {
418
+ const validator = buildServerSchemaValidator(attachedSchemas);
419
+ if (validator) ctx.validateMeta = validator;
420
+ const advertisedTypes = /* @__PURE__ */ new Set();
421
+ for (const r of attachedSchemas) for (const t of r.types.keys()) advertisedTypes.add(t);
422
+ console.log(
423
+ `[abracadabra-service] ${attachedSchemas.length} schema registr${attachedSchemas.length === 1 ? "y" : "ies"} attached covering types: [${[...advertisedTypes].sort().join(", ")}]`
424
+ );
405
425
  }
406
- });
407
- await nitroApp.hooks.callHook("abracadabra:before-runners", ctx);
408
- delete ctx.attachSchema;
409
- if (attachedSchemas.length > 0) {
410
- const validator = buildServerSchemaValidator(attachedSchemas);
411
- if (validator) ctx.validateMeta = validator;
412
- const advertisedTypes = /* @__PURE__ */ new Set();
413
- for (const r of attachedSchemas) for (const t of r.types.keys()) advertisedTypes.add(t);
414
- console.log(
415
- `[abracadabra-service] ${attachedSchemas.length} schema registr${attachedSchemas.length === 1 ? "y" : "ies"} attached covering types: [${[...advertisedTypes].sort().join(", ")}]`
426
+ await bootRunners(ctx);
427
+ console.log("[abracadabra-service] All runners started");
428
+ nitroApp.hooks.hook("close", async () => {
429
+ await shutdownAllRunners();
430
+ wsp?.destroy?.();
431
+ console.log("[abracadabra-service] Shutdown complete");
432
+ });
433
+ return;
434
+ } catch (err) {
435
+ const message = err instanceof Error ? err.message : String(err);
436
+ wsp?.destroy?.();
437
+ wsp = null;
438
+ const delay = Math.min(1e3 * 2 ** (initAttempt - 1), INIT_BACKOFF_CAP_MS);
439
+ if (initAttempt === 1) {
440
+ console.error(`[abracadabra-service] Failed to initialize: ${message}`);
441
+ console.error(
442
+ "[abracadabra-service] NO SERVER RUNNER IS RUNNING YET. Until one does, this deployment cannot server-render: no SSR document cache, no RPC handlers, no seeding, no background jobs. Browsers sync the CRDT tree themselves, so the site will still LOOK correct \u2014 check this log, not the site. Retrying until it succeeds."
443
+ );
444
+ }
445
+ console.warn(
446
+ `[abracadabra-service] init attempt ${initAttempt} failed (${message}) \u2014 retrying in ${delay}ms.`
416
447
  );
448
+ await new Promise((resolve) => setTimeout(resolve, delay));
417
449
  }
418
- await bootRunners(ctx);
419
- console.log("[abracadabra-service] All runners started");
420
- nitroApp.hooks.hook("close", async () => {
421
- await shutdownAllRunners();
422
- wsp?.destroy?.();
423
- console.log("[abracadabra-service] Shutdown complete");
424
- });
425
- } catch (err) {
426
- console.error("[abracadabra-service] Failed to initialize:", err instanceof Error ? err.message : err);
427
- wsp?.destroy?.();
428
450
  }
429
451
  });
@@ -0,0 +1,93 @@
1
+ /**
2
+ * The Ed25519 challenge-response handshake, retried — and importable, so it
3
+ * can be TESTED.
4
+ *
5
+ * ── Why this file exists as its own module ───────────────────────────────────
6
+ * This logic used to be four lines inside `plugins/abracadabra-service.ts`.
7
+ * That file imports `nitropack/runtime/*`, which cannot load outside a built
8
+ * Nitro app, so nothing in it was reachable from a unit test — which is
9
+ * exactly why a one-shot, un-retried auth call survived in the single most
10
+ * deploy-critical path in the module. Anything here worth asserting on belongs
11
+ * in a util with **zero imports**, the same split the doc cache and the
12
+ * activity ledger already use.
13
+ *
14
+ * ── What it is defending against ─────────────────────────────────────────────
15
+ * `POST /auth/verify` answers **410** `{"error":"challenge expired","retry":true}`
16
+ * whenever the process receiving the verify is not the process that ISSUED the
17
+ * challenge. The server's challenge store is an in-memory `DashMap` per
18
+ * process (`identity.rs` → `issue_challenge` / `consume_challenge`) and
19
+ * nothing shares it between replicas. So the handshake breaks whenever:
20
+ *
21
+ * • a rolling deploy briefly runs the old and the new backend container
22
+ * behind one service name (Docker DNS round-robins between them, and the
23
+ * two halves of one handshake take two different connections);
24
+ * • the backend restarts between the challenge and the verify;
25
+ * • the deployment genuinely runs more than one replica, which the server's
26
+ * own `.env.postgres.example` documents as supported.
27
+ *
28
+ * **"Expired" is a misnomer** and it is why this cost days of debugging.
29
+ * Reproduced against two 3.1.0 containers sharing one database, the split
30
+ * handshake fails in **4 ms** against a 60 s `auth.challenge_ttl_secs`.
31
+ *
32
+ * A FRESH challenge per attempt is the whole point — a consumed challenge is
33
+ * the other way to earn a 410, so a retry that reused it would fail
34
+ * identically forever. `loginWithKey` re-runs challenge→sign→verify in full.
35
+ *
36
+ * Responses carrying `retry: false` (403 bad signature, unknown public key)
37
+ * are CONFIGURATION errors and fail immediately: retrying those only buries
38
+ * the one log line that names the fix.
39
+ */
40
+ /**
41
+ * Wait until the backend is actually answering before starting the handshake.
42
+ *
43
+ * Compose's `depends_on: { condition: service_healthy }` is supposed to make
44
+ * this unnecessary. It measurably does not hold on every orchestrator: on a
45
+ * real Dokploy deploy the app logged `Listening` at 10:12:21.362 and failed
46
+ * its handshake 193ms later, while the backend that would serve it did not
47
+ * finish booting until 10:12:35.384 — **14 seconds after the app had already
48
+ * given up**. The app had handshaked against the outgoing container.
49
+ *
50
+ * Polling `/health` first turns that race into a wait. It is deliberately
51
+ * NON-fatal: a budget exhaustion returns `false` and lets the caller try the
52
+ * handshake anyway, because a readiness probe that can block boot is another
53
+ * way to never start.
54
+ */
55
+ export declare function waitForBackendReady(opts: {
56
+ serverUrl: string;
57
+ fetchImpl?: typeof globalThis.fetch;
58
+ /** Total wall-clock budget. Default 120s — longer than any cold start. */
59
+ timeoutMs?: number;
60
+ now?: () => number;
61
+ sleep?: (ms: number) => Promise<void>;
62
+ onLog?: (level: 'warn' | 'info', message: string) => void;
63
+ }): Promise<boolean>;
64
+ /** The slice of `AbracadabraClient` this needs — kept structural so tests need no SDK. */
65
+ export interface LoginCapableClient {
66
+ loginWithKey: (publicKey: string, signChallenge: (challenge: string) => Promise<string>) => Promise<string>;
67
+ }
68
+ export interface LoginRetryOptions {
69
+ client: LoginCapableClient;
70
+ publicKey: string;
71
+ sign: (challenge: string) => Promise<string>;
72
+ /** Total attempts including the first. Default 5. */
73
+ attempts?: number;
74
+ /** Injected for tests so a retry suite runs in microseconds, not seconds. */
75
+ sleep?: (ms: number) => Promise<void>;
76
+ onLog?: (level: 'warn' | 'error' | 'info', message: string) => void;
77
+ }
78
+ /**
79
+ * Is this failure worth another attempt with a fresh challenge?
80
+ *
81
+ * - `410` — this backend process did not issue our challenge. Transient by
82
+ * construction: the next attempt gets a challenge from whichever process
83
+ * answers, and only needs the verify to land on that same one.
84
+ * - `undefined` — no HTTP status at all: a socket error, DNS mid-rollover, a
85
+ * container that is listening but not yet accepting. Always transient.
86
+ * - `5xx` — the backend is up but unwell.
87
+ * - `401` / `403` — the key is not registered, or the signature is wrong.
88
+ * **Never retried.** The server itself answers these with `retry: false`.
89
+ */
90
+ export declare function isRetryableAuthStatus(status: number | undefined): boolean;
91
+ /** Exponential backoff, capped. Exported so a test can pin the schedule. */
92
+ export declare function authRetryDelayMs(attempt: number): number;
93
+ export declare function loginWithKeyRetrying(opts: LoginRetryOptions): Promise<void>;
@@ -0,0 +1,84 @@
1
+ export async function waitForBackendReady(opts) {
2
+ const doFetch = opts.fetchImpl ?? globalThis.fetch;
3
+ const timeoutMs = opts.timeoutMs ?? 12e4;
4
+ const now = opts.now ?? (() => Date.now());
5
+ const sleep = opts.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
6
+ const log = opts.onLog ?? ((level, message) => {
7
+ if (level === "warn") console.warn(message);
8
+ else console.log(message);
9
+ });
10
+ const started = now();
11
+ let attempt = 0;
12
+ let warned = false;
13
+ for (; ; ) {
14
+ attempt += 1;
15
+ try {
16
+ const res = await doFetch(`${opts.serverUrl}/health`);
17
+ if (res.ok) {
18
+ if (warned) {
19
+ log("info", `[abracadabra-service] backend ready after ${Math.round((now() - started) / 1e3)}s`);
20
+ }
21
+ return true;
22
+ }
23
+ } catch {
24
+ }
25
+ if (now() - started >= timeoutMs) {
26
+ log(
27
+ "warn",
28
+ `[abracadabra-service] ${opts.serverUrl}/health did not answer within ${Math.round(timeoutMs / 1e3)}s \u2014 attempting the handshake anyway.`
29
+ );
30
+ return false;
31
+ }
32
+ if (!warned) {
33
+ warned = true;
34
+ log(
35
+ "warn",
36
+ `[abracadabra-service] waiting for ${opts.serverUrl} to become ready \u2014 the backend is not answering /health yet.`
37
+ );
38
+ }
39
+ await sleep(Math.min(500 * 2 ** (attempt - 1), 5e3));
40
+ }
41
+ }
42
+ export function isRetryableAuthStatus(status) {
43
+ if (status === void 0) return true;
44
+ if (status === 410) return true;
45
+ return status >= 500 && status < 600;
46
+ }
47
+ export function authRetryDelayMs(attempt) {
48
+ return Math.min(250 * 2 ** (attempt - 1), 4e3);
49
+ }
50
+ export async function loginWithKeyRetrying(opts) {
51
+ const attempts = opts.attempts ?? 5;
52
+ const sleep = opts.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
53
+ const log = opts.onLog ?? ((level, message) => {
54
+ if (level === "error") console.error(message);
55
+ else if (level === "warn") console.warn(message);
56
+ else console.log(message);
57
+ });
58
+ for (let attempt = 1; ; attempt++) {
59
+ try {
60
+ await opts.client.loginWithKey(opts.publicKey, opts.sign);
61
+ if (attempt > 1) {
62
+ log("info", `[abracadabra-service] handshake succeeded on attempt ${attempt}`);
63
+ }
64
+ return;
65
+ } catch (err) {
66
+ const status = err?.status;
67
+ const message = err instanceof Error ? err.message : String(err);
68
+ if (!isRetryableAuthStatus(status)) {
69
+ log("error", `[abracadabra-service] handshake refused (${message}) \u2014 not retrying. This is a credential problem, not a transient one: the runner's public key is not the key the backend registered for its service account. The backend only registers a key at ITS OWN boot, so after rotating one, recreate the backend container too.`);
70
+ throw err;
71
+ }
72
+ if (attempt >= attempts) {
73
+ log("error", `[abracadabra-service] handshake still failing after ${attempts} attempts: ${message}`);
74
+ throw err;
75
+ }
76
+ const delay = authRetryDelayMs(attempt);
77
+ log(
78
+ "warn",
79
+ `[abracadabra-service] handshake attempt ${attempt}/${attempts} failed (${message}) \u2014 retrying with a fresh challenge in ${delay}ms.` + (status === 410 ? " A 410 here means the backend process that answered /auth/verify never issued the challenge \u2014 expected while a deploy is still swapping backend containers." : "")
80
+ );
81
+ await sleep(delay);
82
+ }
83
+ }
84
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@abraca/nuxt",
3
- "version": "2.85.0",
3
+ "version": "2.86.0",
4
4
  "description": "First-class Nuxt module for the Abracadabra CRDT collaboration platform",
5
5
  "repository": "abracadabra/abracadabra-nuxt",
6
6
  "license": "MIT",
@@ -173,9 +173,9 @@
173
173
  }
174
174
  },
175
175
  "devDependencies": {
176
- "@abraca/convert": "^2.84.0",
177
- "@abraca/dabra": "^2.84.0",
178
- "@abraca/plugin": "^2.84.0",
176
+ "@abraca/convert": "^2.85.0",
177
+ "@abraca/dabra": "^2.85.0",
178
+ "@abraca/plugin": "^2.85.0",
179
179
  "@codemirror/autocomplete": "^6.18.0",
180
180
  "@codemirror/commands": "^6.7.0",
181
181
  "@codemirror/lang-css": "^6.3.1",