@sylphx/sdk 0.22.0 → 0.23.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.
@@ -1488,6 +1488,9 @@ declare function getStreams(): StreamsClient;
1488
1488
  /**
1489
1489
  * Sylphx Server SDK
1490
1490
  *
1491
+ * @privilege-asymmetry:O-5 — re-exports Customer Zero identity predicate;
1492
+ * see docs/catalog/subsystems/privilege-asymmetry.md §3.2.
1493
+ *
1491
1494
  * Server-side operations using REST API for type safety.
1492
1495
  * Uses connection URL (sylphx://sk_*@tenant-slug.api.sylphx.com) for authentication.
1493
1496
  *
@@ -1551,6 +1554,14 @@ declare function createServerRestClient(config: ServerConfig): RestClient;
1551
1554
  * Create a Server REST Client with user context (access token)
1552
1555
  */
1553
1556
  declare function createAuthenticatedServerClient(config: ServerConfig, accessToken: string): RestClient;
1557
+ /**
1558
+ * Canonical JWT `iss` for Platform-minted access tokens.
1559
+ * Matches `packages/core` `JWT_ISSUER` production fallback (`https://sylphx.com`).
1560
+ * Not the tenant BaaS routing host (`{slug}.api.sylphx.com`).
1561
+ */
1562
+ declare const DEFAULT_JWT_ISSUER = "https://sylphx.com";
1563
+ /** Public JWKS path on the issuer origin (not tenant BaaS; tenant JWKS requires app secret). */
1564
+ declare const JWT_JWKS_PATH = "/api/v1/auth/.well-known/jwks.json";
1554
1565
  /**
1555
1566
  * Reset the JWKS cache.
1556
1567
  *
@@ -1564,61 +1575,62 @@ declare function createAuthenticatedServerClient(config: ServerConfig, accessTok
1564
1575
  */
1565
1576
  declare function resetJwksCache(): void;
1566
1577
  /**
1567
- * Fetch JWKS from the platform
1578
+ * Resolve the JWT issuer origin used for `iss` pin + JWKS fetch.
1579
+ * `SYLPHX_JWT_ISSUER` overrides for non-prod / dedicated issuer hosts.
1568
1580
  */
1569
- declare function getJwks(platformUrl?: string): Promise<JsonWebKey[]>;
1581
+ declare function resolveJwtIssuer(explicit?: string): string;
1582
+ /**
1583
+ * Fetch JWKS from the **issuer** origin (canonical Platform JWT contract).
1584
+ *
1585
+ * Do not pass a tenant BaaS routing URL (`{slug}.api.sylphx.com`): that host
1586
+ * requires `x-app-secret` on JWKS and is not the JWT issuer.
1587
+ *
1588
+ * @param issuer - JWT issuer origin (default {@link DEFAULT_JWT_ISSUER})
1589
+ */
1590
+ declare function getJwks(issuer?: string): Promise<JsonWebKey[]>;
1570
1591
  /**
1571
1592
  * Verify an access token from the platform.
1572
1593
  *
1573
- * Verifies the RS256 signature against the cached JWKS and the `iss` claim.
1594
+ * Verifies RS256 signature against issuer JWKS, pins `iss` to the canonical
1595
+ * JWT issuer (not the tenant BaaS host), and **requires** `audience`.
1596
+ *
1597
+ * ## Issuer vs routing URL
1598
+ *
1599
+ * Tokens are minted with `iss = JWT_ISSUER` (`https://sylphx.com` in prod).
1600
+ * `platformUrl` is the BaaS routing target only; it must never be used as
1601
+ * `iss` or as the JWKS origin (tenant hosts return 401 on public JWKS).
1574
1602
  *
1575
1603
  * ## Audience
1576
1604
  *
1577
- * Pass `audience` to bind the token to the resource server it was minted for.
1578
- * Platform-issued tokens carry `aud === app_id` (literal `'platform'` for
1579
- * Platform-app tokens; the customer app's identity otherwise — see ADR-2062).
1580
- * When supplied, `jose` rejects any token whose `aud` does not match — a token
1581
- * signed for a different audience is refused even though its signature is
1582
- * valid. **Always pass `audience` on a resource server**; omitting it accepts
1583
- * any validly-signed token regardless of its intended audience (a fail-open
1584
- * trap). The option is optional only for backward compatibility with existing
1585
- * callers; new code should always pass it.
1586
- *
1587
- * The canonical verifier with mandatory audience + kid-rotation is the root
1588
- * `verifyAccessToken` from `@sylphx/sdk` (`{ baseUrl, audience }`); prefer it
1589
- * for Platform-internal resource servers. This `/server` variant exists for
1590
- * customer apps verifying their own end-user tokens.
1591
- *
1592
- * ## Returned claims
1593
- *
1594
- * Org context (`org_id`/`org_slug`/`org_role`) and the RFC 7800 `cnf`
1595
- * confirmation claim are preserved when present. Downstream org-scoped
1596
- * authorization and DPoP binding depend on these — a resource server MUST
1597
- * compare `org_id` against the addressed resource and assert `org_role`
1598
- * against its allowlist before granting org-scoped access.
1605
+ * Platform-issued project tokens carry `aud === app.slug` (and Platform-app
1606
+ * tokens use `aud === 'platform'` — ADR-2062). Audience is mandatory:
1607
+ * omitting it is a fail-open trap and is rejected.
1599
1608
  *
1600
1609
  * @example
1601
1610
  * ```typescript
1602
1611
  * import { verifyAccessToken } from '@sylphx/sdk/server'
1603
1612
  *
1604
1613
  * const claims = await verifyAccessToken(bearer, {
1605
- * platformUrl: 'https://your-app.api.sylphx.com',
1606
- * audience: 'your-app', // pins `aud`; reject tokens for other audiences
1614
+ * audience: 'your-app-slug',
1615
+ * // optional: issuer defaults to https://sylphx.com
1607
1616
  * })
1608
1617
  * if (claims.org_id !== resource.orgId) throw new Error('cross-org access')
1609
1618
  * ```
1610
1619
  */
