@goodtiming/baton-sdk 0.3.2 → 0.3.3
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/index.cjs +187 -16
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +137 -2
- package/dist/index.d.ts +137 -2
- package/dist/index.js +183 -14
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/dist/index.d.cts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { z } from 'zod';
|
|
2
2
|
|
|
3
|
-
declare const SDK_VERSION = "ts-0.3.
|
|
3
|
+
declare const SDK_VERSION = "ts-0.3.3";
|
|
4
4
|
|
|
5
5
|
/**
|
|
6
6
|
* Zod schemas + TS types for the Baton event stream per SPEC §11.4.
|
|
@@ -541,6 +541,109 @@ declare class HttpSink implements Sink {
|
|
|
541
541
|
private sendWithRetry;
|
|
542
542
|
}
|
|
543
543
|
|
|
544
|
+
/** The ASSERTED derivation tag — a principal a vendor's own hook supplied.
|
|
545
|
+
*
|
|
546
|
+
* Deliberately outside the `h*` family: `h2:` is reserved for HMAC key
|
|
547
|
+
* rotation, so a vendor assertion must never be mistakable for an
|
|
548
|
+
* attestation (SPEC §11.4's registered-set rule). */
|
|
549
|
+
declare const VENDOR_HASH_SCHEME = "v1";
|
|
550
|
+
declare const USER_ID_MODE_HASHED = "hashed";
|
|
551
|
+
declare const USER_ID_MODE_RAW = "raw";
|
|
552
|
+
type UserIdMode = typeof USER_ID_MODE_HASHED | typeof USER_ID_MODE_RAW;
|
|
553
|
+
/** A raw, UNHASHED end-user principal, as a resolver produced it. */
|
|
554
|
+
interface Principal {
|
|
555
|
+
/** The subject — a stable per-person identifier from the vendor's own
|
|
556
|
+
* system. Never an application id: that names the app and is identical for
|
|
557
|
+
* every one of its users, which merges them into one actor. */
|
|
558
|
+
userId: string;
|
|
559
|
+
/** The issuing authority, where one exists (the OIDC `iss`). Folded into
|
|
560
|
+
* the hash because a subject is unique only within the provider that minted
|
|
561
|
+
* it, so two identity providers behind one vendor can hand the same subject
|
|
562
|
+
* to different people. */
|
|
563
|
+
issuer?: string | null | undefined;
|
|
564
|
+
}
|
|
565
|
+
/** HMAC-SHA256 a raw principal into a console-safe, per-tenant `user_id`.
|
|
566
|
+
*
|
|
567
|
+
* `tenantId` is folded into the HMAC MESSAGE (not just the key) so the same
|
|
568
|
+
* principal under two tenants can never collide or be cross-tenant-correlated.
|
|
569
|
+
* Returns `"<scheme>:<hex>"`.
|
|
570
|
+
*
|
|
571
|
+
* `scheme` tags the DERIVATION and only the tag changes — the digest for a
|
|
572
|
+
* given `(tenantId, principal, issuer)` is identical under every scheme,
|
|
573
|
+
* because the tag is not part of the message. That is deliberate: the same
|
|
574
|
+
* person reached by two provenances is meant to be recognisably the same hex
|
|
575
|
+
* under two tags, not two unrelated values.
|
|
576
|
+
*
|
|
577
|
+
* ⚠ **`issuer` null/undefined MUST hash byte-identically to the pre-issuer
|
|
578
|
+
* form** — the append-only message layout is what guarantees it, and every
|
|
579
|
+
* hash baton-proxy and baton-extmcp have produced since 0.5.0 was issuer-less.
|
|
580
|
+
*/
|
|
581
|
+
declare function hashUserId(rawPrincipal: string, options: {
|
|
582
|
+
tenantId: string;
|
|
583
|
+
key: Uint8Array | string;
|
|
584
|
+
issuer?: string | null | undefined;
|
|
585
|
+
/** ⚠ **REQUIRED, and deliberately NOT defaulted the way Python's is.**
|
|
586
|
+
* Python defaults to `HASH_SCHEME` (`h1:`), which is right there because
|
|
587
|
+
* that arm emits both provenances. This arm emits ONLY `v1:` — it has no
|
|
588
|
+
* attested rung — so an `h1:` default would hand the documented
|
|
589
|
+
* "recompute the pseudonym to join your own records against Console data"
|
|
590
|
+
* use a value matching nothing we ever wrote, forever, with an equality
|
|
591
|
+
* join silently returning zero rows. The hex halves are identical under
|
|
592
|
+
* both tags, so it fails in the most confusing way available. Naming the
|
|
593
|
+
* provenance is one word and removes the whole failure. */
|
|
594
|
+
scheme: string;
|
|
595
|
+
}): string;
|
|
596
|
+
|
|
597
|
+
/** `BatonConfig.resolveUser` — the ASSERTED identity provenance.
|
|
598
|
+
*
|
|
599
|
+
* The TypeScript half of Python's `integrations/identity_adapter.py`, built to
|
|
600
|
+
* close register D6: `user_id` has been on this SDK's envelope since 0.3.0 and
|
|
601
|
+
* NOTHING could populate it, so a partition that works on one of two SDKs is
|
|
602
|
+
* not a partition.
|
|
603
|
+
*
|
|
604
|
+
* **Hook only — there is deliberately no attested (`h1:`) rung here yet.**
|
|
605
|
+
* Python reads `claims["sub"]` off a verified access token; TypeScript's
|
|
606
|
+
* `AuthInfo` has no `claims` field at all (it is
|
|
607
|
+
* `{token, clientId, scopes, expiresAt?, resource?, extra?}`), so the nearest
|
|
608
|
+
* carrier is the untyped `extra` bag and nothing specifies that `sub` lives
|
|
609
|
+
* there. Reading it would mean guessing where a subject lives, vendor by
|
|
610
|
+
* vendor — and a wrong guess is how two people end up as one actor. Recorded
|
|
611
|
+
* as a divergence rather than filled with a guess.
|
|
612
|
+
*/
|
|
613
|
+
|
|
614
|
+
/** What a vendor's `resolveUser` hook is handed.
|
|
615
|
+
*
|
|
616
|
+
* Adapter-neutral BY CONSTRUCTION rather than by convention — the peers' own
|
|
617
|
+
* handler-context objects differ in shape between the two majors, and this
|
|
618
|
+
* type is what makes one hook portable across them. The prior art takes the
|
|
619
|
+
* opposite approach: AgentCat's `identify()` receives the raw per-major object
|
|
620
|
+
* behind `{ sessionId?: string; [key: string]: any }`, documented as "only
|
|
621
|
+
* `sessionId` is common to both; everything else is SDK-version-specific".
|
|
622
|
+
* That is the divergence handed to the vendor as `any`; this is the divergence
|
|
623
|
+
* absorbed by us.
|
|
624
|
+
*/
|
|
625
|
+
interface UserResolutionContext {
|
|
626
|
+
/** The call's HTTP headers, case-insensitive on BOTH majors — see
|
|
627
|
+
* `extraHeaders` for the two shapes it reconciles.
|
|
628
|
+
*
|
|
629
|
+
* `null` means NO HTTP REQUEST (every stdio call, the common case), never
|
|
630
|
+
* "the client sent no headers". The distinction matters: the first is us
|
|
631
|
+
* telling you the question does not apply, the second would be a claim about
|
|
632
|
+
* the caller that we are not in a position to make. */
|
|
633
|
+
headers: Headers | null;
|
|
634
|
+
/** The call's `_meta`, from wherever this major keeps it. */
|
|
635
|
+
meta: Record<string, unknown> | null;
|
|
636
|
+
/** The tool being called — the annotation tool's own name on that path, so a
|
|
637
|
+
* hook can answer differently per call rather than per install. */
|
|
638
|
+
toolName: string;
|
|
639
|
+
/** The call's arguments, AFTER Baton's injected intent params are stripped,
|
|
640
|
+
* so a hook sees exactly what the vendor's own handler will. */
|
|
641
|
+
arguments: Record<string, unknown>;
|
|
642
|
+
}
|
|
643
|
+
/** A vendor's per-request identity resolver. Sync or async; returning `null`
|
|
644
|
+
* means "no opinion about this caller", which is not an error. */
|
|
645
|
+
type ResolveUserHook = (context: UserResolutionContext) => Principal | null | Promise<Principal | null>;
|
|
646
|
+
|
|
544
647
|
/**
|
|
545
648
|
* `BatonConfig` — vendor-side configuration for `withBaton`. A trimmed
|
|
546
649
|
* mirror of `baton` (Python)'s `integrations/_config.py::VendorConfig`.
|
|
@@ -639,6 +742,38 @@ interface BatonConfig {
|
|
|
639
742
|
* nothing. A tool registered with no `inputSchema` at all is left alone
|
|
640
743
|
* regardless of this setting (see `schemaCompat.injectGoalParams`). */
|
|
641
744
|
intentParamMode?: "optional" | "required" | "off";
|
|
745
|
+
/** Per-request end-user identity — the ASSERTED provenance behind the
|
|
746
|
+
* envelope's `user_id` (SPEC §11.4 rung 0), tagged `v1:`.
|
|
747
|
+
*
|
|
748
|
+
* Called on every captured tool call and on the annotation tool, with an
|
|
749
|
+
* adapter-neutral {@link UserResolutionContext}: headers folded to ONE
|
|
750
|
+
* case-insensitive shape across both SDK majors, the call's `_meta`, the
|
|
751
|
+
* tool name, and the arguments the vendor's own handler will see. Return a
|
|
752
|
+
* `Principal`, or `null` for "no opinion about this caller".
|
|
753
|
+
*
|
|
754
|
+
* **This is the only identity mechanism on this arm.** MCP auth is HTTP
|
|
755
|
+
* middleware, so a stdio server has no token at all; and unlike Python, no
|
|
756
|
+
* attested rung is implemented here — see `userResolution.ts` for why
|
|
757
|
+
* (TypeScript's `AuthInfo` carries no `claims`).
|
|
758
|
+
*
|
|
759
|
+
* Never fails a tool call: a hook that throws or returns junk yields an
|
|
760
|
+
* anonymous call. ⚠ It is awaited INLINE with no timeout — a blocking hook
|
|
761
|
+
* stalls its own request. */
|
|
762
|
+
resolveUser?: ResolveUserHook;
|
|
763
|
+
/** `"hashed"` (default) emits a `v1:` per-tenant HMAC pseudonym; `"raw"`
|
|
764
|
+
* emits the subject VERBATIM.
|
|
765
|
+
*
|
|
766
|
+
* `"raw"` puts real end-user identity in the collector's database and is the
|
|
767
|
+
* vendor's deliberate choice — which is why SPEC §11.4 tells a consumer
|
|
768
|
+
* never to treat this field as anonymous. */
|
|
769
|
+
userIdMode?: "hashed" | "raw";
|
|
770
|
+
/** The HMAC secret for hashed mode. Resolved explicit →
|
|
771
|
+
* `BATON_USER_ID_HMAC_KEY` → unset.
|
|
772
|
+
*
|
|
773
|
+
* ⚠ **With none set, hashed mode DROPS `user_id` rather than falling back to
|
|
774
|
+
* raw.** The fallback would be a residency breach that looks like success:
|
|
775
|
+
* the field present, populated, and carrying the subject verbatim. */
|
|
776
|
+
userIdHmacKey?: string | Uint8Array;
|
|
642
777
|
}
|
|
643
778
|
|
|
644
779
|
/**
|
|
@@ -762,4 +897,4 @@ interface SupportedMcpServer {
|
|
|
762
897
|
/** Install Baton into an `McpServer`. See module docstring for usage. */
|
|
763
898
|
declare function withBaton(server: SupportedMcpServer, supplied?: BatonConfig): BatonHandle;
|
|
764
899
|
|
|
765
|
-
export { type AnnotationEvent, AnnotationEventSchema, type AnnotationPayload, AnnotationPayloadSchema, type BatonConfig, BatonHandle, DEFAULT_CONSENT_TOKEN, DEPTH_LIMIT, type Event, EventSchema, type EventType, EventTypeSchema, HttpSink, type HttpSinkOptions, SDK_VERSION, Scrubber, type Sink, StdoutSink, type StdoutSinkOptions, type SupportedMcpServer, type SurfaceSnapshotEvent, SurfaceSnapshotEventSchema, type SurfaceSnapshotPayload, SurfaceSnapshotPayloadSchema, type ToolCallEndEvent, ToolCallEndEventSchema, type ToolCallEndPayload, ToolCallEndPayloadSchema, type ToolCallErrorEvent, ToolCallErrorEventSchema, type ToolCallErrorPayload, ToolCallErrorPayloadSchema, type ToolCallStartEvent, ToolCallStartEventSchema, type ToolCallStartPayload, ToolCallStartPayloadSchema, identityScrub, safeWrite, withBaton };
|
|
900
|
+
export { type AnnotationEvent, AnnotationEventSchema, type AnnotationPayload, AnnotationPayloadSchema, type BatonConfig, BatonHandle, DEFAULT_CONSENT_TOKEN, DEPTH_LIMIT, type Event, EventSchema, type EventType, EventTypeSchema, HttpSink, type HttpSinkOptions, type Principal, type ResolveUserHook, SDK_VERSION, Scrubber, type Sink, StdoutSink, type StdoutSinkOptions, type SupportedMcpServer, type SurfaceSnapshotEvent, SurfaceSnapshotEventSchema, type SurfaceSnapshotPayload, SurfaceSnapshotPayloadSchema, type ToolCallEndEvent, ToolCallEndEventSchema, type ToolCallEndPayload, ToolCallEndPayloadSchema, type ToolCallErrorEvent, ToolCallErrorEventSchema, type ToolCallErrorPayload, ToolCallErrorPayloadSchema, type ToolCallStartEvent, ToolCallStartEventSchema, type ToolCallStartPayload, ToolCallStartPayloadSchema, type UserIdMode, type UserResolutionContext, VENDOR_HASH_SCHEME, hashUserId, identityScrub, safeWrite, withBaton };
|
package/dist/index.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { z } from 'zod';
|
|
2
2
|
|
|
3
|
-
declare const SDK_VERSION = "ts-0.3.
|
|
3
|
+
declare const SDK_VERSION = "ts-0.3.3";
|
|
4
4
|
|
|
5
5
|
/**
|
|
6
6
|
* Zod schemas + TS types for the Baton event stream per SPEC §11.4.
|
|
@@ -541,6 +541,109 @@ declare class HttpSink implements Sink {
|
|
|
541
541
|
private sendWithRetry;
|
|
542
542
|
}
|
|
543
543
|
|
|
544
|
+
/** The ASSERTED derivation tag — a principal a vendor's own hook supplied.
|
|
545
|
+
*
|
|
546
|
+
* Deliberately outside the `h*` family: `h2:` is reserved for HMAC key
|
|
547
|
+
* rotation, so a vendor assertion must never be mistakable for an
|
|
548
|
+
* attestation (SPEC §11.4's registered-set rule). */
|
|
549
|
+
declare const VENDOR_HASH_SCHEME = "v1";
|
|
550
|
+
declare const USER_ID_MODE_HASHED = "hashed";
|
|
551
|
+
declare const USER_ID_MODE_RAW = "raw";
|
|
552
|
+
type UserIdMode = typeof USER_ID_MODE_HASHED | typeof USER_ID_MODE_RAW;
|
|
553
|
+
/** A raw, UNHASHED end-user principal, as a resolver produced it. */
|
|
554
|
+
interface Principal {
|
|
555
|
+
/** The subject — a stable per-person identifier from the vendor's own
|
|
556
|
+
* system. Never an application id: that names the app and is identical for
|
|
557
|
+
* every one of its users, which merges them into one actor. */
|
|
558
|
+
userId: string;
|
|
559
|
+
/** The issuing authority, where one exists (the OIDC `iss`). Folded into
|
|
560
|
+
* the hash because a subject is unique only within the provider that minted
|
|
561
|
+
* it, so two identity providers behind one vendor can hand the same subject
|
|
562
|
+
* to different people. */
|
|
563
|
+
issuer?: string | null | undefined;
|
|
564
|
+
}
|
|
565
|
+
/** HMAC-SHA256 a raw principal into a console-safe, per-tenant `user_id`.
|
|
566
|
+
*
|
|
567
|
+
* `tenantId` is folded into the HMAC MESSAGE (not just the key) so the same
|
|
568
|
+
* principal under two tenants can never collide or be cross-tenant-correlated.
|
|
569
|
+
* Returns `"<scheme>:<hex>"`.
|
|
570
|
+
*
|
|
571
|
+
* `scheme` tags the DERIVATION and only the tag changes — the digest for a
|
|
572
|
+
* given `(tenantId, principal, issuer)` is identical under every scheme,
|
|
573
|
+
* because the tag is not part of the message. That is deliberate: the same
|
|
574
|
+
* person reached by two provenances is meant to be recognisably the same hex
|
|
575
|
+
* under two tags, not two unrelated values.
|
|
576
|
+
*
|
|
577
|
+
* ⚠ **`issuer` null/undefined MUST hash byte-identically to the pre-issuer
|
|
578
|
+
* form** — the append-only message layout is what guarantees it, and every
|
|
579
|
+
* hash baton-proxy and baton-extmcp have produced since 0.5.0 was issuer-less.
|
|
580
|
+
*/
|
|
581
|
+
declare function hashUserId(rawPrincipal: string, options: {
|
|
582
|
+
tenantId: string;
|
|
583
|
+
key: Uint8Array | string;
|
|
584
|
+
issuer?: string | null | undefined;
|
|
585
|
+
/** ⚠ **REQUIRED, and deliberately NOT defaulted the way Python's is.**
|
|
586
|
+
* Python defaults to `HASH_SCHEME` (`h1:`), which is right there because
|
|
587
|
+
* that arm emits both provenances. This arm emits ONLY `v1:` — it has no
|
|
588
|
+
* attested rung — so an `h1:` default would hand the documented
|
|
589
|
+
* "recompute the pseudonym to join your own records against Console data"
|
|
590
|
+
* use a value matching nothing we ever wrote, forever, with an equality
|
|
591
|
+
* join silently returning zero rows. The hex halves are identical under
|
|
592
|
+
* both tags, so it fails in the most confusing way available. Naming the
|
|
593
|
+
* provenance is one word and removes the whole failure. */
|
|
594
|
+
scheme: string;
|
|
595
|
+
}): string;
|
|
596
|
+
|
|
597
|
+
/** `BatonConfig.resolveUser` — the ASSERTED identity provenance.
|
|
598
|
+
*
|
|
599
|
+
* The TypeScript half of Python's `integrations/identity_adapter.py`, built to
|
|
600
|
+
* close register D6: `user_id` has been on this SDK's envelope since 0.3.0 and
|
|
601
|
+
* NOTHING could populate it, so a partition that works on one of two SDKs is
|
|
602
|
+
* not a partition.
|
|
603
|
+
*
|
|
604
|
+
* **Hook only — there is deliberately no attested (`h1:`) rung here yet.**
|
|
605
|
+
* Python reads `claims["sub"]` off a verified access token; TypeScript's
|
|
606
|
+
* `AuthInfo` has no `claims` field at all (it is
|
|
607
|
+
* `{token, clientId, scopes, expiresAt?, resource?, extra?}`), so the nearest
|
|
608
|
+
* carrier is the untyped `extra` bag and nothing specifies that `sub` lives
|
|
609
|
+
* there. Reading it would mean guessing where a subject lives, vendor by
|
|
610
|
+
* vendor — and a wrong guess is how two people end up as one actor. Recorded
|
|
611
|
+
* as a divergence rather than filled with a guess.
|
|
612
|
+
*/
|
|
613
|
+
|
|
614
|
+
/** What a vendor's `resolveUser` hook is handed.
|
|
615
|
+
*
|
|
616
|
+
* Adapter-neutral BY CONSTRUCTION rather than by convention — the peers' own
|
|
617
|
+
* handler-context objects differ in shape between the two majors, and this
|
|
618
|
+
* type is what makes one hook portable across them. The prior art takes the
|
|
619
|
+
* opposite approach: AgentCat's `identify()` receives the raw per-major object
|
|
620
|
+
* behind `{ sessionId?: string; [key: string]: any }`, documented as "only
|
|
621
|
+
* `sessionId` is common to both; everything else is SDK-version-specific".
|
|
622
|
+
* That is the divergence handed to the vendor as `any`; this is the divergence
|
|
623
|
+
* absorbed by us.
|
|
624
|
+
*/
|
|
625
|
+
interface UserResolutionContext {
|
|
626
|
+
/** The call's HTTP headers, case-insensitive on BOTH majors — see
|
|
627
|
+
* `extraHeaders` for the two shapes it reconciles.
|
|
628
|
+
*
|
|
629
|
+
* `null` means NO HTTP REQUEST (every stdio call, the common case), never
|
|
630
|
+
* "the client sent no headers". The distinction matters: the first is us
|
|
631
|
+
* telling you the question does not apply, the second would be a claim about
|
|
632
|
+
* the caller that we are not in a position to make. */
|
|
633
|
+
headers: Headers | null;
|
|
634
|
+
/** The call's `_meta`, from wherever this major keeps it. */
|
|
635
|
+
meta: Record<string, unknown> | null;
|
|
636
|
+
/** The tool being called — the annotation tool's own name on that path, so a
|
|
637
|
+
* hook can answer differently per call rather than per install. */
|
|
638
|
+
toolName: string;
|
|
639
|
+
/** The call's arguments, AFTER Baton's injected intent params are stripped,
|
|
640
|
+
* so a hook sees exactly what the vendor's own handler will. */
|
|
641
|
+
arguments: Record<string, unknown>;
|
|
642
|
+
}
|
|
643
|
+
/** A vendor's per-request identity resolver. Sync or async; returning `null`
|
|
644
|
+
* means "no opinion about this caller", which is not an error. */
|
|
645
|
+
type ResolveUserHook = (context: UserResolutionContext) => Principal | null | Promise<Principal | null>;
|
|
646
|
+
|
|
544
647
|
/**
|
|
545
648
|
* `BatonConfig` — vendor-side configuration for `withBaton`. A trimmed
|
|
546
649
|
* mirror of `baton` (Python)'s `integrations/_config.py::VendorConfig`.
|
|
@@ -639,6 +742,38 @@ interface BatonConfig {
|
|
|
639
742
|
* nothing. A tool registered with no `inputSchema` at all is left alone
|
|
640
743
|
* regardless of this setting (see `schemaCompat.injectGoalParams`). */
|
|
641
744
|
intentParamMode?: "optional" | "required" | "off";
|
|
745
|
+
/** Per-request end-user identity — the ASSERTED provenance behind the
|
|
746
|
+
* envelope's `user_id` (SPEC §11.4 rung 0), tagged `v1:`.
|
|
747
|
+
*
|
|
748
|
+
* Called on every captured tool call and on the annotation tool, with an
|
|
749
|
+
* adapter-neutral {@link UserResolutionContext}: headers folded to ONE
|
|
750
|
+
* case-insensitive shape across both SDK majors, the call's `_meta`, the
|
|
751
|
+
* tool name, and the arguments the vendor's own handler will see. Return a
|
|
752
|
+
* `Principal`, or `null` for "no opinion about this caller".
|
|
753
|
+
*
|
|
754
|
+
* **This is the only identity mechanism on this arm.** MCP auth is HTTP
|
|
755
|
+
* middleware, so a stdio server has no token at all; and unlike Python, no
|
|
756
|
+
* attested rung is implemented here — see `userResolution.ts` for why
|
|
757
|
+
* (TypeScript's `AuthInfo` carries no `claims`).
|
|
758
|
+
*
|
|
759
|
+
* Never fails a tool call: a hook that throws or returns junk yields an
|
|
760
|
+
* anonymous call. ⚠ It is awaited INLINE with no timeout — a blocking hook
|
|
761
|
+
* stalls its own request. */
|
|
762
|
+
resolveUser?: ResolveUserHook;
|
|
763
|
+
/** `"hashed"` (default) emits a `v1:` per-tenant HMAC pseudonym; `"raw"`
|
|
764
|
+
* emits the subject VERBATIM.
|
|
765
|
+
*
|
|
766
|
+
* `"raw"` puts real end-user identity in the collector's database and is the
|
|
767
|
+
* vendor's deliberate choice — which is why SPEC §11.4 tells a consumer
|
|
768
|
+
* never to treat this field as anonymous. */
|
|
769
|
+
userIdMode?: "hashed" | "raw";
|
|
770
|
+
/** The HMAC secret for hashed mode. Resolved explicit →
|
|
771
|
+
* `BATON_USER_ID_HMAC_KEY` → unset.
|
|
772
|
+
*
|
|
773
|
+
* ⚠ **With none set, hashed mode DROPS `user_id` rather than falling back to
|
|
774
|
+
* raw.** The fallback would be a residency breach that looks like success:
|
|
775
|
+
* the field present, populated, and carrying the subject verbatim. */
|
|
776
|
+
userIdHmacKey?: string | Uint8Array;
|
|
642
777
|
}
|
|
643
778
|
|
|
644
779
|
/**
|
|
@@ -762,4 +897,4 @@ interface SupportedMcpServer {
|
|
|
762
897
|
/** Install Baton into an `McpServer`. See module docstring for usage. */
|
|
763
898
|
declare function withBaton(server: SupportedMcpServer, supplied?: BatonConfig): BatonHandle;
|
|
764
899
|
|
|
765
|
-
export { type AnnotationEvent, AnnotationEventSchema, type AnnotationPayload, AnnotationPayloadSchema, type BatonConfig, BatonHandle, DEFAULT_CONSENT_TOKEN, DEPTH_LIMIT, type Event, EventSchema, type EventType, EventTypeSchema, HttpSink, type HttpSinkOptions, SDK_VERSION, Scrubber, type Sink, StdoutSink, type StdoutSinkOptions, type SupportedMcpServer, type SurfaceSnapshotEvent, SurfaceSnapshotEventSchema, type SurfaceSnapshotPayload, SurfaceSnapshotPayloadSchema, type ToolCallEndEvent, ToolCallEndEventSchema, type ToolCallEndPayload, ToolCallEndPayloadSchema, type ToolCallErrorEvent, ToolCallErrorEventSchema, type ToolCallErrorPayload, ToolCallErrorPayloadSchema, type ToolCallStartEvent, ToolCallStartEventSchema, type ToolCallStartPayload, ToolCallStartPayloadSchema, identityScrub, safeWrite, withBaton };
|
|
900
|
+
export { type AnnotationEvent, AnnotationEventSchema, type AnnotationPayload, AnnotationPayloadSchema, type BatonConfig, BatonHandle, DEFAULT_CONSENT_TOKEN, DEPTH_LIMIT, type Event, EventSchema, type EventType, EventTypeSchema, HttpSink, type HttpSinkOptions, type Principal, type ResolveUserHook, SDK_VERSION, Scrubber, type Sink, StdoutSink, type StdoutSinkOptions, type SupportedMcpServer, type SurfaceSnapshotEvent, SurfaceSnapshotEventSchema, type SurfaceSnapshotPayload, SurfaceSnapshotPayloadSchema, type ToolCallEndEvent, ToolCallEndEventSchema, type ToolCallEndPayload, ToolCallEndPayloadSchema, type ToolCallErrorEvent, ToolCallErrorEventSchema, type ToolCallErrorPayload, ToolCallErrorPayloadSchema, type ToolCallStartEvent, ToolCallStartEventSchema, type ToolCallStartPayload, ToolCallStartPayloadSchema, type UserIdMode, type UserResolutionContext, VENDOR_HASH_SCHEME, hashUserId, identityScrub, safeWrite, withBaton };
|
package/dist/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// src/version.ts
|
|
2
|
-
var SDK_VERSION = "ts-0.3.
|
|
2
|
+
var SDK_VERSION = "ts-0.3.3";
|
|
3
3
|
|
|
4
4
|
// src/events.ts
|
|
5
5
|
import { z } from "zod";
|
|
@@ -406,6 +406,134 @@ async function emit(sink, build) {
|
|
|
406
406
|
await safeWrite(sink, event);
|
|
407
407
|
}
|
|
408
408
|
|
|
409
|
+
// src/identity.ts
|
|
410
|
+
import { createHmac } from "crypto";
|
|
411
|
+
|
|
412
|
+
// src/_text.ts
|
|
413
|
+
function capCodePoints(value, max) {
|
|
414
|
+
if (value.length <= max) return value;
|
|
415
|
+
return [...value].slice(0, max).join("");
|
|
416
|
+
}
|
|
417
|
+
|
|
418
|
+
// src/identity.ts
|
|
419
|
+
var VENDOR_HASH_SCHEME = "v1";
|
|
420
|
+
var RAW_USER_ID_MAX_LEN = 128;
|
|
421
|
+
var USER_ID_MODE_HASHED = "hashed";
|
|
422
|
+
var USER_ID_MODE_RAW = "raw";
|
|
423
|
+
var PYTHON_WHITESPACE = "\\t\\n\\v\\f\\r\\x1c-\\x1f \\x85\\xa0\\u1680\\u2000-\\u200a\\u2028\\u2029\\u202f\\u205f\\u3000";
|
|
424
|
+
var PYTHON_STRIP = new RegExp(`^[${PYTHON_WHITESPACE}]+|[${PYTHON_WHITESPACE}]+$`, "gu");
|
|
425
|
+
var LONE_SURROGATE = /\p{Surrogate}/u;
|
|
426
|
+
function canonicalize(rawPrincipal) {
|
|
427
|
+
return rawPrincipal.normalize("NFC").replace(PYTHON_STRIP, "").toLowerCase();
|
|
428
|
+
}
|
|
429
|
+
function hashUserId(rawPrincipal, options) {
|
|
430
|
+
const { tenantId, key, issuer = null, scheme } = options;
|
|
431
|
+
let message = `${tenantId}\0${canonicalize(rawPrincipal)}`;
|
|
432
|
+
if (issuer !== null) {
|
|
433
|
+
message += `\0${canonicalize(issuer)}`;
|
|
434
|
+
}
|
|
435
|
+
const keyBytes = typeof key === "string" ? Buffer.from(key, "utf8") : key;
|
|
436
|
+
const digest = createHmac("sha256", keyBytes).update(message, "utf8").digest("hex");
|
|
437
|
+
return `${scheme}:${digest}`;
|
|
438
|
+
}
|
|
439
|
+
function normalizePrincipal(result) {
|
|
440
|
+
if (result === null || typeof result !== "object") return null;
|
|
441
|
+
const candidate = result;
|
|
442
|
+
if (typeof candidate.userId !== "string") return null;
|
|
443
|
+
if (LONE_SURROGATE.test(candidate.userId)) return null;
|
|
444
|
+
if (canonicalize(candidate.userId) === "") return null;
|
|
445
|
+
const issuerRaw = typeof candidate.issuer === "string" && candidate.issuer ? candidate.issuer : null;
|
|
446
|
+
const issuer = issuerRaw !== null && !LONE_SURROGATE.test(issuerRaw) ? issuerRaw : null;
|
|
447
|
+
return { userId: candidate.userId, issuer };
|
|
448
|
+
}
|
|
449
|
+
function userIdForPrincipal(principal, options) {
|
|
450
|
+
if (options.mode === USER_ID_MODE_RAW) {
|
|
451
|
+
return capCodePoints(principal.userId, RAW_USER_ID_MAX_LEN);
|
|
452
|
+
}
|
|
453
|
+
if (options.key === null || options.key === void 0) return null;
|
|
454
|
+
return hashUserId(principal.userId, {
|
|
455
|
+
tenantId: options.tenantId,
|
|
456
|
+
key: options.key,
|
|
457
|
+
issuer: principal.issuer ?? null,
|
|
458
|
+
// Unconditional: this arm has no attested rung, so every principal it
|
|
459
|
+
// hashes is vendor-ASSERTED. A `scheme` option here would be an argument
|
|
460
|
+
// no caller can vary — configurability for a rung the design says is not
|
|
461
|
+
// coming to this SDK.
|
|
462
|
+
scheme: VENDOR_HASH_SCHEME
|
|
463
|
+
});
|
|
464
|
+
}
|
|
465
|
+
|
|
466
|
+
// src/integrations/mcp/mcpTypes.ts
|
|
467
|
+
function extraMeta(extra) {
|
|
468
|
+
const direct = extra._meta;
|
|
469
|
+
if (direct) return direct;
|
|
470
|
+
const nested = extra.mcpReq?._meta;
|
|
471
|
+
return nested ?? null;
|
|
472
|
+
}
|
|
473
|
+
function extraEnvelope(extra) {
|
|
474
|
+
const envelope = extra.mcpReq?.envelope;
|
|
475
|
+
return envelope ?? null;
|
|
476
|
+
}
|
|
477
|
+
function extraHeaders(extra) {
|
|
478
|
+
const fromV2 = extra.http?.req?.headers;
|
|
479
|
+
if (fromV2 && typeof fromV2.get === "function") return fromV2;
|
|
480
|
+
const fromV1 = extra.requestInfo?.headers;
|
|
481
|
+
if (fromV1 && typeof fromV1 === "object") {
|
|
482
|
+
const headers = new Headers();
|
|
483
|
+
for (const [name, value] of Object.entries(fromV1)) {
|
|
484
|
+
for (const item of Array.isArray(value) ? value : [value]) {
|
|
485
|
+
if (typeof item !== "string") continue;
|
|
486
|
+
try {
|
|
487
|
+
headers.append(name, item);
|
|
488
|
+
} catch {
|
|
489
|
+
}
|
|
490
|
+
}
|
|
491
|
+
}
|
|
492
|
+
return headers;
|
|
493
|
+
}
|
|
494
|
+
return null;
|
|
495
|
+
}
|
|
496
|
+
|
|
497
|
+
// src/integrations/mcp/userResolution.ts
|
|
498
|
+
function buildUserResolutionContext(extra, toolName, args) {
|
|
499
|
+
return {
|
|
500
|
+
headers: extraHeaders(extra),
|
|
501
|
+
meta: extraMeta(extra),
|
|
502
|
+
toolName,
|
|
503
|
+
arguments: args
|
|
504
|
+
};
|
|
505
|
+
}
|
|
506
|
+
function warnIfIdentityCannotResolve(config) {
|
|
507
|
+
if (config.resolveUser === void 0) return;
|
|
508
|
+
if (config.userIdMode !== USER_ID_MODE_HASHED) return;
|
|
509
|
+
if (config.userIdHmacKey !== void 0) return;
|
|
510
|
+
if (typeof process === "undefined" || typeof process.emitWarning !== "function") return;
|
|
511
|
+
process.emitWarning(
|
|
512
|
+
'baton: resolveUser is configured but no user_id HMAC key is set, so user_id is dropped from every event (events still emit). Set BATON_USER_ID_HMAC_KEY or BatonConfig.userIdHmacKey, or pass userIdMode: "raw" if you intend to emit the subject verbatim.'
|
|
513
|
+
);
|
|
514
|
+
}
|
|
515
|
+
async function resolveCallUserId(hook, call, options) {
|
|
516
|
+
if (hook === void 0) return null;
|
|
517
|
+
let result;
|
|
518
|
+
try {
|
|
519
|
+
const context = buildUserResolutionContext(call.extra, call.toolName, call.arguments);
|
|
520
|
+
result = await hook(context);
|
|
521
|
+
} catch {
|
|
522
|
+
return null;
|
|
523
|
+
}
|
|
524
|
+
const principal = normalizePrincipal(result);
|
|
525
|
+
if (principal === null) return null;
|
|
526
|
+
try {
|
|
527
|
+
return userIdForPrincipal(principal, {
|
|
528
|
+
mode: options.mode,
|
|
529
|
+
tenantId: options.tenantId,
|
|
530
|
+
key: options.key
|
|
531
|
+
});
|
|
532
|
+
} catch {
|
|
533
|
+
return null;
|
|
534
|
+
}
|
|
535
|
+
}
|
|
536
|
+
|
|
409
537
|
// src/integrations/mcp/llmText.ts
|
|
410
538
|
var SERVER_INSTRUCTIONS_TEMPLATE = (vendorDisplayName, annotationToolName) => `This server is wrapped in the ${vendorDisplayName} support-signal SDK. Use \`${annotationToolName}\` to record what the user is trying to do and how each ${vendorDisplayName} tool call went. See that tool's description for field-level detail.
|
|
411
539
|
|
|
@@ -467,18 +595,6 @@ function buildExpectedResultParamDescription() {
|
|
|
467
595
|
return EXPECTED_RESULT_PARAM_DESCRIPTION;
|
|
468
596
|
}
|
|
469
597
|
|
|
470
|
-
// src/integrations/mcp/mcpTypes.ts
|
|
471
|
-
function extraMeta(extra) {
|
|
472
|
-
const direct = extra._meta;
|
|
473
|
-
if (direct) return direct;
|
|
474
|
-
const nested = extra.mcpReq?._meta;
|
|
475
|
-
return nested ?? null;
|
|
476
|
-
}
|
|
477
|
-
function extraEnvelope(extra) {
|
|
478
|
-
const envelope = extra.mcpReq?.envelope;
|
|
479
|
-
return envelope ?? null;
|
|
480
|
-
}
|
|
481
|
-
|
|
482
598
|
// src/integrations/mcp/runtimeAdapter.ts
|
|
483
599
|
var CLIENT_INFO_META_KEY = "io.modelcontextprotocol/clientInfo";
|
|
484
600
|
var CLIENT_NAME_MAX_LEN = 128;
|
|
@@ -492,7 +608,7 @@ function clean(name, scrubber) {
|
|
|
492
608
|
cleaned = scrubbed;
|
|
493
609
|
}
|
|
494
610
|
if (!cleaned) return null;
|
|
495
|
-
return
|
|
611
|
+
return capCodePoints(cleaned, CLIENT_NAME_MAX_LEN);
|
|
496
612
|
}
|
|
497
613
|
function declaredOnRequest(meta, envelope) {
|
|
498
614
|
for (const source of [envelope, meta]) {
|
|
@@ -578,6 +694,15 @@ function registerAnnotationTool(server, options) {
|
|
|
578
694
|
if (args.signal_type === void 0) {
|
|
579
695
|
options.tracker?.mark(sessionId);
|
|
580
696
|
}
|
|
697
|
+
const userId = await resolveCallUserId(
|
|
698
|
+
options.resolveUser,
|
|
699
|
+
{ extra, toolName: name, arguments: args },
|
|
700
|
+
{
|
|
701
|
+
mode: options.userIdMode,
|
|
702
|
+
tenantId: options.tenantId,
|
|
703
|
+
key: options.userIdHmacKey
|
|
704
|
+
}
|
|
705
|
+
);
|
|
581
706
|
await emit(
|
|
582
707
|
options.sink,
|
|
583
708
|
() => AnnotationEventSchema.parse({
|
|
@@ -588,6 +713,7 @@ function registerAnnotationTool(server, options) {
|
|
|
588
713
|
captured_at: (/* @__PURE__ */ new Date()).toISOString(),
|
|
589
714
|
consent_token: options.consentToken,
|
|
590
715
|
agent_runtime: runtime,
|
|
716
|
+
user_id: userId,
|
|
591
717
|
runtime_meta: scrubbedMeta,
|
|
592
718
|
payload: {
|
|
593
719
|
// Agent-facing names -> wire keys, as with `overall_task`
|
|
@@ -825,12 +951,18 @@ function sealKey(dsn) {
|
|
|
825
951
|
|
|
826
952
|
// src/integrations/mcp/config.ts
|
|
827
953
|
var INTENT_PARAM_MODES = /* @__PURE__ */ new Set(["optional", "required", "off"]);
|
|
954
|
+
var USER_ID_MODES = /* @__PURE__ */ new Set(["hashed", "raw"]);
|
|
828
955
|
function resolveTenantId(explicit, vendorId) {
|
|
829
956
|
if (explicit) return explicit;
|
|
830
957
|
const fromEnv = typeof process !== "undefined" ? process.env?.BATON_TENANT_ID : void 0;
|
|
831
958
|
if (fromEnv) return fromEnv;
|
|
832
959
|
return vendorId;
|
|
833
960
|
}
|
|
961
|
+
function resolveUserIdHmacKey(explicit) {
|
|
962
|
+
if (explicit !== void 0) return explicit;
|
|
963
|
+
const fromEnv = typeof process !== "undefined" ? process.env?.BATON_USER_ID_HMAC_KEY : void 0;
|
|
964
|
+
return fromEnv ? fromEnv : void 0;
|
|
965
|
+
}
|
|
834
966
|
function resolveBatonConfig(config) {
|
|
835
967
|
const dsnString = selectDsn(
|
|
836
968
|
config.dsn,
|
|
@@ -912,6 +1044,17 @@ function validateBatonConfig(config) {
|
|
|
912
1044
|
`BatonConfig.intentParamMode ${JSON.stringify(config.intentParamMode)} must be one of ${JSON.stringify([...INTENT_PARAM_MODES].sort())}.`
|
|
913
1045
|
);
|
|
914
1046
|
}
|
|
1047
|
+
if (config.resolveUser !== void 0 && typeof config.resolveUser !== "function") {
|
|
1048
|
+
throw new Error("BatonConfig.resolveUser must be a function.");
|
|
1049
|
+
}
|
|
1050
|
+
if (config.userIdHmacKey !== void 0 && typeof config.userIdHmacKey !== "string" && !(config.userIdHmacKey instanceof Uint8Array)) {
|
|
1051
|
+
throw new Error("BatonConfig.userIdHmacKey must be a string or a Uint8Array.");
|
|
1052
|
+
}
|
|
1053
|
+
if (config.userIdMode !== void 0 && !USER_ID_MODES.has(config.userIdMode)) {
|
|
1054
|
+
throw new Error(
|
|
1055
|
+
`BatonConfig.userIdMode ${JSON.stringify(config.userIdMode)} must be one of ${JSON.stringify([...USER_ID_MODES].sort())}.`
|
|
1056
|
+
);
|
|
1057
|
+
}
|
|
915
1058
|
}
|
|
916
1059
|
|
|
917
1060
|
// src/optout.ts
|
|
@@ -1263,12 +1406,23 @@ function batonWrap(nameRef, original, ctx) {
|
|
|
1263
1406
|
const scrubbedExpected = rawExpected !== null ? ctx.scrubber(rawExpected) : null;
|
|
1264
1407
|
const scrubbedWorkflow = rawWorkflow !== null ? ctx.scrubber(rawWorkflow) : null;
|
|
1265
1408
|
const callId = uuidv72();
|
|
1409
|
+
const userId = await resolveCallUserId(
|
|
1410
|
+
ctx.resolveUser,
|
|
1411
|
+
{ extra, toolName, arguments: params },
|
|
1412
|
+
{ mode: ctx.userIdMode, tenantId: ctx.tenantId, key: ctx.userIdHmacKey }
|
|
1413
|
+
);
|
|
1266
1414
|
const common = {
|
|
1267
1415
|
tenant_id: ctx.tenantId,
|
|
1268
1416
|
vendor_id: ctx.vendorId,
|
|
1269
1417
|
session_id: sessionId,
|
|
1270
1418
|
consent_token: ctx.consentToken,
|
|
1271
1419
|
agent_runtime: runtime,
|
|
1420
|
+
// The four `...common` sites below are the tool-call legs and the
|
|
1421
|
+
// proactive annotation — the same four Python stamps
|
|
1422
|
+
// (`middleware.py` 481/524/562/606). `surface_snapshot` is deliberately
|
|
1423
|
+
// NOT among them: it describes the SERVER and is captured outside any
|
|
1424
|
+
// call, so there is no caller to name (register D5).
|
|
1425
|
+
user_id: userId,
|
|
1272
1426
|
runtime_meta: scrubbedMeta
|
|
1273
1427
|
};
|
|
1274
1428
|
if (scrubbedIntent !== null && ctx.tracker.claim(sessionId)) {
|
|
@@ -1571,12 +1725,16 @@ function withBaton(server, supplied = {}) {
|
|
|
1571
1725
|
annotationToolName,
|
|
1572
1726
|
intentParamMode,
|
|
1573
1727
|
paramRegistry: /* @__PURE__ */ new Map(),
|
|
1728
|
+
resolveUser: config.resolveUser,
|
|
1729
|
+
userIdMode: config.userIdMode ?? "hashed",
|
|
1730
|
+
userIdHmacKey: resolveUserIdHmacKey(config.userIdHmacKey),
|
|
1574
1731
|
vendorToolJsonSchema,
|
|
1575
1732
|
bustSchemaMemo,
|
|
1576
1733
|
tracker,
|
|
1577
1734
|
surfaceState,
|
|
1578
1735
|
emitSurface
|
|
1579
1736
|
};
|
|
1737
|
+
warnIfIdentityCannotResolve(ctx);
|
|
1580
1738
|
const instructions = buildServerInstructions({
|
|
1581
1739
|
vendorDisplayName: config.vendorDisplayName,
|
|
1582
1740
|
annotationToolName
|
|
@@ -1589,6 +1747,15 @@ function withBaton(server, supplied = {}) {
|
|
|
1589
1747
|
vendorId: ctx.vendorId,
|
|
1590
1748
|
vendorDisplayName: config.vendorDisplayName,
|
|
1591
1749
|
consentToken: ctx.consentToken,
|
|
1750
|
+
// Read off `ctx`, never re-resolved from `config`: the two paths must
|
|
1751
|
+
// agree on the actor, and `userIdMode`/`userIdHmacKey` each have a
|
|
1752
|
+
// default and an env fallback that a second resolution could take
|
|
1753
|
+
// differently. Required (not optional) on the options type ON PURPOSE —
|
|
1754
|
+
// the compiler then refuses a registration that forgets them, which is
|
|
1755
|
+
// the mechanical version of "wiring two of four call sites".
|
|
1756
|
+
resolveUser: ctx.resolveUser,
|
|
1757
|
+
userIdMode: ctx.userIdMode,
|
|
1758
|
+
userIdHmacKey: ctx.userIdHmacKey,
|
|
1592
1759
|
fallbackSessionId: ctx.fallbackSessionId,
|
|
1593
1760
|
scrubber: ctx.scrubber,
|
|
1594
1761
|
annotationToolName: config.annotationToolName,
|
|
@@ -1633,6 +1800,8 @@ export {
|
|
|
1633
1800
|
ToolCallErrorPayloadSchema,
|
|
1634
1801
|
ToolCallStartEventSchema,
|
|
1635
1802
|
ToolCallStartPayloadSchema,
|
|
1803
|
+
VENDOR_HASH_SCHEME,
|
|
1804
|
+
hashUserId,
|
|
1636
1805
|
identityScrub,
|
|
1637
1806
|
safeWrite,
|
|
1638
1807
|
withBaton
|