@devvibex/aiflow 1.7.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.7.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
@@ -518,6 +518,14 @@ export interface AIFlowClientOptions {
518
518
  * `x-app-user-token`). Set/clear later with `setEndUser(id, token)`.
519
519
  */
520
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;
521
529
  timeout?: number;
522
530
  maxRetries?: number;
523
531
  fetch?: typeof fetch;
@@ -613,6 +621,12 @@ export class AIFlowClient {
613
621
  endUserId: string | null;
614
622
  /** Current end-user access token (or null), sent as `x-app-user-token`. Set via `setEndUser`. */
615
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;
616
630
  /** Per-user knowledge base — upload / list / delete the current user's docs. */
617
631
  readonly knowledge: KnowledgeNamespace;
618
632
  /** Admin namespace — manage the app's AIFlow module config (needs `setAdminToken`). */
@@ -648,6 +662,15 @@ export class AIFlowClient {
648
662
  */
649
663
  setAdminToken(token: string | null): this;
650
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
+
651
674
  /**
652
675
  * Fetch (and cache) the server-side AIFlow config. Pass `{ refresh: true }`
653
676
  * to force a reload.
package/src/index.js CHANGED
@@ -30,6 +30,7 @@ export class AIFlowClient {
30
30
  * @param {string} [options.defaultImageModel]
31
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
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()`.
33
34
  * @param {number} [options.timeout] Per-request timeout (ms). Default 60000.
34
35
  * @param {number} [options.maxRetries] Retries on 429/5xx / network errors. Default 2.
35
36
  * @param {typeof fetch} [options.fetch] Custom fetch implementation.
@@ -45,6 +46,7 @@ export class AIFlowClient {
45
46
  defaultSfxModel = null,
46
47
  endUserId = null,
47
48
  appUserToken = null,
49
+ appSecret = null,
48
50
  timeout = DEFAULT_TIMEOUT_MS,
49
51
  maxRetries = DEFAULT_MAX_RETRIES,
50
52
  fetch: customFetch,
@@ -61,6 +63,10 @@ export class AIFlowClient {
61
63
  // gateway VERIFIES it and derives a trusted end-user id from it — this is
62
64
  // what secures the per-user knowledge base against a spoofed id header.
63
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;
64
70
  // Caller-provided overrides — win over server-fetched config.
65
71
  this._userDefaults = {
66
72
  chat: defaultModel,
@@ -163,6 +169,20 @@ export class AIFlowClient {
163
169
  return this;
164
170
  }
165
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
+
166
186
  /**
167
187
  * Fetch (and cache) the server-side AIFlow config. Subsequent calls
168
188
  * return the cached object; pass `{ refresh: true }` to force a reload.
@@ -191,7 +211,10 @@ export class AIFlowClient {
191
211
  method: 'GET',
192
212
  headers: {
193
213
  Accept: 'application/json',
194
- '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(),
195
218
  },
196
219
  });
197
220
  if (!res.ok) {
@@ -712,6 +735,14 @@ export class AIFlowClient {
712
735
  io,
713
736
  origin,
714
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,
715
746
  params: { targetLang, sourceLang, mode, voice, echoTargetLanguage },
716
747
  autoStart,
717
748
  handlers: {
@@ -733,15 +764,21 @@ export class AIFlowClient {
733
764
  // ────────────────────────────────────────────────────────────────────────
734
765
 
735
766
  /**
736
- * Auth/identity headers attached to every gateway call: the public app id,
737
- * the current end-user's VERIFIED access token (`x-app-user-token`, the
738
- * secure identity the gateway trusts), and the end-user id (`x-end-user-id`,
739
- * legacy/diagnostic only — the gateway ignores it unless an operator opts
740
- * into the unverified mode).
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.
741
777
  */
742
778
  _authHeaders() {
743
779
  const h = { 'x-app-id': this.appId };
744
780
  if (this.appUserToken) h['x-app-user-token'] = this.appUserToken;
781
+ if (this.appSecret) h['x-app-secret'] = this.appSecret;
745
782
  if (this.endUserId) h['x-end-user-id'] = this.endUserId;
746
783
  return h;
747
784
  }
@@ -982,10 +1019,22 @@ export class AIFlowClient {
982
1019
  * audio out (`onAudio`) is 24 kHz PCM.
983
1020
  */
984
1021
  export class LiveTranslateSession {
985
- 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
+ }) {
986
1032
  this._io = io;
987
1033
  this._origin = String(origin).replace(/\/+$/, '');
988
1034
  this._appId = appId;
1035
+ // Handshake identity forwarded to the live gateway (both optional).
1036
+ this._appUserToken = appUserToken || null;
1037
+ this._appSecret = appSecret || null;
989
1038
  this.params = params;
990
1039
  this._autoStart = autoStart;
991
1040
  this._handlers = handlers || {};
@@ -999,7 +1048,16 @@ export class LiveTranslateSession {
999
1048
  this.socket = this._io(`${this._origin}/aiflow-live`, {
1000
1049
  path: '/ws',
1001
1050
  transports: ['websocket'],
1002
- 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
+ },
1003
1061
  });
1004
1062
 
1005
1063
  const fwd = (event, cb) =>