@tangle-network/agent-app 0.43.24 → 0.43.25

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.
Files changed (50) hide show
  1. package/dist/app-auth/index.d.ts +163 -0
  2. package/dist/app-auth/index.js +166 -0
  3. package/dist/app-auth/index.js.map +1 -0
  4. package/dist/assets/index.d.ts +2 -2
  5. package/dist/assistant/index.d.ts +1 -0
  6. package/dist/assistant/index.js +2 -1
  7. package/dist/assistant/index.js.map +1 -1
  8. package/dist/chat-store/index.d.ts +193 -0
  9. package/dist/chat-store/index.js +194 -0
  10. package/dist/chat-store/index.js.map +1 -0
  11. package/dist/chunk-4H77LX3V.js +38 -0
  12. package/dist/chunk-4H77LX3V.js.map +1 -0
  13. package/dist/chunk-4TXDD6P2.js +163 -0
  14. package/dist/chunk-4TXDD6P2.js.map +1 -0
  15. package/dist/chunk-AVBANQ67.js +295 -0
  16. package/dist/chunk-AVBANQ67.js.map +1 -0
  17. package/dist/{chunk-3PK3T4KD.js → chunk-JJGZ54EB.js} +44 -1
  18. package/dist/chunk-JJGZ54EB.js.map +1 -0
  19. package/dist/{chunk-VMY4TKMN.js → chunk-PEPXQTJ3.js} +921 -432
  20. package/dist/chunk-PEPXQTJ3.js.map +1 -0
  21. package/dist/chunk-U7DLCPJ6.js +203 -0
  22. package/dist/chunk-U7DLCPJ6.js.map +1 -0
  23. package/dist/{chunk-SAOAAA3S.js → chunk-UHXQ3KNX.js} +1 -22
  24. package/dist/chunk-UHXQ3KNX.js.map +1 -0
  25. package/dist/contract-DYbTzEDf.d.ts +122 -0
  26. package/dist/index.d.ts +5 -2
  27. package/dist/index.js +170 -88
  28. package/dist/interactions/index.d.ts +141 -0
  29. package/dist/interactions/index.js +59 -0
  30. package/dist/interactions/index.js.map +1 -0
  31. package/dist/parts-BeRnK54I.d.ts +185 -0
  32. package/dist/platform/index.d.ts +2 -270
  33. package/dist/platform/index.js +12 -278
  34. package/dist/platform/index.js.map +1 -1
  35. package/dist/preset-cloudflare/index.d.ts +0 -10
  36. package/dist/preset-cloudflare/index.js +1 -1
  37. package/dist/profile/index.d.ts +33 -2
  38. package/dist/profile/index.js +37 -1
  39. package/dist/profile/index.js.map +1 -1
  40. package/dist/sandbox/index.d.ts +47 -1
  41. package/dist/sandbox/index.js +11 -1
  42. package/dist/sso-Df4wtL8D.d.ts +270 -0
  43. package/dist/teams/index.js +9 -9
  44. package/dist/teams/invitations-api.js +3 -3
  45. package/dist/web-react/index.d.ts +206 -96
  46. package/dist/web-react/index.js +68 -22
  47. package/package.json +20 -1
  48. package/dist/chunk-3PK3T4KD.js.map +0 -1
  49. package/dist/chunk-SAOAAA3S.js.map +0 -1
  50. package/dist/chunk-VMY4TKMN.js.map +0 -1
