@datafn/server 0.1.3 → 0.2.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/dist/index.d.cts CHANGED
@@ -5,6 +5,7 @@ import { DatafnSchema, DatafnPlugin as DatafnPlugin$1 } from '@datafn/core/types
5
5
  import { Route, Router } from '@superfunctions/http';
6
6
  import { ConditionalKVStoreAdapter, IndexedDirectoryStoreAdapter, Adapter, AtomicKVStoreAdapter, RuntimeStores, RowLevelNamespaceConfig } from '@superfunctions/db';
7
7
  import { DatafnError } from '@datafn/core/errors';
8
+ import { KeyObject } from 'node:crypto';
8
9
  export { DatafnPlacementConstraint, DatafnPlacementConstraintContext, DatafnPlacementDecision, DatafnPlacementDecisionSource, DatafnPlacementLocation, DatafnPlacementRankingInput, DatafnPlacementRegionCandidate, DatafnPlacementSelectionInput, rankDatafnPlacementRegions, readDatafnCloudflarePlacementLocation, selectDatafnPlacementRegion } from './placement.cjs';
9
10
 
10
11
  /**
@@ -109,6 +110,15 @@ declare function createDatafnHmacRouteTickets(input: {
109
110
  /** At least 32 bytes of cryptographically random key material per key. */
110
111
  keys: Record<string, string | Uint8Array>;
111
112
  }): DatafnRouteTicketSigner & DatafnRouteTicketVerifier;
