@tenonai/yew 0.0.0-stage → 1.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (133) hide show
  1. package/CHANGELOG.md +273 -0
  2. package/LICENSE +21 -0
  3. package/README.md +64 -2
  4. package/THIRD-PARTY-NOTICES.md +122 -0
  5. package/bin/yew.js +9 -0
  6. package/dist/cli/app.js +211 -0
  7. package/dist/cli/export.js +57 -0
  8. package/dist/cli/io.js +65 -0
  9. package/dist/cli/key.js +113 -0
  10. package/dist/cli/main.js +58 -0
  11. package/dist/cli/mcp.js +76 -0
  12. package/dist/cli/remote.js +116 -0
  13. package/dist/cli/run.js +72 -0
  14. package/dist/cli/schedule.js +123 -0
  15. package/dist/cli/send.js +127 -0
  16. package/dist/cli/serve.js +301 -0
  17. package/dist/cli/service.js +268 -0
  18. package/dist/cli/system.js +44 -0
  19. package/dist/remote/access.js +107 -0
  20. package/dist/remote/connector.js +278 -0
  21. package/dist/remote/identity.js +71 -0
  22. package/dist/remote/noise.js +287 -0
  23. package/dist/remote/protocol.js +51 -0
  24. package/dist/remote/push.js +37 -0
  25. package/dist/server/agent/compaction.js +242 -0
  26. package/dist/server/agent/context.js +120 -0
  27. package/dist/server/agent/held.js +48 -0
  28. package/dist/server/agent/helper.js +122 -0
  29. package/dist/server/agent/mailroom.js +510 -0
  30. package/dist/server/agent/prompt.js +268 -0
  31. package/dist/server/agent/runner.js +1159 -0
  32. package/dist/server/artifacts.js +216 -0
  33. package/dist/server/budget.js +88 -0
  34. package/dist/server/data-export.js +105 -0
  35. package/dist/server/data-usage.js +144 -0
  36. package/dist/server/db/database.js +49 -0
  37. package/dist/server/db/migrations.js +343 -0
  38. package/dist/server/errors.js +16 -0
  39. package/dist/server/events.js +17 -0
  40. package/dist/server/export.js +378 -0
  41. package/dist/server/folder-picker.js +32 -0
  42. package/dist/server/from-jig.js +98 -0
  43. package/dist/server/http/agents.js +78 -0
  44. package/dist/server/http/api.js +465 -0
  45. package/dist/server/http/app.js +111 -0
  46. package/dist/server/http/artifacts.js +53 -0
  47. package/dist/server/http/data.js +54 -0
  48. package/dist/server/http/devices.js +47 -0
  49. package/dist/server/http/events.js +134 -0
  50. package/dist/server/http/idempotency.js +53 -0
  51. package/dist/server/http/input.js +106 -0
  52. package/dist/server/http/mail.js +52 -0
  53. package/dist/server/http/mcp.js +134 -0
  54. package/dist/server/http/notes.js +91 -0
  55. package/dist/server/http/problem.js +55 -0
  56. package/dist/server/http/providers.js +131 -0
  57. package/dist/server/http/schedules.js +58 -0
  58. package/dist/server/http/search.js +42 -0
  59. package/dist/server/http/security.js +168 -0
  60. package/dist/server/http/skills.js +53 -0
  61. package/dist/server/http/system.js +26 -0
  62. package/dist/server/ids.js +30 -0
  63. package/dist/server/keys.js +70 -0
  64. package/dist/server/mail/envelope.js +152 -0
  65. package/dist/server/mail/post.js +603 -0
  66. package/dist/server/mail/store.js +279 -0
  67. package/dist/server/manage.js +601 -0
  68. package/dist/server/mcp-builtin.js +180 -0
  69. package/dist/server/mcp-config.js +305 -0
  70. package/dist/server/mcp-oauth.js +448 -0
  71. package/dist/server/mcp.js +668 -0
  72. package/dist/server/model/gateway.js +410 -0
  73. package/dist/server/paths.js +43 -0
  74. package/dist/server/permissions/engine.js +249 -0
  75. package/dist/server/permissions/paths.js +93 -0
  76. package/dist/server/permissions/shell.js +635 -0
  77. package/dist/server/push.js +345 -0
  78. package/dist/server/reveal.js +36 -0
  79. package/dist/server/runtime.js +17 -0
  80. package/dist/server/schedules.js +356 -0
  81. package/dist/server/settings.js +77 -0
  82. package/dist/server/skills.js +263 -0
  83. package/dist/server/store.js +1077 -0
  84. package/dist/server/tools/files.js +318 -0
  85. package/dist/server/tools/html.js +221 -0
  86. package/dist/server/tools/jobs.js +38 -0
  87. package/dist/server/tools/mail.js +680 -0
  88. package/dist/server/tools/match.js +81 -0
  89. package/dist/server/tools/misc.js +253 -0
  90. package/dist/server/tools/process.js +128 -0
  91. package/dist/server/tools/read-state.js +40 -0
  92. package/dist/server/tools/registry.js +43 -0
  93. package/dist/server/tools/search.js +175 -0
  94. package/dist/server/tools/shell.js +124 -0
  95. package/dist/server/tools/types.js +43 -0
  96. package/dist/server/tools/web-search.js +198 -0
  97. package/dist/server/tools/web.js +240 -0
  98. package/dist/shared/cron.js +105 -0
  99. package/dist/shared/mcp-presets.js +170 -0
  100. package/dist/shared/messages.js +45 -0
  101. package/dist/shared/policy.js +42 -0
  102. package/dist/shared/types.js +34 -0
  103. package/dist/shared/version.js +8 -0
  104. package/mcp-builtin/package-lock.json +3398 -0
  105. package/mcp-builtin/package.json +14 -0
  106. package/mcp-builtin/presets/gitee/package-lock.json +105 -0
  107. package/mcp-builtin/presets/gitee/package.json +10 -0
  108. package/mcp-builtin/presets/notion/package-lock.json +2243 -0
  109. package/mcp-builtin/presets/notion/package.json +10 -0
  110. package/mcp-builtin/presets/sentry/package-lock.json +28 -0
  111. package/mcp-builtin/presets/sentry/package.json +10 -0
  112. package/package.json +75 -5
  113. package/web/dist/THIRD-PARTY-NOTICES.txt +1944 -0
  114. package/web/dist/assets/index-BtK_SzpF.css +1 -0
  115. package/web/dist/assets/index-C0rnUFI-.js +68 -0
  116. package/web/dist/icons/app-icon.png +0 -0
  117. package/web/dist/icons/apple-touch-icon.png +0 -0
  118. package/web/dist/icons/favicon-16.png +0 -0
  119. package/web/dist/icons/favicon-32.png +0 -0
  120. package/web/dist/icons/favicon-64.png +0 -0
  121. package/web/dist/icons/tenon-mark.svg +1 -0
  122. package/web/dist/icons/yew-mark.svg +1 -0
  123. package/web/dist/index.html +18 -0
  124. package/web/dist/mascot/gift.webp +0 -0
  125. package/web/dist/mascot/greeting.webp +0 -0
  126. package/web/dist/mascot/happy.webp +0 -0
  127. package/web/dist/mascot/lost.webp +0 -0
  128. package/web/dist/mascot/shush.webp +0 -0
  129. package/web/dist/mascot/sleepy.webp +0 -0
  130. package/web/dist/mascot/sorry.webp +0 -0
  131. package/web/dist/mascot/thinking.webp +0 -0
  132. package/web/dist/mascot/waking.webp +0 -0
  133. package/web/dist/mascot/writing.webp +0 -0
