@mitralab.io/sdk-core 0.2.0-beta.1 → 0.2.0-beta.2

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/dist/index.cjs CHANGED
@@ -20,9 +20,11 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
20
20
  // src/index.ts
21
21
  var index_exports = {};
22
22
  __export(index_exports, {
23
+ API_KEY_EXCHANGE_PATH: () => API_KEY_EXCHANGE_PATH,
23
24
  AgentTaskTurnError: () => AgentTaskTurnError,
24
25
  SdkCoreConfigurationError: () => SdkCoreConfigurationError,
25
26
  SdkCoreResponseError: () => SdkCoreResponseError,
27
+ appAccessTokenPath: () => appAccessTokenPath,
26
28
  createAgentConnectionsModule: () => createAgentConnectionsModule,
27
29
  createAgentCredentialsModule: () => createAgentCredentialsModule,
28
30
  createAgentTaskSessionManager: () => createAgentTaskSessionManager,
@@ -58,7 +60,12 @@ __export(index_exports, {
58
60
  expectObjectArray: () => expectObjectArray,
59
61
  expectPage: () => expectPage,
60
62
  expectStringArray: () => expectStringArray,
63
+ isWorkspaceSession: () => isWorkspaceSession,
64
+ readTokenAppId: () => readTokenAppId,
65
+ readTokenExpiry: () => readTokenExpiry,
66
+ resolveApiKeyToken: () => resolveApiKeyToken,
61
67
  toAgentTimelineItem: () => toAgentTimelineItem,
68
+ tokenAuthorizesApp: () => tokenAuthorizesApp,
62
69
  withAgentTaskSessions: () => withAgentTaskSessions
63
70
  });
64
71
  module.exports = __toCommonJS(index_exports);
@@ -3694,11 +3701,80 @@ var CoreAgentTaskSession = class {
3694
3701
  }
3695
3702
  }
3696
3703
  };
3704
+
3705
+ // src/apiKeySession.ts
3706
+ var API_KEY_EXCHANGE_PATH = "/api/v1/auth/exchange";
3707
+ function appAccessTokenPath(appId) {
3708
+ return `/api/v1/auth/apps/${encodeURIComponent(appId)}/access-token`;
3709
+ }
3710
+ function decodeTokenPayload(token) {
3711
+ const segment = token.split(".")[1];
3712
+ if (!segment || typeof globalThis.atob !== "function") return null;
3713
+ try {
3714
+ const base64 = segment.replaceAll("-", "+").replaceAll("_", "/");
3715
+ const padded = base64 + "=".repeat((4 - base64.length % 4) % 4);
3716
+ const decoded = JSON.parse(globalThis.atob(padded));
3717
+ if (!decoded || typeof decoded !== "object" || Array.isArray(decoded)) return null;
3718
+ return decoded;
3719
+ } catch {
3720
+ return null;
3721
+ }
3722
+ }
3723
+ function readTokenAppId(token) {
3724
+ const appId = decodeTokenPayload(token)?.app_id;
3725
+ return typeof appId === "string" && appId ? appId : null;
3726
+ }
3727
+ function readTokenExpiry(token) {
3728
+ const exp = decodeTokenPayload(token)?.exp;
3729
+ return typeof exp === "number" && Number.isFinite(exp) ? exp * 1e3 : null;
3730
+ }
3731
+ function tokenAuthorizesApp(token, appId) {
3732
+ const payload = decodeTokenPayload(token);
3733
+ if (!payload) return true;
3734
+ return payload.app_id === appId;
3735
+ }
3736
+ function isWorkspaceSession(token) {
3737
+ const payload = decodeTokenPayload(token);
3738
+ return payload !== null && payload.app_id === void 0;
3739
+ }
3740
+ function readAccessToken(payload, operation, errors) {
3741
+ const token = payload && typeof payload === "object" ? payload.accessToken : void 0;
3742
+ if (typeof token !== "string" || !token.trim()) {
3743
+ throw errors.invalidResponse(`The ${operation} response did not include an access token`);
3744
+ }
3745
+ return token;
3746
+ }
3747
+ async function resolveApiKeyToken(call, appId, apiKey, errors = defaultSdkCoreErrorFactory) {
3748
+ if (!apiKey.trim()) {
3749
+ throw errors.configuration("An api key is required to authenticate with an api key");
3750
+ }
3751
+ if (!appId.trim()) {
3752
+ throw errors.configuration("An app id is required to authenticate with an api key");
3753
+ }
3754
+ const exchanged = readAccessToken(
3755
+ await call(API_KEY_EXCHANGE_PATH, { body: { apiKey } }),
3756
+ "api key exchange",
3757
+ errors
3758
+ );
3759
+ if (tokenAuthorizesApp(exchanged, appId)) return exchanged;
3760
+ if (!isWorkspaceSession(exchanged)) {
3761
+ throw errors.configuration(
3762
+ `This api key belongs to app ${readTokenAppId(exchanged) ?? "unknown"}, not to ${appId}. Create the key for this app, or use a workspace key.`
3763
+ );
3764
+ }
3765
+ return readAccessToken(
3766
+ await call(appAccessTokenPath(appId), { bearer: exchanged }),
3767
+ "app token",
3768
+ errors
3769
+ );
3770
+ }
3697
3771
  // Annotate the CommonJS export names for ESM import in node:
