@goodtiming/baton-sdk 0.5.1 → 0.5.2

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/README.md CHANGED
@@ -62,11 +62,11 @@ withBaton(server, {
62
62
  });
63
63
  ```
64
64
 
65
- `principalFromOAuthEmail` keys on the token's `email` claim (the whole address); `principalFromOAuthSub` on its subject and issuer. Each returns `null` when the claim is missing, so they compose: `(ctx) => principalFromOAuthEmail(ctx) ?? principalFromOAuthSub(ctx)`. Set `displayName` on the returned `Principal` to choose what your dashboard shows for a person; it is sent as-is, even when ids are hashed. The email hook sets it to the part before `@`.
65
+ `principalFromOAuthEmail` keys on the token's `email` claim (the whole address); `principalFromOAuthSub` on its subject. Each returns `null` when the claim is missing, so they compose: `(ctx) => principalFromOAuthEmail(ctx) ?? principalFromOAuthSub(ctx)`. Set `displayName` on the returned `Principal` to choose what your dashboard shows for a person; it is sent as-is. The email hook sets it to the part before `@`.
66
66
 
67
67
  ⚠ **They read the claims from `authInfo.extra`.** The MCP SDK's `AuthInfo` has no `claims` field, so these hooks expect your token verifier to put the decoded JWT claims (`sub`, `iss`, `email`) at the top level of `extra`. If yours keeps them elsewhere, write the three-line hook that reads them from there. A token exists only on HTTP with auth configured; on stdio, write a hook that names the user from whatever you authenticated them with.
68
68
 
69
- The value is HMAC-hashed in your process before it is sent, keyed with `BATON_PRINCIPAL_ID_HMAC_KEY`; without a key, nothing is attached.
69
+ The id is sent exactly as your hook returns it, so the hook decides what is safe to send. To send a pseudonym instead, hash the id inside your hook and return `form: "hashed"` with it.
70
70
 
71
71
  ## Not capturing responses at all
72
72
 
package/dist/index.cjs CHANGED
@@ -77,7 +77,6 @@ __export(index_exports, {
77
77
  ToolCallErrorPayloadSchema: () => ToolCallErrorPayloadSchema,
78
78
  ToolCallStartEventSchema: () => ToolCallStartEventSchema,
79
79
  ToolCallStartPayloadSchema: () => ToolCallStartPayloadSchema,
80
- hashPrincipalId: () => hashPrincipalId,
81
80
  identityScrub: () => identityScrub,
82
81
  principalFromOAuthEmail: () => principalFromOAuthEmail,
83
82
  principalFromOAuthSub: () => principalFromOAuthSub,
@@ -87,7 +86,7 @@ __export(index_exports, {
87
86
  module.exports = __toCommonJS(index_exports);
88
87
 
89
88
  // src/version.ts
90
- var SDK_VERSION = "ts-0.5.1";
89
+ var SDK_VERSION = "ts-0.5.2";
91
90
 
92
91
  // src/events.ts
93
92
  var import_zod = require("zod");
@@ -727,9 +726,6 @@ function roundMetaCoordinates(meta) {
727
726
  return walk(meta, 0);
728
727
  }
729
728
 
730
- // src/identity.ts
731
- var import_node_crypto = require("crypto");
732
-
733
729
  // src/_text.ts
734
730
  function exceedsCodePoints(value, max) {
735
731
  if (value.length <= max) return false;
@@ -745,7 +741,7 @@ function capCodePoints(value, max) {
745
741
  var PRINCIPAL_SOURCE_ASSERTED = "asserted";
746
742
  var PRINCIPAL_FORM_HASHED = "hashed";
747
743
  var PRINCIPAL_FORM_RAW = "raw";
748
- var RAW_PRINCIPAL_ID_MAX_LEN = 128;
744
+ var PRINCIPAL_ID_MAX_LEN = 128;
749
745
  var DISPLAY_NAME_MAX_LEN = 128;
750
746
  var ALL_WHITE_SPACE = /^\p{White_Space}*$/u;
751
747
  function wireDisplayName(value) {
@@ -753,59 +749,40 @@ function wireDisplayName(value) {
753
749
  if (LONE_SURROGATE.test(value) || value.includes("\0") || ALL_WHITE_SPACE.test(value)) return null;
754
750
  return value;
755
751
  }
756
- var PRINCIPAL_ID_MODE_HASHED = "hashed";
757
- var PRINCIPAL_ID_MODE_RAW = "raw";
758
- var FORM_BY_MODE = {
759
- [PRINCIPAL_ID_MODE_HASHED]: PRINCIPAL_FORM_HASHED,
760
- [PRINCIPAL_ID_MODE_RAW]: PRINCIPAL_FORM_RAW
761
- };
762
- var PRINCIPAL_ID_MODES = Object.keys(
763
- FORM_BY_MODE
764
- );
752
+ var PRINCIPAL_FORMS = /* @__PURE__ */ new Set([PRINCIPAL_FORM_RAW, PRINCIPAL_FORM_HASHED]);
765
753
  var PYTHON_WHITESPACE = "\\t\\n\\v\\f\\r\\x1c-\\x1f \\x85\\xa0\\u1680\\u2000-\\u200a\\u2028\\u2029\\u202f\\u205f\\u3000";
766
754
  var PYTHON_STRIP = new RegExp(`^[${PYTHON_WHITESPACE}]+|[${PYTHON_WHITESPACE}]+$`, "gu");
767
755
  var LONE_SURROGATE = /\p{Surrogate}/u;
768
- function canonicalize(rawPrincipal) {
769
- return pythonStrip(rawPrincipal.normalize("NFC")).toLowerCase();
770
- }
771
756
  function pythonStrip(value) {
772
757
  return value.replace(PYTHON_STRIP, "");
773
758
  }
774
- function hashPrincipalId(rawPrincipal, options) {
775
- const { tenantId, key, issuer = null } = options;
776
- let message = `${tenantId}\0${canonicalize(rawPrincipal)}`;
777
- if (issuer !== null) {
778
- message += `\0${canonicalize(issuer)}`;
779
- }
780
- const keyBytes = typeof key === "string" ? Buffer.from(key, "utf8") : key;
781
- return (0, import_node_crypto.createHmac)("sha256", keyBytes).update(message, "utf8").digest("hex");
782
- }
783
759
  function normalizePrincipal(result) {
784
760
  if (result === null || typeof result !== "object") return null;
785
761
  const candidate = result;
786
762
  if (typeof candidate.principalId !== "string") return null;
787
763
  if (LONE_SURROGATE.test(candidate.principalId)) return null;
788
- if (canonicalize(candidate.principalId) === "") return null;
789
- const issuerRaw = typeof candidate.issuer === "string" && candidate.issuer ? candidate.issuer : null;
790
- const issuer = issuerRaw !== null && !LONE_SURROGATE.test(issuerRaw) ? issuerRaw : null;
791
- return typeof candidate.displayName === "string" ? { principalId: candidate.principalId, issuer, displayName: candidate.displayName } : { principalId: candidate.principalId, issuer };
792
- }
793
- function principalFor(principal, options) {
794
- let id;
795
- if (options.mode === PRINCIPAL_ID_MODE_RAW) {
796
- id = capCodePoints(principal.principalId, RAW_PRINCIPAL_ID_MAX_LEN);
797
- } else {
798
- if (options.key === null || options.key === void 0) return null;
799
- id = hashPrincipalId(principal.principalId, {
800
- tenantId: options.tenantId,
801
- key: options.key,
802
- issuer: principal.issuer ?? null
803
- });
764
+ if (candidate.principalId.includes("\0")) return null;
765
+ if (pythonStrip(candidate.principalId) === "") return null;
766
+ const principal = { principalId: candidate.principalId };
767
+ if (candidate.form !== void 0) principal.form = candidate.form;
768
+ if (typeof candidate.displayName === "string") principal.displayName = candidate.displayName;
769
+ return principal;
770
+ }
771
+ function principalFor(principal, onUnregisteredForm) {
772
+ let form = PRINCIPAL_FORM_RAW;
773
+ if (principal.form !== void 0) {
774
+ if (PRINCIPAL_FORMS.has(principal.form)) {
775
+ form = principal.form;
776
+ } else {
777
+ onUnregisteredForm?.(principal.form);
778
+ }
804
779
  }
805
780
  const wire = {
806
- id,
781
+ // `capCodePoints`, not `.slice()`: a plain slice counts UTF-16 units, so
782
+ // an astral id cut at the boundary would ship a lone surrogate.
783
+ id: capCodePoints(principal.principalId, PRINCIPAL_ID_MAX_LEN),
807
784
  source: PRINCIPAL_SOURCE_ASSERTED,
808
- form: FORM_BY_MODE[options.mode]
785
+ form
809
786
  };
810
787
  const displayName = wireDisplayName(principal.displayName);
811
788
  if (displayName !== null) wire.display_name = displayName;
@@ -915,12 +892,18 @@ function slugServerName(serverName) {
915
892
  const collapsed = mapped.replace(/-+/g, "-").replace(/^-+|-+$/g, "");
916
893
  return collapsed.slice(0, SLUG_CAP).replace(/^-+|-+$/g, "") || void 0;
917
894
  }
895
+ function toolNameCandidate(serverName) {
896
+ const slug = slugServerName(serverName);
897
+ if (slug === void 0) return void 0;
898
+ const candidate = `${slug}${SUFFIX}`;
899
+ return TOOL_NAME_PATTERN.test(candidate) ? candidate : void 0;
900
+ }
918
901
  function displayNameFromServer(serverName, tool) {
919
902
  if (serverName === void 0) return void 0;
920
- const fallbackToolName = tool.annotationToolName || `${tool.vendorId}${SUFFIX}`;
921
- if (!fitsInstructionsCap({ vendorDisplayName: serverName, annotationToolName: fallbackToolName })) {
903
+ const proposed = tool.annotationToolName || toolNameCandidate(serverName) || `${tool.vendorId}${SUFFIX}`;
904
+ if (!fitsInstructionsCap({ vendorDisplayName: serverName, annotationToolName: proposed })) {
922
905
  warn(
923
- `baton: the server name (${serverName.length} chars) does not fit the server-instructions budget as the display name; keeping the DSN's server segment. Pass vendorDisplayName to choose a shorter one.`
906
+ `baton: the server name (${serverName.length} chars) does not fit the server-instructions budget as the display name beside the annotation tool ${JSON.stringify(proposed)}; keeping the DSN's server segment. Pass vendorDisplayName to name the server in fewer characters.`
924
907
  );
