@warlock.js/devtools 5.57.0 → 5.59.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/CHANGELOG.md +23 -0
- package/README.md +3 -0
- package/cjs/{ai-source-DTpxumMA.cjs → ai-source-BdvMfyKw.cjs} +84 -17
- package/cjs/ai-source-BdvMfyKw.cjs.map +1 -0
- package/cjs/app-versions-DfpPZOI2.cjs +253 -0
- package/cjs/app-versions-DfpPZOI2.cjs.map +1 -0
- package/cjs/{auth-DzU0gHDG.cjs → auth-B3wyjJnQ.cjs} +43 -406
- package/cjs/auth-B3wyjJnQ.cjs.map +1 -0
- package/cjs/{boot-Dy5OqgTM.cjs → boot-nczSvJ_F.cjs} +15 -12
- package/cjs/boot-nczSvJ_F.cjs.map +1 -0
- package/cjs/{capture-CqIiaznN.cjs → capture-CuyT8Vab.cjs} +4 -4
- package/cjs/{capture-CqIiaznN.cjs.map → capture-CuyT8Vab.cjs.map} +1 -1
- package/cjs/{cascade-store-pHjKeSFm.cjs → cascade-store-CuRRYzt_.cjs} +141 -4
- package/cjs/cascade-store-CuRRYzt_.cjs.map +1 -0
- package/cjs/{current-request-id-BoJJb3y7.cjs → current-request-id-CeQhRz9Q.cjs} +3 -3
- package/cjs/{current-request-id-BoJJb3y7.cjs.map → current-request-id-CeQhRz9Q.cjs.map} +1 -1
- package/cjs/{errors-CyZp5yS-.cjs → errors-BadbSDX8.cjs} +6 -4
- package/cjs/errors-BadbSDX8.cjs.map +1 -0
- package/cjs/helpers-BcMBFy9v.cjs +439 -0
- package/cjs/helpers-BcMBFy9v.cjs.map +1 -0
- package/cjs/{histogram-BaI-PnCv.cjs → histogram-DTOGnNBW.cjs} +6 -6
- package/cjs/{histogram-BaI-PnCv.cjs.map → histogram-DTOGnNBW.cjs.map} +1 -1
- package/cjs/{http-DCfXQvw-.cjs → http-Biauhqi0.cjs} +517 -28
- package/cjs/http-Biauhqi0.cjs.map +1 -0
- package/cjs/index.cjs +1 -1
- package/cjs/{insights-BKtqxdnP.cjs → insights-BjJA6Ret.cjs} +8 -7
- package/cjs/{insights-BKtqxdnP.cjs.map → insights-BjJA6Ret.cjs.map} +1 -1
- package/cjs/{migrations-w7GMsrQw.cjs → migrations-BP4cYTGo.cjs} +40 -5
- package/cjs/migrations-BP4cYTGo.cjs.map +1 -0
- package/cjs/{options-CWqFC5__.cjs → options-B9FHbRAJ.cjs} +29 -5
- package/cjs/options-B9FHbRAJ.cjs.map +1 -0
- package/cjs/{panels-Rcmeitu3.cjs → panels-D1ITm-jc.cjs} +77 -11
- package/cjs/panels-D1ITm-jc.cjs.map +1 -0
- package/cjs/{process-panel-DEOnLxoT.cjs → process-panel-DskSA7Cm.cjs} +4 -4
- package/cjs/{process-panel-DEOnLxoT.cjs.map → process-panel-DskSA7Cm.cjs.map} +1 -1
- package/cjs/production/index.cjs +4 -4
- package/cjs/{server-ykxsOwob.cjs → server-D3XRbSSb.cjs} +8 -5
- package/cjs/server-D3XRbSSb.cjs.map +1 -0
- package/cjs/{src-UPtTCI2j.cjs → src-QcNghoYN.cjs} +52 -15
- package/cjs/src-QcNghoYN.cjs.map +1 -0
- package/cjs/{store-aq207T8v.cjs → store-CNFv3wVp.cjs} +2 -2
- package/cjs/{stream-route-CJTABkUy.cjs → stream-route-BqyAlfxQ.cjs} +92 -17
- package/cjs/stream-route-BqyAlfxQ.cjs.map +1 -0
- package/esm/app-versions.mjs +74 -0
- package/esm/app-versions.mjs.map +1 -0
- package/esm/devtools-connector.d.mts.map +1 -1
- package/esm/devtools-connector.mjs +10 -3
- package/esm/devtools-connector.mjs.map +1 -1
- package/esm/index.d.mts +3 -3
- package/esm/panel-errors.mjs +33 -0
- package/esm/panel-errors.mjs.map +1 -0
- package/esm/panels.mjs +73 -6
- package/esm/panels.mjs.map +1 -1
- package/esm/production/auth/helpers.mjs +8 -5
- package/esm/production/auth/helpers.mjs.map +1 -1
- package/esm/production/auth/service.mjs +15 -5
- package/esm/production/auth/service.mjs.map +1 -1
- package/esm/production/boot.mjs +5 -2
- package/esm/production/boot.mjs.map +1 -1
- package/esm/production/contracts.d.mts +75 -2
- package/esm/production/contracts.d.mts.map +1 -1
- package/esm/production/contracts.mjs +5 -1
- package/esm/production/contracts.mjs.map +1 -1
- package/esm/production/errors.d.mts +1 -1
- package/esm/production/errors.mjs +5 -3
- package/esm/production/errors.mjs.map +1 -1
- package/esm/production/http/access.mjs +6 -2
- package/esm/production/http/access.mjs.map +1 -1
- package/esm/production/http/constants.mjs +7 -1
- package/esm/production/http/constants.mjs.map +1 -1
- package/esm/production/http/context.mjs.map +1 -1
- package/esm/production/http/cookie.mjs +23 -2
- package/esm/production/http/cookie.mjs.map +1 -1
- package/esm/production/http/mount.mjs +25 -3
- package/esm/production/http/mount.mjs.map +1 -1
- package/esm/production/http/share-session.mjs +114 -0
- package/esm/production/http/share-session.mjs.map +1 -0
- package/esm/production/http/share.mjs +339 -0
- package/esm/production/http/share.mjs.map +1 -0
- package/esm/production/index.d.mts +2 -2
- package/esm/production/insights/writer.mjs +2 -1
- package/esm/production/insights/writer.mjs.map +1 -1
- package/esm/production/options.d.mts +10 -1
- package/esm/production/options.d.mts.map +1 -1
- package/esm/production/options.mjs +27 -3
- package/esm/production/options.mjs.map +1 -1
- package/esm/production/store/cascade-store.mjs +49 -2
- package/esm/production/store/cascade-store.mjs.map +1 -1
- package/esm/production/store/mapping.mjs +29 -1
- package/esm/production/store/mapping.mjs.map +1 -1
- package/esm/production/store/memory-store.mjs +62 -0
- package/esm/production/store/memory-store.mjs.map +1 -1
- package/esm/production/store/migrations.d.mts +2 -1
- package/esm/production/store/migrations.d.mts.map +1 -1
- package/esm/production/store/migrations.mjs +5 -2
- package/esm/production/store/migrations.mjs.map +1 -1
- package/esm/production/store/models/index.mjs +3 -1
- package/esm/production/store/models/share.migration.mjs +27 -0
- package/esm/production/store/models/share.migration.mjs.map +1 -0
- package/esm/production/store/models/share.model.mjs +13 -0
- package/esm/production/store/models/share.model.mjs.map +1 -0
- package/esm/server/ai-routes.mjs +20 -6
- package/esm/server/ai-routes.mjs.map +1 -1
- package/esm/server/panel-files.mjs +35 -0
- package/esm/server/panel-files.mjs.map +1 -0
- package/esm/server/panel-routes.mjs +27 -7
- package/esm/server/panel-routes.mjs.map +1 -1
- package/esm/server/session-routes.mjs +4 -1
- package/esm/server/session-routes.mjs.map +1 -1
- package/esm/sources/ai-source.d.mts.map +1 -1
- package/esm/sources/ai-source.mjs +75 -7
- package/esm/sources/ai-source.mjs.map +1 -1
- package/esm/types.d.mts +91 -3
- package/esm/types.d.mts.map +1 -1
- package/llms-full.txt +57 -19
- package/package.json +8 -8
- package/skills/SKILL.md +57 -19
- package/ui/dashboard/assets/app.css +1 -1
- package/ui/dashboard/assets/app.js +16 -16
- package/ui/dashboard/build-info.json +7 -7
- package/cjs/ai-source-DTpxumMA.cjs.map +0 -1
- package/cjs/auth-DzU0gHDG.cjs.map +0 -1
- package/cjs/boot-Dy5OqgTM.cjs.map +0 -1
- package/cjs/cascade-store-pHjKeSFm.cjs.map +0 -1
- package/cjs/contracts-CVmplkNb.cjs +0 -112
- package/cjs/contracts-CVmplkNb.cjs.map +0 -1
- package/cjs/errors-CyZp5yS-.cjs.map +0 -1
- package/cjs/http-DCfXQvw-.cjs.map +0 -1
- package/cjs/migrations-w7GMsrQw.cjs.map +0 -1
- package/cjs/options-CWqFC5__.cjs.map +0 -1
- package/cjs/panels-Rcmeitu3.cjs.map +0 -1
- package/cjs/rolldown-runtime-Zuuoy_Rh.cjs +0 -52
- package/cjs/server-ykxsOwob.cjs.map +0 -1
- package/cjs/src-UPtTCI2j.cjs.map +0 -1
- package/cjs/stream-route-CJTABkUy.cjs.map +0 -1
|
@@ -0,0 +1,339 @@
|
|
|
1
|
+
import { DEVTOOLS_FAILURE_AUDIT_TYPES } from "../contracts.mjs";
|
|
2
|
+
import { panelContentType } from "../../panels.mjs";
|
|
3
|
+
import { DevtoolsApiError } from "../errors.mjs";
|
|
4
|
+
import { rateLimitClient } from "./ip.mjs";
|
|
5
|
+
import { generateToken, hashToken } from "../auth/helpers.mjs";
|
|
6
|
+
import { devtoolsRequestContext } from "./context.mjs";
|
|
7
|
+
import { readCookie, shareCookie, shareCookieName } from "./cookie.mjs";
|
|
8
|
+
import { sendFile } from "../../server/ui-assets.mjs";
|
|
9
|
+
import { sendPanelFile } from "../../server/panel-routes.mjs";
|
|
10
|
+
import { createShareSessions } from "./share-session.mjs";
|
|
11
|
+
|
|
12
|
+
//#region ../../packages/devtools/src/production/http/share.ts
|
|
13
|
+
const DAY_MS = 864e5;
|
|
14
|
+
const MAX_TOKEN = 512;
|
|
15
|
+
const MAX_PANEL_ID = 64;
|
|
16
|
+
/** A failed token is not looked up again for this long once its client is over the limit. */
|
|
17
|
+
const BLOCK_CACHE_MS = 3e4;
|
|
18
|
+
const BLOCK_CACHE_SIZE = 1e3;
|
|
19
|
+
/** A cookie failure is audited at most this often per client (a revoked link in use must not flood the log). */
|
|
20
|
+
const COOKIE_AUDIT_INTERVAL_MS = 6e4;
|
|
21
|
+
/** The path pattern `pattern` (`/flows/:feature`) matched against `path`, as its params; `null` for no match. */
|
|
22
|
+
function matchSharePath(pattern, path) {
|
|
23
|
+
if (/[\0\\]/.test(path)) return null;
|
|
24
|
+
const wanted = pattern.split("/");
|
|
25
|
+
const given = path.split("/");
|
|
26
|
+
if (wanted.length !== given.length) return null;
|
|
27
|
+
const params = {};
|
|
28
|
+
for (const [index, part] of wanted.entries()) {
|
|
29
|
+
const actual = given[index];
|
|
30
|
+
if (actual === void 0) return null;
|
|
31
|
+
if (part.startsWith(":")) {
|
|
32
|
+
if (actual === "") return null;
|
|
33
|
+
params[part.slice(1)] = actual;
|
|
34
|
+
} else if (part !== actual) return null;
|
|
35
|
+
}
|
|
36
|
+
return params;
|
|
37
|
+
}
|
|
38
|
+
function bodyOf(request) {
|
|
39
|
+
const body = request.body;
|
|
40
|
+
if (body === null || typeof body !== "object" || Array.isArray(body)) throw new DevtoolsApiError("input.invalid");
|
|
41
|
+
return body;
|
|
42
|
+
}
|
|
43
|
+
function viewOf(record, createdBy, at) {
|
|
44
|
+
return {
|
|
45
|
+
id: record.id,
|
|
46
|
+
panel: record.panel,
|
|
47
|
+
label: record.label,
|
|
48
|
+
createdBy,
|
|
49
|
+
createdAt: record.createdAt,
|
|
50
|
+
expiresAt: record.expiresAt,
|
|
51
|
+
revokedAt: record.revokedAt,
|
|
52
|
+
lastUsedAt: record.lastUsedAt,
|
|
53
|
+
uses: record.uses,
|
|
54
|
+
status: record.revokedAt !== null ? "revoked" : record.expiresAt <= at ? "expired" : "active"
|
|
55
|
+
};
|
|
56
|
+
}
|
|
57
|
+
function openAnswer(grant) {
|
|
58
|
+
const { panel, share } = grant;
|
|
59
|
+
return {
|
|
60
|
+
panel: panel.id,
|
|
61
|
+
title: panel.title,
|
|
62
|
+
label: share.label,
|
|
63
|
+
expiresAt: share.expiresAt,
|
|
64
|
+
assets: [...panel.share?.assets ?? []],
|
|
65
|
+
files: panel.share?.files === true
|
|
66
|
+
};
|
|
67
|
+
}
|
|
68
|
+
/**
|
|
69
|
+
* Read-only share links of the production monitor. An admin creates a link
|
|
70
|
+
* for a panel that declares `share`; the token is shown once and only its
|
|
71
|
+
* SHA-256 is stored. Opening a link exchanges the token for a scoped cookie
|
|
72
|
+
* (`__Secure-warlock-devtools-share`) that reaches only that panel's shared
|
|
73
|
+
* view. Every refusal answers the dashboard's uniform 404, is audited as
|
|
74
|
+
* `share.failed` (which counts toward the per-IP failure limit) and never
|
|
75
|
+
* records the token.
|
|
76
|
+
*/
|
|
77
|
+
function createDevtoolsShare(deps) {
|
|
78
|
+
const { production, store, auth } = deps;
|
|
79
|
+
const now = deps.now ?? (() => Date.now());
|
|
80
|
+
if (typeof deps.hmac !== "function") throw new Error("Share links need deps.hmac (HMAC-SHA256 keyed with encryption.key).");
|
|
81
|
+
const sessions = createShareSessions({
|
|
82
|
+
store,
|
|
83
|
+
panels: deps.panels,
|
|
84
|
+
hmac: deps.hmac,
|
|
85
|
+
now,
|
|
86
|
+
...deps.warn ? { warn: deps.warn } : {}
|
|
87
|
+
});
|
|
88
|
+
const cookieOptions = {
|
|
89
|
+
path: production.path,
|
|
90
|
+
secure: production.requireHttps
|
|
91
|
+
};
|
|
92
|
+
const cookieName = shareCookieName(production.requireHttps);
|
|
93
|
+
const sharePanels = deps.panels.filter((panel) => panel.share !== null);
|
|
94
|
+
const blocked = /* @__PURE__ */ new Map();
|
|
95
|
+
const cookieAudited = /* @__PURE__ */ new Map();
|
|
96
|
+
const limits = production.rateLimits;
|
|
97
|
+
const windowMs = limits.windowMinutes * 6e4;
|
|
98
|
+
async function overLimit(ip) {
|
|
99
|
+
const client = rateLimitClient(ip);
|
|
100
|
+
const at = now();
|
|
101
|
+
const until = blocked.get(client);
|
|
102
|
+
if (until !== void 0 && at < until) return true;
|
|
103
|
+
const state = await store.state.read();
|
|
104
|
+
const since = Math.max(at - windowMs, state.failuresResetAt ?? 0);
|
|
105
|
+
const count = await store.audit.count({
|
|
106
|
+
types: DEVTOOLS_FAILURE_AUDIT_TYPES,
|
|
107
|
+
since,
|
|
108
|
+
ip
|
|
109
|
+
});
|
|
110
|
+
blocked.delete(client);
|
|
111
|
+
if (count < limits.ip) return false;
|
|
112
|
+
if (blocked.size >= BLOCK_CACHE_SIZE) {
|
|
113
|
+
const oldest = blocked.keys().next();
|
|
114
|
+
if (!oldest.done) blocked.delete(oldest.value);
|
|
115
|
+
}
|
|
116
|
+
blocked.set(client, at + BLOCK_CACHE_MS);
|
|
117
|
+
return true;
|
|
118
|
+
}
|
|
119
|
+
/** Writes one `share.failed` entry (never the token). Never throws. */
|
|
120
|
+
async function failed(meta, reason, shareId) {
|
|
121
|
+
await auth.audit("share.failed", {
|
|
122
|
+
meta,
|
|
123
|
+
detail: {
|
|
124
|
+
reason,
|
|
125
|
+
share: shareId
|
|
126
|
+
}
|
|
127
|
+
});
|
|
128
|
+
}
|
|
129
|
+
/** The cookie check for a share request. */
|
|
130
|
+
async function authorize(request, meta) {
|
|
131
|
+
const value = readCookie(request.headers.cookie, cookieName);
|
|
132
|
+
if (value === void 0) return null;
|
|
133
|
+
let result;
|
|
134
|
+
try {
|
|
135
|
+
result = await sessions.verify(value);
|
|
136
|
+
} catch (error) {
|
|
137
|
+
deps.warn?.(`A devtools share link could not be checked and the request was refused: ${error instanceof Error ? error.message : String(error)}`);
|
|
138
|
+
return null;
|
|
139
|
+
}
|
|
140
|
+
if ("grant" in result) {
|
|
141
|
+
sessions.touch(result.grant.share.id);
|
|
142
|
+
return result.grant;
|
|
143
|
+
}
|
|
144
|
+
const client = rateLimitClient(meta.ip);
|
|
145
|
+
const last = cookieAudited.get(client);
|
|
146
|
+
if (last === void 0 || now() - last >= COOKIE_AUDIT_INTERVAL_MS) {
|
|
147
|
+
cookieAudited.delete(client);
|
|
148
|
+
if (cookieAudited.size >= BLOCK_CACHE_SIZE) {
|
|
149
|
+
const oldest = cookieAudited.keys().next();
|
|
150
|
+
if (!oldest.done) cookieAudited.delete(oldest.value);
|
|
151
|
+
}
|
|
152
|
+
cookieAudited.set(client, now());
|
|
153
|
+
try {
|
|
154
|
+
if (!await overLimit(meta.ip)) await failed(meta, result.refused, result.shareId);
|
|
155
|
+
} catch {}
|
|
156
|
+
}
|
|
157
|
+
return null;
|
|
158
|
+
}
|
|
159
|
+
function grantOf(request) {
|
|
160
|
+
const grant = devtoolsRequestContext(request)?.share;
|
|
161
|
+
if (!grant) throw new Error("A share route ran without its grant.");
|
|
162
|
+
return grant;
|
|
163
|
+
}
|
|
164
|
+
function createdByOf(accounts, id) {
|
|
165
|
+
return accounts.find((account) => account.id === id)?.email ?? null;
|
|
166
|
+
}
|
|
167
|
+
async function list() {
|
|
168
|
+
const [records, accounts] = await Promise.all([store.shares.list(), store.accounts.list()]);
|
|
169
|
+
const at = now();
|
|
170
|
+
return {
|
|
171
|
+
enabled: true,
|
|
172
|
+
maxDays: production.share.maxDays,
|
|
173
|
+
panels: sharePanels.map((panel) => ({
|
|
174
|
+
id: panel.id,
|
|
175
|
+
title: panel.title
|
|
176
|
+
})),
|
|
177
|
+
shares: records.map((record) => viewOf(record, createdByOf(accounts, record.createdBy), at))
|
|
178
|
+
};
|
|
179
|
+
}
|
|
180
|
+
async function create(authenticated, meta, body) {
|
|
181
|
+
const panel = body.panel;
|
|
182
|
+
const label = typeof body.label === "string" ? body.label.trim() : "";
|
|
183
|
+
const days = body.days;
|
|
184
|
+
if (typeof panel !== "string" || panel.length > MAX_PANEL_ID || !sharePanels.some((item) => item.id === panel) || label === "" || label.length > 80 || /[\u0000-\u001f\u007f]/.test(label) || typeof days !== "number" || !Number.isInteger(days) || days < 1 || days > production.share.maxDays) throw new DevtoolsApiError("input.invalid");
|
|
185
|
+
const token = generateToken();
|
|
186
|
+
const at = now();
|
|
187
|
+
const record = await store.shares.create({
|
|
188
|
+
tokenHash: hashToken(token),
|
|
189
|
+
panel,
|
|
190
|
+
label,
|
|
191
|
+
createdBy: authenticated.account.id,
|
|
192
|
+
createdAt: at,
|
|
193
|
+
expiresAt: at + days * DAY_MS
|
|
194
|
+
});
|
|
195
|
+
sessions.invalidate();
|
|
196
|
+
await auth.audit("share.created", {
|
|
197
|
+
auth: authenticated,
|
|
198
|
+
meta,
|
|
199
|
+
detail: {
|
|
200
|
+
share: record.id,
|
|
201
|
+
panel,
|
|
202
|
+
days
|
|
203
|
+
}
|
|
204
|
+
});
|
|
205
|
+
return {
|
|
206
|
+
share: viewOf(record, authenticated.account.email, at),
|
|
207
|
+
url: `${meta.origin}${production.path}/#/share/${token}`
|
|
208
|
+
};
|
|
209
|
+
}
|
|
210
|
+
function register(server, notFound) {
|
|
211
|
+
const requireAuth = (request) => {
|
|
212
|
+
const context = devtoolsRequestContext(request);
|
|
213
|
+
if (!context?.authenticated) throw new Error("A dashboard route ran without its session.");
|
|
214
|
+
return {
|
|
215
|
+
auth: context.authenticated,
|
|
216
|
+
meta: context.meta
|
|
217
|
+
};
|
|
218
|
+
};
|
|
219
|
+
server.post("/api/share/open", async (request, reply) => {
|
|
220
|
+
const context = devtoolsRequestContext(request);
|
|
221
|
+
if (!context) return notFound(request, reply);
|
|
222
|
+
const { meta } = context;
|
|
223
|
+
const token = request.body?.token;
|
|
224
|
+
if (typeof token !== "string" || token === "" || token.length > MAX_TOKEN) return notFound(request, reply);
|
|
225
|
+
try {
|
|
226
|
+
if (await overLimit(meta.ip)) return notFound(request, reply);
|
|
227
|
+
const result = await sessions.open(hashToken(token));
|
|
228
|
+
if (!("grant" in result)) {
|
|
229
|
+
await failed(meta, result.refused, result.shareId);
|
|
230
|
+
return notFound(request, reply);
|
|
231
|
+
}
|
|
232
|
+
const { value, maxAgeSeconds } = sessions.issue(result.grant.share);
|
|
233
|
+
sessions.touch(result.grant.share.id);
|
|
234
|
+
reply.header("set-cookie", shareCookie(value, {
|
|
235
|
+
...cookieOptions,
|
|
236
|
+
maxAgeSeconds
|
|
237
|
+
}));
|
|
238
|
+
return openAnswer(result.grant);
|
|
239
|
+
} catch (error) {
|
|
240
|
+
deps.warn?.(`A devtools share link could not be opened: ${error instanceof Error ? error.message : String(error)}`);
|
|
241
|
+
return notFound(request, reply);
|
|
242
|
+
}
|
|
243
|
+
});
|
|
244
|
+
server.get("/api/share/info", async (request) => openAnswer(grantOf(request)));
|
|
245
|
+
server.get("/api/share/view.js", async (request, reply) => {
|
|
246
|
+
const view = grantOf(request).panel.share?.view;
|
|
247
|
+
if (view === void 0) return notFound(request, reply);
|
|
248
|
+
sendFile(reply, view, "text/javascript; charset=utf-8");
|
|
249
|
+
return reply;
|
|
250
|
+
});
|
|
251
|
+
server.get("/api/share/assets/:name", async (request, reply) => {
|
|
252
|
+
const { panel } = grantOf(request);
|
|
253
|
+
const name = request.params.name;
|
|
254
|
+
const file = panel.share?.assets.includes(name) === true && Object.hasOwn(panel.assets, name) ? panel.assets[name] : void 0;
|
|
255
|
+
if (file === void 0) return notFound(request, reply);
|
|
256
|
+
sendFile(reply, file, panelContentType(name));
|
|
257
|
+
return reply;
|
|
258
|
+
});
|
|
259
|
+
server.get("/api/share/files/*", async (request, reply) => {
|
|
260
|
+
const { panel } = grantOf(request);
|
|
261
|
+
return sendPanelFile({ files: panel.share?.files === true ? panel.files : null }, request.params["*"], request, reply, notFound);
|
|
262
|
+
});
|
|
263
|
+
const panelRoute = async (request, reply) => {
|
|
264
|
+
const { panel } = grantOf(request);
|
|
265
|
+
const sub = request.params["*"];
|
|
266
|
+
const path = sub === void 0 || sub === "" ? "" : `/${sub}`;
|
|
267
|
+
let matched = null;
|
|
268
|
+
for (const pattern of panel.share?.routes ?? []) {
|
|
269
|
+
const params = matchSharePath(pattern, path);
|
|
270
|
+
const route = panel.routes.find((candidate) => candidate.method === "GET" && candidate.path === pattern);
|
|
271
|
+
if (params !== null && route !== void 0) {
|
|
272
|
+
matched = {
|
|
273
|
+
route,
|
|
274
|
+
params
|
|
275
|
+
};
|
|
276
|
+
break;
|
|
277
|
+
}
|
|
278
|
+
}
|
|
279
|
+
if (matched === null) return notFound(request, reply);
|
|
280
|
+
const input = {
|
|
281
|
+
params: matched.params,
|
|
282
|
+
query: request.query ?? {},
|
|
283
|
+
body: void 0,
|
|
284
|
+
shared: true
|
|
285
|
+
};
|
|
286
|
+
const result = await matched.route.handler(input);
|
|
287
|
+
reply.header("cache-control", "no-store");
|
|
288
|
+
if (result === void 0) return reply.code(204).send();
|
|
289
|
+
return result;
|
|
290
|
+
};
|
|
291
|
+
server.get("/api/share/panel", panelRoute);
|
|
292
|
+
server.get("/api/share/panel/*", panelRoute);
|
|
293
|
+
server.get("/api/admin/shares", async () => list());
|
|
294
|
+
server.post("/api/admin/shares", async (request, reply) => {
|
|
295
|
+
const { auth: authenticated, meta } = requireAuth(request);
|
|
296
|
+
const created = await create(authenticated, meta, bodyOf(request));
|
|
297
|
+
return reply.code(201).send(created);
|
|
298
|
+
});
|
|
299
|
+
server.delete("/api/admin/shares/:id", async (request, reply) => {
|
|
300
|
+
const { auth: authenticated, meta } = requireAuth(request);
|
|
301
|
+
const id = request.params.id;
|
|
302
|
+
if (typeof id !== "string" || id === "" || id.length > 64) throw new DevtoolsApiError("input.invalid");
|
|
303
|
+
const record = await store.shares.get(id);
|
|
304
|
+
if (!record || !await store.shares.revoke(id, now())) throw new DevtoolsApiError("share.not-found");
|
|
305
|
+
sessions.invalidate();
|
|
306
|
+
await auth.audit("share.revoked", {
|
|
307
|
+
auth: authenticated,
|
|
308
|
+
meta,
|
|
309
|
+
detail: {
|
|
310
|
+
share: id,
|
|
311
|
+
panel: record.panel
|
|
312
|
+
}
|
|
313
|
+
});
|
|
314
|
+
return reply.code(204).send();
|
|
315
|
+
});
|
|
316
|
+
server.post("/api/admin/shares/revoke-all", async (request) => {
|
|
317
|
+
const { auth: authenticated, meta } = requireAuth(request);
|
|
318
|
+
const revoked = await store.shares.revokeAll(now());
|
|
319
|
+
sessions.invalidate();
|
|
320
|
+
await auth.audit("share.revoked", {
|
|
321
|
+
auth: authenticated,
|
|
322
|
+
meta,
|
|
323
|
+
detail: {
|
|
324
|
+
all: true,
|
|
325
|
+
count: revoked
|
|
326
|
+
}
|
|
327
|
+
});
|
|
328
|
+
return { revoked };
|
|
329
|
+
});
|
|
330
|
+
}
|
|
331
|
+
return {
|
|
332
|
+
authorize,
|
|
333
|
+
register
|
|
334
|
+
};
|
|
335
|
+
}
|
|
336
|
+
|
|
337
|
+
//#endregion
|
|
338
|
+
export { createDevtoolsShare, matchSharePath };
|
|
339
|
+
//# sourceMappingURL=share.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"share.mjs","names":[],"sources":["../../../../../../../../../packages/devtools/src/production/http/share.ts"],"sourcesContent":["import type { FastifyInstance, FastifyReply, FastifyRequest } from \"fastify\";\nimport { panelContentType, type MountedDevtoolsPanel } from \"../../panels\";\nimport { sendPanelFile } from \"../../server/panel-routes\";\nimport { sendFile } from \"../../server/ui-assets\";\nimport type { DevtoolsPanelRequest } from \"../../types\";\nimport { generateToken, hashToken } from \"../auth/helpers\";\nimport type { DevtoolsAuthenticated, DevtoolsRequestMeta } from \"../auth/types\";\nimport {\n DEVTOOLS_FAILURE_AUDIT_TYPES,\n DEVTOOLS_SHARE_LABEL_MAX,\n type DevtoolsCreatedShare,\n type DevtoolsShareList,\n type DevtoolsShareOpenAnswer,\n type DevtoolsShareView,\n} from \"../contracts\";\nimport { DevtoolsApiError } from \"../errors\";\nimport type { DevtoolsShareRecord } from \"../store/types\";\nimport { devtoolsRequestContext } from \"./context\";\nimport { readCookie, shareCookie, shareCookieName } from \"./cookie\";\nimport { rateLimitClient } from \"./ip\";\nimport { createShareSessions, type DevtoolsShareGrant } from \"./share-session\";\nimport type { MountProductionDevtoolsDeps } from \"./types\";\n\nconst DAY_MS = 86_400_000;\nconst MAX_TOKEN = 512;\nconst MAX_PANEL_ID = 64;\n\n/** A failed token is not looked up again for this long once its client is over the limit. */\nconst BLOCK_CACHE_MS = 30_000;\nconst BLOCK_CACHE_SIZE = 1000;\n\n/** A cookie failure is audited at most this often per client (a revoked link in use must not flood the log). */\nconst COOKIE_AUDIT_INTERVAL_MS = 60_000;\n\ntype Notfound = (request: FastifyRequest, reply: FastifyReply) => FastifyReply;\n\n/** The path pattern `pattern` (`/flows/:feature`) matched against `path`, as its params; `null` for no match. */\nexport function matchSharePath(pattern: string, path: string): Record<string, string> | null {\n if (/[\\0\\\\]/.test(path)) return null;\n\n const wanted = pattern.split(\"/\");\n const given = path.split(\"/\");\n\n if (wanted.length !== given.length) return null;\n\n const params: Record<string, string> = {};\n\n for (const [index, part] of wanted.entries()) {\n const actual = given[index];\n\n if (actual === undefined) return null;\n\n if (part.startsWith(\":\")) {\n if (actual === \"\") return null;\n\n params[part.slice(1)] = actual;\n } else if (part !== actual) {\n return null;\n }\n }\n\n return params;\n}\n\nfunction bodyOf(request: FastifyRequest): Record<string, unknown> {\n const body: unknown = request.body;\n\n if (body === null || typeof body !== \"object\" || Array.isArray(body)) {\n throw new DevtoolsApiError(\"input.invalid\");\n }\n\n return body as Record<string, unknown>;\n}\n\nfunction viewOf(\n record: DevtoolsShareRecord,\n createdBy: string | null,\n at: number,\n): DevtoolsShareView {\n return {\n id: record.id,\n panel: record.panel,\n label: record.label,\n createdBy,\n createdAt: record.createdAt,\n expiresAt: record.expiresAt,\n revokedAt: record.revokedAt,\n lastUsedAt: record.lastUsedAt,\n uses: record.uses,\n status: record.revokedAt !== null ? \"revoked\" : record.expiresAt <= at ? \"expired\" : \"active\",\n };\n}\n\nfunction openAnswer(grant: DevtoolsShareGrant): DevtoolsShareOpenAnswer {\n const { panel, share } = grant;\n\n return {\n panel: panel.id,\n title: panel.title,\n label: share.label,\n expiresAt: share.expiresAt,\n assets: [...(panel.share?.assets ?? [])],\n files: panel.share?.files === true,\n };\n}\n\n/** What `mountProductionDevtools` gets back when sharing is on. */\nexport type DevtoolsShareMount = {\n /** The grant of a request's share cookie, or `null` (the gate then answers the uniform 404). */\n authorize(request: FastifyRequest, meta: DevtoolsRequestMeta): Promise<DevtoolsShareGrant | null>;\n /** Registers the share routes and the admin routes that manage links. */\n register(server: FastifyInstance, notFound: Notfound): void;\n};\n\n/**\n * Read-only share links of the production monitor. An admin creates a link\n * for a panel that declares `share`; the token is shown once and only its\n * SHA-256 is stored. Opening a link exchanges the token for a scoped cookie\n * (`__Secure-warlock-devtools-share`) that reaches only that panel's shared\n * view. Every refusal answers the dashboard's uniform 404, is audited as\n * `share.failed` (which counts toward the per-IP failure limit) and never\n * records the token.\n */\nexport function createDevtoolsShare(\n deps: MountProductionDevtoolsDeps & { now?: () => number },\n): DevtoolsShareMount {\n const { production, store, auth } = deps;\n const now = deps.now ?? (() => Date.now());\n\n if (typeof deps.hmac !== \"function\") {\n throw new Error(\"Share links need deps.hmac (HMAC-SHA256 keyed with encryption.key).\");\n }\n\n const sessions = createShareSessions({\n store,\n panels: deps.panels,\n hmac: deps.hmac,\n now,\n ...(deps.warn ? { warn: deps.warn } : {}),\n });\n const cookieOptions = { path: production.path, secure: production.requireHttps };\n const cookieName = shareCookieName(production.requireHttps);\n const sharePanels = deps.panels.filter((panel) => panel.share !== null);\n const blocked = new Map<string, number>();\n const cookieAudited = new Map<string, number>();\n\n const limits = production.rateLimits;\n const windowMs = limits.windowMinutes * 60_000;\n\n async function overLimit(ip: string): Promise<boolean> {\n const client = rateLimitClient(ip);\n const at = now();\n const until = blocked.get(client);\n\n if (until !== undefined && at < until) return true;\n\n const state = await store.state.read();\n const since = Math.max(at - windowMs, state.failuresResetAt ?? 0);\n const count = await store.audit.count({ types: DEVTOOLS_FAILURE_AUDIT_TYPES, since, ip });\n\n blocked.delete(client);\n\n if (count < limits.ip) return false;\n\n if (blocked.size >= BLOCK_CACHE_SIZE) {\n const oldest = blocked.keys().next();\n\n if (!oldest.done) blocked.delete(oldest.value);\n }\n\n blocked.set(client, at + BLOCK_CACHE_MS);\n\n return true;\n }\n\n /** Writes one `share.failed` entry (never the token). Never throws. */\n async function failed(\n meta: DevtoolsRequestMeta,\n reason: string,\n shareId: string | null,\n ): Promise<void> {\n await auth.audit(\"share.failed\", { meta, detail: { reason, share: shareId } });\n }\n\n /** The cookie check for a share request. */\n async function authorize(\n request: FastifyRequest,\n meta: DevtoolsRequestMeta,\n ): Promise<DevtoolsShareGrant | null> {\n const value = readCookie(request.headers.cookie, cookieName);\n\n if (value === undefined) return null;\n\n let result;\n\n try {\n result = await sessions.verify(value);\n } catch (error) {\n deps.warn?.(\n `A devtools share link could not be checked and the request was refused: ${error instanceof Error ? error.message : String(error)}`,\n );\n\n return null;\n }\n\n if (\"grant\" in result) {\n sessions.touch(result.grant.share.id);\n\n return result.grant;\n }\n\n const client = rateLimitClient(meta.ip);\n const last = cookieAudited.get(client);\n\n if (last === undefined || now() - last >= COOKIE_AUDIT_INTERVAL_MS) {\n cookieAudited.delete(client);\n\n if (cookieAudited.size >= BLOCK_CACHE_SIZE) {\n const oldest = cookieAudited.keys().next();\n\n if (!oldest.done) cookieAudited.delete(oldest.value);\n }\n\n cookieAudited.set(client, now());\n\n try {\n if (!(await overLimit(meta.ip))) await failed(meta, result.refused, result.shareId);\n } catch {\n // The refusal stands even when the audit cannot be written.\n }\n }\n\n return null;\n }\n\n function grantOf(request: FastifyRequest): DevtoolsShareGrant {\n const grant = devtoolsRequestContext(request)?.share;\n\n if (!grant) throw new Error(\"A share route ran without its grant.\");\n\n return grant;\n }\n\n function createdByOf(\n accounts: readonly { id: string; email: string }[],\n id: string | null,\n ): string | null {\n return accounts.find((account) => account.id === id)?.email ?? null;\n }\n\n // ---- Admin ----------------------------------------------------------------\n\n async function list(): Promise<DevtoolsShareList> {\n const [records, accounts] = await Promise.all([store.shares.list(), store.accounts.list()]);\n const at = now();\n\n return {\n enabled: true,\n maxDays: production.share.maxDays,\n panels: sharePanels.map((panel) => ({ id: panel.id, title: panel.title })),\n shares: records.map((record) => viewOf(record, createdByOf(accounts, record.createdBy), at)),\n };\n }\n\n async function create(\n authenticated: DevtoolsAuthenticated,\n meta: DevtoolsRequestMeta,\n body: Record<string, unknown>,\n ): Promise<DevtoolsCreatedShare> {\n const panel = body.panel;\n const label = typeof body.label === \"string\" ? body.label.trim() : \"\";\n const days = body.days;\n\n if (\n typeof panel !== \"string\" ||\n panel.length > MAX_PANEL_ID ||\n !sharePanels.some((item) => item.id === panel) ||\n label === \"\" ||\n label.length > DEVTOOLS_SHARE_LABEL_MAX ||\n // eslint-disable-next-line no-control-regex\n /[\\u0000-\\u001f\\u007f]/.test(label) ||\n typeof days !== \"number\" ||\n !Number.isInteger(days) ||\n days < 1 ||\n days > production.share.maxDays\n ) {\n throw new DevtoolsApiError(\"input.invalid\");\n }\n\n const token = generateToken();\n const at = now();\n const record = await store.shares.create({\n tokenHash: hashToken(token),\n panel,\n label,\n createdBy: authenticated.account.id,\n createdAt: at,\n expiresAt: at + days * DAY_MS,\n });\n\n sessions.invalidate();\n await auth.audit(\"share.created\", {\n auth: authenticated,\n meta,\n detail: { share: record.id, panel, days },\n });\n\n return {\n share: viewOf(record, authenticated.account.email, at),\n // The token rides in the fragment: it never reaches an access log or a Referer header.\n url: `${meta.origin}${production.path}/#/share/${token}`,\n };\n }\n\n // ---- Registration -----------------------------------------------------------\n\n function register(server: FastifyInstance, notFound: Notfound): void {\n const requireAuth = (request: FastifyRequest) => {\n const context = devtoolsRequestContext(request);\n\n if (!context?.authenticated) throw new Error(\"A dashboard route ran without its session.\");\n\n return { auth: context.authenticated, meta: context.meta };\n };\n\n // The grant exchange. Every failure answers the uniform 404.\n server.post(\"/api/share/open\", async (request, reply) => {\n const context = devtoolsRequestContext(request);\n\n if (!context) return notFound(request, reply);\n\n const { meta } = context;\n const token = (request.body as { token?: unknown } | null | undefined)?.token;\n\n if (typeof token !== \"string\" || token === \"\" || token.length > MAX_TOKEN) {\n return notFound(request, reply);\n }\n\n try {\n if (await overLimit(meta.ip)) return notFound(request, reply);\n\n const result = await sessions.open(hashToken(token));\n\n if (!(\"grant\" in result)) {\n await failed(meta, result.refused, result.shareId);\n\n return notFound(request, reply);\n }\n\n const { value, maxAgeSeconds } = sessions.issue(result.grant.share);\n\n sessions.touch(result.grant.share.id);\n reply.header(\"set-cookie\", shareCookie(value, { ...cookieOptions, maxAgeSeconds }));\n\n return openAnswer(result.grant);\n } catch (error) {\n deps.warn?.(\n `A devtools share link could not be opened: ${error instanceof Error ? error.message : String(error)}`,\n );\n\n return notFound(request, reply);\n }\n });\n\n server.get(\"/api/share/info\", async (request) => openAnswer(grantOf(request)));\n\n server.get(\"/api/share/view.js\", async (request, reply) => {\n const view = grantOf(request).panel.share?.view;\n\n if (view === undefined) return notFound(request, reply);\n\n sendFile(reply, view, \"text/javascript; charset=utf-8\");\n\n return reply;\n });\n\n server.get<{ Params: { name: string } }>(\"/api/share/assets/:name\", async (request, reply) => {\n const { panel } = grantOf(request);\n const name = request.params.name;\n const file =\n panel.share?.assets.includes(name) === true && Object.hasOwn(panel.assets, name)\n ? panel.assets[name]\n : undefined;\n\n if (file === undefined) return notFound(request, reply);\n\n sendFile(reply, file, panelContentType(name));\n\n return reply;\n });\n\n server.get<{ Params: { \"*\": string } }>(\"/api/share/files/*\", async (request, reply) => {\n const { panel } = grantOf(request);\n\n return sendPanelFile(\n { files: panel.share?.files === true ? panel.files : null },\n request.params[\"*\"],\n request,\n reply,\n notFound,\n );\n });\n\n const panelRoute = async (request: FastifyRequest, reply: FastifyReply) => {\n const { panel } = grantOf(request);\n const sub = (request.params as { \"*\"?: string })[\"*\"];\n const path = sub === undefined || sub === \"\" ? \"\" : `/${sub}`;\n let matched: {\n route: MountedDevtoolsPanel[\"routes\"][number];\n params: Record<string, string>;\n } | null = null;\n\n for (const pattern of panel.share?.routes ?? []) {\n const params = matchSharePath(pattern, path);\n const route = panel.routes.find(\n (candidate) => candidate.method === \"GET\" && candidate.path === pattern,\n );\n\n if (params !== null && route !== undefined) {\n matched = { route, params };\n break;\n }\n }\n\n if (matched === null) return notFound(request, reply);\n\n const input: DevtoolsPanelRequest = {\n params: matched.params,\n query: (request.query ?? {}) as Record<string, string | string[]>,\n body: undefined,\n shared: true,\n };\n const result = await matched.route.handler(input);\n\n reply.header(\"cache-control\", \"no-store\");\n\n if (result === undefined) return reply.code(204).send();\n\n return result;\n };\n\n server.get(\"/api/share/panel\", panelRoute);\n server.get(\"/api/share/panel/*\", panelRoute);\n\n server.get(\"/api/admin/shares\", async () => list());\n\n server.post(\"/api/admin/shares\", async (request, reply) => {\n const { auth: authenticated, meta } = requireAuth(request);\n const created = await create(authenticated, meta, bodyOf(request));\n\n return reply.code(201).send(created);\n });\n\n server.delete<{ Params: { id: string } }>(\"/api/admin/shares/:id\", async (request, reply) => {\n const { auth: authenticated, meta } = requireAuth(request);\n const id = request.params.id;\n\n if (typeof id !== \"string\" || id === \"\" || id.length > 64) {\n throw new DevtoolsApiError(\"input.invalid\");\n }\n\n const record = await store.shares.get(id);\n\n if (!record || !(await store.shares.revoke(id, now()))) {\n throw new DevtoolsApiError(\"share.not-found\");\n }\n\n sessions.invalidate();\n await auth.audit(\"share.revoked\", {\n auth: authenticated,\n meta,\n detail: { share: id, panel: record.panel },\n });\n\n return reply.code(204).send();\n });\n\n server.post(\"/api/admin/shares/revoke-all\", async (request) => {\n const { auth: authenticated, meta } = requireAuth(request);\n const revoked = await store.shares.revokeAll(now());\n\n sessions.invalidate();\n await auth.audit(\"share.revoked\", {\n auth: authenticated,\n meta,\n detail: { all: true, count: revoked },\n });\n\n return { revoked };\n });\n }\n\n return { authorize, register };\n}\n"],"mappings":";;;;;;;;;;;;AAuBA,MAAM,SAAS;AACf,MAAM,YAAY;AAClB,MAAM,eAAe;;AAGrB,MAAM,iBAAiB;AACvB,MAAM,mBAAmB;;AAGzB,MAAM,2BAA2B;;AAKjC,SAAgB,eAAe,SAAiB,MAA6C;CAC3F,IAAI,SAAS,KAAK,IAAI,GAAG,OAAO;CAEhC,MAAM,SAAS,QAAQ,MAAM,GAAG;CAChC,MAAM,QAAQ,KAAK,MAAM,GAAG;CAE5B,IAAI,OAAO,WAAW,MAAM,QAAQ,OAAO;CAE3C,MAAM,SAAiC,CAAC;CAExC,KAAK,MAAM,CAAC,OAAO,SAAS,OAAO,QAAQ,GAAG;EAC5C,MAAM,SAAS,MAAM;EAErB,IAAI,WAAW,QAAW,OAAO;EAEjC,IAAI,KAAK,WAAW,GAAG,GAAG;GACxB,IAAI,WAAW,IAAI,OAAO;GAE1B,OAAO,KAAK,MAAM,CAAC,KAAK;EAC1B,OAAO,IAAI,SAAS,QAClB,OAAO;CAEX;CAEA,OAAO;AACT;AAEA,SAAS,OAAO,SAAkD;CAChE,MAAM,OAAgB,QAAQ;CAE9B,IAAI,SAAS,QAAQ,OAAO,SAAS,YAAY,MAAM,QAAQ,IAAI,GACjE,MAAM,IAAI,iBAAiB,eAAe;CAG5C,OAAO;AACT;AAEA,SAAS,OACP,QACA,WACA,IACmB;CACnB,OAAO;EACL,IAAI,OAAO;EACX,OAAO,OAAO;EACd,OAAO,OAAO;EACd;EACA,WAAW,OAAO;EAClB,WAAW,OAAO;EAClB,WAAW,OAAO;EAClB,YAAY,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W;GACpB,MAAM,KAAK,MAAM,iBAAiB;IAChC,MAAM;IACN;IACA,QAAQ;KAAE,OAAO;KAAI,OAAO,OAAO;IAAM;GAC3C,CAAC;GAED,OAAO,MAAM,KAAK,GAAG,CAAC,CAAC,KAAK;EAC9B,CAAC;EAED,OAAO,KAAK,gCAAgC,OAAO,YAAY;GAC7D,MAAM,EAAE,MAAM,eAAe,SAAS,YAAY,OAAO;GACzD,MAAM,UAAU,MAAM,MAAM,OAAO,UAAU,IAAI,CAAC;GAElD,SAAS,WAAW;GACpB,MAAM,KAAK,MAAM,iBAAiB;IAChC,MAAM;IACN;IACA,QAAQ;KAAE,KAAK;KAAM,OAAO;IAAQ;GACtC,CAAC;GAED,OAAO,EAAE,QAAQ;EACnB,CAAC;CACH;CAEA,OAAO;EAAE;EAAW;CAAS;AAC/B"}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { DEVTOOLS_BUILT_IN_PANELS, DEVTOOLS_FAILURE_AUDIT_TYPES, DEVTOOLS_LATENCY_BUCKETS_MS, DevtoolsAccountView, DevtoolsApiErrorBody, DevtoolsAuditEntry, DevtoolsAuditType, DevtoolsAuthStepResult, DevtoolsBuiltInPanelId, DevtoolsCaptureCounters, DevtoolsCreatedInvite, DevtoolsErrorCode, DevtoolsErrorGroup, DevtoolsErrorsView, DevtoolsExplainResult, DevtoolsHealthReport, DevtoolsHealthView, DevtoolsHistogram, DevtoolsInstanceInfo, DevtoolsInstanceReport, DevtoolsInstancesView, DevtoolsInviteView, DevtoolsJobsReport, DevtoolsJobsView, DevtoolsLogRow, DevtoolsLoginInput, DevtoolsLogsView, DevtoolsMode, DevtoolsPanelInfo, DevtoolsPasswordSource, DevtoolsQueryShapeRow, DevtoolsQueryShapeStats, DevtoolsQueryStatsView, DevtoolsRecoveryCodes, DevtoolsReportLogEntry, DevtoolsResourcePoint, DevtoolsResourceSnapshot, DevtoolsResourcesView, DevtoolsRole, DevtoolsRoutePhaseStats, DevtoolsRouteStats, DevtoolsRouteStatsRow, DevtoolsRouteStatsView, DevtoolsSampleDetail, DevtoolsSampleQuery, DevtoolsSampleSummary, DevtoolsScheduleInfo, DevtoolsSessionInfo, DevtoolsSessionStage, DevtoolsSessionView, DevtoolsTotpEnrolment, DevtoolsUserListView } from "./contracts.mjs";
|
|
1
|
+
import { DEVTOOLS_BUILT_IN_PANELS, DEVTOOLS_FAILURE_AUDIT_TYPES, DEVTOOLS_LATENCY_BUCKETS_MS, DEVTOOLS_SHARE_LABEL_MAX, DevtoolsAccountView, DevtoolsApiErrorBody, DevtoolsAuditEntry, DevtoolsAuditType, DevtoolsAuthStepResult, DevtoolsBuiltInPanelId, DevtoolsCaptureCounters, DevtoolsCreatedInvite, DevtoolsCreatedShare, DevtoolsErrorCode, DevtoolsErrorGroup, DevtoolsErrorsView, DevtoolsExplainResult, DevtoolsHealthReport, DevtoolsHealthView, DevtoolsHistogram, DevtoolsInstanceInfo, DevtoolsInstanceReport, DevtoolsInstancesView, DevtoolsInviteView, DevtoolsJobsReport, DevtoolsJobsView, DevtoolsLogRow, DevtoolsLoginInput, DevtoolsLogsView, DevtoolsMode, DevtoolsPanelInfo, DevtoolsPasswordSource, DevtoolsQueryShapeRow, DevtoolsQueryShapeStats, DevtoolsQueryStatsView, DevtoolsRecoveryCodes, DevtoolsReportLogEntry, DevtoolsResourcePoint, DevtoolsResourceSnapshot, DevtoolsResourcesView, DevtoolsRole, DevtoolsRoutePhaseStats, DevtoolsRouteStats, DevtoolsRouteStatsRow, DevtoolsRouteStatsView, DevtoolsSampleDetail, DevtoolsSampleQuery, DevtoolsSampleSummary, DevtoolsScheduleInfo, DevtoolsSessionInfo, DevtoolsSessionStage, DevtoolsSessionView, DevtoolsShareCreateInput, DevtoolsShareList, DevtoolsShareOpenAnswer, DevtoolsShareStatus, DevtoolsShareView, DevtoolsTotpEnrolment, DevtoolsUserListView } from "./contracts.mjs";
|
|
2
2
|
import { registerDevtoolsCommands } from "./cli/index.mjs";
|
|
3
3
|
import { DEVTOOLS_CONFIG_CODES, DevtoolsConfigCode, DevtoolsProductionConfigError } from "./errors.mjs";
|
|
4
4
|
import { devtoolsMigrations } from "./store/migrations.mjs";
|
|
5
5
|
import { ResolvedDevtoolsProductionOptions } from "./options.mjs";
|
|
6
|
-
export { type DEVTOOLS_BUILT_IN_PANELS, DEVTOOLS_CONFIG_CODES, type DEVTOOLS_FAILURE_AUDIT_TYPES, type DEVTOOLS_LATENCY_BUCKETS_MS, type DevtoolsAccountView, type DevtoolsApiErrorBody, type DevtoolsAuditEntry, type DevtoolsAuditType, type DevtoolsAuthStepResult, type DevtoolsBuiltInPanelId, type DevtoolsCaptureCounters, type DevtoolsConfigCode, type DevtoolsCreatedInvite, type DevtoolsErrorCode, type DevtoolsErrorGroup, type DevtoolsErrorsView, type DevtoolsExplainResult, type DevtoolsHealthReport, type DevtoolsHealthView, type DevtoolsHistogram, type DevtoolsInstanceInfo, type DevtoolsInstanceReport, type DevtoolsInstancesView, type DevtoolsInviteView, type DevtoolsJobsReport, type DevtoolsJobsView, type DevtoolsLogRow, type DevtoolsLoginInput, type DevtoolsLogsView, type DevtoolsMode, type DevtoolsPanelInfo, type DevtoolsPasswordSource, DevtoolsProductionConfigError, type DevtoolsQueryShapeRow, type DevtoolsQueryShapeStats, type DevtoolsQueryStatsView, type DevtoolsRecoveryCodes, type DevtoolsReportLogEntry, type DevtoolsResourcePoint, type DevtoolsResourceSnapshot, type DevtoolsResourcesView, type DevtoolsRole, type DevtoolsRoutePhaseStats, type DevtoolsRouteStats, type DevtoolsRouteStatsRow, type DevtoolsRouteStatsView, type DevtoolsSampleDetail, type DevtoolsSampleQuery, type DevtoolsSampleSummary, type DevtoolsScheduleInfo, type DevtoolsSessionInfo, type DevtoolsSessionStage, type DevtoolsSessionView, type DevtoolsTotpEnrolment, type DevtoolsUserListView, type ResolvedDevtoolsProductionOptions, devtoolsMigrations, registerDevtoolsCommands };
|
|
6
|
+
export { type DEVTOOLS_BUILT_IN_PANELS, DEVTOOLS_CONFIG_CODES, type DEVTOOLS_FAILURE_AUDIT_TYPES, type DEVTOOLS_LATENCY_BUCKETS_MS, type DEVTOOLS_SHARE_LABEL_MAX, type DevtoolsAccountView, type DevtoolsApiErrorBody, type DevtoolsAuditEntry, type DevtoolsAuditType, type DevtoolsAuthStepResult, type DevtoolsBuiltInPanelId, type DevtoolsCaptureCounters, type DevtoolsConfigCode, type DevtoolsCreatedInvite, type DevtoolsCreatedShare, type DevtoolsErrorCode, type DevtoolsErrorGroup, type DevtoolsErrorsView, type DevtoolsExplainResult, type DevtoolsHealthReport, type DevtoolsHealthView, type DevtoolsHistogram, type DevtoolsInstanceInfo, type DevtoolsInstanceReport, type DevtoolsInstancesView, type DevtoolsInviteView, type DevtoolsJobsReport, type DevtoolsJobsView, type DevtoolsLogRow, type DevtoolsLoginInput, type DevtoolsLogsView, type DevtoolsMode, type DevtoolsPanelInfo, type DevtoolsPasswordSource, DevtoolsProductionConfigError, type DevtoolsQueryShapeRow, type DevtoolsQueryShapeStats, type DevtoolsQueryStatsView, type DevtoolsRecoveryCodes, type DevtoolsReportLogEntry, type DevtoolsResourcePoint, type DevtoolsResourceSnapshot, type DevtoolsResourcesView, type DevtoolsRole, type DevtoolsRoutePhaseStats, type DevtoolsRouteStats, type DevtoolsRouteStatsRow, type DevtoolsRouteStatsView, type DevtoolsSampleDetail, type DevtoolsSampleQuery, type DevtoolsSampleSummary, type DevtoolsScheduleInfo, type DevtoolsSessionInfo, type DevtoolsSessionStage, type DevtoolsSessionView, type DevtoolsShareCreateInput, type DevtoolsShareList, type DevtoolsShareOpenAnswer, type DevtoolsShareStatus, type DevtoolsShareView, type DevtoolsTotpEnrolment, type DevtoolsUserListView, type ResolvedDevtoolsProductionOptions, devtoolsMigrations, registerDevtoolsCommands };
|
|
@@ -7,7 +7,7 @@ const WARN_EVERY_MS = 6e4;
|
|
|
7
7
|
/**
|
|
8
8
|
* Writes the report every `production.reportIntervalMs`, and every 10
|
|
9
9
|
* minutes prunes: reports unseen for 5 minutes, samples older than
|
|
10
|
-
* `requestRetentionHours`, expired sessions and invites, audit entries older
|
|
10
|
+
* `requestRetentionHours`, expired sessions and invites, share links that expired or were revoked more than 30 days ago, audit entries older
|
|
11
11
|
* than `auditRetentionDays`. Timers are `unref`ed; a failed write is logged
|
|
12
12
|
* once per minute, never thrown.
|
|
13
13
|
*/
|
|
@@ -39,6 +39,7 @@ function startReportWriter(input) {
|
|
|
39
39
|
["remove old request samples", () => store.samples.prune(now - production.requestRetentionHours * 36e5)],
|
|
40
40
|
["remove expired sessions", () => store.sessions.removeExpired(now)],
|
|
41
41
|
["remove expired invites", () => store.invites.removeExpired(now)],
|
|
42
|
+
["remove old share links", async () => production.share.enabled ? store.shares.removeOld(now - 2592e6) : 0],
|
|
42
43
|
["remove old audit entries", () => store.audit.prune(now - production.auditRetentionDays * 864e5)]
|
|
43
44
|
];
|
|
44
45
|
for (const [what, step] of steps) try {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"writer.mjs","names":[],"sources":["../../../../../../../../../packages/devtools/src/production/insights/writer.ts"],"sourcesContent":["import type { ResolvedDevtoolsProductionOptions } from \"../options\";\nimport type { DevtoolsStore } from \"../store/types\";\nimport { capReportSize } from \"./cap-report\";\nimport type { DevtoolsLocalReporter, DevtoolsReportWriter } from \"./types\";\n\nconst HOUSEKEEPING_INTERVAL_MS = 10 * 60_000;\nconst REPORT_MAX_AGE_MS = 5 * 60_000;\nconst WARN_EVERY_MS = 60_000;\n\n/**\n * Writes the report every `production.reportIntervalMs`, and every 10\n * minutes prunes: reports unseen for 5 minutes, samples older than\n * `requestRetentionHours`, expired sessions and invites, audit entries older\n * than `auditRetentionDays`. Timers are `unref`ed; a failed write is logged\n * once per minute, never thrown.\n */\nexport function startReportWriter(input: {\n reporter: DevtoolsLocalReporter;\n store: DevtoolsStore;\n production: ResolvedDevtoolsProductionOptions;\n warn?: (message: string) => void;\n}): DevtoolsReportWriter {\n const { reporter, store, production, warn } = input;\n let stopped = false;\n let lastWarnAt = Number.NEGATIVE_INFINITY;\n let pending: Promise<void> = Promise.resolve();\n\n function fail(what: string, error: unknown): void {\n const now = Date.now();\n\n if (!warn || now - lastWarnAt < WARN_EVERY_MS) return;\n\n lastWarnAt = now;\n\n const reason = error instanceof Error ? error.message : String(error);\n\n warn(`Devtools could not ${what}: ${reason}. It will try again.`);\n }\n\n async function write(): Promise<void> {\n if (stopped) return;\n\n try {\n await store.reports.write(capReportSize(await reporter.snapshot()));\n } catch (error) {\n fail(\"write this instance's report to the database\", error);\n }\n }\n\n async function housekeeping(): Promise<void> {\n if (stopped) return;\n\n const now = Date.now();\n const steps: [string, () => Promise<unknown>][] = [\n [\"remove old instance reports\", () => store.reports.prune(now - REPORT_MAX_AGE_MS)],\n [\n \"remove old request samples\",\n () => store.samples.prune(now - production.requestRetentionHours * 3_600_000),\n ],\n [\"remove expired sessions\", () => store.sessions.removeExpired(now)],\n [\"remove expired invites\", () => store.invites.removeExpired(now)],\n [\n \"remove old audit entries\",\n () => store.audit.prune(now - production.auditRetentionDays * 86_400_000),\n ],\n ];\n\n for (const [what, step] of steps) {\n try {\n await step();\n } catch (error) {\n fail(what, error);\n }\n }\n }\n\n function enqueue(task: () => Promise<void>): Promise<void> {\n pending = pending.then(task);\n\n return pending;\n }\n\n const writeTimer = setInterval(() => void enqueue(write), production.reportIntervalMs);\n const housekeepingTimer = setInterval(() => void enqueue(housekeeping), HOUSEKEEPING_INTERVAL_MS);\n\n writeTimer.unref();\n housekeepingTimer.unref();\n void enqueue(write);\n\n return {\n writeNow: () => enqueue(write),\n\n async stop() {\n stopped = true;\n clearInterval(writeTimer);\n clearInterval(housekeepingTimer);\n await pending;\n },\n };\n}\n"],"mappings":";;;AAKA,MAAM,2BAA2B;AACjC,MAAM,oBAAoB;AAC1B,MAAM,gBAAgB;;;;;;;;AAStB,SAAgB,kBAAkB,OAKT;CACvB,MAAM,EAAE,UAAU,OAAO,YAAY,SAAS;CAC9C,IAAI,UAAU;CACd,I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CAElB,OAAO;EACL,gBAAgB,QAAQ,KAAK;EAE7B,MAAM,OAAO;GACX,UAAU;GACV,cAAc,UAAU;GACxB,cAAc,iBAAiB;GAC/B,MAAM;EACR;CACF;AACF"}
|
|
1
|
+
{"version":3,"file":"writer.mjs","names":[],"sources":["../../../../../../../../../packages/devtools/src/production/insights/writer.ts"],"sourcesContent":["import type { ResolvedDevtoolsProductionOptions } from \"../options\";\nimport type { DevtoolsStore } from \"../store/types\";\nimport { capReportSize } from \"./cap-report\";\nimport type { DevtoolsLocalReporter, DevtoolsReportWriter } from \"./types\";\n\nconst HOUSEKEEPING_INTERVAL_MS = 10 * 60_000;\nconst REPORT_MAX_AGE_MS = 5 * 60_000;\nconst WARN_EVERY_MS = 60_000;\n\n/**\n * Writes the report every `production.reportIntervalMs`, and every 10\n * minutes prunes: reports unseen for 5 minutes, samples older than\n * `requestRetentionHours`, expired sessions and invites, share links that expired or were revoked more than 30 days ago, audit entries older\n * than `auditRetentionDays`. Timers are `unref`ed; a failed write is logged\n * once per minute, never thrown.\n */\nexport function startReportWriter(input: {\n reporter: DevtoolsLocalReporter;\n store: DevtoolsStore;\n production: ResolvedDevtoolsProductionOptions;\n warn?: (message: string) => void;\n}): DevtoolsReportWriter {\n const { reporter, store, production, warn } = input;\n let stopped = false;\n let lastWarnAt = Number.NEGATIVE_INFINITY;\n let pending: Promise<void> = Promise.resolve();\n\n function fail(what: string, error: unknown): void {\n const now = Date.now();\n\n if (!warn || now - lastWarnAt < WARN_EVERY_MS) return;\n\n lastWarnAt = now;\n\n const reason = error instanceof Error ? error.message : String(error);\n\n warn(`Devtools could not ${what}: ${reason}. It will try again.`);\n }\n\n async function write(): Promise<void> {\n if (stopped) return;\n\n try {\n await store.reports.write(capReportSize(await reporter.snapshot()));\n } catch (error) {\n fail(\"write this instance's report to the database\", error);\n }\n }\n\n async function housekeeping(): Promise<void> {\n if (stopped) return;\n\n const now = Date.now();\n const steps: [string, () => Promise<unknown>][] = [\n [\"remove old instance reports\", () => store.reports.prune(now - REPORT_MAX_AGE_MS)],\n [\n \"remove old request samples\",\n () => store.samples.prune(now - production.requestRetentionHours * 3_600_000),\n ],\n [\"remove expired sessions\", () => store.sessions.removeExpired(now)],\n [\"remove expired invites\", () => store.invites.removeExpired(now)],\n [\n \"remove old share links\",\n // Links that expired or were revoked more than 30 days ago; the table exists only when sharing is on.\n async () => (production.share.enabled ? store.shares.removeOld(now - 30 * 86_400_000) : 0),\n ],\n [\n \"remove old audit entries\",\n () => store.audit.prune(now - production.auditRetentionDays * 86_400_000),\n ],\n ];\n\n for (const [what, step] of steps) {\n try {\n await step();\n } catch (error) {\n fail(what, error);\n }\n }\n }\n\n function enqueue(task: () => Promise<void>): Promise<void> {\n pending = pending.then(task);\n\n return pending;\n }\n\n const writeTimer = setInterval(() => void enqueue(write), production.reportIntervalMs);\n const housekeepingTimer = setInterval(() => void enqueue(housekeeping), HOUSEKEEPING_INTERVAL_MS);\n\n writeTimer.unref();\n housekeepingTimer.unref();\n void enqueue(write);\n\n return {\n writeNow: () => enqueue(write),\n\n async stop() {\n stopped = true;\n clearInterval(writeTimer);\n clearInterval(housekeepingTimer);\n await pending;\n },\n };\n}\n"],"mappings":";;;AAKA,MAAM,2BAA2B;AACjC,MAAM,oBAAoB;AAC1B,MAAM,gBAAgB;;;;;;;;AAStB,SAAgB,kBAAkB,OAKT;CACvB,MAAM,EAAE,UAAU,OAAO,YAAY,SAAS;CAC9C,IAAI,UAAU;CACd,IAAI,aAAa,OAAO;CACxB,IAAI,UAAyB,QAAQ,QAAQ;CAE7C,SAAS,KAAK,MAAc,OAAsB;EAChD,MAAM,MAAM,KAAK,IAAI;EAErB,IAAI,CAAC,QAAQ,MAAM,aAAa,eAAe;EAE/C,aAAa;EAEb,MAAM,SAAS,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;EAEpE,KAAK,sBAAsB,KAAK,IAAI,OAAO,qBAAqB;CAClE;CAEA,eAAe,QAAuB;EACpC,IAAI,SAAS;EA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
|
39
39
|
};
|
|
40
|
-
twoFactor: "admins" | "everyone";
|
|
40
|
+
twoFactor: "off" | "admins" | "everyone";
|
|
41
|
+
passwords: {
|
|
42
|
+
minLength: number;
|
|
43
|
+
rejectCommon: boolean;
|
|
44
|
+
};
|
|
41
45
|
rateLimits: {
|
|
42
46
|
windowMinutes: number;
|
|
43
47
|
account: number;
|
|
@@ -55,6 +59,11 @@ export type ResolvedDevtoolsProductionOptions = {
|
|
|
55
59
|
rpName: string;
|
|
56
60
|
rpId: string | null;
|
|
57
61
|
};
|
|
62
|
+
/** Read-only share links. */
|
|
63
|
+
share: {
|
|
64
|
+
enabled: boolean;
|
|
65
|
+
maxDays: number;
|
|
66
|
+
};
|
|
58
67
|
};
|
|
59
68
|
//#endregion
|
|
60
69
|
//# sourceMappingURL=options.d.mts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"options.d.mts","names":[],"sources":["../../../../../../../../packages/devtools/src/production/options.ts"],"mappings":";;;;;;YAQY;;EAEV;;EAEA;IAAS;IAAsB;IAAyB;;EACxD;EACA;EACA;EACA;;EAEA;;EAEA;;EAEA;;EAEA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;IAAW;IAAqB;IAAkB;;EAClD;EACA;IACE;IACA;IACA;IACA;IACA;;EAEF;IAAW;;EACX,QAAQ,SAAS;EACjB,oBAAoB;EACpB;EACA;IAAY;IAAgB"}
|
|
1
|
+
{"version":3,"file":"options.d.mts","names":[],"sources":["../../../../../../../../packages/devtools/src/production/options.ts"],"mappings":";;;;;;YAQY;;EAEV;;EAEA;IAAS;IAAsB;IAAyB;;EACxD;EACA;EACA;EACA;;EAEA;;EAEA;;EAEA;;EAEA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;IAAW;IAAqB;IAAkB;;EAClD;EACA;IAAa;IAAmB;;EAChC;IACE;IACA;IACA;IACA;IACA;;EAEF;IAAW;;EACX,QAAQ,SAAS;EACjB,oBAAoB;EACpB;EACA;IAAY;IAAgB;;;EAE5B;IAAS;IAAkB"}
|
|
@@ -22,6 +22,10 @@ const DEVTOOLS_PRODUCTION_DEFAULTS = {
|
|
|
22
22
|
pendingMinutes: 10
|
|
23
23
|
},
|
|
24
24
|
twoFactor: "admins",
|
|
25
|
+
passwords: {
|
|
26
|
+
minLength: 8,
|
|
27
|
+
rejectCommon: true
|
|
28
|
+
},
|
|
25
29
|
rateLimits: {
|
|
26
30
|
windowMinutes: 15,
|
|
27
31
|
account: 5,
|
|
@@ -32,7 +36,11 @@ const DEVTOOLS_PRODUCTION_DEFAULTS = {
|
|
|
32
36
|
explain: { executing: false },
|
|
33
37
|
logLevels: ["warn", "error"],
|
|
34
38
|
auditRetentionDays: 90,
|
|
35
|
-
passkeys: { rpName: "Warlock monitor" }
|
|
39
|
+
passkeys: { rpName: "Warlock monitor" },
|
|
40
|
+
share: {
|
|
41
|
+
enabled: false,
|
|
42
|
+
maxDays: 30
|
|
43
|
+
}
|
|
36
44
|
};
|
|
37
45
|
/** The environment variables production mode reads. */
|
|
38
46
|
const DEVTOOLS_ENV = {
|
|
@@ -83,7 +91,7 @@ function resolvePath(value) {
|
|
|
83
91
|
* `env`, and validates everything.
|
|
84
92
|
*
|
|
85
93
|
* Throws `DevtoolsProductionConfigError`: DT001 (no path), DT002 (bad path),
|
|
86
|
-
* DT007 (an option out of range: sampleRate outside 0–1, a non-positive
|
|
94
|
+
* DT007 (an option out of range: sampleRate outside 0–1, share.maxDays outside 1–365, a non-positive
|
|
87
95
|
* limit, an unknown twoFactor value, a bad CIDR, an origin that is not
|
|
88
96
|
* `https://host[:port]`), DT009 (both a password and a setup token), DT010
|
|
89
97
|
* (setup token shorter than 32 characters). DT003/DT004 (admin) are checked
|
|
@@ -98,7 +106,11 @@ function resolveProductionOptions(options, env) {
|
|
|
98
106
|
const requireHttps = given.requireHttps ?? defaults.requireHttps;
|
|
99
107
|
if (typeof requireHttps !== "boolean") invalid("requireHttps", "use true or false");
|
|
100
108
|
const twoFactor = given.twoFactor ?? defaults.twoFactor;
|
|
101
|
-
if (twoFactor !== "admins" && twoFactor !== "everyone") invalid("twoFactor", "use \"admins\" or \"everyone\"");
|
|
109
|
+
if (twoFactor !== "off" && twoFactor !== "admins" && twoFactor !== "everyone") invalid("twoFactor", "use \"off\", \"admins\" or \"everyone\"");
|
|
110
|
+
const minLength = given.passwords?.minLength ?? defaults.passwords.minLength;
|
|
111
|
+
if (!Number.isInteger(minLength) || minLength < 8 || minLength > 72) invalid("passwords.minLength", "use a whole number from 8 to 72 (passwords are limited to 72 bytes, so a longer minimum would refuse every password)");
|
|
112
|
+
const rejectCommon = given.passwords?.rejectCommon ?? defaults.passwords.rejectCommon;
|
|
113
|
+
if (typeof rejectCommon !== "boolean") invalid("passwords.rejectCommon", "use true or false");
|
|
102
114
|
const origin = given.origin ?? null;
|
|
103
115
|
if (origin !== null) {
|
|
104
116
|
if (typeof origin !== "string" || !(requireHttps ? /^https:\/\/[^/\s]+$/ : /^https?:\/\/[^/\s]+$/).test(origin)) invalid("origin", requireHttps ? "use an origin such as https://app.example.com, without a path or a trailing slash" : "use an origin such as http://localhost:3000, without a path or a trailing slash");
|
|
@@ -114,6 +126,10 @@ function resolveProductionOptions(options, env) {
|
|
|
114
126
|
const rpId = given.passkeys?.rpId ?? null;
|
|
115
127
|
if (typeof rpName !== "string" || rpName.trim() === "") invalid("passkeys.rpName", "use a non-empty name");
|
|
116
128
|
if (rpId !== null && (typeof rpId !== "string" || rpId.trim() === "")) invalid("passkeys.rpId", "use a host name such as app.example.com");
|
|
129
|
+
const shareEnabled = given.share?.enabled ?? defaults.share.enabled;
|
|
130
|
+
const shareMaxDays = given.share?.maxDays ?? defaults.share.maxDays;
|
|
131
|
+
if (typeof shareEnabled !== "boolean") invalid("share.enabled", "use true or false");
|
|
132
|
+
if (!Number.isInteger(shareMaxDays) || shareMaxDays < 1 || shareMaxDays > 365) invalid("share.maxDays", "use a whole number of days from 1 to 365");
|
|
117
133
|
const limits = given.rateLimits ?? {};
|
|
118
134
|
const session = given.session ?? {};
|
|
119
135
|
const resolved = {
|
|
@@ -144,6 +160,10 @@ function resolveProductionOptions(options, env) {
|
|
|
144
160
|
pendingMinutes: defaults.session.pendingMinutes
|
|
145
161
|
},
|
|
146
162
|
twoFactor,
|
|
163
|
+
passwords: {
|
|
164
|
+
minLength,
|
|
165
|
+
rejectCommon
|
|
166
|
+
},
|
|
147
167
|
rateLimits: {
|
|
148
168
|
windowMinutes: integerAtLeastOne("rateLimits.windowMinutes", limits.windowMinutes, defaults.rateLimits.windowMinutes),
|
|
149
169
|
account: integerAtLeastOne("rateLimits.account", limits.account, defaults.rateLimits.account),
|
|
@@ -158,6 +178,10 @@ function resolveProductionOptions(options, env) {
|
|
|
158
178
|
passkeys: {
|
|
159
179
|
rpName,
|
|
160
180
|
rpId
|
|
181
|
+
},
|
|
182
|
+
share: {
|
|
183
|
+
enabled: shareEnabled,
|
|
184
|
+
maxDays: shareMaxDays
|
|
161
185
|
}
|
|
162
186
|
};
|
|
163
187
|
if (resolved.admin.password !== null && resolved.admin.setupToken !== null) throw new DevtoolsProductionConfigError("DT009");
|