@goodtiming/baton-sdk 0.5.0 → 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/dist/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  // src/version.ts
2
- var SDK_VERSION = "ts-0.5.0";
2
+ var SDK_VERSION = "ts-0.5.2";
3
3
 
4
4
  // src/events.ts
5
5
  import { z } from "zod";
@@ -99,7 +99,8 @@ var DEFAULT_CONSENT_TOKEN = "customer-consented";
99
99
  var PrincipalWireSchema = z.object({
100
100
  id: z.string(),
101
101
  source: z.string(),
102
- form: z.string()
102
+ form: z.string(),
103
+ display_name: z.string().nullable().optional()
103
104
  }).strict();
104
105
  var envelopeShape = {
105
106
  event_id: z.uuid().default(() => uuidv7()),
@@ -638,10 +639,12 @@ function roundMetaCoordinates(meta) {
638
639
  return walk(meta, 0);
639
640
  }
640
641
 
641
- // src/identity.ts
642
- import { createHmac } from "crypto";
643
-
644
642
  // src/_text.ts
643
+ function exceedsCodePoints(value, max) {
644
+ if (value.length <= max) return false;
645
+ if (value.length > 2 * max) return true;
646
+ return [...value].length > max;
647
+ }
645
648
  function capCodePoints(value, max) {
646
649
  if (value.length <= max) return value;
647
650
  return [...value].slice(0, max).join("");
@@ -651,57 +654,52 @@ function capCodePoints(value, max) {
651
654
  var PRINCIPAL_SOURCE_ASSERTED = "asserted";
652
655
  var PRINCIPAL_FORM_HASHED = "hashed";
653
656
  var PRINCIPAL_FORM_RAW = "raw";
654
- var RAW_PRINCIPAL_ID_MAX_LEN = 128;
655
- var PRINCIPAL_ID_MODE_HASHED = "hashed";
656
- var PRINCIPAL_ID_MODE_RAW = "raw";
657
- var FORM_BY_MODE = {
658
- [PRINCIPAL_ID_MODE_HASHED]: PRINCIPAL_FORM_HASHED,
659
- [PRINCIPAL_ID_MODE_RAW]: PRINCIPAL_FORM_RAW
660
- };
661
- var PRINCIPAL_ID_MODES = Object.keys(
662
- FORM_BY_MODE
663
- );
657
+ var PRINCIPAL_ID_MAX_LEN = 128;
658
+ var DISPLAY_NAME_MAX_LEN = 128;
659
+ var ALL_WHITE_SPACE = /^\p{White_Space}*$/u;
660
+ function wireDisplayName(value) {
661
+ if (typeof value !== "string" || exceedsCodePoints(value, DISPLAY_NAME_MAX_LEN)) return null;
662
+ if (LONE_SURROGATE.test(value) || value.includes("\0") || ALL_WHITE_SPACE.test(value)) return null;
663
+ return value;
664
+ }
665
+ var PRINCIPAL_FORMS = /* @__PURE__ */ new Set([PRINCIPAL_FORM_RAW, PRINCIPAL_FORM_HASHED]);
664
666
  var PYTHON_WHITESPACE = "\\t\\n\\v\\f\\r\\x1c-\\x1f \\x85\\xa0\\u1680\\u2000-\\u200a\\u2028\\u2029\\u202f\\u205f\\u3000";
665
667
  var PYTHON_STRIP = new RegExp(`^[${PYTHON_WHITESPACE}]+|[${PYTHON_WHITESPACE}]+$`, "gu");
666
668
  var LONE_SURROGATE = /\p{Surrogate}/u;
667
- function canonicalize(rawPrincipal) {
668
- return pythonStrip(rawPrincipal.normalize("NFC")).toLowerCase();
669
- }
670
669
  function pythonStrip(value) {
671
670
  return value.replace(PYTHON_STRIP, "");
672
671
  }
673
- function hashPrincipalId(rawPrincipal, options) {
674
- const { tenantId, key, issuer = null } = options;
675
- let message = `${tenantId}\0${canonicalize(rawPrincipal)}`;
676
- if (issuer !== null) {
677
- message += `\0${canonicalize(issuer)}`;
678
- }
679
- const keyBytes = typeof key === "string" ? Buffer.from(key, "utf8") : key;
680
- return createHmac("sha256", keyBytes).update(message, "utf8").digest("hex");
681
- }
682
672
  function normalizePrincipal(result) {
683
673
  if (result === null || typeof result !== "object") return null;
684
674
  const candidate = result;
685
675
  if (typeof candidate.principalId !== "string") return null;
686
676
  if (LONE_SURROGATE.test(candidate.principalId)) return null;
687
- if (canonicalize(candidate.principalId) === "") return null;
688
- const issuerRaw = typeof candidate.issuer === "string" && candidate.issuer ? candidate.issuer : null;
689
- const issuer = issuerRaw !== null && !LONE_SURROGATE.test(issuerRaw) ? issuerRaw : null;
690
- return { principalId: candidate.principalId, issuer };
691
- }
692
- function principalFor(principal, options) {
693
- let id;
694
- if (options.mode === PRINCIPAL_ID_MODE_RAW) {
695
- id = capCodePoints(principal.principalId, RAW_PRINCIPAL_ID_MAX_LEN);
696
- } else {
697
- if (options.key === null || options.key === void 0) return null;
698
- id = hashPrincipalId(principal.principalId, {
699
- tenantId: options.tenantId,
700
- key: options.key,
701
- issuer: principal.issuer ?? null
702
- });
677
+ if (candidate.principalId.includes("\0")) return null;
678
+ if (pythonStrip(candidate.principalId) === "") return null;
679
+ const principal = { principalId: candidate.principalId };
680
+ if (candidate.form !== void 0) principal.form = candidate.form;
681
+ if (typeof candidate.displayName === "string") principal.displayName = candidate.displayName;
682
+ return principal;
683
+ }
684
+ function principalFor(principal, onUnregisteredForm) {
685
+ let form = PRINCIPAL_FORM_RAW;
686
+ if (principal.form !== void 0) {
687
+ if (PRINCIPAL_FORMS.has(principal.form)) {
688
+ form = principal.form;
689
+ } else {
690
+ onUnregisteredForm?.(principal.form);
691
+ }
703
692
  }
704
- return { id, source: PRINCIPAL_SOURCE_ASSERTED, form: FORM_BY_MODE[options.mode] };
693
+ const wire = {
694
+ // `capCodePoints`, not `.slice()`: a plain slice counts UTF-16 units, so
695
+ // an astral id cut at the boundary would ship a lone surrogate.
696
+ id: capCodePoints(principal.principalId, PRINCIPAL_ID_MAX_LEN),
697
+ source: PRINCIPAL_SOURCE_ASSERTED,
698
+ form
699
+ };
700
+ const displayName = wireDisplayName(principal.displayName);
701
+ if (displayName !== null) wire.display_name = displayName;
702
+ return wire;
705
703
  }
706
704
 
707
705
  // src/integrations/mcp/llmText.ts
@@ -807,12 +805,18 @@ function slugServerName(serverName) {
807
805
  const collapsed = mapped.replace(/-+/g, "-").replace(/^-+|-+$/g, "");
808
806
  return collapsed.slice(0, SLUG_CAP).replace(/^-+|-+$/g, "") || void 0;
809
807
  }
808
+ function toolNameCandidate(serverName) {
809
+ const slug = slugServerName(serverName);
810
+ if (slug === void 0) return void 0;
811
+ const candidate = `${slug}${SUFFIX}`;
812
+ return TOOL_NAME_PATTERN.test(candidate) ? candidate : void 0;
813
+ }
810
814
  function displayNameFromServer(serverName, tool) {
811
815
  if (serverName === void 0) return void 0;
812
- const fallbackToolName = tool.annotationToolName || `${tool.vendorId}${SUFFIX}`;
813
- if (!fitsInstructionsCap({ vendorDisplayName: serverName, annotationToolName: fallbackToolName })) {
816
+ const proposed = tool.annotationToolName || toolNameCandidate(serverName) || `${tool.vendorId}${SUFFIX}`;
817
+ if (!fitsInstructionsCap({ vendorDisplayName: serverName, annotationToolName: proposed })) {
814
818
  warn(
815
- `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.`
819
+ `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.`
816
820
  );
817
821
  return void 0;
818
822
  }
@@ -820,10 +824,8 @@ function displayNameFromServer(serverName, tool) {
820
824
  }
821
825
  function annotationToolNameFromServer(serverName, vendorDisplayName) {
822
826
  if (serverName === void 0) return void 0;
823
- const slug = slugServerName(serverName);
824
- if (slug === void 0) return void 0;
825
- const candidate = `${slug}${SUFFIX}`;
826
- if (!TOOL_NAME_PATTERN.test(candidate)) return void 0;
827
+ const candidate = toolNameCandidate(serverName);
828
+ if (candidate === void 0) return void 0;
827
829
  if (!fitsInstructionsCap({ vendorDisplayName, annotationToolName: candidate })) {
828
830
  warn(
829
831
  `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.`
@@ -862,6 +864,10 @@ async function emit(sink, build) {
862
864
  }
863
865
 
864
866
  // src/integrations/mcp/mcpTypes.ts
867
+ function extraAuthInfo(extra) {
868
+ const found = extra.authInfo ?? extra.http?.authInfo;
869
+ return found !== null && typeof found === "object" ? found : null;
870
+ }
865
871
  function extraMeta(extra) {
866
872
  const direct = extra._meta;
867
873
  if (direct) return direct;
@@ -906,19 +912,10 @@ function buildPrincipalResolutionContext(extra, toolName, args) {
906
912
  headers: extraHeaders(extra),
907
913
  meta: extraMeta(extra),
908
914
  toolName,
909
- arguments: args
915
+ arguments: args,
916
+ authInfo: extraAuthInfo(extra)
910
917
  };
911
918
  }
912
- function warnIfIdentityCannotResolve(config) {
913
- if (config.resolvePrincipal === void 0) return;
914
- if (config.principalIdMode !== PRINCIPAL_ID_MODE_HASHED) return;
915
- if (config.principalIdHmacKey !== void 0) return;
916
- if (typeof process === "undefined" || typeof process.emitWarning !== "function") return;
917
- 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. " : "";
918
- process.emitWarning(
919
- `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.`
920
- );
921
- }
922
919
  var warnedPreRenameShape = false;
923
920
  function warnIfPreRenameShape(result) {
924
921
  const userId = result?.userId;
@@ -928,30 +925,28 @@ function warnIfPreRenameShape(result) {
928
925
  "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."
929
926
  );
930
927
  }
931
- async function resolveCallPrincipal(hook, call, options) {
928
+ async function resolveCallPrincipal(hook, call) {
932
929
  if (hook === void 0) return null;
933
- let result;
934
930
  try {
935
931
  const context = buildPrincipalResolutionContext(call.extra, call.toolName, call.arguments);
936
- result = await hook(context);
937
- } catch {
938
- return null;
939
- }
940
- const principal = normalizePrincipal(result);
941
- if (principal === null) {
942
- warnIfPreRenameShape(result);
943
- return null;
944
- }
945
- try {
946
- return principalFor(principal, {
947
- mode: options.mode,
948
- tenantId: options.tenantId,
949
- key: options.key
932
+ const result = await hook(context);
933
+ const principal = normalizePrincipal(result);
934
+ if (principal === null) {
935
+ warnIfPreRenameShape(result);
936
+ return null;
937
+ }
938
+ return principalFor(principal, (form) => {
939
+ warn(
940
+ `baton: resolvePrincipal returned form ${describeForm(form)}, expected "raw" or "hashed" \u2014 sending it as "${PRINCIPAL_FORM_RAW}".`
941
+ );
950
942
  });
951
943
  } catch {
952
944
  return null;
953
945
  }
954
946
  }
947
+ function describeForm(form) {
948
+ return typeof form === "string" ? JSON.stringify(form.slice(0, 32)) : `of type ${typeof form}`;
949
+ }
955
950
 
956
951
  // src/integrations/mcp/safeScrub.ts
957
952
  var warned = /* @__PURE__ */ new Set();
@@ -1066,12 +1061,7 @@ function registerAnnotationTool(server, options) {
1066
1061
  }
1067
1062
  const principal = await resolveCallPrincipal(
1068
1063
  options.resolvePrincipal,
1069
- { extra, toolName: name, arguments: args },
1070
- {
1071
- mode: options.principalIdMode,
1072
- tenantId: options.tenantId,
1073
- key: options.principalIdHmacKey
1074
- }
1064
+ { extra, toolName: name, arguments: args }
1075
1065
  );
1076
1066
  await emit(
1077
1067
  options.sink,
@@ -1385,18 +1375,12 @@ function requestSideErrorFields(text, errorBody2) {
1385
1375
  // src/integrations/mcp/config.ts
1386
1376
  var INTENT_PARAM_MODES = /* @__PURE__ */ new Set(["optional", "required", "off"]);
1387
1377
  var RESULT_CAPTURE_MODE_SET = new Set(RESULT_CAPTURE_MODES);
1388
- var PRINCIPAL_ID_MODE_SET = new Set(PRINCIPAL_ID_MODES);
1389
1378
  function resolveTenantId(explicit, vendorId) {
1390
1379
  if (explicit) return explicit;
1391
1380
  const fromEnv = typeof process !== "undefined" ? process.env?.BATON_TENANT_ID : void 0;
1392
1381
  if (fromEnv) return fromEnv;
1393
1382
  return vendorId;
1394
1383
  }
1395
- function resolvePrincipalIdHmacKey(explicit) {
1396
- if (explicit !== void 0) return explicit;
1397
- const fromEnv = typeof process !== "undefined" ? process.env?.BATON_PRINCIPAL_ID_HMAC_KEY : void 0;
1398
- return fromEnv ? fromEnv : void 0;
1399
- }
1400
1384
  function resolveBatonConfig(config, serverName) {
1401
1385
  const dsnString = selectDsn(
1402
1386
  config.dsn,
@@ -1455,9 +1439,7 @@ function resolveBatonConfig(config, serverName) {
1455
1439
  };
1456
1440
  }
1457
1441
  var RENAMED_KEYS = {
1458
- resolveUser: "resolvePrincipal",
1459
- userIdMode: "principalIdMode",
1460
- userIdHmacKey: "principalIdHmacKey"
1442
+ resolveUser: "resolvePrincipal"
1461
1443
  };
1462
1444
  function validateBatonConfig(config) {
1463
1445
  for (const [was, now] of Object.entries(RENAMED_KEYS)) {
@@ -1506,14 +1488,6 @@ function validateBatonConfig(config) {
1506
1488
  if (config.resolvePrincipal !== void 0 && typeof config.resolvePrincipal !== "function") {
1507
1489
  throw new Error("BatonConfig.resolvePrincipal must be a function.");
1508
1490
  }
1509
- if (config.principalIdHmacKey !== void 0 && typeof config.principalIdHmacKey !== "string" && !(config.principalIdHmacKey instanceof Uint8Array)) {
1510
- throw new Error("BatonConfig.principalIdHmacKey must be a string or a Uint8Array.");
1511
- }
1512
- if (config.principalIdMode !== void 0 && !PRINCIPAL_ID_MODE_SET.has(config.principalIdMode)) {
1513
- throw new Error(
1514
- `BatonConfig.principalIdMode ${JSON.stringify(config.principalIdMode)} must be one of ${JSON.stringify([...PRINCIPAL_ID_MODE_SET].sort())}.`
1515
- );
1516
- }
1517
1491
  }
1518
1492
 
1519
1493
  // src/optout.ts
@@ -1898,8 +1872,7 @@ async function openCall(ctx, toolName, extra, params, registered = true) {
1898
1872
  const callId = uuidv72();
1899
1873
  const principal = await resolveCallPrincipal(
1900
1874
  ctx.resolvePrincipal,
1901
- { extra, toolName, arguments: params },
1902
- { mode: ctx.principalIdMode, tenantId: ctx.tenantId, key: ctx.principalIdHmacKey }
1875
+ { extra, toolName, arguments: params }
1903
1876
  );
1904
1877
  const common = {
1905
1878
  tenant_id: ctx.tenantId,
@@ -2662,15 +2635,12 @@ function withBaton(server, supplied = {}) {
2662
2635
  resultCaptureMode: config.resultCaptureMode ?? "full",
2663
2636
  paramRegistry: /* @__PURE__ */ new Map(),
2664
2637
  resolvePrincipal: config.resolvePrincipal,
2665
- principalIdMode: config.principalIdMode ?? "hashed",
2666
- principalIdHmacKey: resolvePrincipalIdHmacKey(config.principalIdHmacKey),
2667
2638
  vendorToolJsonSchema,
2668
2639
  bustSchemaMemo,
2669
2640
  tracker,
2670
2641
  surfaceState,
2671
2642
  emitSurface
2672
2643
  };
2673
- warnIfIdentityCannotResolve(ctx);
2674
2644
  const instructions = buildServerInstructions({
2675
2645
  vendorDisplayName: config.vendorDisplayName,
2676
2646
  annotationToolName
@@ -2700,15 +2670,7 @@ function withBaton(server, supplied = {}) {
2700
2670
  vendorId: ctx.vendorId,
2701
2671
  vendorDisplayName: config.vendorDisplayName,
2702
2672
  consentToken: ctx.consentToken,
2703
- // Read off `ctx`, never re-resolved from `config`: the two paths must
2704
- // agree on the actor, and `principalIdMode`/`principalIdHmacKey` each have a
2705
- // default and an env fallback that a second resolution could take
2706
- // differently. Required (not optional) on the options type ON PURPOSE —
2707
- // the compiler then refuses a registration that forgets them, which is
2708
- // the mechanical version of "wiring two of four call sites".
2709
2673
  resolvePrincipal: ctx.resolvePrincipal,
2710
- principalIdMode: ctx.principalIdMode,
2711
- principalIdHmacKey: ctx.principalIdHmacKey,
2712
2674
  fallbackSessionId: ctx.fallbackSessionId,
2713
2675
  scrubber: ctx.scrubber,
2714
2676
  // The RESOLVED name, never `config.annotationToolName`: handing over the
@@ -2736,6 +2698,37 @@ function withBaton(server, supplied = {}) {
2736
2698
  annotationToolName: resolvedAnnotationToolName
2737
2699
  });
2738
2700
  }
2701
+
2702
+ // src/integrations/mcp/oauthHooks.ts
2703
+ function claimsOf(context) {
2704
+ try {
2705
+ const extra = context.authInfo?.extra;
2706
+ return extra !== null && typeof extra === "object" ? extra : null;
2707
+ } catch {
2708
+ return null;
2709
+ }
2710
+ }
2711
+ function stringClaim(claims, name) {
2712
+ const value = claims[name];
2713
+ return typeof value === "string" && pythonStrip(value) !== "" ? value : null;
2714
+ }
2715
+ function principalFromOAuthSub(context) {
2716
+ const claims = claimsOf(context);
2717
+ if (claims === null) return null;
2718
+ const sub = stringClaim(claims, "sub");
2719
+ return sub === null ? null : { principalId: sub };
2720
+ }
2721
+ function principalFromOAuthEmail(context) {
2722
+ const claims = claimsOf(context);
2723
+ if (claims === null) return null;
2724
+ const email = stringClaim(claims, "email");
2725
+ if (email === null) return null;
2726
+ const at = email.lastIndexOf("@");
2727
+ return {
2728
+ principalId: email,
2729
+ displayName: at > 0 ? email.slice(0, at) : null
2730
+ };
2731
+ }
2739
2732
  export {
2740
2733
  AnnotationEventSchema,
2741
2734
  AnnotationPayloadSchema,
@@ -2784,8 +2777,9 @@ export {
2784
2777
  ToolCallErrorPayloadSchema,
2785
2778
  ToolCallStartEventSchema,
2786
2779
  ToolCallStartPayloadSchema,
2787
- hashPrincipalId,
2788
2780
  identityScrub,
2781
+ principalFromOAuthEmail,
2782
+ principalFromOAuthSub,
2789
2783
  safeWrite,
2790
2784
  withBaton
2791
2785
  };