@stigmer/sdk 3.1.6 → 3.1.8
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/__tests__/errors.test.js +42 -0
- package/__tests__/errors.test.js.map +1 -1
- package/__tests__/guest-auth.test.d.ts +2 -0
- package/__tests__/guest-auth.test.d.ts.map +1 -0
- package/__tests__/guest-auth.test.js +223 -0
- package/__tests__/guest-auth.test.js.map +1 -0
- package/__tests__/sharing.test.d.ts +2 -0
- package/__tests__/sharing.test.d.ts.map +1 -0
- package/__tests__/sharing.test.js +106 -0
- package/__tests__/sharing.test.js.map +1 -0
- package/gen/agent.d.ts +20 -1
- package/gen/agent.d.ts.map +1 -1
- package/gen/agent.js +54 -1
- package/gen/agent.js.map +1 -1
- package/gen/client.d.ts +1 -1
- package/gen/client.d.ts.map +1 -1
- package/gen/environment.d.ts +2 -0
- package/gen/environment.d.ts.map +1 -1
- package/gen/environment.js +8 -0
- package/gen/environment.js.map +1 -1
- package/gen/mcpserver.d.ts +1 -0
- package/gen/mcpserver.d.ts.map +1 -1
- package/gen/mcpserver.js +2 -0
- package/gen/mcpserver.js.map +1 -1
- package/gen/platformclient.d.ts +2 -1
- package/gen/platformclient.d.ts.map +1 -1
- package/gen/platformclient.js +8 -0
- package/gen/platformclient.js.map +1 -1
- package/gen/session.d.ts +2 -2
- package/gen/session.d.ts.map +1 -1
- package/gen/session.js +2 -2
- package/gen/session.js.map +1 -1
- package/guest-auth.d.ts +172 -0
- package/guest-auth.d.ts.map +1 -0
- package/guest-auth.js +227 -0
- package/guest-auth.js.map +1 -0
- package/index.d.ts +2 -0
- package/index.d.ts.map +1 -1
- package/index.js +4 -0
- package/index.js.map +1 -1
- package/package.json +2 -2
- package/sharing.d.ts +75 -0
- package/sharing.d.ts.map +1 -0
- package/sharing.js +116 -0
- package/sharing.js.map +1 -0
- package/src/__tests__/errors.test.ts +56 -0
- package/src/__tests__/guest-auth.test.ts +287 -0
- package/src/__tests__/sharing.test.ts +159 -0
- package/src/gen/agent.ts +61 -2
- package/src/gen/client.ts +1 -1
- package/src/gen/environment.ts +7 -1
- package/src/gen/mcpserver.ts +2 -0
- package/src/gen/platformclient.ts +7 -1
- package/src/gen/session.ts +3 -3
- package/src/guest-auth.ts +331 -0
- package/src/index.ts +20 -0
- package/src/sharing.ts +134 -0
|
@@ -0,0 +1,331 @@
|
|
|
1
|
+
import { createGrpcWebTransport } from "@connectrpc/connect-web";
|
|
2
|
+
import { createClient, type Client } from "@connectrpc/connect";
|
|
3
|
+
import { create } from "@bufbuild/protobuf";
|
|
4
|
+
import { PlatformClientTokenController } from "@stigmer/protos/ai/stigmer/iam/platformclient/v1/token_pb";
|
|
5
|
+
import { MintGuestTokenRequestSchema } from "@stigmer/protos/ai/stigmer/iam/platformclient/v1/token_pb";
|
|
6
|
+
import { wrapError } from "./gen/errors.js";
|
|
7
|
+
import {
|
|
8
|
+
rpcMetadataInterceptor,
|
|
9
|
+
errorStripInterceptor,
|
|
10
|
+
} from "./internal/interceptors.js";
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* Minimal persistence contract for the visitor's guest id.
|
|
14
|
+
*
|
|
15
|
+
* Matches the subset of the Web Storage API that {@link GuestAuth}
|
|
16
|
+
* needs, so `localStorage` satisfies it directly. Inject a custom
|
|
17
|
+
* implementation for non-browser environments or tests.
|
|
18
|
+
*/
|
|
19
|
+
export interface GuestIdStorage {
|
|
20
|
+
getItem(key: string): string | null;
|
|
21
|
+
setItem(key: string, value: string): void;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* Configuration for a guest token-minting helper.
|
|
26
|
+
*
|
|
27
|
+
* Unlike {@link PlatformClientAuthConfig}, this carries **no
|
|
28
|
+
* credentials** — `mintGuestToken` is a public RPC gated server-side
|
|
29
|
+
* on the agent's `spec.sharing.enabled`. It is therefore safe to use
|
|
30
|
+
* directly from a browser.
|
|
31
|
+
*
|
|
32
|
+
* @example
|
|
33
|
+
* ```typescript
|
|
34
|
+
* import { createGuestAuth } from "@stigmer/sdk";
|
|
35
|
+
*
|
|
36
|
+
* const guestAuth = createGuestAuth({
|
|
37
|
+
* baseUrl: "https://api.stigmer.ai",
|
|
38
|
+
* org: "acme",
|
|
39
|
+
* slug: "support-agent",
|
|
40
|
+
* });
|
|
41
|
+
* ```
|
|
42
|
+
*/
|
|
43
|
+
export interface GuestAuthConfig {
|
|
44
|
+
/** Stigmer API server URL (e.g., "https://api.stigmer.ai"). */
|
|
45
|
+
readonly baseUrl: string;
|
|
46
|
+
|
|
47
|
+
/** Organization slug from the share URL. */
|
|
48
|
+
readonly org: string;
|
|
49
|
+
|
|
50
|
+
/** Agent slug from the share URL. */
|
|
51
|
+
readonly slug: string;
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* Where to persist the visitor's guest id across visits.
|
|
55
|
+
*
|
|
56
|
+
* Defaults to `localStorage` when available, falling back to
|
|
57
|
+
* in-memory storage (guest identity then lasts one page load).
|
|
58
|
+
* The stored value is an opaque server-generated id — not a
|
|
59
|
+
* credential — that keys this browser's session read-isolation.
|
|
60
|
+
*/
|
|
61
|
+
readonly storage?: GuestIdStorage;
|
|
62
|
+
|
|
63
|
+
/**
|
|
64
|
+
* Web origin of the page embedding the shared agent.
|
|
65
|
+
*
|
|
66
|
+
* Set this when the chat runs embedded — inside an iframe (the
|
|
67
|
+
* embedding page's origin, discovered via `@stigmer/embed`'s
|
|
68
|
+
* `resolveParentOrigin`) or directly in your own app
|
|
69
|
+
* (`window.location.origin`). Leave unset on the unframed hosted
|
|
70
|
+
* page. The server validates it against the agent's
|
|
71
|
+
* `spec.sharing.allowed_origins` at mint (an empty list admits any
|
|
72
|
+
* origin) and refuses with `"permission-denied"` when the origin is
|
|
73
|
+
* not allowed.
|
|
74
|
+
*/
|
|
75
|
+
readonly embedOrigin?: string;
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* Share-link token from the URL's `?k=` parameter.
|
|
79
|
+
*
|
|
80
|
+
* Required when the agent's share link has been locked with a
|
|
81
|
+
* rotatable token; harmless (ignored server-side) on plain links.
|
|
82
|
+
* On a locked link a missing or rotated-away token refuses the mint
|
|
83
|
+
* with `"not-found"` — deliberately indistinguishable from an agent
|
|
84
|
+
* that does not exist.
|
|
85
|
+
*/
|
|
86
|
+
readonly linkToken?: string;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/**
|
|
90
|
+
* How long before expiry a cached guest token is considered stale.
|
|
91
|
+
* Re-minting inside this window keeps long-lived streams from starting
|
|
92
|
+
* with a token that expires moments later.
|
|
93
|
+
*/
|
|
94
|
+
const EXPIRY_SKEW_MS = 60_000;
|
|
95
|
+
|
|
96
|
+
/** Storage key prefix for the persisted guest id, namespaced per org. */
|
|
97
|
+
const GUEST_ID_STORAGE_PREFIX = "stigmer:guest-id:";
|
|
98
|
+
|
|
99
|
+
/**
|
|
100
|
+
* Guest token-minting helper for shared-agent pages.
|
|
101
|
+
*
|
|
102
|
+
* A minimal, purpose-built companion to the main Stigmer client: it
|
|
103
|
+
* lazily mints short-lived guest JWTs via the public `mintGuestToken`
|
|
104
|
+
* RPC, caches them in memory until just before expiry, and persists
|
|
105
|
+
* the server-issued guest id so the same browser resolves to the same
|
|
106
|
+
* guest across visits.
|
|
107
|
+
*
|
|
108
|
+
* Wire {@link getAccessToken} into a `Stigmer` client — the SDK calls
|
|
109
|
+
* it per request, so refresh is automatic and no token ever needs to
|
|
110
|
+
* be stored outside memory.
|
|
111
|
+
*
|
|
112
|
+
* Failure semantics: when minting fails (e.g. sharing was revoked —
|
|
113
|
+
* the server answers NOT_FOUND, indistinguishable from "no such
|
|
114
|
+
* agent"), {@link getAccessToken} rejects with a `StigmerError`, which
|
|
115
|
+
* fails the triggering request with the real cause instead of sending
|
|
116
|
+
* it unauthenticated.
|
|
117
|
+
*
|
|
118
|
+
* @example
|
|
119
|
+
* ```typescript
|
|
120
|
+
* const guestAuth = createGuestAuth({
|
|
121
|
+
* baseUrl: "https://api.stigmer.ai",
|
|
122
|
+
* org: "acme",
|
|
123
|
+
* slug: "support-agent",
|
|
124
|
+
* });
|
|
125
|
+
*
|
|
126
|
+
* const client = new Stigmer({
|
|
127
|
+
* baseUrl: "https://api.stigmer.ai",
|
|
128
|
+
* getAccessToken: guestAuth.getAccessToken,
|
|
129
|
+
* });
|
|
130
|
+
* ```
|
|
131
|
+
*/
|
|
132
|
+
export class GuestAuth {
|
|
133
|
+
private readonly tokenClient: Client<typeof PlatformClientTokenController>;
|
|
134
|
+
private readonly org: string;
|
|
135
|
+
private readonly slug: string;
|
|
136
|
+
private readonly storage: GuestIdStorage;
|
|
137
|
+
private readonly storageKey: string;
|
|
138
|
+
private readonly embedOrigin: string;
|
|
139
|
+
private readonly linkToken: string;
|
|
140
|
+
|
|
141
|
+
private cached: { accessToken: string; expiresAt: number } | null = null;
|
|
142
|
+
private pendingMint: Promise<string> | null = null;
|
|
143
|
+
|
|
144
|
+
/** @internal Use {@link createGuestAuth} instead. */
|
|
145
|
+
constructor(config: GuestAuthConfig) {
|
|
146
|
+
this.org = config.org;
|
|
147
|
+
this.slug = config.slug;
|
|
148
|
+
this.storage = config.storage ?? resolveDefaultStorage();
|
|
149
|
+
this.storageKey = `${GUEST_ID_STORAGE_PREFIX}${config.org}`;
|
|
150
|
+
this.embedOrigin = config.embedOrigin ?? "";
|
|
151
|
+
this.linkToken = config.linkToken ?? "";
|
|
152
|
+
|
|
153
|
+
const transport = createGrpcWebTransport({
|
|
154
|
+
baseUrl: config.baseUrl,
|
|
155
|
+
interceptors: [rpcMetadataInterceptor, errorStripInterceptor],
|
|
156
|
+
});
|
|
157
|
+
|
|
158
|
+
this.tokenClient = createClient(PlatformClientTokenController, transport);
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
/**
|
|
162
|
+
* The visitor's persisted guest id, or `null` before the first
|
|
163
|
+
* successful mint in this browser.
|
|
164
|
+
*/
|
|
165
|
+
get guestCookieId(): string | null {
|
|
166
|
+
return safeGetItem(this.storage, this.storageKey);
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
/**
|
|
170
|
+
* Token provider for `StigmerConfig.getAccessToken`.
|
|
171
|
+
*
|
|
172
|
+
* Returns the cached guest JWT while it has more than a minute of
|
|
173
|
+
* life left; otherwise mints a fresh one. Concurrent callers during
|
|
174
|
+
* a mint share the same in-flight request (single-flight).
|
|
175
|
+
*
|
|
176
|
+
* Defined as an arrow property so it can be passed detached:
|
|
177
|
+
* `new Stigmer({ ..., getAccessToken: guestAuth.getAccessToken })`.
|
|
178
|
+
*
|
|
179
|
+
* @throws {StigmerError} with code `"not-found"` when the agent is
|
|
180
|
+
* not shared (or sharing was revoked — the server keeps the two
|
|
181
|
+
* indistinguishable by design)
|
|
182
|
+
* @throws {StigmerError} with code `"permission-denied"` when
|
|
183
|
+
* `embedOrigin` is not in the agent's `allowed_origins` — embeds
|
|
184
|
+
* should hide the widget on this code rather than surface an error
|
|
185
|
+
* @throws {StigmerError} with code `"invalid-argument"` when org or
|
|
186
|
+
* slug is malformed
|
|
187
|
+
*/
|
|
188
|
+
readonly getAccessToken = async (): Promise<string | null> => {
|
|
189
|
+
if (this.cached && this.cached.expiresAt - Date.now() > EXPIRY_SKEW_MS) {
|
|
190
|
+
return this.cached.accessToken;
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
// Single-flight: the provider is invoked once per request, so a
|
|
194
|
+
// burst at page load (registry fetches + profile resolution) must
|
|
195
|
+
// collapse into one mint — both for latency and because concurrent
|
|
196
|
+
// first mints would otherwise race to persist different guest ids.
|
|
197
|
+
this.pendingMint ??= this.mint().finally(() => {
|
|
198
|
+
this.pendingMint = null;
|
|
199
|
+
});
|
|
200
|
+
|
|
201
|
+
return this.pendingMint;
|
|
202
|
+
};
|
|
203
|
+
|
|
204
|
+
private async mint(): Promise<string> {
|
|
205
|
+
try {
|
|
206
|
+
const response = await this.tokenClient.mintGuestToken(
|
|
207
|
+
create(MintGuestTokenRequestSchema, {
|
|
208
|
+
org: this.org,
|
|
209
|
+
slug: this.slug,
|
|
210
|
+
guestCookieId: safeGetItem(this.storage, this.storageKey) ?? "",
|
|
211
|
+
embedOrigin: this.embedOrigin,
|
|
212
|
+
linkToken: this.linkToken,
|
|
213
|
+
}),
|
|
214
|
+
);
|
|
215
|
+
|
|
216
|
+
safeSetItem(this.storage, this.storageKey, response.guestCookieId);
|
|
217
|
+
this.cached = {
|
|
218
|
+
accessToken: response.accessToken,
|
|
219
|
+
expiresAt: Date.now() + response.expiresIn * 1000,
|
|
220
|
+
};
|
|
221
|
+
return response.accessToken;
|
|
222
|
+
} catch (e) {
|
|
223
|
+
throw wrapError(e);
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
/**
|
|
229
|
+
* `localStorage` when usable, otherwise an in-memory fallback.
|
|
230
|
+
*
|
|
231
|
+
* Access is probed inside try/catch because merely touching
|
|
232
|
+
* `localStorage` can throw (e.g. sandboxed iframes with storage
|
|
233
|
+
* blocked). With the fallback, the chat still works — the visitor
|
|
234
|
+
* just gets a fresh guest identity per page load.
|
|
235
|
+
*
|
|
236
|
+
* `globalThis` is typed structurally because this package compiles
|
|
237
|
+
* without DOM libs (it is also consumed from Node, where
|
|
238
|
+
* `localStorage` does not exist).
|
|
239
|
+
*/
|
|
240
|
+
function resolveDefaultStorage(): GuestIdStorage {
|
|
241
|
+
try {
|
|
242
|
+
const { localStorage: storage } = globalThis as {
|
|
243
|
+
localStorage?: GuestIdStorage & { removeItem(key: string): void };
|
|
244
|
+
};
|
|
245
|
+
if (storage) {
|
|
246
|
+
const probeKey = "stigmer:storage-probe";
|
|
247
|
+
storage.setItem(probeKey, "1");
|
|
248
|
+
storage.removeItem(probeKey);
|
|
249
|
+
return storage;
|
|
250
|
+
}
|
|
251
|
+
} catch {
|
|
252
|
+
// Fall through to the in-memory storage below.
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
const memory = new Map<string, string>();
|
|
256
|
+
return {
|
|
257
|
+
getItem: (key) => memory.get(key) ?? null,
|
|
258
|
+
setItem: (key, value) => {
|
|
259
|
+
memory.set(key, value);
|
|
260
|
+
},
|
|
261
|
+
};
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
/**
|
|
265
|
+
* Storage reads/writes never fail the mint: the guest id is a
|
|
266
|
+
* convenience (stable identity across visits), not a requirement —
|
|
267
|
+
* the server issues a fresh id when none is presented.
|
|
268
|
+
*/
|
|
269
|
+
function safeGetItem(storage: GuestIdStorage, key: string): string | null {
|
|
270
|
+
try {
|
|
271
|
+
return storage.getItem(key);
|
|
272
|
+
} catch {
|
|
273
|
+
return null;
|
|
274
|
+
}
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
function safeSetItem(storage: GuestIdStorage, key: string, value: string): void {
|
|
278
|
+
try {
|
|
279
|
+
storage.setItem(key, value);
|
|
280
|
+
} catch {
|
|
281
|
+
// Persisting the id is best-effort; see safeGetItem.
|
|
282
|
+
}
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
/**
|
|
286
|
+
* Create a guest token-minting helper for a shared agent's hosted page
|
|
287
|
+
* or embed.
|
|
288
|
+
*
|
|
289
|
+
* This is the browser-side counterpart of `createPlatformClientAuth`:
|
|
290
|
+
* it involves **no credentials** — the server gates minting on the
|
|
291
|
+
* agent's `spec.sharing.enabled` and issues a short-lived guest JWT
|
|
292
|
+
* scoped to the sharing org. Pass {@link GuestAuth.getAccessToken} to
|
|
293
|
+
* a `Stigmer` client and every request authenticates as this visitor.
|
|
294
|
+
*
|
|
295
|
+
* @example
|
|
296
|
+
* ```typescript
|
|
297
|
+
* import { Stigmer, createGuestAuth } from "@stigmer/sdk";
|
|
298
|
+
*
|
|
299
|
+
* const guestAuth = createGuestAuth({
|
|
300
|
+
* baseUrl: "https://api.stigmer.ai",
|
|
301
|
+
* org: "acme",
|
|
302
|
+
* slug: "support-agent",
|
|
303
|
+
* });
|
|
304
|
+
*
|
|
305
|
+
* const client = new Stigmer({
|
|
306
|
+
* baseUrl: "https://api.stigmer.ai",
|
|
307
|
+
* getAccessToken: guestAuth.getAccessToken,
|
|
308
|
+
* });
|
|
309
|
+
* ```
|
|
310
|
+
*
|
|
311
|
+
* @throws {Error} if `baseUrl`, `org`, or `slug` is missing or empty
|
|
312
|
+
*/
|
|
313
|
+
export function createGuestAuth(config: GuestAuthConfig): GuestAuth {
|
|
314
|
+
if (!config.baseUrl) {
|
|
315
|
+
throw new Error(
|
|
316
|
+
"createGuestAuth: baseUrl is required (e.g., \"https://api.stigmer.ai\")",
|
|
317
|
+
);
|
|
318
|
+
}
|
|
319
|
+
if (!config.org) {
|
|
320
|
+
throw new Error(
|
|
321
|
+
"createGuestAuth: org is required — the organization slug from the share URL",
|
|
322
|
+
);
|
|
323
|
+
}
|
|
324
|
+
if (!config.slug) {
|
|
325
|
+
throw new Error(
|
|
326
|
+
"createGuestAuth: slug is required — the agent slug from the share URL",
|
|
327
|
+
);
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
return new GuestAuth(config);
|
|
331
|
+
}
|
package/src/index.ts
CHANGED
|
@@ -13,6 +13,26 @@ export {
|
|
|
13
13
|
// Configuration
|
|
14
14
|
export { type StigmerConfig, type TokenProvider } from "./config.js";
|
|
15
15
|
|
|
16
|
+
// Guest auth (shared-agent pages and embeds; browser-safe, credential-free)
|
|
17
|
+
export {
|
|
18
|
+
createGuestAuth,
|
|
19
|
+
GuestAuth,
|
|
20
|
+
type GuestAuthConfig,
|
|
21
|
+
type GuestIdStorage,
|
|
22
|
+
} from "./guest-auth.js";
|
|
23
|
+
|
|
24
|
+
// Agent sharing (hosted link + embed snippet; framework-free)
|
|
25
|
+
export {
|
|
26
|
+
MAX_ALLOWED_ORIGINS,
|
|
27
|
+
LINK_TOKEN_PARAM,
|
|
28
|
+
validateOrigin,
|
|
29
|
+
chatPath,
|
|
30
|
+
buildChatUrl,
|
|
31
|
+
appendLinkToken,
|
|
32
|
+
buildEmbedLoaderUrl,
|
|
33
|
+
buildEmbedSnippet,
|
|
34
|
+
} from "./sharing.js";
|
|
35
|
+
|
|
16
36
|
// Error handling
|
|
17
37
|
export {
|
|
18
38
|
StigmerError,
|
package/src/sharing.ts
ADDED
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Agent-sharing helpers — the single source of truth for the hosted chat
|
|
3
|
+
* URL shape, the embed snippet, and client-side `allowed_origins`
|
|
4
|
+
* validation. Framework-free by design: consumed by the web console and
|
|
5
|
+
* desktop app (via `@stigmer/react`), the `stigmer` CLI, and any platform
|
|
6
|
+
* builder that wants to construct share links or embed snippets itself.
|
|
7
|
+
*
|
|
8
|
+
* The canonical URL shape is `<app-origin>/chat/<org>/<slug>` (a T01
|
|
9
|
+
* design decision), and `embed.js` is served from the root of that same
|
|
10
|
+
* app origin (T04). Callers supply the origin — resolving it is a host
|
|
11
|
+
* concern (the console knows its `appUrl`, the CLI resolves it from the
|
|
12
|
+
* backend type) — while the path and snippet shapes live here so every
|
|
13
|
+
* surface emits byte-identical output.
|
|
14
|
+
*/
|
|
15
|
+
|
|
16
|
+
/** Maximum number of allowed origins (proto: `repeated.max_items = 32`). */
|
|
17
|
+
export const MAX_ALLOWED_ORIGINS = 32;
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* Exact web origin: scheme://host[:port] — no path, query, fragment, or
|
|
21
|
+
* trailing slash. Mirrors the CEL expression `allowed_origins.format` on
|
|
22
|
+
* `AgentSharing` (`apis/ai/stigmer/agentic/agent/v1/spec.proto`).
|
|
23
|
+
*
|
|
24
|
+
* The proto is the source of truth — if the CEL expression changes, this
|
|
25
|
+
* pattern must change with it. Mirroring it client-side gives immediate
|
|
26
|
+
* feedback instead of a round-trip rejection.
|
|
27
|
+
*/
|
|
28
|
+
const ORIGIN_PATTERN =
|
|
29
|
+
/^https?:\/\/[A-Za-z0-9]([A-Za-z0-9-]*[A-Za-z0-9])?(\.[A-Za-z0-9]([A-Za-z0-9-]*[A-Za-z0-9])?)*(:[0-9]{1,5})?$/;
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* Validate a single `allowed_origins` entry.
|
|
33
|
+
*
|
|
34
|
+
* Returns `null` when valid, or a user-facing message explaining what
|
|
35
|
+
* to fix (DD-006: errors state what happened and what to do).
|
|
36
|
+
*/
|
|
37
|
+
export function validateOrigin(value: string): string | null {
|
|
38
|
+
const trimmed = value.trim();
|
|
39
|
+
if (!trimmed) return "Enter an origin, like https://example.com";
|
|
40
|
+
if (!ORIGIN_PATTERN.test(trimmed)) {
|
|
41
|
+
return "Must be an exact web origin like https://example.com — no path, query, or trailing slash";
|
|
42
|
+
}
|
|
43
|
+
return null;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* Query parameter carrying the share-link token on a locked link:
|
|
48
|
+
* `/chat/<org>/<slug>?k=<token>`. Short by design — the token rides every
|
|
49
|
+
* copied link, and `k` (for "key") is the platform's one-character
|
|
50
|
+
* convention, mirrored by the hosted page and the embed widget.
|
|
51
|
+
*/
|
|
52
|
+
export const LINK_TOKEN_PARAM = "k";
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* The hosted chat page path for a shared agent: `/chat/<org>/<slug>`,
|
|
56
|
+
* plus `?k=<token>` when the share link is locked with a rotatable token
|
|
57
|
+
* (`agent.status.shareLinkToken`).
|
|
58
|
+
*
|
|
59
|
+
* Useful on its own when the caller renders relative to the current
|
|
60
|
+
* origin (e.g. a host that never configured an absolute app URL).
|
|
61
|
+
*/
|
|
62
|
+
export function chatPath(org: string, slug: string, linkToken?: string): string {
|
|
63
|
+
const path = `/chat/${org}/${slug}`;
|
|
64
|
+
return linkToken
|
|
65
|
+
? `${path}?${LINK_TOKEN_PARAM}=${encodeURIComponent(linkToken)}`
|
|
66
|
+
: path;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/**
|
|
70
|
+
* The absolute hosted chat URL for a shared agent:
|
|
71
|
+
* `<appOrigin>/chat/<org>/<slug>[?k=<token>]`.
|
|
72
|
+
*
|
|
73
|
+
* A trailing slash on `appOrigin` is tolerated so callers can pass
|
|
74
|
+
* user-configured values verbatim. An empty `appOrigin` degrades to the
|
|
75
|
+
* relative {@link chatPath} — the same graceful fallback a host without a
|
|
76
|
+
* configured public origin gets in the share dialog.
|
|
77
|
+
*/
|
|
78
|
+
export function buildChatUrl(
|
|
79
|
+
appOrigin: string,
|
|
80
|
+
org: string,
|
|
81
|
+
slug: string,
|
|
82
|
+
linkToken?: string,
|
|
83
|
+
): string {
|
|
84
|
+
return stripTrailingSlash(appOrigin) + chatPath(org, slug, linkToken);
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/**
|
|
88
|
+
* Append the share-link token to an already-built chat URL.
|
|
89
|
+
*
|
|
90
|
+
* For hosts that construct the base URL through their own callback (the
|
|
91
|
+
* share dialog's `buildShareUrl` prop) rather than {@link buildChatUrl}.
|
|
92
|
+
* A `null`/empty token returns the URL unchanged, so callers can pass
|
|
93
|
+
* `agent.status?.shareLinkToken` straight through. Emits the identical
|
|
94
|
+
* `?k=` shape as {@link chatPath} — one URL grammar across every surface.
|
|
95
|
+
*/
|
|
96
|
+
export function appendLinkToken(url: string, linkToken: string | null | undefined): string {
|
|
97
|
+
if (!linkToken) return url;
|
|
98
|
+
const separator = url.includes("?") ? "&" : "?";
|
|
99
|
+
return `${url}${separator}${LINK_TOKEN_PARAM}=${encodeURIComponent(linkToken)}`;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/**
|
|
103
|
+
* The embed loader URL: `embed.js` lives at the root of the app origin
|
|
104
|
+
* (the loader derives the chat-page origin from its own script URL, so
|
|
105
|
+
* the two must share an origin). An empty `appOrigin` degrades to the
|
|
106
|
+
* relative `/embed.js`.
|
|
107
|
+
*/
|
|
108
|
+
export function buildEmbedLoaderUrl(appOrigin: string): string {
|
|
109
|
+
return `${stripTrailingSlash(appOrigin)}/embed.js`;
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/**
|
|
113
|
+
* The two-line embed snippet an owner pastes into any website: the
|
|
114
|
+
* loader script plus the `<stigmer-agent>` element where the widget
|
|
115
|
+
* renders. A locked share link adds the `token` attribute, which the
|
|
116
|
+
* widget forwards as `?k=` on its iframe URL. Every surface (share
|
|
117
|
+
* dialog, CLI, docs) emits exactly this.
|
|
118
|
+
*/
|
|
119
|
+
export function buildEmbedSnippet(
|
|
120
|
+
appOrigin: string,
|
|
121
|
+
org: string,
|
|
122
|
+
slug: string,
|
|
123
|
+
linkToken?: string,
|
|
124
|
+
): string {
|
|
125
|
+
const tokenAttribute = linkToken ? ` token="${linkToken}"` : "";
|
|
126
|
+
return [
|
|
127
|
+
`<script src="${buildEmbedLoaderUrl(appOrigin)}" async></script>`,
|
|
128
|
+
`<stigmer-agent org="${org}" agent="${slug}"${tokenAttribute}></stigmer-agent>`,
|
|
129
|
+
].join("\n");
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
function stripTrailingSlash(origin: string): string {
|
|
133
|
+
return origin.endsWith("/") ? origin.slice(0, -1) : origin;
|
|
134
|
+
}
|