factoryhub 0.0.0-stage → 0.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +202 -0
- package/NOTICE +16 -0
- package/README.md +195 -2
- package/factories/README.md +17 -0
- package/factories/client-file-readiness/README.md +3 -0
- package/factories/client-file-readiness/agents/analyst/agent.md +10 -0
- package/factories/client-file-readiness/agents/reviewer/agent.md +10 -0
- package/factories/client-file-readiness/agents/writer/agent.md +11 -0
- package/factories/client-file-readiness/factory.yaml +12 -0
- package/factories/client-file-readiness/flow.yaml +56 -0
- package/factories/competitor-teardown/README.md +3 -0
- package/factories/competitor-teardown/agents/analyst/agent.md +10 -0
- package/factories/competitor-teardown/agents/researcher/agent.md +11 -0
- package/factories/competitor-teardown/agents/reviewer/agent.md +10 -0
- package/factories/competitor-teardown/agents/writer/agent.md +11 -0
- package/factories/competitor-teardown/factory.yaml +11 -0
- package/factories/competitor-teardown/flow.yaml +75 -0
- package/factories/homepage-audit/README.md +3 -0
- package/factories/homepage-audit/agents/analyst/agent.md +10 -0
- package/factories/homepage-audit/agents/researcher/agent.md +11 -0
- package/factories/homepage-audit/agents/reviewer/agent.md +10 -0
- package/factories/homepage-audit/agents/writer/agent.md +11 -0
- package/factories/homepage-audit/factory.yaml +11 -0
- package/factories/homepage-audit/flow.yaml +77 -0
- package/factories/inbox-triage/README.md +3 -0
- package/factories/inbox-triage/agents/analyst/agent.md +10 -0
- package/factories/inbox-triage/agents/reviewer/agent.md +10 -0
- package/factories/inbox-triage/agents/writer/agent.md +11 -0
- package/factories/inbox-triage/factory.yaml +11 -0
- package/factories/inbox-triage/flow.yaml +57 -0
- package/factories/index.json +587 -0
- package/factories/launch-kit/README.md +3 -0
- package/factories/launch-kit/agents/reviewer/agent.md +10 -0
- package/factories/launch-kit/agents/strategist/agent.md +10 -0
- package/factories/launch-kit/agents/writer/agent.md +11 -0
- package/factories/launch-kit/factory.yaml +12 -0
- package/factories/launch-kit/flow.yaml +75 -0
- package/factories/meeting-to-actions/CHANGELOG.md +7 -0
- package/factories/meeting-to-actions/README.md +15 -0
- package/factories/meeting-to-actions/agents/analyst/agent.md +10 -0
- package/factories/meeting-to-actions/agents/reviewer/agent.md +10 -0
- package/factories/meeting-to-actions/agents/writer/agent.md +11 -0
- package/factories/meeting-to-actions/factory.yaml +11 -0
- package/factories/meeting-to-actions/flow.yaml +53 -0
- package/factories/meeting-to-actions/mindburn.requirements.yaml +8 -0
- package/factories/meeting-to-actions/mindburn.tests.yaml +16 -0
- package/factories/newsletter-note/README.md +11 -0
- package/factories/newsletter-note/agents/reviewer/agent.md +10 -0
- package/factories/newsletter-note/agents/writer/agent.md +11 -0
- package/factories/newsletter-note/factory.yaml +12 -0
- package/factories/newsletter-note/flow.yaml +45 -0
- package/factories/newsletter-note/mindburn.tests.yaml +80 -0
- package/factories/outreach-pack/README.md +3 -0
- package/factories/outreach-pack/agents/reviewer/agent.md +5 -0
- package/factories/outreach-pack/agents/writer/agent.md +5 -0
- package/factories/outreach-pack/factory.yaml +9 -0
- package/factories/outreach-pack/flow.yaml +42 -0
- package/factories/prospect-brief/README.md +3 -0
- package/factories/prospect-brief/agents/researcher/agent.md +11 -0
- package/factories/prospect-brief/agents/reviewer/agent.md +10 -0
- package/factories/prospect-brief/agents/strategist/agent.md +10 -0
- package/factories/prospect-brief/agents/writer/agent.md +11 -0
- package/factories/prospect-brief/factory.yaml +11 -0
- package/factories/prospect-brief/flow.yaml +79 -0
- package/factories/release-desk/README.md +13 -0
- package/factories/release-desk/agents/editor/agent.md +10 -0
- package/factories/release-desk/agents/reviewer/agent.md +10 -0
- package/factories/release-desk/factory.yaml +13 -0
- package/factories/release-desk/flow.yaml +67 -0
- package/factories/release-desk/mindburn.tests.yaml +163 -0
- package/factories/short-video-cut/README.md +11 -0
- package/factories/short-video-cut/agents/reviewer/agent.md +10 -0
- package/factories/short-video-cut/agents/writer/agent.md +11 -0
- package/factories/short-video-cut/factory.yaml +13 -0
- package/factories/short-video-cut/flow.yaml +46 -0
- package/factories/short-video-cut/mindburn.tests.yaml +80 -0
- package/factories/video-facts/README.md +11 -0
- package/factories/video-facts/agents/analyst/agent.md +10 -0
- package/factories/video-facts/agents/reviewer/agent.md +10 -0
- package/factories/video-facts/factory.yaml +13 -0
- package/factories/video-facts/flow.yaml +39 -0
- package/factories/video-facts/mindburn.tests.yaml +34 -0
- package/factories/video-to-posts/README.md +35 -0
- package/factories/video-to-posts/agents/analyst/agent.md +10 -0
- package/factories/video-to-posts/agents/reviewer/agent.md +10 -0
- package/factories/video-to-posts/agents/writer/agent.md +11 -0
- package/factories/video-to-posts/factory.yaml +12 -0
- package/factories/video-to-posts/flow.yaml +62 -0
- package/factories/video-to-posts/mindburn.tests.yaml +34 -0
- package/factories/week-of-posts/README.md +11 -0
- package/factories/week-of-posts/agents/reviewer/agent.md +10 -0
- package/factories/week-of-posts/agents/writer/agent.md +11 -0
- package/factories/week-of-posts/factory.yaml +12 -0
- package/factories/week-of-posts/flow.yaml +46 -0
- package/factories/week-of-posts/mindburn.tests.yaml +80 -0
- package/package.json +92 -4
- package/packages/cli/bin/factoryhub.mjs +8 -0
- package/packages/cli/package.json +29 -0
- package/packages/cli/src/args.mjs +47 -0
- package/packages/cli/src/commands/export.mjs +54 -0
- package/packages/cli/src/commands/get.mjs +37 -0
- package/packages/cli/src/commands/inspect.mjs +65 -0
- package/packages/cli/src/commands/list.mjs +24 -0
- package/packages/cli/src/commands/login.mjs +161 -0
- package/packages/cli/src/commands/logout.mjs +43 -0
- package/packages/cli/src/commands/mcp.mjs +25 -0
- package/packages/cli/src/commands/new.mjs +147 -0
- package/packages/cli/src/commands/pack.mjs +96 -0
- package/packages/cli/src/commands/publish.mjs +62 -0
- package/packages/cli/src/commands/pull.mjs +59 -0
- package/packages/cli/src/commands/push.mjs +115 -0
- package/packages/cli/src/commands/resume.mjs +66 -0
- package/packages/cli/src/commands/run.mjs +352 -0
- package/packages/cli/src/commands/runs.mjs +52 -0
- package/packages/cli/src/commands/search.mjs +30 -0
- package/packages/cli/src/commands/validate.mjs +79 -0
- package/packages/cli/src/commands/whoami.mjs +34 -0
- package/packages/cli/src/hosted.mjs +159 -0
- package/packages/cli/src/main.mjs +134 -0
- package/packages/cli/src/tool-sources.mjs +272 -0
- package/packages/cli/src/util.mjs +58 -0
- package/packages/engine/lib/catalog.mjs +50 -0
- package/packages/engine/lib/credentials.mjs +121 -0
- package/packages/engine/lib/hosted.mjs +119 -0
- package/packages/engine/lib/hub.mjs +423 -0
- package/packages/engine/lib/nango.mjs +157 -0
- package/packages/engine/lib/node.mjs +242 -0
- package/packages/engine/lib/providers.mjs +57 -0
- package/packages/engine/lib/run.mjs +192 -0
- package/packages/engine/lib/skill.mjs +229 -0
- package/packages/engine/lib/text.mjs +5 -0
- package/packages/engine/package.json +45 -0
- package/packages/engine/src/author-tests.mjs +78 -0
- package/packages/engine/src/compose.mjs +150 -0
- package/packages/engine/src/cost.mjs +41 -0
- package/packages/engine/src/diagnostics.mjs +21 -0
- package/packages/engine/src/factory-engine.mjs +2109 -0
- package/packages/engine/src/flow-sources.mjs +135 -0
- package/packages/engine/src/index.mjs +9 -0
- package/packages/engine/src/markdown.mjs +97 -0
- package/packages/engine/src/mcp-client.mjs +429 -0
- package/packages/engine/src/package.mjs +116 -0
- package/packages/engine/src/run.mjs +308 -0
- package/packages/engine/src/tool-sources.mjs +566 -0
- package/packages/mcp/bin/factoryhub-mcp.mjs +6 -0
- package/packages/mcp/package.json +36 -0
- package/packages/mcp/src/server.mjs +310 -0
- package/packages/sdk/package.json +28 -0
- package/packages/sdk/src/index.d.ts +163 -0
- package/packages/sdk/src/index.mjs +266 -0
- package/spec/README.md +42 -0
- package/spec/factory-format.md +866 -0
- package/spec/schema/factory.schema.json +43 -0
- package/spec/schema/factory.yaml.json +815 -0
- package/spec/schema/flow.schema.json +191 -0
- package/spec/skill-export.md +129 -0
|
@@ -0,0 +1,272 @@
|
|
|
1
|
+
// Experimental tool sources for `factoryhub run`: reading the flags, and
|
|
2
|
+
// opening the MCP servers and Nango sessions they name. Nothing here runs
|
|
3
|
+
// without --experimental-tools. See docs/experimental-tool-sources.md.
|
|
4
|
+
import { usage } from './util.mjs';
|
|
5
|
+
import { createMcpClient, MIN_TOKEN_LENGTH } from '../../engine/src/mcp-client.mjs';
|
|
6
|
+
import { createToolSources, displayLine } from '../../engine/src/tool-sources.mjs';
|
|
7
|
+
import { openNangoSession } from '../../engine/lib/nango.mjs';
|
|
8
|
+
import { isPrivateIp } from '../../engine/lib/run.mjs';
|
|
9
|
+
import { isPublicAddress } from '../../engine/src/factory-engine.mjs';
|
|
10
|
+
import { lookup } from 'node:dns/promises';
|
|
11
|
+
|
|
12
|
+
// Flags that name sources on the command line; and flags that grant the sources a factory declares.
|
|
13
|
+
export const TOOL_SOURCE_FLAGS = ['mcp', 'mcp-token-env', 'allow-tool', 'read-only', 'nango'];
|
|
14
|
+
export const GRANT_FLAGS = ['grant', 'bind', 'target'];
|
|
15
|
+
const NAME = /^[a-z0-9][a-z0-9_-]{0,40}$/;
|
|
16
|
+
const TOOL = /^[A-Za-z0-9_.-]{1,128}$/;
|
|
17
|
+
const ENV = /^[A-Za-z_][A-Za-z0-9_]{0,127}$/;
|
|
18
|
+
const LOOPBACK = new Set(['localhost', '127.0.0.1', '[::1]']);
|
|
19
|
+
|
|
20
|
+
const split = (value, sep, flag) => {
|
|
21
|
+
const at = value.indexOf(sep);
|
|
22
|
+
if (at < 1 || at === value.length - 1) throw usage(`--${flag} needs ${flag === 'mcp' ? 'name=url' : flag === 'mcp-token-env' ? 'name=ENV_VAR' : 'name:tool'}, not "${value}".`);
|
|
23
|
+
return [value.slice(0, at), value.slice(at + 1)];
|
|
24
|
+
};
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* The tool sources the flags name, checked, or null when none are given.
|
|
28
|
+
* Every flag here needs --experimental-tools.
|
|
29
|
+
*/
|
|
30
|
+
export function toolSourcePlan(flags, env) {
|
|
31
|
+
const given = [...TOOL_SOURCE_FLAGS, ...GRANT_FLAGS].filter((flag) => flags[flag]?.length);
|
|
32
|
+
if (flags['nango-user'] !== undefined) given.push('nango-user');
|
|
33
|
+
if (!flags['experimental-tools']) {
|
|
34
|
+
if (given.length) throw usage(`${given.map((flag) => `--${flag}`).join(', ')} need${given.length === 1 ? 's' : ''} --experimental-tools: tool sources are an experimental runner mode.`);
|
|
35
|
+
return null;
|
|
36
|
+
}
|
|
37
|
+
const granting = GRANT_FLAGS.filter((flag) => flags[flag]?.length);
|
|
38
|
+
if (granting.length) throw usage(`${granting.map((flag) => `--${flag}`).join(', ')} grant${granting.length === 1 ? 's' : ''} the sources a factory declares, and this factory declares none.`);
|
|
39
|
+
const sources = new Map();
|
|
40
|
+
const add = (name, entry, flag) => {
|
|
41
|
+
if (!NAME.test(name)) throw usage(`--${flag}: "${name}" is not a source name. Use lowercase letters, digits, - and _.`);
|
|
42
|
+
if (sources.has(name)) throw usage(`The tool source "${name}" is named twice.`);
|
|
43
|
+
sources.set(name, { name, allow: [], readOnly: [], ...entry });
|
|
44
|
+
};
|
|
45
|
+
for (const value of flags.mcp || []) {
|
|
46
|
+
const [name, address] = split(value, '=', 'mcp');
|
|
47
|
+
let url;
|
|
48
|
+
try { url = new URL(address); } catch { throw usage(`--mcp ${name}: "${address}" is not a URL.`); }
|
|
49
|
+
if (url.protocol !== 'https:' && !(url.protocol === 'http:' && LOOPBACK.has(url.hostname))) throw usage(`--mcp ${name}: the address must start with https:// (http:// only for this machine).`);
|
|
50
|
+
if (url.username || url.password) throw usage(`--mcp ${name}: put credentials in an environment variable and name it with --mcp-token-env, not in the address.`);
|
|
51
|
+
add(name, { kind: 'mcp', url: url.href, tokenEnv: null }, 'mcp');
|
|
52
|
+
}
|
|
53
|
+
for (const value of flags['mcp-token-env'] || []) {
|
|
54
|
+
const [name, variable] = split(value, '=', 'mcp-token-env');
|
|
55
|
+
const source = sources.get(name);
|
|
56
|
+
if (!source || source.kind !== 'mcp') throw usage(`--mcp-token-env ${name}: there is no --mcp ${name}=<url>.`);
|
|
57
|
+
if (!ENV.test(variable)) throw usage(`--mcp-token-env ${name}: "${variable}" is not an environment variable name.`);
|
|
58
|
+
if (!env[variable]) throw usage(`${variable} is not set.`);
|
|
59
|
+
if (env[variable].length < MIN_TOKEN_LENGTH) throw usage(`${variable} holds a token shorter than ${MIN_TOKEN_LENGTH} characters, too short to find again in what the server sends back.`);
|
|
60
|
+
source.tokenEnv = variable;
|
|
61
|
+
}
|
|
62
|
+
for (const value of flags.nango || []) {
|
|
63
|
+
const [integration, list] = value.includes(':') ? split(value, ':', 'nango') : [value, ''];
|
|
64
|
+
add(integration, { kind: 'nango' }, 'nango');
|
|
65
|
+
for (const tool of list.split(',').map((item) => item.trim()).filter(Boolean)) sources.get(integration).allow.push(tool);
|
|
66
|
+
}
|
|
67
|
+
for (const [flag, field] of [['allow-tool', 'allow'], ['read-only', 'readOnly']]) {
|
|
68
|
+
for (const value of flags[flag] || []) {
|
|
69
|
+
const [name, list] = split(value, ':', flag);
|
|
70
|
+
const source = sources.get(name);
|
|
71
|
+
if (!source) throw usage(`--${flag} ${name}: there is no tool source "${name}". Name it with --mcp or --nango first.`);
|
|
72
|
+
source[field].push(...list.split(',').map((item) => item.trim()).filter(Boolean));
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
if (!sources.size) throw usage('--experimental-tools needs a tool source: --mcp name=url or --nango integration:tool.');
|
|
76
|
+
if (flags['nango-user'] !== undefined && ![...sources.values()].some((source) => source.kind === 'nango')) throw usage('--nango-user goes with --nango.');
|
|
77
|
+
for (const source of sources.values()) {
|
|
78
|
+
const tools = [...source.allow, ...source.readOnly];
|
|
79
|
+
const bad = tools.find((tool) => !TOOL.test(tool));
|
|
80
|
+
if (bad) throw usage(`"${bad}" is not a tool name.`);
|
|
81
|
+
if (!tools.length) throw usage(`Allow at least one tool of "${source.name}": --allow-tool ${source.name}:<tool>, --read-only ${source.name}:<tool>${source.kind === 'nango' ? ` or --nango ${source.name}:<tool>` : ''}.`);
|
|
82
|
+
if (source.kind === 'nango' && !env.NANGO_API_KEY) throw usage('NANGO_API_KEY is not set.');
|
|
83
|
+
source.allow = [...new Set(source.allow)];
|
|
84
|
+
source.readOnly = [...new Set(source.readOnly)];
|
|
85
|
+
}
|
|
86
|
+
return { sources: [...sources.values()], endUserId: flags['nango-user'] || 'local-dev-user' };
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/**
|
|
90
|
+
* What is open, so it can be closed from anywhere: the end of a run, an
|
|
91
|
+
* error, or Ctrl+C while sources are still being opened. Closing twice is
|
|
92
|
+
* harmless.
|
|
93
|
+
*/
|
|
94
|
+
export function openThings() {
|
|
95
|
+
const closers = [];
|
|
96
|
+
return {
|
|
97
|
+
add(closeOne) { closers.push(closeOne); },
|
|
98
|
+
async close() { await Promise.all(closers.splice(0).map((closeOne) => Promise.resolve().then(closeOne).catch(() => {}))); },
|
|
99
|
+
};
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/**
|
|
103
|
+
* Opens every source in the plan and builds the run's catalog. Each source
|
|
104
|
+
* is added to `open` as soon as it exists. Resolves to `{ sources, close }`,
|
|
105
|
+
* or to `{ needsConnection }` when a Nango integration is not connected yet
|
|
106
|
+
* (nothing stays open then).
|
|
107
|
+
*/
|
|
108
|
+
export async function openToolSources(plan, { env, fetchImpl, open = openThings() }) {
|
|
109
|
+
const closers = { push: (closeOne) => open.add(closeOne) };
|
|
110
|
+
const close = () => open.close();
|
|
111
|
+
try {
|
|
112
|
+
const specs = [];
|
|
113
|
+
for (const source of plan.sources) {
|
|
114
|
+
let client;
|
|
115
|
+
if (source.kind === 'nango') {
|
|
116
|
+
// Registered for Ctrl+C before Nango is first asked: see openNangoSession.
|
|
117
|
+
const session = await openNangoSession({ apiKey: env.NANGO_API_KEY, integration: source.integration || source.name, tools: [...new Set([...source.allow, ...source.readOnly])], endUserId: plan.endUserId, fetchImpl, register: (closeOne) => closers.push(closeOne) });
|
|
118
|
+
if (!session.connected) {
|
|
119
|
+
await close();
|
|
120
|
+
return { needsConnection: session };
|
|
121
|
+
}
|
|
122
|
+
client = session.client;
|
|
123
|
+
} else {
|
|
124
|
+
client = createMcpClient({ url: source.url, token: source.tokenEnv ? env[source.tokenEnv] : '', fetchImpl });
|
|
125
|
+
closers.push(() => client.close());
|
|
126
|
+
}
|
|
127
|
+
specs.push({
|
|
128
|
+
name: source.name, client, allow: source.allow, readOnly: source.readOnly,
|
|
129
|
+
// A source the factory declares: its declarations, target, and how it was granted.
|
|
130
|
+
...(source.declared ? { declared: source.declared, target: source.target || null, targetValue: source.targetValue } : {}),
|
|
131
|
+
...(source.kind === 'nango' && source.integration && source.integration !== source.name ? { prefix: source.integration } : {}),
|
|
132
|
+
granted: source.granted || (source.kind === 'nango' ? 'nango' : 'address'),
|
|
133
|
+
});
|
|
134
|
+
}
|
|
135
|
+
const sources = await createToolSources(specs);
|
|
136
|
+
return { sources, close };
|
|
137
|
+
} catch (error) {
|
|
138
|
+
await close();
|
|
139
|
+
throw error;
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
const PLAIN = { read: 'reads', write: 'changes something', external: 'sends outside', irreversible: 'cannot be undone' };
|
|
144
|
+
const hostOf = (url) => { try { return new URL(url).host; } catch { return '(no address)'; } };
|
|
145
|
+
|
|
146
|
+
/**
|
|
147
|
+
* The plan for the sources a factory declares (RFC 0017, experimental): for
|
|
148
|
+
* each source a step uses, the grant the flags give it, if any. Nothing is
|
|
149
|
+
* granted by the factory alone, and --yes never grants. A source the person
|
|
150
|
+
* has not granted here may still be granted at an interactive terminal; the
|
|
151
|
+
* run starts only when every one is.
|
|
152
|
+
*
|
|
153
|
+
* - `--grant <source>`: the address the factory declares, with a token from
|
|
154
|
+
* `--mcp-token-env <source>=<ENV>` when the server needs one.
|
|
155
|
+
* - `--bind <source>=nango:<integration>`: a Nango agent session limited to
|
|
156
|
+
* the declared tools the steps use.
|
|
157
|
+
* - `--bind <source>=<url>`: another address, with a token as above.
|
|
158
|
+
* - `--target <source>=<value>`: the one target the run is limited to.
|
|
159
|
+
* - `--read-only <source>:<tool>`: the person vouches that a declared read
|
|
160
|
+
* only reads, for a server that does not mark it so.
|
|
161
|
+
*/
|
|
162
|
+
export function declaredPlan(declarations, flags, env) {
|
|
163
|
+
const cliOnly = ['mcp', 'nango', 'allow-tool'].filter((flag) => flags[flag]?.length);
|
|
164
|
+
if (cliOnly.length) throw usage(`This factory declares the sources it needs: grant them with --grant or --bind, not ${cliOnly.map((flag) => `--${flag}`).join(', ')}.`);
|
|
165
|
+
const used = new Map();
|
|
166
|
+
for (const capability of Object.keys(declarations.uses)) {
|
|
167
|
+
const [source, tool] = capability.split('/');
|
|
168
|
+
if (!used.has(source)) used.set(source, new Set());
|
|
169
|
+
used.get(source).add(tool);
|
|
170
|
+
}
|
|
171
|
+
const known = (key, flag) => { if (!Object.hasOwn(declarations.sources, key)) throw usage(`--${flag} ${displayLine(key)}: the factory declares no source "${displayLine(key)}".`); return declarations.sources[key]; };
|
|
172
|
+
const bindings = new Map();
|
|
173
|
+
const bind = (key, binding) => { if (bindings.has(key)) throw usage(`The source "${key}" is granted twice.`); bindings.set(key, binding); };
|
|
174
|
+
for (const key of flags.grant || []) {
|
|
175
|
+
const source = known(key, 'grant');
|
|
176
|
+
if (!source.url) throw usage(`The source "${key}" declares no address, only a registry name: bind it with --bind ${key}=<url> or --bind ${key}=nango:<integration>.`);
|
|
177
|
+
bind(key, { kind: 'mcp', url: source.url, granted: 'declared' });
|
|
178
|
+
}
|
|
179
|
+
for (const value of flags.bind || []) {
|
|
180
|
+
const [key, where] = split(value, '=', 'bind');
|
|
181
|
+
known(key, 'bind');
|
|
182
|
+
if (where.startsWith('nango:')) {
|
|
183
|
+
const integration = where.slice('nango:'.length);
|
|
184
|
+
if (!NAME.test(integration)) throw usage(`--bind ${key}: "${integration}" is not a Nango integration name.`);
|
|
185
|
+
if (!env.NANGO_API_KEY) throw usage('NANGO_API_KEY is not set.');
|
|
186
|
+
bind(key, { kind: 'nango', integration, granted: 'nango' });
|
|
187
|
+
continue;
|
|
188
|
+
}
|
|
189
|
+
let url;
|
|
190
|
+
try { url = new URL(where); } catch { throw usage(`--bind ${key}: "${where}" is not a URL or nango:<integration>.`); }
|
|
191
|
+
if (url.protocol !== 'https:' && !(url.protocol === 'http:' && LOOPBACK.has(url.hostname))) throw usage(`--bind ${key}: the address must start with https:// (http:// only for this machine).`);
|
|
192
|
+
if (url.username || url.password) throw usage(`--bind ${key}: put credentials in an environment variable and name it with --mcp-token-env, not in the address.`);
|
|
193
|
+
bind(key, { kind: 'mcp', url: url.href, granted: 'address' });
|
|
194
|
+
}
|
|
195
|
+
const targets = new Map();
|
|
196
|
+
for (const value of flags.target || []) {
|
|
197
|
+
const [key, given] = split(value, '=', 'target');
|
|
198
|
+
const source = known(key, 'target');
|
|
199
|
+
if (!source.target) throw usage(`The source "${key}" declares no target.`);
|
|
200
|
+
if (given.length > 500 || /[\p{Cc}\p{Cf}]/u.test(given)) throw usage(`--target ${key}: a target is plain text of at most 500 characters.`);
|
|
201
|
+
targets.set(key, given);
|
|
202
|
+
}
|
|
203
|
+
const tokens = new Map();
|
|
204
|
+
for (const value of flags['mcp-token-env'] || []) {
|
|
205
|
+
const [key, variable] = split(value, '=', 'mcp-token-env');
|
|
206
|
+
known(key, 'mcp-token-env');
|
|
207
|
+
if (!ENV.test(variable)) throw usage(`--mcp-token-env ${key}: "${variable}" is not an environment variable name.`);
|
|
208
|
+
if (!env[variable]) throw usage(`${variable} is not set.`);
|
|
209
|
+
if (env[variable].length < MIN_TOKEN_LENGTH) throw usage(`${variable} holds a token shorter than ${MIN_TOKEN_LENGTH} characters, too short to find again in what the server sends back.`);
|
|
210
|
+
tokens.set(key, variable);
|
|
211
|
+
}
|
|
212
|
+
const vouched = new Map();
|
|
213
|
+
for (const value of flags['read-only'] || []) {
|
|
214
|
+
const [key, list] = split(value, ':', 'read-only');
|
|
215
|
+
const source = known(key, 'read-only');
|
|
216
|
+
for (const tool of list.split(',').map((item) => item.trim()).filter(Boolean)) {
|
|
217
|
+
if (!Object.hasOwn(source.tools, tool)) throw usage(`--read-only ${key}: the factory declares no tool "${displayLine(tool)}" for that source.`);
|
|
218
|
+
if (source.tools[tool].effect !== 'read') throw usage(`--read-only ${key}: the factory declares "${tool}" as ${source.tools[tool].effect}, so it cannot be vouched for as a read.`);
|
|
219
|
+
if (!vouched.has(key)) vouched.set(key, []);
|
|
220
|
+
vouched.get(key).push(tool);
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
for (const [key, binding] of bindings) if (binding.kind === 'nango' && tokens.has(key)) throw usage(`--mcp-token-env ${key}: a Nango session brings its own token.`);
|
|
224
|
+
if (flags['nango-user'] !== undefined && ![...bindings.values()].some((binding) => binding.kind === 'nango')) throw usage('--nango-user goes with --bind <source>=nango:<integration>.');
|
|
225
|
+
return {
|
|
226
|
+
endUserId: flags['nango-user'] || 'local-dev-user',
|
|
227
|
+
sources: [...used.keys()].map((key) => {
|
|
228
|
+
const source = declarations.sources[key];
|
|
229
|
+
return {
|
|
230
|
+
name: key, title: source.title, url: source.url, binding: bindings.get(key) || null,
|
|
231
|
+
allow: [...used.get(key)], readOnly: vouched.get(key) || [], declared: source.tools, target: source.target,
|
|
232
|
+
targetValue: targets.get(key), tokenEnv: tokens.get(key) || null, uses: declarations.uses,
|
|
233
|
+
};
|
|
234
|
+
}),
|
|
235
|
+
};
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
/**
|
|
239
|
+
* An address the factory declares is reached only when it is public: a host
|
|
240
|
+
* name on the normal ports that resolves to no local or private address
|
|
241
|
+
* (section 5.5 of the format). The check is made before any connection.
|
|
242
|
+
* An address the person gives with --bind is theirs to choose.
|
|
243
|
+
*/
|
|
244
|
+
export async function checkDeclaredAddress(source, { lookupImpl = (host) => lookup(host, { all: true, verbatim: true }) } = {}) {
|
|
245
|
+
const host = hostOf(source.url);
|
|
246
|
+
const refuse = (why) => usage(`The address the factory declares for the source "${source.name}" (${host}) ${why}, so nothing was connected. Bind it yourself with --bind ${source.name}=<url> if you mean to reach it.`);
|
|
247
|
+
if (!isPublicAddress(source.url)) throw refuse('is not a public address');
|
|
248
|
+
let answers;
|
|
249
|
+
try { answers = await lookupImpl(new URL(source.url).hostname); } catch { throw refuse('could not be found'); }
|
|
250
|
+
if (!answers?.length || answers.some((answer) => isPrivateIp(answer.address))) throw refuse('points at this machine or a private network');
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
/** What the factory asks for, for the person to read before granting anything. */
|
|
254
|
+
export function consentText({ title, version, hash, plan, provider }) {
|
|
255
|
+
const lines = [`${displayLine(title, 120)} v${displayLine(version, 40)} (sha256 ${hash.slice(0, 12)}) asks to use these sources. Nothing is connected until each one is granted:`];
|
|
256
|
+
for (const source of plan.sources) {
|
|
257
|
+
const binding = source.binding;
|
|
258
|
+
const where = !binding ? (source.url ? `${hostOf(source.url)}, the address the factory declares` : 'no address yet: the factory names only a registry entry')
|
|
259
|
+
: binding.kind === 'nango' ? `a Nango agent session for ${binding.integration}, limited to the tools below`
|
|
260
|
+
: `${hostOf(binding.url)}${binding.granted === 'declared' ? ', the address the factory declares' : ', the address you gave'}`;
|
|
261
|
+
lines.push('', ` ${source.name}: ${displayLine(source.title, 100)}`, ` reached at: ${where}`);
|
|
262
|
+
if (source.target) lines.push(` limited to one ${displayLine(source.target.label, 40)}: ${source.targetValue === undefined ? '(not given yet)' : displayLine(source.targetValue, 200)}${source.target.help ? `. ${displayLine(source.target.help, 200)}` : ''}`);
|
|
263
|
+
for (const tool of source.allow) {
|
|
264
|
+
const declared = source.declared[tool];
|
|
265
|
+
const steps = source.uses[`${source.name}/${tool}`] || [];
|
|
266
|
+
lines.push(` ${source.name}/${tool} "${displayLine(declared.title, 100)}" the factory says it ${PLAIN[declared.effect]} used by: ${steps.map((step) => displayLine(step, 100)).join(', ')}${source.target && !declared.target ? ` (not limited to one ${displayLine(source.target.label, 40)})` : ''}`);
|
|
267
|
+
}
|
|
268
|
+
}
|
|
269
|
+
lines.push('', ' A source receives the arguments the model writes, which can include the inputs a step sees.',
|
|
270
|
+
` What a tool returns goes to the model provider: ${displayLine(provider, 200)}. Only tools that read can run, and a grant lasts for this run only.`);
|
|
271
|
+
return lines.join('\n');
|
|
272
|
+
}
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
// Shared bits for the commands: styling, output and the engine imports.
|
|
2
|
+
import { hubClient, checkedBase, DEFAULT_HUB } from '../../engine/lib/hub.mjs';
|
|
3
|
+
import { resolveToken } from '../../engine/lib/credentials.mjs';
|
|
4
|
+
import { usage as usageError } from '../../engine/lib/node.mjs';
|
|
5
|
+
export * as engine from '../../engine/src/factory-engine.mjs';
|
|
6
|
+
export { readFactory, readFolder, writeFiles, listFactoryDirs, usage, HOUSE_FACTORIES } from '../../engine/lib/node.mjs';
|
|
7
|
+
export { summarize, canonicalFiles, matches } from '../../engine/lib/catalog.mjs';
|
|
8
|
+
|
|
9
|
+
export function styles(io) {
|
|
10
|
+
const wrap = (open, close) => (text) => (io.color ? `\x1b[${open}m${text}\x1b[${close}m` : String(text));
|
|
11
|
+
return { bold: wrap(1, 22), dim: wrap(2, 22), red: wrap(31, 39), green: wrap(32, 39), yellow: wrap(33, 39) };
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
export const out = (io, text = '') => io.stdout.write(`${text}\n`);
|
|
15
|
+
export const err = (io, text = '') => io.stderr.write(`${text}\n`);
|
|
16
|
+
export const json = (io, value) => io.stdout.write(`${JSON.stringify(value, null, 2)}\n`);
|
|
17
|
+
export const plural = (n, one, many = `${one}s`) => `${n} ${n === 1 ? one : many}`;
|
|
18
|
+
|
|
19
|
+
/** Lays rows out in columns, padding every column but the last. */
|
|
20
|
+
export function table(rows) {
|
|
21
|
+
if (!rows.length) return '';
|
|
22
|
+
const widths = rows[0].map((_, column) => Math.max(...rows.map((row) => String(row[column] ?? '').length)));
|
|
23
|
+
return rows.map((row) => row.map((cell, column) => (column === row.length - 1 ? String(cell ?? '') : String(cell ?? '').padEnd(widths[column]))).join(' ').trimEnd()).join('\n');
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
// ---- the factoryhub site ----
|
|
27
|
+
|
|
28
|
+
export { DEFAULT_HUB };
|
|
29
|
+
export const BASE_URL_HELP = `the factoryhub address (default: FACTORYHUB_BASE_URL or ${DEFAULT_HUB})`;
|
|
30
|
+
|
|
31
|
+
/** The hub address a command talks to. Tokens travel only over https, or http to this machine. */
|
|
32
|
+
export function hubBase(flags, io) {
|
|
33
|
+
try {
|
|
34
|
+
return checkedBase(flags['base-url'] || io.env.FACTORYHUB_BASE_URL || DEFAULT_HUB);
|
|
35
|
+
} catch (error) {
|
|
36
|
+
throw usageError(error.message);
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** A date for people: 2027-02-13. */
|
|
41
|
+
export const day = (iso) => (iso ? String(iso).slice(0, 10) : 'never');
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* A hub client with the token from FACTORYHUB_TOKEN or `factoryhub login`.
|
|
45
|
+
* With `needToken`, refuses before any request when there is none.
|
|
46
|
+
*/
|
|
47
|
+
export async function connect(flags, io, { needToken = false } = {}) {
|
|
48
|
+
const base = hubBase(flags, io);
|
|
49
|
+
const credential = await resolveToken(base, io.env);
|
|
50
|
+
if (credential.warning) io.stderr.write(`${styles(io).yellow(credential.warning)}\n`);
|
|
51
|
+
if (needToken && !credential.token) {
|
|
52
|
+
throw new Error(credential.expired
|
|
53
|
+
? `Your login to ${base} expired on ${day(credential.record.expires)}. Run "factoryhub login" to log in again.`
|
|
54
|
+
: `You are not logged in to ${base}. Run "factoryhub login" first, or set FACTORYHUB_TOKEN.`);
|
|
55
|
+
}
|
|
56
|
+
const hub = hubClient({ baseUrl: base, env: io.env, fetchImpl: io.fetch, token: credential.token, tokenSource: credential.source, tokenScopes: credential.record?.scopes || null });
|
|
57
|
+
return { hub, credential, base };
|
|
58
|
+
}
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
// A factory's public summary, the same fields the factoryhub site lists, and
|
|
2
|
+
// the canonical bundle those fields and hashes are computed from.
|
|
3
|
+
import { parseBundle, withForeman, bundleHash, inputSchema } from '../src/factory-engine.mjs';
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* The canonical bundle: the source files plus the foreman the engine writes
|
|
7
|
+
* from the flow when the author did not write one. An author's own foreman
|
|
8
|
+
* is kept byte for byte. Its hash is the factory's identity.
|
|
9
|
+
*/
|
|
10
|
+
export function canonicalFiles(files) {
|
|
11
|
+
return withForeman(files);
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
/** A summary of a factory for listings, search and `inspect`. */
|
|
15
|
+
export async function summarize(files, { id } = {}) {
|
|
16
|
+
const bundle = canonicalFiles(files);
|
|
17
|
+
const { ok, errors, warnings, factory } = parseBundle(bundle);
|
|
18
|
+
return {
|
|
19
|
+
id: id || factory.name,
|
|
20
|
+
name: factory.name,
|
|
21
|
+
title: factory.title,
|
|
22
|
+
description: factory.description,
|
|
23
|
+
author: factory.author,
|
|
24
|
+
version: factory.version,
|
|
25
|
+
license: factory.license,
|
|
26
|
+
tags: factory.tags,
|
|
27
|
+
time: factory.time,
|
|
28
|
+
valid: ok,
|
|
29
|
+
runnable: ok && factory.runnable,
|
|
30
|
+
errors,
|
|
31
|
+
warnings,
|
|
32
|
+
blockers: factory.blockers,
|
|
33
|
+
inputs: factory.inputs,
|
|
34
|
+
steps: factory.steps.map((step) => ({ id: step.id, title: step.title, kind: step.kind, agent: step.agent, needs: step.needs, target: step.target, tools: step.tools, missing: step.missing })),
|
|
35
|
+
agents: Object.values(factory.agents).map((agent) => ({ name: agent.name, description: agent.description, type: agent.type })),
|
|
36
|
+
tools: [...new Set(factory.steps.flatMap((step) => [...step.tools, ...step.missing]))].sort(),
|
|
37
|
+
done: factory.done,
|
|
38
|
+
files: Object.keys(bundle),
|
|
39
|
+
sha256: await bundleHash(bundle),
|
|
40
|
+
...(ok ? { inputSchema: inputSchema(factory) } : {}),
|
|
41
|
+
};
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** Keeps the entries whose words contain every word of the query. */
|
|
45
|
+
export function matches(entry, query) {
|
|
46
|
+
const words = String(query || '').toLowerCase().split(/\s+/).filter(Boolean);
|
|
47
|
+
if (!words.length) return true;
|
|
48
|
+
const text = [entry.id, entry.name, entry.title, entry.description, ...(entry.tags || [])].join(' ').toLowerCase();
|
|
49
|
+
return words.every((word) => text.includes(word));
|
|
50
|
+
}
|
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
// Where the factoryhub CLI and SDK keep personal access tokens.
|
|
2
|
+
//
|
|
3
|
+
// FACTORYHUB_TOKEN wins when it is set
|
|
4
|
+
// ${XDG_CONFIG_HOME:-~/.config}/factoryhub/credentials.json otherwise
|
|
5
|
+
//
|
|
6
|
+
// The file maps each hub address to the token `factoryhub login` stored for
|
|
7
|
+
// it, with the token's name, scopes, expiry and origin: "device" for a token
|
|
8
|
+
// this computer received by device login, "pasted" for one the person passed
|
|
9
|
+
// in. On macOS and Linux only the person may read it (mode 0600, in a 0700
|
|
10
|
+
// folder), and a file others can read is refused, as ssh refuses a readable
|
|
11
|
+
// key. On Windows no permissions are set: the file is as private as the
|
|
12
|
+
// person's user folder. Nothing here prints or logs a token.
|
|
13
|
+
//
|
|
14
|
+
// FACTORYHUB_TOKEN goes only to the production hub, or to the hub named in
|
|
15
|
+
// FACTORYHUB_BASE_URL: a --base-url pointing elsewhere does not receive it.
|
|
16
|
+
import { readFile, writeFile, rename, mkdir, chmod, stat, rm } from 'node:fs/promises';
|
|
17
|
+
import { homedir } from 'node:os';
|
|
18
|
+
import { join, dirname } from 'node:path';
|
|
19
|
+
import { DEFAULT_HUB, TOKEN_PATTERN } from './hub.mjs';
|
|
20
|
+
|
|
21
|
+
export const TOKEN_ENV = 'FACTORYHUB_TOKEN';
|
|
22
|
+
export { TOKEN_PATTERN };
|
|
23
|
+
const POSIX = process.platform !== 'win32';
|
|
24
|
+
|
|
25
|
+
/** How private the credentials file is on this computer, for messages. */
|
|
26
|
+
export const PRIVACY = POSIX
|
|
27
|
+
? 'readable only by you (mode 0600)'
|
|
28
|
+
: 'protected only by your Windows user folder\'s permissions: factoryhub does not set file permissions on Windows';
|
|
29
|
+
|
|
30
|
+
/** The credentials file for this environment. */
|
|
31
|
+
export function credentialsPath(env = process.env) {
|
|
32
|
+
const config = env.XDG_CONFIG_HOME || join(env.HOME || env.USERPROFILE || homedir(), '.config');
|
|
33
|
+
return join(config, 'factoryhub', 'credentials.json');
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
async function readAll(env) {
|
|
37
|
+
const path = credentialsPath(env);
|
|
38
|
+
let info;
|
|
39
|
+
try { info = await stat(path); } catch (error) {
|
|
40
|
+
if (error.code === 'ENOENT') return {};
|
|
41
|
+
throw error;
|
|
42
|
+
}
|
|
43
|
+
if (POSIX && (info.mode & 0o077)) throw new Error(`${path} can be read by other users of this computer, so factoryhub will not use it. Run "chmod 600 ${path}" and try again.`);
|
|
44
|
+
let parsed;
|
|
45
|
+
try { parsed = JSON.parse(await readFile(path, 'utf8')); } catch {
|
|
46
|
+
throw new Error(`${path} is not valid JSON. Delete it and run "factoryhub login" again.`);
|
|
47
|
+
}
|
|
48
|
+
return parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed : {};
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
async function writeAll(env, all) {
|
|
52
|
+
const path = credentialsPath(env);
|
|
53
|
+
await mkdir(dirname(path), { recursive: true, mode: 0o700 });
|
|
54
|
+
// Written beside the file and renamed over it, so a crash never leaves half
|
|
55
|
+
// a file, and created 0600 so the token is never readable by others.
|
|
56
|
+
const temporary = `${path}.${process.pid}.${Date.now()}.tmp`;
|
|
57
|
+
try {
|
|
58
|
+
await writeFile(temporary, `${JSON.stringify(all, null, 2)}\n`, { mode: 0o600, flag: 'wx' });
|
|
59
|
+
if (POSIX) await chmod(temporary, 0o600);
|
|
60
|
+
await rename(temporary, path);
|
|
61
|
+
} catch (error) {
|
|
62
|
+
await rm(temporary, { force: true });
|
|
63
|
+
throw error;
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/** The stored record for one hub, or null. */
|
|
68
|
+
export async function storedCredential(base, env = process.env) {
|
|
69
|
+
const record = (await readAll(env))[base];
|
|
70
|
+
return record && typeof record.token === 'string' ? record : null;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/**
|
|
74
|
+
* Stores the token `login` received for one hub, replacing any earlier one.
|
|
75
|
+
* `record.origin` is "device" for a token received by device login on this
|
|
76
|
+
* computer, "pasted" for one passed in; only a "device" token is ever revoked
|
|
77
|
+
* when a later login replaces it.
|
|
78
|
+
*/
|
|
79
|
+
export async function saveCredential(base, record, env = process.env) {
|
|
80
|
+
if (!TOKEN_PATTERN.test(record?.token || '')) throw new Error('That is not a factoryhub personal access token.');
|
|
81
|
+
if (!['device', 'pasted'].includes(record.origin)) throw new Error('A stored token needs its origin: "device" or "pasted".');
|
|
82
|
+
const all = await readAll(env);
|
|
83
|
+
all[base] = { ...record, saved: new Date().toISOString() };
|
|
84
|
+
await writeAll(env, all);
|
|
85
|
+
return credentialsPath(env);
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/** Forgets the token stored for one hub. True when there was one. */
|
|
89
|
+
export async function deleteCredential(base, env = process.env) {
|
|
90
|
+
const all = await readAll(env);
|
|
91
|
+
if (!all[base]) return false;
|
|
92
|
+
delete all[base];
|
|
93
|
+
if (Object.keys(all).length) await writeAll(env, all);
|
|
94
|
+
else await rm(credentialsPath(env), { force: true });
|
|
95
|
+
return true;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/** The same hub address, written either way: no trailing slash. */
|
|
99
|
+
const sameBase = (a, b) => Boolean(a && b) && String(a).replace(/\/+$/, '') === String(b).replace(/\/+$/, '');
|
|
100
|
+
|
|
101
|
+
/** Whether FACTORYHUB_TOKEN may be sent to `base`: production, or the hub FACTORYHUB_BASE_URL names. */
|
|
102
|
+
export function envTokenGoesTo(base, env = process.env) {
|
|
103
|
+
return sameBase(base, DEFAULT_HUB) || sameBase(base, env.FACTORYHUB_BASE_URL);
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/**
|
|
107
|
+
* The token to send to one hub: FACTORYHUB_TOKEN, else the stored one.
|
|
108
|
+
* FACTORYHUB_TOKEN is used only for production or the hub FACTORYHUB_BASE_URL
|
|
109
|
+
* names; for any other hub it is left out and `warning` says so.
|
|
110
|
+
* Returns { token, source: 'env' | 'file' | null, record, expired, warning }.
|
|
111
|
+
*/
|
|
112
|
+
export async function resolveToken(base, env = process.env, now = Date.now()) {
|
|
113
|
+
const fromEnv = (env[TOKEN_ENV] || '').trim();
|
|
114
|
+
let warning = null;
|
|
115
|
+
if (fromEnv && envTokenGoesTo(base, env)) return { token: fromEnv, source: 'env', record: null, expired: false, warning };
|
|
116
|
+
if (fromEnv) warning = `FACTORYHUB_TOKEN was not sent to ${String(base).replace(/\/+$/, '')}: it goes only to ${DEFAULT_HUB} or to the address in FACTORYHUB_BASE_URL.`;
|
|
117
|
+
const record = await storedCredential(base, env);
|
|
118
|
+
if (!record) return { token: null, source: null, record: null, expired: false, warning };
|
|
119
|
+
const expired = Boolean(record.expires) && Date.parse(record.expires) <= now;
|
|
120
|
+
return { token: expired ? null : record.token, source: 'file', record, expired, warning };
|
|
121
|
+
}
|
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
// Hosted runs on a factoryhub site, through /api/v1: follow a run's events,
|
|
2
|
+
// stop where it waits for the person, and read the whole result with its
|
|
3
|
+
// signed receipt. Shared by the CLI and the SDK. Nothing here decides a step:
|
|
4
|
+
// a decision is sent only when the caller passes one the person made.
|
|
5
|
+
import { randomUUID } from 'node:crypto';
|
|
6
|
+
import { verifyReceipt, fromBase64Url } from '../src/factory-engine.mjs';
|
|
7
|
+
import { DEFAULT_HUB } from './hub.mjs';
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* The receipt signing keys of the production hub, pinned by the SHA-256 of
|
|
11
|
+
* the raw Ed25519 public key. A receipt from https://factory.mindburn.org
|
|
12
|
+
* verifies only against these, whatever its key endpoint answers; a new key
|
|
13
|
+
* needs a release. Read from
|
|
14
|
+
* https://factory.mindburn.org/.well-known/factory-hub-keys.json:
|
|
15
|
+
* hub-20a58d31af55 created 2026-11-10T14:17:31.177Z
|
|
16
|
+
*/
|
|
17
|
+
export const PINNED_KEYS = Object.freeze({
|
|
18
|
+
[DEFAULT_HUB]: Object.freeze(['3c2acc0709aef8748b5dd8b8ea6574a4ddbdd9911096fc6b89242425f6a9e62d']),
|
|
19
|
+
});
|
|
20
|
+
|
|
21
|
+
/** The SHA-256 of a published key's raw public key bytes, or null when it is not one. */
|
|
22
|
+
export async function keyFingerprint(key) {
|
|
23
|
+
try {
|
|
24
|
+
const raw = fromBase64Url(String(key?.public_key || ''));
|
|
25
|
+
if (raw.length !== 32) return null;
|
|
26
|
+
return [...new Uint8Array(await crypto.subtle.digest('SHA-256', raw))].map((byte) => byte.toString(16).padStart(2, '0')).join('');
|
|
27
|
+
} catch { return null; }
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* Checks a hosted run's receipt the way the CLI and SDK report it:
|
|
32
|
+
* - the signature, against the pinned keys for the production hub, or
|
|
33
|
+
* against the keys the hub at `base` publishes for any other address;
|
|
34
|
+
* - the receipt's issuer, against the hub's host;
|
|
35
|
+
* - with `text`, the deliverable against the hash the receipt records.
|
|
36
|
+
* `keys` are the hub's published keys; `pinned` overrides PINNED_KEYS (tests).
|
|
37
|
+
* Returns verifyReceipt's answer plus { trust, host, issuer, issuerMatches, verified }.
|
|
38
|
+
* `trust` is "pinned" or "published"; `verified` is the one answer to act on.
|
|
39
|
+
*/
|
|
40
|
+
export async function checkHostedReceipt(receipt, { base, keys, text, pinned = PINNED_KEYS } = {}) {
|
|
41
|
+
const url = new URL(base);
|
|
42
|
+
const host = url.host;
|
|
43
|
+
const pins = pinned[url.origin] || null;
|
|
44
|
+
let usable = Array.isArray(keys) ? keys : [];
|
|
45
|
+
if (pins) {
|
|
46
|
+
const fingerprints = await Promise.all(usable.map(keyFingerprint));
|
|
47
|
+
usable = usable.filter((_, index) => fingerprints[index] && pins.includes(fingerprints[index]));
|
|
48
|
+
}
|
|
49
|
+
const result = await verifyReceipt(receipt, usable, text);
|
|
50
|
+
if (pins && result.signed && !usable.some((key) => key.key_id === result.keyId)) {
|
|
51
|
+
result.problems = result.problems.map((problem) => (problem.startsWith('No published key with id') ? `Key ${result.keyId} is not one of the production keys pinned in this version of factoryhub.` : problem));
|
|
52
|
+
}
|
|
53
|
+
const issuer = receipt && typeof receipt === 'object' ? receipt.issuer ?? null : null;
|
|
54
|
+
const issuerMatches = issuer === host;
|
|
55
|
+
if (receipt?.kind === 'factory-run-receipt' && !issuerMatches) result.problems.push(`The receipt names its issuer as ${issuer === null ? 'nobody' : `"${issuer}"`}, not ${host}.`);
|
|
56
|
+
return { ...result, trust: pins ? 'pinned' : 'published', host, issuer, issuerMatches, verified: result.signatureValid && result.deliverableMatches !== false && issuerMatches };
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** One line for a person: what the receipt check found. */
|
|
60
|
+
export function receiptVerdict(verification) {
|
|
61
|
+
if (verification.verified) {
|
|
62
|
+
return verification.trust === 'pinned'
|
|
63
|
+
? `signature valid against a production key pinned in factoryhub (${verification.keyId})`
|
|
64
|
+
: `signature valid against keys published by ${verification.host}`;
|
|
65
|
+
}
|
|
66
|
+
return `not verified: ${verification.problems.join(' ') || 'unknown reason'}`;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/** Run states after which nothing more happens. */
|
|
70
|
+
export const FINISHED = new Set(['done', 'failed', 'stopped', 'expired', 'deleted', 'cancelled', 'canceled']);
|
|
71
|
+
const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
72
|
+
|
|
73
|
+
/** An Idempotency-Key for one start: the same key retried returns the same run. */
|
|
74
|
+
export const newIdempotencyKey = () => `fh-${randomUUID()}`;
|
|
75
|
+
|
|
76
|
+
/**
|
|
77
|
+
* Polls a run until it finishes or waits for a decision. Calls onEvent for
|
|
78
|
+
* every new event, in order. Returns the last run view.
|
|
79
|
+
*/
|
|
80
|
+
export async function followRun(hub, id, { onEvent = () => {}, sleep = wait, every = 2000, after = 0 } = {}) {
|
|
81
|
+
let cursor = after;
|
|
82
|
+
let shown = -1;
|
|
83
|
+
for (;;) {
|
|
84
|
+
const run = await hub.getRun(id, { after: cursor });
|
|
85
|
+
for (const event of run.events || []) {
|
|
86
|
+
if (Number.isInteger(event.i) && event.i <= shown) continue;
|
|
87
|
+
if (Number.isInteger(event.i)) shown = event.i;
|
|
88
|
+
await onEvent(event, run);
|
|
89
|
+
}
|
|
90
|
+
if (Number.isInteger(run.cursor) && run.cursor > cursor) cursor = run.cursor;
|
|
91
|
+
if (run.waiting || FINISHED.has(run.status)) return run;
|
|
92
|
+
await sleep(every);
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
const MAX_PAGES = 1000;
|
|
97
|
+
|
|
98
|
+
/**
|
|
99
|
+
* The whole result of a finished run, paged in, with the receipt checked
|
|
100
|
+
* here (checkHostedReceipt), not only by the hub. Returns null when the run
|
|
101
|
+
* is not done or the hub sent no result.
|
|
102
|
+
* Returns { text, receipt, verification, review, sha256 }.
|
|
103
|
+
*/
|
|
104
|
+
export async function runResult(hub, id, { keys, pinned } = {}) {
|
|
105
|
+
let run = await hub.getRun(id, { offset: 0 });
|
|
106
|
+
if (run?.status !== 'done' || !run.result || typeof run.result.text !== 'string') return null;
|
|
107
|
+
const receipt = run.receipt || null;
|
|
108
|
+
let text = run.result.text;
|
|
109
|
+
for (let pages = 1; Number.isInteger(run.result.nextOffset) && run.result.nextOffset > 0; pages += 1) {
|
|
110
|
+
if (pages >= MAX_PAGES) throw new Error(`The result of run ${id} did not end after ${MAX_PAGES} pages.`);
|
|
111
|
+
run = await hub.getRun(id, { offset: run.result.nextOffset });
|
|
112
|
+
if (!run?.result || typeof run.result.text !== 'string') throw new Error(`The hub stopped sending the result of run ${id} part way.`);
|
|
113
|
+
text += run.result.text;
|
|
114
|
+
}
|
|
115
|
+
const verification = receipt
|
|
116
|
+
? await checkHostedReceipt(receipt, { base: hub.base, keys: keys || await hub.keys(), text, pinned })
|
|
117
|
+
: { signed: false, signatureValid: false, deliverableMatches: null, keyId: null, trust: null, host: new URL(hub.base).host, issuer: null, issuerMatches: false, verified: false, problems: ['The hub sent no receipt.'] };
|
|
118
|
+
return { text, receipt, verification, review: receipt?.deliverable_review?.status || run.review || 'unknown', sha256: run.result.sha256 || null };
|
|
119
|
+
}
|