@tangle-network/agent-app 0.45.21 → 0.45.23
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/dist/DesignCanvas-ZG7DJS7C.js +10 -0
- package/dist/DesignCanvasEditor-SLFMHOII.js +13 -0
- package/dist/app-auth/index.js +2 -2
- package/dist/assistant/index.d.ts +1 -1
- package/dist/assistant/index.js +5 -5
- package/dist/{attachment-validation-CsmUzuI3.d.ts → attachment-validation-BfJDBU1g.d.ts} +41 -5
- package/dist/{auth-DJjJBtYw.d.ts → auth-BYtiazA4.d.ts} +1 -1
- package/dist/chat-react/index.js +2 -2
- package/dist/chat-routes/index.d.ts +8 -4
- package/dist/chat-routes/index.js +21 -4
- package/dist/chat-routes/index.js.map +1 -1
- package/dist/{chunk-KPRBFNGT.js → chunk-3IHYJIDJ.js} +3 -3
- package/dist/{chunk-MYS7DHMM.js → chunk-4QVG4WJQ.js} +2 -2
- package/dist/{chunk-RMHZKMQ4.js → chunk-73CQJOIU.js} +5 -5
- package/dist/{chunk-AH3IOSWF.js → chunk-7PFFFRVU.js} +2077 -341
- package/dist/chunk-7PFFFRVU.js.map +1 -0
- package/dist/chunk-CCVG2TL6.js +327 -0
- package/dist/chunk-CCVG2TL6.js.map +1 -0
- package/dist/{chunk-U4BXAZCN.js → chunk-DRB77FYL.js} +2 -2
- package/dist/{chunk-6MUJROBT.js → chunk-E4DHYENH.js} +2 -2
- package/dist/chunk-F7VH4G5C.js +283 -0
- package/dist/chunk-F7VH4G5C.js.map +1 -0
- package/dist/chunk-I24YIKHO.js +183 -0
- package/dist/chunk-I24YIKHO.js.map +1 -0
- package/dist/{chunk-OO4DROKM.js → chunk-OASVAPRL.js} +3 -3
- package/dist/{chunk-ZSGTG6PK.js → chunk-P5PIAQVS.js} +2 -2
- package/dist/chunk-PC2WYTK7.js +405 -0
- package/dist/chunk-PC2WYTK7.js.map +1 -0
- package/dist/{chunk-YEFFHORB.js → chunk-TX6S7XXU.js} +8 -2
- package/dist/chunk-TX6S7XXU.js.map +1 -0
- package/dist/chunk-UGWQLQDS.js +35 -0
- package/dist/chunk-UGWQLQDS.js.map +1 -0
- package/dist/{chunk-O22STZ3P.js → chunk-X5DQ5QOP.js} +2 -2
- package/dist/chunk-XEA5EG6P.js +1478 -0
- package/dist/chunk-XEA5EG6P.js.map +1 -0
- package/dist/{chunk-PCJHEZA7.js → chunk-YABHE2QY.js} +2 -2
- package/dist/design-canvas/index.d.ts +3 -3
- package/dist/design-canvas/index.js +2 -2
- package/dist/design-canvas-react/engine.js +4 -4
- package/dist/design-canvas-react/index.js +7 -7
- package/dist/design-canvas-react/lazy.js +1 -1
- package/dist/documents/index.d.ts +233 -0
- package/dist/documents/index.js +495 -0
- package/dist/documents/index.js.map +1 -0
- package/dist/documents/pdf-inspector.d.ts +60 -0
- package/dist/documents/pdf-inspector.js +100 -0
- package/dist/documents/pdf-inspector.js.map +1 -0
- package/dist/eval/index.d.ts +1 -1
- package/dist/fold-DACU7gtf.d.ts +320 -0
- package/dist/legibility/cli.d.ts +1 -0
- package/dist/legibility/cli.js +143 -0
- package/dist/legibility/cli.js.map +1 -0
- package/dist/legibility/index.d.ts +572 -0
- package/dist/legibility/index.js +33 -0
- package/dist/legibility/index.js.map +1 -0
- package/dist/{mcp-BiKqnsJV.d.ts → mcp-xxoZZfor.d.ts} +2 -2
- package/dist/openui/index.d.ts +208 -0
- package/dist/openui/index.js +350 -0
- package/dist/openui/index.js.map +1 -0
- package/dist/openui-react/index.d.ts +119 -0
- package/dist/openui-react/index.js +149 -0
- package/dist/openui-react/index.js.map +1 -0
- package/dist/platform/index.js +2 -2
- package/dist/preset-cloudflare/index.d.ts +2 -2
- package/dist/rate-limit-BOVmJRXZ.d.ts +35 -0
- package/dist/record/drizzle.d.ts +682 -0
- package/dist/record/drizzle.js +579 -0
- package/dist/record/drizzle.js.map +1 -0
- package/dist/record/index.d.ts +16 -0
- package/dist/record/index.js +35 -0
- package/dist/record/index.js.map +1 -0
- package/dist/runtime/index.d.ts +3 -3
- package/dist/sandbox/index.d.ts +2 -2
- package/dist/sandbox/index.js +3 -2
- package/dist/sequences/index.d.ts +3 -3
- package/dist/sequences/index.js +1 -1
- package/dist/session-shell/index.d.ts +173 -1
- package/dist/session-shell/index.js +13 -1
- package/dist/teams/index.js +9 -9
- package/dist/teams/invitations-api.js +3 -3
- package/dist/tools/index.d.ts +5 -5
- package/dist/tools/index.js +3 -2
- package/dist/{types-DbU-oO5h.d.ts → types-B25Mib1r.d.ts} +11 -0
- package/dist/types-DrBidf3O.d.ts +123 -0
- package/dist/values-C7RidJuI.d.ts +156 -0
- package/dist/web/index.d.ts +197 -31
- package/dist/web/index.js +15 -3
- package/dist/web-react/async/index.d.ts +309 -0
- package/dist/web-react/async/index.js +327 -0
- package/dist/web-react/async/index.js.map +1 -0
- package/dist/web-react/index.d.ts +586 -2
- package/dist/web-react/index.js +84 -6
- package/dist/work-product/index.d.ts +1 -1
- package/dist/work-product/index.js +2 -1
- package/dist/work-product/index.js.map +1 -1
- package/dist/workspace-react/index.js +1 -1
- package/package.json +49 -3
- package/dist/DesignCanvas-NEIW3AER.js +0 -10
- package/dist/DesignCanvasEditor-QD33OI2W.js +0 -13
- package/dist/chunk-AH3IOSWF.js.map +0 -1
- package/dist/chunk-GINKOZFD.js +0 -214
- package/dist/chunk-GINKOZFD.js.map +0 -1
- package/dist/chunk-J25RST7G.js +0 -126
- package/dist/chunk-J25RST7G.js.map +0 -1
- package/dist/chunk-WBHPN5DY.js +0 -158
- package/dist/chunk-WBHPN5DY.js.map +0 -1
- package/dist/chunk-YEFFHORB.js.map +0 -1
- /package/dist/{DesignCanvas-NEIW3AER.js.map → DesignCanvas-ZG7DJS7C.js.map} +0 -0
- /package/dist/{DesignCanvasEditor-QD33OI2W.js.map → DesignCanvasEditor-SLFMHOII.js.map} +0 -0
- /package/dist/{chunk-KPRBFNGT.js.map → chunk-3IHYJIDJ.js.map} +0 -0
- /package/dist/{chunk-MYS7DHMM.js.map → chunk-4QVG4WJQ.js.map} +0 -0
- /package/dist/{chunk-RMHZKMQ4.js.map → chunk-73CQJOIU.js.map} +0 -0
- /package/dist/{chunk-U4BXAZCN.js.map → chunk-DRB77FYL.js.map} +0 -0
- /package/dist/{chunk-6MUJROBT.js.map → chunk-E4DHYENH.js.map} +0 -0
- /package/dist/{chunk-OO4DROKM.js.map → chunk-OASVAPRL.js.map} +0 -0
- /package/dist/{chunk-ZSGTG6PK.js.map → chunk-P5PIAQVS.js.map} +0 -0
- /package/dist/{chunk-O22STZ3P.js.map → chunk-X5DQ5QOP.js.map} +0 -0
- /package/dist/{chunk-PCJHEZA7.js.map → chunk-YABHE2QY.js.map} +0 -0
package/dist/chunk-GINKOZFD.js
DELETED
|
@@ -1,214 +0,0 @@
|
|
|
1
|
-
// src/session-shell/index.ts
|
|
2
|
-
var UNTITLED_SESSION_LABEL = "Untitled chat";
|
|
3
|
-
function sessionLabel(session, untitled = UNTITLED_SESSION_LABEL) {
|
|
4
|
-
return session.title?.trim() || untitled;
|
|
5
|
-
}
|
|
6
|
-
function buildSessionSubItems({
|
|
7
|
-
sessions,
|
|
8
|
-
hrefForSession,
|
|
9
|
-
respondingSessionIds,
|
|
10
|
-
actions,
|
|
11
|
-
untitledLabel = UNTITLED_SESSION_LABEL,
|
|
12
|
-
prefetch = "intent",
|
|
13
|
-
overflow
|
|
14
|
-
}) {
|
|
15
|
-
const rowActions = (session) => {
|
|
16
|
-
if (!actions?.canEdit) return void 0;
|
|
17
|
-
const built = [];
|
|
18
|
-
const { onRename, onDelete, extraActions } = actions;
|
|
19
|
-
if (onRename) {
|
|
20
|
-
built.push({
|
|
21
|
-
id: "rename",
|
|
22
|
-
label: actions.renameLabel ?? "Rename",
|
|
23
|
-
icon: actions.renameIcon,
|
|
24
|
-
onSelect: () => onRename(session)
|
|
25
|
-
});
|
|
26
|
-
}
|
|
27
|
-
if (extraActions) built.push(...extraActions(session));
|
|
28
|
-
if (onDelete) {
|
|
29
|
-
built.push({
|
|
30
|
-
id: "delete",
|
|
31
|
-
label: actions.deleteLabel ?? "Delete",
|
|
32
|
-
icon: actions.deleteIcon,
|
|
33
|
-
destructive: true,
|
|
34
|
-
onSelect: () => onDelete(session)
|
|
35
|
-
});
|
|
36
|
-
}
|
|
37
|
-
return built.length ? built : void 0;
|
|
38
|
-
};
|
|
39
|
-
const rows = sessions.map((session) => ({
|
|
40
|
-
id: session.id,
|
|
41
|
-
label: sessionLabel(session, untitledLabel),
|
|
42
|
-
href: hrefForSession(session.id),
|
|
43
|
-
prefetch,
|
|
44
|
-
isLoading: respondingSessionIds?.has(session.id) ?? false,
|
|
45
|
-
unread: Boolean(session.unread),
|
|
46
|
-
actions: rowActions(session)
|
|
47
|
-
}));
|
|
48
|
-
if (!overflow) return rows;
|
|
49
|
-
return [
|
|
50
|
-
...rows,
|
|
51
|
-
{
|
|
52
|
-
id: "view-all",
|
|
53
|
-
label: overflow.label ?? "View all chats",
|
|
54
|
-
href: overflow.href,
|
|
55
|
-
prefetch,
|
|
56
|
-
emphasis: true
|
|
57
|
-
}
|
|
58
|
-
];
|
|
59
|
-
}
|
|
60
|
-
function buildSessionNavItem({
|
|
61
|
-
id = "history",
|
|
62
|
-
label = "History",
|
|
63
|
-
icon,
|
|
64
|
-
href,
|
|
65
|
-
activeSessionId,
|
|
66
|
-
emptyLabel = "No chats yet",
|
|
67
|
-
defaultOpen = true,
|
|
68
|
-
...subItemOptions
|
|
69
|
-
}) {
|
|
70
|
-
return {
|
|
71
|
-
id,
|
|
72
|
-
icon,
|
|
73
|
-
label,
|
|
74
|
-
href,
|
|
75
|
-
expandable: true,
|
|
76
|
-
defaultOpen,
|
|
77
|
-
subItems: buildSessionSubItems(subItemOptions),
|
|
78
|
-
subActiveIds: activeSessionId ? [activeSessionId] : void 0,
|
|
79
|
-
emptyLabel,
|
|
80
|
-
prefetch: subItemOptions.prefetch ?? "intent"
|
|
81
|
-
};
|
|
82
|
-
}
|
|
83
|
-
function stripTrailingSlashes(value) {
|
|
84
|
-
return value.replace(/\/+$/, "");
|
|
85
|
-
}
|
|
86
|
-
function stripSlashes(value) {
|
|
87
|
-
return value.replace(/^\/+|\/+$/g, "");
|
|
88
|
-
}
|
|
89
|
-
function normalizePath(pathname) {
|
|
90
|
-
const withoutHash = pathname.split("#")[0] ?? "";
|
|
91
|
-
const withoutQuery = withoutHash.split("?")[0] ?? "";
|
|
92
|
-
return stripTrailingSlashes(withoutQuery);
|
|
93
|
-
}
|
|
94
|
-
function isUnderPrefix(path, prefix) {
|
|
95
|
-
const p = stripTrailingSlashes(prefix);
|
|
96
|
-
if (p === "") return true;
|
|
97
|
-
return path === p || path.startsWith(`${p}/`);
|
|
98
|
-
}
|
|
99
|
-
function activeSessionIdFromPath({
|
|
100
|
-
pathname,
|
|
101
|
-
base,
|
|
102
|
-
segment = "chat",
|
|
103
|
-
newSegment = "new",
|
|
104
|
-
reserved
|
|
105
|
-
}) {
|
|
106
|
-
const path = normalizePath(pathname);
|
|
107
|
-
const root = stripTrailingSlashes(base);
|
|
108
|
-
const prefix = segment ? `${root}/${segment}` : root;
|
|
109
|
-
if (!isUnderPrefix(path, prefix) || path === prefix) return null;
|
|
110
|
-
const id = path.slice(prefix.length + 1).split("/")[0] ?? "";
|
|
111
|
-
if (!id || id === newSegment) return null;
|
|
112
|
-
if (reserved?.some((name) => stripSlashes(name) === id)) return null;
|
|
113
|
-
return decodeURIComponent(id);
|
|
114
|
-
}
|
|
115
|
-
function resolveActiveNavId({
|
|
116
|
-
pathname,
|
|
117
|
-
base,
|
|
118
|
-
routes,
|
|
119
|
-
aliases,
|
|
120
|
-
claimsNothing
|
|
121
|
-
}) {
|
|
122
|
-
const path = normalizePath(pathname);
|
|
123
|
-
const root = stripTrailingSlashes(base);
|
|
124
|
-
let bestLength = -1;
|
|
125
|
-
let bestId;
|
|
126
|
-
const consider = (relative, id, winsTies = false) => {
|
|
127
|
-
const full = stripTrailingSlashes(`${root}${relative}`);
|
|
128
|
-
if (!isUnderPrefix(path, full)) return;
|
|
129
|
-
if (full.length > bestLength || winsTies && full.length === bestLength) {
|
|
130
|
-
bestLength = full.length;
|
|
131
|
-
bestId = id;
|
|
132
|
-
}
|
|
133
|
-
};
|
|
134
|
-
for (const route of routes) consider(route.path, route.id);
|
|
135
|
-
for (const [prefix, id] of Object.entries(aliases ?? {})) consider(prefix, id);
|
|
136
|
-
for (const prefix of claimsNothing ?? []) consider(prefix, void 0, true);
|
|
137
|
-
return bestId;
|
|
138
|
-
}
|
|
139
|
-
function resolveSessionUnread({
|
|
140
|
-
sessionId,
|
|
141
|
-
loaderUnread,
|
|
142
|
-
liveUnreadIds,
|
|
143
|
-
locallyReadIds,
|
|
144
|
-
currentSessionId
|
|
145
|
-
}) {
|
|
146
|
-
if (sessionId === currentSessionId) return false;
|
|
147
|
-
if (liveUnreadIds?.has(sessionId)) return true;
|
|
148
|
-
if (locallyReadIds?.has(sessionId)) return false;
|
|
149
|
-
return loaderUnread;
|
|
150
|
-
}
|
|
151
|
-
function composeSidebarSessions({
|
|
152
|
-
loaderSessions,
|
|
153
|
-
optimisticSessions = [],
|
|
154
|
-
limit,
|
|
155
|
-
totalCount,
|
|
156
|
-
liveUnreadIds,
|
|
157
|
-
locallyReadIds,
|
|
158
|
-
currentSessionId
|
|
159
|
-
}) {
|
|
160
|
-
const loaderIds = new Set(loaderSessions.map((session) => session.id));
|
|
161
|
-
const pendingNew = optimisticSessions.filter((session) => !loaderIds.has(session.id));
|
|
162
|
-
const merged = [...pendingNew, ...loaderSessions];
|
|
163
|
-
const sessions = merged.slice(0, Math.max(0, limit)).map((session) => ({
|
|
164
|
-
...session,
|
|
165
|
-
unread: resolveSessionUnread({
|
|
166
|
-
sessionId: session.id,
|
|
167
|
-
loaderUnread: Boolean(session.unread),
|
|
168
|
-
liveUnreadIds,
|
|
169
|
-
locallyReadIds,
|
|
170
|
-
currentSessionId
|
|
171
|
-
})
|
|
172
|
-
}));
|
|
173
|
-
const known = (totalCount ?? loaderSessions.length) + pendingNew.length;
|
|
174
|
-
return { sessions, hasMore: known > sessions.length };
|
|
175
|
-
}
|
|
176
|
-
function mergeSessionPages(existing, incoming) {
|
|
177
|
-
const seen = new Set(existing.map((session) => session.id));
|
|
178
|
-
return [...existing, ...incoming.filter((session) => !seen.has(session.id))];
|
|
179
|
-
}
|
|
180
|
-
var DEFAULT_RAIL_COOKIE_NAME = "agent-sidebar-rail-collapsed";
|
|
181
|
-
function readRailCollapsedCookie(cookieHeader, name = DEFAULT_RAIL_COOKIE_NAME) {
|
|
182
|
-
for (const pair of (cookieHeader ?? "").split(";")) {
|
|
183
|
-
const eq = pair.indexOf("=");
|
|
184
|
-
if (eq === -1) continue;
|
|
185
|
-
if (pair.slice(0, eq).trim() !== name) continue;
|
|
186
|
-
return pair.slice(eq + 1).trim() === "1";
|
|
187
|
-
}
|
|
188
|
-
return false;
|
|
189
|
-
}
|
|
190
|
-
function railCollapsedCookie(collapsed, { name = DEFAULT_RAIL_COOKIE_NAME, maxAge = 31536e3, path = "/", secure } = {}) {
|
|
191
|
-
const isSecure = secure ?? (typeof location !== "undefined" && location.protocol === "https:");
|
|
192
|
-
return `${name}=${collapsed ? "1" : "0"}; path=${path}; max-age=${maxAge}; samesite=lax${isSecure ? "; secure" : ""}`;
|
|
193
|
-
}
|
|
194
|
-
function writeRailCollapsedCookie(collapsed, options = {}) {
|
|
195
|
-
if (typeof document === "undefined") return;
|
|
196
|
-
document.cookie = railCollapsedCookie(collapsed, options);
|
|
197
|
-
}
|
|
198
|
-
|
|
199
|
-
export {
|
|
200
|
-
UNTITLED_SESSION_LABEL,
|
|
201
|
-
sessionLabel,
|
|
202
|
-
buildSessionSubItems,
|
|
203
|
-
buildSessionNavItem,
|
|
204
|
-
activeSessionIdFromPath,
|
|
205
|
-
resolveActiveNavId,
|
|
206
|
-
resolveSessionUnread,
|
|
207
|
-
composeSidebarSessions,
|
|
208
|
-
mergeSessionPages,
|
|
209
|
-
DEFAULT_RAIL_COOKIE_NAME,
|
|
210
|
-
readRailCollapsedCookie,
|
|
211
|
-
railCollapsedCookie,
|
|
212
|
-
writeRailCollapsedCookie
|
|
213
|
-
};
|
|
214
|
-
//# sourceMappingURL=chunk-GINKOZFD.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/session-shell/index.ts"],"sourcesContent":["/**\n * Session shell — the app-shell mechanism every agent product needs around the\n * chat surface: a list of past sessions in the rail, an entry point for a new\n * one, and a paged history view behind it.\n *\n * `/web-react` already owns the chat SURFACE (composer, transcript, cards); it\n * owned no session SHELL, so all four products hand-rolled one and drifted.\n * This module is the shell's pure half: no React, no DOM, no peer imports, so a\n * server loader can call `readRailCollapsedCookie` without dragging React into\n * a worker bundle (`/web-react` holds the rendered half).\n *\n * Domain stays a parameter. A \"session\" here is only an id, a title and a\n * timestamp — a gtm thread, a tax session and a legal matter are all the same\n * shape to the shell, and the product supplies routing through `hrefForSession`\n * rather than the shell knowing any URL.\n */\n\n/** One session as the shell needs to see it. Products map their own row\n * (thread / session / matter) onto this before handing it over. */\nexport interface SessionSummary {\n id: string\n /** `null`/empty renders as the untitled placeholder rather than a blank row. */\n title: string | null\n /** ISO-8601. `null` when the product has no timestamp to show. */\n updatedAt: string | null\n isPinned?: boolean\n /** Unread for the viewer. Use `resolveSessionUnread` to fold live overlays in. */\n unread?: boolean\n /** Free-form product label (gtm categories, legal matter types). Passed\n * through untouched — the shell never interprets it. */\n category?: string | null\n}\n\n/** One fetched page of sessions with an optional continuation cursor. */\nexport interface SessionPage {\n items: SessionSummary[]\n /** Opaque continuation token; absent/null ⇒ no further pages. */\n nextCursor?: string | null\n}\n\n/** Sort order for the history view. The product's fetcher decides what these\n * mean against its own storage; the shell only round-trips the value. */\nexport type SessionSort = 'newest' | 'oldest'\n\n// ---------------------------------------------------------------------------\n// Rail items — structurally assignable to sandbox-ui's SidebarLayout types\n// ---------------------------------------------------------------------------\n\n/**\n * These mirror `@tangle-network/sandbox-ui/dashboard`'s `SidebarLayoutNavItem`\n * / `RailExpandableSubItem` STRUCTURALLY rather than importing them, so this\n * module stays free of the optional peer (invariant 3 — structural over\n * hard-dep when the surface is small). `tests/session-shell/rail-contract.test.ts`\n * assigns the builder output to the real sandbox-ui types, so a drift in either\n * direction fails CI instead of silently dropping a field at runtime.\n *\n * `TIcon` is the product's icon component type (lucide, custom, anything) —\n * generic so this file needs no React types.\n */\nexport interface SessionRailAction<TIcon = unknown> {\n id: string\n label: string\n icon?: TIcon\n destructive?: boolean\n onSelect: () => void\n}\n\nexport type RailPrefetch = 'none' | 'intent' | 'render' | 'viewport'\n\nexport interface SessionRailSubItem<TIcon = unknown> {\n id: string\n label: string\n href: string\n prefetch?: RailPrefetch\n /** Live working indicator — the session is mid-turn. */\n isLoading?: boolean\n /** Bold + leading dot. sandbox-ui suppresses it while `isLoading`. */\n unread?: boolean\n /** Emphasised row, used for the trailing \"view all\" overflow link. */\n emphasis?: boolean\n actions?: SessionRailAction<TIcon>[]\n}\n\nexport interface SessionRailNavItem<TIcon = unknown> {\n id: string\n /** REQUIRED, mirroring sandbox-ui — the rail renders `<Icon />` unguarded, so\n * an omitted icon is a blank/crashing row rather than a styling nit. */\n icon: TIcon\n label: string\n href: string\n badge?: number\n expandable?: boolean\n defaultOpen?: boolean\n subItems?: SessionRailSubItem<TIcon>[]\n subActiveIds?: string[]\n emptyLabel?: string\n prefetch?: RailPrefetch\n}\n\n/** Per-row rename/delete wiring. Supplied by the layout that owns the dialogs;\n * omitted (or `canEdit: false`) leaves rows read-only. */\nexport interface SessionRowActions<TIcon = unknown> {\n canEdit: boolean\n renameIcon?: TIcon\n deleteIcon?: TIcon\n renameLabel?: string\n deleteLabel?: string\n /**\n * Omit when the product cannot rename a session — the row then offers delete\n * only, instead of a menu item that does nothing.\n *\n * Independently optional, matching `SessionHistoryPanel`, which has always\n * rendered whichever of the two it was given. The rail builder used to demand\n * both, so a product with archive-but-no-rename (tax) could either fake a\n * rename or ship no row actions at all.\n */\n onRename?: (session: SessionSummary) => void\n onDelete?: (session: SessionSummary) => void\n /**\n * Row actions this shell has no opinion about — pin, categorise, duplicate,\n * share. Evaluated per session so a label can read that row's state\n * (\"Pin\" vs \"Unpin\"), and ordered between rename and delete so the\n * destructive action stays last.\n *\n * `id` must not be `rename` or `delete`; those are the shell's own.\n */\n extraActions?: (session: SessionSummary) => SessionRailAction<TIcon>[]\n}\n\nexport const UNTITLED_SESSION_LABEL = 'Untitled chat'\n\n/** Display title for a session row — trims, and falls back rather than\n * rendering an empty row the user cannot aim at. */\nexport function sessionLabel(session: SessionSummary, untitled = UNTITLED_SESSION_LABEL): string {\n return session.title?.trim() || untitled\n}\n\nexport interface BuildSessionSubItemsOptions<TIcon = unknown> {\n sessions: SessionSummary[]\n /** The product's route for one session. The shell never builds a URL itself. */\n hrefForSession: (sessionId: string) => string\n /** Ids currently mid-turn — renders the working indicator. */\n respondingSessionIds?: ReadonlySet<string>\n actions?: SessionRowActions<TIcon>\n untitledLabel?: string\n prefetch?: RailPrefetch\n /** Trailing \"view all\" row, appended when the capped list hides sessions. */\n overflow?: { href: string; label?: string }\n}\n\n/** Session rows for the rail's expandable history item. */\nexport function buildSessionSubItems<TIcon = unknown>({\n sessions,\n hrefForSession,\n respondingSessionIds,\n actions,\n untitledLabel = UNTITLED_SESSION_LABEL,\n prefetch = 'intent',\n overflow,\n}: BuildSessionSubItemsOptions<TIcon>): SessionRailSubItem<TIcon>[] {\n /**\n * Only the handlers the product actually supplied. An empty result becomes\n * `undefined` rather than `[]`, because sandbox-ui renders the kebab trigger\n * whenever `actions` is an array — an empty one is a button that opens an\n * empty menu.\n */\n const rowActions = (session: SessionSummary): SessionRailAction<TIcon>[] | undefined => {\n if (!actions?.canEdit) return undefined\n const built: SessionRailAction<TIcon>[] = []\n const { onRename, onDelete, extraActions } = actions\n if (onRename) {\n built.push({\n id: 'rename',\n label: actions.renameLabel ?? 'Rename',\n icon: actions.renameIcon,\n onSelect: () => onRename(session),\n })\n }\n if (extraActions) built.push(...extraActions(session))\n if (onDelete) {\n built.push({\n id: 'delete',\n label: actions.deleteLabel ?? 'Delete',\n icon: actions.deleteIcon,\n destructive: true,\n onSelect: () => onDelete(session),\n })\n }\n return built.length ? built : undefined\n }\n\n const rows: SessionRailSubItem<TIcon>[] = sessions.map((session) => ({\n id: session.id,\n label: sessionLabel(session, untitledLabel),\n href: hrefForSession(session.id),\n prefetch,\n isLoading: respondingSessionIds?.has(session.id) ?? false,\n unread: Boolean(session.unread),\n actions: rowActions(session),\n }))\n if (!overflow) return rows\n return [\n ...rows,\n {\n id: 'view-all',\n label: overflow.label ?? 'View all chats',\n href: overflow.href,\n prefetch,\n emphasis: true,\n },\n ]\n}\n\nexport interface BuildSessionNavItemOptions<TIcon = unknown>\n extends BuildSessionSubItemsOptions<TIcon> {\n /** Nav id the product highlights against (`activeNavId === id`). */\n id?: string\n label?: string\n /** The product's icon component. Required — see `SessionRailNavItem.icon`. */\n icon: TIcon\n /** The expandable row's own destination — the full history page. */\n href: string\n /** Session currently open, highlighted inside the expandable. */\n activeSessionId?: string | null\n emptyLabel?: string\n defaultOpen?: boolean\n}\n\n/**\n * The rail's session entry: one expandable nav row whose sub-items are the\n * recent sessions. This is the structure the owner asked for — history lives IN\n * the rail, not in a second sidebar panel beside it.\n */\nexport function buildSessionNavItem<TIcon = unknown>({\n id = 'history',\n label = 'History',\n icon,\n href,\n activeSessionId,\n emptyLabel = 'No chats yet',\n defaultOpen = true,\n ...subItemOptions\n}: BuildSessionNavItemOptions<TIcon>): SessionRailNavItem<TIcon> {\n return {\n id,\n icon,\n label,\n href,\n expandable: true,\n defaultOpen,\n subItems: buildSessionSubItems<TIcon>(subItemOptions),\n subActiveIds: activeSessionId ? [activeSessionId] : undefined,\n emptyLabel,\n prefetch: subItemOptions.prefetch ?? 'intent',\n }\n}\n\n// ---------------------------------------------------------------------------\n// Routing / selection\n// ---------------------------------------------------------------------------\n\nfunction stripTrailingSlashes(value: string): string {\n return value.replace(/\\/+$/, '')\n}\n\n/** Bare segment name, so `reserved` accepts `'/settings'` or `'settings'`. */\nfunction stripSlashes(value: string): string {\n return value.replace(/^\\/+|\\/+$/g, '')\n}\n\n/** Path with query + fragment removed and trailing slashes trimmed. A caller\n * passing a full href instead of a pathname would otherwise match nothing. */\nfunction normalizePath(pathname: string): string {\n const withoutHash = pathname.split('#')[0] ?? ''\n const withoutQuery = withoutHash.split('?')[0] ?? ''\n return stripTrailingSlashes(withoutQuery)\n}\n\n/** True when `path` is `prefix` or a segment-aligned descendant of it, so\n * `/vault` never claims `/vault-archive`. */\nfunction isUnderPrefix(path: string, prefix: string): boolean {\n const p = stripTrailingSlashes(prefix)\n if (p === '') return true\n return path === p || path.startsWith(`${p}/`)\n}\n\nexport interface ActiveSessionIdOptions {\n pathname: string\n /** Workspace-scoped route base, e.g. `/app/ws_123`. */\n base: string\n /** Route segment sessions live under. Default `chat` ⇒ `${base}/chat/:id`.\n * Pass `''` when sessions sit DIRECTLY under the base (`/app/:sessionId`),\n * which is how one product routes them — then `reserved` is mandatory. */\n segment?: string\n /** Segment that means \"composing a new session\", not an id. Default `new`. */\n newSegment?: string\n /**\n * First segments that are OTHER routes, not session ids. Only meaningful\n * with `segment: ''`, where `/app/settings` is otherwise indistinguishable\n * from a session called `settings` — and resolving it as one would highlight\n * and prefetch a session that does not exist. Pass the product's own nav\n * paths; unknown-but-reserved is a routing bug, so this fails closed.\n */\n reserved?: readonly string[]\n}\n\n/**\n * The session id the current route has open, or `null` on the new-session\n * composer / anywhere else.\n *\n * Anchored at `base` on purpose. A bare `/\\/chat\\/([^/]+)/` scan — the shape\n * three products shipped — matches the FIRST `/chat/` anywhere in the path, so\n * a workspace or vault folder named `chat` resolves a neighbouring segment as a\n * session id and the rail highlights (and prefetches) a session the user is not\n * in. Same class as attaching to a stale box: it looks right and points at the\n * wrong row.\n */\nexport function activeSessionIdFromPath({\n pathname,\n base,\n segment = 'chat',\n newSegment = 'new',\n reserved,\n}: ActiveSessionIdOptions): string | null {\n const path = normalizePath(pathname)\n const root = stripTrailingSlashes(base)\n const prefix = segment ? `${root}/${segment}` : root\n if (!isUnderPrefix(path, prefix) || path === prefix) return null\n const id = path.slice(prefix.length + 1).split('/')[0] ?? ''\n if (!id || id === newSegment) return null\n // `/app/settings` under a segment-less route is a sibling page, not a\n // session named \"settings\".\n if (reserved?.some((name) => stripSlashes(name) === id)) return null\n return decodeURIComponent(id)\n}\n\n/** One rail destination. `path` is relative to the workspace base. */\nexport interface NavRouteDef {\n id: string\n path: string\n}\n\nexport interface ResolveActiveNavIdOptions {\n pathname: string\n base: string\n /** The product's rail rows, in any order — resolution is longest-prefix. */\n routes: NavRouteDef[]\n /** Extra prefixes that light an existing row: `{ '/agents': 'integrations' }`.\n * Participates in the same longest-prefix contest. */\n aliases?: Record<string, string>\n /** Prefixes that deliberately highlight NOTHING, beating any shorter match.\n * gtm uses this so an open chat lights no rail row while `/chat/new` still\n * lights \"New\". */\n claimsNothing?: string[]\n}\n\n/**\n * The rail row to highlight for the current route.\n *\n * Longest-prefix wins, so declaration order cannot change the answer. The\n * per-product versions this replaces were first-match over an array, which made\n * `/chat/new` vs `/chat` an ordering accident rather than a rule.\n */\nexport function resolveActiveNavId({\n pathname,\n base,\n routes,\n aliases,\n claimsNothing,\n}: ResolveActiveNavIdOptions): string | undefined {\n const path = normalizePath(pathname)\n const root = stripTrailingSlashes(base)\n let bestLength = -1\n let bestId: string | undefined\n const consider = (relative: string, id: string | undefined, winsTies = false) => {\n const full = stripTrailingSlashes(`${root}${relative}`)\n if (!isUnderPrefix(path, full)) return\n if (full.length > bestLength || (winsTies && full.length === bestLength)) {\n bestLength = full.length\n bestId = id\n }\n }\n for (const route of routes) consider(route.path, route.id)\n for (const [prefix, id] of Object.entries(aliases ?? {})) consider(prefix, id)\n // Declared last and wins an exact-length tie: naming a prefix in\n // `claimsNothing` is a deliberate override of the row that owns it, so\n // `claimsNothing: ['/chat']` beats a `{ id: 'chat', path: '/chat' }` row while\n // a longer `/chat/new` still wins on specificity.\n for (const prefix of claimsNothing ?? []) consider(prefix, undefined, true)\n return bestId\n}\n\n// ---------------------------------------------------------------------------\n// Sidebar list composition\n// ---------------------------------------------------------------------------\n\nexport interface ResolveSessionUnreadOptions {\n sessionId: string\n /** Server-computed unread from the route loader. */\n loaderUnread: boolean\n /** Live \"went unread\" ids from the workspace channel. */\n liveUnreadIds?: ReadonlySet<string>\n /** Ids this tab has already opened since the loader ran. */\n locallyReadIds?: ReadonlySet<string>\n /** The open session is never unread to its own viewer. */\n currentSessionId?: string | null\n}\n\n/**\n * Effective unread for one row. The loader's value can be stale — a layout\n * loader that survives same-workspace navigation keeps reporting a session as\n * unread after the user opened it — so live and local overlays win over it, and\n * the currently-open session always reads as read.\n */\nexport function resolveSessionUnread({\n sessionId,\n loaderUnread,\n liveUnreadIds,\n locallyReadIds,\n currentSessionId,\n}: ResolveSessionUnreadOptions): boolean {\n if (sessionId === currentSessionId) return false\n if (liveUnreadIds?.has(sessionId)) return true\n if (locallyReadIds?.has(sessionId)) return false\n return loaderUnread\n}\n\nexport interface ComposeSidebarSessionsOptions {\n /** Server-rendered rows, already ordered by the product's query. */\n loaderSessions: SessionSummary[]\n /** Optimistic rows from the live channel (a chat created in another tab). */\n optimisticSessions?: SessionSummary[]\n /** Rail cap. The full list lives on the history page. */\n limit: number\n /** Total sessions the product holds, used to decide the overflow row. */\n totalCount?: number\n liveUnreadIds?: ReadonlySet<string>\n locallyReadIds?: ReadonlySet<string>\n currentSessionId?: string | null\n}\n\nexport interface ComposedSidebarSessions {\n sessions: SessionSummary[]\n /** More sessions exist than the rail shows ⇒ render the \"view all\" row. */\n hasMore: boolean\n}\n\n/**\n * The rail's session list: optimistic rows first, then the loader's, capped,\n * with unread resolved per row.\n *\n * Optimistic rows are deduped against the loader by id — once a revalidation\n * brings a live-created session back from the server it must not appear twice\n * (duplicate React keys, and the row's actions would target the same session\n * from two places).\n */\nexport function composeSidebarSessions({\n loaderSessions,\n optimisticSessions = [],\n limit,\n totalCount,\n liveUnreadIds,\n locallyReadIds,\n currentSessionId,\n}: ComposeSidebarSessionsOptions): ComposedSidebarSessions {\n const loaderIds = new Set(loaderSessions.map((session) => session.id))\n const pendingNew = optimisticSessions.filter((session) => !loaderIds.has(session.id))\n const merged = [...pendingNew, ...loaderSessions]\n const sessions = merged.slice(0, Math.max(0, limit)).map((session) => ({\n ...session,\n unread: resolveSessionUnread({\n sessionId: session.id,\n loaderUnread: Boolean(session.unread),\n liveUnreadIds,\n locallyReadIds,\n currentSessionId,\n }),\n }))\n const known = (totalCount ?? loaderSessions.length) + pendingNew.length\n return { sessions, hasMore: known > sessions.length }\n}\n\n/**\n * Append a fetched page to held rows, dropping ids already shown. A session\n * bumped to the top between two page fetches otherwise arrives twice — once in\n * the page it moved out of and once in the page it moved into.\n */\nexport function mergeSessionPages(\n existing: SessionSummary[],\n incoming: SessionSummary[],\n): SessionSummary[] {\n const seen = new Set(existing.map((session) => session.id))\n return [...existing, ...incoming.filter((session) => !seen.has(session.id))]\n}\n\n// ---------------------------------------------------------------------------\n// Rail collapse cookie (SSR-seeded so the first paint matches the client)\n// ---------------------------------------------------------------------------\n\nexport const DEFAULT_RAIL_COOKIE_NAME = 'agent-sidebar-rail-collapsed'\n\n/**\n * Read the persisted rail-collapse state from a request's `Cookie` header, so\n * the server renders the rail in the state the user left it and the first\n * client render does not re-flow.\n *\n * Parses the header rather than building a `RegExp` from the cookie name (the\n * shape the products shipped): a name containing a regex metacharacter would\n * silently match the wrong cookie or none at all.\n */\nexport function readRailCollapsedCookie(\n cookieHeader: string | null | undefined,\n name: string = DEFAULT_RAIL_COOKIE_NAME,\n): boolean {\n for (const pair of (cookieHeader ?? '').split(';')) {\n const eq = pair.indexOf('=')\n if (eq === -1) continue\n if (pair.slice(0, eq).trim() !== name) continue\n return pair.slice(eq + 1).trim() === '1'\n }\n return false\n}\n\nexport interface RailCookieOptions {\n name?: string\n /** Seconds. Default one year. */\n maxAge?: number\n path?: string\n /** Omit to auto-detect: `secure` on https, off on http://localhost — a Secure\n * cookie is dropped there and the rail state would not persist in dev. */\n secure?: boolean\n}\n\n/** The cookie string for a collapse state. Usable as `document.cookie` or as a\n * `Set-Cookie` value. Exported separately so it is testable without a DOM. */\nexport function railCollapsedCookie(\n collapsed: boolean,\n { name = DEFAULT_RAIL_COOKIE_NAME, maxAge = 31_536_000, path = '/', secure }: RailCookieOptions = {},\n): string {\n const isSecure =\n secure ?? (typeof location !== 'undefined' && location.protocol === 'https:')\n return `${name}=${collapsed ? '1' : '0'}; path=${path}; max-age=${maxAge}; samesite=lax${isSecure ? '; secure' : ''}`\n}\n\n/** Persist the rail-collapse state from the browser. No-op without a document\n * so a shared toggle handler is safe to call during SSR. */\nexport function writeRailCollapsedCookie(collapsed: boolean, options: RailCookieOptions = {}): void {\n if (typeof document === 'undefined') return\n document.cookie = railCollapsedCookie(collapsed, options)\n}\n"],"mappings":";AAiIO,IAAM,yBAAyB;AAI/B,SAAS,aAAa,SAAyB,WAAW,wBAAgC;AAC/F,SAAO,QAAQ,OAAO,KAAK,KAAK;AAClC;AAgBO,SAAS,qBAAsC;AAAA,EACpD;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA,gBAAgB;AAAA,EAChB,WAAW;AAAA,EACX;AACF,GAAoE;AAOlE,QAAM,aAAa,CAAC,YAAoE;AACtF,QAAI,CAAC,SAAS,QAAS,QAAO;AAC9B,UAAM,QAAoC,CAAC;AAC3C,UAAM,EAAE,UAAU,UAAU,aAAa,IAAI;AAC7C,QAAI,UAAU;AACZ,YAAM,KAAK;AAAA,QACT,IAAI;AAAA,QACJ,OAAO,QAAQ,eAAe;AAAA,QAC9B,MAAM,QAAQ;AAAA,QACd,UAAU,MAAM,SAAS,OAAO;AAAA,MAClC,CAAC;AAAA,IACH;AACA,QAAI,aAAc,OAAM,KAAK,GAAG,aAAa,OAAO,CAAC;AACrD,QAAI,UAAU;AACZ,YAAM,KAAK;AAAA,QACT,IAAI;AAAA,QACJ,OAAO,QAAQ,eAAe;AAAA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SAAO,CAAC,GAAG,UAAU,GAAG,SAAS,OAAO,CAAC,YAAY,CAAC,KAAK,IAAI,QAAQ,EAAE,CAAC,CAAC;AAC7E;AAMO,IAAM,2BAA2B;AAWjC,SAAS,wBACd,cACA,OAAe,0BACN;AACT,aAAW,SAAS,gBAAgB,IAAI,MAAM,GAAG,GAAG;AAClD,UAAM,KAAK,KAAK,QAAQ,GAAG;AAC3B,QAAI,OAAO,GAAI;AACf,QAAI,KAAK,MAAM,GAAG,EAAE,EAAE,KAAK,MAAM,KAAM;AACvC,WAAO,KAAK,MAAM,KAAK,CAAC,EAAE,KAAK,MAAM;AAAA,EACvC;AACA,SAAO;AACT;AAcO,SAAS,oBACd,WACA,EAAE,OAAO,0BAA0B,SAAS,SAAY,OAAO,KAAK,OAAO,IAAuB,CAAC,GAC3F;AACR,QAAM,WACJ,WAAW,OAAO,aAAa,eAAe,SAAS,aAAa;AACtE,SAAO,GAAG,IAAI,IAAI,YAAY,MAAM,GAAG,UAAU,IAAI,aAAa,MAAM,iBAAiB,WAAW,aAAa,EAAE;AACrH;AAIO,SAAS,yBAAyB,WAAoB,UAA6B,CAAC,GAAS;AAClG,MAAI,OAAO,aAAa,YAAa;AACrC,WAAS,SAAS,oBAAoB,WAAW,OAAO;AAC1D;","names":[]}
|
package/dist/chunk-J25RST7G.js
DELETED
|
@@ -1,126 +0,0 @@
|
|
|
1
|
-
// src/web/index.ts
|
|
2
|
-
async function parseJsonObjectBody(request) {
|
|
3
|
-
let raw;
|
|
4
|
-
try {
|
|
5
|
-
raw = await request.json();
|
|
6
|
-
} catch {
|
|
7
|
-
return [null, Response.json({ error: "Invalid JSON body" }, { status: 400 })];
|
|
8
|
-
}
|
|
9
|
-
if (raw === null || typeof raw !== "object" || Array.isArray(raw)) {
|
|
10
|
-
return [null, Response.json({ error: "Body must be a JSON object" }, { status: 400 })];
|
|
11
|
-
}
|
|
12
|
-
return [raw, null];
|
|
13
|
-
}
|
|
14
|
-
function requireString(body, field) {
|
|
15
|
-
const v = body[field];
|
|
16
|
-
if (typeof v !== "string" || v.length === 0) {
|
|
17
|
-
return Response.json({ error: `Missing or non-string field: ${field}` }, { status: 400 });
|
|
18
|
-
}
|
|
19
|
-
return v;
|
|
20
|
-
}
|
|
21
|
-
function extractRequestContext(request) {
|
|
22
|
-
const ipAddress = request.headers.get("CF-Connecting-IP") ?? request.headers.get("X-Forwarded-For")?.split(",")[0]?.trim() ?? "0.0.0.0";
|
|
23
|
-
return {
|
|
24
|
-
ipAddress,
|
|
25
|
-
userAgent: request.headers.get("User-Agent") ?? "",
|
|
26
|
-
timestamp: (/* @__PURE__ */ new Date()).toISOString(),
|
|
27
|
-
requestId: crypto.randomUUID()
|
|
28
|
-
};
|
|
29
|
-
}
|
|
30
|
-
async function checkRateLimit(kv, key, limit, windowSeconds) {
|
|
31
|
-
const now = Math.floor(Date.now() / 1e3);
|
|
32
|
-
const windowStart = now - windowSeconds;
|
|
33
|
-
const kvKey = `rl:${key}`;
|
|
34
|
-
const raw = await kv.get(kvKey);
|
|
35
|
-
const parsed = parseRateLimitState(raw);
|
|
36
|
-
if (parsed === POISONED_STATE) {
|
|
37
|
-
return { allowed: false, remaining: 0, resetAt: now + windowSeconds };
|
|
38
|
-
}
|
|
39
|
-
const valid = parsed.filter((t) => t > windowStart);
|
|
40
|
-
if (valid.length >= limit) return { allowed: false, remaining: 0, resetAt: (valid[0] ?? now) + windowSeconds };
|
|
41
|
-
valid.push(now);
|
|
42
|
-
await kv.put(kvKey, JSON.stringify(valid), { expirationTtl: windowSeconds * 2 });
|
|
43
|
-
return { allowed: true, remaining: limit - valid.length, resetAt: now + windowSeconds };
|
|
44
|
-
}
|
|
45
|
-
var POISONED_STATE = /* @__PURE__ */ Symbol("rate-limit-poisoned-state");
|
|
46
|
-
function parseRateLimitState(raw) {
|
|
47
|
-
if (raw === null) return [];
|
|
48
|
-
let parsed;
|
|
49
|
-
try {
|
|
50
|
-
parsed = JSON.parse(raw);
|
|
51
|
-
} catch {
|
|
52
|
-
return POISONED_STATE;
|
|
53
|
-
}
|
|
54
|
-
if (!Array.isArray(parsed)) return POISONED_STATE;
|
|
55
|
-
return parsed.filter((t) => typeof t === "number" && Number.isFinite(t));
|
|
56
|
-
}
|
|
57
|
-
function serializeCookie(value, opts) {
|
|
58
|
-
if (opts.sameSite === "None" && !opts.secure) {
|
|
59
|
-
throw new Error("SameSite=None cookies require secure: true (browsers reject them otherwise)");
|
|
60
|
-
}
|
|
61
|
-
const parts = [`${opts.name}=${encodeURIComponent(value)}`, `Path=${opts.path ?? "/"}`];
|
|
62
|
-
if (opts.httpOnly !== false) parts.push("HttpOnly");
|
|
63
|
-
parts.push(`SameSite=${opts.sameSite ?? "Lax"}`);
|
|
64
|
-
if (opts.maxAgeSeconds !== void 0) parts.push(`Max-Age=${opts.maxAgeSeconds}`);
|
|
65
|
-
if (opts.secure) parts.push("Secure");
|
|
66
|
-
return parts.join("; ");
|
|
67
|
-
}
|
|
68
|
-
function clearCookieHeader(opts) {
|
|
69
|
-
return serializeCookie("", { ...opts, maxAgeSeconds: 0 });
|
|
70
|
-
}
|
|
71
|
-
function readCookieValue(cookieHeader, name) {
|
|
72
|
-
if (!cookieHeader) return null;
|
|
73
|
-
for (const part of cookieHeader.split(/;\s*/)) {
|
|
74
|
-
const [cookieName, ...rest] = part.split("=");
|
|
75
|
-
if (cookieName === name) {
|
|
76
|
-
try {
|
|
77
|
-
return decodeURIComponent(rest.join("="));
|
|
78
|
-
} catch {
|
|
79
|
-
return null;
|
|
80
|
-
}
|
|
81
|
-
}
|
|
82
|
-
}
|
|
83
|
-
return null;
|
|
84
|
-
}
|
|
85
|
-
var STANDARD_SECURITY_HEADERS = Object.freeze({
|
|
86
|
-
"Strict-Transport-Security": "max-age=31536000; includeSubDomains; preload",
|
|
87
|
-
"X-Content-Type-Options": "nosniff",
|
|
88
|
-
"X-Frame-Options": "SAMEORIGIN",
|
|
89
|
-
"Referrer-Policy": "same-origin",
|
|
90
|
-
"X-XSS-Protection": "1; mode=block"
|
|
91
|
-
});
|
|
92
|
-
function addSecurityHeaders(response, opts = {}) {
|
|
93
|
-
for (const [name, value] of Object.entries(STANDARD_SECURITY_HEADERS)) {
|
|
94
|
-
response.headers.set(name, value);
|
|
95
|
-
}
|
|
96
|
-
if (opts.disclaimer) response.headers.set("X-AI-Disclaimer", opts.disclaimer);
|
|
97
|
-
if (opts.retention) response.headers.set("X-Data-Retention", opts.retention);
|
|
98
|
-
for (const [k, v] of Object.entries(opts.extra ?? {})) response.headers.set(k, v);
|
|
99
|
-
return response;
|
|
100
|
-
}
|
|
101
|
-
var REJECTED_MEDIA_SCHEMES = ["file:", "data:", "blob:", "javascript:", "vbscript:"];
|
|
102
|
-
function assertMediaUrl(url, what = "media url") {
|
|
103
|
-
const trimmed = url.trim();
|
|
104
|
-
if (/^https?:\/\//i.test(trimmed)) return;
|
|
105
|
-
if (trimmed.startsWith("/api/")) return;
|
|
106
|
-
const shown = trimmed.length > 96 ? `${trimmed.slice(0, 96)}\u2026` : trimmed;
|
|
107
|
-
const lower = trimmed.toLowerCase();
|
|
108
|
-
if (REJECTED_MEDIA_SCHEMES.some((scheme) => lower.startsWith(scheme)) || lower.startsWith("/tmp/") || lower.startsWith("/home/")) {
|
|
109
|
-
throw new Error(`${what} must reference a provider http(s) URL or a rooted /api/ path, not a local sandbox file (${shown})`);
|
|
110
|
-
}
|
|
111
|
-
throw new Error(`${what} must be http(s) or a rooted /api/ path (${shown})`);
|
|
112
|
-
}
|
|
113
|
-
|
|
114
|
-
export {
|
|
115
|
-
parseJsonObjectBody,
|
|
116
|
-
requireString,
|
|
117
|
-
extractRequestContext,
|
|
118
|
-
checkRateLimit,
|
|
119
|
-
serializeCookie,
|
|
120
|
-
clearCookieHeader,
|
|
121
|
-
readCookieValue,
|
|
122
|
-
STANDARD_SECURITY_HEADERS,
|
|
123
|
-
addSecurityHeaders,
|
|
124
|
-
assertMediaUrl
|
|
125
|
-
};
|
|
126
|
-
//# sourceMappingURL=chunk-J25RST7G.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/web/index.ts"],"sourcesContent":["/**\n * Web-boundary utilities every agent app's routes hand-roll: JSON body parsing\n * + narrowing, request-context extraction (real client IP behind Cloudflare),\n * a KV-backed sliding-window rate limiter, and security response headers. Pure\n * mechanism — no DB, no domain. The KV is a structural interface so this needs\n * no `@cloudflare/workers-types` dependency.\n */\n\nexport type JsonObject = Record<string, unknown>\n\n/** Parse + object-narrow a Request body. `[body, null]` on success, `[null,\n * errorResponse]` on a non-object body (callers `if (err) return err`). */\nexport async function parseJsonObjectBody(request: Request): Promise<[JsonObject, null] | [null, Response]> {\n let raw: unknown\n try {\n raw = await request.json()\n } catch {\n return [null, Response.json({ error: 'Invalid JSON body' }, { status: 400 })]\n }\n if (raw === null || typeof raw !== 'object' || Array.isArray(raw)) {\n return [null, Response.json({ error: 'Body must be a JSON object' }, { status: 400 })]\n }\n return [raw as JsonObject, null]\n}\n\n/** Narrow one required string field, 400 if missing/empty. */\nexport function requireString(body: JsonObject, field: string): string | Response {\n const v = body[field]\n if (typeof v !== 'string' || v.length === 0) {\n return Response.json({ error: `Missing or non-string field: ${field}` }, { status: 400 })\n }\n return v\n}\n\n/** Define the context of a request including IP address, user agent, timestamp, and request ID */\nexport interface RequestContext {\n ipAddress: string\n userAgent: string\n timestamp: string\n requestId: string\n}\n\n/** Extract request context for audit trails. Uses `CF-Connecting-IP` for the\n * real client IP behind Cloudflare. */\nexport function extractRequestContext(request: Request): RequestContext {\n const ipAddress =\n request.headers.get('CF-Connecting-IP') ??\n request.headers.get('X-Forwarded-For')?.split(',')[0]?.trim() ??\n '0.0.0.0'\n return {\n ipAddress,\n userAgent: request.headers.get('User-Agent') ?? '',\n timestamp: new Date().toISOString(),\n requestId: crypto.randomUUID(),\n }\n}\n\n/** Minimal KV contract (Cloudflare `KVNamespace` satisfies it structurally). */\nexport interface KvLike {\n get(key: string): Promise<string | null>\n put(key: string, value: string, options?: { expirationTtl?: number }): Promise<void>\n}\n\n/** Describe the outcome of a rate limit check including allowance, remaining count, and reset time */\nexport interface RateLimitResult {\n allowed: boolean\n remaining: number\n resetAt: number\n}\n\n/** KV-backed sliding-window rate limit. Stores recent timestamps per key,\n * prunes the window, allows until `limit` is hit.\n *\n * Read-modify-write is best-effort, NOT atomic: KV has no compare-and-swap, so\n * two requests racing on the same key can each read the same pre-state and both\n * write — a concurrent burst can momentarily admit up to one extra request per\n * racing writer. This is acceptable for coarse abuse limiting; it is NOT a hard\n * quota gate.\n *\n * Fail-CLOSED on unreadable state: corrupt/non-array KV (a poisoned or\n * truncated value) is treated as a full window, so a tampered key cannot reset\n * the count and bypass the limiter. A bare `JSON.parse` here would throw and\n * abort the request handler, silently disabling the limit (fail-open). */\nexport async function checkRateLimit(kv: KvLike, key: string, limit: number, windowSeconds: number): Promise<RateLimitResult> {\n const now = Math.floor(Date.now() / 1000)\n const windowStart = now - windowSeconds\n const kvKey = `rl:${key}`\n const raw = await kv.get(kvKey)\n const parsed = parseRateLimitState(raw)\n if (parsed === POISONED_STATE) {\n // Unreadable state (parse threw or value is not a JSON array): deny rather\n // than reset the window to empty. A poisoned key must not become a bypass.\n return { allowed: false, remaining: 0, resetAt: now + windowSeconds }\n }\n const valid = parsed.filter((t) => t > windowStart)\n if (valid.length >= limit) return { allowed: false, remaining: 0, resetAt: (valid[0] ?? now) + windowSeconds }\n valid.push(now)\n await kv.put(kvKey, JSON.stringify(valid), { expirationTtl: windowSeconds * 2 })\n return { allowed: true, remaining: limit - valid.length, resetAt: now + windowSeconds }\n}\n\n/** Sentinel returned by `parseRateLimitState` when the stored value cannot be\n * read as a timestamp array — distinct from an empty window so the limiter can\n * fail closed instead of treating corruption as a fresh window. */\nconst POISONED_STATE = Symbol('rate-limit-poisoned-state')\n\n/** Parse stored rate-limit state into a timestamp array. Absent state is a\n * fresh (empty) window. A value that fails to parse, or parses to a non-array,\n * returns `POISONED_STATE`; numeric junk inside a valid array is dropped. */\nfunction parseRateLimitState(raw: string | null): number[] | typeof POISONED_STATE {\n if (raw === null) return []\n let parsed: unknown\n try {\n parsed = JSON.parse(raw)\n } catch {\n return POISONED_STATE\n }\n if (!Array.isArray(parsed)) return POISONED_STATE\n return parsed.filter((t): t is number => typeof t === 'number' && Number.isFinite(t))\n}\n\n/** Define options for configuring cookie attributes and behavior */\nexport interface CookieOptions {\n name: string\n /** Default '/'. */\n path?: string\n /** Default true. */\n httpOnly?: boolean\n /** Adds the `Secure` attribute. Default false. */\n secure?: boolean\n /** Default 'Lax'. */\n sameSite?: 'Lax' | 'Strict' | 'None'\n maxAgeSeconds?: number\n}\n\n/** Serialize a Set-Cookie header value: `name=encodeURIComponent(value)` plus\n * attributes in Path / HttpOnly / SameSite / Max-Age / Secure order.\n * Throws on `SameSite=None` without `secure` — browsers silently drop that\n * combination, which would otherwise fail invisibly. */\nexport function serializeCookie(value: string, opts: CookieOptions): string {\n if (opts.sameSite === 'None' && !opts.secure) {\n throw new Error('SameSite=None cookies require secure: true (browsers reject them otherwise)')\n }\n const parts = [`${opts.name}=${encodeURIComponent(value)}`, `Path=${opts.path ?? '/'}`]\n if (opts.httpOnly !== false) parts.push('HttpOnly')\n parts.push(`SameSite=${opts.sameSite ?? 'Lax'}`)\n if (opts.maxAgeSeconds !== undefined) parts.push(`Max-Age=${opts.maxAgeSeconds}`)\n if (opts.secure) parts.push('Secure')\n return parts.join('; ')\n}\n\n/** Set-Cookie header value that deletes the cookie (empty value, Max-Age=0). */\nexport function clearCookieHeader(opts: Omit<CookieOptions, 'maxAgeSeconds'>): string {\n return serializeCookie('', { ...opts, maxAgeSeconds: 0 })\n}\n\n/** Read + decode one cookie from a Cookie request header; null when absent. */\nexport function readCookieValue(cookieHeader: string | null, name: string): string | null {\n if (!cookieHeader) return null\n for (const part of cookieHeader.split(/;\\s*/)) {\n const [cookieName, ...rest] = part.split('=')\n if (cookieName === name) {\n try {\n return decodeURIComponent(rest.join('='))\n } catch {\n return null\n }\n }\n }\n return null\n}\n\n/** Define options for configuring security-related HTTP headers including disclaimers and retention labels */\nexport interface SecurityHeaderOptions {\n /** Product disclaimer (e.g. \"AI-powered tool. Not legal advice.\"). Omitted if absent. */\n disclaimer?: string\n /** Data-retention label (e.g. \"7-years\"). Omitted if absent. */\n retention?: string\n /** Extra headers to set. */\n extra?: Record<string, string>\n}\n\n/** Canonical generic response headers used by {@link addSecurityHeaders}.\n * Exported so static-asset hosts can apply the same policy without copying\n * values that silently drift from Worker/API responses. */\nexport const STANDARD_SECURITY_HEADERS = Object.freeze({\n 'Strict-Transport-Security':\n 'max-age=31536000; includeSubDomains; preload',\n 'X-Content-Type-Options': 'nosniff',\n 'X-Frame-Options': 'SAMEORIGIN',\n 'Referrer-Policy': 'same-origin',\n 'X-XSS-Protection': '1; mode=block',\n} as const)\n\n/** Set standard security headers on a response (HSTS, nosniff, frame-options,\n * referrer-policy, XSS) + optional product disclaimer/retention. The security\n * set is generic; the disclaimer/retention are the product's. */\nexport function addSecurityHeaders(response: Response, opts: SecurityHeaderOptions = {}): Response {\n for (const [name, value] of Object.entries(STANDARD_SECURITY_HEADERS)) {\n response.headers.set(name, value)\n }\n if (opts.disclaimer) response.headers.set('X-AI-Disclaimer', opts.disclaimer)\n if (opts.retention) response.headers.set('X-Data-Retention', opts.retention)\n for (const [k, v] of Object.entries(opts.extra ?? {})) response.headers.set(k, v)\n return response\n}\n\n/** Local-sandbox / inline schemes a stored media reference must never use.\n * Reachable from neither a browser nor the product worker, and a `file:`/`data:`\n * url is the tell of an agent substituting local ffmpeg output for a real\n * provider artifact. `blob:` and `javascript:` are inert/active client schemes\n * with no server reachability. */\nconst REJECTED_MEDIA_SCHEMES = ['file:', 'data:', 'blob:', 'javascript:', 'vbscript:'] as const\n\n/**\n * Canonical media-reference boundary shared by every surface that persists a\n * media url (sequences clips, design-canvas image/video src). The ONE rule:\n * remote `http(s)` or a rooted `/api/` path are allowed; everything else is\n * rejected, with a named reason for known-bad local/inline schemes so the\n * thrown message is actionable for an LLM planner. The url is trimmed before\n * the scheme check so leading whitespace cannot smuggle a rejected scheme past\n * a naive `startsWith`.\n *\n * @param what - noun for the error message (e.g. 'media url', 'src').\n */\nexport function assertMediaUrl(url: string, what = 'media url'): void {\n const trimmed = url.trim()\n if (/^https?:\\/\\//i.test(trimmed)) return\n if (trimmed.startsWith('/api/')) return\n const shown = trimmed.length > 96 ? `${trimmed.slice(0, 96)}…` : trimmed\n const lower = trimmed.toLowerCase()\n if (\n REJECTED_MEDIA_SCHEMES.some((scheme) => lower.startsWith(scheme)) ||\n lower.startsWith('/tmp/') ||\n lower.startsWith('/home/')\n ) {\n throw new Error(`${what} must reference a provider http(s) URL or a rooted /api/ path, not a local sandbox file (${shown})`)\n }\n throw new Error(`${what} must be http(s) or a rooted /api/ path (${shown})`)\n}\n"],"mappings":";AAYA,eAAsB,oBAAoB,SAAkE;AAC1G,MAAI;AACJ,MAAI;AACF,UAAM,MAAM,QAAQ,KAAK;AAAA,EAC3B,QAAQ;AACN,WAAO,CAAC,MAAM,SAAS,KAAK,EAAE,OAAO,oBAAoB,GAAG,EAAE,QAAQ,IAAI,CAAC,CAAC;AAAA,EAC9E;AACA,MAAI,QAAQ,QAAQ,OAAO,QAAQ,YAAY,MAAM,QAAQ,GAAG,GAAG;AACjE,WAAO,CAAC,MAAM,SAAS,KAAK,EAAE,OAAO,6BAA6B,GAAG,EAAE,QAAQ,IAAI,CAAC,CAAC;AAAA,EACvF;AACA,SAAO,CAAC,KAAmB,IAAI;AACjC;AAGO,SAAS,cAAc,MAAkB,OAAkC;AAChF,QAAM,IAAI,KAAK,KAAK;AACpB,MAAI,OAAO,MAAM,YAAY,EAAE,WAAW,GAAG;AAC3C,WAAO,SAAS,KAAK,EAAE,OAAO,gCAAgC,KAAK,GAAG,GAAG,EAAE,QAAQ,IAAI,CAAC;AAAA,EAC1F;AACA,SAAO;AACT;AAYO,SAAS,sBAAsB,SAAkC;AACtE,QAAM,YACJ,QAAQ,QAAQ,IAAI,kBAAkB,KACt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AAA,EAClC;AACA,MAAI,KAAK,WAAY,UAAS,QAAQ,IAAI,mBAAmB,KAAK,UAAU;AAC5E,MAAI,KAAK,UAAW,UAAS,QAAQ,IAAI,oBAAoB,KAAK,SAAS;AAC3E,aAAW,CAAC,GAAG,CAAC,KAAK,OAAO,QAAQ,KAAK,SAAS,CAAC,CAAC,EAAG,UAAS,QAAQ,IAAI,GAAG,CAAC;AAChF,SAAO;AACT;AAOA,IAAM,yBAAyB,CAAC,SAAS,SAAS,SAAS,eAAe,WAAW;AAa9E,SAAS,eAAe,KAAa,OAAO,aAAmB;AACpE,QAAM,UAAU,IAAI,KAAK;AACzB,MAAI,gBAAgB,KAAK,OAAO,EAAG;AACnC,MAAI,QAAQ,WAAW,OAAO,EAAG;AACjC,QAAM,QAAQ,QAAQ,SAAS,KAAK,GAAG,QAAQ,MAAM,GAAG,EAAE,CAAC,WAAM;AACjE,QAAM,QAAQ,QAAQ,YAAY;AAClC,MACE,uBAAuB,KAAK,CAAC,WAAW,MAAM,WAAW,MAAM,CAAC,KAChE,MAAM,WAAW,OAAO,KACxB,MAAM,WAAW,QAAQ,GACzB;AACA,UAAM,IAAI,MAAM,GAAG,IAAI,4FAA4F,KAAK,GAAG;AAAA,EAC7H;AACA,QAAM,IAAI,MAAM,GAAG,IAAI,4CAA4C,KAAK,GAAG;AAC7E;","names":[]}
|
package/dist/chunk-WBHPN5DY.js
DELETED
|
@@ -1,158 +0,0 @@
|
|
|
1
|
-
import {
|
|
2
|
-
formatBytes
|
|
3
|
-
} from "./chunk-KWXUBMXU.js";
|
|
4
|
-
|
|
5
|
-
// src/chat-routes/binary-sniff.ts
|
|
6
|
-
function bytesStartWith(bytes, offset, signature) {
|
|
7
|
-
if (bytes.length < offset + signature.length) return false;
|
|
8
|
-
for (let i = 0; i < signature.length; i++) {
|
|
9
|
-
if (bytes[offset + i] !== signature[i]) return false;
|
|
10
|
-
}
|
|
11
|
-
return true;
|
|
12
|
-
}
|
|
13
|
-
function asciiAt(bytes, offset, text) {
|
|
14
|
-
if (bytes.length < offset + text.length) return false;
|
|
15
|
-
for (let i = 0; i < text.length; i++) {
|
|
16
|
-
if (bytes[offset + i] !== text.charCodeAt(i)) return false;
|
|
17
|
-
}
|
|
18
|
-
return true;
|
|
19
|
-
}
|
|
20
|
-
function sniffRiff(bytes) {
|
|
21
|
-
if (!asciiAt(bytes, 0, "RIFF")) return null;
|
|
22
|
-
if (asciiAt(bytes, 8, "WEBP")) return "image/webp";
|
|
23
|
-
if (asciiAt(bytes, 8, "WAVE")) return "audio/wav";
|
|
24
|
-
return null;
|
|
25
|
-
}
|
|
26
|
-
function sniffFtyp(bytes) {
|
|
27
|
-
if (!asciiAt(bytes, 4, "ftyp")) return null;
|
|
28
|
-
if (asciiAt(bytes, 8, "qt ")) return "video/quicktime";
|
|
29
|
-
if (asciiAt(bytes, 8, "avif") || asciiAt(bytes, 8, "avis")) return "image/avif";
|
|
30
|
-
if (asciiAt(bytes, 8, "heic") || asciiAt(bytes, 8, "heix") || asciiAt(bytes, 8, "hevc") || asciiAt(bytes, 8, "hevx")) return "image/heic";
|
|
31
|
-
if (asciiAt(bytes, 8, "mif1") || asciiAt(bytes, 8, "msf1")) return "image/heif";
|
|
32
|
-
return "video/mp4";
|
|
33
|
-
}
|
|
34
|
-
function sniffBmp(bytes) {
|
|
35
|
-
return asciiAt(bytes, 0, "BM") && bytes.length >= 10 && bytes[6] === 0 && bytes[7] === 0 && bytes[8] === 0 && bytes[9] === 0;
|
|
36
|
-
}
|
|
37
|
-
function sniffId3(bytes) {
|
|
38
|
-
return asciiAt(bytes, 0, "ID3") && bytes.length >= 10 && bytes[3] < 16 && bytes[6] < 128 && bytes[7] < 128 && bytes[8] < 128 && bytes[9] < 128;
|
|
39
|
-
}
|
|
40
|
-
function sniffMagicBytes(bytes) {
|
|
41
|
-
if (bytesStartWith(bytes, 0, [137, 80, 78, 71, 13, 10, 26, 10])) return "image/png";
|
|
42
|
-
if (bytesStartWith(bytes, 0, [255, 216, 255])) return "image/jpeg";
|
|
43
|
-
if (asciiAt(bytes, 0, "GIF87a") || asciiAt(bytes, 0, "GIF89a")) return "image/gif";
|
|
44
|
-
if (sniffBmp(bytes)) return "image/bmp";
|
|
45
|
-
if (bytesStartWith(bytes, 0, [73, 73, 42, 0])) return "image/tiff";
|
|
46
|
-
if (bytesStartWith(bytes, 0, [77, 77, 0, 42])) return "image/tiff";
|
|
47
|
-
if (bytesStartWith(bytes, 0, [0, 0, 1, 0])) return "image/x-icon";
|
|
48
|
-
if (asciiAt(bytes, 0, "%PDF-")) return "application/pdf";
|
|
49
|
-
if (bytesStartWith(bytes, 0, [80, 75, 3, 4])) return "application/zip";
|
|
50
|
-
if (bytesStartWith(bytes, 0, [31, 139])) return "application/gzip";
|
|
51
|
-
if (sniffId3(bytes) || bytesStartWith(bytes, 0, [255, 251])) return "audio/mpeg";
|
|
52
|
-
if (asciiAt(bytes, 0, "OggS")) return "audio/ogg";
|
|
53
|
-
const riff = sniffRiff(bytes);
|
|
54
|
-
if (riff) return riff;
|
|
55
|
-
const ftyp = sniffFtyp(bytes);
|
|
56
|
-
if (ftyp) return ftyp;
|
|
57
|
-
return null;
|
|
58
|
-
}
|
|
59
|
-
function sniffSvgText(decoded) {
|
|
60
|
-
let text = decoded;
|
|
61
|
-
if (text.charCodeAt(0) === 65279) text = text.slice(1);
|
|
62
|
-
text = text.trimStart();
|
|
63
|
-
if (/^<svg[\s>/]/.test(text)) return true;
|
|
64
|
-
if (!text.startsWith("<?xml")) return false;
|
|
65
|
-
return /<svg[\s>/]/.test(text.slice(0, 1024));
|
|
66
|
-
}
|
|
67
|
-
function sniffBinary(bytes) {
|
|
68
|
-
const mime = sniffMagicBytes(bytes);
|
|
69
|
-
if (mime) return { binary: true, mime };
|
|
70
|
-
if (bytes.includes(0)) return { binary: true, mime: null };
|
|
71
|
-
let decoded;
|
|
72
|
-
try {
|
|
73
|
-
decoded = new TextDecoder("utf-8", { fatal: true }).decode(bytes);
|
|
74
|
-
} catch {
|
|
75
|
-
return { binary: true, mime: null };
|
|
76
|
-
}
|
|
77
|
-
if (sniffSvgText(decoded)) return { binary: true, mime: "image/svg+xml" };
|
|
78
|
-
return { binary: false, mime: null };
|
|
79
|
-
}
|
|
80
|
-
|
|
81
|
-
// src/chat-routes/attachment-validation.ts
|
|
82
|
-
var MAX_BINARY_ATTACHMENT_BYTES = 10 * 1024 * 1024;
|
|
83
|
-
var MAX_TEXT_ATTACHMENT_BYTES = 950 * 1024;
|
|
84
|
-
var ATTACHMENT_MAX_COUNT = 10;
|
|
85
|
-
var MAX_ATTACHMENT_TOTAL_BYTES = 25 * 1024 * 1024;
|
|
86
|
-
var ATTACHMENT_ACCEPT = "image/*,.pdf,.txt,.md,.csv,.json,.yaml,.yml,.html";
|
|
87
|
-
var ALLOWED_ATTACHMENT_SNIFFED_MIMES = /* @__PURE__ */ new Set([
|
|
88
|
-
"image/png",
|
|
89
|
-
"image/jpeg",
|
|
90
|
-
"image/gif",
|
|
91
|
-
"image/bmp",
|
|
92
|
-
"image/tiff",
|
|
93
|
-
"image/x-icon",
|
|
94
|
-
"image/webp",
|
|
95
|
-
"image/svg+xml",
|
|
96
|
-
"image/avif",
|
|
97
|
-
"image/heic",
|
|
98
|
-
"image/heif",
|
|
99
|
-
"application/pdf"
|
|
100
|
-
]);
|
|
101
|
-
var EXTENSION_IMPLIES_SNIFFED_MIME = {
|
|
102
|
-
png: "image/png",
|
|
103
|
-
jpg: "image/jpeg",
|
|
104
|
-
jpeg: "image/jpeg",
|
|
105
|
-
gif: "image/gif",
|
|
106
|
-
bmp: "image/bmp",
|
|
107
|
-
tif: "image/tiff",
|
|
108
|
-
tiff: "image/tiff",
|
|
109
|
-
ico: "image/x-icon",
|
|
110
|
-
webp: "image/webp",
|
|
111
|
-
svg: "image/svg+xml",
|
|
112
|
-
pdf: "application/pdf"
|
|
113
|
-
};
|
|
114
|
-
function checkAttachmentType(fileName, sniff, allowed = ALLOWED_ATTACHMENT_SNIFFED_MIMES) {
|
|
115
|
-
if (sniff.binary === false) return { succeeded: true };
|
|
116
|
-
const extension = fileName.split(".").pop()?.toLowerCase() ?? "";
|
|
117
|
-
const impliedMime = EXTENSION_IMPLIES_SNIFFED_MIME[extension];
|
|
118
|
-
if (impliedMime && sniff.mime && sniff.mime !== impliedMime) {
|
|
119
|
-
return {
|
|
120
|
-
succeeded: false,
|
|
121
|
-
code: "attachment_type_mismatch",
|
|
122
|
-
message: `${fileName} has a .${extension} extension, but its content is ${sniff.mime}`
|
|
123
|
-
};
|
|
124
|
-
}
|
|
125
|
-
if (!sniff.mime || !allowed.has(sniff.mime)) {
|
|
126
|
-
return {
|
|
127
|
-
succeeded: false,
|
|
128
|
-
code: "attachment_type_not_allowed",
|
|
129
|
-
message: sniff.mime ? `${fileName}'s content (${sniff.mime}) is not an allowed attachment type` : `${fileName}'s content is not a recognized attachment type`
|
|
130
|
-
};
|
|
131
|
-
}
|
|
132
|
-
return { succeeded: true };
|
|
133
|
-
}
|
|
134
|
-
function sanitizeAttachmentFileName(name) {
|
|
135
|
-
const sanitized = name.trim().replace(/[^A-Za-z0-9._-]+/g, "-").replace(/^[.-]+/, "");
|
|
136
|
-
return sanitized || "file";
|
|
137
|
-
}
|
|
138
|
-
function attachmentSizeErrorMessage(name, actualBytes, limitBytes) {
|
|
139
|
-
return `${name} is ${formatBytes(actualBytes)}; attachments are limited to ${formatBytes(limitBytes)}`;
|
|
140
|
-
}
|
|
141
|
-
function attachmentTotalSizeErrorMessage(totalBytes, limitBytes) {
|
|
142
|
-
return `Attachments total ${formatBytes(totalBytes)}; each message is limited to ${formatBytes(limitBytes)}`;
|
|
143
|
-
}
|
|
144
|
-
|
|
145
|
-
export {
|
|
146
|
-
sniffBinary,
|
|
147
|
-
MAX_BINARY_ATTACHMENT_BYTES,
|
|
148
|
-
MAX_TEXT_ATTACHMENT_BYTES,
|
|
149
|
-
ATTACHMENT_MAX_COUNT,
|
|
150
|
-
MAX_ATTACHMENT_TOTAL_BYTES,
|
|
151
|
-
ATTACHMENT_ACCEPT,
|
|
152
|
-
ALLOWED_ATTACHMENT_SNIFFED_MIMES,
|
|
153
|
-
checkAttachmentType,
|
|
154
|
-
sanitizeAttachmentFileName,
|
|
155
|
-
attachmentSizeErrorMessage,
|
|
156
|
-
attachmentTotalSizeErrorMessage
|
|
157
|
-
};
|
|
158
|
-
//# sourceMappingURL=chunk-WBHPN5DY.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/chat-routes/binary-sniff.ts","../src/chat-routes/attachment-validation.ts"],"sourcesContent":["/**\n * Content-based binary/text classification, shared by the attachment upload\n * route (server) and the composer's client-side pre-validation (browser) —\n * both sides must agree on what counts as binary before a byte ever leaves\n * the client. Extension-based allowlists lie (a renamed `.docx`, a PNG saved\n * as `.txt`), so classification reads the actual bytes: a magic-byte table\n * for common binary formats first, then a UTF-8 decode attempt for\n * everything else.\n *\n * Lifted near-verbatim from gtm-agent's `src/lib/binary-sniff.ts` (the\n * source PRs hardened this against real corruption/gate bugs: gtm#584,\n * gtm#592). Import-free by design — `/web-react` re-exports `/chat-routes`\n * modules into browser bundles (`tests/browser-safe-subpaths.test.ts` walks\n * the graph), so nothing here may reach a Node builtin or an engine package.\n */\n\nexport interface SniffResult {\n binary: boolean\n mime: string | null\n}\n\nfunction bytesStartWith(bytes: Uint8Array, offset: number, signature: number[]): boolean {\n if (bytes.length < offset + signature.length) return false\n for (let i = 0; i < signature.length; i++) {\n if (bytes[offset + i] !== signature[i]) return false\n }\n return true\n}\n\nfunction asciiAt(bytes: Uint8Array, offset: number, text: string): boolean {\n if (bytes.length < offset + text.length) return false\n for (let i = 0; i < text.length; i++) {\n if (bytes[offset + i] !== text.charCodeAt(i)) return false\n }\n return true\n}\n\n/** RIFF containers (WebP, WAV) share the `RIFF....<TYPE>` header; the type\n * tag at byte offset 8 distinguishes them. */\nfunction sniffRiff(bytes: Uint8Array): string | null {\n if (!asciiAt(bytes, 0, 'RIFF')) return null\n if (asciiAt(bytes, 8, 'WEBP')) return 'image/webp'\n if (asciiAt(bytes, 8, 'WAVE')) return 'audio/wav'\n return null\n}\n\n/** MP4/MOV/AVIF/HEIC containers share an `ftyp` box at byte offset 4; the\n * major brand at offset 8 tells them apart within the shared ISO-BMFF\n * family. Brands outside this table (mp4, m4a, m4v, etc) fall back to\n * `video/mp4`, the family's most common member. */\nfunction sniffFtyp(bytes: Uint8Array): string | null {\n if (!asciiAt(bytes, 4, 'ftyp')) return null\n if (asciiAt(bytes, 8, 'qt ')) return 'video/quicktime'\n if (asciiAt(bytes, 8, 'avif') || asciiAt(bytes, 8, 'avis')) return 'image/avif'\n if (asciiAt(bytes, 8, 'heic') || asciiAt(bytes, 8, 'heix') || asciiAt(bytes, 8, 'hevc') || asciiAt(bytes, 8, 'hevx')) return 'image/heic'\n if (asciiAt(bytes, 8, 'mif1') || asciiAt(bytes, 8, 'msf1')) return 'image/heif'\n return 'video/mp4'\n}\n\n/** `BM` alone matches ordinary prose (\"BMW…\"), so require the BMP header's\n * reserved bytes (offsets 6-9), which the format mandates to be zero. */\nfunction sniffBmp(bytes: Uint8Array): boolean {\n return asciiAt(bytes, 0, 'BM')\n && bytes.length >= 10\n && bytes[6] === 0 && bytes[7] === 0 && bytes[8] === 0 && bytes[9] === 0\n}\n\n/** `ID3` alone matches ordinary prose (\"ID3 tags…\"), so require the ID3v2\n * header shape: a plausible version byte and sync-safe size bytes. */\nfunction sniffId3(bytes: Uint8Array): boolean {\n return asciiAt(bytes, 0, 'ID3')\n && bytes.length >= 10\n && bytes[3]! < 0x10\n && bytes[6]! < 0x80 && bytes[7]! < 0x80 && bytes[8]! < 0x80 && bytes[9]! < 0x80\n}\n\nfunction sniffMagicBytes(bytes: Uint8Array): string | null {\n if (bytesStartWith(bytes, 0, [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a])) return 'image/png'\n if (bytesStartWith(bytes, 0, [0xff, 0xd8, 0xff])) return 'image/jpeg'\n if (asciiAt(bytes, 0, 'GIF87a') || asciiAt(bytes, 0, 'GIF89a')) return 'image/gif'\n if (sniffBmp(bytes)) return 'image/bmp'\n if (bytesStartWith(bytes, 0, [0x49, 0x49, 0x2a, 0x00])) return 'image/tiff' // little-endian\n if (bytesStartWith(bytes, 0, [0x4d, 0x4d, 0x00, 0x2a])) return 'image/tiff' // big-endian\n if (bytesStartWith(bytes, 0, [0x00, 0x00, 0x01, 0x00])) return 'image/x-icon'\n if (asciiAt(bytes, 0, '%PDF-')) return 'application/pdf'\n // OOXML (.docx/.xlsx/.pptx) is a zip archive; the container format is all\n // that matters here, so no attempt is made to distinguish the payload.\n if (bytesStartWith(bytes, 0, [0x50, 0x4b, 0x03, 0x04])) return 'application/zip'\n if (bytesStartWith(bytes, 0, [0x1f, 0x8b])) return 'application/gzip'\n if (sniffId3(bytes) || bytesStartWith(bytes, 0, [0xff, 0xfb])) return 'audio/mpeg'\n if (asciiAt(bytes, 0, 'OggS')) return 'audio/ogg'\n\n const riff = sniffRiff(bytes)\n if (riff) return riff\n\n const ftyp = sniffFtyp(bytes)\n if (ftyp) return ftyp\n\n return null\n}\n\n/** SVG is valid UTF-8 but must round-trip byte-identical (image tools read\n * it from the box as a file), so it is classified binary. Conservative\n * match: the document's first element is `<svg`, or an `<?xml` prolog is\n * followed by an `<svg` element within the first ~1KB (comments/doctype may\n * sit between). Plain XML without an svg root, or prose that merely\n * mentions \"<svg\", stays text. */\nfunction sniffSvgText(decoded: string): boolean {\n let text = decoded\n if (text.charCodeAt(0) === 0xfeff) text = text.slice(1)\n text = text.trimStart()\n if (/^<svg[\\s>/]/.test(text)) return true\n if (!text.startsWith('<?xml')) return false\n return /<svg[\\s>/]/.test(text.slice(0, 1024))\n}\n\n/** Decide whether uploaded bytes are binary or text, and identify the mime\n * type when it can be determined from content. Magic bytes are checked\n * first; anything unmatched falls back to a fatal UTF-8 decode. A NUL byte\n * or a decode failure means binary. Valid UTF-8 that is an SVG document is\n * binary (byte-identity matters for image tooling). Content that matches\n * nothing and does not decode as text is binary with an unknown mime —\n * extension-based guessing happens at the call site, not here. */\nexport function sniffBinary(bytes: Uint8Array): SniffResult {\n const mime = sniffMagicBytes(bytes)\n if (mime) return { binary: true, mime }\n\n if (bytes.includes(0x00)) return { binary: true, mime: null }\n\n let decoded: string\n try {\n decoded = new TextDecoder('utf-8', { fatal: true }).decode(bytes)\n } catch {\n return { binary: true, mime: null }\n }\n if (sniffSvgText(decoded)) return { binary: true, mime: 'image/svg+xml' }\n return { binary: false, mime: null }\n}\n","/**\n * Shared attachment validation core — constants, type-gate, and filename\n * sanitization used by BOTH the (server) attachment upload route and the\n * (browser) composer's client-side pre-validation, so a rejection never\n * differs depending on which side classified the bytes first.\n *\n * ≈ gtm-agent's `src/lib/attachment-limits.ts`, minus what agent-app already\n * has (`ATTACHMENT_MAX_COUNT`/`MAX_ATTACHMENT_TOTAL_BYTES`/\n * `attachmentTotalSizeErrorMessage` lived in `./resolve-attachments` and are\n * re-homed here so the whole validation vocabulary — count cap, size caps,\n * and type gate — has one address). Import-free besides `./wire`\n * (`formatBytes`) and `./binary-sniff` (`SniffResult`): `/web-react`\n * re-exports `/chat-routes` modules into browser bundles\n * (`tests/browser-safe-subpaths.test.ts` walks the graph), so nothing here\n * may reach a Node builtin or an engine package.\n */\n\nimport { formatBytes } from './wire'\nimport type { SniffResult } from './binary-sniff'\n\n/** Ceiling on a binary attachment's raw (pre-encoding) byte size. */\nexport const MAX_BINARY_ATTACHMENT_BYTES = 10 * 1024 * 1024\n\n/** Ceiling on a text attachment's raw byte size. Text hydrates through\n * inline prompt parts, a separate path that remains proxy-capped (see\n * `INLINE_PARTS_MAX_BYTES` in `./wire`). */\nexport const MAX_TEXT_ATTACHMENT_BYTES = 950 * 1024\n\n/** Most files a single request may carry: the composer staging cap, the\n * upload route's per-request cap, and the chat body's `attachments` cap. */\nexport const ATTACHMENT_MAX_COUNT = 10\n\n/** Aggregate raw-byte ceiling across one message's attachments. */\nexport const MAX_ATTACHMENT_TOTAL_BYTES = 25 * 1024 * 1024\n\n/**\n * Accept list for the composer file picker + type validation, same grammar as\n * the native `<input accept>` attribute. Images plus the text/doc types a\n * product's store actually reads.\n */\nexport const ATTACHMENT_ACCEPT =\n 'image/*,.pdf,.txt,.md,.csv,.json,.yaml,.yml,.html'\n\n/** Sniffed-mime counterpart of `ATTACHMENT_ACCEPT`: the binary formats\n * `sniffBinary` can identify from magic bytes among the accepted types.\n * Values must match `sniffBinary`'s output strings verbatim, or every\n * upload of that format fails the type gate. */\nexport const ALLOWED_ATTACHMENT_SNIFFED_MIMES: ReadonlySet<string> = new Set([\n 'image/png',\n 'image/jpeg',\n 'image/gif',\n 'image/bmp',\n 'image/tiff',\n 'image/x-icon',\n 'image/webp',\n 'image/svg+xml',\n 'image/avif',\n 'image/heic',\n 'image/heif',\n 'application/pdf',\n])\n\n/** Extensions whose magic-byte family is unambiguous, mapped to the mime\n * `sniffBinary` emits for genuine content of that format. Keep in sync with\n * `ATTACHMENT_ACCEPT`: an extension only belongs here if its format has a\n * detectable magic-byte signature. Text extensions (.txt/.md/.csv/.json/\n * .yaml/.yml/.html) are deliberately absent — they have no magic bytes to\n * compare against, so they ride the plain UTF-8 gate instead. AVIF/HEIC/HEIF\n * extensions are also deliberately absent: the ISO-BMFF brand-to-extension\n * mapping in that family isn't one-to-one (a legitimate `.heic` can carry a\n * `mif1` brand), so an extension-implies-mime entry would reject genuine\n * files. They still ride the allowlist gate below, which is what catches an\n * mp4 renamed `.avif` (its content sniffs `video/mp4`, not an allowed mime). */\nconst EXTENSION_IMPLIES_SNIFFED_MIME: Readonly<Record<string, string>> = {\n png: 'image/png',\n jpg: 'image/jpeg',\n jpeg: 'image/jpeg',\n gif: 'image/gif',\n bmp: 'image/bmp',\n tif: 'image/tiff',\n tiff: 'image/tiff',\n ico: 'image/x-icon',\n webp: 'image/webp',\n svg: 'image/svg+xml',\n pdf: 'application/pdf',\n}\n\n/** Represent the result of checking an attachment's type with success or specific failure details */\nexport type AttachmentTypeCheckResult =\n | { succeeded: true }\n | { succeeded: false; code: 'attachment_type_mismatch' | 'attachment_type_not_allowed'; message: string }\n\n/**\n * Cross-check a filename's extension against its sniffed content.\n *\n * Text content (`sniff.binary === false`) always passes here — it has no\n * magic bytes to compare, so it rides the existing UTF-8 gate instead. For\n * binary content: an extension with an unambiguous magic-byte family (e.g.\n * `.pdf`) must match the sniffed mime, or the upload is a mismatch (a\n * renamed file). Otherwise the sniffed mime must be one of `allowed`\n * (default {@link ALLOWED_ATTACHMENT_SNIFFED_MIMES}), or the upload is\n * rejected outright. The `allowed` param feeds a route's override seam (a\n * product accepting a narrower or wider set than the default).\n */\nexport function checkAttachmentType(\n fileName: string,\n sniff: SniffResult,\n allowed: ReadonlySet<string> = ALLOWED_ATTACHMENT_SNIFFED_MIMES,\n): AttachmentTypeCheckResult {\n if (sniff.binary === false) return { succeeded: true }\n\n const extension = fileName.split('.').pop()?.toLowerCase() ?? ''\n const impliedMime = EXTENSION_IMPLIES_SNIFFED_MIME[extension]\n if (impliedMime && sniff.mime && sniff.mime !== impliedMime) {\n return {\n succeeded: false,\n code: 'attachment_type_mismatch',\n message: `${fileName} has a .${extension} extension, but its content is ${sniff.mime}`,\n }\n }\n\n if (!sniff.mime || !allowed.has(sniff.mime)) {\n return {\n succeeded: false,\n code: 'attachment_type_not_allowed',\n message: sniff.mime\n ? `${fileName}'s content (${sniff.mime}) is not an allowed attachment type`\n : `${fileName}'s content is not a recognized attachment type`,\n }\n }\n\n return { succeeded: true }\n}\n\n/**\n * Rewrite a filename into the store-path charset (`A-Za-z0-9._-` per\n * segment) — attachment paths double as store keys, sandbox file paths, and\n * in-message path references, none of which tolerate spaces or punctuation.\n * Runs of unsupported characters collapse to one `-`; leading dots/dashes are\n * stripped so the name can't read as a hidden segment. The original name is\n * preserved separately (the returned `ChatAttachmentInput.name`), so\n * sanitization loses nothing.\n */\nexport function sanitizeAttachmentFileName(name: string): string {\n const sanitized = name\n .trim()\n .replace(/[^A-Za-z0-9._-]+/g, '-')\n .replace(/^[.-]+/, '')\n return sanitized || 'file'\n}\n\n/** Human-readable error naming both the actual size and the limit that was\n * exceeded. Shared so the server route and the composer pre-check report\n * the same message shape. */\nexport function attachmentSizeErrorMessage(name: string, actualBytes: number, limitBytes: number): string {\n return `${name} is ${formatBytes(actualBytes)}; attachments are limited to ${formatBytes(limitBytes)}`\n}\n\n/** Human-readable error for a chat message whose combined attachments exceed\n * the aggregate raw-byte ceiling. */\nexport function attachmentTotalSizeErrorMessage(totalBytes: number, limitBytes: number): string {\n return `Attachments total ${formatBytes(totalBytes)}; each message is limited to ${formatBytes(limitBytes)}`\n}\n"],"mappings":";;;;;AAqBA,SAAS,eAAe,OAAmB,QAAgB,WAA8B;AACvF,MAAI,MAAM,SAAS,SAAS,UAAU,OAAQ,QAAO;AACrD,WAAS,IAAI,GAAG,IAAI,UAAU,QAAQ,KAAK;AACzC,QAAI,MAAM,SAAS,CAAC,MAAM,UAAU,CAAC,EAAG,QAAO;AAAA,EACjD;AACA,SAAO;AACT;AAEA,SAAS,QAAQ,OAAmB,QAAgB,MAAuB;AACzE,MAAI,MAAM,SAAS,SAAS,KAAK,OAAQ,QAAO;AAChD,WAAS,IAAI,GAAG,IAAI,KAAK,QAAQ,KAAK;AACpC,QAAI,MAAM,SAAS,CAAC,MAAM,KAAK,WAAW,CAAC,EAAG,QAAO;AAAA,EACvD;AACA,SAAO;AACT;AAIA,SAAS,UAAU,OAAkC;AACnD,MAAI,CAAC,QAAQ,OAAO,GAAG,MAAM,EAAG,QAAO;AACvC,MAAI,QAAQ,OAAO,GAAG,MAAM,EAAG,QAAO;AACtC,MAAI,QAAQ,OAAO,GAAG,MAAM,EAAG,QAAO;AACtC,SAAO;AACT;AAMA,SAAS,UAAU,OAAkC;AACnD,MAAI,CAAC,QAAQ,OAAO,GAAG,MAAM,EAAG,QAAO;AACvC,MAAI,QAAQ,OAAO,GAAG,MAAM,EAAG,QAAO;AACtC,MAAI,QAAQ,OAAO,GAAG,MAAM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