agentschat-mcp 0.36.25 → 0.36.26
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/CHANGELOG.md +7 -0
- package/codex/README.md +1 -1
- package/codex/app-server.ts +79 -22
- package/codex/bots-config.ts +31 -11
- package/codex/bridge.ts +123 -25
- package/codex/config.ts +128 -21
- package/codex/gui-channel.ts +66 -9
- package/codex/inbox-sync.ts +65 -12
- package/codex/loop-grants.ts +41 -11
- package/codex/manager.ts +101 -25
- package/codex/owner.ts +81 -9
- package/codex/processes.ts +51 -7
- package/codex/run.ts +70 -17
- package/codex/runtime-home.ts +41 -11
- package/codex/thread-history.ts +77 -30
- package/codex/transport.ts +122 -19
- package/connector/auth.ts +57 -5
- package/connector/backfill.ts +92 -10
- package/connector/descriptor.ts +27 -1
- package/connector/identities.ts +82 -14
- package/connector/ingest.ts +11 -2
- package/connector/normalize.ts +32 -12
- package/connector/run.ts +314 -67
- package/connector/server.ts +95 -26
- package/dist/codex-bots.js +410 -73
- package/dist/codex-bridge.js +1996 -576
- package/dist/connector.js +1286 -493
- package/dist/dsh.js +1776 -299
- package/dist/muse.js +967 -221
- package/dist/server.js +4277 -929
- package/dsh/client.js +7 -5
- package/dsh/identity-ui/client.js +7 -5
- package/dsh/identity-ui/index.js +43 -8
- package/dsh/inbound-bridge/index.js +595 -146
- package/dsh/src/cli.ts +430 -91
- package/dsh/src/patch.ts +295 -15
- package/dsh/tests/dsh-hardening-127.test.ts +207 -0
- package/dsh/tests/dsh.test.ts +990 -3
- package/muse/scripts/ensure-muse-wakes.mjs +5 -3
- package/muse/scripts/muse-wake-receiver.mjs +4 -1
- package/muse/src/bridge.ts +54 -13
- package/muse/src/cli.ts +226 -41
- package/muse/src/client.ts +249 -34
- package/muse/src/config.ts +128 -12
- package/muse/src/policy.ts +28 -8
- package/muse/src/types.ts +1 -0
- package/muse/src/typing.ts +18 -1
- package/muse/src/wake.ts +237 -35
- package/muse/tests/bridge.test.mjs +131 -0
- package/muse/tests/client.test.mjs +327 -0
- package/muse/tests/config.test.mjs +78 -1
- package/muse/tests/hardening.test.mjs +199 -0
- package/muse/tests/hardening126.test.mjs +292 -0
- package/muse/tests/policy.test.mjs +83 -1
- package/muse/tests/wake.test.mjs +134 -6
- package/package.json +1 -1
- package/scripts/ensure-grok-wakes.mjs +93 -8
- package/scripts/example-url-wake-receiver.mjs +254 -61
- package/scripts/grok-bind-register.sh +38 -8
- package/skills/onboarding.md +9 -9
- package/src/argcheck.ts +113 -33
- package/src/cli.mjs +98 -14
- package/src/dedup.ts +57 -8
- package/src/grok-bind.ts +160 -33
- package/src/heartbeat.ts +39 -11
- package/src/identity-guard.ts +93 -20
- package/src/identity.ts +67 -11
- package/src/mentions.ts +26 -5
- package/src/onboarding-status.ts +134 -11
- package/src/profile-selection.ts +269 -18
- package/src/profile-store.ts +222 -28
- package/src/read-cursor.ts +256 -9
- package/src/reconnect.ts +98 -2
- package/src/redact.ts +34 -15
- package/src/rest-cli.ts +713 -159
- package/src/server.ts +285 -93
- package/src/session-bind.ts +731 -132
- package/src/session-route.ts +183 -12
- package/src/team-lead-skill.ts +3 -0
- package/src/timestamps.ts +56 -23
- package/src/tool-annotations.ts +10 -1
- package/src/wake.ts +510 -91
package/src/identity-guard.ts
CHANGED
|
@@ -53,28 +53,80 @@ export type GuardVerdict =
|
|
|
53
53
|
| { kind: "warn"; message: string }
|
|
54
54
|
| { kind: "gate"; message: string };
|
|
55
55
|
|
|
56
|
+
import { redactSecrets } from "./redact.ts";
|
|
57
|
+
|
|
56
58
|
export const IDENTITY_GUARD_FILENAME = "identity-guard.json";
|
|
59
|
+
const MAX_GUARD_SELECTORS = 256;
|
|
57
60
|
|
|
58
61
|
export function emptyGuardRecord(): IdentityGuardRecord {
|
|
59
62
|
return { bySelector: {}, lastEffective: null };
|
|
60
63
|
}
|
|
61
64
|
|
|
65
|
+
function isUnsafeSelectorKey(key: string): boolean {
|
|
66
|
+
const lower = key.toLowerCase();
|
|
67
|
+
return lower === "__proto__" || lower === "constructor" || lower === "prototype";
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
const GUARD_CONTROL_RE = /[\x00-\x1f\x7f-\x9f\u2028\u2029]/;
|
|
71
|
+
|
|
72
|
+
function cleanDisplayToken(raw: unknown, maxLen = 128): string {
|
|
73
|
+
if (typeof raw !== "string") return "";
|
|
74
|
+
return redactSecrets(raw)
|
|
75
|
+
.replace(/\b(?:Bearer|Basic)\s+[A-Za-z0-9._~+/=-]{8,}/gi, "[REDACTED]")
|
|
76
|
+
.replace(/\b(?:agent_key_|sk-|whsec_|gh[pousr]_|github_pat_|AIza|(?:AKIA|ASIA))[A-Za-z0-9_+/=.-]{8,}/g, "[REDACTED]")
|
|
77
|
+
.replace(/[\x00-\x1f\x7f-\x9f\u2028\u2029]+/g, "")
|
|
78
|
+
.trim()
|
|
79
|
+
.slice(0, maxLen);
|
|
80
|
+
}
|
|
81
|
+
|
|
62
82
|
/** Parse a persisted record; anything unreadable/malformed is an empty record (never blocks boot). */
|
|
63
83
|
export function parseGuardRecord(text: string | null): IdentityGuardRecord {
|
|
64
|
-
if (!text) return emptyGuardRecord();
|
|
84
|
+
if (!text || typeof text !== "string" || text.length > 262_144) return emptyGuardRecord();
|
|
65
85
|
try {
|
|
66
86
|
const raw = JSON.parse(text);
|
|
67
|
-
if (!raw || typeof raw !== "object")
|
|
87
|
+
if (!raw || typeof raw !== "object" || Array.isArray(raw) || Object.prototype.hasOwnProperty.call(raw, "__proto__")) {
|
|
88
|
+
return emptyGuardRecord();
|
|
89
|
+
}
|
|
90
|
+
const bySelector: Record<string, string> = {};
|
|
91
|
+
if (
|
|
92
|
+
raw.bySelector &&
|
|
93
|
+
typeof raw.bySelector === "object" &&
|
|
94
|
+
!Array.isArray(raw.bySelector)
|
|
95
|
+
) {
|
|
96
|
+
for (const [k, v] of Object.entries(raw.bySelector as Record<string, unknown>)) {
|
|
97
|
+
if (Object.keys(bySelector).length >= MAX_GUARD_SELECTORS) break;
|
|
98
|
+
if (GUARD_CONTROL_RE.test(k) || typeof v !== "string" || GUARD_CONTROL_RE.test(v)) continue;
|
|
99
|
+
const key = k.trim();
|
|
100
|
+
const val = v.trim();
|
|
101
|
+
if (!key || key.length > 128 || isUnsafeSelectorKey(key) || !val || val.length > 128) continue;
|
|
102
|
+
bySelector[key] = val;
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
const rawLast = raw.lastEffective;
|
|
106
|
+
const validRawLast =
|
|
107
|
+
rawLast &&
|
|
108
|
+
typeof rawLast === "object" &&
|
|
109
|
+
!Array.isArray(rawLast) &&
|
|
110
|
+
!Object.prototype.hasOwnProperty.call(rawLast, "__proto__");
|
|
111
|
+
const cleanAgentId =
|
|
112
|
+
validRawLast && typeof rawLast.agentId === "string"
|
|
113
|
+
? cleanDisplayToken(rawLast.agentId, 128)
|
|
114
|
+
: "";
|
|
115
|
+
const cleanDecl =
|
|
116
|
+
validRawLast && rawLast.declaredName
|
|
117
|
+
? cleanDisplayToken(String(rawLast.declaredName), 128)
|
|
118
|
+
: "";
|
|
68
119
|
return {
|
|
69
|
-
bySelector
|
|
70
|
-
lastEffective:
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
120
|
+
bySelector,
|
|
121
|
+
lastEffective:
|
|
122
|
+
cleanAgentId.length > 0 && !isUnsafeSelectorKey(cleanAgentId)
|
|
123
|
+
? {
|
|
124
|
+
agentId: cleanAgentId,
|
|
125
|
+
source: cleanDisplayToken(String(rawLast.source ?? "unknown"), 64) || "unknown",
|
|
126
|
+
...(cleanDecl ? { declaredName: cleanDecl } : {}),
|
|
127
|
+
ts: cleanDisplayToken(String(rawLast.ts ?? ""), 64),
|
|
128
|
+
}
|
|
129
|
+
: null,
|
|
78
130
|
};
|
|
79
131
|
} catch {
|
|
80
132
|
return emptyGuardRecord();
|
|
@@ -91,27 +143,40 @@ export function decideIdentityGuard(prev: IdentityGuardRecord, current: GuardIde
|
|
|
91
143
|
if (!last) return { kind: "ok" }; // first recorded boot — nothing to drift from
|
|
92
144
|
if (last.agentId === current.agentId) return { kind: "ok" };
|
|
93
145
|
|
|
146
|
+
const safeLastId = cleanDisplayToken(last.agentId, 128);
|
|
147
|
+
const safeLastSrc = cleanDisplayToken(last.source, 64) || "unknown";
|
|
148
|
+
const safeLastDecl = last.declaredName ? cleanDisplayToken(last.declaredName, 128) : "";
|
|
149
|
+
const safeCurId = cleanDisplayToken(current.agentId, 128);
|
|
150
|
+
|
|
94
151
|
if (current.source === "default") {
|
|
95
152
|
// THE incident pattern: we used to run as X (possibly via an explicit
|
|
96
153
|
// selector), and this boot silently landed on the default profile Y.
|
|
97
154
|
return {
|
|
98
155
|
kind: "gate",
|
|
99
156
|
message:
|
|
100
|
-
`IDENTITY CHANGED after reconnect/restart: previously trusted as "${
|
|
101
|
-
`(via ${
|
|
102
|
-
`"${
|
|
157
|
+
`IDENTITY CHANGED after reconnect/restart: previously trusted as "${safeLastId}" ` +
|
|
158
|
+
`(via ${safeLastSrc}${safeLastDecl ? ` "${safeLastDecl}"` : ""}), but this boot resolved the DEFAULT profile ` +
|
|
159
|
+
`"${safeCurId}". Silent fallback is how wrong-identity posts happen — write actions are REFUSED until identity is confirmed. ` +
|
|
103
160
|
`Run whoami to inspect and confirm, or relaunch with the intended profile selector.`,
|
|
104
161
|
};
|
|
105
162
|
}
|
|
106
163
|
|
|
107
|
-
|
|
164
|
+
const prevSelectorAgent =
|
|
165
|
+
current.declaredName &&
|
|
166
|
+
!isUnsafeSelectorKey(current.declaredName) &&
|
|
167
|
+
Object.hasOwn(prev.bySelector, current.declaredName)
|
|
168
|
+
? prev.bySelector[current.declaredName]
|
|
169
|
+
: undefined;
|
|
170
|
+
if (current.declaredName && typeof prevSelectorAgent === "string" && prevSelectorAgent !== current.agentId) {
|
|
108
171
|
// Same selector, different identity: the profile file behind the selector
|
|
109
172
|
// changed (likely an intentional edit). Loud, but not gated.
|
|
173
|
+
const safeCurDecl = cleanDisplayToken(current.declaredName, 128);
|
|
174
|
+
const safePrevSel = cleanDisplayToken(prevSelectorAgent, 128);
|
|
110
175
|
return {
|
|
111
176
|
kind: "warn",
|
|
112
177
|
message:
|
|
113
|
-
`identity for selector "${
|
|
114
|
-
`now "${
|
|
178
|
+
`identity for selector "${safeCurDecl}" changed: was "${safePrevSel}", ` +
|
|
179
|
+
`now "${safeCurId}". If you edited the profile on purpose, ignore this; if not, investigate before posting.`,
|
|
115
180
|
};
|
|
116
181
|
}
|
|
117
182
|
|
|
@@ -134,7 +199,13 @@ export function advanceGuardRecord(
|
|
|
134
199
|
): IdentityGuardRecord {
|
|
135
200
|
const next: IdentityGuardRecord = { bySelector: { ...prev.bySelector }, lastEffective: prev.lastEffective };
|
|
136
201
|
if (!current.agentId) return next;
|
|
137
|
-
if (current.declaredName
|
|
202
|
+
if (current.declaredName && !isUnsafeSelectorKey(current.declaredName)) {
|
|
203
|
+
if (!Object.hasOwn(next.bySelector, current.declaredName) && Object.keys(next.bySelector).length >= MAX_GUARD_SELECTORS) {
|
|
204
|
+
const oldestKey = Object.keys(next.bySelector)[0];
|
|
205
|
+
if (oldestKey !== undefined) delete next.bySelector[oldestKey];
|
|
206
|
+
}
|
|
207
|
+
next.bySelector[current.declaredName] = current.agentId;
|
|
208
|
+
}
|
|
138
209
|
if (trusted) {
|
|
139
210
|
next.lastEffective = {
|
|
140
211
|
agentId: current.agentId,
|
|
@@ -176,9 +247,11 @@ export const EXPECT_PIN_EXEMPT_TOOLS = new Set(["whoami", "switch_profile", "con
|
|
|
176
247
|
export function expectedAgentIdViolation(expected: string | null, liveAgentId: string): string | null {
|
|
177
248
|
if (!expected) return null;
|
|
178
249
|
if (liveAgentId === expected) return null;
|
|
250
|
+
const safeLive = cleanDisplayToken(liveAgentId, 128) || "(none)";
|
|
251
|
+
const safeExpected = cleanDisplayToken(expected, 128) || "(invalid-pin)";
|
|
179
252
|
return (
|
|
180
|
-
`IDENTITY PIN: this MCP process is "${
|
|
253
|
+
`IDENTITY PIN: this MCP process is "${safeLive}" but AGENTCHAT_EXPECT_AGENT_ID is "${safeExpected}". ` +
|
|
181
254
|
`Write tools are refused so nothing posts under the wrong identity. ` +
|
|
182
|
-
`Call switch_profile with the profile for ${
|
|
255
|
+
`Call switch_profile with the profile for ${safeExpected} (then whoami), or relaunch with the correct --profile / AGENTSCHAT_PROFILE.`
|
|
183
256
|
);
|
|
184
257
|
}
|
package/src/identity.ts
CHANGED
|
@@ -59,14 +59,55 @@ export interface IdentityInputs {
|
|
|
59
59
|
fallbackName: string;
|
|
60
60
|
}
|
|
61
61
|
|
|
62
|
+
import { redactSecrets } from "./redact.ts";
|
|
63
|
+
|
|
64
|
+
const RESERVED_IDENTITY_IDS = new Set(["__proto__", "constructor", "prototype"]);
|
|
65
|
+
const MAX_DISPLAY_NAME_LEN = 128;
|
|
66
|
+
const MAX_AGENT_ID_LEN = 128;
|
|
67
|
+
const MAX_CAPABILITIES_LEN = 64;
|
|
68
|
+
|
|
69
|
+
const CONTROL_OR_SEP_RE = /[\x00-\x1f\x7f-\x9f\u2028\u2029]/;
|
|
70
|
+
|
|
71
|
+
function isValidDisplayName(raw: unknown): raw is string {
|
|
72
|
+
if (typeof raw !== "string" || CONTROL_OR_SEP_RE.test(raw)) return false;
|
|
73
|
+
const trimmed = raw.trim();
|
|
74
|
+
return trimmed.length > 0 && trimmed.length <= MAX_DISPLAY_NAME_LEN && !RESERVED_IDENTITY_IDS.has(trimmed.toLowerCase());
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
function isValidProfileAgentId(raw: unknown): raw is string {
|
|
78
|
+
if (typeof raw !== "string" || /[\x00-\x1f\x7f-\x9f\u2028\u2029/\\\s]/.test(raw) || /(?:%2e|%2f|%5c|%00)/i.test(raw)) return false;
|
|
79
|
+
const trimmed = raw.trim();
|
|
80
|
+
return (
|
|
81
|
+
trimmed.length > 0 &&
|
|
82
|
+
trimmed === raw &&
|
|
83
|
+
trimmed.length <= MAX_AGENT_ID_LEN &&
|
|
84
|
+
trimmed !== "." &&
|
|
85
|
+
!trimmed.includes("..") &&
|
|
86
|
+
!RESERVED_IDENTITY_IDS.has(trimmed.toLowerCase())
|
|
87
|
+
);
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
function sanitizeDiagnosticField(raw: string | undefined, fallback = "(unknown)"): string {
|
|
91
|
+
if (typeof raw !== "string") return fallback;
|
|
92
|
+
const cleaned = redactSecrets(raw)
|
|
93
|
+
.replace(/\b(?:Bearer|Basic)\s+[A-Za-z0-9._~+/=-]{8,}/gi, "[REDACTED]")
|
|
94
|
+
.replace(/\b(?:agent_key_|sk-|whsec_|gh[pousr]_|github_pat_|AIza|(?:AKIA|ASIA))[A-Za-z0-9_+/=.-]{8,}/g, "[REDACTED]")
|
|
95
|
+
.replace(/[\x00-\x1f\x7f-\x9f\u2028\u2029]+/g, " ")
|
|
96
|
+
.trim();
|
|
97
|
+
return cleaned.length > 0 ? cleaned.slice(0, 256) : fallback;
|
|
98
|
+
}
|
|
99
|
+
|
|
62
100
|
export function decideIdentity(i: IdentityInputs): IdentityDecision {
|
|
63
101
|
// An existing profile is authoritative — this is the overwhelmingly common path.
|
|
64
102
|
if (i.profileExists) return { mode: "profile" };
|
|
65
103
|
|
|
104
|
+
const safeProfileFile = sanitizeDiagnosticField(i.profileFile, "(unknown-path)");
|
|
105
|
+
|
|
66
106
|
// A selected existing identity cannot be replaced by credentials or registration
|
|
67
107
|
// flags when its backing file is missing. --name is the separate creation path.
|
|
68
108
|
if (i.source !== "default" && i.source !== "flag-name") {
|
|
69
|
-
|
|
109
|
+
const safeDeclared = sanitizeDiagnosticField(i.declaredName, "(unknown)");
|
|
110
|
+
return { mode: "error", message: `no profile for "${safeDeclared}" at ${safeProfileFile}. Refusing to auto-register or fall back to another identity; repair the selection or use --name <new-name> separately.` };
|
|
70
111
|
}
|
|
71
112
|
|
|
72
113
|
// Credentials handed to us directly: we can authenticate, so there is nothing to
|
|
@@ -75,16 +116,26 @@ export function decideIdentity(i: IdentityInputs): IdentityDecision {
|
|
|
75
116
|
if (i.hasToken) return { mode: "env-creds" };
|
|
76
117
|
|
|
77
118
|
// Explicit opt-in to creating a new account.
|
|
78
|
-
if (i.cliName)
|
|
79
|
-
|
|
119
|
+
if (i.cliName !== undefined) {
|
|
120
|
+
if (!isValidDisplayName(i.cliName)) {
|
|
121
|
+
return { mode: "error", message: `invalid --name value: display name must be 1..${MAX_DISPLAY_NAME_LEN} chars, non-reserved, and free of control characters.` };
|
|
122
|
+
}
|
|
123
|
+
return { mode: "register", displayName: i.cliName.trim() };
|
|
124
|
+
}
|
|
125
|
+
if (i.registerFlag) {
|
|
126
|
+
if (!isValidDisplayName(i.fallbackName)) {
|
|
127
|
+
return { mode: "error", message: `invalid fallback display name for --register.` };
|
|
128
|
+
}
|
|
129
|
+
return { mode: "register", displayName: i.fallbackName.trim() };
|
|
130
|
+
}
|
|
80
131
|
|
|
81
132
|
// An identity was named but no profile backs it. Do NOT invent one.
|
|
82
133
|
if (i.source !== "default") {
|
|
83
|
-
const name = i.declaredName ?? i.cliName
|
|
134
|
+
const name = sanitizeDiagnosticField(i.declaredName ?? i.cliName, "(unknown)");
|
|
84
135
|
return {
|
|
85
136
|
mode: "error",
|
|
86
137
|
message:
|
|
87
|
-
`no profile for "${name}" at ${
|
|
138
|
+
`no profile for "${name}" at ${safeProfileFile}.\n` +
|
|
88
139
|
` Refusing to auto-register — that creates a real account under a name you did not choose.\n` +
|
|
89
140
|
` Use an existing profile: --profile <name> (or AGENTSCHAT_PROFILE=<name>)\n` +
|
|
90
141
|
` Register a NEW agent: --name <new-name> (or --register)\n` +
|
|
@@ -98,7 +149,7 @@ export function decideIdentity(i: IdentityInputs): IdentityDecision {
|
|
|
98
149
|
reason:
|
|
99
150
|
`no agent identity configured — running ANONYMOUS (tools are listed; any call needing auth will fail).\n` +
|
|
100
151
|
` Refusing to auto-register: it would create a real account and persist its\n` +
|
|
101
|
-
` credentials to the shared default profile (${
|
|
152
|
+
` credentials to the shared default profile (${safeProfileFile}), which every later\n` +
|
|
102
153
|
` identity-less session would then load as its own.\n` +
|
|
103
154
|
` To fix: --name <your-agent> register a new agent\n` +
|
|
104
155
|
` --profile <name> use an existing profile (or AGENTSCHAT_PROFILE=<name>)\n` +
|
|
@@ -108,13 +159,18 @@ export function decideIdentity(i: IdentityInputs): IdentityDecision {
|
|
|
108
159
|
|
|
109
160
|
/** Validate effective credentials without including credential values in errors. */
|
|
110
161
|
export function validateIdentityProfile(profile: any, file: string, allowDevToken = false): void {
|
|
111
|
-
const
|
|
162
|
+
const cleanNonempty = (value: unknown): value is string =>
|
|
163
|
+
typeof value === "string" && value.trim().length > 0 && value.length <= 4096 && !CONTROL_OR_SEP_RE.test(value);
|
|
164
|
+
const safeFile = sanitizeDiagnosticField(file, "(unknown-path)");
|
|
112
165
|
if (!profile || typeof profile !== "object" || Array.isArray(profile) ||
|
|
113
|
-
|
|
114
|
-
(
|
|
166
|
+
Object.prototype.hasOwnProperty.call(profile, "__proto__") ||
|
|
167
|
+
!isValidProfileAgentId(profile.agent_id) ||
|
|
168
|
+
!cleanNonempty(profile.token) ||
|
|
169
|
+
(!allowDevToken && profile.token.trim() === "dev-token") ||
|
|
115
170
|
(profile.capabilities !== undefined && (!Array.isArray(profile.capabilities) ||
|
|
116
|
-
|
|
117
|
-
|
|
171
|
+
profile.capabilities.length > MAX_CAPABILITIES_LEN ||
|
|
172
|
+
!profile.capabilities.every((c: unknown) => cleanNonempty(c) && (c as string).length <= 64)))) {
|
|
173
|
+
throw new Error(`Invalid identity profile at ${safeFile}. Use --profile <valid-name>, or provide a paired --id / AGENTCHAT_AGENT_ID and --token / AGENTCHAT_TOKEN; token must not be empty or dev-token and capabilities must be a string array.`);
|
|
118
174
|
}
|
|
119
175
|
}
|
|
120
176
|
|
package/src/mentions.ts
CHANGED
|
@@ -14,10 +14,31 @@
|
|
|
14
14
|
* Extracted from server.ts so it can be unit-tested without loading the
|
|
15
15
|
* side-effecting server entrypoint (which opens a WebSocket on import).
|
|
16
16
|
*/
|
|
17
|
+
const MAX_MENTION_ID_CHARS = 128;
|
|
18
|
+
const MAX_MENTION_CONTENT_CHARS = 100_000;
|
|
19
|
+
const PROTOTYPE_MENTION_IDS = new Set(["__proto__", "constructor", "prototype"]);
|
|
20
|
+
|
|
17
21
|
export function matchesMention(content: string, agentId: string): boolean {
|
|
18
|
-
if (
|
|
19
|
-
if (
|
|
20
|
-
const
|
|
21
|
-
|
|
22
|
-
|
|
22
|
+
if (typeof content !== "string" || typeof agentId !== "string") return false;
|
|
23
|
+
if (/[\x00-\x1f\x7f-\x9f\u2028\u2029]/.test(agentId)) return false;
|
|
24
|
+
const trimmedId = agentId.trim();
|
|
25
|
+
if (
|
|
26
|
+
!content ||
|
|
27
|
+
!trimmedId ||
|
|
28
|
+
trimmedId.length > MAX_MENTION_ID_CHARS ||
|
|
29
|
+
trimmedId === "." ||
|
|
30
|
+
trimmedId === ".." ||
|
|
31
|
+
/[\/\\\s\x00-\x1f\x7f-\x9f\u2028\u2029]/.test(trimmedId) ||
|
|
32
|
+
PROTOTYPE_MENTION_IDS.has(trimmedId.toLowerCase())
|
|
33
|
+
) {
|
|
34
|
+
return false;
|
|
35
|
+
}
|
|
36
|
+
const hay = content.length > MAX_MENTION_CONTENT_CHARS ? content.slice(0, MAX_MENTION_CONTENT_CHARS) : content;
|
|
37
|
+
const idEsc = trimmedId.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
38
|
+
const bareMentionRe = new RegExp(`(?<![A-Za-z0-9_])@${idEsc}(?![A-Za-z0-9_-]|\\.[A-Za-z0-9])`);
|
|
39
|
+
if (bareMentionRe.test(hay)) return true;
|
|
40
|
+
const displayMentionRe = new RegExp(
|
|
41
|
+
`(?<![A-Za-z0-9_])@[^\\s(@,:;<>"'\\x60\\n]+(?: [^\\s(@,:;<>"'\\x60\\n]+){0,4}\\(${idEsc}\\)`,
|
|
42
|
+
);
|
|
43
|
+
return displayMentionRe.test(hay);
|
|
23
44
|
}
|
package/src/onboarding-status.ts
CHANGED
|
@@ -2,25 +2,148 @@ export interface OnboardingStatus {
|
|
|
2
2
|
agent_id: string; claimed: boolean | null; authentication: "ok" | "failed" | "unknown";
|
|
3
3
|
chat_url: string; claim_url: string; next_step: "join_public_chat" | "verify_reply" | "check_identity";
|
|
4
4
|
}
|
|
5
|
+
const DEFAULT_PUBLIC_BASE = "https://agents-chat.com";
|
|
6
|
+
|
|
7
|
+
function isForbiddenMetadataOrLinkLocalHost(host: string): boolean {
|
|
8
|
+
if (
|
|
9
|
+
host === "metadata" ||
|
|
10
|
+
host === "instance-data" ||
|
|
11
|
+
host === "metadata.google.internal" ||
|
|
12
|
+
host.endsWith(".metadata.google.internal") ||
|
|
13
|
+
host === "metadata.goog" ||
|
|
14
|
+
host.endsWith(".metadata.goog") ||
|
|
15
|
+
host === "169.254.169.254" ||
|
|
16
|
+
host === "100.100.100.200" ||
|
|
17
|
+
host === "0.0.0.0"
|
|
18
|
+
) {
|
|
19
|
+
return true;
|
|
20
|
+
}
|
|
21
|
+
if (/^\d+\.\d+\.\d+\.\d+$/.test(host)) {
|
|
22
|
+
const [a, b] = host.split(".").map(Number);
|
|
23
|
+
if (a === 0 || (a === 169 && b === 254)) return true;
|
|
24
|
+
}
|
|
25
|
+
if (host.startsWith("[") && host.endsWith("]")) {
|
|
26
|
+
const inner = host.slice(1, -1).toLowerCase();
|
|
27
|
+
if (
|
|
28
|
+
inner === "::" ||
|
|
29
|
+
inner === "0:0:0:0:0:0:0:0" ||
|
|
30
|
+
inner === "fd00:ec2::254" ||
|
|
31
|
+
/^fe[89ab][0-9a-f]*:/i.test(inner)
|
|
32
|
+
) {
|
|
33
|
+
return true;
|
|
34
|
+
}
|
|
35
|
+
if (/^::ffff:(?:0:)?(?:0\.0\.0\.0|0:[0-9a-f]{1,4}$|169\.254\.|a9fe:|100\.100\.100\.200$|6464:64c8$)/i.test(inner)) {
|
|
36
|
+
return true;
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
return false;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
function isSafeOnboardingBase(base: string): boolean {
|
|
43
|
+
try {
|
|
44
|
+
if (!base || base !== base.trim() || /[\x00-\x20\x7f-\x9f\u2028\u2029"<>\\]/.test(base)) return false;
|
|
45
|
+
if (/:0(?:\/|$)/.test(base)) return false;
|
|
46
|
+
const parsed = new URL(base);
|
|
47
|
+
const host = parsed.hostname.toLowerCase().replace(/\.$/, "");
|
|
48
|
+
if (!host || isForbiddenMetadataOrLinkLocalHost(host)) return false;
|
|
49
|
+
if (parsed.port !== "") {
|
|
50
|
+
const p = Number(parsed.port);
|
|
51
|
+
if (!Number.isInteger(p) || p < 1 || p > 65535) return false;
|
|
52
|
+
}
|
|
53
|
+
const isLoopback = host === "127.0.0.1" || host === "localhost" || host === "[::1]" || host === "::1";
|
|
54
|
+
if (parsed.protocol !== "https:" && !(parsed.protocol === "http:" && isLoopback)) return false;
|
|
55
|
+
if (parsed.username || parsed.password || parsed.search || parsed.hash) return false;
|
|
56
|
+
return true;
|
|
57
|
+
} catch {
|
|
58
|
+
return false;
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
function isSafeOnboardingAgentId(id: string): boolean {
|
|
63
|
+
if (!id || id.length > 128 || /[\x00-\x1f\x7f-\x9f\u2028\u2029\s/\\]/.test(id)) return false;
|
|
64
|
+
if (id === "." || id.includes("..")) return false;
|
|
65
|
+
const lower = id.toLowerCase();
|
|
66
|
+
if (lower === "__proto__" || lower === "constructor" || lower === "prototype") return false;
|
|
67
|
+
return true;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
const MAX_ONBOARDING_JSON_BYTES = 64 * 1024;
|
|
71
|
+
|
|
72
|
+
async function readBoundedJson(r: Response, maxBytes = MAX_ONBOARDING_JSON_BYTES): Promise<unknown> {
|
|
73
|
+
const rawContentLen = r.headers?.get?.("content-length");
|
|
74
|
+
if (rawContentLen !== null && rawContentLen !== undefined && rawContentLen.trim() !== "") {
|
|
75
|
+
const trimmedLen = rawContentLen.trim();
|
|
76
|
+
if (!/^\d+$/.test(trimmedLen) || Number(trimmedLen) > maxBytes) {
|
|
77
|
+
try { await r.body?.cancel?.(); } catch {}
|
|
78
|
+
throw new Error("onboarding response too large");
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
if (!r.body) {
|
|
82
|
+
const txt = await r.text();
|
|
83
|
+
if (Buffer.byteLength(txt, "utf8") > maxBytes) throw new Error("onboarding response too large");
|
|
84
|
+
return JSON.parse(txt);
|
|
85
|
+
}
|
|
86
|
+
const reader = r.body.getReader();
|
|
87
|
+
const chunks: Uint8Array[] = [];
|
|
88
|
+
let total = 0;
|
|
89
|
+
try {
|
|
90
|
+
while (true) {
|
|
91
|
+
const { done, value } = await reader.read();
|
|
92
|
+
if (done) break;
|
|
93
|
+
if (value) {
|
|
94
|
+
total += value.byteLength;
|
|
95
|
+
if (total > maxBytes) {
|
|
96
|
+
await reader.cancel().catch(() => {});
|
|
97
|
+
throw new Error("onboarding response too large");
|
|
98
|
+
}
|
|
99
|
+
chunks.push(value);
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
} finally {
|
|
103
|
+
try { reader.releaseLock(); } catch {}
|
|
104
|
+
}
|
|
105
|
+
return JSON.parse(Buffer.concat(chunks).toString("utf8"));
|
|
106
|
+
}
|
|
107
|
+
|
|
5
108
|
export async function getOnboardingStatus(base: string, agentId: string, token: string, request: (url: string, options: RequestInit) => Promise<Response> = fetch): Promise<OnboardingStatus> {
|
|
6
|
-
const
|
|
7
|
-
const
|
|
109
|
+
const cleanBase = typeof base === "string" ? base.trim().replace(/\/+$/, "") : "";
|
|
110
|
+
const rawAgentId = typeof agentId === "string" ? agentId.trim() : "";
|
|
111
|
+
const validAgent = isSafeOnboardingAgentId(rawAgentId);
|
|
112
|
+
const safeAgentId = validAgent ? rawAgentId : "";
|
|
113
|
+
const validBase = Boolean(cleanBase && !/[\x00-\x1f\x7f-\x9f\u2028\u2029]/.test(cleanBase) && isSafeOnboardingBase(cleanBase));
|
|
114
|
+
const safeDisplayBase = validBase ? cleanBase : DEFAULT_PUBLIC_BASE;
|
|
115
|
+
const chat = `${safeDisplayBase}/chat/${encodeURIComponent(safeAgentId)}`;
|
|
116
|
+
const result: OnboardingStatus = {agent_id: safeAgentId, claimed: null, authentication: "unknown", chat_url: chat,
|
|
8
117
|
claim_url: `${chat}?claim=1`, next_step: "check_identity"};
|
|
118
|
+
if (!validBase || !validAgent ||
|
|
119
|
+
typeof token !== "string" || !token.trim() || /[\x00-\x1f\x7f-\x9f\u2028\u2029]/.test(token)) {
|
|
120
|
+
return result;
|
|
121
|
+
}
|
|
9
122
|
try {
|
|
10
|
-
const r = await request(`${
|
|
11
|
-
headers: {Authorization: `Bearer ${token}`}, cache: "no-store", signal: AbortSignal.timeout(8000), redirect: "error",
|
|
123
|
+
const r = await request(`${cleanBase}/api/account/onboarding`, {
|
|
124
|
+
headers: {Authorization: `Bearer ${token.trim()}`}, cache: "no-store", signal: AbortSignal.timeout(8000), redirect: "error",
|
|
12
125
|
});
|
|
13
|
-
if (r.status === 401 || r.status === 403) {
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
126
|
+
if (r.status === 401 || r.status === 403) {
|
|
127
|
+
try { await r.body?.cancel?.(); } catch {}
|
|
128
|
+
result.authentication = "failed";
|
|
129
|
+
return result;
|
|
130
|
+
}
|
|
131
|
+
if (!r.ok) {
|
|
132
|
+
try { await r.body?.cancel?.(); } catch {}
|
|
133
|
+
return result;
|
|
134
|
+
}
|
|
135
|
+
const data = await readBoundedJson(r) as any;
|
|
136
|
+
if (!data || typeof data !== "object" || Array.isArray(data) || Object.prototype.hasOwnProperty.call(data, "__proto__") || data.agent_id !== safeAgentId || typeof data.claimed !== "boolean") return result;
|
|
17
137
|
result.authentication = "ok"; result.claimed = data.claimed;
|
|
18
138
|
result.next_step = data.claimed ? "verify_reply" : "join_public_chat";
|
|
19
139
|
} catch { /* Network/unsupported endpoint is unknown, never unclaimed. */ }
|
|
20
140
|
return result;
|
|
21
141
|
}
|
|
22
142
|
export function claimSummary(status: OnboardingStatus): string {
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
143
|
+
const safeClaimUrl = typeof status?.claim_url === "string"
|
|
144
|
+
? status.claim_url.replace(/[\x00-\x1f\x7f-\x9f\u2028\u2029]+/g, "").slice(0, 512)
|
|
145
|
+
: "";
|
|
146
|
+
if (status?.claimed === true) return "Claimed: yes — verify an actual message/reply in the authorized conversation before marking setup complete.";
|
|
147
|
+
if (status?.claimed === false) return `Claimed: NO — public group chat can proceed within the authorized scope and service limits. Claiming unlocks DMs, private channels and owner features: open ${safeClaimUrl} and enter the token from your private profile.`;
|
|
148
|
+
return `Claimed: unknown — ownership could not be verified. Check the service and account; do not register a replacement. Claim entry: ${safeClaimUrl}`;
|
|
26
149
|
}
|