@robosystems/client 2.35.0 → 2.37.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.
@@ -4,36 +4,26 @@
4
4
  * Core SSE (Server-Sent Events) client for RoboSystems API
5
5
  * Provides automatic reconnection, event replay, and type-safe event handling
6
6
  *
7
- * SECURITY NOTE: When using JWT authentication, tokens are passed as query parameters
8
- * due to EventSource API limitations. This means tokens may appear in:
9
- * - Server access logs
10
- * - Proxy logs
11
- * - Browser history
12
- * - Referer headers
7
+ * The stream is read over `fetch` rather than `EventSource`, so a credential
8
+ * travels in a header, never in the URL, and the same code runs in browsers
9
+ * and Node.
13
10
  *
14
- * For production environments with sensitive data, consider:
15
- * - Using cookie-based authentication instead
16
- * - Implementing a WebSocket-based alternative
17
- * - Using short-lived tokens that expire quickly
18
- * - Ensuring all connections use HTTPS
19
- *
20
- * CREDENTIAL ROTATION: the stream endpoint authenticates the JWT it finds in
21
- * the URL, and the backend revokes the previous JWT on every session refresh.
22
- * A `token` captured once therefore goes dead the moment the session rotates
23
- * (about every 25 minutes in the browser apps); pass a `tokenProvider` and it
24
- * is consulted on every connect — including automatic reconnects — instead.
11
+ * CREDENTIAL ROTATION: the backend revokes the previous JWT on every session
12
+ * refresh. A `token` captured once therefore goes dead the moment the session
13
+ * rotates (about every 25 minutes in the browser apps); pass a `tokenProvider`
14
+ * and it is consulted on every connect, including automatic reconnects.
25
15
  */
26
16
 
27
17
  import type { TokenProvider } from './graphql/client'
28
- import { pathSegment } from './graphql/client'
18
+ import { applyAuthHeader, pathSegment } from './graphql/client'
29
19
 
