suppa-mcp-2 1.42.0 → 1.42.2
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/README.md +2 -1
- package/dist/auth.js +47 -10
- package/dist/refreshLock.js +241 -0
- package/dist/server.js +10 -8
- package/dist/tools/entity.js +21 -5
- package/dist/tools/fieldTypeChange.js +45 -3
- package/dist/tools/formLifecycle.js +24 -26
- package/dist/tools/formV2.js +87 -26
- package/dist/tools/query.js +5 -1
- package/package.json +1 -1
- package/skills/suppa-form-v2/SKILL.md +4 -4
- package/skills/suppa-form-v2/VUE_COMPILER.json +2 -2
- package/skills/suppa-form-v2/references/charts.md +5 -3
- package/skills/suppa-form-v2/references/custom-chart.md +11 -9
- package/skills/suppa-form-v2/references/layout.md +1 -1
- package/skills/suppa-form-v2/references/tables.md +1 -1
- package/skills/suppa-form-v2/scripts/form-rules.mjs +1 -1
- package/skills/suppa-form-v2/scripts/validate-form-schema.mjs +24 -7
- package/skills/suppa-form-v2/scripts/vue-compiler-diagnostics.mjs +34 -0
- package/skills/suppa-form-v2/scripts/vue-compiler.mjs +18 -20
- package/skills/suppa-form-v2/scripts/widget-code.mjs +80 -35
package/README.md
CHANGED
|
@@ -546,7 +546,7 @@ the `schema` column on the row since 2.1, 58 component types — and is served b
|
|
|
546
546
|
| Tool | Description |
|
|
547
547
|
|---|---|
|
|
548
548
|
| `suppa_form_kb` | The 2.0 form knowledge base: the 58 element types, one type's prop table, a behaviour note, a reference topic, a template |
|
|
549
|
-
| `suppa_validate_form_schema` | Run the 2.0 form gate over a draft before writing it — 37 structural error codes (the authoring lints live in the source agent, not here), each chart's and each custom chart source's readiness, and widget code: every widget template is compiled with the builder's own compiler (`@vue/compiler-dom` 3.5.12,
|
|
549
|
+
| `suppa_validate_form_schema` | Run the 2.0 form gate over a draft before writing it — 37 structural error codes (the authoring lints live in the source agent, not here), each chart's and each custom chart source's readiness, and widget code: every widget template is compiled with the builder's own compiler (`@vue/compiler-dom` 3.5.12, the esm-bundler production build the builder runs) into the `compiledRender` the runtime executes, and checked against the widget sandbox |
|
|
550
550
|
| `suppa_write_form_draft` | Save a checked draft through the builder's own save (`PUT /core/forms/:id/schema`) — gated first against the live form (what the form already has does not block), guarded by the form's revision, recorded in History; saves the widget renders the gate compiled, never a hand-written one; `variables` only when the draft lists some. It never publishes |
|
|
551
551
|
| `suppa_create_form_v2` | Create a 2.0 form (create / update / custom) with its draft in one transaction — the routing flag and default variable the builder adds, optionally filed into a folder (confirm-gated) |
|
|
552
552
|
| `suppa_form_versions` | A form's published versions, the component diff between two of them, and a summary of recent draft saves (read-only) |
|
|
@@ -778,6 +778,7 @@ suppa-mcp-node/
|
|
|
778
778
|
│ ├── registry.ts # Non-secret tenant registry (~/.suppa-mcp/tenants.json)
|
|
779
779
|
│ ├── tenants.ts # Tenant context, active tenant, resolve, diagnostics
|
|
780
780
|
│ ├── auth.ts # JWT refresh (single-flight) + browser Google login
|
|
781
|
+
│ ├── refreshLock.ts # one refresh per tenant across processes (~/.suppa-mcp/locks)
|
|
781
782
|
│ ├── httpClient.ts # fetch client: retry, envelope unwrap, 401→refresh→retry
|
|
782
783
|
│ ├── utils.ts # filters, dates, JSON params, multipart, confirm gate
|
|
783
784
|
│ └── tools/
|
package/dist/auth.js
CHANGED
|
@@ -5,7 +5,8 @@
|
|
|
5
5
|
*
|
|
6
6
|
* 1. `maybeRefresh` — called from `tenants.ensureValid` before every request.
|
|
7
7
|
* If the stored access token is near expiry it GETs the refresh endpoint
|
|
8
|
-
* (under a per-tenant single-flight guard
|
|
8
|
+
* (under a per-tenant single-flight guard in this process, and a per-tenant
|
|
9
|
+
* lock file across processes — refreshLock.ts), persists the *rotated* access
|
|
9
10
|
* *and* refresh tokens, and lets the request proceed. If the refresh token
|
|
10
11
|
* itself is gone/expired it throws {@link ReloginRequired}.
|
|
11
12
|
*
|
|
@@ -26,12 +27,17 @@ import { spawn } from "node:child_process";
|
|
|
26
27
|
import { createServer } from "node:http";
|
|
27
28
|
import { readFileSync, statSync, writeFileSync } from "node:fs";
|
|
28
29
|
import { config } from "./config.js";
|
|
30
|
+
import { withRefreshLock } from "./refreshLock.js";
|
|
29
31
|
import * as store from "./store.js";
|
|
30
32
|
import * as tenants from "./tenants.js";
|
|
31
33
|
import { recordRefreshFailure, clearRefreshFailure } from "./sessionDiag.js";
|
|
32
34
|
export const REFRESH_PATH = "/api/auth/accounts/refresh-token";
|
|
33
35
|
export const OAUTH2_PATH = "/api/auth/accounts/oauth2";
|
|
34
36
|
export const EXPIRY_SKEW = 30.0; // seconds — refresh this long before the token actually expires
|
|
37
|
+
// One refresh attempt, response body included. Bounded well below the refresh lock's patience
|
|
38
|
+
// (refreshLock.ts WAIT_MS): a waiting process gives up rather than spend the token a second time, so
|
|
39
|
+
// the holder must finish — or fail — first. Two attempts at most (the verb fallback).
|
|
40
|
+
export const REFRESH_TIMEOUT_S = 15;
|
|
35
41
|
export class ReloginRequired extends Error {
|
|
36
42
|
host;
|
|
37
43
|
constructor(host) {
|
|
@@ -230,8 +236,21 @@ const rawPost = async (url, opts) => {
|
|
|
230
236
|
const reason = e instanceof Error ? e.message : String(e);
|
|
231
237
|
throw new Error(`Connection error: ${reason}`);
|
|
232
238
|
}
|
|
233
|
-
|
|
234
|
-
|
|
239
|
+
// The body is read inside the same timer: a server that answers headers and then stalls must not
|
|
240
|
+
// hold a refresh — and with it the cross-process refresh lock — open without limit.
|
|
241
|
+
let raw;
|
|
242
|
+
try {
|
|
243
|
+
raw = await resp.text();
|
|
244
|
+
}
|
|
245
|
+
catch (e) {
|
|
246
|
+
if (e instanceof Error && e.name === "AbortError") {
|
|
247
|
+
throw new Error(`Auth request to ${url} timed out after ${timeout}s.`);
|
|
248
|
+
}
|
|
249
|
+
throw e;
|
|
250
|
+
}
|
|
251
|
+
finally {
|
|
252
|
+
clearTimeout(timer);
|
|
253
|
+
}
|
|
235
254
|
if (!resp.ok) {
|
|
236
255
|
throw new AuthHttpError(resp.status, resp.statusText, method, url, raw);
|
|
237
256
|
}
|
|
@@ -326,6 +345,10 @@ function writeTokensToEnv(host, accessToken, refreshToken) {
|
|
|
326
345
|
// ---------------------------------------------------------------------------
|
|
327
346
|
// A per-host in-flight promise. Concurrent callers for the same host share the
|
|
328
347
|
// SAME refresh (exactly one network call); the entry is cleared in a finally.
|
|
348
|
+
// Across processes the same is done by a lock file (refreshLock.ts), and the
|
|
349
|
+
// credentials are re-read once it is held: another process may have rotated
|
|
350
|
+
// the pair while this one waited, and presenting the old refresh token again
|
|
351
|
+
// is what Suppa answers by revoking the session everywhere.
|
|
329
352
|
const inflight = new Map();
|
|
330
353
|
function accessExpiring(creds) {
|
|
331
354
|
const exp = creds.accessExp || jwtExp(creds.accessToken);
|
|
@@ -366,8 +389,8 @@ export async function maybeRefresh(ctx) {
|
|
|
366
389
|
}
|
|
367
390
|
let promise = inflight.get(ctx.host);
|
|
368
391
|
if (!promise) {
|
|
369
|
-
promise = (async () => {
|
|
370
|
-
// re-read under the
|
|
392
|
+
promise = withRefreshLock(ctx.host, async () => {
|
|
393
|
+
// re-read under the lock (another caller, or another process, may have refreshed)
|
|
371
394
|
const fresh = store.load(ctx.host);
|
|
372
395
|
if (!fresh || !fresh.accessToken || !accessExpiring(fresh)) {
|
|
373
396
|
return;
|
|
@@ -377,7 +400,7 @@ export async function maybeRefresh(ctx) {
|
|
|
377
400
|
throw new ReloginRequired(ctx.host);
|
|
378
401
|
}
|
|
379
402
|
await doRefresh(ctx.baseUrl, ctx.host, fresh);
|
|
380
|
-
})
|
|
403
|
+
});
|
|
381
404
|
// Ensure the map entry is cleared once this refresh settles.
|
|
382
405
|
promise = promise.finally(() => {
|
|
383
406
|
inflight.delete(ctx.host);
|
|
@@ -403,7 +426,7 @@ export async function forceRefresh(ctx) {
|
|
|
403
426
|
}
|
|
404
427
|
let promise = inflight.get(ctx.host);
|
|
405
428
|
if (!promise) {
|
|
406
|
-
promise = (async () => {
|
|
429
|
+
promise = withRefreshLock(ctx.host, async () => {
|
|
407
430
|
const fresh = store.load(ctx.host);
|
|
408
431
|
if (!fresh || refreshDead(fresh)) {
|
|
409
432
|
if (fresh) {
|
|
@@ -411,8 +434,13 @@ export async function forceRefresh(ctx) {
|
|
|
411
434
|
}
|
|
412
435
|
throw new ReloginRequired(ctx.host);
|
|
413
436
|
}
|
|
437
|
+
// Rotated by another process while this one waited for the lock: the 401 was the old
|
|
438
|
+
// access token's, the stored pair is new, and refreshing again would spend a token twice.
|
|
439
|
+
if (fresh.refreshToken !== creds.refreshToken && !accessExpiring(fresh)) {
|
|
440
|
+
return;
|
|
441
|
+
}
|
|
414
442
|
await doRefresh(ctx.baseUrl, ctx.host, fresh);
|
|
415
|
-
})
|
|
443
|
+
});
|
|
416
444
|
promise = promise.finally(() => {
|
|
417
445
|
inflight.delete(ctx.host);
|
|
418
446
|
});
|
|
@@ -450,7 +478,7 @@ async function callRefresh(baseUrl, host, creds) {
|
|
|
450
478
|
const first = refreshVerb.get(host) ?? "GET";
|
|
451
479
|
const second = first === "GET" ? "POST" : "GET";
|
|
452
480
|
try {
|
|
453
|
-
const result = await authPost(url, { cookie, method: first });
|
|
481
|
+
const result = await authPost(url, { cookie, method: first, timeout: REFRESH_TIMEOUT_S });
|
|
454
482
|
refreshVerb.set(host, first);
|
|
455
483
|
return result;
|
|
456
484
|
}
|
|
@@ -459,7 +487,7 @@ async function callRefresh(baseUrl, host, creds) {
|
|
|
459
487
|
throw e; // the route answered on the merits — asking again as a verb it
|
|
460
488
|
// does accept would just be a second failed auth attempt
|
|
461
489
|
}
|
|
462
|
-
const result = await authPost(url, { cookie, method: second });
|
|
490
|
+
const result = await authPost(url, { cookie, method: second, timeout: REFRESH_TIMEOUT_S });
|
|
463
491
|
refreshVerb.set(host, second);
|
|
464
492
|
return result;
|
|
465
493
|
}
|
|
@@ -507,6 +535,15 @@ export async function doRefresh(baseUrl, host, creds) {
|
|
|
507
535
|
fresh.refreshToken = creds.refreshToken;
|
|
508
536
|
fresh.refreshExp = creds.refreshExp;
|
|
509
537
|
}
|
|
538
|
+
// COMPARE, then save. Refreshes are serialized by the refresh lock, but login and logout are not:
|
|
539
|
+
// one that landed while this request was in flight owns the store now. Saving over it would bring
|
|
540
|
+
// a logged-out session back, or replace a fresh sign-in with the pair of the session it replaced.
|
|
541
|
+
const now = store.load(host);
|
|
542
|
+
if (!now || now.refreshToken !== creds.refreshToken) {
|
|
543
|
+
if (!now)
|
|
544
|
+
throw new ReloginRequired(host);
|
|
545
|
+
return now;
|
|
546
|
+
}
|
|
510
547
|
store.save(host, fresh);
|
|
511
548
|
clearRefreshFailure(host);
|
|
512
549
|
writeTokensToEnv(host, fresh.accessToken, fresh.refreshToken); // Persist both tokens to .env
|
|
@@ -0,0 +1,241 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* One token refresh at a time per tenant, across every suppa-mcp-2 process on this machine.
|
|
3
|
+
*
|
|
4
|
+
* Suppa ROTATES the refresh token on every refresh and treats a second use of a rotated one as
|
|
5
|
+
* theft: it revokes the session everywhere (seen live 2026-09-25, when parallel CLI probes shared one
|
|
6
|
+
* keychain entry). The single-flight guard in auth.ts only collapses refreshes inside ONE process,
|
|
7
|
+
* and one process is no longer the shape of a user's machine: since 2026-10-02 the company's Claude
|
|
8
|
+
* Code plugin starts `npx -y suppa-mcp-2@latest` in every Claude Code window, beside the `suppa` CLI.
|
|
9
|
+
* Two of them whose access tokens expire in the same minute both refreshed with the same refresh
|
|
10
|
+
* token, and the second one ended the session for all of them (reproduced with four processes:
|
|
11
|
+
* three presented the rotated token).
|
|
12
|
+
*
|
|
13
|
+
* The lock is a file created exclusively (`wx`) under the config dir; the caller re-reads the
|
|
14
|
+
* credentials AFTER it is acquired, so a process that waited uses the pair the other one stored
|
|
15
|
+
* instead of spending the rotated token again. Three things keep it a lock and not a suggestion
|
|
16
|
+
* (each found by review before release):
|
|
17
|
+
*
|
|
18
|
+
* - A HEARTBEAT, and nothing else, says the holder is alive. While its work runs the holder
|
|
19
|
+
* touches the file every HEARTBEAT_MS; only a file left untouched for STALE_MS may be taken over.
|
|
20
|
+
* An age limit alone let a slow refresh (a 60 s request timeout, a VPN, a laptop resuming) be
|
|
21
|
+
* "stale" at 30 s while it was still in flight. The holder's PID was asked too, at first, and
|
|
22
|
+
* dropped: under load `process.kill(pid, 0)` on Windows answered ESRCH for a holder that was
|
|
23
|
+
* still inside, a second process took the lock over (traced, 1 in ~40 six-process races), and a
|
|
24
|
+
* reused PID would have made a dead holder look alive. A crashed holder costs a wait of STALE_MS.
|
|
25
|
+
* - Takeover under a second lock (`<lock>.break`), with staleness judged AGAIN under it. Check,
|
|
26
|
+
* unlink, create was not atomic: with a dead holder, five of six waiting processes ended up
|
|
27
|
+
* inside together, each one deleting the fresh lock the previous one had just made.
|
|
28
|
+
* - EPERM is not "no lock here". On Windows a name another process has just deleted stays
|
|
29
|
+
* delete-pending for a moment, and creating it then fails EPERM, not EEXIST: read as "this
|
|
30
|
+
* directory takes no lock", it let a process run unlocked beside the holder (2 of 30 six-process
|
|
31
|
+
* races). EPERM / EACCES / EBUSY are retried, and a refresh runs unlocked only when a throwaway
|
|
32
|
+
* file cannot be made in the directory either — one that really refuses files. A lock name that
|
|
33
|
+
* keeps refusing in a working directory is waited out (bounded by WAIT_MS).
|
|
34
|
+
* - No unlocked fallback while a live holder works. A waiter that runs out of patience is refused
|
|
35
|
+
* with a sentence; refreshing anyway is exactly the double spend this exists to stop. Only a
|
|
36
|
+
* place where no lock can be made at all (the config dir unwritable) runs unlocked.
|
|
37
|
+
*/
|
|
38
|
+
import { closeSync, mkdirSync, openSync, readFileSync, statSync, unlinkSync, utimesSync, writeSync } from "node:fs";
|
|
39
|
+
import { randomBytes } from "node:crypto";
|
|
40
|
+
import { dirname, join } from "node:path";
|
|
41
|
+
import { homeDir } from "./registry.js";
|
|
42
|
+
/** How often a holder proves it is alive. */
|
|
43
|
+
let HEARTBEAT_MS = 2_000;
|
|
44
|
+
/** A lock untouched this long has no live holder working on it. */
|
|
45
|
+
export let STALE_MS = 10_000;
|
|
46
|
+
/** A takeover holds `.break` for microseconds; one this old was left by a crash. */
|
|
47
|
+
let BREAK_STALE_MS = 5_000;
|
|
48
|
+
/** How long a waiter waits for a LIVE holder before it gives up (a refresh is bounded well below). */
|
|
49
|
+
let WAIT_MS = 45_000;
|
|
50
|
+
/** How long create may keep failing with a transient Windows error before the dir counts as unusable. */
|
|
51
|
+
const BUSY_MS = 2_000;
|
|
52
|
+
const POLL_MS = 50;
|
|
53
|
+
/** Test-only seam: shorter timings, so heartbeat and staleness can be exercised in milliseconds. */
|
|
54
|
+
export function __setLockTiming(t) {
|
|
55
|
+
HEARTBEAT_MS = t?.heartbeat ?? 2_000;
|
|
56
|
+
STALE_MS = t?.stale ?? 10_000;
|
|
57
|
+
BREAK_STALE_MS = t?.breakStale ?? 5_000;
|
|
58
|
+
WAIT_MS = t?.wait ?? 45_000;
|
|
59
|
+
}
|
|
60
|
+
export class RefreshLockTimeout extends Error {
|
|
61
|
+
constructor(host, waitedMs) {
|
|
62
|
+
super(`Another suppa process has been refreshing the session for '${host}' for over ` +
|
|
63
|
+
`${Math.round(waitedMs / 1000)} s and is still alive, so this one did not refresh too — presenting ` +
|
|
64
|
+
"the same refresh token twice makes Suppa revoke the session everywhere. Retry in a moment.");
|
|
65
|
+
this.name = "RefreshLockTimeout";
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
/** The lock file for one tenant. */
|
|
69
|
+
export function lockPath(host) {
|
|
70
|
+
return join(homeDir(), "locks", `refresh-${host.replace(/[^A-Za-z0-9.-]/g, "_")}.lock`);
|
|
71
|
+
}
|
|
72
|
+
function readHolder(path) {
|
|
73
|
+
try {
|
|
74
|
+
return JSON.parse(readFileSync(path, "utf-8"));
|
|
75
|
+
}
|
|
76
|
+
catch {
|
|
77
|
+
return null; // half-written or gone — judged by its age instead
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
/** Milliseconds since the file was last touched, or null when it is gone. */
|
|
81
|
+
function ageOf(path) {
|
|
82
|
+
try {
|
|
83
|
+
return Date.now() - statSync(path).mtimeMs;
|
|
84
|
+
}
|
|
85
|
+
catch {
|
|
86
|
+
return null;
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
/** The lock may be taken over: its holder has not touched it for STALE_MS. */
|
|
90
|
+
function stale(path) {
|
|
91
|
+
const age = ageOf(path);
|
|
92
|
+
return age !== null && age > STALE_MS; // null: vanished — just try to create it again
|
|
93
|
+
}
|
|
94
|
+
/** What a failed exclusive create means: the lock is held, the name is briefly busy, or no lock can be made. */
|
|
95
|
+
export function createFailure(code) {
|
|
96
|
+
if (code === "EEXIST")
|
|
97
|
+
return "held";
|
|
98
|
+
// A delete-pending name (Windows), or a scanner holding the file a moment: try again.
|
|
99
|
+
if (code === "EPERM" || code === "EACCES" || code === "EBUSY")
|
|
100
|
+
return "busy";
|
|
101
|
+
return "unavailable";
|
|
102
|
+
}
|
|
103
|
+
function tryCreate(path, token) {
|
|
104
|
+
let fd;
|
|
105
|
+
try {
|
|
106
|
+
fd = openSync(path, "wx");
|
|
107
|
+
}
|
|
108
|
+
catch (e) {
|
|
109
|
+
return createFailure(e.code);
|
|
110
|
+
}
|
|
111
|
+
try {
|
|
112
|
+
writeSync(fd, JSON.stringify({ pid: process.pid, token, at: Date.now() }));
|
|
113
|
+
}
|
|
114
|
+
catch {
|
|
115
|
+
// An empty lock file is one nobody can judge but by age; do not leave it behind.
|
|
116
|
+
try {
|
|
117
|
+
closeSync(fd);
|
|
118
|
+
unlinkSync(path);
|
|
119
|
+
}
|
|
120
|
+
catch {
|
|
121
|
+
/* best effort */
|
|
122
|
+
}
|
|
123
|
+
return "unavailable";
|
|
124
|
+
}
|
|
125
|
+
closeSync(fd);
|
|
126
|
+
return "acquired";
|
|
127
|
+
}
|
|
128
|
+
/**
|
|
129
|
+
* Remove a stale lock — under `<lock>.break`, re-judging it there, so two waiters can never both
|
|
130
|
+
* decide "stale" and the second delete the lock the first one just created.
|
|
131
|
+
*/
|
|
132
|
+
function breakStale(path) {
|
|
133
|
+
const guard = `${path}.break`;
|
|
134
|
+
const token = randomBytes(8).toString("hex");
|
|
135
|
+
if (tryCreate(guard, token) !== "acquired") {
|
|
136
|
+
const age = ageOf(guard);
|
|
137
|
+
if (age !== null && age > BREAK_STALE_MS) {
|
|
138
|
+
try {
|
|
139
|
+
unlinkSync(guard); // a breaker crashed mid-takeover; the next round takes the guard
|
|
140
|
+
}
|
|
141
|
+
catch {
|
|
142
|
+
/* someone else cleared it */
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
return;
|
|
146
|
+
}
|
|
147
|
+
try {
|
|
148
|
+
if (stale(path))
|
|
149
|
+
unlinkSync(path);
|
|
150
|
+
}
|
|
151
|
+
catch {
|
|
152
|
+
/* gone already */
|
|
153
|
+
}
|
|
154
|
+
finally {
|
|
155
|
+
release(guard, token);
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
function release(path, token) {
|
|
159
|
+
// Only our own: a holder judged stale may have been replaced, and that lock is someone else's now.
|
|
160
|
+
if (readHolder(path)?.token !== token)
|
|
161
|
+
return;
|
|
162
|
+
try {
|
|
163
|
+
unlinkSync(path);
|
|
164
|
+
}
|
|
165
|
+
catch {
|
|
166
|
+
/* already gone */
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
/** Can a file be made in `dir` at all? A throwaway name, created and removed at once. */
|
|
170
|
+
function dirTakesFiles(dir) {
|
|
171
|
+
const probe = join(dir, `probe-${process.pid}-${randomBytes(4).toString("hex")}`);
|
|
172
|
+
try {
|
|
173
|
+
closeSync(openSync(probe, "wx"));
|
|
174
|
+
}
|
|
175
|
+
catch {
|
|
176
|
+
return false;
|
|
177
|
+
}
|
|
178
|
+
try {
|
|
179
|
+
unlinkSync(probe);
|
|
180
|
+
}
|
|
181
|
+
catch {
|
|
182
|
+
/* a leftover probe file costs nothing */
|
|
183
|
+
}
|
|
184
|
+
return true;
|
|
185
|
+
}
|
|
186
|
+
/** Run `fn` holding the tenant's refresh lock. Throws {@link RefreshLockTimeout} past WAIT_MS. */
|
|
187
|
+
export async function withRefreshLock(host, fn) {
|
|
188
|
+
const path = lockPath(host);
|
|
189
|
+
try {
|
|
190
|
+
mkdirSync(join(homeDir(), "locks"), { recursive: true });
|
|
191
|
+
}
|
|
192
|
+
catch {
|
|
193
|
+
return fn(); // no place for a lock: refresh unlocked rather than not at all
|
|
194
|
+
}
|
|
195
|
+
const token = randomBytes(8).toString("hex");
|
|
196
|
+
const started = Date.now();
|
|
197
|
+
let busySince = 0;
|
|
198
|
+
for (;;) {
|
|
199
|
+
const got = tryCreate(path, token);
|
|
200
|
+
if (got === "acquired")
|
|
201
|
+
break;
|
|
202
|
+
if (got === "busy" || got === "unavailable") {
|
|
203
|
+
// Unlocked ONLY when the directory itself takes no file: a lock NAME that keeps refusing in a
|
|
204
|
+
// directory that works is contention — a reader descheduled while holding the just-deleted
|
|
205
|
+
// file keeps it delete-pending — and running beside the holder is the double spend. (Seen once
|
|
206
|
+
// under the full parallel suite of `npm publish`: a 2 s busy limit alone ran a process unlocked.)
|
|
207
|
+
busySince ||= Date.now();
|
|
208
|
+
if ((got === "unavailable" || Date.now() - busySince > BUSY_MS) && !dirTakesFiles(dirname(path)))
|
|
209
|
+
return fn();
|
|
210
|
+
if (Date.now() - started > WAIT_MS)
|
|
211
|
+
throw new RefreshLockTimeout(host, Date.now() - started);
|
|
212
|
+
await new Promise((r) => setTimeout(r, 5));
|
|
213
|
+
continue;
|
|
214
|
+
}
|
|
215
|
+
busySince = 0;
|
|
216
|
+
if (stale(path)) {
|
|
217
|
+
breakStale(path);
|
|
218
|
+
continue;
|
|
219
|
+
}
|
|
220
|
+
if (Date.now() - started > WAIT_MS)
|
|
221
|
+
throw new RefreshLockTimeout(host, Date.now() - started);
|
|
222
|
+
await new Promise((r) => setTimeout(r, POLL_MS));
|
|
223
|
+
}
|
|
224
|
+
const beat = setInterval(() => {
|
|
225
|
+
try {
|
|
226
|
+
const now = new Date();
|
|
227
|
+
utimesSync(path, now, now);
|
|
228
|
+
}
|
|
229
|
+
catch {
|
|
230
|
+
/* the next beat tries again; a lock we cannot touch goes stale, which only costs a wait */
|
|
231
|
+
}
|
|
232
|
+
}, HEARTBEAT_MS);
|
|
233
|
+
beat.unref();
|
|
234
|
+
try {
|
|
235
|
+
return await fn();
|
|
236
|
+
}
|
|
237
|
+
finally {
|
|
238
|
+
clearInterval(beat);
|
|
239
|
+
release(path, token);
|
|
240
|
+
}
|
|
241
|
+
}
|
package/dist/server.js
CHANGED
|
@@ -1023,7 +1023,9 @@ export function buildToolTable() {
|
|
|
1023
1023
|
" Runs with the caller's read permissions; deleted rows are excluded. A missing LIMIT\n" +
|
|
1024
1024
|
" is added and a bigger literal one clamped, so at most `limit` rows come back, with\n" +
|
|
1025
1025
|
" `truncated` and `columns` — the result keys, nested ones as dot paths\n" +
|
|
1026
|
-
" (owner.firstName)
|
|
1026
|
+
" (owner.firstName): a TABLE column's key. A CHART's sqlCategoryColumn and\n" +
|
|
1027
|
+
" sqlValueColumns[].key take the alias, else the last segment (firstName); a dot path\n" +
|
|
1028
|
+
" there matches nothing and the chart shows demo data.",
|
|
1027
1029
|
inputSchema: {
|
|
1028
1030
|
query: z
|
|
1029
1031
|
.string()
|
|
@@ -1031,7 +1033,7 @@ export function buildToolTable() {
|
|
|
1031
1033
|
bind_params_json: z
|
|
1032
1034
|
.string()
|
|
1033
1035
|
.optional()
|
|
1034
|
-
.describe('JSON object of bind values for $name / $1 / = ANY($arr), e.g. {"owner": 479}. $current-user is set by the server.'),
|
|
1036
|
+
.describe('JSON object of bind values for $name / $1 / = ANY($arr), e.g. {"owner": 479}. $current-user is set by the server, but not in an FB2 widget; $now / $current_date never are (use NOW()).'),
|
|
1035
1037
|
limit: z
|
|
1036
1038
|
.number()
|
|
1037
1039
|
.int()
|
|
@@ -1314,10 +1316,9 @@ export function buildToolTable() {
|
|
|
1314
1316
|
" Send only what changes — everything is optional.\n\n" +
|
|
1315
1317
|
" Use it to fix a label, rename a field, flip required/unique, set a default, or\n" +
|
|
1316
1318
|
" change the field OPTIONS: searchable / searchPriority (1-4) / readOnly / canGroup /\n" +
|
|
1317
|
-
" canSort / showInTable / editFromTable / canFilter. A field
|
|
1318
|
-
"
|
|
1319
|
-
"
|
|
1320
|
-
" searchable (+searchPriority), or turning one of the others OFF.\n\n" +
|
|
1319
|
+
" canSort / showInTable / editFromTable / canFilter. A new field already has the\n" +
|
|
1320
|
+
" defaults — visible, sortable, groupable, filterable, editable, not read-only, NOT\n" +
|
|
1321
|
+
" searchable — so the usual reason to come here is searchable, or turning one OFF.\n\n" +
|
|
1321
1322
|
" WHAT THE PLATFORM DOES NOT ALLOW (refused here BEFORE any request, so a rejected\n" +
|
|
1322
1323
|
" call changes nothing):\n" +
|
|
1323
1324
|
" - The TYPE (and a timestamp's date/time/timestamp) is NOT changed here — use\n" +
|
|
@@ -1328,7 +1329,8 @@ export function buildToolTable() {
|
|
|
1328
1329
|
" canSort and canGroup off (plus unique, max_length, min_length, mask), so it\n" +
|
|
1329
1330
|
" cannot be combined with them in one call. Encrypting rewrites the existing rows.\n" +
|
|
1330
1331
|
" - A field the tenant does not own (initiator 'system' or 'application') takes only\n" +
|
|
1331
|
-
" a title and options.trackStateHistory
|
|
1332
|
+
" a title and options.trackStateHistory (an application's also a default — until the\n" +
|
|
1333
|
+
" app's next re-sync); the platform answers 403 to the rest.\n" +
|
|
1332
1334
|
" Removing a CORE field is still UI-only — this server has no remove-field call for\n" +
|
|
1333
1335
|
" one. A CUSTOM field is different: suppa_remove_custom_field parks it reversibly.\n" +
|
|
1334
1336
|
" This tool edits a custom field too — pass entity_name='<Entity>CustomFields'.\n\n" +
|
|
@@ -2621,7 +2623,7 @@ export function buildToolTable() {
|
|
|
2621
2623
|
" version; a published form reads `editing`. The save appears in the builder's History.\n\n" +
|
|
2622
2624
|
" The gate runs first, judged against the live form: what the form already has does not\n" +
|
|
2623
2625
|
" block, a refusal or an error the draft adds and nothing is written. It compiles each\n" +
|
|
2624
|
-
" widget's compiledRender from its template; a hand-written one is never saved.\n" +
|
|
2626
|
+
" changed widget's compiledRender from its template; a hand-written one is never saved.\n" +
|
|
2625
2627
|
" The row is read first and a read that does not clearly succeed ABORTS — merging over a\n" +
|
|
2626
2628
|
" failed read is how a saved mobile layout and code-form vanish on a call returning 200.\n" +
|
|
2627
2629
|
" Writes schema and settings; `variables` only when the draft lists some — the list is the\n" +
|
package/dist/tools/entity.js
CHANGED
|
@@ -2103,6 +2103,11 @@ export async function addField(entityName, fieldName, fieldType, title, opts = {
|
|
|
2103
2103
|
// options no longer hold. This tool sends no comment, so title is the only top-level key.
|
|
2104
2104
|
const _SYSTEM_FIELD_TOP_KEYS = ["title", "options"];
|
|
2105
2105
|
const _SYSTEM_FIELD_OPTION_KEYS = ["trackStateHistory"];
|
|
2106
|
+
// entity-builder develop 938f05a3 (2026-10-02, APPLICATION_EDITABLE_FIELDS): an APPLICATION-owned
|
|
2107
|
+
// field's defaultValue is tenant configuration the application cannot know in advance. Not a system
|
|
2108
|
+
// field's: every entity inherits BaseEntity's defaults. Nothing holds it across a re-sync of the
|
|
2109
|
+
// application — a sync that declares another default overwrites it.
|
|
2110
|
+
const _APPLICATION_FIELD_TOP_KEYS = ["defaultValue"];
|
|
2106
2111
|
/**
|
|
2107
2112
|
* Field types a unique index cannot cover on update: they have no column of their own
|
|
2108
2113
|
* (entity-builder ColumnBuilderUtils.physicalColumnNames → [] ; field-index-check-sync.service.ts
|
|
@@ -2166,8 +2171,9 @@ function _changeResolutionRefusal(e) {
|
|
|
2166
2171
|
* with searchable/canFilter/canSort/canGroup, which encryption forces off
|
|
2167
2172
|
* (migrations.txt:245).
|
|
2168
2173
|
* - a field the tenant does not own (initiator "system" or "application") takes a new
|
|
2169
|
-
* title and options.trackStateHistory
|
|
2170
|
-
* refused 403 by the platform
|
|
2174
|
+
* title and options.trackStateHistory — and an application-owned one a new defaultValue
|
|
2175
|
+
* (938f05a3); any other key that CHANGES the stored value is refused 403 by the platform
|
|
2176
|
+
* (metadata-protection.extension.ts, c165fc4d).
|
|
2171
2177
|
* The field's live metadata is read once to check those; a failed read SKIPS the
|
|
2172
2178
|
* checks rather than blocking a legitimate edit (same rule as _relationPreflight).
|
|
2173
2179
|
*/
|
|
@@ -2350,7 +2356,9 @@ async function _updateField(entityName, fieldName, opts, checkOnly) {
|
|
|
2350
2356
|
const fieldOwner = _protectedOwner(meta);
|
|
2351
2357
|
if (meta && fieldOwner) {
|
|
2352
2358
|
const stored = isPlainObject(meta.options) ? meta.options : {};
|
|
2353
|
-
const
|
|
2359
|
+
const appOwned = meta.initiator === "application" && meta.system !== true;
|
|
2360
|
+
const badTop = Object.keys(body).filter((k) => !_SYSTEM_FIELD_TOP_KEYS.includes(k) &&
|
|
2361
|
+
!(appOwned && _APPLICATION_FIELD_TOP_KEYS.includes(k)));
|
|
2354
2362
|
// The platform compares each option with the stored value: one sent at the value it already
|
|
2355
2363
|
// has is no change and passes.
|
|
2356
2364
|
const badOptions = Object.entries(fieldOptions ?? {})
|
|
@@ -2360,14 +2368,16 @@ async function _updateField(entityName, fieldName, opts, checkOnly) {
|
|
|
2360
2368
|
if (badTop.length > 0 || badOptions.length > 0) {
|
|
2361
2369
|
return jsonResponse({
|
|
2362
2370
|
error: `Refused: '${fieldName}' is owned by ${fieldOwner} (initiator="${String(meta.initiator ?? "system")}"). ` +
|
|
2363
|
-
"On such a field a tenant may change only its title and options.trackStateHistory
|
|
2364
|
-
'platform refuses the rest with 403
|
|
2371
|
+
"On such a field a tenant may change only its title and options.trackStateHistory (and, on an " +
|
|
2372
|
+
'application-owned field, its defaultValue) — the platform refuses the rest with 403 ' +
|
|
2373
|
+
'"Cannot modify system/application-owned metadata". ' +
|
|
2365
2374
|
"Only its owner changes them: the platform's own migration, or that application's code. " +
|
|
2366
2375
|
"Nothing was sent.",
|
|
2367
2376
|
rejected_keys: [...badTop, ...badOptions.map((k) => `options.${k}`)],
|
|
2368
2377
|
accepted_on_system_fields: [
|
|
2369
2378
|
"title",
|
|
2370
2379
|
..._SYSTEM_FIELD_OPTION_KEYS.map((k) => `options.${k}`),
|
|
2380
|
+
...(appOwned ? _APPLICATION_FIELD_TOP_KEYS.map((k) => `${k} (application-owned fields only)`) : []),
|
|
2371
2381
|
],
|
|
2372
2382
|
});
|
|
2373
2383
|
}
|
|
@@ -2445,6 +2455,12 @@ async function _updateField(entityName, fieldName, opts, checkOnly) {
|
|
|
2445
2455
|
if (notApplicable.length > 0) {
|
|
2446
2456
|
out.not_applicable = notApplicable;
|
|
2447
2457
|
}
|
|
2458
|
+
if ("defaultValue" in body && meta?.initiator === "application") {
|
|
2459
|
+
out.default_note =
|
|
2460
|
+
`'${fieldName}' is owned by an application: this default is the tenant's own, and nothing keeps ` +
|
|
2461
|
+
"it across a re-sync of that application — a redeploy that declares another default overwrites " +
|
|
2462
|
+
"it (entity-builder metadata-protection, 938f05a3). If it must last, change it in the application's code.";
|
|
2463
|
+
}
|
|
2448
2464
|
if (subTypeValue === "encrypted") {
|
|
2449
2465
|
// migrations.txt:244-247 — what the platform does to the field and its rows.
|
|
2450
2466
|
out.encryption_note =
|
|
@@ -21,8 +21,8 @@
|
|
|
21
21
|
* files, serial, bytea, tsvector and multi-type are out of scope on either side. Tables over
|
|
22
22
|
* 500,000 rows are refused (`table-too-large`, field-change-planner.service.ts:31). The refusal at
|
|
23
23
|
* write time is 400 `metadata.change_requires_resolution` with `fieldChange` and a FLAT
|
|
24
|
-
* `conflicts[]` on the body root; its `message`
|
|
25
|
-
* `conflicts[].kind`, never on the text.
|
|
24
|
+
* `conflicts[]` on the body root; its `message` was Ukrainian until aebfdc34 and is English since,
|
|
25
|
+
* so everything here keys on `code` and `conflicts[].kind`, never on the text.
|
|
26
26
|
*
|
|
27
27
|
* `update-field` is a PATCH, so what the request leaves out keeps its stored value on the new
|
|
28
28
|
* column (entity-builder f20cf2d6, 2026-09-30). A default the new type cannot hold is a
|
|
@@ -32,6 +32,11 @@
|
|
|
32
32
|
* the column saved at the earlier conversion as it was then; a change to a third type drops that
|
|
33
33
|
* saved column (`stash-dropped` — at most one is kept per field); and duplicates a conversion folds
|
|
34
34
|
* together surface only at write time. This tool says each before anything is sent.
|
|
35
|
+
*
|
|
36
|
+
* entity-builder aebfdc34 (2026-10-01): soft-deleted rows are scanned too, and their offenders are a
|
|
37
|
+
* blocking `unconvertible-deleted-values` with `recordIds` (DSE-7297 — no UI shows those rows, so the
|
|
38
|
+
* samples alone cannot find them); and an inherited `maxLength`/`minLength`/`decimalPlaces` whose
|
|
39
|
+
* meaning changes with the type is reset to null (DSE-7208). Both reach the caller here.
|
|
35
40
|
*/
|
|
36
41
|
import { makeRequest } from "../httpClient.js";
|
|
37
42
|
import { confirmRequired, jsonResponse } from "../utils.js";
|
|
@@ -70,6 +75,17 @@ const TYPE_BOUND_VALIDATIONS = {
|
|
|
70
75
|
maxValue: (to, isArray) => !isArray && (to === "numeric" || to === "integer"),
|
|
71
76
|
mask: (to, isArray) => !isArray && to === "text",
|
|
72
77
|
};
|
|
78
|
+
/**
|
|
79
|
+
* physical-type.ts OPTION_MEANING (develop aebfdc34, DSE-7208): `maxLength` is a character limit on
|
|
80
|
+
* text and the PRECISION on numeric, `minLength` exists only on text, `decimalPlaces` only on numeric.
|
|
81
|
+
* When a change moves an option to another meaning, the platform resets the inherited value to null —
|
|
82
|
+
* carried over, `text(5000) → numeric` had read 5000 as the precision and failed with a 500.
|
|
83
|
+
*/
|
|
84
|
+
const OPTION_MEANING = {
|
|
85
|
+
maxLength: (t) => (t === "text" ? "a character limit" : t === "numeric" ? "the precision (total digits)" : undefined),
|
|
86
|
+
minLength: (t) => (t === "text" ? "a character minimum" : undefined),
|
|
87
|
+
decimalPlaces: (t) => (t === "numeric" ? "the scale (digits after the point)" : undefined),
|
|
88
|
+
};
|
|
73
89
|
/** `false`, `null` and absence all mean "no CHECK"; `0` and `''` do not (isValidationSet). */
|
|
74
90
|
function isValidationSet(value) {
|
|
75
91
|
return value !== undefined && value !== null && value !== false;
|
|
@@ -89,7 +105,8 @@ function summarizePlan(plan) {
|
|
|
89
105
|
rows_exact: fc.rowsExact,
|
|
90
106
|
conflicts: conflicts.map((c) => {
|
|
91
107
|
const out = { kind: c.kind, level: c.level };
|
|
92
|
-
|
|
108
|
+
// `recordIds`: the rows a soft-delete hides from every UI and search (unconvertible-deleted-values).
|
|
109
|
+
for (const k of ["scope", "count", "countExact", "samples", "recordIds", "objectType", "objectName", "action", "resolution", "requires"]) {
|
|
93
110
|
if (c[k] !== undefined)
|
|
94
111
|
out[k] = c[k];
|
|
95
112
|
}
|
|
@@ -261,10 +278,24 @@ export async function changeFieldType(entityName, fieldName, opts = {}) {
|
|
|
261
278
|
'"stash-restore-divergence"). Pass accept_stash_restore=true only if the user wants that — ' +
|
|
262
279
|
"otherwise add a new field of that type with suppa_add_field and move the values with a query.";
|
|
263
280
|
if (refused) {
|
|
281
|
+
// DSE-7297: the conversion rewrites deleted rows too, and their values block it the same way, but
|
|
282
|
+
// no UI or normal search shows those rows — the plan carries their ids instead.
|
|
283
|
+
const deleted = summary.conflicts.filter((c) => c.kind === "unconvertible-deleted-values");
|
|
284
|
+
const ids = deleted.flatMap((c) => (Array.isArray(c.recordIds) ? c.recordIds : []));
|
|
285
|
+
const count = deleted.reduce((n, c) => n + (typeof c.count === "number" ? c.count : 0), 0);
|
|
264
286
|
return jsonResponse({
|
|
265
287
|
error: `The platform would refuse this change (decision: ${String(summary.decision)}) — nothing was ` +
|
|
266
288
|
"sent. Each blocking conflict says what stands in the way; fix the data (the samples show " +
|
|
267
289
|
"which values) and ask again.",
|
|
290
|
+
...(deleted.length
|
|
291
|
+
? {
|
|
292
|
+
deleted_rows: "Some of the values in the way are on SOFT-DELETED rows: invisible in the UI and to a normal " +
|
|
293
|
+
"search, but converted with the column all the same, so their samples alone cannot be found. " +
|
|
294
|
+
`Their ids are in the conflict's recordIds${ids.length < count ? ` (${ids.length} of the ${count} — the list is capped)` : ""}: ` +
|
|
295
|
+
"bring each back with suppa_restore_record, fix the value, delete it again with suppa_delete_record, " +
|
|
296
|
+
"then ask again.",
|
|
297
|
+
}
|
|
298
|
+
: {}),
|
|
268
299
|
target,
|
|
269
300
|
plan: summary,
|
|
270
301
|
});
|
|
@@ -291,6 +322,17 @@ export async function changeFieldType(entityName, fieldName, opts = {}) {
|
|
|
291
322
|
warnings.push(`'${fieldName}' is unique: values the conversion folds into one ('20' and '020' → 20) are ` +
|
|
292
323
|
"caught only by the write, not by this plan — the write then refuses with the duplicates.");
|
|
293
324
|
}
|
|
325
|
+
const fromType = live ? String(live.type) : "";
|
|
326
|
+
const reinterpreted = live
|
|
327
|
+
? Object.keys(OPTION_MEANING).filter((k) => isValidationSet(live[k]) && OPTION_MEANING[k](fromType) !== OPTION_MEANING[k](toType))
|
|
328
|
+
: [];
|
|
329
|
+
if (reinterpreted.length) {
|
|
330
|
+
const meaning = (k, t) => OPTION_MEANING[k](t) ?? "nothing";
|
|
331
|
+
warnings.push(`The platform resets ${reinterpreted.map((k) => `${k} (${JSON.stringify(live[k])})`).join(", ")} to null: ` +
|
|
332
|
+
reinterpreted.map((k) => `${k} is ${meaning(k, fromType)} on a ${fromType} field and ${meaning(k, toType)} on a ${toType} one`).join("; ") +
|
|
333
|
+
", so the old value would be read as something else. Set the option again for the new type with " +
|
|
334
|
+
"suppa_update_field after the change, if it matters.");
|
|
335
|
+
}
|
|
294
336
|
if (switchedOff.length) {
|
|
295
337
|
warnings.push(`The platform switches off ${switchedOff.join(", ")}: ${switchedOff.length > 1 ? "they cannot" : "it cannot"} ` +
|
|
296
338
|
`apply to a ${toType} field, so ${switchedOff.length > 1 ? "they are" : "it is"} not carried over.`);
|