@softure-ai/files 0.2.0 → 0.3.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.
Files changed (59) hide show
  1. package/CHANGELOG.md +24 -0
  2. package/README.md +127 -3
  3. package/dist/client/index.d.ts +3 -0
  4. package/dist/client/index.d.ts.map +1 -0
  5. package/dist/client/index.js +6 -0
  6. package/dist/client/index.js.map +1 -0
  7. package/dist/client/send-upload.d.ts +26 -0
  8. package/dist/client/send-upload.d.ts.map +1 -0
  9. package/dist/client/send-upload.js +66 -0
  10. package/dist/client/send-upload.js.map +1 -0
  11. package/dist/client/upload-queue.d.ts +52 -0
  12. package/dist/client/upload-queue.d.ts.map +1 -0
  13. package/dist/client/upload-queue.js +164 -0
  14. package/dist/client/upload-queue.js.map +1 -0
  15. package/dist/index.d.ts +5 -0
  16. package/dist/index.d.ts.map +1 -1
  17. package/dist/index.js +1 -1
  18. package/dist/mcp/index.d.ts +25 -1
  19. package/dist/mcp/index.d.ts.map +1 -1
  20. package/dist/mcp/index.js +31 -14
  21. package/dist/mcp/index.js.map +1 -1
  22. package/dist/messages/en.d.ts +5 -0
  23. package/dist/messages/en.d.ts.map +1 -1
  24. package/dist/messages/en.js +7 -1
  25. package/dist/messages/en.js.map +1 -1
  26. package/dist/messages/index.d.ts +5 -0
  27. package/dist/messages/index.d.ts.map +1 -1
  28. package/dist/next/index.d.ts +1 -0
  29. package/dist/next/index.d.ts.map +1 -1
  30. package/dist/next/index.js +3 -2
  31. package/dist/next/index.js.map +1 -1
  32. package/dist/next/stored-file-route.d.ts +25 -0
  33. package/dist/next/stored-file-route.d.ts.map +1 -0
  34. package/dist/next/stored-file-route.js +14 -0
  35. package/dist/next/stored-file-route.js.map +1 -0
  36. package/dist/server/index.d.ts +1 -1
  37. package/dist/server/index.d.ts.map +1 -1
  38. package/dist/server/index.js +1 -1
  39. package/dist/server/index.js.map +1 -1
  40. package/dist/server/serve.d.ts +15 -0
  41. package/dist/server/serve.d.ts.map +1 -1
  42. package/dist/server/serve.js +38 -14
  43. package/dist/server/serve.js.map +1 -1
  44. package/dist/server/upload-page.d.ts.map +1 -1
  45. package/dist/server/upload-page.js +16 -23
  46. package/dist/server/upload-page.js.map +1 -1
  47. package/module.json +1 -1
  48. package/package.json +7 -2
  49. package/src/client/index.ts +12 -0
  50. package/src/client/send-upload.ts +89 -0
  51. package/src/client/upload-queue.ts +220 -0
  52. package/src/index.ts +1 -1
  53. package/src/mcp/index.ts +52 -15
  54. package/src/messages/en.ts +7 -1
  55. package/src/next/index.ts +9 -2
  56. package/src/next/stored-file-route.ts +43 -0
  57. package/src/server/index.ts +1 -1
  58. package/src/server/serve.ts +51 -14
  59. package/src/server/upload-page.ts +16 -23
@@ -1,9 +1,11 @@
1
- // The public link answer, framework-free: `GET` and `HEAD` with `Content-Length`, `Accept-Ranges`, single byte
2
- // ranges (`206`, `416`), `Content-Disposition`, and `Cache-Control: private, no-store` so no CDN keeps a copy. Every
3
- // dead link (forged, expired, revoked, deleted, missing from storage) gets the same `404`. A stored file is user
1
+ // The answer for a stored file, framework-free, behind a public link (`serveFileLink`) or for its signed-in owner
2
+ // (`serveStoredFile`): `GET` and `HEAD` with `Content-Length`, `Accept-Ranges`, single byte ranges (`206`, `416`),
3
+ // `Content-Disposition`, and `Cache-Control: private, no-store` so no CDN keeps a copy. Every dead link or lookup
4
+ // (forged, expired, revoked, deleted, another owner's, missing from storage) gets the same `404`. A stored file is user
4
5
  // content on the app's origin, so it is sent with `nosniff` and a sandboxing CSP: an HTML or SVG file never runs.
5
6
  import { errorLogLabel } from "@softure-ai/core";
6
7
  import type { ByteRange } from "../contract.js";
8
+ import type { FileRow } from "../schema.js";
7
9
  import type { FilesContext } from "./context.js";
