@devvibex/aiflow 1.6.0 → 1.8.0

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
@@ -78,6 +78,8 @@ console.log(emb.data[0].embedding.length);
78
78
  | `defaultAudioModel` | `string` | from `GET /config` | Override (music / Lyria). |
79
79
  | `defaultSfxModel` | `string` | from `GET /config` | Override (sound effects / ElevenLabs). |
80
80
  | `endUserId` | `string` | `null` | Current end-user id; scopes the knowledge base (`x-end-user-id`). Set/clear later with `setEndUser`. |
81
+ | `appUserToken` | `string` | `null` | Logged-in end user's access token (from your app's `POST /:projectKey/auth/login`). Sent as `x-app-user-token`; the gateway verifies it → trusted per-user identity. Set/clear later with `setEndUser(id, token)`. |
82
+ | `appSecret` | `string` | `null` | **SERVER-ONLY.** App server key (`sk-...`); sent as `x-app-secret` for owner-billed **server-to-server** calls. **NEVER** put this in a browser bundle. Set/clear later with `setAppSecret`. |
81
83
  | `timeout` | `number` | `60000` | Per-request timeout (ms). |
82
84
  | `maxRetries` | `number` | `2` | Retries on 429 / 5xx / network errors. |
83
85
  | `fetch` | `typeof fetch` | `globalThis.fetch` | Custom fetch (Node <18, testing). |
@@ -244,6 +246,49 @@ cost more than text), settled periodically and on close. If the balance runs
244
246
  out mid-session you'll get `onError({ code: 'INSUFFICIENT_CREDITS' })` and the
245
247
  session closes.
246
248
 
