@synthigy/sdk 0.2.0 → 0.2.1

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.
@@ -11,7 +11,7 @@ import path from 'node:path'
11
11
  import { createHash } from 'node:crypto'
12
12
  import { execFileSync } from 'node:child_process'
13
13
  import { createRequire } from 'node:module'
14
- import { TS, tsScalar, pascal, camel } from './lib.mjs'
14
+ import { TS, tsScalar, pascal, camel, warnStaleSchema } from './lib.mjs'
15
15
  import { PLATFORM_AUDIENCE } from '../src/index.js'
16
16
 
17
17
  let tsVersion = null
@@ -140,6 +140,8 @@ if (!flags.schemaOverride && (flags.pull || !fs.existsSync(schemaPath))) {
140
140
  execFileSync(process.execPath,
141
141
  [path.join(here, 'pull.mjs'), endpoint(), schemaPath],
142
142
  { stdio: 'inherit', env: process.env })
143
+ } else {
144
+ await warnStaleSchema(ENDPOINT, schemaPath)
143
145
  }
144
146
 
145
147
  if (!fs.existsSync(schemaPath)) {
package/codegen/lib.mjs CHANGED
@@ -1,3 +1,5 @@
1
+ import fs from 'node:fs'
2
+
1
3
  // Shared codegen primitives for the TS emitters — one home for the scalar-type
2
4
  // map + casing so the read and write emitters can't drift apart.
3
5
 
@@ -28,3 +30,25 @@ export const camel = (s) => { const p = pascal(s); return p[0].toLowerCase() + p
28
30
  export const snake = (s) => words(s).join('_')
29
31
  // kebab wire keys aren't valid TS identifiers → keep verbatim, quote when needed.
30
32
  export const tsKey = (k) => (/^[A-Za-z_$][\w$]*$/.test(k) ? k : JSON.stringify(k))
33
+
34
+ // One line on `write` when the schema's deploy stamp is older than the model at
35
+ // /.well-known/synthigy. Silent on any failure: generation stays offline-capable.
36
+ export async function warnStaleSchema(endpoint, schemaPath, write = (s) => console.error(s)) {
37
+ if (!endpoint || !fs.existsSync(schemaPath)) return
38
+ let local, remote
39
+ try {
40
+ local = JSON.parse(fs.readFileSync(schemaPath, 'utf8')).datasets ?? {}
41
+ const r = await fetch(`${endpoint.replace(/\/$/, '')}/.well-known/synthigy`,
42
+ { signal: AbortSignal.timeout(2000) })
43
+ if (!r.ok) return
44
+ remote = (await r.json()).datasets ?? {}
45
+ } catch {
46
+ return
47
+ }
48
+ const instant = (s) => (Number.isNaN(Date.parse(s)) ? s : Date.parse(s))
49
+ const changed = Object.keys(remote).filter((id) => instant(local[id]?.['deployed-at']) !== instant(remote[id]))
50
+ .concat(Object.keys(local).filter((id) => !(id in remote)))
51
+ if (changed.length) {
52
+ write(`warning: ${schemaPath} is stale against ${endpoint} (${changed.length} datasets changed since the pull) — re-run with --pull`)
53
+ }
54
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@synthigy/sdk",
3
- "version": "0.2.0",
3
+ "version": "0.2.1",
4
4
  "description": "Zero-dependency client for Synthigy's /data endpoint",
5
5
  "author": "Robert Geršak",
6
6
  "license": "MIT",
@@ -14,7 +14,8 @@
14
14
  import { pkce, decodeJwtPayload } from './login.js'
15
15
 
16
16
  const PENDING_PREFIX = 'synthigy.login:'
17
- const PENDING_TTL_MS = 5 * 60_000
17
+ // must exceed the server's 8-minute login window, or slow logins fail LOGIN_STATE_UNKNOWN
18
+ const PENDING_TTL_MS = 10 * 60_000
18
19
  const MESSAGE_SOURCE = 'synthigy-login'
19
20
 
20
21
  function randomToken(bytes) {
package/src/index.d.ts CHANGED
@@ -275,6 +275,13 @@ export interface Schema {
275
275
  * UNAUTHORIZED, CLIENT_NOT_FOUND, CLIENT_INACTIVE,
276
276
  * PUBLIC_CLIENT_FORBIDDEN, NOT_TRUSTED, USER_NOT_FOUND, FORBIDDEN
277
277
  *
278
+ * Token mint refused (client credentials):
279
+ * INVALID_CLIENT, INVALID_SCOPE, INVALID_AUDIENCE
280
+ *
281
+ * Permission denied (RBAC/RLS):
282
+ * ENTITY_FORBIDDEN, RELATION_FORBIDDEN, ATTRIBUTE_FORBIDDEN,
283
+ * ROW_FORBIDDEN, CREATE_FORBIDDEN, DELETE_FORBIDDEN, SLOT_OCCUPIED
284
+ *
278
285
  * Request shape:
279
286
  * INVALID_BODY, NO_OPERATIONS, BAD_OP, MISSING_ENTITY,
280
287
  * BAD_ARGS_SHAPE
@@ -302,6 +309,9 @@ export type SynthigyErrorCode =
302
309
  | 'UNAUTHORIZED' | 'CLIENT_NOT_FOUND' | 'CLIENT_INACTIVE'
303
310
  | 'PUBLIC_CLIENT_FORBIDDEN' | 'NOT_TRUSTED' | 'USER_NOT_FOUND'
304
311
  | 'FORBIDDEN' | 'NO_TOKEN'
312
+ | 'INVALID_CLIENT' | 'INVALID_SCOPE' | 'INVALID_AUDIENCE'
313
+ | 'ENTITY_FORBIDDEN' | 'RELATION_FORBIDDEN' | 'ATTRIBUTE_FORBIDDEN'
314
+ | 'ROW_FORBIDDEN' | 'CREATE_FORBIDDEN' | 'DELETE_FORBIDDEN' | 'SLOT_OCCUPIED'
305
315
  | 'NO_LOGIN_STORE' | 'LOGIN_REQUIRES_CONFIDENTIAL_CLIENT'
306
316
  | 'LOGIN_STATE_UNKNOWN' | 'LOGIN_NONCE_MISMATCH' | 'LOGIN_EXCHANGE_FAILED'
307
317
  | 'INVALID_BODY' | 'NO_OPERATIONS' | 'BAD_OP' | 'MISSING_ENTITY'
package/src/index.js CHANGED
@@ -415,10 +415,7 @@ class TokenManager {
415
415
  body: params,
416
416
  })
417
417
 
418
- if (!resp.ok) {
419
- const text = await resp.text()
420
- throw new Error(`Token request failed (${resp.status}): ${text}`)
421
- }
418
+ if (!resp.ok) throw _tokenRefusal(resp.status, await resp.text())
422
419
 
423
420
  const data = await resp.json()
424
421
  this._tokens.set(key, {
@@ -434,6 +431,28 @@ class TokenManager {
434
431
  }
435
432
  }
436
433
 
434
+ /** RFC 6749 §5.2 / RFC 8707 refusals with their own code; any other refusal is UNAUTHORIZED. */
435
+ const REFUSAL_CODES = {
436
+ invalid_client: 'INVALID_CLIENT',
437
+ invalid_scope: 'INVALID_SCOPE',
438
+ invalid_target: 'INVALID_AUDIENCE',
439
+ }
440
+
441
+ function _tokenRefusal(status, text) {
442
+ let oauth = null
443
+ try { oauth = JSON.parse(text) } catch {}
444
+ if (typeof oauth?.error !== 'string' || oauth.error === '') {
445
+ return new SynthigyError(`Token request failed (${status}): ${text}`, 'UNAUTHORIZED', undefined, { status })
446
+ }
447
+ const code = Object.hasOwn(REFUSAL_CODES, oauth.error) ? REFUSAL_CODES[oauth.error] : 'UNAUTHORIZED'
448
+ const desc = typeof oauth.error_description === 'string' && oauth.error_description !== ''
449
+ ? ` — ${oauth.error_description}` : ''
450
+ return new SynthigyError(`Token request refused (${status}): ${oauth.error}${desc}`, code, oauth, {
451
+ status,
452
+ hint: code === 'INVALID_CLIENT' ? 'check the client id and secret, and that the client is active' : undefined,
453
+ })
454
+ }
455
+
437
456
  // ============================================================================
438
457
  // Supervised stdio — SYNTHIGY_SUPERVISED=1. The SDK never mints locally
439
458
  // under this mode: the CLI/commander is the platform's stdio owner, so a
@@ -665,6 +684,10 @@ const ERROR_CATEGORIES = {
665
684
  LOGIN_NONCE_MISMATCH: 'auth',
666
685
  LOGIN_EXCHANGE_FAILED: 'auth',
667
686
  SILENT_TIMEOUT: 'auth',
687
+ USERINFO_SUB_MISMATCH: 'auth',
688
+ INVALID_CLIENT: 'auth',
689
+ INVALID_SCOPE: 'auth',
690
+ INVALID_AUDIENCE: 'auth',
668
691
  // OAuth error codes the IdP redirects back with (RFC 6749 4.1.2.1, OIDC 3.1.2.6)
669
692
  access_denied: 'auth',
670
693
  login_required: 'auth',
@@ -676,6 +699,12 @@ const ERROR_CATEGORIES = {
676
699
  ENTITY_FORBIDDEN: 'iam',
677
700
  ENTITY_NOT_READABLE: 'iam',
678
701
  RELATION_NOT_READABLE: 'iam',
702
+ RELATION_FORBIDDEN: 'iam',
703
+ ATTRIBUTE_FORBIDDEN: 'iam',
704
+ ROW_FORBIDDEN: 'iam',
705
+ CREATE_FORBIDDEN: 'iam',
706
+ DELETE_FORBIDDEN: 'iam',
707
+ SLOT_OCCUPIED: 'iam',
679
708
  // validation
680
709
  INVALID_BODY: 'validation',
681
710
  NO_OPERATIONS: 'validation',
@@ -732,11 +761,14 @@ const ERROR_CATEGORIES = {
732
761
  INTERNAL_ERROR: 'internal',
733
762
  OPERATION_ERROR: 'internal',
734
763
  HTTP_ERROR: 'internal',
764
+ OPERATION_FAILED: 'internal',
765
+ USERINFO_FAILED: 'internal',
735
766
  }
736
767
 
737
768
  /**
738
769
  * Codes whose category is automatically retryable. Any other code is
739
- * one-shot: the caller must fix something before retrying.
770
+ * one-shot: the caller must fix something before retrying. A code missing
771
+ * from ERROR_CATEGORIES is retryable only when the server marks it so.
740
772
  */
741
773
  const RETRYABLE_CATEGORIES = new Set(['network', 'rate_limit', 'internal'])
742
774
 
@@ -777,7 +809,9 @@ export class SynthigyError extends Error {
777
809
  this.name = 'SynthigyError'
778
810
  this.code = code
779
811
  this.category = ERROR_CATEGORIES[code] ?? 'internal'
780
- this.retryable = RETRYABLE_CATEGORIES.has(this.category)
812
+ this.retryable = typeof extras?.retryable === 'boolean'
813
+ ? extras.retryable
814
+ : Object.hasOwn(ERROR_CATEGORIES, code) && RETRYABLE_CATEGORIES.has(this.category)
781
815
  if (details !== undefined) this.details = details
782
816
  if (extras) {
783
817
  if (extras.hint !== undefined) this.hint = extras.hint
@@ -833,6 +867,7 @@ function _errorFromServer(err, status, requestId) {
833
867
  start: err.start,
834
868
  end: err.end,
835
869
  diagnostics: err.diagnostics,
870
+ retryable: err.retryable,
836
871
  requestId,
837
872
  status,
838
873
  })
package/src/login.js CHANGED
@@ -13,7 +13,8 @@
13
13
 
14
14
  const PKCE_VERIFIER_BYTES = 32
15
15
  const STATE_BYTES = 24
16
- const DEFAULT_TTL_MS = 5 * 60_000
16
+ // must exceed the server's 8-minute login window, or slow logins fail LOGIN_STATE_UNKNOWN
17
+ const LOGIN_TTL_MS = 10 * 60_000
17
18
 
18
19
  function base64urlEncode(bytes) {
19
20
  let binary = ''
@@ -69,7 +70,7 @@ export function decodeJwtPayload(jwt) {
69
70
  * holds their sessions (Redis, Postgres, a signed cookie).
70
71
  */
71
72
  export class MemoryLoginStore {
72
- constructor({ ttlMs = DEFAULT_TTL_MS } = {}) {
73
+ constructor({ ttlMs = LOGIN_TTL_MS } = {}) {
73
74
  this._ttlMs = ttlMs
74
75
  this._pending = new Map()
75
76
  }
@@ -127,6 +128,12 @@ export function createLoginApi(client, { SynthigyError }) {
127
128
  }
128
129
  }
129
130
 
131
+ // the store's own expiry is not trusted: one that never expires would accept a login of any age
132
+ const takePending = async (state) => {
133
+ const pending = state ? await client._loginStore.take(state) : null
134
+ return pending && pending.createdAt > Date.now() - LOGIN_TTL_MS ? pending : null
135
+ }
136
+
130
137
  return {
131
138
  /**
132
139
  * Begin a login: returns the URL to redirect the browser to, and stashes
@@ -167,7 +174,7 @@ export function createLoginApi(client, { SynthigyError }) {
167
174
  */
168
175
  async complete({ code, state, redirectUri } = {}) {
169
176
  requireConfidential()
170
- const pending = state ? await client._loginStore.take(state) : null
177
+ const pending = await takePending(state)
171
178
  if (!pending) {
172
179
  throw new SynthigyError(
173
180
  'unknown or expired login state: the store never saw it, it was ' +
@@ -230,7 +237,7 @@ export function createLoginApi(client, { SynthigyError }) {
230
237
  * here rather than a throw.
231
238
  */
232
239
  async cancel(state) {
233
- const pending = state ? await client._loginStore.take(state) : null
240
+ const pending = await takePending(state)
234
241
  return pending ? { returnTo: pending.returnTo } : null
235
242
  },
236
243
  }