@@ -0,0 +1,163 @@
1
+ // src/interactions/contract.ts
2
+ import {
3
+ InteractionRequestSchema
4
+ } from "@tangle-network/agent-interface";
5
+ var INTERACTION_EVENT = "interaction";
6
+ var INTERACTION_CANCEL_EVENT = "interaction.cancel";
7
+ var INTERACTION_RESOLVED_EVENT = "interaction.resolved";
8
+ var RENDERABLE_INTERACTION_KINDS = /* @__PURE__ */ new Set(["question", "plan"]);
9
+ function isRenderableInteractionKind(kind) {
10
+ return RENDERABLE_INTERACTION_KINDS.has(kind);
11
+ }
12
+ function isSafeInteractionFieldKey(key) {
13
+ return /^[A-Za-z0-9_-]+$/.test(key) && key !== "__proto__" && key !== "constructor" && key !== "prototype";
14
+ }
15
+ function isTerminalInteractionStatus(status) {
16
+ return status !== "pending";
17
+ }
18
+ function canTransitionInteractionStatus(from, to) {
19
+ return from === "pending" && to !== from;
20
+ }
21
+ function cancelStatusFor(reason) {
22
+ return reason === "timeout" ? "expired" : "cancelled";
23
+ }
24
+ function stableValue(value) {
25
+ if (Array.isArray(value)) return value.map(stableValue);
26
+ if (!value || typeof value !== "object") return value;
27
+ return Object.fromEntries(
28
+ Object.entries(value).sort(([left], [right]) => left.localeCompare(right)).map(([key, nested]) => [key, stableValue(nested)])
29
+ );
30
+ }
31
+ function normalizedInteractionText(value) {
32
+ return (value ?? "").replace(/\s+/g, " ").trim();
33
+ }
34
+ function questionInteractionContentSignature(interaction) {
35
+ if (interaction.kind !== "question") return null;
36
+ return JSON.stringify(stableValue({
37
+ kind: interaction.kind,
38
+ title: normalizedInteractionText(interaction.title),
39
+ body: normalizedInteractionText(interaction.body),
40
+ fields: interaction.fields
41
+ }));
42
+ }
43
+ function dedupeQuestionInteractionsByContent(interactions) {
44
+ const seen = /* @__PURE__ */ new Set();
45
+ return interactions.filter((interaction) => {
46
+ const signature = questionInteractionContentSignature(interaction);
47
+ if (!signature) return true;
48
+ if (seen.has(signature)) return false;
49
+ seen.add(signature);
50
+ return true;
51
+ });
52
+ }
53
+ function parseInteractionRequest(data) {
54
+ const request = data?.request;
55
+ if (!request || typeof request !== "object") {
56
+ return { succeeded: false, error: "interaction event carried no request object" };
57
+ }
58
+ const validation = InteractionRequestSchema.safeParse(request);
59
+ if (!validation.success) {
60
+ return { succeeded: false, error: `malformed interaction request: ${validation.error.message}` };
61
+ }
62
+ return { succeeded: true, value: request };
63
+ }
64
+ function parseInteractionCancel(data) {
65
+ const id = typeof data?.id === "string" && data.id ? data.id : null;
66
+ if (!id) return { succeeded: false, error: "interaction.cancel event carried no id" };
67
+ const reason = typeof data?.reason === "string" && data.reason ? data.reason : void 0;
68
+ return { succeeded: true, value: { id, ...reason ? { reason } : {} } };
69
+ }
70
+ function fieldAcceptsFreeText(field) {
71
+ if (field.type === "text") return true;
72
+ if (field.type === "select") return field.allowCustom === true;
73
+ return false;
74
+ }
75
+ function composerAnswerDeliveries(pending) {
76
+ const deliveries = [];
77
+ for (const interaction of pending) {
78
+ if (interaction.kind !== "question") continue;
79
+ const field = interaction.fields.find(fieldAcceptsFreeText) ?? interaction.fields[0];
80
+ if (!field) continue;
81
+ deliveries.push({ interactionId: interaction.id, field });
82
+ }
83
+ return deliveries;
84
+ }
85
+ function composerAnswerData(field, text) {
86
+ return { [field.name]: field.type === "select" ? [text] : text };
87
+ }
88
+ function interactionPartKey(id) {
89
+ return `interaction:${id}`;
90
+ }
91
+ function noticePartKey(id) {
92
+ return `notice:${id}`;
93
+ }
94
+ function noticePart(noticeKind, id, text) {
95
+ return { type: "notice", id, noticeKind, text };
96
+ }
97
+ function interactionFromWireRequest(request) {
98
+ return {
99
+ id: request.id,
100
+ kind: request.kind,
101
+ title: request.title,
102
+ ...request.body ? { body: request.body } : {},
103
+ fields: request.answerSpec.fields,
104
+ status: "pending"
105
+ };
106
+ }
107
+ function interactionToPersistedPart(request, status, cancelReason) {
108
+ return {
109
+ type: "interaction",
110
+ id: request.id,
111
+ kind: request.kind,
112
+ title: request.title,
113
+ ...request.body ? { body: request.body } : {},
114
+ answerSpec: { fields: request.answerSpec.fields },
115
+ status,
116
+ ...cancelReason ? { cancelReason } : {}
117
+ };
118
+ }
119
+ function persistedPartToInteraction(part) {
120
+ if (String(part.type ?? "") !== "interaction") return null;
121
+ const id = typeof part.id === "string" && part.id ? part.id : null;
122
+ const kind = typeof part.kind === "string" && part.kind ? part.kind : null;
123
+ const title = typeof part.title === "string" ? part.title : "";
124
+ const answerSpec = part.answerSpec;
125
+ const fields = Array.isArray(answerSpec?.fields) ? answerSpec.fields : null;
126
+ const status = part.status;
127
+ const validStatus = status && ["pending", "answered", "declined", "cancelled", "expired"].includes(status);
128
+ if (!id || !kind || !fields || !validStatus) return null;
129
+ return {
130
+ id,
131
+ kind,
132
+ title,
133
+ ...typeof part.body === "string" && part.body ? { body: part.body } : {},
134
+ fields,
135
+ status,
136
+ ...typeof part.cancelReason === "string" && part.cancelReason ? { cancelReason: part.cancelReason } : {}
137
+ };
138
+ }
139
+
140
+ export {
141
+ INTERACTION_EVENT,
142
+ INTERACTION_CANCEL_EVENT,
143
+ INTERACTION_RESOLVED_EVENT,
144
+ isRenderableInteractionKind,
145
+ isSafeInteractionFieldKey,
146
+ isTerminalInteractionStatus,
147
+ canTransitionInteractionStatus,
148
+ cancelStatusFor,
149
+ questionInteractionContentSignature,
150
+ dedupeQuestionInteractionsByContent,
151
+ parseInteractionRequest,
152
+ parseInteractionCancel,
153
+ fieldAcceptsFreeText,
154
+ composerAnswerDeliveries,
155
+ composerAnswerData,
156
+ interactionPartKey,
157
+ noticePartKey,
158
+ noticePart,
159
+ interactionFromWireRequest,
160
+ interactionToPersistedPart,
161
+ persistedPartToInteraction
162
+ };
163
+ //# sourceMappingURL=chunk-4TXDD6P2.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/interactions/contract.ts"],"sourcesContent":["// Shared contract for agent interaction events (kind: \"question\" et al) — the\n// generalized human-in-the-loop primitive on the chat stream. Framework-agnostic\n// (no server- or React-only imports) so a producer (chat route) and a consumer\n// (stream parser, transcript, question card) agree on one wire shape and one\n// persisted-part shape.\n//\n// An `interaction` event means the run is BLOCKED inside the sidecar's\n// InteractionBroker until the user answers, the agent withdraws the ask\n// (`interaction.cancel`), or the broker times out. A pending interaction is\n// \"waiting on the user\", not \"model working\".\n\nimport {\n InteractionRequestSchema,\n type InteractionData,\n type InteractionField,\n type InteractionOutcome,\n type InteractionRequest,\n} from '@tangle-network/agent-interface'\n\nexport type { InteractionData, InteractionOutcome, InteractionRequest }\n\n// ---------------------------------------------------------------------------\n// Event names\n\n/** Sidecar → client: the agent raised an ask; data = `{ request }`. */\nexport const INTERACTION_EVENT = 'interaction' as const\n/** Sidecar → client: the ask was withdrawn; data = `{ id, reason? }`. */\nexport const INTERACTION_CANCEL_EVENT = 'interaction.cancel' as const\n/** An ask was answered; data = `{ id, status }`. In the wire contract so a\n * server broadcast and a client-local mark share one event name. */\nexport const INTERACTION_RESOLVED_EVENT = 'interaction.resolved' as const\n\n/** Interaction kinds a product typically renders a card for. Anything else is\n * auto-declined by the chat producer's safety net and never reaches a client.\n * A pure default; a product may substitute its own renderable set. */\nconst RENDERABLE_INTERACTION_KINDS: ReadonlySet<string> = new Set(['question', 'plan'])\n\nexport function isRenderableInteractionKind(kind: string): boolean {\n return RENDERABLE_INTERACTION_KINDS.has(kind)\n}\n\n/** Answer/field keys the sidecar will accept: identifier-safe and never a\n * prototype-pollution vector. */\nexport function isSafeInteractionFieldKey(key: string): boolean {\n return /^[A-Za-z0-9_-]+$/.test(key) && key !== '__proto__' && key !== 'constructor' && key !== 'prototype'\n}\n\n// ---------------------------------------------------------------------------\n// Field types\n//\n// `allowCustom` (a select that also accepts a write-in value) is defined by\n// newer agent-interface schemas; older pinned schemas strip unknown keys on\n// parse. The wire/persisted field types below carry the flag so a card can gate\n// its write-in input, and `parseInteractionRequest` returns the RAW payload\n// (schema-validated, not schema-parsed) so the flag survives.\n\nexport type ChatSelectField = Extract<InteractionField, { type: 'select' }> & {\n allowCustom?: boolean\n}\nexport type ChatInteractionField = Exclude<InteractionField, { type: 'select' }> | ChatSelectField\n\n/** `InteractionRequest` whose select fields may carry `allowCustom`. */\nexport type InteractionRequestWire = Omit<InteractionRequest, 'answerSpec'> & {\n answerSpec: { fields: ChatInteractionField[] }\n}\n\n// ---------------------------------------------------------------------------\n// Interaction lifecycle\n\nexport type ChatInteractionStatus = 'pending' | 'answered' | 'declined' | 'cancelled' | 'expired'\n\n/** The client/persisted view of one ask. `fields` come verbatim off the wire. */\nexport interface ChatInteraction {\n id: string\n kind: string\n title: string\n body?: string\n fields: ChatInteractionField[]\n status: ChatInteractionStatus\n /** Set when status came from an `interaction.cancel` (e.g. \"timeout\"). */\n cancelReason?: string\n}\n\nexport function isTerminalInteractionStatus(status: ChatInteractionStatus): boolean {\n return status !== 'pending'\n}\n\n/** Statuses only move forward (pending → terminal); a replayed/stale `pending`\n * must never resurrect a resolved card. */\nexport function canTransitionInteractionStatus(\n from: ChatInteractionStatus,\n to: ChatInteractionStatus,\n): boolean {\n return from === 'pending' && to !== from\n}\n\n/** Maps an `interaction.cancel` reason to the card's terminal status. */\nexport function cancelStatusFor(reason: string | undefined): ChatInteractionStatus {\n return reason === 'timeout' ? 'expired' : 'cancelled'\n}\n\nfunction stableValue(value: unknown): unknown {\n if (Array.isArray(value)) return value.map(stableValue)\n if (!value || typeof value !== 'object') return value\n return Object.fromEntries(\n Object.entries(value as Record<string, unknown>)\n .sort(([left], [right]) => left.localeCompare(right))\n .map(([key, nested]) => [key, stableValue(nested)]),\n )\n}\n\nfunction normalizedInteractionText(value: string | undefined): string {\n return (value ?? '').replace(/\\s+/g, ' ').trim()\n}\n\n/** Content identity for duplicate safety nets. Excludes volatile ids/statuses. */\nexport function questionInteractionContentSignature(interaction: ChatInteraction): string | null {\n if (interaction.kind !== 'question') return null\n return JSON.stringify(stableValue({\n kind: interaction.kind,\n title: normalizedInteractionText(interaction.title),\n body: normalizedInteractionText(interaction.body),\n fields: interaction.fields,\n }))\n}\n\nexport function dedupeQuestionInteractionsByContent(interactions: ChatInteraction[]): ChatInteraction[] {\n const seen = new Set<string>()\n return interactions.filter((interaction) => {\n const signature = questionInteractionContentSignature(interaction)\n if (!signature) return true\n if (seen.has(signature)) return false\n seen.add(signature)\n return true\n })\n}\n\n// ---------------------------------------------------------------------------\n// Wire parsing — typed outcomes, fail loud at the caller (log + skip; never a\n// half-rendered card).\n\nexport type ParseInteractionResult =\n | { succeeded: true; value: InteractionRequestWire }\n | { succeeded: false; error: string }\n\n/** Parses an `interaction` event's data (`{ request }`). Validates the shape\n * with the agent-interface schema but returns the raw request so a field a\n * pinned schema predates (`allowCustom`) survives. */\nexport function parseInteractionRequest(data: Record<string, unknown> | undefined): ParseInteractionResult {\n const request = data?.request\n if (!request || typeof request !== 'object') {\n return { succeeded: false, error: 'interaction event carried no request object' }\n }\n const validation = InteractionRequestSchema.safeParse(request)\n if (!validation.success) {\n return { succeeded: false, error: `malformed interaction request: ${validation.error.message}` }\n }\n return { succeeded: true, value: request as InteractionRequestWire }\n}\n\nexport interface InteractionCancelData {\n id: string\n reason?: string\n}\n\nexport function parseInteractionCancel(\n data: Record<string, unknown> | undefined,\n): { succeeded: true; value: InteractionCancelData } | { succeeded: false; error: string } {\n const id = typeof data?.id === 'string' && data.id ? data.id : null\n if (!id) return { succeeded: false, error: 'interaction.cancel event carried no id' }\n const reason = typeof data?.reason === 'string' && data.reason ? data.reason : undefined\n return { succeeded: true, value: { id, ...(reason ? { reason } : {}) } }\n}\n\n// ---------------------------------------------------------------------------\n// Composer-as-answer delivery: while asks are pending the composer never\n// blocks — typed text is delivered verbatim to every open ask and the agent\n// decides what it means. No interpretation here; the sidecar validates answers\n// fail-closed (invalid free text on an option-only ask → 400).\n\nexport function fieldAcceptsFreeText(field: ChatInteractionField): boolean {\n if (field.type === 'text') return true\n if (field.type === 'select') return (field as ChatSelectField).allowCustom === true\n return false\n}\n\nexport interface ComposerAnswerDelivery {\n interactionId: string\n field: ChatInteractionField\n}\n\n/** One delivery per pending ask: the first free-text-capable field, else the\n * first field. Zero-field asks are skipped (nothing to carry the text). */\nexport function composerAnswerDeliveries(pending: ChatInteraction[]): ComposerAnswerDelivery[] {\n const deliveries: ComposerAnswerDelivery[] = []\n for (const interaction of pending) {\n // Only questions take a composer-routed answer. A non-question ask (a plan)\n // is POSTed as outcome:\"accepted\" when answered — routing composer text to\n // it would silently APPROVE it. Approval is an explicit card click, so the\n // composer skips it and the plan card stays the only path.\n if (interaction.kind !== 'question') continue\n const field = interaction.fields.find(fieldAcceptsFreeText) ?? interaction.fields[0]\n if (!field) continue\n deliveries.push({ interactionId: interaction.id, field })\n }\n return deliveries\n}\n\n/** Shapes composer text into the respond payload for the routed field\n * (select answers are string arrays on the wire; text answers are strings). */\nexport function composerAnswerData(field: ChatInteractionField, text: string): InteractionData {\n return { [field.name]: field.type === 'select' ? [text] : text }\n}\n\n// ---------------------------------------------------------------------------\n// Part keys + codecs (persisted `messages.parts` entries and live stream parts\n// share these shapes).\n\nexport function interactionPartKey(id: string): string {\n return `interaction:${id}`\n}\n\nexport function noticePartKey(id: string): string {\n return `notice:${id}`\n}\n\nexport type NoticeKind = 'warning' | 'auto-declined'\n\n/**\n * Persisted-part shapes the codecs below produce — the SAME rows\n * `/chat-store`'s `ChatInteractionPart`/`ChatNoticePart` store, typed at the\n * source so a product pushing them into a `ChatMessagePart[]` transcript needs\n * no cast. Type aliases (not interfaces) on purpose: the implicit index\n * signature keeps them assignable to the `Record<string, unknown>` these\n * codecs previously returned, so existing consumers stay source-compatible.\n */\nexport type InteractionPersistedPart = {\n type: 'interaction'\n id: string\n kind: string\n title: string\n body?: string\n answerSpec: { fields: ChatInteractionField[] }\n status: ChatInteractionStatus\n cancelReason?: string\n}\n\nexport type NoticePersistedPart = {\n type: 'notice'\n id: string\n noticeKind: NoticeKind\n text: string\n}\n\n/** Builds the persisted/streamed `notice` part — a one-line transcript notice\n * explaining an out-of-band event (warning, auto-declined interaction). */\nexport function noticePart(noticeKind: NoticeKind, id: string, text: string): NoticePersistedPart {\n return { type: 'notice', id, noticeKind, text }\n}\n\n/** Reads a wire request into the client's pending `ChatInteraction`. */\nexport function interactionFromWireRequest(request: InteractionRequestWire): ChatInteraction {\n return {\n id: request.id,\n kind: request.kind,\n title: request.title,\n ...(request.body ? { body: request.body } : {}),\n fields: request.answerSpec.fields,\n status: 'pending',\n }\n}\n\n/** Builds the persisted/streamed `interaction` part from a wire request. */\nexport function interactionToPersistedPart(\n request: InteractionRequestWire,\n status: ChatInteractionStatus,\n cancelReason?: string,\n): InteractionPersistedPart {\n return {\n type: 'interaction',\n id: request.id,\n kind: request.kind,\n title: request.title,\n ...(request.body ? { body: request.body } : {}),\n answerSpec: { fields: request.answerSpec.fields },\n status,\n ...(cancelReason ? { cancelReason } : {}),\n }\n}\n\n/** Reads a persisted/streamed `interaction` part back into a `ChatInteraction`.\n * Returns null (caller logs) when the part is not one of ours. */\nexport function persistedPartToInteraction(part: Record<string, unknown>): ChatInteraction | null {\n if (String(part.type ?? '') !== 'interaction') return null\n const id = typeof part.id === 'string' && part.id ? part.id : null\n const kind = typeof part.kind === 'string' && part.kind ? part.kind : null\n const title = typeof part.title === 'string' ? part.title : ''\n const answerSpec = part.answerSpec as { fields?: unknown } | undefined\n const fields = Array.isArray(answerSpec?.fields) ? (answerSpec.fields as ChatInteractionField[]) : null\n const status = part.status as ChatInteractionStatus | undefined\n const validStatus = status && ['pending', 'answered', 'declined', 'cancelled', 'expired'].includes(status)\n if (!id || !kind || !fields || !validStatus) return null\n return {\n id,\n kind,\n title,\n ...(typeof part.body === 'string' && part.body ? { body: part.body } : {}),\n fields,\n status,\n ...(typeof part.cancelReason === 'string' && part.cancelReason ? { cancelReason: part.cancelReason } : {}),\n }\n}\n"],"mappings":";AAWA;AAAA,EACE;AAAA,OAKK;AAQA,IAAM,oBAAoB;AAE1B,IAAM,2BAA2B;AAGjC,IAAM,6BAA6B;AAK1C,IAAM,+BAAoD,oBAAI,IAAI,CAAC,YAAY,MAAM,CAAC;AAE/E,SAAS,4BAA4B,MAAuB;AACjE,SAAO,6BAA6B,IAAI,IAAI;AAC9C;AAIO,SAAS,0BAA0B,KAAsB;AAC9D,SAAO,mBAAmB,KAAK,GAAG,KAAK,QAAQ,eAAe,QAAQ,iBAAiB,QAAQ;AACjG;AAsCO,SAAS,4BAA4B,QAAwC;AAClF,SAAO,WAAW;AACpB;AAIO,SAAS,+BACd,MACA,IACS;AACT,SAAO,SAAS,aAAa,OAAO;AACtC;AAGO,SAAS,gBAAgB,QAAmD;AACjF,SAAO,WAAW,YAAY,YAAY;AAC5C;AAEA,SAAS,YAAY,OAAyB;AAC5C,MAAI,MAAM,QAAQ,KAAK,EAAG,QAAO,MAAM,IAAI,WAAW;AACtD,MAAI,CAAC,SAAS,OAAO,UAAU,SAAU,QAAO;AAChD,SAAO,OAAO;AAAA,IACZ,OAAO,QAAQ,KAAgC,EAC5C,KAAK,CAAC,CAAC,IAAI,GAAG,CAAC,KAAK,MAAM,KAAK,cAAc,KAAK,CAAC,EACnD,IAAI,CAAC,CAAC,KAAK,MAAM,MAAM,CAAC,KAAK,YAAY,MAAM,CAAC,CAAC;AAAA,EACtD;AACF;AAEA,SAAS,0BAA0B,OAAmC;AACpE,UAAQ,SAAS,IAAI,QAA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AQ,QAAQ,WAAW,OAAO;AAAA,IAChD;AAAA,IACA,GAAI,eAAe,EAAE,aAAa,IAAI,CAAC;AAAA,EACzC;AACF;AAIO,SAAS,2BAA2B,MAAuD;AAChG,MAAI,OAAO,KAAK,QAAQ,EAAE,MAAM,cAAe,QAAO;AACtD,QAAM,KAAK,OAAO,KAAK,OAAO,YAAY,KAAK,KAAK,KAAK,KAAK;AAC9D,QAAM,OAAO,OAAO,KAAK,SAAS,YAAY,KAAK,OAAO,KAAK,OAAO;AACtE,QAAM,QAAQ,OAAO,KAAK,UAAU,WAAW,KAAK,QAAQ;AAC5D,QAAM,aAAa,KAAK;AACxB,QAAM,SAAS,MAAM,QAAQ,YAAY,MAAM,IAAK,WAAW,SAAoC;AACnG,QAAM,SAAS,KAAK;AACpB,QAAM,cAAc,UAAU,CAAC,WAAW,YAAY,YAAY,aAAa,SAAS,EAAE,SAAS,MAAM;AACzG,MAAI,CAAC,MAAM,CAAC,QAAQ,CAAC,UAAU,CAAC,YAAa,QAAO;AACpD,SAAO;AAAA,IACL;AAAA,IACA;AAAA,IACA;AAAA,IACA,GAAI,OAAO,KAAK,SAAS,YAAY,KAAK,OAAO,EAAE,MAAM,KAAK,KAAK,IAAI,CAAC;AAAA,IACxE;AAAA,IACA;AAAA,IACA,GAAI,OAAO,KAAK,iBAAiB,YAAY,KAAK,eAAe,EAAE,cAAc,KAAK,aAAa,IAAI,CAAC;AAAA,EAC1G;AACF;","names":[]}
@@ -0,0 +1,295 @@
1
+ import {
2
+ clearCookieHeader,
3
+ readCookieValue,
4
+ serializeCookie
5
+ } from "./chunk-HFC4BTWJ.js";
6
+ import {
7
+ isTangleBillingEnforcementDisabled
8
+ } from "./chunk-7W5XSTUF.js";
9
+
10
+ // src/platform/sso.ts
11
+ var DEFAULT_STATE_TTL_SECONDS = 600;
12
+ var DEFAULT_SESSION_TTL_SECONDS = 60 * 60 * 24 * 7;
13
+ var DEFAULT_REDIRECT_PATH = "/app";
14
+ var DEFAULT_LOGIN_PATH = "/login";
15
+ var DEFAULT_SESSION_COOKIE = "better-auth.session_token";
16
+ function randomHex(bytes) {
17
+ const buf = new Uint8Array(bytes);
18
+ crypto.getRandomValues(buf);
19
+ return Array.from(buf, (b) => b.toString(16).padStart(2, "0")).join("");
20
+ }
21
+ async function hmacBytes(secret, value) {
22
+ const key = await crypto.subtle.importKey(
23
+ "raw",
24
+ new TextEncoder().encode(secret),
25
+ { name: "HMAC", hash: "SHA-256" },
26
+ false,
27
+ ["sign"]
28
+ );
29
+ return new Uint8Array(await crypto.subtle.sign("HMAC", key, new TextEncoder().encode(value)));
30
+ }
31
+ async function hmacHex(secret, value) {
32
+ return Array.from(await hmacBytes(secret, value), (b) => b.toString(16).padStart(2, "0")).join("");
33
+ }
34
+ function constantTimeEqual(a, b) {
35
+ if (a.length !== b.length) return false;
36
+ let diff = 0;
37
+ for (let i = 0; i < a.length; i++) diff |= a.charCodeAt(i) ^ b.charCodeAt(i);
38
+ return diff === 0;
39
+ }
40
+ async function createSignedSsoState(config) {
41
+ if (!config.secret) throw new Error("SsoStateConfig.secret is required");
42
+ const now = config.now ?? Date.now;
43
+ const payload = `${randomHex(16)}.${now().toString(36)}`;
44
+ return `${payload}.${await hmacHex(config.secret, payload)}`;
45
+ }
46
+ async function verifySignedSsoState(state, config) {
47
+ if (!config.secret) throw new Error("SsoStateConfig.secret is required");
48
+ const parts = state.split(".");
49
+ if (parts.length !== 3) return false;
50
+ const [random, timestamp, mac] = parts;
51
+ if (!random || !timestamp || !mac) return false;
52
+ const expected = await hmacHex(config.secret, `${random}.${timestamp}`);
53
+ if (!constantTimeEqual(mac, expected)) return false;
54
+ const mintedAt = parseInt(timestamp, 36);
55
+ if (!Number.isFinite(mintedAt)) return false;
56
+ const now = config.now ?? Date.now;
57
+ const ttlMs = config.ttlMs ?? DEFAULT_STATE_TTL_SECONDS * 1e3;
58
+ return now() - mintedAt <= ttlMs;
59
+ }
60
+ var TangleSsoUserCreateError = class extends Error {
61
+ constructor(message = "Failed to create local user for Tangle SSO") {
62
+ super(message);
63
+ this.name = "TangleSsoUserCreateError";
64
+ }
65
+ };
66
+ async function signSessionCookieValue(token, secret) {
67
+ if (!secret) throw new Error("signSessionCookieValue requires a non-empty secret");
68
+ const sig = await hmacBytes(secret, token);
69
+ let bin = "";
70
+ for (const byte of sig) bin += String.fromCharCode(byte);
71
+ return `${token}.${btoa(bin)}`;
72
+ }
73
+ function createBetterAuthSessionCookieMinter(auth, options = {}) {
74
+ const warn = options.warn ?? ((message) => console.warn(message));
75
+ return async ({ token, ttlSeconds }) => {
76
+ const ctx = await auth.$context;
77
+ if (!ctx.secret) {
78
+ throw new Error("createBetterAuthSessionCookieMinter: auth context has no secret");
79
+ }
80
+ const { name, attributes } = ctx.authCookies.sessionToken;
81
+ if (attributes.domain) {
82
+ throw new Error(
83
+ `createBetterAuthSessionCookieMinter: refusing a domain-scoped session cookie (Domain=${attributes.domain}) \u2014 a domain-wide session cookie shadows sibling apps that share the parent domain`
84
+ );
85
+ }
86
+ if (name === DEFAULT_SESSION_COOKIE || name === `__Secure-${DEFAULT_SESSION_COOKIE}`) {
87
+ warn(
88
+ `[tangle-sso] session cookie is named "${name}" \u2014 better-auth's default. The Tangle platform (id.tangle.tools) sets a Domain=.tangle.tools cookie under the same name, and the platform's (older) cookie wins the Cookie-header order, so this app's sessions read back null. Set a per-app prefix: betterAuth({ advanced: { cookiePrefix: '<app>' } }).`
89
+ );
90
+ }
91
+ const sameSite = typeof attributes.sameSite === "string" ? attributes.sameSite : "lax";
92
+ const cookieOptions = {
93
+ name,
94
+ path: typeof attributes.path === "string" ? attributes.path : "/",
95
+ httpOnly: attributes.httpOnly !== false,
96
+ sameSite: sameSite.charAt(0).toUpperCase() + sameSite.slice(1),
97
+ secure: Boolean(attributes.secure) || name.startsWith("__Secure-"),
98
+ maxAgeSeconds: ttlSeconds
99
+ };
100
+ const cookies = [serializeCookie(await signSessionCookieValue(token, ctx.secret), cookieOptions)];
101
+ if (name !== DEFAULT_SESSION_COOKIE) {
102
+ cookies.push(clearCookieHeader({ ...cookieOptions, name: DEFAULT_SESSION_COOKIE }));
103
+ }
104
+ return cookies;
105
+ };
106
+ }
107
+ function sanitizeRedirectPath(value, fallback) {
108
+ if (value && value.startsWith("/") && !value.startsWith("//")) return value;
109
+ return fallback;
110
+ }
111
+ function redirectResponse(location, headers = new Headers()) {
112
+ headers.set("Location", location);
113
+ return new Response(null, { status: 302, headers });
114
+ }
115
+ function clientIp(request) {
116
+ return request.headers.get("CF-Connecting-IP") ?? request.headers.get("x-forwarded-for")?.split(",")[0]?.trim() ?? null;
117
+ }
118
+ function parseStateCookiePayload(raw) {
119
+ if (!raw) return null;
120
+ try {
121
+ const parsed = JSON.parse(raw);
122
+ if (parsed === null || typeof parsed !== "object") return null;
123
+ const { s, r } = parsed;
124
+ if (typeof s !== "string" || typeof r !== "string") return null;
125
+ return { s, r };
126
+ } catch {
127
+ return null;
128
+ }
129
+ }
130
+ function createTangleSsoHandlers(opts) {
131
+ if (!opts.stateSecret) throw new Error("TangleSsoHandlerOptions.stateSecret is required");
132
+ if (!opts.callbackUrl) throw new Error("TangleSsoHandlerOptions.callbackUrl is required");
133
+ if (!opts.stateCookieName) throw new Error("TangleSsoHandlerOptions.stateCookieName is required");
134
+ const sessionCookieName = opts.sessionCookieName ?? DEFAULT_SESSION_COOKIE;
135
+ let mintSessionCookies;
136
+ if (opts.setSessionCookie) {
137
+ const seam = opts.setSessionCookie;
138
+ mintSessionCookies = async (args) => await seam(args);
139
+ } else if (opts.sessionCookieSecret) {
140
+ const secret = opts.sessionCookieSecret;
141
+ mintSessionCookies = async ({ token, secure, ttlSeconds }) => [
142
+ serializeCookie(await signSessionCookieValue(token, secret), {
143
+ name: secure ? `__Secure-${sessionCookieName}` : sessionCookieName,
144
+ secure,
145
+ maxAgeSeconds: ttlSeconds
146
+ })
147
+ ];
148
+ } else {
149
+ throw new Error(
150
+ "TangleSsoHandlerOptions requires setSessionCookie or sessionCookieSecret: better-auth only accepts HMAC-signed (and, on https, __Secure--prefixed) session cookies, so an unsigned default would mint sessions that read back null"
151
+ );
152
+ }
153
+ const sessionTtlSeconds = opts.sessionTtlSeconds ?? DEFAULT_SESSION_TTL_SECONDS;
154
+ const stateTtlSeconds = opts.stateTtlSeconds ?? DEFAULT_STATE_TTL_SECONDS;
155
+ const defaultRedirectPath = opts.defaultRedirectPath ?? DEFAULT_REDIRECT_PATH;
156
+ const loginPath = opts.loginPath ?? DEFAULT_LOGIN_PATH;
157
+ const log = opts.log ?? (() => {
158
+ });
159
+ const now = opts.now ?? Date.now;
160
+ const stateConfig = { secret: opts.stateSecret, ttlMs: stateTtlSeconds * 1e3, now };
161
+ const stateCookieOpts = { name: opts.stateCookieName, secure: opts.secureCookies };
162
+ function loginErrorRedirect(code) {
163
+ const headers = new Headers();
164
+ headers.append("Set-Cookie", clearCookieHeader(stateCookieOpts));
165
+ return redirectResponse(`${loginPath}?error=${code}`, headers);
166
+ }
167
+ return {
168
+ async start(request) {
169
+ const url = new URL(request.url);
170
+ const redirectPath = sanitizeRedirectPath(url.searchParams.get("redirect"), defaultRedirectPath);
171
+ const state = await createSignedSsoState(stateConfig);
172
+ const cookie = serializeCookie(JSON.stringify({ s: state, r: redirectPath }), {
173
+ ...stateCookieOpts,
174
+ maxAgeSeconds: stateTtlSeconds
175
+ });
176
+ const headers = new Headers();
177
+ headers.append("Set-Cookie", cookie);
178
+ return redirectResponse(opts.auth.authorizeUrl({ state, redirectUri: opts.callbackUrl }), headers);
179
+ },
180
+ async callback(request) {
181
+ const url = new URL(request.url);
182
+ const code = url.searchParams.get("code");
183
+ const stateFromPlatform = url.searchParams.get("state");
184
+ if (!code || !stateFromPlatform) return loginErrorRedirect("tangle_callback_missing");
185
+ const payload = parseStateCookiePayload(readCookieValue(request.headers.get("cookie"), opts.stateCookieName));
186
+ if (!payload || payload.s !== stateFromPlatform) return loginErrorRedirect("tangle_state_mismatch");
187
+ if (!await verifySignedSsoState(payload.s, stateConfig)) return loginErrorRedirect("tangle_state_mismatch");
188
+ let exchanged;
189
+ try {
190
+ exchanged = await opts.auth.exchange(code);
191
+ } catch (err) {
192
+ log("[tangle-sso] exchange failed", err);
193
+ return loginErrorRedirect("tangle_exchange_failed");
194
+ }
195
+ let userId;
196
+ try {
197
+ ;
198
+ ({ userId } = await opts.store.upsertUserByEmail({
199
+ email: exchanged.user.email,
200
+ name: exchanged.user.name ?? null,
201
+ tangleUserId: exchanged.user.id
202
+ }));
203
+ } catch (err) {
204
+ if (err instanceof TangleSsoUserCreateError) return loginErrorRedirect("tangle_user_create_failed");
205
+ throw err;
206
+ }
207
+ const expiresAt = new Date(now() + sessionTtlSeconds * 1e3);
208
+ const { token } = await opts.store.createSession({
209
+ userId,
210
+ expiresAt,
211
+ ipAddress: clientIp(request),
212
+ userAgent: request.headers.get("user-agent")
213
+ });
214
+ await opts.store.saveTangleLink({
215
+ userId,
216
+ sessionToken: token,
217
+ tangleUserId: exchanged.user.id,
218
+ email: exchanged.user.email,
219
+ name: exchanged.user.name ?? null,
220
+ apiKey: exchanged.apiKey,
221
+ planTier: exchanged.plan?.tier ?? null
222
+ });
223
+ const headers = new Headers();
224
+ headers.append("Set-Cookie", clearCookieHeader(stateCookieOpts));
225
+ const sessionCookies = await mintSessionCookies({
226
+ token,
227
+ expiresAt,
228
+ ttlSeconds: sessionTtlSeconds,
229
+ secure: opts.secureCookies
230
+ });
231
+ for (const cookie of sessionCookies) headers.append("Set-Cookie", cookie);
232
+ return redirectResponse(sanitizeRedirectPath(payload.r, defaultRedirectPath), headers);
233
+ }
234
+ };
235
+ }
236
+
237
+ // src/platform/guards.ts
238
+ function createAuthGuard(opts) {
239
+ const loginPath = opts.loginPath ?? "/login";
240
+ async function requireSession(request, o = {}) {
241
+ const session = await opts.getSession(request);
242
+ if (!session) {
243
+ if (o.apiResponse) {
244
+ throw Response.json({ error: "Unauthorized", code: "auth.unauthenticated" }, { status: 401 });
245
+ }
246
+ throw new Response(null, { status: 302, headers: { Location: loginPath } });
247
+ }
248
+ return session;
249
+ }
250
+ return {
251
+ requireSession,
252
+ requireUser: (request) => requireSession(request),
253
+ requireApiUser: (request) => requireSession(request, { apiResponse: true }),
254
+ getOptionalSession: async (request) => await opts.getSession(request) ?? null
255
+ };
256
+ }
257
+ function parseAdminEmails(raw) {
258
+ return (raw ?? "").split(/[,\s]+/).map((e) => e.trim().toLowerCase()).filter(Boolean);
259
+ }
260
+ function createAdminGuard(opts) {
261
+ return async (request) => {
262
+ const session = await opts.requireUser(request);
263
+ const allowed = opts.allowedEmails();
264
+ if (allowed.length === 0) throw new Response("Not found", { status: 404 });
265
+ const email = (opts.emailOf(session) ?? "").toLowerCase();
266
+ if (!allowed.includes(email)) throw new Response("Not found", { status: 404 });
267
+ return session;
268
+ };
269
+ }
270
+ function assertBillableBalance(state, opts = {}) {
271
+ if (isTangleBillingEnforcementDisabled({ env: opts.env, enforcementEnvVar: opts.enforcementEnvVar })) return;
272
+ if (state.overageAllowed || state.remainingBalanceUsd > 0) return;
273
+ throw Response.json(
274
+ {
275
+ ...opts.errorBody,
276
+ error: opts.errorMessage ?? "Add balance or upgrade your plan to invoke this agent.",
277
+ code: "billing.balance_required"
278
+ },
279
+ { status: 402 }
280
+ );
281
+ }
282
+
283
+ export {
284
+ createSignedSsoState,
285
+ verifySignedSsoState,
286
+ TangleSsoUserCreateError,
287
+ signSessionCookieValue,
288
+ createBetterAuthSessionCookieMinter,
289
+ createTangleSsoHandlers,
290
+ createAuthGuard,
291
+ parseAdminEmails,
292
+ createAdminGuard,
293
+ assertBillableBalance
294
+ };
295
+ //# sourceMappingURL=chunk-AVBANQ67.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/platform/sso.ts","../src/platform/guards.ts"],"sourcesContent":["/**\n * Cross-site Tangle SSO for agent apps: signed-state CSRF cookies plus the\n * full start/callback orchestration against the platform's /cross-site\n * bridge. The platform wire client and account persistence are structural\n * seams (`TangleSsoAuthClient` / `TangleSsoAccountStore`), so this module\n * never imports agent-runtime, an auth framework, or a database driver.\n * WebCrypto only — runs in workerd without node compatibility flags.\n */\n\nimport { clearCookieHeader, readCookieValue, serializeCookie } from '../web/index'\n\nconst DEFAULT_STATE_TTL_SECONDS = 600\nconst DEFAULT_SESSION_TTL_SECONDS = 60 * 60 * 24 * 7\nconst DEFAULT_REDIRECT_PATH = '/app'\nconst DEFAULT_LOGIN_PATH = '/login'\nconst DEFAULT_SESSION_COOKIE = 'better-auth.session_token'\n\n// ── Signed state ────────────────────────────────────────────────────────────\n\nexport interface SsoStateConfig {\n /** HMAC-SHA256 secret (e.g. the app's auth secret). */\n secret: string\n /** State lifetime in ms. Default 600 000. */\n ttlMs?: number\n /** Injectable clock (ms since epoch). Default Date.now. */\n now?: () => number\n}\n\nfunction randomHex(bytes: number): string {\n const buf = new Uint8Array(bytes)\n crypto.getRandomValues(buf)\n return Array.from(buf, (b) => b.toString(16).padStart(2, '0')).join('')\n}\n\nasync function hmacBytes(secret: string, value: string): Promise<Uint8Array> {\n const key = await crypto.subtle.importKey(\n 'raw',\n new TextEncoder().encode(secret),\n { name: 'HMAC', hash: 'SHA-256' },\n false,\n ['sign'],\n )\n return new Uint8Array(await crypto.subtle.sign('HMAC', key, new TextEncoder().encode(value)))\n}\n\nasync function hmacHex(secret: string, value: string): Promise<string> {\n return Array.from(await hmacBytes(secret, value), (b) => b.toString(16).padStart(2, '0')).join('')\n}\n\nfunction constantTimeEqual(a: string, b: string): boolean {\n if (a.length !== b.length) return false\n let diff = 0\n for (let i = 0; i < a.length; i++) diff |= a.charCodeAt(i) ^ b.charCodeAt(i)\n return diff === 0\n}\n\n/** Mint a `<randomHex32>.<timestamp36>.<hmacHex>` state value. The timestamp\n * is inside the signed payload, so expiry survives cookie-attribute tampering. */\nexport async function createSignedSsoState(config: SsoStateConfig): Promise<string> {\n if (!config.secret) throw new Error('SsoStateConfig.secret is required')\n const now = config.now ?? Date.now\n const payload = `${randomHex(16)}.${now().toString(36)}`\n return `${payload}.${await hmacHex(config.secret, payload)}`\n}\n\n/** Verify the MAC (constant-time) and the signed TTL. */\nexport async function verifySignedSsoState(state: string, config: SsoStateConfig): Promise<boolean> {\n if (!config.secret) throw new Error('SsoStateConfig.secret is required')\n const parts = state.split('.')\n if (parts.length !== 3) return false\n const [random, timestamp, mac] = parts\n if (!random || !timestamp || !mac) return false\n const expected = await hmacHex(config.secret, `${random}.${timestamp}`)\n if (!constantTimeEqual(mac, expected)) return false\n const mintedAt = parseInt(timestamp, 36)\n if (!Number.isFinite(mintedAt)) return false\n const now = config.now ?? Date.now\n const ttlMs = config.ttlMs ?? DEFAULT_STATE_TTL_SECONDS * 1000\n return now() - mintedAt <= ttlMs\n}\n\n// ── Seams ───────────────────────────────────────────────────────────────────\n\nexport interface TangleSsoExchangeResult {\n apiKey: string\n user: { id: string; email: string; name?: string | null }\n plan?: { tier: string } | null\n}\n\n/** Structural mirror of the platform auth wire client — any object with these\n * two methods satisfies it without this module importing the concrete class. */\nexport interface TangleSsoAuthClient {\n authorizeUrl(options: { state: string; redirectUri?: string }): string\n exchange(code: string): Promise<TangleSsoExchangeResult>\n}\n\n/** Thrown by `upsertUserByEmail` when the app-local user row cannot be\n * created; the callback handler maps it to `?error=tangle_user_create_failed`.\n * Any other store error propagates. */\nexport class TangleSsoUserCreateError extends Error {\n constructor(message = 'Failed to create local user for Tangle SSO') {\n super(message)\n this.name = 'TangleSsoUserCreateError'\n }\n}\n\n/**\n * Account persistence seam. Covers both storage styles in use: link-table\n * apps (a per-user platform-link row) and session-column apps (the key on the\n * session row) — `saveTangleLink` receives both `userId` and `sessionToken`,\n * and each app persists with the key it needs. `createSession` runs first so\n * the token is always available to `saveTangleLink`.\n */\nexport interface TangleSsoAccountStore {\n /** Find-or-create the app-local user. `tangleUserId` is the platform's\n * stable user id — match on it first when the app stores it (emails are\n * mutable on the platform; the id is not), falling back to email for\n * first-time logins. */\n upsertUserByEmail(input: { email: string; name: string | null; tangleUserId: string }): Promise<{ userId: string }>\n /** Create an app session row; returns the session-cookie token value. */\n createSession(input: {\n userId: string\n expiresAt: Date\n ipAddress: string | null\n userAgent: string | null\n }): Promise<{ token: string }>\n /** Persist the platform link (API key + platform identity). */\n saveTangleLink(input: {\n userId: string\n sessionToken: string\n tangleUserId: string\n email: string\n name: string | null\n apiKey: string\n planTier: string | null\n }): Promise<void>\n}\n\n// ── Session cookie ──────────────────────────────────────────────────────────\n\n/** Successful-login context handed to the `setSessionCookie` seam. */\nexport interface TangleSsoSessionCookieArgs {\n /** Session token returned by `store.createSession`. */\n token: string\n /** Session expiry (now + `sessionTtlSeconds`). */\n expiresAt: Date\n /** Mirrors `sessionTtlSeconds` after defaulting. */\n ttlSeconds: number\n /** Mirrors `TangleSsoHandlerOptions.secureCookies`. */\n secure: boolean\n}\n\n/**\n * Sign a session token to better-call's signed-cookie contract — the value\n * better-auth's `getSignedCookie` verifies: `<token>.<signature>` where the\n * signature is the raw HMAC-SHA256 of the token under `secret`, encoded as\n * STANDARD base64 WITH padding (32 bytes → 44 chars ending `=`; better-call\n * rejects any other length or suffix, so url-safe/unpadded variants read back\n * as a null session). The joined value is percent-encoded once at cookie\n * serialization, matching better-call's `serializeSignedCookie` byte-exactly.\n */\nexport async function signSessionCookieValue(token: string, secret: string): Promise<string> {\n if (!secret) throw new Error('signSessionCookieValue requires a non-empty secret')\n const sig = await hmacBytes(secret, token)\n let bin = ''\n for (const byte of sig) bin += String.fromCharCode(byte)\n return `${token}.${btoa(bin)}`\n}\n\n/** Structural slice of a `betterAuth()` instance — only what cookie minting\n * reads. No better-auth import: the signing contract is implemented by\n * `signSessionCookieValue`, byte-compatible with better-auth's own\n * `makeSignature`. */\nexport interface BetterAuthSessionCookieSource {\n $context: PromiseLike<{\n secret: string\n authCookies: {\n sessionToken: {\n /** Final cookie name — better-auth decides the `__Secure-` prefix\n * (and any `advanced.cookiePrefix`) once at `betterAuth()` init. */\n name: string\n attributes: {\n secure?: boolean\n sameSite?: string\n path?: string\n httpOnly?: boolean\n domain?: string\n }\n }\n }\n }>\n}\n\nexport interface BetterAuthSessionCookieMinterOptions {\n /** Receives the shadowed-cookie-name warning (see below). Default\n * console.warn. */\n warn?: (message: string) => void\n}\n\n/**\n * Canonical `setSessionCookie` wiring for better-auth apps: mint the session\n * Set-Cookie exactly as better-auth's own login flows do — name + attributes\n * from `auth.$context.authCookies.sessionToken` (better-auth stays\n * authoritative over prefix/name/attributes) and the value signed to\n * better-call's `getSignedCookie` contract. A raw unprefixed\n * `better-auth.session_token` left by an earlier login is explicitly expired\n * so it cannot shadow the real cookie.\n *\n * Warns when the app's session cookie still has better-auth's DEFAULT name:\n * the Tangle platform (id.tangle.tools) sets a `Domain=.tangle.tools` cookie\n * under that exact name, and equal-path cookies are sent oldest-first — the\n * platform's cookie is always older (the user signs in there before the app's\n * callback runs), so the app reads the platform's token, fails its own\n * signature check, and every fresh login lands logged-out. Per-app\n * `advanced.cookiePrefix` is the fix.\n *\n * Throws on a domain-scoped session cookie for the same reason: a\n * `Domain=`-wide session cookie is exactly the shadowing footgun.\n */\nexport function createBetterAuthSessionCookieMinter(\n auth: BetterAuthSessionCookieSource,\n options: BetterAuthSessionCookieMinterOptions = {},\n): (args: TangleSsoSessionCookieArgs) => Promise<string[]> {\n const warn = options.warn ?? ((message: string) => console.warn(message))\n return async ({ token, ttlSeconds }) => {\n const ctx = await auth.$context\n if (!ctx.secret) {\n throw new Error('createBetterAuthSessionCookieMinter: auth context has no secret')\n }\n const { name, attributes } = ctx.authCookies.sessionToken\n if (attributes.domain) {\n throw new Error(\n `createBetterAuthSessionCookieMinter: refusing a domain-scoped session cookie (Domain=${attributes.domain}) — ` +\n 'a domain-wide session cookie shadows sibling apps that share the parent domain',\n )\n }\n if (name === DEFAULT_SESSION_COOKIE || name === `__Secure-${DEFAULT_SESSION_COOKIE}`) {\n warn(\n `[tangle-sso] session cookie is named \"${name}\" — better-auth's default. ` +\n 'The Tangle platform (id.tangle.tools) sets a Domain=.tangle.tools cookie under the same name, ' +\n \"and the platform's (older) cookie wins the Cookie-header order, so this app's sessions read back null. \" +\n \"Set a per-app prefix: betterAuth({ advanced: { cookiePrefix: '<app>' } }).\",\n )\n }\n const sameSite = typeof attributes.sameSite === 'string' ? attributes.sameSite : 'lax'\n const cookieOptions = {\n name,\n path: typeof attributes.path === 'string' ? attributes.path : '/',\n httpOnly: attributes.httpOnly !== false,\n sameSite: (sameSite.charAt(0).toUpperCase() + sameSite.slice(1)) as 'Lax' | 'Strict' | 'None',\n secure: Boolean(attributes.secure) || name.startsWith('__Secure-'),\n maxAgeSeconds: ttlSeconds,\n }\n const cookies = [serializeCookie(await signSessionCookieValue(token, ctx.secret), cookieOptions)]\n if (name !== DEFAULT_SESSION_COOKIE) {\n cookies.push(clearCookieHeader({ ...cookieOptions, name: DEFAULT_SESSION_COOKIE }))\n }\n return cookies\n }\n}\n\n// ── Handlers ────────────────────────────────────────────────────────────────\n\nexport interface TangleSsoHandlerOptions {\n auth: TangleSsoAuthClient\n store: TangleSsoAccountStore\n /** HMAC secret for the state cookie. */\n stateSecret: string\n /** Absolute callback URL registered with the platform. */\n callbackUrl: string\n stateCookieName: string\n /** Default 'better-auth.session_token'. Ignored when `setSessionCookie` is\n * provided. The default path prepends `__Secure-` iff `secureCookies`. */\n sessionCookieName?: string\n /** Mint the host auth framework's own session cookie(s); return complete\n * Set-Cookie header values (the handler appends them verbatim and sets no\n * session cookie itself). Supply this when the framework should stay\n * authoritative over name/prefix/signing/attributes — e.g. better-auth:\n * `auth.$context.authCookies.sessionToken` + `makeSignature`. */\n setSessionCookie?: (\n args: TangleSsoSessionCookieArgs,\n ) => readonly string[] | Promise<readonly string[]>\n /** HMAC-SHA256 secret the host auth framework verifies session cookies with\n * (better-auth: its `secret`). Required when `setSessionCookie` is absent —\n * the default cookie is minted to better-call's signed contract via\n * `signSessionCookieValue`; an unsigned or mis-signed value reads back as a\n * null session, so there is deliberately no fallback to `stateSecret`\n * (which is not guaranteed to be the auth secret). */\n sessionCookieSecret?: string\n /** Adds `Secure` to every cookie this module sets, and (default session\n * cookie only) the `__Secure-` name prefix. Must match the auth\n * framework's own secure-cookie decision (better-auth: https `baseURL` /\n * `advanced.useSecureCookies`), or it will look up a different cookie name\n * than the one set here. */\n secureCookies: boolean\n /** Default 604 800 (7 days). */\n sessionTtlSeconds?: number\n /** Default 600. Applies to both the cookie Max-Age and the signed TTL. */\n stateTtlSeconds?: number\n /** Default '/app'. */\n defaultRedirectPath?: string\n /** Default '/login'. */\n loginPath?: string\n /** Failure log hook (e.g. console.error). Default no-op. */\n log?: (message: string, error?: unknown) => void\n now?: () => number\n}\n\nexport interface TangleSsoHandlers {\n /** GET start route: mint + sign state, set the state cookie, 302 to the\n * platform authorize URL. `?redirect=` carries the post-login path. */\n start(request: Request): Promise<Response>\n /** GET callback route: verify state, exchange the code, upsert the user,\n * create the session, save the platform link, set the session cookie\n * (via the `setSessionCookie` seam, else signed to better-call's contract\n * with `sessionCookieSecret`), 302 to the saved redirect. Every failure\n * 302s to `loginPath?error=…` with the state cookie cleared. */\n callback(request: Request): Promise<Response>\n}\n\n/** Accept only same-origin absolute paths (rejects `//host` protocol-relative URLs). */\nfunction sanitizeRedirectPath(value: string | null, fallback: string): string {\n if (value && value.startsWith('/') && !value.startsWith('//')) return value\n return fallback\n}\n\nfunction redirectResponse(location: string, headers = new Headers()): Response {\n headers.set('Location', location)\n return new Response(null, { status: 302, headers })\n}\n\n/** Real client IP: `CF-Connecting-IP` behind Cloudflare, else the first\n * `x-forwarded-for` hop (the rest of the list is sender-controlled). */\nfunction clientIp(request: Request): string | null {\n return (\n request.headers.get('CF-Connecting-IP') ??\n request.headers.get('x-forwarded-for')?.split(',')[0]?.trim() ??\n null\n )\n}\n\ninterface StateCookiePayload {\n s: string\n r: string\n}\n\nfunction parseStateCookiePayload(raw: string | null): StateCookiePayload | null {\n if (!raw) return null\n try {\n const parsed = JSON.parse(raw) as unknown\n if (parsed === null || typeof parsed !== 'object') return null\n const { s, r } = parsed as Record<string, unknown>\n if (typeof s !== 'string' || typeof r !== 'string') return null\n return { s, r }\n } catch {\n return null\n }\n}\n\nexport function createTangleSsoHandlers(opts: TangleSsoHandlerOptions): TangleSsoHandlers {\n if (!opts.stateSecret) throw new Error('TangleSsoHandlerOptions.stateSecret is required')\n if (!opts.callbackUrl) throw new Error('TangleSsoHandlerOptions.callbackUrl is required')\n if (!opts.stateCookieName) throw new Error('TangleSsoHandlerOptions.stateCookieName is required')\n\n const sessionCookieName = opts.sessionCookieName ?? DEFAULT_SESSION_COOKIE\n\n let mintSessionCookies: (args: TangleSsoSessionCookieArgs) => Promise<readonly string[]>\n if (opts.setSessionCookie) {\n const seam = opts.setSessionCookie\n mintSessionCookies = async (args) => await seam(args)\n } else if (opts.sessionCookieSecret) {\n const secret = opts.sessionCookieSecret\n mintSessionCookies = async ({ token, secure, ttlSeconds }) => [\n serializeCookie(await signSessionCookieValue(token, secret), {\n name: secure ? `__Secure-${sessionCookieName}` : sessionCookieName,\n secure,\n maxAgeSeconds: ttlSeconds,\n }),\n ]\n } else {\n throw new Error(\n 'TangleSsoHandlerOptions requires setSessionCookie or sessionCookieSecret: ' +\n 'better-auth only accepts HMAC-signed (and, on https, __Secure--prefixed) session cookies, ' +\n 'so an unsigned default would mint sessions that read back null',\n )\n }\n const sessionTtlSeconds = opts.sessionTtlSeconds ?? DEFAULT_SESSION_TTL_SECONDS\n const stateTtlSeconds = opts.stateTtlSeconds ?? DEFAULT_STATE_TTL_SECONDS\n const defaultRedirectPath = opts.defaultRedirectPath ?? DEFAULT_REDIRECT_PATH\n const loginPath = opts.loginPath ?? DEFAULT_LOGIN_PATH\n const log = opts.log ?? (() => {})\n const now = opts.now ?? Date.now\n const stateConfig: SsoStateConfig = { secret: opts.stateSecret, ttlMs: stateTtlSeconds * 1000, now }\n\n const stateCookieOpts = { name: opts.stateCookieName, secure: opts.secureCookies }\n\n function loginErrorRedirect(code: string): Response {\n const headers = new Headers()\n headers.append('Set-Cookie', clearCookieHeader(stateCookieOpts))\n return redirectResponse(`${loginPath}?error=${code}`, headers)\n }\n\n return {\n async start(request) {\n const url = new URL(request.url)\n const redirectPath = sanitizeRedirectPath(url.searchParams.get('redirect'), defaultRedirectPath)\n const state = await createSignedSsoState(stateConfig)\n const cookie = serializeCookie(JSON.stringify({ s: state, r: redirectPath }), {\n ...stateCookieOpts,\n maxAgeSeconds: stateTtlSeconds,\n })\n const headers = new Headers()\n headers.append('Set-Cookie', cookie)\n return redirectResponse(opts.auth.authorizeUrl({ state, redirectUri: opts.callbackUrl }), headers)\n },\n\n async callback(request) {\n const url = new URL(request.url)\n const code = url.searchParams.get('code')\n const stateFromPlatform = url.searchParams.get('state')\n if (!code || !stateFromPlatform) return loginErrorRedirect('tangle_callback_missing')\n\n const payload = parseStateCookiePayload(readCookieValue(request.headers.get('cookie'), opts.stateCookieName))\n if (!payload || payload.s !== stateFromPlatform) return loginErrorRedirect('tangle_state_mismatch')\n if (!(await verifySignedSsoState(payload.s, stateConfig))) return loginErrorRedirect('tangle_state_mismatch')\n\n let exchanged: TangleSsoExchangeResult\n try {\n exchanged = await opts.auth.exchange(code)\n } catch (err) {\n log('[tangle-sso] exchange failed', err)\n return loginErrorRedirect('tangle_exchange_failed')\n }\n\n let userId: string\n try {\n ;({ userId } = await opts.store.upsertUserByEmail({\n email: exchanged.user.email,\n name: exchanged.user.name ?? null,\n tangleUserId: exchanged.user.id,\n }))\n } catch (err) {\n if (err instanceof TangleSsoUserCreateError) return loginErrorRedirect('tangle_user_create_failed')\n throw err\n }\n\n const expiresAt = new Date(now() + sessionTtlSeconds * 1000)\n const { token } = await opts.store.createSession({\n userId,\n expiresAt,\n ipAddress: clientIp(request),\n userAgent: request.headers.get('user-agent'),\n })\n\n await opts.store.saveTangleLink({\n userId,\n sessionToken: token,\n tangleUserId: exchanged.user.id,\n email: exchanged.user.email,\n name: exchanged.user.name ?? null,\n apiKey: exchanged.apiKey,\n planTier: exchanged.plan?.tier ?? null,\n })\n\n const headers = new Headers()\n headers.append('Set-Cookie', clearCookieHeader(stateCookieOpts))\n const sessionCookies = await mintSessionCookies({\n token,\n expiresAt,\n ttlSeconds: sessionTtlSeconds,\n secure: opts.secureCookies,\n })\n for (const cookie of sessionCookies) headers.append('Set-Cookie', cookie)\n return redirectResponse(sanitizeRedirectPath(payload.r, defaultRedirectPath), headers)\n },\n }\n}\n","/**\n * Request guards for agent-app routes: session auth (302 redirect for pages,\n * JSON 401 for APIs), admin allowlisting (404 — the route stays invisible to\n * non-admins), and the billable-balance gate (402 with a stable code).\n * Session resolution is a seam; thrown Responses follow the router convention\n * of surfacing a thrown Response as the route result.\n */\n\nimport { isTangleBillingEnforcementDisabled } from '../runtime/model'\n\nexport interface AuthGuardOptions<Session> {\n /** e.g. a better-auth `auth.api.getSession` wrapped by the app. */\n getSession(request: Request): Promise<Session | null | undefined>\n /** Default '/login'. */\n loginPath?: string\n}\n\nexport interface AuthGuard<Session> {\n /** Page guard — throws a 302 redirect Response to `loginPath`. */\n requireUser(request: Request): Promise<Session>\n /** API guard — throws JSON 401 `{ error: 'Unauthorized', code: 'auth.unauthenticated' }`. */\n requireApiUser(request: Request): Promise<Session>\n /** `apiResponse` selects the 401 JSON path over the redirect. */\n requireSession(request: Request, opts?: { apiResponse?: boolean }): Promise<Session>\n getOptionalSession(request: Request): Promise<Session | null>\n}\n\nexport function createAuthGuard<Session>(opts: AuthGuardOptions<Session>): AuthGuard<Session> {\n const loginPath = opts.loginPath ?? '/login'\n\n async function requireSession(request: Request, o: { apiResponse?: boolean } = {}): Promise<Session> {\n const session = await opts.getSession(request)\n if (!session) {\n if (o.apiResponse) {\n throw Response.json({ error: 'Unauthorized', code: 'auth.unauthenticated' }, { status: 401 })\n }\n throw new Response(null, { status: 302, headers: { Location: loginPath } })\n }\n return session\n }\n\n return {\n requireSession,\n requireUser: (request) => requireSession(request),\n requireApiUser: (request) => requireSession(request, { apiResponse: true }),\n getOptionalSession: async (request) => (await opts.getSession(request)) ?? null,\n }\n}\n\n/** Comma/whitespace separated → trimmed, lowercased, empties dropped. */\nexport function parseAdminEmails(raw: string | null | undefined): string[] {\n return (raw ?? '')\n .split(/[,\\s]+/)\n .map((e) => e.trim().toLowerCase())\n .filter(Boolean)\n}\n\nexport interface AdminGuardOptions<Session> {\n requireUser(request: Request): Promise<Session>\n emailOf(session: Session): string | null | undefined\n /** Resolved per request; an EMPTY allowlist refuses everyone. */\n allowedEmails(): string[]\n}\n\n/** Non-admins (and empty allowlists) get 404, keeping the route invisible —\n * better than a \"forbidden\" footprint that advertises its existence. */\nexport function createAdminGuard<Session>(opts: AdminGuardOptions<Session>): (request: Request) => Promise<Session> {\n return async (request) => {\n const session = await opts.requireUser(request)\n const allowed = opts.allowedEmails()\n if (allowed.length === 0) throw new Response('Not found', { status: 404 })\n const email = (opts.emailOf(session) ?? '').toLowerCase()\n if (!allowed.includes(email)) throw new Response('Not found', { status: 404 })\n return session\n }\n}\n\nexport interface BillableBalanceState {\n overageAllowed: boolean\n remainingBalanceUsd: number\n}\n\nexport interface AssertBillableBalanceOptions {\n env?: Record<string, string | undefined>\n /** App-specific enforcement override flag (e.g. 'GTM_BILLING_ENFORCEMENT'),\n * fed to `isTangleBillingEnforcementDisabled`. */\n enforcementEnvVar?: string\n /** Default 'Add balance or upgrade your plan to invoke this agent.'. */\n errorMessage?: string\n /** Merged into the 402 JSON body (e.g. `{ organizationId }`). */\n errorBody?: Record<string, unknown>\n}\n\n/**\n * Gate a billable turn: passes when enforcement is disabled (dev default),\n * the tier allows overage, or remaining balance is positive. Otherwise throws\n * a 402 Response with the stable `billing.balance_required` code so clients\n * can route to the billing screen.\n */\nexport function assertBillableBalance(state: BillableBalanceState, opts: AssertBillableBalanceOptions = {}): void {\n if (isTangleBillingEnforcementDisabled({ env: opts.env, enforcementEnvVar: opts.enforcementEnvVar })) return\n if (state.overageAllowed || state.remainingBalanceUsd > 0) return\n // errorBody first: the stable error/code contract always wins over caller extras.\n throw Response.json(\n {\n ...opts.errorBody,\n error: opts.errorMessage ?? 'Add balance or upgrade your plan to inv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,QAAQ,OAAO,KAAK,IAAI,YAAY;AACxD,QAAI,CAAC,QAAQ,SAAS,KAAK,EAAG,OAAM,IAAI,SAAS,aAAa,EAAE,QAAQ,IAAI,CAAC;AAC7E,WAAO;AAAA,EACT;AACF;AAwBO,SAAS,sBAAsB,OAA6B,OAAqC,CAAC,GAAS;AAChH,MAAI,mCAAmC,EAAE,KAAK,KAAK,KAAK,mBAAmB,KAAK,kBAAkB,CAAC,EAAG;AACtG,MAAI,MAAM,kBAAkB,MAAM,sBAAsB,EAAG;AAE3D,QAAM,SAAS;AAAA,IACb;AAAA,MACE,GAAG,KAAK;AAAA,MACR,OAAO,KAAK,gBAAgB;AAAA,MAC5B,MAAM;AAAA,IACR;AAAA,IACA,EAAE,QAAQ,IAAI;AAAA,EAChB;AACF;","names":[]}
@@ -809,6 +809,42 @@ async function deleteBox(box) {
809
809
  return fail(err);
810
810
  }
