@camstack/develop 0.1.39 → 0.1.41

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.
@@ -0,0 +1,163 @@
1
+ export const FINDING_CODES = [
2
+ 'ZERO_MEDIA',
3
+ 'MISSING_FIRSTFRAME',
4
+ 'MISSING_LASTFRAME',
5
+ 'MISSING_THUMBNAIL',
6
+ 'FF_EQ_LF',
7
+ 'LASTFRAME_STALE',
8
+ 'MEDIA_STOPPED_EARLY',
9
+ 'BEST_SHOT_STALE',
10
+ 'BEST_AT_EDGE',
11
+ 'ENDED_MID_FRAME',
12
+ 'FRAGMENT_SUSPECT',
13
+ 'FACE_EXPECTED_MISSING',
14
+ 'PLATE_EXPECTED_MISSING',
15
+ 'MEDIA_UNREADABLE',
16
+ 'DEVICE_AUDIT_ERROR',
17
+ ];
18
+ export const THRESHOLDS = {
19
+ lastFrameStaleMs: 2_000,
20
+ mediaCoverageMin: 0.5,
21
+ longTrackMs: 5_000,
22
+ betterShotRatio: 1.5,
23
+ edgeFraction: 0.01,
24
+ faceMinTrackMs: 3_000,
25
+ plateMinTrackMs: 2_000,
26
+ fragmentMaxMs: 1_500,
27
+ fragmentNeighborWindowMs: 15_000,
28
+ };
29
+ /** Native sensor width the face-size estimate scales to (4K). */
30
+ const NATIVE_WIDTH_PX = 3_840;
31
+ /** Rough facial height as a fraction of a standing person's bbox height. */
32
+ const FACE_FRACTION_DENOMINATOR = 7;
33
+ export const isSynthetic = (t) => t.trackId.startsWith('pa-synth-') ||
34
+ t.source === 'synthetic' ||
35
+ t.source === 'sensor' ||
36
+ t.className === 'switch';
37
+ /** Detection-grid dimensions, estimated from positions and the normalised envelope. */
38
+ export function frameDims(track) {
39
+ let maxX = 0;
40
+ let maxY = 0;
41
+ for (const p of track.positions) {
42
+ maxX = Math.max(maxX, p.bbox.x + p.bbox.w);
43
+ maxY = Math.max(maxY, p.bbox.y + p.bbox.h);
44
+ }
45
+ const env = track.envelope;
46
+ const W = env?.maxX !== undefined && env.maxX > 0.05 ? maxX / env.maxX : Math.max(640, maxX);
47
+ const H = env?.maxY !== undefined && env.maxY > 0.05 ? maxY / env.maxY : Math.max(360, maxY);
48
+ return { W, H };
49
+ }
50
+ export function touchesEdge(b, W, H) {
51
+ const f = THRESHOLDS.edgeFraction;
52
+ return b.x <= W * f || b.y <= H * f || b.x + b.w >= W * (1 - f) || b.y + b.h >= H * (1 - f);
53
+ }
54
+ const seconds = (ms) => (ms / 1000).toFixed(1);
55
+ function faceVerdict(track, W, dur) {
56
+ const maxH = Math.max(...track.positions.map((p) => p.bbox.h), 0);
57
+ const detPx = maxH / FACE_FRACTION_DENOMINATOR;
58
+ const nativePx = detPx * (NATIVE_WIDTH_PX / W);
59
+ const verdict = nativePx >= 60
60
+ ? 'UNEXPECTED — well above native gate, investigate detector/step'
61
+ : nativePx >= 30
62
+ ? 'borderline vs native gate'
63
+ : 'likely below native gate (expected miss)';
64
+ return `no face held for ${seconds(dur)}s; est. face ~${detPx.toFixed(0)}px detection-space (~${nativePx.toFixed(0)}px native) — ${verdict}`;
65
+ }
66
+ /** The audit rules for one track. Pure: same input, same findings. */
67
+ export function analyzeTrack(input) {
68
+ const { track, media } = input;
69
+ const findings = [];
70
+ const flag = (code, detail) => {
71
+ findings.push({
72
+ deviceId: track.deviceId,
73
+ trackId: track.trackId,
74
+ className: track.className,
75
+ code,
76
+ detail,
77
+ });
78
+ };
79
+ if (media === null) {
80
+ flag('MEDIA_UNREADABLE', 'media index could not be read — media findings are unknown, not absent');
81
+ return findings;
82
+ }
83
+ const dur = track.lastSeen - track.firstSeen;
84
+ const pos = track.positions;
85
+ const { W, H } = frameDims(track);
86
+ const closed = track.active !== true;
87
+ const ofKind = (kind) => media.find((m) => m.kind === kind);
88
+ const ff = ofKind('firstFrame');
89
+ const lf = ofKind('lastFrame');
90
+ const thumb = ofKind('thumbnail');
91
+ if (media.length === 0)
92
+ flag('ZERO_MEDIA', `dur=${dur}ms positions=${pos.length} state=${track.state}`);
93
+ if (closed && media.length > 0) {
94
+ if (!ff)
95
+ flag('MISSING_FIRSTFRAME', `dur=${dur}ms media=${media.length}`);
96
+ if (!lf)
97
+ flag('MISSING_LASTFRAME', `dur=${dur}ms media=${media.length}`);
98
+ if (!thumb)
99
+ flag('MISSING_THUMBNAIL', `dur=${dur}ms media=${media.length}`);
100
+ }
101
+ if (input.ffEqualsLf === true)
102
+ flag('FF_EQ_LF', 'firstFrame and lastFrame byte-identical');
103
+ if (closed && lf && track.lastSeen - lf.timestamp > THRESHOLDS.lastFrameStaleMs) {
104
+ flag('LASTFRAME_STALE', `lastFrame ${seconds(track.lastSeen - lf.timestamp)}s before close`);
105
+ }
106
+ if (closed && dur >= THRESHOLDS.longTrackMs && media.length > 0) {
107
+ const lastMediaTs = Math.max(...media.map((m) => m.timestamp));
108
+ const coverage = (lastMediaTs - track.firstSeen) / dur;
109
+ if (coverage < THRESHOLDS.mediaCoverageMin) {
110
+ flag('MEDIA_STOPPED_EARLY', `captures ceased at ${(coverage * 100).toFixed(0)}% of a ${seconds(dur)}s track`);
111
+ }
112
+ }
113
+ if (thumb && pos.length > 2) {
114
+ const atThumb = pos.reduce((best, p) => Math.abs(p.timestamp - thumb.timestamp) < Math.abs(best.timestamp - thumb.timestamp)
115
+ ? p
116
+ : best);
117
+ const areaAtThumb = atThumb.bbox.w * atThumb.bbox.h;
118
+ if (touchesEdge(atThumb.bbox, W, H)) {
119
+ flag('BEST_AT_EDGE', `bbox ${JSON.stringify(atThumb.bbox)} touches frame edge at capture (grid ~${W.toFixed(0)}x${H.toFixed(0)}) — letterbox/cut risk`);
120
+ }
121
+ let better = null;
122
+ for (const p of pos) {
123
+ if (p.timestamp <= thumb.timestamp)
124
+ continue;
125
+ const area = p.bbox.w * p.bbox.h;
126
+ if (area >= areaAtThumb * THRESHOLDS.betterShotRatio && !touchesEdge(p.bbox, W, H)) {
127
+ if (!better || area > better.area)
128
+ better = { area, at: p.timestamp };
129
+ }
130
+ }
131
+ if (better) {
132
+ flag('BEST_SHOT_STALE', `thumbnail@+${seconds(thumb.timestamp - track.firstSeen)}s area=${areaAtThumb.toFixed(0)}; in-frame area=${better.area.toFixed(0)} (${(better.area / areaAtThumb).toFixed(1)}x) existed @+${seconds(better.at - track.firstSeen)}s`);
133
+ }
134
+ }
135
+ if (closed && pos.length > 2) {
136
+ const last = pos[pos.length - 1];
137
+ if (!touchesEdge(last.bbox, W, H) && dur >= THRESHOLDS.fragmentMaxMs) {
138
+ flag('ENDED_MID_FRAME', `last bbox ${JSON.stringify(last.bbox)} well inside ~${W.toFixed(0)}x${H.toFixed(0)} — early loss suspect (dur=${seconds(dur)}s)`);
139
+ }
140
+ }
141
+ if (closed && dur <= THRESHOLDS.fragmentMaxMs && track.state === 'entered') {
142
+ const sibling = input.siblings.find((o) => o.trackId !== track.trackId &&
143
+ o.className === track.className &&
144
+ Math.abs(o.firstSeen - track.lastSeen) <= THRESHOLDS.fragmentNeighborWindowMs);
145
+ flag('FRAGMENT_SUSPECT', `dur=${dur}ms never confirmed${sibling ? `; same-class sibling ${sibling.trackId.slice(0, 8)} within ${THRESHOLDS.fragmentNeighborWindowMs / 1000}s` : ''}`);
146
+ }
147
+ if (input.enrichment.face === 'missing')
148
+ flag('FACE_EXPECTED_MISSING', faceVerdict(track, W, dur));
149
+ if (input.enrichment.plate === 'missing') {
150
+ flag('PLATE_EXPECTED_MISSING', `no plate for ${seconds(dur)}s vehicle track`);
151
+ }
152
+ return findings;
153
+ }
154
+ export function qualifiesForFace(track, faceDevices) {
155
+ return (track.className === 'person' &&
156
+ faceDevices.has(track.deviceId) &&
157
+ track.lastSeen - track.firstSeen >= THRESHOLDS.faceMinTrackMs);
158
+ }
159
+ export function qualifiesForPlate(track, plateDevices) {
160
+ return (track.className === 'vehicle' &&
161
+ plateDevices.has(track.deviceId) &&
162
+ track.lastSeen - track.firstSeen >= THRESHOLDS.plateMinTrackMs);
163
+ }
@@ -0,0 +1,61 @@
1
+ /**
2
+ * The slices of hub payloads the ops tools actually read, validated at the
3
+ * boundary (a hub answer is external data). Loose objects: fields we do not name
4
+ * are carried, not rejected — the hub adds fields faster than this file.
5
+ */
6
+ import { z } from 'zod';
7
+ export interface TrackBBox {
8
+ x: number;
9
+ y: number;
10
+ w: number;
11
+ h: number;
12
+ }
13
+ export interface TrackPosition {
14
+ timestamp: number;
15
+ bbox: TrackBBox;
16
+ }
17
+ export interface TrackEnvelope {
18
+ maxX?: number;
19
+ maxY?: number;
20
+ }
21
+ export interface Track {
22
+ trackId: string;
23
+ deviceId: number;
24
+ className: string;
25
+ source?: string;
26
+ firstSeen: number;
27
+ lastSeen: number;
28
+ state?: string;
29
+ active?: boolean;
30
+ positions: TrackPosition[];
31
+ envelope?: TrackEnvelope;
32
+ }
33
+ export declare const TrackSchema: z.ZodType<Track>;
34
+ export interface RecentTracksPage {
35
+ tracks: Track[];
36
+ nextCursor?: string | null;
37
+ }
38
+ export declare const RecentTracksPageSchema: z.ZodType<RecentTracksPage>;
39
+ export interface MediaInfo {
40
+ mediaId: number;
41
+ kind: string;
42
+ sizeBytes: number;
43
+ timestamp: number;
44
+ }
45
+ export declare const MediaInfoSchema: z.ZodType<MediaInfo>;
46
+ export interface MediaWithBytes extends MediaInfo {
47
+ base64?: string;
48
+ }
49
+ export declare const MediaWithBytesSchema: z.ZodType<MediaWithBytes>;
50
+ export declare const CameraStatusSchema: z.ZodType<{
51
+ deviceId: number;
52
+ }>;
53
+ export interface LogDestinationProvider {
54
+ addonId: string;
55
+ isActive?: boolean;
56
+ mode?: string;
57
+ }
58
+ export declare const LogDestinationProviderSchema: z.ZodType<LogDestinationProvider>;
59
+ /** Parse a hub answer, naming the method on failure instead of throwing a bare zod dump. */
60
+ export declare function parseWire<S extends z.ZodType>(schema: S, value: unknown, label: string): z.infer<S>;
61
+ //# sourceMappingURL=wire.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"wire.d.ts","sourceRoot":"","sources":["../../../src/mcp/ops/wire.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAA;AASvB,MAAM,WAAW,SAAS;IACxB,CAAC,EAAE,MAAM,CAAA;IACT,CAAC,EAAE,MAAM,CAAA;IACT,CAAC,EAAE,MAAM,CAAA;IACT,CAAC,EAAE,MAAM,CAAA;CACV;AAED,MAAM,WAAW,aAAa;IAC5B,SAAS,EAAE,MAAM,CAAA;IACjB,IAAI,EAAE,SAAS,CAAA;CAChB;AAED,MAAM,WAAW,aAAa;IAC5B,IAAI,CAAC,EAAE,MAAM,CAAA;IACb,IAAI,CAAC,EAAE,MAAM,CAAA;CACd;AAED,MAAM,WAAW,KAAK;IACpB,OAAO,EAAE,MAAM,CAAA;IACf,QAAQ,EAAE,MAAM,CAAA;IAChB,SAAS,EAAE,MAAM,CAAA;IACjB,MAAM,CAAC,EAAE,MAAM,CAAA;IACf,SAAS,EAAE,MAAM,CAAA;IACjB,QAAQ,EAAE,MAAM,CAAA;IAChB,KAAK,CAAC,EAAE,MAAM,CAAA;IACd,MAAM,CAAC,EAAE,OAAO,CAAA;IAChB,SAAS,EAAE,aAAa,EAAE,CAAA;IAC1B,QAAQ,CAAC,EAAE,aAAa,CAAA;CACzB;AAsBD,eAAO,MAAM,WAAW,EAAE,CAAC,CAAC,OAAO,CAAC,KAAK,CAAe,CAAA;AAExD,MAAM,WAAW,gBAAgB;IAC/B,MAAM,EAAE,KAAK,EAAE,CAAA;IACf,UAAU,CAAC,EAAE,MAAM,GAAG,IAAI,CAAA;CAC3B;AAED,eAAO,MAAM,sBAAsB,EAAE,CAAC,CAAC,OAAO,CAAC,gBAAgB,CAG7D,CAAA;AAEF,MAAM,WAAW,SAAS;IACxB,OAAO,EAAE,MAAM,CAAA;IACf,IAAI,EAAE,MAAM,CAAA;IACZ,SAAS,EAAE,MAAM,CAAA;IACjB,SAAS,EAAE,MAAM,CAAA;CAClB;AAQD,eAAO,MAAM,eAAe,EAAE,CAAC,CAAC,OAAO,CAAC,SAAS,CAAmB,CAAA;AAEpE,MAAM,WAAW,cAAe,SAAQ,SAAS;IAC/C,MAAM,CAAC,EAAE,MAAM,CAAA;CAChB;AAED,eAAO,MAAM,oBAAoB,EAAE,CAAC,CAAC,OAAO,CAAC,cAAc,CAEzD,CAAA;AAEF,eAAO,MAAM,kBAAkB,EAAE,CAAC,CAAC,OAAO,CAAC;IAAE,QAAQ,EAAE,MAAM,CAAA;CAAE,CAE7D,CAAA;AAEF,MAAM,WAAW,sBAAsB;IACrC,OAAO,EAAE,MAAM,CAAA;IACf,QAAQ,CAAC,EAAE,OAAO,CAAA;IAClB,IAAI,CAAC,EAAE,MAAM,CAAA;CACd;AAED,eAAO,MAAM,4BAA4B,EAAE,CAAC,CAAC,OAAO,CAAC,sBAAsB,CAIzE,CAAA;AAEF,4FAA4F;AAC5F,wBAAgB,SAAS,CAAC,CAAC,SAAS,CAAC,CAAC,OAAO,EAC3C,MAAM,EAAE,CAAC,EACT,KAAK,EAAE,OAAO,EACd,KAAK,EAAE,MAAM,GACZ,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,CAWZ"}
@@ -0,0 +1,66 @@
1
+ /**
2
+ * The slices of hub payloads the ops tools actually read, validated at the
3
+ * boundary (a hub answer is external data). Loose objects: fields we do not name
4
+ * are carried, not rejected — the hub adds fields faster than this file.
5
+ */
6
+ import { z } from 'zod';
7
+ const BBoxSchema = z.object({
8
+ x: z.number(),
9
+ y: z.number(),
10
+ w: z.number(),
11
+ h: z.number(),
12
+ });
13
+ const trackSchema = z.looseObject({
14
+ trackId: z.string(),
15
+ deviceId: z.number(),
16
+ className: z.string(),
17
+ source: z.string().optional(),
18
+ firstSeen: z.number(),
19
+ lastSeen: z.number(),
20
+ state: z.string().optional(),
21
+ active: z.boolean().optional(),
22
+ positions: z
23
+ .array(z.looseObject({ timestamp: z.number(), bbox: BBoxSchema }))
24
+ .optional()
25
+ .default([]),
26
+ envelope: z
27
+ .looseObject({
28
+ maxX: z.number().optional(),
29
+ maxY: z.number().optional(),
30
+ })
31
+ .optional(),
32
+ });
33
+ export const TrackSchema = trackSchema;
34
+ export const RecentTracksPageSchema = z.looseObject({
35
+ tracks: z.array(trackSchema),
36
+ nextCursor: z.string().nullable().optional(),
37
+ });
38
+ const mediaInfoSchema = z.looseObject({
39
+ mediaId: z.number(),
40
+ kind: z.string(),
41
+ sizeBytes: z.number(),
42
+ timestamp: z.number(),
43
+ });
44
+ export const MediaInfoSchema = mediaInfoSchema;
45
+ export const MediaWithBytesSchema = mediaInfoSchema.extend({
46
+ base64: z.string().optional(),
47
+ });
48
+ export const CameraStatusSchema = z.looseObject({
49
+ deviceId: z.number(),
50
+ });
51
+ export const LogDestinationProviderSchema = z.looseObject({
52
+ addonId: z.string(),
53
+ isActive: z.boolean().optional(),
54
+ mode: z.string().optional(),
55
+ });
56
+ /** Parse a hub answer, naming the method on failure instead of throwing a bare zod dump. */
57
+ export function parseWire(schema, value, label) {
58
+ const result = schema.safeParse(value);
59
+ if (!result.success) {
60
+ throw new Error(`${label}: unexpected answer shape (${result.error.issues
61
+ .slice(0, 3)
62
+ .map((i) => `${i.path.join('.')}: ${i.message}`)
63
+ .join('; ')}) — the hub and this tool may be on different versions`);
64
+ }
65
+ return result.data;
66
+ }
@@ -0,0 +1,16 @@
1
+ /**
2
+ * The gate every ops call passes before a byte leaves the machine:
3
+ * query-only, tier-checked, and never a credential-bearing method.
4
+ */
5
+ import type { CredentialTier } from '../hub/credentials.js';
6
+ import type { ApiIndex, ApiMethod } from './api-index.js';
7
+ export type GateDecision = {
8
+ readonly allowed: true;
9
+ readonly method: ApiMethod;
10
+ } | {
11
+ readonly allowed: false;
12
+ readonly reason: string;
13
+ };
14
+ export declare function isSecretBearing(methodPath: string): boolean;
15
+ export declare function gateQuery(index: ApiIndex, methodPath: string, tier: CredentialTier): GateDecision;
16
+ //# sourceMappingURL=query-gate.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"query-gate.d.ts","sourceRoot":"","sources":["../../src/mcp/query-gate.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,uBAAuB,CAAA;AAC3D,OAAO,KAAK,EAAE,QAAQ,EAAE,SAAS,EAAE,MAAM,gBAAgB,CAAA;AAEzD,MAAM,MAAM,YAAY,GACpB;IAAE,QAAQ,CAAC,OAAO,EAAE,IAAI,CAAC;IAAC,QAAQ,CAAC,MAAM,EAAE,SAAS,CAAA;CAAE,GACtD;IAAE,QAAQ,CAAC,OAAO,EAAE,KAAK,CAAC;IAAC,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAA;CAAE,CAAA;AAWxD,wBAAgB,eAAe,CAAC,UAAU,EAAE,MAAM,GAAG,OAAO,CAI3D;AAED,wBAAgB,SAAS,CAAC,KAAK,EAAE,QAAQ,EAAE,UAAU,EAAE,MAAM,EAAE,IAAI,EAAE,cAAc,GAAG,YAAY,CA2BjG"}
@@ -0,0 +1,42 @@
1
+ /**
2
+ * Methods that return secret material even though they are `query` and
3
+ * admin-gated: the keychain's plaintext resolver and reveal, a camera's
4
+ * credentials, anything named for a secret. The ops toolset never reads them
5
+ * (D783: a tool, like a log line, is not a place a secret may land).
6
+ */
7
+ const SECRET_BEARING_ROUTERS = new Set(['keychain', 'keychainAdmin']);
8
+ const SECRET_BEARING_NAME = /secret|password|passphrase|recoverykey|reveal|getcredentials|jwt/i;
9
+ export function isSecretBearing(methodPath) {
10
+ const [router = '', ...rest] = methodPath.split('.');
11
+ if (SECRET_BEARING_ROUTERS.has(router))
12
+ return true;
13
+ return SECRET_BEARING_NAME.test(rest.join('.'));
14
+ }
15
+ export function gateQuery(index, methodPath, tier) {
16
+ const method = index.get(methodPath);
17
+ if (!method) {
18
+ return {
19
+ allowed: false,
20
+ reason: `${methodPath} is not in the generated API index (docs/reference/api.md) — check the path, or run \`npm run docs:generate\` if it is new.`,
21
+ };
22
+ }
23
+ if (method.kind !== 'query') {
24
+ return {
25
+ allowed: false,
26
+ reason: `${methodPath} is a ${method.kind}; the ops toolset is read-only and only calls queries.`,
27
+ };
28
+ }
29
+ if (isSecretBearing(methodPath)) {
30
+ return {
31
+ allowed: false,
32
+ reason: `${methodPath} returns secret material; the ops toolset never reads it.`,
33
+ };
34
+ }
35
+ if (method.auth === 'admin' && tier !== 'admin') {
36
+ return {
37
+ allowed: false,
38
+ reason: `${methodPath} is admin-tier and this credential is not admin-scoped. Log in with an admin account via \`camstack login\`.`,
39
+ };
40
+ }
41
+ return { allowed: true, method };
42
+ }
@@ -0,0 +1,39 @@
1
+ /**
2
+ * What may leave an ops call: secret fields redacted by their DECLARATION, and
3
+ * the payload bounded so a media blob or a 10k-row list never floods a context.
4
+ *
5
+ * Declarations (the repository's own, D783/D787):
6
+ * - a stored marker `{ "$secret": "secret://…", "v": 1 }` (or its UI view);
7
+ * - a config-UI field declared `type: 'password'` or `secret: true` — its
8
+ * `value`/`default` is the secret, whatever the key is called.
9
+ * The output layer (`text()`) then adds the name/pattern scrub on top.
10
+ */
11
+ export declare const REDACTED = "[SECRET]";
12
+ /** A copy of `value` with every declared secret replaced; the input is untouched. */
13
+ export declare function redactDeclaredSecrets(value: unknown): unknown;
14
+ export interface TruncateLimits {
15
+ readonly maxItems: number;
16
+ readonly maxStringChars: number;
17
+ readonly maxTotalChars: number;
18
+ }
19
+ export declare const DEFAULT_LIMITS: TruncateLimits;
20
+ export interface Truncated {
21
+ readonly truncated: true;
22
+ readonly reason: string;
23
+ readonly totalChars: number;
24
+ readonly preview: string;
25
+ }
26
+ /**
27
+ * Bound a payload: long strings (a base64 frame) are cut, long arrays are
28
+ * capped, and a result still over the total budget becomes a labelled preview.
29
+ */
30
+ export declare function truncateOutput(value: unknown, limits?: TruncateLimits): unknown;
31
+ /** Redact then bound — the only way a hub payload becomes tool output. */
32
+ export declare function toToolOutput(value: unknown, limits?: TruncateLimits): unknown;
33
+ /**
34
+ * What a tool's ARGUMENTS may become before any log line: declared secrets,
35
+ * credential-named keys, then the pattern scrub — the same layers the output
36
+ * goes through, so a secret that must not come back must not be logged either.
37
+ */
38
+ export declare function redactToolArgs(args: unknown): unknown;
39
+ //# sourceMappingURL=redact.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"redact.d.ts","sourceRoot":"","sources":["../../src/mcp/redact.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AAIH,eAAO,MAAM,QAAQ,aAAa,CAAA;AAUlC,qFAAqF;AACrF,wBAAgB,qBAAqB,CAAC,KAAK,EAAE,OAAO,GAAG,OAAO,CAW7D;AAED,MAAM,WAAW,cAAc;IAC7B,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAA;IACzB,QAAQ,CAAC,cAAc,EAAE,MAAM,CAAA;IAC/B,QAAQ,CAAC,aAAa,EAAE,MAAM,CAAA;CAC/B;AAED,eAAO,MAAM,cAAc,EAAE,cAI5B,CAAA;AAED,MAAM,WAAW,SAAS;IACxB,QAAQ,CAAC,SAAS,EAAE,IAAI,CAAA;IACxB,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAA;IACvB,QAAQ,CAAC,UAAU,EAAE,MAAM,CAAA;IAC3B,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAA;CACzB;AAsBD;;;GAGG;AACH,wBAAgB,cAAc,CAAC,KAAK,EAAE,OAAO,EAAE,MAAM,GAAE,cAA+B,GAAG,OAAO,CAU/F;AAED,0EAA0E;AAC1E,wBAAgB,YAAY,CAAC,KAAK,EAAE,OAAO,EAAE,MAAM,GAAE,cAA+B,GAAG,OAAO,CAE7F;AAkBD;;;;GAIG;AACH,wBAAgB,cAAc,CAAC,IAAI,EAAE,OAAO,GAAG,OAAO,CAErD"}
@@ -0,0 +1,102 @@
1
+ /**
2
+ * What may leave an ops call: secret fields redacted by their DECLARATION, and
3
+ * the payload bounded so a media blob or a 10k-row list never floods a context.
4
+ *
5
+ * Declarations (the repository's own, D783/D787):
6
+ * - a stored marker `{ "$secret": "secret://…", "v": 1 }` (or its UI view);
7
+ * - a config-UI field declared `type: 'password'` or `secret: true` — its
8
+ * `value`/`default` is the secret, whatever the key is called.
9
+ * The output layer (`text()`) then adds the name/pattern scrub on top.
10
+ */
11
+ import { scrubValue } from './scrub.js';
12
+ export const REDACTED = '[SECRET]';
13
+ function isRecord(value) {
14
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
15
+ }
16
+ function isDeclaredSecretField(value) {
17
+ return value['type'] === 'password' || value['secret'] === true;
18
+ }
19
+ /** A copy of `value` with every declared secret replaced; the input is untouched. */
20
+ export function redactDeclaredSecrets(value) {
21
+ if (Array.isArray(value))
22
+ return value.map((v) => redactDeclaredSecrets(v));
23
+ if (!isRecord(value))
24
+ return value;
25
+ if (Object.prototype.hasOwnProperty.call(value, '$secret'))
26
+ return REDACTED;
27
+ const declared = isDeclaredSecretField(value);
28
+ const out = {};
29
+ for (const [key, child] of Object.entries(value)) {
30
+ out[key] =
31
+ declared && (key === 'value' || key === 'default') ? REDACTED : redactDeclaredSecrets(child);
32
+ }
33
+ return out;
34
+ }
35
+ export const DEFAULT_LIMITS = {
36
+ maxItems: 100,
37
+ maxStringChars: 1_000,
38
+ maxTotalChars: 30_000,
39
+ };
40
+ function shrink(value, limits) {
41
+ if (typeof value === 'string') {
42
+ return value.length > limits.maxStringChars
43
+ ? `${value.slice(0, 80)}… [${value.length - 80} more chars omitted]`
44
+ : value;
45
+ }
46
+ if (Array.isArray(value)) {
47
+ const head = value.slice(0, limits.maxItems).map((v) => shrink(v, limits));
48
+ return value.length > limits.maxItems
49
+ ? [...head, { _omitted: `${value.length - limits.maxItems} more items` }]
50
+ : head;
51
+ }
52
+ if (isRecord(value)) {
53
+ const out = {};
54
+ for (const [k, v] of Object.entries(value))
55
+ out[k] = shrink(v, limits);
56
+ return out;
57
+ }
58
+ return value;
59
+ }
60
+ /**
61
+ * Bound a payload: long strings (a base64 frame) are cut, long arrays are
62
+ * capped, and a result still over the total budget becomes a labelled preview.
63
+ */
64
+ export function truncateOutput(value, limits = DEFAULT_LIMITS) {
65
+ const shrunk = shrink(value, limits);
66
+ const json = JSON.stringify(shrunk) ?? 'null';
67
+ if (json.length <= limits.maxTotalChars)
68
+ return shrunk;
69
+ return {
70
+ truncated: true,
71
+ reason: `result is ${json.length} chars, over the ${limits.maxTotalChars} budget — narrow the query (limit, window, ids)`,
72
+ totalChars: json.length,
73
+ preview: json.slice(0, limits.maxTotalChars),
74
+ };
75
+ }
76
+ /** Redact then bound — the only way a hub payload becomes tool output. */
77
+ export function toToolOutput(value, limits = DEFAULT_LIMITS) {
78
+ return truncateOutput(redactDeclaredSecrets(value), limits);
79
+ }
80
+ /** Key names that read as a credential, beyond what `scrubValue` already catches. */
81
+ const CREDENTIAL_KEY = /pass(word|wd|phrase)?|token|secret|api[_-]?key|credential|private[_-]?key|authorization|cookie/i;
82
+ function redactCredentialKeys(value) {
83
+ if (Array.isArray(value))
84
+ return value.map((v) => redactCredentialKeys(v));
85
+ if (!isRecord(value))
86
+ return value;
87
+ const out = {};
88
+ for (const [key, child] of Object.entries(value)) {
89
+ // `confirm_token` is the gate's own one-shot handle, bound to the arguments.
90
+ out[key] =
91
+ key !== 'confirm_token' && CREDENTIAL_KEY.test(key) ? REDACTED : redactCredentialKeys(child);
92
+ }
93
+ return out;
94
+ }
95
+ /**
96
+ * What a tool's ARGUMENTS may become before any log line: declared secrets,
97
+ * credential-named keys, then the pattern scrub — the same layers the output
98
+ * goes through, so a secret that must not come back must not be logged either.
99
+ */
100
+ export function redactToolArgs(args) {
101
+ return scrubValue(redactCredentialKeys(redactDeclaredSecrets(args)));
102
+ }
@@ -0,0 +1,4 @@
1
+ /** Redact secrets and credential paths from tool outputs before they leave the MCP. */
2
+ export declare function scrubSecrets(text: string): string;
3
+ export declare function scrubValue(value: unknown): unknown;
4
+ //# sourceMappingURL=scrub.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"scrub.d.ts","sourceRoot":"","sources":["../../src/mcp/scrub.ts"],"names":[],"mappings":"AAAA,uFAAuF;AAWvF,wBAAgB,YAAY,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAMjD;AAMD,wBAAgB,UAAU,CAAC,KAAK,EAAE,OAAO,GAAG,OAAO,CA0BlD"}
@@ -0,0 +1,49 @@
1
+ /** Redact secrets and credential paths from tool outputs before they leave the MCP. */
2
+ const SECRET_PATTERNS = [
3
+ /\bglsa_[A-Za-z0-9_-]{10,}\b/g,
4
+ /\beyJ[A-Za-z0-9_-]{20,}\.[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\b/g,
5
+ /\bBearer\s+[A-Za-z0-9._\-+=/]{20,}\b/gi,
6
+ /(?:password|passwd|secret|token|api[_-]?key)\s*[:=]\s*['"]?[^\s'"]{8,}/gi,
7
+ /(?:\/Users\/[^/\s]+\/\.camstack\/[^\s'"]+)/g,
8
+ /(?:~\/\.camstack\/[^\s'"]+)/g,
9
+ ];
10
+ export function scrubSecrets(text) {
11
+ let out = text;
12
+ for (const re of SECRET_PATTERNS) {
13
+ out = out.replace(re, '[REDACTED]');
14
+ }
15
+ return out;
16
+ }
17
+ function isRecord(value) {
18
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
19
+ }
20
+ export function scrubValue(value) {
21
+ if (typeof value === 'string')
22
+ return scrubSecrets(value);
23
+ if (value === null || value === undefined)
24
+ return value;
25
+ if (Array.isArray(value))
26
+ return value.map((v) => scrubValue(v));
27
+ if (isRecord(value)) {
28
+ const out = {};
29
+ for (const [k, v] of Object.entries(value)) {
30
+ const keyLower = k.toLowerCase();
31
+ // `confirm_token` is the mutation gate's one-shot, argument-bound,
32
+ // short-lived handle — the operator must be able to read it back.
33
+ if (k === 'confirm_token') {
34
+ out[k] = v;
35
+ }
36
+ else if (keyLower.includes('token') ||
37
+ keyLower.includes('password') ||
38
+ keyLower.includes('secret') ||
39
+ keyLower === 'authorization') {
40
+ out[k] = '[REDACTED]';
41
+ }
42
+ else {
43
+ out[k] = scrubValue(v);
44
+ }
45
+ }
46
+ return out;
47
+ }
48
+ return value;
49
+ }
@@ -0,0 +1,14 @@
1
+ export declare function text(value: unknown): {
2
+ content: {
3
+ type: 'text';
4
+ text: string;
5
+ }[];
6
+ };
7
+ export declare function textError(message: string): {
8
+ content: {
9
+ type: 'text';
10
+ text: string;
11
+ }[];
12
+ isError: true;
13
+ };
14
+ //# sourceMappingURL=text.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"text.d.ts","sourceRoot":"","sources":["../../src/mcp/text.ts"],"names":[],"mappings":"AAEA,wBAAgB,IAAI,CAAC,KAAK,EAAE,OAAO,GAAG;IAAE,OAAO,EAAE;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,IAAI,EAAE,MAAM,CAAA;KAAE,EAAE,CAAA;CAAE,CAOlF;AAED,wBAAgB,SAAS,CAAC,OAAO,EAAE,MAAM,GAAG;IAC1C,OAAO,EAAE;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,IAAI,EAAE,MAAM,CAAA;KAAE,EAAE,CAAA;IACzC,OAAO,EAAE,IAAI,CAAA;CACd,CAKA"}
@@ -0,0 +1,14 @@
1
+ import { scrubSecrets, scrubValue } from './scrub.js';
2
+ export function text(value) {
3
+ const cleaned = scrubValue(value);
4
+ const body = typeof cleaned === 'string' ? scrubSecrets(cleaned) : JSON.stringify(cleaned, null, 2);
5
+ return {
6
+ content: [{ type: 'text', text: scrubSecrets(body) }],
7
+ };
8
+ }
9
+ export function textError(message) {
10
+ return {
11
+ content: [{ type: 'text', text: scrubSecrets(message) }],
12
+ isError: true,
13
+ };
14
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@camstack/develop",
3
- "version": "0.1.39",
3
+ "version": "0.1.41",
4
4
  "description": "CamStack developer tooling — catalogue, scaffold, validate, and example lookup shared by the CLI and MCP server.",
5
5
  "keywords": [
6
6
  "camstack",
@@ -57,6 +57,7 @@
57
57
  },
58
58
  "dependencies": {
59
59
  "@camstack/types": "*",
60
- "multicast-dns": "^7.2.5"
60
+ "multicast-dns": "^7.2.5",
61
+ "zod": "^4.3.6"
61
62
  }
62
63
  }