@zeruxjs/files 0.0.0-stage → 0.0.1
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/LICENSE-APACHE +201 -0
- package/LICENSE-MIT +9 -0
- package/README.md +63 -2
- package/dist/authorization.d.ts +25 -0
- package/dist/authorization.js +27 -0
- package/dist/authorization.js.map +1 -0
- package/dist/aws-credentials.d.ts +43 -0
- package/dist/aws-credentials.js +64 -0
- package/dist/aws-credentials.js.map +1 -0
- package/dist/cache.d.ts +22 -0
- package/dist/cache.js +49 -0
- package/dist/cache.js.map +1 -0
- package/dist/client.d.ts +18 -0
- package/dist/client.js +38 -0
- package/dist/client.js.map +1 -0
- package/dist/drivers/local.d.ts +8 -0
- package/dist/drivers/local.js +277 -0
- package/dist/drivers/local.js.map +1 -0
- package/dist/drivers/s3.d.ts +54 -0
- package/dist/drivers/s3.js +219 -0
- package/dist/drivers/s3.js.map +1 -0
- package/dist/http.d.ts +23 -0
- package/dist/http.js +157 -0
- package/dist/http.js.map +1 -0
- package/dist/index.d.ts +10 -0
- package/dist/index.js +11 -0
- package/dist/index.js.map +1 -0
- package/dist/manager.d.ts +2 -0
- package/dist/manager.js +171 -0
- package/dist/manager.js.map +1 -0
- package/dist/types.d.ts +104 -0
- package/dist/types.js +2 -0
- package/dist/types.js.map +1 -0
- package/dist/validation.d.ts +9 -0
- package/dist/validation.js +84 -0
- package/dist/validation.js.map +1 -0
- package/package.json +42 -4
package/LICENSE-APACHE
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright [yyyy] [name of copyright owner]
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
package/LICENSE-MIT
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
The MIT License (MIT)
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 ZeruxJS.
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
|
|
6
|
+
|
|
7
|
+
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
|
|
8
|
+
|
|
9
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,64 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @zeruxjs/files
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Multiple named storage connectors for binary objects, including local **S3-lite** and AWS S3-compatible providers (MinIO, RustFS, Ceph, etc.). A common bucket/key API supports uploads, downloads, streaming, ranges, metadata, copies, list, delete, public/private visibility, expiring URLs (where supported), and an optional bounded public-byte cache.
|
|
4
|
+
|
|
5
|
+
## Storage manager
|
|
6
|
+
|
|
7
|
+
```ts
|
|
8
|
+
import {createFileManager, createLocalStorage, createS3Storage, createFileResponse, uploadFileRequest} from '@zeruxjs/files';
|
|
9
|
+
|
|
10
|
+
const files = createFileManager({
|
|
11
|
+
defaultStorage:'local',
|
|
12
|
+
cache:{maxEntries:200,maxBytes:32*1024*1024,ttlMs:30_000},
|
|
13
|
+
stores:[
|
|
14
|
+
{name:'local',driver:createLocalStorage({root:'./private/files'})},
|
|
15
|
+
{name:'object',driver:createS3Storage({
|
|
16
|
+
region:'us-east-1',endpoint:'https://s3.internal.example',forcePathStyle:true,
|
|
17
|
+
credentials:{accessKeyId:process.env.S3_ACCESS_KEY!,secretAccessKey:process.env.S3_SECRET_KEY!},
|
|
18
|
+
encryption:{mode:'AES256'}
|
|
19
|
+
}),allowedBuckets:['uploads']}
|
|
20
|
+
]
|
|
21
|
+
});
|
|
22
|
+
|
|
23
|
+
const addr={storage:'local',bucket:'uploads',key:'images/photo.webp'};
|
|
24
|
+
await files.put(addr,new Uint8Array([1,2,3]),{contentType:'image/webp',visibility:'private'});
|
|
25
|
+
await files.stat(addr);
|
|
26
|
+
for await(const bytes of await files.read(addr)) {/* consume with backpressure */}
|
|
27
|
+
await files.copy(addr,{storage:'object',bucket:'uploads',key:'images/photo.webp'});
|
|
28
|
+
await files.close();
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
The same S3 adapter works with **AWS**, **MinIO**, **RustFS** and S3-compatible endpoints using `endpoint`, `region`, `forcePathStyle`, and `allowInsecureHttp` (only for trusted local connections). Third-party implementations may differ in multipart, KMS, ACL, signing and versioning support; verify against your provider. The `publicUrl` method is a URL formatter, not permission authorization.
|
|
32
|
+
|
|
33
|
+
### AWS credentials and encryption
|
|
34
|
+
|
|
35
|
+
Credential modes are mutually exclusive: AWS SDK **default credential provider chain**, `profile`, explicit `credentials`, `assumeRole` (STS with source credentials/profile, optional external ID/MFA), or `webIdentity` (OIDC token file + role ARN). An ARN identifies the target role; you still need a trusted source identity allowed to assume it.
|
|
36
|
+
|
|
37
|
+
For AWS S3, choose `encryption:{mode:'AES256'}`, `encryption:{mode:'aws:kms',keyId:'alias/uploads',bucketKeyEnabled:true}`, or `encryption:{mode:'SSE-C',customerKeyBase64:'...'}`. Use HTTPS for customer-provided encryption keys. Your IAM/bucket/KMS policies must authorize the requested operation. For CloudFront URL signing configure `publicBaseUrl` plus `cloudFrontSigning:{keyPairId,privateKey}`; URL signing does not itself configure your distribution or origin access.
|
|
38
|
+
|
|
39
|
+
The S3-specific client is accessible to trusted server code via `getClient()`, so advanced AWS operations (bucket policies, lifecycle, versioning, replication, multipart cleanup, etc.) can be done with official AWS SDK commands instead of promising storage-independent abstractions.
|
|
40
|
+
|
|
41
|
+
### HTTP streaming and authorization
|
|
42
|
+
|
|
43
|
+
```ts
|
|
44
|
+
// In an authenticated GET/HEAD application route:
|
|
45
|
+
return createFileResponse(files,addr,request,{
|
|
46
|
+
authorize: async(req,addr,action)=>await canAccessFile(req,addr,action),
|
|
47
|
+
inline:true
|
|
48
|
+
});
|
|
49
|
+
// In an authenticated PUT/POST application route:
|
|
50
|
+
return uploadFileRequest(files,addr,request,{
|
|
51
|
+
maxBytes:16*1024*1024,visibility:'private',
|
|
52
|
+
authorize: async(req,addr,action)=>await canAccessFile(req,addr,action)
|
|
53
|
+
});
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
File downloads use Fetch streams, ETags, conditional requests and single byte ranges where the storage backend supports them. Private files require an authorization callback in `createFileResponse`. Never expose a handler without authenticating uploads or checking write permission; `@zeruxjs/auth` may be used in these callbacks. For any file type, prefer attachment download unless a carefully allowlisted inline type is required. Encryption-aware local storage verifies AES-GCM authentication before emitting plaintext; encrypted local objects do not support byte ranges.
|
|
57
|
+
|
|
58
|
+
Local S3-lite is S3-**style** object addressing; it is *not* an HTTP server implementing the entire AWS S3 wire API. If you need third-party S3 SDK clients connecting over HTTP, use MinIO/RustFS or another actual S3 server.
|
|
59
|
+
|
|
60
|
+
Install official AWS SDK modules including `@aws-sdk/client-s3`, `@aws-sdk/lib-storage`, `@aws-sdk/credential-providers`, `@aws-sdk/s3-request-presigner`, and `@aws-sdk/cloudfront-signer`. The runtime imports them lazily. SDK integration tests use an injected client, not live cloud infrastructure.
|
|
61
|
+
|
|
62
|
+
### Section 80 streamed request/copy safety
|
|
63
|
+
|
|
64
|
+
Fetch uploads validate a declared `Content-Length` **inside the stream** and reject missing/excess bytes before storage commits; they do not delete already-committed keys as cleanup. All manager copies, including storage-native copies, enforce destination `allowedTypes` and `maxBytes`. Do not use a signed PUT or raw driver call as a substitute for tenant authorization. Native S3 multipart create-only behavior needs real-provider concurrency tests.
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import type { FileAddress, FileInfo } from './types.js';
|
|
2
|
+
/** Minimal structural contract accepted from @zeruxjs/auth token stores or external token validators. */
|
|
3
|
+
export interface StorageTokenVerifier {
|
|
4
|
+
verify(token: string, scope?: string): {
|
|
5
|
+
subject: string;
|
|
6
|
+
scopes: string[];
|
|
7
|
+
} | null | Promise<{
|
|
8
|
+
subject: string;
|
|
9
|
+
scopes: string[];
|
|
10
|
+
} | null>;
|
|
11
|
+
}
|
|
12
|
+
export interface StorageTokenAuthOptions {
|
|
13
|
+
/** Permission naming: e.g. files:read:photos, files:write:photos, files:delete:photos. */
|
|
14
|
+
scopePrefix?: string;
|
|
15
|
+
/** Explicitly allow anonymous reads of objects marked public. Defaults false. */
|
|
16
|
+
publicRead?: boolean;
|
|
17
|
+
/** Optional principal/tenant policy evaluated after token validation. */
|
|
18
|
+
allow?: (subject: string, address: FileAddress, action: 'read' | 'write' | 'delete', info?: FileInfo) => boolean | Promise<boolean>;
|
|
19
|
+
}
|
|
20
|
+
/**
|
|
21
|
+
* Bridges the scoped token store in @zeruxjs/auth without adding a hard runtime dependency.
|
|
22
|
+
* Never trusts an unverified X-User, forwarded identity or query-string token.
|
|
23
|
+
* The token store here is in-memory; production multi-node deployments need shared persistence.
|
|
24
|
+
*/
|
|
25
|
+
export declare function createFileTokenAuthorizer(store: StorageTokenVerifier, options?: StorageTokenAuthOptions): (request: Request, address: FileAddress, action: "read" | "write" | "delete", info?: FileInfo) => Promise<boolean>;
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Bridges the scoped token store in @zeruxjs/auth without adding a hard runtime dependency.
|
|
3
|
+
* Never trusts an unverified X-User, forwarded identity or query-string token.
|
|
4
|
+
* The token store here is in-memory; production multi-node deployments need shared persistence.
|
|
5
|
+
*/
|
|
6
|
+
export function createFileTokenAuthorizer(store, options = {}) {
|
|
7
|
+
if (!store || typeof store.verify !== 'function')
|
|
8
|
+
throw new TypeError('Token verifier required');
|
|
9
|
+
const prefix = options.scopePrefix ?? 'files';
|
|
10
|
+
if (!/^[A-Za-z0-9:_-]{1,64}$/.test(prefix))
|
|
11
|
+
throw new TypeError('Invalid scope prefix');
|
|
12
|
+
return async (request, address, action, info) => {
|
|
13
|
+
if (action === 'read' && options.publicRead && info?.visibility === 'public')
|
|
14
|
+
return true;
|
|
15
|
+
const header = request.headers.get('authorization') ?? '';
|
|
16
|
+
const match = /^Bearer ([A-Za-z0-9_.-]{1,256})$/.exec(header);
|
|
17
|
+
if (!match)
|
|
18
|
+
return false;
|
|
19
|
+
const record = await store.verify(match[1], `${prefix}:${action}:${address.bucket}`);
|
|
20
|
+
// Also permit a global permission explicitly issued by the application.
|
|
21
|
+
const identity = record ?? await store.verify(match[1], `${prefix}:${action}:*`);
|
|
22
|
+
if (!identity)
|
|
23
|
+
return false;
|
|
24
|
+
return options.allow ? !!await options.allow(identity.subject, address, action, info) : true;
|
|
25
|
+
};
|
|
26
|
+
}
|
|
27
|
+
//# sourceMappingURL=authorization.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"authorization.js","sourceRoot":"","sources":["../src/authorization.ts"],"names":[],"mappings":"AAaA;;;;GAIG;AACH,MAAM,UAAU,yBAAyB,CAAC,KAA2B,EAAE,UAAmC,EAAE;IAC1G,IAAI,CAAC,KAAK,IAAI,OAAO,KAAK,CAAC,MAAM,KAAK,UAAU;QAAE,MAAM,IAAI,SAAS,CAAC,yBAAyB,CAAC,CAAC;IACjG,MAAM,MAAM,GAAG,OAAO,CAAC,WAAW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yId: string;
|
|
4
|
+
secretAccessKey: string;
|
|
5
|
+
sessionToken?: string;
|
|
6
|
+
}
|
|
7
|
+
export type AwsCredentialProvider = () => Promise<AwsKeyCredentials>;
|
|
8
|
+
export interface AssumeRoleOptions {
|
|
9
|
+
roleArn: string;
|
|
10
|
+
sessionName?: string;
|
|
11
|
+
externalId?: string;
|
|
12
|
+
durationSeconds?: number;
|
|
13
|
+
/** MFA code and serial (when trust policy demands MFA). Prefer short-lived credentials. */
|
|
14
|
+
mfa?: {
|
|
15
|
+
serial: string;
|
|
16
|
+
tokenCode: string;
|
|
17
|
+
};
|
|
18
|
+
/** Source identity: explicit credentials, profile, or the default AWS credential chain. */
|
|
19
|
+
sourceCredentials?: AwsKeyCredentials | AwsCredentialProvider;
|
|
20
|
+
sourceProfile?: string;
|
|
21
|
+
/** Region for STS; defaults to the S3 region. */
|
|
22
|
+
stsRegion?: string;
|
|
23
|
+
}
|
|
24
|
+
export interface WebIdentityOptions {
|
|
25
|
+
roleArn: string;
|
|
26
|
+
tokenFile: string;
|
|
27
|
+
sessionName?: string;
|
|
28
|
+
stsRegion?: string;
|
|
29
|
+
}
|
|
30
|
+
export interface AwsCredentialOptions {
|
|
31
|
+
credentials?: AwsKeyCredentials | AwsCredentialProvider;
|
|
32
|
+
profile?: string;
|
|
33
|
+
assumeRole?: AssumeRoleOptions;
|
|
34
|
+
webIdentity?: WebIdentityOptions;
|
|
35
|
+
}
|
|
36
|
+
export declare function assertRoleArn(value: string): void;
|
|
37
|
+
export declare function validateAwsCredentialOptions(input: AwsCredentialOptions): void;
|
|
38
|
+
/**
|
|
39
|
+
* Returns undefined to let S3Client use the complete AWS default provider chain:
|
|
40
|
+
* environment, SSO, shared config, IAM Identity Center, ECS/EKS, EC2 metadata, etc.
|
|
41
|
+
* The official AWS SDK refreshes assumed-role / web-identity credentials automatically.
|
|
42
|
+
*/
|
|
43
|
+
export declare function resolveAwsCredentials(input: AwsCredentialOptions, region: string): Promise<AwsKeyCredentials | AwsCredentialProvider | undefined>;
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
const rolePattern = /^arn:(aws|aws-cn|aws-us-gov):iam::\d{12}:role\/[A-Za-z0-9_+=,.@/-]{1,512}$/;
|
|
2
|
+
export function assertRoleArn(value) {
|
|
3
|
+
if (typeof value !== 'string' || !rolePattern.test(value))
|
|
4
|
+
throw new TypeError('A valid IAM role ARN is required');
|
|
5
|
+
}
|
|
6
|
+
export function validateAwsCredentialOptions(input) {
|
|
7
|
+
const choices = [input.credentials !== undefined, input.profile !== undefined, input.assumeRole !== undefined, input.webIdentity !== undefined];
|
|
8
|
+
if (choices.filter(Boolean).length > 1)
|
|
9
|
+
throw new TypeError('Choose exactly one top-level AWS credential mode');
|
|
10
|
+
if (input.profile !== undefined && !/^[A-Za-z0-9_+=,.@-]{1,128}$/.test(input.profile))
|
|
11
|
+
throw new TypeError('Invalid AWS profile');
|
|
12
|
+
if (input.assumeRole) {
|
|
13
|
+
const role = input.assumeRole;
|
|
14
|
+
assertRoleArn(role.roleArn);
|
|
15
|
+
if (role.sourceCredentials && role.sourceProfile)
|
|
16
|
+
throw new TypeError('Choose one role source credential mode');
|
|
17
|
+
if (role.sourceProfile && !/^[A-Za-z0-9_+=,.@-]{1,128}$/.test(role.sourceProfile))
|
|
18
|
+
throw new TypeError('Invalid source profile');
|
|
19
|
+
if (role.externalId !== undefined && (!role.externalId || role.externalId.length > 1224))
|
|
20
|
+
throw new TypeError('Invalid role external ID');
|
|
21
|
+
if (role.durationSeconds !== undefined && (!Number.isSafeInteger(role.durationSeconds) || role.durationSeconds < 900 || role.durationSeconds > 43200))
|
|
22
|
+
throw new RangeError('Invalid STS role duration');
|
|
23
|
+
if (role.mfa && (!/^arn:(aws|aws-cn|aws-us-gov):iam::\d{12}:mfa\/[A-Za-z0-9_+=,.@/-]{1,512}$/.test(role.mfa.serial) || !/^[0-9]{6,8}$/.test(role.mfa.tokenCode)))
|
|
24
|
+
throw new TypeError('Invalid role MFA details');
|
|
25
|
+
}
|
|
26
|
+
if (input.webIdentity) {
|
|
27
|
+
assertRoleArn(input.webIdentity.roleArn);
|
|
28
|
+
if (!input.webIdentity.tokenFile || input.webIdentity.tokenFile.includes('\0'))
|
|
29
|
+
throw new TypeError('Invalid OIDC token file');
|
|
30
|
+
}
|
|
31
|
+
for (const credentials of [input.credentials, input.assumeRole?.sourceCredentials]) {
|
|
32
|
+
if (credentials && typeof credentials !== 'function' && (typeof credentials.accessKeyId !== 'string' || !credentials.accessKeyId || typeof credentials.secretAccessKey !== 'string' || !credentials.secretAccessKey))
|
|
33
|
+
throw new TypeError('Invalid AWS access key credentials');
|
|
34
|
+
}
|
|
35
|
+
for (const name of [input.assumeRole?.sessionName, input.webIdentity?.sessionName]) {
|
|
36
|
+
if (name !== undefined && !/^[A-Za-z0-9_+=,.@-]{2,64}$/.test(name))
|
|
37
|
+
throw new TypeError('Invalid AWS role session name');
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
/**
|
|
41
|
+
* Returns undefined to let S3Client use the complete AWS default provider chain:
|
|
42
|
+
* environment, SSO, shared config, IAM Identity Center, ECS/EKS, EC2 metadata, etc.
|
|
43
|
+
* The official AWS SDK refreshes assumed-role / web-identity credentials automatically.
|
|
44
|
+
*/
|
|
45
|
+
export async function resolveAwsCredentials(input, region) {
|
|
46
|
+
validateAwsCredentialOptions(input);
|
|
47
|
+
if (input.credentials)
|
|
48
|
+
return input.credentials;
|
|
49
|
+
if (input.profile) {
|
|
50
|
+
const { fromIni } = await import('@aws-sdk/credential-providers');
|
|
51
|
+
return fromIni({ profile: input.profile, clientConfig: { region } });
|
|
52
|
+
}
|
|
53
|
+
if (input.assumeRole) {
|
|
54
|
+
const role = input.assumeRole, { fromTemporaryCredentials, fromIni } = await import('@aws-sdk/credential-providers');
|
|
55
|
+
const masterCredentials = role.sourceCredentials ?? (role.sourceProfile ? fromIni({ profile: role.sourceProfile, clientConfig: { region: role.stsRegion ?? region } }) : undefined);
|
|
56
|
+
return fromTemporaryCredentials({ clientConfig: { region: role.stsRegion ?? region }, masterCredentials, params: { RoleArn: role.roleArn, RoleSessionName: role.sessionName ?? 'zerux-files', ExternalId: role.externalId, DurationSeconds: role.durationSeconds, ...(role.mfa ? { SerialNumber: role.mfa.serial, TokenCode: role.mfa.tokenCode } : {}) } });
|
|
57
|
+
}
|
|
58
|
+
if (input.webIdentity) {
|
|
59
|
+
const role = input.webIdentity, { fromTokenFile } = await import('@aws-sdk/credential-providers');
|
|
60
|
+
return fromTokenFile({ roleArn: role.roleArn, webIdentityTokenFile: role.tokenFile, roleSessionName: role.sessionName ?? 'zerux-files', clientConfig: { region: role.stsRegion ?? region } });
|
|
61
|
+
}
|
|
62
|
+
return undefined;
|
|
63
|
+
}
|
|
64
|
+
//# sourceMappingURL=aws-credentials.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"aws-credentials.js","sourceRoot":"","sources":["../src/aws-credentials.ts"],"names":[],"mappings":"AA4BA,MAAM,WAAW,GAAG,4EAA4E,CAAC;AACjG,MAAM,UAAU,aAAa,CAAC,KAAa;IACzC,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,CAAC,WAAW,CAAC,IAAI,CAAC,KAAK,CAAC;QAAE,MAAM,IAAI,SAAS,CAAC,kCAAkC,CAAC,CAAC;AACrH,CAAC;AACD,MAAM,UAAU,4BAA4B,CAAC,KAA2B;IACtE,MAAM,OAAO,GAAC,CAAC,KAAK,CAAC,WAAW,KAAG,SAAS,EAAC,KAAK,CAAC,OAAO,KAAG,SAAS,EAAC,KAAK,CAAC,UAAU,KAAG,SAAS,EAAC,KAAK,CAAC,WAAW,KAAG,SAAS,CAAC,CAAC;IACnI,IAAI,OAAO,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC,MAAM,GAAC,CAAC;QAAE,MAAM,IAAI,SAAS,CAAC,kDAAkD,CAAC,CAAC;IAC9G,IAAI,KAAK,CAAC,OAAO,KAAK,SAAS,IAAI,CAAC,6BAA6B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AAC,SAAS,EAAC,eAAe,EAAC,IAAI,CAAC,WAAW,IAAE,aAAa,EAAC,YAAY,EAAC,EAAC,MAAM,EAAC,IAAI,CAAC,SAAS,IAAE,MAAM,EAAC,EAAC,CAAC,CAAC;IAAA,CAAC;IAChS,OAAO,SAAS,CAAC;AACnB,CAAC"}
|
package/dist/cache.d.ts
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
/** In-memory bounded public-object cache: never cache private or encrypted objects. */
|
|
2
|
+
export declare class FileByteCache {
|
|
3
|
+
private readonly maxEntries;
|
|
4
|
+
private readonly maxBytes;
|
|
5
|
+
private readonly ttlMs;
|
|
6
|
+
private readonly entries;
|
|
7
|
+
private bytes;
|
|
8
|
+
private hits;
|
|
9
|
+
private misses;
|
|
10
|
+
constructor(maxEntries?: number, maxBytes?: number, ttlMs?: number);
|
|
11
|
+
get(key: string): Uint8Array | undefined;
|
|
12
|
+
set(key: string, data: Uint8Array): void;
|
|
13
|
+
delete(key: string): void;
|
|
14
|
+
deletePrefix(prefix: string): void;
|
|
15
|
+
clear(): void;
|
|
16
|
+
stats(): {
|
|
17
|
+
entries: number;
|
|
18
|
+
bytes: number;
|
|
19
|
+
hits: number;
|
|
20
|
+
misses: number;
|
|
21
|
+
};
|
|
22
|
+
}
|
package/dist/cache.js
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
/** In-memory bounded public-object cache: never cache private or encrypted objects. */
|
|
2
|
+
export class FileByteCache {
|
|
3
|
+
maxEntries;
|
|
4
|
+
maxBytes;
|
|
5
|
+
ttlMs;
|
|
6
|
+
entries = new Map();
|
|
7
|
+
bytes = 0;
|
|
8
|
+
hits = 0;
|
|
9
|
+
misses = 0;
|
|
10
|
+
constructor(maxEntries = 64, maxBytes = 8 * 1024 * 1024, ttlMs = 15000) {
|
|
11
|
+
this.maxEntries = maxEntries;
|
|
12
|
+
this.maxBytes = maxBytes;
|
|
13
|
+
this.ttlMs = ttlMs;
|
|
14
|
+
if (![maxEntries, maxBytes, ttlMs].every(n => Number.isSafeInteger(n) && n > 0))
|
|
15
|
+
throw new RangeError('Invalid file cache limits');
|
|
16
|
+
}
|
|
17
|
+
get(key) {
|
|
18
|
+
const hit = this.entries.get(key);
|
|
19
|
+
if (!hit || Date.now() > hit.expires) {
|
|
20
|
+
this.misses++;
|
|
21
|
+
if (hit)
|
|
22
|
+
this.delete(key);
|
|
23
|
+
return undefined;
|
|
24
|
+
}
|
|
25
|
+
this.hits++;
|
|
26
|
+
this.entries.delete(key);
|
|
27
|
+
this.entries.set(key, hit);
|
|
28
|
+
return hit.data.slice();
|
|
29
|
+
}
|
|
30
|
+
set(key, data) {
|
|
31
|
+
if (data.byteLength > this.maxBytes)
|
|
32
|
+
return;
|
|
33
|
+
this.delete(key);
|
|
34
|
+
this.entries.set(key, { data: data.slice(), expires: Date.now() + this.ttlMs });
|
|
35
|
+
this.bytes += data.byteLength;
|
|
36
|
+
while (this.entries.size > this.maxEntries || this.bytes > this.maxBytes)
|
|
37
|
+
this.delete(this.entries.keys().next().value);
|
|
38
|
+
}
|
|
39
|
+
delete(key) { const entry = this.entries.get(key); if (entry) {
|
|
40
|
+
this.bytes -= entry.data.byteLength;
|
|
41
|
+
this.entries.delete(key);
|
|
42
|
+
} }
|
|
43
|
+
deletePrefix(prefix) { for (const key of [...this.entries.keys()])
|
|
44
|
+
if (key.startsWith(prefix))
|
|
45
|
+
this.delete(key); }
|
|
46
|
+
clear() { this.entries.clear(); this.bytes = 0; }
|
|
47
|
+
stats() { return { entries: this.entries.size, bytes: this.bytes, hits: this.hits, misses: this.misses }; }
|
|
48
|
+
}
|
|
49
|
+
//# sourceMappingURL=cache.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"cache.js","sourceRoot":"","sources":["../src/cache.ts"],"names":[],"mappings":"AAAA,uFAAuF;AACvF,MAAM,OAAO,aAAa;IAGK;IAAkC;IAAyC;IAFvF,OAAO,GAAG,IAAI,GAAG,EAA2C,CAAC;I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AM,EAAC,IAAI,CAAC,MAAM,EAAC,CAAC,CAAA,CAAC;CAChG"}
|
package/dist/client.d.ts
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
/** Lightweight Fetch client; safe to import in browsers without Node/AWS dependencies. */
|
|
2
|
+
export declare function createFilesClient(options: {
|
|
3
|
+
baseUrl: string;
|
|
4
|
+
fetch?: typeof fetch;
|
|
5
|
+
headers?: Record<string, string>;
|
|
6
|
+
}): {
|
|
7
|
+
upload(key: string, data: Blob | Uint8Array | ReadableStream<Uint8Array>, opts?: {
|
|
8
|
+
contentType?: string;
|
|
9
|
+
signal?: AbortSignal;
|
|
10
|
+
}): Promise<any>;
|
|
11
|
+
download(key: string, opts?: {
|
|
12
|
+
signal?: AbortSignal;
|
|
13
|
+
range?: string;
|
|
14
|
+
}): Promise<Response>;
|
|
15
|
+
bytes(key: string, maxBytes?: number): Promise<Uint8Array<ArrayBuffer>>;
|
|
16
|
+
head(key: string): Promise<Headers>;
|
|
17
|
+
remove(key: string): Promise<undefined>;
|
|
18
|
+
};
|
package/dist/client.js
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
/** Lightweight Fetch client; safe to import in browsers without Node/AWS dependencies. */
|
|
2
|
+
export function createFilesClient(options) {
|
|
3
|
+
const fetcher = options.fetch ?? fetch;
|
|
4
|
+
const base = new URL(options.baseUrl);
|
|
5
|
+
if (!['https:', 'http:'].includes(base.protocol))
|
|
6
|
+
throw new TypeError('Invalid files URL');
|
|
7
|
+
function path(key) { if (!key || key.split('/').some(s => !s || s === '.' || s === '..'))
|
|
8
|
+
throw new TypeError('Invalid file key'); const url = new URL(base.toString()); url.pathname = base.pathname.replace(/\/?$/, '/') + key.split('/').map(encodeURIComponent).join('/'); return url.toString(); }
|
|
9
|
+
async function request(key, init) { const result = await fetcher(path(key), { ...init, headers: { ...options.headers, ...init.headers } }); if (!result.ok)
|
|
10
|
+
throw Object.assign(new Error(`File request failed: ${result.status}`), { status: result.status }); return result; }
|
|
11
|
+
return {
|
|
12
|
+
upload(key, data, opts = {}) { return request(key, { method: 'PUT', headers: { 'Content-Type': opts.contentType ?? 'application/octet-stream' }, body: data, signal: opts.signal, ...(data instanceof ReadableStream ? { duplex: 'half' } : {}) }).then(r => r.json()); },
|
|
13
|
+
download(key, opts = {}) { return request(key, { method: 'GET', headers: opts.range ? { Range: opts.range } : {}, signal: opts.signal }); },
|
|
14
|
+
async bytes(key, maxBytes = 16 * 1024 * 1024) { const response = await request(key, { method: 'GET' }); const length = Number(response.headers.get('content-length') ?? 0); if (length > maxBytes)
|
|
15
|
+
throw new RangeError('File too large'); const chunks = []; let total = 0; const reader = response.body?.getReader(); if (!reader)
|
|
16
|
+
return new Uint8Array(); try {
|
|
17
|
+
while (true) {
|
|
18
|
+
const part = await reader.read();
|
|
19
|
+
if (part.done)
|
|
20
|
+
break;
|
|
21
|
+
total += part.value.byteLength;
|
|
22
|
+
if (total > maxBytes)
|
|
23
|
+
throw new RangeError('File too large');
|
|
24
|
+
chunks.push(part.value);
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
finally {
|
|
28
|
+
await reader.cancel().catch(() => { });
|
|
29
|
+
reader.releaseLock();
|
|
30
|
+
} const output = new Uint8Array(total); let i = 0; for (const chunk of chunks) {
|
|
31
|
+
output.set(chunk, i);
|
|
32
|
+
i += chunk.byteLength;
|
|
33
|
+
} return output; },
|
|
34
|
+
head(key) { return request(key, { method: 'HEAD' }).then(r => r.headers); },
|
|
35
|
+
remove(key) { return request(key, { method: 'DELETE' }).then(() => undefined); }
|
|
36
|
+
};
|
|
37
|
+
}
|
|
38
|
+
//# sourceMappingURL=client.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"client.js","sourceRoot":"","sources":["../src/client.ts"],"names":[],"mappings":"AAAA,0FAA0F;AAC1F,MAAM,UAAU,iBAAiB,CAAC,OAA2E;IAC3G,MAAM,OAAO,GAAC,OAAO,CAAC,KAAK,IAAE,KAAK,CAAC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,EAAC,MAAM,EAAC,QAAQ,EAAC,CAAC,CAAC,IAAI,CAAC,GAAE,EAAE,CAAA,SAAS,CAAC,CAAA,CAAA,CAAC;KAC9E,CAAC;AACJ,CAAC"}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import type { StorageDriver } from '../types.js';
|
|
2
|
+
export interface LocalStorageOptions {
|
|
3
|
+
root: string;
|
|
4
|
+
/** 32-byte application-owned AES-256-GCM key; binary or base64-encoded. */
|
|
5
|
+
encryptionKey?: Uint8Array | string;
|
|
6
|
+
}
|
|
7
|
+
export declare function createLocalStorage(options: LocalStorageOptions): StorageDriver;
|
|
8
|
+
export declare const createS3LiteStorage: typeof createLocalStorage;
|