8
10
  import { findLiveRow } from "./files.js";
9
11
  import { verifyFileLink } from "./links.js";
@@ -19,8 +21,8 @@ const ALLOWED_METHODS = "GET, HEAD";
19
21
 
20
22
  const NOT_FOUND_BODY = "Not found\n";
21
23
 
22
- /** The one answer for every link that does not lead to a live file. */
23
- function notFound(): Response {
24
+ /** The one answer for every link or lookup that does not lead to a live file. */
25
+ export function notFound(): Response {
24
26
  return new Response(NOT_FOUND_BODY, {
25
27
  status: 404,
26
28
  headers: {
@@ -33,12 +35,7 @@ function notFound(): Response {
33
35
 
34
36
  /** Answers a request for a public link (`GET` or `HEAD`). */
35
37
  export async function serveFileLink(ctx: FilesContext, request: Request): Promise<Response> {
36
- if (request.method !== "GET" && request.method !== "HEAD") {
37
- return new Response(null, {
38
- status: 405,
39
- headers: { ...BASE_HEADERS, allow: ALLOWED_METHODS },
40
- });
41
- }
38
+ if (!isReadMethod(request)) return methodNotAllowed();
42
39
  const link = verifyFileLink(ctx, new URL(request.url).pathname);
43
40
  if (!link.ok) {
44
41
  if (link.error !== "files.not_found") console.error(`@softure-ai/files: a link could not be checked: ${link.error}`);
@@ -46,13 +43,53 @@ export async function serveFileLink(ctx: FilesContext, request: Request): Promis
46
43
  }
47
44
  const row = await findLiveRow(ctx, link.value.fileId);
48
45
  if (row?.linkGeneration !== link.value.generation) return notFound();
46
+ const disposition = getFilesOptions(ctx.config).links.disposition;
47
+ return answerStoredFile(ctx, request, row, { name: link.value.name, disposition });
48
+ }
49
+
50
+ export interface ServeStoredFileOptions {
51
+ /** The signed-in user the app's session names; another owner's file reads as missing. */
52
+ readonly ownerId: string;
53
+ /** `inline` (the default: shown in the app's own page, a player or an image) or `attachment` (a download). */
54
+ readonly disposition?: "attachment" | "inline";
55
+ }
56
+
57
+ /**
58
+ * Answers a request (`GET` or `HEAD`) for a stored file on behalf of its signed-in owner: the answer of a public link
59
+ * (single byte ranges, `private, no-store`, `nosniff`, the sandboxing CSP) under the file's stored name, with no link
60
+ * to mint or verify. The caller has already checked the session; a file that is missing, expired, deleted or another
61
+ * owner's gets the same `404`.
62
+ */
63
+ export async function serveStoredFile(ctx: FilesContext, fileId: string, request: Request, options: ServeStoredFileOptions): Promise<Response> {
64
+ if (!isReadMethod(request)) return methodNotAllowed();
65
+ const row = await findLiveRow(ctx, fileId, { ownerId: options.ownerId });
66
+ if (row === undefined) return notFound();
67
+ return answerStoredFile(ctx, request, row, { name: row.originalName, disposition: options.disposition ?? "inline" });
68
+ }
69
+
70
+ function isReadMethod(request: Request): boolean {
71
+ return request.method === "GET" || request.method === "HEAD";
72
+ }
73
+
74
+ function methodNotAllowed(): Response {
75
+ return new Response(null, {
76
+ status: 405,
77
+ headers: { ...BASE_HEADERS, allow: ALLOWED_METHODS },
78
+ });
79
+ }
80
+
81
+ interface StoredFileAnswerOptions {
82
+ readonly name: string;
83
+ readonly disposition: "attachment" | "inline";
84
+ }
49
85
 
50
- const options = getFilesOptions(ctx.config);
86
+ /** The bytes of a live row as the answer to a `GET` or `HEAD`, honouring a single byte range. */
87
+ async function answerStoredFile(ctx: FilesContext, request: Request, row: FileRow, options: StoredFileAnswerOptions): Promise<Response> {
51
88
  const headers: Record<string, string> = {
52
89
  ...BASE_HEADERS,
53
90
  "content-type": row.contentType,
54
91
  "accept-ranges": "bytes",
55
- "content-disposition": formatContentDisposition(options.links.disposition, link.value.name),
92
+ "content-disposition": formatContentDisposition(options.disposition, options.name),
56
93
  "content-security-policy": "sandbox; default-src 'none'",
57
94
  };
58
95
  const range = parseRangeHeader(request.headers.get("range"), row.size);
@@ -69,7 +106,7 @@ export async function serveFileLink(ctx: FilesContext, request: Request): Promis
69
106
 
70
107
  let body: ReadableStream<Uint8Array> | null;
71
108
  try {
72
- body = await options.storage.get(row.storageKey, range ?? undefined);
109
+ body = await getFilesOptions(ctx.config).storage.get(row.storageKey, range ?? undefined);
73
110
  } catch (error) {
74
111
  console.error(`@softure-ai/files: reading file ${row.id} from storage failed: ${errorLogLabel(error)}`);
75
112
  throw error;
@@ -1,9 +1,11 @@
1
1
  // The browser fallback for an upload session: a small page on the upload URL itself, for a person on a phone or an
2
2
  // assistant that cannot run `curl`. It sends the missing chunks of the chosen file one by one with `fetch`, so a
3
- // broken connection resumes where it stopped. No framework and no external asset: one inline script and one inline
4
- // style, allowed by a per-response nonce. The copy comes from the module dictionary (`uploadPage`).
3
+ // broken connection resumes where it stopped. The loop is `sendUpload` of `@softure-ai/files/client`, inlined. No
4
+ // framework and no external asset: one inline script and one inline style, allowed by a per-response nonce. The copy
5
+ // comes from the module dictionary (`uploadPage`).
5
6
  import { randomBytes } from "node:crypto";
6
7
  import { selectMessages } from "@softure-ai/core";
8
+ import { sendUpload } from "../client/send-upload.js";
7
9
  import type { UploadStatus } from "../contract.js";
8
10
  import type { FilesMessages } from "../messages/index.js";
9
11
  import type { FilesContext } from "./context.js";
@@ -13,38 +15,29 @@ const STYLE = `body{font:16px/1.5 system-ui,sans-serif;max-width:32rem;margin:2r
13
15
  button,input{font:inherit}button{margin-top:1rem;padding:.5rem 1rem}progress{width:100%;margin-top:1rem}
14
16
  p[role=status]{min-height:1.5em}`;
15
17
 
16
- const SCRIPT = `const config = JSON.parse(document.getElementById("upload-config").textContent);
18
+ // The page's script: the client's own `sendUpload`, inlined from its source, then the few lines that wire it to the
19
+ // form. `sendUpload` references nothing outside its body (see `client/send-upload.ts`).
20
+ const SCRIPT = `${sendUpload.toString()}
21
+ const config = JSON.parse(document.getElementById("upload-config").textContent);
17
22
  const input = document.getElementById("file");
18
23
  const button = document.getElementById("start");
19
24
  const bar = document.getElementById("bar");
20
25
  const status = document.getElementById("status");
21
26
  const megabytes = (bytes) => (bytes / 1048576).toFixed(1) + " MB";
22
27
  function show(text) { status.textContent = text; }
28
+ function showProgress(progress) {
29
+ bar.value = progress.totalBytes === 0 ? 1 : progress.sentBytes / progress.totalBytes;
30
+ show(config.text.progress.replace("{done}", megabytes(progress.sentBytes)).replace("{total}", megabytes(progress.totalBytes)));
31
+ }
23
32
  async function upload() {
24
33
  const file = input.files[0];
25
34
  if (!file) return;
26
35
  if (file.size !== config.size) { show(config.text.wrongSize); return; }
27
36
  button.disabled = true;
28
- try {
29
- const answer = await fetch(location.href, { headers: { accept: "application/json" } });
30
- if (!answer.ok) throw new Error("status " + answer.status);
31
- const state = await answer.json();
32
- let done = state.receivedBytes;
33
- for (const index of state.missingChunks) {
34
- const start = index * config.chunkSize;
35
- const end = Math.min(start + config.chunkSize, config.size) - 1;
36
- const sent = await fetch(location.href, { method: "PUT", headers: { "content-range": "bytes " + start + "-" + end + "/" + config.size }, body: file.slice(start, end + 1) });
37
- if (!sent.ok) throw new Error("status " + sent.status);
38
- done += end - start + 1;
39
- bar.value = done / config.size;
40
- show(config.text.progress.replace("{done}", megabytes(done)).replace("{total}", megabytes(config.size)));
41
- }
42
- bar.value = 1;
43
- show(config.text.done);
44
- } catch {
45
- show(config.text.failed);
46
- button.disabled = false;
47
- }
37
+ const sent = await sendUpload(file, { uploadUrl: location.href, onProgress: showProgress });
38
+ if (sent.ok) { bar.value = 1; show(config.text.done); return; }
39
+ show(sent.error === "files.upload_expired" ? config.text.expired : config.text.failed);
40
+ button.disabled = sent.error === "files.upload_expired";
48
41
  }
49
42
  button.addEventListener("click", upload);`;
50
43