@getstrata/core 3.0.4 → 3.0.7

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.
Files changed (103) hide show
  1. package/CHANGELOG.md +28 -0
  2. package/README.md +17 -9
  3. package/dist/core/auth/policy.d.ts +4 -1
  4. package/dist/core/auth/saml/samlServiceProvider.d.ts +2 -3
  5. package/dist/core/cache/createCacheStore.d.ts +1 -1
  6. package/dist/core/cache/expiration.d.ts +2 -0
  7. package/dist/core/cache/redisCacheScript.d.ts +1 -1
  8. package/dist/core/cache/redisCacheStore.d.ts +5 -5
  9. package/dist/core/cache/repository.d.ts +2 -0
  10. package/dist/core/cache/simpleCache.d.ts +5 -5
  11. package/dist/core/cache/simpleCacheStore.d.ts +3 -3
  12. package/dist/core/cache/store.d.ts +5 -4
  13. package/dist/core/cache/taggedCache.d.ts +2 -0
  14. package/dist/core/cache/tokens.d.ts +1 -1
  15. package/dist/core/config/envSchema.d.ts +13 -0
  16. package/dist/core/contracts/application.d.ts +4 -0
  17. package/dist/core/contracts/di.d.ts +2 -2
  18. package/dist/core/contracts/provider.d.ts +13 -0
  19. package/dist/core/contracts/serviceTokens.d.ts +12 -11
  20. package/dist/core/database/factory.d.ts +3 -0
  21. package/dist/core/database/index.d.ts +1 -1
  22. package/dist/core/database/migrations/declaration.d.ts +11 -0
  23. package/dist/core/database/migrations/runner.d.ts +2 -0
  24. package/dist/core/database/model.d.ts +16 -3
  25. package/dist/core/database/modelQuery.d.ts +1 -10
  26. package/dist/core/database/modelRelationLoader.d.ts +31 -0
  27. package/dist/core/database/mysqlConnection.d.ts +2 -2
  28. package/dist/core/database/mysqlNative.d.ts +2 -0
  29. package/dist/core/database/ormRuntime.d.ts +1 -1
  30. package/dist/core/database/rawMysql.d.ts +1 -1
  31. package/dist/core/events/eventBusClass.d.ts +6 -3
  32. package/dist/core/events/index.d.ts +1 -1
  33. package/dist/core/http/formRequest.d.ts +2 -0
  34. package/dist/core/http/loginThrottleMiddleware.d.ts +1 -2
  35. package/dist/core/http/memoryThrottleMiddleware.d.ts +1 -3
  36. package/dist/core/http/webFormRequest.d.ts +3 -5
  37. package/dist/core/mail/mailer.d.ts +6 -3
  38. package/dist/core/mail/markdownMailable.d.ts +2 -2
  39. package/dist/core/notifications/dispatcher.d.ts +5 -5
  40. package/dist/core/notifications/index.d.ts +1 -1
  41. package/dist/core/notifications/types.d.ts +9 -2
  42. package/dist/core/queue/index.d.ts +8 -3
  43. package/dist/core/queue/queueHandoff.d.ts +2 -2
  44. package/dist/core/runtime/application.d.ts +2 -0
  45. package/dist/core/security/oauthState.d.ts +12 -2
  46. package/dist/core/security/safeUrl.d.ts +1 -11
  47. package/dist/core/storage/storage.d.ts +23 -6
  48. package/dist/core/testing.d.ts +5 -0
  49. package/dist/core/testingState.d.ts +22 -0
  50. package/dist/entries/audit/exportAuditLogs.js +1 -0
  51. package/dist/entries/auth/intendedUrlCookie.js +106 -18
  52. package/dist/entries/auth/jwt.js +68 -6
  53. package/dist/entries/auth/jwtGuard.js +76 -12
  54. package/dist/entries/auth/oauth/samlProvider.js +4 -5
  55. package/dist/entries/auth/passwordConfirmCookie.js +69 -3
  56. package/dist/entries/auth/saml/samlServiceProvider.js +5 -7
  57. package/dist/entries/auth/sessionCookie.js +69 -6
  58. package/dist/entries/auth/sessionGuard.js +69 -6
  59. package/dist/entries/cache/createCacheStore.js +45 -23
  60. package/dist/entries/cache/repository.js +20 -5
  61. package/dist/entries/cache/simpleCache.js +21 -7
  62. package/dist/entries/cache/simpleCacheStore.js +2 -3
  63. package/dist/entries/config/envSchema.js +13 -0
  64. package/dist/entries/contracts/serviceTokens.js +2 -0
  65. package/dist/entries/database/bindings.js +19 -95
  66. package/dist/entries/database/factory.js +4 -0
  67. package/dist/entries/database/migrations.js +714 -1
  68. package/dist/entries/database/ownedReadOnlyObservation.js +1 -5
  69. package/dist/entries/database/sqliteConnection.js +1 -5
  70. package/dist/entries/http/flashMiddleware.js +33 -14
  71. package/dist/entries/http/flashSession.js +33 -14
  72. package/dist/entries/http/formRequest.js +12 -6
  73. package/dist/entries/http/memoryThrottleMiddleware.js +12 -11
  74. package/dist/entries/http/pagination.js +4 -4
  75. package/dist/entries/http/parseMultipartUpload.js +62 -9
  76. package/dist/entries/http/requirePasswordConfirmMiddleware.js +5 -2
  77. package/dist/entries/http/requireWebAuthMiddleware.js +5 -2
  78. package/dist/entries/http/routeModelBinding.js +4 -4
  79. package/dist/entries/http/safeInternalPath.js +5 -2
  80. package/dist/entries/http/scimThrottleMiddleware.js +5 -2
  81. package/dist/entries/http/securedRouteModelBinding.js +4 -4
  82. package/dist/entries/http/throttleMiddleware.js +5 -2
  83. package/dist/entries/http/uploads.js +62 -9
  84. package/dist/entries/http/validation.js +4 -4
  85. package/dist/entries/http/webFormRequest.js +74 -95
  86. package/dist/entries/jobs/exportAuditLogsJob.js +9 -4
  87. package/dist/entries/jobs/invalidateCacheTagsJob.js +9 -4
  88. package/dist/entries/queue/createAppQueue.js +10 -5
  89. package/dist/entries/queue/publicQueue.js +10 -5
  90. package/dist/entries/queue/queueWorkerTransport.js +10 -5
  91. package/dist/entries/queue.js +9 -4
  92. package/dist/entries/runtime/application.js +50 -3
  93. package/dist/entries/security/oauthState.js +61 -2
  94. package/dist/entries/security/tokenExpiry.js +62 -9
  95. package/dist/entries/storage/storage.js +102 -1
  96. package/dist/entries/testing.js +18 -0
  97. package/dist/framework/public-api.d.ts +16 -13
  98. package/dist/index.js +380 -266
  99. package/dist/internal/mysqlNative.js +97 -0
  100. package/dist/internal/ormRuntime.js +41 -4
  101. package/dist/internal/testingState.js +31 -0
  102. package/dist/types/services.d.ts +8 -1
  103. package/package.json +17 -4
