@machinal/mcp 0.0.0-stage → 0.4.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/README.md +366 -2
- package/bin/machinal-mcp.mjs +19 -0
- package/bin/machinal-stdio.mjs +14 -0
- package/package.json +47 -4
- package/skills/machinal-cinema/SKILL.md +18 -0
- package/skills/machinal-cinema/references/film-library/DIRECTOR.md +149 -0
- package/skills/machinal-cinema/references/film-library/LICENSE +21 -0
- package/skills/machinal-cinema/references/film-library/MY-STYLES.md +139 -0
- package/skills/machinal-cinema/references/film-library/README.md +13 -0
- package/skills/machinal-cinema/references/film-library/TECHNIQUE.md +162 -0
- package/skills/machinal-cinema/references/film-library/core/lib.js +44 -0
- package/skills/machinal-cinema/references/film-library/core/post/crt.js +144 -0
- package/skills/machinal-cinema/references/film-library/core/three/post.js +102 -0
- package/skills/machinal-cinema/references/film-library/manifest.json +394 -0
- package/skills/machinal-cinema/references/film-library/styleboard/catalog.json +1128 -0
- package/skills/machinal-cinema/references/film-library/styles/README.md +126 -0
- package/skills/machinal-cinema/references/film-library/styles/archive-lighttable/STYLE.md +107 -0
- package/skills/machinal-cinema/references/film-library/styles/art-deco/STYLE.md +110 -0
- package/skills/machinal-cinema/references/film-library/styles/ascii-crt/STYLE.md +113 -0
- package/skills/machinal-cinema/references/film-library/styles/backrooms/STYLE.md +123 -0
- package/skills/machinal-cinema/references/film-library/styles/blueprint/STYLE.md +118 -0
- package/skills/machinal-cinema/references/film-library/styles/brick-toy/STYLE.md +112 -0
- package/skills/machinal-cinema/references/film-library/styles/briefing-board/STYLE.md +120 -0
- package/skills/machinal-cinema/references/film-library/styles/caption-news/STYLE.md +135 -0
- package/skills/machinal-cinema/references/film-library/styles/cel-anime-80s/STYLE.md +117 -0
- package/skills/machinal-cinema/references/film-library/styles/chalkboard/STYLE.md +153 -0
- package/skills/machinal-cinema/references/film-library/styles/circuit-board/STYLE.md +149 -0
- package/skills/machinal-cinema/references/film-library/styles/city-symphony/STYLE.md +140 -0
- package/skills/machinal-cinema/references/film-library/styles/countdown/STYLE.md +130 -0
- package/skills/machinal-cinema/references/film-library/styles/crayon-book/STYLE.md +107 -0
- package/skills/machinal-cinema/references/film-library/styles/dark-keynote/STYLE.md +115 -0
- package/skills/machinal-cinema/references/film-library/styles/data-physical/STYLE.md +117 -0
- package/skills/machinal-cinema/references/film-library/styles/dataviz/STYLE.md +121 -0
- package/skills/machinal-cinema/references/film-library/styles/desktop-flythrough/STYLE.md +145 -0
- package/skills/machinal-cinema/references/film-library/styles/engraving/STYLE.md +121 -0
- package/skills/machinal-cinema/references/film-library/styles/game-show/STYLE.md +116 -0
- package/skills/machinal-cinema/references/film-library/styles/glass-product/STYLE.md +108 -0
- package/skills/machinal-cinema/references/film-library/styles/halftone-dossier/STYLE.md +120 -0
- package/skills/machinal-cinema/references/film-library/styles/hd-2d/STYLE.md +109 -0
- package/skills/machinal-cinema/references/film-library/styles/hologram-hud/STYLE.md +127 -0
- package/skills/machinal-cinema/references/film-library/styles/impasto/STYLE.md +122 -0
- package/skills/machinal-cinema/references/film-library/styles/ink-wash/STYLE.md +118 -0
- package/skills/machinal-cinema/references/film-library/styles/iso-infographic/STYLE.md +115 -0
- package/skills/machinal-cinema/references/film-library/styles/isometric-picture-book/STYLE.md +130 -0
- package/skills/machinal-cinema/references/film-library/styles/kino-montage/STYLE.md +149 -0
- package/skills/machinal-cinema/references/film-library/styles/lidar-survey/STYLE.md +116 -0
- package/skills/machinal-cinema/references/film-library/styles/living-screencast/STYLE.md +122 -0
- package/skills/machinal-cinema/references/film-library/styles/lowpoly-island/STYLE.md +110 -0
- package/skills/machinal-cinema/references/film-library/styles/memphis-diorama/STYLE.md +142 -0
- package/skills/machinal-cinema/references/film-library/styles/microgame/STYLE.md +120 -0
- package/skills/machinal-cinema/references/film-library/styles/microscope/STYLE.md +106 -0
- package/skills/machinal-cinema/references/film-library/styles/midcentury-toon/STYLE.md +122 -0
- package/skills/machinal-cinema/references/film-library/styles/news-package/STYLE.md +156 -0
- package/skills/machinal-cinema/references/film-library/styles/newsreel/STYLE.md +134 -0
- package/skills/machinal-cinema/references/film-library/styles/one-line/STYLE.md +112 -0
- package/skills/machinal-cinema/references/film-library/styles/paper-lantern/STYLE.md +120 -0
- package/skills/machinal-cinema/references/film-library/styles/paper-popup/STYLE.md +117 -0
- package/skills/machinal-cinema/references/film-library/styles/papercut-red/STYLE.md +108 -0
- package/skills/machinal-cinema/references/film-library/styles/pictogram-motion/STYLE.md +119 -0
- package/skills/machinal-cinema/references/film-library/styles/pixel-rpg/STYLE.md +115 -0
- package/skills/machinal-cinema/references/film-library/styles/printed-long-take/STYLE.md +141 -0
- package/skills/machinal-cinema/references/film-library/styles/risograph/STYLE.md +123 -0
- package/skills/machinal-cinema/references/film-library/styles/rubber-hose/STYLE.md +110 -0
- package/skills/machinal-cinema/references/film-library/styles/satellite-briefing/STYLE.md +114 -0
- package/skills/machinal-cinema/references/film-library/styles/scifi-toon/STYLE.md +119 -0
- package/skills/machinal-cinema/references/film-library/styles/shadow-puppet/STYLE.md +122 -0
- package/skills/machinal-cinema/references/film-library/styles/silent-film/STYLE.md +107 -0
- package/skills/machinal-cinema/references/film-library/styles/silkscreen-poster/STYLE.md +138 -0
- package/skills/machinal-cinema/references/film-library/styles/spy-titles/STYLE.md +114 -0
- package/skills/machinal-cinema/references/film-library/styles/stained-glass/STYLE.md +121 -0
- package/skills/machinal-cinema/references/film-library/styles/swiss-motion/STYLE.md +113 -0
- package/skills/machinal-cinema/references/film-library/styles/teardown/STYLE.md +125 -0
- package/skills/machinal-cinema/references/film-library/styles/telestrator/STYLE.md +135 -0
- package/skills/machinal-cinema/references/film-library/styles/tilt-shift/STYLE.md +105 -0
- package/skills/machinal-cinema/references/film-library/styles/transit-map/STYLE.md +194 -0
- package/skills/machinal-cinema/references/film-library/styles/ukiyoe/STYLE.md +110 -0
- package/skills/machinal-cinema/references/film-library/styles/urban-sketch/STYLE.md +124 -0
- package/skills/machinal-cinema/references/film-library/styles/visual-investigation/STYLE.md +138 -0
- package/skills/machinal-cinema/references/film-library/styles/watercolor/STYLE.md +111 -0
- package/skills/machinal-cinema/references/film-library/styles/white-model/STYLE.md +113 -0
- package/skills/machinal-cinema/references/film-library/styles/whiteboard/STYLE.md +116 -0
- package/skills/machinal-cinema/references/film-library/styles/woodcut/STYLE.md +120 -0
- package/skills/machinal-cinema/references/film-library/upstream-skill.md +13 -0
- package/skills/machinal-cinema/references/film-styles.json +1322 -0
- package/skills/machinal-cinema/references/film-techniques.json +107 -0
- package/skills/machinal-cinema/references/workflow.md +58 -0
- package/skills/machinal-credits/SKILL.md +24 -0
- package/skills/machinal-editing/SKILL.md +43 -0
- package/skills/machinal-editing/references/brief.md +98 -0
- package/skills/machinal-editing/references/effects.md +58 -0
- package/skills/machinal-editing/references/looks-motion.md +37 -0
- package/skills/machinal-editing/references/styles.json +15 -0
- package/skills/machinal-editing/references/styles.md +16 -0
- package/skills/machinal-editing/references/transitions.md +46 -0
- package/skills/machinal-editing/references/workflow.md +43 -0
- package/skills/machinal-media/SKILL.md +23 -0
- package/skills/machinal-media/references/workflow.md +160 -0
- package/skills/machinal-recipes/SKILL.md +32 -0
- package/skills/machinal-recipes/references/catalog.v1.json +10445 -0
- package/skills/machinal-recipes/references/commands.md +45 -0
- package/skills/machinal-recipes/references/example.edit.yaml +26 -0
- package/skills/machinal-recipes/references/examples/caption-audio.yaml +28 -0
- package/skills/machinal-recipes/references/examples/cinematic-sequence.yaml +21 -0
- package/skills/machinal-recipes/references/examples/client-scene.yaml +26 -0
- package/skills/machinal-recipes/references/examples/generated-media.yaml +25 -0
- package/skills/machinal-recipes/references/examples/modify-snapshot.yaml +22 -0
- package/skills/machinal-recipes/references/examples/montage-v3.yaml +28 -0
- package/skills/machinal-recipes/references/examples/narrated-documentary.yaml +112 -0
- package/skills/machinal-recipes/references/examples/narration-timing.yaml +43 -0
- package/skills/machinal-recipes/references/examples/scene-edit.yaml +19 -0
- package/skills/machinal-recipes/references/examples/scene-generated-image.yaml +36 -0
- package/skills/machinal-recipes/references/examples/scene-generation.yaml +35 -0
- package/skills/machinal-recipes/references/examples/scene-image-insert.yaml +41 -0
- package/skills/machinal-recipes/references/examples/scene-three-explainer.yaml +38 -0
- package/skills/machinal-recipes/references/examples/social-hook.yaml +26 -0
- package/skills/machinal-recipes/references/examples/tutorial-clean.yaml +19 -0
- package/skills/machinal-recipes/references/examples.md +28 -0
- package/skills/machinal-recipes/references/jobs-scenes.md +206 -0
- package/skills/machinal-recipes/references/text-audio.md +118 -0
- package/skills/machinal-recipes/references/yaml.md +72 -0
- package/skills/machinal-review/SKILL.md +18 -0
- package/skills/machinal-review/references/production.md +146 -0
- package/skills/machinal-scenes/SKILL.md +44 -0
- package/skills/machinal-scenes/references/authoring.md +97 -0
- package/skills/machinal-scenes/references/runtime.md +136 -0
- package/skills/machinal-scenes/references/scene-templates/blueprint-mechanism.svelte +62 -0
- package/skills/machinal-scenes/references/scene-templates/glitch-handoff.svelte +30 -0
- package/skills/machinal-scenes/references/scene-templates/image-reveal.svelte +33 -0
- package/skills/machinal-scenes/references/scene-templates/kinetic-type.svelte +38 -0
- package/skills/machinal-scenes/references/scene-templates/layered-parallax.svelte +31 -0
- package/skills/machinal-scenes/references/scene-templates/lens-assembly-3d.svelte +57 -0
- package/skills/machinal-scenes/references/scene-templates/paper-stage-3d.svelte +83 -0
- package/skills/machinal-scenes/references/scene-templates/signal-diagram.svelte +43 -0
- package/skills/machinal-scenes/references/scene-templates/swiss-grid-motion.svelte +54 -0
- package/skills/machinal-scenes/references/scene-templates.json +178 -0
- package/skills/machinal-scenes/references/scene-templates.md +50 -0
- package/skills/machinal-scenes/references/workflow.md +206 -0
- package/skills/machinal-support/SKILL.md +42 -0
- package/src/bridge.mjs +287 -0
- package/src/cli.mjs +157 -0
- package/src/configuration.mjs +148 -0
- package/src/connection.mjs +187 -0
- package/src/credential-store.mjs +61 -0
- package/src/credits.mjs +86 -0
- package/src/docker.mjs +93 -0
- package/src/download.mjs +90 -0
- package/src/endpoints.mjs +3 -0
- package/src/errors.mjs +9 -0
- package/src/formats.mjs +140 -0
- package/src/keys.mjs +127 -0
- package/src/launch.mjs +29 -0
- package/src/local-setup.mjs +109 -0
- package/src/opencode-auth.mjs +246 -0
- package/src/opencode-checkpoints.mjs +90 -0
- package/src/opencode-configuration.mjs +53 -0
- package/src/opencode-media.mjs +139 -0
- package/src/opencode-plugin/index.mjs +7 -0
- package/src/opencode-plugin/package.json +5 -0
- package/src/opencode-recipes.mjs +130 -0
- package/src/opencode-routing.mjs +154 -0
- package/src/opencode-tools.mjs +30 -0
- package/src/opencode-workflow.mjs +32 -0
- package/src/presentation.mjs +31 -0
- package/src/prompts.mjs +32 -0
- package/src/reference-files.json +127 -0
- package/src/runtime.mjs +51 -0
- package/src/setup-options.mjs +69 -0
- package/src/setup-stdio.mjs +116 -0
- package/src/setup.mjs +173 -0
- package/src/skills.mjs +68 -0
- package/src/transfer-http.mjs +109 -0
- package/src/version.mjs +3 -0
- package/src/windows-key-prompt.mjs +37 -0
- package/src/windows-key-prompt.ps1 +77 -0
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
import { InstallerError } from './errors.mjs';
|
|
2
|
+
import { isLoopbackEndpoint, normalizeEndpoint } from './connection.mjs';
|
|
3
|
+
import styleProfiles from '../skills/machinal-editing/references/styles.json' with { type: 'json' };
|
|
4
|
+
import { DEFAULT_LOCAL_URL, MACHINAL_SERVER_URL } from './endpoints.mjs';
|
|
5
|
+
|
|
6
|
+
export { DEFAULT_LOCAL_URL, MACHINAL_SERVER_URL };
|
|
7
|
+
export const EDITING_STYLES = styleProfiles.map((profile) => profile.id);
|
|
8
|
+
|
|
9
|
+
export async function chooseClient(value, { interactive, ui }) {
|
|
10
|
+
if (value && ['opencode', 'claude', 'codex'].includes(value)) return value;
|
|
11
|
+
if (value || !interactive) throw new InstallerError('Specify --client opencode, --client claude, or --client codex.');
|
|
12
|
+
return ui.select({ message: 'Client', choices: [
|
|
13
|
+
{ name: 'OpenCode V2', value: 'opencode' },
|
|
14
|
+
{ name: 'Claude Code', value: 'claude' },
|
|
15
|
+
{ name: 'Codex', value: 'codex' },
|
|
16
|
+
] });
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export async function chooseEndpoint(values, { env, interactive, ui }) {
|
|
20
|
+
let mode = values.mode === 'hosted' ? 'server' : values.mode;
|
|
21
|
+
if (mode && !['local', 'server', 'custom'].includes(mode)) throw new InstallerError('Choose --mode server (Machinal Server), local or custom (--mode hosted is an alias for server).');
|
|
22
|
+
const customDefault = env.MACHINAL_API_ORIGIN || env.DIRECTION_API_ORIGIN;
|
|
23
|
+
if (!mode && values.url) mode = 'custom';
|
|
24
|
+
if (!mode && interactive && !values.url) {
|
|
25
|
+
mode = await ui.select({ message: 'API location', default: 'server', choices: [
|
|
26
|
+
{ name: 'Machinal Server', value: 'server', short: 'Machinal Server', description: 'Official hosted service. Only your Machinal API key is needed.' },
|
|
27
|
+
{ name: 'Local', value: 'local', short: 'Local', description: 'Independent Docker backend with your own OpenRouter key.' },
|
|
28
|
+
{ name: 'Custom server (advanced)', value: 'custom', short: 'Custom server', description: 'Your own deployment. Enter its API URL.' },
|
|
29
|
+
] });
|
|
30
|
+
}
|
|
31
|
+
mode ??= customDefault ? 'custom' : 'server';
|
|
32
|
+
// An explicit legacy --url remains a custom deployment, never branded as the official service.
|
|
33
|
+
if (mode === 'server' && values.url && normalizeEndpoint(values.url) !== MACHINAL_SERVER_URL) mode = 'custom';
|
|
34
|
+
if (mode === 'server') return { mode, url: MACHINAL_SERVER_URL };
|
|
35
|
+
let rawURL = values.url || customDefault;
|
|
36
|
+
if (mode === 'local' && !values.url && (!rawURL || !isLoopbackEndpoint(normalizeEndpoint(rawURL)))) rawURL = DEFAULT_LOCAL_URL;
|
|
37
|
+
if (interactive && !values.url) {
|
|
38
|
+
rawURL = await ui.input({
|
|
39
|
+
message: mode === 'local' ? 'Local API URL' : 'Custom server API URL (not the website)',
|
|
40
|
+
...(rawURL ? { default: rawURL } : {}), required: true,
|
|
41
|
+
validate: (value) => {
|
|
42
|
+
try {
|
|
43
|
+
const url = normalizeEndpoint(value);
|
|
44
|
+
return mode !== 'local' || isLoopbackEndpoint(url) || 'Local mode needs a loopback URL. Choose Custom server for your own remote API.';
|
|
45
|
+
} catch (error) { return error.message; }
|
|
46
|
+
},
|
|
47
|
+
});
|
|
48
|
+
}
|
|
49
|
+
if (!rawURL) throw new InstallerError('Custom server requires --url with your API origin. Use --mode server for Machinal Server without a URL.');
|
|
50
|
+
const url = normalizeEndpoint(rawURL);
|
|
51
|
+
if (mode === 'local' && !isLoopbackEndpoint(url)) {
|
|
52
|
+
throw new InstallerError('Local mode requires a loopback API URL. Use --mode server for a deployed HTTPS API.');
|
|
53
|
+
}
|
|
54
|
+
return { mode, url };
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
export async function chooseSkillOptions(values, { interactive, ui }) {
|
|
58
|
+
if (values['no-skills']) {
|
|
59
|
+
if (values.style || values['replace-skills']) throw new InstallerError('--no-skills cannot be combined with --style or --replace-skills.');
|
|
60
|
+
return null;
|
|
61
|
+
}
|
|
62
|
+
if (values.style && !EDITING_STYLES.includes(values.style)) throw new InstallerError(`Choose --style from: ${EDITING_STYLES.join(', ')}.`);
|
|
63
|
+
if (interactive && !await ui.confirm({ message: 'Install editing, recipe, scene, credit and media skills?', default: true })) return null;
|
|
64
|
+
const style = values.style ?? (interactive ? await ui.select({
|
|
65
|
+
message: 'Default editing style (change per brief)', default: 'auto',
|
|
66
|
+
choices: styleProfiles.map(({ id, label }) => ({ name: id === 'auto' ? 'Auto — adapt to the brief' : label, short: id, value: id })),
|
|
67
|
+
}) : 'auto');
|
|
68
|
+
return { style };
|
|
69
|
+
}
|
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
import { dirname, resolve } from 'node:path';
|
|
2
|
+
import { chooseClient, chooseEndpoint, chooseSkillOptions } from './setup-options.mjs';
|
|
3
|
+
import { planConfiguration, saveConfiguration } from './configuration.mjs';
|
|
4
|
+
import { planSkills, saveSkills } from './skills.mjs';
|
|
5
|
+
import { readKey, offerKeyStorage } from './keys.mjs';
|
|
6
|
+
import { checkConnection } from './connection.mjs';
|
|
7
|
+
import { cacheCatalog, MCPBridge } from './bridge.mjs';
|
|
8
|
+
import { endpointFiles, installRuntime } from './runtime.mjs';
|
|
9
|
+
import { prepareIndependentLocal } from './local-setup.mjs';
|
|
10
|
+
import { backupSummary } from './presentation.mjs';
|
|
11
|
+
import { compactCreditSummaryLines } from './credits.mjs';
|
|
12
|
+
import { InstallerError } from './errors.mjs';
|
|
13
|
+
|
|
14
|
+
async function approveConflict(conflict, allowed, message, context) {
|
|
15
|
+
if (!conflict || allowed) return;
|
|
16
|
+
if (!context.interactive || !await context.ui.confirm({ message, default: false })) {
|
|
17
|
+
throw new InstallerError('Existing settings were preserved. Use --replace for the named server or --replace-skills for changed bundled skills.');
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
async function serverCredentials(values, context) {
|
|
22
|
+
if (values['defer-login']) return null;
|
|
23
|
+
let saved;
|
|
24
|
+
if (!values['session-key'] && !context.env.MACHINAL_API_KEY && !context.env.DIRECTION_API_KEY) {
|
|
25
|
+
try { saved = await context.credentialStore?.read(); } catch {
|
|
26
|
+
context.log('Credential storage unavailable; configure Login required or use hidden entry. The saved credential was not deleted.');
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
const available = context.env.MACHINAL_API_KEY || context.env.DIRECTION_API_KEY || saved;
|
|
30
|
+
if (!available && !context.interactive) return null;
|
|
31
|
+
if (!available && !await context.ui.confirm({ message: 'Enter your Machinal API key now? Choose no to configure with Login required.', default: true })) return null;
|
|
32
|
+
return readKey(context, { sessionOnly: values['session-key'] });
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export async function setupStdio(values, context) {
|
|
36
|
+
const { cwd, home, env, interactive, ui, log } = context;
|
|
37
|
+
const client = await chooseClient(values.client, context);
|
|
38
|
+
const defaultScope = client === 'codex' ? 'global' : 'project';
|
|
39
|
+
const scope = values.scope ?? (interactive ? await ui.select({ message: 'Available in', default: defaultScope, choices: [
|
|
40
|
+
{ name: client === 'codex' ? 'All my projects (recommended for Codex discovery)' : 'All my projects', value: 'global' },
|
|
41
|
+
{ name: 'This project only', value: 'project' },
|
|
42
|
+
] }) : defaultScope);
|
|
43
|
+
if (scope === 'project' && dirname(resolve(cwd)) === resolve(cwd)) log('Warning: project setup is running at a drive/filesystem root. Its settings may apply to all descendant projects.');
|
|
44
|
+
const endpoint = await chooseEndpoint(values, context);
|
|
45
|
+
log(`Connection: ${{ server: 'Machinal Server', local: 'Local', custom: 'Custom server' }[endpoint.mode]}`);
|
|
46
|
+
const local = endpoint.mode === 'local';
|
|
47
|
+
if (!local && (values['docker-dir'] || values['start-docker'] || values['configure-local'])) throw new InstallerError('Docker/provider setup options require --mode local. Server mode never configures providers or Docker.');
|
|
48
|
+
if (local && (values['session-key'] || values['defer-login'])) throw new InstallerError('Local mode uses an automatically generated device token, not a Machinal login.');
|
|
49
|
+
const files = endpointFiles(endpoint.url, context);
|
|
50
|
+
const script = await installRuntime(context);
|
|
51
|
+
const options = { client, scope, cwd, home, env, url: endpoint.url, name: values.name ?? 'machinal', transport: 'stdio', script,
|
|
52
|
+
catalogFile: files.catalogFile, ...(local ? { localConfig: files.localConfig } : {}) };
|
|
53
|
+
const plan = await planConfiguration(options);
|
|
54
|
+
if (client === 'codex' && scope === 'global') {
|
|
55
|
+
try {
|
|
56
|
+
const project = await planConfiguration({ ...options, scope: 'project' });
|
|
57
|
+
if (project.conflict) log(`Warning: ${project.file} already defines this server differently and may override global settings in a trusted project. Update that scope explicitly with --scope project --replace; no project settings were changed.`);
|
|
58
|
+
} catch {
|
|
59
|
+
log('Warning: project Codex settings could not be inspected safely. Global setup does not repair a conflicting or invalid .codex/config.toml; inspect the effective client configuration.');
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
const skillOptions = await chooseSkillOptions(values, context);
|
|
63
|
+
const skills = skillOptions ? await planSkills({ ...options, ...skillOptions }) : null;
|
|
64
|
+
await approveConflict(plan.conflict, values.replace, 'Replace only this named MCP server with the resilient stdio adapter?', context);
|
|
65
|
+
await approveConflict(skills?.conflict, values['replace-skills'], 'Back up and replace only the changed bundled skill files?', context);
|
|
66
|
+
let credentials;
|
|
67
|
+
let result;
|
|
68
|
+
let connection;
|
|
69
|
+
if (local) {
|
|
70
|
+
log('Independent local mode: your OpenRouter key and local disk/compute. No Machinal account, subscription, credits or PocketBase.');
|
|
71
|
+
const profile = await prepareIndependentLocal(values, endpoint.url, files.localConfig, context);
|
|
72
|
+
credentials = { key: profile.key, source: 'local' };
|
|
73
|
+
const verify = () => (context.checkConnection ?? checkConnection)(endpoint.url, profile.key, { local: true });
|
|
74
|
+
try { result = await verify(); } catch (error) {
|
|
75
|
+
if (error.code !== 'network') throw error;
|
|
76
|
+
await profile.start();
|
|
77
|
+
result = await verify();
|
|
78
|
+
}
|
|
79
|
+
if (!result.local) throw new InstallerError('The endpoint is not the independent local profile. No client configuration was written; use Server for an authenticated deployment.');
|
|
80
|
+
} else {
|
|
81
|
+
credentials = await serverCredentials(values, context);
|
|
82
|
+
if (credentials) {
|
|
83
|
+
try { result = await (context.checkConnection ?? checkConnection)(endpoint.url, credentials.key); } catch (error) {
|
|
84
|
+
const diagnostic = new MCPBridge({ url: endpoint.url, env: {}, credentialStore: null });
|
|
85
|
+
diagnostic.failure(error);
|
|
86
|
+
connection = diagnostic.status();
|
|
87
|
+
log(connection.message);
|
|
88
|
+
}
|
|
89
|
+
} else log('Login required. Installing the MCP adapter without credentials; it will remain available for connection diagnostics.');
|
|
90
|
+
}
|
|
91
|
+
if (result?.tools) {
|
|
92
|
+
await cacheCatalog(files.catalogFile, { url: endpoint.url, tools: result.tools, instructions: result.instructions });
|
|
93
|
+
}
|
|
94
|
+
const saved = await saveConfiguration(plan);
|
|
95
|
+
const installed = skills ? await saveSkills(skills) : null;
|
|
96
|
+
const backups = backupSummary(saved, installed, skills?.root);
|
|
97
|
+
if (backups) log(backups);
|
|
98
|
+
if (!local && result && credentials) await offerKeyStorage(credentials, context, { sessionOnly: values['session-key'] });
|
|
99
|
+
log(`MCP adapter configured for ${client}: ${plan.file}`);
|
|
100
|
+
log(result ? `Service verified: ${result.toolCount} tools. A running client connection has not been checked.`
|
|
101
|
+
: `Service status: ${connection?.status ?? 'login_required'}. The adapter is installed, not a verified service connection.`);
|
|
102
|
+
if (result?.credits) for (const line of compactCreditSummaryLines(result.credits)) log(line);
|
|
103
|
+
if (result?.creditsWarning) log(result.creditsWarning);
|
|
104
|
+
if (client === 'codex') log(scope === 'global'
|
|
105
|
+
? 'Codex: global config is visible from every project (CODEX_HOME is respected). Check with codex mcp list, then /mcp in a new session.'
|
|
106
|
+
: 'Codex loads .codex/config.toml only in trusted projects. Trust the project yourself or rerun with --scope global.');
|
|
107
|
+
if (client === 'claude') log('Claude Code: approve project MCP settings if asked. Check with claude mcp get machinal or /mcp.');
|
|
108
|
+
log('Use connection_status to see Login required, Connection unavailable, or Connected. Client-owned MCP badges cannot be renamed by an API-key adapter.');
|
|
109
|
+
if (!values['no-launch'] && interactive && result && credentials && await ui.confirm({ message: `Start ${client} now?`, default: true })) {
|
|
110
|
+
if (local) return context.launch(client, undefined, { cwd, env, unkeyed: true });
|
|
111
|
+
return context.launch(client, credentials.key, { cwd, env });
|
|
112
|
+
}
|
|
113
|
+
log(local ? 'Open the client normally. The adapter reads the generated local device token; no Machinal login is used.'
|
|
114
|
+
: 'Open the client normally. Saved Windows keys are loaded by the adapter; otherwise provide MACHINAL_API_KEY in its environment or use machinal-mcp launch.');
|
|
115
|
+
return 0;
|
|
116
|
+
}
|
package/src/setup.mjs
ADDED
|
@@ -0,0 +1,173 @@
|
|
|
1
|
+
import { dirname, resolve } from 'node:path';
|
|
2
|
+
import { InstallerError } from './errors.mjs';
|
|
3
|
+
import { checkConnection } from './connection.mjs';
|
|
4
|
+
import { planConfiguration, saveConfiguration } from './configuration.mjs';
|
|
5
|
+
import { compactCreditSummaryLines, creditSummaryLines } from './credits.mjs';
|
|
6
|
+
import { chooseClient, chooseEndpoint, chooseSkillOptions } from './setup-options.mjs';
|
|
7
|
+
import { offerKeyStorage, readKey } from './keys.mjs';
|
|
8
|
+
import { planSkills, saveSkills } from './skills.mjs';
|
|
9
|
+
import { prepareLocalDocker } from './docker.mjs';
|
|
10
|
+
import { API_KEYS_URL, backupSummary } from './presentation.mjs';
|
|
11
|
+
|
|
12
|
+
async function confirmReplacement(conflict, allowed, message, errorMessage, { interactive, ui }) {
|
|
13
|
+
if (!conflict || allowed) return;
|
|
14
|
+
if (!interactive || !await ui.confirm({ message, default: false })) throw new InstallerError(errorMessage);
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
async function scopeFor(values, { interactive, ui }) {
|
|
18
|
+
return values.scope ?? (interactive ? ui.select({
|
|
19
|
+
message: 'Available in', default: 'project', choices: [
|
|
20
|
+
{ name: 'This project', value: 'project' }, { name: 'All my projects', value: 'global' },
|
|
21
|
+
],
|
|
22
|
+
}) : 'project');
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
function reportConfiguration(result, saved, { log, verbose }, installed, file) {
|
|
26
|
+
if (!verbose) {
|
|
27
|
+
log('Setup ready', 'heading');
|
|
28
|
+
log(`MCP verified: ${result.toolCount} tools. Client connection not checked.`);
|
|
29
|
+
log(`Configuration ${saved.changed ? 'saved' : 'already up to date'}: ${file}`);
|
|
30
|
+
if (installed) log(`Skills ready: ${installed.changed} bundled files updated.`);
|
|
31
|
+
if (result.referenceWarning) log(result.referenceWarning);
|
|
32
|
+
if (result.mediaWarning) log(result.mediaWarning);
|
|
33
|
+
if (result.credits) {
|
|
34
|
+
for (const line of compactCreditSummaryLines(result.credits)) log(line);
|
|
35
|
+
} else {
|
|
36
|
+
log(result.creditsWarning);
|
|
37
|
+
}
|
|
38
|
+
return;
|
|
39
|
+
}
|
|
40
|
+
log(`Configured: ${result.toolCount} API tools verified. ${saved.changed ? 'Configuration saved.' : 'Configuration already up to date.'}`);
|
|
41
|
+
if (result.referenceWarning) log(result.referenceWarning);
|
|
42
|
+
if (result.mediaWarning) log(result.mediaWarning);
|
|
43
|
+
if (result.credits) {
|
|
44
|
+
for (const line of creditSummaryLines(result.credits)) log(line);
|
|
45
|
+
} else {
|
|
46
|
+
log(result.creditsWarning);
|
|
47
|
+
}
|
|
48
|
+
log('Only non-secret connection settings were written. The API check does not verify a running client connection.');
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
async function planClientStartup(values, client, credentials, { env, interactive, ui, log, verbose }, automaticAuth) {
|
|
52
|
+
const hasEnvironmentKey = (env.MACHINAL_API_KEY || env.DIRECTION_API_KEY)?.trim() === credentials.key;
|
|
53
|
+
const hasAutomaticKey = automaticAuth && credentials.source === 'saved';
|
|
54
|
+
if (!hasEnvironmentKey && !hasAutomaticKey) {
|
|
55
|
+
log('Warning: the verified key is available only to this installer. A saved key or hidden prompt does not provide MACHINAL_API_KEY to clients started separately.');
|
|
56
|
+
}
|
|
57
|
+
const launchNow = !values['no-launch'] && interactive && await ui.confirm({
|
|
58
|
+
message: `Start ${client} now with the verified API key?`, default: true,
|
|
59
|
+
});
|
|
60
|
+
if (!launchNow && !hasEnvironmentKey && !hasAutomaticKey) {
|
|
61
|
+
throw new InstallerError('The verified API key is not available in the client environment. No configuration, skills, or saved credentials were changed. Rerun setup without --no-launch and accept starting the client with the key, or supply MACHINAL_API_KEY in the environment used to start the client. A key in Windows Credential Manager is read by machinal-mcp launch, not by a client started directly.');
|
|
62
|
+
}
|
|
63
|
+
if (hasAutomaticKey && verbose) log('OpenCode will read the saved machinal key automatically through its MCP authentication integration. No separate launcher or environment setup is required for later sessions.');
|
|
64
|
+
return launchNow;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
async function verifyEndpoint(values, endpoint, initial, context) {
|
|
68
|
+
const verify = context.checkConnection ?? checkConnection;
|
|
69
|
+
let credentials = initial;
|
|
70
|
+
let dockerAttempted = false;
|
|
71
|
+
for (let attempt = 1; ; attempt++) {
|
|
72
|
+
try {
|
|
73
|
+
return { result: await verify(endpoint.url, credentials.key), credentials };
|
|
74
|
+
} catch (error) {
|
|
75
|
+
if (endpoint.mode === 'local' && error.code === 'network' && error.retryable && !dockerAttempted && attempt < 3) {
|
|
76
|
+
dockerAttempted = true;
|
|
77
|
+
await prepareLocalDocker(values, endpoint.url, context);
|
|
78
|
+
continue;
|
|
79
|
+
}
|
|
80
|
+
if (!context.interactive || attempt >= 3 || !(error.status === 401 || error.retryable)) throw error;
|
|
81
|
+
context.log(`Warning: ${error.message} Configuration and skills have not been changed.`);
|
|
82
|
+
const action = await context.ui.select({ message: 'How would you like to continue?', choices: [
|
|
83
|
+
...(error.status === 401 ? [
|
|
84
|
+
{ name: 'Enter a different API key I already have (hidden)', value: 'key' },
|
|
85
|
+
{ name: `Create a new API key — ${API_KEYS_URL}`, value: 'create' },
|
|
86
|
+
] : []),
|
|
87
|
+
{ name: 'Retry connection with the current key', value: 'retry' },
|
|
88
|
+
{ name: 'Cancel — keep existing settings', value: 'cancel' },
|
|
89
|
+
] });
|
|
90
|
+
if (action === 'key' || action === 'create') credentials = await readKey({ ...context, env: {}, credentialStore: null }, { sessionOnly: true });
|
|
91
|
+
else if (action !== 'retry') throw error;
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
export async function setup(values, context) {
|
|
97
|
+
const { cwd, home, env, interactive, ui, log, launch, verbose } = context;
|
|
98
|
+
if (interactive) {
|
|
99
|
+
log('machinal MCP', 'heading');
|
|
100
|
+
log('Connect your client. Setup does not render, generate media or use API credits.');
|
|
101
|
+
}
|
|
102
|
+
const client = await chooseClient(values.client, context);
|
|
103
|
+
const scope = await scopeFor(values, context);
|
|
104
|
+
if (scope === 'project' && dirname(resolve(cwd)) === resolve(cwd)) {
|
|
105
|
+
log('Warning: project setup is running at a drive/filesystem root. Its settings may apply to all descendant projects. Prefer running setup inside your project folder.');
|
|
106
|
+
}
|
|
107
|
+
const endpoint = await chooseEndpoint(values, context);
|
|
108
|
+
const { mode, url } = endpoint;
|
|
109
|
+
if (mode !== 'local' && (values['start-docker'] || values['docker-dir'])) throw new InstallerError('--start-docker and --docker-dir require --mode local. Server mode never manages Docker.');
|
|
110
|
+
const skillOptions = await chooseSkillOptions(values, context);
|
|
111
|
+
const options = { client, scope, cwd, home, env, url, name: values.name ?? 'machinal' };
|
|
112
|
+
const plan = await planConfiguration(options);
|
|
113
|
+
const skills = skillOptions ? await planSkills({ ...options, ...skillOptions }) : null;
|
|
114
|
+
if (verbose) {
|
|
115
|
+
log(`Mode: ${mode}. ${mode === 'local' ? 'Runs on this user’s computer. Reuses a running API or offers Docker setup from a checkout with your approval. Authentication and billing still apply.' : 'Connects to an existing server, including development Docker on localhost. No server is installed or started.'}`);
|
|
116
|
+
log(`MCP endpoint: ${url}`);
|
|
117
|
+
log(`Configuration: ${plan.file}`);
|
|
118
|
+
if (skills) log(`Bundled skills: ${skills.root} (default style: ${skillOptions.style}).`);
|
|
119
|
+
} else {
|
|
120
|
+
log(`Endpoint: ${url}`);
|
|
121
|
+
log(`Will configure: ${plan.file}`);
|
|
122
|
+
if (skills?.conflict) log(`Bundled skills: ${skills.root}`);
|
|
123
|
+
if (mode === 'local') log('Local Docker: Authentication and billing still apply.');
|
|
124
|
+
}
|
|
125
|
+
await confirmReplacement(plan.conflict, values.replace,
|
|
126
|
+
'This named server already has different settings. Replace only this server?',
|
|
127
|
+
'Existing server settings were preserved. Choose another --name, or explicitly use --replace.', context);
|
|
128
|
+
await confirmReplacement(skills?.conflict, values['replace-skills'],
|
|
129
|
+
'Some bundled skill files already differ. Back up and replace only these bundled files?',
|
|
130
|
+
'Existing skills were preserved. Use --no-skills to keep them, or explicitly use --replace-skills.', context);
|
|
131
|
+
|
|
132
|
+
const keyOptions = { sessionOnly: values['session-key'] };
|
|
133
|
+
if (interactive) log('API access', 'heading');
|
|
134
|
+
const initial = await readKey(context, keyOptions);
|
|
135
|
+
log('Checking MCP authentication, tool discovery, and live credits (no paid operations)...');
|
|
136
|
+
const { result, credentials } = await verifyEndpoint(values, endpoint, initial, context);
|
|
137
|
+
const { key } = credentials;
|
|
138
|
+
const launchNow = await planClientStartup(values, client, credentials, context, plan.automaticAuth);
|
|
139
|
+
if (verbose) log(`MCP verified: ${result.toolCount} tools. Saving client configuration...`);
|
|
140
|
+
const saved = await saveConfiguration(plan);
|
|
141
|
+
if (plan.automaticAuth && verbose) log('Automatic OpenCode MCP authentication configured: one saved machinal key, in-memory headers, secure replacement and automatic reconnection.');
|
|
142
|
+
if (verbose) reportConfiguration(result, saved, context);
|
|
143
|
+
let installed;
|
|
144
|
+
try {
|
|
145
|
+
if (skills) {
|
|
146
|
+
installed = await saveSkills(skills);
|
|
147
|
+
if (verbose) log(`Skills ready: machinal-editing, machinal-recipes, machinal-scenes, machinal-credits, machinal-media (${installed.changed} files updated).`);
|
|
148
|
+
}
|
|
149
|
+
} finally {
|
|
150
|
+
const summary = backupSummary(saved, installed, skills?.root);
|
|
151
|
+
if (summary) log(summary);
|
|
152
|
+
}
|
|
153
|
+
if (client === 'claude') log('If prompted, approve the project MCP configuration in Claude Code.');
|
|
154
|
+
if (client === 'codex' && scope === 'project') log('Codex loads project MCP settings only in trusted projects.');
|
|
155
|
+
|
|
156
|
+
await offerKeyStorage(credentials, context, keyOptions);
|
|
157
|
+
if (!verbose) reportConfiguration(result, saved, context, installed, plan.file);
|
|
158
|
+
|
|
159
|
+
if (launchNow) {
|
|
160
|
+
if (!verbose) log(`Starting ${client}...`);
|
|
161
|
+
return launch(client, key, { cwd, env });
|
|
162
|
+
}
|
|
163
|
+
log(verbose ? 'Warning: no client was started or connected. Existing client processes do not inherit environment changes.'
|
|
164
|
+
: 'Client not started. Existing client processes were not changed.');
|
|
165
|
+
if (plan.automaticAuth && credentials.source === 'saved') {
|
|
166
|
+
log(verbose ? 'OpenCode can start normally. Its MCP integration reads the one saved machinal key and reconnects automatically when that key is replaced.'
|
|
167
|
+
: 'Next: open OpenCode normally. Its MCP integration uses your saved key.');
|
|
168
|
+
} else {
|
|
169
|
+
log(`Next session: npx @machinal/mcp launch ${client}`);
|
|
170
|
+
log('Or start the client yourself with MACHINAL_API_KEY in its environment.');
|
|
171
|
+
}
|
|
172
|
+
return 0;
|
|
173
|
+
}
|
package/src/skills.mjs
ADDED
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
import { lstat, readFile } from 'node:fs/promises';
|
|
2
|
+
import { homedir } from 'node:os';
|
|
3
|
+
import { dirname, join } from 'node:path';
|
|
4
|
+
import { fileURLToPath } from 'node:url';
|
|
5
|
+
import { InstallerError } from './errors.mjs';
|
|
6
|
+
import { planTextFile, saveConfiguration } from './configuration.mjs';
|
|
7
|
+
import { EDITING_STYLES } from './setup-options.mjs';
|
|
8
|
+
import referenceFiles from './reference-files.json' with { type: 'json' };
|
|
9
|
+
|
|
10
|
+
export const SKILL_FILES = [
|
|
11
|
+
'machinal-editing/SKILL.md',
|
|
12
|
+
'machinal-recipes/SKILL.md',
|
|
13
|
+
'machinal-recipes/references/example.edit.yaml',
|
|
14
|
+
'machinal-credits/SKILL.md',
|
|
15
|
+
'machinal-scenes/SKILL.md',
|
|
16
|
+
'machinal-cinema/SKILL.md',
|
|
17
|
+
'machinal-review/SKILL.md',
|
|
18
|
+
'machinal-media/SKILL.md',
|
|
19
|
+
'machinal-support/SKILL.md',
|
|
20
|
+
...referenceFiles,
|
|
21
|
+
];
|
|
22
|
+
const bundle = fileURLToPath(new URL('../skills/', import.meta.url));
|
|
23
|
+
|
|
24
|
+
export function skillsDirectory({ client, scope, cwd = process.cwd(), home = homedir(), env = process.env }) {
|
|
25
|
+
if (!['project', 'global'].includes(scope)) throw new InstallerError('Choose project or global skill scope.');
|
|
26
|
+
if (client === 'opencode') return join(scope === 'project' ? join(cwd, '.opencode') : join(env.XDG_CONFIG_HOME || join(home, '.config'), 'opencode'), 'skills');
|
|
27
|
+
if (client === 'claude') return join(scope === 'project' ? join(cwd, '.claude') : env.CLAUDE_CONFIG_DIR || join(home, '.claude'), 'skills');
|
|
28
|
+
if (client === 'codex') return join(scope === 'project' ? cwd : home, '.agents', 'skills');
|
|
29
|
+
throw new InstallerError('Choose opencode, claude, or codex.');
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
async function refuseSymlinkParents(file, root) {
|
|
33
|
+
let directory = dirname(file);
|
|
34
|
+
while (directory.length >= dirname(root).length) {
|
|
35
|
+
try {
|
|
36
|
+
if ((await lstat(directory)).isSymbolicLink()) throw new InstallerError('Skill directories must not be symlinks. Existing files were preserved.');
|
|
37
|
+
} catch (error) {
|
|
38
|
+
if (error.code !== 'ENOENT') throw error;
|
|
39
|
+
}
|
|
40
|
+
if (directory === dirname(root)) break;
|
|
41
|
+
directory = dirname(directory);
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
export async function planSkills(options) {
|
|
46
|
+
if (!EDITING_STYLES.includes(options.style)) throw new InstallerError('Unsupported editing style.');
|
|
47
|
+
const root = skillsDirectory(options);
|
|
48
|
+
const contents = await Promise.all(SKILL_FILES.map(async (file) => [file, await readFile(join(bundle, file), 'utf8')]));
|
|
49
|
+
contents.push(['machinal-editing/references/preferences.md', `# Installed editing preference\n\nDefault style: **${options.style}**.\n\nUse this only when the user's current brief does not choose a different style. Read machinal://skills/editing for the profile definitions. This preference does not add YAML fields or authorize paid work.\n`]);
|
|
50
|
+
const plans = [];
|
|
51
|
+
for (const [relative, content] of contents) {
|
|
52
|
+
const file = join(root, relative);
|
|
53
|
+
await refuseSymlinkParents(file, root);
|
|
54
|
+
plans.push(await planTextFile(file, content));
|
|
55
|
+
}
|
|
56
|
+
return { root, plans, conflict: plans.some((plan) => plan.original !== null && plan.original !== plan.content) };
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
export async function saveSkills({ plans }) {
|
|
60
|
+
const saved = [];
|
|
61
|
+
try {
|
|
62
|
+
for (const plan of plans) saved.push(await saveConfiguration(plan));
|
|
63
|
+
} catch {
|
|
64
|
+
const backups = saved.filter((result) => result.backup).length;
|
|
65
|
+
throw new InstallerError(`MCP configuration was saved, but skill installation was incomplete (${saved.filter((result) => result.changed).length} files updated). ${backups} completed skill backups were retained beside their originals under <filename>.machinal-backup-*. Check permissions/disk space and run setup again; any backup made during the failed write is also retained.`);
|
|
66
|
+
}
|
|
67
|
+
return { changed: saved.filter((result) => result.changed).length, backups: saved.map((result) => result.backup).filter(Boolean) };
|
|
68
|
+
}
|
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
import { lookup } from 'node:dns/promises';
|
|
2
|
+
import http from 'node:http';
|
|
3
|
+
import https from 'node:https';
|
|
4
|
+
import { BlockList, isIP } from 'node:net';
|
|
5
|
+
|
|
6
|
+
export class TransferError extends Error {}
|
|
7
|
+
|
|
8
|
+
const privateIPv4 = new BlockList();
|
|
9
|
+
for (const [address, prefix] of [
|
|
10
|
+
['0.0.0.0', 8], ['10.0.0.0', 8], ['100.64.0.0', 10], ['127.0.0.0', 8],
|
|
11
|
+
['169.254.0.0', 16], ['172.16.0.0', 12], ['192.0.0.0', 24], ['192.0.2.0', 24],
|
|
12
|
+
['192.88.99.0', 24], ['192.168.0.0', 16], ['198.18.0.0', 15],
|
|
13
|
+
['198.51.100.0', 24], ['203.0.113.0', 24], ['224.0.0.0', 4], ['240.0.0.0', 4],
|
|
14
|
+
]) privateIPv4.addSubnet(address, prefix, 'ipv4');
|
|
15
|
+
|
|
16
|
+
const globalIPv6 = new BlockList();
|
|
17
|
+
globalIPv6.addSubnet('2000::', 3, 'ipv6');
|
|
18
|
+
const reservedIPv6 = new BlockList();
|
|
19
|
+
for (const [address, prefix] of [['2001::', 23], ['2001:db8::', 32], ['2002::', 16], ['3fff::', 20]]) {
|
|
20
|
+
reservedIPv6.addSubnet(address, prefix, 'ipv6');
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export function isPublicAddress(address) {
|
|
24
|
+
if (isIP(address) === 4) return !privateIPv4.check(address, 'ipv4');
|
|
25
|
+
return isIP(address) === 6 && globalIPv6.check(address, 'ipv6') && !reservedIPv6.check(address, 'ipv6');
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export function transferURL(value, trustedOrigin) {
|
|
29
|
+
let url;
|
|
30
|
+
try { url = new URL(value); } catch { throw new TransferError('Use an absolute HTTPS download URL.'); }
|
|
31
|
+
if (url.username || url.password || url.hash) throw new TransferError('Download URLs must not contain login credentials or fragments.');
|
|
32
|
+
const trusted = url.origin === trustedOrigin;
|
|
33
|
+
if (url.protocol !== 'https:' && !(trusted && url.protocol === 'http:')) {
|
|
34
|
+
throw new TransferError('HTTPS is required for internet downloads and redirects.');
|
|
35
|
+
}
|
|
36
|
+
const host = url.hostname.replace(/^\[|\]$/g, '');
|
|
37
|
+
if (!trusted && (host.toLowerCase().replace(/\.$/, '') === 'localhost' || (isIP(host) && !isPublicAddress(host)))) {
|
|
38
|
+
throw new TransferError('Internet downloads cannot access private, loopback or reserved addresses.');
|
|
39
|
+
}
|
|
40
|
+
return url;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export function publicLookup(resolve = lookup) {
|
|
44
|
+
return (hostname, options, callback) => {
|
|
45
|
+
void resolve(hostname, { all: true, verbatim: true }).then((addresses) => {
|
|
46
|
+
if (!addresses.length || addresses.some(({ address }) => !isPublicAddress(address))) {
|
|
47
|
+
throw new TransferError('The download host resolves to a private or reserved address.');
|
|
48
|
+
}
|
|
49
|
+
const matches = options.family ? addresses.filter(({ family }) => family === options.family) : addresses;
|
|
50
|
+
if (!matches.length) throw new TransferError('The download host has no usable public address.');
|
|
51
|
+
if (options.all) callback(null, matches);
|
|
52
|
+
else callback(null, matches[0].address, matches[0].family);
|
|
53
|
+
}).catch((error) => callback(error));
|
|
54
|
+
};
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
export function requestTransfer(value, { trustedOrigin, signal, method = 'GET', headers = {}, body } = {}) {
|
|
58
|
+
const url = transferURL(value, trustedOrigin);
|
|
59
|
+
const transport = url.protocol === 'https:' ? https : http;
|
|
60
|
+
return new Promise((resolve, reject) => {
|
|
61
|
+
const request = transport.request(url, {
|
|
62
|
+
method, headers, signal, agent: false,
|
|
63
|
+
...(url.origin === trustedOrigin ? {} : { lookup: publicLookup() }),
|
|
64
|
+
}, (response) => { clearTimeout(deadline); resolve(response); });
|
|
65
|
+
const deadline = setTimeout(() => request.destroy(new TransferError('The download server did not respond within 15 seconds.')), 15_000);
|
|
66
|
+
deadline.unref?.();
|
|
67
|
+
request.setTimeout(30_000, () => request.destroy(new TransferError('The download connection stalled for 30 seconds.')));
|
|
68
|
+
request.once('error', (error) => { clearTimeout(deadline); reject(error); });
|
|
69
|
+
if (body) request.end(body);
|
|
70
|
+
else request.end();
|
|
71
|
+
});
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
export async function downloadResponse(value, { trustedOrigin, signal, request = requestTransfer } = {}) {
|
|
75
|
+
let url = transferURL(value, trustedOrigin);
|
|
76
|
+
for (let redirects = 0; redirects <= 5; redirects++) {
|
|
77
|
+
const response = await request(url, { trustedOrigin, signal, headers: { 'Accept-Encoding': 'identity' } });
|
|
78
|
+
if ([301, 302, 303, 307, 308].includes(response.statusCode)) {
|
|
79
|
+
const location = response.headers.location;
|
|
80
|
+
response.destroy();
|
|
81
|
+
if (!location || redirects === 5) throw new TransferError('The download has too many redirects or no redirect target.');
|
|
82
|
+
url = transferURL(new URL(location, url).href, trustedOrigin);
|
|
83
|
+
continue;
|
|
84
|
+
}
|
|
85
|
+
if (response.statusCode !== 200) {
|
|
86
|
+
response.destroy();
|
|
87
|
+
throw new TransferError(`Download failed (HTTP ${response.statusCode}). Refresh an expired project link; do not render again.`);
|
|
88
|
+
}
|
|
89
|
+
return response;
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
export async function readTransferJSON(response, maxBytes = 2 * 1024 * 1024) {
|
|
94
|
+
try {
|
|
95
|
+
if (!response.headers['content-type']?.toLowerCase().startsWith('application/json')) {
|
|
96
|
+
throw new TransferError('The API returned an unexpected response instead of JSON.');
|
|
97
|
+
}
|
|
98
|
+
const chunks = [];
|
|
99
|
+
let bytes = 0;
|
|
100
|
+
for await (const chunk of response) {
|
|
101
|
+
bytes += chunk.length;
|
|
102
|
+
if (bytes > maxBytes) throw new TransferError('The API response exceeded the safety limit.');
|
|
103
|
+
chunks.push(chunk);
|
|
104
|
+
}
|
|
105
|
+
return JSON.parse(Buffer.concat(chunks).toString('utf8'));
|
|
106
|
+
} finally {
|
|
107
|
+
response.destroy();
|
|
108
|
+
}
|
|
109
|
+
}
|
package/src/version.mjs
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import { spawn as spawnProcess } from 'node:child_process';
|
|
2
|
+
import { readFile } from 'node:fs/promises';
|
|
3
|
+
import { InstallerError } from './errors.mjs';
|
|
4
|
+
|
|
5
|
+
export async function promptWindowsKey({ endpoint, apiKeysURL, signal, platform = process.platform, spawn = spawnProcess }) {
|
|
6
|
+
if (platform !== 'win32') throw new InstallerError('Secure desktop key entry is available on Windows. No saved key was changed.');
|
|
7
|
+
if (signal?.aborted) return null;
|
|
8
|
+
const script = await readFile(new URL('./windows-key-prompt.ps1', import.meta.url), 'utf8');
|
|
9
|
+
return new Promise((resolve, reject) => {
|
|
10
|
+
const child = spawn('powershell.exe', ['-NoProfile', '-STA', '-NonInteractive', '-Command', '-'], {
|
|
11
|
+
windowsHide: true, stdio: ['pipe', 'pipe', 'pipe'],
|
|
12
|
+
env: { ...process.env, MACHINAL_AUTH_ENDPOINT: endpoint, MACHINAL_AUTH_KEYS_URL: apiKeysURL },
|
|
13
|
+
});
|
|
14
|
+
let output = '';
|
|
15
|
+
let failed = false;
|
|
16
|
+
const abort = () => child.kill();
|
|
17
|
+
signal?.addEventListener('abort', abort, { once: true });
|
|
18
|
+
if (signal?.aborted) abort();
|
|
19
|
+
child.stdout.setEncoding('utf8');
|
|
20
|
+
child.stdout.on('data', (chunk) => {
|
|
21
|
+
output += chunk;
|
|
22
|
+
if (output.length > 16_384) { failed = true; output = ''; child.kill(); }
|
|
23
|
+
});
|
|
24
|
+
child.stderr.resume();
|
|
25
|
+
child.stdin.on('error', () => {});
|
|
26
|
+
child.on('error', () => { failed = true; });
|
|
27
|
+
child.once('close', (code) => {
|
|
28
|
+
signal?.removeEventListener('abort', abort);
|
|
29
|
+
if (signal?.aborted) return resolve(null);
|
|
30
|
+
if (!failed && code === 0) {
|
|
31
|
+
try { return resolve(JSON.parse(output)); } catch {}
|
|
32
|
+
}
|
|
33
|
+
reject(new InstallerError('Could not open secure machinal key entry. The saved key was not changed.'));
|
|
34
|
+
});
|
|
35
|
+
child.stdin.end(script);
|
|
36
|
+
});
|
|
37
|
+
}
|