@abraca/nuxt 2.77.0 → 2.79.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.d.mts CHANGED
@@ -103,6 +103,10 @@ declare module '@nuxt/schema' {
103
103
  serviceRootDocId: string;
104
104
  serviceServerUrl: string;
105
105
  serviceDisabled: boolean;
106
+ serviceRequireServiceRole: boolean;
107
+ serviceEnsureRootDoc: boolean;
108
+ serviceRootDocLabel: string;
109
+ serviceRootDocPublicAccess: string;
106
110
  };
107
111
  }
108
112
  }
@@ -418,6 +422,39 @@ interface ModuleOptions {
418
422
  serverUrl?: string;
419
423
  /** Disable the service provider even if keys are present. Default: false. */
420
424
  disabled?: boolean;
425
+ /**
426
+ * Refuse to boot runners when the authenticated identity is not actually
427
+ * `service` role. Default `true`.
428
+ *
429
+ * Without a `[[users.system_users]]` entry carrying the runner's public
430
+ * key, the runner falls back to registering an ORDINARY account. That
431
+ * account authenticates fine and then lands on `[access].authenticated`
432
+ * (typically `viewer`), so every write it makes is refused on the wire —
433
+ * the seed never echoes back, the doc cache never fills, and the app boots
434
+ * clean and stays permanently empty. Booting mute is worse than not
435
+ * booting: set this to `false` only if you genuinely want a read-only
436
+ * runner.
437
+ */
438
+ requireServiceRole?: boolean;
439
+ /**
440
+ * Create the root document over REST when it does not exist. Default
441
+ * `true` (only possible when the identity really is `service`).
442
+ *
443
+ * `[documents].auto_create` is off by default server-side, so pointing an
444
+ * app at an entry-doc id that has never existed leaves the runner waiting
445
+ * on a document nobody will create — it times out, and because that
446
+ * happens before any runner boots, the app gets no doc cache, no RPC and
447
+ * no seeding at all.
448
+ */
449
+ ensureRootDoc?: boolean;
450
+ /** Label for a root document created by `ensureRootDoc`. */
451
+ rootDocLabel?: string;
452
+ /**
453
+ * `public_access` to apply to a root document created by `ensureRootDoc` —
454
+ * `"none" | "observer" | "viewer" | "editor"`. Applied as a follow-up
455
+ * PATCH, since document creation only accepts `none`/`observer`.
456
+ */
457
+ rootDocPublicAccess?: string;
421
458
  };