@@ -1,6 +1,9 @@
1
1
  type EventListener = (payload: unknown) => void | Promise<void>;
2
- declare class EventBus {
3
- constructor();
2
+ /** Capability for publishing application events; listener ownership stays with composition. */
3
+ interface EventDispatcher {
4
+ dispatch(event: string, payload: unknown): Promise<void>;
5
+ }
6
+ declare class EventBus implements EventDispatcher {
4
7
  private readonly transactionalListeners;
5
8
  listenTransactional(event: string, listener: EventListener): () => void;
6
9
  hasTransactionalListeners(event: string): boolean;
@@ -11,5 +14,5 @@ declare class EventBus {
11
14
  emit(event: string, payload: unknown): Promise<void>;
12
15
  dispatch(event: string, payload: unknown): Promise<void>;
13
16
  }
14
- export type { EventListener };
17
+ export type { EventDispatcher, EventListener };
15
18
  export { EventBus };
@@ -1,4 +1,4 @@
1
- export type { EventListener } from "./eventBusClass";
1
+ export type { EventDispatcher, EventListener } from "./eventBusClass";
2
2
  export { EventBus } from "./eventBusClass";
3
3
  declare function modelEventName(tableName: string, action: string): string;
4
4
  export { modelEventName };
@@ -1,6 +1,8 @@
1
1
  declare abstract class FormRequest<TOutput> {
2
2
  authorize(_request: Request): boolean | Promise<boolean>;
3
3
  protected abstract parse(payload: unknown): TOutput;
4
+ validatePayload(payload: unknown): TOutput;
5
+ protected readPayload(request: Request): Promise<unknown>;
4
6
  validate(request: Request): Promise<TOutput>;
5
7
  }
6
8
  declare abstract class QueryFormRequest<TOutput> {
@@ -13,6 +13,5 @@ declare function resolveLoginIdentity(request: Request, trustForwardedFor?: bool
13
13
  declare function resolveLoginEmail(request: Request): Promise<string>;
14
14
  declare function createMemoryLoginThrottleMiddleware(options: LoginThrottleOptions): DisposableMemoryThrottle;
15
15
  declare function createLoginThrottleMiddleware(options: LoginThrottleOptions): DisposableThrottle;
16
- declare function resetMemoryLoginThrottleForTests(): void;
17
16
  export type { LoginThrottleOptions };
18
- export { createLoginThrottleMiddleware, createMemoryLoginThrottleMiddleware, resetMemoryLoginThrottleForTests, resolveLoginEmail, resolveLoginIdentity, };
17
+ export { createLoginThrottleMiddleware, createMemoryLoginThrottleMiddleware, resolveLoginEmail, resolveLoginIdentity, };
@@ -12,7 +12,5 @@ type DisposableMemoryThrottle = Middleware & {
12
12
  stats(): MemoryThrottleStats;
13
13
  };
14
14
  declare function createMemoryThrottleMiddleware(options: MemoryThrottleOptions): DisposableMemoryThrottle;
15
- /** Lazy generation reset avoids retaining middleware instances in a global test registry. */
16
- declare function resetMemoryThrottleForTests(): void;
17
15
  export type { DisposableMemoryThrottle, MemoryThrottleOptions, MemoryThrottleStats, MemoryThrottleStorageOptions, };
18
- export { createMemoryThrottleMiddleware, resetMemoryThrottleForTests };
16
+ export { createMemoryThrottleMiddleware };
@@ -1,10 +1,8 @@
1
+ import { FormRequest } from "./formRequest";
1
2
  import { type FormBodyOptions } from "./parseFormBody";
2
- declare abstract class WebFormRequest<TOutput> {
3
+ declare abstract class WebFormRequest<TOutput> extends FormRequest<TOutput> {
3
4
  #private;
4
5
  constructor(options?: FormBodyOptions);
5
- authorize(_request: Request): boolean | Promise<boolean>;
6
- protected abstract parse(payload: unknown): TOutput;
7
- validatePayload(payload: unknown): TOutput;
8
- validate(request: Request): Promise<TOutput>;
6
+ protected readPayload(request: Request): Promise<unknown>;
9
7
  }
10
8
  export { WebFormRequest };
@@ -8,9 +8,12 @@ interface MailMessage {
8
8
  html?: string;
9
9
  signal?: AbortSignal;
10
10
  }
11
- interface MailDriver {
11
+ interface MailSender {
12
12
  send(message: MailMessage): Promise<void>;
13
13
  }
14
+ /** A mail transport implements the same minimal sending capability. */
15
+ interface MailDriver extends MailSender {
16
+ }
14
17
  interface SmtpConfig {
15
18
  host: string;
16
19
  port: number;
@@ -36,11 +39,11 @@ declare class SmtpMailDriver implements MailDriver {
36
39
  constructor(config: SmtpConfig, transport?: SmtpTransport);
37
40
  send(message: MailMessage): Promise<void>;
38
41
  }
39
- declare class Mailer {
42
+ declare class Mailer implements MailSender {
40
43
  private readonly driver;
41
44
  constructor(driver: MailDriver);
42
45
  send(message: MailMessage): Promise<void>;
43
46
  }
44
47
  declare function createMailDriver(env?: Readonly<Record<string, string | undefined>>): MailDriver;
45
- export type { MailDriver, MailMessage, SmtpConfig, SmtpTransport };
48
+ export type { MailDriver, MailMessage, MailSender, SmtpConfig, SmtpTransport };
46
49
  export { assertSafeSmtpAddress, assertSafeSmtpField, buildSmtpPayload, CORE_MAIL_TOKEN, createMailDriver, defaultSmtpTransport, LogMailDriver, Mailer, redactMailBody, resolveSmtpConfig, SmtpMailDriver, smtpEnvelopeAddress, snapshotSmtpConfig, };
@@ -1,4 +1,4 @@
1
- import type { Mailer, MailMessage } from "./mailer.ts";
1
+ import type { MailMessage, MailSender } from "./mailer.ts";
2
2
  import { type MarkdownMailLayoutOptions } from "./markdownMail.ts";
3
3
  interface MarkdownMailableInput {
4
4
  to: string;
@@ -7,6 +7,6 @@ interface MarkdownMailableInput {
7
7
  layout?: MarkdownMailLayoutOptions;
8
8
  }
9
9
  declare function buildMarkdownMailMessage(input: MarkdownMailableInput): MailMessage;
10
- declare function sendMarkdownMail(mailer: Mailer, input: MarkdownMailableInput): Promise<void>;
10
+ declare function sendMarkdownMail(mailer: MailSender, input: MarkdownMailableInput): Promise<void>;
11
11
  export type { MarkdownMailableInput };
12
12
  export { buildMarkdownMailMessage, sendMarkdownMail };
@@ -1,13 +1,13 @@
1
- import type { Mailer } from "../mail/mailer.ts";
1
+ import type { MailSender } from "../mail/mailer.ts";
2
2
  import type { Notification } from "./notification.ts";
3
- import type { DatabaseNotificationStore, Notifiable } from "./types.ts";
3
+ import type { DatabaseNotificationStore, Notifiable, NotificationChannels } from "./types.ts";
4
4
  declare class NotificationDispatcher {
5
5
  private readonly mailer;
6
- private readonly databaseStore;
7
- constructor(mailer: Mailer, databaseStore?: DatabaseNotificationStore | null);
6
+ private readonly channels;
7
+ constructor(mailer: MailSender, databaseStore?: DatabaseNotificationStore | null, channels?: NotificationChannels);
8
8
  send(notifiable: Notifiable, notification: Notification): Promise<void>;
9
9
  private sendMail;
10
10
  private sendDatabase;
11
11
  }
12
- declare function createNotificationDispatcher(mailer: Mailer, databaseStore?: DatabaseNotificationStore): NotificationDispatcher;
12
+ declare function createNotificationDispatcher(mailer: MailSender, databaseStore?: DatabaseNotificationStore, channels?: NotificationChannels): NotificationDispatcher;
13
13
  export { createNotificationDispatcher, NotificationDispatcher };
@@ -1,3 +1,3 @@
1
1
  export { createNotificationDispatcher, NotificationDispatcher } from "./dispatcher.ts";
2
2
  export { Notification } from "./notification.ts";
3
- export type { DatabaseNotificationPayload, DatabaseNotificationStore, MailNotificationMessage, Notifiable, NotificationChannelName, } from "./types.ts";
3
+ export type { DatabaseNotificationPayload, DatabaseNotificationStore, MailNotificationMessage, Notifiable, NotificationChannel, NotificationChannelName, NotificationChannels, } from "./types.ts";
@@ -1,4 +1,11 @@
1
- type NotificationChannelName = "mail" | "database";
1
+ import type { Notification } from "./notification.ts";
2
+ /** Channel names belong to the application; built-ins retain editor completion. */
3
+ type NotificationChannelName = "mail" | "database" | (string & {});
4
+ /** An application-owned delivery capability. Failures propagate to the caller. */
5
+ interface NotificationChannel {
6
+ send(notifiable: Notifiable, notification: Notification): Promise<void>;
7
+ }
8
+ type NotificationChannels = Readonly<Record<string, NotificationChannel>>;
2
9
  interface MailNotificationMessage {
3
10
  subject: string;
4
11
  markdown?: string;
@@ -22,4 +29,4 @@ interface Notifiable {
22
29
  getNotificationKey(): string | number;
23
30
  routeNotificationFor(channel: NotificationChannelName): string | number | null;
24
31
  }
25
- export type { DatabaseNotificationPayload, DatabaseNotificationStore, MailNotificationMessage, Notifiable, NotificationChannelName, };
32
+ export type { DatabaseNotificationPayload, DatabaseNotificationStore, MailNotificationMessage, Notifiable, NotificationChannel, NotificationChannelName, NotificationChannels, };
@@ -25,11 +25,14 @@ interface QueueDispatchOptions {
25
25
  /** Opaque authenticated identity snapshot created by application composition. */
26
26
  readonly handoff?: string;
27
27
  }
28
- interface Queue {
28
+ /** Dispatch capability for application consumers, without replay or shutdown ownership. */
29
+ interface QueueDispatcher {
30
+ dispatch<TPayload extends object>(job: Job<TPayload>, payload: TPayload, options?: QueueDispatchOptions): Promise<void>;
31
+ }
32
+ interface Queue extends QueueDispatcher {
29
33
  close?(): void | Promise<void>;
30
34
  /** Preserve a stored logical identity on deliberate replay; reset execution controls. */
31
35
  replay?<TPayload extends object>(job: Job<TPayload>, payload: TPayload, jobId: string, options?: QueueDispatchOptions): Promise<void>;
32
- dispatch<TPayload extends object>(job: Job<TPayload>, payload: TPayload, options?: QueueDispatchOptions): Promise<void>;
33
36
  }
34
37
  declare class SyncQueue implements Queue {
35
38
  dispatch<TPayload extends object>(job: Job<TPayload>, payload: TPayload, options?: QueueDispatchOptions): Promise<void>;
@@ -39,10 +42,12 @@ declare class AsyncQueue implements Queue {
39
42
  private closing?;
40
43
  private closed;
41
44
  protected assertOpen(): void;
45
+ /** Join admitted work without consuming the dispatch caller's failure. */
46
+ protected track(running: Promise<void>): Promise<void>;
42
47
  protected enqueue(task: () => Promise<void>, onError: (error: unknown) => void): void;
43
48
  dispatch<TPayload extends object>(job: Job<TPayload>, payload: TPayload, options?: QueueDispatchOptions): Promise<void>;
44
49
  close(): Promise<void>;
45
50
  }
46
51
  declare function createQueue(driver: "sync" | "async"): Queue;
47
- export type { JobContext, Queue, QueueDispatchOptions, QueuePriority };
52
+ export type { JobContext, Queue, QueueDispatcher, QueueDispatchOptions, QueuePriority };
48
53
  export { AsyncQueue, createQueue, Job, SyncQueue };
@@ -1,5 +1,5 @@
1
1
  import type { ApplicationConfig, ExecutionActor } from "../contracts/application";
2
- import type { Queue } from "./index";
2
+ import type { QueueDispatcher } from "./index";
3
3
  import type { JobRegistry } from "./jobRegistry";
4
4
  import type { QueueJobEnvelope } from "./jobRunner";
5
5
  interface QueueIdentity {
@@ -26,6 +26,6 @@ declare function createQueueHandoff(options: {
26
26
  readonly audience: string;
27
27
  }): QueueHandoff;
28
28
  /** Capture identity data only; no request scope, signal, database session or resolver survives dispatch. */
29
- declare function createIdentityQueue(queue: Queue, registry: JobRegistry, handoff: QueueHandoff, identity: QueueIdentity): Pick<Queue, "dispatch">;
29
+ declare function createIdentityQueue(queue: QueueDispatcher, registry: JobRegistry, handoff: QueueHandoff, identity: QueueIdentity): QueueDispatcher;
30
30
  export type { QueueHandoff, QueueIdentity };
31
31
  export { createIdentityQueue, createQueueHandoff, QueueHandoffError };
@@ -3,5 +3,7 @@ import type { Application, ApplicationDefinition } from "../contracts/applicatio
3
3
  declare function createApplication(definition: ApplicationDefinition): Application;
4
4
  export { aliasService, resourceService, service, valueService, } from "@getstrata/core/contracts/services";
5
5
  export type * from "../contracts/application";
6
+ export type * from "../contracts/provider";
7
+ export { defineProvider } from "../contracts/provider";
6
8
  export type * from "../contracts/services";
7
9
  export { CORE_EXECUTION_CONTEXT_TOKEN, createApplication };
@@ -1,4 +1,5 @@
1
1
  declare const OAUTH_STATE_COOKIE = "oauth_state";
2
+ declare const SAML_STATE_COOKIE = "saml_state";
2
3
  declare const OIDC_PKCE_COOKIE = "oidc_pkce";
3
4
  interface OAuthStateOptions {
4
5
  readonly secret: string;
@@ -9,6 +10,7 @@ interface OidcPkceSeal {
9
10
  nonce: string;
10
11
  codeVerifier: string;
11
12
  }
13
+ /** Validate the signature and lifetime only; browser binding must be supplied separately. */
12
14
  declare function verifySignedOAuthStateValue(value: string, options?: OAuthStateOptions): boolean;
13
15
  declare function createOAuthState(options?: OAuthStateOptions): {
14
16
  state: string;
@@ -17,7 +19,15 @@ declare function createOAuthStateCookie(options?: OAuthStateOptions): {
17
19
  state: string;
18
20
  cookie: string;
19
21
  };
20
- declare function verifyOAuthState(_request: Request, returnedState: string | null, options?: OAuthStateOptions): boolean;
22
+ /** Require signed state to match the initiating browser's OAuth state cookie. */
23
+ declare function verifyOAuthState(request: Request, returnedState: string | null, options?: OAuthStateOptions): boolean;
24
+ /** Cross-site IdP POSTs require SameSite=None; browsers require Secure and HTTPS. */
25
+ declare function createSamlStateCookie(options?: OAuthStateOptions): {
26
+ state: string;
27
+ cookie: string;
28
+ };
29
+ declare function verifySamlState(request: Request, returnedState: string | null, options?: OAuthStateOptions): boolean;
30
+ declare function clearSamlStateCookie(): string;
21
31
  declare function clearOAuthStateCookie(options?: OAuthStateOptions): string;
22
32
  declare function sealOidcPkceCookie(payload: OidcPkceSeal, options?: OAuthStateOptions): string;
23
33
  declare function clearOidcPkceCookie(options?: OAuthStateOptions): string;
@@ -26,4 +36,4 @@ declare function readOidcPkceCookie(request: Request, returnedState: string | nu
26
36
  codeVerifier: string;
27
37
  } | null;
28
38
  export type { OAuthStateOptions, OidcPkceSeal };
29
- export { clearOAuthStateCookie, clearOidcPkceCookie, createOAuthState, createOAuthStateCookie, OAUTH_STATE_COOKIE, OIDC_PKCE_COOKIE, readOidcPkceCookie, sealOidcPkceCookie, verifyOAuthState, verifySignedOAuthStateValue, };
39
+ export { clearOAuthStateCookie, clearOidcPkceCookie, clearSamlStateCookie, createOAuthState, createOAuthStateCookie, createSamlStateCookie, OAUTH_STATE_COOKIE, OIDC_PKCE_COOKIE, readOidcPkceCookie, SAML_STATE_COOKIE, sealOidcPkceCookie, verifyOAuthState, verifySamlState, verifySignedOAuthStateValue, };
@@ -1,11 +1,3 @@
1
- type DnsLookupResult = {
2
- address: string;
3
- family: number;
4
- };
5
- type DnsLookup = (hostname: string, options: {
6
- all: true;
7
- verbatim: true;
8
- }) => Promise<DnsLookupResult[]>;
9
1
  declare function isBlockedHostname(hostname: string): boolean;
10
2
  declare function assertSafeOutboundUrl(rawUrl: string, options?: {
11
3
  allowHttp?: boolean;
@@ -30,7 +22,5 @@ declare function assertSafeOutboundUrlResolved(rawUrl: string, options?: {
30
22
  production?: boolean;
31
23
  allowPrivate?: boolean;
32
24
  }): Promise<URL>;
33
- declare function setDnsLookupForTests(lookupFn: DnsLookup): void;
34
- declare function resetDnsLookupForTests(): void;
35
25
  export type { ResolvedOutboundUrl };
36
- export { assertSafeOutboundUrl, assertSafeOutboundUrlResolved, isBlockedHostname, isBlockedIpAddress, pinUrlToAddress, resetDnsLookupForTests, resolveSafeOutboundTarget, setDnsLookupForTests, };
26
+ export { assertSafeOutboundUrl, assertSafeOutboundUrlResolved, isBlockedHostname, isBlockedIpAddress, pinUrlToAddress, resolveSafeOutboundTarget, };
@@ -1,11 +1,21 @@
1
1
  import { CORE_STORAGE_TOKEN } from "@getstrata/core/contracts/serviceTokens";
2
2
  import { S3Client } from "bun";
3
3
  /** Missing reads return null; deletion is idempotent. All other failures reject. */
4
- interface StorageDriver {
4
+ interface Storage {
5
5
  put(path: string, contents: string | Uint8Array): Promise<string>;
6
6
  get(path: string): Promise<Uint8Array | null>;
7
7
  delete(path: string): Promise<void>;
8
8
  }
9
+ /** Buffered consumers need no streaming or concrete manager dependency. */
10
+ interface StorageDriver extends Storage {
11
+ }
12
+ /** Streams are single-use. Late read errors reject reader.read(); cancellation closes the source. */
13
+ interface StreamingStorage extends Storage {
14
+ readStream(path: string): Promise<ReadableStream<Uint8Array> | null>;
15
+ writeStream(path: string, contents: ReadableStream<Uint8Array> | Blob): Promise<string>;
16
+ }
17
+ /** Narrow a consumer port when an operation requires native streaming support. */
18
+ declare function requireStreamingStorage(storage: Storage): StreamingStorage;
9
19
  interface S3StorageConfig {
10
20
  accessKeyId: string;
11
21
  secretAccessKey: string;
@@ -14,26 +24,33 @@ interface S3StorageConfig {
14
24
  endpoint?: string;
15
25
  sessionToken?: string;
16
26
  }
17
- declare class LocalStorageDriver implements StorageDriver {
27
+ declare class LocalStorageDriver implements StreamingStorage {
18
28
  private readonly rootDirectory;
19
29
  constructor(rootDirectory?: string);
20
30
  private resolvePath;
21
31
  put(path: string, contents: string | Uint8Array): Promise<string>;
22
32
  get(path: string): Promise<Uint8Array | null>;
33
+ readStream(path: string): Promise<ReadableStream<Uint8Array> | null>;
34
+ writeStream(path: string, contents: ReadableStream<Uint8Array> | Blob): Promise<string>;
23
35
  delete(path: string): Promise<void>;
24
36
  }
25
- declare class S3StorageDriver implements StorageDriver {
37
+ declare class S3StorageDriver implements StreamingStorage {
26
38
  private readonly client;
27
39
  constructor(client: S3Client);
28
40
  put(path: string, contents: string | Uint8Array): Promise<string>;
29
41
  get(path: string): Promise<Uint8Array | null>;
42
+ readStream(path: string): Promise<ReadableStream<Uint8Array> | null>;
43
+ writeStream(path: string, contents: ReadableStream<Uint8Array> | Blob): Promise<string>;
30
44
  delete(path: string): Promise<void>;
31
45
  }
32
- declare class StorageManager {
46
+ declare class StorageManager implements StreamingStorage {
33
47
  private readonly driver;
34
48
  constructor(driver: StorageDriver);
35
49
  put(path: string, contents: string | Uint8Array): Promise<string>;
36
50
  get(path: string): Promise<Uint8Array | null>;
51
+ streamingDriver(): StreamingStorage;
52
+ readStream(path: string): Promise<ReadableStream<Uint8Array> | null>;
53
+ writeStream(path: string, contents: ReadableStream<Uint8Array> | Blob): Promise<string>;
37
54
  delete(path: string): Promise<void>;
38
55
  }
39
56
  type StorageConfig = {
@@ -49,5 +66,5 @@ declare function resolveS3Config(env?: Readonly<Record<string, string | undefine
49
66
  declare function resolveStorageConfig(env?: Readonly<Record<string, string | undefined>>): StorageConfig;
50
67
  declare function createS3Client(config: Readonly<S3StorageConfig>): S3Client;
51
68
  declare function createStorageDriver(config: StorageConfig): StorageDriver;
52
- export type { S3StorageConfig, StorageConfig, StorageDriver };
53
- export { CORE_STORAGE_TOKEN, createS3Client, createStorageDriver, LocalStorageDriver, resolveS3Config, resolveStorageConfig, S3StorageDriver, StorageManager, snapshotStorageConfig, };
69
+ export type { S3StorageConfig, Storage, StorageConfig, StorageDriver, StreamingStorage };
70
+ export { CORE_STORAGE_TOKEN, createS3Client, createStorageDriver, LocalStorageDriver, requireStreamingStorage, resolveS3Config, resolveStorageConfig, S3StorageDriver, StorageManager, snapshotStorageConfig, };
@@ -0,0 +1,5 @@
1
+ /** Test controls share the same package-private state as every production entry.
2
+ * Production imports expose no test controls; this entry shares their private state.
3
+ */
4
+ export { resetMysqlLoaderForTests } from "#strata-mysql-native";
5
+ export { resetDnsLookupForTests, resetMemoryLoginThrottleForTests, resetMemoryThrottleForTests, setDnsLookupForTests, setNodeSamlLoaderForTests, } from "#strata-test-state";
@@ -0,0 +1,22 @@
1
+ import type { NodeSamlModule } from "./auth/saml/samlServiceProvider";
2
+ type DnsLookup = (hostname: string, options: {
3
+ all: true;
4
+ verbatim: true;
5
+ }) => Promise<{
6
+ address: string;
7
+ family: number;
8
+ }[]>;
9
+ /** Package-private test controls. Production resource ownership stays with each adapter. */
10
+ declare const testState: {
11
+ throttleGeneration: number;
12
+ loginThrottleGeneration: number;
13
+ dnsLookup: DnsLookup | undefined;
14
+ nodeSamlLoader: (() => Promise<NodeSamlModule>) | null;
15
+ };
16
+ /** Generations avoid retaining middleware instances in a global test registry. */
17
+ declare function resetMemoryThrottleForTests(): void;
18
+ declare function resetMemoryLoginThrottleForTests(): void;
19
+ declare function setDnsLookupForTests(lookupFn: NonNullable<typeof testState.dnsLookup>): void;
20
+ declare function resetDnsLookupForTests(): void;
21
+ declare function setNodeSamlLoaderForTests(loader: typeof testState.nodeSamlLoader): void;
22
+ export { resetDnsLookupForTests, resetMemoryLoginThrottleForTests, resetMemoryThrottleForTests, setDnsLookupForTests, setNodeSamlLoaderForTests, testState, };
@@ -189,6 +189,7 @@ async function safeFetch(input, init = {}, options = {}) {
189
189
 
190
190
  // ../../src/core/security/safeUrl.ts
191
191
  import { BadRequestError } from "@getstrata/core/errors/http";
192
+ import { testState } from "#strata-test-state";
192
193
  var BLOCKED_HOSTNAMES = new Set([
193
194
  "localhost",
194
195
  "127.0.0.1",
@@ -1,8 +1,104 @@
1
1
  // @bun
2
+ // ../../src/core/config/envSchema.ts
3
+ function defineEnvSchema(schema) {
4
+ return schema;
5
+ }
6
+ function validateEnv(schema, env = process.env) {
7
+ const resolved = {};
8
+ for (const [name, rule] of Object.entries(schema)) {
9
+ if (rule.integer) {
10
+ if (rule.minimum !== undefined && !Number.isSafeInteger(rule.minimum) || rule.maximum !== undefined && !Number.isSafeInteger(rule.maximum) || rule.minimum !== undefined && rule.maximum !== undefined && rule.minimum > rule.maximum) {
11
+ throw new TypeError(`Environment integer rule for "${name}" has invalid bounds.`);
12
+ }
13
+ }
14
+ const rawValue = env[name];
15
+ if (rawValue !== undefined && typeof rawValue !== "string") {
16
+ throw new TypeError(`Environment variable "${name}" must be a string.`);
17
+ }
18
+ const value = rawValue === undefined || rawValue.trim() === "" ? rule.default : rawValue;
19
+ if (value !== undefined && typeof value !== "string") {
20
+ throw new TypeError(`Environment variable "${name}" must resolve to a string.`);
21
+ }
22
+ if (value === undefined || value.trim() === "") {
23
+ if (rule.required) {
24
+ throw new Error(`Missing required environment variable "${name}".`);
25
+ }
26
+ continue;
27
+ }
28
+ if (rule.integer) {
29
+ const completeInteger = /^[+-]?\d+$/.test(value.trim());
30
+ const parsed = Number.parseInt(value, 10);
31
+ const minimum = rule.minimum ?? Number.NEGATIVE_INFINITY;
32
+ const maximum = rule.maximum ?? Number.POSITIVE_INFINITY;
33
+ if (!completeInteger || !Number.isSafeInteger(parsed) || parsed < minimum || parsed > maximum) {
34
+ const comparison = minimum !== Number.NEGATIVE_INFINITY && maximum !== Number.POSITIVE_INFINITY ? `an integer between ${minimum} and ${maximum}` : maximum !== Number.POSITIVE_INFINITY ? `an integer <= ${maximum}` : minimum === Number.NEGATIVE_INFINITY ? "an integer" : `an integer >= ${minimum}`;
35
+ throw new Error(`Environment variable "${name}" must be ${comparison}.`);
36
+ }
37
+ }
38
+ if (rule.pattern && !new RegExp(rule.pattern.source, rule.pattern.flags).test(value)) {
39
+ throw new Error(`Environment variable "${name}" has an invalid format.`);
40
+ }
41
+ Object.defineProperty(resolved, name, {
42
+ value,
43
+ enumerable: true,
44
+ configurable: true,
45
+ writable: true
46
+ });
47
+ }
48
+ return resolved;
49
+ }
50
+ function resolveEnv(schema, env = process.env) {
51
+ const validated = validateEnv(schema, env);
52
+ const resolved = {};
53
+ for (const [name, rule] of Object.entries(schema)) {
54
+ const value = validated[name];
55
+ Object.defineProperty(resolved, name, {
56
+ value: value === undefined ? undefined : rule.integer ? Number(value) : value,
57
+ enumerable: true
58
+ });
59
+ }
60
+ return Object.freeze(resolved);
61
+ }
62
+
63
+ // ../../src/core/http/cookies.ts
64
+ function readRequestCookie(request, name) {
65
+ const cookies = request.cookies;
66
+ if (cookies && typeof cookies.get === "function") {
67
+ const value = cookies.get(name);
68
+ if (value) {
69
+ return value;
70
+ }
71
+ }
72
+ const header = request.headers.get("cookie");
73
+ if (!header) {
74
+ return null;
75
+ }
76
+ for (const part of header.split(";")) {
77
+ const idx = part.indexOf("=");
78
+ if (idx === -1)
79
+ continue;
80
+ const cookieName = part.slice(0, idx).trim();
81
+ if (cookieName !== name)
82
+ continue;
83
+ try {
84
+ return decodeURIComponent(part.slice(idx + 1).trim());
85
+ } catch {
86
+ return null;
87
+ }
88
+ }
89
+ return null;
90
+ }
91
+ function readBunRequestCookie(request, name) {
92
+ return request.cookies.get(name) ?? readRequestCookie(request, name);
93
+ }
94
+
2
95
  // ../../src/core/http/safeInternalPath.ts
3
96
  var NESTED_REDIRECT_KEYS = new Set(["redirect", "next", "return", "returnTo", "return_to"]);
4
97
  function looksLikeExternalTarget(value) {
5
98
  const trimmed = value.trim();
99
+ if (/[\t\r\n]/.test(trimmed)) {
100
+ return true;
101
+ }
6
102
  if (!trimmed.startsWith("/") || trimmed.startsWith("//") || trimmed.includes("\\")) {
7
103
  return true;
8
104
  }
@@ -28,13 +124,13 @@ function sanitizeNestedQuery(search) {
28
124
  for (const [key, value] of params.entries()) {
29
125
  if (NESTED_REDIRECT_KEYS.has(key)) {
30
126
  const sanitized = sanitizeInternalPath(value, "/");
31
- next.set(key, sanitized);
127
+ next.append(key, sanitized);
32
128
  continue;
33
129
  }
34
130
  if (looksLikeExternalTarget(value) && value.includes("://")) {
35
131
  continue;
36
132
  }
37
- next.set(key, value);
133
+ next.append(key, value);
38
134
  }
39
135
  const serialized = next.toString();
40
136
  return serialized ? `?${serialized}` : "";
@@ -142,8 +238,13 @@ function intendedUrlCookieName(env) {
142
238
  return env.INTENDED_URL_COOKIE_NAME?.trim() || appCookieName("intended", env);
143
239
  }
144
240
  function intendedUrlTtlSeconds(env) {
145
- const parsed = Number.parseInt(env.INTENDED_URL_TTL_SECONDS ?? "", 10);
146
- return Number.isInteger(parsed) && parsed > 0 ? parsed : DEFAULT_INTENDED_URL_TTL_SECONDS;
241
+ return resolveEnv({
242
+ INTENDED_URL_TTL_SECONDS: {
243
+ integer: true,
244
+ minimum: 1,
245
+ default: String(DEFAULT_INTENDED_URL_TTL_SECONDS)
246
+ }
247
+ }, env).INTENDED_URL_TTL_SECONDS;
147
248
  }
148
249
  function cookieSecureFlag(options) {
149
250
  return options.production ? "; Secure" : "";
@@ -163,19 +264,6 @@ function isStashableIntendedPath(path) {
163
264
  }
164
265
  return true;
165
266
  }
166
- function readCookieValue(request, cookieName) {
167
- const cookieHeader = request.headers.get("cookie");
168
- if (!cookieHeader) {
169
- return null;
170
- }
171
- for (const part of cookieHeader.split(";")) {
172
- const [name, ...rest] = part.trim().split("=");
173
- if (name === cookieName) {
174
- return decodeURIComponent(rest.join("="));
175
- }
176
- }
177
- return null;
178
- }
179
267
  function createIntendedUrlCookie(path, options) {
180
268
  const sanitized = sanitizeInternalPath(path, "");
181
269
  if (!sanitized || !isStashableIntendedPath(sanitized)) {
@@ -190,7 +278,7 @@ function createIntendedUrlCookieFromRequest(request, options) {
190
278
  return createIntendedUrlCookie(safeInternalRedirectPath(request, ""), options);
191
279
  }
192
280
  function readIntendedUrl(request, options) {
193
- const cookieValue = readCookieValue(request, options.cookieName);
281
+ const cookieValue = readRequestCookie(request, options.cookieName);
194
282
  if (!cookieValue) {
195
283
  return null;
196
284
  }
@@ -2,6 +2,67 @@
2
2
  // ../../src/core/auth/jwt.ts
3
3
  import { createHmac, timingSafeEqual } from "crypto";
4
4
 
5
+ // ../../src/core/config/envSchema.ts
6
+ function defineEnvSchema(schema) {
7
+ return schema;
8
+ }
9
+ function validateEnv(schema, env = process.env) {
10
+ const resolved = {};
11
+ for (const [name, rule] of Object.entries(schema)) {
12
+ if (rule.integer) {
13
+ if (rule.minimum !== undefined && !Number.isSafeInteger(rule.minimum) || rule.maximum !== undefined && !Number.isSafeInteger(rule.maximum) || rule.minimum !== undefined && rule.maximum !== undefined && rule.minimum > rule.maximum) {
14
+ throw new TypeError(`Environment integer rule for "${name}" has invalid bounds.`);
15
+ }
16
+ }
17
+ const rawValue = env[name];
18
+ if (rawValue !== undefined && typeof rawValue !== "string") {
19
+ throw new TypeError(`Environment variable "${name}" must be a string.`);
20
+ }
21
+ const value = rawValue === undefined || rawValue.trim() === "" ? rule.default : rawValue;
22
+ if (value !== undefined && typeof value !== "string") {
23
+ throw new TypeError(`Environment variable "${name}" must resolve to a string.`);
24
+ }
25
+ if (value === undefined || value.trim() === "") {
26
+ if (rule.required) {
27
+ throw new Error(`Missing required environment variable "${name}".`);
28
+ }
29
+ continue;
30
+ }
31
+ if (rule.integer) {
32
+ const completeInteger = /^[+-]?\d+$/.test(value.trim());
33
+ const parsed = Number.parseInt(value, 10);
34
+ const minimum = rule.minimum ?? Number.NEGATIVE_INFINITY;
35
+ const maximum = rule.maximum ?? Number.POSITIVE_INFINITY;
36
+ if (!completeInteger || !Number.isSafeInteger(parsed) || parsed < minimum || parsed > maximum) {
37
+ const comparison = minimum !== Number.NEGATIVE_INFINITY && maximum !== Number.POSITIVE_INFINITY ? `an integer between ${minimum} and ${maximum}` : maximum !== Number.POSITIVE_INFINITY ? `an integer <= ${maximum}` : minimum === Number.NEGATIVE_INFINITY ? "an integer" : `an integer >= ${minimum}`;
38
+ throw new Error(`Environment variable "${name}" must be ${comparison}.`);
39
+ }
40
+ }
41
+ if (rule.pattern && !new RegExp(rule.pattern.source, rule.pattern.flags).test(value)) {
42
+ throw new Error(`Environment variable "${name}" has an invalid format.`);
43
+ }
44
+ Object.defineProperty(resolved, name, {
45
+ value,
46
+ enumerable: true,
47
+ configurable: true,
48
+ writable: true
49
+ });
50
+ }
51
+ return resolved;
52
+ }
53
+ function resolveEnv(schema, env = process.env) {
54
+ const validated = validateEnv(schema, env);
55
+ const resolved = {};
56
+ for (const [name, rule] of Object.entries(schema)) {
57
+ const value = validated[name];
58
+ Object.defineProperty(resolved, name, {
59
+ value: value === undefined ? undefined : rule.integer ? Number(value) : value,
60
+ enumerable: true
61
+ });
62
+ }
63
+ return Object.freeze(resolved);
64
+ }
65
+
5
66
  // ../../src/core/runtime/appEnv.ts
6
67
  var NON_PRODUCTION_APP_ENVS = new Set(["local", "development", "dev", "test", "testing", "ci"]);
7
68
  function normalizeEnvValue(value) {
@@ -58,10 +119,10 @@ function otelServiceName(env = process.env) {
58
119
 
59
120
  // ../../src/core/auth/jwt.ts
60
121
  function jwtOptionsFromEnvironment(env) {
61
- const parsed = Number.parseInt(env.JWT_TTL_SECONDS ?? "", 10);
122
+ const ttl = resolveEnv({ JWT_TTL_SECONDS: { integer: true, minimum: 1, default: "3600" } }, env);
62
123
  return Object.freeze({
63
124
  secret: requireConfiguredSecret(["JWT_SECRET", "SESSION_SECRET"], "jwt-secret", env),
64
- ttlSeconds: Number.isInteger(parsed) && parsed > 0 ? parsed : 3600
125
+ ttlSeconds: ttl.JWT_TTL_SECONDS
65
126
  });
66
127
  }
67
128
  function resolveJwtSecret(secret) {
@@ -71,10 +132,11 @@ function resolveJwtSecret(secret) {
71
132
  throw new TypeError("Explicit JWT secret is required.");
72
133
  }
73
134
  function jwtTtlSeconds(override) {
74
- if (typeof override === "number" && Number.isInteger(override) && override > 0) {
75
- return override;
76
- }
77
- return 3600;
135
+ if (override === undefined)
136
+ return 3600;
137
+ if (!Number.isSafeInteger(override) || override <= 0)
138
+ throw new TypeError("JWT ttlSeconds must be a positive safe integer.");
139
+ return override;
78
140
  }
79
141
  function encodeJson(value) {
80
142
  return Buffer.from(JSON.stringify(value)).toString("base64url");