30
20
  export interface SSEConfig {
31
21
  baseUrl: string
32
22
  credentials?: 'include' | 'same-origin' | 'omit'
33
23
  headers?: Record<string, string>
34
24
  /**
35
- * Static JWT captured at construction. Fine for long-lived API keys and
36
- * server-side flows; browser sessions should use `tokenProvider`.
25
+ * Static credential captured at construction: an API key or a JWT. Fine for
26
+ * API keys and server-side flows; browser sessions should use `tokenProvider`.
37
27
  */
38
28
  token?: string
39
29
  /**
@@ -68,9 +58,27 @@ export enum EventType {
68
58
  QUEUE_UPDATE = 'queue_update',
69
59
  }
70
60
 
61
+ const CONNECT_TIMEOUT_MS = 10000
62
+
63
+ /** Names this client emits itself, which a stream must not be able to trigger. */
64
+ const CLIENT_EVENTS = new Set([
65
+ 'connected',
66
+ 'closed',
67
+ 'reconnecting',
68
+ 'max_retries_exceeded',
69
+ 'parse_error',
70
+ ])
71
+
72
+ interface ParsedEvent {
73
+ type: string
74
+ data: string
75
+ lastEventId: string
76
+ }
77
+
71
78
  export class SSEClient {
72
79
  private config: SSEConfig
73
- private eventSource?: EventSource
80
+ private connection?: AbortController
81
+ private opened: boolean = false
74
82
  private reconnectAttempts: number = 0
75
83
  private lastEventId?: string
76
84
  private closed: boolean = false
@@ -86,6 +94,7 @@ export class SSEClient {
86
94
  }
87
95
 
88
96
  async connect(operationId: string, fromSequence: number = 0): Promise<void> {
97
+ this.closed = false
89
98
  return this.open(operationId, fromSequence, false)
90
99
  }
91
100
 
@@ -94,97 +103,156 @@ export class SSEClient {
94
103
  // not just the first one after construction.
95
104
  const token = await this.resolveToken()
96
105
 
97
- // A close() during the backoff or the token lookup ends a reconnect.
98
- if (reconnect && this.closed) return
106
+ // A close() during the backoff or the token lookup ends the attempt.
107
+ if (this.closed) {
108
+ if (reconnect) return
109
+ throw new Error('SSE stream closed before opening')
110
+ }
99
111
 
100
- return new Promise((resolve, reject) => {
101
- let url = `${this.config.baseUrl}/v1/operations/${pathSegment(operationId, 'operationId')}/stream?from_sequence=${encodeURIComponent(String(fromSequence))}`
112
+ const url = `${this.config.baseUrl}/v1/operations/${pathSegment(operationId, 'operationId')}/stream?from_sequence=${encodeURIComponent(String(fromSequence))}`
113
+ // Accept is the only stream header the API's CORS policy needs; `cache`
114
+ // below stands in for Cache-Control, which the preflight would refuse.
115
+ const headers = new Headers({ ...this.config.headers, Accept: 'text/event-stream' })
116
+ if (token) applyAuthHeader(headers, token)
117
+
118
+ // Never leave a previous stream running beside its replacement: two live
119
+ // streams deliver every event twice.
120
+ this.connection?.abort()
121
+ const connection = new AbortController()
122
+ this.connection = connection
123
+ this.opened = false
124
+
125
+ let timedOut = false
126
+ const connectionTimeout = setTimeout(() => {
127
+ timedOut = true
128
+ connection.abort()
129
+ }, CONNECT_TIMEOUT_MS)
130
+
131
+ let response: Response
132
+ try {
133
+ response = await fetch(url, {
134
+ headers,
135
+ cache: 'no-store',
136
+ signal: connection.signal,
137
+ ...(this.config.credentials ? { credentials: this.config.credentials } : {}),
138
+ })
139
+ } catch (error) {
140
+ clearTimeout(connectionTimeout)
141
+ const message = timedOut
142
+ ? 'SSE connection timed out before opening'
143
+ : `SSE connection error before open: ${error instanceof Error ? error.message : String(error)}`
144
+ return this.failToOpen(
145
+ connection,
146
+ new Error(message),
147
+ true,
148
+ operationId,
149
+ fromSequence,
150
+ reconnect
151
+ )
152
+ }
153
+ clearTimeout(connectionTimeout)
154
+
155
+ if (!response.ok || !response.body) {
156
+ const retryable = response.status === 429 || response.status >= 500
157
+ return this.failToOpen(
158
+ connection,
159
+ new Error(`SSE connection failed: HTTP ${response.status}${await readDetail(response)}`),
160
+ retryable,
161
+ operationId,
162
+ fromSequence,
163
+ reconnect
164
+ )
165
+ }
102
166
 
103
- // Add JWT token as query parameter if provided
104
- // WARNING: EventSource API doesn't support custom headers, so tokens are passed via query param
105
- // This has security implications - see class documentation
106
- if (token) {
107
- url += `&token=${encodeURIComponent(token)}`
108
- }
167
+ if (this.connection !== connection) return
109
168
 
110
- // Never leave a previous source running beside its replacement: two
111
- // live streams deliver every event twice.
112
- this.eventSource?.close()
113
- const eventSource = new EventSource(url, {
114
- withCredentials: this.config.credentials === 'include',
115
- } as any)
116
- this.eventSource = eventSource
169
+ this.opened = true
170
+ this.emit('connected', null)
117
171
 
118
- let opened = false
172
+ // Callers attach their listeners when connect() resolves, so reading waits
173
+ // a tick: an event that is already buffered must not be delivered to nobody.
174
+ const body = response.body
175
+ setTimeout(() => {
176
+ void this.readStream(body, connection, operationId, fromSequence)
177
+ }, 0)
178
+ }
119
179
 
120
- const connectionTimeout = setTimeout(() => {
121
- if (!opened) {
122
- reject(new Error('SSE connection timed out before opening'))
123
- this.close()
124
- }
125
- }, 10000)
126
-
127
- eventSource.onopen = () => {
128
- opened = true
129
- clearTimeout(connectionTimeout)
130
- this.reconnectAttempts = 0
131
- this.emit('connected', null)
132
- resolve()
133
- }
180
+ /**
181
+ * A connect that never opened. The first connect reports it to the caller; a
182
+ * reconnect retries what could pass, such as a 503 during a deploy, and
183
+ * otherwise tells the listeners, since no caller is waiting on it.
184
+ */
185
+ private failToOpen(
186
+ connection: AbortController,
187
+ error: Error,
188
+ retryable: boolean,
189
+ operationId: string,
190
+ fromSequence: number,
191
+ reconnect: boolean
192
+ ): void {
193
+ if (this.connection !== connection) {
194
+ if (!reconnect) throw new Error('SSE stream closed before opening')
195
+ return
196
+ }
197
+ if (!reconnect) {
198
+ this.close()
199
+ throw error
200
+ }
201
+ if (retryable) {
202
+ this.handleError(error, operationId, fromSequence)
203
+ return
204
+ }
205
+ this.emit('error', { error: error.message })
206
+ this.close()
207
+ }
134
208
 
135
- eventSource.onerror = (error) => {
136
- if (this.eventSource !== eventSource) return
137
-
138
- const serverError = readServerError(error)
139
- if (serverError) {
140
- // The server's own `event: error` — the per-user connection cap, an
141
- // unknown or foreign operation, a failed stream — ends the stream
142
- // for good. Reconnecting would only repeat it (and, since the
143
- // stream opens first, reset the retry budget each time).
144
- clearTimeout(connectionTimeout)
145
- this.emit('error', serverError)
146
- this.close()
147
- if (!opened) {
148
- reject(new Error(serverError.error))
149
- }
150
- return
151
- }
152
-
153
- if (!opened) {
154
- // Failed before the stream ever opened. Browser EventSource doesn't
155
- // expose the HTTP status, but a CLOSED readyState at this point
156
- // means a non-retryable response (commonly 401/403/404). Reject
157
- // the initial promise so callers surface a clear error instead of
158
- // waiting out the 10s connectionTimeout or spinning retries that
159
- // can never satisfy this promise.
160
- clearTimeout(connectionTimeout)
161
- const nonRetryable = eventSource.readyState === EventSource.CLOSED
162
- this.close()
163
- reject(
164
- new Error(
165
- nonRetryable
166
- ? 'SSE connection failed before open (likely auth/not-found; EventSource hides the HTTP status)'
167
- : 'SSE connection error before open'
168
- )
169
- )
170
- return
171
- }
172
- if (!this.closed) {
173
- this.handleError(error, operationId, fromSequence)
174
- }
175
- }
209
+ private async readStream(
210
+ body: ReadableStream<Uint8Array>,
211
+ connection: AbortController,
212
+ operationId: string,
213
+ fromSequence: number
214
+ ): Promise<void> {
215
+ const reader = body.getReader()
216
+ const decoder = new TextDecoder()
217
+ const parser = new SSEParser((event) => {
218
+ if (this.connection === connection) this.dispatch(event)
219
+ })
176
220
 
177
- eventSource.onmessage = (event) => {
178
- this.handleMessage(event)
221
+ let failure: unknown
222
+ try {
223
+ for (;;) {
224
+ const { done, value } = await reader.read()
225
+ if (done) break
226
+ parser.feed(decoder.decode(value, { stream: true }))
227
+ if (this.connection !== connection) break
179
228
  }
229
+ } catch (error) {
230
+ failure = error
231
+ }
232
+ reader.cancel().catch(() => {})
233
+
234
+ // Still current means the server went away without saying it was finished.
235
+ if (this.connection === connection && !this.closed) {
236
+ this.handleError(
237
+ failure ?? new Error('SSE stream ended before the operation finished'),
238
+ operationId,
239
+ fromSequence
240
+ )
241
+ }
242
+ }
180
243
 
181
- // Set up specific event listeners
182
- Object.values(EventType).forEach((eventType) => {
183
- eventSource.addEventListener(eventType, (event: any) => {
184
- this.handleTypedEvent(eventType, event)
185
- })
186
- })
187
- })
244
+ private dispatch(event: ParsedEvent): void {
245
+ if (event.type === 'message') {
246
+ this.handleMessage(event)
247
+ } else if (event.type === 'error') {
248
+ // The server's own `event: error` — the per-user connection cap, an
249
+ // unknown or foreign operation, a failed stream — ends the stream for
250
+ // good. Reconnecting would only repeat it.
251
+ this.emit('error', readServerError(event.data))
252
+ this.close()
253
+ } else if (event.type !== 'keepalive' && !CLIENT_EVENTS.has(event.type)) {
254
+ this.handleTypedEvent(event.type, event)
255
+ }
188
256
  }
189
257
 
190
258
  /**
@@ -213,7 +281,7 @@ export class SSEClient {
213
281
  return token || undefined
214
282
  }
215
283
 
216
- private handleMessage(event: MessageEvent): void {
284
+ private handleMessage(event: ParsedEvent): void {
217
285
  try {
218
286
  const data = JSON.parse(event.data)
219
287
  const sseEvent: SSEEvent = {
@@ -230,17 +298,22 @@ export class SSEClient {
230
298
  }
231
299
  }
232
300
 
233
- private handleTypedEvent(eventType: string, event: MessageEvent): void {
301
+ private handleTypedEvent(eventType: string, event: ParsedEvent): void {
234
302
  try {
235
303
  const data = JSON.parse(event.data)
236
304
  this.lastEventId = event.lastEventId
305
+ // Only a real event shows the stream got anywhere. Resetting when a
306
+ // stream opens would let one that opens and ends retry forever.
307
+ this.reconnectAttempts = 0
237
308
  this.emit(eventType, data)
238
309
 
239
- // Check for completion events
310
+ // `stream_end` covers an operation that paused: nothing more arrives
311
+ // until a resume, so reconnecting would only replay it.
240
312
  if (
241
313
  eventType === EventType.OPERATION_COMPLETED ||
242
314
  eventType === EventType.OPERATION_ERROR ||
243
- eventType === EventType.OPERATION_CANCELLED
315
+ eventType === EventType.OPERATION_CANCELLED ||
316
+ eventType === 'stream_end'
244
317
  ) {
245
318
  this.close()
246
319
  }
@@ -249,12 +322,12 @@ export class SSEClient {
249
322
  }
250
323
  }
251
324
 
252
- private async handleError(error: any, operationId: string, fromSequence: number): Promise<void> {
325
+ private handleError(error: any, operationId: string, fromSequence: number): void {
253
326
  if (this.closed) return
254
327
 
255
- // Close the failed source now: a browser EventSource retries on its own,
256
- // and that retry would run alongside the reconnect scheduled below.
257
- this.eventSource?.close()
328
+ this.connection?.abort()
329
+ this.connection = undefined
330
+ this.opened = false
258
331
 
259
332
  if (this.reconnectAttempts < this.config.maxRetries!) {
260
333
  this.reconnectAttempts++
@@ -269,8 +342,10 @@ export class SSEClient {
269
342
  setTimeout(() => {
270
343
  if (this.closed) return
271
344
  const resumeFrom = this.lastEventId ? parseInt(this.lastEventId) + 1 : fromSequence
272
- this.open(operationId, resumeFrom, true).catch(() => {
273
- // Error handled in connect
345
+ this.open(operationId, resumeFrom, true).catch((err) => {
346
+ // A throwing tokenProvider: there is no caller left to reject.
347
+ this.emit('error', { error: err instanceof Error ? err.message : String(err) })
348
+ this.close()
274
349
  })
275
350
  }, delay)
276
351
  } else {
@@ -302,32 +377,83 @@ export class SSEClient {
302
377
 
303
378
  close(): void {
304
379
  this.closed = true
305
- if (this.eventSource) {
306
- this.eventSource.close()
307
- this.eventSource = undefined
308
- }
380
+ this.connection?.abort()
381
+ this.connection = undefined
382
+ this.opened = false
309
383
  this.emit('closed', null)
310
384
  this.listeners.clear()
311
385
  }
312
386
 
313
387
  isConnected(): boolean {
314
- return this.eventSource !== undefined && this.eventSource.readyState === EventSource.OPEN
388
+ return this.opened
315
389
  }
316
390
  }
317
391
 
318
- /**
319
- * The payload of a server-sent `event: error`, or null for a transport
320
- * error. A named `error` event reaches `onerror` as a `MessageEvent`
321
- * carrying the server's JSON (`{"error": "..."}`); a dropped connection
322
- * arrives as a bare `Event` with no data.
323
- */
324
- function readServerError(event: any): { error: string; [key: string]: any } | null {
325
- if (typeof event?.data !== 'string' || event.data === '') return null
392
+ /** The payload of a server-sent `event: error`, normalised to carry `error`. */
393
+ function readServerError(raw: string): { error: string; [key: string]: any } {
326
394
  try {
327
- const data = JSON.parse(event.data)
395
+ const data = JSON.parse(raw)
328
396
  const message = data?.error ?? data?.message ?? data?.detail
329
- return { ...(typeof data === 'object' ? data : {}), error: String(message ?? event.data) }
397
+ return { ...(typeof data === 'object' ? data : {}), error: String(message ?? raw) }
398
+ } catch {
399
+ return { error: raw }
400
+ }
401
+ }
402
+
403
+ /** The API's `detail` from a refused connect, as a suffix for the error message. */
404
+ async function readDetail(response: Response): Promise<string> {
405
+ try {
406
+ const body = await response.text()
407
+ try {
408
+ const detail = JSON.parse(body)?.detail
409
+ if (detail) return ` ${typeof detail === 'string' ? detail : JSON.stringify(detail)}`
410
+ } catch {
411
+ // Not JSON; fall through to the raw text.
412
+ }
413
+ return body ? ` ${body.slice(0, 200)}` : ''
330
414
  } catch {
331
- return { error: event.data }
415
+ return ''
416
+ }
417
+ }
418
+
419
+ /** The `text/event-stream` format, fed in chunks that can split anywhere. */
420
+ class SSEParser {
421
+ private buffer = ''
422
+ private type = ''
423
+ private data: string[] = []
424
+ private lastEventId = ''
425
+
426
+ constructor(private onEvent: (event: ParsedEvent) => void) {}
427
+
428
+ feed(text: string): void {
429
+ this.buffer += text
430
+ // A trailing CR may be half of a CRLF split across chunks, so it waits.
431
+ const heldCR = this.buffer.endsWith('\r')
432
+ const lines = (heldCR ? this.buffer.slice(0, -1) : this.buffer).split(/\r\n|\n|\r/)
433
+ this.buffer = (lines.pop() ?? '') + (heldCR ? '\r' : '')
434
+ for (const line of lines) this.readLine(line)
435
+ }
436
+
437
+ private readLine(line: string): void {
438
+ if (line === '') {
439
+ if (this.data.length > 0) {
440
+ this.onEvent({
441
+ type: this.type || 'message',
442
+ data: this.data.join('\n'),
443
+ lastEventId: this.lastEventId,
444
+ })
445
+ }
446
+ this.type = ''
447
+ this.data = []
448
+ return
449
+ }
450
+ if (line.startsWith(':')) return
451
+
452
+ const colon = line.indexOf(':')
453
+ const field = colon === -1 ? line : line.slice(0, colon)
454
+ const value = colon === -1 ? '' : line.slice(colon + 1).replace(/^ /, '')
455
+ if (field === 'event') this.type = value
456
+ else if (field === 'data') this.data.push(value)
457
+ else if (field === 'id' && !value.includes('\0')) this.lastEventId = value
332
458
  }
333
459
  }
@@ -102,6 +102,19 @@ export interface GraphQLClientConfig {
102
102
  /** Base of the retry backoff, in milliseconds. */
103
103
  retryDelay?: number;
104
104
  }
105
+ /**
106
+ * Apply a credential to an in-progress request's headers, choosing
107
+ * the right header based on token shape:
108
+ *
109
+ * - `rfs…` prefix → `X-API-Key` (long-lived API key, validated
110
+ * against the database's api_keys table).
111
+ * - anything else → `Authorization: Bearer …` (short-lived JWT,
112
+ * validated by JWT middleware).
113
+ *
114
+ * The two credential types are NOT interchangeable at the backend —
115
+ * sending a JWT as `X-API-Key` or an API key as Bearer both 401.
116
+ */
117
+ export declare function applyAuthHeader(headers: Headers, token: string): void;
105
118
  /** The auth header for a credential — see {@link applyAuthHeader} for the rule. */
106
119
  export declare function authHeaderFor(token: string): Record<string, string>;
107
120
  /**
@@ -3,6 +3,7 @@
3
3
  Object.defineProperty(exports, "__esModule", { value: true });
4
4
  exports.GraphQLClientCache = exports.GraphQLError = exports.DEFAULT_GRAPHQL_TIMEOUT_MS = void 0;
5
5
  exports.toGraphQLError = toGraphQLError;
6
+ exports.applyAuthHeader = applyAuthHeader;
6
7
  exports.authHeaderFor = authHeaderFor;
7
8
  exports.resolveCredential = resolveCredential;
8
9
  exports.pathSegment = pathSegment;
@@ -164,7 +164,7 @@ function createTimeoutFetch(timeoutMs: number): typeof fetch {
164
164
  * The two credential types are NOT interchangeable at the backend —
165
165
  * sending a JWT as `X-API-Key` or an API key as Bearer both 401.
166
166
  */
167
- function applyAuthHeader(headers: Headers, token: string): void {
167
+ export function applyAuthHeader(headers: Headers, token: string): void {
168
168
  // The resolved credential replaces any the static headers carry, so
169
169
  // exactly one is sent.
170
170
  headers.delete('X-API-Key')