Open
docs: 对齐对外站点与 AgentKit 文档 #19
docs: 对齐对外站点与 AgentKit 文档 #19
Open
jaxAdd on Oct 27
Total: 409 files changed+2052-65033
@@ -1,96 +1,4 @@
1-API_HOST=127.0.0.11+# Optional server-side model. You can also configure the model in the Web UI.
2-API_PORT=8787
3-WEB_HOST=127.0.0.1
4-WEB_PORT=3000
5- 
6-# LLM_* values are optional server-side defaults. Models can also be created in the Web UI after deploy.
7-LLM_PROVIDER=openai-compatible
8LLM_MODEL=qwen-plus2LLM_MODEL=qwen-plus
9LLM_BASE_URL=https://dashscope.aliyuncs.com/compatible-mode/v13LLM_BASE_URL=https://dashscope.aliyuncs.com/compatible-mode/v1
10LLM_API_KEY=4LLM_API_KEY=
11- 
12-# Optional Agent runtime limit overrides. Defaults and safe ranges are defined in
13-# packages/agent-runtime/src/config/agent-runtime-limits.ts.
14-# DATAFOUNDRY_AGENT_MAX_STEPS=80
15-# DATAFOUNDRY_SQL_MAX_EXECUTION_COUNT=60
16-# DATAFOUNDRY_DATA_ANALYSIS_MAX_PROTOCOL_ACTIONS=500
17-# DATAFOUNDRY_GENERAL_TASK_MAX_PROTOCOL_ACTIONS=100
18-# DATAFOUNDRY_PROTOCOL_DEFAULT_MAX_ACTIONS=100
19-# DATAFOUNDRY_PROTOCOL_MAX_COMPLETION_REJECTIONS=3
20-# DATAFOUNDRY_PROTOCOL_MAX_COMMIT_RETRIES=8
21-# DATAFOUNDRY_PROTOCOL_AUTOMATIC_ACTION_MAX_DEPTH=10
22-# DATAFOUNDRY_SCHEMA_MAX_TABLES=20
23-# DATAFOUNDRY_SCHEMA_MAX_COLUMNS_PER_TABLE=50
24-# DATAFOUNDRY_SQL_MAX_MODEL_ROWS=20
25-# DATAFOUNDRY_SQL_MAX_ACTIVITY_ROWS=20
26-# DATAFOUNDRY_SQL_MAX_CELL_CHARS=500
27-# DATAFOUNDRY_SQL_MAX_SQL_CHARS=4000
28-# DATAFOUNDRY_CONTEXT_MAX_TOKENS=32000
29-# DATAFOUNDRY_CONTEXT_MAX_CHARS=32000
30-# DATAFOUNDRY_TOOL_ERROR_MAX_MESSAGE_CHARS=500
31-# DATAFOUNDRY_KNOWLEDGE_MAX_TOP_K=20
32-# DATAFOUNDRY_REQUIREMENT_COMMIT_MAX_CLAIMS=16
33-# DATAFOUNDRY_REQUIREMENT_COMMIT_MAX_OUTPUT_FIELDS=32
34-# DATAFOUNDRY_MODEL_HELPER_MAX_STEPS=1
35-# DATAFOUNDRY_PROTOCOL_CLASSIFIER_MAX_OUTPUT_TOKENS=512
36-# DATAFOUNDRY_REQUIREMENT_EXTRACTOR_MAX_OUTPUT_TOKENS=4096
37-# DATAFOUNDRY_CONTRACT_GROUNDER_MAX_OUTPUT_TOKENS=8192
38-# DATAFOUNDRY_CONTRACT_GROUNDER_MAX_ATTEMPTS=2
39-# DATAFOUNDRY_TOOL_OBSERVATION_MAX_NAMES=5
40-# DATAFOUNDRY_TOOL_OBSERVATION_MAX_NAME_CHARS=120
41-# DATAFOUNDRY_TOOL_OBSERVATION_MAX_CHARS=12000
42- 
43-EMBEDDING_PROVIDER=bailian
44-EMBEDDING_MODEL=text-embedding-v4
45-EMBEDDING_DIM=1024
46-EMBEDDING_OUTPUT_TYPE=dense
47-EMBEDDING_BASE_URL=https://dashscope.aliyuncs.com/compatible-mode/v1
48-EMBEDDING_API_KEY=
49- 
50-# Agent execute_command sandbox: Python venv with numpy/pandas/matplotlib/scikit-learn.
51-# Default auto-detects repo `.venv` (also checks npm INIT_CWD). Override with absolute path:
52-# WORKSPACE_PYTHON_VENV=/path/to/DataFoundry/.venv
53-# WORKSPACE_COMMAND_TIMEOUT_MS=120000
54- 
55-STORAGE_ROOT_DIR=storage
56-METADATA_DB_PATH=storage/metadata/workbench.sqlite
57-SECRET_MASTER_KEY=replace-with-a-long-random-local-key
58- 
59-# ---------------------------------------------------------------------------
60-# Formal deploy (default): password + build/start. Do NOT use npm run dev here.
61-#
62-#
63-# Two formal environments share the same start commands; differ mainly here:
64-#
65-# Formal test (local / private acceptance):
66-# AUTH_PUBLIC_BASE_URL=http://127.0.0.1:3000
67-# AUTH_EMAIL_DELIVERY=test # verification links → API console
68-#
69-# Real production (public service):
70-# AUTH_PUBLIC_BASE_URL=https://datafoundry.example.com
71-# AUTH_EMAIL_DELIVERY=smtp # fill AUTH_SMTP_* below
72-# + reverse proxy: deploy/nginx.datafoundry.conf.example
73-#
74-# ---------------------------------------------------------------------------
75-AUTH_SESSION_SECRET=replace-with-at-least-32-random-characters
76-AUTH_PUBLIC_BASE_URL=http://127.0.0.1:3000
77-# Required in password mode (open|closed). open = self-register; closed = REGISTRATION_CLOSED.
78-# Exposed via GET /api/v1/auth/status (no secrets). Do not use AUTH_EMAIL_DELIVERY=test
79-# with a non-loopback AUTH_PUBLIC_BASE_URL.
80-AUTH_REGISTRATION_MODE=open
81-# Required when set: only smtp|test. test = log links to console; smtp = send real email.
82-AUTH_EMAIL_DELIVERY=test
83-AUTH_EMAIL_FROM=DataFoundry <no-reply@example.com>
84-AUTH_SMTP_HOST=smtp.example.com
85-AUTH_SMTP_PORT=587
86-AUTH_SMTP_SECURE=false
87-AUTH_SMTP_USER=
88-AUTH_SMTP_PASSWORD=
89- 
90-# Next.js BFF (apps/web) → API. Set this in apps/web/.env.local (not required in root .env).
91-# Used in password / formal mode when the browser calls same-origin `/api/v1/*` and `/api/copilotkit`.
92-# API_PROXY_TARGET=http://127.0.0.1:8787
93- 
94-SQL_DEFAULT_LIMIT=100
95-SQL_MAX_LIMIT=1000
96-SQL_TIMEOUT_MS=10000
@@ -37,20 +37,14 @@ jobs:
37 - name: Install dependencies37 - name: Install dependencies
38 run: npm ci38 run: npm ci
39 39 
40- - name: Build TypeScript workspaces
41- run: npm run build
42- 
43- - name: Run package unit tests
44- run: npm run test:packages
45- 
46 - name: Run Web tests40 - name: Run Web tests
47 run: npm run test:web41 run: npm run test:web
48 42 
49 - name: Run TUI unit tests43 - name: Run TUI unit tests
50- run: npm --workspace @datafoundry/tui test44+ run: npm run test:tui
51 45 
52- - name: Build Web application46+ - name: Build web and TUI
53- run: npm run build:web47+ run: npm run build
54 48 
55 native-deploy-smoke:49 native-deploy-smoke:
56 name: Native Deploy Smoke50 name: Native Deploy Smoke
@@ -10,11 +10,13 @@ Thanks for helping improve this project.
10 10 
11## Local Setup11## Local Setup
12 12 
13+Node.js 22+ and uv are required. `npm install` syncs the AgentKit Python environment. `npm run build` compiles the web app and TUI.
14+ 
13```bash15```bash
14npm install16npm install
15cp .env.example .env17cp .env.example .env
16-cp apps/web/.env.example apps/web/.env.local18+npm run build
17-npm run dev19+npm run start
18```20```
19 21 
20Open the workbench at <http://127.0.0.1:3000/data-tasks>.22Open the workbench at <http://127.0.0.1:3000/data-tasks>.
MMakefile+6-11
@@ -1,7 +1,7 @@
1# 开发:make prepare && make build && make test。出包:make prepare && make package && make start。1# 开发:make prepare && make build && make test。出包:make prepare && make package && make start。
2-# prepare 装 devDependencies 和 agentkit;build 只编测试用的 TS/API/TUI;package 再加 build:web。2+# prepare 执行 npm ci。安装后的同步只装 agentkit 运行依赖,不含 pytest/ruff;读 UV_PYTHON,默认 3.12,且不受 SKIP_POSTINSTALL_BUILD 影响。build 编译网页和 TUI。
3# 不另写启动器、不生成密钥、不打 agentkit wheel。编译不 omit=dev、也不 prune,node_modules 仍含构建期依赖。3# 不另写启动器、不生成密钥、不打 agentkit wheel。编译不 omit=dev、也不 prune,node_modules 仍含构建期依赖。
4-# make start 没有 Make 变量,只调用 ./deploy.sh start:缺 .env 不会启动,缺 apps/web/.env.local 就按 .env 补上。4+# make start 没有 Make 变量,只调用 ./deploy.sh start:缺 .env 或网页构建结果不会启动。
5# ut/st 目标名覆盖 TIER:make ut TIER=st 仍跑 ut。范围目标才读 TIER,默认 test;不写 TIER 时 make test 一起跑 ut 和 st。5# ut/st 目标名覆盖 TIER:make ut TIER=st 仍跑 ut。范围目标才读 TIER,默认 test;不写 TIER 时 make test 一起跑 ut 和 st。
6# make st 与 make test 的系统测试不能带 -n/--numprocesses(含 -n4、--numprocesses=4):st 直接失败,test 去掉后仍串行,单元测试可以带。6# make st 与 make test 的系统测试不能带 -n/--numprocesses(含 -n4、--numprocesses=4):st 直接失败,test 去掉后仍串行,单元测试可以带。
7# PYTEST_ARGS 里的 $ 用单引号:make ut PYTEST_ARGS='-k $HOME'。不要写成 $$。make test 时 -k 同时过滤 ut 和 st。7# PYTEST_ARGS 里的 $ 用单引号:make ut PYTEST_ARGS='-k $HOME'。不要写成 $$。make test 时 -k 同时过滤 ut 和 st。
@@ -34,7 +34,7 @@ ifeq ($(OS),Windows_NT)
34 SHELL := bash.exe34 SHELL := bash.exe
35endif35endif
36 36 
37-.PHONY: ut st test prepare build package start agentkit api web tui packages deploy37+.PHONY: ut st test prepare build package start agentkit api web tui deploy
38 38 
39# 例:make test UV_RUN_OPTS=--no-sync(只跳过套件里的再次同步)。39# 例:make test UV_RUN_OPTS=--no-sync(只跳过套件里的再次同步)。
40UV := uv run --project "$(PROJECT_DIR)/runtime/agentkit" --python "$(PYTHON_VERSION)" python40UV := uv run --project "$(PROJECT_DIR)/runtime/agentkit" --python "$(PYTHON_VERSION)" python
@@ -48,25 +48,20 @@ ut st test:
48 cd "$(PROJECT_DIR)" && $(UV) scripts/run_product_tests.py --tier $(if $(filter ut st,$(MAKECMDGOALS)),$@,$(TIER)) $(if $(SCOPE),--scope "$(SCOPE)") --pytest-args='$(PYTEST_ARGS)' --node-test-args='$(NODE_TEST_ARGS)' $(UV_RUN_OPTS)48 cd "$(PROJECT_DIR)" && $(UV) scripts/run_product_tests.py --tier $(if $(filter ut st,$(MAKECMDGOALS)),$@,$(TIER)) $(if $(SCOPE),--scope "$(SCOPE)") --pytest-args='$(PYTEST_ARGS)' --node-test-args='$(NODE_TEST_ARGS)' $(UV_RUN_OPTS)
49 49 
50prepare:50prepare:
51- cd "$(PROJECT_DIR)" && uv sync --project runtime/agentkit --python "$(PYTHON_VERSION)"
52ifdef NPM_REGISTRY51ifdef NPM_REGISTRY
53- cd "$(PROJECT_DIR)" && npm ci --engine-strict=false --registry "$(NPM_REGISTRY)"52+ cd "$(PROJECT_DIR)" && env -u SKIP_POSTINSTALL_BUILD npm ci --engine-strict=false --registry "$(NPM_REGISTRY)"
54else53else
55- cd "$(PROJECT_DIR)" && npm ci --engine-strict=false54+ cd "$(PROJECT_DIR)" && env -u SKIP_POSTINSTALL_BUILD npm ci --engine-strict=false
56endif55endif
57 56 
58-# 不含 Next 生产构建。
59build:57build:
60 cd "$(PROJECT_DIR)" && npm run build58 cd "$(PROJECT_DIR)" && npm run build
61- cd "$(PROJECT_DIR)" && npm run build:tui
62 59 
63-# make packages 仍是测试范围。
64package: build60package: build
65- cd "$(PROJECT_DIR)" && npm run build:web
66 61 
67start:62start:
68 cd "$(PROJECT_DIR)" && ./deploy.sh start63 cd "$(PROJECT_DIR)" && ./deploy.sh start
69 64 
70# 该 scope 没有 st 用例时仍非 0 退出。65# 该 scope 没有 st 用例时仍非 0 退出。
71-agentkit api web tui packages deploy:66+agentkit api web tui deploy:
72 cd "$(PROJECT_DIR)" && $(UV) scripts/run_product_tests.py --tier $(TIER) --scope $@ --pytest-args='$(PYTEST_ARGS)' --node-test-args='$(NODE_TEST_ARGS)' $(UV_RUN_OPTS)67 cd "$(PROJECT_DIR)" && $(UV) scripts/run_product_tests.py --tier $(TIER) --scope $@ --pytest-args='$(PYTEST_ARGS)' --node-test-args='$(NODE_TEST_ARGS)' $(UV_RUN_OPTS)
MREADME.md+9-27
@@ -32,7 +32,6 @@
32 <img src="https://img.shields.io/badge/PRs-welcome-ff69b4" alt="PRs welcome" />32 <img src="https://img.shields.io/badge/PRs-welcome-ff69b4" alt="PRs welcome" />
33 <img src="https://img.shields.io/badge/status-early%20but%20usable-orange" alt="Status" />33 <img src="https://img.shields.io/badge/status-early%20but%20usable-orange" alt="Status" />
34 <br />34 <br />
35- <a href="https://github.com/mastra-ai/mastra"><img src="https://img.shields.io/badge/Mastra-agent%20runtime-111827" alt="Mastra agent runtime" /></a>
36 <a href="https://github.com/ag-ui-protocol/ag-ui"><img src="https://img.shields.io/badge/AG--UI-event%20stream-6f42c1" alt="AG-UI event stream" /></a>35 <a href="https://github.com/ag-ui-protocol/ag-ui"><img src="https://img.shields.io/badge/AG--UI-event%20stream-6f42c1" alt="AG-UI event stream" /></a>
37 <a href="https://github.com/vadimdemedes/ink"><img src="https://img.shields.io/badge/Ink-terminal%20UI-0f766e" alt="Ink terminal UI" /></a>36 <a href="https://github.com/vadimdemedes/ink"><img src="https://img.shields.io/badge/Ink-terminal%20UI-0f766e" alt="Ink terminal UI" /></a>
38</p>37</p>
@@ -71,7 +70,7 @@ See the [v0.2.0 release notes](docs/en/releases/v0.2.0.md) for the complete capa
71 70 
72## 🚀 Formal deploy71## 🚀 Formal deploy
73 72 
74-Formal mode has two paths (do **not** run `npm run dev`). Docker / Compose is not provided in this release.73+Formal mode has two paths. Docker / Compose is not provided in this release.
75 74 
76### Recommended: Ubuntu / Debian one-click75### Recommended: Ubuntu / Debian one-click
77 76 
@@ -100,7 +99,7 @@ Common management commands:
100./deploy.sh tui # optional: foreground TUI client (API must already be up)99./deploy.sh tui # optional: foreground TUI client (API must already be up)
101```100```
102 101 
103-Open `http://127.0.0.1:3000/login`, register or sign in, create an OpenAI-compatible model profile, then go to `/data-tasks`. For remote hosts set `AUTH_PUBLIC_BASE_URL`. Re-running `./deploy.sh deploy` uses a maintenance window (stop the managed process group before install/build).102+Open `http://127.0.0.1:3000/data-tasks`. The model comes from `.env` or the Home `config.json`. Re-running `./deploy.sh deploy` uses a maintenance window (stop the managed process group before install/build).
104 103 
105### Windows / macOS / other: manual npm104### Windows / macOS / other: manual npm
106 105 
@@ -111,40 +110,24 @@ git clone https://github.com/datagallery-lab/datafoundry.git
111cd datafoundry110cd datafoundry
112npm install111npm install
113cp .env.example .env112cp .env.example .env
114-cp apps/web/.env.example apps/web/.env.local
115```113```
116 114 
117-Configure any OpenAI-compatible model in the root `.env`, plus auth for formal test or real production (sample defaults lean formal test):115+Configure an optional server-side model in the root `.env` (you can also configure the model only in the Web UI):
118 116 
119```bash117```bash
120-LLM_PROVIDER=openai-compatible
121LLM_MODEL=qwen-plus # or deepseek-chat, gpt-4o, ...118LLM_MODEL=qwen-plus # or deepseek-chat, gpt-4o, ...
122LLM_BASE_URL=https://dashscope.aliyuncs.com/compatible-mode/v1119LLM_BASE_URL=https://dashscope.aliyuncs.com/compatible-mode/v1
123LLM_API_KEY=replace-with-your-key120LLM_API_KEY=replace-with-your-key
124- 
125-AUTH_SESSION_SECRET=replace-with-at-least-32-random-characters
126-AUTH_PUBLIC_BASE_URL=http://127.0.0.1:3000 # real production: https://your.domain
127-AUTH_REGISTRATION_MODE=open
128-AUTH_EMAIL_DELIVERY=test # real production: smtp + AUTH_SMTP_*
129```121```
130 122 
131-`apps/web/.env.local`:123+Build and start. `npm install` syncs the control-plane Python dependencies when it finishes. `npm run build` compiles the web app and TUI:
132- 
133-```bash
134-NEXT_PUBLIC_AGENT_RUNTIME_URL=
135-NEXT_PUBLIC_CONFIG_API_URL=
136-API_PROXY_TARGET=http://127.0.0.1:8787
137-```
138- 
139-Build and start:
140 124 
141```bash125```bash
142npm run build126npm run build
143-npm run build:web127+npm run start # web defaults to 127.0.0.1:3000; override with --web-host / --web-port
144-npm run start # Web :3000 + API :8787
145```128```
146 129 
147-Open `http://127.0.0.1:3000/login`, register or sign in, go to `/data-tasks`, and ask:130+Open `http://127.0.0.1:3000/data-tasks` and ask:
148 131 
149```text132```text
150Show me the tables in this datasource and explain the main fields of each.133Show me the tables in this datasource and explain the main fields of each.
@@ -152,9 +135,9 @@ Show me the tables in this datasource and explain the main fields of each.
152 135 
153You will see the full chain: schema inspection → read-only SQL → SQL audit → table output → replayable run history.136You will see the full chain: schema inspection → read-only SQL → SQL audit → table output → replayable run history.
154 137 
155-For real production, also configure SMTP and a reverse proxy: [`deploy/nginx.datafoundry.conf.example`](deploy/nginx.datafoundry.conf.example) (gzip/brotli static assets; keep `/api/copilotkit` uncompressed and unbuffered for SSE).138+For real production, put a reverse proxy in front: [`deploy/nginx.datafoundry.conf.example`](deploy/nginx.datafoundry.conf.example) (gzip/brotli static assets; keep `/dataagent/stream` and `/api/copilotkit` uncompressed and unbuffered for SSE).
156 139 
157-> Full steps, the two-environment matrix, and optional external DataLink notes: [Quick Start](docs/en/quick-start.md). Contributor hot-reload (`npm run dev`) is appendix-only. Connect your own PostgreSQL / MySQL / CSV and more: [Data Sources guide](docs/en/guides/data-sources.md).140+> Full steps, the two-environment matrix, and optional external DataLink notes: [Quick Start](docs/en/quick-start.md). Connect your own PostgreSQL / MySQL / CSV and more: [Data Sources guide](docs/en/guides/data-sources.md).
158 141 
159 142 
160## 🆚 How It Differs From Coding Agents And SQL Chatbots143## 🆚 How It Differs From Coding Agents And SQL Chatbots
@@ -236,7 +219,7 @@ DataAgent moves quickly, so small, well-scoped PRs are the easiest to merge:
236 219 
2371. Open an issue or discussion first for behavioral, protocol, datasource-adapter, or agent-policy changes.2201. Open an issue or discussion first for behavioral, protocol, datasource-adapter, or agent-policy changes.
2382. Keep each PR focused on one runtime boundary or feature area.2212. Keep each PR focused on one runtime boundary or feature area.
239-3. Run `npm run build` plus the targeted smoke checks for what you touched (e.g. `npm run smoke:data-gateway`).222+3. Run `npm run build` plus the targeted smoke checks for what you touched (e.g. `npm run smoke:docs`).
2404. Update docs when a change affects setup, APIs, datasource configuration, or user-visible output.2234. Update docs when a change affects setup, APIs, datasource configuration, or user-visible output.
2415. Do not commit credentials, local databases, generated storage, or private benchmark data.2245. Do not commit credentials, local databases, generated storage, or private benchmark data.
242 225 
@@ -266,7 +249,6 @@ Join the DataAgent community to discuss the product, roadmap, and real-world ado
266DataAgent is inspired by and built with ideas from excellent open-source projects and communities:249DataAgent is inspired by and built with ideas from excellent open-source projects and communities:
267 250 
268- Thanks to the [LINUX DO](https://linux.do/) community for their support and discussions.251- Thanks to the [LINUX DO](https://linux.do/) community for their support and discussions.
269-- [Mastra](https://github.com/mastra-ai/mastra) for agent runtime patterns.
270- [AG-UI](https://github.com/ag-ui-protocol/ag-ui) for event stream protocol design.252- [AG-UI](https://github.com/ag-ui-protocol/ag-ui) for event stream protocol design.
271- [CopilotKit](https://github.com/CopilotKit/CopilotKit) for agent-native UX patterns.253- [CopilotKit](https://github.com/CopilotKit/CopilotKit) for agent-native UX patterns.
272- [Ink](https://github.com/vadimdemedes/ink) for terminal UI foundations.254- [Ink](https://github.com/vadimdemedes/ink) for terminal UI foundations.
@@ -32,7 +32,6 @@
32 <img src="https://img.shields.io/badge/PRs-welcome-ff69b4" alt="PRs welcome" />32 <img src="https://img.shields.io/badge/PRs-welcome-ff69b4" alt="PRs welcome" />
33 <img src="https://img.shields.io/badge/status-early%20but%20usable-orange" alt="Status" />33 <img src="https://img.shields.io/badge/status-early%20but%20usable-orange" alt="Status" />
34 <br />34 <br />
35- <a href="https://github.com/mastra-ai/mastra"><img src="https://img.shields.io/badge/Mastra-agent%20runtime-111827" alt="Mastra agent runtime" /></a>
36 <a href="https://github.com/ag-ui-protocol/ag-ui"><img src="https://img.shields.io/badge/AG--UI-event%20stream-6f42c1" alt="AG-UI event stream" /></a>35 <a href="https://github.com/ag-ui-protocol/ag-ui"><img src="https://img.shields.io/badge/AG--UI-event%20stream-6f42c1" alt="AG-UI event stream" /></a>
37 <a href="https://github.com/vadimdemedes/ink"><img src="https://img.shields.io/badge/Ink-terminal%20UI-0f766e" alt="Ink terminal UI" /></a>36 <a href="https://github.com/vadimdemedes/ink"><img src="https://img.shields.io/badge/Ink-terminal%20UI-0f766e" alt="Ink terminal UI" /></a>
38</p>37</p>
@@ -71,7 +70,7 @@ DataAgent 0.2 在首个可用版本上,进一步补齐了有状态、可追溯
71 70 
72## 🚀 正式态跑通71## 🚀 正式态跑通
73 72 
74-正式态有两条路径(都不要跑 `npm run dev`)。本版本不提供 Docker / Compose。73+正式态有两条路径。本版本不提供 Docker / Compose。
75 74 
76### 推荐:Ubuntu / Debian 一键部署75### 推荐:Ubuntu / Debian 一键部署
77 76 
@@ -100,7 +99,7 @@ cd datafoundry
100./deploy.sh tui # 可选:前台启动 TUI(需 API 已在运行)99./deploy.sh tui # 可选:前台启动 TUI(需 API 已在运行)
101```100```
102 101 
103-打开 `http://127.0.0.1:3000/login` 注册登录,在模型配置中创建 OpenAI-compatible Profile,然后进入 `/data-tasks`。远程部署请设置 `AUTH_PUBLIC_BASE_URL`;重复执行 `./deploy.sh deploy` 会进入维护窗口(先停止旧进程再安装/构建)。102+打开 `http://127.0.0.1:3000/data-tasks`。模型来自 `.env` 或 Home `config.json`。重复执行 `./deploy.sh deploy` 会进入维护窗口(先停止旧进程再安装/构建)。
104 103 
105### Windows / macOS / 其他:手动 npm104### Windows / macOS / 其他:手动 npm
106 105 
@@ -111,40 +110,24 @@ git clone https://github.com/datagallery-lab/datafoundry.git
111cd datafoundry110cd datafoundry
112npm install111npm install
113cp .env.example .env112cp .env.example .env
114-cp apps/web/.env.example apps/web/.env.local
115```113```
116 114 
117-在根目录 `.env` 配置模型,并按正式测试或真实生产填好认证(样例默认偏正式测试):115+在根目录 `.env` 配置可选的服务端模型(也可以只在网页里配置):
118 116 
119```bash117```bash
120-LLM_PROVIDER=openai-compatible
121LLM_MODEL=qwen-plus # 或 deepseek-chat、gpt-4o……118LLM_MODEL=qwen-plus # 或 deepseek-chat、gpt-4o……
122LLM_BASE_URL=https://dashscope.aliyuncs.com/compatible-mode/v1119LLM_BASE_URL=https://dashscope.aliyuncs.com/compatible-mode/v1
123LLM_API_KEY=replace-with-your-key120LLM_API_KEY=replace-with-your-key
124- 
125-AUTH_SESSION_SECRET=replace-with-at-least-32-random-characters
126-AUTH_PUBLIC_BASE_URL=http://127.0.0.1:3000 # 真实生产改为 https://你的域名
127-AUTH_REGISTRATION_MODE=open
128-AUTH_EMAIL_DELIVERY=test # 真实生产改为 smtp,并填 AUTH_SMTP_*
129```121```
130 122 
131-`apps/web/.env.local`:123+构建并启动。`npm install` 结束时同步控制面的 Python 依赖。`npm run build` 编译网页和 TUI:
132- 
133-```bash
134-NEXT_PUBLIC_AGENT_RUNTIME_URL=
135-NEXT_PUBLIC_CONFIG_API_URL=
136-API_PROXY_TARGET=http://127.0.0.1:8787
137-```
138- 
139-构建并启动:
140 124 
141```bash125```bash
142npm run build126npm run build
143-npm run build:web127+npm run start # 网页默认 127.0.0.1:3000,可用 --web-host / --web-port 改
144-npm run start # Web :3000 + API :8787
145```128```
146 129 
147-打开 `http://127.0.0.1:3000/login` 注册登录后进入 `/data-tasks`,提问:130+打开 `http://127.0.0.1:3000/data-tasks`,提问:
148 131 
149```text132```text
150帮我查看数据源里有哪些表,并说明每张表的主要字段。133帮我查看数据源里有哪些表,并说明每张表的主要字段。
@@ -152,9 +135,9 @@ npm run start # Web :3000 + API :8787
152 135 
153你会看到完整的一条链路:schema 检查 → 只读 SQL → SQL 审计 → 表格产出 → 可回放的 run history。136你会看到完整的一条链路:schema 检查 → 只读 SQL → SQL 审计 → 表格产出 → 可回放的 run history。
154 137 
155-真实生产请再配 SMTP 与反代:[`deploy/nginx.datafoundry.conf.example`](deploy/nginx.datafoundry.conf.example)(静态 gzip/brotli;`/api/copilotkit` 关压缩与缓冲以保护 SSE)。138+真实生产请再配反代:[`deploy/nginx.datafoundry.conf.example`](deploy/nginx.datafoundry.conf.example)(静态 gzip/brotli;`/dataagent/stream` 与 `/api/copilotkit` 关压缩与缓冲以保护 SSE)。
156 139 
157-> 完整步骤与两种环境对照见 [快速开始](docs/zh/quick-start.md);贡献者热更新(`npm run dev`)仅见该文档附录。接入自己的 PostgreSQL / MySQL / CSV 等见 [数据源指南](docs/zh/guides/data-sources.md)。140+> 完整步骤与两种环境对照见 [快速开始](docs/zh/quick-start.md)。接入自己的 PostgreSQL / MySQL / CSV 等见 [数据源指南](docs/zh/guides/data-sources.md)。
158 141 
159## 🆚 和 Coding Agent、SQL Chatbot 有什么不同142## 🆚 和 Coding Agent、SQL Chatbot 有什么不同
160 143 
@@ -235,7 +218,7 @@ DataAgent 迭代很快,小而聚焦的 PR 最容易被合入:
235 218 
2361. 行为、协议、数据源适配器和 Agent 策略变更,请先开 issue 或 discussion。2191. 行为、协议、数据源适配器和 Agent 策略变更,请先开 issue 或 discussion。
2372. 每个 PR 聚焦一个运行时边界或功能区。2202. 每个 PR 聚焦一个运行时边界或功能区。
238-3. 提交前运行 `npm run build` 和改动区域对应的 smoke 检查(如 `npm run smoke:data-gateway`)。221+3. 提交前运行 `npm run build` 和改动区域对应的 smoke 检查(如 `npm run smoke:docs`)。
2394. 改动 setup、API、数据源配置或用户可见输出时,同步更新文档。2224. 改动 setup、API、数据源配置或用户可见输出时,同步更新文档。
2405. 不提交凭据、本地数据库、生成的 storage 或私有 benchmark 数据。2235. 不提交凭据、本地数据库、生成的 storage 或私有 benchmark 数据。
241 224 
@@ -265,7 +248,6 @@ DataAgent 迭代很快,小而聚焦的 PR 最容易被合入:
265DataAgent 受益于这些优秀的开源项目与社区:248DataAgent 受益于这些优秀的开源项目与社区:
266 249 
267- 感谢 [LINUX DO](https://linux.do/) 社区的支持与讨论。250- 感谢 [LINUX DO](https://linux.do/) 社区的支持与讨论。
268-- [Mastra](https://github.com/mastra-ai/mastra):Agent 运行时模式。
269- [AG-UI](https://github.com/ag-ui-protocol/ag-ui):事件流协议设计。251- [AG-UI](https://github.com/ag-ui-protocol/ag-ui):事件流协议设计。
270- [CopilotKit](https://github.com/CopilotKit/CopilotKit):Agent 原生交互体验。252- [CopilotKit](https://github.com/CopilotKit/CopilotKit):Agent 原生交互体验。
271- [Ink](https://github.com/vadimdemedes/ink):终端 UI 基础能力。253- [Ink](https://github.com/vadimdemedes/ink):终端 UI 基础能力。
@@ -10,41 +10,24 @@ From the repository root:
10```bash10```bash
11npm install11npm install
12npm run start:tui12npm run start:tui
13-npm run start:tui -- --runtime-url http://127.0.0.1:8787/api/copilotkit
14-npm run start:tui -- --no-auto-login
15```13```
16 14 
17-## DataAgent V2 local mode15+`npm run start:tui` is V2. It connects to `/dataagent/stream` at the address in Home `config.json` `server.host` and `server.port`, default `http://127.0.0.1:8790`. Nothing listening there starts `dataagent serve`; a control plane that is already up is reused. It does not open `/api/copilotkit`.
18 16 
19-The existing TUI directly starts and manages `runtime/agentkit`'s backend.17+## DataAgent V2
20-No registration, web service, runtime UI directory or Python TUI forwarding is needed.
21 18 
22-Using the repository-root `.env` with your model configuration:19+Home defaults live in `~/.dataagent`. Add `--resume` or `--resume <threadId>` to restore a session. `--config`, `--env-file`, `--workspace`, `--user` and `--session` are forwarded to a backend this TUI starts, so they do not attach to one that is already running.
20+ 
21+`--runtime-url` attaches and does not start a backend. The host must be `server.host` from `config.json`, or `127.0.0.1`.
23 22 
24```bash23```bash
25-uv sync --project runtime/agentkit24+npm run start:tui -- --runtime-url http://127.0.0.1:8790
26-npm run start:tui -- --v2 --env-file .env --workspace "$PWD"
27```25```
28 26 
29-Home defaults live in `~/.dataagent`; the first local launch creates non-overwriting
30-templates. Fill in its `.env`, then `npm run start:tui -- --v2` works without a config flag.
31-Optional `--config /absolute/path/config.json` adds a partial layer above Home;
32-its sibling `.env` is also loaded by the backend. Home is the single working root,
33-selected with `DATAAGENT_HOME` (default `~/.dataagent`). Optional `--workspace` paths
34-are existing read-only inputs; without them the input list is empty. Relative paths
35-resolve from the npm launch directory, which supplies no configuration or extensions.
36-Add `--resume` or `--resume <threadId>` to restore
37-a session. `/exit` closes the UI and its owned backend. An occupied port fails without
38-attaching to or stopping another service.
39- 
40-For an already running V2 backend, use `--v2 --runtime-url http://127.0.0.1:8790/dataagent/stream`
41-without a login or token. That mode does not own or stop the service;
42-do not combine it with `--config`, `--env-file` or `--workspace`.
43- 
44There is no project configuration layer or trust prompt. Logs/checkpoints live in27There is no project configuration layer or trust prompt. Logs/checkpoints live in
45`<home>/runtime`; session outputs live in `runtime/users/<user>/sessions/<session>/outputs`.28`<home>/runtime`; session outputs live in `runtime/users/<user>/sessions/<session>/outputs`.
46-Existing session input bindings are retained; no files are migrated or deleted. The backend29+Existing session input bindings are retained; no files are migrated or deleted. TUI theme
47-owns `--env-file` parsing, so TUI theme/log variables must be in the TUI process environment.30+and log variables stay in the TUI process environment. `--env-file` is forwarded to the backend that this TUI starts.
48 31 
49See the [V2 configuration and plugin guide](../../runtime/agentkit/README.md).32See the [V2 configuration and plugin guide](../../runtime/agentkit/README.md).
50 33 
@@ -59,7 +42,7 @@ is four rows. Both home and chat support
59- Enter submits. Shift+Enter (CSI-u or xterm modifyOtherKeys), Alt+Enter and Ctrl+J insert a newline.42- Enter submits. Shift+Enter (CSI-u or xterm modifyOtherKeys), Alt+Enter and Ctrl+J insert a newline.
60- Multi-line bracketed paste stays one editable draft; large pastes keep the existing fold/expand behavior.43- Multi-line bracketed paste stays one editable draft; large pastes keep the existing fold/expand behavior.
61- Up/Down navigate the draft and command history. Messages entered during a run remain queued.44- Up/Down navigate the draft and command history. Messages entered during a run remain queued.
62-- `/` opens commands and Tab completes. V2 exposes `/help`, `/clear`, `/resume [id]`, `/outputs` and `/exit`.45+- `/` opens commands and Tab completes. V2 exposes `/help`, `/clear`, `/resume`, `/resume list`, `/resume latest`, `/resume <id>`, `/outputs` and `/exit`. `/resume` and `/resume list` open the session picker.
63- `/outputs` opens the full output list at any width. Enter previews a result; Esc returns to the list, then chat; q closes the view. Chat always uses a single column, with no output sidebar or extra footer indicators.46- `/outputs` opens the full output list at any width. Enter previews a result; Esc returns to the list, then chat; q closes the view. Chat always uses a single column, with no output sidebar or extra footer indicators.
64- Ctrl+C keeps the existing two-press exit flow; Ctrl+Z/fg restores the terminal and input cursor in V2.47- Ctrl+C keeps the existing two-press exit flow; Ctrl+Z/fg restores the terminal and input cursor in V2.
65 48 
@@ -92,7 +75,7 @@ text and symbols.
92From the repository root:75From the repository root:
93 76 
94```bash77```bash
95-npm --workspace @datafoundry/tui test78+npm run test:tui
96uv run --project runtime/agentkit --locked pytest runtime/agentkit/tests -m 'not live'79uv run --project runtime/agentkit --locked pytest runtime/agentkit/tests -m 'not live'
97```80```
98 81 
@@ -14,7 +14,7 @@
14 "dev": "tsc --watch",14 "dev": "tsc --watch",
15 "prestart": "npm run build",15 "prestart": "npm run build",
16 "start": "node -- dist/index.js",16 "start": "node -- dist/index.js",
17- "test": "npm run build && node --test dist/auth/cookie-jar.test.js dist/auth/session-store.test.js dist/auth/authenticated-transport.test.js dist/auth/auth-client.test.js dist/auth/bootstrap.test.js dist/auth/browser-opener.test.js dist/auth/interactive-login.test.js dist/config/config-client.test.js dist/protocol/copilotkit-client-auth.test.js dist/protocol/agui-client.test.js dist/v2.test.js dist/v2-startup.test.js dist/startup-preflight.test.js dist/runtime-url.test.js dist/index-auth-wiring.test.js dist/commands/logout-command.test.js dist/no-bare-fetch.guard.test.js dist/ui/components/EnhancedInputBox.test.js dist/ui/App-v2.test.js dist/ui/assistant-stream-buffer.test.js dist/state/live-run-state.test.js dist/ui/fullscreen-cursor.test.js dist/ui/conversation-design.test.js dist/terminal-screen.test.js",17+ "test": "npm run build && node --test dist/config/config-client.test.js dist/protocol/agui-client.test.js dist/v2.test.js dist/v2-startup.test.js dist/startup-preflight.test.js dist/runtime-url.test.js dist/no-bare-fetch.guard.test.js dist/ui/components/EnhancedInputBox.test.js dist/ui/App-v2.test.js dist/ui/assistant-stream-buffer.test.js dist/state/live-run-state.test.js dist/ui/fullscreen-cursor.test.js dist/ui/conversation-design.test.js dist/terminal-screen.test.js",
18 "clean": "rm -rf dist"18 "clean": "rm -rf dist"
19 },19 },
20 "keywords": [20 "keywords": [
@@ -27,7 +27,6 @@
27 "dependencies": {27 "dependencies": {
28 "@ag-ui/core": "^0.0.57",28 "@ag-ui/core": "^0.0.57",
29 "ink": "^7.1.0",29 "ink": "^7.1.0",
30- "ink-table": "^3.1.0",
31 "react": "^19.2.0",30 "react": "^19.2.0",
32 "zod": "^4.4.3"31 "zod": "^4.4.3"
33 },32 },
@@ -1,278 +0,0 @@
1-import assert from "node:assert/strict";
2-import { describe, it } from "node:test";
3-import { assertSafeAuthRedirect, TuiAuthClient, TuiAuthError } from "./auth-client.js";
4-import { TuiCookieJar } from "./cookie-jar.js";
5- 
6-describe("TuiAuthClient", () => {
7- it("calls status/login/me/csrf/logout with expected URLs and methods", async () => {
8- const jar = new TuiCookieJar();
9- const calls: Array<{ url: string; method: string; body?: unknown }> = [];
10- const client = new TuiAuthClient({
11- apiBaseUrl: "http://127.0.0.1:8787",
12- cookieJar: jar,
13- fetchImpl: async (input, init) => {
14- const url = String(input);
15- const method = String(init?.method ?? "GET");
16- const body = init?.body ? JSON.parse(String(init.body)) : undefined;
17- calls.push({ url, method, body });
18- if (url.endsWith("/api/v1/auth/status")) {
19- return json(200, {
20- success: true,
21- data: { publicBaseUrl: "http://127.0.0.1:3000", registrationEnabled: true },
22- });
23- }
24- if (url.endsWith("/api/v1/auth/login")) {
25- return json(
26- 200,
27- {
28- success: true,
29- data: {
30- user: { id: "u1", email: "a@example.com" },
31- workspace: { id: "w1" },
32- session: { expiresAt: "2099-01-01T00:00:00.000Z" },
33- },
34- },
35- [
36- "df_session=sess; Path=/; HttpOnly",
37- "df_csrf=csrf; Path=/",
38- ],
39- );
40- }
41- if (url.endsWith("/api/v1/me")) {
42- return json(200, {
43- success: true,
44- data: { user: { id: "u1", email: "a@example.com" }, workspace: { id: "w1" } },
45- });
46- }
47- if (url.endsWith("/api/v1/auth/csrf/refresh")) {
48- return json(200, { success: true, data: { csrfToken: "new" } }, ["df_csrf=new; Path=/"]);
49- }
50- if (url.endsWith("/api/v1/auth/logout")) {
51- return json(200, { success: true, data: { ok: true } });
52- }
53- return json(404, { success: false, error: { code: "NOT_FOUND", message: "missing" } });
54- },
55- });
56- 
57- await client.getStatus();
58- await client.login("a@example.com", "password");
59- await client.me();
60- await client.refreshCsrf();
61- await client.logout();
62- 
63- assert.deepEqual(
64- calls.map((call) => ({ method: call.method, path: new URL(call.url).pathname })),
65- [
66- { method: "GET", path: "/api/v1/auth/status" },
67- { method: "POST", path: "/api/v1/auth/login" },
68- { method: "GET", path: "/api/v1/me" },
69- { method: "POST", path: "/api/v1/auth/csrf/refresh" },
70- { method: "POST", path: "/api/v1/auth/logout" },
71- ],
72- );
73- assert.equal((calls[1]?.body as { client?: string } | undefined)?.client, "tui");
74- assert.equal(
75- calls.some((call) => call.url.includes("/api/v1/auth/me")),
76- false,
77- );
78- });
79- 
80- it("requires session.expiresAt from login response", async () => {
81- const client = new TuiAuthClient({
82- apiBaseUrl: "http://127.0.0.1:8787",
83- cookieJar: new TuiCookieJar(),
84- fetchImpl: async () =>
85- json(200, {
86- success: true,
87- data: {
88- user: { id: "u1", email: "a@example.com" },
89- workspace: { id: "w1" },
90- session: {},
91- },
92- }),
93- });
94- 
95- await assert.rejects(
96- () => client.login("a@example.com", "password"),
97- (error: unknown) => error instanceof TuiAuthError && error.code === "INVALID_LOGIN_RESPONSE",
98- );
99- });
100- 
101- it("times out hung auth requests", async () => {
102- const client = new TuiAuthClient({
103- apiBaseUrl: "http://127.0.0.1:8787",
104- cookieJar: new TuiCookieJar(),
105- timeoutMs: 20,
106- fetchImpl: async (_input, init) =>
107- new Promise((_resolve, reject) => {
108- init?.signal?.addEventListener("abort", () => {
109- const error = new Error("aborted");
110- error.name = "AbortError";
111- reject(error);
112- });
113- }),
114- });
115- 
116- await assert.rejects(
117- () => client.getStatus(),
118- (error: unknown) => error instanceof TuiAuthError && error.code === "TIMEOUT",
119- );
120- });
121- 
122- it("maps transport failures to NETWORK_ERROR", async () => {
123- const client = new TuiAuthClient({
124- apiBaseUrl: "http://127.0.0.1:8787",
125- cookieJar: new TuiCookieJar(),
126- fetchImpl: async () => {
127- throw new TypeError("fetch failed");
128- },
129- });
130- 
131- await assert.rejects(
132- () => client.getStatus(),
133- (error: unknown) => error instanceof TuiAuthError && error.code === "NETWORK_ERROR",
134- );
135- });
136- 
137- it("uses redirect:manual and rejects HTTPS→HTTP auth redirects", async () => {
138- const seen: Array<{ redirect?: RequestRedirect; url: string }> = [];
139- const client = new TuiAuthClient({
140- apiBaseUrl: "https://api.example.com",
141- cookieJar: new TuiCookieJar(),
142- fetchImpl: async (input, init) => {
143- seen.push({
144- url: String(input),
145- ...(init?.redirect ? { redirect: init.redirect } : {}),
146- });
147- return new Response(null, {
148- status: 308,
149- headers: { location: "http://api.example.com/api/v1/auth/login" },
150- });
151- },
152- });
153- 
154- await assert.rejects(
155- () => client.login("a@example.com", "password"),
156- (error: unknown) =>
157- error instanceof TuiAuthError
158- && error.code === "UNSAFE_REDIRECT"
159- && /HTTPS to HTTP/i.test(error.message),
160- );
161- assert.equal(seen[0]?.redirect, "manual");
162- assert.equal(seen.length, 1);
163- });
164- 
165- it("rejects cross-origin auth redirects and does not forward the password body", async () => {
166- let bodies = 0;
167- const client = new TuiAuthClient({
168- apiBaseUrl: "https://api.example.com",
169- cookieJar: new TuiCookieJar(),
170- fetchImpl: async (_input, init) => {
171- if (init?.body) {
172- bodies += 1;
173- }
174- return new Response(null, {
175- status: 307,
176- headers: { location: "https://evil.example.com/api/v1/auth/login" },
177- });
178- },
179- });
180- 
181- await assert.rejects(
182- () => client.login("a@example.com", "password"),
183- (error: unknown) =>
184- error instanceof TuiAuthError
185- && error.code === "UNSAFE_REDIRECT"
186- && /cross-origin/i.test(error.message),
187- );
188- assert.equal(bodies, 1);
189- });
190- 
191- it("follows same-origin 307 and keeps timeout armed through body parse", async () => {
192- let fetches = 0;
193- let bodyReadStarted = false;
194- let abortedDuringBody = false;
195- const client = new TuiAuthClient({
196- apiBaseUrl: "http://127.0.0.1:8787",
197- cookieJar: new TuiCookieJar(),
198- timeoutMs: 40,
199- fetchImpl: async (input, init) => {
200- fetches += 1;
201- assert.equal(init?.redirect, "manual");
202- if (fetches === 1) {
203- return new Response(null, {
204- status: 307,
205- headers: { location: "http://127.0.0.1:8787/api/v1/auth/status" },
206- });
207- }
208- const payload = JSON.stringify({
209- success: true,
210- data: { publicBaseUrl: "http://127.0.0.1:3000", registrationEnabled: false },
211- });
212- return new Response(
213- new ReadableStream({
214- start(controller) {
215- bodyReadStarted = true;
216- const timer = setTimeout(() => {
217- controller.enqueue(new TextEncoder().encode(payload));
218- controller.close();
219- }, 80);
220- init?.signal?.addEventListener("abort", () => {
221- abortedDuringBody = true;
222- clearTimeout(timer);
223- try {
224- controller.error(Object.assign(new Error("aborted"), { name: "AbortError" }));
225- } catch {
226- // already closed
227- }
228- });
229- },
230- }),
231- { status: 200, headers: { "content-type": "application/json" } },
232- );
233- },
234- });
235- 
236- await assert.rejects(
237- () => client.getStatus(),
238- (error: unknown) => error instanceof TuiAuthError && error.code === "TIMEOUT",
239- );
240- assert.equal(fetches, 2);
241- assert.equal(bodyReadStarted, true);
242- assert.equal(abortedDuringBody, true);
243- });
244-});
245- 
246-describe("assertSafeAuthRedirect", () => {
247- it("allows same-origin HTTPS hops and rejects downgrade/cross-origin", () => {
248- assert.equal(
249- assertSafeAuthRedirect(
250- "https://api.example.com/api/v1/auth/login",
251- "/api/v1/auth/login?next=1",
252- ),
253- "https://api.example.com/api/v1/auth/login?next=1",
254- );
255- assert.throws(
256- () => assertSafeAuthRedirect(
257- "https://api.example.com/login",
258- "http://api.example.com/login",
259- ),
260- (error: unknown) => error instanceof TuiAuthError && error.code === "UNSAFE_REDIRECT",
261- );
262- assert.throws(
263- () => assertSafeAuthRedirect(
264- "https://api.example.com/login",
265- "https://other.example.com/login",
266- ),
267- (error: unknown) => error instanceof TuiAuthError && error.code === "UNSAFE_REDIRECT",
268- );
269- });
270-});
271- 
272-function json(status: number, body: unknown, setCookies: string[] = []): Response {
273- const headers = new Headers({ "content-type": "application/json" });
274- for (const cookie of setCookies) {
275- headers.append("set-cookie", cookie);
276- }
277- return new Response(JSON.stringify(body), { status, headers });
278-}
@@ -1,373 +0,0 @@
1-import { isLoopbackHostname } from "../runtime-url.js";
2-import { TuiCookieJar } from "./cookie-jar.js";
3-import { normalizeApiBaseUrl } from "./session-store.js";
4-import type { AuthStatus, StoredTuiSession, TuiUser, TuiWorkspace } from "./types.js";
5- 
6-export const DEFAULT_AUTH_TIMEOUT_MS = 15_000;
7-const MAX_AUTH_REDIRECTS = 5;
8-const REDIRECT_STATUSES = new Set([301, 302, 303, 307, 308]);
9- 
10-export type TuiAuthClientOptions = {
11- apiBaseUrl: string;
12- cookieJar: TuiCookieJar;
13- fetchImpl?: typeof fetch;
14- timeoutMs?: number;
15-};
16- 
17-export class TuiAuthError extends Error {
18- readonly status: number;
19- readonly code: string;
20- 
21- constructor(status: number, code: string, message: string) {
22- super(message);
23- this.name = "TuiAuthError";
24- this.status = status;
25- this.code = code;
26- }
27-}
28- 
29-export class TuiAuthClient {
30- readonly apiBaseUrl: string;
31- readonly cookieJar: TuiCookieJar;
32- readonly fetchImpl: typeof fetch;
33- readonly timeoutMs: number;
34- 
35- constructor(options: TuiAuthClientOptions) {
36- this.apiBaseUrl = normalizeApiBaseUrl(options.apiBaseUrl);
37- this.cookieJar = options.cookieJar;
38- this.fetchImpl = options.fetchImpl ?? globalThis.fetch.bind(globalThis);
39- this.timeoutMs = options.timeoutMs ?? DEFAULT_AUTH_TIMEOUT_MS;
40- }
41- 
42- async getStatus(): Promise<AuthStatus> {
43- const body = await this.requestJson("GET", "/api/v1/auth/status");
44- const data = asRecord(body.data);
45- const publicBaseUrl = asString(data?.publicBaseUrl);
46- if (!publicBaseUrl) {
47- throw new TuiAuthError(500, "INVALID_STATUS", "Auth status missing publicBaseUrl.");
48- }
49- return {
50- publicBaseUrl,
51- registrationEnabled: Boolean(data?.registrationEnabled),
52- };
53- }
54- 
55- async login(email: string, password: string): Promise<StoredTuiSession> {
56- const { response, json: body } = await this.requestRaw("POST", "/api/v1/auth/login", {
57- email,
58- password,
59- client: "tui",
60- });
61- if (!response.ok) {
62- throw errorFromBody(response.status, body);
63- }
64- 
65- const data = asRecord(body.data);
66- const user = parseUser(data?.user);
67- const workspace = parseWorkspace(data?.workspace);
68- const session = asRecord(data?.session);
69- const expiresAt = asString(session?.expiresAt);
70- if (!expiresAt || Number.isNaN(Date.parse(expiresAt))) {
71- throw new TuiAuthError(
72- 500,
73- "INVALID_LOGIN_RESPONSE",
74- "Login response missing session.expiresAt.",
75- );
76- }
77- 
78- return {
79- apiBaseUrl: this.apiBaseUrl,
80- cookies: this.cookieJar.snapshot(),
81- user,
82- workspace,
83- expiresAt,
84- };
85- }
86- 
87- async me(): Promise<TuiUser & { workspace: TuiWorkspace }> {
88- const body = await this.requestJson("GET", "/api/v1/me");
89- const data = asRecord(body.data);
90- const user = parseUser(data?.user);
91- const workspace = parseWorkspace(data?.workspace);
92- return { ...user, workspace };
93- }
94- 
95- async refreshCsrf(): Promise<void> {
96- const { response, json } = await this.requestRaw("POST", "/api/v1/auth/csrf/refresh");
97- if (!response.ok) {
98- throw errorFromBody(response.status, json);
99- }
100- }
101- 
102- async logout(): Promise<void> {
103- const { response, json } = await this.requestRaw("POST", "/api/v1/auth/logout");
104- if (!response.ok && response.status !== 401) {
105- throw errorFromBody(response.status, json);
106- }
107- this.cookieJar.clear();
108- }
109- 
110- private async requestJson(
111- method: string,
112- path: string,
113- body?: unknown,
114- ): Promise<{ data?: unknown; error?: { code?: string; message?: string } }> {
115- const { response, json } = await this.requestRaw(method, path, body);
116- if (!response.ok) {
117- throw errorFromBody(response.status, json);
118- }
119- return json;
120- }
121- 
122- /**
123- * Fetch + JSON parse under one AbortController so timeouts cover the full body read.
124- * Auth requests never auto-follow redirects; hops are validated manually.
125- */
126- private async requestRaw(
127- method: string,
128- path: string,
129- body?: unknown,
130- ): Promise<{
131- response: Response;
132- json: { data?: unknown; error?: { code?: string; message?: string } };
133- }> {
134- return this.withTimeout(async (signal) => {
135- const response = await this.performFetch(method, path, body, signal);
136- this.cookieJar.absorbSetCookie(response.headers);
137- const json = await readJson(response);
138- return { response, json };
139- });
140- }
141- 
142- private async withTimeout<T>(fn: (signal: AbortSignal) => Promise<T>): Promise<T> {
143- const controller = new AbortController();
144- const timeoutId = setTimeout(() => controller.abort(), this.timeoutMs);
145- try {
146- return await fn(controller.signal);
147- } catch (error) {
148- if (error instanceof TuiAuthError) {
149- throw error;
150- }
151- if (isAbortError(error)) {
152- throw new TuiAuthError(
153- 0,
154- "TIMEOUT",
155- `Auth request timed out after ${this.timeoutMs}ms`,
156- );
157- }
158- const message = error instanceof Error ? error.message : String(error);
159- throw new TuiAuthError(0, "NETWORK_ERROR", message || "Network request failed");
160- } finally {
161- clearTimeout(timeoutId);
162- }
163- }
164- 
165- private async performFetch(
166- method: string,
167- path: string,
168- body: unknown | undefined,
169- signal: AbortSignal,
170- ): Promise<Response> {
171- let url = resolveApiUrl(this.apiBaseUrl, path);
172- let currentMethod = method;
173- let currentBody = body;
174- for (let hop = 0; hop <= MAX_AUTH_REDIRECTS; hop += 1) {
175- const headers = new Headers();
176- const cookieHeader = this.cookieJar.headerValue();
177- if (cookieHeader) {
178- headers.set("cookie", cookieHeader);
179- }
180- if (currentMethod !== "GET" && currentMethod !== "HEAD") {
181- headers.set("content-type", "application/json");
182- const csrf = this.cookieJar.csrfToken();
183- if (csrf) {
184- headers.set("x-csrf-token", csrf);
185- }
186- }
187- 
188- const response = await this.fetchImpl(url, {
189- method: currentMethod,
190- headers,
191- signal,
192- redirect: "manual",
193- ...(currentBody !== undefined ? { body: JSON.stringify(currentBody) } : {}),
194- });
195- 
196- if (!REDIRECT_STATUSES.has(response.status)) {
197- return response;
198- }
199- 
200- if (hop === MAX_AUTH_REDIRECTS) {
201- throw new TuiAuthError(
202- response.status,
203- "UNSAFE_REDIRECT",
204- "Auth request exceeded redirect hop limit.",
205- );
206- }
207- 
208- const nextUrl = assertSafeAuthRedirect(url, response.headers.get("location"));
209- // Absorb cookies from redirect responses before following.
210- this.cookieJar.absorbSetCookie(response.headers);
211- 
212- if (response.status === 301 || response.status === 302 || response.status === 303) {
213- if (currentMethod !== "GET" && currentMethod !== "HEAD") {
214- throw new TuiAuthError(
215- response.status,
216- "UNSAFE_REDIRECT",
217- "Refusing method-changing auth redirect for non-GET request.",
218- );
219- }
220- currentMethod = "GET";
221- currentBody = undefined;
222- }
223- url = nextUrl;
224- }
225- 
226- throw new TuiAuthError(0, "UNSAFE_REDIRECT", "Auth request exceeded redirect hop limit.");
227- }
228-}
229- 
230-export function assertSafeAuthRedirect(fromUrl: string, location: string | null): string {
231- if (!location?.trim()) {
232- throw new TuiAuthError(
233- 0,
234- "UNSAFE_REDIRECT",
235- "Auth redirect missing Location header.",
236- );
237- }
238- 
239- let from: URL;
240- let next: URL;
241- try {
242- from = new URL(fromUrl);
243- next = new URL(location, from);
244- } catch {
245- throw new TuiAuthError(0, "UNSAFE_REDIRECT", "Auth redirect Location is not a valid URL.");
246- }
247- 
248- if (next.username || next.password) {
249- throw new TuiAuthError(
250- 0,
251- "UNSAFE_REDIRECT",
252- "Auth redirect must not include credentials.",
253- );
254- }
255- 
256- if (next.protocol !== "http:" && next.protocol !== "https:") {
257- throw new TuiAuthError(
258- 0,
259- "UNSAFE_REDIRECT",
260- "Auth redirect must use http:// or https://.",
261- );
262- }
263- 
264- // Protocol is part of origin — check downgrade before the generic cross-origin error.
265- if (from.protocol === "https:" && next.protocol === "http:") {
266- throw new TuiAuthError(
267- 0,
268- "UNSAFE_REDIRECT",
269- "Refusing HTTPS to HTTP auth redirect.",
270- );
271- }
272- 
273- if (next.origin !== from.origin) {
274- throw new TuiAuthError(
275- 0,
276- "UNSAFE_REDIRECT",
277- "Refusing cross-origin auth redirect.",
278- );
279- }
280- 
281- if (next.protocol === "http:" && !isLoopbackHostname(next.hostname)) {
282- throw new TuiAuthError(
283- 0,
284- "UNSAFE_REDIRECT",
285- "Refusing non-loopback HTTP auth redirect.",
286- );
287- }
288- 
289- return next.toString();
290-}
291- 
292-function resolveApiUrl(apiBaseUrl: string, path: string): string {
293- const base = new URL(apiBaseUrl);
294- const prefix = base.pathname.replace(/\/?$/, "/");
295- const resolved = new URL(path.replace(/^\/+/, ""), `https://resolve.invalid${prefix}`);
296- base.pathname = resolved.pathname;
297- base.search = resolved.search;
298- base.hash = "";
299- return base.toString();
300-}
301- 
302-function parseUser(value: unknown): TuiUser {
303- const record = asRecord(value);
304- const id = asString(record?.id);
305- const email = asString(record?.email);
306- if (!id || !email) {
307- throw new TuiAuthError(500, "INVALID_USER", "Auth response missing user identity.");
308- }
309- const displayName = asString(record?.displayName);
310- return {
311- id,
312- email,
313- ...(displayName ? { displayName } : {}),
314- };
315-}
316- 
317-function parseWorkspace(value: unknown): TuiWorkspace {
318- const record = asRecord(value);
319- const id = asString(record?.id);
320- if (!id) {
321- throw new TuiAuthError(500, "INVALID_WORKSPACE", "Auth response missing workspace id.");
322- }
323- const name = asString(record?.name);
324- return {
325- id,
326- ...(name ? { name } : {}),
327- };
328-}
329- 
330-function errorFromBody(
331- status: number,
332- body: { error?: { code?: string; message?: string } },
333-): TuiAuthError {
334- return new TuiAuthError(
335- status,
336- body.error?.code ?? "HTTP_ERROR",
337- body.error?.message ?? `Request failed with status ${status}`,
338- );
339-}
340- 
341-async function readJson(
342- response: Response,
343-): Promise<{ data?: unknown; error?: { code?: string; message?: string } }> {
344- try {
345- return await response.json() as {
346- data?: unknown;
347- error?: { code?: string; message?: string };
348- };
349- } catch (error) {
350- // Timeouts must surface; only swallow malformed JSON bodies.
351- if (isAbortError(error)) {
352- throw error;
353- }
354- return {};
355- }
356-}
357- 
358-function asRecord(value: unknown): Record<string, unknown> | undefined {
359- return value && typeof value === "object" ? value as Record<string, unknown> : undefined;
360-}
361- 
362-function asString(value: unknown): string | undefined {
363- return typeof value === "string" && value.trim() ? value : undefined;
364-}
365- 
366-function isAbortError(error: unknown): boolean {
367- return Boolean(
368- error
369- && typeof error === "object"
370- && "name" in error
371- && (error as { name?: string }).name === "AbortError",
372- );
373-}
@@ -1,453 +0,0 @@
1-import assert from "node:assert/strict";
2-import { describe, it } from "node:test";
3-import { AuthenticatedTransport } from "./authenticated-transport.js";
4-import { TuiCookieJar } from "./cookie-jar.js";
5- 
6-function jsonResponse(
7- status: number,
8- body: unknown,
9- headers?: Record<string, string>,
10-): Response {
11- return new Response(JSON.stringify(body), {
12- status,
13- headers: {
14- "content-type": "application/json",
15- ...headers,
16- },
17- });
18-}
19- 
20-describe("AuthenticatedTransport", () => {
21- it("attaches cookies to all requests and CSRF only to unsafe methods", async () => {
22- const jar = new TuiCookieJar();
23- jar.replace({ df_session: "sess", df_csrf: "csrf-1" });
24- const seen: Array<{ method: string; cookie?: string | null; csrf?: string | null }> = [];
25- const transport = new AuthenticatedTransport({
26- cookieJar: jar,
27- refreshCsrf: async () => {},
28- onSessionInvalid: async () => {},
29- fetchImpl: async (input, init) => {
30- const request = input instanceof Request ? input : new Request(input, init);
31- seen.push({
32- method: request.method,
33- cookie: request.headers.get("cookie"),
34- csrf: request.headers.get("x-csrf-token"),
35- });
36- return jsonResponse(200, { ok: true });
37- },
38- });
39- 
40- await transport.fetch("http://127.0.0.1/api/v1/me");
41- await transport.fetch("http://127.0.0.1/api/v1/datasources", {
42- method: "POST",
43- body: "{}",
44- });
45- 
46- assert.deepEqual(seen, [
47- {
48- method: "GET",
49- cookie: "df_session=sess; df_csrf=csrf-1",
50- csrf: null,
51- },
52- {
53- method: "POST",
54- cookie: "df_session=sess; df_csrf=csrf-1",
55- csrf: "csrf-1",
56- },
57- ]);
58- });
59- 
60- it("invokes onSessionInvalid once on 401 and does not retry the business request", async () => {
61- const jar = new TuiCookieJar();
62- jar.replace({ df_session: "sess", df_csrf: "csrf-1" });
63- let fetches = 0;
64- let invalidCalls = 0;
65- const transport = new AuthenticatedTransport({
66- cookieJar: jar,
67- refreshCsrf: async () => {
68- throw new Error("should not refresh on 401");
69- },
70- onSessionInvalid: async () => {
71- invalidCalls += 1;
72- },
73- fetchImpl: async () => {
74- fetches += 1;
75- return jsonResponse(401, { error: { code: "UNAUTHORIZED" } });
76- },
77- });
78- 
79- const response = await transport.fetch("http://127.0.0.1/api/v1/me");
80- assert.equal(response.status, 401);
81- assert.equal(fetches, 1);
82- assert.equal(invalidCalls, 1);
83- });
84- 
85- it("retries once only for CSRF_INVALID and uses response.clone for code checks", async () => {
86- const jar = new TuiCookieJar();
87- jar.replace({ df_session: "sess", df_csrf: "old" });
88- let fetches = 0;
89- let refreshed = 0;
90- const transport = new AuthenticatedTransport({
91- cookieJar: jar,
92- refreshCsrf: async () => {
93- refreshed += 1;
94- jar.replace({ df_session: "sess", df_csrf: "new" });
95- },
96- onSessionInvalid: async () => {
97- throw new Error("should not invalidate after successful retry");
98- },
99- fetchImpl: async (_input, init) => {
100- fetches += 1;
101- const headers = new Headers(init?.headers);
102- if (fetches === 1) {
103- return jsonResponse(403, { error: { code: "CSRF_INVALID", message: "bad" } });
104- }
105- assert.equal(headers.get("x-csrf-token"), "new");
106- return jsonResponse(200, { success: true, data: { ok: true } });
107- },
108- });
109- 
110- const response = await transport.fetch("http://127.0.0.1/api/v1/datasources", {
111- method: "POST",
112- headers: { "content-type": "application/json" },
113- body: JSON.stringify({ id: "x" }),
114- });
115- const body = await response.json() as { success: boolean };
116- assert.equal(response.status, 200);
117- assert.equal(body.success, true);
118- assert.equal(fetches, 2);
119- assert.equal(refreshed, 1);
120- });
121- 
122- it("does not retry other 403 responses", async () => {
123- const jar = new TuiCookieJar();
124- jar.replace({ df_session: "sess", df_csrf: "csrf" });
125- let fetches = 0;
126- const transport = new AuthenticatedTransport({
127- cookieJar: jar,
128- refreshCsrf: async () => {
129- throw new Error("should not refresh");
130- },
131- onSessionInvalid: async () => {},
132- fetchImpl: async () => {
133- fetches += 1;
134- return jsonResponse(403, { error: { code: "FORBIDDEN", message: "no" } });
135- },
136- });
137- 
138- const response = await transport.fetch("http://127.0.0.1/api/v1/datasources", {
139- method: "POST",
140- body: "{}",
141- });
142- assert.equal(response.status, 403);
143- assert.equal(fetches, 1);
144- });
145- 
146- it("invalidates session when Request body cannot be cloned for CSRF retry", async () => {
147- const jar = new TuiCookieJar();
148- jar.replace({ df_session: "sess", df_csrf: "csrf" });
149- let invalid = 0;
150- const stream = new ReadableStream({
151- start(controller) {
152- controller.enqueue(new TextEncoder().encode("{}"));
153- controller.close();
154- },
155- });
156- const request = new Request("http://127.0.0.1/api/v1/datasources", {
157- method: "POST",
158- body: stream,
159- // @ts-expect-error Node fetch duplex
160- duplex: "half",
161- });
162- // Consume clone ability by locking in environments that disallow second clone.
163- const transport = new AuthenticatedTransport({
164- cookieJar: jar,
165- refreshCsrf: async () => {},
166- onSessionInvalid: async () => {
167- invalid += 1;
168- },
169- fetchImpl: async () => jsonResponse(403, { error: { code: "CSRF_INVALID" } }),
170- });
171- 
172- // Force non-replayable by passing stream body via init.
173- const response = await transport.fetch("http://127.0.0.1/api/v1/datasources", {
174- method: "POST",
175- body: new ReadableStream({
176- start(controller) {
177- controller.enqueue(new TextEncoder().encode("{}"));
178- controller.close();
179- },
180- }),
181- // @ts-expect-error Node fetch duplex
182- duplex: "half",
183- });
184- assert.equal(response.status, 403);
185- assert.equal(invalid, 1);
186- void request;
187- });
188- 
189- it("single-flights concurrent CSRF refresh", async () => {
190- const jar = new TuiCookieJar();
191- jar.replace({ df_session: "sess", df_csrf: "old" });
192- let refreshCalls = 0;
193- let releaseRefresh!: () => void;
194- const refreshGate = new Promise<void>((resolve) => {
195- releaseRefresh = resolve;
196- });
197- const transport = new AuthenticatedTransport({
198- cookieJar: jar,
199- refreshCsrf: async () => {
200- refreshCalls += 1;
201- jar.replace({ df_session: "sess", df_csrf: "new" });
202- await refreshGate;
203- },
204- onSessionInvalid: async () => {},
205- fetchImpl: async (input, init) => {
206- const method = String(init?.method ?? "GET");
207- if (method === "POST" && jar.csrfToken() === "old") {
208- return jsonResponse(403, { error: { code: "CSRF_INVALID" } });
209- }
210- return jsonResponse(200, { ok: true });
211- },
212- });
213- 
214- const pending = Promise.all([
215- transport.fetch("http://127.0.0.1/api/v1/a", { method: "POST", body: "{}" }),
216- transport.fetch("http://127.0.0.1/api/v1/b", { method: "POST", body: "{}" }),
217- ]);
218- await new Promise((resolve) => setImmediate(resolve));
219- assert.equal(refreshCalls, 1);
220- releaseRefresh();
221- const responses = await pending;
222- assert.equal(refreshCalls, 1);
223- assert.deepEqual(responses.map((response) => response.status), [200, 200]);
224- });
225- 
226- it("invalidates session when CSRF refresh fails", async () => {
227- const jar = new TuiCookieJar();
228- jar.replace({ df_session: "sess", df_csrf: "old" });
229- let invalid = 0;
230- let authRequired = 0;
231- const transport = new AuthenticatedTransport({
232- cookieJar: jar,
233- refreshCsrf: async () => {
234- throw new Error("refresh 401");
235- },
236- onSessionInvalid: async () => {
237- invalid += 1;
238- },
239- fetchImpl: async () => jsonResponse(403, { error: { code: "CSRF_INVALID" } }),
240- });
241- transport.onAuthRequired(() => {
242- authRequired += 1;
243- });
244- 
245- const response = await transport.fetch("http://127.0.0.1/api/v1/datasources", {
246- method: "POST",
247- body: "{}",
248- });
249- assert.equal(response.status, 403);
250- assert.equal(invalid, 1);
251- assert.equal(authRequired, 1);
252- });
253- 
254- it("notifies auth-required listeners once on 401", async () => {
255- const jar = new TuiCookieJar();
256- jar.replace({ df_session: "sess", df_csrf: "csrf" });
257- let authRequired = 0;
258- let invalidCalls = 0;
259- const transport = new AuthenticatedTransport({
260- cookieJar: jar,
261- refreshCsrf: async () => {},
262- onSessionInvalid: async () => {
263- invalidCalls += 1;
264- },
265- fetchImpl: async () => jsonResponse(401, { error: { code: "UNAUTHORIZED" } }),
266- });
267- transport.onAuthRequired(() => {
268- authRequired += 1;
269- });
270- 
271- await transport.fetch("http://127.0.0.1/api/v1/me");
272- await transport.fetch("http://127.0.0.1/api/v1/me");
273- assert.equal(authRequired, 1);
274- assert.equal(invalidCalls, 1);
275- });
276- 
277- it("still notifies auth-required when onSessionInvalid cleanup throws", async () => {
278- const jar = new TuiCookieJar();
279- jar.replace({ df_session: "sess", df_csrf: "csrf" });
280- let authRequired = 0;
281- const transport = new AuthenticatedTransport({
282- cookieJar: jar,
283- refreshCsrf: async () => {},
284- onSessionInvalid: async () => {
285- throw new Error("disk locked");
286- },
287- fetchImpl: async () => jsonResponse(401, { error: { code: "UNAUTHORIZED" } }),
288- });
289- transport.onAuthRequired(() => {
290- authRequired += 1;
291- });
292- 
293- const response = await transport.fetch("http://127.0.0.1/api/v1/me");
294- assert.equal(response.status, 401);
295- assert.equal(authRequired, 1);
296- 
297- // Sticky replay for late subscribers must still work after a failed cleanup.
298- let late = 0;
299- transport.onAuthRequired(() => {
300- late += 1;
301- });
302- assert.equal(late, 1);
303- });
304- 
305- it("dedups concurrent 401 cleanup before onSessionInvalid side effects", async () => {
306- const jar = new TuiCookieJar();
307- jar.replace({ df_session: "sess", df_csrf: "csrf" });
308- let invalidCalls = 0;
309- let releaseCleanup!: () => void;
310- const cleanupGate = new Promise<void>((resolve) => {
311- releaseCleanup = resolve;
312- });
313- const transport = new AuthenticatedTransport({
314- cookieJar: jar,
315- refreshCsrf: async () => {},
316- onSessionInvalid: async () => {
317- invalidCalls += 1;
318- await cleanupGate;
319- },
320- fetchImpl: async () => jsonResponse(401, { error: { code: "UNAUTHORIZED" } }),
321- });
322- 
323- const pending = Promise.all([
324- transport.fetch("http://127.0.0.1/api/v1/a"),
325- transport.fetch("http://127.0.0.1/api/v1/b"),
326- ]);
327- await new Promise((resolve) => setImmediate(resolve));
328- assert.equal(invalidCalls, 1);
329- releaseCleanup();
330- await pending;
331- assert.equal(invalidCalls, 1);
332- });
333- 
334- it("retries CSRF_INVALID with jar token when single-flight already advanced it", async () => {
335- const jar = new TuiCookieJar();
336- jar.replace({ df_session: "sess", df_csrf: "old" });
337- let refreshCalls = 0;
338- let fetches = 0;
339- const transport = new AuthenticatedTransport({
340- cookieJar: jar,
341- refreshCsrf: async () => {
342- refreshCalls += 1;
343- jar.replace({ df_session: "sess", df_csrf: "from-refresh" });
344- },
345- onSessionInvalid: async () => {
346- throw new Error("should not invalidate");
347- },
348- fetchImpl: async (_input, init) => {
349- fetches += 1;
350- const headers = new Headers(init?.headers);
351- if (fetches === 1) {
352- // Simulate a peer request refreshing CSRF while this one is in flight.
353- jar.replace({ df_session: "sess", df_csrf: "peer-new" });
354- return jsonResponse(403, { error: { code: "CSRF_INVALID" } });
355- }
356- assert.equal(headers.get("x-csrf-token"), "peer-new");
357- return jsonResponse(200, { ok: true });
358- },
359- });
360- 
361- const response = await transport.fetch("http://127.0.0.1/api/v1/datasources", {
362- method: "POST",
363- body: "{}",
364- });
365- assert.equal(response.status, 200);
366- assert.equal(refreshCalls, 0);
367- assert.equal(fetches, 2);
368- });
369- 
370- it("replays sticky auth-required when listener subscribes after 401", async () => {
371- const jar = new TuiCookieJar();
372- jar.replace({ df_session: "sess", df_csrf: "csrf" });
373- let invalidCalls = 0;
374- const transport = new AuthenticatedTransport({
375- cookieJar: jar,
376- refreshCsrf: async () => {},
377- onSessionInvalid: async () => {
378- invalidCalls += 1;
379- },
380- fetchImpl: async () => jsonResponse(401, { error: { code: "UNAUTHORIZED" } }),
381- });
382- 
383- await transport.fetch("http://127.0.0.1/api/v1/run-defaults");
384- assert.equal(invalidCalls, 1);
385- 
386- let lateListenerCalls = 0;
387- transport.onAuthRequired(() => {
388- lateListenerCalls += 1;
389- });
390- assert.equal(lateListenerCalls, 1);
391- 
392- let secondLateCalls = 0;
393- transport.onAuthRequired(() => {
394- secondLateCalls += 1;
395- });
396- assert.equal(secondLateCalls, 1);
397- assert.equal(lateListenerCalls, 1);
398- });
399- 
400- it("keeps sensitive headers out of thrown error messages", async () => {
401- const jar = new TuiCookieJar();
402- jar.replace({ df_session: "super-secret", df_csrf: "csrf-secret" });
403- const transport = new AuthenticatedTransport({
404- cookieJar: jar,
405- refreshCsrf: async () => {},
406- onSessionInvalid: async () => {},
407- fetchImpl: async () => {
408- throw new Error("network down");
409- },
410- });
411- 
412- await assert.rejects(
413- () => transport.fetch("http://127.0.0.1/api/v1/me"),
414- (error: unknown) => {
415- const message = error instanceof Error ? error.message : String(error);
416- assert.equal(message.includes("super-secret"), false);
417- assert.equal(message.includes("csrf-secret"), false);
418- return true;
419- },
420- );
421- });
422- 
423- it("uses redirect:manual so open redirects cannot poison the cookie jar", async () => {
424- const jar = new TuiCookieJar();
425- jar.replace({ df_session: "good", df_csrf: "csrf" });
426- let seenRedirect: RequestRedirect | undefined;
427- const transport = new AuthenticatedTransport({
428- cookieJar: jar,
429- refreshCsrf: async () => {},
430- onSessionInvalid: async () => {
431- throw new Error("redirect must not invalidate the session");
432- },
433- fetchImpl: async (_input, init) => {
434- seenRedirect = init?.redirect;
435- // With redirect:manual the client must surface the hop, never follow to evil.
436- return new Response(null, {
437- status: 302,
438- headers: {
439- Location: "http://127.0.0.1:9/evil",
440- "Set-Cookie": "df_session=POISONED; Path=/",
441- },
442- });
443- },
444- });
445- 
446- const response = await transport.fetch("http://127.0.0.1:8787/api/v1/me");
447- assert.equal(seenRedirect, "manual");
448- assert.equal(response.status, 302);
449- // Same-origin 302 Set-Cookie from the API is still absorbed; the security win is
450- // never fetching the Location target (whose Set-Cookie would otherwise replace df_session).
451- assert.equal(jar.snapshot().df_session, "POISONED");
452- });
453-});
@@ -1,209 +0,0 @@
1-import type { TuiCookieJar } from "./cookie-jar.js";
2- 
3-const UNSAFE_METHODS = new Set(["POST", "PUT", "PATCH", "DELETE"]);
4- 
5-export type AuthenticatedTransportOptions = {
6- cookieJar: TuiCookieJar;
7- fetchImpl?: typeof fetch;
8- refreshCsrf: () => Promise<void>;
9- onSessionInvalid: () => Promise<void>;
10-};
11- 
12-export class AuthenticatedTransport {
13- private readonly cookieJar: TuiCookieJar;
14- private readonly fetchImpl: typeof fetch;
15- private readonly refreshCsrf: () => Promise<void>;
16- private readonly onSessionInvalid: () => Promise<void>;
17- private readonly authRequiredListeners = new Set<() => void>();
18- private sessionInvalidNotified = false;
19- private sessionInvalidInflight: Promise<void> | null = null;
20- private csrfRefreshInflight: Promise<void> | null = null;
21- 
22- constructor(options: AuthenticatedTransportOptions) {
23- this.cookieJar = options.cookieJar;
24- this.fetchImpl = options.fetchImpl ?? globalThis.fetch.bind(globalThis);
25- this.refreshCsrf = options.refreshCsrf;
26- this.onSessionInvalid = options.onSessionInvalid;
27- }
28- 
29- /** Subscribe to session-invalid signals (401 / failed CSRF recovery). */
30- onAuthRequired(listener: () => void): () => void {
31- this.authRequiredListeners.add(listener);
32- // Sticky: preflight may 401 before Ink registers a listener — replay immediately.
33- if (this.sessionInvalidNotified) {
34- try {
35- listener();
36- } catch {
37- // Listeners must not break transport cleanup.
38- }
39- }
40- return () => {
41- this.authRequiredListeners.delete(listener);
42- };
43- }
44- 
45- async fetch(input: string | URL | Request, init?: RequestInit): Promise<Response> {
46- const { first, replay } = createReplayPair(input, init);
47- const csrfUsed = this.cookieJar.csrfToken();
48- const response = await this.send(first.input, first.init);
49- this.cookieJar.absorbSetCookie(response.headers);
50- 
51- if (response.status === 401) {
52- await this.handleSessionInvalid();
53- return response;
54- }
55- 
56- if (response.status !== 403 || !(await isCsrfInvalid(response))) {
57- return response;
58- }
59- 
60- if (!replay) {
61- await this.handleSessionInvalid();
62- return response;
63- }
64- 
65- const csrfNow = this.cookieJar.csrfToken();
66- const jarAlreadyAdvanced = Boolean(
67- csrfUsed
68- && csrfNow
69- && csrfNow !== csrfUsed,
70- );
71- 
72- if (!jarAlreadyAdvanced) {
73- try {
74- await this.refreshCsrfSingleFlight();
75- } catch {
76- // CSRF refresh 401/network failure: same recovery path as session invalid.
77- await this.handleSessionInvalid();
78- return response;
79- }
80- }
81- 
82- const retried = await this.send(replay.input, replay.init);
83- this.cookieJar.absorbSetCookie(retried.headers);
84- 
85- if (
86- retried.status === 401
87- || (retried.status === 403 && (await isCsrfInvalid(retried)))
88- ) {
89- await this.handleSessionInvalid();
90- }
91- return retried;
92- }
93- 
94- private async handleSessionInvalid(): Promise<void> {
95- // Dedup sticky flag BEFORE cleanup side effects so concurrent 401s share one path.
96- if (!this.sessionInvalidInflight) {
97- this.sessionInvalidNotified = true;
98- this.sessionInvalidInflight = this.runSessionInvalid();
99- }
100- await this.sessionInvalidInflight;
101- }
102- 
103- private async runSessionInvalid(): Promise<void> {
104- try {
105- await this.onSessionInvalid();
106- } catch {
107- // Disk/cleanup failures must not block auth-required UX; jar clear is best-effort
108- // inside onSessionInvalid. Sticky notification still proceeds below.
109- }
110- for (const listener of this.authRequiredListeners) {
111- try {
112- listener();
113- } catch {
114- // Listeners must not break transport cleanup.
115- }
116- }
117- }
118- 
119- /** Share one in-flight CSRF refresh across concurrent 403 CSRF_INVALID callers. */
120- private async refreshCsrfSingleFlight(): Promise<void> {
121- if (!this.csrfRefreshInflight) {
122- this.csrfRefreshInflight = this.refreshCsrf().finally(() => {
123- this.csrfRefreshInflight = null;
124- });
125- }
126- await this.csrfRefreshInflight;
127- }
128- 
129- private async send(
130- input: string | URL | Request,
131- init?: RequestInit,
132- ): Promise<Response> {
133- // Never auto-follow redirects: a hop to another origin can return Set-Cookie
134- // that would overwrite df_session/df_csrf in the jar (open-redirect poison).
135- if (input instanceof Request) {
136- const headers = new Headers(input.headers);
137- applyAuthHeaders(headers, input.method, this.cookieJar);
138- return this.fetchImpl(new Request(input, { headers, redirect: "manual" }));
139- }
140- 
141- const headers = new Headers(init?.headers);
142- const method = String(init?.method ?? "GET");
143- applyAuthHeaders(headers, method, this.cookieJar);
144- return this.fetchImpl(input, { ...init, headers, redirect: "manual" });
145- }
146-}
147- 
148-function applyAuthHeaders(
149- headers: Headers,
150- method: string,
151- cookieJar: TuiCookieJar,
152-): void {
153- const cookieHeader = cookieJar.headerValue();
154- if (cookieHeader) {
155- headers.set("cookie", cookieHeader);
156- }
157- if (UNSAFE_METHODS.has(method.toUpperCase())) {
158- const csrf = cookieJar.csrfToken();
159- if (csrf && !headers.has("x-csrf-token")) {
160- headers.set("x-csrf-token", csrf);
161- }
162- }
163-}
164- 
165-function createReplayPair(
166- input: string | URL | Request,
167- init?: RequestInit,
168-): {
169- first: { input: string | URL | Request; init?: RequestInit };
170- replay?: { input: string | URL | Request; init?: RequestInit };
171-} {
172- if (input instanceof Request) {
173- try {
174- const replayRequest = input.clone();
175- return {
176- first: { input },
177- replay: { input: replayRequest },
178- };
179- } catch {
180- return { first: { input } };
181- }
182- }
183- 
184- if (init?.body && isNonReplayableBody(init.body)) {
185- return { first: { input, ...(init ? { init } : {}) } };
186- }
187- 
188- const replayInit = init ? { ...init } : undefined;
189- return {
190- first: { input, ...(init ? { init } : {}) },
191- replay: { input, ...(replayInit ? { init: replayInit } : {}) },
192- };
193-}
194- 
195-function isNonReplayableBody(body: BodyInit): boolean {
196- return typeof ReadableStream !== "undefined" && body instanceof ReadableStream;
197-}
198- 
199-async function isCsrfInvalid(response: Response): Promise<boolean> {
200- try {
201- const body = await response.clone().json() as {
202- error?: { code?: string };
203- code?: string;
204- };
205- return body?.error?.code === "CSRF_INVALID" || body?.code === "CSRF_INVALID";
206- } catch {
207- return false;
208- }
209-}
@@ -1,296 +0,0 @@
1-import assert from "node:assert/strict";
2-import { mkdtemp } from "node:fs/promises";
3-import { tmpdir } from "node:os";
4-import { join } from "node:path";
5-import { describe, it } from "node:test";
6-import {
7- bootstrapTuiAuth,
8- completeInteractiveLogin,
9- createAuthController,
10- SESSION_EXPIRY_TOLERANCE_MS,
11-} from "./bootstrap.js";
12-import { TuiAuthClient } from "./auth-client.js";
13-import { TuiCookieJar } from "./cookie-jar.js";
14-import { TuiSessionStore } from "./session-store.js";
15-import type { StoredTuiSession } from "./types.js";
16- 
17-function statusOk(): Response {
18- return json(200, {
19- success: true,
20- data: { publicBaseUrl: "http://127.0.0.1:3000", registrationEnabled: true },
21- });
22-}
23- 
24-describe("bootstrapTuiAuth", () => {
25- it("restores cached session via GET /api/v1/me", async () => {
26- const dir = await mkdtemp(join(tmpdir(), "tui-bootstrap-"));
27- const store = new TuiSessionStore({ filePath: join(dir, "tui-auth.json") });
28- const session = sampleSession("http://127.0.0.1:8787");
29- await store.save(session);
30- const paths: string[] = [];
31- 
32- const result = await bootstrapTuiAuth({
33- apiBaseUrl: "http://127.0.0.1:8787",
34- sessionStore: store,
35- fetchImpl: async (input) => {
36- const path = new URL(String(input)).pathname;
37- paths.push(path);
38- if (path === "/api/v1/auth/status") return statusOk();
39- if (path === "/api/v1/me") {
40- return json(200, {
41- success: true,
42- data: {
43- user: { id: "u1", email: "a@example.com", displayName: "A" },
44- workspace: { id: "w1", name: "Personal" },
45- },
46- });
47- }
48- return json(404, { success: false, error: { code: "NOT_FOUND", message: "x" } });
49- },
50- });
51- 
52- assert.equal(result.kind, "authenticated");
53- assert.deepEqual(paths, ["/api/v1/auth/status", "/api/v1/me"]);
54- });
55- 
56- it("skips /me only when expiresAt is beyond tolerance", async () => {
57- const dir = await mkdtemp(join(tmpdir(), "tui-bootstrap-exp-"));
58- const store = new TuiSessionStore({ filePath: join(dir, "tui-auth.json") });
59- const now = Date.UTC(2026, 0, 1, 12, 0, 0);
60- await store.save({
61- ...sampleSession("http://127.0.0.1:8787"),
62- expiresAt: new Date(now - SESSION_EXPIRY_TOLERANCE_MS - 1).toISOString(),
63- });
64- const paths: string[] = [];
65- 
66- const result = await bootstrapTuiAuth({
67- apiBaseUrl: "http://127.0.0.1:8787",
68- sessionStore: store,
69- now: () => now,
70- fetchImpl: async (input) => {
71- paths.push(new URL(String(input)).pathname);
72- return statusOk();
73- },
74- });
75- 
76- assert.equal(result.kind, "login-required");
77- assert.deepEqual(paths, ["/api/v1/auth/status"]);
78- });
79- 
80- it("still calls /me when expiresAt is within tolerance", async () => {
81- const dir = await mkdtemp(join(tmpdir(), "tui-bootstrap-tol-"));
82- const store = new TuiSessionStore({ filePath: join(dir, "tui-auth.json") });
83- const now = Date.UTC(2026, 0, 1, 12, 0, 0);
84- await store.save({
85- ...sampleSession("http://127.0.0.1:8787"),
86- expiresAt: new Date(now - SESSION_EXPIRY_TOLERANCE_MS + 1_000).toISOString(),
87- });
88- const paths: string[] = [];
89- 
90- await bootstrapTuiAuth({
91- apiBaseUrl: "http://127.0.0.1:8787",
92- sessionStore: store,
93- now: () => now,
94- fetchImpl: async (input) => {
95- const path = new URL(String(input)).pathname;
96- paths.push(path);
97- if (path === "/api/v1/auth/status") return statusOk();
98- return json(401, { success: false, error: { code: "UNAUTHORIZED", message: "gone" } });
99- },
100- });
101- 
102- assert.ok(paths.includes("/api/v1/me"));
103- });
104- 
105- it("ignores cache restore when --no-auto-login is set but keeps previousSession", async () => {
106- const dir = await mkdtemp(join(tmpdir(), "tui-bootstrap-noauto-"));
107- const store = new TuiSessionStore({ filePath: join(dir, "tui-auth.json") });
108- const cached = sampleSession("http://127.0.0.1:8787");
109- await store.save(cached);
110- const paths: string[] = [];
111- 
112- const result = await bootstrapTuiAuth({
113- apiBaseUrl: "http://127.0.0.1:8787",
114- noAutoLogin: true,
115- sessionStore: store,
116- fetchImpl: async (input) => {
117- paths.push(new URL(String(input)).pathname);
118- return statusOk();
119- },
120- });
121- 
122- assert.equal(result.kind, "login-required");
123- assert.deepEqual(paths, ["/api/v1/auth/status"]);
124- if (result.kind === "login-required") {
125- assert.equal(result.previousSession?.user.email, cached.user.email);
126- assert.equal(result.previousSession?.cookies.df_session, "sess");
127- }
128- });
129-});
130- 
131-describe("completeInteractiveLogin", () => {
132- it("does not overwrite cache when login fails", async () => {
133- const dir = await mkdtemp(join(tmpdir(), "tui-login-fail-"));
134- const store = new TuiSessionStore({ filePath: join(dir, "tui-auth.json") });
135- const previous = sampleSession("http://127.0.0.1:8787", "old@example.com");
136- await store.save(previous);
137- 
138- await assert.rejects(() =>
139- completeInteractiveLogin({
140- apiBaseUrl: "http://127.0.0.1:8787",
141- email: "new@example.com",
142- password: "bad",
143- fetchImpl: async () =>
144- json(401, {
145- success: false,
146- error: { code: "UNAUTHORIZED", message: "Invalid email or password." },
147- }),
148- sessionStore: store,
149- previousSession: previous,
150- }));
151- 
152- const still = await store.load("http://127.0.0.1:8787");
153- assert.equal(still?.user.email, "old@example.com");
154- });
155- 
156- it("best-effort logs out previous session then saves the new one", async () => {
157- const dir = await mkdtemp(join(tmpdir(), "tui-login-ok-"));
158- const store = new TuiSessionStore({ filePath: join(dir, "tui-auth.json") });
159- const previous = sampleSession("http://127.0.0.1:8787", "old@example.com");
160- previous.cookies = { df_session: "old-sess", df_csrf: "old-csrf" };
161- await store.save(previous);
162- const paths: string[] = [];
163- 
164- const result = await completeInteractiveLogin({
165- apiBaseUrl: "http://127.0.0.1:8787",
166- email: "new@example.com",
167- password: "good-password",
168- sessionStore: store,
169- previousSession: previous,
170- fetchImpl: async (input, init) => {
171- const path = new URL(String(input)).pathname;
172- paths.push(`${String(init?.method ?? "GET")} ${path}`);
173- if (path === "/api/v1/auth/login") {
174- return json(
175- 200,
176- {
177- success: true,
178- data: {
179- user: { id: "u2", email: "new@example.com" },
180- workspace: { id: "w2" },
181- session: { expiresAt: "2099-01-01T00:00:00.000Z" },
182- },
183- },
184- ["df_session=new-sess; Path=/", "df_csrf=new-csrf; Path=/"],
185- );
186- }
187- if (path === "/api/v1/auth/logout") {
188- return json(200, { success: true, data: { ok: true } });
189- }
190- return json(404, { success: false, error: { code: "NOT_FOUND", message: "x" } });
191- },
192- });
193- 
194- assert.equal(result.session.user.email, "new@example.com");
195- assert.ok(paths.includes("POST /api/v1/auth/logout"));
196- const saved = await store.load("http://127.0.0.1:8787");
197- assert.equal(saved?.user.email, "new@example.com");
198- });
199- 
200- it("keeps new account and warns when old logout fails", async () => {
201- const dir = await mkdtemp(join(tmpdir(), "tui-login-warn-"));
202- const store = new TuiSessionStore({ filePath: join(dir, "tui-auth.json") });
203- const previous = sampleSession("http://127.0.0.1:8787", "old@example.com");
204- previous.cookies = { df_session: "old-sess", df_csrf: "old-csrf" };
205- 
206- const result = await completeInteractiveLogin({
207- apiBaseUrl: "http://127.0.0.1:8787",
208- email: "new@example.com",
209- password: "good-password",
210- sessionStore: store,
211- previousSession: previous,
212- fetchImpl: async (input) => {
213- const path = new URL(String(input)).pathname;
214- if (path === "/api/v1/auth/login") {
215- return json(
216- 200,
217- {
218- success: true,
219- data: {
220- user: { id: "u2", email: "new@example.com" },
221- workspace: { id: "w2" },
222- session: { expiresAt: "2099-01-01T00:00:00.000Z" },
223- },
224- },
225- ["df_session=new-sess; Path=/", "df_csrf=new-csrf; Path=/"],
226- );
227- }
228- return json(503, { success: false, error: { code: "UNAVAILABLE", message: "down" } });
229- },
230- });
231- 
232- assert.equal(result.session.user.email, "new@example.com");
233- assert.match(result.warning ?? "", /previous remote session/i);
234- });
235-});
236- 
237-describe("createAuthController", () => {
238- it("distinguishes remote logout failure from local cleanup failure", async () => {
239- const dir = await mkdtemp(join(tmpdir(), "tui-logout-"));
240- const store = new TuiSessionStore({ filePath: join(dir, "tui-auth.json") });
241- await store.save(sampleSession("http://127.0.0.1:8787"));
242- 
243- const remoteFailed = createAuthController({
244- apiBaseUrl: "http://127.0.0.1:8787",
245- sessionStore: store,
246- authClient: new TuiAuthClient({
247- apiBaseUrl: "http://127.0.0.1:8787",
248- cookieJar: new TuiCookieJar(),
249- fetchImpl: async () => json(503, { success: false, error: { code: "DOWN", message: "x" } }),
250- }),
251- });
252- const remote = await remoteFailed.logout();
253- assert.equal(remote.kind, "remote-failed");
254- 
255- const jar = new TuiCookieJar();
256- jar.replace({ df_session: "sess", df_csrf: "csrf" });
257- const localFailed = createAuthController({
258- apiBaseUrl: "http://127.0.0.1:8787",
259- sessionStore: {
260- path: store.path,
261- async remove() {
262- throw new Error("disk full");
263- },
264- } as unknown as TuiSessionStore,
265- authClient: new TuiAuthClient({
266- apiBaseUrl: "http://127.0.0.1:8787",
267- cookieJar: jar,
268- fetchImpl: async () => json(200, { success: true, data: { ok: true } }),
269- }),
270- });
271- const local = await localFailed.logout();
272- assert.equal(local.kind, "local-cleanup-failed");
273- if (local.kind === "local-cleanup-failed") {
274- assert.equal(local.storePath, store.path);
275- assert.match(local.error, /disk full/i);
276- }
277- });
278-});
279- 
280-function sampleSession(apiBaseUrl: string, email = "a@example.com"): StoredTuiSession {
281- return {
282- apiBaseUrl,
283- cookies: { df_session: "sess", df_csrf: "csrf" },
284- user: { id: "u1", email },
285- workspace: { id: "w1" },
286- expiresAt: "2099-01-01T00:00:00.000Z",
287- };
288-}
289- 
290-function json(status: number, body: unknown, setCookies: string[] = []): Response {
291- const headers = new Headers({ "content-type": "application/json" });
292- for (const cookie of setCookies) {
293- headers.append("set-cookie", cookie);
294- }
295- return new Response(JSON.stringify(body), { status, headers });
296-}
@@ -1,260 +0,0 @@
1-import { AuthenticatedTransport } from "./authenticated-transport.js";
2-import { TuiAuthClient, TuiAuthError } from "./auth-client.js";
3-import { TuiCookieJar } from "./cookie-jar.js";
4-import { normalizeApiBaseUrl, TuiSessionStore } from "./session-store.js";
5-import type { AuthStatus, StoredTuiSession } from "./types.js";
6- 
7-/** Local expiresAt may lag clock skew; only skip /me beyond this grace. */
8-export const SESSION_EXPIRY_TOLERANCE_MS = 60_000;
9- 
10-export type BootstrapAuthOptions = {
11- apiBaseUrl: string;
12- noAutoLogin?: boolean;
13- sessionStore?: TuiSessionStore;
14- fetchImpl?: typeof fetch;
15- now?: () => number;
16-};
17- 
18-export type BootstrapAuthResult =
19- | {
20- kind: "authenticated";
21- session: StoredTuiSession;
22- transport: AuthenticatedTransport;
23- authClient: TuiAuthClient;
24- cookieJar: TuiCookieJar;
25- sessionStore: TuiSessionStore;
26- warning?: string;
27- }
28- | {
29- kind: "login-required";
30- status: AuthStatus;
31- previousSession?: StoredTuiSession;
32- authClient: TuiAuthClient;
33- cookieJar: TuiCookieJar;
34- sessionStore: TuiSessionStore;
35- };
36- 
37-export async function bootstrapTuiAuth(
38- options: BootstrapAuthOptions,
39-): Promise<BootstrapAuthResult> {
40- const apiBaseUrl = normalizeApiBaseUrl(options.apiBaseUrl);
41- const sessionStore = options.sessionStore ?? new TuiSessionStore();
42- const cookieJar = new TuiCookieJar();
43- const fetchImpl = options.fetchImpl ?? globalThis.fetch.bind(globalThis);
44- const authClient = new TuiAuthClient({ apiBaseUrl, cookieJar, fetchImpl });
45- const now = options.now ?? Date.now;
46- const status = await authClient.getStatus();
47- const cached = await sessionStore.load(apiBaseUrl);
48- 
49- // --no-auto-login: do not restore cookies / call /me, but keep the cached
50- // session as previousSession so a successful re-login can revoke it remotely.
51- if (options.noAutoLogin) {
52- return {
53- kind: "login-required",
54- status,
55- ...(cached ? { previousSession: cached } : {}),
56- authClient,
57- cookieJar,
58- sessionStore,
59- };
60- }
61- 
62- if (!cached) {
63- return {
64- kind: "login-required",
65- status,
66- authClient,
67- cookieJar,
68- sessionStore,
69- };
70- }
71- 
72- if (isExpiredBeyondTolerance(cached.expiresAt, now())) {
73- await sessionStore.remove(apiBaseUrl);
74- return {
75- kind: "login-required",
76- status,
77- previousSession: cached,
78- authClient,
79- cookieJar,
80- sessionStore,
81- };
82- }
83- 
84- cookieJar.replace(cached.cookies);
85- try {
86- const me = await authClient.me();
87- const session: StoredTuiSession = {
88- ...cached,
89- user: {
90- id: me.id,
91- email: me.email,
92- ...(me.displayName ? { displayName: me.displayName } : {}),
93- },
94- workspace: me.workspace,
95- cookies: cookieJar.snapshot(),
96- };
97- await sessionStore.save(session);
98- return {
99- kind: "authenticated",
100- session,
101- transport: createTransport({ cookieJar, authClient, sessionStore, apiBaseUrl, fetchImpl }),
102- authClient,
103- cookieJar,
104- sessionStore,
105- };
106- } catch (error) {
107- if (error instanceof TuiAuthError && (error.status === 401 || error.code === "UNAUTHORIZED")) {
108- await sessionStore.remove(apiBaseUrl);
109- cookieJar.clear();
110- return {
111- kind: "login-required",
112- status,
113- previousSession: cached,
114- authClient,
115- cookieJar,
116- sessionStore,
117- };
118- }
119- throw error;
120- }
121-}
122- 
123-export async function completeInteractiveLogin(options: {
124- apiBaseUrl: string;
125- email: string;
126- password: string;
127- fetchImpl: typeof fetch;
128- sessionStore: TuiSessionStore;
129- previousSession?: StoredTuiSession;
130-}): Promise<{
131- session: StoredTuiSession;
132- transport: AuthenticatedTransport;
133- authClient: TuiAuthClient;
134- cookieJar: TuiCookieJar;
135- warning?: string;
136-}> {
137- const apiBaseUrl = normalizeApiBaseUrl(options.apiBaseUrl);
138- const loginJar = new TuiCookieJar();
139- const loginClient = new TuiAuthClient({
140- apiBaseUrl,
141- cookieJar: loginJar,
142- fetchImpl: options.fetchImpl,
143- });
144- 
145- // Login uses a fresh jar so failures never mutate the previous in-memory session.
146- const session = await loginClient.login(options.email, options.password);
147- 
148- let warning: string | undefined;
149- if (options.previousSession?.cookies && Object.keys(options.previousSession.cookies).length > 0) {
150- try {
151- const oldJar = new TuiCookieJar();
152- oldJar.replace(options.previousSession.cookies);
153- const oldClient = new TuiAuthClient({
154- apiBaseUrl,
155- cookieJar: oldJar,
156- fetchImpl: options.fetchImpl,
157- });
158- await oldClient.logout();
159- } catch {
160- warning =
161- "Signed in with the new account, but the previous remote session could not be revoked.";
162- }
163- }
164- 
165- await options.sessionStore.save(session);
166- const cookieJar = loginJar;
167- const authClient = loginClient;
168- return {
169- session,
170- authClient,
171- cookieJar,
172- transport: createTransport({
173- cookieJar,
174- authClient,
175- sessionStore: options.sessionStore,
176- apiBaseUrl,
177- fetchImpl: options.fetchImpl,
178- }),
179- ...(warning ? { warning } : {}),
180- };
181-}
182- 
183-export function createTransport(options: {
184- cookieJar: TuiCookieJar;
185- authClient: TuiAuthClient;
186- sessionStore: TuiSessionStore;
187- apiBaseUrl: string;
188- fetchImpl: typeof fetch;
189-}): AuthenticatedTransport {
190- const apiBaseUrl = normalizeApiBaseUrl(options.apiBaseUrl);
191- return new AuthenticatedTransport({
192- cookieJar: options.cookieJar,
193- fetchImpl: options.fetchImpl,
194- refreshCsrf: () => options.authClient.refreshCsrf(),
195- onSessionInvalid: async () => {
196- options.cookieJar.clear();
197- try {
198- await options.sessionStore.remove(apiBaseUrl);
199- } catch {
200- // Prefer clearing the in-memory jar and surfacing auth-required over crashing
201- // the transport when the on-disk store is locked or unwritable.
202- }
203- },
204- });
205-}
206- 
207-/** Wire Ink exit when the shared transport observes an invalidated session. */
208-export function bindTransportAuthRequired(
209- transport: AuthenticatedTransport,
210- onAuthRequired: () => void,
211-): () => void {
212- return transport.onAuthRequired(onAuthRequired);
213-}
214- 
215-export function isExpiredBeyondTolerance(expiresAt: string, nowMs: number): boolean {
216- const expiresMs = Date.parse(expiresAt);
217- if (Number.isNaN(expiresMs)) {
218- return true;
219- }
220- return nowMs > expiresMs + SESSION_EXPIRY_TOLERANCE_MS;
221-}
222- 
223-export function createAuthController(options: {
224- apiBaseUrl: string;
225- authClient: TuiAuthClient;
226- sessionStore: TuiSessionStore;
227-}): import("./types.js").AuthCommandController {
228- const apiBaseUrl = normalizeApiBaseUrl(options.apiBaseUrl);
229- return {
230- async logout() {
231- try {
232- await options.authClient.logout();
233- } catch {
234- return {
235- kind: "remote-failed" as const,
236- clearLocalOnly: async () => {
237- options.authClient.cookieJar.clear();
238- await options.sessionStore.remove(apiBaseUrl);
239- },
240- };
241- }
242- 
243- try {
244- await options.sessionStore.remove(apiBaseUrl);
245- return { kind: "complete" as const };
246- } catch (error) {
247- const message = error instanceof Error ? error.message : String(error);
248- return {
249- kind: "local-cleanup-failed" as const,
250- storePath: options.sessionStore.path,
251- error: message,
252- retry: async () => {
253- options.authClient.cookieJar.clear();
254- await options.sessionStore.remove(apiBaseUrl);
255- },
256- };
257- }
258- },
259- };
260-}
@@ -1,109 +0,0 @@
1-import assert from "node:assert/strict";
2-import { EventEmitter } from "node:events";
3-import { describe, it } from "node:test";
4-import { buildRegisterUrl, openBrowserUrl } from "./browser-opener.js";
5- 
6-describe("buildRegisterUrl", () => {
7- it("keeps deployment path prefix from publicBaseUrl", () => {
8- assert.equal(
9- buildRegisterUrl("https://example.com/deploy"),
10- "https://example.com/deploy/register",
11- );
12- assert.equal(
13- buildRegisterUrl("https://example.com/deploy/"),
14- "https://example.com/deploy/register",
15- );
16- });
17-});
18- 
19-describe("openBrowserUrl", () => {
20- it("uses rundll32 argument array on Windows without shell", () => {
21- const calls: Array<{ command: string; args: string[]; options: object }> = [];
22- const result = openBrowserUrl("http://127.0.0.1:3000/register", {
23- platform: "win32",
24- spawn: ((command: string, args: string[], options: object) => {
25- calls.push({ command, args, options });
26- return fakeChild();
27- }) as typeof import("node:child_process").spawn,
28- });
29- assert.equal(result.ok, true);
30- assert.deepEqual(calls[0]?.command, "rundll32");
31- assert.deepEqual(calls[0]?.args, [
32- "url.dll,FileProtocolHandler",
33- "http://127.0.0.1:3000/register",
34- ]);
35- assert.equal((calls[0]?.options as { shell?: boolean }).shell, false);
36- });
37- 
38- it("uses open on macOS and xdg-open on Linux", () => {
39- const mac = captureSpawn("darwin", "https://example.com/register");
40- assert.deepEqual(mac, { command: "open", args: ["https://example.com/register"] });
41- const linux = captureSpawn("linux", "https://example.com/register");
42- assert.deepEqual(linux, { command: "xdg-open", args: ["https://example.com/register"] });
43- });
44- 
45- it("returns the full URL when spawn fails", () => {
46- const result = openBrowserUrl("https://example.com/app/register", {
47- platform: "linux",
48- spawn: (() => {
49- throw new Error("spawn failed");
50- }) as typeof import("node:child_process").spawn,
51- });
52- assert.equal(result.ok, false);
53- if (!result.ok) {
54- assert.equal(result.url, "https://example.com/app/register");
55- }
56- });
57- 
58- it("attaches an error listener so async spawn failures do not crash", () => {
59- let errorListener: ((err: Error) => void) | undefined;
60- const result = openBrowserUrl("https://example.com/register", {
61- platform: "linux",
62- spawn: ((() => {
63- const child = fakeChild();
64- const originalOn = child.on.bind(child);
65- child.on = ((event: string, listener: (...args: unknown[]) => void) => {
66- if (event === "error") {
67- errorListener = listener as (err: Error) => void;
68- }
69- return originalOn(event, listener);
70- }) as typeof child.on;
71- return child;
72- }) as unknown) as typeof import("node:child_process").spawn,
73- });
74- assert.equal(result.ok, true);
75- if (result.ok) {
76- assert.equal(result.url, "https://example.com/register");
77- }
78- assert.equal(typeof errorListener, "function");
79- assert.doesNotThrow(() => errorListener?.(new Error("ENOENT")));
80- });
81-});
82- 
83-function captureSpawn(osPlatform: NodeJS.Platform, url: string) {
84- let captured: { command: string; args: string[] } | undefined;
85- openBrowserUrl(url, {
86- platform: osPlatform,
87- spawn: ((command: string, args: string[]) => {
88- captured = { command, args };
89- return fakeChild();
90- }) as typeof import("node:child_process").spawn,
91- });
92- return captured;
93-}
94- 
95-function fakeChild() {
96- const child = new EventEmitter() as EventEmitter & {
97- unref: () => void;
98- stdin: null;
99- stdout: null;
100- stderr: null;
101- pid: number;
102- };
103- child.unref = () => {};
104- child.stdin = null;
105- child.stdout = null;
106- child.stderr = null;
107- child.pid = 1;
108- return child;
109-}
@@ -1,77 +0,0 @@
1-import { spawn, type ChildProcess } from "node:child_process";
2-import { platform } from "node:os";
3- 
4-export type BrowserOpenerDeps = {
5- platform?: NodeJS.Platform;
6- spawn?: typeof spawn;
7-};
8- 
9-export type OpenBrowserResult =
10- | { ok: true; command: string; args: string[]; url: string }
11- | { ok: false; reason: string; url: string };
12- 
13-export function buildRegisterUrl(publicBaseUrl: string): string {
14- const base = new URL(publicBaseUrl);
15- if (base.protocol !== "http:" && base.protocol !== "https:") {
16- throw new Error("Registration URL must use http or https.");
17- }
18- base.pathname = `${base.pathname.replace(/\/?$/, "/")}register`;
19- base.search = "";
20- base.hash = "";
21- return base.toString();
22-}
23- 
24-export function openBrowserUrl(
25- url: string,
26- deps: BrowserOpenerDeps = {},
27-): OpenBrowserResult {
28- let parsed: URL;
29- try {
30- parsed = new URL(url);
31- } catch {
32- return { ok: false, reason: "Invalid URL", url };
33- }
34- if (parsed.protocol !== "http:" && parsed.protocol !== "https:") {
35- return { ok: false, reason: "URL must use http or https", url };
36- }
37- 
38- const osPlatform = deps.platform ?? platform();
39- const spawnImpl = deps.spawn ?? spawn;
40- const { command, args } = browserCommand(osPlatform, parsed.toString());
41- const normalizedUrl = parsed.toString();
42- 
43- try {
44- const child: ChildProcess = spawnImpl(command, args, {
45- shell: false,
46- detached: true,
47- stdio: "ignore",
48- windowsHide: true,
49- });
50- // Missing binaries (e.g. xdg-open) emit 'error' asynchronously; without a
51- // listener Node can crash the process even though spawn() returned.
52- child.on("error", () => {
53- // Caller always prints a copyable URL; swallow to avoid unhandled crash.
54- });
55- child.unref();
56- return { ok: true, command, args, url: normalizedUrl };
57- } catch (error) {
58- const reason = error instanceof Error ? error.message : String(error);
59- return { ok: false, reason, url: normalizedUrl };
60- }
61-}
62- 
63-function browserCommand(
64- osPlatform: NodeJS.Platform,
65- url: string,
66-): { command: string; args: string[] } {
67- if (osPlatform === "win32") {
68- return {
69- command: "rundll32",
70- args: ["url.dll,FileProtocolHandler", url],
71- };
72- }
73- if (osPlatform === "darwin") {
74- return { command: "open", args: [url] };
75- }
76- return { command: "xdg-open", args: [url] };
77-}
@@ -1,87 +0,0 @@
1-import assert from "node:assert/strict";
2-import { describe, it } from "node:test";
3-import { TuiCookieJar } from "./cookie-jar.js";
4- 
5-describe("TuiCookieJar", () => {
6- it("parses multiple Set-Cookie headers and keeps only name/value", () => {
7- const jar = new TuiCookieJar();
8- const headers = new Headers();
9- headers.append(
10- "set-cookie",
11- "df_session=abc%20123; Path=/; HttpOnly; Max-Age=3600",
12- );
13- headers.append("set-cookie", "df_csrf=token-value; Path=/; Max-Age=3600");
14- jar.absorbSetCookie(headers);
15- 
16- assert.deepEqual(jar.snapshot(), {
17- df_session: "abc 123",
18- df_csrf: "token-value",
19- });
20- assert.equal(jar.csrfToken(), "token-value");
21- assert.equal(
22- jar.headerValue(),
23- "df_session=abc%20123; df_csrf=token-value",
24- );
25- });
26- 
27- it("generates a stable Cookie header from snapshot order", () => {
28- const jar = new TuiCookieJar();
29- jar.replace({ df_session: "s1", df_csrf: "c1" });
30- assert.equal(jar.headerValue(), "df_session=s1; df_csrf=c1");
31- });
32- 
33- it("replace clears previous cookies so sessions do not mix", () => {
34- const jar = new TuiCookieJar();
35- jar.replace({ df_session: "old", df_csrf: "old-csrf", leftover: "x" });
36- jar.replace({ df_session: "new", df_csrf: "new-csrf" });
37- assert.deepEqual(jar.snapshot(), {
38- df_session: "new",
39- df_csrf: "new-csrf",
40- });
41- assert.equal(jar.csrfToken(), "new-csrf");
42- });
43- 
44- it("does not expose toJSON to avoid accidental secret logging", () => {
45- const jar = new TuiCookieJar();
46- jar.replace({ df_session: "secret", df_csrf: "csrf" });
47- assert.equal(
48- Object.prototype.hasOwnProperty.call(jar, "toJSON"),
49- false,
50- );
51- assert.equal(typeof (jar as { toJSON?: unknown }).toJSON, "undefined");
52- });
53- 
54- it("clear removes all cookies", () => {
55- const jar = new TuiCookieJar();
56- jar.replace({ df_session: "s", df_csrf: "c" });
57- jar.clear();
58- assert.deepEqual(jar.snapshot(), {});
59- assert.equal(jar.headerValue(), undefined);
60- assert.equal(jar.csrfToken(), undefined);
61- });
62- 
63- it("deletes cookies when Set-Cookie uses Max-Age=0 (logout/clear)", () => {
64- const jar = new TuiCookieJar();
65- jar.replace({ df_session: "live", df_csrf: "csrf-live", keep: "yes" });
66- const headers = new Headers();
67- headers.append("set-cookie", "df_session=; Path=/; HttpOnly; Max-Age=0");
68- headers.append("set-cookie", "df_csrf=; Path=/; Max-Age=0");
69- jar.absorbSetCookie(headers);
70- 
71- assert.deepEqual(jar.snapshot(), { keep: "yes" });
72- assert.equal(jar.csrfToken(), undefined);
73- assert.equal(jar.headerValue(), "keep=yes");
74- });
75- 
76- it("deletes cookies when Expires is in the past", () => {
77- const jar = new TuiCookieJar();
78- jar.replace({ df_session: "live" });
79- const headers = new Headers();
80- headers.append(
81- "set-cookie",
82- "df_session=; Path=/; Expires=Thu, 01 Jan 1970 00:00:00 GMT",
83- );
84- jar.absorbSetCookie(headers);
85- assert.deepEqual(jar.snapshot(), {});
86- });
87-});
@@ -1,100 +0,0 @@
1-const CSRF_COOKIE = "df_csrf";
2- 
3-export class TuiCookieJar {
4- private readonly store: Record<string, string> = Object.create(null);
5- 
6- replace(cookies: Record<string, string>): void {
7- this.clear();
8- for (const [name, value] of Object.entries(cookies ?? {})) {
9- if (!name) {
10- continue;
11- }
12- this.store[name] = String(value);
13- }
14- }
15- 
16- absorbSetCookie(headers: Headers): void {
17- const values =
18- typeof headers.getSetCookie === "function"
19- ? headers.getSetCookie()
20- : splitSetCookieHeader(headers.get("set-cookie"));
21- 
22- for (const cookie of values) {
23- const segments = String(cookie).split(";");
24- const pair = segments[0] ?? "";
25- const eq = pair.indexOf("=");
26- if (eq <= 0) {
27- continue;
28- }
29- const name = pair.slice(0, eq).trim();
30- if (!name) {
31- continue;
32- }
33- if (shouldDeleteCookie(segments.slice(1))) {
34- delete this.store[name];
35- continue;
36- }
37- const rawValue = pair.slice(eq + 1);
38- try {
39- this.store[name] = decodeURIComponent(rawValue);
40- } catch {
41- this.store[name] = rawValue;
42- }
43- }
44- }
45- 
46- headerValue(): string | undefined {
47- const parts = Object.entries(this.store).map(
48- ([name, value]) => `${name}=${encodeURIComponent(value)}`,
49- );
50- return parts.length > 0 ? parts.join("; ") : undefined;
51- }
52- 
53- csrfToken(): string | undefined {
54- const value = this.store[CSRF_COOKIE];
55- return typeof value === "string" && value.length > 0 ? value : undefined;
56- }
57- 
58- snapshot(): Record<string, string> {
59- return { ...this.store };
60- }
61- 
62- clear(): void {
63- for (const key of Object.keys(this.store)) {
64- delete this.store[key];
65- }
66- }
67-}
68- 
69-function splitSetCookieHeader(value: string | null): string[] {
70- if (!value) {
71- return [];
72- }
73- return [value];
74-}
75- 
76-/** Honor Max-Age=0 / past Expires so logout Set-Cookie actually clears the jar. */
77-function shouldDeleteCookie(attributeSegments: string[]): boolean {
78- for (const segment of attributeSegments) {
79- const trimmed = segment.trim();
80- if (!trimmed) {
81- continue;
82- }
83- const eq = trimmed.indexOf("=");
84- const attrName = (eq >= 0 ? trimmed.slice(0, eq) : trimmed).trim().toLowerCase();
85- const attrValue = eq >= 0 ? trimmed.slice(eq + 1).trim() : "";
86- if (attrName === "max-age") {
87- const maxAge = Number(attrValue);
88- if (Number.isFinite(maxAge) && maxAge <= 0) {
89- return true;
90- }
91- }
92- if (attrName === "expires") {
93- const expiresMs = Date.parse(attrValue);
94- if (!Number.isNaN(expiresMs) && expiresMs <= Date.now()) {
95- return true;
96- }
97- }
98- }
99- return false;
100-}
@@ -1,33 +0,0 @@
1-export { AuthenticatedTransport } from "./authenticated-transport.js";
2-export { DEFAULT_AUTH_TIMEOUT_MS, TuiAuthClient, TuiAuthError } from "./auth-client.js";
3-export {
4- bindTransportAuthRequired,
5- bootstrapTuiAuth,
6- completeInteractiveLogin,
7- createAuthController,
8- createTransport,
9- isExpiredBeyondTolerance,
10- SESSION_EXPIRY_TOLERANCE_MS,
11-} from "./bootstrap.js";
12-export { buildRegisterUrl, openBrowserUrl } from "./browser-opener.js";
13-export { TuiCookieJar } from "./cookie-jar.js";
14-export {
15- canHidePasswordEcho,
16- createSecurePrompt,
17- isUnreachableAuthError,
18- resolveReadlineTerminal,
19- runInteractiveLogin,
20-} from "./interactive-login.js";
21-export {
22- normalizeApiBaseUrl,
23- resolveTuiAuthStorePath,
24- TuiSessionStore,
25-} from "./session-store.js";
26-export type {
27- AppExitReason,
28- AuthCommandController,
29- AuthStatus,
30- StoredTuiSession,
31- TuiUser,
32- TuiWorkspace,
33-} from "./types.js";
@@ -1,221 +0,0 @@
1-import assert from "node:assert/strict";
2-import { mkdtemp } from "node:fs/promises";
3-import { tmpdir } from "node:os";
4-import { join } from "node:path";
5-import { describe, it } from "node:test";
6-import {
7- canHidePasswordEcho,
8- createSecurePrompt,
9- resolveReadlineTerminal,
10- runInteractiveLogin,
11- type PromptFn,
12-} from "./interactive-login.js";
13-import { TuiAuthError } from "./auth-client.js";
14-import { TuiSessionStore } from "./session-store.js";
15-import { PassThrough } from "node:stream";
16- 
17-describe("runInteractiveLogin", () => {
18- it("supports login, registration guidance, and exit without echoing passwords", async () => {
19- const dir = await mkdtemp(join(tmpdir(), "tui-interactive-"));
20- const store = new TuiSessionStore({ filePath: join(dir, "auth.json") });
21- const output: string[] = [];
22- const passwords: string[] = [];
23- const answers = ["2", "", "1", "user@example.com", "secret-password", "3"];
24- let answerIndex = 0;
25- const prompt: PromptFn = {
26- question: async () => answers[answerIndex++] ?? "3",
27- password: async () => {
28- const value = answers[answerIndex++] ?? "";
29- passwords.push(value);
30- return value;
31- },
32- close: () => {},
33- };
34- 
35- let openedUrl: string | undefined;
36- const first = await runInteractiveLogin({
37- apiBaseUrl: "http://127.0.0.1:8787",
38- status: {
39- publicBaseUrl: "http://127.0.0.1:3000/app",
40- registrationEnabled: true,
41- },
42- deps: {
43- prompt,
44- stdout: {
45- write(chunk: string) {
46- output.push(String(chunk));
47- return true;
48- },
49- } as NodeJS.WritableStream,
50- fetchImpl: async (input) => {
51- const path = new URL(String(input)).pathname;
52- if (path === "/api/v1/auth/login") {
53- return json(
54- 200,
55- {
56- success: true,
57- data: {
58- user: { id: "u1", email: "user@example.com" },
59- workspace: { id: "w1" },
60- session: { expiresAt: "2099-01-01T00:00:00.000Z" },
61- },
62- },
63- ["df_session=s; Path=/", "df_csrf=c; Path=/"],
64- );
65- }
66- return json(404, { success: false, error: { code: "NOT_FOUND", message: "x" } });
67- },
68- sessionStore: store,
69- openBrowser: (url) => {
70- openedUrl = url;
71- return { ok: true, command: "xdg-open", args: [url], url };
72- },
73- },
74- });
75- 
76- assert.equal(first.kind, "authenticated");
77- assert.equal(openedUrl, "http://127.0.0.1:3000/app/register");
78- assert.equal(passwords[0], "secret-password");
79- assert.equal(output.join("").includes("secret-password"), false);
80- 
81- const exitResult = await runInteractiveLogin({
82- apiBaseUrl: "http://127.0.0.1:8787",
83- status: { publicBaseUrl: "http://127.0.0.1:3000", registrationEnabled: false },
84- deps: {
85- prompt: {
86- question: async () => "3",
87- password: async () => "",
88- close: () => {},
89- },
90- stdout: { write: () => true } as unknown as NodeJS.WritableStream,
91- fetchImpl: async () => json(500, {}),
92- sessionStore: store,
93- },
94- });
95- assert.equal(exitResult.kind, "exit");
96- });
97- 
98- it("does not auto-loop login after rate limiting", async () => {
99- const dir = await mkdtemp(join(tmpdir(), "tui-rate-"));
100- const store = new TuiSessionStore({ filePath: join(dir, "auth.json") });
101- let loginCalls = 0;
102- const answers = ["1", "user@example.com", "pw", "3"];
103- let idx = 0;
104- const result = await runInteractiveLogin({
105- apiBaseUrl: "http://127.0.0.1:8787",
106- status: { publicBaseUrl: "http://127.0.0.1:3000", registrationEnabled: false },
107- deps: {
108- prompt: {
109- question: async () => answers[idx++] ?? "3",
110- password: async () => answers[idx++] ?? "",
111- close: () => {},
112- },
113- stdout: { write: () => true } as unknown as NodeJS.WritableStream,
114- sessionStore: store,
115- fetchImpl: async () => {
116- loginCalls += 1;
117- return json(429, {
118- success: false,
119- error: { code: "RATE_LIMITED", message: "Too many requests" },
120- });
121- },
122- },
123- });
124- assert.equal(result.kind, "exit");
125- assert.equal(loginCalls, 1);
126- });
127- 
128- it("createSecurePrompt rejects overlapping readers on the same stdin", async () => {
129- const stdin = new PassThrough();
130- const stdoutChunks: string[] = [];
131- const stdout = new PassThrough();
132- stdout.on("data", (chunk) => stdoutChunks.push(String(chunk)));
133- const prompt = createSecurePrompt({ stdin, stdout });
134- 
135- const first = prompt.question("Q1: ");
136- await assert.rejects(() => prompt.question("Q2: "), /already waiting/i);
137- stdin.write("one\n");
138- assert.equal(await first, "one");
139- await prompt.close();
140- });
141- 
142- it("uses stdin TTY (not stdout) for terminal mode under piped stdout", () => {
143- const stdin = Object.assign(new PassThrough(), {
144- isTTY: true,
145- isRaw: false,
146- setRawMode(mode: boolean) {
147- this.isRaw = mode;
148- },
149- });
150- const stdout = Object.assign(new PassThrough(), { isTTY: false });
151- assert.equal(resolveReadlineTerminal(stdin), true);
152- assert.equal(Boolean((stdout as { isTTY?: boolean }).isTTY), false);
153- assert.equal(canHidePasswordEcho(stdin), true);
154- });
155- 
156- it("refuses password when stdin cannot hide echo", async () => {
157- const stdin = new PassThrough(); // not a TTY
158- const stdout = Object.assign(new PassThrough(), { isTTY: true });
159- const prompt = createSecurePrompt({ stdin, stdout });
160- await assert.rejects(() => prompt.password("Password: "), /hide echo/i);
161- await prompt.close();
162- });
163- 
164- it("reads password with stdin TTY + piped stdout without echoing to stdout", async () => {
165- const modes: boolean[] = [];
166- const stdin = Object.assign(new PassThrough(), {
167- isTTY: true,
168- isRaw: false,
169- setRawMode(mode: boolean) {
170- this.isRaw = mode;
171- modes.push(mode);
172- },
173- });
174- const stdoutChunks: string[] = [];
175- const stdout = Object.assign(new PassThrough(), { isTTY: false });
176- stdout.on("data", (chunk) => stdoutChunks.push(String(chunk)));
177- const prompt = createSecurePrompt({ stdin, stdout });
178- 
179- const pending = prompt.password("Password: ");
180- // Allow readline to attach before writing.
181- await new Promise((resolve) => setImmediate(resolve));
182- stdin.write("s3cret\n");
183- assert.equal(await pending, "s3cret");
184- assert.equal(stdoutChunks.join("").includes("s3cret"), false);
185- assert.ok(modes.includes(true));
186- assert.equal(stdin.isRaw, false);
187- await prompt.close();
188- });
189- 
190- it("returns unreachable on login network/timeout errors", async () => {
191- const dir = await mkdtemp(join(tmpdir(), "tui-unreachable-"));
192- const store = new TuiSessionStore({ filePath: join(dir, "auth.json") });
193- const answers = ["1", "user@example.com", "pw"];
194- let idx = 0;
195- const result = await runInteractiveLogin({
196- apiBaseUrl: "http://127.0.0.1:8787",
197- status: { publicBaseUrl: "http://127.0.0.1:3000", registrationEnabled: false },
198- deps: {
199- prompt: {
200- question: async () => answers[idx++] ?? "3",
201- password: async () => answers[idx++] ?? "",
202- close: () => {},
203- },
204- stdout: { write: () => true } as unknown as NodeJS.WritableStream,
205- sessionStore: store,
206- fetchImpl: async () => {
207- throw new TuiAuthError(0, "TIMEOUT", "Auth request timed out after 15ms");
208- },
209- },
210- });
211- assert.equal(result.kind, "unreachable");
212- });
213-});
214- 
215-function json(status: number, body: unknown, setCookies: string[] = []): Response {
216- const headers = new Headers({ "content-type": "application/json" });
217- for (const cookie of setCookies) {
218- headers.append("set-cookie", cookie);
219- }
220- return new Response(JSON.stringify(body), { status, headers });
221-}
@@ -1,251 +0,0 @@
1-import { createInterface, type Interface } from "node:readline/promises";
2-import { Writable } from "node:stream";
3-import { completeInteractiveLogin } from "./bootstrap.js";
4-import { buildRegisterUrl, openBrowserUrl, type BrowserOpenerDeps } from "./browser-opener.js";
5-import { TuiAuthError } from "./auth-client.js";
6-import type { TuiSessionStore } from "./session-store.js";
7-import type { AuthStatus, StoredTuiSession } from "./types.js";
8-import type { AuthenticatedTransport } from "./authenticated-transport.js";
9-import type { TuiAuthClient } from "./auth-client.js";
10-import type { TuiCookieJar } from "./cookie-jar.js";
11- 
12-export type PromptFn = {
13- question(message: string): Promise<string>;
14- password(message: string): Promise<string>;
15- close(): Promise<void> | void;
16-};
17- 
18-export type InteractiveLoginDeps = {
19- prompt?: PromptFn;
20- stdout?: NodeJS.WritableStream;
21- stdin?: NodeJS.ReadableStream;
22- fetchImpl: typeof fetch;
23- sessionStore: TuiSessionStore;
24- browser?: BrowserOpenerDeps;
25- openBrowser?: typeof openBrowserUrl;
26-};
27- 
28-export type InteractiveLoginSuccess = {
29- kind: "authenticated";
30- session: StoredTuiSession;
31- transport: AuthenticatedTransport;
32- authClient: TuiAuthClient;
33- cookieJar: TuiCookieJar;
34- warning?: string;
35-};
36- 
37-export type InteractiveLoginResult =
38- | InteractiveLoginSuccess
39- | { kind: "exit" }
40- | { kind: "unreachable"; error: unknown };
41- 
42-export async function runInteractiveLogin(options: {
43- apiBaseUrl: string;
44- status: AuthStatus;
45- previousSession?: StoredTuiSession;
46- deps: InteractiveLoginDeps;
47-}): Promise<InteractiveLoginResult> {
48- const stdout = options.deps.stdout ?? process.stdout;
49- const prompt = options.deps.prompt ?? createSecurePrompt({
50- stdin: options.deps.stdin ?? process.stdin,
51- stdout,
52- });
53- const open = options.deps.openBrowser ?? openBrowserUrl;
54- 
55- try {
56- while (true) {
57- writeLine(stdout, "");
58- writeLine(stdout, "DataFoundry TUI login");
59- writeLine(stdout, " [1] Sign in with email and password");
60- if (options.status.registrationEnabled) {
61- writeLine(stdout, " [2] Open web registration");
62- }
63- writeLine(stdout, " [3] Exit");
64- const choice = (await prompt.question("Select an option: ")).trim();
65- 
66- if (choice === "3" || choice.toLowerCase() === "q" || choice.toLowerCase() === "exit") {
67- return { kind: "exit" };
68- }
69- 
70- if (choice === "2" && options.status.registrationEnabled) {
71- const registerUrl = buildRegisterUrl(options.status.publicBaseUrl);
72- const opened = open(registerUrl, options.deps.browser);
73- // Always print a copyable URL: spawn success does not guarantee a browser opened.
74- if (opened.ok) {
75- writeLine(stdout, `Opened registration page. If the browser did not open, visit:\n${registerUrl}`);
76- } else {
77- writeLine(stdout, `Could not open a browser (${opened.reason}). Visit:\n${registerUrl}`);
78- }
79- await prompt.question("Press Enter to return to login...");
80- continue;
81- }
82- 
83- if (choice !== "1") {
84- writeLine(stdout, "Please choose a valid option.");
85- continue;
86- }
87- 
88- const email = (await prompt.question("Email: ")).trim();
89- const password = await prompt.password("Password: ");
90- if (!email || !password) {
91- writeLine(stdout, "Email and password are required.");
92- continue;
93- }
94- 
95- try {
96- const result = await completeInteractiveLogin({
97- apiBaseUrl: options.apiBaseUrl,
98- email,
99- password,
100- fetchImpl: options.deps.fetchImpl,
101- sessionStore: options.deps.sessionStore,
102- ...(options.previousSession ? { previousSession: options.previousSession } : {}),
103- });
104- if (result.warning) {
105- writeLine(stdout, result.warning);
106- }
107- writeLine(stdout, `Signed in as ${result.session.user.email}`);
108- return {
109- kind: "authenticated",
110- session: result.session,
111- transport: result.transport,
112- authClient: result.authClient,
113- cookieJar: result.cookieJar,
114- ...(result.warning ? { warning: result.warning } : {}),
115- };
116- } catch (error) {
117- if (isUnreachableAuthError(error)) {
118- return { kind: "unreachable", error };
119- }
120- if (error instanceof TuiAuthError && error.status === 429) {
121- writeLine(stdout, "Too many login attempts. Wait a moment and try again.");
122- continue;
123- }
124- const message = error instanceof Error ? error.message : String(error);
125- writeLine(stdout, `Login failed: ${sanitizeErrorMessage(message)}`);
126- }
127- }
128- } finally {
129- await prompt.close();
130- }
131-}
132- 
133-/**
134- * Prefer stdin TTY for readline `terminal` mode. Using stdout.isTTY breaks
135- * password echo suppression under `tui | tee` (stdin TTY, stdout pipe).
136- */
137-export function resolveReadlineTerminal(stdin: NodeJS.ReadableStream): boolean {
138- return Boolean((stdin as NodeJS.ReadStream).isTTY);
139-}
140- 
141-/** Password entry requires an stdin TTY that can disable echo via setRawMode. */
142-export function canHidePasswordEcho(stdin: NodeJS.ReadableStream): boolean {
143- const stream = stdin as NodeJS.ReadStream;
144- return Boolean(stream.isTTY && typeof stream.setRawMode === "function");
145-}
146- 
147-/**
148- * One readline at a time on stdin. Dual visible+muted interfaces can leave the
149- * visible reader echoing while the muted reader collects a password.
150- */
151-export function createSecurePrompt(options: {
152- stdin: NodeJS.ReadableStream;
153- stdout: NodeJS.WritableStream;
154-}): PromptFn {
155- const stdin = options.stdin as NodeJS.ReadStream;
156- const terminal = resolveReadlineTerminal(options.stdin);
157- const mutedStdout = new Writable({
158- write(chunk, _encoding, callback) {
159- const text = String(chunk);
160- if (text.includes("\n") || text.includes("\r")) {
161- options.stdout.write(text.replace(/[^\r\n]/g, ""));
162- }
163- callback();
164- },
165- });
166- 
167- let active: Interface | undefined;
168- 
169- const withReader = async <T>(
170- output: NodeJS.WritableStream,
171- historySize: number | undefined,
172- run: (rl: Interface) => Promise<T>,
173- ): Promise<T> => {
174- if (active) {
175- throw new Error("Prompt is already waiting for input.");
176- }
177- const rl = createInterface({
178- input: options.stdin as NodeJS.ReadableStream,
179- output,
180- terminal,
181- ...(historySize !== undefined ? { historySize } : {}),
182- });
183- active = rl;
184- try {
185- return await run(rl);
186- } finally {
187- rl.close();
188- if (active === rl) {
189- active = undefined;
190- }
191- }
192- };
193- 
194- return {
195- question: (message) => withReader(options.stdout, undefined, (rl) => rl.question(message)),
196- password: async (message) => {
197- if (!canHidePasswordEcho(options.stdin)) {
198- throw new Error(
199- "Password input requires an interactive stdin TTY that can hide echo. "
200- + "Refusing to read a password that would be visible.",
201- );
202- }
203- options.stdout.write(message);
204- const previousRaw = Boolean(stdin.isRaw);
205- stdin.setRawMode(true);
206- try {
207- const value = await withReader(mutedStdout, 0, (rl) => rl.question(""));
208- options.stdout.write("\n");
209- return value;
210- } finally {
211- stdin.setRawMode(previousRaw);
212- }
213- },
214- close: () => {
215- active?.close();
216- active = undefined;
217- },
218- };
219-}
220- 
221-export function isUnreachableAuthError(error: unknown): boolean {
222- if (error instanceof TuiAuthError) {
223- return error.code === "TIMEOUT" || error.code === "NETWORK_ERROR";
224- }
225- if (!(error instanceof Error)) {
226- return false;
227- }
228- if (error.name === "AbortError") {
229- return true;
230- }
231- const message = error.message.toLowerCase();
232- return (
233- message.includes("fetch failed")
234- || message.includes("network")
235- || message.includes("econnrefused")
236- || message.includes("enotfound")
237- || message.includes("etimedout")
238- || message.includes("econnreset")
239- || message.includes("socket hang up")
240- );
241-}
242- 
243-function writeLine(stdout: NodeJS.WritableStream, message: string): void {
244- stdout.write(`${message}\n`);
245-}
246- 
247-function sanitizeErrorMessage(message: string): string {
248- return message
249- .replace(/df_session=[^;\s]+/gi, "df_session=[redacted]")
250- .replace(/df_csrf=[^;\s]+/gi, "df_csrf=[redacted]");
251-}
Mapps/web/src/app/data-tasks/components/task-console/ExpandedArtifactView.tsx+1-1File content is under review, please try again later
Mapps/web/src/app/data-tasks/components/task-console/evidence-selection.tsx+1-1File content is under review, please try again later
Mapps/web/src/app/data-tasks/data-tasks-app.tsx+1-1File content is under review, please try again later
Mapps/web/src/app/data-tasks/live-run-state.ts+1-1File content is under review, please try again later