@timqi/pier 0.0.1 → 0.0.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +76 -12
- package/dist/agent/config.js +273 -27
- package/dist/agent/credentials.js +18 -12
- package/dist/agent/events.js +5 -41
- package/dist/agent/models.js +12 -0
- package/dist/agent/pi.js +182 -27
- package/dist/boards/boards.js +20 -10
- package/dist/channels/routes.js +1 -1
- package/dist/channels/runtime.js +36 -5
- package/dist/channels/slack-api.js +2 -4
- package/dist/channels/slack-outbound.js +4 -8
- package/dist/channels/slack-render.js +1 -4
- package/dist/channels/slack.js +20 -9
- package/dist/channels/telegram-api.js +3 -4
- package/dist/channels/telegram.js +37 -28
- package/dist/cli.js +177 -29
- package/dist/core/hub.js +36 -5
- package/dist/core/identity.js +5 -0
- package/dist/core/inbound-file.js +70 -0
- package/dist/core/inbox.js +32 -0
- package/dist/core/queue.js +9 -3
- package/dist/core/reply.js +20 -5
- package/dist/core/router.js +186 -14
- package/dist/core/types.js +53 -0
- package/dist/db.js +54 -8
- package/dist/drain.js +145 -0
- package/dist/main.js +86 -18
- package/dist/secrets.js +10 -6
- package/dist/service.js +142 -18
- package/dist/settings.js +69 -8
- package/dist/tasks/agent.js +41 -5
- package/dist/tasks/callbacks.js +29 -89
- package/dist/tasks/definitions.js +2 -6
- package/dist/tasks/execution.js +10 -1
- package/dist/tasks/groups.js +20 -49
- package/dist/tasks/messages.js +106 -21
- package/dist/tasks/outbox.js +157 -0
- package/dist/tasks/routes.js +6 -4
- package/dist/tasks/service.js +79 -22
- package/dist/tasks/store.js +48 -55
- package/dist/tasks/tool.js +19 -4
- package/dist/tasks/types.js +7 -0
- package/dist/update.js +94 -0
- package/dist/web/auth.js +75 -22
- package/dist/web/explorer.js +146 -0
- package/dist/web/files.js +26 -11
- package/dist/web/instance.js +99 -0
- package/dist/web/provider-flows.js +249 -0
- package/dist/web/providers.js +129 -0
- package/dist/web/public/assets/index-BK64pHmP.js +90 -0
- package/dist/web/public/assets/index-De4GlOq4.css +2 -0
- package/dist/web/public/icon-192.png +0 -0
- package/dist/web/public/icon-32.png +0 -0
- package/dist/web/public/icon-512.png +0 -0
- package/dist/web/public/icon-maskable-512.png +0 -0
- package/dist/web/public/icon-touch-192.png +0 -0
- package/dist/web/public/icon.svg +29 -11
- package/dist/web/public/index.html +43 -28
- package/dist/web/server.js +47 -120
- package/docs/deploy.md +120 -64
- package/package.json +1 -1
- package/skills/pier-help/SKILL.md +110 -0
- package/skills/pier-slack/SKILL.md +3 -2
- package/skills/pier-tasks/SKILL.md +19 -12
- package/dist/web/public/assets/index-8CinH1uR.css +0 -2
- package/dist/web/public/assets/index-DAgP1Gq8.js +0 -78
- package/dist/web/public/sw.js +0 -21
package/dist/web/auth.js
CHANGED
|
@@ -16,6 +16,7 @@
|
|
|
16
16
|
// whole revocation story a single-user system needs. A cookie (not a bearer
|
|
17
17
|
// header) because the workbench lives on SSE, and EventSource sends no headers.
|
|
18
18
|
import { createHash, createHmac, randomBytes, randomInt, scryptSync, timingSafeEqual, } from "node:crypto";
|
|
19
|
+
import { getConnInfo } from "@hono/node-server/conninfo";
|
|
19
20
|
import { getCookie, setCookie } from "hono/cookie";
|
|
20
21
|
import { pierDb } from "../db.js";
|
|
21
22
|
import { logger } from "../log.js";
|
|
@@ -25,6 +26,9 @@ const TTL_MS = 90 * 24 * 60 * 60_000;
|
|
|
25
26
|
/** Failed attempts one client may make before it has to wait out the window. */
|
|
26
27
|
const MAX_FAILURES = 10;
|
|
27
28
|
const WINDOW_MS = 15 * 60_000;
|
|
29
|
+
/** Distinct throttle buckets retained at once; the last is shared overflow. */
|
|
30
|
+
const MAX_FAILURE_CLIENTS = 1024;
|
|
31
|
+
const OVERFLOW_CLIENT = "\0overflow";
|
|
28
32
|
/** Shortest password a human may choose. The generated one is longer; this is
|
|
29
33
|
* the floor under which the throttle above stops being enough. */
|
|
30
34
|
const MIN_LENGTH = 10;
|
|
@@ -109,11 +113,12 @@ const hash = (password, salt) => scryptSync(password, salt, KEY_BYTES).toString(
|
|
|
109
113
|
* it. `/boards/*` stays behind the boundary; `/p/*` is the published mirror,
|
|
110
114
|
* the single exempt prefix `docs/architecture.md` reserved for this.
|
|
111
115
|
*/
|
|
112
|
-
function isPublic(path) {
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
116
|
+
function isPublic(method, path) {
|
|
117
|
+
if (path === "/login")
|
|
118
|
+
return method === "GET" || method === "HEAD" || method === "POST";
|
|
119
|
+
if (method !== "GET" && method !== "HEAD")
|
|
120
|
+
return false;
|
|
121
|
+
return path.startsWith("/p/") || path === "/boards/_assets/pier.css";
|
|
117
122
|
}
|
|
118
123
|
const sign = (secret, expiresAt) => createHmac("sha256", secret).update(String(expiresAt)).digest("base64url");
|
|
119
124
|
/** Constant-time equality that also hides length: both sides are digested. */
|
|
@@ -137,40 +142,90 @@ function valid(secret, cookie) {
|
|
|
137
142
|
const safeNext = (raw) => typeof raw === "string" && /^\/(?![/\\])/.test(raw) ? raw : "/";
|
|
138
143
|
// Failed logins per client, in memory: a restart clearing them is fine, since
|
|
139
144
|
// the window is minutes and the point is to make guessing slow, not to keep
|
|
140
|
-
// books.
|
|
145
|
+
// books. Expired entries are pruned, and fresh identities spill into one
|
|
146
|
+
// overflow bucket once the fixed map cap is reached.
|
|
141
147
|
const failures = new Map();
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
148
|
+
const loopback = (address) => address === "::1" || address.startsWith("127.") || address.startsWith("::ffff:127.");
|
|
149
|
+
function remoteOf(c) {
|
|
150
|
+
const env = c.env;
|
|
151
|
+
return env?.incoming || env?.server?.incoming
|
|
152
|
+
? getConnInfo(c).remote.address
|
|
153
|
+
: undefined;
|
|
154
|
+
}
|
|
155
|
+
/** Trust a forwarded address only from a local reverse proxy. The rightmost
|
|
156
|
+
* hop is the address that proxy appended, not one the client put at the front. */
|
|
149
157
|
function clientOf(c) {
|
|
150
|
-
|
|
158
|
+
const remote = remoteOf(c);
|
|
159
|
+
if (remote && !loopback(remote))
|
|
160
|
+
return remote;
|
|
161
|
+
return c.req.header("x-forwarded-for")?.split(",").at(-1)?.trim() || remote || "local";
|
|
162
|
+
}
|
|
163
|
+
function failureClient(client) {
|
|
164
|
+
if (failures.has(client) || failures.size < MAX_FAILURE_CLIENTS - 1)
|
|
165
|
+
return client;
|
|
166
|
+
return OVERFLOW_CLIENT;
|
|
151
167
|
}
|
|
152
168
|
function throttled(client) {
|
|
153
169
|
const now = Date.now();
|
|
154
170
|
for (const [id, entry] of failures)
|
|
155
171
|
if (entry.resetAt <= now)
|
|
156
172
|
failures.delete(id);
|
|
157
|
-
return (failures.get(client)?.count ?? 0) >= MAX_FAILURES;
|
|
173
|
+
return (failures.get(failureClient(client))?.count ?? 0) >= MAX_FAILURES;
|
|
158
174
|
}
|
|
159
175
|
function noteFailure(client) {
|
|
176
|
+
client = failureClient(client);
|
|
160
177
|
const entry = failures.get(client);
|
|
161
178
|
if (entry && entry.resetAt > Date.now())
|
|
162
179
|
entry.count += 1;
|
|
163
180
|
else
|
|
164
181
|
failures.set(client, { count: 1, resetAt: Date.now() + WINDOW_MS });
|
|
165
182
|
}
|
|
183
|
+
/** Browsers name the source of unsafe requests. Compare hosts rather than
|
|
184
|
+
* schemes because TLS commonly terminates at the reverse proxy. */
|
|
185
|
+
function sameOrigin(c) {
|
|
186
|
+
const origin = c.req.header("origin");
|
|
187
|
+
if (!origin)
|
|
188
|
+
return true; // curl and other non-browser clients
|
|
189
|
+
try {
|
|
190
|
+
const parsed = new URL(origin);
|
|
191
|
+
const remote = remoteOf(c);
|
|
192
|
+
const forwarded = remote && loopback(remote)
|
|
193
|
+
? c.req.header("x-forwarded-host")?.split(",").at(-1)?.trim()
|
|
194
|
+
: undefined;
|
|
195
|
+
const host = forwarded || c.req.header("host") || new URL(c.req.url).host;
|
|
196
|
+
const external = new URL(`${parsed.protocol}//${host}`);
|
|
197
|
+
return parsed.origin === origin && external.origin === parsed.origin &&
|
|
198
|
+
external.pathname === "/" && !external.search && !external.hash;
|
|
199
|
+
}
|
|
200
|
+
catch {
|
|
201
|
+
return false;
|
|
202
|
+
}
|
|
203
|
+
}
|
|
166
204
|
/** Every route, in one place — no per-route opt-in to forget on the next one. */
|
|
167
205
|
export function requireAuth(store) {
|
|
168
206
|
return async (c, next) => {
|
|
169
|
-
|
|
207
|
+
// On every response, public ones included: the login form is the one page
|
|
208
|
+
// strangers reach, and it must not be frameable either.
|
|
209
|
+
c.header("x-frame-options", "DENY");
|
|
210
|
+
if (isPublic(c.req.method, c.req.path))
|
|
170
211
|
return next();
|
|
212
|
+
const authenticated = valid(store.cookieKey, getCookie(c, COOKIE));
|
|
213
|
+
const unsafe = c.req.method !== "GET" && c.req.method !== "HEAD";
|
|
214
|
+
if (authenticated && unsafe && !sameOrigin(c)) {
|
|
215
|
+
log.warn(`blocked ${c.req.method} ${c.req.path} from origin ${c.req.header("origin")}`);
|
|
216
|
+
return c.json({ error: "forbidden origin" }, 403);
|
|
217
|
+
}
|
|
218
|
+
if (authenticated) {
|
|
219
|
+
await next();
|
|
220
|
+
// Cookie-authenticated content must not become public in a shared proxy.
|
|
221
|
+
if (!c.res.headers.has("cache-control")) {
|
|
222
|
+
c.header("cache-control", c.req.path.startsWith("/api/") ? "private, no-store" : "private");
|
|
223
|
+
}
|
|
224
|
+
return;
|
|
225
|
+
}
|
|
171
226
|
// An API caller gets a status it can act on; a navigation gets the form.
|
|
172
227
|
// Anything non-GET is a client call too — never a link worth redirecting.
|
|
173
|
-
if (c.req.path.startsWith("/api/") ||
|
|
228
|
+
if (c.req.path.startsWith("/api/") || unsafe) {
|
|
174
229
|
return c.json({ error: "unauthorized" }, 401);
|
|
175
230
|
}
|
|
176
231
|
return c.redirect(`/login?next=${encodeURIComponent(c.req.path)}`);
|
|
@@ -198,10 +253,8 @@ export function registerAuthRoutes(app, store) {
|
|
|
198
253
|
issueCookie(c, store);
|
|
199
254
|
return c.redirect(next);
|
|
200
255
|
});
|
|
201
|
-
//
|
|
202
|
-
//
|
|
203
|
-
// "sign in" does. So it needs no cookie of its own: whoever knows the current
|
|
204
|
-
// password can already get one.
|
|
256
|
+
// Re-authenticate before rotating the credential. The global boundary also
|
|
257
|
+
// requires a live cookie; knowing a password is not permission to call APIs.
|
|
205
258
|
app.post("/api/password", async (c) => {
|
|
206
259
|
const client = clientOf(c);
|
|
207
260
|
const body = (await c.req.json().catch(() => null));
|
|
@@ -211,7 +264,7 @@ export function registerAuthRoutes(app, store) {
|
|
|
211
264
|
return c.json({ error: "Too many attempts. Wait a few minutes." }, 429);
|
|
212
265
|
if (!store.verify(current)) {
|
|
213
266
|
noteFailure(client);
|
|
214
|
-
return c.json({ error: "Wrong current password." },
|
|
267
|
+
return c.json({ error: "Wrong current password." }, 403);
|
|
215
268
|
}
|
|
216
269
|
if (next.length < MIN_LENGTH) {
|
|
217
270
|
return c.json({ error: `Use at least ${MIN_LENGTH} characters.` }, 400);
|
|
@@ -0,0 +1,146 @@
|
|
|
1
|
+
// Files view backend: read-only directory listing, file bytes and git
|
|
2
|
+
// ref/diff queries for the Console's Files view. Every route is scoped to a
|
|
3
|
+
// known project cwd — the picker offers exactly those roots, and nothing
|
|
4
|
+
// outside one is ever listed, read or diffed.
|
|
5
|
+
import { execFile } from "node:child_process";
|
|
6
|
+
import { readdir, readFile, realpath, stat } from "node:fs/promises";
|
|
7
|
+
import { basename, extname, isAbsolute, resolve, sep } from "node:path";
|
|
8
|
+
import { promisify } from "node:util";
|
|
9
|
+
import { guarded } from "./files.js";
|
|
10
|
+
const run = promisify(execFile);
|
|
11
|
+
// Inline-renderable binary types; text is sniffed, everything else downloads.
|
|
12
|
+
const BINARY_TYPES = {
|
|
13
|
+
".png": "image/png",
|
|
14
|
+
".jpg": "image/jpeg",
|
|
15
|
+
".jpeg": "image/jpeg",
|
|
16
|
+
".gif": "image/gif",
|
|
17
|
+
".webp": "image/webp",
|
|
18
|
+
".avif": "image/avif",
|
|
19
|
+
".bmp": "image/bmp",
|
|
20
|
+
".svg": "image/svg+xml",
|
|
21
|
+
".pdf": "application/pdf",
|
|
22
|
+
};
|
|
23
|
+
const MAX_FILE_BYTES = 32 * 1024 * 1024;
|
|
24
|
+
const MAX_DIFF_BYTES = 2 * 1024 * 1024;
|
|
25
|
+
/** A ref never starts with `-`: execFile blocks the shell, this blocks the
|
|
26
|
+
* argument parser (`--output=…` is a write). Git validates the rest. */
|
|
27
|
+
const REF_RE = /^[^-\s][^\s]*$/;
|
|
28
|
+
/** git in `root`, output capped — a diff is display data, not an archive. */
|
|
29
|
+
const git = async (root, ...args) => (await run("git", ["-C", root, ...args], { maxBuffer: MAX_DIFF_BYTES })).stdout;
|
|
30
|
+
export function registerExplorerRoutes(app, { factory, nascentCwds }) {
|
|
31
|
+
/** The scope check every route shares: `root` must be a project cwd Pi
|
|
32
|
+
* already knows, and `path` must resolve inside it (realpath both ends —
|
|
33
|
+
* neither `..` nor a symlink steps outside). Returns the real target. */
|
|
34
|
+
const resolveScoped = async (root, path = "") => {
|
|
35
|
+
if (!root || !isAbsolute(root))
|
|
36
|
+
throw new Error("root must be a known project directory");
|
|
37
|
+
const known = new Set([...(await factory.list()).map((s) => s.cwd), ...nascentCwds()]);
|
|
38
|
+
if (!known.has(root))
|
|
39
|
+
throw new Error("root must be a known project directory");
|
|
40
|
+
const real = await realpath(root);
|
|
41
|
+
const target = await realpath(resolve(real, path));
|
|
42
|
+
if (target !== real && !target.startsWith(real + sep))
|
|
43
|
+
throw new Error("path escapes root");
|
|
44
|
+
return target;
|
|
45
|
+
};
|
|
46
|
+
// Directory listing, names only. `.git` is plumbing, not content.
|
|
47
|
+
guarded(app, "GET", "/api/explorer/ls", 404, async (c) => {
|
|
48
|
+
c.header("cache-control", "no-store");
|
|
49
|
+
const dir = await resolveScoped(c.req.query("root"), c.req.query("path"));
|
|
50
|
+
const entries = (await readdir(dir, { withFileTypes: true }))
|
|
51
|
+
.filter((e) => e.name !== ".git" && (e.isDirectory() || e.isFile()))
|
|
52
|
+
.map((e) => ({ name: e.name, dir: e.isDirectory() }))
|
|
53
|
+
.sort((a, b) => Number(b.dir) - Number(a.dir) || a.name.localeCompare(b.name));
|
|
54
|
+
return c.json({ entries });
|
|
55
|
+
});
|
|
56
|
+
// File bytes, read-only. Known binary types render inline; anything else is
|
|
57
|
+
// sniffed — a NUL in the head means bytes we can't vouch for, so it
|
|
58
|
+
// downloads instead of rendering (that is how a file starts executing).
|
|
59
|
+
guarded(app, "GET", "/api/explorer/file", 404, async (c) => {
|
|
60
|
+
const file = await resolveScoped(c.req.query("root"), c.req.query("path"));
|
|
61
|
+
if (!(await stat(file)).isFile())
|
|
62
|
+
throw new Error("not a file");
|
|
63
|
+
const bytes = await readFile(file);
|
|
64
|
+
if (bytes.byteLength > MAX_FILE_BYTES)
|
|
65
|
+
return c.json({ error: "file too large" }, 413);
|
|
66
|
+
const binary = BINARY_TYPES[extname(file).toLowerCase()];
|
|
67
|
+
const text = !binary && !bytes.subarray(0, 8192).includes(0);
|
|
68
|
+
return c.body(bytes, 200, {
|
|
69
|
+
"content-type": binary ?? (text ? "text/plain; charset=utf-8" : "application/octet-stream"),
|
|
70
|
+
"content-disposition": `${binary || text ? "inline" : "attachment"}; filename*=UTF-8''${encodeURIComponent(basename(file))}`,
|
|
71
|
+
"cache-control": "no-store",
|
|
72
|
+
});
|
|
73
|
+
});
|
|
74
|
+
// Git refs for the diff pickers: current branch, branches+tags, recent
|
|
75
|
+
// commits. Not a repo → { branch: null }, which the UI renders as "no git".
|
|
76
|
+
guarded(app, "GET", "/api/explorer/git", 404, async (c) => {
|
|
77
|
+
c.header("cache-control", "no-store");
|
|
78
|
+
const root = await resolveScoped(c.req.query("root"));
|
|
79
|
+
let branch;
|
|
80
|
+
try {
|
|
81
|
+
branch = (await git(root, "rev-parse", "--abbrev-ref", "HEAD")).trim();
|
|
82
|
+
}
|
|
83
|
+
catch {
|
|
84
|
+
return c.json({ branch: null, refs: [], commits: [] }); // not a repo, or no commits yet
|
|
85
|
+
}
|
|
86
|
+
const refs = (await git(root, "for-each-ref", "--format=%(refname:short)\t%(subject)", "refs/heads", "refs/tags"))
|
|
87
|
+
.split("\n")
|
|
88
|
+
.filter(Boolean)
|
|
89
|
+
.map((line) => {
|
|
90
|
+
const tab = line.indexOf("\t");
|
|
91
|
+
return { name: line.slice(0, tab), subject: line.slice(tab + 1) };
|
|
92
|
+
});
|
|
93
|
+
// Unit/record separators, because a body is multi-line by nature.
|
|
94
|
+
const commits = (await git(root, "log", "-20", "--format=%h\u001f%at\u001f%an\u001f%s\u001f%b\u001e"))
|
|
95
|
+
.split("\u001e")
|
|
96
|
+
.map((r) => r.trimStart())
|
|
97
|
+
.filter(Boolean)
|
|
98
|
+
.map((r) => {
|
|
99
|
+
const [hash = "", at = "", author = "", subject = "", body = ""] = r.split("\u001f");
|
|
100
|
+
return { hash, at: Number(at) * 1000, author, subject, body: body.trim() };
|
|
101
|
+
});
|
|
102
|
+
return c.json({ branch, refs, commits });
|
|
103
|
+
});
|
|
104
|
+
// One endpoint, two shapes: without `file` the changed-file list
|
|
105
|
+
// (name-status), with it that file's unified diff. `head` empty or absent
|
|
106
|
+
// means the working tree.
|
|
107
|
+
guarded(app, "GET", "/api/explorer/diff", 404, async (c) => {
|
|
108
|
+
c.header("cache-control", "no-store");
|
|
109
|
+
const root = await resolveScoped(c.req.query("root"));
|
|
110
|
+
const base = c.req.query("base") ?? "";
|
|
111
|
+
const head = c.req.query("head") ?? "";
|
|
112
|
+
if (!REF_RE.test(base) || (head !== "" && !REF_RE.test(head)))
|
|
113
|
+
return c.json({ error: "invalid ref" }, 400);
|
|
114
|
+
const range = head ? [base, head] : [base];
|
|
115
|
+
// Context radius for per-file diffs — the UI asks for a huge one to render
|
|
116
|
+
// the whole file with changes toned inline, not a bare patch.
|
|
117
|
+
const context = Math.min(99_999, Math.max(0, Math.trunc(Number(c.req.query("context"))) || 0));
|
|
118
|
+
const file = c.req.query("file");
|
|
119
|
+
if (file === undefined) {
|
|
120
|
+
// name-status carries the letter, numstat the +/- counts; joined by path.
|
|
121
|
+
const [nameStatus, numstat] = await Promise.all([
|
|
122
|
+
git(root, "diff", "--name-status", ...range, "--"),
|
|
123
|
+
git(root, "diff", "--numstat", ...range, "--"),
|
|
124
|
+
]);
|
|
125
|
+
// numstat spells a rename "a/{old => new}.ts" — reduce it to the new path.
|
|
126
|
+
const newPath = (p) => p.replace(/\{([^{}]*) => ([^{}]*)\}/g, "$2").replace(/^(.*) => (.*)$/, "$2");
|
|
127
|
+
const counts = new Map(numstat.split("\n").filter(Boolean).map((line) => {
|
|
128
|
+
const [add = "", del = "", ...path] = line.split("\t");
|
|
129
|
+
// "-" on both sides means binary — no line counts to report.
|
|
130
|
+
return [newPath(path.join("\t")), { add: Number(add) || 0, del: Number(del) || 0 }];
|
|
131
|
+
}));
|
|
132
|
+
const files = nameStatus
|
|
133
|
+
.split("\n")
|
|
134
|
+
.filter(Boolean)
|
|
135
|
+
.map((line) => {
|
|
136
|
+
// Renames/copies are "R100\told\tnew" — show the new path.
|
|
137
|
+
const [status = "", ...paths] = line.split("\t");
|
|
138
|
+
const path = paths[paths.length - 1] ?? "";
|
|
139
|
+
return { status: status.charAt(0), path, ...(counts.get(path) ?? { add: 0, del: 0 }) };
|
|
140
|
+
});
|
|
141
|
+
return c.json({ files });
|
|
142
|
+
}
|
|
143
|
+
// The path only reaches git behind `--`, so it is data, never an option.
|
|
144
|
+
return c.json({ diff: await git(root, "diff", `-U${context || 3}`, ...range, "--", file) });
|
|
145
|
+
});
|
|
146
|
+
}
|
package/dist/web/files.js
CHANGED
|
@@ -5,6 +5,7 @@
|
|
|
5
5
|
import { mkdir, readdir, readFile, realpath, stat } from "node:fs/promises";
|
|
6
6
|
import { homedir } from "node:os";
|
|
7
7
|
import { basename, dirname, extname, isAbsolute, resolve, sep } from "node:path";
|
|
8
|
+
import { INBOX_DIR } from "../core/inbox.js";
|
|
8
9
|
// Content types for the attachment route. Anything unlisted downloads as
|
|
9
10
|
// bytes — guessing a type we can't vouch for is how a file starts executing.
|
|
10
11
|
const FILE_TYPES = {
|
|
@@ -48,15 +49,19 @@ export function registerFileRoutes(app, { factory, config, nascentCwd }) {
|
|
|
48
49
|
return known.some((s) => s.cwd === raw) ? { kind: "project", cwd: raw } : null;
|
|
49
50
|
};
|
|
50
51
|
app.get("/api/config", async (c) => {
|
|
52
|
+
c.header("cache-control", "no-store");
|
|
51
53
|
const scope = await parseScope(c.req.query("scope"));
|
|
52
54
|
if (!scope)
|
|
53
55
|
return c.json({ error: "unknown scope" }, 400);
|
|
54
56
|
return c.json({
|
|
57
|
+
// Where this scope's files live on disk — the UI labels "Global" with it.
|
|
58
|
+
dir: scope.kind === "global" ? config.globalDir : scope.cwd,
|
|
55
59
|
files: await config.listFiles(scope),
|
|
56
60
|
resources: await config.listResources(scope),
|
|
57
61
|
});
|
|
58
62
|
});
|
|
59
63
|
guarded(app, "GET", "/api/config/files/:name", 400, async (c) => {
|
|
64
|
+
c.header("cache-control", "no-store");
|
|
60
65
|
const scope = await parseScope(c.req.query("scope"));
|
|
61
66
|
if (!scope)
|
|
62
67
|
return c.json({ error: "unknown scope" }, 400);
|
|
@@ -67,13 +72,16 @@ export function registerFileRoutes(app, { factory, config, nascentCwd }) {
|
|
|
67
72
|
if (!scope)
|
|
68
73
|
return c.json({ error: "unknown scope" }, 400);
|
|
69
74
|
const body = await c.req.json().catch(() => null);
|
|
70
|
-
if (typeof body?.content !== "string")
|
|
71
|
-
return c.json({ error: "content required" }, 400);
|
|
72
|
-
|
|
73
|
-
|
|
75
|
+
if (typeof body?.content !== "string" || typeof body?.expected !== "string") {
|
|
76
|
+
return c.json({ error: "content and expected content required" }, 400);
|
|
77
|
+
}
|
|
78
|
+
const name = c.req.param("name");
|
|
79
|
+
await config.writeFile(scope, name, body.content, body.expected);
|
|
80
|
+
return c.json({ ok: true, content: await config.readFile(scope, name) });
|
|
74
81
|
});
|
|
75
82
|
// Resource names may contain slashes — query params, not path params.
|
|
76
83
|
guarded(app, "GET", "/api/config/resource", 400, async (c) => {
|
|
84
|
+
c.header("cache-control", "no-store");
|
|
77
85
|
const scope = await parseScope(c.req.query("scope"));
|
|
78
86
|
if (!scope)
|
|
79
87
|
return c.json({ error: "unknown scope" }, 400);
|
|
@@ -84,16 +92,23 @@ export function registerFileRoutes(app, { factory, config, nascentCwd }) {
|
|
|
84
92
|
}
|
|
85
93
|
return c.json({ content: await config.readResource(scope, kind, name) });
|
|
86
94
|
});
|
|
87
|
-
/** Real path of a file a session may expose: inside its cwd
|
|
95
|
+
/** Real path of a file a session may expose: inside its cwd or the inbox
|
|
96
|
+
* (where inbound user attachments land — core/inbox.ts), nothing else. */
|
|
88
97
|
const resolveFile = async (id, raw) => {
|
|
89
98
|
const cwd = nascentCwd(id) ?? (await factory.list()).find((s) => s.id === id)?.cwd;
|
|
90
99
|
if (!cwd || !isAbsolute(raw))
|
|
91
100
|
return null;
|
|
92
101
|
try {
|
|
93
102
|
// realpath both ends, so neither `..` nor a symlink can step outside.
|
|
94
|
-
const
|
|
95
|
-
|
|
96
|
-
|
|
103
|
+
const roots = [await realpath(cwd)];
|
|
104
|
+
try {
|
|
105
|
+
roots.push(await realpath(INBOX_DIR));
|
|
106
|
+
}
|
|
107
|
+
catch {
|
|
108
|
+
/* no inbox yet — nothing was ever uploaded */
|
|
109
|
+
}
|
|
110
|
+
const target = await realpath(resolve(roots[0], raw));
|
|
111
|
+
if (!roots.some((root) => target === root || target.startsWith(root + sep)))
|
|
97
112
|
return null;
|
|
98
113
|
return (await stat(target)).isFile() ? target : null;
|
|
99
114
|
}
|
|
@@ -101,9 +116,9 @@ export function registerFileRoutes(app, { factory, config, nascentCwd }) {
|
|
|
101
116
|
return null; // missing, unreadable, or not a file
|
|
102
117
|
}
|
|
103
118
|
};
|
|
104
|
-
//
|
|
105
|
-
//
|
|
106
|
-
// the session's own
|
|
119
|
+
// Attachments, both directions: the agent links a file it produced, the
|
|
120
|
+
// chat renders a file the user sent — the client fetches the bytes here,
|
|
121
|
+
// read-only, and only from the session's own cwd or the inbox.
|
|
107
122
|
app.get("/api/sessions/:id/files", async (c) => {
|
|
108
123
|
const raw = c.req.query("path");
|
|
109
124
|
if (!raw)
|
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
// Routes about the Pier instance itself — settings, update availability,
|
|
2
|
+
// layer-1 secrets control, the browser's error reports. Nothing here touches
|
|
3
|
+
// a session; server.ts stays the session/event surface.
|
|
4
|
+
import { logger } from "../log.js";
|
|
5
|
+
import { normalizeModelMenu, normalizePublicUrl } from "../settings.js";
|
|
6
|
+
/** Client reports per minute, for the whole server: a browser bug can fire in
|
|
7
|
+
* a loop, and the journal is shared with everything else Pier says. */
|
|
8
|
+
const CLIENT_LOG_PER_MINUTE = 60;
|
|
9
|
+
export function registerInstanceRoutes(app, deps) {
|
|
10
|
+
const { settings, updates, secrets, onUnlocked } = deps;
|
|
11
|
+
// The browser's half of the log. A workbench that threw after the response
|
|
12
|
+
// left the server is otherwise invisible here (ui/report.ts) — this is the
|
|
13
|
+
// one route whose entire purpose is to make it visible.
|
|
14
|
+
const clientLog = logger("client");
|
|
15
|
+
let reports = [];
|
|
16
|
+
app.post("/api/client-log", async (c) => {
|
|
17
|
+
const body = (await c.req.json().catch(() => null));
|
|
18
|
+
if (typeof body?.message !== "string" || !body.message.trim()) {
|
|
19
|
+
return c.json({ error: "message required" }, 400);
|
|
20
|
+
}
|
|
21
|
+
const now = Date.now();
|
|
22
|
+
reports = reports.filter((at) => now - at < 60_000);
|
|
23
|
+
if (reports.length >= CLIENT_LOG_PER_MINUTE)
|
|
24
|
+
return c.body(null, 429);
|
|
25
|
+
reports.push(now);
|
|
26
|
+
const cap = (value, max) => typeof value === "string" ? value.slice(0, max) : "";
|
|
27
|
+
const where = cap(body.view, 120);
|
|
28
|
+
const stack = cap(body.stack, 2000);
|
|
29
|
+
// One line, ua included: "only on iOS" is the answer half these questions
|
|
30
|
+
// have, and the report is the only place it exists.
|
|
31
|
+
clientLog.warn(`${cap(body.message, 500)} [${where || "/"}] ${cap(c.req.header("user-agent"), 160)}` +
|
|
32
|
+
(stack ? `\n${stack}` : ""));
|
|
33
|
+
return c.body(null, 204);
|
|
34
|
+
});
|
|
35
|
+
// Instance settings. The password lives behind its own route (web/auth.ts):
|
|
36
|
+
// it is a credential, and changing it takes the old one.
|
|
37
|
+
app.get("/api/settings", (c) => c.json(settings.get()));
|
|
38
|
+
// Read-only on purpose: the workbench says a newer Pier exists, and applying
|
|
39
|
+
// it stays `pier update` in a terminal. An HTTP route that installs packages
|
|
40
|
+
// is a supply-chain surface behind one password.
|
|
41
|
+
app.get("/api/update", (c) => c.json(updates.status()));
|
|
42
|
+
// Partial on purpose: each surface sends only the setting it edits, and a
|
|
43
|
+
// malformed field is rejected before anything is written.
|
|
44
|
+
app.put("/api/settings", async (c) => {
|
|
45
|
+
const body = await c.req.json().catch(() => null);
|
|
46
|
+
if (!body || (body.publicUrl === undefined && body.modelMenu === undefined)) {
|
|
47
|
+
return c.json({ error: "publicUrl or modelMenu required" }, 400);
|
|
48
|
+
}
|
|
49
|
+
if (body.publicUrl !== undefined) {
|
|
50
|
+
if (typeof body.publicUrl !== "string")
|
|
51
|
+
return c.json({ error: "publicUrl must be a string" }, 400);
|
|
52
|
+
const publicUrl = normalizePublicUrl(body.publicUrl);
|
|
53
|
+
if (publicUrl === null) {
|
|
54
|
+
return c.json({ error: "not a URL: expected http(s)://host, no query or fragment" }, 400);
|
|
55
|
+
}
|
|
56
|
+
settings.setPublicUrl(publicUrl);
|
|
57
|
+
}
|
|
58
|
+
if (body.modelMenu !== undefined) {
|
|
59
|
+
const menu = normalizeModelMenu(body.modelMenu);
|
|
60
|
+
if (menu === null) {
|
|
61
|
+
return c.json({ error: "modelMenu must be [{provider, id, note?}] (≤32 entries)" }, 400);
|
|
62
|
+
}
|
|
63
|
+
settings.setModelMenu(menu);
|
|
64
|
+
}
|
|
65
|
+
return c.json(settings.get());
|
|
66
|
+
});
|
|
67
|
+
// Layer-1 key status and control (Console → Settings → Security). The GET
|
|
68
|
+
// is what a locked instance shows; unlock is how it recovers without a
|
|
69
|
+
// restart, and rotate is the only way to change how the KEK is protected.
|
|
70
|
+
const secretsStatus = () => ({
|
|
71
|
+
state: secrets.state,
|
|
72
|
+
mode: secrets.mode ?? null,
|
|
73
|
+
...(secrets.state === "locked" ? { reason: secrets.lockedReason } : {}),
|
|
74
|
+
});
|
|
75
|
+
app.get("/api/secrets", (c) => c.json(secretsStatus()));
|
|
76
|
+
app.post("/api/secrets/unlock", async (c) => {
|
|
77
|
+
try {
|
|
78
|
+
await secrets.unlock();
|
|
79
|
+
}
|
|
80
|
+
catch (err) {
|
|
81
|
+
return c.json({ error: String(err) }, 500);
|
|
82
|
+
}
|
|
83
|
+
onUnlocked?.();
|
|
84
|
+
return c.json(secretsStatus());
|
|
85
|
+
});
|
|
86
|
+
app.post("/api/secrets/rotate", async (c) => {
|
|
87
|
+
const body = (await c.req.json().catch(() => ({})));
|
|
88
|
+
if (body.mode !== undefined && body.mode !== "vt" && body.mode !== "file") {
|
|
89
|
+
return c.json({ error: "mode must be vt or file" }, 400);
|
|
90
|
+
}
|
|
91
|
+
try {
|
|
92
|
+
await secrets.rotateKek(body.mode);
|
|
93
|
+
}
|
|
94
|
+
catch (err) {
|
|
95
|
+
return c.json({ error: String(err) }, 500);
|
|
96
|
+
}
|
|
97
|
+
return c.json(secretsStatus());
|
|
98
|
+
});
|
|
99
|
+
}
|