925
908
  return void 0;
926
909
  }
@@ -928,10 +911,8 @@ function displayNameFromServer(serverName, tool) {
928
911
  }
929
912
  function annotationToolNameFromServer(serverName, vendorDisplayName) {
930
913
  if (serverName === void 0) return void 0;
931
- const slug = slugServerName(serverName);
932
- if (slug === void 0) return void 0;
933
- const candidate = `${slug}${SUFFIX}`;
934
- if (!TOOL_NAME_PATTERN.test(candidate)) return void 0;
914
+ const candidate = toolNameCandidate(serverName);
915
+ if (candidate === void 0) return void 0;
935
916
  if (!fitsInstructionsCap({ vendorDisplayName, annotationToolName: candidate })) {
936
917
  warn(
937
918
  `baton: the server-derived annotation tool name ${JSON.stringify(candidate)} does not fit the server-instructions budget beside the display name (${vendorDisplayName.length} chars); keeping {vendorId}_annotate. A shorter display name gets the readable one.`
@@ -1022,16 +1003,6 @@ function buildPrincipalResolutionContext(extra, toolName, args) {
1022
1003
  authInfo: extraAuthInfo(extra)
1023
1004
  };
1024
1005
  }
1025
- function warnIfIdentityCannotResolve(config) {
1026
- if (config.resolvePrincipal === void 0) return;
1027
- if (config.principalIdMode !== PRINCIPAL_ID_MODE_HASHED) return;
1028
- if (config.principalIdHmacKey !== void 0) return;
1029
- if (typeof process === "undefined" || typeof process.emitWarning !== "function") return;
1030
- const renamed = process.env?.BATON_USER_ID_HMAC_KEY ? "BATON_USER_ID_HMAC_KEY is set, but it was renamed to BATON_PRINCIPAL_ID_HMAC_KEY in 0.3.5 and is no longer read. " : "";
1031
- process.emitWarning(
1032
- `baton: resolvePrincipal is configured but no principal HMAC key is set, so the principal is dropped from every event (events still emit). ${renamed}Set BATON_PRINCIPAL_ID_HMAC_KEY or BatonConfig.principalIdHmacKey, or pass principalIdMode: "raw" if you intend to emit the subject verbatim.`
1033
- );
1034
- }
1035
1006
  var warnedPreRenameShape = false;
1036
1007
  function warnIfPreRenameShape(result) {
1037
1008
  const userId = result?.userId;
@@ -1041,30 +1012,28 @@ function warnIfPreRenameShape(result) {
1041
1012
  "baton: resolvePrincipal returned { userId }, which was renamed to { principalId } in 0.3.5, so the principal is dropped from every event until the hook returns the new key."
1042
1013
  );
1043
1014
  }
1044
- async function resolveCallPrincipal(hook, call, options) {
1015
+ async function resolveCallPrincipal(hook, call) {
1045
1016
  if (hook === void 0) return null;
1046
- let result;
1047
1017
  try {
1048
1018
  const context = buildPrincipalResolutionContext(call.extra, call.toolName, call.arguments);
1049
- result = await hook(context);
1050
- } catch {
1051
- return null;
1052
- }
1053
- const principal = normalizePrincipal(result);
1054
- if (principal === null) {
1055
- warnIfPreRenameShape(result);
1056
- return null;
1057
- }
1058
- try {
1059
- return principalFor(principal, {
1060
- mode: options.mode,
1061
- tenantId: options.tenantId,
1062
- key: options.key
1019
+ const result = await hook(context);
1020
+ const principal = normalizePrincipal(result);
1021
+ if (principal === null) {
1022
+ warnIfPreRenameShape(result);
1023
+ return null;
1024
+ }
1025
+ return principalFor(principal, (form) => {
1026
+ warn(
1027
+ `baton: resolvePrincipal returned form ${describeForm(form)}, expected "raw" or "hashed" \u2014 sending it as "${PRINCIPAL_FORM_RAW}".`
1028
+ );
1063
1029
  });
1064
1030
  } catch {
1065
1031
  return null;
1066
1032
  }
1067
1033
  }
1034
+ function describeForm(form) {
1035
+ return typeof form === "string" ? JSON.stringify(form.slice(0, 32)) : `of type ${typeof form}`;
1036
+ }
1068
1037
 
1069
1038
  // src/integrations/mcp/safeScrub.ts
1070
1039
  var warned = /* @__PURE__ */ new Set();
@@ -1179,12 +1148,7 @@ function registerAnnotationTool(server, options) {
1179
1148
  }
1180
1149
  const principal = await resolveCallPrincipal(
1181
1150
  options.resolvePrincipal,
1182
- { extra, toolName: name, arguments: args },
1183
- {
1184
- mode: options.principalIdMode,
1185
- tenantId: options.tenantId,
1186
- key: options.principalIdHmacKey
1187
- }
1151
+ { extra, toolName: name, arguments: args }
1188
1152
  );
1189
1153
  await emit(
1190
1154
  options.sink,
@@ -1498,18 +1462,12 @@ function requestSideErrorFields(text, errorBody2) {
1498
1462
  // src/integrations/mcp/config.ts
1499
1463
  var INTENT_PARAM_MODES = /* @__PURE__ */ new Set(["optional", "required", "off"]);
1500
1464
  var RESULT_CAPTURE_MODE_SET = new Set(RESULT_CAPTURE_MODES);
1501
- var PRINCIPAL_ID_MODE_SET = new Set(PRINCIPAL_ID_MODES);
1502
1465
  function resolveTenantId(explicit, vendorId) {
1503
1466
  if (explicit) return explicit;
1504
1467
  const fromEnv = typeof process !== "undefined" ? process.env?.BATON_TENANT_ID : void 0;
1505
1468
  if (fromEnv) return fromEnv;
1506
1469
  return vendorId;
1507
1470
  }
1508
- function resolvePrincipalIdHmacKey(explicit) {
1509
- if (explicit !== void 0) return explicit;
1510
- const fromEnv = typeof process !== "undefined" ? process.env?.BATON_PRINCIPAL_ID_HMAC_KEY : void 0;
1511
- return fromEnv ? fromEnv : void 0;
1512
- }
1513
1471
  function resolveBatonConfig(config, serverName) {
1514
1472
  const dsnString = selectDsn(
1515
1473
  config.dsn,
@@ -1568,9 +1526,7 @@ function resolveBatonConfig(config, serverName) {
1568
1526
  };
1569
1527
  }
1570
1528
  var RENAMED_KEYS = {
1571
- resolveUser: "resolvePrincipal",
1572
- userIdMode: "principalIdMode",
1573
- userIdHmacKey: "principalIdHmacKey"
1529
+ resolveUser: "resolvePrincipal"
1574
1530
  };
1575
1531
  function validateBatonConfig(config) {
1576
1532
  for (const [was, now] of Object.entries(RENAMED_KEYS)) {
@@ -1619,14 +1575,6 @@ function validateBatonConfig(config) {
1619
1575
  if (config.resolvePrincipal !== void 0 && typeof config.resolvePrincipal !== "function") {
1620
1576
  throw new Error("BatonConfig.resolvePrincipal must be a function.");
1621
1577
  }
1622
- if (config.principalIdHmacKey !== void 0 && typeof config.principalIdHmacKey !== "string" && !(config.principalIdHmacKey instanceof Uint8Array)) {
1623
- throw new Error("BatonConfig.principalIdHmacKey must be a string or a Uint8Array.");
1624
- }
1625
- if (config.principalIdMode !== void 0 && !PRINCIPAL_ID_MODE_SET.has(config.principalIdMode)) {
1626
- throw new Error(
1627
- `BatonConfig.principalIdMode ${JSON.stringify(config.principalIdMode)} must be one of ${JSON.stringify([...PRINCIPAL_ID_MODE_SET].sort())}.`
1628
- );
1629
- }
1630
1578
  }
1631
1579
 
1632
1580
  // src/optout.ts
@@ -1871,10 +1819,10 @@ function toolInputJsonSchema(inputSchema) {
1871
1819
  }
1872
1820
 
1873
1821
  // src/integrations/mcp/surface.ts
1874
- var import_node_crypto2 = require("crypto");
1822
+ var import_node_crypto = require("crypto");
1875
1823
  function surfaceHash(surface) {
1876
1824
  const canonical = canonicalJson(surface);
1877
- const digest = (0, import_node_crypto2.createHash)("sha256").update(canonical, "utf-8").digest("hex");
1825
+ const digest = (0, import_node_crypto.createHash)("sha256").update(canonical, "utf-8").digest("hex");
1878
1826
  return `sha256:${digest}`;
1879
1827
  }
1880
1828
  function canonicalJson(value) {
@@ -2011,8 +1959,7 @@ async function openCall(ctx, toolName, extra, params, registered = true) {
2011
1959
  const callId = (0, import_uuid2.v7)();
2012
1960
  const principal = await resolveCallPrincipal(
2013
1961
  ctx.resolvePrincipal,
2014
- { extra, toolName, arguments: params },
2015
- { mode: ctx.principalIdMode, tenantId: ctx.tenantId, key: ctx.principalIdHmacKey }
1962
+ { extra, toolName, arguments: params }
2016
1963
  );
2017
1964
  const common = {
2018
1965
  tenant_id: ctx.tenantId,
@@ -2775,15 +2722,12 @@ function withBaton(server, supplied = {}) {
2775
2722
  resultCaptureMode: config.resultCaptureMode ?? "full",
2776
2723
  paramRegistry: /* @__PURE__ */ new Map(),
2777
2724
  resolvePrincipal: config.resolvePrincipal,
2778
- principalIdMode: config.principalIdMode ?? "hashed",
2779
- principalIdHmacKey: resolvePrincipalIdHmacKey(config.principalIdHmacKey),
2780
2725
  vendorToolJsonSchema,
2781
2726
  bustSchemaMemo,
2782
2727
  tracker,
2783
2728
  surfaceState,
2784
2729
  emitSurface
2785
2730
  };
2786
- warnIfIdentityCannotResolve(ctx);
2787
2731
  const instructions = buildServerInstructions({
2788
2732
  vendorDisplayName: config.vendorDisplayName,
2789
2733
  annotationToolName
@@ -2813,15 +2757,7 @@ function withBaton(server, supplied = {}) {
2813
2757
  vendorId: ctx.vendorId,
2814
2758
  vendorDisplayName: config.vendorDisplayName,
2815
2759
  consentToken: ctx.consentToken,
2816
- // Read off `ctx`, never re-resolved from `config`: the two paths must
2817
- // agree on the actor, and `principalIdMode`/`principalIdHmacKey` each have a
2818
- // default and an env fallback that a second resolution could take
2819
- // differently. Required (not optional) on the options type ON PURPOSE —
2820
- // the compiler then refuses a registration that forgets them, which is
2821
- // the mechanical version of "wiring two of four call sites".
2822
2760
  resolvePrincipal: ctx.resolvePrincipal,
2823
- principalIdMode: ctx.principalIdMode,
2824
- principalIdHmacKey: ctx.principalIdHmacKey,
2825
2761
  fallbackSessionId: ctx.fallbackSessionId,
2826
2762
  scrubber: ctx.scrubber,
2827
2763
  // The RESOLVED name, never `config.annotationToolName`: handing over the
@@ -2867,8 +2803,7 @@ function principalFromOAuthSub(context) {
2867
2803
  const claims = claimsOf(context);
2868
2804
  if (claims === null) return null;
2869
2805
  const sub = stringClaim(claims, "sub");
2870
- const iss = claims.iss;
2871
- return sub === null ? null : { principalId: sub, issuer: typeof iss === "string" && iss !== "" ? iss : null };
2806
+ return sub === null ? null : { principalId: sub };
2872
2807
  }
2873
2808
  function principalFromOAuthEmail(context) {
2874
2809
  const claims = claimsOf(context);
@@ -2930,7 +2865,6 @@ function principalFromOAuthEmail(context) {
2930
2865
  ToolCallErrorPayloadSchema,
2931
2866
  ToolCallStartEventSchema,
2932
2867
  ToolCallStartPayloadSchema,
2933
- hashPrincipalId,
2934
2868
  identityScrub,
2935
2869
  principalFromOAuthEmail,
2936
2870
  principalFromOAuthSub,