@c9up/ream 0.1.7 → 0.1.9

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 (162) hide show
  1. package/dist/Application.d.ts +9 -1
  2. package/dist/Application.d.ts.map +1 -1
  3. package/dist/Application.js +35 -5
  4. package/dist/Application.js.map +1 -1
  5. package/dist/GracefulShutdown.d.ts.map +1 -1
  6. package/dist/GracefulShutdown.js +13 -7
  7. package/dist/GracefulShutdown.js.map +1 -1
  8. package/dist/HttpKernel.d.ts.map +1 -1
  9. package/dist/HttpKernel.js +43 -14
  10. package/dist/HttpKernel.js.map +1 -1
  11. package/dist/Ignitor.d.ts +10 -10
  12. package/dist/Ignitor.d.ts.map +1 -1
  13. package/dist/Ignitor.js +104 -32
  14. package/dist/Ignitor.js.map +1 -1
  15. package/dist/bodyparser/BodyParserMiddleware.d.ts +3 -0
  16. package/dist/bodyparser/BodyParserMiddleware.d.ts.map +1 -1
  17. package/dist/bodyparser/BodyParserMiddleware.js +32 -16
  18. package/dist/bodyparser/BodyParserMiddleware.js.map +1 -1
  19. package/dist/bodyparser/parseSize.d.ts +2 -1
  20. package/dist/bodyparser/parseSize.d.ts.map +1 -1
  21. package/dist/bodyparser/parseSize.js +2 -1
  22. package/dist/bodyparser/parseSize.js.map +1 -1
  23. package/dist/container/Container.d.ts.map +1 -1
  24. package/dist/container/Container.js +39 -9
  25. package/dist/container/Container.js.map +1 -1
  26. package/dist/decorators/Service.d.ts +4 -6
  27. package/dist/decorators/Service.d.ts.map +1 -1
  28. package/dist/decorators/Service.js +0 -1
  29. package/dist/decorators/Service.js.map +1 -1
  30. package/dist/events/Emitter.d.ts +16 -6
  31. package/dist/events/Emitter.d.ts.map +1 -1
  32. package/dist/events/Emitter.js +32 -25
  33. package/dist/events/Emitter.js.map +1 -1
  34. package/dist/events/EventsProvider.d.ts +1 -0
  35. package/dist/events/EventsProvider.d.ts.map +1 -1
  36. package/dist/events/EventsProvider.js +6 -4
  37. package/dist/events/EventsProvider.js.map +1 -1
  38. package/dist/graphql/GraphQLEngine.d.ts +16 -0
  39. package/dist/graphql/GraphQLEngine.d.ts.map +1 -1
  40. package/dist/graphql/GraphQLEngine.js +122 -4
  41. package/dist/graphql/GraphQLEngine.js.map +1 -1
  42. package/dist/graphql/GraphQLProvider.d.ts.map +1 -1
  43. package/dist/graphql/GraphQLProvider.js +13 -2
  44. package/dist/graphql/GraphQLProvider.js.map +1 -1
  45. package/dist/http/HttpContext.d.ts +27 -1
  46. package/dist/http/HttpContext.d.ts.map +1 -1
  47. package/dist/http/HttpContext.js +20 -1
  48. package/dist/http/HttpContext.js.map +1 -1
  49. package/dist/http/RedirectBuilder.d.ts +5 -1
  50. package/dist/http/RedirectBuilder.d.ts.map +1 -1
  51. package/dist/http/RedirectBuilder.js +26 -3
  52. package/dist/http/RedirectBuilder.js.map +1 -1
  53. package/dist/http/Request.d.ts +13 -0
  54. package/dist/http/Request.d.ts.map +1 -1
  55. package/dist/http/Request.js +18 -0
  56. package/dist/http/Request.js.map +1 -1
  57. package/dist/index.d.ts +1 -1
  58. package/dist/index.d.ts.map +1 -1
  59. package/dist/middleware/Pipeline.d.ts +13 -0
  60. package/dist/middleware/Pipeline.d.ts.map +1 -1
  61. package/dist/middleware/Pipeline.js +43 -7
  62. package/dist/middleware/Pipeline.js.map +1 -1
  63. package/dist/router/Router.d.ts +21 -2
  64. package/dist/router/Router.d.ts.map +1 -1
  65. package/dist/router/Router.js +53 -8
  66. package/dist/router/Router.js.map +1 -1
  67. package/dist/rpc/RpcProvider.d.ts.map +1 -1
  68. package/dist/rpc/RpcProvider.js +11 -2
  69. package/dist/rpc/RpcProvider.js.map +1 -1
  70. package/dist/rpc/RpcRouter.d.ts +11 -3
  71. package/dist/rpc/RpcRouter.d.ts.map +1 -1
  72. package/dist/rpc/RpcRouter.js +92 -8
  73. package/dist/rpc/RpcRouter.js.map +1 -1
  74. package/dist/scheduler/ScheduleProvider.d.ts.map +1 -1
  75. package/dist/scheduler/ScheduleProvider.js +10 -0
  76. package/dist/scheduler/ScheduleProvider.js.map +1 -1
  77. package/dist/scheduler/locks/MemoryLockBackend.d.ts +0 -1
  78. package/dist/scheduler/locks/MemoryLockBackend.d.ts.map +1 -1
  79. package/dist/scheduler/locks/MemoryLockBackend.js +0 -1
  80. package/dist/scheduler/locks/MemoryLockBackend.js.map +1 -1
  81. package/dist/services/app.d.ts +6 -0
  82. package/dist/services/app.d.ts.map +1 -1
  83. package/dist/services/app.js +9 -0
  84. package/dist/services/app.js.map +1 -1
  85. package/dist/services/router.d.ts +5 -0
  86. package/dist/services/router.d.ts.map +1 -1
  87. package/dist/services/router.js +8 -0
  88. package/dist/services/router.js.map +1 -1
  89. package/dist/services/server.d.ts +5 -0
  90. package/dist/services/server.d.ts.map +1 -1
  91. package/dist/services/server.js +8 -0
  92. package/dist/services/server.js.map +1 -1
  93. package/dist/session/SessionMiddleware.d.ts.map +1 -1
  94. package/dist/session/SessionMiddleware.js +4 -0
  95. package/dist/session/SessionMiddleware.js.map +1 -1
  96. package/dist/session/drivers/MemoryDriver.d.ts +1 -1
  97. package/dist/session/drivers/MemoryDriver.d.ts.map +1 -1
  98. package/dist/session/drivers/MemoryDriver.js +14 -6
  99. package/dist/session/drivers/MemoryDriver.js.map +1 -1
  100. package/dist/testing/TestClient.d.ts +11 -5
  101. package/dist/testing/TestClient.d.ts.map +1 -1
  102. package/dist/testing/TestClient.js +9 -4
  103. package/dist/testing/TestClient.js.map +1 -1
  104. package/events.darwin-arm64.node +0 -0
  105. package/events.darwin-x64.node +0 -0
  106. package/events.linux-arm64-gnu.node +0 -0
  107. package/events.linux-x64-gnu.node +0 -0
  108. package/events.win32-x64-msvc.node +0 -0
  109. package/index.darwin-arm64.node +0 -0
  110. package/index.darwin-x64.node +0 -0
  111. package/index.linux-arm64-gnu.node +0 -0
  112. package/index.linux-x64-gnu.node +0 -0
  113. package/index.win32-x64-msvc.node +0 -0
  114. package/package.json +1 -1
  115. package/scheduler.darwin-arm64.node +0 -0
  116. package/scheduler.darwin-x64.node +0 -0
  117. package/scheduler.linux-arm64-gnu.node +0 -0
  118. package/scheduler.linux-x64-gnu.node +0 -0
  119. package/scheduler.win32-x64-msvc.node +0 -0
  120. package/src/Application.ts +36 -5
  121. package/src/GracefulShutdown.ts +15 -7
  122. package/src/HttpKernel.ts +52 -17
  123. package/src/Ignitor.ts +106 -34
  124. package/src/bodyparser/BodyParserMiddleware.ts +43 -16
  125. package/src/bodyparser/parseSize.ts +2 -1
  126. package/src/container/Container.ts +42 -12
  127. package/src/decorators/Service.ts +4 -6
  128. package/src/events/Emitter.ts +36 -28
  129. package/src/events/EventsProvider.ts +6 -4
  130. package/src/graphql/GraphQLEngine.ts +139 -3
  131. package/src/graphql/GraphQLProvider.ts +17 -2
  132. package/src/http/HttpContext.ts +38 -1
  133. package/src/http/RedirectBuilder.ts +23 -3
  134. package/src/http/Request.ts +20 -0
  135. package/src/index.ts +1 -1
  136. package/src/middleware/Pipeline.ts +61 -8
  137. package/src/router/Router.ts +53 -8
  138. package/src/rpc/RpcProvider.ts +14 -2
  139. package/src/rpc/RpcRouter.ts +115 -11
  140. package/src/scheduler/ScheduleProvider.ts +10 -0
  141. package/src/scheduler/locks/MemoryLockBackend.ts +0 -2
  142. package/src/services/app.ts +9 -0
  143. package/src/services/router.ts +8 -0
  144. package/src/services/server.ts +8 -0
  145. package/src/session/SessionMiddleware.ts +6 -0
  146. package/src/session/drivers/MemoryDriver.ts +14 -6
  147. package/src/testing/TestClient.ts +18 -7
  148. package/dist/server/HyperServer.d.ts +0 -64
  149. package/dist/server/HyperServer.d.ts.map +0 -1
  150. package/dist/server/HyperServer.js +0 -54
  151. package/dist/server/HyperServer.js.map +0 -1
  152. package/dist/storage/S3Driver.d.ts +0 -27
  153. package/dist/storage/S3Driver.d.ts.map +0 -1
  154. package/dist/storage/S3Driver.js +0 -135
  155. package/dist/storage/S3Driver.js.map +0 -1
  156. package/dist/storage/StorageManager.d.ts +0 -31
  157. package/dist/storage/StorageManager.d.ts.map +0 -1
  158. package/dist/storage/StorageManager.js +0 -120
  159. package/dist/storage/StorageManager.js.map +0 -1
  160. package/src/server/HyperServer.ts +0 -121
  161. package/src/storage/S3Driver.ts +0 -171
  162. package/src/storage/StorageManager.ts +0 -142
