fito-tui 0.9.2 → 0.10.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.
@@ -1,8 +1,10 @@
1
1
  import * as fs from "node:fs";
2
+ import * as os from "node:os";
2
3
  import * as path from "node:path";
3
4
  import { getShellConfig, } from "@earendil-works/pi-coding-agent";
4
5
  import packageJson from "../package.json" with { type: "json" };
5
6
  import { FitoApiError, createFitoApiClient } from "../shared/fito-api/client.js";
7
+ import { readSavedLogin } from "../shared/fito-session/credentials.js";
6
8
  import { fitoApiUrl } from "../shared/fito-url/fito-url.js";
7
9
  import { registerFitoDelegateTool } from "./fito-delegate.js";
8
10
  import { registerFitoCasePartialFetchTool, registerFitoCompetenceListTool, registerFitoKnowledgeFetchTool, registerFitoKnowledgeSearchTool, registerFitoTechnologyFetchTool, registerFitoTemplateFetchTool, } from "./fito-fetch-tools.js";
@@ -24,7 +26,8 @@ import { registerFitoCasePartialFetchTool, registerFitoCompetenceListTool, regis
24
26
  * What remains here is the `session_start` checks — the guard for the missing
25
27
  * `subagent` tool, the `pi-subagents` version floor, and the backend's refusal of this
26
28
  * TUI's version (both Task 15d.7b), and Bash on Windows (Task 17a.3) — the footer line
27
- * that names this Fito's version and API address (Task 17.26), and registration
29
+ * that names this Fito's version and API address (Task 17.26) and the account it is logged in as,
30
+ * read again after every tool call (Task 17.33), and registration
28
31
  * of Fito-owned custom tools (`pi.registerTool(...)`) for the **main**
29
32
  * session: `fito_knowledge_fetch` (Task 5.1b), the in-process knowledge-component
30
33
  * read that the `fito-tutor` worker holds while denied bash/filesystem (Success
@@ -75,6 +78,10 @@ import { registerFitoCasePartialFetchTool, registerFitoCompetenceListTool, regis
75
78
  */
76
79
  export default function registerFitoStartup(pi, options = {}) {
77
80
  const platform = options.platform ?? process.platform;
81
+ const home = options.home ?? os.homedir();
82
+ /** The footer line last set, so a tool call that changed nothing sets nothing (Task 17.33). */
83
+ let footerLine;
84
+ const currentFooterLine = (ctx) => fitoStatusLine(ctx.ui.theme, readSavedLogin(home));
78
85
  if (process.env.PI_SUBAGENT_CHILD !== "1") {
79
86
  registerFitoKnowledgeFetchTool(pi);
80
87
  registerFitoKnowledgeSearchTool(pi);
@@ -98,10 +105,12 @@ export default function registerFitoStartup(pi, options = {}) {
98
105
  }
99
106
  if (process.env.PI_SUBAGENT_CHILD === "1")
100
107
  return;
101
- // Which Fito runs and which API it uses, in the footer for the whole session (Task 17.26). It
102
- // is set at every start — `/new`, `/resume`, `/fork` and `/reload` included — and asks nothing
103
- // of the backend, so a backend that is down or slow neither delays it nor changes it.
104
- ctx.ui.setStatus("fito", fitoStatusLine(ctx.ui.theme));
108
+ // Which Fito runs, which API it uses (Task 17.26) and which account the saved login names
109
+ // (Task 17.33), in the footer for the whole session. It is set at every start — `/new`,
110
+ // `/resume`, `/fork` and `/reload` included — and asks nothing of the backend, so a backend
111
+ // that is down or slow neither delays it nor changes it.
112
+ footerLine = currentFooterLine(ctx);
113
+ ctx.ui.setStatus("fito", footerLine);
105
114
  if (subagent !== undefined && isBelowPiSubagentsFloor(subagent.sourceInfo)) {
106
115
  ctx.ui.notify(`Fito needs pi-subagents ${PI_SUBAGENTS_FLOOR.join(".")} or newer. Run: \`pi update --extensions\``, "error");
107
116
  }
@@ -115,6 +124,23 @@ export default function registerFitoStartup(pi, options = {}) {
115
124
  // Not awaited: pi awaits what a handler returns, so the start would wait for the backend.
116
125
  void warnIfTuiTooOld(ctx);
117
126
  });
127
+ // The account in the footer line follows a login or a logout as soon as its command ends (Task
128
+ // 17.33). `/fito-login`, `/fito-login-by-device`, `/fito-logout` and `/fito-auth-refresh` run
129
+ // their scripts through the bash tool, each as its own `node` process that cannot call this
130
+ // extension, so the saved login is read again when any tool call ends. A change made outside
131
+ // pi's tools — a `!` command, another terminal — shows at the next tool call or the next start.
132
+ // A subagent child shows no footer line, so it gets no handler.
133
+ if (process.env.PI_SUBAGENT_CHILD !== "1") {
134
+ pi.on("tool_execution_end", (_event, ctx) => {
135
+ if (!ctx.hasUI)
136
+ return;
137
+ const line = currentFooterLine(ctx);
138
+ if (line === footerLine)
139
+ return;
140
+ footerLine = line;
141
+ ctx.ui.setStatus("fito", line);
142
+ });
143
+ }
118
144
  }
119
145
  /**
120
146
  * The Fito mark's three ascending pills, each in its own colour, drawn in text because a terminal
@@ -133,13 +159,17 @@ function trueColour(hex, text) {
133
159
  return `\x1b[38;2;${rgb >> 16};${(rgb >> 8) & 255};${rgb & 255}m${text}\x1b[39m`;
134
160
  }
135
161
  /**
136
- * The footer line: the mark, then `Fito <version> · API <address>` in the theme's `dim` colour, as
137
- * pi's own footer lines are. The version is this package's, and the address is `fitoApiUrl()`, the
138
- * one every Fito call uses, so the line cannot disagree with the calls.
162
+ * The footer line: the mark, then `Fito <version> · API <address> · <account>` in the theme's `dim`
163
+ * colour, as pi's own footer lines are. The version is this package's, and the address is
164
+ * `fitoApiUrl()`, the one every Fito call uses, so the line cannot disagree with the calls. The
165
+ * account is the saved `login`'s (Task 17.33): `logged in as <username>`, `logged in` when its token
166
+ * names no account, or `not logged in` when no login is saved. pi cuts its line of statuses at its
167
+ * end, so a narrow terminal loses the account before the version and the address.
139
168
  */
140
- export function fitoStatusLine(theme, env = process.env) {
169
+ export function fitoStatusLine(theme, login, env = process.env) {
141
170
  const mark = MARK_PILLS.map(([pill, hex]) => trueColour(hex, pill)).join("");
142
- return `${mark} ${theme.fg("dim", `Fito ${packageJson.version} · API ${fitoApiUrl(env)}`)}`;
171
+ const account = login === null ? "not logged in" : login.username === undefined ? "logged in" : `logged in as ${login.username}`;
172
+ return `${mark} ${theme.fg("dim", `Fito ${packageJson.version} · API ${fitoApiUrl(env)} · ${account}`)}`;
143
173
  }
144
174
  /**
145
175
  * The oldest `pi-subagents` Fito works with (ADR-002 Decision 3, "Version floor"): Fito's personas
@@ -1,4 +1,5 @@
1
1
  import * as fs from "node:fs";
2
+ import * as os from "node:os";
2
3
  import * as path from "node:path";
3
4
 
4
5
  import {
@@ -11,6 +12,7 @@ import {
11
12
 
12
13
  import packageJson from "../package.json" with { type: "json" };
13
14
  import { FitoApiError, createFitoApiClient } from "../shared/fito-api/client.ts";
15
+ import { type SavedLogin, readSavedLogin } from "../shared/fito-session/credentials.ts";
14
16
  import { fitoApiUrl } from "../shared/fito-url/fito-url.ts";
15
17
  import { registerFitoDelegateTool } from "./fito-delegate.ts";
16
18
  import {
@@ -40,7 +42,8 @@ import {
40
42
  * What remains here is the `session_start` checks — the guard for the missing
41
43
  * `subagent` tool, the `pi-subagents` version floor, and the backend's refusal of this
42
44
  * TUI's version (both Task 15d.7b), and Bash on Windows (Task 17a.3) — the footer line
43
- * that names this Fito's version and API address (Task 17.26), and registration
45
+ * that names this Fito's version and API address (Task 17.26) and the account it is logged in as,
46
+ * read again after every tool call (Task 17.33), and registration
44
47
  * of Fito-owned custom tools (`pi.registerTool(...)`) for the **main**
45
48
  * session: `fito_knowledge_fetch` (Task 5.1b), the in-process knowledge-component
46
49
  * read that the `fito-tutor` worker holds while denied bash/filesystem (Success
@@ -91,9 +94,14 @@ import {
91
94
  */
92
95
  export default function registerFitoStartup(
93
96
  pi: ExtensionAPI,
94
- options: { platform?: NodeJS.Platform } = {},
97
+ options: { platform?: NodeJS.Platform; home?: string } = {},
95
98
  ): void {
96
99
  const platform = options.platform ?? process.platform;
100
+ const home = options.home ?? os.homedir();
101
+
102
+ /** The footer line last set, so a tool call that changed nothing sets nothing (Task 17.33). */
103
+ let footerLine: string | undefined;
104
+ const currentFooterLine = (ctx: ExtensionContext) => fitoStatusLine(ctx.ui.theme, readSavedLogin(home));
97
105
 
98
106
  if (process.env.PI_SUBAGENT_CHILD !== "1") {
99
107
  registerFitoKnowledgeFetchTool(pi);
@@ -123,10 +131,12 @@ export default function registerFitoStartup(
123
131
 
124
132
  if (process.env.PI_SUBAGENT_CHILD === "1") return;
125
133
 
126
- // Which Fito runs and which API it uses, in the footer for the whole session (Task 17.26). It
127
- // is set at every start — `/new`, `/resume`, `/fork` and `/reload` included — and asks nothing
128
- // of the backend, so a backend that is down or slow neither delays it nor changes it.
129
- ctx.ui.setStatus("fito", fitoStatusLine(ctx.ui.theme));
134
+ // Which Fito runs, which API it uses (Task 17.26) and which account the saved login names
135
+ // (Task 17.33), in the footer for the whole session. It is set at every start — `/new`,
136
+ // `/resume`, `/fork` and `/reload` included — and asks nothing of the backend, so a backend
137
+ // that is down or slow neither delays it nor changes it.
138
+ footerLine = currentFooterLine(ctx);
139
+ ctx.ui.setStatus("fito", footerLine);
130
140
 
131
141
  if (subagent !== undefined && isBelowPiSubagentsFloor(subagent.sourceInfo)) {
132
142
  ctx.ui.notify(
@@ -149,6 +159,22 @@ export default function registerFitoStartup(
149
159
  // Not awaited: pi awaits what a handler returns, so the start would wait for the backend.
150
160
  void warnIfTuiTooOld(ctx);
151
161
  });
162
+
163
+ // The account in the footer line follows a login or a logout as soon as its command ends (Task
164
+ // 17.33). `/fito-login`, `/fito-login-by-device`, `/fito-logout` and `/fito-auth-refresh` run
165
+ // their scripts through the bash tool, each as its own `node` process that cannot call this
166
+ // extension, so the saved login is read again when any tool call ends. A change made outside
167
+ // pi's tools — a `!` command, another terminal — shows at the next tool call or the next start.
168
+ // A subagent child shows no footer line, so it gets no handler.
169
+ if (process.env.PI_SUBAGENT_CHILD !== "1") {
170
+ pi.on("tool_execution_end", (_event, ctx: ExtensionContext) => {
171
+ if (!ctx.hasUI) return;
172
+ const line = currentFooterLine(ctx);
173
+ if (line === footerLine) return;
174
+ footerLine = line;
175
+ ctx.ui.setStatus("fito", line);
176
+ });
177
+ }
152
178
  }
153
179
 
154
180
  /**
@@ -170,16 +196,22 @@ function trueColour(hex: string, text: string): string {
170
196
  }
171
197
 
172
198
  /**
173
- * The footer line: the mark, then `Fito <version> · API <address>` in the theme's `dim` colour, as
174
- * pi's own footer lines are. The version is this package's, and the address is `fitoApiUrl()`, the
175
- * one every Fito call uses, so the line cannot disagree with the calls.
199
+ * The footer line: the mark, then `Fito <version> · API <address> · <account>` in the theme's `dim`
200
+ * colour, as pi's own footer lines are. The version is this package's, and the address is
201
+ * `fitoApiUrl()`, the one every Fito call uses, so the line cannot disagree with the calls. The
202
+ * account is the saved `login`'s (Task 17.33): `logged in as <username>`, `logged in` when its token
203
+ * names no account, or `not logged in` when no login is saved. pi cuts its line of statuses at its
204
+ * end, so a narrow terminal loses the account before the version and the address.
176
205
  */
177
206
  export function fitoStatusLine(
178
207
  theme: Pick<Theme, "fg">,
208
+ login: SavedLogin | null,
179
209
  env: Record<string, string | undefined> = process.env,
180
210
  ): string {
181
211
  const mark = MARK_PILLS.map(([pill, hex]) => trueColour(hex, pill)).join("");
182
- return `${mark} ${theme.fg("dim", `Fito ${packageJson.version} · API ${fitoApiUrl(env)}`)}`;
212
+ const account =
213
+ login === null ? "not logged in" : login.username === undefined ? "logged in" : `logged in as ${login.username}`;
214
+ return `${mark} ${theme.fg("dim", `Fito ${packageJson.version} · API ${fitoApiUrl(env)} · ${account}`)}`;
183
215
  }
184
216
 
185
217
  /**
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "fito-tui",
3
- "version": "0.9.2",
3
+ "version": "0.10.0",
4
4
  "description": "Fito for pi: case-based practice for software engineers, in your terminal.",
5
5
  "keywords": [
6
6
  "pi-package"
@@ -31,7 +31,7 @@
31
31
  },
32
32
  "dependencies": {
33
33
  "yaml": "2.9.0",
34
- "zod": "4.4.3"
34
+ "zod": "4.6.7"
35
35
  },
36
36
  "pi": {
37
37
  "extensions": [
@@ -0,0 +1,24 @@
1
+ ---
2
+ description: Log in to Fito with a code you approve in a browser (no localhost needed)
3
+ ---
4
+ Log the user in to Fito with a device code.
5
+
6
+ Use the `fito-auth` skill (read its `SKILL.md`), then run:
7
+
8
+ ```bash
9
+ node "<fito-auth skill dir>/login-by-device.js"
10
+ ```
11
+
12
+ The script prints Fito's `/device` address, a short code such as `WDJB-MJHT` and a
13
+ direct link, and tries to open the link in a browser. The user approves the code on
14
+ that page, from this computer or any other, and the script then writes this Fito's
15
+ `~/.fito/credentials-<host>`. Nothing calls `localhost`, so this login works over
16
+ SSH, in WSL or a VM, and where the browser blocks `localhost`.
17
+
18
+ Run the command in the foreground, so pi shows its output live: the user reads the
19
+ address and the code there while the script waits. Leave the bash tool's `timeout`
20
+ unset: the script waits for the approval as long as the code lives, and ends on its
21
+ own when the code expires.
22
+
23
+ When it prints the success line, confirm the user is logged in. When it fails,
24
+ report its error and suggest running `/fito-login-by-device` again.
@@ -40,6 +40,11 @@ const user = await api.me(accessToken); // GET /me -> SessionUser (+ linked
40
40
  const { user, tokens } = await api.meWithRefresh(storedTokens);
41
41
  // user.githubLogin / user.githubUserId are null when no GitHub identity is linked.
42
42
 
43
+ // POST /auth/device + POST /device-login/poll -> the device login (no token; Task 17.32): start one,
44
+ // then poll until the answer is { status: "approved", ...tokens } instead of { status: "pending" }.
45
+ const { deviceCode, userCode, expiresIn, interval } = await api.startDeviceLogin();
46
+ const answer = await api.pollDeviceLogin(deviceCode);
47
+
43
48
  // GET /knowledge/{type}/{slug} -> one component by (type, slug) (public read, no token):
44
49
  const component = await api.getKnowledgeComponent("concept", "git.bisect");
45
50
 
@@ -34,6 +34,25 @@ export const meResponseSchema = z.object({
34
34
  githubLogin: z.string().nullable().optional(),
35
35
  githubUserId: z.number().nullable().optional(),
36
36
  });
37
+ /**
38
+ * `POST /auth/device`'s answer, the start of a device login (Task 17.32): the long secret
39
+ * `deviceCode` the CLI polls with, the short `userCode` the user approves on the website
40
+ * (`WDJB-MJHT`), the code's lifetime and the wait between two polls, in seconds.
41
+ */
42
+ export const deviceLoginStartSchema = z.object({
43
+ deviceCode: z.string().min(1),
44
+ userCode: z.string().min(1),
45
+ expiresIn: z.number().int().positive(),
46
+ interval: z.number().int().positive(),
47
+ });
48
+ /**
49
+ * `POST /device-login/poll`'s answer: still waiting for the approval, or approved, with the token
50
+ * pair, which the backend sends once. A pending poll is a `200`, not RFC 8628's `400`.
51
+ */
52
+ export const deviceLoginPollSchema = z.discriminatedUnion("status", [
53
+ z.object({ status: z.literal("pending") }),
54
+ tokenResponseSchema.extend({ status: z.literal("approved") }),
55
+ ]);
37
56
  /** The backend's health answer (`GET /actuator/health`); `status` is `UP` or `DOWN`. */
38
57
  export const healthSchema = z.object({ status: z.string() });
39
58
  /** The component-type wire tokens, identical to the URL path segments. Mirrors `web/src/lib/api/knowledge.ts`. */
@@ -522,6 +541,11 @@ export function createFitoApiClient(options = {}) {
522
541
  return { user: await me(fresh.accessToken), tokens: fresh };
523
542
  }
524
543
  }
544
+ const startDeviceLogin = () => request("/auth/device", deviceLoginStartSchema, { method: "POST" });
545
+ const pollDeviceLogin = (deviceCode) => request("/device-login/poll", deviceLoginPollSchema, {
546
+ method: "POST",
547
+ body: JSON.stringify({ deviceCode }),
548
+ });
525
549
  const getHealth = (options = {}) => request("/actuator/health", healthSchema, { method: "GET", signal: options.signal });
526
550
  const getKnowledgeComponent = (type, slug, params = {}) => {
527
551
  const query = new URLSearchParams();
@@ -680,6 +704,8 @@ export function createFitoApiClient(options = {}) {
680
704
  logout,
681
705
  me,
682
706
  meWithRefresh,
707
+ startDeviceLogin,
708
+ pollDeviceLogin,
683
709
  getHealth,
684
710
  getKnowledgeComponent,
685
711
  searchKnowledgeComponents,
@@ -42,6 +42,29 @@ export const meResponseSchema = z.object({
42
42
  });
43
43
  export type SessionUser = z.infer<typeof meResponseSchema>;
44
44
 
45
+ /**
46
+ * `POST /auth/device`'s answer, the start of a device login (Task 17.32): the long secret
47
+ * `deviceCode` the CLI polls with, the short `userCode` the user approves on the website
48
+ * (`WDJB-MJHT`), the code's lifetime and the wait between two polls, in seconds.
49
+ */
50
+ export const deviceLoginStartSchema = z.object({
51
+ deviceCode: z.string().min(1),
52
+ userCode: z.string().min(1),
53
+ expiresIn: z.number().int().positive(),
54
+ interval: z.number().int().positive(),
55
+ });
56
+ export type DeviceLoginStart = z.infer<typeof deviceLoginStartSchema>;
57
+
58
+ /**
59
+ * `POST /device-login/poll`'s answer: still waiting for the approval, or approved, with the token
60
+ * pair, which the backend sends once. A pending poll is a `200`, not RFC 8628's `400`.
61
+ */
62
+ export const deviceLoginPollSchema = z.discriminatedUnion("status", [
63
+ z.object({ status: z.literal("pending") }),
64
+ tokenResponseSchema.extend({ status: z.literal("approved") }),
65
+ ]);
66
+ export type DeviceLoginPoll = z.infer<typeof deviceLoginPollSchema>;
67
+
45
68
  /** The backend's health answer (`GET /actuator/health`); `status` is `UP` or `DOWN`. */
46
69
  export const healthSchema = z.object({ status: z.string() });
47
70
  export type Health = z.infer<typeof healthSchema>;
@@ -730,6 +753,15 @@ export interface FitoApiClient {
730
753
  * the user and the (possibly refreshed) token pair so the caller can persist it.
731
754
  */
732
755
  meWithRefresh(tokens: TokenResponse): Promise<{ user: SessionUser; tokens: TokenResponse }>;
756
+ /**
757
+ * `POST /auth/device` — start a device login (Task 17.32). No login: the CLI holds no token yet.
758
+ */
759
+ startDeviceLogin(): Promise<DeviceLoginStart>;
760
+ /**
761
+ * `POST /device-login/poll` — whether the user approved the device login yet. No login. An
762
+ * unknown, expired or used device code is a 400 `FitoApiError`.
763
+ */
764
+ pollDeviceLogin(deviceCode: string): Promise<DeviceLoginPoll>;
733
765
  /**
734
766
  * `GET /actuator/health` — whether the backend is up. No login. The startup check calls it for
735
767
  * the backend's answer to this TUI's version (Task 15d.7b), and bounds the wait with `signal`.
@@ -1094,6 +1126,15 @@ export function createFitoApiClient(options: FitoApiClientOptions = {}): FitoApi
1094
1126
  }
1095
1127
  }
1096
1128
 
1129
+ const startDeviceLogin = (): Promise<DeviceLoginStart> =>
1130
+ request("/auth/device", deviceLoginStartSchema, { method: "POST" });
1131
+
1132
+ const pollDeviceLogin = (deviceCode: string): Promise<DeviceLoginPoll> =>
1133
+ request("/device-login/poll", deviceLoginPollSchema, {
1134
+ method: "POST",
1135
+ body: JSON.stringify({ deviceCode }),
1136
+ });
1137
+
1097
1138
  const getHealth = (options: { signal?: AbortSignal } = {}): Promise<Health> =>
1098
1139
  request("/actuator/health", healthSchema, { method: "GET", signal: options.signal });
1099
1140
 
@@ -1375,6 +1416,8 @@ export function createFitoApiClient(options: FitoApiClientOptions = {}): FitoApi
1375
1416
  logout,
1376
1417
  me,
1377
1418
  meWithRefresh,
1419
+ startDeviceLogin,
1420
+ pollDeviceLogin,
1378
1421
  getHealth,
1379
1422
  getKnowledgeComponent,
1380
1423
  searchKnowledgeComponents,
@@ -70,6 +70,34 @@ export function readCredentials(home = os.homedir(), url = fitoUrl()) {
70
70
  const parsed = credentialsSchema.safeParse(safeJsonParse(raw));
71
71
  return parsed.success ? parsed.data : null;
72
72
  }
73
+ /**
74
+ * The saved login of the Fito at `url`, read with no call to the backend: `null` when none is saved,
75
+ * as {@link readCredentials} reads the file, and otherwise the `username` claim of its access token.
76
+ * The claim is read from the token's payload (base64url JSON) **without checking the signature**: the
77
+ * footer line only shows the name, and the backend checks every token it is sent. A token that is
78
+ * not a JWT, or names no account, gives a login with no name. It never throws.
79
+ */
80
+ export function readSavedLogin(home = os.homedir(), url = fitoUrl()) {
81
+ let credentials;
82
+ try {
83
+ credentials = readCredentials(home, url);
84
+ }
85
+ catch {
86
+ return null;
87
+ }
88
+ return credentials === null ? null : { username: usernameClaim(credentials.accessToken) };
89
+ }
90
+ /** The `username` claim of a JWT's payload, or `undefined` when the token is no JWT or has none. */
91
+ function usernameClaim(token) {
92
+ const parts = token.split(".");
93
+ if (parts.length !== 3)
94
+ return undefined;
95
+ const claims = safeJsonParse(Buffer.from(parts[1], "base64url").toString("utf8"));
96
+ if (typeof claims !== "object" || claims === null)
97
+ return undefined;
98
+ const username = claims.username;
99
+ return typeof username === "string" && username !== "" ? username : undefined;
100
+ }
73
101
  /** Delete the credentials file. Returns `true` if a file was removed, `false` if absent. */
74
102
  export function deleteCredentials(home = os.homedir(), url = fitoUrl()) {
75
103
  const file = credentialsPath(home, url);
@@ -86,6 +86,39 @@ export function readCredentials(home: string = os.homedir(), url: string = fitoU
86
86
  return parsed.success ? parsed.data : null;
87
87
  }
88
88
 
89
+ /** The saved login of one Fito, as pi's footer line names it (Task 17.33). */
90
+ export type SavedLogin = {
91
+ /** The access token's `username` claim; `undefined` when the token names no account. */
92
+ username: string | undefined;
93
+ };
94
+
95
+ /**
96
+ * The saved login of the Fito at `url`, read with no call to the backend: `null` when none is saved,
97
+ * as {@link readCredentials} reads the file, and otherwise the `username` claim of its access token.
98
+ * The claim is read from the token's payload (base64url JSON) **without checking the signature**: the
99
+ * footer line only shows the name, and the backend checks every token it is sent. A token that is
100
+ * not a JWT, or names no account, gives a login with no name. It never throws.
101
+ */
102
+ export function readSavedLogin(home: string = os.homedir(), url: string = fitoUrl()): SavedLogin | null {
103
+ let credentials: Credentials | null;
104
+ try {
105
+ credentials = readCredentials(home, url);
106
+ } catch {
107
+ return null;
108
+ }
109
+ return credentials === null ? null : { username: usernameClaim(credentials.accessToken) };
110
+ }
111
+
112
+ /** The `username` claim of a JWT's payload, or `undefined` when the token is no JWT or has none. */
113
+ function usernameClaim(token: string): string | undefined {
114
+ const parts = token.split(".");
115
+ if (parts.length !== 3) return undefined;
116
+ const claims = safeJsonParse(Buffer.from(parts[1], "base64url").toString("utf8"));
117
+ if (typeof claims !== "object" || claims === null) return undefined;
118
+ const username = (claims as Record<string, unknown>).username;
119
+ return typeof username === "string" && username !== "" ? username : undefined;
120
+ }
121
+
89
122
  /** Delete the credentials file. Returns `true` if a file was removed, `false` if absent. */
90
123
  export function deleteCredentials(home: string = os.homedir(), url: string = fitoUrl()): boolean {
91
124
  const file = credentialsPath(home, url);
@@ -3,18 +3,19 @@ name: fito-auth
3
3
  description: >
4
4
  Authenticate the Fito TUI against the backend and manage the local credential
5
5
  store. Use when the learner wants to log in, log out, or refresh their Fito
6
- session — the /fito-login, /fito-logout, and /fito-auth-refresh commands — or
7
- when a command confirms the login before it writes to Fito.
6
+ session — the /fito-login, /fito-login-by-device, /fito-logout, and
7
+ /fito-auth-refresh commands — or when a command confirms the login before it
8
+ writes to Fito.
8
9
  allowed-tools: bash
9
10
  ---
10
11
 
11
12
  # Fito Auth
12
13
 
13
- Handles the browser-based login handoff and the token store: one credentials file
14
- per Fito, `~/.fito/credentials-<host>` (off Windows, file mode `0600` and dir
15
- `0700`). Backend access goes through the `fito-api` client (ADR-003); this skill
16
- never sees a password — the browser performs the login and hands back only the
17
- token pair.
14
+ Handles the two logins — the browser handoff and the device login — and the token
15
+ store: one credentials file per Fito, `~/.fito/credentials-<host>` (off Windows,
16
+ file mode `0600` and dir `0700`). Backend access goes through the `fito-api` client
17
+ (ADR-003); this skill never sees a password — the user logs in in the browser, and
18
+ the skill receives only the token pair.
18
19
 
19
20
  Run the commands from wherever you are — each one below names this
20
21
  skill's directory itself.
@@ -31,6 +32,21 @@ freshly minted token pair back. On success it writes this Fito's credentials fil
31
32
  and prints a confirmation that names it. The learner can complete either
32
33
  auth flow (email/password or "Continue with GitHub") in the browser.
33
34
 
35
+ ## Log in by device
36
+
37
+ ```bash
38
+ node "<fito-auth skill dir>/login-by-device.js"
39
+ ```
40
+
41
+ The login for a browser that cannot reach `localhost`: over SSH, in WSL or a VM,
42
+ or where the browser blocks the call. Starts a device login, prints Fito's
43
+ `/device` address with a short code and a direct link, and tries to open the link.
44
+ The user approves the code on that page, from any computer; the script polls
45
+ until then, writes this Fito's credentials file, and prints the same confirmation
46
+ as the login above. When the code expires first, it prints
47
+ `✗ The code expired. Run /fito-login-by-device again.` and exits non-zero. Run it
48
+ with the bash tool's `timeout` unset: it ends on its own when the code expires.
49
+
34
50
  ## Log out
35
51
 
36
52
  ```bash
@@ -66,7 +82,7 @@ first, so a logged-out author stops before any work.
66
82
  |---|---|
67
83
  | `callback-server.ts` | Loopback receiver for the browser token handoff (CORS) |
68
84
  | `browser.ts` | Per-platform system-browser launcher |
69
- | `login.ts` / `logout.ts` / `auth-refresh.ts` / `status.ts` | CLI entrypoints (above) |
85
+ | `login.ts` / `login-by-device.ts` / `logout.ts` / `auth-refresh.ts` / `status.ts` | CLI entrypoints (above) |
70
86
 
71
87
  The credentials store (read/write/delete, Zod-validated) lives in the
72
88
  shared [`fito-session`](../../shared/fito-session/credentials.ts) module, reused by `fito-case-runner`.
@@ -0,0 +1,98 @@
1
+ /**
2
+ * `/fito-login-by-device` CLI entrypoint (Task 17.32): a login that needs no `localhost`, for a
3
+ * browser that cannot call the CLI on this computer (a blocked browser, SSH, WSL, a VM). It starts
4
+ * a device login (RFC 8628), prints `<FITO_URL>/device` and the code, tries to open the direct link,
5
+ * and polls until the user approves the code on the website. Then it writes this Fito's
6
+ * `~/.fito/credentials-<host>`, as `/fito-login` does. No token passes through the browser.
7
+ * Run from this skill's directory: `node login-by-device.js`.
8
+ */
9
+ import * as os from "node:os";
10
+ import * as path from "node:path";
11
+ import { fileURLToPath } from "node:url";
12
+ import { openBrowser } from "./browser.js";
13
+ import { loginSuccessMessage } from "./login.js";
14
+ import { FitoApiError, createFitoApiClient, } from "../../shared/fito-api/client.js";
15
+ import { credentialsFileName, writeCredentials } from "../../shared/fito-session/credentials.js";
16
+ import { fitoUrl } from "../../shared/fito-url/fito-url.js";
17
+ /** How much longer each later poll waits after a `429` (RFC 8628 §3.5's `slow_down`; PLAN decision D3). */
18
+ const SLOW_DOWN_MS = 5000;
19
+ const EXPIRED_LINE = "✗ The code expired. Run /fito-login-by-device again.";
20
+ /** `600` as "10 minutes"; a lifetime that is not whole minutes, in seconds. */
21
+ function describeLifetime(seconds) {
22
+ if (seconds % 60 !== 0)
23
+ return `${seconds} seconds`;
24
+ const minutes = seconds / 60;
25
+ return minutes === 1 ? "1 minute" : `${minutes} minutes`;
26
+ }
27
+ /**
28
+ * Runs one device login and returns its exit code: `0` once the credentials are saved, `1` when the
29
+ * code expired. Any other failure throws, for the caller to report.
30
+ *
31
+ * The code has expired when this script's own clock passes its lifetime, or when the poll answers
32
+ * `400`. The backend refuses a code that is unknown, expired or used, and for the new code this
33
+ * script polls, and stops polling once it is used, only "expired" happens: the backend's clock can
34
+ * reach the end a little before this one.
35
+ */
36
+ export async function runDeviceLogin(options) {
37
+ const started = await options.client.startDeviceLogin();
38
+ const deadline = options.now() + started.expiresIn * 1000;
39
+ const approvalUrl = `${options.webOrigin}/device`;
40
+ const directLink = `${approvalUrl}?code=${encodeURIComponent(started.userCode)}`;
41
+ options.print(`Open ${approvalUrl} and confirm the code ${started.userCode}.`);
42
+ options.print(`Or open this link: ${directLink}`);
43
+ options.print(`The code expires in ${describeLifetime(started.expiresIn)}. Waiting for your approval…`);
44
+ try {
45
+ options.openBrowser(directLink);
46
+ }
47
+ catch {
48
+ // Best effort: over SSH or with no browser nothing opens, and the printed address is enough.
49
+ }
50
+ let waitMs = started.interval * 1000;
51
+ for (;;) {
52
+ await options.sleep(waitMs);
53
+ if (options.now() >= deadline)
54
+ break;
55
+ let answer;
56
+ try {
57
+ answer = await options.client.pollDeviceLogin(started.deviceCode);
58
+ }
59
+ catch (error) {
60
+ if (error instanceof FitoApiError && error.status === 429) {
61
+ waitMs += SLOW_DOWN_MS;
62
+ continue;
63
+ }
64
+ if (error instanceof FitoApiError && error.status === 400)
65
+ break;
66
+ throw error;
67
+ }
68
+ if (answer.status === "approved") {
69
+ const { status: _status, ...tokens } = answer;
70
+ writeCredentials({ ...tokens, savedAt: new Date(options.now()).toISOString() }, options.home, options.webOrigin);
71
+ options.print(loginSuccessMessage(credentialsFileName(options.webOrigin)));
72
+ return 0;
73
+ }
74
+ }
75
+ options.printError(EXPIRED_LINE);
76
+ return 1;
77
+ }
78
+ async function main() {
79
+ process.exitCode = await runDeviceLogin({
80
+ client: createFitoApiClient(),
81
+ webOrigin: fitoUrl(),
82
+ home: os.homedir(),
83
+ sleep: (ms) => new Promise((resolve) => setTimeout(resolve, ms)),
84
+ now: Date.now,
85
+ openBrowser: (url) => openBrowser(url),
86
+ print: (line) => console.log(line),
87
+ printError: (line) => console.error(line),
88
+ });
89
+ }
90
+ /** Only auto-invoke the CLI when run directly (`node login-by-device.js`), not when imported. */
91
+ const entry = process.argv[1];
92
+ const isMainModule = !!entry && path.resolve(entry) === fileURLToPath(import.meta.url);
93
+ if (isMainModule) {
94
+ main().catch((error) => {
95
+ console.error(`✗ Login failed: ${error instanceof Error ? error.message : String(error)}`);
96
+ process.exitCode = 1;
97
+ });
98
+ }
@@ -0,0 +1,119 @@
1
+ /**
2
+ * `/fito-login-by-device` CLI entrypoint (Task 17.32): a login that needs no `localhost`, for a
3
+ * browser that cannot call the CLI on this computer (a blocked browser, SSH, WSL, a VM). It starts
4
+ * a device login (RFC 8628), prints `<FITO_URL>/device` and the code, tries to open the direct link,
5
+ * and polls until the user approves the code on the website. Then it writes this Fito's
6
+ * `~/.fito/credentials-<host>`, as `/fito-login` does. No token passes through the browser.
7
+ * Run from this skill's directory: `node login-by-device.js`.
8
+ */
9
+ import * as os from "node:os";
10
+ import * as path from "node:path";
11
+ import { fileURLToPath } from "node:url";
12
+
13
+ import { openBrowser } from "./browser.ts";
14
+ import { loginSuccessMessage } from "./login.ts";
15
+ import {
16
+ type DeviceLoginPoll,
17
+ type FitoApiClient,
18
+ FitoApiError,
19
+ createFitoApiClient,
20
+ } from "../../shared/fito-api/client.ts";
21
+ import { credentialsFileName, writeCredentials } from "../../shared/fito-session/credentials.ts";
22
+ import { fitoUrl } from "../../shared/fito-url/fito-url.ts";
23
+
24
+ /** How much longer each later poll waits after a `429` (RFC 8628 §3.5's `slow_down`; PLAN decision D3). */
25
+ const SLOW_DOWN_MS = 5000;
26
+
27
+ const EXPIRED_LINE = "✗ The code expired. Run /fito-login-by-device again.";
28
+
29
+ export interface DeviceLoginOptions {
30
+ client: Pick<FitoApiClient, "startDeviceLogin" | "pollDeviceLogin">;
31
+ /** The address of the Fito the user approves on, which also names the credentials file. */
32
+ webOrigin: string;
33
+ home: string;
34
+ sleep: (ms: number) => Promise<void>;
35
+ now: () => number;
36
+ openBrowser: (url: string) => void;
37
+ print: (line: string) => void;
38
+ printError: (line: string) => void;
39
+ }
40
+
41
+ /** `600` as "10 minutes"; a lifetime that is not whole minutes, in seconds. */
42
+ function describeLifetime(seconds: number): string {
43
+ if (seconds % 60 !== 0) return `${seconds} seconds`;
44
+ const minutes = seconds / 60;
45
+ return minutes === 1 ? "1 minute" : `${minutes} minutes`;
46
+ }
47
+
48
+ /**
49
+ * Runs one device login and returns its exit code: `0` once the credentials are saved, `1` when the
50
+ * code expired. Any other failure throws, for the caller to report.
51
+ *
52
+ * The code has expired when this script's own clock passes its lifetime, or when the poll answers
53
+ * `400`. The backend refuses a code that is unknown, expired or used, and for the new code this
54
+ * script polls, and stops polling once it is used, only "expired" happens: the backend's clock can
55
+ * reach the end a little before this one.
56
+ */
57
+ export async function runDeviceLogin(options: DeviceLoginOptions): Promise<number> {
58
+ const started = await options.client.startDeviceLogin();
59
+ const deadline = options.now() + started.expiresIn * 1000;
60
+ const approvalUrl = `${options.webOrigin}/device`;
61
+ const directLink = `${approvalUrl}?code=${encodeURIComponent(started.userCode)}`;
62
+
63
+ options.print(`Open ${approvalUrl} and confirm the code ${started.userCode}.`);
64
+ options.print(`Or open this link: ${directLink}`);
65
+ options.print(`The code expires in ${describeLifetime(started.expiresIn)}. Waiting for your approval…`);
66
+ try {
67
+ options.openBrowser(directLink);
68
+ } catch {
69
+ // Best effort: over SSH or with no browser nothing opens, and the printed address is enough.
70
+ }
71
+
72
+ let waitMs = started.interval * 1000;
73
+ for (;;) {
74
+ await options.sleep(waitMs);
75
+ if (options.now() >= deadline) break;
76
+ let answer: DeviceLoginPoll;
77
+ try {
78
+ answer = await options.client.pollDeviceLogin(started.deviceCode);
79
+ } catch (error) {
80
+ if (error instanceof FitoApiError && error.status === 429) {
81
+ waitMs += SLOW_DOWN_MS;
82
+ continue;
83
+ }
84
+ if (error instanceof FitoApiError && error.status === 400) break;
85
+ throw error;
86
+ }
87
+ if (answer.status === "approved") {
88
+ const { status: _status, ...tokens } = answer;
89
+ writeCredentials({ ...tokens, savedAt: new Date(options.now()).toISOString() }, options.home, options.webOrigin);
90
+ options.print(loginSuccessMessage(credentialsFileName(options.webOrigin)));
91
+ return 0;
92
+ }
93
+ }
94
+ options.printError(EXPIRED_LINE);
95
+ return 1;
96
+ }
97
+
98
+ async function main(): Promise<void> {
99
+ process.exitCode = await runDeviceLogin({
100
+ client: createFitoApiClient(),
101
+ webOrigin: fitoUrl(),
102
+ home: os.homedir(),
103
+ sleep: (ms) => new Promise((resolve) => setTimeout(resolve, ms)),
104
+ now: Date.now,
105
+ openBrowser: (url) => openBrowser(url),
106
+ print: (line) => console.log(line),
107
+ printError: (line) => console.error(line),
108
+ });
109
+ }
110
+
111
+ /** Only auto-invoke the CLI when run directly (`node login-by-device.js`), not when imported. */
112
+ const entry = process.argv[1];
113
+ const isMainModule = !!entry && path.resolve(entry) === fileURLToPath(import.meta.url);
114
+ if (isMainModule) {
115
+ main().catch((error: unknown) => {
116
+ console.error(`✗ Login failed: ${error instanceof Error ? error.message : String(error)}`);
117
+ process.exitCode = 1;
118
+ });
119
+ }