@univerjs-pro/collaboration-file-endpoint 0.0.0-stage → 1.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +201 -0
- package/README.md +81 -2
- package/README.zh-CN.md +92 -0
- package/dist/index.cjs +1 -0
- package/dist/index.d.ts +42 -0
- package/dist/index.mjs +3 -0
- package/package.json +34 -3
package/LICENSE
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/README.md
CHANGED
|
@@ -1,3 +1,82 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @univerjs-pro/collaboration-file-endpoint
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
English | [简体中文](./README.zh-CN.md)
|
|
4
|
+
|
|
5
|
+
`UniverFileEndpoint` serves the HTTP routes the Univer frontend calls for image and attachment uploads and for Office import and export. It maps each request to `@univerjs-pro/collaboration-file-service` and runs on `@univerjs-pro/collaboration-transport-node`.
|
|
6
|
+
|
|
7
|
+
```text
|
|
8
|
+
HTTP request
|
|
9
|
+
→ Transport authentication middleware (sets ctx.userID)
|
|
10
|
+
→ UniverFileEndpoint (multipart, inflate, limits, response headers)
|
|
11
|
+
→ UniverFileService (ownership rules, middleware)
|
|
12
|
+
→ metadata adapter and blob store
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
## Installation and registration
|
|
16
|
+
|
|
17
|
+
```bash
|
|
18
|
+
pnpm add \
|
|
19
|
+
@univerjs-pro/collaboration-file-service \
|
|
20
|
+
@univerjs-pro/collaboration-file-endpoint \
|
|
21
|
+
@univerjs-pro/collaboration-transport-node
|
|
22
|
+
```
|
|
23
|
+
|
|
24
|
+
```ts
|
|
25
|
+
const fileEndpoint = new UniverFileEndpoint(fileService, {
|
|
26
|
+
maxUploadBytes: 100 * 1024 * 1024,
|
|
27
|
+
});
|
|
28
|
+
|
|
29
|
+
transport.use(authenticationMiddleware);
|
|
30
|
+
transport.register(fileEndpoint);
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
Register the File Endpoint before Endpoints that build on the File Service, so that Transport disposes them first. The Endpoint does not dispose the File Service.
|
|
34
|
+
|
|
35
|
+
| Option | Default |
|
|
36
|
+
| --- | --- |
|
|
37
|
+
| `routePrefix` | `/universer-api`; absolute, without a trailing slash |
|
|
38
|
+
| `maxUploadBytes` | unlimited; counts bytes actually read, after inflate |
|
|
39
|
+
| `uploadTimeoutMs` | 600000 (10 minutes) from the start of the request |
|
|
40
|
+
| `downloadCacheMaxAgeSeconds` | 3600; `max-age` of proxy downloads, `0` makes browsers revalidate every time |
|
|
41
|
+
|
|
42
|
+
## Routes
|
|
43
|
+
|
|
44
|
+
| Method | Path | Response |
|
|
45
|
+
| --- | --- | --- |
|
|
46
|
+
| `POST` | `{prefix}/stream/file/upload?size=&source=&assign=&flate=` | `{ error, FileId }` |
|
|
47
|
+
| `GET` | `{prefix}/file/{fileID}/sign-url` | `{ error, url }` |
|
|
48
|
+
| `GET` | `{prefix}/file/{fileID}/download` | file content |
|
|
49
|
+
|
|
50
|
+
With the default prefix these are the URLs that `exchange-client` and `collaboration-client` use by default, so the clients only need `downloadEndpointUrl` when the API is not served from the page origin.
|
|
51
|
+
|
|
52
|
+
**Upload.** The body is `multipart/form-data`; the part named `file` is streamed to the blob store without buffering, so Transport `maxRequestBodyBytes` does not apply. `flate=true` means the part is raw DEFLATE and is inflated while reading. `size` is only a hint; the stored size is what was actually written, and empty files are accepted. `source` that is missing or not an integer is stored as `0`. A request that is rejected, too large or timed out is answered and the connection is closed instead of reading the rest of the body.
|
|
53
|
+
|
|
54
|
+
**sign-url.** Returns an absolute direct link when the blob store signs one, otherwise the relative path of the download route. Clients resolve relative paths against `downloadEndpointUrl`.
|
|
55
|
+
|
|
56
|
+
**Download.** Responses carry `Content-Type` from the record, `Content-Length`, `Content-Disposition: attachment` with the file name (RFC 6266, `filename*` for non-ASCII names), `X-Content-Type-Options: nosniff`, an `ETag` and `Cache-Control: private, max-age=<downloadCacheMaxAgeSeconds>, immutable`. Every file is served as an attachment; `<img>` embedding is not affected.
|
|
57
|
+
|
|
58
|
+
## Authentication
|
|
59
|
+
|
|
60
|
+
The Endpoint uses the `userID` that Transport middleware sets for the request and answers `401` when it is missing.
|
|
61
|
+
|
|
62
|
+
Images are loaded by the browser itself: the request carries cookies only when the file routes share the page's origin, and never carries the `Authorization` header the application adds to its own requests.
|
|
63
|
+
|
|
64
|
+
- **Cookie authentication, same origin:** proxy downloads work without extra configuration.
|
|
65
|
+
- **Cookie authentication, file routes on another origin** (a different subdomain counts): serve the file routes under the page's origin through a reverse proxy, or configure a blob store that signs direct links.
|
|
66
|
+
- **Bearer tokens only:** configure a blob store that signs direct links.
|
|
67
|
+
|
|
68
|
+
A direct link is authorized when it is issued through `sign-url` and needs no credentials when loaded.
|
|
69
|
+
|
|
70
|
+
## Errors
|
|
71
|
+
|
|
72
|
+
JSON routes always return a protocol `error` object; `error.code` is `OK` on success. Proxy download failures return a status code with a plain-text message.
|
|
73
|
+
|
|
74
|
+
| `FileError` code | HTTP | protocol `ErrorCode` |
|
|
75
|
+
| --- | --- | --- |
|
|
76
|
+
| `INVALID_REQUEST` | 400 | `INVALID_ARGUMENT` |
|
|
77
|
+
| `UNAUTHENTICATED` | 401 | `UNAUTHENTICATED` |
|
|
78
|
+
| `PERMISSION_DENIED` | 403 | `PERMISSION_DENIED` |
|
|
79
|
+
| `FILE_NOT_FOUND` | 404 | `NOT_FOUND` |
|
|
80
|
+
| `UPLOAD_TIMEOUT` | 408 | `INTERNAL_ERROR` |
|
|
81
|
+
| `PAYLOAD_TOO_LARGE` | 413 | `INVALID_ARGUMENT` |
|
|
82
|
+
| `STORAGE_FAILURE`, `SERVICE_DISPOSED` | 503 | `INTERNAL_ERROR` |
|
package/README.zh-CN.md
ADDED
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
# @univerjs-pro/collaboration-file-endpoint
|
|
2
|
+
|
|
3
|
+
[English](./README.md) | [简体中文](./README.zh-CN.md)
|
|
4
|
+
|
|
5
|
+
`UniverFileEndpoint` 提供 Univer 前端上传图片、附件以及 Office 导入导出时调用的 HTTP 路由。
|
|
6
|
+
它把每个请求映射到 `@univerjs-pro/collaboration-file-service`,运行在
|
|
7
|
+
`@univerjs-pro/collaboration-transport-node` 之上。
|
|
8
|
+
|
|
9
|
+
```text
|
|
10
|
+
HTTP 请求
|
|
11
|
+
→ Transport 认证 middleware(设置 ctx.userID)
|
|
12
|
+
→ UniverFileEndpoint(multipart、解压、限制、响应头)
|
|
13
|
+
→ UniverFileService(归属规则、middleware)
|
|
14
|
+
→ 元数据 adapter 与 blob store
|
|
15
|
+
```
|
|
16
|
+
|
|
17
|
+
## 安装与注册
|
|
18
|
+
|
|
19
|
+
```bash
|
|
20
|
+
pnpm add \
|
|
21
|
+
@univerjs-pro/collaboration-file-service \
|
|
22
|
+
@univerjs-pro/collaboration-file-endpoint \
|
|
23
|
+
@univerjs-pro/collaboration-transport-node
|
|
24
|
+
```
|
|
25
|
+
|
|
26
|
+
```ts
|
|
27
|
+
const fileEndpoint = new UniverFileEndpoint(fileService, {
|
|
28
|
+
maxUploadBytes: 100 * 1024 * 1024,
|
|
29
|
+
});
|
|
30
|
+
|
|
31
|
+
transport.use(authenticationMiddleware);
|
|
32
|
+
transport.register(fileEndpoint);
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
File Endpoint 要先于依赖 File Service 的其他 Endpoint 注册,这样 Transport 会先释放那些 Endpoint。
|
|
36
|
+
Endpoint 不会 dispose File Service。
|
|
37
|
+
|
|
38
|
+
| 选项 | 默认值 |
|
|
39
|
+
| --- | --- |
|
|
40
|
+
| `routePrefix` | `/universer-api`;绝对路径,不带末尾斜杠 |
|
|
41
|
+
| `maxUploadBytes` | 不限;按解压后实际读到的字节计数 |
|
|
42
|
+
| `uploadTimeoutMs` | 600000(10 分钟),从请求开始处理时计时 |
|
|
43
|
+
| `downloadCacheMaxAgeSeconds` | 3600;代理下载的 `max-age`,`0` 表示浏览器每次都重新确认 |
|
|
44
|
+
|
|
45
|
+
## 路由
|
|
46
|
+
|
|
47
|
+
| 方法 | 路径 | 响应 |
|
|
48
|
+
| --- | --- | --- |
|
|
49
|
+
| `POST` | `{prefix}/stream/file/upload?size=&source=&assign=&flate=` | `{ error, FileId }` |
|
|
50
|
+
| `GET` | `{prefix}/file/{fileID}/sign-url` | `{ error, url }` |
|
|
51
|
+
| `GET` | `{prefix}/file/{fileID}/download` | 文件内容 |
|
|
52
|
+
|
|
53
|
+
使用默认前缀时,这些就是 `exchange-client` 和 `collaboration-client` 默认请求的地址。只有 API 不在页面
|
|
54
|
+
同源下时,客户端才需要配置 `downloadEndpointUrl`。
|
|
55
|
+
|
|
56
|
+
**上传**:请求体为 `multipart/form-data`,名为 `file` 的 part 不经缓冲直接流式写入 blob store,
|
|
57
|
+
因此不受 Transport `maxRequestBodyBytes` 限制。`flate=true` 表示该 part 是 raw DEFLATE,读取时边读边解压。
|
|
58
|
+
`size` 只作提示,保存的大小是实际写入的字节数,允许上传空文件。`source` 缺失或不是整数时按 `0` 保存。
|
|
59
|
+
被拒绝、超出大小或超时的请求会立即响应并关闭连接,不再读取剩余的请求体。
|
|
60
|
+
|
|
61
|
+
**sign-url**:blob store 签发了直链时返回绝对 URL,否则返回下载路由的相对路径,客户端用
|
|
62
|
+
`downloadEndpointUrl` 解析相对路径。
|
|
63
|
+
|
|
64
|
+
**下载**:响应带记录中的 `Content-Type`、`Content-Length`、带文件名的 `Content-Disposition: attachment`(RFC 6266,非 ASCII 文件名带 `filename*`)、
|
|
65
|
+
`X-Content-Type-Options: nosniff`、`ETag` 以及 `Cache-Control: private, max-age=<downloadCacheMaxAgeSeconds>, immutable`。
|
|
66
|
+
所有文件都以附件形式返回,不影响 `<img>` 嵌入显示。
|
|
67
|
+
|
|
68
|
+
## 认证
|
|
69
|
+
|
|
70
|
+
Endpoint 使用 Transport 中间件为本次请求设置的 `userID`,缺失时返回 `401`。
|
|
71
|
+
|
|
72
|
+
图片由浏览器直接加载:只有文件路由与页面同源时,请求才会带 cookie;应用自己添加的 `Authorization` 头则始终不会带上。
|
|
73
|
+
|
|
74
|
+
- **cookie 认证,同源部署**:代理下载无需额外配置。
|
|
75
|
+
- **cookie 认证,文件路由在其他源**(不同子域名也算):用反向代理把文件路由挂到页面同源下,或配置能签发直链的 blob store。
|
|
76
|
+
- **只用 Bearer token**:配置能签发直链的 blob store。
|
|
77
|
+
|
|
78
|
+
直链在通过 `sign-url` 签发时就完成了鉴权,加载时不需要凭证。
|
|
79
|
+
|
|
80
|
+
## 错误
|
|
81
|
+
|
|
82
|
+
JSON 路由总是返回 protocol `error` 对象,成功时 `error.code` 为 `OK`。代理下载失败时只返回状态码和纯文本消息。
|
|
83
|
+
|
|
84
|
+
| `FileError` code | HTTP | protocol `ErrorCode` |
|
|
85
|
+
| --- | --- | --- |
|
|
86
|
+
| `INVALID_REQUEST` | 400 | `INVALID_ARGUMENT` |
|
|
87
|
+
| `UNAUTHENTICATED` | 401 | `UNAUTHENTICATED` |
|
|
88
|
+
| `PERMISSION_DENIED` | 403 | `PERMISSION_DENIED` |
|
|
89
|
+
| `FILE_NOT_FOUND` | 404 | `NOT_FOUND` |
|
|
90
|
+
| `UPLOAD_TIMEOUT` | 408 | `INTERNAL_ERROR` |
|
|
91
|
+
| `PAYLOAD_TOO_LARGE` | 413 | `INVALID_ARGUMENT` |
|
|
92
|
+
| `STORAGE_FAILURE`、`SERVICE_DISPOSED` | 503 | `INTERNAL_ERROR` |
|
package/dist/index.cjs
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});let e=require("@univerjs-pro/collaboration-file-service"),t=require("node:stream"),n=require("node:stream/promises"),r=require("content-disposition"),i=require("@univerjs-pro/collaboration-transport-node"),a=require("@univerjs/protocol"),o=require("node:zlib"),s=require("@fastify/busboy");function c(e,t){return{"content-type":e.contentType,"content-length":String(e.size),"content-disposition":(0,r.create)(e.name),"x-content-type-options":`nosniff`,"cache-control":`private, max-age=${t}, immutable`,etag:`"${e.fileID}"`}}async function l(e,r,i,a){e.statusCode=200;for(let[t,n]of Object.entries(c(r,a)))e.setHeader(t,n);await(0,n.pipeline)(t.Readable.from(i),e)}var u={code:a.ErrorCode.OK,message:``};function d(t){if(t instanceof i.NodeTransportError){let e=t.code===`REQUEST_BODY_TOO_LARGE`?413:t.code===`INVALID_JSON`||t.code===`REQUEST_ABORTED`||t.code===`INVALID_URL`?400:503;return{status:e,error:{code:e===503?a.ErrorCode.INTERNAL_ERROR:a.ErrorCode.INVALID_ARGUMENT,message:t.message}}}if(!(t instanceof e.FileError))return{status:500,error:{code:a.ErrorCode.INTERNAL_ERROR,message:`Internal error`}};let[n,r]=(()=>{switch(t.code){case`INVALID_REQUEST`:return[400,a.ErrorCode.INVALID_ARGUMENT];case`UNAUTHENTICATED`:return[401,a.ErrorCode.UNAUTHENTICATED];case`PERMISSION_DENIED`:return[403,a.ErrorCode.PERMISSION_DENIED];case`FILE_NOT_FOUND`:return[404,a.ErrorCode.NOT_FOUND];case`UPLOAD_TIMEOUT`:return[408,a.ErrorCode.INTERNAL_ERROR];case`PAYLOAD_TOO_LARGE`:return[413,a.ErrorCode.INVALID_ARGUMENT];case`STORAGE_FAILURE`:case`SERVICE_DISPOSED`:return[503,a.ErrorCode.INTERNAL_ERROR];default:return[500,a.ErrorCode.INTERNAL_ERROR]}})();return{status:n,error:{code:r,message:t.message}}}function f(e,t,n){e.writableEnded||(e.statusCode=t,e.setHeader(`content-type`,`application/json; charset=utf-8`),e.end(JSON.stringify(n)))}function p(e,t,n={}){let r=d(t);f(e,r.status,{error:r.error,...n})}function m(e,t){if(e.writableEnded)return;if(e.headersSent){e.destroy();return}let n=d(t);e.statusCode=n.status,e.setHeader(`content-type`,`text/plain; charset=utf-8`),e.end(n.error.message)}function h(e){let t=e.searchParams.get(`size`),n=t===null?void 0:Number(t),r=e.searchParams.getAll(`source`),i=r.length===1&&r[0]!==``?Number(r[0]):NaN,a=Number.isInteger(i)&&i>=-2147483648&&i<=2147483647?i:0;return{...n!==void 0&&Number.isFinite(n)?{size:n}:{},source:a,assign:e.searchParams.get(`assign`)??``,flate:e.searchParams.get(`flate`)===`true`}}function g(n,r,i){return new Promise((a,c)=>{let l=n.headers[`content-type`]??``;if(!/^multipart\/form-data\b/i.test(l)){c(new e.FileError(`INVALID_REQUEST`,`Upload must be multipart/form-data`));return}let u;try{u=new s.Busboy({headers:n.headers,isPartAFile:(e,t,n)=>e===`file`||n!==void 0})}catch(t){c(new e.FileError(`INVALID_REQUEST`,`Malformed multipart request`,{cause:t}));return}let d=!1,f=!1,p,m=setTimeout(()=>g(new e.FileError(`UPLOAD_TIMEOUT`,`Upload timed out`)),i.timeoutMs);m.unref?.();let h=()=>{clearTimeout(m),n.off(`close`,_)},g=e=>{f||(f=!0,h(),n.unpipe(u),p&&p.destroy(e),d||c(e))},_=()=>{n.complete||g(new e.FileError(`INVALID_REQUEST`,`Client disconnected during upload`))};n.on(`close`,_),u.on(`file`,(s,c,l,m,_)=>{if(s!==`file`||d||f){c.resume();return}let v=0,y=new t.Transform({transform(t,n,r){if(v+=t.byteLength,i.maxBytes!==void 0&&v>i.maxBytes){r(new e.FileError(`PAYLOAD_TOO_LARGE`,`Upload exceeds ${i.maxBytes} bytes`));return}r(null,t)}});p=y;let b=r.flate?[c,(0,o.createInflateRaw)(),y]:[c,y],x=t=>t instanceof e.FileError?t:new e.FileError(`INVALID_REQUEST`,r.flate?`Upload is not valid raw DEFLATE data`:`Upload stream failed`,{cause:t});(0,t.pipeline)(b,e=>{if(!e){f=!0,h();return}g(x(e))});let S=(async function*(){try{yield*y}catch(e){throw x(e)}})();d=!0,a({name:l??``,contentType:_||`application/octet-stream`,content:S,release:()=>{f||(f=!0,h(),n.unpipe(u),y.destroy())}})}),u.on(`error`,t=>g(new e.FileError(`INVALID_REQUEST`,`Malformed multipart request`,{cause:t}))),u.on(`finish`,()=>{d||g(new e.FileError(`INVALID_REQUEST`,`Multipart request has no file part`))}),n.pipe(u)})}var _=600*1e3,v=3600,y=class{_service;_routePrefix;_maxUploadBytes;_uploadTimeoutMs;_downloadCacheMaxAgeSeconds;_calls=new Set;_disposed=!1;_disposePromise;constructor(e,t={}){if(!e)throw TypeError(`UniverFileEndpoint requires a service`);this._service=e,this._routePrefix=C(t.routePrefix??`/universer-api`),this._maxUploadBytes=w(t.maxUploadBytes,`maxUploadBytes`),this._uploadTimeoutMs=w(t.uploadTimeoutMs,`uploadTimeoutMs`)??_,this._downloadCacheMaxAgeSeconds=T(t.downloadCacheMaxAgeSeconds,`downloadCacheMaxAgeSeconds`,v)}register(t){if(this._disposed)throw new e.FileError(`SERVICE_DISPOSED`,`File Endpoint is disposed`);t.post(`${this._routePrefix}/stream/file/upload`,e=>this._track(this._handleUpload(e))),t.get(`${this._routePrefix}/file/:fileID/sign-url`,e=>this._track(this._handleSignUrl(e))),t.get(`${this._routePrefix}/file/:fileID/download`,e=>this._track(this._handleDownload(e)))}dispose(){return this._disposePromise?this._disposePromise:(this._disposed=!0,this._disposePromise=Promise.allSettled([...this._calls]).then(()=>void 0),this._disposePromise)}async _handleUpload(e){let t;try{let n=this._requireUser(e),r=h(S(e));t=await g(e.incomingMessage,r,{maxBytes:this._maxUploadBytes,timeoutMs:this._uploadTimeoutMs});let i=await this._service.upload({name:t.name,contentType:t.contentType,...r.size===void 0?{}:{size:r.size},source:r.source,assign:r.assign,flate:r.flate,content:t.content},{userID:n,customData:e.customData});f(e.response,200,{error:u,FileId:i.fileID})}catch(n){t?.release(),b(e),p(e.response,n,{FileId:``})}finally{t?.release()}}async _handleSignUrl(e){try{let t=this._requireUser(e),n=x(e),r=(await this._service.signUrl({fileID:n},{userID:t,customData:e.customData})).direct?.url??`${this._routePrefix}/file/${encodeURIComponent(n)}/download`;f(e.response,200,{error:u,url:r})}catch(t){p(e.response,t,{url:``})}}async _handleDownload(e){try{let t=this._requireUser(e),n=x(e),{record:r,content:i}=await this._service.openDownload({fileID:n},{userID:t,customData:e.customData});await l(e.response,r,i,this._downloadCacheMaxAgeSeconds)}catch(t){m(e.response,t)}}_requireUser(t){if(this._disposed)throw new e.FileError(`SERVICE_DISPOSED`,`File Endpoint is disposed`);if(!t.userID)throw new e.FileError(`UNAUTHENTICATED`,`HTTP user is not authenticated`);return t.userID}_track(e){return this._calls.add(e),e.finally(()=>this._calls.delete(e)).catch(()=>void 0),e}};function b(e){e.incomingMessage.complete||e.response.headersSent||(e.response.setHeader(`connection`,`close`),e.response.once(`finish`,()=>e.incomingMessage.destroy()))}function x(t){let n=t.params.fileID;if(!n||n.includes(`/`))throw new e.FileError(`INVALID_REQUEST`,`Invalid route fileID`);return n}function S(e){return new URL(e.incomingMessage.url??`/`,`http://localhost`)}function C(e){if(!e.startsWith(`/`)||e===`/`||e.endsWith(`/`)||e.includes(`//`))throw TypeError(`routePrefix must be an absolute path without a trailing slash`);return e}function w(e,t){if(e!==void 0){if(!Number.isFinite(e)||e<=0)throw TypeError(`${t} must be a positive number`);return e}}function T(e,t,n){if(e===void 0)return n;if(!Number.isSafeInteger(e)||e<0)throw TypeError(`${t} must be a non-negative integer`);return e}exports.UniverFileEndpoint=y;
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import { IUniverFileService } from "@univerjs-pro/collaboration-file-service";
|
|
2
|
+
import { NodeRouter, NodeTransportEndpoint } from "@univerjs-pro/collaboration-transport-node";
|
|
3
|
+
|
|
4
|
+
//#region src/endpoint.d.ts
|
|
5
|
+
/** @public */
|
|
6
|
+
interface UniverFileEndpointOptions {
|
|
7
|
+
/** Defaults to `/universer-api`; absolute, no trailing slash. */
|
|
8
|
+
readonly routePrefix?: string;
|
|
9
|
+
/** Defaults to unlimited. Counted on bytes actually read, after inflate. */
|
|
10
|
+
readonly maxUploadBytes?: number;
|
|
11
|
+
/** Defaults to 10 minutes, measured from the start of request handling. */
|
|
12
|
+
readonly uploadTimeoutMs?: number;
|
|
13
|
+
/** `max-age` of proxy downloads in seconds. Defaults to 3600; `0` makes browsers revalidate every time. */
|
|
14
|
+
readonly downloadCacheMaxAgeSeconds?: number;
|
|
15
|
+
}
|
|
16
|
+
/**
|
|
17
|
+
* The file routes the Univer frontend calls, on top of the Node Transport:
|
|
18
|
+
* `POST {prefix}/stream/file/upload`, `GET {prefix}/file/{fileID}/sign-url` and
|
|
19
|
+
* `GET {prefix}/file/{fileID}/download`. Authentication is the Transport ingress middleware's job;
|
|
20
|
+
* this Endpoint only maps HTTP to `IUniverFileService` and back.
|
|
21
|
+
* @public
|
|
22
|
+
*/
|
|
23
|
+
declare class UniverFileEndpoint implements NodeTransportEndpoint {
|
|
24
|
+
private readonly _service;
|
|
25
|
+
private readonly _routePrefix;
|
|
26
|
+
private readonly _maxUploadBytes;
|
|
27
|
+
private readonly _uploadTimeoutMs;
|
|
28
|
+
private readonly _downloadCacheMaxAgeSeconds;
|
|
29
|
+
private readonly _calls;
|
|
30
|
+
private _disposed;
|
|
31
|
+
private _disposePromise;
|
|
32
|
+
constructor(service: IUniverFileService, options?: UniverFileEndpointOptions);
|
|
33
|
+
register(router: NodeRouter): void;
|
|
34
|
+
dispose(): Promise<void>;
|
|
35
|
+
private _handleUpload;
|
|
36
|
+
private _handleSignUrl;
|
|
37
|
+
private _handleDownload;
|
|
38
|
+
private _requireUser;
|
|
39
|
+
private _track;
|
|
40
|
+
}
|
|
41
|
+
//#endregion
|
|
42
|
+
export { UniverFileEndpoint, type UniverFileEndpointOptions };
|
package/dist/index.mjs
ADDED
package/package.json
CHANGED
|
@@ -1,6 +1,37 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@univerjs-pro/collaboration-file-endpoint",
|
|
3
|
-
"
|
|
4
|
-
"
|
|
5
|
-
|
|
3
|
+
"description": "HTTP file routes of the Univer frontend for the Univer Collaboration File Service",
|
|
4
|
+
"repository": {
|
|
5
|
+
"type": "git",
|
|
6
|
+
"url": "git+https://github.com/dream-num/univer-collaboration-sdk-community.git",
|
|
7
|
+
"directory": "packages/collaboration-file-endpoint"
|
|
8
|
+
},
|
|
9
|
+
"license": "Apache-2.0",
|
|
10
|
+
"type": "module",
|
|
11
|
+
"engines": {
|
|
12
|
+
"node": ">=22"
|
|
13
|
+
},
|
|
14
|
+
"version": "1.4.0",
|
|
15
|
+
"main": "./dist/index.cjs",
|
|
16
|
+
"module": "./dist/index.mjs",
|
|
17
|
+
"types": "./dist/index.d.ts",
|
|
18
|
+
"exports": {
|
|
19
|
+
".": {
|
|
20
|
+
"types": "./dist/index.d.ts",
|
|
21
|
+
"import": "./dist/index.mjs",
|
|
22
|
+
"require": "./dist/index.cjs"
|
|
23
|
+
}
|
|
24
|
+
},
|
|
25
|
+
"files": [
|
|
26
|
+
"dist"
|
|
27
|
+
],
|
|
28
|
+
"dependencies": {
|
|
29
|
+
"@fastify/busboy": "^3.2.4",
|
|
30
|
+
"content-disposition": "^3.0.0"
|
|
31
|
+
},
|
|
32
|
+
"peerDependencies": {
|
|
33
|
+
"@univerjs-pro/collaboration-file-service": "1.4.0",
|
|
34
|
+
"@univerjs-pro/collaboration-transport-node": "1.4.0",
|
|
35
|
+
"@univerjs/protocol": "1.4.0"
|
|
36
|
+
}
|
|
6
37
|
}
|