249
+ ## Identity & auth headers
250
+
251
+ Every request the SDK sends carries these identity headers automatically:
252
+
253
+ | Header | When | Purpose |
254
+ | ------------------ | -------------------------------------- | ----------------------------------------------------------------------- |
255
+ | `x-app-id` | **always** | Public app id — resolves the module/project on the gateway. |
256
+ | `x-app-user-token` | after `setEndUser(id, token)` | The end user's verified access token → trusted per-user identity (RAG). |
257
+ | `x-app-secret` | after `setAppSecret(secret)` (backend) | **Server-only** owner-billed server-to-server auth (see below). |
258
+
259
+ ## Server-side mode (`appSecret` — owner-billed, backend only)
260
+
261
+ Most apps run the SDK **in the browser** with just `appId` (public) — the gateway
262
+ enforces the project's Origin allowlist and bills the owner's credits. But when
263
+ you need to call AIFlow **from your own backend** (a cron job, a webhook handler,
264
+ an internal service — where there's no browser Origin and no logged-in end user),
265
+ pass the app's **server key** (`sk-...`, from the module dashboard) so the gateway
266
+ authorizes the owner-billed spend server-to-server:
267
+
268
+ ```js
269
+ import AIFlowClient from '@devvibex/aiflow';
270
+
271
+ // SERVER-SIDE ONLY — e.g. inside a Node backend, never shipped to the browser.
272
+ const aiflow = new AIFlowClient({
273
+ appId: process.env.AIFLOW_APP_ID,
274
+ baseUrl: process.env.AIFLOW_BASE_URL,
275
+ appSecret: process.env.AIFLOW_APP_SECRET, // sk-... — sent as x-app-secret
276
+ });
277
+
278
+ const res = await aiflow.chat({ messages: [{ role: 'user', content: 'Hi' }] });
279
+ ```
280
+
281
+ You can also set/clear it later with `aiflow.setAppSecret('sk-...')` /
282
+ `aiflow.setAppSecret(null)`. The server key:
283
+
284
+ - authorizes owner-billed calls **without** a per-end-user token, and
285
+ - **bypasses the browser-Origin allowlist** (a trusted backend has no Origin).
286
+
287
+ > ⚠️ **NEVER put `appSecret` in a browser bundle, mobile app, or any client you
288
+ > ship to users.** Anyone who obtains it can spend the project owner's credits.
289
+ > Keep it in a server-side environment variable / secret store. In the browser,
290
+ > use `appId` alone (plus `setEndUser` for per-user knowledge).
291
+
247
292
  ## Error handling
248
293
 
249
294
  All failures throw `AIFlowError` with `.status`, `.code`, and `.requestId`.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@devvibex/aiflow",
3
- "version": "1.6.0",
3
+ "version": "1.8.0",
4
4
  "description": "First-party LLM gateway SDK for apps generated on the VibeX platform — chat, streaming, image, video, music (Lyria), sound effects (ElevenLabs), embeddings and real-time speech translation (Gemini Live) without shipping any third-party API key.",
5
5
  "keywords": [
6
6
  "ai",
package/src/index.d.ts CHANGED
@@ -508,9 +508,24 @@ export interface AIFlowClientOptions {
508
508
  defaultSfxModel?: string | null;
509
509
  /**
510
510
  * Current end-user id (the app's logged-in user). Scopes the per-user
511
- * knowledge base; sent as `x-end-user-id`. Set/clear later with `setEndUser`.
511
+ * knowledge base. Set/clear later with `setEndUser`.
512
512
  */
513
513
  endUserId?: string | null;
514
+ /**
515
+ * The logged-in end user's access token (from your app's
516
+ * `POST /:projectKey/auth/login`). REQUIRED for the knowledge base: the
517
+ * gateway verifies it and derives a TRUSTED end-user id (sent as
518
+ * `x-app-user-token`). Set/clear later with `setEndUser(id, token)`.
519
+ */
520
+ appUserToken?: string | null;
521
+ /**
522
+ * SERVER-ONLY. The app's server key (`sk-...`), sent as `x-app-secret` to
523
+ * authorize owner-billed server-to-server calls (no per-end-user token, and
524
+ * bypassing the browser-Origin allowlist). NEVER ship this in a browser
525
+ * bundle — a client holding it can spend the project owner's credits. Use
526
+ * only in a trusted backend. Set/clear later with `setAppSecret`.
527
+ */
528
+ appSecret?: string | null;
514
529
  timeout?: number;
515
530
  maxRetries?: number;
516
531
  fetch?: typeof fetch;
@@ -604,6 +619,14 @@ export class AIFlowClient {
604
619
  readonly maxRetries: number;
605
620
  /** Current end-user id (or null). Set via `setEndUser`. */
606
621
  endUserId: string | null;
622
+ /** Current end-user access token (or null), sent as `x-app-user-token`. Set via `setEndUser`. */
623
+ appUserToken: string | null;
624
+ /**
625
+ * SERVER-ONLY server key (or null), sent as `x-app-secret` to authorize
626
+ * owner-billed server-to-server spend. Set via `setAppSecret` / constructor.
627
+ * Never expose in a browser.
628
+ */
629
+ appSecret: string | null;
607
630
  /** Per-user knowledge base — upload / list / delete the current user's docs. */
608
631
  readonly knowledge: KnowledgeNamespace;
609
632
  /** Admin namespace — manage the app's AIFlow module config (needs `setAdminToken`). */
@@ -613,11 +636,13 @@ export class AIFlowClient {
613
636
 
614
637
  /**
615
638
  * Set (or clear with `null`) the current end user. Call after your app
616
- * authenticates a user — every subsequent knowledge AND chat call then
617
- * carries `x-end-user-id`, so the user's own uploaded documents ground their
618
- * answers. Returns `this` for chaining.
639
+ * authenticates a user, passing the user's id AND their access token (from
640
+ * your app's `POST /:projectKey/auth/login`). Every subsequent knowledge AND
641
+ * chat call then carries the verified `x-app-user-token`, so the gateway
642
+ * derives a TRUSTED end-user id and grounds answers in that user's own
643
+ * documents. The token is REQUIRED for the knowledge base. Returns `this`.
619
644
  */
620
- setEndUser(endUserId: string | null): this;
645
+ setEndUser(endUserId: string | null, appUserToken?: string | null): this;
621
646
 
622
647
  /**
623
648
  * Set a session-level default model for one generation kind. Wins over the
@@ -637,6 +662,15 @@ export class AIFlowClient {
637
662
  */
638
663
  setAdminToken(token: string | null): this;
639
664
 
665
+ /**
666
+ * Set (or clear with `null`) the SERVER-ONLY app secret (`sk-...`), sent as
667
+ * `x-app-secret` to authorize owner-billed server-to-server calls without a
668
+ * per-end-user token (and bypassing the browser-Origin allowlist). Use ONLY
669
+ * from a trusted backend — a browser holding this key can spend the project
670
+ * owner's credits. Returns `this` for chaining.
671
+ */
672
+ setAppSecret(appSecret: string | null): this;
673
+
640
674
  /**
641
675
  * Fetch (and cache) the server-side AIFlow config. Pass `{ refresh: true }`
642
676
  * to force a reload.
package/src/index.js CHANGED
@@ -28,7 +28,9 @@ export class AIFlowClient {
28
28
  * @param {string} options.baseUrl VibeX gateway base URL (e.g. "https://api.vibe-x.io/aiflow").
29
29
  * @param {string} [options.defaultModel]
30
30
  * @param {string} [options.defaultImageModel]
31
- * @param {string} [options.endUserId] Current end-user id (the app's logged-in user). Scopes the per-user knowledge base; sent as `x-end-user-id`. Set/clear later with `setEndUser()`.
31
+ * @param {string} [options.endUserId] Current end-user id (the app's logged-in user). Scopes the per-user knowledge base. Set/clear later with `setEndUser()`.
32
+ * @param {string} [options.appUserToken] The logged-in end user's access token (from your app's `POST /:projectKey/auth/login`). REQUIRED for the knowledge base: the gateway verifies it and derives a TRUSTED end-user id (sent as `x-app-user-token`). Set/clear later with `setEndUser(id, token)`.
33
+ * @param {string} [options.appSecret] SERVER-ONLY. The app's server key (`sk-...`), sent as `x-app-secret` to authorize owner-billed server-to-server calls (no per-end-user token, no browser Origin check). NEVER ship this to a browser bundle — it authorizes spend on the owner's balance. Use only in a trusted backend. Set/clear later with `setAppSecret()`.
32
34
  * @param {number} [options.timeout] Per-request timeout (ms). Default 60000.
33
35
  * @param {number} [options.maxRetries] Retries on 429/5xx / network errors. Default 2.
34
36
  * @param {typeof fetch} [options.fetch] Custom fetch implementation.
@@ -43,6 +45,8 @@ export class AIFlowClient {
43
45
  defaultAudioModel = null,
44
46
  defaultSfxModel = null,
45
47
  endUserId = null,
48
+ appUserToken = null,
49
+ appSecret = null,
46
50
  timeout = DEFAULT_TIMEOUT_MS,
47
51
  maxRetries = DEFAULT_MAX_RETRIES,
48
52
  fetch: customFetch,
@@ -55,6 +59,14 @@ export class AIFlowClient {
55
59
  // Current end user (the app's logged-in user). Scopes the knowledge base
56
60
  // so each user only ever sees/retrieves their own uploaded documents.
57
61
  this.endUserId = endUserId ? String(endUserId) : null;
62
+ // The end user's access token (issued by your app's own login). The
63
+ // gateway VERIFIES it and derives a trusted end-user id from it — this is
64
+ // what secures the per-user knowledge base against a spoofed id header.
65
+ this.appUserToken = appUserToken ? String(appUserToken) : null;
66
+ // SERVER-ONLY app secret (`sk-...`). Sent as `x-app-secret` to authorize
67
+ // owner-billed server-to-server calls. Keep it on your backend — never
68
+ // bundle it into a browser client (it can spend the owner's credits).
69
+ this.appSecret = appSecret ? String(appSecret) : null;
58
70
  // Caller-provided overrides — win over server-fetched config.
59
71
  this._userDefaults = {
60
72
  chat: defaultModel,
@@ -114,13 +126,23 @@ export class AIFlowClient {
114
126
 
115
127
  /**
116
128
  * Set (or clear) the current end user. Call after your app authenticates a
117
- * user — every subsequent knowledge AND chat call carries `x-end-user-id`,
118
- * so the user's own uploaded documents ground their answers. Pass `null` on
119
- * logout. Returns `this` for chaining.
129
+ * user, passing the user's id AND their access token (the one your app got
130
+ * from `POST /:projectKey/auth/login`). Every subsequent knowledge AND chat
131
+ * call then carries the verified `x-app-user-token`, so the gateway can
132
+ * derive a TRUSTED end-user id and ground answers in that user's own
133
+ * documents. Pass `null` (or no args) on logout to clear both. Returns
134
+ * `this` for chaining.
135
+ *
136
+ * The token is REQUIRED for the knowledge base to work securely: without it
137
+ * the gateway has no authenticated identity, so uploads are rejected and
138
+ * chat is not grounded in the user's documents (the legacy id-only mode is
139
+ * off by default because a raw id header is spoofable).
120
140
  * @param {string|null} endUserId
141
+ * @param {string|null} [appUserToken] The user's access token from your app's login.
121
142
  */
122
- setEndUser(endUserId) {
143
+ setEndUser(endUserId, appUserToken = null) {
123
144
  this.endUserId = endUserId ? String(endUserId) : null;
145
+ this.appUserToken = appUserToken ? String(appUserToken) : null;
124
146
  return this;
125
147
  }
126
148
 
@@ -147,6 +169,20 @@ export class AIFlowClient {
147
169
  return this;
148
170
  }
149
171
 
172
+ /**
173
+ * Set (or clear) the SERVER-ONLY app secret (`sk-...`), sent as
174
+ * `x-app-secret` to authorize owner-billed server-to-server calls (chat,
175
+ * image, video, live translate, …) without a per-end-user token, and
176
+ * bypassing the browser-Origin allowlist. Use ONLY from a trusted backend —
177
+ * a browser that holds this key can spend the project owner's credits. Pass
178
+ * `null` to clear. Returns `this` for chaining.
179
+ * @param {string|null} appSecret
180
+ */
181
+ setAppSecret(appSecret) {
182
+ this.appSecret = appSecret ? String(appSecret) : null;
183
+ return this;
184
+ }
185
+
150
186
  /**
151
187
  * Fetch (and cache) the server-side AIFlow config. Subsequent calls
152
188
  * return the cached object; pass `{ refresh: true }` to force a reload.
@@ -175,7 +211,10 @@ export class AIFlowClient {
175
211
  method: 'GET',
176
212
  headers: {
177
213
  Accept: 'application/json',
178
- 'x-app-id': this.appId,
214
+ // Full identity header set (x-app-id always; plus the app-user
215
+ // token / server key when set) so config resolves under the same
216
+ // auth as the data-plane calls.
217
+ ...this._authHeaders(),
179
218
  },
180
219
  });
181
220
  if (!res.ok) {
@@ -696,6 +735,14 @@ export class AIFlowClient {
696
735
  io,
697
736
  origin,
698
737
  appId: this.appId,
738
+ // Forward the current identity into the WS handshake so the live
739
+ // gateway applies the SAME per-project origin allowlist + billing
740
+ // identity as the HTTP path: the verified end-user token (parity with
741
+ // `x-app-user-token`) and the SERVER-ONLY server key (parity with
742
+ // `x-app-secret`, which also bypasses the browser-Origin check for a
743
+ // trusted backend). Both are omitted when unset.
744
+ appUserToken: this.appUserToken,
745
+ appSecret: this.appSecret,
699
746
  params: { targetLang, sourceLang, mode, voice, echoTargetLanguage },
700
747
  autoStart,
701
748
  handlers: {
@@ -717,11 +764,21 @@ export class AIFlowClient {
717
764
  // ────────────────────────────────────────────────────────────────────────
718
765
 
719
766
  /**
720
- * Auth/identity headers attached to every gateway call: the public app id
721
- * and (when set) the current end-user id that scopes the knowledge base.
767
+ * Auth/identity headers attached to every gateway call:
768
+ * - `x-app-id` — the public app id (ALWAYS present).
769
+ * - `x-app-user-token` — the current end-user's VERIFIED access token, the
770
+ * secure identity the gateway trusts (when set via
771
+ * `setEndUser(id, token)`).
772
+ * - `x-app-secret` — SERVER-ONLY server key, authorizes owner-billed
773
+ * server-to-server spend (when set via
774
+ * `setAppSecret()` / constructor `appSecret`).
775
+ * - `x-end-user-id` — legacy/diagnostic only; the gateway ignores it
776
+ * unless an operator opts into the unverified mode.
722
777
  */
723
778
  _authHeaders() {
724
779
  const h = { 'x-app-id': this.appId };
780
+ if (this.appUserToken) h['x-app-user-token'] = this.appUserToken;
781
+ if (this.appSecret) h['x-app-secret'] = this.appSecret;
725
782
  if (this.endUserId) h['x-end-user-id'] = this.endUserId;
726
783
  return h;
727
784
  }
@@ -863,9 +920,11 @@ export class AIFlowClient {
863
920
  if (!file) {
864
921
  throw new AIFlowError('a File/Blob is required to ingest knowledge');
865
922
  }
866
- if (!this.endUserId) {
923
+ if (!this.appUserToken) {
867
924
  throw new AIFlowError(
868
- 'setEndUser(id) must be called before uploading knowledge',
925
+ 'setEndUser(id, appUserToken) must be called with the logged-in ' +
926
+ "user's access token before uploading knowledge — the gateway " +
927
+ 'verifies it to scope uploads to that user.',
869
928
  );
870
929
  }
871
930
  if (typeof FormData === 'undefined') {
@@ -960,10 +1019,22 @@ export class AIFlowClient {
960
1019
  * audio out (`onAudio`) is 24 kHz PCM.
961
1020
  */
962
1021
  export class LiveTranslateSession {
963
- constructor({ io, origin, appId, params, autoStart, handlers }) {
1022
+ constructor({
1023
+ io,
1024
+ origin,
1025
+ appId,
1026
+ appUserToken,
1027
+ appSecret,
1028
+ params,
1029
+ autoStart,
1030
+ handlers,
1031
+ }) {
964
1032
  this._io = io;
965
1033
  this._origin = String(origin).replace(/\/+$/, '');
966
1034
  this._appId = appId;
1035
+ // Handshake identity forwarded to the live gateway (both optional).
1036
+ this._appUserToken = appUserToken || null;
1037
+ this._appSecret = appSecret || null;
967
1038
  this.params = params;
968
1039
  this._autoStart = autoStart;
969
1040
  this._handlers = handlers || {};
@@ -977,7 +1048,16 @@ export class LiveTranslateSession {
977
1048
  this.socket = this._io(`${this._origin}/aiflow-live`, {
978
1049
  path: '/ws',
979
1050
  transports: ['websocket'],
980
- auth: { appId: this._appId },
1051
+ // appId is ALWAYS sent; the verified end-user token and the
1052
+ // server-only server key are added when present so the live gateway
1053
+ // can bind billing identity and run its per-project origin allowlist.
1054
+ auth: {
1055
+ appId: this._appId,
1056
+ ...(this._appUserToken
1057
+ ? { appUserToken: this._appUserToken }
1058
+ : {}),
1059
+ ...(this._appSecret ? { appSecret: this._appSecret } : {}),
1060
+ },
981
1061
  });
982
1062
 
983
1063
  const fwd = (event, cb) =>