deepspace 0.30.1 → 0.31.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/CHANGELOG.md +14 -0
- package/dist/{chunk-YEJGFP6X.js → chunk-UWOOAXHQ.js} +2 -2
- package/dist/{chunk-YEJGFP6X.js.map → chunk-UWOOAXHQ.js.map} +1 -1
- package/dist/cli.js +24 -47
- package/dist/cli.js.map +1 -1
- package/dist/documentation-client-core.js +1 -1
- package/dist/documentation-default-renderer.cjs +1 -1
- package/dist/documentation-react.js +1 -1
- package/dist/documentation-runtime.js +1 -1
- package/dist/documentation-server-core.js +1 -1
- package/dist/documentation.js +1 -1
- package/dist/documentation.js.map +1 -1
- package/dist/index.d.ts +26 -12
- package/dist/index.js +6 -1
- package/dist/index.js.map +1 -1
- package/dist/server.d.ts +63 -3
- package/dist/server.js +106 -4
- package/dist/server.js.map +1 -1
- package/dist/worker.d.ts +91 -9
- package/dist/worker.js +156 -8
- package/dist/worker.js.map +1 -1
- package/package.json +1 -1
package/dist/worker.d.ts
CHANGED
|
@@ -2253,6 +2253,10 @@ declare const BUILD_INJECTED_APP_ID_MIGRATION_ID = "2026-08-build-injected-app-i
|
|
|
2253
2253
|
* session has none) instead of crashing on a non-null assertion, and the
|
|
2254
2254
|
* file states the trust model actions run under. */
|
|
2255
2255
|
declare const ACTION_ROUTES_BEARER_GUARD_MIGRATION_ID = "2026-08-action-routes-bearer-guard";
|
|
2256
|
+
/** The files proxy identifies a header-less same-origin read (an `<img>`,
|
|
2257
|
+
* `<audio>`, or `<video>` load) by the app-origin session cookie, so private
|
|
2258
|
+
* file URLs render for the signed-in user without tokens or signed URLs. */
|
|
2259
|
+
declare const FILES_SESSION_COOKIE_READS_MIGRATION_ID = "2026-09-files-session-cookie-reads";
|
|
2256
2260
|
type AppMigrationIdsValidation = {
|
|
2257
2261
|
valid: true;
|
|
2258
2262
|
ids: string[];
|
|
@@ -2846,7 +2850,8 @@ interface StorageAdmission {
|
|
|
2846
2850
|
* POST /api/files/multipart/complete → assemble the parts
|
|
2847
2851
|
* DELETE /api/files/multipart → abandon a chunked upload
|
|
2848
2852
|
* GET /api/files → list (prefix + optional user prefix)
|
|
2849
|
-
* GET /api/files/:key → download (validated against prefix)
|
|
2853
|
+
* GET /api/files/:key → download (validated against prefix; Range-aware)
|
|
2854
|
+
* HEAD /api/files/:key → the download's headers, no body
|
|
2850
2855
|
* DELETE /api/files/:key → delete (validated against prefix)
|
|
2851
2856
|
*
|
|
2852
2857
|
* ## One transport discipline
|
|
@@ -2915,6 +2920,48 @@ declare function isFilesVerbPath(method: string, subpath: string): boolean;
|
|
|
2915
2920
|
*/
|
|
2916
2921
|
declare function createScopedR2Handler(config: ScopedR2Config): ScopedR2Handler;
|
|
2917
2922
|
|
|
2923
|
+
/**
|
|
2924
|
+
* Platform API error normalization — the one chokepoint that turns the
|
|
2925
|
+
* api-worker's error envelope into a render-safe + branch-safe shape.
|
|
2926
|
+
*
|
|
2927
|
+
* The platform emits errors as `{ error: <machine slug>, message?: <human>,
|
|
2928
|
+
* ...details }` (e.g. 402 `{ error: 'insufficient_credits', message:
|
|
2929
|
+
* 'Insufficient credits.', availableCredits, requiredCredits }`; some routes
|
|
2930
|
+
* send the bare slug with no `message` at all, e.g. 409
|
|
2931
|
+
* `{ error: 'owner_connect_not_ready' }`). Consumers must never show the slug
|
|
2932
|
+
* to a person or make an agent parse the sentence — this module separates the
|
|
2933
|
+
* two once, for the integration client, server actions, billing hooks, and the
|
|
2934
|
+
* CLI.
|
|
2935
|
+
*/
|
|
2936
|
+
/** One structured validation issue (Zod shape) from a `validation_failed` response. */
|
|
2937
|
+
interface ApiErrorIssue {
|
|
2938
|
+
path?: string[];
|
|
2939
|
+
message: string;
|
|
2940
|
+
code?: string;
|
|
2941
|
+
}
|
|
2942
|
+
/** A platform error response, normalized. */
|
|
2943
|
+
interface NormalizedApiError {
|
|
2944
|
+
/**
|
|
2945
|
+
* Human-readable text, safe to render:
|
|
2946
|
+
* `message ?? non-slug error ?? humanized(slug) ?? slug`.
|
|
2947
|
+
*/
|
|
2948
|
+
error: string;
|
|
2949
|
+
/** The machine slug (e.g. 'insufficient_credits') for branching — never render it. */
|
|
2950
|
+
code?: string;
|
|
2951
|
+
/** HTTP status of the response; 0 when no HTTP response arrived (transport failure). */
|
|
2952
|
+
status: number;
|
|
2953
|
+
/** Structured fields the server sent alongside the error (e.g. `availableCredits`). */
|
|
2954
|
+
details?: Record<string, unknown>;
|
|
2955
|
+
/** Zod issues accompanying a `validation_failed` response. */
|
|
2956
|
+
issues?: ApiErrorIssue[];
|
|
2957
|
+
}
|
|
2958
|
+
/**
|
|
2959
|
+
* Normalize a platform error body (parsed JSON, or anything else) plus its
|
|
2960
|
+
* HTTP status into a {@link NormalizedApiError}. Pass status 0 for failures
|
|
2961
|
+
* that never produced an HTTP response.
|
|
2962
|
+
*/
|
|
2963
|
+
declare function normalizeApiError(status: number, body: unknown): NormalizedApiError;
|
|
2964
|
+
|
|
2918
2965
|
/**
|
|
2919
2966
|
* Server Action Types
|
|
2920
2967
|
*
|
|
@@ -2939,7 +2986,16 @@ type ActionResult<TData = unknown> = {
|
|
|
2939
2986
|
} | {
|
|
2940
2987
|
success: false;
|
|
2941
2988
|
data?: never;
|
|
2989
|
+
/** Human-readable error, safe to render directly. */
|
|
2942
2990
|
error: string;
|
|
2991
|
+
/** Machine slug for branching, when the failing tool supplied one. */
|
|
2992
|
+
code?: string;
|
|
2993
|
+
/** HTTP status from an upstream platform request, when applicable. */
|
|
2994
|
+
status?: number;
|
|
2995
|
+
/** Structured fields supplied with the error response. */
|
|
2996
|
+
details?: Record<string, unknown>;
|
|
2997
|
+
/** Validation issues supplied with a `validation_failed` response. */
|
|
2998
|
+
issues?: ApiErrorIssue[];
|
|
2943
2999
|
};
|
|
2944
3000
|
/** Shape of the data field for `tools.query`. */
|
|
2945
3001
|
interface QueryActionData<T = Record<string, unknown>> {
|
|
@@ -2994,7 +3050,9 @@ interface ActionTools {
|
|
|
2994
3050
|
* api-worker. On success, `result.data` is the integration's response
|
|
2995
3051
|
* body directly — there is no `.response` wrapper. So an OpenAI call
|
|
2996
3052
|
* yields `result.data.choices`, a Freepik image call yields
|
|
2997
|
-
* `result.data.images`, etc.
|
|
3053
|
+
* `result.data.images`, etc. On failure, `result.error` is human-readable;
|
|
3054
|
+
* branch on `result.code` and inspect `status`, `details`, or `issues` when
|
|
3055
|
+
* present.
|
|
2998
3056
|
*/
|
|
2999
3057
|
integration<T = unknown>(endpoint: string, data?: unknown): Promise<ActionResult<T>>;
|
|
3000
3058
|
/**
|
|
@@ -4045,6 +4103,34 @@ interface VerifyOutcome {
|
|
|
4045
4103
|
*/
|
|
4046
4104
|
declare function verifyJwt(config: JwtVerifierConfig, token: string | null | undefined): Promise<VerifyOutcome>;
|
|
4047
4105
|
|
|
4106
|
+
/**
|
|
4107
|
+
* Session-cookie identity for header-less file reads.
|
|
4108
|
+
*
|
|
4109
|
+
* `<img>`, `<audio>`, `<video>`, and `<a href>` cannot send `Authorization`,
|
|
4110
|
+
* but the browser attaches the app-origin Better Auth session cookie to every
|
|
4111
|
+
* same-origin load. This exchanges that cookie for the same 15-minute JWT the
|
|
4112
|
+
* client already holds and returns only the verified identity.
|
|
4113
|
+
*
|
|
4114
|
+
* Bearer always wins: this applies only when no `Authorization` header is
|
|
4115
|
+
* present, only to GET/HEAD, and only when `Sec-Fetch-Site` is `same-origin`
|
|
4116
|
+
* or `none`. `app.space` is not on the Public Suffix List, so a sibling
|
|
4117
|
+
* `evil.app.space` is same-SITE and `SameSite=Lax` alone would let its
|
|
4118
|
+
* `<img src>` carry the victim's cookie; `Sec-Fetch-Site` cannot be set by
|
|
4119
|
+
* page script. A browser that omits it (Safari before 16.4) and a cross-site
|
|
4120
|
+
* top-level link both get 401 by design.
|
|
4121
|
+
*/
|
|
4122
|
+
|
|
4123
|
+
type SessionReadEnv = AuthWorkerEnv & {
|
|
4124
|
+
AUTH_JWT_PUBLIC_KEY: string;
|
|
4125
|
+
AUTH_JWT_ISSUER: string;
|
|
4126
|
+
};
|
|
4127
|
+
/**
|
|
4128
|
+
* Identify a same-origin GET/HEAD by the app-origin session cookie. Returns
|
|
4129
|
+
* `null` — never throws — whenever the request does not qualify or the
|
|
4130
|
+
* exchange fails. Use it only as the fallback after bearer verification.
|
|
4131
|
+
*/
|
|
4132
|
+
declare function resolveSessionReadAuth(req: Request, env: SessionReadEnv): Promise<VerifyResult | null>;
|
|
4133
|
+
|
|
4048
4134
|
declare const AGENT_TOKEN_SCOPE = "agent";
|
|
4049
4135
|
/** A separate issuer keeps agent credentials invalid at ordinary platform APIs. */
|
|
4050
4136
|
declare function agentTokenIssuer(issuer: string): string;
|
|
@@ -5237,15 +5323,11 @@ declare function registerAgentToolRoutes<Env extends AgentToolRouteEnv>(app: Hon
|
|
|
5237
5323
|
Bindings: Env;
|
|
5238
5324
|
}>, options: AgentToolRouteOptions<Env>): void;
|
|
5239
5325
|
|
|
5240
|
-
/**
|
|
5241
|
-
* First-party non-app origins allowed as agent targets on the production app
|
|
5242
|
-
* domain. The token minter and the CLI must agree on this policy, so both the
|
|
5243
|
-
* set AND the "is production" predicate (appDomain === PRODUCTION_APP_DOMAIN)
|
|
5244
|
-
* live here — callers never re-derive either.
|
|
5245
|
-
*/
|
|
5326
|
+
/** First-party non-app origins retained for callers using the legacy policy shape. */
|
|
5246
5327
|
declare const PRODUCTION_OFFICIAL_AGENT_ORIGINS: readonly string[];
|
|
5247
5328
|
interface AgentTargetPolicy {
|
|
5248
5329
|
appDomain: string;
|
|
5330
|
+
platformDomain?: string;
|
|
5249
5331
|
allowLoopback?: boolean;
|
|
5250
5332
|
}
|
|
5251
5333
|
/** Normalize an agent target only when it is an exact trusted origin. */
|
|
@@ -5400,4 +5482,4 @@ declare const MAX_LOG_TEXT_LENGTH: number;
|
|
|
5400
5482
|
*/
|
|
5401
5483
|
declare function workerErrorHandler(prefix: string, respond?: (c: Context) => Response): ErrorHandler;
|
|
5402
5484
|
|
|
5403
|
-
export { ACCOUNT_STORAGE_LIMIT_BYTES, ACTION_ROUTES_BEARER_GUARD_MIGRATION_ID, ACTION_TOOLS_DELETE_WHERE_MIGRATION_ID, AGENT_TOKEN_SCOPE, AGENT_TOOL_REQUEST_BODY_CAP, AGENT_TOOL_RESPONSE_BODY_CAP, AI_CHATS_SCHEMA, AI_MESSAGES_SCHEMA, ALLOWED_BINDING_TYPES, ANONYMOUS_USER_ID_PREFIX, APP_ID_RE, APP_LOG_EVENT_KEYS, APP_NAME_RULES, ASSET_NOT_FOUND_HANDLING_VALUES, AUTO_PROVISIONABLE_TYPES, AUTO_PROVISION_SENTINEL, type ActionContext, type ActionHandler, type ActionResult, type ActionTools, type AgentTargetPolicy, type AgentToolAccessResult, type AgentToolRouteEnv, type AgentToolRouteOptions, type ApiWorkerEnv, type AppLogEvent, type AppLogEventKey, type AppLogsResponse, type AppMembership, type AppMigrationIdsValidation, type AppNameResolution, type AppNameValidation, type AssetNotFoundHandling, type AuthWorkerEnv, Awareness, type AwarenessState, type AwarenessStates, BASE_USERS_SCHEMA, BROWSER_PROXY_ROUTES, BUILD_INJECTED_APP_ID_MIGRATION_ID, BUILT_IN_TOOLS, type BaseMessage, BaseRoom, type BindingJsonValue, CHANNELS_SCHEMA, CHANNEL_MEMBERS_SCHEMA, COST_RATES, CanvasRoom, type CanvasShape, type ChatContextConfig, type ChatMessageRow, type ChatRow, type ChatTurn, type ClientMessage, type CollectionSchema, type ColumnDefinition, type ColumnInterpretation, type ComposioToolsOptions, type ConnectionAttachment, type CronContext, type CronExecution, CronRoom, type CronRoomConfig, type CronTask, type CustomBinding, type CustomBindingManifest, DEEPSPACE_AGENT_PROFILES, DEEPSPACE_AI_DEFAULTS, DEEPSPACE_AI_MODELS, DEEPSPACE_MODEL_CATALOG_PROVENANCE, DEFAULT_CONTEXT_CONFIG, DEFAULT_DELETE_WHERE_LIMIT, DEFAULT_DO_MANIFEST, DEFAULT_QUERY_LIMIT, DEPLOYED_APPS_DEFAULTS, type DOBindings, type DOManifest, type DOManifestEntry, type DeepSpaceAIEnv, type DeepSpaceAIModel, type DeepSpaceAIModelId, type DeepSpaceAIOptions, type DeepSpaceAIProvider, type DeepSpaceAgentDiagnosticContext, DeepSpaceAgentModelError, type DeepSpaceAgentProfile, DeepSpaceAgentProfileError, type DeepSpaceAgentProfileId, type DeepSpaceAgentStream, type DeepSpaceAgentStreamOptions, type DeepSpaceAgentSupport, type DeepSpaceAuth, type DeepSpaceAuthConfig, type DeepSpaceDocumentationRouteEnv, type DeepSpaceDocumentationRouteOptions, type DoMigrationDirective, type DoMigrationPlan, type ExistingDOBinding, type GetActionData, type HandlerContext, type Job, type JobContext, JobRoom, type JobRoomConfig, type JobStatus, type JwtClaims, type JwtVerifierConfig, type KnowledgeAddOptions, type KnowledgeAddResult, type KnowledgeClient, type KnowledgeEnv, KnowledgeError, type KnowledgeItem, type KnowledgeListOptions, type KnowledgeListResult, type KnowledgeSearchChunk, type KnowledgeSearchOptions, type KnowledgeSearchResult, type KnowledgeStatus, LOG_LEVELS, type LogLevel, MAX_APP_FILE_BYTES, MAX_BINDING_NAME_LENGTH, MAX_DELETE_WHERE_LIMIT, MAX_DEPLOY_ASSET_FILE_BYTES, MAX_ENV_VAR_BYTES, MAX_LOG_TEXT_LENGTH, MAX_UPLOAD_PARTS, MAX_UPLOAD_REQUEST_BYTES, MESSAGES_SCHEMA, MSG, MSG_AWARENESS, MSG_SYNC, MSG_SYNC_STEP1, MSG_SYNC_STEP2, MSG_SYNC_UPDATE, MSG_YJS_AWARENESS, MSG_YJS_SYNC, type MessageHandlers, type MsgType, type MutateActionData, PRODUCTION_OFFICIAL_AGENT_ORIGINS, type PermissionContext, type PermissionLevel, type PlatformWorkerEnv, type PrefixResult, type PresencePeer, PresenceRoom, type ProtocolMessage, type ProxyRoute, type QueryActionData, REACTIONS_SCHEMA, READ_RECEIPTS_SCHEMA, RECORD_NOT_FOUND, REGISTRY_INSTANCE, RELEASE_STAMP_PATH, REPO_STORE_LIMIT_BYTES, REQUIRED_COMPATIBILITY_FLAGS, RESERVED_BINDING_NAMES, RESERVED_RUN_WORKER_FIRST, RESOURCE_ID_RE, ROLE_ADMIN, ROLE_ANONYMOUS, ROLE_DEFAULT, RecordRoom, type RecordRoomConfig, RegistryClientError, type ResolvedColumn, type ResolvedDeepSpaceAgentModel, type RolePermissions, type RunMigrationsResult, SDK_RUN_WORKER_FIRST, SECRET_NAME_RE, SECURE_ROOM_BOUNDARIES_MIGRATION_ID, SESSION_COOKIE, STRICT_APP_ID_RE, SYSTEM_ASSIGNED_COLUMNS, SYSTEM_COLLECTIONS, SYSTEM_MAINTAINED_COLUMNS, SYSTEM_MANAGED_COLUMNS, SchemaRegistry, type ScopeContext, type ScopedKnowledgeClient, type ScopedR2Auth, type ScopedR2Config, type ScopedR2Handler, type ScreenshotEnv, type ScreenshotResult, type ServerMessage, type StorageAdmission, type StoredRecord, type Summarizer, type SyncResult, TEST_ACCOUNT_EMAIL_SUFFIX, type TokenDebugInfo, type ToolResult, type ToolSchema, UNDECLARED_ASSET_NOT_FOUND_HANDLING, UPLOAD_PART_BYTES, USERS_COLUMNS, type User, type UserAttachment, type UserToolExecutorEnv, type ValidationError, type VerifiedAuth, type VerifyOutcome, type VerifyResult, type Viewport, WORKER_OWNED_NOT_FOUND_MIGRATION_ID, YjsRoom, agentTokenIssuer, apiWorkerFetch, appendMessage, applyAiToolDefaults, applySlidingWindow, armCronRoom, authWorkerFetch, authenticatedRoomRequest, bindingManifestFromOutputConfig, buildCronContext, buildTableSelect, buildUiParts, callRegistry, canCreate, canDelete, canRead, canUpdate, capToolResultSize, captureScreenshot, checkFieldPermissions, checkUnclaimedOwnerTransition, clientBuild, coerceValue, collectionTableName, columnId, composioTools, computeDoMigration, computeHmacHex, createChat, createDecoder, createDeepSpaceAI, createDeepSpaceAuth, createEncoder, createScopedR2Handler, createUserToolExecutor, dataToColumnValues, decodeJwtPayload, deepSpaceAgentErrorSummary, deleteChatCascade, dispatch, encode, encodeAwarenessMessage, encodeSyncStep1, encodeSyncStep2, encodeUpdate, enqueueJob, epochSeconds, folderFilter, formatBytes, getChat, getDeepSpaceAIModel, getMessageType, getRolePermissions, handleAwarenessMessage, handleSyncMessage, hasContent, isAnonymousUserId, isAssetNotFoundHandling, isAutoProvision, isFilesVerbPath, isOwner, isPlatformReservedPath, isTestAccountClaims, isTestAccountEmail, isTestAccountTier, knowledge, lintSchema, lintSchemaSet, lintSchemas, listDeepSpaceAgentModels, loadMessages, logEventText, loggableError, makeDefaultSummarizer, matchOrigin, meterAi, meterUsage, meterVectorize, mintAppId, mintUlid, noopPermissionContext, normalizeAgentTargetOrigin, normalizeKnowledgeFolder, parseQuotaLimit, platformCorsPatterns, platformWorkerFetch, prepareMessagesWithCompaction, priceBindingUsageEvent, readVarUint, readVarUint8Array, registerAgentToolRoutes, registerDeepSpaceDocumentation, registryErrorJson, registryStub, resolveAppMembership, resolveAppName, resolveAppRole, resolveColumn, resolveCompatibilityFlags, resolveDeepSpaceAgentModel, rowToData, runMigrations, serverBuild, storageLimitForTier, storageQuotaMessage, streamDeepSpaceAgent, timingSafeEqualHex, timingSafeEqualStrings, toUint8Array, totalChars, truncateLogText, truncateOldToolResults, turnsToCoreMessages, unwrapToolOutput, updateChat, validateAppMigrationIds, validateAppName, validateBindingManifest, validateDoManifest, verifyAgentToken, verifyJwt, workerErrorHandler, writeVarUint, writeVarUint8Array };
|
|
5485
|
+
export { ACCOUNT_STORAGE_LIMIT_BYTES, ACTION_ROUTES_BEARER_GUARD_MIGRATION_ID, ACTION_TOOLS_DELETE_WHERE_MIGRATION_ID, AGENT_TOKEN_SCOPE, AGENT_TOOL_REQUEST_BODY_CAP, AGENT_TOOL_RESPONSE_BODY_CAP, AI_CHATS_SCHEMA, AI_MESSAGES_SCHEMA, ALLOWED_BINDING_TYPES, ANONYMOUS_USER_ID_PREFIX, APP_ID_RE, APP_LOG_EVENT_KEYS, APP_NAME_RULES, ASSET_NOT_FOUND_HANDLING_VALUES, AUTO_PROVISIONABLE_TYPES, AUTO_PROVISION_SENTINEL, type ActionContext, type ActionHandler, type ActionResult, type ActionTools, type AgentTargetPolicy, type AgentToolAccessResult, type AgentToolRouteEnv, type AgentToolRouteOptions, type ApiErrorIssue, type ApiWorkerEnv, type AppLogEvent, type AppLogEventKey, type AppLogsResponse, type AppMembership, type AppMigrationIdsValidation, type AppNameResolution, type AppNameValidation, type AssetNotFoundHandling, type AuthWorkerEnv, Awareness, type AwarenessState, type AwarenessStates, BASE_USERS_SCHEMA, BROWSER_PROXY_ROUTES, BUILD_INJECTED_APP_ID_MIGRATION_ID, BUILT_IN_TOOLS, type BaseMessage, BaseRoom, type BindingJsonValue, CHANNELS_SCHEMA, CHANNEL_MEMBERS_SCHEMA, COST_RATES, CanvasRoom, type CanvasShape, type ChatContextConfig, type ChatMessageRow, type ChatRow, type ChatTurn, type ClientMessage, type CollectionSchema, type ColumnDefinition, type ColumnInterpretation, type ComposioToolsOptions, type ConnectionAttachment, type CronContext, type CronExecution, CronRoom, type CronRoomConfig, type CronTask, type CustomBinding, type CustomBindingManifest, DEEPSPACE_AGENT_PROFILES, DEEPSPACE_AI_DEFAULTS, DEEPSPACE_AI_MODELS, DEEPSPACE_MODEL_CATALOG_PROVENANCE, DEFAULT_CONTEXT_CONFIG, DEFAULT_DELETE_WHERE_LIMIT, DEFAULT_DO_MANIFEST, DEFAULT_QUERY_LIMIT, DEPLOYED_APPS_DEFAULTS, type DOBindings, type DOManifest, type DOManifestEntry, type DeepSpaceAIEnv, type DeepSpaceAIModel, type DeepSpaceAIModelId, type DeepSpaceAIOptions, type DeepSpaceAIProvider, type DeepSpaceAgentDiagnosticContext, DeepSpaceAgentModelError, type DeepSpaceAgentProfile, DeepSpaceAgentProfileError, type DeepSpaceAgentProfileId, type DeepSpaceAgentStream, type DeepSpaceAgentStreamOptions, type DeepSpaceAgentSupport, type DeepSpaceAuth, type DeepSpaceAuthConfig, type DeepSpaceDocumentationRouteEnv, type DeepSpaceDocumentationRouteOptions, type DoMigrationDirective, type DoMigrationPlan, type ExistingDOBinding, FILES_SESSION_COOKIE_READS_MIGRATION_ID, type GetActionData, type HandlerContext, type Job, type JobContext, JobRoom, type JobRoomConfig, type JobStatus, type JwtClaims, type JwtVerifierConfig, type KnowledgeAddOptions, type KnowledgeAddResult, type KnowledgeClient, type KnowledgeEnv, KnowledgeError, type KnowledgeItem, type KnowledgeListOptions, type KnowledgeListResult, type KnowledgeSearchChunk, type KnowledgeSearchOptions, type KnowledgeSearchResult, type KnowledgeStatus, LOG_LEVELS, type LogLevel, MAX_APP_FILE_BYTES, MAX_BINDING_NAME_LENGTH, MAX_DELETE_WHERE_LIMIT, MAX_DEPLOY_ASSET_FILE_BYTES, MAX_ENV_VAR_BYTES, MAX_LOG_TEXT_LENGTH, MAX_UPLOAD_PARTS, MAX_UPLOAD_REQUEST_BYTES, MESSAGES_SCHEMA, MSG, MSG_AWARENESS, MSG_SYNC, MSG_SYNC_STEP1, MSG_SYNC_STEP2, MSG_SYNC_UPDATE, MSG_YJS_AWARENESS, MSG_YJS_SYNC, type MessageHandlers, type MsgType, type MutateActionData, type NormalizedApiError, PRODUCTION_OFFICIAL_AGENT_ORIGINS, type PermissionContext, type PermissionLevel, type PlatformWorkerEnv, type PrefixResult, type PresencePeer, PresenceRoom, type ProtocolMessage, type ProxyRoute, type QueryActionData, REACTIONS_SCHEMA, READ_RECEIPTS_SCHEMA, RECORD_NOT_FOUND, REGISTRY_INSTANCE, RELEASE_STAMP_PATH, REPO_STORE_LIMIT_BYTES, REQUIRED_COMPATIBILITY_FLAGS, RESERVED_BINDING_NAMES, RESERVED_RUN_WORKER_FIRST, RESOURCE_ID_RE, ROLE_ADMIN, ROLE_ANONYMOUS, ROLE_DEFAULT, RecordRoom, type RecordRoomConfig, RegistryClientError, type ResolvedColumn, type ResolvedDeepSpaceAgentModel, type RolePermissions, type RunMigrationsResult, SDK_RUN_WORKER_FIRST, SECRET_NAME_RE, SECURE_ROOM_BOUNDARIES_MIGRATION_ID, SESSION_COOKIE, STRICT_APP_ID_RE, SYSTEM_ASSIGNED_COLUMNS, SYSTEM_COLLECTIONS, SYSTEM_MAINTAINED_COLUMNS, SYSTEM_MANAGED_COLUMNS, SchemaRegistry, type ScopeContext, type ScopedKnowledgeClient, type ScopedR2Auth, type ScopedR2Config, type ScopedR2Handler, type ScreenshotEnv, type ScreenshotResult, type ServerMessage, type StorageAdmission, type StoredRecord, type Summarizer, type SyncResult, TEST_ACCOUNT_EMAIL_SUFFIX, type TokenDebugInfo, type ToolResult, type ToolSchema, UNDECLARED_ASSET_NOT_FOUND_HANDLING, UPLOAD_PART_BYTES, USERS_COLUMNS, type User, type UserAttachment, type UserToolExecutorEnv, type ValidationError, type VerifiedAuth, type VerifyOutcome, type VerifyResult, type Viewport, WORKER_OWNED_NOT_FOUND_MIGRATION_ID, YjsRoom, agentTokenIssuer, apiWorkerFetch, appendMessage, applyAiToolDefaults, applySlidingWindow, armCronRoom, authWorkerFetch, authenticatedRoomRequest, bindingManifestFromOutputConfig, buildCronContext, buildTableSelect, buildUiParts, callRegistry, canCreate, canDelete, canRead, canUpdate, capToolResultSize, captureScreenshot, checkFieldPermissions, checkUnclaimedOwnerTransition, clientBuild, coerceValue, collectionTableName, columnId, composioTools, computeDoMigration, computeHmacHex, createChat, createDecoder, createDeepSpaceAI, createDeepSpaceAuth, createEncoder, createScopedR2Handler, createUserToolExecutor, dataToColumnValues, decodeJwtPayload, deepSpaceAgentErrorSummary, deleteChatCascade, dispatch, encode, encodeAwarenessMessage, encodeSyncStep1, encodeSyncStep2, encodeUpdate, enqueueJob, epochSeconds, folderFilter, formatBytes, getChat, getDeepSpaceAIModel, getMessageType, getRolePermissions, handleAwarenessMessage, handleSyncMessage, hasContent, isAnonymousUserId, isAssetNotFoundHandling, isAutoProvision, isFilesVerbPath, isOwner, isPlatformReservedPath, isTestAccountClaims, isTestAccountEmail, isTestAccountTier, knowledge, lintSchema, lintSchemaSet, lintSchemas, listDeepSpaceAgentModels, loadMessages, logEventText, loggableError, makeDefaultSummarizer, matchOrigin, meterAi, meterUsage, meterVectorize, mintAppId, mintUlid, noopPermissionContext, normalizeAgentTargetOrigin, normalizeApiError, normalizeKnowledgeFolder, parseQuotaLimit, platformCorsPatterns, platformWorkerFetch, prepareMessagesWithCompaction, priceBindingUsageEvent, readVarUint, readVarUint8Array, registerAgentToolRoutes, registerDeepSpaceDocumentation, registryErrorJson, registryStub, resolveAppMembership, resolveAppName, resolveAppRole, resolveColumn, resolveCompatibilityFlags, resolveDeepSpaceAgentModel, resolveSessionReadAuth, rowToData, runMigrations, serverBuild, storageLimitForTier, storageQuotaMessage, streamDeepSpaceAgent, timingSafeEqualHex, timingSafeEqualStrings, toUint8Array, totalChars, truncateLogText, truncateOldToolResults, turnsToCoreMessages, unwrapToolOutput, updateChat, validateAppMigrationIds, validateAppName, validateBindingManifest, validateDoManifest, verifyAgentToken, verifyJwt, workerErrorHandler, writeVarUint, writeVarUint8Array };
|
package/dist/worker.js
CHANGED
|
@@ -5794,6 +5794,7 @@ var SECURE_ROOM_BOUNDARIES_MIGRATION_ID = "2026-08-secure-room-boundaries";
|
|
|
5794
5794
|
var ACTION_TOOLS_DELETE_WHERE_MIGRATION_ID = "2026-08-action-tools-delete-where";
|
|
5795
5795
|
var BUILD_INJECTED_APP_ID_MIGRATION_ID = "2026-08-build-injected-app-id";
|
|
5796
5796
|
var ACTION_ROUTES_BEARER_GUARD_MIGRATION_ID = "2026-08-action-routes-bearer-guard";
|
|
5797
|
+
var FILES_SESSION_COOKIE_READS_MIGRATION_ID = "2026-09-files-session-cookie-reads";
|
|
5797
5798
|
function validateAppMigrationIds(value) {
|
|
5798
5799
|
if (!Array.isArray(value)) {
|
|
5799
5800
|
return { valid: false, reason: "app migrations must be a JSON string array" };
|
|
@@ -6780,7 +6781,7 @@ function createScopedR2Handler(config) {
|
|
|
6780
6781
|
if (!subpath && request2.method === "GET") {
|
|
6781
6782
|
return handleList(bucket, prefix, excludedPrefixes, url, scope, auth);
|
|
6782
6783
|
}
|
|
6783
|
-
if (subpath && request2.method === "GET") {
|
|
6784
|
+
if (subpath && (request2.method === "GET" || request2.method === "HEAD")) {
|
|
6784
6785
|
if (!isKeyWithinScope(subpath, prefix, excludedPrefixes)) {
|
|
6785
6786
|
return Response.json(
|
|
6786
6787
|
{ error: "Access denied: key outside scope" },
|
|
@@ -7387,11 +7388,64 @@ async function handleList(bucket, prefix, excludedPrefixes, url, scope, auth) {
|
|
|
7387
7388
|
{ headers: CORS_HEADERS4 }
|
|
7388
7389
|
);
|
|
7389
7390
|
}
|
|
7391
|
+
function parseByteRange(header, size) {
|
|
7392
|
+
const [, first, last] = /^bytes=(\d*)-(\d*)$/.exec(header.trim()) ?? [];
|
|
7393
|
+
if (first === void 0 || first === "" && last === "") return void 0;
|
|
7394
|
+
const offset = first === "" ? Math.max(0, size - Number(last)) : Number(first);
|
|
7395
|
+
if (offset >= size) return "unsatisfiable";
|
|
7396
|
+
const end = first === "" || last === "" ? size - 1 : Math.min(Number(last), size - 1);
|
|
7397
|
+
return end < offset ? void 0 : { offset, length: end - offset + 1 };
|
|
7398
|
+
}
|
|
7390
7399
|
async function handleDownload(request2, bucket, key, scope) {
|
|
7391
|
-
|
|
7392
|
-
|
|
7400
|
+
if (request2.method === "HEAD") {
|
|
7401
|
+
const object = await bucket.head(key);
|
|
7402
|
+
if (!object) {
|
|
7403
|
+
return Response.json({ error: "File not found" }, { status: 404, headers: CORS_HEADERS4 });
|
|
7404
|
+
}
|
|
7405
|
+
const headers2 = downloadHeaders(object, key, scope);
|
|
7406
|
+
if (scope === "app" && request2.headers.get("if-none-match") === object.httpEtag) {
|
|
7407
|
+
return new Response(null, { status: 304, headers: headers2 });
|
|
7408
|
+
}
|
|
7409
|
+
headers2.set("Content-Length", String(object.size));
|
|
7410
|
+
return new Response(null, { status: 200, headers: headers2 });
|
|
7411
|
+
}
|
|
7412
|
+
const rangeHeader = request2.headers.get("range");
|
|
7413
|
+
if (rangeHeader === null) {
|
|
7414
|
+
return wholeDownload(request2, await bucket.get(key), key, scope);
|
|
7415
|
+
}
|
|
7416
|
+
const head = await bucket.head(key);
|
|
7417
|
+
if (!head) {
|
|
7393
7418
|
return Response.json({ error: "File not found" }, { status: 404, headers: CORS_HEADERS4 });
|
|
7394
7419
|
}
|
|
7420
|
+
if (scope === "app" && request2.headers.get("if-none-match") === head.httpEtag) {
|
|
7421
|
+
return new Response(null, { status: 304, headers: downloadHeaders(head, key, scope) });
|
|
7422
|
+
}
|
|
7423
|
+
const ifRange = request2.headers.get("if-range");
|
|
7424
|
+
if (ifRange !== null && ifRange !== head.httpEtag) {
|
|
7425
|
+
return wholeDownload(request2, await bucket.get(key), key, scope);
|
|
7426
|
+
}
|
|
7427
|
+
const range = parseByteRange(rangeHeader, head.size);
|
|
7428
|
+
if (range === "unsatisfiable") {
|
|
7429
|
+
const headers2 = { ...CORS_HEADERS4, "Content-Range": `bytes */${head.size}` };
|
|
7430
|
+
return new Response(null, { status: 416, headers: headers2 });
|
|
7431
|
+
}
|
|
7432
|
+
if (!range) {
|
|
7433
|
+
return wholeDownload(request2, await bucket.get(key), key, scope);
|
|
7434
|
+
}
|
|
7435
|
+
const conditional = await bucket.get(key, {
|
|
7436
|
+
range,
|
|
7437
|
+
onlyIf: { etagMatches: head.etag }
|
|
7438
|
+
});
|
|
7439
|
+
if (!conditional || !("body" in conditional)) {
|
|
7440
|
+
return wholeDownload(request2, await bucket.get(key), key, scope);
|
|
7441
|
+
}
|
|
7442
|
+
const headers = downloadHeaders(conditional, key, scope);
|
|
7443
|
+
const end = range.offset + range.length - 1;
|
|
7444
|
+
headers.set("Content-Range", `bytes ${range.offset}-${end}/${conditional.size}`);
|
|
7445
|
+
headers.set("Content-Length", String(range.length));
|
|
7446
|
+
return new Response(conditional.body, { status: 206, headers });
|
|
7447
|
+
}
|
|
7448
|
+
function downloadHeaders(object, key, scope) {
|
|
7395
7449
|
const headers = new Headers();
|
|
7396
7450
|
const storedType = resolveMimeType(object.httpMetadata?.contentType ?? "");
|
|
7397
7451
|
const mustDownload = DANGEROUS_MIME_TYPES.has(storedType);
|
|
@@ -7409,10 +7463,19 @@ async function handleDownload(request2, bucket, key, scope) {
|
|
|
7409
7463
|
contentDisposition(originalName, mustDownload ? "attachment" : "inline")
|
|
7410
7464
|
);
|
|
7411
7465
|
if (mustDownload) headers.set("Content-Security-Policy", "sandbox; default-src 'none'");
|
|
7466
|
+
headers.set("Accept-Ranges", "bytes");
|
|
7467
|
+
return headers;
|
|
7468
|
+
}
|
|
7469
|
+
function wholeDownload(request2, object, key, scope) {
|
|
7470
|
+
if (!object) {
|
|
7471
|
+
return Response.json({ error: "File not found" }, { status: 404, headers: CORS_HEADERS4 });
|
|
7472
|
+
}
|
|
7473
|
+
const headers = downloadHeaders(object, key, scope);
|
|
7412
7474
|
if (scope === "app" && request2.headers.get("if-none-match") === object.httpEtag) {
|
|
7413
7475
|
return new Response(null, { status: 304, headers });
|
|
7414
7476
|
}
|
|
7415
|
-
|
|
7477
|
+
headers.set("Content-Length", String(object.size));
|
|
7478
|
+
return new Response(object.body, { status: 200, headers });
|
|
7416
7479
|
}
|
|
7417
7480
|
|
|
7418
7481
|
// src/server/utils/proxies.ts
|
|
@@ -10061,6 +10124,45 @@ async function verifyJwt(config, token) {
|
|
|
10061
10124
|
}
|
|
10062
10125
|
}
|
|
10063
10126
|
|
|
10127
|
+
// src/shared/auth-session.ts
|
|
10128
|
+
var SESSION_COOKIE = "__Secure-better-auth.session_token";
|
|
10129
|
+
|
|
10130
|
+
// src/server/auth/sessionReadAuth.ts
|
|
10131
|
+
var TTL_MS = 5 * 6e4;
|
|
10132
|
+
var sessions = /* @__PURE__ */ new Map();
|
|
10133
|
+
async function exchange(session, env) {
|
|
10134
|
+
try {
|
|
10135
|
+
const res = await authWorkerFetch(env, "/api/auth/token", {
|
|
10136
|
+
method: "POST",
|
|
10137
|
+
headers: { Cookie: `${SESSION_COOKIE}=${session}` },
|
|
10138
|
+
signal: AbortSignal.timeout(1e4)
|
|
10139
|
+
});
|
|
10140
|
+
const { token } = res.ok ? await res.json() : {};
|
|
10141
|
+
if (typeof token !== "string") return null;
|
|
10142
|
+
const config = { publicKey: env.AUTH_JWT_PUBLIC_KEY, issuer: env.AUTH_JWT_ISSUER };
|
|
10143
|
+
return (await verifyJwt(config, token)).result;
|
|
10144
|
+
} catch {
|
|
10145
|
+
return null;
|
|
10146
|
+
}
|
|
10147
|
+
}
|
|
10148
|
+
async function resolveSessionReadAuth(req, env) {
|
|
10149
|
+
const site = req.headers.get("Sec-Fetch-Site");
|
|
10150
|
+
if (req.method !== "GET" && req.method !== "HEAD") return null;
|
|
10151
|
+
if (req.headers.has("Authorization") || site !== "same-origin" && site !== "none") return null;
|
|
10152
|
+
const session = (req.headers.get("Cookie") ?? "").split(";").find((part) => part.trim().startsWith(`${SESSION_COOKIE}=`))?.trim().slice(SESSION_COOKIE.length + 1);
|
|
10153
|
+
if (!session) return null;
|
|
10154
|
+
const now = Date.now();
|
|
10155
|
+
const cached = sessions.get(session);
|
|
10156
|
+
if (cached && cached.expiresAt > now) return cached.promise;
|
|
10157
|
+
if (sessions.size >= 500) sessions.clear();
|
|
10158
|
+
const promise = exchange(session, env).then((result) => {
|
|
10159
|
+
if (!result) sessions.delete(session);
|
|
10160
|
+
return result;
|
|
10161
|
+
});
|
|
10162
|
+
sessions.set(session, { promise, expiresAt: now + TTL_MS });
|
|
10163
|
+
return promise;
|
|
10164
|
+
}
|
|
10165
|
+
|
|
10064
10166
|
// src/server/auth/agentToken.ts
|
|
10065
10167
|
var AGENT_TOKEN_SCOPE = "agent";
|
|
10066
10168
|
function agentTokenIssuer(issuer) {
|
|
@@ -10537,17 +10639,60 @@ function normalizeAgentTargetOrigin(value, policy) {
|
|
|
10537
10639
|
return policy.allowLoopback && ["http:", "https:"].includes(url.protocol) ? url.origin : null;
|
|
10538
10640
|
}
|
|
10539
10641
|
if (url.protocol !== "https:" || url.port) return null;
|
|
10540
|
-
|
|
10642
|
+
const appDomain = policy.appDomain.toLowerCase();
|
|
10643
|
+
const platformDomain = policy.platformDomain?.toLowerCase();
|
|
10644
|
+
const officialAdminOrigin = platformDomain ? `https://admin.${platformDomain}` : appDomain === PRODUCTION_APP_DOMAIN ? PRODUCTION_OFFICIAL_AGENT_ORIGINS[0] : null;
|
|
10645
|
+
if (url.origin === officialAdminOrigin) {
|
|
10541
10646
|
return url.origin;
|
|
10542
10647
|
}
|
|
10543
|
-
const suffix = `.${
|
|
10648
|
+
const suffix = `.${appDomain}`;
|
|
10544
10649
|
if (!hostname.endsWith(suffix)) return null;
|
|
10545
10650
|
const label = hostname.slice(0, -suffix.length);
|
|
10546
10651
|
return !label.includes(".") && validateAppName(label).valid ? url.origin : null;
|
|
10547
10652
|
}
|
|
10548
10653
|
|
|
10549
|
-
// src/shared/
|
|
10550
|
-
var
|
|
10654
|
+
// src/shared/api-error.ts
|
|
10655
|
+
var SLUG_RE = /^[a-z0-9]+(?:[_.-][a-z0-9]+)*$/;
|
|
10656
|
+
var HUMAN_MESSAGES = {
|
|
10657
|
+
owner_connect_not_ready: "This app isn't ready to accept payments yet \u2014 the app owner needs to finish payment setup.",
|
|
10658
|
+
invalid_json: "The request body was not valid JSON.",
|
|
10659
|
+
invalid_body: "The request body is invalid.",
|
|
10660
|
+
invalid_product_id: "Invalid product id.",
|
|
10661
|
+
duplicate_product_id: "Duplicate product id.",
|
|
10662
|
+
unknown_product: "Unknown product.",
|
|
10663
|
+
too_many_products: "Too many products declared.",
|
|
10664
|
+
invalid_amount: "Invalid amount.",
|
|
10665
|
+
invalid_name: "Invalid product name.",
|
|
10666
|
+
invalid_description: "Invalid product description.",
|
|
10667
|
+
unsupported_currency: "Unsupported currency.",
|
|
10668
|
+
unknown_app: "Unknown app.",
|
|
10669
|
+
not_app_owner: "Only the app owner (or a collaborator) can do this.",
|
|
10670
|
+
invalid_return_url: "Invalid return URL.",
|
|
10671
|
+
invalid_cancel_url: "Invalid cancel URL.",
|
|
10672
|
+
unknown_plan: "Unknown subscription plan.",
|
|
10673
|
+
unknown_price: "No price is configured for that billing interval.",
|
|
10674
|
+
no_subscription: "No subscription found for this account."
|
|
10675
|
+
};
|
|
10676
|
+
function normalizeApiError(status, body) {
|
|
10677
|
+
const payload = body !== null && typeof body === "object" ? body : {};
|
|
10678
|
+
const rawError = typeof payload.error === "string" ? payload.error : void 0;
|
|
10679
|
+
const message = typeof payload.message === "string" ? payload.message : void 0;
|
|
10680
|
+
const humanError = rawError !== void 0 && !SLUG_RE.test(rawError) ? rawError : void 0;
|
|
10681
|
+
const code = rawError !== void 0 && SLUG_RE.test(rawError) ? rawError : typeof payload.code === "string" && SLUG_RE.test(payload.code) ? payload.code : void 0;
|
|
10682
|
+
const details = {};
|
|
10683
|
+
for (const [key, value] of Object.entries(payload)) {
|
|
10684
|
+
if (key === "success" || key === "error" || key === "message" || key === "issues" || key === "code")
|
|
10685
|
+
continue;
|
|
10686
|
+
details[key] = value;
|
|
10687
|
+
}
|
|
10688
|
+
return {
|
|
10689
|
+
error: message ?? humanError ?? (code !== void 0 ? HUMAN_MESSAGES[code] : void 0) ?? rawError ?? `Request failed (${status})`,
|
|
10690
|
+
...code !== void 0 ? { code } : {},
|
|
10691
|
+
status,
|
|
10692
|
+
...Object.keys(details).length > 0 ? { details } : {},
|
|
10693
|
+
...Array.isArray(payload.issues) ? { issues: payload.issues } : {}
|
|
10694
|
+
};
|
|
10695
|
+
}
|
|
10551
10696
|
|
|
10552
10697
|
// src/server/worker-error.ts
|
|
10553
10698
|
function workerErrorHandler(prefix, respond = (c) => c.text("Internal Server Error", 500)) {
|
|
@@ -10601,6 +10746,7 @@ export {
|
|
|
10601
10746
|
DEPLOYED_APPS_DEFAULTS,
|
|
10602
10747
|
DeepSpaceAgentModelError,
|
|
10603
10748
|
DeepSpaceAgentProfileError,
|
|
10749
|
+
FILES_SESSION_COOKIE_READS_MIGRATION_ID,
|
|
10604
10750
|
JobRoom,
|
|
10605
10751
|
KnowledgeError,
|
|
10606
10752
|
LOG_LEVELS,
|
|
@@ -10736,6 +10882,7 @@ export {
|
|
|
10736
10882
|
mintUlid,
|
|
10737
10883
|
noopPermissionContext,
|
|
10738
10884
|
normalizeAgentTargetOrigin,
|
|
10885
|
+
normalizeApiError,
|
|
10739
10886
|
normalizeKnowledgeFolder,
|
|
10740
10887
|
parseQuotaLimit,
|
|
10741
10888
|
platformCorsPatterns,
|
|
@@ -10754,6 +10901,7 @@ export {
|
|
|
10754
10901
|
resolveColumn,
|
|
10755
10902
|
resolveCompatibilityFlags,
|
|
10756
10903
|
resolveDeepSpaceAgentModel,
|
|
10904
|
+
resolveSessionReadAuth,
|
|
10757
10905
|
rowToData,
|
|
10758
10906
|
runMigrations,
|
|
10759
10907
|
serverBuild,
|