devanvil 0.0.0-stage → 2.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.ar.md +113 -0
- package/README.md +272 -2
- package/SECURITY.md +49 -0
- package/dist/cli.d.ts +2 -0
- package/dist/cli.js +664 -0
- package/dist/core/contract-drift.d.ts +49 -0
- package/dist/core/contract-drift.js +312 -0
- package/dist/core/converters.d.ts +18 -0
- package/dist/core/converters.js +989 -0
- package/dist/core/cron.d.ts +33 -0
- package/dist/core/cron.js +309 -0
- package/dist/core/crypto.d.ts +59 -0
- package/dist/core/crypto.js +260 -0
- package/dist/core/curl.d.ts +17 -0
- package/dist/core/curl.js +174 -0
- package/dist/core/diff.d.ts +36 -0
- package/dist/core/diff.js +148 -0
- package/dist/core/encoding.d.ts +3 -0
- package/dist/core/encoding.js +143 -0
- package/dist/core/importers.d.ts +65 -0
- package/dist/core/importers.js +361 -0
- package/dist/core/jwt.d.ts +39 -0
- package/dist/core/jwt.js +269 -0
- package/dist/core/llm-tokens.d.ts +38 -0
- package/dist/core/llm-tokens.js +125 -0
- package/dist/core/log-analyzer.d.ts +30 -0
- package/dist/core/log-analyzer.js +155 -0
- package/dist/core/network.d.ts +72 -0
- package/dist/core/network.js +185 -0
- package/dist/core/oauth-protobuf.d.ts +74 -0
- package/dist/core/oauth-protobuf.js +396 -0
- package/dist/core/openapi.d.ts +27 -0
- package/dist/core/openapi.js +257 -0
- package/dist/core/pipeline.d.ts +28 -0
- package/dist/core/pipeline.js +154 -0
- package/dist/core/regex.d.ts +50 -0
- package/dist/core/regex.js +360 -0
- package/dist/core/runner.d.ts +53 -0
- package/dist/core/runner.js +250 -0
- package/dist/core/secrets.d.ts +87 -0
- package/dist/core/secrets.js +603 -0
- package/dist/core/security.d.ts +34 -0
- package/dist/core/security.js +301 -0
- package/dist/core/sql-explain.d.ts +50 -0
- package/dist/core/sql-explain.js +259 -0
- package/dist/core/tls.d.ts +44 -0
- package/dist/core/tls.js +169 -0
- package/dist/index.d.ts +31 -0
- package/dist/index.js +31 -0
- package/dist/server/app.d.ts +31 -0
- package/dist/server/app.js +359 -0
- package/dist/server/http-proxy.d.ts +55 -0
- package/dist/server/http-proxy.js +373 -0
- package/dist/server/http-utils.d.ts +28 -0
- package/dist/server/http-utils.js +118 -0
- package/dist/server/load-tester.d.ts +53 -0
- package/dist/server/load-tester.js +137 -0
- package/dist/server/mcp.d.ts +35 -0
- package/dist/server/mcp.js +470 -0
- package/dist/server/mock-store.d.ts +38 -0
- package/dist/server/mock-store.js +238 -0
- package/dist/server/plugin-loader.d.ts +61 -0
- package/dist/server/plugin-loader.js +305 -0
- package/dist/server/recorder-store.d.ts +35 -0
- package/dist/server/recorder-store.js +147 -0
- package/dist/server/routes/network-routes.d.ts +3 -0
- package/dist/server/routes/network-routes.js +441 -0
- package/dist/server/routes/tools-routes.d.ts +3 -0
- package/dist/server/routes/tools-routes.js +299 -0
- package/dist/server/routes/workspace-routes.d.ts +3 -0
- package/dist/server/routes/workspace-routes.js +262 -0
- package/dist/server/webhook-store.d.ts +29 -0
- package/dist/server/webhook-store.js +100 -0
- package/dist/server/workspace-store.d.ts +91 -0
- package/dist/server/workspace-store.js +448 -0
- package/dist/server/ws-probe.d.ts +34 -0
- package/dist/server/ws-probe.js +291 -0
- package/dist/ui/app.js +290 -0
- package/dist/ui/favicon.svg +14 -0
- package/dist/ui/index.html +83 -0
- package/dist/ui/logo.png +0 -0
- package/dist/ui/styles.css +694 -0
- package/dist/ui/tools-data.js +719 -0
- package/dist/ui/tools-network.js +769 -0
- package/dist/ui/tools-ops.js +299 -0
- package/dist/ui/tools-pro.js +500 -0
- package/dist/ui/tools-security.js +397 -0
- package/dist/ui/tools-v12.js +765 -0
- package/dist/ui/tools-v13.js +321 -0
- package/dist/ui/tools-v20.js +563 -0
- package/dist/ui/tools-v21.js +411 -0
- package/package.json +75 -4
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
export interface ParsedCron {
|
|
2
|
+
expression: string;
|
|
3
|
+
normalized: string;
|
|
4
|
+
hasSeconds: boolean;
|
|
5
|
+
seconds: Set<number>;
|
|
6
|
+
minutes: Set<number>;
|
|
7
|
+
hours: Set<number>;
|
|
8
|
+
daysOfMonth: Set<number>;
|
|
9
|
+
months: Set<number>;
|
|
10
|
+
daysOfWeek: Set<number>;
|
|
11
|
+
domWildcard: boolean;
|
|
12
|
+
dowWildcard: boolean;
|
|
13
|
+
}
|
|
14
|
+
export declare function parseCron(expression: string): ParsedCron;
|
|
15
|
+
export declare function describeCron(expression: string): string;
|
|
16
|
+
export interface CronScheduleResult {
|
|
17
|
+
expression: string;
|
|
18
|
+
description: string;
|
|
19
|
+
nextRuns: string[];
|
|
20
|
+
}
|
|
21
|
+
export declare function getNextCronRuns(expression: string, count?: number, fromDate?: Date): CronScheduleResult;
|
|
22
|
+
export interface TimestampInfo {
|
|
23
|
+
isoUtc: string;
|
|
24
|
+
rfc2822: string;
|
|
25
|
+
unixSeconds: number;
|
|
26
|
+
unixMillis: number;
|
|
27
|
+
unixNanos: string;
|
|
28
|
+
relative: string;
|
|
29
|
+
dayOfYear: number;
|
|
30
|
+
isoWeek: number;
|
|
31
|
+
detectedFormat: string;
|
|
32
|
+
}
|
|
33
|
+
export declare function parseTimestamp(input: string, nowMs?: number): TimestampInfo;
|
|
@@ -0,0 +1,309 @@
|
|
|
1
|
+
const CRON_MACROS = {
|
|
2
|
+
'@yearly': '0 0 1 1 *',
|
|
3
|
+
'@annually': '0 0 1 1 *',
|
|
4
|
+
'@monthly': '0 0 1 * *',
|
|
5
|
+
'@weekly': '0 0 * * 0',
|
|
6
|
+
'@daily': '0 0 * * *',
|
|
7
|
+
'@midnight': '0 0 * * *',
|
|
8
|
+
'@hourly': '0 * * * *',
|
|
9
|
+
};
|
|
10
|
+
const MONTH_NAMES = {
|
|
11
|
+
JAN: 1, FEB: 2, MAR: 3, APR: 4, MAY: 5, JUN: 6,
|
|
12
|
+
JUL: 7, AUG: 8, SEP: 9, OCT: 10, NOV: 11, DEC: 12,
|
|
13
|
+
};
|
|
14
|
+
const DOW_NAMES = {
|
|
15
|
+
SUN: 0, MON: 1, TUE: 2, WED: 3, THU: 4, FRI: 5, SAT: 6,
|
|
16
|
+
};
|
|
17
|
+
const DOW_LABELS = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
|
|
18
|
+
const MONTH_LABELS = ['', 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
|
|
19
|
+
function parseCronField(raw, min, max, names, isDow = false) {
|
|
20
|
+
const result = new Set();
|
|
21
|
+
const replaceNames = (tok) => {
|
|
22
|
+
if (!names)
|
|
23
|
+
return tok;
|
|
24
|
+
return tok.replace(/[A-Za-z]{3}/g, (m) => {
|
|
25
|
+
const up = m.toUpperCase();
|
|
26
|
+
const val = Object.prototype.hasOwnProperty.call(names, up) ? names[up] : undefined;
|
|
27
|
+
if (val === undefined)
|
|
28
|
+
throw new Error(`Unknown cron token "${m}"`);
|
|
29
|
+
return String(val);
|
|
30
|
+
});
|
|
31
|
+
};
|
|
32
|
+
for (const part of raw.split(',')) {
|
|
33
|
+
const cleaned = replaceNames(part.trim());
|
|
34
|
+
if (!cleaned)
|
|
35
|
+
throw new Error(`Empty segment in cron field "${raw}"`);
|
|
36
|
+
const [rangePart, stepPart] = cleaned.split('/');
|
|
37
|
+
const step = stepPart !== undefined ? Number(stepPart) : 1;
|
|
38
|
+
if (!Number.isInteger(step) || step < 1) {
|
|
39
|
+
throw new Error(`Invalid cron step "${stepPart}" in "${raw}"`);
|
|
40
|
+
}
|
|
41
|
+
let start = min;
|
|
42
|
+
let end = max;
|
|
43
|
+
if (rangePart === '*') {
|
|
44
|
+
start = min;
|
|
45
|
+
end = max;
|
|
46
|
+
}
|
|
47
|
+
else if (rangePart.includes('-')) {
|
|
48
|
+
const [sStr, eStr] = rangePart.split('-');
|
|
49
|
+
start = Number(sStr);
|
|
50
|
+
end = Number(eStr);
|
|
51
|
+
if (isDow && end === 7)
|
|
52
|
+
end = 7; // allow 5-7 etc., normalize 7 -> 0 below
|
|
53
|
+
if (!Number.isInteger(start) || !Number.isInteger(end) || start < min || end > (isDow ? 7 : max) || start > end) {
|
|
54
|
+
throw new Error(`Invalid cron range "${rangePart}" (allowed ${min}-${max})`);
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
else {
|
|
58
|
+
start = Number(rangePart);
|
|
59
|
+
if (isDow && start === 7)
|
|
60
|
+
start = 0;
|
|
61
|
+
if (!Number.isInteger(start) || start < min || start > max) {
|
|
62
|
+
throw new Error(`Invalid cron value "${rangePart}" (allowed ${min}-${max})`);
|
|
63
|
+
}
|
|
64
|
+
end = stepPart !== undefined ? max : start;
|
|
65
|
+
}
|
|
66
|
+
for (let v = start; v <= end; v += step) {
|
|
67
|
+
result.add(isDow && v === 7 ? 0 : v);
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
if (result.size === 0)
|
|
71
|
+
throw new Error(`Cron field "${raw}" matched no values`);
|
|
72
|
+
return result;
|
|
73
|
+
}
|
|
74
|
+
export function parseCron(expression) {
|
|
75
|
+
const trimmed = expression.trim();
|
|
76
|
+
const lower = trimmed.toLowerCase();
|
|
77
|
+
const expanded = Object.prototype.hasOwnProperty.call(CRON_MACROS, lower) ? CRON_MACROS[lower] : trimmed;
|
|
78
|
+
const fields = expanded.split(/\s+/);
|
|
79
|
+
if (fields.length !== 5 && fields.length !== 6) {
|
|
80
|
+
throw new Error(`Cron expression must have 5 fields (min hour dom month dow) or 6 fields (sec ...), got ${fields.length}`);
|
|
81
|
+
}
|
|
82
|
+
const hasSeconds = fields.length === 6;
|
|
83
|
+
const [secF, minF, hourF, domF, monF, dowF] = hasSeconds
|
|
84
|
+
? fields
|
|
85
|
+
: ['0', ...fields];
|
|
86
|
+
return {
|
|
87
|
+
expression: trimmed,
|
|
88
|
+
normalized: expanded,
|
|
89
|
+
hasSeconds,
|
|
90
|
+
seconds: parseCronField(secF, 0, 59),
|
|
91
|
+
minutes: parseCronField(minF, 0, 59),
|
|
92
|
+
hours: parseCronField(hourF, 0, 23),
|
|
93
|
+
daysOfMonth: parseCronField(domF, 1, 31),
|
|
94
|
+
months: parseCronField(monF, 1, 12, MONTH_NAMES),
|
|
95
|
+
daysOfWeek: parseCronField(dowF, 0, 6, DOW_NAMES, true),
|
|
96
|
+
domWildcard: domF === '*',
|
|
97
|
+
dowWildcard: dowF === '*',
|
|
98
|
+
};
|
|
99
|
+
}
|
|
100
|
+
export function describeCron(expression) {
|
|
101
|
+
const parsed = parseCron(expression);
|
|
102
|
+
const fields = parsed.normalized.split(/\s+/);
|
|
103
|
+
const [minF, hourF, domF, monF, dowF] = parsed.hasSeconds ? fields.slice(1) : fields;
|
|
104
|
+
const parts = [];
|
|
105
|
+
if (minF === '*' && hourF === '*') {
|
|
106
|
+
parts.push('Every minute');
|
|
107
|
+
}
|
|
108
|
+
else if (minF.startsWith('*/') && hourF === '*') {
|
|
109
|
+
parts.push(`Every ${minF.slice(2)} minutes`);
|
|
110
|
+
}
|
|
111
|
+
else if (hourF.startsWith('*/')) {
|
|
112
|
+
parts.push(`At minute ${minF} past every ${hourF.slice(2)} hours`);
|
|
113
|
+
}
|
|
114
|
+
else if (hourF === '*') {
|
|
115
|
+
parts.push(`At minute ${minF} of every hour`);
|
|
116
|
+
}
|
|
117
|
+
else if (/^\d+$/.test(minF) && /^\d+$/.test(hourF)) {
|
|
118
|
+
parts.push(`At ${hourF.padStart(2, '0')}:${minF.padStart(2, '0')} UTC`);
|
|
119
|
+
}
|
|
120
|
+
else {
|
|
121
|
+
parts.push(`At minute ${minF} during hour(s) ${hourF} UTC`);
|
|
122
|
+
}
|
|
123
|
+
if (domF !== '*')
|
|
124
|
+
parts.push(`on day ${domF} of the month`);
|
|
125
|
+
if (monF !== '*') {
|
|
126
|
+
const months = Array.from(parsed.months)
|
|
127
|
+
.sort((a, b) => a - b)
|
|
128
|
+
.map((m) => MONTH_LABELS[m] ?? String(m));
|
|
129
|
+
parts.push(`in ${months.join(', ')}`);
|
|
130
|
+
}
|
|
131
|
+
if (dowF !== '*') {
|
|
132
|
+
const dows = Array.from(parsed.daysOfWeek)
|
|
133
|
+
.sort((a, b) => a - b)
|
|
134
|
+
.map((d) => DOW_LABELS[d] ?? String(d));
|
|
135
|
+
parts.push(`on ${dows.join(', ')}`);
|
|
136
|
+
}
|
|
137
|
+
return parts.join(' ');
|
|
138
|
+
}
|
|
139
|
+
function nextAllowed(sortedValues, current) {
|
|
140
|
+
for (let i = 0; i < sortedValues.length; i++) {
|
|
141
|
+
if (sortedValues[i] >= current)
|
|
142
|
+
return sortedValues[i];
|
|
143
|
+
}
|
|
144
|
+
return null;
|
|
145
|
+
}
|
|
146
|
+
export function getNextCronRuns(expression, count = 10, fromDate = new Date()) {
|
|
147
|
+
const parsed = parseCron(expression);
|
|
148
|
+
const safeCount = Number.isFinite(count) ? Math.floor(count) : 10;
|
|
149
|
+
const maxCount = Math.min(Math.max(safeCount, 1), 50);
|
|
150
|
+
const runs = [];
|
|
151
|
+
const sortedHours = Array.from(parsed.hours).sort((a, b) => a - b);
|
|
152
|
+
const sortedMinutes = Array.from(parsed.minutes).sort((a, b) => a - b);
|
|
153
|
+
const sortedSeconds = Array.from(parsed.seconds).sort((a, b) => a - b);
|
|
154
|
+
// Work strictly in UTC to remain deterministic across server timezones
|
|
155
|
+
const cursor = new Date(fromDate.getTime());
|
|
156
|
+
cursor.setUTCMilliseconds(0);
|
|
157
|
+
if (parsed.hasSeconds) {
|
|
158
|
+
cursor.setUTCSeconds(cursor.getUTCSeconds() + 1);
|
|
159
|
+
}
|
|
160
|
+
else {
|
|
161
|
+
cursor.setUTCSeconds(0);
|
|
162
|
+
cursor.setUTCMinutes(cursor.getUTCMinutes() + 1);
|
|
163
|
+
}
|
|
164
|
+
const maxYear = cursor.getUTCFullYear() + 8;
|
|
165
|
+
let guard = 0;
|
|
166
|
+
while (runs.length < maxCount && cursor.getUTCFullYear() <= maxYear && guard < 100_000) {
|
|
167
|
+
guard++;
|
|
168
|
+
const month = cursor.getUTCMonth() + 1;
|
|
169
|
+
if (!parsed.months.has(month)) {
|
|
170
|
+
cursor.setUTCMonth(cursor.getUTCMonth() + 1, 1);
|
|
171
|
+
cursor.setUTCHours(0, 0, 0, 0);
|
|
172
|
+
continue;
|
|
173
|
+
}
|
|
174
|
+
const dom = cursor.getUTCDate();
|
|
175
|
+
const dow = cursor.getUTCDay();
|
|
176
|
+
const dayMatches = parsed.domWildcard && parsed.dowWildcard
|
|
177
|
+
? true
|
|
178
|
+
: parsed.domWildcard
|
|
179
|
+
? parsed.daysOfWeek.has(dow)
|
|
180
|
+
: parsed.dowWildcard
|
|
181
|
+
? parsed.daysOfMonth.has(dom)
|
|
182
|
+
: parsed.daysOfMonth.has(dom) || parsed.daysOfWeek.has(dow);
|
|
183
|
+
if (!dayMatches) {
|
|
184
|
+
cursor.setUTCDate(cursor.getUTCDate() + 1);
|
|
185
|
+
cursor.setUTCHours(0, 0, 0, 0);
|
|
186
|
+
continue;
|
|
187
|
+
}
|
|
188
|
+
const hour = cursor.getUTCHours();
|
|
189
|
+
const nextHr = nextAllowed(sortedHours, hour);
|
|
190
|
+
if (nextHr === null) {
|
|
191
|
+
cursor.setUTCDate(cursor.getUTCDate() + 1);
|
|
192
|
+
cursor.setUTCHours(0, 0, 0, 0);
|
|
193
|
+
continue;
|
|
194
|
+
}
|
|
195
|
+
if (nextHr !== hour) {
|
|
196
|
+
cursor.setUTCHours(nextHr, sortedMinutes[0] ?? 0, sortedSeconds[0] ?? 0, 0);
|
|
197
|
+
continue;
|
|
198
|
+
}
|
|
199
|
+
const minute = cursor.getUTCMinutes();
|
|
200
|
+
const nextMin = nextAllowed(sortedMinutes, minute);
|
|
201
|
+
if (nextMin === null) {
|
|
202
|
+
cursor.setUTCHours(hour + 1, 0, 0, 0);
|
|
203
|
+
continue;
|
|
204
|
+
}
|
|
205
|
+
if (nextMin !== minute) {
|
|
206
|
+
cursor.setUTCMinutes(nextMin, sortedSeconds[0] ?? 0, 0);
|
|
207
|
+
continue;
|
|
208
|
+
}
|
|
209
|
+
const second = cursor.getUTCSeconds();
|
|
210
|
+
const nextSec = nextAllowed(sortedSeconds, second);
|
|
211
|
+
if (nextSec === null) {
|
|
212
|
+
cursor.setUTCMinutes(minute + 1, 0, 0);
|
|
213
|
+
continue;
|
|
214
|
+
}
|
|
215
|
+
if (nextSec !== second) {
|
|
216
|
+
cursor.setUTCSeconds(nextSec, 0);
|
|
217
|
+
continue;
|
|
218
|
+
}
|
|
219
|
+
runs.push(cursor.toISOString());
|
|
220
|
+
if (parsed.hasSeconds) {
|
|
221
|
+
cursor.setUTCSeconds(cursor.getUTCSeconds() + 1);
|
|
222
|
+
}
|
|
223
|
+
else {
|
|
224
|
+
cursor.setUTCMinutes(cursor.getUTCMinutes() + 1);
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
return {
|
|
228
|
+
expression: parsed.expression,
|
|
229
|
+
description: describeCron(parsed.expression),
|
|
230
|
+
nextRuns: runs,
|
|
231
|
+
};
|
|
232
|
+
}
|
|
233
|
+
function getIsoWeek(date) {
|
|
234
|
+
const tmp = new Date(Date.UTC(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate()));
|
|
235
|
+
const dayNum = tmp.getUTCDay() || 7;
|
|
236
|
+
tmp.setUTCDate(tmp.getUTCDate() + 4 - dayNum);
|
|
237
|
+
const yearStart = new Date(Date.UTC(tmp.getUTCFullYear(), 0, 1));
|
|
238
|
+
return Math.ceil(((tmp.getTime() - yearStart.getTime()) / 86400000 + 1) / 7);
|
|
239
|
+
}
|
|
240
|
+
function formatRelative(targetMs, nowMs) {
|
|
241
|
+
const diffSec = Math.round((targetMs - nowMs) / 1000);
|
|
242
|
+
const abs = Math.abs(diffSec);
|
|
243
|
+
if (abs < 5)
|
|
244
|
+
return 'just now';
|
|
245
|
+
const suffix = diffSec >= 0 ? 'from now' : 'ago';
|
|
246
|
+
if (abs < 60)
|
|
247
|
+
return `${abs}s ${suffix}`;
|
|
248
|
+
if (abs < 3600)
|
|
249
|
+
return `${Math.round(abs / 60)}m ${suffix}`;
|
|
250
|
+
if (abs < 86400)
|
|
251
|
+
return `${Math.round(abs / 3600)}h ${suffix}`;
|
|
252
|
+
if (abs < 86400 * 30)
|
|
253
|
+
return `${Math.round(abs / 86400)}d ${suffix}`;
|
|
254
|
+
if (abs < 86400 * 365)
|
|
255
|
+
return `${Math.round(abs / (86400 * 30))}mo ${suffix}`;
|
|
256
|
+
return `${(abs / (86400 * 365.25)).toFixed(1)}y ${suffix}`;
|
|
257
|
+
}
|
|
258
|
+
export function parseTimestamp(input, nowMs = Date.now()) {
|
|
259
|
+
const raw = input.trim();
|
|
260
|
+
let date;
|
|
261
|
+
let detectedFormat = 'ISO-8601 / Date String';
|
|
262
|
+
if (!raw || raw.toLowerCase() === 'now') {
|
|
263
|
+
date = new Date(nowMs);
|
|
264
|
+
detectedFormat = 'Current Time';
|
|
265
|
+
}
|
|
266
|
+
else if (/^-?\d+$/.test(raw)) {
|
|
267
|
+
const absDigits = raw.replace('-', '').length;
|
|
268
|
+
if (absDigits >= 17) {
|
|
269
|
+
// nanoseconds
|
|
270
|
+
const ms = Number(BigInt(raw) / 1000000n);
|
|
271
|
+
date = new Date(ms);
|
|
272
|
+
detectedFormat = 'Unix Nanoseconds';
|
|
273
|
+
}
|
|
274
|
+
else if (absDigits >= 14) {
|
|
275
|
+
// microseconds
|
|
276
|
+
const ms = Number(BigInt(raw) / 1000n);
|
|
277
|
+
date = new Date(ms);
|
|
278
|
+
detectedFormat = 'Unix Microseconds';
|
|
279
|
+
}
|
|
280
|
+
else if (absDigits >= 12) {
|
|
281
|
+
date = new Date(Number(raw));
|
|
282
|
+
detectedFormat = 'Unix Milliseconds';
|
|
283
|
+
}
|
|
284
|
+
else {
|
|
285
|
+
date = new Date(Number(raw) * 1000);
|
|
286
|
+
detectedFormat = 'Unix Seconds';
|
|
287
|
+
}
|
|
288
|
+
}
|
|
289
|
+
else {
|
|
290
|
+
date = new Date(raw);
|
|
291
|
+
}
|
|
292
|
+
if (Number.isNaN(date.getTime())) {
|
|
293
|
+
throw new Error(`Unable to parse timestamp: "${input}"`);
|
|
294
|
+
}
|
|
295
|
+
const startOfYear = Date.UTC(date.getUTCFullYear(), 0, 0);
|
|
296
|
+
const dayOfYear = Math.floor((date.getTime() - startOfYear) / 86_400_000);
|
|
297
|
+
const unixMillis = date.getTime();
|
|
298
|
+
return {
|
|
299
|
+
isoUtc: date.toISOString(),
|
|
300
|
+
rfc2822: date.toUTCString(),
|
|
301
|
+
unixSeconds: Math.floor(unixMillis / 1000),
|
|
302
|
+
unixMillis,
|
|
303
|
+
unixNanos: (BigInt(unixMillis) * 1000000n).toString(),
|
|
304
|
+
relative: formatRelative(unixMillis, nowMs),
|
|
305
|
+
dayOfYear,
|
|
306
|
+
isoWeek: getIsoWeek(date),
|
|
307
|
+
detectedFormat,
|
|
308
|
+
};
|
|
309
|
+
}
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
export type HashAlgorithm = 'sha256' | 'sha384' | 'sha512' | 'sha1' | 'md5' | 'blake2b512' | 'blake2s256';
|
|
2
|
+
export interface HashResult {
|
|
3
|
+
algorithm: HashAlgorithm;
|
|
4
|
+
hex: string;
|
|
5
|
+
base64: string;
|
|
6
|
+
bits: number;
|
|
7
|
+
warning?: string;
|
|
8
|
+
}
|
|
9
|
+
export declare function hashText(input: string, algorithm?: HashAlgorithm): HashResult;
|
|
10
|
+
export declare function hmacText(input: string, secret: string, algorithm?: HashAlgorithm): HashResult;
|
|
11
|
+
/**
|
|
12
|
+
* Authenticated AES-256-GCM encryption with random 16-byte salt (scrypt KDF) and 12-byte IV.
|
|
13
|
+
* Output envelope: v1:<salt_b64url>:<iv_b64url>:<authTag_b64url>:<ciphertext_b64url>
|
|
14
|
+
*/
|
|
15
|
+
export declare function encryptAesGcm(plaintext: string, passphrase: string): string;
|
|
16
|
+
export declare function decryptAesGcm(envelope: string, passphrase: string): string;
|
|
17
|
+
export declare function deriveKey(password: string, options?: {
|
|
18
|
+
kdf?: 'scrypt' | 'pbkdf2';
|
|
19
|
+
saltHex?: string;
|
|
20
|
+
iterations?: number;
|
|
21
|
+
keyLength?: number;
|
|
22
|
+
}): {
|
|
23
|
+
kdf: string;
|
|
24
|
+
saltHex: string;
|
|
25
|
+
derivedHex: string;
|
|
26
|
+
derivedBase64: string;
|
|
27
|
+
};
|
|
28
|
+
export interface PasswordOptions {
|
|
29
|
+
length?: number;
|
|
30
|
+
uppercase?: boolean;
|
|
31
|
+
lowercase?: boolean;
|
|
32
|
+
numbers?: boolean;
|
|
33
|
+
symbols?: boolean;
|
|
34
|
+
excludeAmbiguous?: boolean;
|
|
35
|
+
}
|
|
36
|
+
export interface PasswordResult {
|
|
37
|
+
password: string;
|
|
38
|
+
entropyBits: number;
|
|
39
|
+
strength: 'weak' | 'fair' | 'strong' | 'very-strong';
|
|
40
|
+
crackTimeEstimate: string;
|
|
41
|
+
}
|
|
42
|
+
export declare function generatePassword(options?: PasswordOptions): PasswordResult;
|
|
43
|
+
export declare function generateUuidV4(): string;
|
|
44
|
+
/**
|
|
45
|
+
* RFC 9562 UUIDv7 (48-bit Unix epoch ms timestamp + 4-bit version 7 + 12-bit rand_a + 2-bit variant + 62-bit rand_b)
|
|
46
|
+
*/
|
|
47
|
+
export declare function generateUuidV7(nowMs?: number): string;
|
|
48
|
+
/**
|
|
49
|
+
* Monotonic-friendly Crockford Base32 ULID (48-bit ms timestamp + 80-bit CSPRNG randomness)
|
|
50
|
+
*/
|
|
51
|
+
export declare function generateUlid(nowMs?: number): string;
|
|
52
|
+
export declare function generateNanoId(size?: number): string;
|
|
53
|
+
export declare function generateApiKey(prefix?: string): string;
|
|
54
|
+
export declare function generateAsymmetricKeyPair(type?: 'rsa' | 'ec'): {
|
|
55
|
+
type: 'rsa' | 'ec';
|
|
56
|
+
algorithmHint: 'RS256' | 'ES256';
|
|
57
|
+
publicKeyPem: string;
|
|
58
|
+
privateKeyPem: string;
|
|
59
|
+
};
|
|
@@ -0,0 +1,260 @@
|
|
|
1
|
+
import { createCipheriv, createDecipheriv, createHash, createHmac, generateKeyPairSync, pbkdf2Sync, randomBytes, randomInt, randomUUID, scryptSync, } from 'node:crypto';
|
|
2
|
+
const ALLOWED_HASH_ALGOS = new Set([
|
|
3
|
+
'sha256',
|
|
4
|
+
'sha384',
|
|
5
|
+
'sha512',
|
|
6
|
+
'sha1',
|
|
7
|
+
'md5',
|
|
8
|
+
'blake2b512',
|
|
9
|
+
'blake2s256',
|
|
10
|
+
]);
|
|
11
|
+
export function hashText(input, algorithm = 'sha256') {
|
|
12
|
+
if (!ALLOWED_HASH_ALGOS.has(algorithm)) {
|
|
13
|
+
throw new Error(`Unsupported hash algorithm: ${String(algorithm)}`);
|
|
14
|
+
}
|
|
15
|
+
const digest = createHash(algorithm).update(input, 'utf8').digest();
|
|
16
|
+
const warning = algorithm === 'md5' || algorithm === 'sha1'
|
|
17
|
+
? `${algorithm.toUpperCase()} is cryptographically broken for collision resistance; use SHA-256 or BLAKE2b for security.`
|
|
18
|
+
: undefined;
|
|
19
|
+
return {
|
|
20
|
+
algorithm,
|
|
21
|
+
hex: digest.toString('hex'),
|
|
22
|
+
base64: digest.toString('base64'),
|
|
23
|
+
bits: digest.length * 8,
|
|
24
|
+
...(warning ? { warning } : {}),
|
|
25
|
+
};
|
|
26
|
+
}
|
|
27
|
+
export function hmacText(input, secret, algorithm = 'sha256') {
|
|
28
|
+
if (!ALLOWED_HASH_ALGOS.has(algorithm)) {
|
|
29
|
+
throw new Error(`Unsupported HMAC algorithm: ${String(algorithm)}`);
|
|
30
|
+
}
|
|
31
|
+
const digest = createHmac(algorithm, secret).update(input, 'utf8').digest();
|
|
32
|
+
return {
|
|
33
|
+
algorithm,
|
|
34
|
+
hex: digest.toString('hex'),
|
|
35
|
+
base64: digest.toString('base64'),
|
|
36
|
+
bits: digest.length * 8,
|
|
37
|
+
};
|
|
38
|
+
}
|
|
39
|
+
/**
|
|
40
|
+
* Authenticated AES-256-GCM encryption with random 16-byte salt (scrypt KDF) and 12-byte IV.
|
|
41
|
+
* Output envelope: v1:<salt_b64url>:<iv_b64url>:<authTag_b64url>:<ciphertext_b64url>
|
|
42
|
+
*/
|
|
43
|
+
export function encryptAesGcm(plaintext, passphrase) {
|
|
44
|
+
if (!passphrase) {
|
|
45
|
+
throw new Error('Passphrase is required for AES-256-GCM encryption');
|
|
46
|
+
}
|
|
47
|
+
const salt = randomBytes(16);
|
|
48
|
+
const iv = randomBytes(12);
|
|
49
|
+
const key = scryptSync(passphrase, salt, 32, { N: 16384, r: 8, p: 1 });
|
|
50
|
+
const cipher = createCipheriv('aes-256-gcm', key, iv);
|
|
51
|
+
const ciphertext = Buffer.concat([cipher.update(plaintext, 'utf8'), cipher.final()]);
|
|
52
|
+
const authTag = cipher.getAuthTag();
|
|
53
|
+
return [
|
|
54
|
+
'v1',
|
|
55
|
+
salt.toString('base64url'),
|
|
56
|
+
iv.toString('base64url'),
|
|
57
|
+
authTag.toString('base64url'),
|
|
58
|
+
ciphertext.toString('base64url'),
|
|
59
|
+
].join(':');
|
|
60
|
+
}
|
|
61
|
+
export function decryptAesGcm(envelope, passphrase) {
|
|
62
|
+
if (!passphrase) {
|
|
63
|
+
throw new Error('Passphrase is required for AES-256-GCM decryption');
|
|
64
|
+
}
|
|
65
|
+
const parts = envelope.trim().split(':');
|
|
66
|
+
if (parts.length !== 5 || parts[0] !== 'v1') {
|
|
67
|
+
throw new Error('Invalid AES-256-GCM envelope format (expected v1:salt:iv:tag:ciphertext)');
|
|
68
|
+
}
|
|
69
|
+
const [, saltB64, ivB64, tagB64, ctB64] = parts;
|
|
70
|
+
const salt = Buffer.from(saltB64, 'base64url');
|
|
71
|
+
const iv = Buffer.from(ivB64, 'base64url');
|
|
72
|
+
const authTag = Buffer.from(tagB64, 'base64url');
|
|
73
|
+
const ciphertext = Buffer.from(ctB64, 'base64url');
|
|
74
|
+
if (salt.length !== 16 || iv.length !== 12 || authTag.length !== 16) {
|
|
75
|
+
throw new Error('Corrupted cryptographic parameters in AES-256-GCM envelope');
|
|
76
|
+
}
|
|
77
|
+
const key = scryptSync(passphrase, salt, 32, { N: 16384, r: 8, p: 1 });
|
|
78
|
+
const decipher = createDecipheriv('aes-256-gcm', key, iv);
|
|
79
|
+
decipher.setAuthTag(authTag);
|
|
80
|
+
try {
|
|
81
|
+
const plaintext = Buffer.concat([decipher.update(ciphertext), decipher.final()]);
|
|
82
|
+
return plaintext.toString('utf8');
|
|
83
|
+
}
|
|
84
|
+
catch {
|
|
85
|
+
throw new Error('Decryption failed: wrong passphrase or tampered ciphertext');
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
export function deriveKey(password, options = {}) {
|
|
89
|
+
const kdf = options.kdf ?? 'scrypt';
|
|
90
|
+
const keyLength = Math.min(Math.max(options.keyLength ?? 32, 16), 64);
|
|
91
|
+
let salt;
|
|
92
|
+
if (options.saltHex !== undefined && options.saltHex !== '') {
|
|
93
|
+
const cleanSalt = options.saltHex.trim();
|
|
94
|
+
if (!/^[0-9a-fA-F]+$/.test(cleanSalt) || cleanSalt.length % 2 !== 0 || cleanSalt.length < 16) {
|
|
95
|
+
throw new Error('saltHex must be a valid even-length hexadecimal string of at least 8 bytes (16 hex chars)');
|
|
96
|
+
}
|
|
97
|
+
salt = Buffer.from(cleanSalt, 'hex');
|
|
98
|
+
}
|
|
99
|
+
else {
|
|
100
|
+
salt = randomBytes(16);
|
|
101
|
+
}
|
|
102
|
+
let derived;
|
|
103
|
+
if (kdf === 'pbkdf2') {
|
|
104
|
+
const iterations = Math.min(Math.max(options.iterations ?? 210_000, 10_000), 1_000_000);
|
|
105
|
+
derived = pbkdf2Sync(password, salt, iterations, keyLength, 'sha512');
|
|
106
|
+
}
|
|
107
|
+
else {
|
|
108
|
+
derived = scryptSync(password, salt, keyLength, { N: 16384, r: 8, p: 1 });
|
|
109
|
+
}
|
|
110
|
+
return {
|
|
111
|
+
kdf,
|
|
112
|
+
saltHex: salt.toString('hex'),
|
|
113
|
+
derivedHex: derived.toString('hex'),
|
|
114
|
+
derivedBase64: derived.toString('base64'),
|
|
115
|
+
};
|
|
116
|
+
}
|
|
117
|
+
function formatCrackTime(entropyBits) {
|
|
118
|
+
// Assume 1e10 guesses/sec (modern GPU cluster offline hash crack benchmark)
|
|
119
|
+
const guessesPerSec = 1e10;
|
|
120
|
+
const seconds = Math.pow(2, Math.max(entropyBits - 1, 0)) / guessesPerSec;
|
|
121
|
+
if (seconds < 1)
|
|
122
|
+
return 'Instant';
|
|
123
|
+
if (seconds < 60)
|
|
124
|
+
return `${Math.round(seconds)} seconds`;
|
|
125
|
+
if (seconds < 3600)
|
|
126
|
+
return `${Math.round(seconds / 60)} minutes`;
|
|
127
|
+
if (seconds < 86400)
|
|
128
|
+
return `${Math.round(seconds / 3600)} hours`;
|
|
129
|
+
if (seconds < 86400 * 365)
|
|
130
|
+
return `${Math.round(seconds / 86400)} days`;
|
|
131
|
+
const years = seconds / (86400 * 365.25);
|
|
132
|
+
if (years < 1e3)
|
|
133
|
+
return `${Math.round(years)} years`;
|
|
134
|
+
if (years < 1e6)
|
|
135
|
+
return `${(years / 1e3).toFixed(1)}k years`;
|
|
136
|
+
if (years < 1e9)
|
|
137
|
+
return `${(years / 1e6).toFixed(1)}M years`;
|
|
138
|
+
if (years < 1e12)
|
|
139
|
+
return `${(years / 1e9).toFixed(1)}B years`;
|
|
140
|
+
return 'Centuries+ (Heat death of universe)';
|
|
141
|
+
}
|
|
142
|
+
export function generatePassword(options = {}) {
|
|
143
|
+
const length = Math.min(Math.max(Math.floor(options.length ?? 20), 6), 128);
|
|
144
|
+
const excludeAmbiguous = Boolean(options.excludeAmbiguous);
|
|
145
|
+
const stripAmb = (s) => (excludeAmbiguous ? s.replace(/[0O1lI|`'"]/g, '') : s);
|
|
146
|
+
const pools = [];
|
|
147
|
+
if (options.lowercase !== false)
|
|
148
|
+
pools.push(stripAmb('abcdefghijklmnopqrstuvwxyz'));
|
|
149
|
+
if (options.uppercase !== false)
|
|
150
|
+
pools.push(stripAmb('ABCDEFGHIJKLMNOPQRSTUVWXYZ'));
|
|
151
|
+
if (options.numbers !== false)
|
|
152
|
+
pools.push(stripAmb('0123456789'));
|
|
153
|
+
if (options.symbols !== false)
|
|
154
|
+
pools.push(stripAmb('!@#$%^&*()-_=+[]{}~?'));
|
|
155
|
+
const activePools = pools.filter((p) => p.length > 0);
|
|
156
|
+
if (!activePools.length) {
|
|
157
|
+
throw new Error('At least one character set must be enabled');
|
|
158
|
+
}
|
|
159
|
+
const combined = activePools.join('');
|
|
160
|
+
const chars = [];
|
|
161
|
+
// Guarantee at least one character from each enabled pool
|
|
162
|
+
for (const pool of activePools) {
|
|
163
|
+
if (chars.length < length) {
|
|
164
|
+
chars.push(pool[randomInt(0, pool.length)]);
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
while (chars.length < length) {
|
|
168
|
+
chars.push(combined[randomInt(0, combined.length)]);
|
|
169
|
+
}
|
|
170
|
+
// Cryptographically secure Fisher-Yates shuffle
|
|
171
|
+
for (let i = chars.length - 1; i > 0; i--) {
|
|
172
|
+
const j = randomInt(0, i + 1);
|
|
173
|
+
const tmp = chars[i];
|
|
174
|
+
chars[i] = chars[j];
|
|
175
|
+
chars[j] = tmp;
|
|
176
|
+
}
|
|
177
|
+
const entropyBits = Math.round(length * Math.log2(combined.length) * 10) / 10;
|
|
178
|
+
let strength = 'weak';
|
|
179
|
+
if (entropyBits >= 96)
|
|
180
|
+
strength = 'very-strong';
|
|
181
|
+
else if (entropyBits >= 64)
|
|
182
|
+
strength = 'strong';
|
|
183
|
+
else if (entropyBits >= 45)
|
|
184
|
+
strength = 'fair';
|
|
185
|
+
return {
|
|
186
|
+
password: chars.join(''),
|
|
187
|
+
entropyBits,
|
|
188
|
+
strength,
|
|
189
|
+
crackTimeEstimate: formatCrackTime(entropyBits),
|
|
190
|
+
};
|
|
191
|
+
}
|
|
192
|
+
export function generateUuidV4() {
|
|
193
|
+
return randomUUID();
|
|
194
|
+
}
|
|
195
|
+
/**
|
|
196
|
+
* RFC 9562 UUIDv7 (48-bit Unix epoch ms timestamp + 4-bit version 7 + 12-bit rand_a + 2-bit variant + 62-bit rand_b)
|
|
197
|
+
*/
|
|
198
|
+
export function generateUuidV7(nowMs = Date.now()) {
|
|
199
|
+
const bytes = randomBytes(16);
|
|
200
|
+
const ts = BigInt(nowMs);
|
|
201
|
+
bytes[0] = Number((ts >> 40n) & 0xffn);
|
|
202
|
+
bytes[1] = Number((ts >> 32n) & 0xffn);
|
|
203
|
+
bytes[2] = Number((ts >> 24n) & 0xffn);
|
|
204
|
+
bytes[3] = Number((ts >> 16n) & 0xffn);
|
|
205
|
+
bytes[4] = Number((ts >> 8n) & 0xffn);
|
|
206
|
+
bytes[5] = Number(ts & 0xffn);
|
|
207
|
+
// Set version 7 (0111)
|
|
208
|
+
bytes[6] = (bytes[6] & 0x0f) | 0x70;
|
|
209
|
+
// Set RFC 4122/9562 variant (10xx)
|
|
210
|
+
bytes[8] = (bytes[8] & 0x3f) | 0x80;
|
|
211
|
+
const hex = bytes.toString('hex');
|
|
212
|
+
return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20, 32)}`;
|
|
213
|
+
}
|
|
214
|
+
const CROCKFORD_B32 = '0123456789ABCDEFGHJKMNPQRSTVWXYZ';
|
|
215
|
+
/**
|
|
216
|
+
* Monotonic-friendly Crockford Base32 ULID (48-bit ms timestamp + 80-bit CSPRNG randomness)
|
|
217
|
+
*/
|
|
218
|
+
export function generateUlid(nowMs = Date.now()) {
|
|
219
|
+
let time = nowMs;
|
|
220
|
+
const timeChars = new Array(10);
|
|
221
|
+
for (let i = 9; i >= 0; i--) {
|
|
222
|
+
timeChars[i] = CROCKFORD_B32[time % 32];
|
|
223
|
+
time = Math.floor(time / 32);
|
|
224
|
+
}
|
|
225
|
+
const randChars = new Array(16);
|
|
226
|
+
for (let i = 0; i < 16; i++) {
|
|
227
|
+
randChars[i] = CROCKFORD_B32[randomInt(0, 32)];
|
|
228
|
+
}
|
|
229
|
+
return timeChars.join('') + randChars.join('');
|
|
230
|
+
}
|
|
231
|
+
const NANOID_ALPHABET = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz_-';
|
|
232
|
+
export function generateNanoId(size = 21) {
|
|
233
|
+
const len = Math.min(Math.max(Math.floor(size), 4), 128);
|
|
234
|
+
let out = '';
|
|
235
|
+
for (let i = 0; i < len; i++) {
|
|
236
|
+
out += NANOID_ALPHABET[randomInt(0, NANOID_ALPHABET.length)];
|
|
237
|
+
}
|
|
238
|
+
return out;
|
|
239
|
+
}
|
|
240
|
+
export function generateApiKey(prefix = 'da_live') {
|
|
241
|
+
const cleanPrefix = prefix.replace(/[^a-zA-Z0-9_-]/g, '').slice(0, 24) || 'key';
|
|
242
|
+
const token = randomBytes(24).toString('base64url');
|
|
243
|
+
return `${cleanPrefix}_${token}`;
|
|
244
|
+
}
|
|
245
|
+
export function generateAsymmetricKeyPair(type = 'ec') {
|
|
246
|
+
if (type === 'rsa') {
|
|
247
|
+
const { publicKey, privateKey } = generateKeyPairSync('rsa', {
|
|
248
|
+
modulusLength: 2048,
|
|
249
|
+
publicKeyEncoding: { type: 'spki', format: 'pem' },
|
|
250
|
+
privateKeyEncoding: { type: 'pkcs8', format: 'pem' },
|
|
251
|
+
});
|
|
252
|
+
return { type: 'rsa', algorithmHint: 'RS256', publicKeyPem: publicKey, privateKeyPem: privateKey };
|
|
253
|
+
}
|
|
254
|
+
const { publicKey, privateKey } = generateKeyPairSync('ec', {
|
|
255
|
+
namedCurve: 'prime256v1',
|
|
256
|
+
publicKeyEncoding: { type: 'spki', format: 'pem' },
|
|
257
|
+
privateKeyEncoding: { type: 'pkcs8', format: 'pem' },
|
|
258
|
+
});
|
|
259
|
+
return { type: 'ec', algorithmHint: 'ES256', publicKeyPem: publicKey, privateKeyPem: privateKey };
|
|
260
|
+
}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
export interface ParsedHttpRequest {
|
|
2
|
+
method: string;
|
|
3
|
+
url: string;
|
|
4
|
+
headers: Record<string, string>;
|
|
5
|
+
body: string;
|
|
6
|
+
}
|
|
7
|
+
/**
|
|
8
|
+
* Parses a pasted cURL command into structured HTTP request parameters.
|
|
9
|
+
*/
|
|
10
|
+
export declare function parseCurlCommand(curlCmd: string): ParsedHttpRequest;
|
|
11
|
+
export interface CodeSnippets {
|
|
12
|
+
curl: string;
|
|
13
|
+
fetch: string;
|
|
14
|
+
python: string;
|
|
15
|
+
go: string;
|
|
16
|
+
}
|
|
17
|
+
export declare function generateCodeSnippets(req: ParsedHttpRequest): CodeSnippets;
|