@@ -0,0 +1,55 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { HTTPException } from "hono/http-exception";
3
+ import { YewError } from "../errors.js";
4
+ /** Problem types are tag URIs (RFC 4151): stable identifiers that are not meant to be fetched. */
5
+ export const problemType = (code) => `tag:tenonai.cn,2026:yew/problem/${code}`;
6
+ export function problemResponse(c, status, code, title, detail, extra) {
7
+ const body = {
8
+ type: problemType(code),
9
+ title,
10
+ status,
11
+ ...(detail ? { detail } : {}),
12
+ ...extra,
13
+ requestId: c.get("requestId"),
14
+ };
15
+ return c.newResponse(JSON.stringify(body), status, {
16
+ "Content-Type": "application/problem+json",
17
+ });
18
+ }
19
+ const TITLES = {
20
+ 400: "Bad request",
21
+ 401: "Sign-in required",
22
+ 403: "Forbidden",
23
+ 404: "Not found",
24
+ 405: "Method not allowed",
25
+ 409: "Conflict",
26
+ 413: "Request too large",
27
+ 415: "Unsupported media type",
28
+ 421: "Misdirected request",
29
+ 422: "Unprocessable request",
30
+ 429: "Too many requests",
31
+ 500: "Internal error",
32
+ 503: "Unavailable",
33
+ };
34
+ export function titleFor(status) {
35
+ return TITLES[status] ?? "Error";
36
+ }
37
+ /** Gives every request an ID, returned in `X-Request-Id` and in problem bodies (spec 12.2, 20.1). */
38
+ export const requestId = () => async (c, next) => {
39
+ const id = randomUUID();
40
+ c.set("requestId", id);
41
+ await next();
42
+ c.res.headers.set("X-Request-Id", id);
43
+ };
44
+ export function errorHandler(log) {
45
+ return (error, c) => {
46
+ if (error instanceof YewError) {
47
+ return problemResponse(c, error.status, error.code, titleFor(error.status), error.message, error.details);
48
+ }
49
+ if (error instanceof HTTPException) {
50
+ return problemResponse(c, error.status, "http-error", titleFor(error.status), error.message);
51
+ }
52
+ log(`[${c.get("requestId")}] ${c.req.method} ${c.req.path}: ${error.stack ?? error.message}`);
53
+ return problemResponse(c, 500, "internal-error", titleFor(500), "Something went wrong inside Yew. The request ID is in the log.");
54
+ };
55
+ }
@@ -0,0 +1,131 @@
1
+ import { Hono } from "hono";
2
+ import { invalid, notFound } from "../errors.js";
3
+ import { optArray, optBoolean, optNumber, optString, pageParams, readJson, reqString, } from "./input.js";
4
+ const PROVIDER_ID = /^[a-z0-9][a-z0-9-]{0,39}$/;
5
+ function parseCustomProvider(id, fields) {
6
+ if (!PROVIDER_ID.test(id)) {
7
+ throw invalid("The provider id uses lowercase letters, digits and dashes, up to 40.", "id");
8
+ }
9
+ const name = reqString(fields, "name", 60).trim();
10
+ if (!name)
11
+ throw invalid("The name cannot be empty.", "name");
12
+ const baseUrl = reqString(fields, "baseUrl", 2000);
13
+ let url;
14
+ try {
15
+ url = new URL(baseUrl);
16
+ }
17
+ catch {
18
+ throw invalid("The base URL is not a valid URL.", "baseUrl");
19
+ }
20
+ if (url.protocol !== "https:" && url.protocol !== "http:") {
21
+ throw invalid("The base URL must start with http:// or https://.", "baseUrl");
22
+ }
23
+ const models = optArray(fields, "models") ?? [];
24
+ if (models.length === 0 || models.length > 100) {
25
+ throw invalid("Add between 1 and 100 models.", "models");
26
+ }
27
+ return {
28
+ id,
29
+ name,
30
+ baseUrl: baseUrl.replace(/\/+$/, ""),
31
+ keyRequired: optBoolean(fields, "keyRequired") ?? true,
32
+ models: models.map((item, index) => {
33
+ if (!item || typeof item !== "object" || Array.isArray(item)) {
34
+ throw invalid(`Model ${index + 1} must be an object.`, "models");
35
+ }
36
+ const model = item;
37
+ const contextWindow = optNumber(model, "contextWindow");
38
+ const maxTokens = optNumber(model, "maxTokens");
39
+ if (!contextWindow || !Number.isInteger(contextWindow) || contextWindow < 1000) {
40
+ throw invalid(`Model ${index + 1} needs a context window of at least 1000 tokens.`, "models");
41
+ }
42
+ if (!maxTokens || !Number.isInteger(maxTokens) || maxTokens > contextWindow) {
43
+ throw invalid(`Model ${index + 1} needs a maximum output no larger than its context window.`, "models");
44
+ }
45
+ const modelName = optString(model, "name", 100);
46
+ const reasoning = optBoolean(model, "reasoning");
47
+ const images = optBoolean(model, "images");
48
+ return {
49
+ id: reqString(model, "id", 200),
50
+ ...(modelName ? { name: modelName } : {}),
51
+ contextWindow,
52
+ maxTokens,
53
+ ...(reasoning !== undefined ? { reasoning } : {}),
54
+ input: images ? ["text", "image"].slice() : ["text"],
55
+ };
56
+ }),
57
+ };
58
+ }
59
+ /** Model providers, their models, and their API keys. Keys are written to the keychain and never read back. */
60
+ export function providerRoutes(store, gateway) {
61
+ const app = new Hono();
62
+ app.get("/providers", async (c) => {
63
+ const providers = gateway.providers();
64
+ const items = await Promise.all(providers.map(async (provider) => ({
65
+ ...provider,
66
+ hasKey: await gateway.hasKey(provider.id),
67
+ modelCount: gateway.models(provider.id).length,
68
+ })));
69
+ return c.json({ items, nextCursor: null });
70
+ });
71
+ // One short request with the stored key: does it work from here, and how long does it take.
72
+ app.post("/providers/:id/test", async (c) => {
73
+ const id = c.req.param("id");
74
+ if (!gateway.provider(id))
75
+ throw notFound("Provider", id);
76
+ const body = (await c.req.json().catch(() => ({})));
77
+ const model = typeof body.model === "string" && body.model ? body.model : undefined;
78
+ return c.json(await gateway.ping(id, model));
79
+ });
80
+ app.get("/providers/:id/models", (c) => {
81
+ const id = c.req.param("id");
82
+ if (!gateway.provider(id))
83
+ throw notFound("Provider", id);
84
+ const { limit, cursor } = pageParams(c, 500);
85
+ const all = gateway.models(id);
86
+ const start = cursor ? all.findIndex((model) => model.id === cursor) + 1 : 0;
87
+ const items = all.slice(start, start + limit);
88
+ const more = start + limit < all.length;
89
+ return c.json({ items, nextCursor: more ? (items.at(-1)?.id ?? null) : null });
90
+ });
91
+ app.put("/providers/:id/key", async (c) => {
92
+ const id = c.req.param("id");
93
+ if (!gateway.provider(id))
94
+ throw notFound("Provider", id);
95
+ const fields = await readJson(c);
96
+ const key = reqString(fields, "key", 4096).trim();
97
+ if (!key)
98
+ throw invalid("The key cannot be empty.", "key");
99
+ await gateway.saveKey(id, key);
100
+ return c.body(null, 204);
101
+ });
102
+ app.delete("/providers/:id/key", async (c) => {
103
+ const id = c.req.param("id");
104
+ if (!gateway.provider(id))
105
+ throw notFound("Provider", id);
106
+ await gateway.deleteKey(id);
107
+ return c.body(null, 204);
108
+ });
109
+ app.put("/providers/:id", async (c) => {
110
+ const id = c.req.param("id");
111
+ const existing = gateway.provider(id);
112
+ if (existing && !existing.custom)
113
+ throw invalid(`${id} is a built-in provider.`, "id");
114
+ const config = parseCustomProvider(id, await readJson(c));
115
+ const others = store.listCustomProviders().filter((provider) => provider.id !== id);
116
+ gateway.setCustomProviders([...others, config]);
117
+ store.saveCustomProvider(config);
118
+ return c.json(gateway.provider(id), existing ? 200 : 201);
119
+ });
120
+ app.delete("/providers/:id", async (c) => {
121
+ const id = c.req.param("id");
122
+ const existing = gateway.provider(id);
123
+ if (!existing?.custom)
124
+ throw notFound("Custom provider", id);
125
+ store.deleteCustomProvider(id);
126
+ gateway.setCustomProviders(store.listCustomProviders());
127
+ await gateway.deleteKey(id);
128
+ return c.body(null, 204);
129
+ });
130
+ return app;
131
+ }
@@ -0,0 +1,58 @@
1
+ import { Hono } from "hono";
2
+ import { PERMISSION_MODES } from "../../shared/types.js";
3
+ import { skippedError } from "../schedules.js";
4
+ import { idempotent } from "./idempotency.js";
5
+ import { optBoolean, optEnum, optString, readJson } from "./input.js";
6
+ function scheduleFields(fields) {
7
+ const permissionMode = fields.permissionMode === null ? null : optEnum(fields, "permissionMode", PERMISSION_MODES);
8
+ const out = {};
9
+ const name = optString(fields, "name", 200);
10
+ const cron = optString(fields, "cron", 200);
11
+ const session = optString(fields, "session", 200);
12
+ const message = optString(fields, "message", 40_000);
13
+ const catchUp = optBoolean(fields, "catchUp");
14
+ const enabled = optBoolean(fields, "enabled");
15
+ if (name !== undefined)
16
+ out.name = name;
17
+ if (cron !== undefined)
18
+ out.cron = cron;
19
+ if (session !== undefined)
20
+ out.session = session;
21
+ if (message !== undefined)
22
+ out.message = message;
23
+ if (permissionMode !== undefined)
24
+ out.permissionMode = permissionMode;
25
+ if (catchUp !== undefined)
26
+ out.catchUp = catchUp;
27
+ if (enabled !== undefined)
28
+ out.enabled = enabled;
29
+ return out;
30
+ }
31
+ /** Scheduled tasks (M3 plan, section 11): list, add, change, remove, and run one now. */
32
+ export function scheduleRoutes(store, scheduler) {
33
+ const app = new Hono();
34
+ const once = idempotent(store.db);
35
+ const book = scheduler.book;
36
+ app.get("/schedules", (c) => c.json({ items: book.list(), nextCursor: null }));
37
+ app.post("/schedules", once, async (c) => {
38
+ const fields = scheduleFields(await readJson(c));
39
+ return c.json(book.create(fields), 201);
40
+ });
41
+ app.patch("/schedules/:id", async (c) => {
42
+ const fields = scheduleFields(await readJson(c));
43
+ return c.json(book.update(c.req.param("id"), fields));
44
+ });
45
+ app.delete("/schedules/:id", (c) => {
46
+ book.delete(c.req.param("id"));
47
+ return c.body(null, 204);
48
+ });
49
+ // Runs it now, outside its times; the next run stays as it was.
50
+ app.post("/schedules/:id/run", (c) => {
51
+ const id = c.req.param("id");
52
+ const result = scheduler.run(id);
53
+ if ("skipped" in result)
54
+ throw skippedError(result.skipped, book.get(id).name);
55
+ return c.json({ schedule: book.get(id), letter: result.letter });
56
+ });
57
+ return app;
58
+ }
@@ -0,0 +1,42 @@
1
+ import { Hono } from "hono";
2
+ import { invalid, notFound } from "../errors.js";
3
+ import { SEARCH_SERVICES } from "../tools/web-search.js";
4
+ import { readJson, reqString } from "./input.js";
5
+ /**
6
+ * The search services and their keys (blueprint 6.10, item 30). As with the model providers, a key
7
+ * is written to the keychain and never read back; the list says only whether one is saved.
8
+ */
9
+ export function searchRoutes(search) {
10
+ const app = new Hono();
11
+ const service = (id) => {
12
+ const found = SEARCH_SERVICES.find((item) => item.id === id);
13
+ if (!found)
14
+ throw notFound("Search service", id);
15
+ return found;
16
+ };
17
+ app.get("/search-services", async (c) => {
18
+ await search.refresh();
19
+ const items = await Promise.all(SEARCH_SERVICES.map(async (item) => ({
20
+ id: item.id,
21
+ name: item.name,
22
+ region: item.region,
23
+ hasKey: await search.hasKey(item),
24
+ // The one web search uses: the first in this order that has a key.
25
+ active: search.service?.id === item.id,
26
+ })));
27
+ return c.json({ items, nextCursor: null });
28
+ });
29
+ app.put("/search-services/:id/key", async (c) => {
30
+ const found = service(c.req.param("id"));
31
+ const key = reqString(await readJson(c), "key", 4096).trim();
32
+ if (!key)
33
+ throw invalid("The key cannot be empty.", "key");
34
+ await search.saveKey(found, key);
35
+ return c.body(null, 204);
36
+ });
37
+ app.delete("/search-services/:id/key", async (c) => {
38
+ await search.deleteKey(service(c.req.param("id")));
39
+ return c.body(null, 204);
40
+ });
41
+ return app;
42
+ }
@@ -0,0 +1,168 @@
1
+ import { createHash, randomBytes } from "node:crypto";
2
+ import { Hono } from "hono";
3
+ import { deleteCookie, getCookie, setCookie } from "hono/cookie";
4
+ import { readJson, reqString } from "./input.js";
5
+ import { problemResponse, titleFor } from "./problem.js";
6
+ const LOGIN_TTL_MS = 10 * 60 * 1000;
7
+ const BROWSER_TTL_MS = 30 * 24 * 60 * 60 * 1000;
8
+ export const cookieName = (port) => `yew_${port}`;
9
+ export function hashToken(token) {
10
+ return createHash("sha256").update(token).digest("hex");
11
+ }
12
+ /** A one-time login token, shown by `yew serve` and `yew open` in the URL fragment (spec 15.1.3). */
13
+ export function issueLoginToken(store) {
14
+ const token = randomBytes(32).toString("base64url");
15
+ store.pruneAuthTokens();
16
+ store.saveAuthToken(hashToken(token), "login", Date.now() + LOGIN_TTL_MS);
17
+ return token;
18
+ }
19
+ /**
20
+ * Only this machine, only this origin (after pi's local checks, prior-art 5.2):
21
+ * - Host must be 127.0.0.1 or localhost with our port, which stops DNS rebinding;
22
+ * - requests that came through a proxy are refused;
23
+ * - API requests must come from Yew's own pages: same-origin `Sec-Fetch-Site`, and a matching `Origin`
24
+ * on writes. Other pages on this machine share the cookie's site (ports do not separate sites), so the
25
+ * cookie alone is not enough;
26
+ * - Yew's pages cannot be framed.
27
+ */
28
+ export function localOnly(port) {
29
+ const hosts = new Set([`127.0.0.1:${port}`, `localhost:${port}`]);
30
+ return async (c, next) => {
31
+ // A paired phone's request, handed over in-process by the relay connector.
32
+ if (c.env?.device)
33
+ return next();
34
+ const host = c.req.header("Host") ?? "";
35
+ if (!hosts.has(host)) {
36
+ return problemResponse(c, 421, "wrong-host", titleFor(421), "Yew only answers on 127.0.0.1 and localhost.");
37
+ }
38
+ for (const header of [
39
+ "Forwarded",
40
+ "X-Forwarded-For",
41
+ "X-Forwarded-Host",
42
+ "X-Forwarded-Proto",
43
+ ]) {
44
+ if (c.req.header(header) !== undefined) {
45
+ return problemResponse(c, 403, "proxied", titleFor(403), "Requests through a proxy are not accepted.");
46
+ }
47
+ }
48
+ if (c.req.path.startsWith("/api/")) {
49
+ const site = c.req.header("Sec-Fetch-Site");
50
+ if (site !== undefined && site !== "same-origin" && site !== "none") {
51
+ return problemResponse(c, 403, "cross-site", titleFor(403), "Requests from other sites are refused.");
52
+ }
53
+ const dest = c.req.header("Sec-Fetch-Dest");
54
+ if (dest === "iframe" || dest === "frame" || dest === "embed" || dest === "object") {
55
+ return problemResponse(c, 403, "embedded", titleFor(403), "Yew cannot be embedded.");
56
+ }
57
+ if (c.req.method !== "GET" && c.req.method !== "HEAD") {
58
+ const origin = c.req.header("Origin");
59
+ if (origin !== `http://${host}`) {
60
+ return problemResponse(c, 403, "bad-origin", titleFor(403), "This request did not come from Yew's own page.");
61
+ }
62
+ }
63
+ }
64
+ await next();
65
+ };
66
+ }
67
+ /** Security headers on every response (M1 plan, section 10). */
68
+ export const securityHeaders = () => async (c, next) => {
69
+ await next();
70
+ const headers = c.res.headers;
71
+ // An HTML artifact brings its own, stricter policy, and is framed by Yew's own page only.
72
+ if (c.req.path.startsWith("/artifact-view/") && headers.has("Content-Security-Policy")) {
73
+ headers.set("X-Content-Type-Options", "nosniff");
74
+ headers.set("Referrer-Policy", "no-referrer");
75
+ headers.set("X-Frame-Options", "SAMEORIGIN");
76
+ return;
77
+ }
78
+ headers.set("Content-Security-Policy", "default-src 'self'; script-src 'self'; style-src 'self'; img-src 'self' data: blob:; font-src 'self'; connect-src 'self'; object-src 'none'; base-uri 'none'; form-action 'self'; frame-ancestors 'none'");
79
+ headers.set("X-Content-Type-Options", "nosniff");
80
+ headers.set("Referrer-Policy", "no-referrer");
81
+ headers.set("X-Frame-Options", "DENY");
82
+ headers.set("Cross-Origin-Opener-Policy", "same-origin");
83
+ headers.set("Cross-Origin-Resource-Policy", "same-origin");
84
+ headers.set("Permissions-Policy", "camera=(), microphone=(), geolocation=()");
85
+ if (c.req.path.startsWith("/api/"))
86
+ headers.set("Cache-Control", "no-store");
87
+ };
88
+ /** Paths that work without signing in. */
89
+ const OPEN_PATHS = new Set(["/api/auth/exchange", "/api/health"]);
90
+ /** API requests need the browser cookie that a login token was exchanged for. */
91
+ export function requireBrowser(store, port) {
92
+ return async (c, next) => {
93
+ if (!c.req.path.startsWith("/api/") || OPEN_PATHS.has(c.req.path))
94
+ return next();
95
+ if (c.env?.device)
96
+ return next();
97
+ const token = getCookie(c, cookieName(port));
98
+ if (!token || !store.touchBrowserToken(hashToken(token), Date.now() + BROWSER_TTL_MS)) {
99
+ return problemResponse(c, 401, "sign-in-required", titleFor(401), "Open Yew with the link from `yew serve` or `yew open`.");
100
+ }
101
+ await next();
102
+ };
103
+ }
104
+ function setBrowserCookie(c, port, token) {
105
+ setCookie(c, cookieName(port), token, {
106
+ httpOnly: true,
107
+ sameSite: "Strict",
108
+ path: "/",
109
+ maxAge: BROWSER_TTL_MS / 1000,
110
+ });
111
+ }
112
+ export function authRoutes(store, port) {
113
+ const app = new Hono();
114
+ /** Trades a one-time login token for an HttpOnly, SameSite=Strict cookie; the token stops working. */
115
+ app.post("/auth/exchange", async (c) => {
116
+ const fields = await readJson(c);
117
+ const token = reqString(fields, "token", 200);
118
+ if (!store.consumeLoginToken(hashToken(token))) {
119
+ return problemResponse(c, 401, "invalid-login-token", titleFor(401), "This sign-in link was already used or has expired. Run `yew open` for a new one.");
120
+ }
121
+ const browser = randomBytes(32).toString("base64url");
122
+ store.saveAuthToken(hashToken(browser), "browser", Date.now() + BROWSER_TTL_MS);
123
+ setBrowserCookie(c, port, browser);
124
+ return c.body(null, 204);
125
+ });
126
+ app.post("/auth/logout", (c) => {
127
+ const token = getCookie(c, cookieName(port));
128
+ if (token)
129
+ store.deleteAuthToken(hashToken(token));
130
+ deleteCookie(c, cookieName(port), { path: "/" });
131
+ return c.body(null, 204);
132
+ });
133
+ return app;
134
+ }
135
+ /**
136
+ * What a paired phone may not do through the relay (M3 plan, section 4): manage API keys, add or revoke
137
+ * devices, or change remote access. Those stay on the Mac. So do the settings that decide what this
138
+ * computer starts or holds as a secret: MCP servers, search keys, starting at login and the launcher,
139
+ * the skills in this computer's folders, and the data folder: its size, export and cleanup.
140
+ */
141
+ const COMPUTER_ONLY = [
142
+ "/api/mcp",
143
+ "/api/search-services",
144
+ "/api/system",
145
+ "/api/skills",
146
+ "/api/data",
147
+ ];
148
+ export function deviceLimits() {
149
+ return async (c, next) => {
150
+ if (!c.env?.device)
151
+ return next();
152
+ const { method, path } = c.req;
153
+ const write = method !== "GET" && method !== "HEAD";
154
+ const self = path === `/api/devices/${c.env.device}`;
155
+ if ((path.startsWith("/api/providers") && write) ||
156
+ // Reading them too: a server's command line is this computer's business.
157
+ COMPUTER_ONLY.some((prefix) => path === prefix || path.startsWith(`${prefix}/`)) ||
158
+ path === "/api/devices/pairing" ||
159
+ // A phone changes or removes only itself, never another phone.
160
+ (path.startsWith("/api/devices/") && write && !self) ||
161
+ // Artifacts are looked at on the phone and managed on the Mac.
162
+ (path.startsWith("/api/artifacts/") && write) ||
163
+ path.startsWith("/api/auth/")) {
164
+ return problemResponse(c, 403, "mac-only", titleFor(403), "Only Yew on the Mac can do this: API keys, devices and remote access stay there.");
165
+ }
166
+ await next();
167
+ };
168
+ }
@@ -0,0 +1,53 @@
1
+ import { Hono } from "hono";
2
+ import { invalid, notFound } from "../errors.js";
3
+ import { revealKind, showInFileManager } from "../reveal.js";
4
+ import { readSettings } from "../settings.js";
5
+ import { listSkills } from "../skills.js";
6
+ import { optBoolean, readJson, reqString } from "./input.js";
7
+ /**
8
+ * Skills in the settings (blueprint 6.10, item 35): list what was read and what could not be, switch
9
+ * one off or on, show one's folder in the file manager. Computer-only: these are this computer's
10
+ * folders. Nothing here changes a skill's files.
11
+ */
12
+ export function skillRoutes(store, options) {
13
+ const app = new Hono();
14
+ const platform = options.platform ?? process.platform;
15
+ const listing = () => {
16
+ const settings = readSettings(store);
17
+ return listSkills(settings.workspaces, options.home, options.userHome, settings.disabledSkills);
18
+ };
19
+ // Only a folder in the list is ever acted on: the request names one, it never supplies a path.
20
+ const listed = (id) => {
21
+ const entry = listing().items.find((item) => item.id === id);
22
+ if (!entry)
23
+ throw notFound("skill", id);
24
+ return entry;
25
+ };
26
+ app.get("/skills", (c) => c.json({
27
+ ...listing(),
28
+ reveal: revealKind(platform),
29
+ nextCursor: null,
30
+ }));
31
+ app.patch("/skills", async (c) => {
32
+ const fields = await readJson(c);
33
+ const id = reqString(fields, "id", 4096);
34
+ const disabled = optBoolean(fields, "disabled");
35
+ if (disabled === undefined)
36
+ throw invalid("disabled is required.", "disabled");
37
+ const entry = listed(id);
38
+ // A folder that could not be read has nothing to switch.
39
+ if (entry.problem)
40
+ throw notFound("skill", id);
41
+ const others = readSettings(store).disabledSkills.filter((item) => item !== id);
42
+ store.setSetting("disabledSkills", disabled ? [...others, id] : others);
43
+ return c.json({ ...entry, disabled });
44
+ });
45
+ app.post("/skills/reveal", async (c) => {
46
+ const fields = await readJson(c);
47
+ const entry = listed(reqString(fields, "id", 4096));
48
+ // Finder opens the folder that holds the skill, with the skill's folder selected.
49
+ await showInFileManager(entry.dir, { platform, run: options.run, field: "id" });
50
+ return c.body(null, 204);
51
+ });
52
+ return app;
53
+ }
@@ -0,0 +1,26 @@
1
+ import { Hono } from "hono";
2
+ import { conflict } from "../errors.js";
3
+ import { optBoolean, readJson } from "./input.js";
4
+ /** Computer-only: these change what this computer starts. */
5
+ export function systemRoutes(system) {
6
+ const app = new Hono();
7
+ app.get("/system", (c) => c.json(system.status()));
8
+ app.patch("/system", async (c) => {
9
+ const fields = await readJson(c);
10
+ const startAtLogin = optBoolean(fields, "startAtLogin");
11
+ const launcher = optBoolean(fields, "launcher");
12
+ const status = system.status();
13
+ if (startAtLogin !== undefined && !status.startAtLogin.supported) {
14
+ throw conflict("Starting at login works on macOS and Linux.", { field: "startAtLogin" }, "not-on-this-system");
15
+ }
16
+ if (launcher !== undefined && !status.launcher.supported) {
17
+ throw conflict("The launcher icon works on macOS.", { field: "launcher" }, "not-on-this-system");
18
+ }
19
+ if (startAtLogin !== undefined)
20
+ system.setStartAtLogin(startAtLogin);
21
+ if (launcher !== undefined)
22
+ system.setLauncher(launcher);
23
+ return c.json(system.status());
24
+ });
25
+ return app;
26
+ }
@@ -0,0 +1,30 @@
1
+ import { randomBytes } from "node:crypto";
2
+ let lastMs = 0;
3
+ let counter = 0;
4
+ /**
5
+ * UUIDv7 (RFC 9562). Ids from one process sort by creation order, which keyset pagination relies on:
6
+ * within the same millisecond a 12-bit counter in `rand_a` keeps them increasing.
7
+ */
8
+ export function newId() {
9
+ const bytes = randomBytes(16);
10
+ let ms = Date.now();
11
+ if (ms > lastMs) {
12
+ lastMs = ms;
13
+ counter = bytes.readUInt16BE(6) & 0x7ff;
14
+ }
15
+ else {
16
+ ms = lastMs;
17
+ counter++;
18
+ if (counter > 0xfff) {
19
+ lastMs++;
20
+ ms = lastMs;
21
+ counter = 0;
22
+ }
23
+ }
24
+ bytes.writeUIntBE(ms, 0, 6);
25
+ bytes[6] = 0x70 | (counter >> 8);
26
+ bytes[7] = counter & 0xff;
27
+ bytes[8] = ((bytes[8] ?? 0) & 0x3f) | 0x80;
28
+ const h = bytes.toString("hex");
29
+ return `${h.slice(0, 8)}-${h.slice(8, 12)}-${h.slice(12, 16)}-${h.slice(16, 20)}-${h.slice(20)}`;
30
+ }
@@ -0,0 +1,70 @@
1
+ import { AsyncEntry } from "@napi-rs/keyring";
2
+ import { fromJigEnv, JIG_KEYCHAIN_SERVICE } from "./from-jig.js";
3
+ export const KEYCHAIN_SERVICE = "cn.tenonai.yew";
4
+ /** Where Jig, Yew's earlier name, kept them; a key found there moves over when first read. */
5
+ const JIG_SERVICE = JIG_KEYCHAIN_SERVICE;
6
+ /** The operating system keychain (macOS Keychain, Windows Credential Manager, Secret Service). */
7
+ export class KeychainStore {
8
+ #prefix;
9
+ /** `prefix` keeps different kinds apart: "provider" for API keys, "remote" for the relay keys. */
10
+ constructor(prefix = "provider") {
11
+ this.#prefix = prefix;
12
+ }
13
+ #entry(name, service = KEYCHAIN_SERVICE) {
14
+ return new AsyncEntry(service, `${this.#prefix}:${name}`);
15
+ }
16
+ async get(provider) {
17
+ const key = await this.#entry(provider).getPassword();
18
+ if (key !== null && key !== undefined)
19
+ return key;
20
+ const old = this.#entry(provider, JIG_SERVICE);
21
+ const kept = await old.getPassword().catch(() => null);
22
+ if (kept === null || kept === undefined)
23
+ return null;
24
+ await this.#entry(provider).setPassword(kept);
25
+ await old.deleteCredential().catch(() => false);
26
+ return kept;
27
+ }
28
+ async set(provider, key) {
29
+ await this.#entry(provider).setPassword(key);
30
+ await this.#entry(provider, JIG_SERVICE)
31
+ .deleteCredential()
32
+ .catch(() => false);
33
+ }
34
+ async delete(provider) {
35
+ const had = await this.#entry(provider)
36
+ .deleteCredential()
37
+ .catch(() => false);
38
+ const hadOld = await this.#entry(provider, JIG_SERVICE)
39
+ .deleteCredential()
40
+ .catch(() => false);
41
+ return had || hadOld;
42
+ }
43
+ }
44
+ /**
45
+ * The key store Yew runs with: the system keychain, or one in memory when `YEW_KEYCHAIN=off`.
46
+ * The keychain is shared by every data folder on this computer, so a Yew started on a scratch
47
+ * `YEW_HOME` to try something out would otherwise hold the real API keys and could call a model
48
+ * with them. With the switch off it starts with no keys and forgets what is saved when it stops.
49
+ */
50
+ export function systemKeys(prefix = "provider", env = process.env) {
51
+ const off = fromJigEnv(env, "KEYCHAIN") === "off";
52
+ return off ? new MemoryKeyStore() : new KeychainStore(prefix);
53
+ }
54
+ /** For tests: keeps keys in memory. */
55
+ export class MemoryKeyStore {
56
+ #keys = new Map();
57
+ constructor(initial = {}) {
58
+ for (const [provider, key] of Object.entries(initial))
59
+ this.#keys.set(provider, key);
60
+ }
61
+ async get(provider) {
62
+ return this.#keys.get(provider) ?? null;
63
+ }
64
+ async set(provider, key) {
65
+ this.#keys.set(provider, key);
66
+ }
67
+ async delete(provider) {
68
+ return this.#keys.delete(provider);
69
+ }
70
+ }