811
811
  }
812
+ var PROVISION_PAYLOAD_MAX_BYTES = 24e4;
813
+ var ENV_VALUE_MAX_BYTES = 12e4;
814
+ var ENV_TOTAL_MAX_BYTES = 2e5;
815
+ function utf8ByteLength(value) {
816
+ return new TextEncoder().encode(typeof value === "string" ? value : JSON.stringify(value ?? null)).byteLength;
817
+ }
818
+ function assertProvisionPayloadWithinCap(payload) {
819
+ const total = utf8ByteLength(payload);
820
+ if (total <= PROVISION_PAYLOAD_MAX_BYTES) return;
821
+ const profile = payload.backend?.profile;
822
+ const files = (typeof profile === "string" ? void 0 : profile?.resources?.files) ?? [];
823
+ const breakdown = `profile=${utf8ByteLength(profile ?? null)}B (files=${utf8ByteLength(files)}B), env=${utf8ByteLength(payload.env ?? {})}B, secrets=${utf8ByteLength(payload.secrets ?? [])}B`;
824
+ throw new Error(
825
+ `sandbox provision payload is ${total} bytes \u2014 over the ${PROVISION_PAYLOAD_MAX_BYTES}-byte gate (the platform caps the create body at 256 KiB; an over-cap payload can never create a sandbox). Breakdown: ${breakdown}. Hint: set deferProfileFiles: true or move content to resources.`
826
+ );
827
+ }
828
+ function assertEnvWithinLimits(env) {
829
+ let total = 0;
830
+ let largest = null;
831
+ for (const [name, value] of Object.entries(env)) {
832
+ const bytes = utf8ByteLength(`${name}=${value}`);
833
+ total += bytes;
834
+ if (!largest || bytes > largest.bytes) largest = { name, bytes };
835
+ if (bytes > ENV_VALUE_MAX_BYTES) {
836
+ throw new Error(
837
+ `sandbox env var ${name} is ${bytes} bytes \u2014 over the ${ENV_VALUE_MAX_BYTES}-byte gate (kernel MAX_ARG_STRLEN is 131072 bytes per env entry; anything larger E2BIGs every exec). Write large content to a file mount or resource instead of an env var.`
838
+ );
839
+ }
840
+ }
841
+ if (total > ENV_TOTAL_MAX_BYTES) {
842
+ const worst = largest ? ` Largest: ${largest.name} (${largest.bytes}B).` : "";
843
+ throw new Error(
844
+ `sandbox env block is ${total} bytes total \u2014 over the ${ENV_TOTAL_MAX_BYTES}-byte gate.${worst} Write large content to a file mount or resource instead of env vars.`
845
+ );
846
+ }
847
+ }
812
848
  async function isBoxAlive(box, harness, probe) {
813
849
  if (!probe) return true;
814
850
  const execTimeout = probe.execTimeoutMs ?? 5e3;
@@ -1135,6 +1171,8 @@ async function ensureWorkspaceSandbox(shell, options) {
1135
1171
  diskGB: resources.diskGB
1136
1172
  }
1137
1173
  };