1611
1620
  declare function verifyAccessToken(token: string, options: {
1612
1621
  secretKey?: string;
1622
+ /**
1623
+ * @deprecated Not used for issuer or JWKS. Kept for call-site
1624
+ * compatibility; pass {@link issuer} / {@link audience} instead.
1625
+ */
1613
1626
  platformUrl?: string;
1627
+ /** JWT issuer origin. Defaults to {@link DEFAULT_JWT_ISSUER}. */
1628
+ issuer?: string;
1614
1629
  /**
1615
- * Expected `aud` claim. When supplied, the token is rejected unless its
1616
- * audience matches (string) or is one of the allowed audiences (array,
1617
- * for multi-audience resource servers). Omitting it skips audience
1618
- * validation — only do this if the token's audience is irrelevant to the
1619
- * caller. See the function doc; new code should always pass this.
1630
+ * Expected `aud` claim (project slug or `'platform'`). Required —
1631
+ * tokens for other audiences are rejected even when signature is valid.
1620
1632
  */
1621
- audience?: string | string[];
1633
+ audience: string | string[];
1622
1634
  }): Promise<AccessTokenPayload>;
1623
1635
  interface WebhookPayload {
1624
1636
  event: string;
@@ -2002,4 +2014,4 @@ declare function getDatabaseConnection(options: AuthenticatedFetchOptions): Prom
2002
2014
  */
2003
2015
  declare function getDatabaseStatus(options: AuthenticatedFetchOptions): Promise<DatabaseStatusInfo>;
2004
2016
 
2005
- export { type AIClient, type AIClientOptions, type AppConfig, type AppMetadata, type ChannelHelper, type ChatCompletionChunk, type ChatCompletionOptions, type ChatCompletionResponse, type ChatCompletionStreamOptions, type ChatMessage, type ConsentType, type DatabaseConnectionInfo, type DatabaseStatusInfo, type EmbeddingOptions, type EmbeddingResponse, type EngagementLeaderboardEntry, type EngagementLeaderboardResult, type EnvironmentType, type FeatureFlagDefinition, type FunctionDeployOptions, type FunctionDeployResult, type FunctionInvokeOptions, type FunctionListOptions, type FunctionLogEntry, type FunctionLogsOptions, type FunctionRecord, type FunctionRuntime, type FunctionStatus, FunctionsClient, type GetAppConfigOptions, InvalidConnectionUrlError, type KeyType, type KeyValidationResult, type KvClient, type KvClientOptions, type KvRateLimitResult, type KvSetOptions, type KvZMember, type ModelInfo, type ModelsResponse, type OAuthProvider, type OAuthProviderInfo, PLATFORM_TENANT_BAAS_URL, type Plan, type PlatformBaasUrlEnv, type ReferralLeaderboardEntry, type ReferralLeaderboardResult, type RestClient, type RestClientConfig as ServerClientConfig, type ServerConfig, type StreamHistoryOptions, type StreamMessage, type StreamsClient, type StreamsClientOptions, type SylphxClientInput, type SylphxConfig, type WebhookPayload, type WebhookVerifyOptions, type WebhookVerifyResult, createAI, createAuthenticatedServerClient, createClient, createKv, createServerClient, createServerRestClient, createStreams, createWebhookHandler, decodeUserId, detectEnvironment, detectKeyType, encodeUserId, getAI, getAppConfig, getAppMetadata, getConsentTypes, getCookieNamespace, getDatabaseConnection, getDatabaseStatus, getEngagementLeaderboard, getFeatureFlags, getJwks, getKv, getOAuthProviders, getOAuthProvidersWithInfo, getPlans, getReferralLeaderboard, getStreams, isAppId, isDevelopmentKey, isDevelopmentRuntime, isProductionKey, isSecretKey, resetJwksCache, resolvePlatformBaasUrl, validateAndSanitizeAppId, validateAndSanitizeKey, validateAndSanitizeSecretKey, validateAppId, validateKey, validateSecretKey, verifyAccessToken, verifyWebhook };
2017
+ export { type AIClient, type AIClientOptions, type AppConfig, type AppMetadata, type ChannelHelper, type ChatCompletionChunk, type ChatCompletionOptions, type ChatCompletionResponse, type ChatCompletionStreamOptions, type ChatMessage, type ConsentType, DEFAULT_JWT_ISSUER, type DatabaseConnectionInfo, type DatabaseStatusInfo, type EmbeddingOptions, type EmbeddingResponse, type EngagementLeaderboardEntry, type EngagementLeaderboardResult, type EnvironmentType, type FeatureFlagDefinition, type FunctionDeployOptions, type FunctionDeployResult, type FunctionInvokeOptions, type FunctionListOptions, type FunctionLogEntry, type FunctionLogsOptions, type FunctionRecord, type FunctionRuntime, type FunctionStatus, FunctionsClient, type GetAppConfigOptions, InvalidConnectionUrlError, JWT_JWKS_PATH, type KeyType, type KeyValidationResult, type KvClient, type KvClientOptions, type KvRateLimitResult, type KvSetOptions, type KvZMember, type ModelInfo, type ModelsResponse, type OAuthProvider, type OAuthProviderInfo, PLATFORM_TENANT_BAAS_URL, type Plan, type PlatformBaasUrlEnv, type ReferralLeaderboardEntry, type ReferralLeaderboardResult, type RestClient, type RestClientConfig as ServerClientConfig, type ServerConfig, type StreamHistoryOptions, type StreamMessage, type StreamsClient, type StreamsClientOptions, type SylphxClientInput, type SylphxConfig, type WebhookPayload, type WebhookVerifyOptions, type WebhookVerifyResult, createAI, createAuthenticatedServerClient, createClient, createKv, createServerClient, createServerRestClient, createStreams, createWebhookHandler, decodeUserId, detectEnvironment, detectKeyType, encodeUserId, getAI, getAppConfig, getAppMetadata, getConsentTypes, getCookieNamespace, getDatabaseConnection, getDatabaseStatus, getEngagementLeaderboard, getFeatureFlags, getJwks, getKv, getOAuthProviders, getOAuthProvidersWithInfo, getPlans, getReferralLeaderboard, getStreams, isAppId, isDevelopmentKey, isDevelopmentRuntime, isProductionKey, isSecretKey, resetJwksCache, resolveJwtIssuer, resolvePlatformBaasUrl, validateAndSanitizeAppId, validateAndSanitizeKey, validateAndSanitizeSecretKey, validateAppId, validateKey, validateSecretKey, verifyAccessToken, verifyWebhook };
@@ -1139,6 +1139,7 @@ function resolveSecretUrl(explicit) {
1139
1139
  }
1140
1140
  var SDK_API_PATH = `/v1`;
1141
1141
  var DEFAULT_SDK_API_HOST = "api.sylphx.com";
1142
+ var DEFAULT_PLATFORM_URL = "https://sylphx.com";
1142
1143
  var SDK_VERSION = "0.5.0";
1143
1144
  function detectSdkPlatform() {
1144
1145
  if (typeof window !== "undefined") return "browser";
@@ -2983,24 +2984,35 @@ function isJwksResponse(data) {
2983
2984
  function isAccessTokenPayload(payload) {
2984
2985
  return typeof payload.sub === "string" && typeof payload.email === "string" && typeof payload.app_id === "string" && typeof payload.iat === "number" && typeof payload.exp === "number";
2985
2986
  }
2987
+ var DEFAULT_JWT_ISSUER = DEFAULT_PLATFORM_URL;
2988
+ var JWT_JWKS_PATH = "/api/v1/auth/.well-known/jwks.json";
2986
2989
  var jwksCache = null;
2987
2990
  function resetJwksCache() {
2988
2991
  jwksCache = null;
2989
2992
  }
2990
- async function getJwks(platformUrl = `https://${DEFAULT_SDK_API_HOST}`) {
2993
+ function normalizeIssuerOrigin(issuer) {
2994
+ return issuer.trim().replace(/\/+$/, "");
2995
+ }
2996
+ function resolveJwtIssuer(explicit) {
2997
+ const fromEnv = process.env.SYLPHX_JWT_ISSUER?.trim();
2998
+ return normalizeIssuerOrigin(explicit || fromEnv || DEFAULT_JWT_ISSUER);
2999
+ }
3000
+ async function getJwks(issuer = DEFAULT_JWT_ISSUER) {
3001
+ const issuerOrigin = resolveJwtIssuer(issuer);
2991
3002
  const now = Date.now();
2992
- if (jwksCache && jwksCache.expiresAt > now) {
3003
+ if (jwksCache && jwksCache.issuer === issuerOrigin && jwksCache.expiresAt > now) {
2993
3004
  return jwksCache.keys;
2994
3005
  }
2995
- const response = await fetch(`${platformUrl}/api/v1/auth/.well-known/jwks.json`);
3006
+ const response = await fetch(`${issuerOrigin}${JWT_JWKS_PATH}`);
2996
3007
  if (!response.ok) {
2997
- throw new Error("Failed to fetch JWKS");
3008
+ throw new Error(`Failed to fetch JWKS from ${issuerOrigin}${JWT_JWKS_PATH}`);
2998
3009
  }
2999
3010
  const data = await response.json();
3000
3011
  if (!isJwksResponse(data)) {
3001
3012
  throw new Error("Invalid JWKS response format");
3002
3013
  }
3003
3014
  jwksCache = {
3015
+ issuer: issuerOrigin,
3004
3016
  keys: data.keys,
3005
3017
  expiresAt: now + JWK_CACHE_TTL_MS
3006
3018
  // Cache for 1 hour
@@ -3008,8 +3020,16 @@ async function getJwks(platformUrl = `https://${DEFAULT_SDK_API_HOST}`) {
3008
3020
  return data.keys;
3009
3021
  }
3010
3022
  async function verifyAccessToken(token, options) {
3011
- const platformUrl = options.platformUrl || `https://${DEFAULT_SDK_API_HOST}`;
3012
- const keys = await getJwks(platformUrl);
3023
+ const audience = options.audience;
3024
+ if (audience === void 0 || audience === null || typeof audience === "string" && !audience.trim() || Array.isArray(audience) && audience.length === 0) {
3025
+ throw new Error(
3026
+ "verifyAccessToken requires audience (token aud / app.slug). Omitting audience is fail-open and is not allowed."
3027
+ );
3028
+ }
3029
+ void options.platformUrl;
3030
+ void options.secretKey;
3031
+ const issuer = resolveJwtIssuer(options.issuer);
3032
+ const keys = await getJwks(issuer);
3013
3033
  if (!keys.length) {
3014
3034
  throw new Error("No keys in JWKS");
3015
3035
  }
@@ -3018,8 +3038,8 @@ async function verifyAccessToken(token, options) {
3018
3038
  try {
3019
3039
  const jwk = await importJWK(key, "RS256");
3020
3040
  const { payload } = await jwtVerify(token, jwk, {
3021
- issuer: platformUrl,
3022
- ...options.audience !== void 0 ? { audience: options.audience } : {}
3041
+ issuer,
3042
+ audience
3023
3043
  });
3024
3044
  if (!isAccessTokenPayload(payload)) {
3025
3045
  throw new Error("Invalid token payload structure");
@@ -3370,8 +3390,10 @@ async function getDatabaseStatus(options) {
3370
3390
  });
3371
3391
  }
3372
3392
  export {
3393
+ DEFAULT_JWT_ISSUER,
3373
3394
  FunctionsClient,
3374
3395
  InvalidConnectionUrlError,
3396
+ JWT_JWKS_PATH,
3375
3397
  LEGACY_PLATFORM_PROJECT_ID,
3376
3398
  PLATFORM_CONSOLE_SLUG,
3377
3399
  PLATFORM_TENANT_BAAS_URL,
@@ -3410,6 +3432,7 @@ export {
3410
3432
  isProductionKey,
3411
3433
  isSecretKey,
3412
3434
  resetJwksCache,
3435
+ resolveJwtIssuer,
3413
3436
  resolvePlatformBaasUrl,
3414
3437
  validateAndSanitizeAppId,
3415
3438
  validateAndSanitizeKey,