113
+ /** Gateway-only Ed25519 signer. Keep the private key out of regional deployments. */
114
+ declare function createDatafnEd25519RouteTicketSigner(input: {
115
+ activeKeyId: string;
116
+ privateKey: string | KeyObject;
117
+ }): DatafnRouteTicketSigner;
118
+ /** Region-only Ed25519 verifier. A public key cannot mint route tickets. */
119
+ declare function createDatafnEd25519RouteTicketVerifier(input: {
120
+ publicKeys: Record<string, string | KeyObject>;
121
+ }): DatafnRouteTicketVerifier;
112
122
  interface DatafnRegionalEndpoint {
113
123
  httpUrl: string;
114
124
  wsUrl?: string;
@@ -135,8 +145,8 @@ interface DatafnRegionalTicketRuntime {
135
145
  verifier: DatafnRouteTicketVerifier;
136
146
  issuer: string;
137
147
  audience: string;
138
- /** Validates application credentials separately from the route grant. Also used on WS handshakes. */
139
- authenticate(request: Request): Promise<DatafnRouteIdentity> | DatafnRouteIdentity;
148
+ /** Optional second credential. Omit when a verified ticket is the sole regional bearer credential. */
149
+ authenticate?(request: Request): Promise<DatafnRouteIdentity> | DatafnRouteIdentity;
140
150
  /** Checks ticket/session revocation on each HTTP request and WS admission. False rejects. */
141
151
  isActive?(claims: DatafnRouteTicketClaims): Promise<boolean> | boolean;
142
152
  /** Optional provider-neutral limiter before plugin authorization/execution. */
@@ -148,6 +158,15 @@ interface DatafnRegionalTicketRuntime {
148
158
  }
149
159
  /** The adapter must negotiate only datafn-sync-v1, never echo the ticket subprotocol. */
150
160
  declare function readDatafnRouteTicket(request: Request, websocket?: boolean): string | undefined;
161
+ /** Verify a ticket before using its subject/namespace to build application context.
162
+ * Route scope, placement epoch, revocation, and rate limits are checked again at admission.
163
+ */
164
+ declare function verifyDatafnRegionalTicketIdentity(input: {
165
+ request: Request;
166
+ regionId: string;
167
+ runtime: DatafnRegionalTicketRuntime;
168
+ websocket?: boolean;
169
+ }): Promise<DatafnRouteTicketClaims>;
151
170
  declare function validateDatafnRouteTicket(input: {
152
171
  request: Request;
153
172
  namespace: string;
@@ -268,6 +287,10 @@ declare const DATAFN_ROUTING_INTERNAL_HEADERS: readonly ["x-datafn-routing-asser
268
287
  declare class DatafnRoutingError extends Error {
269
288
  readonly code: "DATAFN_ROUTE_TICKET_INVALID" | "DATAFN_ROUTE_TICKET_EXPIRED" | "DATAFN_ROUTE_TICKET_REVOKED" | "DATAFN_ROUTE_FORBIDDEN" | "DATAFN_ROUTE_RATE_LIMITED" | "DATAFN_PLACEMENT_NOT_FOUND" | "DATAFN_PLACEMENT_UNAVAILABLE" | "DATAFN_REGION_MISMATCH" | "DATAFN_NAMESPACE_MOVING" | "DATAFN_CELL_UNAVAILABLE" | "DATAFN_ROUTING_ASSERTION_INVALID" | "DATAFN_ROUTING_RETRY_EXHAUSTED" | "DATAFN_PAYLOAD_TOO_LARGE";
270
289
  readonly status: number;
290
+ /** HTTP-shaped metadata so framework routers map an uncaught routing error to its status
291
+ * (e.g. a ticket-only context provider rejection) instead of a generic 500. */
292
+ readonly isHttpError = true;
293
+ readonly statusCode: number;
271
294
  readonly retryable: boolean;
272
295
  readonly executionStarted: boolean;
273
296
  readonly placement?: DatafnNamespacePlacement;
@@ -1277,4 +1300,4 @@ declare function recomputeAncestorInactiveAll(adapter: Adapter, schema: DatafnSc
1277
1300
  maxSweeps?: number;
1278
1301
  }): Promise<RecomputeAncestorInactiveAllResult>;
1279
1302
 
1280
- export { type AncestorInactiveCursor, type ApplicationNamespaceStorageEntry, AtomicSequenceStore, ChainedSequenceStore, type CreateDatafnPublicLinkInput, type CrossResourceSearchParams, DATAFN_MULTI_REGION_CAPABILITY, DATAFN_ROUTING_ASSERTION_HEADER, DATAFN_ROUTING_INTERNAL_HEADERS, type DataFnAction, type DataFnAuthorizationDeniedEvent, type DataFnAuthorizationDeniedMetadata, type DataFnEvent, type DataFnEventMap, type DataFnEventType, type DataFnPayloadRejectedEvent, type DataFnPayloadRejectedMetadata, type DataFnRateLimitedEvent, type DataFnRateLimitedMetadata, type DataFnRequestEventMetadata, type DataFnRequestFailedEvent, type DataFnRequestFailedMetadata, type DataFnRetentionPruneFailedEvent, type DataFnRetentionPruneFailedMetadata, type DataFnRetentionPrunedEvent, type DataFnRetentionPrunedMetadata, DatabaseSequenceStore, type DatafnApp, type DatafnAppConfig, type DatafnAppServerConfig, type DatafnComposableRoute, type DatafnExecutor, type DatafnExecutorAction, DatafnExecutorError, type DatafnGatewayCellRegistry, type DatafnGatewayDispatcher, type DatafnGatewayRouter, type DatafnGatewayRouterConfig, type DatafnMultiRegionDirectory, type DatafnMultiRegionPluginConfig, type DatafnMultiRegionRuntimeConfig, type DatafnNamespaceMigrationContext, type DatafnNamespaceMigrationHooks, type DatafnNamespaceMigrationState, type DatafnNamespacePlacement, DatafnNamespaceStorageError, type DatafnNamespaceStorageErrorCode, type DatafnPermissionDirectoryGrant, type DatafnPlacementDirectoryAdapter, type DatafnPlacementRuntimeConfig, type DatafnPlacementState, type DatafnPluginAuthorizationInput, type DatafnPluginAuthorizationResult, type DatafnPluginRoutePlacement, type DatafnPluginRoutePlacementResult, type DatafnPublicLinkAuthorizationInput, type DatafnPublicLinkGrant, DatafnPublicLinkInputError, type DatafnPublicLinkPrincipal, type DatafnPublicLinkRecord, type DatafnPublicLinkShareLevel, type DatafnPublicLinkShareScope, type DatafnPublicLinksPlugin, type DatafnPublicLinksPluginConfig, type DatafnRegionalEndpoint, type DatafnRegionalTicketRuntime, type DatafnRouteBootstrapConfig, type DatafnRouteHeaderEntries, type DatafnRouteHeaderInput, type DatafnRouteHeaders, type DatafnRouteHookInput, type DatafnRouteHooks, type DatafnRouteIdentity, type DatafnRouteResponseHook, type DatafnRouteTicketClaims, type DatafnRouteTicketEvent, type DatafnRouteTicketSigner, type DatafnRouteTicketVerifier, type DatafnRoutingAssertionClaims, type DatafnRoutingAssertionSigner, type DatafnRoutingAssertionVerifier, DatafnRoutingError, type DatafnRoutingEvent, type DatafnRoutingEventType, type DatafnRoutingReplayStore, type DatafnServer, type DatafnServerConfig, type NamespaceStorageCatalog, type NamespaceStorageCatalogRelation, type NamespaceStorageEntry, type NamespaceStoragePlan, POSTGRES_NAMESPACE_STORAGE_CATALOG_SQL, POSTGRES_NAMESPACE_STORAGE_INDEX_SQL, type PostgresNamespaceStorageQuery, type RateLimitConfig, type RecomputeAncestorInactiveAllResult, type RecomputeAncestorInactiveOptions, type RecomputeAncestorInactiveResult, type SearchProvider, type SearchResult, type SearchResultItem, type SequenceStore, type SequenceStorePolicy, type StatusResult, ancestorInactiveResources, assertInternalNamespaceStorageMetadataComplete, claimDatafnNamespacePlacement, composeNamespaceStoragePlan, createConditionalKvDatafnPlacementDirectory, createDatafnGatewayRouter, createDatafnHmacRouteTickets, createDatafnHmacRoutingAssertions, createDatafnMultiRegionPlugin, createDatafnPublicLinksPlugin, createDatafnRouteBootstrap, createDatafnServer, createMemoryDatafnPlacementDirectory, createMemoryDatafnRoutingReplayStore, createSequenceStore, datafn, datafnMultiRegionPlugin, drainNamespacePermissionDirectoryOutbox, drainNamespaceStorage, inspectPostgresNamespaceStorage, migrateDatafnNamespace, namespacedInternalTableRoles, quotePostgresIdentifier, readDatafnPublicLinkToken, readDatafnRouteTicket, recomputeAncestorInactive, recomputeAncestorInactiveAll, resolveDatafnPublicLink, resolveNamespaceStoragePlan, routeTicketError, selectNamespaceStorageEntries, validateDatafnPlacement, validateDatafnRouteTicket, validateDatafnRoutingBodyLimit, withDatafnPublicLinksSchema, withDatafnRegionalCors, withDatafnRoutingAssertion };
1303
+ export { type AncestorInactiveCursor, type ApplicationNamespaceStorageEntry, AtomicSequenceStore, ChainedSequenceStore, type CreateDatafnPublicLinkInput, type CrossResourceSearchParams, DATAFN_MULTI_REGION_CAPABILITY, DATAFN_ROUTING_ASSERTION_HEADER, DATAFN_ROUTING_INTERNAL_HEADERS, type DataFnAction, type DataFnAuthorizationDeniedEvent, type DataFnAuthorizationDeniedMetadata, type DataFnEvent, type DataFnEventMap, type DataFnEventType, type DataFnPayloadRejectedEvent, type DataFnPayloadRejectedMetadata, type DataFnRateLimitedEvent, type DataFnRateLimitedMetadata, type DataFnRequestEventMetadata, type DataFnRequestFailedEvent, type DataFnRequestFailedMetadata, type DataFnRetentionPruneFailedEvent, type DataFnRetentionPruneFailedMetadata, type DataFnRetentionPrunedEvent, type DataFnRetentionPrunedMetadata, DatabaseSequenceStore, type DatafnApp, type DatafnAppConfig, type DatafnAppServerConfig, type DatafnComposableRoute, type DatafnExecutor, type DatafnExecutorAction, DatafnExecutorError, type DatafnGatewayCellRegistry, type DatafnGatewayDispatcher, type DatafnGatewayRouter, type DatafnGatewayRouterConfig, type DatafnMultiRegionDirectory, type DatafnMultiRegionPluginConfig, type DatafnMultiRegionRuntimeConfig, type DatafnNamespaceMigrationContext, type DatafnNamespaceMigrationHooks, type DatafnNamespaceMigrationState, type DatafnNamespacePlacement, DatafnNamespaceStorageError, type DatafnNamespaceStorageErrorCode, type DatafnPermissionDirectoryGrant, type DatafnPlacementDirectoryAdapter, type DatafnPlacementRuntimeConfig, type DatafnPlacementState, type DatafnPluginAuthorizationInput, type DatafnPluginAuthorizationResult, type DatafnPluginRoutePlacement, type DatafnPluginRoutePlacementResult, type DatafnPublicLinkAuthorizationInput, type DatafnPublicLinkGrant, DatafnPublicLinkInputError, type DatafnPublicLinkPrincipal, type DatafnPublicLinkRecord, type DatafnPublicLinkShareLevel, type DatafnPublicLinkShareScope, type DatafnPublicLinksPlugin, type DatafnPublicLinksPluginConfig, type DatafnRegionalEndpoint, type DatafnRegionalTicketRuntime, type DatafnRouteBootstrapConfig, type DatafnRouteHeaderEntries, type DatafnRouteHeaderInput, type DatafnRouteHeaders, type DatafnRouteHookInput, type DatafnRouteHooks, type DatafnRouteIdentity, type DatafnRouteResponseHook, type DatafnRouteTicketClaims, type DatafnRouteTicketEvent, type DatafnRouteTicketSigner, type DatafnRouteTicketVerifier, type DatafnRoutingAssertionClaims, type DatafnRoutingAssertionSigner, type DatafnRoutingAssertionVerifier, DatafnRoutingError, type DatafnRoutingEvent, type DatafnRoutingEventType, type DatafnRoutingReplayStore, type DatafnServer, type DatafnServerConfig, type NamespaceStorageCatalog, type NamespaceStorageCatalogRelation, type NamespaceStorageEntry, type NamespaceStoragePlan, POSTGRES_NAMESPACE_STORAGE_CATALOG_SQL, POSTGRES_NAMESPACE_STORAGE_INDEX_SQL, type PostgresNamespaceStorageQuery, type RateLimitConfig, type RecomputeAncestorInactiveAllResult, type RecomputeAncestorInactiveOptions, type RecomputeAncestorInactiveResult, type SearchProvider, type SearchResult, type SearchResultItem, type SequenceStore, type SequenceStorePolicy, type StatusResult, ancestorInactiveResources, assertInternalNamespaceStorageMetadataComplete, claimDatafnNamespacePlacement, composeNamespaceStoragePlan, createConditionalKvDatafnPlacementDirectory, createDatafnEd25519RouteTicketSigner, createDatafnEd25519RouteTicketVerifier, createDatafnGatewayRouter, createDatafnHmacRouteTickets, createDatafnHmacRoutingAssertions, createDatafnMultiRegionPlugin, createDatafnPublicLinksPlugin, createDatafnRouteBootstrap, createDatafnServer, createMemoryDatafnPlacementDirectory, createMemoryDatafnRoutingReplayStore, createSequenceStore, datafn, datafnMultiRegionPlugin, drainNamespacePermissionDirectoryOutbox, drainNamespaceStorage, inspectPostgresNamespaceStorage, migrateDatafnNamespace, namespacedInternalTableRoles, quotePostgresIdentifier, readDatafnPublicLinkToken, readDatafnRouteTicket, recomputeAncestorInactive, recomputeAncestorInactiveAll, resolveDatafnPublicLink, resolveNamespaceStoragePlan, routeTicketError, selectNamespaceStorageEntries, validateDatafnPlacement, validateDatafnRouteTicket, validateDatafnRoutingBodyLimit, verifyDatafnRegionalTicketIdentity, withDatafnPublicLinksSchema, withDatafnRegionalCors, withDatafnRoutingAssertion };
package/dist/index.d.ts CHANGED
@@ -5,6 +5,7 @@ import { DatafnSchema, DatafnPlugin as DatafnPlugin$1 } from '@datafn/core/types
5
5
  import { Route, Router } from '@superfunctions/http';
6
6
  import { ConditionalKVStoreAdapter, IndexedDirectoryStoreAdapter, Adapter, AtomicKVStoreAdapter, RuntimeStores, RowLevelNamespaceConfig } from '@superfunctions/db';
7
7
  import { DatafnError } from '@datafn/core/errors';
8
+ import { KeyObject } from 'node:crypto';
8
9
  export { DatafnPlacementConstraint, DatafnPlacementConstraintContext, DatafnPlacementDecision, DatafnPlacementDecisionSource, DatafnPlacementLocation, DatafnPlacementRankingInput, DatafnPlacementRegionCandidate, DatafnPlacementSelectionInput, rankDatafnPlacementRegions, readDatafnCloudflarePlacementLocation, selectDatafnPlacementRegion } from './placement.js';
9
10
 
10
11
  /**
@@ -109,6 +110,15 @@ declare function createDatafnHmacRouteTickets(input: {
109
110
  /** At least 32 bytes of cryptographically random key material per key. */
110
111
  keys: Record<string, string | Uint8Array>;
111
112
  }): DatafnRouteTicketSigner & DatafnRouteTicketVerifier;
113
+ /** Gateway-only Ed25519 signer. Keep the private key out of regional deployments. */
114
+ declare function createDatafnEd25519RouteTicketSigner(input: {
115
+ activeKeyId: string;
116
+ privateKey: string | KeyObject;
117
+ }): DatafnRouteTicketSigner;
118
+ /** Region-only Ed25519 verifier. A public key cannot mint route tickets. */
119
+ declare function createDatafnEd25519RouteTicketVerifier(input: {
120
+ publicKeys: Record<string, string | KeyObject>;
121
+ }): DatafnRouteTicketVerifier;
112
122
  interface DatafnRegionalEndpoint {
113
123
  httpUrl: string;
114
124
  wsUrl?: string;
@@ -135,8 +145,8 @@ interface DatafnRegionalTicketRuntime {
135
145
  verifier: DatafnRouteTicketVerifier;
136
146
  issuer: string;
137
147
  audience: string;
138
- /** Validates application credentials separately from the route grant. Also used on WS handshakes. */
139
- authenticate(request: Request): Promise<DatafnRouteIdentity> | DatafnRouteIdentity;
148
+ /** Optional second credential. Omit when a verified ticket is the sole regional bearer credential. */
149
+ authenticate?(request: Request): Promise<DatafnRouteIdentity> | DatafnRouteIdentity;
140
150
  /** Checks ticket/session revocation on each HTTP request and WS admission. False rejects. */
141
151
  isActive?(claims: DatafnRouteTicketClaims): Promise<boolean> | boolean;
142
152
  /** Optional provider-neutral limiter before plugin authorization/execution. */
@@ -148,6 +158,15 @@ interface DatafnRegionalTicketRuntime {
148
158
  }
149
159
  /** The adapter must negotiate only datafn-sync-v1, never echo the ticket subprotocol. */
150
160
  declare function readDatafnRouteTicket(request: Request, websocket?: boolean): string | undefined;
161
+ /** Verify a ticket before using its subject/namespace to build application context.
162
+ * Route scope, placement epoch, revocation, and rate limits are checked again at admission.
163
+ */
164
+ declare function verifyDatafnRegionalTicketIdentity(input: {
165
+ request: Request;
166
+ regionId: string;
167
+ runtime: DatafnRegionalTicketRuntime;
168
+ websocket?: boolean;
169
+ }): Promise<DatafnRouteTicketClaims>;
151
170
  declare function validateDatafnRouteTicket(input: {
152
171
  request: Request;
153
172
  namespace: string;
@@ -268,6 +287,10 @@ declare const DATAFN_ROUTING_INTERNAL_HEADERS: readonly ["x-datafn-routing-asser
268
287
  declare class DatafnRoutingError extends Error {
269
288
  readonly code: "DATAFN_ROUTE_TICKET_INVALID" | "DATAFN_ROUTE_TICKET_EXPIRED" | "DATAFN_ROUTE_TICKET_REVOKED" | "DATAFN_ROUTE_FORBIDDEN" | "DATAFN_ROUTE_RATE_LIMITED" | "DATAFN_PLACEMENT_NOT_FOUND" | "DATAFN_PLACEMENT_UNAVAILABLE" | "DATAFN_REGION_MISMATCH" | "DATAFN_NAMESPACE_MOVING" | "DATAFN_CELL_UNAVAILABLE" | "DATAFN_ROUTING_ASSERTION_INVALID" | "DATAFN_ROUTING_RETRY_EXHAUSTED" | "DATAFN_PAYLOAD_TOO_LARGE";
270
289
  readonly status: number;
290
+ /** HTTP-shaped metadata so framework routers map an uncaught routing error to its status
291
+ * (e.g. a ticket-only context provider rejection) instead of a generic 500. */
292
+ readonly isHttpError = true;
293
+ readonly statusCode: number;
271
294
  readonly retryable: boolean;
272
295
  readonly executionStarted: boolean;
273
296
  readonly placement?: DatafnNamespacePlacement;
@@ -1277,4 +1300,4 @@ declare function recomputeAncestorInactiveAll(adapter: Adapter, schema: DatafnSc
1277
1300
  maxSweeps?: number;
1278
1301
  }): Promise<RecomputeAncestorInactiveAllResult>;
1279
1302
 
1280
- export { type AncestorInactiveCursor, type ApplicationNamespaceStorageEntry, AtomicSequenceStore, ChainedSequenceStore, type CreateDatafnPublicLinkInput, type CrossResourceSearchParams, DATAFN_MULTI_REGION_CAPABILITY, DATAFN_ROUTING_ASSERTION_HEADER, DATAFN_ROUTING_INTERNAL_HEADERS, type DataFnAction, type DataFnAuthorizationDeniedEvent, type DataFnAuthorizationDeniedMetadata, type DataFnEvent, type DataFnEventMap, type DataFnEventType, type DataFnPayloadRejectedEvent, type DataFnPayloadRejectedMetadata, type DataFnRateLimitedEvent, type DataFnRateLimitedMetadata, type DataFnRequestEventMetadata, type DataFnRequestFailedEvent, type DataFnRequestFailedMetadata, type DataFnRetentionPruneFailedEvent, type DataFnRetentionPruneFailedMetadata, type DataFnRetentionPrunedEvent, type DataFnRetentionPrunedMetadata, DatabaseSequenceStore, type DatafnApp, type DatafnAppConfig, type DatafnAppServerConfig, type DatafnComposableRoute, type DatafnExecutor, type DatafnExecutorAction, DatafnExecutorError, type DatafnGatewayCellRegistry, type DatafnGatewayDispatcher, type DatafnGatewayRouter, type DatafnGatewayRouterConfig, type DatafnMultiRegionDirectory, type DatafnMultiRegionPluginConfig, type DatafnMultiRegionRuntimeConfig, type DatafnNamespaceMigrationContext, type DatafnNamespaceMigrationHooks, type DatafnNamespaceMigrationState, type DatafnNamespacePlacement, DatafnNamespaceStorageError, type DatafnNamespaceStorageErrorCode, type DatafnPermissionDirectoryGrant, type DatafnPlacementDirectoryAdapter, type DatafnPlacementRuntimeConfig, type DatafnPlacementState, type DatafnPluginAuthorizationInput, type DatafnPluginAuthorizationResult, type DatafnPluginRoutePlacement, type DatafnPluginRoutePlacementResult, type DatafnPublicLinkAuthorizationInput, type DatafnPublicLinkGrant, DatafnPublicLinkInputError, type DatafnPublicLinkPrincipal, type DatafnPublicLinkRecord, type DatafnPublicLinkShareLevel, type DatafnPublicLinkShareScope, type DatafnPublicLinksPlugin, type DatafnPublicLinksPluginConfig, type DatafnRegionalEndpoint, type DatafnRegionalTicketRuntime, type DatafnRouteBootstrapConfig, type DatafnRouteHeaderEntries, type DatafnRouteHeaderInput, type DatafnRouteHeaders, type DatafnRouteHookInput, type DatafnRouteHooks, type DatafnRouteIdentity, type DatafnRouteResponseHook, type DatafnRouteTicketClaims, type DatafnRouteTicketEvent, type DatafnRouteTicketSigner, type DatafnRouteTicketVerifier, type DatafnRoutingAssertionClaims, type DatafnRoutingAssertionSigner, type DatafnRoutingAssertionVerifier, DatafnRoutingError, type DatafnRoutingEvent, type DatafnRoutingEventType, type DatafnRoutingReplayStore, type DatafnServer, type DatafnServerConfig, type NamespaceStorageCatalog, type NamespaceStorageCatalogRelation, type NamespaceStorageEntry, type NamespaceStoragePlan, POSTGRES_NAMESPACE_STORAGE_CATALOG_SQL, POSTGRES_NAMESPACE_STORAGE_INDEX_SQL, type PostgresNamespaceStorageQuery, type RateLimitConfig, type RecomputeAncestorInactiveAllResult, type RecomputeAncestorInactiveOptions, type RecomputeAncestorInactiveResult, type SearchProvider, type SearchResult, type SearchResultItem, type SequenceStore, type SequenceStorePolicy, type StatusResult, ancestorInactiveResources, assertInternalNamespaceStorageMetadataComplete, claimDatafnNamespacePlacement, composeNamespaceStoragePlan, createConditionalKvDatafnPlacementDirectory, createDatafnGatewayRouter, createDatafnHmacRouteTickets, createDatafnHmacRoutingAssertions, createDatafnMultiRegionPlugin, createDatafnPublicLinksPlugin, createDatafnRouteBootstrap, createDatafnServer, createMemoryDatafnPlacementDirectory, createMemoryDatafnRoutingReplayStore, createSequenceStore, datafn, datafnMultiRegionPlugin, drainNamespacePermissionDirectoryOutbox, drainNamespaceStorage, inspectPostgresNamespaceStorage, migrateDatafnNamespace, namespacedInternalTableRoles, quotePostgresIdentifier, readDatafnPublicLinkToken, readDatafnRouteTicket, recomputeAncestorInactive, recomputeAncestorInactiveAll, resolveDatafnPublicLink, resolveNamespaceStoragePlan, routeTicketError, selectNamespaceStorageEntries, validateDatafnPlacement, validateDatafnRouteTicket, validateDatafnRoutingBodyLimit, withDatafnPublicLinksSchema, withDatafnRegionalCors, withDatafnRoutingAssertion };
1303
+ export { type AncestorInactiveCursor, type ApplicationNamespaceStorageEntry, AtomicSequenceStore, ChainedSequenceStore, type CreateDatafnPublicLinkInput, type CrossResourceSearchParams, DATAFN_MULTI_REGION_CAPABILITY, DATAFN_ROUTING_ASSERTION_HEADER, DATAFN_ROUTING_INTERNAL_HEADERS, type DataFnAction, type DataFnAuthorizationDeniedEvent, type DataFnAuthorizationDeniedMetadata, type DataFnEvent, type DataFnEventMap, type DataFnEventType, type DataFnPayloadRejectedEvent, type DataFnPayloadRejectedMetadata, type DataFnRateLimitedEvent, type DataFnRateLimitedMetadata, type DataFnRequestEventMetadata, type DataFnRequestFailedEvent, type DataFnRequestFailedMetadata, type DataFnRetentionPruneFailedEvent, type DataFnRetentionPruneFailedMetadata, type DataFnRetentionPrunedEvent, type DataFnRetentionPrunedMetadata, DatabaseSequenceStore, type DatafnApp, type DatafnAppConfig, type DatafnAppServerConfig, type DatafnComposableRoute, type DatafnExecutor, type DatafnExecutorAction, DatafnExecutorError, type DatafnGatewayCellRegistry, type DatafnGatewayDispatcher, type DatafnGatewayRouter, type DatafnGatewayRouterConfig, type DatafnMultiRegionDirectory, type DatafnMultiRegionPluginConfig, type DatafnMultiRegionRuntimeConfig, type DatafnNamespaceMigrationContext, type DatafnNamespaceMigrationHooks, type DatafnNamespaceMigrationState, type DatafnNamespacePlacement, DatafnNamespaceStorageError, type DatafnNamespaceStorageErrorCode, type DatafnPermissionDirectoryGrant, type DatafnPlacementDirectoryAdapter, type DatafnPlacementRuntimeConfig, type DatafnPlacementState, type DatafnPluginAuthorizationInput, type DatafnPluginAuthorizationResult, type DatafnPluginRoutePlacement, type DatafnPluginRoutePlacementResult, type DatafnPublicLinkAuthorizationInput, type DatafnPublicLinkGrant, DatafnPublicLinkInputError, type DatafnPublicLinkPrincipal, type DatafnPublicLinkRecord, type DatafnPublicLinkShareLevel, type DatafnPublicLinkShareScope, type DatafnPublicLinksPlugin, type DatafnPublicLinksPluginConfig, type DatafnRegionalEndpoint, type DatafnRegionalTicketRuntime, type DatafnRouteBootstrapConfig, type DatafnRouteHeaderEntries, type DatafnRouteHeaderInput, type DatafnRouteHeaders, type DatafnRouteHookInput, type DatafnRouteHooks, type DatafnRouteIdentity, type DatafnRouteResponseHook, type DatafnRouteTicketClaims, type DatafnRouteTicketEvent, type DatafnRouteTicketSigner, type DatafnRouteTicketVerifier, type DatafnRoutingAssertionClaims, type DatafnRoutingAssertionSigner, type DatafnRoutingAssertionVerifier, DatafnRoutingError, type DatafnRoutingEvent, type DatafnRoutingEventType, type DatafnRoutingReplayStore, type DatafnServer, type DatafnServerConfig, type NamespaceStorageCatalog, type NamespaceStorageCatalogRelation, type NamespaceStorageEntry, type NamespaceStoragePlan, POSTGRES_NAMESPACE_STORAGE_CATALOG_SQL, POSTGRES_NAMESPACE_STORAGE_INDEX_SQL, type PostgresNamespaceStorageQuery, type RateLimitConfig, type RecomputeAncestorInactiveAllResult, type RecomputeAncestorInactiveOptions, type RecomputeAncestorInactiveResult, type SearchProvider, type SearchResult, type SearchResultItem, type SequenceStore, type SequenceStorePolicy, type StatusResult, ancestorInactiveResources, assertInternalNamespaceStorageMetadataComplete, claimDatafnNamespacePlacement, composeNamespaceStoragePlan, createConditionalKvDatafnPlacementDirectory, createDatafnEd25519RouteTicketSigner, createDatafnEd25519RouteTicketVerifier, createDatafnGatewayRouter, createDatafnHmacRouteTickets, createDatafnHmacRoutingAssertions, createDatafnMultiRegionPlugin, createDatafnPublicLinksPlugin, createDatafnRouteBootstrap, createDatafnServer, createMemoryDatafnPlacementDirectory, createMemoryDatafnRoutingReplayStore, createSequenceStore, datafn, datafnMultiRegionPlugin, drainNamespacePermissionDirectoryOutbox, drainNamespaceStorage, inspectPostgresNamespaceStorage, migrateDatafnNamespace, namespacedInternalTableRoles, quotePostgresIdentifier, readDatafnPublicLinkToken, readDatafnRouteTicket, recomputeAncestorInactive, recomputeAncestorInactiveAll, resolveDatafnPublicLink, resolveNamespaceStoragePlan, routeTicketError, selectNamespaceStorageEntries, validateDatafnPlacement, validateDatafnRouteTicket, validateDatafnRoutingBodyLimit, verifyDatafnRegionalTicketIdentity, withDatafnPublicLinksSchema, withDatafnRegionalCors, withDatafnRoutingAssertion };
package/dist/index.js CHANGED
@@ -3,7 +3,7 @@ export { DATAFN_REQUEST_ACTIONS, DATAFN_REQUEST_PROTOCOL_VERSION, DATAFN_REQUEST
3
3
  import { createRouter, createObservabilityMiddleware, executeMiddlewareChain } from '@superfunctions/http';
4
4
  import { wrapWithRowLevelNamespace, instrumentAdapter, instrumentKVStore } from '@superfunctions/db';
5
5
  import { normalizeObservability } from '@superfunctions/observability';
6
- import { timingSafeEqual, randomUUID, createHash, createHmac } from 'crypto';
6
+ import { timingSafeEqual, createPrivateKey, sign, createPublicKey, verify, randomUUID, createHash, createHmac } from 'crypto';
7
7
 
8
8
  // src/index.ts
9
9
 
@@ -6068,6 +6068,61 @@ function createDatafnHmacRouteTickets(input) {
6068
6068
  }
6069
6069
  };
6070
6070
  }
6071
+ var routeKeyId = (value) => /^[A-Za-z0-9_-]{1,128}$/.test(value);
6072
+ var routeSigningInput = (content) => Buffer.from(`datafn-regional-route-v1:${content}`);
6073
+ function createDatafnEd25519RouteTicketSigner(input) {
6074
+ if (!routeKeyId(input.activeKeyId)) throw new Error("DATAFN_ROUTE_KEY_INVALID");
6075
+ let key;
6076
+ try {
6077
+ key = typeof input.privateKey === "string" ? createPrivateKey(input.privateKey) : input.privateKey;
6078
+ } catch {
6079
+ throw new Error("DATAFN_ROUTE_KEY_INVALID");
6080
+ }
6081
+ if (key.type !== "private" || key.asymmetricKeyType !== "ed25519") throw new Error("DATAFN_ROUTE_KEY_INVALID");
6082
+ return {
6083
+ sign(claims) {
6084
+ assertClaims(claims);
6085
+ const header = Buffer.from(JSON.stringify({ typ: "datafn-route-v1", alg: "EdDSA", kid: input.activeKeyId })).toString("base64url");
6086
+ const payload = Buffer.from(JSON.stringify(claims)).toString("base64url");
6087
+ const content = `${header}.${payload}`;
6088
+ return `${content}.${sign(null, routeSigningInput(content), key).toString("base64url")}`;
6089
+ }
6090
+ };
6091
+ }
6092
+ function createDatafnEd25519RouteTicketVerifier(input) {
6093
+ const keys = new Map(Object.entries(input.publicKeys).map(([id, value]) => {
6094
+ if (!routeKeyId(id)) throw new Error("DATAFN_ROUTE_KEY_INVALID");
6095
+ if (typeof value === "string" && !value.startsWith("-----BEGIN PUBLIC KEY-----")) {
6096
+ throw new Error("DATAFN_ROUTE_KEY_INVALID");
6097
+ }
6098
+ let key;
6099
+ try {
6100
+ key = typeof value === "string" ? createPublicKey(value) : value;
6101
+ } catch {
6102
+ throw new Error("DATAFN_ROUTE_KEY_INVALID");
6103
+ }
6104
+ if (key.type !== "public" || key.asymmetricKeyType !== "ed25519") throw new Error("DATAFN_ROUTE_KEY_INVALID");
6105
+ return [id, key];
6106
+ }));
6107
+ if (keys.size === 0) throw new Error("DATAFN_ROUTE_KEY_INVALID");
6108
+ return {
6109
+ verify(ticket) {
6110
+ try {
6111
+ if (typeof ticket !== "string" || ticket.length > 16384 || !/^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/.test(ticket)) throw new Error();
6112
+ const [header, payload, signature] = ticket.split(".");
6113
+ const protectedHeader = JSON.parse(Buffer.from(header, "base64url").toString());
6114
+ const key = keys.get(protectedHeader.kid);
6115
+ if (!key || protectedHeader.typ !== "datafn-route-v1" || protectedHeader.alg !== "EdDSA") throw new Error();
6116
+ if (!verify(null, routeSigningInput(`${header}.${payload}`), key, Buffer.from(signature, "base64url"))) throw new Error();
6117
+ const claims = JSON.parse(Buffer.from(payload, "base64url").toString());
6118
+ assertClaims(claims);
6119
+ return claims;
6120
+ } catch {
6121
+ throw routeTicketError("DATAFN_ROUTE_TICKET_INVALID");
6122
+ }
6123
+ }
6124
+ };
6125
+ }
6071
6126
  function createDatafnRouteBootstrap(config) {
6072
6127
  const ttl = config.ttlMs ?? 6e4;
6073
6128
  if (!text(config.issuer) || !Number.isSafeInteger(ttl) || ttl < 1e3 || ttl > DATAFN_ROUTE_MAX_TTL_MS) {
@@ -6137,12 +6192,13 @@ function readDatafnRouteTicket(request, websocket = false) {
6137
6192
  if (tickets.length > 1 || header && tickets.length || !websocket && tickets.length || tickets.length && !protocols.includes(DATAFN_ROUTE_WS_PROTOCOL)) throw routeTicketError("DATAFN_ROUTE_TICKET_INVALID");
6138
6193
  return header ?? tickets[0]?.slice(DATAFN_ROUTE_WS_TICKET_PREFIX.length);
6139
6194
  }
6140
- async function validateDatafnRouteTicket(input) {
6141
- const { runtime } = input;
6195
+ async function verifyDatafnRegionalTicketIdentity(input) {
6196
+ const { request, regionId, runtime } = input;
6142
6197
  try {
6143
- const origin = input.request.headers.get("origin");
6198
+ const origin = request.headers.get("origin");
6144
6199
  if (origin && !runtime.allowedOrigins?.includes(origin)) throw routeTicketError("DATAFN_ROUTE_FORBIDDEN");
6145
- const token = readDatafnRouteTicket(input.request, input.scope === "websocket");
6200
+ if (!runtime.authenticate && request.headers.has("cookie")) throw routeTicketError("DATAFN_ROUTE_FORBIDDEN");
6201
+ const token = readDatafnRouteTicket(request, input.websocket);
6146
6202
  if (!token) throw routeTicketError("DATAFN_ROUTE_TICKET_INVALID");
6147
6203
  const claims = await runtime.verifier.verify(token);
6148
6204
  assertClaims(claims);
@@ -6150,16 +6206,38 @@ async function validateDatafnRouteTicket(input) {
6150
6206
  const skew = runtime.clockSkewMs ?? 5e3;
6151
6207
  if (!Number.isFinite(skew) || skew < 0 || skew > 3e4) throw routeTicketError("DATAFN_ROUTE_TICKET_INVALID");
6152
6208
  if (claims.expiresAt <= now) throw routeTicketError("DATAFN_ROUTE_TICKET_EXPIRED");
6153
- if (claims.issuedAt > now + skew || claims.notBefore > now + skew || claims.issuer !== runtime.issuer || claims.audience !== runtime.audience || claims.regionId !== input.regionId || claims.namespace !== input.namespace || !claims.scopes.includes(input.scope)) throw routeTicketError("DATAFN_ROUTE_TICKET_INVALID");
6154
- const identity = await runtime.authenticate(input.request);
6155
- if (!identity || identity.subject !== claims.subject || identity.namespace !== claims.namespace || identity.sessionBinding !== claims.sessionBinding || identity.expiresAt !== void 0 && (!Number.isFinite(identity.expiresAt) || identity.expiresAt <= (runtime.now ?? Date.now)())) {
6156
- throw routeTicketError("DATAFN_ROUTE_FORBIDDEN");
6209
+ if (claims.issuedAt > now + skew || claims.notBefore > now + skew || claims.issuer !== runtime.issuer || claims.audience !== runtime.audience || claims.regionId !== regionId) throw routeTicketError("DATAFN_ROUTE_TICKET_INVALID");
6210
+ return claims;
6211
+ } catch (error) {
6212
+ const safe = error instanceof DatafnRoutingError ? error : routeTicketError("DATAFN_ROUTE_TICKET_INVALID");
6213
+ emit(runtime, { type: "rejected", code: safe.code });
6214
+ throw safe;
6215
+ }
6216
+ }
6217
+ async function validateDatafnRouteTicket(input) {
6218
+ const { runtime } = input;
6219
+ const claims = await verifyDatafnRegionalTicketIdentity({
6220
+ request: input.request,
6221
+ regionId: input.regionId,
6222
+ runtime,
6223
+ websocket: input.scope === "websocket"
6224
+ });
6225
+ try {
6226
+ if (claims.namespace !== input.namespace || !claims.scopes.includes(input.scope)) {
6227
+ throw routeTicketError("DATAFN_ROUTE_TICKET_INVALID");
6228
+ }
6229
+ let identity;
6230
+ if (runtime.authenticate) {
6231
+ identity = await runtime.authenticate(input.request);
6232
+ if (!identity || identity.subject !== claims.subject || identity.namespace !== claims.namespace || identity.sessionBinding !== claims.sessionBinding || identity.expiresAt !== void 0 && (!Number.isFinite(identity.expiresAt) || identity.expiresAt <= (runtime.now ?? Date.now)())) {
6233
+ throw routeTicketError("DATAFN_ROUTE_FORBIDDEN");
6234
+ }
6235
+ if (identity.expiresAt !== void 0 && claims.expiresAt > identity.expiresAt) throw routeTicketError("DATAFN_ROUTE_TICKET_EXPIRED");
6157
6236
  }
6158
- if (identity.expiresAt !== void 0 && claims.expiresAt > identity.expiresAt) throw routeTicketError("DATAFN_ROUTE_TICKET_EXPIRED");
6159
6237
  if (runtime.isActive && !await runtime.isActive(claims)) throw routeTicketError("DATAFN_ROUTE_TICKET_REVOKED");
6160
6238
  if (runtime.allowRequest && !await runtime.allowRequest(claims)) throw routeTicketError("DATAFN_ROUTE_RATE_LIMITED");
6161
6239
  const admittedAt = (runtime.now ?? Date.now)();
6162
- if (identity.expiresAt !== void 0 && identity.expiresAt <= admittedAt) throw routeTicketError("DATAFN_ROUTE_FORBIDDEN");
6240
+ if (identity?.expiresAt !== void 0 && identity.expiresAt <= admittedAt) throw routeTicketError("DATAFN_ROUTE_FORBIDDEN");
6163
6241
  if (claims.expiresAt <= admittedAt) throw routeTicketError("DATAFN_ROUTE_TICKET_EXPIRED");
6164
6242
  emit(runtime, { type: "accepted" });
6165
6243
  return claims;
@@ -6184,6 +6262,7 @@ function withDatafnRegionalCors(handler, options) {
6184
6262
  return async (request) => {
6185
6263
  const origin = request.headers.get("origin");
6186
6264
  if (origin && !origins.has(origin)) return routeTicketError("DATAFN_ROUTE_FORBIDDEN").toResponse();
6265
+ if (request.headers.has("cookie")) return routeTicketError("DATAFN_ROUTE_FORBIDDEN").toResponse();
6187
6266
  if (request.method === "OPTIONS") {
6188
6267
  const method = request.headers.get("access-control-request-method");
6189
6268
  const headers2 = (request.headers.get("access-control-request-headers") ?? "").split(",").map((s) => s.trim().toLowerCase()).filter(Boolean);
@@ -6225,9 +6304,13 @@ var DEFAULT_MIGRATION_RECOVERY_LEASE_MS = 3e4;
6225
6304
  var DatafnRoutingError = class extends Error {
6226
6305
  constructor(input) {
6227
6306
  super(input.message);
6307
+ /** HTTP-shaped metadata so framework routers map an uncaught routing error to its status
6308
+ * (e.g. a ticket-only context provider rejection) instead of a generic 500. */
6309
+ this.isHttpError = true;
6228
6310
  this.name = "DatafnRoutingError";
6229
6311
  this.code = input.code;
6230
6312
  this.status = input.status;
6313
+ this.statusCode = input.status;
6231
6314
  this.retryable = input.retryable;
6232
6315
  this.executionStarted = input.executionStarted ?? false;
6233
6316
  this.placement = input.placement;
@@ -21504,6 +21587,6 @@ async function recomputeAncestorInactiveAll(adapter, schema, options) {
21504
21587
  return { scanned, updated, skipped, sweeps, converged };
21505
21588
  }
21506
21589
 
21507
- export { AtomicSequenceStore, ChainedSequenceStore, DATAFN_MULTI_REGION_CAPABILITY, DATAFN_ROUTING_ASSERTION_HEADER, DATAFN_ROUTING_INTERNAL_HEADERS, DatabaseSequenceStore, DatafnExecutorError, DatafnNamespaceStorageError, DatafnPublicLinkInputError, DatafnRoutingError, POSTGRES_NAMESPACE_STORAGE_CATALOG_SQL, POSTGRES_NAMESPACE_STORAGE_INDEX_SQL, ancestorInactiveResources, assertInternalNamespaceStorageMetadataComplete, claimDatafnNamespacePlacement, composeNamespaceStoragePlan, createConditionalKvDatafnPlacementDirectory, createDatafnGatewayRouter, createDatafnHmacRouteTickets, createDatafnHmacRoutingAssertions, createDatafnMultiRegionPlugin, createDatafnPublicLinksPlugin, createDatafnRouteBootstrap, createDatafnServer, createMemoryDatafnPlacementDirectory, createMemoryDatafnRoutingReplayStore, createSequenceStore, datafn, datafnMultiRegionPlugin, drainNamespacePermissionDirectoryOutbox, drainNamespaceStorage, inspectPostgresNamespaceStorage, migrateDatafnNamespace, namespacedInternalTableRoles, quotePostgresIdentifier, rankDatafnPlacementRegions, readDatafnCloudflarePlacementLocation, readDatafnPublicLinkToken, readDatafnRouteTicket, recomputeAncestorInactive, recomputeAncestorInactiveAll, resolveDatafnPublicLink, resolveNamespaceStoragePlan, routeTicketError, selectDatafnPlacementRegion, selectNamespaceStorageEntries, validateDatafnPlacement, validateDatafnRouteTicket, validateDatafnRoutingBodyLimit, withDatafnPublicLinksSchema, withDatafnRegionalCors, withDatafnRoutingAssertion };
21590
+ export { AtomicSequenceStore, ChainedSequenceStore, DATAFN_MULTI_REGION_CAPABILITY, DATAFN_ROUTING_ASSERTION_HEADER, DATAFN_ROUTING_INTERNAL_HEADERS, DatabaseSequenceStore, DatafnExecutorError, DatafnNamespaceStorageError, DatafnPublicLinkInputError, DatafnRoutingError, POSTGRES_NAMESPACE_STORAGE_CATALOG_SQL, POSTGRES_NAMESPACE_STORAGE_INDEX_SQL, ancestorInactiveResources, assertInternalNamespaceStorageMetadataComplete, claimDatafnNamespacePlacement, composeNamespaceStoragePlan, createConditionalKvDatafnPlacementDirectory, createDatafnEd25519RouteTicketSigner, createDatafnEd25519RouteTicketVerifier, createDatafnGatewayRouter, createDatafnHmacRouteTickets, createDatafnHmacRoutingAssertions, createDatafnMultiRegionPlugin, createDatafnPublicLinksPlugin, createDatafnRouteBootstrap, createDatafnServer, createMemoryDatafnPlacementDirectory, createMemoryDatafnRoutingReplayStore, createSequenceStore, datafn, datafnMultiRegionPlugin, drainNamespacePermissionDirectoryOutbox, drainNamespaceStorage, inspectPostgresNamespaceStorage, migrateDatafnNamespace, namespacedInternalTableRoles, quotePostgresIdentifier, rankDatafnPlacementRegions, readDatafnCloudflarePlacementLocation, readDatafnPublicLinkToken, readDatafnRouteTicket, recomputeAncestorInactive, recomputeAncestorInactiveAll, resolveDatafnPublicLink, resolveNamespaceStoragePlan, routeTicketError, selectDatafnPlacementRegion, selectNamespaceStorageEntries, validateDatafnPlacement, validateDatafnRouteTicket, validateDatafnRoutingBodyLimit, verifyDatafnRegionalTicketIdentity, withDatafnPublicLinksSchema, withDatafnRegionalCors, withDatafnRoutingAssertion };
21508
21591
  //# sourceMappingURL=index.js.map
21509
21592
  //# sourceMappingURL=index.js.map