@venizia/ignis-helpers 0.4.8-7 → 0.4.8-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.
- package/dist/esm/common/constants/http.d.ts +2 -0
- package/dist/esm/common/constants/http.js +2 -0
- package/dist/esm/common/constants/http.js.map +1 -1
- package/dist/esm/modules/storage/base.d.ts +9 -4
- package/dist/esm/modules/storage/base.js +10 -4
- package/dist/esm/modules/storage/base.js.map +1 -1
- package/dist/esm/modules/storage/bun-s3/helper.d.ts +2 -3
- package/dist/esm/modules/storage/bun-s3/helper.js +6 -5
- package/dist/esm/modules/storage/bun-s3/helper.js.map +1 -1
- package/dist/esm/modules/storage/bun-s3/utility.d.ts +2 -1
- package/dist/esm/modules/storage/bun-s3/utility.js +4 -3
- package/dist/esm/modules/storage/bun-s3/utility.js.map +1 -1
- package/dist/esm/modules/storage/common/constants.d.ts +7 -0
- package/dist/esm/modules/storage/common/constants.js +5 -0
- package/dist/esm/modules/storage/common/constants.js.map +1 -1
- package/dist/esm/modules/storage/common/errors.d.ts +17 -0
- package/dist/esm/modules/storage/common/errors.js +14 -0
- package/dist/esm/modules/storage/common/errors.js.map +1 -1
- package/dist/esm/modules/storage/common/types.d.ts +17 -4
- package/dist/esm/modules/storage/common/types.js.map +1 -1
- package/dist/esm/modules/storage/disk/helper.d.ts +1 -0
- package/dist/esm/modules/storage/disk/helper.js +2 -1
- package/dist/esm/modules/storage/disk/helper.js.map +1 -1
- package/dist/esm/modules/uid/common/constants.d.ts +26 -0
- package/dist/esm/modules/uid/common/constants.js +27 -0
- package/dist/esm/modules/uid/common/constants.js.map +1 -1
- package/dist/esm/modules/uid/common/crc32.d.ts +22 -0
- package/dist/esm/modules/uid/common/crc32.js +39 -0
- package/dist/esm/modules/uid/common/crc32.js.map +1 -0
- package/dist/esm/modules/uid/common/random.d.ts +46 -0
- package/dist/esm/modules/uid/common/random.js +94 -0
- package/dist/esm/modules/uid/common/random.js.map +1 -0
- package/dist/esm/modules/uid/common/segments.d.ts +36 -0
- package/dist/esm/modules/uid/common/segments.js +81 -0
- package/dist/esm/modules/uid/common/segments.js.map +1 -0
- package/dist/esm/modules/uid/common/types.d.ts +45 -1
- package/dist/esm/modules/uid/common/types.js.map +1 -1
- package/dist/esm/modules/uid/index.d.ts +2 -0
- package/dist/esm/modules/uid/index.js +2 -0
- package/dist/esm/modules/uid/index.js.map +1 -1
- package/dist/esm/modules/uid/numeric.d.ts +18 -0
- package/dist/esm/modules/uid/numeric.js +31 -0
- package/dist/esm/modules/uid/numeric.js.map +1 -0
- package/dist/esm/modules/uid/opaque.d.ts +0 -15
- package/dist/esm/modules/uid/opaque.js +17 -107
- package/dist/esm/modules/uid/opaque.js.map +1 -1
- package/dist/esm/modules/uid/token.d.ts +57 -0
- package/dist/esm/modules/uid/token.js +218 -0
- package/dist/esm/modules/uid/token.js.map +1 -0
- package/dist/esm/modules/uid/uuid/helper.d.ts +2 -1
- package/dist/esm/modules/uid/uuid/helper.js +2 -1
- package/dist/esm/modules/uid/uuid/helper.js.map +1 -1
- package/dist/esm/utilities/parse.utility.d.ts +5 -0
- package/dist/esm/utilities/parse.utility.js +17 -1
- package/dist/esm/utilities/parse.utility.js.map +1 -1
- package/dist/esm/utilities/request.utility.d.ts +4 -0
- package/dist/esm/utilities/request.utility.js +10 -1
- package/dist/esm/utilities/request.utility.js.map +1 -1
- package/package.json +2 -2
|
@@ -58,7 +58,8 @@ export declare class S3SignatureUtility {
|
|
|
58
58
|
*/
|
|
59
59
|
static buildPostPolicy(opts: {
|
|
60
60
|
bucket: string;
|
|
61
|
-
|
|
61
|
+
/** The ONE key the form may be posted under. */
|
|
62
|
+
key: string;
|
|
62
63
|
maxBytes: number;
|
|
63
64
|
expiresInSeconds: number;
|
|
64
65
|
accessKey: string;
|
|
@@ -179,7 +179,7 @@ export class S3SignatureUtility {
|
|
|
179
179
|
* expressible at all.
|
|
180
180
|
*/
|
|
181
181
|
static async buildPostPolicy(opts) {
|
|
182
|
-
const { bucket,
|
|
182
|
+
const { bucket, key, maxBytes, expiresInSeconds, accessKey, secretKey, region, sessionToken, contentType, } = opts;
|
|
183
183
|
const now = new Date();
|
|
184
184
|
const { amzDate, dateStamp } = S3SignatureUtility.toAmzDate({ now });
|
|
185
185
|
const credentialScope = `${dateStamp}/${region}/s3/aws4_request`;
|
|
@@ -194,9 +194,9 @@ export class S3SignatureUtility {
|
|
|
194
194
|
};
|
|
195
195
|
const conditions = [
|
|
196
196
|
{ bucket },
|
|
197
|
-
|
|
197
|
+
{ key },
|
|
198
198
|
['content-length-range', 0, maxBytes],
|
|
199
|
-
...Object.entries(fields).map(([
|
|
199
|
+
...Object.entries(fields).map(([fieldName, fieldValue]) => ({ [fieldName]: fieldValue })),
|
|
200
200
|
...(contentType ? [{ 'Content-Type': contentType }] : []),
|
|
201
201
|
];
|
|
202
202
|
const policy = Buffer.from(JSON.stringify({ expiration: expiresAt, conditions })).toString('base64');
|
|
@@ -204,6 +204,7 @@ export class S3SignatureUtility {
|
|
|
204
204
|
const result = await S3SignatureUtility.hmacSHA256({ key: signingKey, data: policy });
|
|
205
205
|
return {
|
|
206
206
|
formData: {
|
|
207
|
+
key,
|
|
207
208
|
...fields,
|
|
208
209
|
...(contentType ? { 'Content-Type': contentType } : {}),
|
|
209
210
|
policy,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"utility.js","sourceRoot":"","sources":["../../../../../src/modules/storage/bun-s3/utility.ts"],"names":[],"mappings":"AAAA,8GAA8G;AAE9G,OAAO,EAAE,QAAQ,EAAE,MAAM,iBAAiB,CAAC;AAE3C,MAAM,OAAO,kBAAkB;IACrB,MAAM,CAAC,KAAK,CAAC,UAAU,CAAC,IAG/B;QACC,MAAM,EAAE,GAAG,EAAE,IAAI,EAAE,GAAG,IAAI,CAAC;QAC3B,MAAM,MAAM,GAAG,OAAO,GAAG,KAAK,QAAQ,CAAC,CAAC,CAAC,IAAI,WAAW,EAAE,CAAC,MAAM,CA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AAC;SAClE,CAAC;QACF,MAAM,oBAAoB,GAAG,kBAAkB,CAAC,yBAAyB,CAAC;YACxE,KAAK,EAAE,eAAe;SACvB,CAAC,CAAC;QAEH,wFAAwF;QACxF,MAAM,gBAAgB,GAAG;YACvB,MAAM;YACN,aAAa;YACb,oBAAoB;YACpB,UAAU,CAAC,GAAG,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC,GAAG,GAAG,IAAI,mBAAmB,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC,IAAI,CAAC,EAAE,CAAC;YACxE,aAAa;YACb,kBAAkB;SACnB,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;QAEb,MAAM,MAAM,GAAG,MAAM,kBAAkB,CAAC,SAAS,CAAC,EAAE,IAAI,EAAE,gBAAgB,EAAE,CAAC,CAAC;QAC9E,MAAM,YAAY,GAAG,CAAC,kBAAkB,EAAE,OAAO,EAAE,eAAe,EAAE,MAAM,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;QAEvF,MAAM,UAAU,GAAG,MAAM,kBAAkB,CAAC,gBAAgB,CAAC,EAAE,SAAS,EAAE,SAAS,EAAE,MAAM,EAAE,CAAC,CAAC;QAC/F,MAAM,OAAO,GAAG,MAAM,kBAAkB,CAAC,UAAU,CAAC,EAAE,GAAG,EAAE,UAAU,EAAE,IAAI,EAAE,YAAY,EAAE,CAAC,CAAC;QAC7F,MAAM,SAAS,GAAG,kBAAkB,CAAC,KAAK,CAAC,EAAE,KAAK,EAAE,OAAO,EAAE,CAAC,CAAC;QAE/D,OAAO,GAAG,MAAM,GAAG,aAAa,IAAI,oBAAoB,oBAAoB,SAAS,EAAE,CAAC;IAC1F,CAAC;CACF","sourcesContent":["// Minimal AWS Signature V4 helpers for bucket-management operations (object ops use Bun's S3Client natively).\n\nimport { getError } from '@/modules/error';\n\nexport class S3SignatureUtility {\n private static async hmacSHA256(opts: {\n key: Uint8Array<ArrayBuffer> | string;\n data: string;\n }): Promise<Uint8Array<ArrayBuffer>> {\n const { key, data } = opts;\n const rawKey = typeof key === 'string' ? new TextEncoder().encode(key) : key;\n const cryptoKey = await crypto.subtle.importKey(\n 'raw',\n rawKey,\n { name: 'HMAC', hash: 'SHA-256' },\n false,\n ['sign'],\n );\n const signature = await crypto.subtle.sign('HMAC', cryptoKey, new TextEncoder().encode(data));\n\n return new Uint8Array(signature);\n }\n\n private static toHex(opts: { bytes: Uint8Array }): string {\n return Array.from(opts.bytes)\n .map((byte) => byte.toString(16).padStart(2, '0'))\n .join('');\n }\n\n private static async sha256Hex(opts: { data: string }): Promise<string> {\n const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(opts.data));\n\n return S3SignatureUtility.toHex({ bytes: new Uint8Array(digest) });\n }\n\n /** SigV4 canonical form needs every reserved character `encodeURIComponent` leaves untouched also percent-encoded. */\n private static encodeSigV4Component(opts: { value: string }): string {\n return encodeURIComponent(opts.value).replace(\n /[!'()*]/g,\n (char) => `%${char.charCodeAt(0).toString(16).toUpperCase()}`,\n );\n }\n\n /** Signing the raw path answers 403 SignatureDoesNotMatch, because `fetch` encodes it on the wire. Separators stay literal. */\n private static encodeSigV4Path(opts: { path: string }): string {\n return opts.path\n .split('/')\n .map((segment) => S3SignatureUtility.encodeSigV4Component({ value: segment }))\n .join('/');\n }\n\n /** `x-amz-copy-source`: S3 URL-decodes it once and splits `?versionId=` off, so a raw `?`, `%` or `+` names another object and a non-Latin-1 key is not a legal header value. */\n static buildCopySource(opts: { bucket: string; key: string }): string {\n return S3SignatureUtility.encodeSigV4Path({ path: `/${opts.bucket}/${opts.key}` });\n }\n\n /** Empty or absent query must sign identically to today - callers of getBuckets/createBucket/removeBucket depend on it. */\n private static buildCanonicalQueryString(opts: { query?: Record<string, string> }): string {\n const { query } = opts;\n\n if (!query) {\n return '';\n }\n\n const keys = Object.keys(query);\n\n if (keys.length === 0) {\n return '';\n }\n\n return keys\n .sort()\n .map(\n (key) =>\n `${S3SignatureUtility.encodeSigV4Component({ value: key })}=${S3SignatureUtility.encodeSigV4Component({ value: query[key] })}`,\n )\n .join('&');\n }\n\n /** The SigV4 four-step chain. Each step keys the next, so the final key is bound to date, region and service. */\n private static async deriveSigningKey(opts: {\n secretKey: string;\n dateStamp: string;\n region: string;\n }): Promise<Uint8Array<ArrayBuffer>> {\n const { secretKey, dateStamp, region } = opts;\n const dateKey = await S3SignatureUtility.hmacSHA256({\n key: `AWS4${secretKey}`,\n data: dateStamp,\n });\n const regionKey = await S3SignatureUtility.hmacSHA256({ key: dateKey, data: region });\n const serviceKey = await S3SignatureUtility.hmacSHA256({ key: regionKey, data: 's3' });\n\n return S3SignatureUtility.hmacSHA256({ key: serviceKey, data: 'aws4_request' });\n }\n\n /** `20130524T000000Z` and its `20130524` prefix - the two forms every signature needs. */\n private static toAmzDate(opts: { now: Date }): { amzDate: string; dateStamp: string } {\n const amzDate = opts.now\n .toISOString()\n .replace(/[-:]/g, '')\n .replace(/\\.\\d{3}Z$/, 'Z');\n\n return { amzDate, dateStamp: amzDate.slice(0, 8) };\n }\n\n static async buildSignedRequest(opts: {\n method: string;\n endpoint: string;\n path: string;\n accessKey: string;\n secretKey: string;\n region: string;\n sessionToken?: string;\n body?: string;\n query?: Record<string, string>;\n /** Extra headers to SIGN, not merely to send - anything outside `SignedHeaders` is refused by S3. */\n headers?: Record<string, string>;\n }): Promise<{ url: string; headers: Record<string, string> }> {\n const {\n method,\n endpoint,\n path,\n accessKey,\n secretKey,\n region,\n sessionToken,\n body = '',\n query,\n headers: extraHeaders,\n } = opts;\n\n const { amzDate, dateStamp } = S3SignatureUtility.toAmzDate({ now: new Date() });\n\n const canonicalQueryString = S3SignatureUtility.buildCanonicalQueryString({ query });\n const canonicalPath = S3SignatureUtility.encodeSigV4Path({ path });\n const baseUrl = `${endpoint.replace(/\\/$/, '')}${canonicalPath}`;\n const url = canonicalQueryString ? `${baseUrl}?${canonicalQueryString}` : baseUrl;\n const host = new URL(endpoint).host;\n const payloadHash = await S3SignatureUtility.sha256Hex({ data: body });\n\n const canonicalHeadersMap: Record<string, string> = {\n host,\n 'x-amz-content-sha256': payloadHash,\n 'x-amz-date': amzDate,\n };\n\n if (sessionToken) {\n canonicalHeadersMap['x-amz-security-token'] = sessionToken;\n }\n\n const extraHeadersEntries = Object.entries(extraHeaders ?? {});\n\n for (const [key, value] of extraHeadersEntries) {\n canonicalHeadersMap[key.toLowerCase()] = value;\n }\n\n const sortedKeys = Object.keys(canonicalHeadersMap).sort();\n const canonicalHeaders = sortedKeys.map((k) => `${k}:${canonicalHeadersMap[k]}\\n`).join('');\n const signedHeaders = sortedKeys.join(';');\n\n const canonicalRequest = [\n method,\n canonicalPath,\n canonicalQueryString,\n canonicalHeaders,\n signedHeaders,\n payloadHash,\n ].join('\\n');\n\n const credentialScope = `${dateStamp}/${region}/s3/aws4_request`;\n const result = await S3SignatureUtility.sha256Hex({ data: canonicalRequest });\n const stringToSign = ['AWS4-HMAC-SHA256', amzDate, credentialScope, result].join('\\n');\n\n const signingKey = await S3SignatureUtility.deriveSigningKey({ secretKey, dateStamp, region });\n const result2 = await S3SignatureUtility.hmacSHA256({ key: signingKey, data: stringToSign });\n const signature = S3SignatureUtility.toHex({ bytes: result2 });\n\n const authHeader = `AWS4-HMAC-SHA256 Credential=${accessKey}/${credentialScope}, SignedHeaders=${signedHeaders}, Signature=${signature}`;\n const contentLength = String(new TextEncoder().encode(body).length);\n\n return {\n url,\n headers: {\n ...canonicalHeadersMap,\n Authorization: authHeader,\n 'Content-Length': contentLength,\n },\n };\n }\n\n private static escapeXmlText(opts: { value: string }): string {\n return opts.value\n .replace(/&/g, '&')\n .replace(/</g, '<')\n .replace(/>/g, '>')\n .replace(/\"/g, '"')\n .replace(/'/g, ''');\n }\n\n /** `&` decodes LAST - a literal `<` in the source text must not turn into `<` through the `&` step. */\n private static unescapeXmlText(opts: { value: string }): string {\n return opts.value\n .replace(/</g, '<')\n .replace(/>/g, '>')\n .replace(/"/g, '\"')\n .replace(/'/g, \"'\")\n .replace(/&/g, '&');\n }\n\n /** S3's PUT tagging body - no XML dependency, so this is hand-built rather than templated by a library. */\n static buildTaggingXml(opts: { tags: Record<string, string> }): string {\n const tagEntries = Object.entries(opts.tags)\n .map(\n ([key, value]) =>\n `<Tag><Key>${S3SignatureUtility.escapeXmlText({ value: key })}</Key><Value>${S3SignatureUtility.escapeXmlText({ value })}</Value></Tag>`,\n )\n .join('');\n\n return `<Tagging><TagSet>${tagEntries}</TagSet></Tagging>`;\n }\n\n /** The `x-amz-tagging` header: a URL-encoded query string, unlike the XML the tagging API takes. */\n static buildTaggingHeader(opts: { tags: Record<string, string> }): string {\n return Object.entries(opts.tags)\n .map(\n ([key, value]) =>\n `${S3SignatureUtility.encodeSigV4Component({ value: key })}=${S3SignatureUtility.encodeSigV4Component({ value })}`,\n )\n .join('&');\n }\n\n /** S3's GET tagging response - hand-parsed rather than a full XML parser; throws rather than returning a half-parsed object. */\n static parseTaggingXml(opts: { xml: string }): Record<string, string> {\n const { xml } = opts;\n const trimmed = xml.trim();\n\n if (/<TagSet\\s*\\/>/.test(trimmed) || /<TagSet>\\s*<\\/TagSet>/.test(trimmed)) {\n return {};\n }\n\n const tagSetMatch = trimmed.match(/<TagSet>([\\s\\S]*?)<\\/TagSet>/);\n\n if (!tagSetMatch) {\n throw getError({ message: `[parseTaggingXml] Malformed tagging response | body: ${xml}` });\n }\n\n const tags: Record<string, string> = {};\n const tagMatches = tagSetMatch[1].matchAll(/<Tag>([\\s\\S]*?)<\\/Tag>/g);\n\n for (const tagMatch of tagMatches) {\n const keyMatch = tagMatch[1].match(/<Key>([\\s\\S]*?)<\\/Key>/);\n const valueMatch = tagMatch[1].match(/<Value>([\\s\\S]*?)<\\/Value>/);\n\n if (!keyMatch || !valueMatch) {\n throw getError({ message: `[parseTaggingXml] Malformed tag entry | body: ${xml}` });\n }\n\n const key = S3SignatureUtility.unescapeXmlText({ value: keyMatch[1].trim() });\n const value = S3SignatureUtility.unescapeXmlText({ value: valueMatch[1].trim() });\n tags[key] = value;\n }\n\n return tags;\n }\n\n /**\n * A signed POST policy: the form a browser posts straight to S3.\n *\n * This is not a presigned PUT and the difference is the point. A signed PUT binds each header to an\n * EXACT value, so `content-length` names one byte count and never a ceiling - every retry or\n * re-encode becomes an opaque 403. A policy carries `content-length-range`, so \"at most N bytes\" is\n * expressible at all.\n */\n static async buildPostPolicy(opts: {\n bucket: string;\n keyPrefix: string;\n maxBytes: number;\n expiresInSeconds: number;\n accessKey: string;\n secretKey: string;\n region: string;\n sessionToken?: string;\n contentType?: string;\n }): Promise<{ formData: Record<string, string>; expiresAt: string }> {\n const {\n bucket,\n keyPrefix,\n maxBytes,\n expiresInSeconds,\n accessKey,\n secretKey,\n region,\n sessionToken,\n contentType,\n } = opts;\n\n const now = new Date();\n const { amzDate, dateStamp } = S3SignatureUtility.toAmzDate({ now });\n const credentialScope = `${dateStamp}/${region}/s3/aws4_request`;\n const credential = `${accessKey}/${credentialScope}`;\n const expiresAt = new Date(now.getTime() + expiresInSeconds * 1000).toISOString();\n\n // Every field the browser posts must ALSO be a condition, or S3 refuses the form it just signed.\n const fields: Record<string, string> = {\n 'x-amz-algorithm': 'AWS4-HMAC-SHA256',\n 'x-amz-credential': credential,\n 'x-amz-date': amzDate,\n ...(sessionToken ? { 'x-amz-security-token': sessionToken } : {}),\n };\n\n const conditions: unknown[] = [\n { bucket },\n ['starts-with', '$key', keyPrefix],\n ['content-length-range', 0, maxBytes],\n ...Object.entries(fields).map(([key, value]) => ({ [key]: value })),\n ...(contentType ? [{ 'Content-Type': contentType }] : []),\n ];\n\n const policy = Buffer.from(JSON.stringify({ expiration: expiresAt, conditions })).toString(\n 'base64',\n );\n\n const signingKey = await S3SignatureUtility.deriveSigningKey({ secretKey, dateStamp, region });\n\n const result = await S3SignatureUtility.hmacSHA256({ key: signingKey, data: policy });\n\n return {\n formData: {\n ...fields,\n ...(contentType ? { 'Content-Type': contentType } : {}),\n policy,\n 'x-amz-signature': S3SignatureUtility.toHex({ bytes: result }),\n },\n expiresAt,\n };\n }\n\n /**\n * A presigned URL: the credential travels in the QUERY, so a browser needs no `Authorization` header.\n *\n * `headers` is what `S3Client.presign` cannot do. Anything named there is inside the signature and\n * listed in `X-Amz-SignedHeaders`, so the client must send it back byte for byte. A signature\n * expresses equality and nothing else, so a pinned `content-length` rejects every retry at another\n * size; for a ceiling, use {@link S3SignatureUtility.buildPostPolicy}.\n */\n static async buildPresignedUrl(opts: {\n method: string;\n endpoint: string;\n path: string;\n accessKey: string;\n secretKey: string;\n region: string;\n sessionToken?: string;\n expiresInSeconds: number;\n /** Headers to SIGN. The client must send each one unchanged, or S3 answers 403. */\n headers?: Record<string, string>;\n /** A fixed clock, so a signature can be checked against a published test vector. */\n now?: Date;\n }): Promise<string> {\n const {\n method,\n endpoint,\n path,\n accessKey,\n secretKey,\n region,\n sessionToken,\n expiresInSeconds,\n headers,\n now = new Date(),\n } = opts;\n\n const { amzDate, dateStamp } = S3SignatureUtility.toAmzDate({ now });\n const credentialScope = `${dateStamp}/${region}/s3/aws4_request`;\n const canonicalPath = S3SignatureUtility.encodeSigV4Path({ path });\n const origin = endpoint.replace(/\\/$/, '');\n\n // SigV4 compares header values after trimming, so signing an untrimmed one answers 403.\n const canonicalHeadersMap: Record<string, string> = { host: new URL(origin).host };\n const signedEntries = Object.entries(headers ?? {});\n\n for (const [key, value] of signedEntries) {\n canonicalHeadersMap[key.toLowerCase()] = String(value).trim();\n }\n\n const sortedKeys = Object.keys(canonicalHeadersMap).sort();\n const signedHeaders = sortedKeys.join(';');\n\n // `X-Amz-SignedHeaders` is itself signed, so the header list has to be settled before the query.\n const queryParameters: Record<string, string> = {\n 'X-Amz-Algorithm': 'AWS4-HMAC-SHA256',\n 'X-Amz-Credential': `${accessKey}/${credentialScope}`,\n 'X-Amz-Date': amzDate,\n 'X-Amz-Expires': String(expiresInSeconds),\n 'X-Amz-SignedHeaders': signedHeaders,\n ...(sessionToken ? { 'X-Amz-Security-Token': sessionToken } : {}),\n };\n const canonicalQueryString = S3SignatureUtility.buildCanonicalQueryString({\n query: queryParameters,\n });\n\n // A presigned URL is signed before its body exists, so the payload is excluded by name.\n const canonicalRequest = [\n method,\n canonicalPath,\n canonicalQueryString,\n sortedKeys.map((key) => `${key}:${canonicalHeadersMap[key]}\\n`).join(''),\n signedHeaders,\n 'UNSIGNED-PAYLOAD',\n ].join('\\n');\n\n const result = await S3SignatureUtility.sha256Hex({ data: canonicalRequest });\n const stringToSign = ['AWS4-HMAC-SHA256', amzDate, credentialScope, result].join('\\n');\n\n const signingKey = await S3SignatureUtility.deriveSigningKey({ secretKey, dateStamp, region });\n const result2 = await S3SignatureUtility.hmacSHA256({ key: signingKey, data: stringToSign });\n const signature = S3SignatureUtility.toHex({ bytes: result2 });\n\n return `${origin}${canonicalPath}?${canonicalQueryString}&X-Amz-Signature=${signature}`;\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"utility.js","sourceRoot":"","sources":["../../../../../src/modules/storage/bun-s3/utility.ts"],"names":[],"mappings":"AAAA,8GAA8G;AAE9G,OAAO,EAAE,QAAQ,EAAE,MAAM,iBAAiB,CAAC;AAE3C,MAAM,OAAO,kBAAkB;IACrB,MAAM,CAAC,KAAK,CAAC,UAAU,CAAC,IAG/B;QACC,MAAM,EAAE,GAAG,EAAE,IAAI,EAAE,GAAG,IAAI,CAAC;QAC3B,MAAM,MAAM,GAAG,OAAO,GAAG,KAAK,QAAQ,CAAC,CAAC,CAAC,IAAI,WAAW,EAAE,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC;QAC7E,MAAM,SAAS,GAAG,MAAM,MAAM,CAAC,MAAM,CAAC,SAAS,CAC7C,KAAK,EACL,MAAM,EACN,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,SAAS,EAAE,EACjC,KAAK,EACL,CAAC,MAAM,CAAC,CACT,CAAC;QACF,MAAM,SAAS,GAAG,MAAM,MAAM,CAAC,MAAM,CAAC,IAAI,CAAC,MAAM,EAAE,S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AE,CAAC;YACxE,aAAa;YACb,kBAAkB;SACnB,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;QAEb,MAAM,MAAM,GAAG,MAAM,kBAAkB,CAAC,SAAS,CAAC,EAAE,IAAI,EAAE,gBAAgB,EAAE,CAAC,CAAC;QAC9E,MAAM,YAAY,GAAG,CAAC,kBAAkB,EAAE,OAAO,EAAE,eAAe,EAAE,MAAM,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;QAEvF,MAAM,UAAU,GAAG,MAAM,kBAAkB,CAAC,gBAAgB,CAAC,EAAE,SAAS,EAAE,SAAS,EAAE,MAAM,EAAE,CAAC,CAAC;QAC/F,MAAM,OAAO,GAAG,MAAM,kBAAkB,CAAC,UAAU,CAAC,EAAE,GAAG,EAAE,UAAU,EAAE,IAAI,EAAE,YAAY,EAAE,CAAC,CAAC;QAC7F,MAAM,SAAS,GAAG,kBAAkB,CAAC,KAAK,CAAC,EAAE,KAAK,EAAE,OAAO,EAAE,CAAC,CAAC;QAE/D,OAAO,GAAG,MAAM,GAAG,aAAa,IAAI,oBAAoB,oBAAoB,SAAS,EAAE,CAAC;IAC1F,CAAC;CACF","sourcesContent":["// Minimal AWS Signature V4 helpers for bucket-management operations (object ops use Bun's S3Client natively).\n\nimport { getError } from '@/modules/error';\n\nexport class S3SignatureUtility {\n private static async hmacSHA256(opts: {\n key: Uint8Array<ArrayBuffer> | string;\n data: string;\n }): Promise<Uint8Array<ArrayBuffer>> {\n const { key, data } = opts;\n const rawKey = typeof key === 'string' ? new TextEncoder().encode(key) : key;\n const cryptoKey = await crypto.subtle.importKey(\n 'raw',\n rawKey,\n { name: 'HMAC', hash: 'SHA-256' },\n false,\n ['sign'],\n );\n const signature = await crypto.subtle.sign('HMAC', cryptoKey, new TextEncoder().encode(data));\n\n return new Uint8Array(signature);\n }\n\n private static toHex(opts: { bytes: Uint8Array }): string {\n return Array.from(opts.bytes)\n .map((byte) => byte.toString(16).padStart(2, '0'))\n .join('');\n }\n\n private static async sha256Hex(opts: { data: string }): Promise<string> {\n const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(opts.data));\n\n return S3SignatureUtility.toHex({ bytes: new Uint8Array(digest) });\n }\n\n /** SigV4 canonical form needs every reserved character `encodeURIComponent` leaves untouched also percent-encoded. */\n private static encodeSigV4Component(opts: { value: string }): string {\n return encodeURIComponent(opts.value).replace(\n /[!'()*]/g,\n (char) => `%${char.charCodeAt(0).toString(16).toUpperCase()}`,\n );\n }\n\n /** Signing the raw path answers 403 SignatureDoesNotMatch, because `fetch` encodes it on the wire. Separators stay literal. */\n private static encodeSigV4Path(opts: { path: string }): string {\n return opts.path\n .split('/')\n .map((segment) => S3SignatureUtility.encodeSigV4Component({ value: segment }))\n .join('/');\n }\n\n /** `x-amz-copy-source`: S3 URL-decodes it once and splits `?versionId=` off, so a raw `?`, `%` or `+` names another object and a non-Latin-1 key is not a legal header value. */\n static buildCopySource(opts: { bucket: string; key: string }): string {\n return S3SignatureUtility.encodeSigV4Path({ path: `/${opts.bucket}/${opts.key}` });\n }\n\n /** Empty or absent query must sign identically to today - callers of getBuckets/createBucket/removeBucket depend on it. */\n private static buildCanonicalQueryString(opts: { query?: Record<string, string> }): string {\n const { query } = opts;\n\n if (!query) {\n return '';\n }\n\n const keys = Object.keys(query);\n\n if (keys.length === 0) {\n return '';\n }\n\n return keys\n .sort()\n .map(\n (key) =>\n `${S3SignatureUtility.encodeSigV4Component({ value: key })}=${S3SignatureUtility.encodeSigV4Component({ value: query[key] })}`,\n )\n .join('&');\n }\n\n /** The SigV4 four-step chain. Each step keys the next, so the final key is bound to date, region and service. */\n private static async deriveSigningKey(opts: {\n secretKey: string;\n dateStamp: string;\n region: string;\n }): Promise<Uint8Array<ArrayBuffer>> {\n const { secretKey, dateStamp, region } = opts;\n const dateKey = await S3SignatureUtility.hmacSHA256({\n key: `AWS4${secretKey}`,\n data: dateStamp,\n });\n const regionKey = await S3SignatureUtility.hmacSHA256({ key: dateKey, data: region });\n const serviceKey = await S3SignatureUtility.hmacSHA256({ key: regionKey, data: 's3' });\n\n return S3SignatureUtility.hmacSHA256({ key: serviceKey, data: 'aws4_request' });\n }\n\n /** `20130524T000000Z` and its `20130524` prefix - the two forms every signature needs. */\n private static toAmzDate(opts: { now: Date }): { amzDate: string; dateStamp: string } {\n const amzDate = opts.now\n .toISOString()\n .replace(/[-:]/g, '')\n .replace(/\\.\\d{3}Z$/, 'Z');\n\n return { amzDate, dateStamp: amzDate.slice(0, 8) };\n }\n\n static async buildSignedRequest(opts: {\n method: string;\n endpoint: string;\n path: string;\n accessKey: string;\n secretKey: string;\n region: string;\n sessionToken?: string;\n body?: string;\n query?: Record<string, string>;\n /** Extra headers to SIGN, not merely to send - anything outside `SignedHeaders` is refused by S3. */\n headers?: Record<string, string>;\n }): Promise<{ url: string; headers: Record<string, string> }> {\n const {\n method,\n endpoint,\n path,\n accessKey,\n secretKey,\n region,\n sessionToken,\n body = '',\n query,\n headers: extraHeaders,\n } = opts;\n\n const { amzDate, dateStamp } = S3SignatureUtility.toAmzDate({ now: new Date() });\n\n const canonicalQueryString = S3SignatureUtility.buildCanonicalQueryString({ query });\n const canonicalPath = S3SignatureUtility.encodeSigV4Path({ path });\n const baseUrl = `${endpoint.replace(/\\/$/, '')}${canonicalPath}`;\n const url = canonicalQueryString ? `${baseUrl}?${canonicalQueryString}` : baseUrl;\n const host = new URL(endpoint).host;\n const payloadHash = await S3SignatureUtility.sha256Hex({ data: body });\n\n const canonicalHeadersMap: Record<string, string> = {\n host,\n 'x-amz-content-sha256': payloadHash,\n 'x-amz-date': amzDate,\n };\n\n if (sessionToken) {\n canonicalHeadersMap['x-amz-security-token'] = sessionToken;\n }\n\n const extraHeadersEntries = Object.entries(extraHeaders ?? {});\n\n for (const [key, value] of extraHeadersEntries) {\n canonicalHeadersMap[key.toLowerCase()] = value;\n }\n\n const sortedKeys = Object.keys(canonicalHeadersMap).sort();\n const canonicalHeaders = sortedKeys.map((k) => `${k}:${canonicalHeadersMap[k]}\\n`).join('');\n const signedHeaders = sortedKeys.join(';');\n\n const canonicalRequest = [\n method,\n canonicalPath,\n canonicalQueryString,\n canonicalHeaders,\n signedHeaders,\n payloadHash,\n ].join('\\n');\n\n const credentialScope = `${dateStamp}/${region}/s3/aws4_request`;\n const result = await S3SignatureUtility.sha256Hex({ data: canonicalRequest });\n const stringToSign = ['AWS4-HMAC-SHA256', amzDate, credentialScope, result].join('\\n');\n\n const signingKey = await S3SignatureUtility.deriveSigningKey({ secretKey, dateStamp, region });\n const result2 = await S3SignatureUtility.hmacSHA256({ key: signingKey, data: stringToSign });\n const signature = S3SignatureUtility.toHex({ bytes: result2 });\n\n const authHeader = `AWS4-HMAC-SHA256 Credential=${accessKey}/${credentialScope}, SignedHeaders=${signedHeaders}, Signature=${signature}`;\n const contentLength = String(new TextEncoder().encode(body).length);\n\n return {\n url,\n headers: {\n ...canonicalHeadersMap,\n Authorization: authHeader,\n 'Content-Length': contentLength,\n },\n };\n }\n\n private static escapeXmlText(opts: { value: string }): string {\n return opts.value\n .replace(/&/g, '&')\n .replace(/</g, '<')\n .replace(/>/g, '>')\n .replace(/\"/g, '"')\n .replace(/'/g, ''');\n }\n\n /** `&` decodes LAST - a literal `<` in the source text must not turn into `<` through the `&` step. */\n private static unescapeXmlText(opts: { value: string }): string {\n return opts.value\n .replace(/</g, '<')\n .replace(/>/g, '>')\n .replace(/"/g, '\"')\n .replace(/'/g, \"'\")\n .replace(/&/g, '&');\n }\n\n /** S3's PUT tagging body - no XML dependency, so this is hand-built rather than templated by a library. */\n static buildTaggingXml(opts: { tags: Record<string, string> }): string {\n const tagEntries = Object.entries(opts.tags)\n .map(\n ([key, value]) =>\n `<Tag><Key>${S3SignatureUtility.escapeXmlText({ value: key })}</Key><Value>${S3SignatureUtility.escapeXmlText({ value })}</Value></Tag>`,\n )\n .join('');\n\n return `<Tagging><TagSet>${tagEntries}</TagSet></Tagging>`;\n }\n\n /** The `x-amz-tagging` header: a URL-encoded query string, unlike the XML the tagging API takes. */\n static buildTaggingHeader(opts: { tags: Record<string, string> }): string {\n return Object.entries(opts.tags)\n .map(\n ([key, value]) =>\n `${S3SignatureUtility.encodeSigV4Component({ value: key })}=${S3SignatureUtility.encodeSigV4Component({ value })}`,\n )\n .join('&');\n }\n\n /** S3's GET tagging response - hand-parsed rather than a full XML parser; throws rather than returning a half-parsed object. */\n static parseTaggingXml(opts: { xml: string }): Record<string, string> {\n const { xml } = opts;\n const trimmed = xml.trim();\n\n if (/<TagSet\\s*\\/>/.test(trimmed) || /<TagSet>\\s*<\\/TagSet>/.test(trimmed)) {\n return {};\n }\n\n const tagSetMatch = trimmed.match(/<TagSet>([\\s\\S]*?)<\\/TagSet>/);\n\n if (!tagSetMatch) {\n throw getError({ message: `[parseTaggingXml] Malformed tagging response | body: ${xml}` });\n }\n\n const tags: Record<string, string> = {};\n const tagMatches = tagSetMatch[1].matchAll(/<Tag>([\\s\\S]*?)<\\/Tag>/g);\n\n for (const tagMatch of tagMatches) {\n const keyMatch = tagMatch[1].match(/<Key>([\\s\\S]*?)<\\/Key>/);\n const valueMatch = tagMatch[1].match(/<Value>([\\s\\S]*?)<\\/Value>/);\n\n if (!keyMatch || !valueMatch) {\n throw getError({ message: `[parseTaggingXml] Malformed tag entry | body: ${xml}` });\n }\n\n const key = S3SignatureUtility.unescapeXmlText({ value: keyMatch[1].trim() });\n const value = S3SignatureUtility.unescapeXmlText({ value: valueMatch[1].trim() });\n tags[key] = value;\n }\n\n return tags;\n }\n\n /**\n * A signed POST policy: the form a browser posts straight to S3.\n *\n * This is not a presigned PUT and the difference is the point. A signed PUT binds each header to an\n * EXACT value, so `content-length` names one byte count and never a ceiling - every retry or\n * re-encode becomes an opaque 403. A policy carries `content-length-range`, so \"at most N bytes\" is\n * expressible at all.\n */\n static async buildPostPolicy(opts: {\n bucket: string;\n /** The ONE key the form may be posted under. */\n key: string;\n maxBytes: number;\n expiresInSeconds: number;\n accessKey: string;\n secretKey: string;\n region: string;\n sessionToken?: string;\n contentType?: string;\n }): Promise<{ formData: Record<string, string>; expiresAt: string }> {\n const {\n bucket,\n key,\n maxBytes,\n expiresInSeconds,\n accessKey,\n secretKey,\n region,\n sessionToken,\n contentType,\n } = opts;\n\n const now = new Date();\n const { amzDate, dateStamp } = S3SignatureUtility.toAmzDate({ now });\n const credentialScope = `${dateStamp}/${region}/s3/aws4_request`;\n const credential = `${accessKey}/${credentialScope}`;\n const expiresAt = new Date(now.getTime() + expiresInSeconds * 1000).toISOString();\n\n // Every field the browser posts must ALSO be a condition, or S3 refuses the form it just signed.\n const fields: Record<string, string> = {\n 'x-amz-algorithm': 'AWS4-HMAC-SHA256',\n 'x-amz-credential': credential,\n 'x-amz-date': amzDate,\n ...(sessionToken ? { 'x-amz-security-token': sessionToken } : {}),\n };\n\n const conditions: unknown[] = [\n { bucket },\n { key },\n ['content-length-range', 0, maxBytes],\n ...Object.entries(fields).map(([fieldName, fieldValue]) => ({ [fieldName]: fieldValue })),\n ...(contentType ? [{ 'Content-Type': contentType }] : []),\n ];\n\n const policy = Buffer.from(JSON.stringify({ expiration: expiresAt, conditions })).toString(\n 'base64',\n );\n\n const signingKey = await S3SignatureUtility.deriveSigningKey({ secretKey, dateStamp, region });\n\n const result = await S3SignatureUtility.hmacSHA256({ key: signingKey, data: policy });\n\n return {\n formData: {\n key,\n ...fields,\n ...(contentType ? { 'Content-Type': contentType } : {}),\n policy,\n 'x-amz-signature': S3SignatureUtility.toHex({ bytes: result }),\n },\n expiresAt,\n };\n }\n\n /**\n * A presigned URL: the credential travels in the QUERY, so a browser needs no `Authorization` header.\n *\n * `headers` is what `S3Client.presign` cannot do. Anything named there is inside the signature and\n * listed in `X-Amz-SignedHeaders`, so the client must send it back byte for byte. A signature\n * expresses equality and nothing else, so a pinned `content-length` rejects every retry at another\n * size; for a ceiling, use {@link S3SignatureUtility.buildPostPolicy}.\n */\n static async buildPresignedUrl(opts: {\n method: string;\n endpoint: string;\n path: string;\n accessKey: string;\n secretKey: string;\n region: string;\n sessionToken?: string;\n expiresInSeconds: number;\n /** Headers to SIGN. The client must send each one unchanged, or S3 answers 403. */\n headers?: Record<string, string>;\n /** A fixed clock, so a signature can be checked against a published test vector. */\n now?: Date;\n }): Promise<string> {\n const {\n method,\n endpoint,\n path,\n accessKey,\n secretKey,\n region,\n sessionToken,\n expiresInSeconds,\n headers,\n now = new Date(),\n } = opts;\n\n const { amzDate, dateStamp } = S3SignatureUtility.toAmzDate({ now });\n const credentialScope = `${dateStamp}/${region}/s3/aws4_request`;\n const canonicalPath = S3SignatureUtility.encodeSigV4Path({ path });\n const origin = endpoint.replace(/\\/$/, '');\n\n // SigV4 compares header values after trimming, so signing an untrimmed one answers 403.\n const canonicalHeadersMap: Record<string, string> = { host: new URL(origin).host };\n const signedEntries = Object.entries(headers ?? {});\n\n for (const [key, value] of signedEntries) {\n canonicalHeadersMap[key.toLowerCase()] = String(value).trim();\n }\n\n const sortedKeys = Object.keys(canonicalHeadersMap).sort();\n const signedHeaders = sortedKeys.join(';');\n\n // `X-Amz-SignedHeaders` is itself signed, so the header list has to be settled before the query.\n const queryParameters: Record<string, string> = {\n 'X-Amz-Algorithm': 'AWS4-HMAC-SHA256',\n 'X-Amz-Credential': `${accessKey}/${credentialScope}`,\n 'X-Amz-Date': amzDate,\n 'X-Amz-Expires': String(expiresInSeconds),\n 'X-Amz-SignedHeaders': signedHeaders,\n ...(sessionToken ? { 'X-Amz-Security-Token': sessionToken } : {}),\n };\n const canonicalQueryString = S3SignatureUtility.buildCanonicalQueryString({\n query: queryParameters,\n });\n\n // A presigned URL is signed before its body exists, so the payload is excluded by name.\n const canonicalRequest = [\n method,\n canonicalPath,\n canonicalQueryString,\n sortedKeys.map((key) => `${key}:${canonicalHeadersMap[key]}\\n`).join(''),\n signedHeaders,\n 'UNSIGNED-PAYLOAD',\n ].join('\\n');\n\n const result = await S3SignatureUtility.sha256Hex({ data: canonicalRequest });\n const stringToSign = ['AWS4-HMAC-SHA256', amzDate, credentialScope, result].join('\\n');\n\n const signingKey = await S3SignatureUtility.deriveSigningKey({ secretKey, dateStamp, region });\n const result2 = await S3SignatureUtility.hmacSHA256({ key: signingKey, data: stringToSign });\n const signature = S3SignatureUtility.toHex({ bytes: result2 });\n\n return `${origin}${canonicalPath}?${canonicalQueryString}&X-Amz-Signature=${signature}`;\n }\n}\n"]}
|
|
@@ -1,4 +1,11 @@
|
|
|
1
1
|
import { type IDuration, type TConstValue } from '../../../common/index.js';
|
|
2
|
+
/** The backend a storage helper writes to. A helper declares its own, so a caller never tells one apart with `instanceof`. */
|
|
3
|
+
export declare class StorageTypes {
|
|
4
|
+
static readonly DISK = "disk";
|
|
5
|
+
static readonly BUN_S3 = "bun-s3";
|
|
6
|
+
}
|
|
7
|
+
/** One of the `StorageTypes` values. */
|
|
8
|
+
export type TStorageType = TConstValue<typeof StorageTypes>;
|
|
2
9
|
/** Presign expiry defaults - a PUT or a POST form carries a file and needs more time; a GET is a redirect. */
|
|
3
10
|
export declare class StoragePresignDefaults {
|
|
4
11
|
static readonly PUT_EXPIRES_IN: IDuration;
|
|
@@ -1,4 +1,9 @@
|
|
|
1
1
|
import { DurationUnits } from '../../../common/index.js';
|
|
2
|
+
/** The backend a storage helper writes to. A helper declares its own, so a caller never tells one apart with `instanceof`. */
|
|
3
|
+
export class StorageTypes {
|
|
4
|
+
static { this.DISK = 'disk'; }
|
|
5
|
+
static { this.BUN_S3 = 'bun-s3'; }
|
|
6
|
+
}
|
|
2
7
|
/** Presign expiry defaults - a PUT or a POST form carries a file and needs more time; a GET is a redirect. */
|
|
3
8
|
export class StoragePresignDefaults {
|
|
4
9
|
static { this.PUT_EXPIRES_IN = { unit: DurationUnits.MINUTE, value: 10 }; }
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"constants.js","sourceRoot":"","sources":["../../../../../src/modules/storage/common/constants.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAoC,MAAM,UAAU,CAAC;AAE3E,8GAA8G;AAC9G,MAAM,OAAO,sBAAsB;aACjB,mBAAc,GAAc,EAAE,IAAI,EAAE,aAAa,CAAC,MAAM,EAAE,KAAK,EAAE,EAAE,EAAE,CAAC;aACtE,mBAAc,GAAc,EAAE,IAAI,EAAE,aAAa,CAAC,MAAM,EAAE,KAAK,EAAE,CAAC,EAAE,CAAC;IAErF,yFAAyF;aACzE,oBAAe,GAAc,EAAE,IAAI,EAAE,aAAa,CAAC,MAAM,EAAE,KAAK,EAAE,EAAE,EAAE,CAAC;;AAGzF,kEAAkE;AAClE,MAAM,OAAO,oBAAoB;aACf,2BAAsB,GAAG,CAAC,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,CAAC;;AAG5D,sFAAsF;AACtF,MAAM,OAAO,kBAAkB;aACb,kBAAa,GAAG,EAAE,CAAC;;AAGrC,uJAAuJ;AACvJ,MAAM,OAAO,WAAW;IACtB,qFAAqF;aACrE,WAAM,GAAG,QAAQ,CAAC;IAElC,sEAAsE;aACtD,YAAO,GAAG,SAAS,CAAC;aAEpB,eAAU,GAAG,IAAI,GAAG,CAAS,CAAC,IAAI,CAAC,MAAM,EAAE,IAAI,CAAC,OAAO,CAAC,CAAC,CAAC;IAE1E,MAAM,CAAC,OAAO,CAAC,QAAgB;QAC7B,OAAO,IAAI,CAAC,UAAU,CAAC,GAAG,CAAC,QAAQ,CAAC,CAAC;IACvC,CAAC","sourcesContent":["import { DurationUnits, type IDuration, type TConstValue } from '@/common';\n\n/** Presign expiry defaults - a PUT or a POST form carries a file and needs more time; a GET is a redirect. */\nexport class StoragePresignDefaults {\n static readonly PUT_EXPIRES_IN: IDuration = { unit: DurationUnits.MINUTE, value: 10 };\n static readonly GET_EXPIRES_IN: IDuration = { unit: DurationUnits.MINUTE, value: 1 };\n\n /** A browser upload form: the user has to pick the file and the bytes have to travel. */\n static readonly POST_EXPIRES_IN: IDuration = { unit: DurationUnits.MINUTE, value: 15 };\n}\n\n/** SigV4 refuses a presigned URL valid for longer than 7 days. */\nexport class StoragePresignLimits {\n static readonly MAX_EXPIRES_IN_SECONDS = 7 * 24 * 60 * 60;\n}\n\n/** Concurrent object operations. Unbounded exhausts sockets and gets rate limited. */\nexport class StorageConcurrency {\n static readonly DEFAULT_LIMIT = 16;\n}\n\n/** Which host a signed artifact names. `host` is inside every SigV4 signature, so this is decided at signing time and cannot be patched afterwards. */\nexport class S3Audiences {\n /** The host THIS process talks to: every bucket operation, copy and tagging call. */\n static readonly SERVER = 'server';\n\n /** The host a BROWSER is handed: presigned URLs and POST policies. */\n static readonly BROWSER = 'browser';\n\n static readonly SCHEME_SET = new Set<string>([this.SERVER, this.BROWSER]);\n\n static isValid(audience: string): boolean {\n return this.SCHEME_SET.has(audience);\n }\n}\n\n/** The host a signed artifact names: `server` (the host this process talks to) or `browser` (the host a browser is handed). */\nexport type TS3Audience = TConstValue<typeof S3Audiences>;\n"]}
|
|
1
|
+
{"version":3,"file":"constants.js","sourceRoot":"","sources":["../../../../../src/modules/storage/common/constants.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAoC,MAAM,UAAU,CAAC;AAE3E,8HAA8H;AAC9H,MAAM,OAAO,YAAY;aACP,SAAI,GAAG,MAAM,CAAC;aACd,WAAM,GAAG,QAAQ,CAAC;;AAMpC,8GAA8G;AAC9G,MAAM,OAAO,sBAAsB;aACjB,mBAAc,GAAc,EAAE,IAAI,EAAE,aAAa,CAAC,MAAM,EAAE,KAAK,EAAE,EAAE,EAAE,CAAC;aACtE,mBAAc,GAAc,EAAE,IAAI,EAAE,aAAa,CAAC,MAAM,EAAE,KAAK,EAAE,CAAC,EAAE,CAAC;IAErF,yFAAyF;aACzE,oBAAe,GAAc,EAAE,IAAI,EAAE,aAAa,CAAC,MAAM,EAAE,KAAK,EAAE,EAAE,EAAE,CAAC;;AAGzF,kEAAkE;AAClE,MAAM,OAAO,oBAAoB;aACf,2BAAsB,GAAG,CAAC,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,CAAC;;AAG5D,sFAAsF;AACtF,MAAM,OAAO,kBAAkB;aACb,kBAAa,GAAG,EAAE,CAAC;;AAGrC,uJAAuJ;AACvJ,MAAM,OAAO,WAAW;IACtB,qFAAqF;aACrE,WAAM,GAAG,QAAQ,CAAC;IAElC,sEAAsE;aACtD,YAAO,GAAG,SAAS,CAAC;aAEpB,eAAU,GAAG,IAAI,GAAG,CAAS,CAAC,IAAI,CAAC,MAAM,EAAE,IAAI,CAAC,OAAO,CAAC,CAAC,CAAC;IAE1E,MAAM,CAAC,OAAO,CAAC,QAAgB;QAC7B,OAAO,IAAI,CAAC,UAAU,CAAC,GAAG,CAAC,QAAQ,CAAC,CAAC;IACvC,CAAC","sourcesContent":["import { DurationUnits, type IDuration, type TConstValue } from '@/common';\n\n/** The backend a storage helper writes to. A helper declares its own, so a caller never tells one apart with `instanceof`. */\nexport class StorageTypes {\n static readonly DISK = 'disk';\n static readonly BUN_S3 = 'bun-s3';\n}\n\n/** One of the `StorageTypes` values. */\nexport type TStorageType = TConstValue<typeof StorageTypes>;\n\n/** Presign expiry defaults - a PUT or a POST form carries a file and needs more time; a GET is a redirect. */\nexport class StoragePresignDefaults {\n static readonly PUT_EXPIRES_IN: IDuration = { unit: DurationUnits.MINUTE, value: 10 };\n static readonly GET_EXPIRES_IN: IDuration = { unit: DurationUnits.MINUTE, value: 1 };\n\n /** A browser upload form: the user has to pick the file and the bytes have to travel. */\n static readonly POST_EXPIRES_IN: IDuration = { unit: DurationUnits.MINUTE, value: 15 };\n}\n\n/** SigV4 refuses a presigned URL valid for longer than 7 days. */\nexport class StoragePresignLimits {\n static readonly MAX_EXPIRES_IN_SECONDS = 7 * 24 * 60 * 60;\n}\n\n/** Concurrent object operations. Unbounded exhausts sockets and gets rate limited. */\nexport class StorageConcurrency {\n static readonly DEFAULT_LIMIT = 16;\n}\n\n/** Which host a signed artifact names. `host` is inside every SigV4 signature, so this is decided at signing time and cannot be patched afterwards. */\nexport class S3Audiences {\n /** The host THIS process talks to: every bucket operation, copy and tagging call. */\n static readonly SERVER = 'server';\n\n /** The host a BROWSER is handed: presigned URLs and POST policies. */\n static readonly BROWSER = 'browser';\n\n static readonly SCHEME_SET = new Set<string>([this.SERVER, this.BROWSER]);\n\n static isValid(audience: string): boolean {\n return this.SCHEME_SET.has(audience);\n }\n}\n\n/** The host a signed artifact names: `server` (the host this process talks to) or `browser` (the host a browser is handed). */\nexport type TS3Audience = TConstValue<typeof S3Audiences>;\n"]}
|
|
@@ -9,6 +9,23 @@ export declare const StorageErrors: {
|
|
|
9
9
|
readonly statusCode: 404;
|
|
10
10
|
readonly category: "business";
|
|
11
11
|
};
|
|
12
|
+
/** An upload named a folder the storage refuses: a segment it cannot hold, or an empty path. */
|
|
13
|
+
readonly FOLDER_PATH_INVALID: {
|
|
14
|
+
readonly message: {
|
|
15
|
+
readonly text: "Invalid folder path";
|
|
16
|
+
readonly code: "core.storage.folder_path_invalid";
|
|
17
|
+
};
|
|
18
|
+
readonly statusCode: 400;
|
|
19
|
+
readonly category: "validation";
|
|
20
|
+
};
|
|
21
|
+
readonly FOLDER_DEPTH_EXCEEDED: {
|
|
22
|
+
readonly message: {
|
|
23
|
+
readonly text: "Folder path exceeds the maximum depth";
|
|
24
|
+
readonly code: "core.storage.folder_depth_exceeded";
|
|
25
|
+
};
|
|
26
|
+
readonly statusCode: 400;
|
|
27
|
+
readonly category: "validation";
|
|
28
|
+
};
|
|
12
29
|
};
|
|
13
30
|
/** Augments inversion, not helpers: TS only treats this as an augmentation when the file imports that module. */
|
|
14
31
|
declare module '@venizia/ignis-inversion' {
|
|
@@ -7,5 +7,19 @@ export const StorageErrors = {
|
|
|
7
7
|
statusCode: HTTP.ResultCodes.RS_4.NotFound,
|
|
8
8
|
category: ErrorScopes.BUSINESS,
|
|
9
9
|
},
|
|
10
|
+
/** An upload named a folder the storage refuses: a segment it cannot hold, or an empty path. */
|
|
11
|
+
FOLDER_PATH_INVALID: {
|
|
12
|
+
message: { text: 'Invalid folder path', code: 'core.storage.folder_path_invalid' },
|
|
13
|
+
statusCode: HTTP.ResultCodes.RS_4.BadRequest,
|
|
14
|
+
category: ErrorScopes.VALIDATION,
|
|
15
|
+
},
|
|
16
|
+
FOLDER_DEPTH_EXCEEDED: {
|
|
17
|
+
message: {
|
|
18
|
+
text: 'Folder path exceeds the maximum depth',
|
|
19
|
+
code: 'core.storage.folder_depth_exceeded',
|
|
20
|
+
},
|
|
21
|
+
statusCode: HTTP.ResultCodes.RS_4.BadRequest,
|
|
22
|
+
category: ErrorScopes.VALIDATION,
|
|
23
|
+
},
|
|
10
24
|
};
|
|
11
25
|
//# sourceMappingURL=errors.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"errors.js","sourceRoot":"","sources":["../../../../../src/modules/storage/common/errors.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,WAAW,EAAE,MAAM,0BAA0B,CAAC;AACvD,OAAO,EAAE,IAAI,EAAE,MAAM,oBAAoB,CAAC;AAE1C,uGAAuG;AACvG,MAAM,CAAC,MAAM,aAAa,GAAG;IAC3B,gBAAgB,EAAE;QAChB,OAAO,EAAE,EAAE,IAAI,EAAE,kBAAkB,EAAE,IAAI,EAAE,+BAA+B,EAAE;QAC5E,UAAU,EAAE,IAAI,CAAC,WAAW,CAAC,IAAI,CAAC,QAAQ;QAC1C,QAAQ,EAAE,WAAW,CAAC,QAAQ;KAC/B;CACkD,CAAC","sourcesContent":["import type { TErrorDefinition, TRegisterErrors } from '@venizia/ignis-inversion';\nimport { ErrorScopes } from '@venizia/ignis-inversion';\nimport { HTTP } from '@/common/constants';\n\n/** Codes a caller branches on for a storage failure that is the request's fault, not the backend's. */\nexport const StorageErrors = {\n OBJECT_NOT_FOUND: {\n message: { text: 'Object not found', code: 'core.storage.object_not_found' },\n statusCode: HTTP.ResultCodes.RS_4.NotFound,\n category: ErrorScopes.BUSINESS,\n },\n} as const satisfies Record<string, TErrorDefinition>;\n\n/** Augments inversion, not helpers: TS only treats this as an augmentation when the file imports that module. */\ndeclare module '@venizia/ignis-inversion' {\n interface IErrorKeyRegistry extends TRegisterErrors<typeof StorageErrors> {}\n}\n"]}
|
|
1
|
+
{"version":3,"file":"errors.js","sourceRoot":"","sources":["../../../../../src/modules/storage/common/errors.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,WAAW,EAAE,MAAM,0BAA0B,CAAC;AACvD,OAAO,EAAE,IAAI,EAAE,MAAM,oBAAoB,CAAC;AAE1C,uGAAuG;AACvG,MAAM,CAAC,MAAM,aAAa,GAAG;IAC3B,gBAAgB,EAAE;QAChB,OAAO,EAAE,EAAE,IAAI,EAAE,kBAAkB,EAAE,IAAI,EAAE,+BAA+B,EAAE;QAC5E,UAAU,EAAE,IAAI,CAAC,WAAW,CAAC,IAAI,CAAC,QAAQ;QAC1C,QAAQ,EAAE,WAAW,CAAC,QAAQ;KAC/B;IACD,gGAAgG;IAChG,mBAAmB,EAAE;QACnB,OAAO,EAAE,EAAE,IAAI,EAAE,qBAAqB,EAAE,IAAI,EAAE,kCAAkC,EAAE;QAClF,UAAU,EAAE,IAAI,CAAC,WAAW,CAAC,IAAI,CAAC,UAAU;QAC5C,QAAQ,EAAE,WAAW,CAAC,UAAU;KACjC;IACD,qBAAqB,EAAE;QACrB,OAAO,EAAE;YACP,IAAI,EAAE,uCAAuC;YAC7C,IAAI,EAAE,oCAAoC;SAC3C;QACD,UAAU,EAAE,IAAI,CAAC,WAAW,CAAC,IAAI,CAAC,UAAU;QAC5C,QAAQ,EAAE,WAAW,CAAC,UAAU;KACjC;CACkD,CAAC","sourcesContent":["import type { TErrorDefinition, TRegisterErrors } from '@venizia/ignis-inversion';\nimport { ErrorScopes } from '@venizia/ignis-inversion';\nimport { HTTP } from '@/common/constants';\n\n/** Codes a caller branches on for a storage failure that is the request's fault, not the backend's. */\nexport const StorageErrors = {\n OBJECT_NOT_FOUND: {\n message: { text: 'Object not found', code: 'core.storage.object_not_found' },\n statusCode: HTTP.ResultCodes.RS_4.NotFound,\n category: ErrorScopes.BUSINESS,\n },\n /** An upload named a folder the storage refuses: a segment it cannot hold, or an empty path. */\n FOLDER_PATH_INVALID: {\n message: { text: 'Invalid folder path', code: 'core.storage.folder_path_invalid' },\n statusCode: HTTP.ResultCodes.RS_4.BadRequest,\n category: ErrorScopes.VALIDATION,\n },\n FOLDER_DEPTH_EXCEEDED: {\n message: {\n text: 'Folder path exceeds the maximum depth',\n code: 'core.storage.folder_depth_exceeded',\n },\n statusCode: HTTP.ResultCodes.RS_4.BadRequest,\n category: ErrorScopes.VALIDATION,\n },\n} as const satisfies Record<string, TErrorDefinition>;\n\n/** Augments inversion, not helpers: TS only treats this as an augmentation when the file imports that module. */\ndeclare module '@venizia/ignis-inversion' {\n interface IErrorKeyRegistry extends TRegisterErrors<typeof StorageErrors> {}\n}\n"]}
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { type IDuration } from '../../../common/index.js';
|
|
2
2
|
import { type Readable } from 'node:stream';
|
|
3
|
+
import type { TStorageType } from './constants.js';
|
|
3
4
|
/** One file handed to `upload`. `buffer` is the whole body; `folderPath`, when set, nests the object under that folder and is depth-checked. */
|
|
4
5
|
export interface IUploadFile {
|
|
5
6
|
originalName: string;
|
|
@@ -90,6 +91,8 @@ export interface IStorageHelperOptions {
|
|
|
90
91
|
}
|
|
91
92
|
/** The contract every storage backend (disk, in-memory, S3) implements. Buckets and objects are addressed by `IBucketRef` and `IObjectRef`. */
|
|
92
93
|
export interface IStorageHelper {
|
|
94
|
+
/** The backend this helper writes to. The helpers IGNIS ships declare it; a custom helper may leave it out. */
|
|
95
|
+
readonly storageType?: TStorageType;
|
|
93
96
|
isValidSegment(opts: {
|
|
94
97
|
segment: string;
|
|
95
98
|
}): boolean;
|
|
@@ -128,7 +131,14 @@ export interface IStorageHelper {
|
|
|
128
131
|
upload(opts: {
|
|
129
132
|
bucket: IBucketRef;
|
|
130
133
|
files: IUploadFile[];
|
|
134
|
+
/** Folders the caller's `folderPath` may carry. */
|
|
131
135
|
maxFolderDepth?: number;
|
|
136
|
+
/**
|
|
137
|
+
* Folders the finished key may carry, a scope the `normalizeNameFn` adds included.
|
|
138
|
+
*
|
|
139
|
+
* @default `maxFolderDepth`
|
|
140
|
+
*/
|
|
141
|
+
maxKeyDepth?: number;
|
|
132
142
|
normalizeNameFn?: (opts: {
|
|
133
143
|
file: TUploadNaming;
|
|
134
144
|
}) => string;
|
|
@@ -159,10 +169,13 @@ export interface IStorageHelper {
|
|
|
159
169
|
bucket: IBucketRef;
|
|
160
170
|
objects: IObjectRef[];
|
|
161
171
|
}): Promise<void>;
|
|
162
|
-
/**
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
172
|
+
/**
|
|
173
|
+
* The form a browser posts straight to the storage, good for exactly ONE object: the policy signs
|
|
174
|
+
* `object.key` as it stands, and `formData` carries that key, so the client does not add it.
|
|
175
|
+
* Unlike a presigned PUT, a policy carries `content-length-range`, so "at most N bytes" is
|
|
176
|
+
* expressible - a signed PUT binds the length to one exact value.
|
|
177
|
+
*/
|
|
178
|
+
presignPost(opts: IObjectLocation & {
|
|
166
179
|
maxBytes: number;
|
|
167
180
|
contentType?: string;
|
|
168
181
|
expiresIn?: IDuration;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.js","sourceRoot":"","sources":["../../../../../src/modules/storage/common/types.ts"],"names":[],"mappings":"","sourcesContent":["import { type IDuration } from '@/common';\nimport { type Readable } from 'node:stream';\n\n/** One file handed to `upload`. `buffer` is the whole body; `folderPath`, when set, nests the object under that folder and is depth-checked. */\nexport interface IUploadFile {\n originalName: string;\n mimetype: string;\n buffer: Buffer;\n size: number;\n encoding?: string;\n folderPath?: string;\n [key: string | symbol]: any;\n}\n\n/** `metaLink` is a union: the old pair allowed both present, or neither. */\nexport interface IUploadResult {\n bucket: IBucketRef;\n object: IObjectRef & { size: number; contentType: string };\n link: string;\n metaLink?: { data: any } | { error: string };\n}\n\n/** `mimetype` is named because consumers persist it; `any` let it be renamed silently. */\nexport interface IObjectMetadata {\n mimetype?: string;\n [key: string]: any;\n}\n\n/** What `getStat` reports for one object. `size` is in bytes. */\nexport interface IFileStat {\n size: number;\n metadata: IObjectMetadata;\n lastModified?: Date;\n etag?: string;\n versionId?: string;\n}\n\n/** A bucket as `getBuckets`, `getBucket` and `createBucket` report it. */\nexport interface IBucketInfo {\n name: string;\n creationDate: Date;\n}\n\n/** One entry of `listObjects`. `name` is the full object key. */\nexport interface IObjectInfo {\n name?: string;\n size?: number;\n lastModified?: Date;\n etag?: string;\n prefix?: string;\n}\n\n/** One bucket. */\nexport interface IBucketRef {\n name: string;\n}\n\n/** The parts of an upload a naming hook needs; `IUploadFile` already declares both. */\nexport type TUploadNaming = Pick<IUploadFile, 'originalName' | 'folderPath'>;\n\n/** One object. `key` is the S3 term. */\nexport interface IObjectRef {\n key: string;\n}\n\n/** Which bucket, which object. */\nexport interface IObjectLocation {\n bucket: IBucketRef;\n object: IObjectRef;\n}\n\n/** Filters for `listObjects`. `maxKeys` caps the result, and `0` returns nothing. */\nexport interface IListObjectsOptions {\n bucket: IBucketRef;\n prefix?: string;\n\n /**\n * Whether the listing descends into folders.\n *\n * @default false\n */\n useRecursive?: boolean;\n maxKeys?: number;\n}\n\n/** What `presignPost` hands a browser: where to post, the fields to post with it, and when the grant dies. */\nexport interface IPostPolicy {\n postURL: string;\n formData: Record<string, string>;\n expiresAt: string;\n}\n\n/** Logger `scope` and `identifier` for a storage helper. */\nexport interface IStorageHelperOptions {\n scope?: string;\n identifier?: string;\n}\n\n/** The contract every storage backend (disk, in-memory, S3) implements. Buckets and objects are addressed by `IBucketRef` and `IObjectRef`. */\nexport interface IStorageHelper {\n isValidSegment(opts: { segment: string }): boolean;\n isValidBucketName(opts: { bucket: IBucketRef }): boolean;\n isValidObjectKey(opts: { object: IObjectRef; maxDepth?: number }): boolean;\n\n hasBucket(opts: { bucket: IBucketRef }): Promise<boolean>;\n getBuckets(): Promise<IBucketInfo[]>;\n getBucket(opts: { bucket: IBucketRef }): Promise<IBucketInfo | null>;\n createBucket(opts: { bucket: IBucketRef }): Promise<IBucketInfo | null>;\n removeBucket(opts: { bucket: IBucketRef }): Promise<boolean>;\n\n getObject(opts: IObjectLocation & { options?: any }): Promise<Readable>;\n\n /** A web stream, what a `Response` body wants. `range` includes `end`, like the HTTP header. */\n getObjectStream(\n opts: IObjectLocation & { range?: { start: number; end?: number } },\n ): Promise<ReadableStream<Uint8Array>>;\n getStat(opts: IObjectLocation): Promise<IFileStat>;\n listObjects(opts: IListObjectsOptions): Promise<IObjectInfo[]>;\n\n upload(opts: {\n bucket: IBucketRef;\n files: IUploadFile[];\n maxFolderDepth?: number;\n normalizeNameFn?: (opts: { file: TUploadNaming }) => string;\n normalizeLinkFn?: (opts: IObjectLocation) => string;\n }): Promise<IUploadResult[]>;\n\n /**\n * Writes an object from a stream, so a large body never lands in this process. A backend whose\n * transport takes a stream overrides it; the default buffers, which is the thing to avoid.\n */\n writeStream(\n opts: IObjectLocation & {\n source: ReadableStream<Uint8Array> | Blob | Response | Request;\n contentType?: string;\n /**\n * Folder nesting the key may carry, as `upload` takes it.\n *\n * @default BaseStorageHelper.DEFAULT_MAX_FOLDER_DEPTH\n */\n maxFolderDepth?: number;\n },\n ): Promise<void>;\n\n /** Copies within one bucket, server side - the bytes never travel through this process. */\n copyObject(opts: {\n bucket: IBucketRef;\n source: IObjectRef;\n destination: IObjectRef;\n }): Promise<void>;\n\n removeObject(opts: IObjectLocation): Promise<void>;\n removeObjects(opts: { bucket: IBucketRef; objects: IObjectRef[] }): Promise<void>;\n\n
|
|
1
|
+
{"version":3,"file":"types.js","sourceRoot":"","sources":["../../../../../src/modules/storage/common/types.ts"],"names":[],"mappings":"","sourcesContent":["import { type IDuration } from '@/common';\nimport { type Readable } from 'node:stream';\nimport type { TStorageType } from './constants';\n\n/** One file handed to `upload`. `buffer` is the whole body; `folderPath`, when set, nests the object under that folder and is depth-checked. */\nexport interface IUploadFile {\n originalName: string;\n mimetype: string;\n buffer: Buffer;\n size: number;\n encoding?: string;\n folderPath?: string;\n [key: string | symbol]: any;\n}\n\n/** `metaLink` is a union: the old pair allowed both present, or neither. */\nexport interface IUploadResult {\n bucket: IBucketRef;\n object: IObjectRef & { size: number; contentType: string };\n link: string;\n metaLink?: { data: any } | { error: string };\n}\n\n/** `mimetype` is named because consumers persist it; `any` let it be renamed silently. */\nexport interface IObjectMetadata {\n mimetype?: string;\n [key: string]: any;\n}\n\n/** What `getStat` reports for one object. `size` is in bytes. */\nexport interface IFileStat {\n size: number;\n metadata: IObjectMetadata;\n lastModified?: Date;\n etag?: string;\n versionId?: string;\n}\n\n/** A bucket as `getBuckets`, `getBucket` and `createBucket` report it. */\nexport interface IBucketInfo {\n name: string;\n creationDate: Date;\n}\n\n/** One entry of `listObjects`. `name` is the full object key. */\nexport interface IObjectInfo {\n name?: string;\n size?: number;\n lastModified?: Date;\n etag?: string;\n prefix?: string;\n}\n\n/** One bucket. */\nexport interface IBucketRef {\n name: string;\n}\n\n/** The parts of an upload a naming hook needs; `IUploadFile` already declares both. */\nexport type TUploadNaming = Pick<IUploadFile, 'originalName' | 'folderPath'>;\n\n/** One object. `key` is the S3 term. */\nexport interface IObjectRef {\n key: string;\n}\n\n/** Which bucket, which object. */\nexport interface IObjectLocation {\n bucket: IBucketRef;\n object: IObjectRef;\n}\n\n/** Filters for `listObjects`. `maxKeys` caps the result, and `0` returns nothing. */\nexport interface IListObjectsOptions {\n bucket: IBucketRef;\n prefix?: string;\n\n /**\n * Whether the listing descends into folders.\n *\n * @default false\n */\n useRecursive?: boolean;\n maxKeys?: number;\n}\n\n/** What `presignPost` hands a browser: where to post, the fields to post with it, and when the grant dies. */\nexport interface IPostPolicy {\n postURL: string;\n formData: Record<string, string>;\n expiresAt: string;\n}\n\n/** Logger `scope` and `identifier` for a storage helper. */\nexport interface IStorageHelperOptions {\n scope?: string;\n identifier?: string;\n}\n\n/** The contract every storage backend (disk, in-memory, S3) implements. Buckets and objects are addressed by `IBucketRef` and `IObjectRef`. */\nexport interface IStorageHelper {\n /** The backend this helper writes to. The helpers IGNIS ships declare it; a custom helper may leave it out. */\n readonly storageType?: TStorageType;\n\n isValidSegment(opts: { segment: string }): boolean;\n isValidBucketName(opts: { bucket: IBucketRef }): boolean;\n isValidObjectKey(opts: { object: IObjectRef; maxDepth?: number }): boolean;\n\n hasBucket(opts: { bucket: IBucketRef }): Promise<boolean>;\n getBuckets(): Promise<IBucketInfo[]>;\n getBucket(opts: { bucket: IBucketRef }): Promise<IBucketInfo | null>;\n createBucket(opts: { bucket: IBucketRef }): Promise<IBucketInfo | null>;\n removeBucket(opts: { bucket: IBucketRef }): Promise<boolean>;\n\n getObject(opts: IObjectLocation & { options?: any }): Promise<Readable>;\n\n /** A web stream, what a `Response` body wants. `range` includes `end`, like the HTTP header. */\n getObjectStream(\n opts: IObjectLocation & { range?: { start: number; end?: number } },\n ): Promise<ReadableStream<Uint8Array>>;\n getStat(opts: IObjectLocation): Promise<IFileStat>;\n listObjects(opts: IListObjectsOptions): Promise<IObjectInfo[]>;\n\n upload(opts: {\n bucket: IBucketRef;\n files: IUploadFile[];\n /** Folders the caller's `folderPath` may carry. */\n maxFolderDepth?: number;\n /**\n * Folders the finished key may carry, a scope the `normalizeNameFn` adds included.\n *\n * @default `maxFolderDepth`\n */\n maxKeyDepth?: number;\n normalizeNameFn?: (opts: { file: TUploadNaming }) => string;\n normalizeLinkFn?: (opts: IObjectLocation) => string;\n }): Promise<IUploadResult[]>;\n\n /**\n * Writes an object from a stream, so a large body never lands in this process. A backend whose\n * transport takes a stream overrides it; the default buffers, which is the thing to avoid.\n */\n writeStream(\n opts: IObjectLocation & {\n source: ReadableStream<Uint8Array> | Blob | Response | Request;\n contentType?: string;\n /**\n * Folder nesting the key may carry, as `upload` takes it.\n *\n * @default BaseStorageHelper.DEFAULT_MAX_FOLDER_DEPTH\n */\n maxFolderDepth?: number;\n },\n ): Promise<void>;\n\n /** Copies within one bucket, server side - the bytes never travel through this process. */\n copyObject(opts: {\n bucket: IBucketRef;\n source: IObjectRef;\n destination: IObjectRef;\n }): Promise<void>;\n\n removeObject(opts: IObjectLocation): Promise<void>;\n removeObjects(opts: { bucket: IBucketRef; objects: IObjectRef[] }): Promise<void>;\n\n /**\n * The form a browser posts straight to the storage, good for exactly ONE object: the policy signs\n * `object.key` as it stands, and `formData` carries that key, so the client does not add it.\n * Unlike a presigned PUT, a policy carries `content-length-range`, so \"at most N bytes\" is\n * expressible - a signed PUT binds the length to one exact value.\n */\n presignPost(\n opts: IObjectLocation & {\n maxBytes: number;\n contentType?: string;\n expiresIn?: IDuration;\n },\n ): Promise<IPostPolicy>;\n\n /** A URL a browser may PUT one object to. Every extra option below is SIGNED - the client must send it back unchanged. A pinned size is exact, never a ceiling; for a ceiling use {@link IStorageHelper.presignPost}. */\n presignPut(\n opts: IObjectLocation & {\n expiresIn?: IDuration;\n /** The object's tag set, written at the moment it is stored. */\n tagging?: Record<string, string>;\n /** Pins the body to EXACTLY this many bytes. A retry at a different size is refused. */\n contentLength?: number;\n /** Pins the stored content type. Unsigned, the uploader picks what is stored - and the stored type is what a browser later renders. */\n contentType?: string;\n },\n ): Promise<string>;\n presignGet(\n opts: IObjectLocation & {\n expiresIn?: IDuration;\n responseContentType?: string;\n responseContentDisposition?: string;\n },\n ): Promise<string>;\n\n getObjectTags(opts: IObjectLocation): Promise<Record<string, string>>;\n replaceObjectTags(opts: IObjectLocation & { tags: Record<string, string> }): Promise<void>;\n\n getMediaType(opts: { mimeType: string }): string;\n getMimeType(opts: { filename: string }): string;\n}\n"]}
|
|
@@ -8,6 +8,7 @@ export interface IDiskHelperOptions extends IStorageHelperOptions {
|
|
|
8
8
|
}
|
|
9
9
|
/** Storage backed by the local filesystem: each bucket is a directory under `basePath`, each object a file whose key is its relative path. Names are validated and resolved paths must stay inside the bucket. */
|
|
10
10
|
export declare class DiskHelper extends BaseStorageHelper {
|
|
11
|
+
readonly storageType = "disk";
|
|
11
12
|
private basePath;
|
|
12
13
|
constructor(options: IDiskHelperOptions);
|
|
13
14
|
private getBucketPath;
|
|
@@ -7,7 +7,7 @@ import fsp from 'node:fs/promises';
|
|
|
7
7
|
import path from 'node:path';
|
|
8
8
|
import { Readable } from 'node:stream';
|
|
9
9
|
import { BaseStorageHelper } from '../base.js';
|
|
10
|
-
import { StorageErrors, } from '../common/index.js';
|
|
10
|
+
import { StorageErrors, StorageTypes, } from '../common/index.js';
|
|
11
11
|
/** Storage backed by the local filesystem: each bucket is a directory under `basePath`, each object a file whose key is its relative path. Names are validated and resolved paths must stay inside the bucket. */
|
|
12
12
|
export class DiskHelper extends BaseStorageHelper {
|
|
13
13
|
constructor(options) {
|
|
@@ -15,6 +15,7 @@ export class DiskHelper extends BaseStorageHelper {
|
|
|
15
15
|
scope: options.scope ?? DiskHelper.name,
|
|
16
16
|
identifier: options.identifier ?? DiskHelper.name,
|
|
17
17
|
});
|
|
18
|
+
this.storageType = StorageTypes.DISK;
|
|
18
19
|
this.basePath = path.resolve(options.basePath);
|
|
19
20
|
if (!fs.existsSync(this.basePath)) {
|
|
20
21
|
fs.mkdirSync(this.basePath, { recursive: true });
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"helper.js","sourceRoot":"","sources":["../../../../../src/modules/storage/disk/helper.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAE,MAAM,yBAAyB,CAAC;AAC/C,OAAO,EAAE,QAAQ,EAAE,MAAM,iBAAiB,CAAC;AAC3C,OAAO,EAAE,aAAa,EAAE,MAAM,kBAAkB,CAAC;AACjD,OAAO,EAAE,WAAW,EAAE,MAAM,0BAA0B,CAAC;AACvD,OAAO,EAAE,MAAM,SAAS,CAAC;AACzB,OAAO,GAAG,MAAM,kBAAkB,CAAC;AAEnC,OAAO,IAAI,MAAM,WAAW,CAAC;AAC7B,OAAO,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAC;AACvC,OAAO,EAAE,iBAAiB,EAAE,MAAM,SAAS,CAAC;AAC5C,OAAO,EAUL,aAAa,GACd,MAAM,W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{ HTTP } from '@/common/constants/http';\nimport { getError } from '@/modules/error';\nimport { ErrorPrettier } from '@/modules/logger';\nimport { EchoUtility } from '@/utilities/echo.utility';\nimport fs from 'node:fs';\nimport fsp from 'node:fs/promises';\nimport type { Stats } from 'node:fs';\nimport path from 'node:path';\nimport { Readable } from 'node:stream';\nimport { BaseStorageHelper } from '../base';\nimport {\n type IBucketInfo,\n type IBucketRef,\n type IFileStat,\n type IListObjectsOptions,\n type IObjectInfo,\n type IObjectLocation,\n type IObjectRef,\n type IStorageHelperOptions,\n type IUploadFile,\n StorageErrors,\n} from '../common';\n\n/** Options for `DiskHelper`; `basePath` is created when missing. */\nexport interface IDiskHelperOptions extends IStorageHelperOptions {\n /** Base directory every bucket lives under. */\n basePath: string;\n}\n\n/** Storage backed by the local filesystem: each bucket is a directory under `basePath`, each object a file whose key is its relative path. Names are validated and resolved paths must stay inside the bucket. */\nexport class DiskHelper extends BaseStorageHelper {\n private basePath: string;\n\n constructor(options: IDiskHelperOptions) {\n super({\n scope: options.scope ?? DiskHelper.name,\n identifier: options.identifier ?? DiskHelper.name,\n });\n this.basePath = path.resolve(options.basePath);\n\n if (!fs.existsSync(this.basePath)) {\n fs.mkdirSync(this.basePath, { recursive: true });\n }\n }\n\n private getBucketPath(opts: { bucket: IBucketRef }): string {\n return path.join(this.basePath, opts.bucket.name);\n }\n\n /**\n * Whether `target`, with every symbolic link followed, lies inside the real storage root. A target that does not exist\n * yet is judged by its nearest existing parent (a write creates the rest beneath it); a link whose own target is\n * missing is refused, because writing through it would create the file where the link points.\n */\n private async isInsideRoot(opts: { target: string }): Promise<boolean> {\n const root = await this.realpathOrFail({ target: this.basePath });\n let probe = opts.target;\n\n for (;;) {\n try {\n const real = await fsp.realpath(probe);\n\n return real === root || real.startsWith(`${root}${path.sep}`);\n } catch (error) {\n const code = (error as NodeJS.ErrnoException)?.code;\n\n // A link loop or a path the system refuses as too long is not a place a name can lead to.\n if (code === 'ELOOP' || code === 'ENAMETOOLONG') {\n return false;\n }\n\n if (code !== 'ENOENT' && code !== 'ENOTDIR') {\n throw this.toRealPathError({ error });\n }\n }\n\n const link = await this.lstatOrNull({ target: probe });\n\n if (link?.isSymbolicLink()) {\n return false;\n }\n\n const parent = path.dirname(probe);\n\n if (parent === probe) {\n return false;\n }\n\n probe = parent;\n }\n }\n\n /** The real path of `target`; a failure leaves as {@link DiskHelper.toRealPathError} answers it. */\n private async realpathOrFail(opts: { target: string }): Promise<string> {\n try {\n const result = await fsp.realpath(opts.target);\n\n return result;\n } catch (error) {\n throw this.toRealPathError({ error });\n }\n }\n\n /**\n * What a failed `realpath` is reported as: the code, never the path. Node's message holds the absolute path of the\n * server, and a refusal reaches the caller of the storage API. The full error stays in the log.\n */\n private toRealPathError(opts: { error: unknown }) {\n const { error } = opts;\n const code = (error as NodeJS.ErrnoException)?.code ?? 'UNKNOWN';\n\n this.logger.error(\n 'Cannot resolve the real path of a storage target | code: %s | %s',\n code,\n // A system error quotes the path it failed on; the path is a caller's key under the storage root.\n EchoUtility.toSafeEcho({ value: ErrorPrettier.format({ error }) }),\n );\n\n // A server-side fault, not the caller's: the default status of `getError` is a 400.\n return getError({\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n message: `[storage] Cannot resolve the real path of a storage target | code: ${code}`,\n });\n }\n\n /** `null` when nothing is there (or it cannot be read): the caller walks up to the parent and judges that. */\n private async lstatOrNull(opts: { target: string }): Promise<Stats | null> {\n try {\n const result = await fsp.lstat(opts.target);\n\n return result;\n // eslint-disable-next-line venizia/no-silent-catch -- a missing or unreadable entry is the answer here: the containment walk goes on to its parent\n } catch {\n return null;\n }\n }\n\n /** A directory that exists AND lies inside the real root: a bucket that is a link leading outside is not one. */\n private async isReachableBucketPath(opts: { target: string }): Promise<boolean> {\n const inside = await this.isInsideRoot(opts);\n\n if (!inside) {\n return false;\n }\n\n return this.exists(opts);\n }\n\n /** The path of an object after the checks of {@link DiskHelper.resolveObjectPath} and the real-path containment check. */\n private async resolveContainedObjectPath(opts: IObjectLocation): Promise<string> {\n const objectPath = this.resolveObjectPath(opts);\n\n const result = await this.isInsideRoot({ target: objectPath });\n\n if (!result) {\n throw getError({\n message: `[storage] Invalid object name | key: ${EchoUtility.toSafeText({ value: opts.object.key })}`,\n });\n }\n\n return objectPath;\n }\n\n /** Validates the name AND the resolved path: containment survives a naming rule we get wrong. */\n private resolveObjectPath(opts: IObjectLocation): string {\n const { bucket, object } = opts;\n\n if (!this.isValidBucketName({ bucket })) {\n throw getError({\n message: `[storage] Invalid bucket name | bucket: ${EchoUtility.toSafeText({ value: bucket.name })}`,\n });\n }\n\n if (!this.isValidObjectKey({ object, maxDepth: Number.MAX_SAFE_INTEGER })) {\n throw getError({\n message: `[storage] Invalid object name | key: ${EchoUtility.toSafeText({ value: object.key })}`,\n });\n }\n\n const bucketPath = this.getBucketPath({ bucket });\n const objectPath = path.resolve(bucketPath, object.key);\n\n if (objectPath !== bucketPath && !objectPath.startsWith(`${bucketPath}${path.sep}`)) {\n throw getError({\n message: `[storage] Invalid object name | key: ${EchoUtility.toSafeText({ value: object.key })}`,\n });\n }\n\n return objectPath;\n }\n\n /** `null` means not there. Anything but ENOENT is logged: it may exist and be unreadable. */\n private async statOrNull(opts: { target: string }): Promise<Stats | null> {\n const { target } = opts;\n\n try {\n const result = await fsp.stat(target);\n\n return result;\n } catch (error) {\n if ((error as NodeJS.ErrnoException)?.code !== 'ENOENT') {\n this.logger.warn(\n '[statOrNull] Cannot determine existence, reporting missing | path: %s | %s',\n EchoUtility.toSafeEcho({ value: target }),\n // The error's own text quotes the path, so it is escaped like the path is.\n EchoUtility.toSafeEcho({ value: ErrorPrettier.format({ error }) }),\n );\n }\n\n return null;\n }\n }\n\n private async exists(opts: { target: string }): Promise<boolean> {\n const result = await this.statOrNull(opts);\n\n return result !== null;\n }\n\n /** An object is a regular file: a directory under the same path is not one, so it reads as not found. */\n private async isFile(opts: { target: string }): Promise<boolean> {\n const result = await this.statOrNull(opts);\n\n return result?.isFile() ?? false;\n }\n\n /** One `stat` answers existence and type. */\n async hasBucket(opts: { bucket: IBucketRef }): Promise<boolean> {\n if (!this.isValidBucketName(opts)) {\n return false;\n }\n\n const target = this.getBucketPath(opts);\n\n // A bucket that is a link leading outside the root is not a bucket.\n const result = await this.isInsideRoot({ target });\n\n if (!result) {\n return false;\n }\n\n const stat = await this.statOrNull({ target });\n\n return stat?.isDirectory() ?? false;\n }\n\n async getBuckets(): Promise<IBucketInfo[]> {\n const result = await this.exists({ target: this.basePath });\n\n if (!result) {\n return [];\n }\n\n const entries = await fsp.readdir(this.basePath, { withFileTypes: true });\n const buckets: IBucketInfo[] = [];\n\n for (const entry of entries) {\n if (entry.isDirectory()) {\n const bucketPath = path.join(this.basePath, entry.name);\n const stat = await fsp.stat(bucketPath);\n buckets.push({\n name: entry.name,\n creationDate: stat.birthtime,\n });\n }\n }\n\n return buckets;\n }\n\n async getBucket(opts: { bucket: IBucketRef }): Promise<IBucketInfo | null> {\n const { name } = opts.bucket;\n\n if (!this.isValidBucketName(opts)) {\n return null;\n }\n\n const target = this.getBucketPath(opts);\n const inside = await this.isInsideRoot({ target });\n\n if (!inside) {\n return null;\n }\n\n const stat = await this.statOrNull({ target });\n\n if (!stat?.isDirectory()) {\n return null;\n }\n\n return { name, creationDate: stat.birthtime };\n }\n\n async createBucket(opts: { bucket: IBucketRef }): Promise<IBucketInfo | null> {\n const { name } = opts.bucket;\n\n if (!this.isValidBucketName(opts)) {\n throw getError({\n message: '[createBucket] Invalid name to create bucket!',\n });\n }\n\n const bucketPath = this.getBucketPath(opts);\n\n const result = await this.exists({ target: bucketPath });\n\n if (result) {\n throw getError({\n message: `[createBucket] Bucket already exists | name: ${EchoUtility.toSafeText({ value: name })}`,\n });\n }\n\n await fsp.mkdir(bucketPath, { recursive: true });\n\n return this.getBucket(opts);\n }\n\n async removeBucket(opts: { bucket: IBucketRef }): Promise<boolean> {\n const { name } = opts.bucket;\n\n if (!this.isValidBucketName(opts)) {\n throw getError({\n message: '[removeBucket] Invalid name to remove bucket!',\n });\n }\n\n const bucketPath = this.getBucketPath(opts);\n\n const result = await this.isReachableBucketPath({ target: bucketPath });\n\n if (!result) {\n throw getError({\n message: `[removeBucket] Bucket does not exist | name: ${EchoUtility.toSafeText({ value: name })}`,\n });\n }\n\n const files = await fsp.readdir(bucketPath);\n\n if (files.length > 0) {\n throw getError({\n message: `[removeBucket] Bucket is not empty | name: ${EchoUtility.toSafeText({ value: name })}`,\n });\n }\n\n await fsp.rmdir(bucketPath);\n\n return true;\n }\n\n protected get defaultLinkPrefix(): string {\n return '/static-resources/';\n }\n\n protected async writeObject(opts: IObjectLocation & { file: IUploadFile }): Promise<void> {\n const { bucket, object, file } = opts;\n // The same validated, contained path every other operation uses: `writeStream` reaches here without `upload`'s checks.\n const objectPath = await this.resolveContainedObjectPath({ bucket, object });\n\n // `recursive` succeeds on an existing directory; probing first wastes a syscall per file.\n await fsp.mkdir(path.dirname(objectPath), { recursive: true });\n await fsp.writeFile(objectPath, file.buffer);\n }\n\n async getObject(opts: IObjectLocation & { options?: any }): Promise<Readable> {\n const { bucket, object } = opts;\n const objectPath = await this.resolveContainedObjectPath({ bucket, object });\n\n const result = await this.isFile({ target: objectPath });\n\n if (!result) {\n throw getError({\n error: StorageErrors.OBJECT_NOT_FOUND,\n message: `[getObject] Object not found | bucket: ${EchoUtility.toSafeText({ value: bucket.name })} | key: ${EchoUtility.toSafeText({ value: object.key })}`,\n });\n }\n\n return fs.createReadStream(objectPath);\n }\n\n /** `createReadStream` seeks natively, so a range never reads the bytes before it. */\n override async getObjectStream(\n opts: IObjectLocation & { range?: { start: number; end?: number } },\n ): Promise<ReadableStream<Uint8Array>> {\n const { bucket, object, range } = opts;\n const objectPath = await this.resolveContainedObjectPath({ bucket, object });\n\n const result = await this.isFile({ target: objectPath });\n\n if (!result) {\n throw getError({\n error: StorageErrors.OBJECT_NOT_FOUND,\n message: `[getObjectStream] Object not found | bucket: ${EchoUtility.toSafeText({ value: bucket.name })} | key: ${EchoUtility.toSafeText({ value: object.key })}`,\n });\n }\n\n const source = fs.createReadStream(\n objectPath,\n range ? { start: range.start, end: range.end } : {},\n );\n\n return Readable.toWeb(source) as ReadableStream<Uint8Array>;\n }\n\n async getStat(opts: IObjectLocation): Promise<IFileStat> {\n const { bucket, object } = opts;\n const objectPath = await this.resolveContainedObjectPath({ bucket, object });\n const stat = await this.statOrNull({ target: objectPath });\n\n if (!stat?.isFile()) {\n throw getError({\n error: StorageErrors.OBJECT_NOT_FOUND,\n message: `[getStat] Object not found | bucket: ${EchoUtility.toSafeText({ value: bucket.name })} | key: ${EchoUtility.toSafeText({ value: object.key })}`,\n });\n }\n\n return {\n size: stat.size,\n lastModified: stat.mtime,\n metadata: {\n mimetype: this.getMimeType({ filename: object.key }),\n },\n };\n }\n\n async removeObject(opts: IObjectLocation): Promise<void> {\n const { bucket, object } = opts;\n const objectPath = await this.resolveContainedObjectPath({ bucket, object });\n\n const result = await this.isFile({ target: objectPath });\n\n if (!result) {\n throw getError({\n error: StorageErrors.OBJECT_NOT_FOUND,\n message: `[removeObject] Object not found | bucket: ${EchoUtility.toSafeText({ value: bucket.name })} | key: ${EchoUtility.toSafeText({ value: object.key })}`,\n });\n }\n\n await fsp.unlink(objectPath);\n }\n\n // Bounded concurrency; one failure stops the batch.\n async removeObjects(opts: { bucket: IBucketRef; objects: IObjectRef[] }): Promise<void> {\n const { bucket, objects } = opts;\n\n await this.mapWithConcurrency({\n items: objects,\n task: ({ item: object }) => this.removeObject({ bucket, object }),\n });\n }\n\n async listObjects(opts: IListObjectsOptions): Promise<IObjectInfo[]> {\n const { bucket, prefix = '', useRecursive = false, maxKeys } = opts;\n\n if (!this.isValidBucketName({ bucket })) {\n throw getError({\n message: `[listObjects] Invalid bucket name | bucket: ${EchoUtility.toSafeText({ value: bucket.name })}`,\n });\n }\n\n // `maxKeys: 0` means zero, not unlimited.\n const limit = maxKeys ?? Number.POSITIVE_INFINITY;\n\n if (limit <= 0) {\n return [];\n }\n\n const bucketPath = this.getBucketPath({ bucket });\n const result = await this.isReachableBucketPath({ target: bucketPath });\n\n if (!result) {\n return [];\n }\n\n const objects: IObjectInfo[] = [];\n\n const scanDirectory = async (scanOptions: {\n directory: { path: string; prefix?: string };\n }): Promise<void> => {\n const { directory } = scanOptions;\n\n if (objects.length >= limit) {\n return;\n }\n\n const entries = await fsp.readdir(directory.path, { withFileTypes: true });\n\n for (const entry of entries) {\n if (objects.length >= limit) {\n return;\n }\n\n // An object key always joins on '/'; `path.join` would emit '\\' on Windows.\n const entryKey = directory.prefix ? `${directory.prefix}/${entry.name}` : entry.name;\n const entryPath = path.join(directory.path, entry.name);\n\n if (entry.isDirectory()) {\n // A prefix that cannot match below here makes descending pointless.\n const canMatch = !prefix || prefix.startsWith(entryKey) || entryKey.startsWith(prefix);\n\n if (useRecursive && canMatch) {\n await scanDirectory({ directory: { path: entryPath, prefix: entryKey } });\n }\n\n continue;\n }\n\n if (!entry.isFile() || (prefix && !entryKey.startsWith(prefix))) {\n continue;\n }\n\n const stat = await this.statOrNull({ target: entryPath });\n\n if (!stat) {\n continue;\n }\n\n objects.push({ name: entryKey, size: stat.size, lastModified: stat.mtime });\n }\n };\n\n await scanDirectory({ directory: { path: bucketPath } });\n\n return objects;\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"helper.js","sourceRoot":"","sources":["../../../../../src/modules/storage/disk/helper.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAE,MAAM,yBAAyB,CAAC;AAC/C,OAAO,EAAE,QAAQ,EAAE,MAAM,iBAAiB,CAAC;AAC3C,OAAO,EAAE,aAAa,EAAE,MAAM,kBAAkB,CAAC;AACjD,OAAO,EAAE,WAAW,EAAE,MAAM,0BAA0B,CAAC;AACvD,OAAO,EAAE,MAAM,SAAS,CAAC;AACzB,OAAO,GAAG,MAAM,kBAAkB,CAAC;AAEnC,OAAO,IAAI,MAAM,WAAW,CAAC;AAC7B,OAAO,EAAE,QAAQ,EAAE,MAAM,aAAa,CAA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;QAEF,MAAM,aAAa,CAAC,EAAE,SAAS,EAAE,EAAE,IAAI,EAAE,UAAU,EAAE,EAAE,CAAC,CAAC;QAEzD,OAAO,OAAO,CAAC;IACjB,CAAC;CACF","sourcesContent":["import { HTTP } from '@/common/constants/http';\nimport { getError } from '@/modules/error';\nimport { ErrorPrettier } from '@/modules/logger';\nimport { EchoUtility } from '@/utilities/echo.utility';\nimport fs from 'node:fs';\nimport fsp from 'node:fs/promises';\nimport type { Stats } from 'node:fs';\nimport path from 'node:path';\nimport { Readable } from 'node:stream';\nimport { BaseStorageHelper } from '../base';\nimport {\n type IBucketInfo,\n type IBucketRef,\n type IFileStat,\n type IListObjectsOptions,\n type IObjectInfo,\n type IObjectLocation,\n type IObjectRef,\n type IStorageHelperOptions,\n type IUploadFile,\n StorageErrors,\n StorageTypes,\n} from '../common';\n\n/** Options for `DiskHelper`; `basePath` is created when missing. */\nexport interface IDiskHelperOptions extends IStorageHelperOptions {\n /** Base directory every bucket lives under. */\n basePath: string;\n}\n\n/** Storage backed by the local filesystem: each bucket is a directory under `basePath`, each object a file whose key is its relative path. Names are validated and resolved paths must stay inside the bucket. */\nexport class DiskHelper extends BaseStorageHelper {\n readonly storageType = StorageTypes.DISK;\n\n private basePath: string;\n\n constructor(options: IDiskHelperOptions) {\n super({\n scope: options.scope ?? DiskHelper.name,\n identifier: options.identifier ?? DiskHelper.name,\n });\n this.basePath = path.resolve(options.basePath);\n\n if (!fs.existsSync(this.basePath)) {\n fs.mkdirSync(this.basePath, { recursive: true });\n }\n }\n\n private getBucketPath(opts: { bucket: IBucketRef }): string {\n return path.join(this.basePath, opts.bucket.name);\n }\n\n /**\n * Whether `target`, with every symbolic link followed, lies inside the real storage root. A target that does not exist\n * yet is judged by its nearest existing parent (a write creates the rest beneath it); a link whose own target is\n * missing is refused, because writing through it would create the file where the link points.\n */\n private async isInsideRoot(opts: { target: string }): Promise<boolean> {\n const root = await this.realpathOrFail({ target: this.basePath });\n let probe = opts.target;\n\n for (;;) {\n try {\n const real = await fsp.realpath(probe);\n\n return real === root || real.startsWith(`${root}${path.sep}`);\n } catch (error) {\n const code = (error as NodeJS.ErrnoException)?.code;\n\n // A link loop or a path the system refuses as too long is not a place a name can lead to.\n if (code === 'ELOOP' || code === 'ENAMETOOLONG') {\n return false;\n }\n\n if (code !== 'ENOENT' && code !== 'ENOTDIR') {\n throw this.toRealPathError({ error });\n }\n }\n\n const link = await this.lstatOrNull({ target: probe });\n\n if (link?.isSymbolicLink()) {\n return false;\n }\n\n const parent = path.dirname(probe);\n\n if (parent === probe) {\n return false;\n }\n\n probe = parent;\n }\n }\n\n /** The real path of `target`; a failure leaves as {@link DiskHelper.toRealPathError} answers it. */\n private async realpathOrFail(opts: { target: string }): Promise<string> {\n try {\n const result = await fsp.realpath(opts.target);\n\n return result;\n } catch (error) {\n throw this.toRealPathError({ error });\n }\n }\n\n /**\n * What a failed `realpath` is reported as: the code, never the path. Node's message holds the absolute path of the\n * server, and a refusal reaches the caller of the storage API. The full error stays in the log.\n */\n private toRealPathError(opts: { error: unknown }) {\n const { error } = opts;\n const code = (error as NodeJS.ErrnoException)?.code ?? 'UNKNOWN';\n\n this.logger.error(\n 'Cannot resolve the real path of a storage target | code: %s | %s',\n code,\n // A system error quotes the path it failed on; the path is a caller's key under the storage root.\n EchoUtility.toSafeEcho({ value: ErrorPrettier.format({ error }) }),\n );\n\n // A server-side fault, not the caller's: the default status of `getError` is a 400.\n return getError({\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n message: `[storage] Cannot resolve the real path of a storage target | code: ${code}`,\n });\n }\n\n /** `null` when nothing is there (or it cannot be read): the caller walks up to the parent and judges that. */\n private async lstatOrNull(opts: { target: string }): Promise<Stats | null> {\n try {\n const result = await fsp.lstat(opts.target);\n\n return result;\n // eslint-disable-next-line venizia/no-silent-catch -- a missing or unreadable entry is the answer here: the containment walk goes on to its parent\n } catch {\n return null;\n }\n }\n\n /** A directory that exists AND lies inside the real root: a bucket that is a link leading outside is not one. */\n private async isReachableBucketPath(opts: { target: string }): Promise<boolean> {\n const inside = await this.isInsideRoot(opts);\n\n if (!inside) {\n return false;\n }\n\n return this.exists(opts);\n }\n\n /** The path of an object after the checks of {@link DiskHelper.resolveObjectPath} and the real-path containment check. */\n private async resolveContainedObjectPath(opts: IObjectLocation): Promise<string> {\n const objectPath = this.resolveObjectPath(opts);\n\n const result = await this.isInsideRoot({ target: objectPath });\n\n if (!result) {\n throw getError({\n message: `[storage] Invalid object name | key: ${EchoUtility.toSafeText({ value: opts.object.key })}`,\n });\n }\n\n return objectPath;\n }\n\n /** Validates the name AND the resolved path: containment survives a naming rule we get wrong. */\n private resolveObjectPath(opts: IObjectLocation): string {\n const { bucket, object } = opts;\n\n if (!this.isValidBucketName({ bucket })) {\n throw getError({\n message: `[storage] Invalid bucket name | bucket: ${EchoUtility.toSafeText({ value: bucket.name })}`,\n });\n }\n\n if (!this.isValidObjectKey({ object, maxDepth: Number.MAX_SAFE_INTEGER })) {\n throw getError({\n message: `[storage] Invalid object name | key: ${EchoUtility.toSafeText({ value: object.key })}`,\n });\n }\n\n const bucketPath = this.getBucketPath({ bucket });\n const objectPath = path.resolve(bucketPath, object.key);\n\n if (objectPath !== bucketPath && !objectPath.startsWith(`${bucketPath}${path.sep}`)) {\n throw getError({\n message: `[storage] Invalid object name | key: ${EchoUtility.toSafeText({ value: object.key })}`,\n });\n }\n\n return objectPath;\n }\n\n /** `null` means not there. Anything but ENOENT is logged: it may exist and be unreadable. */\n private async statOrNull(opts: { target: string }): Promise<Stats | null> {\n const { target } = opts;\n\n try {\n const result = await fsp.stat(target);\n\n return result;\n } catch (error) {\n if ((error as NodeJS.ErrnoException)?.code !== 'ENOENT') {\n this.logger.warn(\n '[statOrNull] Cannot determine existence, reporting missing | path: %s | %s',\n EchoUtility.toSafeEcho({ value: target }),\n // The error's own text quotes the path, so it is escaped like the path is.\n EchoUtility.toSafeEcho({ value: ErrorPrettier.format({ error }) }),\n );\n }\n\n return null;\n }\n }\n\n private async exists(opts: { target: string }): Promise<boolean> {\n const result = await this.statOrNull(opts);\n\n return result !== null;\n }\n\n /** An object is a regular file: a directory under the same path is not one, so it reads as not found. */\n private async isFile(opts: { target: string }): Promise<boolean> {\n const result = await this.statOrNull(opts);\n\n return result?.isFile() ?? false;\n }\n\n /** One `stat` answers existence and type. */\n async hasBucket(opts: { bucket: IBucketRef }): Promise<boolean> {\n if (!this.isValidBucketName(opts)) {\n return false;\n }\n\n const target = this.getBucketPath(opts);\n\n // A bucket that is a link leading outside the root is not a bucket.\n const result = await this.isInsideRoot({ target });\n\n if (!result) {\n return false;\n }\n\n const stat = await this.statOrNull({ target });\n\n return stat?.isDirectory() ?? false;\n }\n\n async getBuckets(): Promise<IBucketInfo[]> {\n const result = await this.exists({ target: this.basePath });\n\n if (!result) {\n return [];\n }\n\n const entries = await fsp.readdir(this.basePath, { withFileTypes: true });\n const buckets: IBucketInfo[] = [];\n\n for (const entry of entries) {\n if (entry.isDirectory()) {\n const bucketPath = path.join(this.basePath, entry.name);\n const stat = await fsp.stat(bucketPath);\n buckets.push({\n name: entry.name,\n creationDate: stat.birthtime,\n });\n }\n }\n\n return buckets;\n }\n\n async getBucket(opts: { bucket: IBucketRef }): Promise<IBucketInfo | null> {\n const { name } = opts.bucket;\n\n if (!this.isValidBucketName(opts)) {\n return null;\n }\n\n const target = this.getBucketPath(opts);\n const inside = await this.isInsideRoot({ target });\n\n if (!inside) {\n return null;\n }\n\n const stat = await this.statOrNull({ target });\n\n if (!stat?.isDirectory()) {\n return null;\n }\n\n return { name, creationDate: stat.birthtime };\n }\n\n async createBucket(opts: { bucket: IBucketRef }): Promise<IBucketInfo | null> {\n const { name } = opts.bucket;\n\n if (!this.isValidBucketName(opts)) {\n throw getError({\n message: '[createBucket] Invalid name to create bucket!',\n });\n }\n\n const bucketPath = this.getBucketPath(opts);\n\n const result = await this.exists({ target: bucketPath });\n\n if (result) {\n throw getError({\n message: `[createBucket] Bucket already exists | name: ${EchoUtility.toSafeText({ value: name })}`,\n });\n }\n\n await fsp.mkdir(bucketPath, { recursive: true });\n\n return this.getBucket(opts);\n }\n\n async removeBucket(opts: { bucket: IBucketRef }): Promise<boolean> {\n const { name } = opts.bucket;\n\n if (!this.isValidBucketName(opts)) {\n throw getError({\n message: '[removeBucket] Invalid name to remove bucket!',\n });\n }\n\n const bucketPath = this.getBucketPath(opts);\n\n const result = await this.isReachableBucketPath({ target: bucketPath });\n\n if (!result) {\n throw getError({\n message: `[removeBucket] Bucket does not exist | name: ${EchoUtility.toSafeText({ value: name })}`,\n });\n }\n\n const files = await fsp.readdir(bucketPath);\n\n if (files.length > 0) {\n throw getError({\n message: `[removeBucket] Bucket is not empty | name: ${EchoUtility.toSafeText({ value: name })}`,\n });\n }\n\n await fsp.rmdir(bucketPath);\n\n return true;\n }\n\n protected get defaultLinkPrefix(): string {\n return '/static-resources/';\n }\n\n protected async writeObject(opts: IObjectLocation & { file: IUploadFile }): Promise<void> {\n const { bucket, object, file } = opts;\n // The same validated, contained path every other operation uses: `writeStream` reaches here without `upload`'s checks.\n const objectPath = await this.resolveContainedObjectPath({ bucket, object });\n\n // `recursive` succeeds on an existing directory; probing first wastes a syscall per file.\n await fsp.mkdir(path.dirname(objectPath), { recursive: true });\n await fsp.writeFile(objectPath, file.buffer);\n }\n\n async getObject(opts: IObjectLocation & { options?: any }): Promise<Readable> {\n const { bucket, object } = opts;\n const objectPath = await this.resolveContainedObjectPath({ bucket, object });\n\n const result = await this.isFile({ target: objectPath });\n\n if (!result) {\n throw getError({\n error: StorageErrors.OBJECT_NOT_FOUND,\n message: `[getObject] Object not found | bucket: ${EchoUtility.toSafeText({ value: bucket.name })} | key: ${EchoUtility.toSafeText({ value: object.key })}`,\n });\n }\n\n return fs.createReadStream(objectPath);\n }\n\n /** `createReadStream` seeks natively, so a range never reads the bytes before it. */\n override async getObjectStream(\n opts: IObjectLocation & { range?: { start: number; end?: number } },\n ): Promise<ReadableStream<Uint8Array>> {\n const { bucket, object, range } = opts;\n const objectPath = await this.resolveContainedObjectPath({ bucket, object });\n\n const result = await this.isFile({ target: objectPath });\n\n if (!result) {\n throw getError({\n error: StorageErrors.OBJECT_NOT_FOUND,\n message: `[getObjectStream] Object not found | bucket: ${EchoUtility.toSafeText({ value: bucket.name })} | key: ${EchoUtility.toSafeText({ value: object.key })}`,\n });\n }\n\n const source = fs.createReadStream(\n objectPath,\n range ? { start: range.start, end: range.end } : {},\n );\n\n return Readable.toWeb(source) as ReadableStream<Uint8Array>;\n }\n\n async getStat(opts: IObjectLocation): Promise<IFileStat> {\n const { bucket, object } = opts;\n const objectPath = await this.resolveContainedObjectPath({ bucket, object });\n const stat = await this.statOrNull({ target: objectPath });\n\n if (!stat?.isFile()) {\n throw getError({\n error: StorageErrors.OBJECT_NOT_FOUND,\n message: `[getStat] Object not found | bucket: ${EchoUtility.toSafeText({ value: bucket.name })} | key: ${EchoUtility.toSafeText({ value: object.key })}`,\n });\n }\n\n return {\n size: stat.size,\n lastModified: stat.mtime,\n metadata: {\n mimetype: this.getMimeType({ filename: object.key }),\n },\n };\n }\n\n async removeObject(opts: IObjectLocation): Promise<void> {\n const { bucket, object } = opts;\n const objectPath = await this.resolveContainedObjectPath({ bucket, object });\n\n const result = await this.isFile({ target: objectPath });\n\n if (!result) {\n throw getError({\n error: StorageErrors.OBJECT_NOT_FOUND,\n message: `[removeObject] Object not found | bucket: ${EchoUtility.toSafeText({ value: bucket.name })} | key: ${EchoUtility.toSafeText({ value: object.key })}`,\n });\n }\n\n await fsp.unlink(objectPath);\n }\n\n // Bounded concurrency; one failure stops the batch.\n async removeObjects(opts: { bucket: IBucketRef; objects: IObjectRef[] }): Promise<void> {\n const { bucket, objects } = opts;\n\n await this.mapWithConcurrency({\n items: objects,\n task: ({ item: object }) => this.removeObject({ bucket, object }),\n });\n }\n\n async listObjects(opts: IListObjectsOptions): Promise<IObjectInfo[]> {\n const { bucket, prefix = '', useRecursive = false, maxKeys } = opts;\n\n if (!this.isValidBucketName({ bucket })) {\n throw getError({\n message: `[listObjects] Invalid bucket name | bucket: ${EchoUtility.toSafeText({ value: bucket.name })}`,\n });\n }\n\n // `maxKeys: 0` means zero, not unlimited.\n const limit = maxKeys ?? Number.POSITIVE_INFINITY;\n\n if (limit <= 0) {\n return [];\n }\n\n const bucketPath = this.getBucketPath({ bucket });\n const result = await this.isReachableBucketPath({ target: bucketPath });\n\n if (!result) {\n return [];\n }\n\n const objects: IObjectInfo[] = [];\n\n const scanDirectory = async (scanOptions: {\n directory: { path: string; prefix?: string };\n }): Promise<void> => {\n const { directory } = scanOptions;\n\n if (objects.length >= limit) {\n return;\n }\n\n const entries = await fsp.readdir(directory.path, { withFileTypes: true });\n\n for (const entry of entries) {\n if (objects.length >= limit) {\n return;\n }\n\n // An object key always joins on '/'; `path.join` would emit '\\' on Windows.\n const entryKey = directory.prefix ? `${directory.prefix}/${entry.name}` : entry.name;\n const entryPath = path.join(directory.path, entry.name);\n\n if (entry.isDirectory()) {\n // A prefix that cannot match below here makes descending pointless.\n const canMatch = !prefix || prefix.startsWith(entryKey) || entryKey.startsWith(prefix);\n\n if (useRecursive && canMatch) {\n await scanDirectory({ directory: { path: entryPath, prefix: entryKey } });\n }\n\n continue;\n }\n\n if (!entry.isFile() || (prefix && !entryKey.startsWith(prefix))) {\n continue;\n }\n\n const stat = await this.statOrNull({ target: entryPath });\n\n if (!stat) {\n continue;\n }\n\n objects.push({ name: entryKey, size: stat.size, lastModified: stat.mtime });\n }\n };\n\n await scanDirectory({ directory: { path: bucketPath } });\n\n return objects;\n }\n}\n"]}
|
|
@@ -53,4 +53,30 @@ export declare const MIN_UID_ALPHABET_SIZE = 16;
|
|
|
53
53
|
export declare const DEFAULT_UID_MAX_ATTEMPTS = 10;
|
|
54
54
|
/** Separates the prefix from the body when both are enabled. Not in any {@link UidAlphabets} set, so an id splits back apart cleanly. */
|
|
55
55
|
export declare const DEFAULT_UID_DELIMITER = "_";
|
|
56
|
+
/** How a token is written as text. */
|
|
57
|
+
export declare class UidTokenEncodings {
|
|
58
|
+
/**
|
|
59
|
+
* `0-9 A-Z a-z`, each character equally likely ({@link UidAlphabets.BASE62}). 32 bytes of entropy is
|
|
60
|
+
* 43 characters. The default: its alphabet holds no `_` or `-`, so a prefix delimiter and a URL both take it cleanly.
|
|
61
|
+
*/
|
|
62
|
+
static readonly BASE62 = "base62";
|
|
63
|
+
/** Lowercase `0-9 a-f`. 32 bytes is 64 characters. Safe anywhere text is, including a case-insensitive column. */
|
|
64
|
+
static readonly HEX = "hex";
|
|
65
|
+
/**
|
|
66
|
+
* URL-safe base64 without padding: `A-Z a-z 0-9 - _`. 32 bytes is 43 characters. Kept for a token
|
|
67
|
+
* whose format already is base64url (the mail verification token). It holds `-` and `_`, the
|
|
68
|
+
* characters a delimiter is made of, so a prefix delimiter is refused unless it avoids both.
|
|
69
|
+
*/
|
|
70
|
+
static readonly BASE64URL = "base64url";
|
|
71
|
+
static readonly SCHEME_SET: Set<string>;
|
|
72
|
+
static isValid(input: string): input is TUidTokenEncoding;
|
|
73
|
+
}
|
|
74
|
+
/** A value of {@link UidTokenEncodings}. */
|
|
75
|
+
export type TUidTokenEncoding = TConstValue<typeof UidTokenEncodings>;
|
|
76
|
+
/** 32 bytes is 256 bits, the size of a SHA-256 output and of an AES-256 key: no brute force reaches it. */
|
|
77
|
+
export declare const DEFAULT_TOKEN_BYTES = 32;
|
|
78
|
+
/** 128 bits. Below this a token can be guessed offline, so the constructor refuses it. */
|
|
79
|
+
export declare const MIN_TOKEN_BYTES = 16;
|
|
80
|
+
/** Six digits is the length of a one-time code in an email or an app: 10^6 combinations, which is why it needs an expiry and an attempt limit. */
|
|
81
|
+
export declare const DEFAULT_NUMERIC_LENGTH = 6;
|
|
56
82
|
//# sourceMappingURL=constants.d.ts.map
|
|
@@ -55,4 +55,31 @@ export const MIN_UID_ALPHABET_SIZE = 16;
|
|
|
55
55
|
export const DEFAULT_UID_MAX_ATTEMPTS = 10;
|
|
56
56
|
/** Separates the prefix from the body when both are enabled. Not in any {@link UidAlphabets} set, so an id splits back apart cleanly. */
|
|
57
57
|
export const DEFAULT_UID_DELIMITER = '_';
|
|
58
|
+
// -------------------------------------------------------------
|
|
59
|
+
/** How a token is written as text. */
|
|
60
|
+
export class UidTokenEncodings {
|
|
61
|
+
/**
|
|
62
|
+
* `0-9 A-Z a-z`, each character equally likely ({@link UidAlphabets.BASE62}). 32 bytes of entropy is
|
|
63
|
+
* 43 characters. The default: its alphabet holds no `_` or `-`, so a prefix delimiter and a URL both take it cleanly.
|
|
64
|
+
*/
|
|
65
|
+
static { this.BASE62 = 'base62'; }
|
|
66
|
+
/** Lowercase `0-9 a-f`. 32 bytes is 64 characters. Safe anywhere text is, including a case-insensitive column. */
|
|
67
|
+
static { this.HEX = 'hex'; }
|
|
68
|
+
/**
|
|
69
|
+
* URL-safe base64 without padding: `A-Z a-z 0-9 - _`. 32 bytes is 43 characters. Kept for a token
|
|
70
|
+
* whose format already is base64url (the mail verification token). It holds `-` and `_`, the
|
|
71
|
+
* characters a delimiter is made of, so a prefix delimiter is refused unless it avoids both.
|
|
72
|
+
*/
|
|
73
|
+
static { this.BASE64URL = 'base64url'; }
|
|
74
|
+
static { this.SCHEME_SET = new Set([this.BASE62, this.HEX, this.BASE64URL]); }
|
|
75
|
+
static isValid(input) {
|
|
76
|
+
return this.SCHEME_SET.has(input);
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
/** 32 bytes is 256 bits, the size of a SHA-256 output and of an AES-256 key: no brute force reaches it. */
|
|
80
|
+
export const DEFAULT_TOKEN_BYTES = 32;
|
|
81
|
+
/** 128 bits. Below this a token can be guessed offline, so the constructor refuses it. */
|
|
82
|
+
export const MIN_TOKEN_BYTES = 16;
|
|
83
|
+
/** Six digits is the length of a one-time code in an email or an app: 10^6 combinations, which is why it needs an expiry and an attempt limit. */
|
|
84
|
+
export const DEFAULT_NUMERIC_LENGTH = 6;
|
|
58
85
|
//# sourceMappingURL=constants.js.map
|