fito-tui 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +88 -0
- package/agents/fito-case-source-planner.md +265 -0
- package/agents/fito-performance-reviewer.md +231 -0
- package/agents/fito-practice-concept-content-generator.md +318 -0
- package/agents/fito-practice-concept-identifier.md +482 -0
- package/agents/fito-practice-execution-fact-content-generator.md +299 -0
- package/agents/fito-practice-execution-fact-identifier.md +367 -0
- package/agents/fito-practice-usage-scenario-content-generator.md +331 -0
- package/agents/fito-practice-usage-scenario-identifier.md +397 -0
- package/agents/fito-subagent-selftest.md +27 -0
- package/agents/fito-technology-generator.md +207 -0
- package/agents/fito-tool-concept-content-generator.md +282 -0
- package/agents/fito-tool-concept-identifier.md +384 -0
- package/agents/fito-tool-execution-fact-content-generator.md +382 -0
- package/agents/fito-tool-execution-fact-identifier.md +360 -0
- package/agents/fito-tool-usage-scenario-content-generator.md +381 -0
- package/agents/fito-tool-usage-scenario-identifier.md +432 -0
- package/agents/fito-tutor.md +185 -0
- package/extensions/fito-delegate.js +539 -0
- package/extensions/fito-delegate.ts +691 -0
- package/extensions/fito-fetch-tools.js +380 -0
- package/extensions/fito-fetch-tools.ts +419 -0
- package/extensions/fito-startup.js +166 -0
- package/extensions/fito-startup.ts +188 -0
- package/package.json +56 -0
- package/prompts/fito-auth-refresh.md +15 -0
- package/prompts/fito-case-design.md +506 -0
- package/prompts/fito-case-edit.md +91 -0
- package/prompts/fito-case-generate.md +222 -0
- package/prompts/fito-case-open.md +124 -0
- package/prompts/fito-case-plan-source.md +114 -0
- package/prompts/fito-create-or-update-competence.md +261 -0
- package/prompts/fito-create-or-update-technology.md +199 -0
- package/prompts/fito-delete-competence.md +147 -0
- package/prompts/fito-evaluate.md +148 -0
- package/prompts/fito-fetch-urls-content.md +35 -0
- package/prompts/fito-generate-domain-concepts.md +85 -0
- package/prompts/fito-generate-execution-facts.md +85 -0
- package/prompts/fito-generate-usage-scenarios.md +85 -0
- package/prompts/fito-identify-domain-concepts.md +49 -0
- package/prompts/fito-identify-execution-facts.md +49 -0
- package/prompts/fito-identify-usage-scenarios.md +49 -0
- package/prompts/fito-login.md +21 -0
- package/prompts/fito-logout.md +14 -0
- package/prompts/fito-publish-case.md +266 -0
- package/prompts/fito-push-knowledge.md +84 -0
- package/prompts/fito-submit.md +208 -0
- package/prompts/fito-tutor.md +120 -0
- package/shared/case-briefing/briefing.js +221 -0
- package/shared/case-briefing/briefing.ts +261 -0
- package/shared/case-quiz/scoring.js +16 -0
- package/shared/case-quiz/scoring.ts +61 -0
- package/shared/case-validation/case-loader.js +88 -0
- package/shared/case-validation/case-loader.ts +106 -0
- package/shared/case-validation/case-schema.js +716 -0
- package/shared/case-validation/case-schema.ts +895 -0
- package/shared/competences/competence-list.js +29 -0
- package/shared/competences/competence-list.ts +32 -0
- package/shared/fito-api/README.md +192 -0
- package/shared/fito-api/client.js +731 -0
- package/shared/fito-api/client.ts +1426 -0
- package/shared/fito-session/credentials.js +79 -0
- package/shared/fito-session/credentials.ts +88 -0
- package/shared/fito-session/session.js +16 -0
- package/shared/fito-session/session.ts +35 -0
- package/shared/github-url/parse.js +26 -0
- package/shared/github-url/parse.ts +35 -0
- package/shared/knowledge-components/component-names.js +35 -0
- package/shared/knowledge-components/component-names.ts +39 -0
- package/shared/knowledge-components/knowledge-fetch.js +46 -0
- package/shared/knowledge-components/knowledge-fetch.ts +57 -0
- package/shared/knowledge-components/knowledge-search.js +101 -0
- package/shared/knowledge-components/knowledge-search.ts +144 -0
- package/shared/knowledge-components/push-payload.js +104 -0
- package/shared/knowledge-components/push-payload.ts +129 -0
- package/shared/knowledge-components/reference.js +24 -0
- package/shared/knowledge-components/reference.ts +43 -0
- package/shared/knowledge-components/technology-fetch.js +30 -0
- package/shared/knowledge-components/technology-fetch.ts +38 -0
- package/shared/shell-exec/exec.js +22 -0
- package/shared/shell-exec/exec.ts +46 -0
- package/skills/fito-auth/SKILL.md +68 -0
- package/skills/fito-auth/auth-refresh.js +23 -0
- package/skills/fito-auth/auth-refresh.ts +25 -0
- package/skills/fito-auth/browser.js +35 -0
- package/skills/fito-auth/browser.ts +57 -0
- package/skills/fito-auth/callback-server.js +152 -0
- package/skills/fito-auth/callback-server.ts +189 -0
- package/skills/fito-auth/login.js +37 -0
- package/skills/fito-auth/login.ts +42 -0
- package/skills/fito-auth/logout.js +24 -0
- package/skills/fito-auth/logout.ts +25 -0
- package/skills/fito-case-author/SKILL.md +179 -0
- package/skills/fito-case-author/checkout.js +222 -0
- package/skills/fito-case-author/checkout.ts +281 -0
- package/skills/fito-case-author/github-publish.js +218 -0
- package/skills/fito-case-author/github-publish.ts +251 -0
- package/skills/fito-case-author/publish-payload.js +108 -0
- package/skills/fito-case-author/publish-payload.ts +186 -0
- package/skills/fito-case-author/publish-state.js +72 -0
- package/skills/fito-case-author/publish-state.ts +87 -0
- package/skills/fito-case-author/publish-version.js +364 -0
- package/skills/fito-case-author/publish-version.ts +495 -0
- package/skills/fito-case-author/publish.js +284 -0
- package/skills/fito-case-author/publish.ts +394 -0
- package/skills/fito-case-author/semver.js +55 -0
- package/skills/fito-case-author/semver.ts +63 -0
- package/skills/fito-case-author/status-gate.js +34 -0
- package/skills/fito-case-author/status-gate.ts +54 -0
- package/skills/fito-case-author/validate.js +62 -0
- package/skills/fito-case-author/validate.ts +64 -0
- package/skills/fito-case-runner/SKILL.md +119 -0
- package/skills/fito-case-runner/case-component-names.js +45 -0
- package/skills/fito-case-runner/case-component-names.ts +65 -0
- package/skills/fito-case-runner/case-detail.js +20 -0
- package/skills/fito-case-runner/case-detail.ts +20 -0
- package/skills/fito-case-runner/github.js +234 -0
- package/skills/fito-case-runner/github.ts +287 -0
- package/skills/fito-case-runner/manifest.js +56 -0
- package/skills/fito-case-runner/manifest.ts +73 -0
- package/skills/fito-case-runner/open.js +175 -0
- package/skills/fito-case-runner/open.ts +241 -0
- package/skills/fito-case-runner/report.js +22 -0
- package/skills/fito-case-runner/report.ts +24 -0
- package/skills/fito-case-runner/runner.js +158 -0
- package/skills/fito-case-runner/runner.ts +304 -0
- package/skills/fito-case-runner/score-quiz-mc.js +85 -0
- package/skills/fito-case-runner/score-quiz-mc.ts +99 -0
- package/skills/fito-case-runner/submit-evaluation.js +73 -0
- package/skills/fito-case-runner/submit-evaluation.ts +98 -0
- package/skills/fito-case-runner/submit-quiz-result.js +75 -0
- package/skills/fito-case-runner/submit-quiz-result.ts +100 -0
- package/skills/fito-case-runner/submit.js +85 -0
- package/skills/fito-case-runner/submit.ts +111 -0
- package/skills/fito-case-runner/workdir.js +10 -0
- package/skills/fito-case-runner/workdir.ts +11 -0
- package/skills/fito-competence-write/SKILL.md +155 -0
- package/skills/fito-competence-write/create.js +64 -0
- package/skills/fito-competence-write/create.ts +80 -0
- package/skills/fito-competence-write/delete.js +136 -0
- package/skills/fito-competence-write/delete.ts +166 -0
- package/skills/fito-competence-write/display.js +20 -0
- package/skills/fito-competence-write/display.ts +21 -0
- package/skills/fito-competence-write/payload.js +96 -0
- package/skills/fito-competence-write/payload.ts +115 -0
- package/skills/fito-competence-write/update.js +155 -0
- package/skills/fito-competence-write/update.ts +206 -0
- package/skills/fito-evaluator/SKILL.md +73 -0
- package/skills/fito-evaluator/criterion-exec.js +64 -0
- package/skills/fito-evaluator/criterion-exec.ts +73 -0
- package/skills/fito-evaluator/evaluate-automated.js +57 -0
- package/skills/fito-evaluator/evaluate-automated.ts +84 -0
- package/skills/fito-evaluator/evaluate.js +28 -0
- package/skills/fito-evaluator/evaluate.ts +86 -0
- package/skills/fito-evaluator/report.js +112 -0
- package/skills/fito-evaluator/report.ts +128 -0
- package/skills/fito-evaluator/rubric.js +90 -0
- package/skills/fito-evaluator/rubric.ts +170 -0
- package/skills/fito-knowledge-push/SKILL.md +114 -0
- package/skills/fito-knowledge-push/push.js +282 -0
- package/skills/fito-knowledge-push/push.ts +360 -0
- package/skills/fito-source-ingestion/SKILL.md +77 -0
- package/skills/fito-source-ingestion/authoring-check.js +128 -0
- package/skills/fito-source-ingestion/authoring-check.ts +155 -0
- package/skills/fito-source-ingestion/bundle.js +198 -0
- package/skills/fito-source-ingestion/bundle.ts +246 -0
- package/skills/fito-technology-write/SKILL.md +108 -0
- package/skills/fito-technology-write/create.js +134 -0
- package/skills/fito-technology-write/create.ts +161 -0
- package/skills/fito-technology-write/payload.js +64 -0
- package/skills/fito-technology-write/payload.ts +70 -0
- package/skills/fito-technology-write/update.js +122 -0
- package/skills/fito-technology-write/update.ts +171 -0
- package/skills/fito-url-content-fetcher/SKILL.md +213 -0
- package/templates/concept-practice-content-template.md +281 -0
- package/templates/concept-tool-content-template.md +207 -0
- package/templates/execution-fact-practice-content-template.md +372 -0
- package/templates/execution-fact-tool-content-template.md +307 -0
- package/templates/usage-scenario-content-template.md +248 -0
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `/fito-auth-refresh` CLI entrypoint. Exchanges the stored refresh token for a
|
|
3
|
+
* fresh token pair via the backend and rewrites `~/.fito/credentials`. Run from
|
|
4
|
+
* this skill's directory: `node auth-refresh.js`.
|
|
5
|
+
*/
|
|
6
|
+
import { createFitoApiClient } from "../../shared/fito-api/client.js";
|
|
7
|
+
import { readCredentials, writeCredentials } from "../../shared/fito-session/credentials.js";
|
|
8
|
+
async function main() {
|
|
9
|
+
const current = readCredentials();
|
|
10
|
+
if (!current) {
|
|
11
|
+
console.error("✗ Not logged in. Run /fito-login first.");
|
|
12
|
+
process.exitCode = 1;
|
|
13
|
+
return;
|
|
14
|
+
}
|
|
15
|
+
const tokens = await createFitoApiClient().refresh(current.refreshToken);
|
|
16
|
+
const credentials = { ...tokens, savedAt: new Date().toISOString() };
|
|
17
|
+
writeCredentials(credentials);
|
|
18
|
+
console.log("✓ Access token refreshed.");
|
|
19
|
+
}
|
|
20
|
+
main().catch((error) => {
|
|
21
|
+
console.error(`✗ Refresh failed: ${error instanceof Error ? error.message : String(error)}`);
|
|
22
|
+
process.exitCode = 1;
|
|
23
|
+
});
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `/fito-auth-refresh` CLI entrypoint. Exchanges the stored refresh token for a
|
|
3
|
+
* fresh token pair via the backend and rewrites `~/.fito/credentials`. Run from
|
|
4
|
+
* this skill's directory: `node auth-refresh.js`.
|
|
5
|
+
*/
|
|
6
|
+
import { createFitoApiClient } from "../../shared/fito-api/client.ts";
|
|
7
|
+
import { type Credentials, readCredentials, writeCredentials } from "../../shared/fito-session/credentials.ts";
|
|
8
|
+
|
|
9
|
+
async function main(): Promise<void> {
|
|
10
|
+
const current = readCredentials();
|
|
11
|
+
if (!current) {
|
|
12
|
+
console.error("✗ Not logged in. Run /fito-login first.");
|
|
13
|
+
process.exitCode = 1;
|
|
14
|
+
return;
|
|
15
|
+
}
|
|
16
|
+
const tokens = await createFitoApiClient().refresh(current.refreshToken);
|
|
17
|
+
const credentials: Credentials = { ...tokens, savedAt: new Date().toISOString() };
|
|
18
|
+
writeCredentials(credentials);
|
|
19
|
+
console.log("✓ Access token refreshed.");
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
main().catch((error: unknown) => {
|
|
23
|
+
console.error(`✗ Refresh failed: ${error instanceof Error ? error.message : String(error)}`);
|
|
24
|
+
process.exitCode = 1;
|
|
25
|
+
});
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import { spawn as nodeSpawn } from "node:child_process";
|
|
2
|
+
/** Resolve the platform-appropriate command to open `url` in the default browser. */
|
|
3
|
+
export function browserOpenCommand(platform, url) {
|
|
4
|
+
switch (platform) {
|
|
5
|
+
case "darwin":
|
|
6
|
+
return { command: "open", args: [url] };
|
|
7
|
+
case "win32":
|
|
8
|
+
// `start` is a cmd builtin; the empty "" is the (required) window-title arg.
|
|
9
|
+
return { command: "cmd", args: ["/c", "start", "", url] };
|
|
10
|
+
default:
|
|
11
|
+
return { command: "xdg-open", args: [url] };
|
|
12
|
+
}
|
|
13
|
+
}
|
|
14
|
+
/**
|
|
15
|
+
* Spawn `command` detached with stdio ignored so the TUI does not block on it.
|
|
16
|
+
* A launch failure (e.g. `xdg-open` not installed) surfaces as an async `error`
|
|
17
|
+
* event on the child; we attach a no-op listener so it stays non-fatal instead
|
|
18
|
+
* of becoming an `uncaughtException` that crashes the login flow.
|
|
19
|
+
*/
|
|
20
|
+
export function launchDetached(command, args) {
|
|
21
|
+
const child = nodeSpawn(command, args, { detached: true, stdio: "ignore" });
|
|
22
|
+
child.on("error", () => { });
|
|
23
|
+
return child;
|
|
24
|
+
}
|
|
25
|
+
/**
|
|
26
|
+
* Launch the default browser at `url`. The child is detached and its stdio
|
|
27
|
+
* ignored so the TUI does not block on it; failures to launch are non-fatal
|
|
28
|
+
* (the user can open the printed URL manually).
|
|
29
|
+
*/
|
|
30
|
+
export function openBrowser(url, options = {}) {
|
|
31
|
+
const platform = options.platform ?? process.platform;
|
|
32
|
+
const { command, args } = browserOpenCommand(platform, url);
|
|
33
|
+
const spawn = options.spawn ?? launchDetached;
|
|
34
|
+
spawn(command, args).unref();
|
|
35
|
+
}
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
import { type ChildProcess, spawn as nodeSpawn } from "node:child_process";
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Opens the system browser to a URL, used by `/fito-login` to send the learner to
|
|
5
|
+
* the web `/auth/login` page. The per-platform launch command is a pure function
|
|
6
|
+
* so it is unit-testable; `openBrowser` takes an injectable spawner so tests do
|
|
7
|
+
* not actually launch a browser. Pure Node module (no pi imports).
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
export type Platform = NodeJS.Platform;
|
|
11
|
+
|
|
12
|
+
export interface BrowserCommand {
|
|
13
|
+
command: string;
|
|
14
|
+
args: string[];
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
/** Resolve the platform-appropriate command to open `url` in the default browser. */
|
|
18
|
+
export function browserOpenCommand(platform: Platform, url: string): BrowserCommand {
|
|
19
|
+
switch (platform) {
|
|
20
|
+
case "darwin":
|
|
21
|
+
return { command: "open", args: [url] };
|
|
22
|
+
case "win32":
|
|
23
|
+
// `start` is a cmd builtin; the empty "" is the (required) window-title arg.
|
|
24
|
+
return { command: "cmd", args: ["/c", "start", "", url] };
|
|
25
|
+
default:
|
|
26
|
+
return { command: "xdg-open", args: [url] };
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export interface OpenBrowserOptions {
|
|
31
|
+
platform?: Platform;
|
|
32
|
+
spawn?: (command: string, args: string[]) => { unref(): void };
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* Spawn `command` detached with stdio ignored so the TUI does not block on it.
|
|
37
|
+
* A launch failure (e.g. `xdg-open` not installed) surfaces as an async `error`
|
|
38
|
+
* event on the child; we attach a no-op listener so it stays non-fatal instead
|
|
39
|
+
* of becoming an `uncaughtException` that crashes the login flow.
|
|
40
|
+
*/
|
|
41
|
+
export function launchDetached(command: string, args: string[]): ChildProcess {
|
|
42
|
+
const child = nodeSpawn(command, args, { detached: true, stdio: "ignore" });
|
|
43
|
+
child.on("error", () => {});
|
|
44
|
+
return child;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/**
|
|
48
|
+
* Launch the default browser at `url`. The child is detached and its stdio
|
|
49
|
+
* ignored so the TUI does not block on it; failures to launch are non-fatal
|
|
50
|
+
* (the user can open the printed URL manually).
|
|
51
|
+
*/
|
|
52
|
+
export function openBrowser(url: string, options: OpenBrowserOptions = {}): void {
|
|
53
|
+
const platform = options.platform ?? process.platform;
|
|
54
|
+
const { command, args } = browserOpenCommand(platform, url);
|
|
55
|
+
const spawn = options.spawn ?? launchDetached;
|
|
56
|
+
spawn(command, args).unref();
|
|
57
|
+
}
|
|
@@ -0,0 +1,152 @@
|
|
|
1
|
+
import * as crypto from "node:crypto";
|
|
2
|
+
import * as http from "node:http";
|
|
3
|
+
import { z } from "zod";
|
|
4
|
+
/**
|
|
5
|
+
* Local loopback HTTP server used by `/fito-login` to receive the freshly minted
|
|
6
|
+
* token pair from the browser. The web
|
|
7
|
+
* `/auth/login?return_to=tui&port=<port>&handoff_secret=<secret>` page POSTs the
|
|
8
|
+
* tokens here (cross-origin: web origin → `localhost:<port>`), so the server
|
|
9
|
+
* answers the browser's CORS preflight.
|
|
10
|
+
*
|
|
11
|
+
* Two gates protect the loopback against a malicious local page that guesses the
|
|
12
|
+
* ephemeral port: the browser must echo the single-use `secret` (minted by
|
|
13
|
+
* `/fito-login`) in the `X-Fito-Handoff-Secret` header — the primary gate — and
|
|
14
|
+
* CORS access is granted only to the configured `webOrigin` (defence in depth).
|
|
15
|
+
*
|
|
16
|
+
* Pure Node module (no pi imports) so it is unit-testable without a pi runtime.
|
|
17
|
+
* Plain HTTP on `localhost` is the dev handoff transport (ADR-003).
|
|
18
|
+
*/
|
|
19
|
+
/** The token pair the browser hands back. Matches the backend token response sans metadata. */
|
|
20
|
+
export const tokenPairSchema = z.object({
|
|
21
|
+
accessToken: z.string().min(1),
|
|
22
|
+
refreshToken: z.string().min(1),
|
|
23
|
+
expiresIn: z.number(),
|
|
24
|
+
tokenType: z.string().min(1),
|
|
25
|
+
});
|
|
26
|
+
function corsHeaders(req, webOrigin) {
|
|
27
|
+
const headers = {
|
|
28
|
+
"Access-Control-Allow-Methods": "POST, OPTIONS",
|
|
29
|
+
"Access-Control-Allow-Headers": "Content-Type, X-Fito-Handoff-Secret",
|
|
30
|
+
Vary: "Origin",
|
|
31
|
+
};
|
|
32
|
+
const origin = req.headers.origin;
|
|
33
|
+
if (webOrigin === undefined) {
|
|
34
|
+
headers["Access-Control-Allow-Origin"] = origin ?? "*";
|
|
35
|
+
}
|
|
36
|
+
else if (origin === webOrigin) {
|
|
37
|
+
headers["Access-Control-Allow-Origin"] = webOrigin;
|
|
38
|
+
}
|
|
39
|
+
return headers;
|
|
40
|
+
}
|
|
41
|
+
/** Constant-time comparison of the handoff secret; `false` on absence or length mismatch. */
|
|
42
|
+
function secretMatches(provided, expected) {
|
|
43
|
+
if (typeof provided !== "string")
|
|
44
|
+
return false;
|
|
45
|
+
const a = Buffer.from(provided);
|
|
46
|
+
const b = Buffer.from(expected);
|
|
47
|
+
return a.length === b.length && crypto.timingSafeEqual(a, b);
|
|
48
|
+
}
|
|
49
|
+
/** Hard cap on the request body. The token JSON is <200 bytes; anything larger is bogus. */
|
|
50
|
+
const MAX_BODY_BYTES = 8 * 1024;
|
|
51
|
+
async function readBody(req) {
|
|
52
|
+
const chunks = [];
|
|
53
|
+
let size = 0;
|
|
54
|
+
for await (const chunk of req) {
|
|
55
|
+
size += chunk.length;
|
|
56
|
+
if (size > MAX_BODY_BYTES)
|
|
57
|
+
throw new Error("payload_too_large");
|
|
58
|
+
chunks.push(chunk);
|
|
59
|
+
}
|
|
60
|
+
return Buffer.concat(chunks).toString("utf8");
|
|
61
|
+
}
|
|
62
|
+
/**
|
|
63
|
+
* Start the loopback callback server on an ephemeral port. The returned promise
|
|
64
|
+
* resolves once the server is listening; use {@link CallbackServer.waitForTokens}
|
|
65
|
+
* to await the browser handoff.
|
|
66
|
+
*/
|
|
67
|
+
export function startCallbackServer(options = {}) {
|
|
68
|
+
let resolveTokens;
|
|
69
|
+
let rejectTokens;
|
|
70
|
+
let settled = false;
|
|
71
|
+
const tokensPromise = new Promise((resolve, reject) => {
|
|
72
|
+
resolveTokens = resolve;
|
|
73
|
+
rejectTokens = reject;
|
|
74
|
+
});
|
|
75
|
+
// Avoid an unhandled-rejection warning if the caller never calls waitForTokens.
|
|
76
|
+
tokensPromise.catch(() => { });
|
|
77
|
+
const { webOrigin, secret } = options;
|
|
78
|
+
const server = http.createServer((req, res) => {
|
|
79
|
+
if (req.method === "OPTIONS") {
|
|
80
|
+
res.writeHead(204, corsHeaders(req, webOrigin));
|
|
81
|
+
res.end();
|
|
82
|
+
return;
|
|
83
|
+
}
|
|
84
|
+
if (req.method !== "POST") {
|
|
85
|
+
res.writeHead(405, corsHeaders(req, webOrigin));
|
|
86
|
+
res.end();
|
|
87
|
+
return;
|
|
88
|
+
}
|
|
89
|
+
// Primary gate: reject any POST that does not carry the single-use secret, before
|
|
90
|
+
// reading the body, so a page that guessed the port cannot inject tokens.
|
|
91
|
+
if (secret !== undefined && !secretMatches(req.headers["x-fito-handoff-secret"], secret)) {
|
|
92
|
+
res.writeHead(403, { ...corsHeaders(req, webOrigin), "Content-Type": "application/json" });
|
|
93
|
+
res.end(JSON.stringify({ error: "forbidden" }));
|
|
94
|
+
return;
|
|
95
|
+
}
|
|
96
|
+
readBody(req).then((raw) => {
|
|
97
|
+
let body;
|
|
98
|
+
try {
|
|
99
|
+
body = JSON.parse(raw);
|
|
100
|
+
}
|
|
101
|
+
catch {
|
|
102
|
+
body = null;
|
|
103
|
+
}
|
|
104
|
+
const parsed = tokenPairSchema.safeParse(body);
|
|
105
|
+
if (!parsed.success) {
|
|
106
|
+
res.writeHead(400, { ...corsHeaders(req, webOrigin), "Content-Type": "application/json" });
|
|
107
|
+
res.end(JSON.stringify({ error: "invalid_token_payload" }));
|
|
108
|
+
return;
|
|
109
|
+
}
|
|
110
|
+
res.writeHead(200, { ...corsHeaders(req, webOrigin), "Content-Type": "application/json" });
|
|
111
|
+
res.end(JSON.stringify({ status: "ok" }));
|
|
112
|
+
if (!settled) {
|
|
113
|
+
settled = true;
|
|
114
|
+
resolveTokens(parsed.data);
|
|
115
|
+
}
|
|
116
|
+
}).catch(() => {
|
|
117
|
+
// Over-large body (or a read error): reject this request but keep listening.
|
|
118
|
+
res.writeHead(413, { ...corsHeaders(req, webOrigin), "Content-Type": "application/json" });
|
|
119
|
+
res.end(JSON.stringify({ error: "payload_too_large" }));
|
|
120
|
+
});
|
|
121
|
+
});
|
|
122
|
+
let timer;
|
|
123
|
+
if (options.timeoutMs && options.timeoutMs > 0) {
|
|
124
|
+
timer = setTimeout(() => {
|
|
125
|
+
if (!settled) {
|
|
126
|
+
settled = true;
|
|
127
|
+
rejectTokens(new Error("Timed out waiting for the browser to return tokens."));
|
|
128
|
+
}
|
|
129
|
+
}, options.timeoutMs);
|
|
130
|
+
timer.unref();
|
|
131
|
+
}
|
|
132
|
+
return new Promise((resolve, reject) => {
|
|
133
|
+
server.once("error", reject);
|
|
134
|
+
server.listen(0, "127.0.0.1", () => {
|
|
135
|
+
const { port } = server.address();
|
|
136
|
+
resolve({
|
|
137
|
+
port,
|
|
138
|
+
url: `http://localhost:${port}`,
|
|
139
|
+
waitForTokens: () => tokensPromise,
|
|
140
|
+
close: () => {
|
|
141
|
+
if (timer)
|
|
142
|
+
clearTimeout(timer);
|
|
143
|
+
if (!settled) {
|
|
144
|
+
settled = true;
|
|
145
|
+
rejectTokens(new Error("Callback server closed before receiving tokens."));
|
|
146
|
+
}
|
|
147
|
+
server.close();
|
|
148
|
+
},
|
|
149
|
+
});
|
|
150
|
+
});
|
|
151
|
+
});
|
|
152
|
+
}
|
|
@@ -0,0 +1,189 @@
|
|
|
1
|
+
import * as crypto from "node:crypto";
|
|
2
|
+
import * as http from "node:http";
|
|
3
|
+
import type { AddressInfo } from "node:net";
|
|
4
|
+
|
|
5
|
+
import { z } from "zod";
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* Local loopback HTTP server used by `/fito-login` to receive the freshly minted
|
|
9
|
+
* token pair from the browser. The web
|
|
10
|
+
* `/auth/login?return_to=tui&port=<port>&handoff_secret=<secret>` page POSTs the
|
|
11
|
+
* tokens here (cross-origin: web origin → `localhost:<port>`), so the server
|
|
12
|
+
* answers the browser's CORS preflight.
|
|
13
|
+
*
|
|
14
|
+
* Two gates protect the loopback against a malicious local page that guesses the
|
|
15
|
+
* ephemeral port: the browser must echo the single-use `secret` (minted by
|
|
16
|
+
* `/fito-login`) in the `X-Fito-Handoff-Secret` header — the primary gate — and
|
|
17
|
+
* CORS access is granted only to the configured `webOrigin` (defence in depth).
|
|
18
|
+
*
|
|
19
|
+
* Pure Node module (no pi imports) so it is unit-testable without a pi runtime.
|
|
20
|
+
* Plain HTTP on `localhost` is the dev handoff transport (ADR-003).
|
|
21
|
+
*/
|
|
22
|
+
|
|
23
|
+
/** The token pair the browser hands back. Matches the backend token response sans metadata. */
|
|
24
|
+
export const tokenPairSchema = z.object({
|
|
25
|
+
accessToken: z.string().min(1),
|
|
26
|
+
refreshToken: z.string().min(1),
|
|
27
|
+
expiresIn: z.number(),
|
|
28
|
+
tokenType: z.string().min(1),
|
|
29
|
+
});
|
|
30
|
+
|
|
31
|
+
export type TokenPair = z.infer<typeof tokenPairSchema>;
|
|
32
|
+
|
|
33
|
+
export interface CallbackServer {
|
|
34
|
+
/** The ephemeral port the server bound to. */
|
|
35
|
+
readonly port: number;
|
|
36
|
+
/** `http://localhost:<port>` — the address the browser POSTs the tokens to. */
|
|
37
|
+
readonly url: string;
|
|
38
|
+
/** Resolves with the token pair once the browser POSTs it; rejects on timeout/close. */
|
|
39
|
+
waitForTokens(): Promise<TokenPair>;
|
|
40
|
+
/** Stop listening and reject any still-pending {@link waitForTokens}. */
|
|
41
|
+
close(): void;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export interface CallbackServerOptions {
|
|
45
|
+
/** Reject `waitForTokens` if no valid token pair arrives within this window. */
|
|
46
|
+
timeoutMs?: number;
|
|
47
|
+
/**
|
|
48
|
+
* Browser origin granted CORS access. Requests from any other origin are not
|
|
49
|
+
* given an `Access-Control-Allow-Origin`, so a browser blocks them. When unset,
|
|
50
|
+
* the request origin is echoed (test/back-compat only — production passes this).
|
|
51
|
+
*/
|
|
52
|
+
webOrigin?: string;
|
|
53
|
+
/**
|
|
54
|
+
* Single-use secret the browser must echo in `X-Fito-Handoff-Secret`. When set,
|
|
55
|
+
* a POST whose header does not match is rejected with 403 before the body is read.
|
|
56
|
+
*/
|
|
57
|
+
secret?: string;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
function corsHeaders(req: http.IncomingMessage, webOrigin?: string): Record<string, string> {
|
|
61
|
+
const headers: Record<string, string> = {
|
|
62
|
+
"Access-Control-Allow-Methods": "POST, OPTIONS",
|
|
63
|
+
"Access-Control-Allow-Headers": "Content-Type, X-Fito-Handoff-Secret",
|
|
64
|
+
Vary: "Origin",
|
|
65
|
+
};
|
|
66
|
+
const origin = req.headers.origin;
|
|
67
|
+
if (webOrigin === undefined) {
|
|
68
|
+
headers["Access-Control-Allow-Origin"] = origin ?? "*";
|
|
69
|
+
} else if (origin === webOrigin) {
|
|
70
|
+
headers["Access-Control-Allow-Origin"] = webOrigin;
|
|
71
|
+
}
|
|
72
|
+
return headers;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/** Constant-time comparison of the handoff secret; `false` on absence or length mismatch. */
|
|
76
|
+
function secretMatches(provided: string | string[] | undefined, expected: string): boolean {
|
|
77
|
+
if (typeof provided !== "string") return false;
|
|
78
|
+
const a = Buffer.from(provided);
|
|
79
|
+
const b = Buffer.from(expected);
|
|
80
|
+
return a.length === b.length && crypto.timingSafeEqual(a, b);
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/** Hard cap on the request body. The token JSON is <200 bytes; anything larger is bogus. */
|
|
84
|
+
const MAX_BODY_BYTES = 8 * 1024;
|
|
85
|
+
|
|
86
|
+
async function readBody(req: http.IncomingMessage): Promise<string> {
|
|
87
|
+
const chunks: Buffer[] = [];
|
|
88
|
+
let size = 0;
|
|
89
|
+
for await (const chunk of req) {
|
|
90
|
+
size += (chunk as Buffer).length;
|
|
91
|
+
if (size > MAX_BODY_BYTES) throw new Error("payload_too_large");
|
|
92
|
+
chunks.push(chunk as Buffer);
|
|
93
|
+
}
|
|
94
|
+
return Buffer.concat(chunks).toString("utf8");
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/**
|
|
98
|
+
* Start the loopback callback server on an ephemeral port. The returned promise
|
|
99
|
+
* resolves once the server is listening; use {@link CallbackServer.waitForTokens}
|
|
100
|
+
* to await the browser handoff.
|
|
101
|
+
*/
|
|
102
|
+
export function startCallbackServer(options: CallbackServerOptions = {}): Promise<CallbackServer> {
|
|
103
|
+
let resolveTokens!: (tokens: TokenPair) => void;
|
|
104
|
+
let rejectTokens!: (error: Error) => void;
|
|
105
|
+
let settled = false;
|
|
106
|
+
const tokensPromise = new Promise<TokenPair>((resolve, reject) => {
|
|
107
|
+
resolveTokens = resolve;
|
|
108
|
+
rejectTokens = reject;
|
|
109
|
+
});
|
|
110
|
+
// Avoid an unhandled-rejection warning if the caller never calls waitForTokens.
|
|
111
|
+
tokensPromise.catch(() => {});
|
|
112
|
+
|
|
113
|
+
const { webOrigin, secret } = options;
|
|
114
|
+
const server = http.createServer((req, res) => {
|
|
115
|
+
if (req.method === "OPTIONS") {
|
|
116
|
+
res.writeHead(204, corsHeaders(req, webOrigin));
|
|
117
|
+
res.end();
|
|
118
|
+
return;
|
|
119
|
+
}
|
|
120
|
+
if (req.method !== "POST") {
|
|
121
|
+
res.writeHead(405, corsHeaders(req, webOrigin));
|
|
122
|
+
res.end();
|
|
123
|
+
return;
|
|
124
|
+
}
|
|
125
|
+
// Primary gate: reject any POST that does not carry the single-use secret, before
|
|
126
|
+
// reading the body, so a page that guessed the port cannot inject tokens.
|
|
127
|
+
if (secret !== undefined && !secretMatches(req.headers["x-fito-handoff-secret"], secret)) {
|
|
128
|
+
res.writeHead(403, { ...corsHeaders(req, webOrigin), "Content-Type": "application/json" });
|
|
129
|
+
res.end(JSON.stringify({ error: "forbidden" }));
|
|
130
|
+
return;
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
readBody(req).then((raw) => {
|
|
134
|
+
let body: unknown;
|
|
135
|
+
try {
|
|
136
|
+
body = JSON.parse(raw);
|
|
137
|
+
} catch {
|
|
138
|
+
body = null;
|
|
139
|
+
}
|
|
140
|
+
const parsed = tokenPairSchema.safeParse(body);
|
|
141
|
+
if (!parsed.success) {
|
|
142
|
+
res.writeHead(400, { ...corsHeaders(req, webOrigin), "Content-Type": "application/json" });
|
|
143
|
+
res.end(JSON.stringify({ error: "invalid_token_payload" }));
|
|
144
|
+
return;
|
|
145
|
+
}
|
|
146
|
+
res.writeHead(200, { ...corsHeaders(req, webOrigin), "Content-Type": "application/json" });
|
|
147
|
+
res.end(JSON.stringify({ status: "ok" }));
|
|
148
|
+
if (!settled) {
|
|
149
|
+
settled = true;
|
|
150
|
+
resolveTokens(parsed.data);
|
|
151
|
+
}
|
|
152
|
+
}).catch(() => {
|
|
153
|
+
// Over-large body (or a read error): reject this request but keep listening.
|
|
154
|
+
res.writeHead(413, { ...corsHeaders(req, webOrigin), "Content-Type": "application/json" });
|
|
155
|
+
res.end(JSON.stringify({ error: "payload_too_large" }));
|
|
156
|
+
});
|
|
157
|
+
});
|
|
158
|
+
|
|
159
|
+
let timer: NodeJS.Timeout | undefined;
|
|
160
|
+
if (options.timeoutMs && options.timeoutMs > 0) {
|
|
161
|
+
timer = setTimeout(() => {
|
|
162
|
+
if (!settled) {
|
|
163
|
+
settled = true;
|
|
164
|
+
rejectTokens(new Error("Timed out waiting for the browser to return tokens."));
|
|
165
|
+
}
|
|
166
|
+
}, options.timeoutMs);
|
|
167
|
+
timer.unref();
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
return new Promise<CallbackServer>((resolve, reject) => {
|
|
171
|
+
server.once("error", reject);
|
|
172
|
+
server.listen(0, "127.0.0.1", () => {
|
|
173
|
+
const { port } = server.address() as AddressInfo;
|
|
174
|
+
resolve({
|
|
175
|
+
port,
|
|
176
|
+
url: `http://localhost:${port}`,
|
|
177
|
+
waitForTokens: () => tokensPromise,
|
|
178
|
+
close: () => {
|
|
179
|
+
if (timer) clearTimeout(timer);
|
|
180
|
+
if (!settled) {
|
|
181
|
+
settled = true;
|
|
182
|
+
rejectTokens(new Error("Callback server closed before receiving tokens."));
|
|
183
|
+
}
|
|
184
|
+
server.close();
|
|
185
|
+
},
|
|
186
|
+
});
|
|
187
|
+
});
|
|
188
|
+
});
|
|
189
|
+
}
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `/fito-login` CLI entrypoint. Starts a loopback server, opens the system
|
|
3
|
+
* browser to the web `/auth/login?return_to=tui&port=<port>` page, waits for the
|
|
4
|
+
* browser to POST the freshly minted token pair back, and writes it to
|
|
5
|
+
* `~/.fito/credentials` (0600). Run from this skill's directory: `node login.js`.
|
|
6
|
+
*/
|
|
7
|
+
import * as crypto from "node:crypto";
|
|
8
|
+
import { openBrowser } from "./browser.js";
|
|
9
|
+
import { startCallbackServer } from "./callback-server.js";
|
|
10
|
+
import { writeCredentials } from "../../shared/fito-session/credentials.js";
|
|
11
|
+
/** Web origin hosting the login page; overridable via `FITO_WEB_ORIGIN`. */
|
|
12
|
+
const WEB_ORIGIN = process.env.FITO_WEB_ORIGIN ?? "http://localhost:5173";
|
|
13
|
+
/** How long to wait for the browser handoff before giving up. */
|
|
14
|
+
const TIMEOUT_MS = 5 * 60 * 1000;
|
|
15
|
+
async function main() {
|
|
16
|
+
// Single-use secret binding this login to the browser handoff: the page must echo it
|
|
17
|
+
// back, so a malicious page that guesses the loopback port cannot inject tokens.
|
|
18
|
+
const secret = crypto.randomBytes(32).toString("base64url");
|
|
19
|
+
const server = await startCallbackServer({ timeoutMs: TIMEOUT_MS, webOrigin: WEB_ORIGIN, secret });
|
|
20
|
+
const loginUrl = `${WEB_ORIGIN}/auth/login?return_to=tui&port=${server.port}&handoff_secret=${secret}`;
|
|
21
|
+
console.log("Opening your browser to log in to Fito…");
|
|
22
|
+
console.log(`If it does not open, visit:\n ${loginUrl}\n`);
|
|
23
|
+
openBrowser(loginUrl);
|
|
24
|
+
try {
|
|
25
|
+
const tokens = await server.waitForTokens();
|
|
26
|
+
const credentials = { ...tokens, savedAt: new Date().toISOString() };
|
|
27
|
+
writeCredentials(credentials);
|
|
28
|
+
console.log("✓ Logged in. Credentials saved to ~/.fito/credentials (mode 0600).");
|
|
29
|
+
}
|
|
30
|
+
finally {
|
|
31
|
+
server.close();
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
main().catch((error) => {
|
|
35
|
+
console.error(`✗ Login failed: ${error instanceof Error ? error.message : String(error)}`);
|
|
36
|
+
process.exitCode = 1;
|
|
37
|
+
});
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `/fito-login` CLI entrypoint. Starts a loopback server, opens the system
|
|
3
|
+
* browser to the web `/auth/login?return_to=tui&port=<port>` page, waits for the
|
|
4
|
+
* browser to POST the freshly minted token pair back, and writes it to
|
|
5
|
+
* `~/.fito/credentials` (0600). Run from this skill's directory: `node login.js`.
|
|
6
|
+
*/
|
|
7
|
+
import * as crypto from "node:crypto";
|
|
8
|
+
|
|
9
|
+
import { openBrowser } from "./browser.ts";
|
|
10
|
+
import { startCallbackServer } from "./callback-server.ts";
|
|
11
|
+
import { type Credentials, writeCredentials } from "../../shared/fito-session/credentials.ts";
|
|
12
|
+
|
|
13
|
+
/** Web origin hosting the login page; overridable via `FITO_WEB_ORIGIN`. */
|
|
14
|
+
const WEB_ORIGIN = process.env.FITO_WEB_ORIGIN ?? "http://localhost:5173";
|
|
15
|
+
/** How long to wait for the browser handoff before giving up. */
|
|
16
|
+
const TIMEOUT_MS = 5 * 60 * 1000;
|
|
17
|
+
|
|
18
|
+
async function main(): Promise<void> {
|
|
19
|
+
// Single-use secret binding this login to the browser handoff: the page must echo it
|
|
20
|
+
// back, so a malicious page that guesses the loopback port cannot inject tokens.
|
|
21
|
+
const secret = crypto.randomBytes(32).toString("base64url");
|
|
22
|
+
const server = await startCallbackServer({ timeoutMs: TIMEOUT_MS, webOrigin: WEB_ORIGIN, secret });
|
|
23
|
+
const loginUrl = `${WEB_ORIGIN}/auth/login?return_to=tui&port=${server.port}&handoff_secret=${secret}`;
|
|
24
|
+
|
|
25
|
+
console.log("Opening your browser to log in to Fito…");
|
|
26
|
+
console.log(`If it does not open, visit:\n ${loginUrl}\n`);
|
|
27
|
+
openBrowser(loginUrl);
|
|
28
|
+
|
|
29
|
+
try {
|
|
30
|
+
const tokens = await server.waitForTokens();
|
|
31
|
+
const credentials: Credentials = { ...tokens, savedAt: new Date().toISOString() };
|
|
32
|
+
writeCredentials(credentials);
|
|
33
|
+
console.log("✓ Logged in. Credentials saved to ~/.fito/credentials (mode 0600).");
|
|
34
|
+
} finally {
|
|
35
|
+
server.close();
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
main().catch((error: unknown) => {
|
|
40
|
+
console.error(`✗ Login failed: ${error instanceof Error ? error.message : String(error)}`);
|
|
41
|
+
process.exitCode = 1;
|
|
42
|
+
});
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `/fito-logout` CLI entrypoint. Best-effort revokes the refresh token
|
|
3
|
+
* server-side, then deletes `~/.fito/credentials`. Idempotent: succeeds even when
|
|
4
|
+
* no credentials are present. Run from this skill's directory: `node logout.js`.
|
|
5
|
+
*/
|
|
6
|
+
import { createFitoApiClient } from "../../shared/fito-api/client.js";
|
|
7
|
+
import { deleteCredentials, readCredentials } from "../../shared/fito-session/credentials.js";
|
|
8
|
+
async function main() {
|
|
9
|
+
const credentials = readCredentials();
|
|
10
|
+
if (credentials) {
|
|
11
|
+
try {
|
|
12
|
+
await createFitoApiClient().logout(credentials.refreshToken);
|
|
13
|
+
}
|
|
14
|
+
catch {
|
|
15
|
+
// Already-invalid token or network error — clear locally regardless.
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
const removed = deleteCredentials();
|
|
19
|
+
console.log(removed ? "✓ Logged out. Credentials removed." : "Already logged out.");
|
|
20
|
+
}
|
|
21
|
+
main().catch((error) => {
|
|
22
|
+
console.error(`✗ Logout failed: ${error instanceof Error ? error.message : String(error)}`);
|
|
23
|
+
process.exitCode = 1;
|
|
24
|
+
});
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `/fito-logout` CLI entrypoint. Best-effort revokes the refresh token
|
|
3
|
+
* server-side, then deletes `~/.fito/credentials`. Idempotent: succeeds even when
|
|
4
|
+
* no credentials are present. Run from this skill's directory: `node logout.js`.
|
|
5
|
+
*/
|
|
6
|
+
import { createFitoApiClient } from "../../shared/fito-api/client.ts";
|
|
7
|
+
import { deleteCredentials, readCredentials } from "../../shared/fito-session/credentials.ts";
|
|
8
|
+
|
|
9
|
+
async function main(): Promise<void> {
|
|
10
|
+
const credentials = readCredentials();
|
|
11
|
+
if (credentials) {
|
|
12
|
+
try {
|
|
13
|
+
await createFitoApiClient().logout(credentials.refreshToken);
|
|
14
|
+
} catch {
|
|
15
|
+
// Already-invalid token or network error — clear locally regardless.
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
const removed = deleteCredentials();
|
|
19
|
+
console.log(removed ? "✓ Logged out. Credentials removed." : "Already logged out.");
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
main().catch((error: unknown) => {
|
|
23
|
+
console.error(`✗ Logout failed: ${error instanceof Error ? error.message : String(error)}`);
|
|
24
|
+
process.exitCode = 1;
|
|
25
|
+
});
|