422
459
  /**
423
460
  * Public plugin registry — the `abracadabra-registry-rs` instance used by
package/dist/module.json CHANGED
@@ -4,7 +4,7 @@
4
4
  "compatibility": {
5
5
  "nuxt": ">=4.0.0"
6
6
  },
7
- "version": "2.77.0",
7
+ "version": "2.79.0",
8
8
  "builder": {
9
9
  "@nuxt/module-builder": "1.0.2",
10
10
  "unbuild": "3.6.1"
package/dist/module.mjs CHANGED
@@ -139,7 +139,14 @@ const module$1 = defineNuxtModule({
139
139
  // runner falls back to the public `url` (single-origin deploys). Set it
140
140
  // to split the runner off the browser origin (public HTTPS ↔ internal).
141
141
  serviceServerUrl: options.service?.serverUrl ?? "",
142
- serviceDisabled: options.service?.disabled ?? false
142
+ serviceDisabled: options.service?.disabled ?? false,
143
+ // Default ON: a runner that authenticated but cannot write is the
144
+ // single most expensive failure mode this module has — it looks
145
+ // healthy in every log line and produces an empty site.
146
+ serviceRequireServiceRole: options.service?.requireServiceRole ?? true,
147
+ serviceEnsureRootDoc: options.service?.ensureRootDoc ?? true,
148
+ serviceRootDocLabel: options.service?.rootDocLabel ?? "",
149
+ serviceRootDocPublicAccess: options.service?.rootDocPublicAccess ?? ""
143
150
  }
144
151
  });
145
152
  nuxt.options.nitro = defu(nuxt.options.nitro, {
@@ -14,13 +14,13 @@ type __VLS_Props = {
14
14
  extraItems?: DropdownMenuItem[][];
15
15
  };
16
16
  declare const __VLS_export: import("vue").DefineComponent<__VLS_Props, {}, {}, {}, {}, import("vue").ComponentOptionsMixin, import("vue").ComponentOptionsMixin, {
17
+ logout: () => any;
17
18
  "open-settings": () => any;
18
19
  "open-account": () => any;
19
- logout: () => any;
20
20
  }, string, import("vue").PublicProps, Readonly<__VLS_Props> & Readonly<{
21
+ onLogout?: (() => any) | undefined;
21
22
  "onOpen-settings"?: (() => any) | undefined;
22
23
  "onOpen-account"?: (() => any) | undefined;
23
- onLogout?: (() => any) | undefined;
24
24
  }>, {
25
25
  color: string;
26
26
  collapsed: boolean;
@@ -14,13 +14,13 @@ type __VLS_Props = {
14
14
  extraItems?: DropdownMenuItem[][];
15
15
  };
16
16
  declare const __VLS_export: import("vue").DefineComponent<__VLS_Props, {}, {}, {}, {}, import("vue").ComponentOptionsMixin, import("vue").ComponentOptionsMixin, {
17
+ logout: () => any;
17
18
  "open-settings": () => any;
18
19
  "open-account": () => any;
19
- logout: () => any;
20
20
  }, string, import("vue").PublicProps, Readonly<__VLS_Props> & Readonly<{
21
+ onLogout?: (() => any) | undefined;
21
22
  "onOpen-settings"?: (() => any) | undefined;
22
23
  "onOpen-account"?: (() => any) | undefined;
23
- onLogout?: (() => any) | undefined;
24
24
  }>, {
25
25
  color: string;
26
26
  collapsed: boolean;
@@ -24,7 +24,7 @@ async function loadOrCreateAutoIdentity(opts) {
24
24
  try {
25
25
  const cached = JSON.parse(readFileSync(opts.cachePath, "utf-8"));
26
26
  if (cached?.publicKey && cached?.privateKey && cached?.serverUrl === opts.serverUrl) {
27
- console.log("[abracadabra-service] using cached auto-bootstrap identity:", cached.username);
27
+ console.log("[abracadabra-service] using cached fallback identity:", cached.username);
28
28
  return cached;
29
29
  }
30
30
  } catch {
@@ -42,10 +42,13 @@ async function loadOrCreateAutoIdentity(opts) {
42
42
  }
43
43
  if (!info.registration_allowed) {
44
44
  console.warn(
45
- "[abracadabra-service] auto-bootstrap aborted: server has registration_allowed=false. Set abracadabra.service.{publicKey,privateKey} module options to use a pre-registered service account."
45
+ "[abracadabra-service] fallback identity aborted: server has registration_allowed=false. Set abracadabra.service.{publicKey,privateKey} module options to use a pre-registered service account."
46
46
  );
47
47
  return null;
48
48
  }
49
+ console.warn(
50
+ "[abracadabra-service] no service.publicKey/privateKey configured \u2014 registering an ORDINARY account for this runner. It will NOT have service role, so unless this server grants writes broadly, its writes will be refused on the wire and the doc cache, seeding and RPC will silently do nothing. Configure a service account for anything but local development."
51
+ );
49
52
  const sk = opts.ed.utils.randomSecretKey();
50
53
  const pk = await opts.ed.getPublicKey(sk);
51
54
  const publicKey = toBase64Url(pk);
@@ -82,6 +85,86 @@ async function loadOrCreateAutoIdentity(opts) {
82
85
  }
83
86
  return identity;
84
87
  }
88
+ async function resolveActualRole(serverUrl, token) {
89
+ if (token && token.split(".").length === 3) {
90
+ try {
91
+ const payload = token.split(".")[1].replace(/-/g, "+").replace(/_/g, "/");
92
+ const json = JSON.parse(
93
+ Buffer.from(payload.padEnd(payload.length + (4 - payload.length % 4) % 4, "="), "base64").toString("utf-8")
94
+ );
95
+ if (typeof json.role === "string" && json.role) return json.role;
96
+ } catch {
97
+ }
98
+ }
99
+ try {
100
+ const me = await $fetch(`${serverUrl}/users/me`, {
101
+ headers: token ? { Authorization: `Bearer ${token}` } : void 0
102
+ });
103
+ return typeof me?.role === "string" ? me.role : null;
104
+ } catch {
105
+ return null;
106
+ }
107
+ }
108
+ async function ensureRootDocument(opts) {
109
+ const { serverUrl, rootDocId, token, role, label, publicAccess, enabled } = opts;
110
+ const authHeaders = token ? { Authorization: `Bearer ${token}` } : void 0;
111
+ try {
112
+ await $fetch(`${serverUrl}/docs/${rootDocId}`, { headers: authHeaders });
113
+ return true;
114
+ } catch (err) {
115
+ const status = err?.status ?? err?.statusCode;
116
+ if (status !== 404) {
117
+ return true;
118
+ }
119
+ }
120
+ if (!enabled) {
121
+ console.error(
122
+ `[abracadabra-service] root document ${rootDocId} does not exist and service.ensureRootDoc is disabled. Create it, or the runner will wait for a document nobody will make.`
123
+ );
124
+ return false;
125
+ }
126
+ if (role !== "service") {
127
+ console.error(
128
+ `[abracadabra-service] root document ${rootDocId} does not exist, and this runner is "${role ?? "unknown"}" \u2014 only a service identity may create a top-level document.
129
+ Fix ONE of these:
130
+ 1. Add a [[users.system_users]] entry (with public_key) to the server config and
131
+ point service.publicKey/privateKey at it, so this runner is service role.
132
+ 2. Seed the document server-side: [[seed.spaces]] id = "${rootDocId}"
133
+ (or ABRA_SEED_SPACES='[{"id":"${rootDocId}","label":"\u2026"}]').
134
+ 3. Create it once by hand via POST /docs with an admin token.`
135
+ );
136
+ return false;
137
+ }
138
+ try {
139
+ await $fetch(`${serverUrl}/docs`, {
140
+ method: "POST",
141
+ headers: authHeaders,
142
+ body: { id: rootDocId, label: label || "Home", kind: "space" }
143
+ });
144
+ console.log(`[abracadabra-service] created missing root document ${rootDocId}`);
145
+ } catch (e) {
146
+ console.error(
147
+ `[abracadabra-service] failed to create root document ${rootDocId}:`,
148
+ e instanceof Error ? e.message : e
149
+ );
150
+ return false;
151
+ }
152
+ if (publicAccess) {
153
+ try {
154
+ await $fetch(`${serverUrl}/docs/${rootDocId}/access`, {
155
+ method: "PATCH",
156
+ headers: authHeaders,
157
+ body: { public_access: publicAccess }
158
+ });
159
+ } catch (e) {
160
+ console.warn(
161
+ `[abracadabra-service] created ${rootDocId} but could not set public_access=${publicAccess}:`,
162
+ e instanceof Error ? e.message : e
163
+ );
164
+ }
165
+ }
166
+ return true;
167
+ }
85
168
  export default defineNitroPlugin(async (nitroApp) => {
86
169
  if (import.meta.prerender) return;
87
170
  const config = useRuntimeConfig();
@@ -93,6 +176,10 @@ export default defineNitroPlugin(async (nitroApp) => {
93
176
  const explicitPrivKey = abraConfig?.servicePrivateKey ?? "";
94
177
  const rootDocIdOverride = abraConfig?.serviceRootDocId ?? "";
95
178
  const disabled = abraConfig?.serviceDisabled ?? false;
179
+ const requireServiceRole = abraConfig?.serviceRequireServiceRole ?? true;
180
+ const ensureRootDoc = abraConfig?.serviceEnsureRootDoc ?? true;
181
+ const rootDocLabel = abraConfig?.serviceRootDocLabel ?? "";
182
+ const rootDocPublicAccess = abraConfig?.serviceRootDocPublicAccess ?? "";
96
183
  const serverUrl = abraConfig?.serviceServerUrl || config.public?.abracadabra?.url;
97
184
  if (disabled) return;
98
185
  if (!serverUrl) {
@@ -145,7 +232,30 @@ export default defineNitroPlugin(async (nitroApp) => {
145
232
  const sig = await ed.sign(fromBase64Url(challenge), privKey);
146
233
  return toBase64Url(sig);
147
234
  });
148
- console.log("[abracadabra-service] Authenticated as service role");
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".
241
+ Consequence: writes are refused ON THE WIRE with no thrown error \u2014 seeding,
242
+ the SSR doc cache and RPC handlers will appear to run and change nothing.
243
+ Runner public key: ${pubKeyB64}
244
+ Fix: add it to the server config as a service account \u2014
245
+ [[users.system_users]]
246
+ username = "app-runner"
247
+ password = "<rotate-me>"
248
+ public_key = "${pubKeyB64}"
249
+ (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
+ );
255
+ return;
256
+ }
257
+ console.warn(detail);
258
+ }
149
259
  const wsUrl = client.wsUrl;
150
260
  wsp = new AbracadabraWS({
151
261
  url: wsUrl,
@@ -158,10 +268,12 @@ export default defineNitroPlugin(async (nitroApp) => {
158
268
  WebSocketPolyfill: WSImpl
159
269
  });
160
270
  let rootDocId = rootDocIdOverride;
271
+ let rootDocFromSentinel = false;
161
272
  if (!rootDocId) {
162
273
  try {
163
274
  const info = await $fetch(`${serverUrl}/info`);
164
275
  rootDocId = info?.root_doc_id ?? "";
276
+ rootDocFromSentinel = !!rootDocId;
165
277
  } catch {
166
278
  }
167
279
  }
@@ -170,6 +282,26 @@ export default defineNitroPlugin(async (nitroApp) => {
170
282
  wsp.destroy?.();
171
283
  return;
172
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
+ }
173
305
  const rootDoc = new Y.Doc();
174
306
  const rootProvider = new AbracadabraProvider({
175
307
  client,
@@ -183,9 +315,20 @@ export default defineNitroPlugin(async (nitroApp) => {
183
315
  return toBase64Url(sig);
184
316
  }
185
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
+ });
186
323
  rootProvider.attach();
187
- await Promise.race([
324
+ const SYNC_ATTEMPTS = 3;
325
+ const SYNC_TIMEOUT_MS = 3e4;
326
+ const waitForSync = () => Promise.race([
188
327
  new Promise((resolve) => {
328
+ if (rootProvider.isSynced) {
329
+ resolve();
330
+ return;
331
+ }
189
332
  const handler = ({ state }) => {
190
333
  if (state) {
191
334
  rootProvider.off("synced", handler);
@@ -194,9 +337,38 @@ export default defineNitroPlugin(async (nitroApp) => {
194
337
  };
195
338
  rootProvider.on("synced", handler);
196
339
  }),
197
- new Promise((_, reject) => setTimeout(() => reject(new Error("sync timeout")), 3e4))
340
+ new Promise(
341
+ (_, reject) => setTimeout(() => reject(new Error("sync timeout")), SYNC_TIMEOUT_MS)
342
+ )
198
343
  ]);
199
- console.log("[abracadabra-service] Root doc synced");
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";
351
+ 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 ?? "?"}`;
359
+ }
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"}`
362
+ );
363
+ }
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
+ }
200
372
  const storage2 = useStorage();
201
373
  const ctx = {
202
374
  client,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@abraca/nuxt",
3
- "version": "2.77.0",
3
+ "version": "2.79.0",
4
4
  "description": "First-class Nuxt module for the Abracadabra CRDT collaboration platform",
5
5
  "repository": "abracadabra/abracadabra-nuxt",
6
6
  "license": "MIT",