@sriinnu/fiche 0.0.0-stage → 0.19.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 +134 -0
- package/LICENSE +22 -0
- package/NOTICE +13 -0
- package/PRIVACY.md +41 -0
- package/README.md +288 -2
- package/SECURITY.md +53 -0
- package/assets/JETBRAINS_MONO_LICENSE.txt +89 -0
- package/assets/SPLEEN_LICENSE.txt +24 -0
- package/assets/UNIFONT_LICENSE.txt +476 -0
- package/assets/fiche-logo-dark.svg +61 -0
- package/assets/fiche-logo-light.svg +61 -0
- package/assets/fiche-logo.svg +71 -0
- package/assets/fiche-mark.svg +48 -0
- package/bin/cli.js +7 -0
- package/bin/mcp.js +8 -0
- package/dist/calibrate.d.ts +30 -0
- package/dist/calibrate.js +588 -0
- package/dist/core/anthropic-vision.d.ts +28 -0
- package/dist/core/anthropic-vision.js +34 -0
- package/dist/core/applicability.d.ts +63 -0
- package/dist/core/applicability.js +151 -0
- package/dist/core/atlas-gray-jbmono10.d.ts +26 -0
- package/dist/core/atlas-gray-jbmono10.js +64 -0
- package/dist/core/atlas-gray-jbmono12.d.ts +26 -0
- package/dist/core/atlas-gray-jbmono12.js +64 -0
- package/dist/core/atlas-gray-jbmono14.d.ts +26 -0
- package/dist/core/atlas-gray-jbmono14.js +64 -0
- package/dist/core/atlas-gray.d.ts +26 -0
- package/dist/core/atlas-gray.js +64 -0
- package/dist/core/atlas-jbmono10.d.ts +34 -0
- package/dist/core/atlas-jbmono10.js +71 -0
- package/dist/core/atlas-jbmono12.d.ts +34 -0
- package/dist/core/atlas-jbmono12.js +71 -0
- package/dist/core/atlas-jbmono14.d.ts +34 -0
- package/dist/core/atlas-jbmono14.js +71 -0
- package/dist/core/atlas.d.ts +34 -0
- package/dist/core/atlas.js +71 -0
- package/dist/core/baseline.d.ts +121 -0
- package/dist/core/baseline.js +200 -0
- package/dist/core/calibration.d.ts +86 -0
- package/dist/core/calibration.js +547 -0
- package/dist/core/casi-delta.d.ts +63 -0
- package/dist/core/casi-delta.js +1271 -0
- package/dist/core/claude-model-profiles.d.ts +53 -0
- package/dist/core/claude-model-profiles.js +160 -0
- package/dist/core/client-tool-round.d.ts +31 -0
- package/dist/core/client-tool-round.js +58 -0
- package/dist/core/codex-cache.d.ts +20 -0
- package/dist/core/codex-cache.js +59 -0
- package/dist/core/context-mmu.d.ts +350 -0
- package/dist/core/context-mmu.js +3028 -0
- package/dist/core/cpt-fit.d.ts +70 -0
- package/dist/core/cpt-fit.js +197 -0
- package/dist/core/env.d.ts +8 -0
- package/dist/core/env.js +15 -0
- package/dist/core/export.d.ts +127 -0
- package/dist/core/export.js +385 -0
- package/dist/core/factsheet.d.ts +77 -0
- package/dist/core/factsheet.js +494 -0
- package/dist/core/gemini-model-profiles.d.ts +20 -0
- package/dist/core/gemini-model-profiles.js +134 -0
- package/dist/core/google.d.ts +76 -0
- package/dist/core/google.js +1380 -0
- package/dist/core/gpt-model-profiles.d.ts +218 -0
- package/dist/core/gpt-model-profiles.js +570 -0
- package/dist/core/gpt-tokens.d.ts +14 -0
- package/dist/core/gpt-tokens.js +165 -0
- package/dist/core/history.d.ts +197 -0
- package/dist/core/history.js +1003 -0
- package/dist/core/index.d.ts +16 -0
- package/dist/core/index.js +16 -0
- package/dist/core/library.d.ts +80 -0
- package/dist/core/library.js +131 -0
- package/dist/core/measurement.d.ts +34 -0
- package/dist/core/measurement.js +280 -0
- package/dist/core/messages-chat-bridge.d.ts +23 -0
- package/dist/core/messages-chat-bridge.js +747 -0
- package/dist/core/messages-responses-bridge.d.ts +11 -0
- package/dist/core/messages-responses-bridge.js +893 -0
- package/dist/core/openai-history.d.ts +184 -0
- package/dist/core/openai-history.js +1279 -0
- package/dist/core/openai-savings.d.ts +57 -0
- package/dist/core/openai-savings.js +116 -0
- package/dist/core/openai.d.ts +68 -0
- package/dist/core/openai.js +2523 -0
- package/dist/core/pin.d.ts +199 -0
- package/dist/core/pin.js +1353 -0
- package/dist/core/png.d.ts +14 -0
- package/dist/core/png.js +188 -0
- package/dist/core/prefix-tape.d.ts +102 -0
- package/dist/core/prefix-tape.js +315 -0
- package/dist/core/price-id.d.ts +10 -0
- package/dist/core/price-id.js +26 -0
- package/dist/core/prices.generated.d.ts +36 -0
- package/dist/core/prices.generated.js +369 -0
- package/dist/core/pricing.d.ts +134 -0
- package/dist/core/pricing.js +335 -0
- package/dist/core/profile-base.d.ts +30 -0
- package/dist/core/profile-base.js +67 -0
- package/dist/core/provider-router.d.ts +51 -0
- package/dist/core/provider-router.js +121 -0
- package/dist/core/proxy.d.ts +252 -0
- package/dist/core/proxy.js +2929 -0
- package/dist/core/reader-tier.d.ts +24 -0
- package/dist/core/reader-tier.js +118 -0
- package/dist/core/render.d.ts +280 -0
- package/dist/core/render.js +1302 -0
- package/dist/core/request-guard.d.ts +31 -0
- package/dist/core/request-guard.js +126 -0
- package/dist/core/request-transform.d.ts +43 -0
- package/dist/core/request-transform.js +173 -0
- package/dist/core/schema-compiler.d.ts +64 -0
- package/dist/core/schema-compiler.js +1696 -0
- package/dist/core/schema-strip.d.ts +29 -0
- package/dist/core/schema-strip.js +173 -0
- package/dist/core/session-state.d.ts +219 -0
- package/dist/core/session-state.js +929 -0
- package/dist/core/stage-plugins.d.ts +45 -0
- package/dist/core/stage-plugins.js +205 -0
- package/dist/core/text-history.d.ts +74 -0
- package/dist/core/text-history.js +612 -0
- package/dist/core/text-hygiene.d.ts +160 -0
- package/dist/core/text-hygiene.js +2259 -0
- package/dist/core/toon.d.ts +29 -0
- package/dist/core/toon.js +425 -0
- package/dist/core/tracker.d.ts +223 -0
- package/dist/core/tracker.js +290 -0
- package/dist/core/transform.d.ts +589 -0
- package/dist/core/transform.js +3153 -0
- package/dist/core/types.d.ts +87 -0
- package/dist/core/types.js +8 -0
- package/dist/core/upstream-hosts.d.ts +127 -0
- package/dist/core/upstream-hosts.js +398 -0
- package/dist/core/vision-cost.d.ts +63 -0
- package/dist/core/vision-cost.js +137 -0
- package/dist/dashboard/fragments.d.ts +87 -0
- package/dist/dashboard/fragments.js +1515 -0
- package/dist/dashboard/types.d.ts +217 -0
- package/dist/dashboard/types.js +3 -0
- package/dist/dashboard/vendor.d.ts +3 -0
- package/dist/dashboard/vendor.js +6 -0
- package/dist/dashboard.d.ts +372 -0
- package/dist/dashboard.js +2731 -0
- package/dist/export-collect.d.ts +36 -0
- package/dist/export-collect.js +59 -0
- package/dist/file-tracker.d.ts +42 -0
- package/dist/file-tracker.js +234 -0
- package/dist/kosha-sync.d.ts +74 -0
- package/dist/kosha-sync.js +272 -0
- package/dist/launchd-socket.d.ts +22 -0
- package/dist/launchd-socket.js +210 -0
- package/dist/mcp/cli.d.ts +2 -0
- package/dist/mcp/cli.js +55 -0
- package/dist/mcp/server.d.ts +48 -0
- package/dist/mcp/server.js +987 -0
- package/dist/mmu-store.d.ts +31 -0
- package/dist/mmu-store.js +179 -0
- package/dist/node-fetch.d.ts +22 -0
- package/dist/node-fetch.js +489 -0
- package/dist/node.d.ts +9 -0
- package/dist/node.js +244396 -0
- package/dist/request-decoding.d.ts +30 -0
- package/dist/request-decoding.js +85 -0
- package/dist/sessions.d.ts +179 -0
- package/dist/sessions.js +837 -0
- package/dist/stats.d.ts +114 -0
- package/dist/stats.js +439 -0
- package/dist/turn-report.d.ts +65 -0
- package/dist/turn-report.js +724 -0
- package/dist/warp/app-launch.d.ts +26 -0
- package/dist/warp/app-launch.js +155 -0
- package/dist/warp/ca.d.ts +74 -0
- package/dist/warp/ca.js +416 -0
- package/dist/warp/connect.d.ts +42 -0
- package/dist/warp/connect.js +686 -0
- package/dist/warp/der.d.ts +57 -0
- package/dist/warp/der.js +151 -0
- package/dist/warp/index.d.ts +79 -0
- package/dist/warp/index.js +650 -0
- package/dist/warp/resolve.d.ts +12 -0
- package/dist/warp/resolve.js +49 -0
- package/dist/warp/route.d.ts +71 -0
- package/dist/warp/route.js +134 -0
- package/dist/worker.d.ts +71 -0
- package/dist/worker.js +174 -0
- package/docs/SECURITY_MODEL.md +84 -0
- package/package.json +122 -4
- package/plugins/fiche-companion/README.md +42 -0
- package/plugins/fiche-companion/assets/logo.svg +48 -0
- package/plugins/fiche-companion/hooks.json +11 -0
- package/plugins/fiche-companion/mcp_config.json +8 -0
- package/plugins/fiche-companion/plugin.json +18 -0
- package/plugins/fiche-companion/scripts/claude-statusline.mjs +35 -0
- package/plugins/fiche-companion/scripts/post-invocation.mjs +122 -0
- package/plugins/fiche-companion/scripts/resolve-turn-report.mjs +132 -0
- package/plugins/fiche-companion/skills/fiche/SKILL.md +61 -0
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Resolve macOS `.app` bundles for `fiche warp --app` and generate POSIX shell
|
|
3
|
+
* helpers (`fiche shell-init`) so both CLIs and GUI provider apps route cleanly
|
|
4
|
+
* through the local Fiche proxy.
|
|
5
|
+
*/
|
|
6
|
+
export interface ResolvedMacApp {
|
|
7
|
+
readonly appPath: string;
|
|
8
|
+
readonly executablePath: string;
|
|
9
|
+
readonly appName: string;
|
|
10
|
+
readonly isElectron: boolean;
|
|
11
|
+
}
|
|
12
|
+
/** Parse CFBundleExecutable from an XML Info.plist without requiring macOS `plutil`. */
|
|
13
|
+
export declare function parseXmlBundleExecutable(infoPlistPath: string): string | null;
|
|
14
|
+
/** Resolve an installed macOS `.app` bundle by app name or `.app` path. */
|
|
15
|
+
export declare function resolveMacAppBundle(spec: string, searchDirs?: readonly string[]): ResolvedMacApp | null;
|
|
16
|
+
/** Build argv to launch a resolved macOS desktop app behind `fiche warp`. */
|
|
17
|
+
export declare function buildWarpAppArgs(app: ResolvedMacApp, proxyUrl: string, extraArgs?: readonly string[], opts?: {
|
|
18
|
+
spkiPins?: readonly string[];
|
|
19
|
+
proxyBypassList?: string;
|
|
20
|
+
}): string[];
|
|
21
|
+
/** Render POSIX zsh/bash shell helpers (or transparent wrappers when `--wrap` is set). */
|
|
22
|
+
export declare function renderShellInitScript(opts?: {
|
|
23
|
+
wrap?: boolean;
|
|
24
|
+
ficheBin?: string;
|
|
25
|
+
}): string;
|
|
26
|
+
//# sourceMappingURL=app-launch.d.ts.map
|
|
@@ -0,0 +1,155 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Resolve macOS `.app` bundles for `fiche warp --app` and generate POSIX shell
|
|
3
|
+
* helpers (`fiche shell-init`) so both CLIs and GUI provider apps route cleanly
|
|
4
|
+
* through the local Fiche proxy.
|
|
5
|
+
*/
|
|
6
|
+
import { spawnSync } from 'node:child_process';
|
|
7
|
+
import { existsSync, readdirSync, readFileSync } from 'node:fs';
|
|
8
|
+
import { homedir } from 'node:os';
|
|
9
|
+
import { basename, join, resolve } from 'node:path';
|
|
10
|
+
const DEFAULT_APP_SEARCH_DIRS = ['/Applications', join(homedir(), 'Applications')];
|
|
11
|
+
function sanitizeExecutableName(raw) {
|
|
12
|
+
const exe = raw.trim();
|
|
13
|
+
if (!exe || exe === '.' || exe === '..' || exe.includes('/') || exe.includes('\\') || exe.includes('\0')) {
|
|
14
|
+
return null;
|
|
15
|
+
}
|
|
16
|
+
return exe;
|
|
17
|
+
}
|
|
18
|
+
/** Parse CFBundleExecutable from an XML Info.plist without requiring macOS `plutil`. */
|
|
19
|
+
export function parseXmlBundleExecutable(infoPlistPath) {
|
|
20
|
+
let xml;
|
|
21
|
+
try {
|
|
22
|
+
xml = readFileSync(infoPlistPath, 'utf8');
|
|
23
|
+
}
|
|
24
|
+
catch {
|
|
25
|
+
return null;
|
|
26
|
+
}
|
|
27
|
+
if (xml.startsWith('bplist'))
|
|
28
|
+
return null;
|
|
29
|
+
const match = /<key>\s*CFBundleExecutable\s*<\/key>\s*<string>([^<]+)<\/string>/i.exec(xml);
|
|
30
|
+
if (!match?.[1])
|
|
31
|
+
return null;
|
|
32
|
+
const decoded = match[1]
|
|
33
|
+
.replaceAll('<', '<')
|
|
34
|
+
.replaceAll('>', '>')
|
|
35
|
+
.replaceAll('"', '"')
|
|
36
|
+
.replaceAll(''', "'")
|
|
37
|
+
.replaceAll('&', '&');
|
|
38
|
+
return sanitizeExecutableName(decoded);
|
|
39
|
+
}
|
|
40
|
+
function readBundleExecutable(infoPlistPath) {
|
|
41
|
+
const pl = spawnSync('plutil', ['-extract', 'CFBundleExecutable', 'raw', '-o', '-', '--', resolve(infoPlistPath)], {
|
|
42
|
+
encoding: 'utf8',
|
|
43
|
+
});
|
|
44
|
+
if (pl.status === 0) {
|
|
45
|
+
const exe = sanitizeExecutableName(pl.stdout ?? '');
|
|
46
|
+
if (exe)
|
|
47
|
+
return exe;
|
|
48
|
+
}
|
|
49
|
+
return parseXmlBundleExecutable(infoPlistPath);
|
|
50
|
+
}
|
|
51
|
+
function findAppBundlePath(spec, searchDirs) {
|
|
52
|
+
const trimmed = spec.trim();
|
|
53
|
+
if (!trimmed)
|
|
54
|
+
return null;
|
|
55
|
+
const direct = trimmed.endsWith('.app') ? trimmed : `${trimmed}.app`;
|
|
56
|
+
if (trimmed.includes('/') || trimmed.startsWith('~')) {
|
|
57
|
+
const expanded = trimmed.startsWith('~/') ? join(homedir(), trimmed.slice(2)) : trimmed;
|
|
58
|
+
const candidate = expanded.endsWith('.app') ? expanded : `${expanded}.app`;
|
|
59
|
+
return existsSync(join(candidate, 'Contents/Info.plist')) ? candidate : null;
|
|
60
|
+
}
|
|
61
|
+
const targetLower = direct.toLowerCase();
|
|
62
|
+
const bareLower = trimmed.toLowerCase();
|
|
63
|
+
for (const dir of searchDirs) {
|
|
64
|
+
try {
|
|
65
|
+
const entries = readdirSync(dir);
|
|
66
|
+
const matched = entries.find((entry) => {
|
|
67
|
+
if (!entry.toLowerCase().endsWith('.app'))
|
|
68
|
+
return false;
|
|
69
|
+
const lower = entry.toLowerCase();
|
|
70
|
+
return lower === targetLower || lower.slice(0, -4) === bareLower;
|
|
71
|
+
});
|
|
72
|
+
if (matched) {
|
|
73
|
+
const resolved = join(dir, matched);
|
|
74
|
+
if (existsSync(join(resolved, 'Contents/Info.plist')))
|
|
75
|
+
return resolved;
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
catch {
|
|
79
|
+
const exact = join(dir, direct);
|
|
80
|
+
if (existsSync(join(exact, 'Contents/Info.plist')))
|
|
81
|
+
return exact;
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
return null;
|
|
85
|
+
}
|
|
86
|
+
/** Resolve an installed macOS `.app` bundle by app name or `.app` path. */
|
|
87
|
+
export function resolveMacAppBundle(spec, searchDirs = DEFAULT_APP_SEARCH_DIRS) {
|
|
88
|
+
const appPath = findAppBundlePath(spec, searchDirs);
|
|
89
|
+
if (!appPath)
|
|
90
|
+
return null;
|
|
91
|
+
const infoPlistPath = join(appPath, 'Contents/Info.plist');
|
|
92
|
+
const exeName = readBundleExecutable(infoPlistPath);
|
|
93
|
+
if (!exeName)
|
|
94
|
+
return null;
|
|
95
|
+
const executablePath = join(appPath, 'Contents/MacOS', exeName);
|
|
96
|
+
if (!existsSync(executablePath))
|
|
97
|
+
return null;
|
|
98
|
+
const isElectron = existsSync(join(appPath, 'Contents/Frameworks/Electron Framework.framework')) ||
|
|
99
|
+
existsSync(join(appPath, 'Contents/Resources/app.asar')) ||
|
|
100
|
+
existsSync(join(appPath, 'Contents/Resources/app.asar.unpacked')) ||
|
|
101
|
+
existsSync(join(appPath, 'Contents/Frameworks/Codex Framework.framework'));
|
|
102
|
+
const appName = basename(appPath).replace(/\.app$/i, '');
|
|
103
|
+
return { appPath, executablePath, appName, isElectron };
|
|
104
|
+
}
|
|
105
|
+
/** Build argv to launch a resolved macOS desktop app behind `fiche warp`. */
|
|
106
|
+
export function buildWarpAppArgs(app, proxyUrl, extraArgs = [], opts) {
|
|
107
|
+
if (app.isElectron) {
|
|
108
|
+
const args = [app.executablePath, `--proxy-server=${proxyUrl}`];
|
|
109
|
+
if (opts?.proxyBypassList) {
|
|
110
|
+
args.push(`--proxy-bypass-list=${opts.proxyBypassList}`);
|
|
111
|
+
}
|
|
112
|
+
if (opts?.spkiPins && opts.spkiPins.length > 0) {
|
|
113
|
+
args.push(`--ignore-certificate-errors-spki-list=${opts.spkiPins.join(',')}`);
|
|
114
|
+
}
|
|
115
|
+
args.push(...extraArgs);
|
|
116
|
+
return args;
|
|
117
|
+
}
|
|
118
|
+
return [app.executablePath, ...extraArgs];
|
|
119
|
+
}
|
|
120
|
+
const CLI_WRAPPERS = ['claude', 'codex', 'ribhu', 'kimi', 'agy', 'gemini', 'opencode', 'cursor-agent', 'amp', 'pi', 'aider'];
|
|
121
|
+
/** Render POSIX zsh/bash shell helpers (or transparent wrappers when `--wrap` is set). */
|
|
122
|
+
export function renderShellInitScript(opts = {}) {
|
|
123
|
+
const bin = opts.ficheBin?.trim() || 'fiche';
|
|
124
|
+
const safeBin = `'${bin.replaceAll("'", `'\\''`)}'`;
|
|
125
|
+
const lines = [
|
|
126
|
+
'# Added by `fiche shell-init` — route coding agent CLIs & macOS apps via local Fiche proxy.',
|
|
127
|
+
`export FICHE_BIN=${safeBin}`,
|
|
128
|
+
'fiche-app() { if [ "$#" -eq 0 ]; then "$FICHE_BIN" warp --app; else local app="$1"; shift; "$FICHE_BIN" warp --app "$app" -- "$@"; fi; }',
|
|
129
|
+
'fclaude() { "$FICHE_BIN" warp -- claude "$@"; }',
|
|
130
|
+
'fcodex() { "$FICHE_BIN" warp -- codex "$@"; }',
|
|
131
|
+
'fribhu() { "$FICHE_BIN" warp -- ribhu "$@"; }',
|
|
132
|
+
'fkimi() { "$FICHE_BIN" warp -- kimi "$@"; }',
|
|
133
|
+
'fagy() { "$FICHE_BIN" warp -- agy "$@"; }',
|
|
134
|
+
'fgemini() { "$FICHE_BIN" warp -- gemini "$@"; }',
|
|
135
|
+
'fopencode() { "$FICHE_BIN" warp -- opencode "$@"; }',
|
|
136
|
+
'fcursor() { "$FICHE_BIN" warp -- cursor-agent "$@"; }',
|
|
137
|
+
'famp() { "$FICHE_BIN" warp -- amp "$@"; }',
|
|
138
|
+
'fpi() { "$FICHE_BIN" warp -- pi "$@"; }',
|
|
139
|
+
'faider() { "$FICHE_BIN" warp -- aider "$@"; }',
|
|
140
|
+
];
|
|
141
|
+
if (opts.wrap) {
|
|
142
|
+
lines.push('');
|
|
143
|
+
lines.push('# Transparent CLI wrappers (set FICHE_BYPASS=1 to skip proxy for one invocation)');
|
|
144
|
+
for (const cli of CLI_WRAPPERS) {
|
|
145
|
+
if (cli === 'codex') {
|
|
146
|
+
lines.push('function codex { if [ "${FICHE_BYPASS:-0}" = "1" ]; then command codex "$@"; elif [ "${FICHE_WARP_ACTIVE:-0}" = "1" ] || ! command -v "$FICHE_BIN" >/dev/null 2>&1; then case "${FICHE_CODEX_KEEP_DAEMON:-}" in 1|true|TRUE|yes|YES|on|ON) command codex "$@"; return ;; esac; case "${1:-}" in app-server|remote-control|completion|update|help|--help|-h|--version|-V) command codex "$@"; return ;; esac; local _arg _has_daemon=0; for _arg in "$@"; do case "$_arg" in *daemon_auto_start*) _has_daemon=1; break ;; esac; done; if [ "$_has_daemon" -eq 1 ]; then command codex "$@"; else command codex -c features.daemon_auto_start=false "$@"; fi; else "$FICHE_BIN" warp -- codex "$@"; fi; }');
|
|
147
|
+
}
|
|
148
|
+
else {
|
|
149
|
+
lines.push(`function ${cli} { if [ "\${FICHE_BYPASS:-0}" = "1" ] || [ "\${FICHE_WARP_ACTIVE:-0}" = "1" ] || ! command -v "$FICHE_BIN" >/dev/null 2>&1; then command ${cli} "$@"; else "$FICHE_BIN" warp -- ${cli} "$@"; fi; }`);
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
return `${lines.join('\n')}\n`;
|
|
154
|
+
}
|
|
155
|
+
//# sourceMappingURL=app-launch.js.map
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* warp's local certificate authority.
|
|
3
|
+
*
|
|
4
|
+
* On first use it generates a self-signed P-256 root, persists it under
|
|
5
|
+
* ~/.inkling, and mints leaf certs per SNI host on demand so the CONNECT proxy
|
|
6
|
+
* can terminate (and therefore route) the agent's TLS. Only the child process
|
|
7
|
+
* trusts it: warp points the child's NODE_EXTRA_CA_CERTS at the root, so
|
|
8
|
+
* nothing is installed in the system keychain and no other process on the
|
|
9
|
+
* machine is affected.
|
|
10
|
+
*
|
|
11
|
+
* Ported from wardex ca.go. The certificate assembly is hand-rolled because
|
|
12
|
+
* Node has no equivalent of Go's x509.CreateCertificate — see ./der.ts.
|
|
13
|
+
*/
|
|
14
|
+
import { type SecureContext } from 'node:tls';
|
|
15
|
+
export declare function findSystemRootBundle(candidates?: readonly string[]): string | null;
|
|
16
|
+
export declare const OS_STORE = "the OS certificate store";
|
|
17
|
+
/**
|
|
18
|
+
* Windows keeps its roots in the certificate store, not in a file, so none of
|
|
19
|
+
* the paths above exist there. Node 22.15+/23.10+ can export that store as PEM;
|
|
20
|
+
* on older runtimes this returns '' and the bundle stays CA-only as before.
|
|
21
|
+
*/
|
|
22
|
+
export declare function osStoreRoots(): string;
|
|
23
|
+
/** The public roots to append to our CA, and where they came from (null: none). */
|
|
24
|
+
export declare function readSystemRoots(candidates?: readonly string[], osStore?: () => string): {
|
|
25
|
+
pem: string;
|
|
26
|
+
source: string | null;
|
|
27
|
+
};
|
|
28
|
+
export declare class CertificateAuthority {
|
|
29
|
+
private readonly certPem;
|
|
30
|
+
private readonly caKey;
|
|
31
|
+
private readonly caSki;
|
|
32
|
+
private readonly leafKey;
|
|
33
|
+
private readonly leafKeyPem;
|
|
34
|
+
readonly certPath: string;
|
|
35
|
+
/** Our CA followed by the system roots; see {@link writeBundle}. */
|
|
36
|
+
readonly bundlePath: string;
|
|
37
|
+
/** Where the roots came from (a file path or {@link OS_STORE}); null when `bundlePath` is CA-only. */
|
|
38
|
+
readonly systemRootsPath: string | null;
|
|
39
|
+
readonly spkiPin: string;
|
|
40
|
+
private readonly leaves;
|
|
41
|
+
private readonly leafSki;
|
|
42
|
+
readonly spkiPins: readonly string[];
|
|
43
|
+
private constructor();
|
|
44
|
+
/**
|
|
45
|
+
* Write `warp-ca-bundle.pem` = our CA + the system roots, for the env vars
|
|
46
|
+
* that replace the trust store. Regenerated on every load: the system bundle
|
|
47
|
+
* rotates underneath us and the cost is one file write.
|
|
48
|
+
*/
|
|
49
|
+
private static writeBundle;
|
|
50
|
+
/**
|
|
51
|
+
* Load the persisted CA, or create and persist one. A CA that fails to load,
|
|
52
|
+
* lacks modern strict-X509 extensions (SKI), mismatches its key, or has expired
|
|
53
|
+
* is replaced rather than reported: it is entirely derived state.
|
|
54
|
+
*/
|
|
55
|
+
static loadOrCreate(dir: string): CertificateAuthority;
|
|
56
|
+
/** Mint a leaf X.509 PEM certificate signed by this CA for `host`. */
|
|
57
|
+
mintLeafCertPem(host: string): string;
|
|
58
|
+
/**
|
|
59
|
+
* Mint PEM `{ key, cert }` credentials for `host` (root included for full chain validation).
|
|
60
|
+
* Useful both for SNI contexts and TLS servers bound to IP literals where clients omit SNI.
|
|
61
|
+
*/
|
|
62
|
+
leafCredentialsFor(host: string): {
|
|
63
|
+
key: string;
|
|
64
|
+
cert: string;
|
|
65
|
+
};
|
|
66
|
+
/**
|
|
67
|
+
* Cached-or-minted TLS context for an SNI host. One leaf key is reused across
|
|
68
|
+
* every host: these certs never leave the machine and are only trusted by the
|
|
69
|
+
* child we spawned, so per-host keygen would buy nothing but latency on the
|
|
70
|
+
* first request to each host.
|
|
71
|
+
*/
|
|
72
|
+
secureContextFor(host: string): SecureContext;
|
|
73
|
+
}
|
|
74
|
+
//# sourceMappingURL=ca.d.ts.map
|
package/dist/warp/ca.js
ADDED
|
@@ -0,0 +1,416 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* warp's local certificate authority.
|
|
3
|
+
*
|
|
4
|
+
* On first use it generates a self-signed P-256 root, persists it under
|
|
5
|
+
* ~/.inkling, and mints leaf certs per SNI host on demand so the CONNECT proxy
|
|
6
|
+
* can terminate (and therefore route) the agent's TLS. Only the child process
|
|
7
|
+
* trusts it: warp points the child's NODE_EXTRA_CA_CERTS at the root, so
|
|
8
|
+
* nothing is installed in the system keychain and no other process on the
|
|
9
|
+
* machine is affected.
|
|
10
|
+
*
|
|
11
|
+
* Ported from wardex ca.go. The certificate assembly is hand-rolled because
|
|
12
|
+
* Node has no equivalent of Go's x509.CreateCertificate — see ./der.ts.
|
|
13
|
+
*/
|
|
14
|
+
import { createHash, createPrivateKey, createPublicKey, generateKeyPairSync, randomBytes, sign, X509Certificate, } from 'node:crypto';
|
|
15
|
+
import * as tls from 'node:tls';
|
|
16
|
+
import { createSecureContext } from 'node:tls';
|
|
17
|
+
import { isIP } from 'node:net';
|
|
18
|
+
import { chmodSync, existsSync, mkdirSync, readFileSync, renameSync, unlinkSync, writeFileSync } from 'node:fs';
|
|
19
|
+
import { join } from 'node:path';
|
|
20
|
+
import { bitString, bool, contextTag, integer, octetString, oid, pem, seq, set, utcTime, utf8String, } from './der.js';
|
|
21
|
+
const textEncoder = new TextEncoder();
|
|
22
|
+
const OID_ECDSA_SHA256 = '1.2.840.10045.4.3.2';
|
|
23
|
+
const OID_COMMON_NAME = '2.5.4.3';
|
|
24
|
+
const OID_ORGANIZATION = '2.5.4.10';
|
|
25
|
+
const OID_SUBJECT_KEY_IDENTIFIER = '2.5.29.14';
|
|
26
|
+
const OID_KEY_USAGE = '2.5.29.15';
|
|
27
|
+
const OID_SUBJECT_ALT_NAME = '2.5.29.17';
|
|
28
|
+
const OID_BASIC_CONSTRAINTS = '2.5.29.19';
|
|
29
|
+
const OID_AUTHORITY_KEY_IDENTIFIER = '2.5.29.35';
|
|
30
|
+
const OID_EXT_KEY_USAGE = '2.5.29.37';
|
|
31
|
+
const OID_SERVER_AUTH = '1.3.6.1.5.5.7.3.1';
|
|
32
|
+
/** DER encoding of OID 2.5.29.14 (subjectKeyIdentifier) used to detect legacy CAs missing SKI. */
|
|
33
|
+
const SKI_OID_DER = Buffer.from([0x06, 0x03, 0x55, 0x1d, 0x0e]);
|
|
34
|
+
const MAX_LEAF_CONTEXTS = 256;
|
|
35
|
+
const CA_COMMON_NAME = 'inkling warp local CA';
|
|
36
|
+
const CA_ORGANIZATION = 'inkling';
|
|
37
|
+
/** ecdsa-with-SHA256 takes no parameters, so the AlgorithmIdentifier is bare. */
|
|
38
|
+
const SIG_ALGORITHM = seq(oid(OID_ECDSA_SHA256));
|
|
39
|
+
function distinguishedName(commonName, organization) {
|
|
40
|
+
const rdns = [set(seq(oid(OID_COMMON_NAME), utf8String(commonName)))];
|
|
41
|
+
if (organization)
|
|
42
|
+
rdns.push(set(seq(oid(OID_ORGANIZATION), utf8String(organization))));
|
|
43
|
+
return seq(...rdns);
|
|
44
|
+
}
|
|
45
|
+
function extension(id, critical, value) {
|
|
46
|
+
const parts = [oid(id)];
|
|
47
|
+
if (critical)
|
|
48
|
+
parts.push(bool(true));
|
|
49
|
+
parts.push(octetString(value));
|
|
50
|
+
return seq(...parts);
|
|
51
|
+
}
|
|
52
|
+
/**
|
|
53
|
+
* KeyUsage is a BIT STRING indexed from the most significant bit:
|
|
54
|
+
* digitalSignature(0), keyCertSign(5), cRLSign(6). The trailing count of unused
|
|
55
|
+
* bits has to match the last bit we actually set or strict verifiers complain.
|
|
56
|
+
*/
|
|
57
|
+
function keyUsageExtension(bits) {
|
|
58
|
+
const highest = Math.max(...bits);
|
|
59
|
+
const byteCount = Math.floor(highest / 8) + 1;
|
|
60
|
+
const bytes = new Uint8Array(byteCount);
|
|
61
|
+
for (const bit of bits)
|
|
62
|
+
bytes[Math.floor(bit / 8)] |= 0x80 >> bit % 8;
|
|
63
|
+
const unused = byteCount * 8 - (highest + 1);
|
|
64
|
+
return extension(OID_KEY_USAGE, true, bitString(bytes, unused));
|
|
65
|
+
}
|
|
66
|
+
/** GeneralName: dNSName is [2] IMPLICIT IA5String, iPAddress is [7] OCTET STRING. */
|
|
67
|
+
function subjectAltNameExtension(host, critical = false) {
|
|
68
|
+
if (isIP(host)) {
|
|
69
|
+
const octets = isIP(host) === 4
|
|
70
|
+
? Uint8Array.from(host.split('.').map((o) => Number.parseInt(o, 10)))
|
|
71
|
+
: ipv6Bytes(host);
|
|
72
|
+
return extension(OID_SUBJECT_ALT_NAME, critical, seq(contextTag(7, octets, false)));
|
|
73
|
+
}
|
|
74
|
+
// [2] IMPLICIT IA5String requires 7-bit ASCII characters.
|
|
75
|
+
if (/[^\x20-\x7e]/.test(host)) {
|
|
76
|
+
throw new Error(`Invalid non-ASCII DNS SAN host: ${host}`);
|
|
77
|
+
}
|
|
78
|
+
// Re-encode content rather than slicing header off ia5String() so >127-char hosts encode cleanly.
|
|
79
|
+
return extension(OID_SUBJECT_ALT_NAME, critical, seq(contextTag(2, textEncoder.encode(host), false)));
|
|
80
|
+
}
|
|
81
|
+
function readDerTlv(buf, offset) {
|
|
82
|
+
const tag = buf[offset];
|
|
83
|
+
const lenByte = buf[offset + 1];
|
|
84
|
+
let len = 0;
|
|
85
|
+
let contentStart = offset + 2;
|
|
86
|
+
if (lenByte < 0x80) {
|
|
87
|
+
len = lenByte;
|
|
88
|
+
}
|
|
89
|
+
else {
|
|
90
|
+
const count = lenByte & 0x7f;
|
|
91
|
+
for (let i = 0; i < count; i++) {
|
|
92
|
+
len = len * 256 + buf[offset + 2 + i];
|
|
93
|
+
}
|
|
94
|
+
contentStart = offset + 2 + count;
|
|
95
|
+
}
|
|
96
|
+
const contentEnd = contentStart + len;
|
|
97
|
+
return { tag, contentStart, contentEnd, next: contentEnd };
|
|
98
|
+
}
|
|
99
|
+
/** RFC 5280 §4.2.1.2 Method 1: 160-bit SHA-1 of the BIT STRING subjectPublicKey value (without unused-bits byte). */
|
|
100
|
+
function subjectKeyIdentifier(pubKey) {
|
|
101
|
+
const spki = new Uint8Array(pubKey.export({ type: 'spki', format: 'der' }));
|
|
102
|
+
const outer = readDerTlv(spki, 0);
|
|
103
|
+
const alg = readDerTlv(spki, outer.contentStart);
|
|
104
|
+
const bitStr = readDerTlv(spki, alg.next);
|
|
105
|
+
const rawKey = spki.subarray(bitStr.contentStart + 1, bitStr.contentEnd);
|
|
106
|
+
return new Uint8Array(createHash('sha1').update(rawKey).digest());
|
|
107
|
+
}
|
|
108
|
+
function spkiSha256Base64(pubKey) {
|
|
109
|
+
const spki = pubKey.export({ type: 'spki', format: 'der' });
|
|
110
|
+
return createHash('sha256').update(spki).digest('base64');
|
|
111
|
+
}
|
|
112
|
+
function writeFileAtomic(filePath, content, mode) {
|
|
113
|
+
const tmp = `${filePath}.tmp.${process.pid}.${randomBytes(4).toString('hex')}`;
|
|
114
|
+
try {
|
|
115
|
+
writeFileSync(tmp, content, { mode });
|
|
116
|
+
chmodSync(tmp, mode);
|
|
117
|
+
renameSync(tmp, filePath);
|
|
118
|
+
chmodSync(filePath, mode);
|
|
119
|
+
}
|
|
120
|
+
catch (err) {
|
|
121
|
+
try {
|
|
122
|
+
unlinkSync(tmp);
|
|
123
|
+
}
|
|
124
|
+
catch {
|
|
125
|
+
/* ignore cleanup error */
|
|
126
|
+
}
|
|
127
|
+
throw err;
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
function ipv6Bytes(host) {
|
|
131
|
+
const cleanHost = host.split('%')[0] ?? host;
|
|
132
|
+
const lastColon = cleanHost.lastIndexOf(':');
|
|
133
|
+
let normalized = cleanHost;
|
|
134
|
+
if (lastColon >= 0 && cleanHost.slice(lastColon + 1).includes('.')) {
|
|
135
|
+
const octets = cleanHost.slice(lastColon + 1).split('.').map((o) => Number.parseInt(o, 10));
|
|
136
|
+
if (octets.length === 4 && octets.every((n) => Number.isInteger(n) && n >= 0 && n <= 255)) {
|
|
137
|
+
const hi = ((octets[0] << 8) | octets[1]).toString(16);
|
|
138
|
+
const lo = ((octets[2] << 8) | octets[3]).toString(16);
|
|
139
|
+
normalized = `${cleanHost.slice(0, lastColon + 1)}${hi}:${lo}`;
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
const [head, tail] = normalized.split('::');
|
|
143
|
+
const parse = (part) => (part ? part.split(':').filter(Boolean) : []);
|
|
144
|
+
const left = parse(head ?? '');
|
|
145
|
+
const right = parse(tail ?? '');
|
|
146
|
+
const groups = tail === undefined
|
|
147
|
+
? left
|
|
148
|
+
: [...left, ...Array(Math.max(0, 8 - left.length - right.length)).fill('0'), ...right];
|
|
149
|
+
const out = new Uint8Array(16);
|
|
150
|
+
groups.forEach((group, i) => {
|
|
151
|
+
if (i >= 8)
|
|
152
|
+
return;
|
|
153
|
+
const v = Number.parseInt(group, 16);
|
|
154
|
+
out[i * 2] = (v >> 8) & 0xff;
|
|
155
|
+
out[i * 2 + 1] = v & 0xff;
|
|
156
|
+
});
|
|
157
|
+
return out;
|
|
158
|
+
}
|
|
159
|
+
/**
|
|
160
|
+
* Assemble and self-sign a TBSCertificate. The SubjectPublicKeyInfo comes
|
|
161
|
+
* straight out of node:crypto's SPKI export, so we never hand-encode a curve
|
|
162
|
+
* point; everything else is RFC 5280 boilerplate.
|
|
163
|
+
*/
|
|
164
|
+
function buildCertificate(spec) {
|
|
165
|
+
const spki = new Uint8Array(spec.subjectPublicKey.export({ type: 'spki', format: 'der' }));
|
|
166
|
+
const tbs = seq(contextTag(0, integer(2)), // v3
|
|
167
|
+
integer(new Uint8Array(randomBytes(16))), SIG_ALGORITHM, spec.issuer, seq(utcTime(spec.notBefore), utcTime(spec.notAfter)), spec.subject, spki, contextTag(3, seq(...spec.extensions)));
|
|
168
|
+
const signature = new Uint8Array(sign('sha256', tbs, spec.signingKey));
|
|
169
|
+
return seq(tbs, SIG_ALGORITHM, bitString(signature));
|
|
170
|
+
}
|
|
171
|
+
function newKeyPair() {
|
|
172
|
+
return generateKeyPairSync('ec', { namedCurve: 'prime256v1' });
|
|
173
|
+
}
|
|
174
|
+
function privateKeyPem(key) {
|
|
175
|
+
return key.export({ type: 'pkcs8', format: 'pem' }).toString();
|
|
176
|
+
}
|
|
177
|
+
/**
|
|
178
|
+
* Where the OS keeps its public root bundle. `SSL_CERT_FILE`,
|
|
179
|
+
* `CURL_CA_BUNDLE` and `REQUESTS_CA_BUNDLE` REPLACE the trust store rather
|
|
180
|
+
* than extend it, so a file holding only our CA would make every non-inkling
|
|
181
|
+
* HTTPS call in the child fail verification (gcloud, gws, pip: #245). The
|
|
182
|
+
* first path that exists wins; none found falls back to {@link osStoreRoots}.
|
|
183
|
+
*/
|
|
184
|
+
const SYSTEM_ROOT_BUNDLES = [
|
|
185
|
+
'/etc/ssl/cert.pem', // macOS, Alpine, FreeBSD
|
|
186
|
+
'/etc/ssl/certs/ca-certificates.crt', // Debian, Ubuntu, Arch
|
|
187
|
+
'/etc/pki/tls/certs/ca-bundle.crt', // RHEL, Fedora, CentOS
|
|
188
|
+
'/etc/ssl/ca-bundle.pem', // openSUSE
|
|
189
|
+
];
|
|
190
|
+
export function findSystemRootBundle(candidates = SYSTEM_ROOT_BUNDLES) {
|
|
191
|
+
const fromEnv = process.env.SSL_CERT_FILE;
|
|
192
|
+
// An operator-supplied bundle is the trust store the child would have had
|
|
193
|
+
// without us; prefer it over the platform guess. Skip it if it is already
|
|
194
|
+
// one of our own files, or the bundle would nest on every warp restart.
|
|
195
|
+
if (fromEnv && existsSync(fromEnv) && !/warp-ca(-bundle)?\.pem$/.test(fromEnv))
|
|
196
|
+
return fromEnv;
|
|
197
|
+
for (const p of candidates)
|
|
198
|
+
if (existsSync(p))
|
|
199
|
+
return p;
|
|
200
|
+
return null;
|
|
201
|
+
}
|
|
202
|
+
export const OS_STORE = 'the OS certificate store';
|
|
203
|
+
/**
|
|
204
|
+
* Windows keeps its roots in the certificate store, not in a file, so none of
|
|
205
|
+
* the paths above exist there. Node 22.15+/23.10+ can export that store as PEM;
|
|
206
|
+
* on older runtimes this returns '' and the bundle stays CA-only as before.
|
|
207
|
+
*/
|
|
208
|
+
export function osStoreRoots() {
|
|
209
|
+
const get = tls.getCACertificates;
|
|
210
|
+
try {
|
|
211
|
+
return get ? get('system').join('\n') : '';
|
|
212
|
+
}
|
|
213
|
+
catch {
|
|
214
|
+
return '';
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
/** The public roots to append to our CA, and where they came from (null: none). */
|
|
218
|
+
export function readSystemRoots(candidates = SYSTEM_ROOT_BUNDLES, osStore = osStoreRoots) {
|
|
219
|
+
const path = findSystemRootBundle(candidates);
|
|
220
|
+
if (path) {
|
|
221
|
+
try {
|
|
222
|
+
const pem = readFileSync(path, 'utf8');
|
|
223
|
+
if (pem)
|
|
224
|
+
return { pem, source: path };
|
|
225
|
+
}
|
|
226
|
+
catch {
|
|
227
|
+
/* unreadable: try the OS store */
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
const pem = osStore();
|
|
231
|
+
return pem ? { pem, source: OS_STORE } : { pem: '', source: null };
|
|
232
|
+
}
|
|
233
|
+
export class CertificateAuthority {
|
|
234
|
+
certPem;
|
|
235
|
+
caKey;
|
|
236
|
+
caSki;
|
|
237
|
+
leafKey;
|
|
238
|
+
leafKeyPem;
|
|
239
|
+
certPath;
|
|
240
|
+
bundlePath;
|
|
241
|
+
systemRootsPath;
|
|
242
|
+
spkiPin;
|
|
243
|
+
leaves = new Map();
|
|
244
|
+
leafSki;
|
|
245
|
+
spkiPins;
|
|
246
|
+
constructor(certPem, caKey, caSki, leafKey, leafKeyPem, certPath,
|
|
247
|
+
/** Our CA followed by the system roots; see {@link writeBundle}. */
|
|
248
|
+
bundlePath,
|
|
249
|
+
/** Where the roots came from (a file path or {@link OS_STORE}); null when `bundlePath` is CA-only. */
|
|
250
|
+
systemRootsPath, spkiPin) {
|
|
251
|
+
this.certPem = certPem;
|
|
252
|
+
this.caKey = caKey;
|
|
253
|
+
this.caSki = caSki;
|
|
254
|
+
this.leafKey = leafKey;
|
|
255
|
+
this.leafKeyPem = leafKeyPem;
|
|
256
|
+
this.certPath = certPath;
|
|
257
|
+
this.bundlePath = bundlePath;
|
|
258
|
+
this.systemRootsPath = systemRootsPath;
|
|
259
|
+
this.spkiPin = spkiPin;
|
|
260
|
+
this.leafSki = subjectKeyIdentifier(leafKey);
|
|
261
|
+
this.spkiPins = [spkiSha256Base64(leafKey), spkiPin];
|
|
262
|
+
}
|
|
263
|
+
/**
|
|
264
|
+
* Write `warp-ca-bundle.pem` = our CA + the system roots, for the env vars
|
|
265
|
+
* that replace the trust store. Regenerated on every load: the system bundle
|
|
266
|
+
* rotates underneath us and the cost is one file write.
|
|
267
|
+
*/
|
|
268
|
+
static writeBundle(dir, certPem) {
|
|
269
|
+
const bundlePath = join(dir, 'warp-ca-bundle.pem');
|
|
270
|
+
const { pem: roots, source } = readSystemRoots();
|
|
271
|
+
const sep = roots && !roots.endsWith('\n') ? '\n' : '';
|
|
272
|
+
writeFileAtomic(bundlePath, certPem + roots + sep, 0o600);
|
|
273
|
+
return { bundlePath, systemRootsPath: source };
|
|
274
|
+
}
|
|
275
|
+
/**
|
|
276
|
+
* Load the persisted CA, or create and persist one. A CA that fails to load,
|
|
277
|
+
* lacks modern strict-X509 extensions (SKI), mismatches its key, or has expired
|
|
278
|
+
* is replaced rather than reported: it is entirely derived state.
|
|
279
|
+
*/
|
|
280
|
+
static loadOrCreate(dir) {
|
|
281
|
+
mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
282
|
+
try {
|
|
283
|
+
chmodSync(dir, 0o700);
|
|
284
|
+
}
|
|
285
|
+
catch {
|
|
286
|
+
/* ignore */
|
|
287
|
+
}
|
|
288
|
+
const certPath = join(dir, 'warp-ca.pem');
|
|
289
|
+
const keyPath = join(dir, 'warp-ca-key.pem');
|
|
290
|
+
try {
|
|
291
|
+
const certPem = readFileSync(certPath, 'utf8');
|
|
292
|
+
const keyPem = readFileSync(keyPath, 'utf8');
|
|
293
|
+
const parsed = new X509Certificate(certPem);
|
|
294
|
+
const caKey = createPrivateKey(keyPem);
|
|
295
|
+
const caPubFromKey = createPublicKey(caKey).export({ type: 'spki', format: 'der' });
|
|
296
|
+
const caPubFromCert = parsed.publicKey.export({ type: 'spki', format: 'der' });
|
|
297
|
+
const hasSki = parsed.raw.includes(SKI_OID_DER);
|
|
298
|
+
const now = Date.now();
|
|
299
|
+
const validFrom = new Date(parsed.validFrom).getTime();
|
|
300
|
+
const validTo = new Date(parsed.validTo).getTime();
|
|
301
|
+
if (parsed.ca === true &&
|
|
302
|
+
validFrom <= now &&
|
|
303
|
+
validTo > now + 365 * 24 * 60 * 60 * 1000 &&
|
|
304
|
+
hasSki &&
|
|
305
|
+
Buffer.from(caPubFromKey).equals(Buffer.from(caPubFromCert))) {
|
|
306
|
+
try {
|
|
307
|
+
chmodSync(keyPath, 0o600);
|
|
308
|
+
chmodSync(certPath, 0o600);
|
|
309
|
+
}
|
|
310
|
+
catch {
|
|
311
|
+
/* ignore */
|
|
312
|
+
}
|
|
313
|
+
const caSki = subjectKeyIdentifier(parsed.publicKey);
|
|
314
|
+
const spkiPin = spkiSha256Base64(parsed.publicKey);
|
|
315
|
+
const leaf = newKeyPair();
|
|
316
|
+
const bundle = CertificateAuthority.writeBundle(dir, certPem);
|
|
317
|
+
return new CertificateAuthority(certPem, caKey, caSki, leaf.publicKey, privateKeyPem(leaf.privateKey), certPath, bundle.bundlePath, bundle.systemRootsPath, spkiPin);
|
|
318
|
+
}
|
|
319
|
+
}
|
|
320
|
+
catch {
|
|
321
|
+
// fall through and mint a fresh CA
|
|
322
|
+
}
|
|
323
|
+
const ca = newKeyPair();
|
|
324
|
+
const name = distinguishedName(CA_COMMON_NAME, CA_ORGANIZATION);
|
|
325
|
+
const caSki = subjectKeyIdentifier(ca.publicKey);
|
|
326
|
+
const spkiPin = spkiSha256Base64(ca.publicKey);
|
|
327
|
+
const now = Date.now();
|
|
328
|
+
const der = buildCertificate({
|
|
329
|
+
subject: name,
|
|
330
|
+
issuer: name,
|
|
331
|
+
subjectPublicKey: ca.publicKey,
|
|
332
|
+
signingKey: ca.privateKey,
|
|
333
|
+
notBefore: new Date(now - 60 * 60 * 1000),
|
|
334
|
+
notAfter: new Date(now + 10 * 365 * 24 * 60 * 60 * 1000),
|
|
335
|
+
extensions: [
|
|
336
|
+
// pathLen 0: this root may sign leaves, never intermediates.
|
|
337
|
+
extension(OID_BASIC_CONSTRAINTS, true, seq(bool(true), integer(0))),
|
|
338
|
+
keyUsageExtension([0, 5, 6]),
|
|
339
|
+
extension(OID_SUBJECT_KEY_IDENTIFIER, false, octetString(caSki)),
|
|
340
|
+
extension(OID_AUTHORITY_KEY_IDENTIFIER, false, seq(contextTag(0, caSki, false))),
|
|
341
|
+
],
|
|
342
|
+
});
|
|
343
|
+
const certPem = pem('CERTIFICATE', der);
|
|
344
|
+
// Write private key first so readers never observe a new cert paired with a stale key.
|
|
345
|
+
writeFileAtomic(keyPath, privateKeyPem(ca.privateKey), 0o600);
|
|
346
|
+
writeFileAtomic(certPath, certPem, 0o600);
|
|
347
|
+
const leaf = newKeyPair();
|
|
348
|
+
const bundle = CertificateAuthority.writeBundle(dir, certPem);
|
|
349
|
+
return new CertificateAuthority(certPem, ca.privateKey, caSki, leaf.publicKey, privateKeyPem(leaf.privateKey), certPath, bundle.bundlePath, bundle.systemRootsPath, spkiPin);
|
|
350
|
+
}
|
|
351
|
+
/** Mint a leaf X.509 PEM certificate signed by this CA for `host`. */
|
|
352
|
+
mintLeafCertPem(host) {
|
|
353
|
+
const stripped = host.replace(/\.$/, '');
|
|
354
|
+
const name = isIP(stripped) ? stripped : stripped.toLowerCase();
|
|
355
|
+
const now = Date.now();
|
|
356
|
+
// RFC 5280 caps CommonName at 64 chars; for long hosts use an empty Subject DN + critical SAN.
|
|
357
|
+
const subject = name.length > 64 ? seq() : distinguishedName(name);
|
|
358
|
+
const sanCritical = name.length > 64;
|
|
359
|
+
const der = buildCertificate({
|
|
360
|
+
subject,
|
|
361
|
+
issuer: distinguishedName(CA_COMMON_NAME, CA_ORGANIZATION),
|
|
362
|
+
subjectPublicKey: this.leafKey,
|
|
363
|
+
signingKey: this.caKey,
|
|
364
|
+
notBefore: new Date(now - 60 * 60 * 1000),
|
|
365
|
+
notAfter: new Date(now + 365 * 24 * 60 * 60 * 1000),
|
|
366
|
+
extensions: [
|
|
367
|
+
extension(OID_BASIC_CONSTRAINTS, true, seq()),
|
|
368
|
+
keyUsageExtension([0]),
|
|
369
|
+
extension(OID_EXT_KEY_USAGE, false, seq(oid(OID_SERVER_AUTH))),
|
|
370
|
+
subjectAltNameExtension(name, sanCritical),
|
|
371
|
+
extension(OID_SUBJECT_KEY_IDENTIFIER, false, octetString(this.leafSki)),
|
|
372
|
+
extension(OID_AUTHORITY_KEY_IDENTIFIER, false, seq(contextTag(0, this.caSki, false))),
|
|
373
|
+
],
|
|
374
|
+
});
|
|
375
|
+
return pem('CERTIFICATE', der);
|
|
376
|
+
}
|
|
377
|
+
/**
|
|
378
|
+
* Mint PEM `{ key, cert }` credentials for `host` (root included for full chain validation).
|
|
379
|
+
* Useful both for SNI contexts and TLS servers bound to IP literals where clients omit SNI.
|
|
380
|
+
*/
|
|
381
|
+
leafCredentialsFor(host) {
|
|
382
|
+
const stripped = host.replace(/\.$/, '');
|
|
383
|
+
const name = isIP(stripped) ? stripped : stripped.toLowerCase();
|
|
384
|
+
return {
|
|
385
|
+
key: this.leafKeyPem,
|
|
386
|
+
// Ship the root alongside the leaf so the child validates the whole chain
|
|
387
|
+
// from NODE_EXTRA_CA_CERTS without a separate fetch.
|
|
388
|
+
cert: this.mintLeafCertPem(name) + this.certPem,
|
|
389
|
+
};
|
|
390
|
+
}
|
|
391
|
+
/**
|
|
392
|
+
* Cached-or-minted TLS context for an SNI host. One leaf key is reused across
|
|
393
|
+
* every host: these certs never leave the machine and are only trusted by the
|
|
394
|
+
* child we spawned, so per-host keygen would buy nothing but latency on the
|
|
395
|
+
* first request to each host.
|
|
396
|
+
*/
|
|
397
|
+
secureContextFor(host) {
|
|
398
|
+
const stripped = host.replace(/\.$/, '');
|
|
399
|
+
const name = isIP(stripped) ? stripped : stripped.toLowerCase();
|
|
400
|
+
const cached = this.leaves.get(name);
|
|
401
|
+
if (cached) {
|
|
402
|
+
this.leaves.delete(name);
|
|
403
|
+
this.leaves.set(name, cached);
|
|
404
|
+
return cached;
|
|
405
|
+
}
|
|
406
|
+
const context = createSecureContext(this.leafCredentialsFor(name));
|
|
407
|
+
if (this.leaves.size >= MAX_LEAF_CONTEXTS) {
|
|
408
|
+
const oldest = this.leaves.keys().next().value;
|
|
409
|
+
if (oldest !== undefined)
|
|
410
|
+
this.leaves.delete(oldest);
|
|
411
|
+
}
|
|
412
|
+
this.leaves.set(name, context);
|
|
413
|
+
return context;
|
|
414
|
+
}
|
|
415
|
+
}
|
|
416
|
+
//# sourceMappingURL=ca.js.map
|