3698
3772
  0 && (module.exports = {
3773
+ API_KEY_EXCHANGE_PATH,
3699
3774
  AgentTaskTurnError,
3700
3775
  SdkCoreConfigurationError,
3701
3776
  SdkCoreResponseError,
3777
+ appAccessTokenPath,
3702
3778
  createAgentConnectionsModule,
3703
3779
  createAgentCredentialsModule,
3704
3780
  createAgentTaskSessionManager,
@@ -3734,6 +3810,11 @@ var CoreAgentTaskSession = class {
3734
3810
  expectObjectArray,
3735
3811
  expectPage,
3736
3812
  expectStringArray,
3813
+ isWorkspaceSession,
3814
+ readTokenAppId,
3815
+ readTokenExpiry,
3816
+ resolveApiKeyToken,
3737
3817
  toAgentTimelineItem,
3818
+ tokenAuthorizesApp,
3738
3819
  withAgentTaskSessions
3739
3820
  });
package/dist/index.d.cts CHANGED
@@ -1846,6 +1846,50 @@ declare function toAgentTimelineItem(message: AgentMessage): AgentTimelineItem;
1846
1846
  declare function createAgentTaskSessionManager(options: AgentTaskSessionManagerOptions): AgentTaskSessionManager;
1847
1847
  declare function withAgentTaskSessions(tasks: AgentTasksModule, manager: AgentTaskSessionManager): AgentTasksWithSessions;
1848
1848
 
1849
+ /**
1850
+ * What the SDKs have to know about trading an api key for a token.
1851
+ *
1852
+ * The knowledge lives here rather than in each SDK because it is a contract with IAM, not a
1853
+ * utility: which claim names the app, what the exchange answers, and when a token still needs
1854
+ * a second call before it authorizes anything. When IAM changes any of that, it changes once.
1855
+ *
1856
+ * This module makes no HTTP call of its own — this package defines `Transport`, it does not
1857
+ * implement one. The caller performs the request and keeps whatever belongs to it: caching,
1858
+ * renewal, its own error type, its own runtime guards.
1859
+ */
1860
+ /** IAM path, relative to the service root, that trades an api key for a token. */
1861
+ declare const API_KEY_EXCHANGE_PATH = "/api/v1/auth/exchange";
1862
+ /** IAM path, relative to the service root, that issues an app token from a workspace session. */
1863
+ declare function appAccessTokenPath(appId: string): string;
1864
+ /** Performs one POST against IAM and returns the parsed body. */
1865
+ type ApiKeyExchangeCaller = (path: string, init: {
1866
+ body?: unknown;
1867
+ bearer?: string;
1868
+ }) => Promise<unknown>;
1869
+ /** The app a token authorizes, or `null` for a workspace session and for anything unreadable. */
1870
+ declare function readTokenAppId(token: string): string | null;
1871
+ /** When a token stops being accepted, in milliseconds, or `null` when it cannot be read. */
1872
+ declare function readTokenExpiry(token: string): number | null;
1873
+ /**
1874
+ * Whether a token already authorizes `appId`.
1875
+ *
1876
+ * An unreadable token counts as authorized: the platform is the authority on a token it
1877
+ * issued, and refusing one the SDK merely failed to parse would break a caller for no reason.
1878
+ */
1879
+ declare function tokenAuthorizesApp(token: string, appId: string): boolean;
1880
+ /** Whether a token is a workspace session, the only kind an app token can be issued from. */
1881
+ declare function isWorkspaceSession(token: string): boolean;
1882
+ /**
1883
+ * Trades an api key for a token that authorizes `appId`.
1884
+ *
1885
+ * A Developer or Business key belongs to a product, so the exchange already answers with that
1886
+ * product's token. An Administrator key belongs to a workspace: the exchange answers with a
1887
+ * workspace session, and the app token is issued from it. That second call is where the
1888
+ * platform decides what the key's owner actually reaches in this product, which is why a
1889
+ * workspace key never turns into blanket access.
1890
+ */
1891
+ declare function resolveApiKeyToken(call: ApiKeyExchangeCaller, appId: string, apiKey: string, errors?: SdkCoreErrorFactory): Promise<string>;
1892
+
1849
1893
  declare function encodePathSegment(value: string | number, name: string, errors?: SdkCoreErrorFactory): string;
1850
1894
 
1851
1895
  declare function expectObject<T extends object>(value: unknown, context: string, errors?: SdkCoreErrorFactory): T;
@@ -1856,4 +1900,4 @@ declare function expectPage<T extends object>(value: unknown, context: string, e
1856
1900
  declare function expectLegacyPage<T extends object>(value: unknown, context: string, errors?: SdkCoreErrorFactory, validateItem?: (value: unknown, context: string, errors: SdkCoreErrorFactory) => T): LegacyPage<T>;
1857
1901
  declare function expectEmpty(value: unknown, context: string, errors?: SdkCoreErrorFactory): void;
1858
1902
 
1859
- export { type AgentBulkDeleteResult, type AgentConnection, type AgentConnectionCreateInput, type AgentConnectionsModule, type AgentCredentialsModule, type AgentDefinition, type AgentInput, type AgentMessage, type AgentModel, type AgentQueueItem, type AgentSendAndWaitOptions, type AgentSendOptions, type AgentSessionTransport, type AgentTask, type AgentTaskCreateInput, type AgentTaskEvent, type AgentTaskEventConnection, type AgentTaskEventObserver, type AgentTaskEventSource, type AgentTaskInput, type AgentTaskListOptions, type AgentTaskSession, type AgentTaskSessionEventMap, type AgentTaskSessionManager, type AgentTaskSessionManagerOptions, type AgentTaskSessionOptions, type AgentTaskSessionStatus, AgentTaskTurnError, type AgentTasksModule, type AgentTasksWithSessions, type AgentTimelineItem, type AgentToolEvent, type AgentTurnResult, type AgentUpdateItem, type AgentsModule, type AppColor, type AppContext, type AppCreateInput, type AppDefinition, type AppDeploy, type AppDomain, type AppFiles, type AppGetOptions, type AppListOptions, type AppMember, type AppPublishOptions, type AppSummary, type AppUpdateInput, type AppVersion, type AppVersionStatus, type AppsModule, type AuthModule, type AuthenticationResult, type BatchExecution, type BatchStatementResult, type BulkUnsubscribeResult, type ColumnInput, type ConnectionConfig, type ConnectionConfigResponse, type ConnectionTestResult, type ContextModule, type ContextModuleDependencies, type CopilotProvider, type CredentialStatus, type CustomQueriesModule, type CustomQueryDefinition, type CustomQueryInput, type CustomQuerySummary, type CustomQueryUpdateInput, type DataSourceBulkItemResult, type DataSourceBulkResult, type DataSourceCreateInput, type DataSourceDbType, type DataSourceDefinition, type DataSourceInstanceType, type DataSourceUpdateInput, type DataSourcesModule, type DdlStatement, type DeviceAuthorization, type DmlStatement, type EmptyFunctionInput, type EntitiesModule, type EntitiesProxy, type EntityListOptions, type EntityListResponse, type EntityTable, type ExistingAgentTaskSessionOptions, type FunctionBulkCreateInput, type FunctionBulkDeleteInput, type FunctionBulkDeleteResult, type FunctionBulkPatchInput, type FunctionBulkPatchItem, type FunctionBulkUpdateItem, type FunctionCreateInput, type FunctionDefinition, type FunctionExecution, type FunctionListOptions, type FunctionPatchInput, type FunctionRuntime, type FunctionSecrets, type FunctionSummary, type FunctionUpdateInput, type FunctionVersion, type FunctionVersionListOptions, type FunctionVisibility, type FunctionsAdminModule, type FunctionsModule, type FunctionsModuleOptions, type HttpMethod, type ImportColumnMapping, type ImportDefinition, type ImportExecution, type ImportExecutionListOptions, type ImportInput, type ImportProcessing, type ImportSchedule, type ImportSource, type ImportSourceResponse, type ImportTarget, type ImportsModule, type IntegrationAdminModule, type IntegrationConnectionStatus, type IntegrationCredentialRule, type IntegrationExecution, type IntegrationFieldSchema, type IntegrationFieldSchemaInput, type IntegrationLoginConfig, type IntegrationModule, type IntegrationProxyMode, type IntegrationRequestConfig, type IntegrationResource, type IntegrationResourceInput, type IntegrationResourceParam, type IntegrationResourceSummary, type IntegrationResourceUpdateInput, type IntegrationResourcesModule, type IntegrationTemplate, type IntegrationTemplateSummary, type IntegrationTemplateType, type IntegrationTemplatesModule, type IntegrationTokenExtraction, type InviteAppUserInput, type InvocationType, type JsonValue, type LegacyPage, type ListTablesOptions, type ListTemplateConfigsOptions, type MembersModule, type MessageAccepted, type MessengerModule, type NewAgentTaskSessionOptions, type OAuthExchangeInput, type OAuthStartResult, type Page, type PageOptions, type PlanPrice, type ProviderCredentialStatus, type ProxyInput, type ProxyResult, type PublicFunctionAsyncResult, type PublicFunctionResult, type PublicFunctionsModule, type QueriesModule, type QueryParamPrimitive, type QueryParamValue, type QueryResult, type SchemaModule, type SchemaScope, type SchemaTables, type SdkCore, SdkCoreConfigurationError, type SdkCoreErrorFactory, type SdkCoreOptions, SdkCoreResponseError, type SdkCoreTransports, type SqlModule, type TableColumn, type TableDefinition, type TableForeignKey, type TemplateConfig, type TemplateConfigBulkItemResult, type TemplateConfigBulkResult, type TemplateConfigCreateInput, type TemplateConfigPage, type TemplateConfigSummary, type TemplateConfigUpdateInput, type Tenant, type TestCredentialsInput, type Transport, type TransportRequestOptions, type User, type UserPlan, type WorkflowDefinition, type WorkflowExecution, type WorkflowInput, type WorkflowSummary, type WorkflowsModule, createAgentConnectionsModule, createAgentCredentialsModule, createAgentTaskSessionManager, createAgentTasksModule, createAgentsModule, createAppsModule, createAuthModule, createContextModule, createCustomQueriesModule, createDataSourcesModule, createEntitiesModule, createFunctionsAdminModule, createFunctionsModule, createImportsModule, createIntegrationAdminModule, createIntegrationModule, createIntegrationResourcesModule, createIntegrationTemplatesModule, createMembersModule, createMessengerModule, createPublicFunctionsModule, createQueriesModule, createSchemaModule, createSdkCore, createSqlModule, createWorkflowsModule, defaultSdkCoreErrorFactory, encodePathSegment, expectEmpty, expectLegacyPage, expectNullableObject, expectObject, expectObjectArray, expectPage, expectStringArray, toAgentTimelineItem, withAgentTaskSessions };
1903
+ export { API_KEY_EXCHANGE_PATH, type AgentBulkDeleteResult, type AgentConnection, type AgentConnectionCreateInput, type AgentConnectionsModule, type AgentCredentialsModule, type AgentDefinition, type AgentInput, type AgentMessage, type AgentModel, type AgentQueueItem, type AgentSendAndWaitOptions, type AgentSendOptions, type AgentSessionTransport, type AgentTask, type AgentTaskCreateInput, type AgentTaskEvent, type AgentTaskEventConnection, type AgentTaskEventObserver, type AgentTaskEventSource, type AgentTaskInput, type AgentTaskListOptions, type AgentTaskSession, type AgentTaskSessionEventMap, type AgentTaskSessionManager, type AgentTaskSessionManagerOptions, type AgentTaskSessionOptions, type AgentTaskSessionStatus, AgentTaskTurnError, type AgentTasksModule, type AgentTasksWithSessions, type AgentTimelineItem, type AgentToolEvent, type AgentTurnResult, type AgentUpdateItem, type AgentsModule, type ApiKeyExchangeCaller, type AppColor, type AppContext, type AppCreateInput, type AppDefinition, type AppDeploy, type AppDomain, type AppFiles, type AppGetOptions, type AppListOptions, type AppMember, type AppPublishOptions, type AppSummary, type AppUpdateInput, type AppVersion, type AppVersionStatus, type AppsModule, type AuthModule, type AuthenticationResult, type BatchExecution, type BatchStatementResult, type BulkUnsubscribeResult, type ColumnInput, type ConnectionConfig, type ConnectionConfigResponse, type ConnectionTestResult, type ContextModule, type ContextModuleDependencies, type CopilotProvider, type CredentialStatus, type CustomQueriesModule, type CustomQueryDefinition, type CustomQueryInput, type CustomQuerySummary, type CustomQueryUpdateInput, type DataSourceBulkItemResult, type DataSourceBulkResult, type DataSourceCreateInput, type DataSourceDbType, type DataSourceDefinition, type DataSourceInstanceType, type DataSourceUpdateInput, type DataSourcesModule, type DdlStatement, type DeviceAuthorization, type DmlStatement, type EmptyFunctionInput, type EntitiesModule, type EntitiesProxy, type EntityListOptions, type EntityListResponse, type EntityTable, type ExistingAgentTaskSessionOptions, type FunctionBulkCreateInput, type FunctionBulkDeleteInput, type FunctionBulkDeleteResult, type FunctionBulkPatchInput, type FunctionBulkPatchItem, type FunctionBulkUpdateItem, type FunctionCreateInput, type FunctionDefinition, type FunctionExecution, type FunctionListOptions, type FunctionPatchInput, type FunctionRuntime, type FunctionSecrets, type FunctionSummary, type FunctionUpdateInput, type FunctionVersion, type FunctionVersionListOptions, type FunctionVisibility, type FunctionsAdminModule, type FunctionsModule, type FunctionsModuleOptions, type HttpMethod, type ImportColumnMapping, type ImportDefinition, type ImportExecution, type ImportExecutionListOptions, type ImportInput, type ImportProcessing, type ImportSchedule, type ImportSource, type ImportSourceResponse, type ImportTarget, type ImportsModule, type IntegrationAdminModule, type IntegrationConnectionStatus, type IntegrationCredentialRule, type IntegrationExecution, type IntegrationFieldSchema, type IntegrationFieldSchemaInput, type IntegrationLoginConfig, type IntegrationModule, type IntegrationProxyMode, type IntegrationRequestConfig, type IntegrationResource, type IntegrationResourceInput, type IntegrationResourceParam, type IntegrationResourceSummary, type IntegrationResourceUpdateInput, type IntegrationResourcesModule, type IntegrationTemplate, type IntegrationTemplateSummary, type IntegrationTemplateType, type IntegrationTemplatesModule, type IntegrationTokenExtraction, type InviteAppUserInput, type InvocationType, type JsonValue, type LegacyPage, type ListTablesOptions, type ListTemplateConfigsOptions, type MembersModule, type MessageAccepted, type MessengerModule, type NewAgentTaskSessionOptions, type OAuthExchangeInput, type OAuthStartResult, type Page, type PageOptions, type PlanPrice, type ProviderCredentialStatus, type ProxyInput, type ProxyResult, type PublicFunctionAsyncResult, type PublicFunctionResult, type PublicFunctionsModule, type QueriesModule, type QueryParamPrimitive, type QueryParamValue, type QueryResult, type SchemaModule, type SchemaScope, type SchemaTables, type SdkCore, SdkCoreConfigurationError, type SdkCoreErrorFactory, type SdkCoreOptions, SdkCoreResponseError, type SdkCoreTransports, type SqlModule, type TableColumn, type TableDefinition, type TableForeignKey, type TemplateConfig, type TemplateConfigBulkItemResult, type TemplateConfigBulkResult, type TemplateConfigCreateInput, type TemplateConfigPage, type TemplateConfigSummary, type TemplateConfigUpdateInput, type Tenant, type TestCredentialsInput, type Transport, type TransportRequestOptions, type User, type UserPlan, type WorkflowDefinition, type WorkflowExecution, type WorkflowInput, type WorkflowSummary, type WorkflowsModule, appAccessTokenPath, createAgentConnectionsModule, createAgentCredentialsModule, createAgentTaskSessionManager, createAgentTasksModule, createAgentsModule, createAppsModule, createAuthModule, createContextModule, createCustomQueriesModule, createDataSourcesModule, createEntitiesModule, createFunctionsAdminModule, createFunctionsModule, createImportsModule, createIntegrationAdminModule, createIntegrationModule, createIntegrationResourcesModule, createIntegrationTemplatesModule, createMembersModule, createMessengerModule, createPublicFunctionsModule, createQueriesModule, createSchemaModule, createSdkCore, createSqlModule, createWorkflowsModule, defaultSdkCoreErrorFactory, encodePathSegment, expectEmpty, expectLegacyPage, expectNullableObject, expectObject, expectObjectArray, expectPage, expectStringArray, isWorkspaceSession, readTokenAppId, readTokenExpiry, resolveApiKeyToken, toAgentTimelineItem, tokenAuthorizesApp, withAgentTaskSessions };
package/dist/index.d.ts CHANGED
@@ -1846,6 +1846,50 @@ declare function toAgentTimelineItem(message: AgentMessage): AgentTimelineItem;
1846
1846
  declare function createAgentTaskSessionManager(options: AgentTaskSessionManagerOptions): AgentTaskSessionManager;
1847
1847
  declare function withAgentTaskSessions(tasks: AgentTasksModule, manager: AgentTaskSessionManager): AgentTasksWithSessions;
1848
1848
 
1849
+ /**
1850
+ * What the SDKs have to know about trading an api key for a token.
1851
+ *
1852
+ * The knowledge lives here rather than in each SDK because it is a contract with IAM, not a
1853
+ * utility: which claim names the app, what the exchange answers, and when a token still needs
1854
+ * a second call before it authorizes anything. When IAM changes any of that, it changes once.
1855
+ *
1856
+ * This module makes no HTTP call of its own — this package defines `Transport`, it does not
1857
+ * implement one. The caller performs the request and keeps whatever belongs to it: caching,
1858
+ * renewal, its own error type, its own runtime guards.
1859
+ */
1860
+ /** IAM path, relative to the service root, that trades an api key for a token. */
1861
+ declare const API_KEY_EXCHANGE_PATH = "/api/v1/auth/exchange";
1862
+ /** IAM path, relative to the service root, that issues an app token from a workspace session. */
1863
+ declare function appAccessTokenPath(appId: string): string;
1864
+ /** Performs one POST against IAM and returns the parsed body. */
1865
+ type ApiKeyExchangeCaller = (path: string, init: {
1866
+ body?: unknown;
1867
+ bearer?: string;
1868
+ }) => Promise<unknown>;
1869
+ /** The app a token authorizes, or `null` for a workspace session and for anything unreadable. */
1870
+ declare function readTokenAppId(token: string): string | null;
1871
+ /** When a token stops being accepted, in milliseconds, or `null` when it cannot be read. */
1872
+ declare function readTokenExpiry(token: string): number | null;
1873
+ /**
1874
+ * Whether a token already authorizes `appId`.
1875
+ *
1876
+ * An unreadable token counts as authorized: the platform is the authority on a token it
1877
+ * issued, and refusing one the SDK merely failed to parse would break a caller for no reason.
1878
+ */
1879
+ declare function tokenAuthorizesApp(token: string, appId: string): boolean;
1880
+ /** Whether a token is a workspace session, the only kind an app token can be issued from. */
1881
+ declare function isWorkspaceSession(token: string): boolean;
1882
+ /**
1883
+ * Trades an api key for a token that authorizes `appId`.
1884
+ *
1885
+ * A Developer or Business key belongs to a product, so the exchange already answers with that
1886
+ * product's token. An Administrator key belongs to a workspace: the exchange answers with a
1887
+ * workspace session, and the app token is issued from it. That second call is where the
1888
+ * platform decides what the key's owner actually reaches in this product, which is why a
1889
+ * workspace key never turns into blanket access.
1890
+ */
1891
+ declare function resolveApiKeyToken(call: ApiKeyExchangeCaller, appId: string, apiKey: string, errors?: SdkCoreErrorFactory): Promise<string>;
1892
+
1849
1893
  declare function encodePathSegment(value: string | number, name: string, errors?: SdkCoreErrorFactory): string;
1850
1894
 
1851
1895
  declare function expectObject<T extends object>(value: unknown, context: string, errors?: SdkCoreErrorFactory): T;
@@ -1856,4 +1900,4 @@ declare function expectPage<T extends object>(value: unknown, context: string, e
1856
1900
  declare function expectLegacyPage<T extends object>(value: unknown, context: string, errors?: SdkCoreErrorFactory, validateItem?: (value: unknown, context: string, errors: SdkCoreErrorFactory) => T): LegacyPage<T>;
1857
1901
  declare function expectEmpty(value: unknown, context: string, errors?: SdkCoreErrorFactory): void;
1858
1902
 
1859
- export { type AgentBulkDeleteResult, type AgentConnection, type AgentConnectionCreateInput, type AgentConnectionsModule, type AgentCredentialsModule, type AgentDefinition, type AgentInput, type AgentMessage, type AgentModel, type AgentQueueItem, type AgentSendAndWaitOptions, type AgentSendOptions, type AgentSessionTransport, type AgentTask, type AgentTaskCreateInput, type AgentTaskEvent, type AgentTaskEventConnection, type AgentTaskEventObserver, type AgentTaskEventSource, type AgentTaskInput, type AgentTaskListOptions, type AgentTaskSession, type AgentTaskSessionEventMap, type AgentTaskSessionManager, type AgentTaskSessionManagerOptions, type AgentTaskSessionOptions, type AgentTaskSessionStatus, AgentTaskTurnError, type AgentTasksModule, type AgentTasksWithSessions, type AgentTimelineItem, type AgentToolEvent, type AgentTurnResult, type AgentUpdateItem, type AgentsModule, type AppColor, type AppContext, type AppCreateInput, type AppDefinition, type AppDeploy, type AppDomain, type AppFiles, type AppGetOptions, type AppListOptions, type AppMember, type AppPublishOptions, type AppSummary, type AppUpdateInput, type AppVersion, type AppVersionStatus, type AppsModule, type AuthModule, type AuthenticationResult, type BatchExecution, type BatchStatementResult, type BulkUnsubscribeResult, type ColumnInput, type ConnectionConfig, type ConnectionConfigResponse, type ConnectionTestResult, type ContextModule, type ContextModuleDependencies, type CopilotProvider, type CredentialStatus, type CustomQueriesModule, type CustomQueryDefinition, type CustomQueryInput, type CustomQuerySummary, type CustomQueryUpdateInput, type DataSourceBulkItemResult, type DataSourceBulkResult, type DataSourceCreateInput, type DataSourceDbType, type DataSourceDefinition, type DataSourceInstanceType, type DataSourceUpdateInput, type DataSourcesModule, type DdlStatement, type DeviceAuthorization, type DmlStatement, type EmptyFunctionInput, type EntitiesModule, type EntitiesProxy, type EntityListOptions, type EntityListResponse, type EntityTable, type ExistingAgentTaskSessionOptions, type FunctionBulkCreateInput, type FunctionBulkDeleteInput, type FunctionBulkDeleteResult, type FunctionBulkPatchInput, type FunctionBulkPatchItem, type FunctionBulkUpdateItem, type FunctionCreateInput, type FunctionDefinition, type FunctionExecution, type FunctionListOptions, type FunctionPatchInput, type FunctionRuntime, type FunctionSecrets, type FunctionSummary, type FunctionUpdateInput, type FunctionVersion, type FunctionVersionListOptions, type FunctionVisibility, type FunctionsAdminModule, type FunctionsModule, type FunctionsModuleOptions, type HttpMethod, type ImportColumnMapping, type ImportDefinition, type ImportExecution, type ImportExecutionListOptions, type ImportInput, type ImportProcessing, type ImportSchedule, type ImportSource, type ImportSourceResponse, type ImportTarget, type ImportsModule, type IntegrationAdminModule, type IntegrationConnectionStatus, type IntegrationCredentialRule, type IntegrationExecution, type IntegrationFieldSchema, type IntegrationFieldSchemaInput, type IntegrationLoginConfig, type IntegrationModule, type IntegrationProxyMode, type IntegrationRequestConfig, type IntegrationResource, type IntegrationResourceInput, type IntegrationResourceParam, type IntegrationResourceSummary, type IntegrationResourceUpdateInput, type IntegrationResourcesModule, type IntegrationTemplate, type IntegrationTemplateSummary, type IntegrationTemplateType, type IntegrationTemplatesModule, type IntegrationTokenExtraction, type InviteAppUserInput, type InvocationType, type JsonValue, type LegacyPage, type ListTablesOptions, type ListTemplateConfigsOptions, type MembersModule, type MessageAccepted, type MessengerModule, type NewAgentTaskSessionOptions, type OAuthExchangeInput, type OAuthStartResult, type Page, type PageOptions, type PlanPrice, type ProviderCredentialStatus, type ProxyInput, type ProxyResult, type PublicFunctionAsyncResult, type PublicFunctionResult, type PublicFunctionsModule, type QueriesModule, type QueryParamPrimitive, type QueryParamValue, type QueryResult, type SchemaModule, type SchemaScope, type SchemaTables, type SdkCore, SdkCoreConfigurationError, type SdkCoreErrorFactory, type SdkCoreOptions, SdkCoreResponseError, type SdkCoreTransports, type SqlModule, type TableColumn, type TableDefinition, type TableForeignKey, type TemplateConfig, type TemplateConfigBulkItemResult, type TemplateConfigBulkResult, type TemplateConfigCreateInput, type TemplateConfigPage, type TemplateConfigSummary, type TemplateConfigUpdateInput, type Tenant, type TestCredentialsInput, type Transport, type TransportRequestOptions, type User, type UserPlan, type WorkflowDefinition, type WorkflowExecution, type WorkflowInput, type WorkflowSummary, type WorkflowsModule, createAgentConnectionsModule, createAgentCredentialsModule, createAgentTaskSessionManager, createAgentTasksModule, createAgentsModule, createAppsModule, createAuthModule, createContextModule, createCustomQueriesModule, createDataSourcesModule, createEntitiesModule, createFunctionsAdminModule, createFunctionsModule, createImportsModule, createIntegrationAdminModule, createIntegrationModule, createIntegrationResourcesModule, createIntegrationTemplatesModule, createMembersModule, createMessengerModule, createPublicFunctionsModule, createQueriesModule, createSchemaModule, createSdkCore, createSqlModule, createWorkflowsModule, defaultSdkCoreErrorFactory, encodePathSegment, expectEmpty, expectLegacyPage, expectNullableObject, expectObject, expectObjectArray, expectPage, expectStringArray, toAgentTimelineItem, withAgentTaskSessions };
1903
+ export { API_KEY_EXCHANGE_PATH, type AgentBulkDeleteResult, type AgentConnection, type AgentConnectionCreateInput, type AgentConnectionsModule, type AgentCredentialsModule, type AgentDefinition, type AgentInput, type AgentMessage, type AgentModel, type AgentQueueItem, type AgentSendAndWaitOptions, type AgentSendOptions, type AgentSessionTransport, type AgentTask, type AgentTaskCreateInput, type AgentTaskEvent, type AgentTaskEventConnection, type AgentTaskEventObserver, type AgentTaskEventSource, type AgentTaskInput, type AgentTaskListOptions, type AgentTaskSession, type AgentTaskSessionEventMap, type AgentTaskSessionManager, type AgentTaskSessionManagerOptions, type AgentTaskSessionOptions, type AgentTaskSessionStatus, AgentTaskTurnError, type AgentTasksModule, type AgentTasksWithSessions, type AgentTimelineItem, type AgentToolEvent, type AgentTurnResult, type AgentUpdateItem, type AgentsModule, type ApiKeyExchangeCaller, type AppColor, type AppContext, type AppCreateInput, type AppDefinition, type AppDeploy, type AppDomain, type AppFiles, type AppGetOptions, type AppListOptions, type AppMember, type AppPublishOptions, type AppSummary, type AppUpdateInput, type AppVersion, type AppVersionStatus, type AppsModule, type AuthModule, type AuthenticationResult, type BatchExecution, type BatchStatementResult, type BulkUnsubscribeResult, type ColumnInput, type ConnectionConfig, type ConnectionConfigResponse, type ConnectionTestResult, type ContextModule, type ContextModuleDependencies, type CopilotProvider, type CredentialStatus, type CustomQueriesModule, type CustomQueryDefinition, type CustomQueryInput, type CustomQuerySummary, type CustomQueryUpdateInput, type DataSourceBulkItemResult, type DataSourceBulkResult, type DataSourceCreateInput, type DataSourceDbType, type DataSourceDefinition, type DataSourceInstanceType, type DataSourceUpdateInput, type DataSourcesModule, type DdlStatement, type DeviceAuthorization, type DmlStatement, type EmptyFunctionInput, type EntitiesModule, type EntitiesProxy, type EntityListOptions, type EntityListResponse, type EntityTable, type ExistingAgentTaskSessionOptions, type FunctionBulkCreateInput, type FunctionBulkDeleteInput, type FunctionBulkDeleteResult, type FunctionBulkPatchInput, type FunctionBulkPatchItem, type FunctionBulkUpdateItem, type FunctionCreateInput, type FunctionDefinition, type FunctionExecution, type FunctionListOptions, type FunctionPatchInput, type FunctionRuntime, type FunctionSecrets, type FunctionSummary, type FunctionUpdateInput, type FunctionVersion, type FunctionVersionListOptions, type FunctionVisibility, type FunctionsAdminModule, type FunctionsModule, type FunctionsModuleOptions, type HttpMethod, type ImportColumnMapping, type ImportDefinition, type ImportExecution, type ImportExecutionListOptions, type ImportInput, type ImportProcessing, type ImportSchedule, type ImportSource, type ImportSourceResponse, type ImportTarget, type ImportsModule, type IntegrationAdminModule, type IntegrationConnectionStatus, type IntegrationCredentialRule, type IntegrationExecution, type IntegrationFieldSchema, type IntegrationFieldSchemaInput, type IntegrationLoginConfig, type IntegrationModule, type IntegrationProxyMode, type IntegrationRequestConfig, type IntegrationResource, type IntegrationResourceInput, type IntegrationResourceParam, type IntegrationResourceSummary, type IntegrationResourceUpdateInput, type IntegrationResourcesModule, type IntegrationTemplate, type IntegrationTemplateSummary, type IntegrationTemplateType, type IntegrationTemplatesModule, type IntegrationTokenExtraction, type InviteAppUserInput, type InvocationType, type JsonValue, type LegacyPage, type ListTablesOptions, type ListTemplateConfigsOptions, type MembersModule, type MessageAccepted, type MessengerModule, type NewAgentTaskSessionOptions, type OAuthExchangeInput, type OAuthStartResult, type Page, type PageOptions, type PlanPrice, type ProviderCredentialStatus, type ProxyInput, type ProxyResult, type PublicFunctionAsyncResult, type PublicFunctionResult, type PublicFunctionsModule, type QueriesModule, type QueryParamPrimitive, type QueryParamValue, type QueryResult, type SchemaModule, type SchemaScope, type SchemaTables, type SdkCore, SdkCoreConfigurationError, type SdkCoreErrorFactory, type SdkCoreOptions, SdkCoreResponseError, type SdkCoreTransports, type SqlModule, type TableColumn, type TableDefinition, type TableForeignKey, type TemplateConfig, type TemplateConfigBulkItemResult, type TemplateConfigBulkResult, type TemplateConfigCreateInput, type TemplateConfigPage, type TemplateConfigSummary, type TemplateConfigUpdateInput, type Tenant, type TestCredentialsInput, type Transport, type TransportRequestOptions, type User, type UserPlan, type WorkflowDefinition, type WorkflowExecution, type WorkflowInput, type WorkflowSummary, type WorkflowsModule, appAccessTokenPath, createAgentConnectionsModule, createAgentCredentialsModule, createAgentTaskSessionManager, createAgentTasksModule, createAgentsModule, createAppsModule, createAuthModule, createContextModule, createCustomQueriesModule, createDataSourcesModule, createEntitiesModule, createFunctionsAdminModule, createFunctionsModule, createImportsModule, createIntegrationAdminModule, createIntegrationModule, createIntegrationResourcesModule, createIntegrationTemplatesModule, createMembersModule, createMessengerModule, createPublicFunctionsModule, createQueriesModule, createSchemaModule, createSdkCore, createSqlModule, createWorkflowsModule, defaultSdkCoreErrorFactory, encodePathSegment, expectEmpty, expectLegacyPage, expectNullableObject, expectObject, expectObjectArray, expectPage, expectStringArray, isWorkspaceSession, readTokenAppId, readTokenExpiry, resolveApiKeyToken, toAgentTimelineItem, tokenAuthorizesApp, withAgentTaskSessions };
package/dist/index.js CHANGED
@@ -3629,10 +3629,79 @@ var CoreAgentTaskSession = class {
3629
3629
  }
3630
3630
  }
3631
3631
  };
3632
+
3633
+ // src/apiKeySession.ts
3634
+ var API_KEY_EXCHANGE_PATH = "/api/v1/auth/exchange";
3635
+ function appAccessTokenPath(appId) {
3636
+ return `/api/v1/auth/apps/${encodeURIComponent(appId)}/access-token`;
3637
+ }
3638
+ function decodeTokenPayload(token) {
3639
+ const segment = token.split(".")[1];
3640
+ if (!segment || typeof globalThis.atob !== "function") return null;
3641
+ try {
3642
+ const base64 = segment.replaceAll("-", "+").replaceAll("_", "/");
3643
+ const padded = base64 + "=".repeat((4 - base64.length % 4) % 4);
3644
+ const decoded = JSON.parse(globalThis.atob(padded));
3645
+ if (!decoded || typeof decoded !== "object" || Array.isArray(decoded)) return null;
3646
+ return decoded;
3647
+ } catch {
3648
+ return null;
3649
+ }
3650
+ }
3651
+ function readTokenAppId(token) {
3652
+ const appId = decodeTokenPayload(token)?.app_id;
3653
+ return typeof appId === "string" && appId ? appId : null;
3654
+ }
3655
+ function readTokenExpiry(token) {
3656
+ const exp = decodeTokenPayload(token)?.exp;
3657
+ return typeof exp === "number" && Number.isFinite(exp) ? exp * 1e3 : null;
3658
+ }
3659
+ function tokenAuthorizesApp(token, appId) {
3660
+ const payload = decodeTokenPayload(token);
3661
+ if (!payload) return true;
3662
+ return payload.app_id === appId;
3663
+ }
3664
+ function isWorkspaceSession(token) {
3665
+ const payload = decodeTokenPayload(token);
3666
+ return payload !== null && payload.app_id === void 0;
3667
+ }
3668
+ function readAccessToken(payload, operation, errors) {
3669
+ const token = payload && typeof payload === "object" ? payload.accessToken : void 0;
3670
+ if (typeof token !== "string" || !token.trim()) {
3671
+ throw errors.invalidResponse(`The ${operation} response did not include an access token`);
3672
+ }
3673
+ return token;
3674
+ }
3675
+ async function resolveApiKeyToken(call, appId, apiKey, errors = defaultSdkCoreErrorFactory) {
3676
+ if (!apiKey.trim()) {
3677
+ throw errors.configuration("An api key is required to authenticate with an api key");
3678
+ }
3679
+ if (!appId.trim()) {
3680
+ throw errors.configuration("An app id is required to authenticate with an api key");
3681
+ }
3682
+ const exchanged = readAccessToken(
3683
+ await call(API_KEY_EXCHANGE_PATH, { body: { apiKey } }),
3684
+ "api key exchange",
3685
+ errors
3686
+ );
3687
+ if (tokenAuthorizesApp(exchanged, appId)) return exchanged;
3688
+ if (!isWorkspaceSession(exchanged)) {
3689
+ throw errors.configuration(
3690
+ `This api key belongs to app ${readTokenAppId(exchanged) ?? "unknown"}, not to ${appId}. Create the key for this app, or use a workspace key.`
3691
+ );
3692
+ }
3693
+ return readAccessToken(
3694
+ await call(appAccessTokenPath(appId), { bearer: exchanged }),
3695
+ "app token",
3696
+ errors
3697
+ );
3698
+ }
3632
3699
  export {
3700
+ API_KEY_EXCHANGE_PATH,
3633
3701
  AgentTaskTurnError,
3634
3702
  SdkCoreConfigurationError,
3635
3703
  SdkCoreResponseError,
3704
+ appAccessTokenPath,
3636
3705
  createAgentConnectionsModule,
3637
3706
  createAgentCredentialsModule,
3638
3707
  createAgentTaskSessionManager,
@@ -3668,6 +3737,11 @@ export {
3668
3737
  expectObjectArray,
3669
3738
  expectPage,
3670
3739
  expectStringArray,
3740
+ isWorkspaceSession,
3741
+ readTokenAppId,
3742
+ readTokenExpiry,
3743
+ resolveApiKeyToken,
3671
3744
  toAgentTimelineItem,
3745
+ tokenAuthorizesApp,
3672
3746
  withAgentTaskSessions
3673
3747
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mitralab.io/sdk-core",
3
- "version": "0.2.0-beta.1",
3
+ "version": "0.2.0-beta.2",
4
4
  "description": "Environment-neutral contracts and modules shared by Mitra JavaScript SDKs",
5
5
  "type": "module",
6
6
  "sideEffects": false,