1174
+ assertEnvWithinLimits(env);
1175
+ assertProvisionPayloadWithinCap(payload ?? {});
1138
1176
  let box = await client.create(payload);
1139
1177
  await box.waitFor("running", { timeoutMs: 12e4, ...onProgress ? { onProgress } : {} });
1140
1178
  box = await refreshRuntimeConnection(client, box);
@@ -1461,6 +1499,11 @@ export {
1461
1499
  splitDeferredProfileFiles,
1462
1500
  SandboxRuntimeAuthRefreshError,
1463
1501
  writeProfileFilesToBox,
1502
+ PROVISION_PAYLOAD_MAX_BYTES,
1503
+ ENV_VALUE_MAX_BYTES,
1504
+ ENV_TOTAL_MAX_BYTES,
1505
+ assertProvisionPayloadWithinCap,
1506
+ assertEnvWithinLimits,
1464
1507
  ensureWorkspaceSandbox,
1465
1508
  resolveModel,
1466
1509
  flattenHistory,
@@ -1482,4 +1525,4 @@ export {
1482
1525
  isTerminalPromptEvent,
1483
1526
  detectInteractiveQuestion
1484
1527
  };
1485
- //# sourceMappingURL=chunk-3PK3T4KD.js.map
1528
+ //# sourceMappingURL=chunk-JJGZ54EB.js.map