@astratra/live 1.1.1 → 1.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -10,7 +10,7 @@ npm install @astratra/live @astratra/voice @astratra/ai
10
10
 
11
11
  ## Server
12
12
 
13
- `attachLive` accepts an HTTP server, a WebSocket server in `noServer` mode, an authentication function, an optional `authorize(request, context)` guard for origin and entitlement checks, and a `createSession` factory. The package does not create servers, read environment variables, or load keys.
13
+ `attachLive` accepts an HTTP server, a WebSocket server in `noServer` mode, an authentication function, an optional `authorize(request, context)` guard for origin and entitlement checks, and a `createSession` factory. The package does not create servers, read environment variables, or load keys. A browser sends its cookies when it opens a WebSocket, whatever page asks: a request whose `Origin` is neither the server's own nor listed in `allowedOrigins` is refused (4403) before authentication; a request without `Origin` (a native app) is left to `authenticate`. A web client served from another origin must be listed in `allowedOrigins`.
14
14
 
15
15
  ```js
16
16
  const { attachLive, createLiveSession, createGeminiLiveAdapter } = require('@astratra/live');
@@ -39,7 +39,7 @@ The provider contract is `connect({ instructions, tools, earlier, mode, onEvent,
39
39
 
40
40
  `quota` is created with `createMinuteQuota({ store, limits, now })`. The injected store has `usedMs(userId, plan, role)` and `addMs(userId, plan, role, ms)`; group limits additionally use `usedGroupMs(groupId, plan)` and `addGroupMs(groupId, plan, ms)`. Set `limits` by plan and role, and `limits.groups` by plan. Absent limits mean unlimited. The session debits while running, emits `QUOTA_WARNING`, and ends with `QUOTA_EXHAUSTED` or `GROUP_LIMIT`. Storage errors fall back to process memory. Use an atomic shared store for concurrent production calls. `createCallLease` accepts a shared get/set/delete store to replace older calls across processes. `createDailyCounter` provides a generic UTC-day counter for provider usage limits.
41
41
 
42
- The `registry` follows `@astratra/ai`'s `ToolRegistry` contract. The `actions` adapter queues and executes write actions. A spoken confirmation needs a proposed action, assistant readback, and recognized affirmative answer with no negative answer. Supply language-specific `catalog.affirmative` and `catalog.negative` phrase arrays. The same pending action can be confirmed by an explicit client `confirm` message. `createLiveShield` composes injected text masking, unmasking, outbound redaction, and structural key filtering. Its `input`/`output` hooks protect model speech, while `args`/`result` protect local tool calls and `external` protects third-party tool arguments. Supply an injected `catalog` and `persona` for instructions and repeat prompts; the package emits codes rather than fixed user-facing sentences.
42
+ The `registry` follows `@astratra/ai`'s `ToolRegistry` contract. The `actions` adapter queues and executes write actions. A spoken confirmation needs a proposed action, assistant readback, and recognized affirmative answer with no negative answer. Supply language-specific `catalog.affirmative` and `catalog.negative` phrase arrays. The same pending action can be confirmed by an explicit client `confirm` message. `createLiveShield` composes injected text masking, unmasking, outbound redaction, and structural key filtering. Its `input`/`output` hooks protect model speech, while `args`/`result` protect local tool calls and `external` protects third-party tool arguments. Supply an injected `catalog` and `persona` for instructions and repeat prompts; the package emits codes rather than fixed user-facing sentences. Once a tool marked `external: true` has read outside content during the call, the model may have been steered by it: `confirm_action` then answers `SCREEN_CONFIRMATION_REQUIRED` and only the client's `confirm` message (a screen that shows the action) confirms; `spokenConfirmationAfterExternal: true` keeps the spoken path.
43
43
 
44
44
  ## A host with its own prompt, tools and protocol
45
45
 
package/package.json CHANGED
@@ -1,16 +1,33 @@
1
1
  {
2
2
  "name": "@astratra/live",
3
- "version": "1.1.1",
3
+ "version": "1.1.2",
4
4
  "description": "Injected real-time voice call sessions and client protocol helpers.",
5
- "engines": { "node": ">=22" },
5
+ "engines": {
6
+ "node": ">=22"
7
+ },
6
8
  "main": "src/index.js",
7
9
  "types": "src/index.d.ts",
8
10
  "type": "commonjs",
9
- "files": ["src"],
10
- "scripts": { "test": "jest --runInBand" },
11
- "jest": { "testMatch": ["**/__tests__/**/*.test.js"] },
11
+ "files": [
12
+ "src"
13
+ ],
14
+ "jest": {
15
+ "testMatch": [
16
+ "**/__tests__/**/*.test.js"
17
+ ]
18
+ },
12
19
  "license": "MIT",
13
- "publishConfig": { "access": "public" },
14
- "dependencies": { "@astratra/voice": "^1.0.0", "@astratra/ai": "^1.4.0 || ^2.0.0" },
15
- "devDependencies": { "jest": "30.4.2" }
16
- }
20
+ "publishConfig": {
21
+ "access": "public"
22
+ },
23
+ "dependencies": {
24
+ "@astratra/voice": "^1.0.0",
25
+ "@astratra/ai": "^1.4.0 || ^2.0.0"
26
+ },
27
+ "devDependencies": {
28
+ "jest": "30.4.2"
29
+ },
30
+ "scripts": {
31
+ "test": "jest --runInBand"
32
+ }
33
+ }
package/src/index.d.ts CHANGED
@@ -259,6 +259,11 @@ export declare function createCallTools(options: {
259
259
  send?(message: CallMessage): void;
260
260
  onResult?(name: string, result: unknown): void;
261
261
  catalog?: Record<string, string>;
262
+ /**
263
+ * Once an `external` tool has read outside content, the model can no longer confirm an action from a spoken yes
264
+ * (`confirm_action` answers SCREEN_CONFIRMATION_REQUIRED): the screen confirms. `true` keeps spoken confirmation.
265
+ */
266
+ spokenConfirmationAfterExternal?: boolean;
262
267
  }): {
263
268
  declarations: unknown[];
264
269
  call(request: {
@@ -555,6 +560,8 @@ export declare function createLiveSession(options: {
555
560
  directAudio?: MicrophoneFilters | MicrophoneGate | ((context: CallContext) => Awaitable<MicrophoneFilters | MicrophoneGate | null>) | null;
556
561
  /** Whether a client's `interrupt` goes to the provider when the sound goes to it as it is (default true). */
557
562
  directInterrupt?: boolean;
563
+ /** See createCallTools: keeps spoken confirmation after an external tool has read outside content. Default false. */
564
+ spokenConfirmationAfterExternal?: boolean;
558
565
  }): {
559
566
  start(): Promise<void>;
560
567
  receive(raw: unknown): Promise<void>;
@@ -576,6 +583,12 @@ export declare function attachLive(options: {
576
583
  close?(): void;
577
584
  };
578
585
  authenticate(request: unknown): Awaitable<CallContext | null>;
586
+ /**
587
+ * Origins a browser page may open a call from, besides the server's own. A request with another Origin is refused
588
+ * (4403) before authentication; a request without Origin (a native app, a server) is left to `authenticate`.
589
+ * `false` turns the check off.
590
+ */
591
+ allowedOrigins?: string[] | false;
579
592
  authorize?(request: unknown, context: CallContext): Awaitable<boolean | {
580
593
  allowed: boolean;
581
594
  reason?: string;
package/src/session.js CHANGED
@@ -73,7 +73,8 @@ function createLiveSession({
73
73
  annotateToolResult,
74
74
  microphone = null,
75
75
  directAudio = null,
76
- directInterrupt = true
76
+ directInterrupt = true,
77
+ spokenConfirmationAfterExternal = false
77
78
  }) {
78
79
  if (!socket || !context?.userId || !clock) throw new TypeError('SESSION_DEPENDENCY_REQUIRED');
79
80
  const encode = wire.encode || encodeMessage;
@@ -529,7 +530,8 @@ function createLiveSession({
529
530
  clock,
530
531
  send: safeSend,
531
532
  onResult: annotate,
532
- catalog
533
+ catalog,
534
+ spokenConfirmationAfterExternal
533
535
  });
534
536
  const prompt = typeof instructionsOption === 'function' ? await instructionsOption({
535
537
  context,
@@ -686,12 +688,30 @@ function attachLive({
686
688
  languages = [],
687
689
  modes = ['normal', 'confidential'],
688
690
  conversationIdPattern = /^[\w:.-]{1,120}$/,
689
- encode = encodeMessage
691
+ encode = encodeMessage,
692
+ allowedOrigins
690
693
  }) {
691
694
  if (!httpServer?.on || !websocketServer?.handleUpgrade ||
692
695
  typeof authenticate !== 'function' || typeof createSession !== 'function') {
693
696
  throw new TypeError('SERVER_DEPENDENCY_REQUIRED');
694
697
  }
698
+ if (allowedOrigins !== undefined && allowedOrigins !== false && (!Array.isArray(allowedOrigins) || allowedOrigins.some((origin) => typeof origin !== 'string' || !origin))) {
699
+ throw new TypeError('ALLOWED_ORIGINS_INVALID');
700
+ }
701
+ /* Un navigateur joint ses cookies à l'ouverture d'un WebSocket, d'où que vienne la page, et rien ne retient une
702
+ page d'un autre site de l'ouvrir. L'en-tête Origin, écrit par le navigateur, est la seule défense : il doit être
703
+ celui du serveur lui-même ou figurer dans allowedOrigins. Sans Origin (une application mobile, un serveur),
704
+ seule l'authentification compte. `allowedOrigins: false` coupe ce contrôle. */
705
+ const originAllowed = (request) => {
706
+ const origin = request.headers?.origin;
707
+ if (origin === undefined || allowedOrigins === false) return true;
708
+ if (Array.isArray(allowedOrigins) && allowedOrigins.includes(origin)) return true;
709
+ try {
710
+ return new URL(origin).host === request.headers.host;
711
+ } catch (_error) {
712
+ return false;
713
+ }
714
+ };
695
715
  const calls = new Map();
696
716
  /* What the server says by itself, in the client's own words (or not at all, if the client never knew it). */
697
717
  const tell = (client, message) => {
@@ -706,6 +726,13 @@ function attachLive({
706
726
  return;
707
727
  }
708
728
  if (url.pathname !== path) return;
729
+ if (!originAllowed(request)) {
730
+ websocketServer.handleUpgrade(request, socket, head, (client) => {
731
+ if (client.readyState === 1) tell(client, { type: 'error', reason: 'ORIGIN' });
732
+ client.close(CLOSE.DENIED);
733
+ });
734
+ return;
735
+ }
709
736
  let context;
710
737
  try {
711
738
  context = await authenticate(request);
package/src/tools.js CHANGED
@@ -112,9 +112,14 @@ function createCallTools({
112
112
  maxResultChars = 6000,
113
113
  send = () => {},
114
114
  onResult = () => {},
115
- catalog = {}
115
+ catalog = {},
116
+ spokenConfirmationAfterExternal = false
116
117
  }) {
117
118
  const safe = (kind, value) => typeof shield[kind] === 'function' ? shield[kind](value) : value;
119
+ /* Dès qu'un outil a lu un contenu venu d'ailleurs (une page, un courriel), le modèle peut avoir été détourné : il
120
+ propose une action, pose une question sans rapport, et prend le « oui » pour un accord. La confirmation de vive
121
+ voix ne suffit plus pour le reste de l'appel ; l'écran, qui montre l'action, confirme (confirmByClient). */
122
+ let readExternal = false;
118
123
  async function withTimeout(promise) {
119
124
  let timer;
120
125
  try {
@@ -180,6 +185,11 @@ function createCallTools({
180
185
  ? shield.external(args)
181
186
  : safe(typeof shield.args === 'function' ? 'args' : 'input', args));
182
187
  if (name === 'confirm_action') {
188
+ if (readExternal && !spokenConfirmationAfterExternal) {
189
+ return {
190
+ code: 'SCREEN_CONFIRMATION_REQUIRED'
191
+ };
192
+ }
183
193
  const verdict = confirmation.verify(input.actionId, context.language);
184
194
  if (verdict !== 'CONFIRMED') return {
185
195
  code: verdict
@@ -246,6 +256,7 @@ function createCallTools({
246
256
  }
247
257
  }
248
258
  try {
259
+ if (tool.external === true) readExternal = true;
249
260
  const rawResult = await withTimeout(Promise.resolve().then(() => tool.handler(input, context)));
250
261
  const result = await safe(typeof shield.result === 'function' ? 'result' : 'output', rawResult);
251
262
  try {