@@ -1,121 +0,0 @@
1
- import type { HttpKernelRequest, HttpKernelResponse } from '../HttpKernel.js'
2
- import { loadNapi } from '../helpers/napi-loader.js'
3
-
4
- /**
5
- * Wire-level shield configuration handed off to the Rust filter at boot.
6
- * Each flag toggles one rule on/off; they all default to true on the Rust
7
- * side, so omitting `configureShield()` entirely leaves the server with no
8
- * filter installed.
9
- */
10
- export interface RustShieldConfig {
11
- pathTraversal: boolean
12
- paramPollution: boolean
13
- }
14
-
15
- export interface RustRateLimitConfig {
16
- max: number
17
- windowSecs: number
18
- }
19
-
20
- export interface HyperServerLike {
21
- onRequest(callback: (request: HttpKernelRequest) => Promise<HttpKernelResponse>): void
22
- configureShield(config: RustShieldConfig): void
23
- configureTrustedProxies(cidrs: string[]): void
24
- configureRateLimit(config: RustRateLimitConfig | null): void
25
- listen(): Promise<void>
26
- port(): Promise<number>
27
- close(): Promise<void>
28
- /**
29
- * Reserve a streaming-response slot. The handler must call this and
30
- * pass the returned id back inside `HttpKernelResponse.streamId`
31
- * BEFORE returning, so the hyper-side response builder can feed the
32
- * body from the matching registry entry.
33
- */
34
- registerStream(streamId: string): Promise<boolean>
35
- /**
36
- * Push a UTF-8 chunk onto a registered stream. Returns `false` once
37
- * the client has disconnected — callers stop pushing.
38
- */
39
- writeStream(streamId: string, chunk: string): Promise<boolean>
40
- /**
41
- * End a stream from the server side. Idempotent.
42
- */
43
- closeStream(streamId: string): Promise<boolean>
44
- /**
45
- * Install a one-shot callback fired the moment the matching stream
46
- * receiver is dropped — i.e. the client disconnected OR
47
- * `closeStream` was called. Used by the JS SDK to drop bookkeeping
48
- * for subscriptions and SSE viewers.
49
- */
50
- onStreamDisconnect(streamId: string, callback: () => void): void
51
- }
52
-
53
- interface NativeModule {
54
- HyperServer: new (port: number) => HyperServerLike
55
- }
56
-
57
- let native: NativeModule | undefined
58
-
59
- function loadNative(): NativeModule {
60
- if (native) return native
61
- native = loadNapi<NativeModule>({
62
- binaryName: 'index',
63
- callerMetaUrl: import.meta.url,
64
- errorCodePrefix: 'HYPER_SERVER',
65
- })
66
- return native
67
- }
68
-
69
- /** HyperServer — Rust-powered HTTP server. */
70
- export class HyperServer implements HyperServerLike {
71
- #inner: HyperServerLike
72
-
73
- constructor(port: number) {
74
- const mod = loadNative()
75
- this.#inner = new mod.HyperServer(port)
76
- }
77
-
78
- onRequest(callback: (request: HttpKernelRequest) => Promise<HttpKernelResponse>): void {
79
- this.#inner.onRequest(callback)
80
- }
81
-
82
- configureShield(config: RustShieldConfig): void {
83
- this.#inner.configureShield(config)
84
- }
85
-
86
- configureTrustedProxies(cidrs: string[]): void {
87
- this.#inner.configureTrustedProxies(cidrs)
88
- }
89
-
90
- configureRateLimit(config: RustRateLimitConfig | null): void {
91
- this.#inner.configureRateLimit(config)
92
- }
93
-
94
- listen(): Promise<void> {
95
- return this.#inner.listen()
96
- }
97
-
98
- port(): Promise<number> {
99
- return this.#inner.port()
100
- }
101
-
102
- close(): Promise<void> {
103
- return this.#inner.close()
104
- }
105
-
106
- registerStream(streamId: string): Promise<boolean> {
107
- return this.#inner.registerStream(streamId)
108
- }
109
-
110
- writeStream(streamId: string, chunk: string): Promise<boolean> {
111
- return this.#inner.writeStream(streamId, chunk)
112
- }
113
-
114
- closeStream(streamId: string): Promise<boolean> {
115
- return this.#inner.closeStream(streamId)
116
- }
117
-
118
- onStreamDisconnect(streamId: string, callback: () => void): void {
119
- this.#inner.onStreamDisconnect(streamId, callback)
120
- }
121
- }
@@ -1,171 +0,0 @@
1
- /**
2
- * S3Driver — S3-compatible cloud storage (AWS S3, Cloudflare R2, MinIO).
3
- *
4
- * Uses fetch API — no external SDK dependency.
5
- * Implements the StorageDriver interface.
6
- *
7
- * @implements MISS-24
8
- */
9
-
10
- import { createHash, createHmac } from 'node:crypto'
11
- import type { StorageDriver } from './StorageManager.js'
12
-
13
- /**
14
- * URI-encode an S3 object key for use in BOTH the request URL and the
15
- * SigV4 canonical path. Each `/`-delimited segment is percent-encoded
16
- * (so the slashes that delimit the key hierarchy survive), which means
17
- * spaces, `#`, `?`, `%` and non-ASCII bytes can't slip the requested
18
- * path away from the signed path — the classic "key with a space gets
19
- * a SignatureDoesNotMatch / 403, or `?`/`#` truncates the path" bug.
20
- *
21
- * S3 expects the canonical URI encoded ONCE (unlike the generic SigV4
22
- * double-encode), and `encodeURIComponent` already escapes the RFC 3986
23
- * sub-delims AWS cares about. We additionally escape `!`, `'`, `(`,
24
- * `)`, `*` which `encodeURIComponent` leaves untouched but AWS expects
25
- * percent-encoded.
26
- */
27
- function encodeS3Key(key: string): string {
28
- return key
29
- .split('/')
30
- .map((segment) =>
31
- encodeURIComponent(segment).replace(
32
- /[!'()*]/g,
33
- (c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`,
34
- ),
35
- )
36
- .join('/')
37
- }
38
-
39
- export interface S3Config {
40
- bucket: string
41
- region?: string
42
- endpoint?: string
43
- accessKeyId: string
44
- secretAccessKey: string
45
- publicUrl?: string
46
- }
47
-
48
- export class S3Driver implements StorageDriver {
49
- #config: S3Config
50
- #endpoint: string
51
-
52
- constructor(config: S3Config) {
53
- this.#config = config
54
- this.#endpoint = config.endpoint ?? `https://s3.${config.region ?? 'us-east-1'}.amazonaws.com`
55
- }
56
-
57
- async put(filePath: string, content: Buffer | string): Promise<void> {
58
- const body = typeof content === 'string' ? Buffer.from(content) : content
59
- const key = encodeS3Key(filePath)
60
- const url = `${this.#endpoint}/${this.#config.bucket}/${key}`
61
- const headers = this.#signRequest('PUT', key, body)
62
-
63
- const res = await fetch(url, { method: 'PUT', headers, body: body as unknown as BodyInit })
64
- if (!res.ok) {
65
- throw new Error(`S3 PUT failed (${res.status}): ${await res.text()}`)
66
- }
67
- }
68
-
69
- async get(filePath: string): Promise<Buffer | null> {
70
- const key = encodeS3Key(filePath)
71
- const url = `${this.#endpoint}/${this.#config.bucket}/${key}`
72
- const headers = this.#signRequest('GET', key)
73
-
74
- const res = await fetch(url, { method: 'GET', headers })
75
- if (res.status === 404) return null
76
- if (!res.ok) throw new Error(`S3 GET failed (${res.status})`)
77
-
78
- const arrayBuffer = await res.arrayBuffer()
79
- return Buffer.from(arrayBuffer)
80
- }
81
-
82
- async delete(filePath: string): Promise<boolean> {
83
- const key = encodeS3Key(filePath)
84
- const url = `${this.#endpoint}/${this.#config.bucket}/${key}`
85
- const headers = this.#signRequest('DELETE', key)
86
-
87
- const res = await fetch(url, { method: 'DELETE', headers })
88
- return res.ok || res.status === 204
89
- }
90
-
91
- async exists(filePath: string): Promise<boolean> {
92
- const key = encodeS3Key(filePath)
93
- const url = `${this.#endpoint}/${this.#config.bucket}/${key}`
94
- const headers = this.#signRequest('HEAD', key)
95
-
96
- const res = await fetch(url, { method: 'HEAD', headers })
97
- return res.ok
98
- }
99
-
100
- url(filePath: string): string {
101
- const key = encodeS3Key(filePath)
102
- if (this.#config.publicUrl) {
103
- return `${this.#config.publicUrl}/${key}`
104
- }
105
- return `${this.#endpoint}/${this.#config.bucket}/${key}`
106
- }
107
-
108
- /**
109
- * Sign a request with AWS Signature V4 (simplified).
110
- * For production, consider using @aws-sdk/signature-v4 for full compliance.
111
- */
112
- #signRequest(method: string, key: string, body?: Buffer): Record<string, string> {
113
- const now = new Date()
114
- const dateStamp = `${now.toISOString().replace(/[-:]/g, '').split('.')[0]}Z`
115
- const shortDate = dateStamp.slice(0, 8)
116
- const region = this.#config.region ?? 'us-east-1'
117
- const service = 's3'
118
-
119
- const payloadHash = createHash('sha256')
120
- .update(body ?? '')
121
- .digest('hex')
122
-
123
- const headers: Record<string, string> = {
124
- host: new URL(this.#endpoint).host,
125
- 'x-amz-date': dateStamp,
126
- 'x-amz-content-sha256': payloadHash,
127
- }
128
-
129
- if (body) {
130
- headers['content-length'] = String(body.length)
131
- }
132
-
133
- // Canonical request
134
- const signedHeaders = Object.keys(headers).sort().join(';')
135
- const canonicalHeaders = Object.keys(headers)
136
- .sort()
137
- .map((k) => `${k}:${headers[k]}\n`)
138
- .join('')
139
- const canonicalRequest = [
140
- method,
141
- `/${this.#config.bucket}/${key}`,
142
- '',
143
- canonicalHeaders,
144
- signedHeaders,
145
- payloadHash,
146
- ].join('\n')
147
-
148
- // String to sign
149
- const scope = `${shortDate}/${region}/${service}/aws4_request`
150
- const stringToSign = [
151
- 'AWS4-HMAC-SHA256',
152
- dateStamp,
153
- scope,
154
- createHash('sha256').update(canonicalRequest).digest('hex'),
155
- ].join('\n')
156
-
157
- // Signing key
158
- const kDate = createHmac('sha256', `AWS4${this.#config.secretAccessKey}`)
159
- .update(shortDate)
160
- .digest()
161
- const kRegion = createHmac('sha256', kDate).update(region).digest()
162
- const kService = createHmac('sha256', kRegion).update(service).digest()
163
- const kSigning = createHmac('sha256', kService).update('aws4_request').digest()
164
-
165
- const signature = createHmac('sha256', kSigning).update(stringToSign).digest('hex')
166
-
167
- headers.authorization = `AWS4-HMAC-SHA256 Credential=${this.#config.accessKeyId}/${scope}, SignedHeaders=${signedHeaders}, Signature=${signature}`
168
-
169
- return headers
170
- }
171
- }
@@ -1,142 +0,0 @@
1
- /**
2
- * Storage — file storage abstraction with driver pattern.
3
- *
4
- * @implements MISS-24
5
- */
6
-
7
- import * as fs from 'node:fs'
8
- import * as path from 'node:path'
9
-
10
- /**
11
- * Resolve `filePath` against `root` and reject any result that escapes
12
- * the storage root. Without this guard a user-controlled path like
13
- * `../secrets.env` would let put/get/delete/exists touch arbitrary
14
- * files outside the configured storage root.
15
- *
16
- * The lexical check (`path.resolve` + `startsWith`) catches the
17
- * `../` / absolute-path class. The realpath re-check catches the
18
- * symlink-escape class: a symlink planted under the root (or anywhere
19
- * else on the resolved path's chain) that points outside the root
20
- * would pass the lexical gate but be caught here.
21
- *
22
- * We canonicalize the longest existing ancestor of `full` — `realpath`
23
- * itself throws ENOENT on a target that doesn't exist yet (the `put`
24
- * happy-path for new files). Symlinks anywhere ABOVE the leaf are
25
- * still dereferenced, which is the only escape vector that matters:
26
- * the driver creates the leaf itself, so no symlink can pre-exist
27
- * there.
28
- */
29
- function assertWithinRoot(root: string, filePath: string): string {
30
- const full = path.resolve(root, filePath)
31
- const rootAbs = path.resolve(root)
32
- if (full !== rootAbs && !full.startsWith(rootAbs + path.sep)) {
33
- throw new Error(`[ream-storage] path '${filePath}' escapes the storage root (E_PATH_TRAVERSAL)`)
34
- }
35
- const canonicalRoot = fs.existsSync(rootAbs) ? fs.realpathSync(rootAbs) : rootAbs
36
- const ancestor = longestExistingAncestor(full)
37
- const canonicalAncestor = ancestor === full ? fs.realpathSync(full) : fs.realpathSync(ancestor)
38
- // Re-attach the not-yet-existing leaf to the canonicalized ancestor.
39
- const canonicalFull = canonicalAncestor + full.slice(ancestor.length)
40
- if (canonicalFull !== canonicalRoot && !canonicalFull.startsWith(canonicalRoot + path.sep)) {
41
- throw new Error(
42
- `[ream-storage] path '${filePath}' escapes the storage root via a symlink (E_PATH_TRAVERSAL)`,
43
- )
44
- }
45
- return full
46
- }
47
-
48
- /** Walk up `full` until we find a path that exists on disk. */
49
- function longestExistingAncestor(full: string): string {
50
- let current = full
51
- while (!fs.existsSync(current)) {
52
- const parent = path.dirname(current)
53
- if (parent === current) return current
54
- current = parent
55
- }
56
- return current
57
- }
58
-
59
- export interface StorageDriver {
60
- put(filePath: string, content: Buffer | string): Promise<void>
61
- get(filePath: string): Promise<Buffer | null>
62
- delete(filePath: string): Promise<boolean>
63
- exists(filePath: string): Promise<boolean>
64
- url(filePath: string): string
65
- }
66
-
67
- export class LocalDriver implements StorageDriver {
68
- #root: string
69
-
70
- constructor(root: string) {
71
- this.#root = root
72
- if (!fs.existsSync(root)) {
73
- fs.mkdirSync(root, { recursive: true })
74
- }
75
- }
76
-
77
- async put(filePath: string, content: Buffer | string): Promise<void> {
78
- const full = assertWithinRoot(this.#root, filePath)
79
- const dir = path.dirname(full)
80
- if (!fs.existsSync(dir)) {
81
- fs.mkdirSync(dir, { recursive: true })
82
- }
83
- fs.writeFileSync(full, content)
84
- }
85
-
86
- async get(filePath: string): Promise<Buffer | null> {
87
- const full = assertWithinRoot(this.#root, filePath)
88
- if (!fs.existsSync(full)) return null
89
- return fs.readFileSync(full)
90
- }
91
-
92
- async delete(filePath: string): Promise<boolean> {
93
- const full = assertWithinRoot(this.#root, filePath)
94
- if (!fs.existsSync(full)) return false
95
- fs.unlinkSync(full)
96
- return true
97
- }
98
-
99
- async exists(filePath: string): Promise<boolean> {
100
- let full: string
101
- try {
102
- full = assertWithinRoot(this.#root, filePath)
103
- } catch {
104
- // exists() must NOT leak existence of out-of-root paths via the
105
- // thrown error — quietly report "no" for any traversal attempt.
106
- return false
107
- }
108
- return fs.existsSync(full)
109
- }
110
-
111
- url(filePath: string): string {
112
- return `/storage/${filePath}`
113
- }
114
- }
115
-
116
- export class StorageManager {
117
- #driver: StorageDriver
118
-
119
- constructor(driver: StorageDriver) {
120
- this.#driver = driver
121
- }
122
-
123
- put(filePath: string, content: Buffer | string): Promise<void> {
124
- return this.#driver.put(filePath, content)
125
- }
126
-
127
- get(filePath: string): Promise<Buffer | null> {
128
- return this.#driver.get(filePath)
129
- }
130
-
131
- delete(filePath: string): Promise<boolean> {
132
- return this.#driver.delete(filePath)
133
- }
134
-
135
- exists(filePath: string): Promise<boolean> {
136
- return this.#driver.exists(filePath)
137
- }
138
-
139
- url(filePath: string): string {
140
- return this.#driver.url(filePath)
141
- }
142
- }