@civitai/app-sdk 0.84.1 → 0.86.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/README.md CHANGED
@@ -33,12 +33,13 @@ pnpm add @civitai/app-sdk
33
33
  | `blocks/*` — `BlockManifestError`, `BLOCK_SCOPES`, `BLOCK_SCOPE_PATTERN`, `isMessage`, types (`BlockManifestV1`, `BlockContext`, `BlockToken`, `BlockSettings`, `ViewerInfo`, `ThemeInfo`, `BlockWorkflowSnapshot`, `BlockInitPayload`, `ParentToBlockMessage`, `BlockToParentMessage`, …) | Framework-agnostic contract for [Civitai Apps](https://github.com/civitai/civitai-app-starters/blob/main/docs/build-your-first-app-block.md). Ships a byte-identical copy of the server-published canonical JSON Schema (draft 2020-12, https://civitai.com/schemas/app-block/v1.json) at the `./schemas/app-block/v1.json` subpath for offline validation; a CI drift-check keeps it in sync. Runtime-agnostic and **zero runtime dependencies** — no React, no DOM types, nothing in your install graph. Hooks and the iframe transport live in a separate package. |
34
34
  | `manifest/*` — `defineBlock`, `SCHEMA_DIVERGENCES`, `KNOWN_GAPS` (**Node only**) | Build-time manifest validation. `defineBlock(config)` compiles the vendored canonical schema with [Ajv](https://ajv.js.org) and validates a `BlockManifestV1` against it, so authoring mistakes surface in `pnpm dev` instead of at `civitai app validate`/submit. It is **derived from the schema, not a hand-written mirror of it** — that mirror is what produced [#330](https://github.com/civitai/civitai-app-starters/issues/330). Needs `node:fs` and the optional peer `ajv`, which is why it is not on the browser-facing `./blocks` surface. |
35
35
  | `vite/*` — `blockManifestPlugin` (**Node only**) | A Vite plugin wrapping `defineBlock`, firing from `configResolved` — the one hook Vite calls on both the dev-server and the build path. Every block scaffold registers it, so `pnpm dev`, `pnpm dev:harness` and `pnpm build` all fail on a bad manifest with the offending field path. On the dev server only, it also exposes the manifest's `scopes` + `storage` to `@civitai/sdk` for a dev-tunnel local preview. Optional peers: `ajv` (runtime) and `vite` (types only). |
36
+ | `save-zip/*` — `validateSaveZip`, `verifySaveZipInflate`, `looksLikeSaveZip`, `SAVE_ZIP_MAX_BYTES`, `SAVE_ZIP_LIMITS`, `SAVE_ZIP_ALLOWED_EXTENSIONS`, the `SAVE_ZIP_*_ERROR` strings | The `.zip` validator behind `SAVE_IMAGE { bytes }` — the ONE copy: the civitai.com host runs it before it starts a download, and `@civitai/blocks-react`'s `createMockHost` imports it, so a block's tests accept and refuse the zips production does. Structure (local headers, central directory and EOCD laid end to end, cross-checked), entry names and types, declared sizes, then an inflate check (`DecompressionStream`). The rules an app author needs are in `@civitai/blocks-react`'s README under `useSaveImage()`. Dependency-free, browser and Node. |
36
37
 
37
38
  ## Entry points, and what the root barrel is
38
39
 
39
40
  The root — `import … from '@civitai/app-sdk'` — is **exactly the union of four subpaths**: `@civitai/app-sdk/oauth`, `/scopes`, `/cookies` and `/orchestrator`. All of each, and nothing else. Import from the root when you want the OAuth-app surface in one specifier; import a subpath when you want only that slice. The two are the same symbols either way, which is asserted in both directions by `test/export-surface.test.ts` — the root cannot quietly gain a symbol none of those four exports, or miss one they do.
40
41
 
41
- The other five subpaths are **deliberately not on the root**, each for a concrete cost it would push onto every consumer:
42
+ The other six subpaths are **deliberately not on the root**, each for a concrete cost it would push onto every consumer:
42
43
 
43
44
  | Subpath | Why it is not on the root |
44
45
  |---|---|
@@ -47,6 +48,7 @@ The other five subpaths are **deliberately not on the root**, each for a concret
47
48
  | `@civitai/app-sdk/orchestrator/steps` | Type-only, and its declarations name `@civitai/client` — an **optional** peer that the root would make mandatory for everyone. |
48
49
  | `@civitai/app-sdk/manifest` | **Node only** — needs `node:fs` and the optional peer `ajv`. |
49
50
  | `@civitai/app-sdk/vite` | **Node only** — optional peers `ajv` (runtime) and `vite` (types). |
51
+ | `@civitai/app-sdk/save-zip` | The host's `SAVE_IMAGE` zip validator, shared by the civitai.com host and `@civitai/blocks-react`'s `createMockHost`. An OAuth app never needs it. |
50
52
 
51
53
  > One name is declared twice on purpose: `BuzzAccountType` is the full set of Civitai Buzz pools on the root and `/oauth`, and a narrower three-pool union on `/blocks` — a block can neither prefer nor read the others. Same name, two subpaths, two types; the divergence is pinned rather than merged.
52
54
 
@@ -3256,6 +3256,15 @@ export interface BlockManifestV1 {
3256
3256
  * locally is necessary, not sufficient.
3257
3257
  */
3258
3258
  repository?: string;
3259
+ /**
3260
+ * Optional PUBLIC issue-tracker / support link, rendered as a `Support` row
3261
+ * on the app's store detail page. A URL string only (the npm-style
3262
+ * `{ url, email }` object is refused), `https://`, at most 200 chars, any
3263
+ * host. `defineBlock` mirrors the canonical's COARSE pattern; the server also
3264
+ * refuses embedded credentials and a port, so passing locally is necessary,
3265
+ * not sufficient.
3266
+ */
3267
+ bugs?: string;
3259
3268
  preview?: ManifestPreview;
3260
3269
  promotionEligible?: boolean;
3261
3270
  /** Optional; dot-separated integers (e.g. `"1"` or `"1.0"`). Informational. */
package/dist/index.d.ts CHANGED
@@ -17,7 +17,7 @@
17
17
  * accident rather than by decision. `./oauth` now re-exports `types.ts`, which
18
18
  * fixes it additively: the root's surface did not change.
19
19
  *
20
- * ## The five subpaths deliberately NOT in the root, and why
20
+ * ## The six subpaths deliberately NOT in the root, and why
21
21
  *
22
22
  * "Reachable two ways" is a cost, but an absent export is a worse one, so the
23
23
  * bar for staying out is a concrete harm to the importer. Each of these clears
@@ -45,9 +45,12 @@
45
45
  * - **`./manifest`** — NODE ONLY. Needs `node:fs` and the optional peer `ajv`.
46
46
  * - **`./vite`** — NODE ONLY. Optional peers `ajv` (runtime) and `vite`
47
47
  * (types).
48
+ * - **`./save-zip`** — the host's `SAVE_IMAGE` zip validator, the one copy the
49
+ * civitai.com host and `@civitai/blocks-react`'s `createMockHost` share. An
50
+ * OAuth app never saves a zip through a block host.
48
51
  *
49
52
  * The ledger in `test/export-surface.test.ts` carries one of these reasons per
50
- * `exports` key and fails when the key set GROWS or SHRINKS — so a sixth
53
+ * `exports` key and fails when the key set GROWS or SHRINKS — so a seventh
51
54
  * subpath cannot arrive without a stated reason to exist, and a deleted one
52
55
  * cannot leave a stale reason behind.
53
56
  *
package/dist/index.js CHANGED
@@ -17,7 +17,7 @@
17
17
  * accident rather than by decision. `./oauth` now re-exports `types.ts`, which
18
18
  * fixes it additively: the root's surface did not change.
19
19
  *
20
- * ## The five subpaths deliberately NOT in the root, and why
20
+ * ## The six subpaths deliberately NOT in the root, and why
21
21
  *
22
22
  * "Reachable two ways" is a cost, but an absent export is a worse one, so the
23
23
  * bar for staying out is a concrete harm to the importer. Each of these clears
@@ -45,9 +45,12 @@
45
45
  * - **`./manifest`** — NODE ONLY. Needs `node:fs` and the optional peer `ajv`.
46
46
  * - **`./vite`** — NODE ONLY. Optional peers `ajv` (runtime) and `vite`
47
47
  * (types).
48
+ * - **`./save-zip`** — the host's `SAVE_IMAGE` zip validator, the one copy the
49
+ * civitai.com host and `@civitai/blocks-react`'s `createMockHost` share. An
50
+ * OAuth app never saves a zip through a block host.
48
51
  *
49
52
  * The ledger in `test/export-surface.test.ts` carries one of these reasons per
50
- * `exports` key and fails when the key set GROWS or SHRINKS — so a sixth
53
+ * `exports` key and fails when the key set GROWS or SHRINKS — so a seventh
51
54
  * subpath cannot arrive without a stated reason to exist, and a deleted one
52
55
  * cannot leave a stale reason behind.
53
56
  *
@@ -272,6 +272,41 @@ function toManifestError(error, manifest, discriminator) {
272
272
  }
273
273
  return new BlockManifestError(message, field);
274
274
  }
275
+ /**
276
+ * What a manifest that declares no surface is told. Worded as civitai/civitai's
277
+ * `manifestSurfaceError` (block-manifest-validator.service.ts) words the same
278
+ * refusal at submit, so the build and the platform name the same two fixes.
279
+ */
280
+ const NO_SURFACE_MESSAGE = 'manifest must declare at least one surface: add a "page" object for a full-page app ' +
281
+ '(e.g. "page": { "path": "/", "title": "My App" }), or a non-empty "targets" array for a ' +
282
+ 'model-page slot app (e.g. "targets": [{ "slotId": "model.sidebar_top" }])';
283
+ const sameStrings = (a, b) => Array.isArray(a) && a.length === b.length && a.every((v, i) => v === b[i]);
284
+ /**
285
+ * True when `error` comes from the canonical's surface rule: an `anyOf` whose
286
+ * members are exactly "requires `targets`" and "requires `page`" (the
287
+ * top-level `allOf` clause from civitai/civitai#8735). The site is found by
288
+ * reading each failed `anyOf`'s own members off the error list (Ajv's
289
+ * `verbose: true` puts them on `schema`), not by a fixed schema path, so it
290
+ * follows the clause if the canonical reorders its `allOf`.
291
+ *
292
+ * Ajv reports the first member's complaint for that site — "`targets` is
293
+ * required", or "`targets` must NOT have fewer than 1 items" — which names only
294
+ * one of the two fixes, and the one a full-page app does not want. This changes
295
+ * the MESSAGE only: the error was already picked, so the verdict is Ajv's.
296
+ */
297
+ function isSurfaceError(error, errors) {
298
+ return errors.some((site) => {
299
+ if (site.keyword !== 'anyOf')
300
+ return false;
301
+ const members = site.schema;
302
+ if (!Array.isArray(members) || members.length !== 2)
303
+ return false;
304
+ const required = members.map((m) => m?.required);
305
+ if (!sameStrings(required[0], ['targets']) || !sameStrings(required[1], ['page']))
306
+ return false;
307
+ return error.schemaPath === site.schemaPath || error.schemaPath.startsWith(`${site.schemaPath}/`);
308
+ });
309
+ }
275
310
  /**
276
311
  * Validates the manifest against the canonical schema and returns it unchanged.
277
312
  * Acts as a typed identity function — call it from the build (see
@@ -323,6 +358,9 @@ export function defineBlock(config) {
323
358
  /* c8 ignore next */
324
359
  if (!picked)
325
360
  throw new BlockManifestError('manifest failed schema validation');
361
+ if (isSurfaceError(picked.error, validate.errors ?? [])) {
362
+ throw new BlockManifestError(NO_SURFACE_MESSAGE, 'targets');
363
+ }
326
364
  throw toManifestError(picked.error, manifest, picked.discriminator);
327
365
  }
328
366
  // (2) The prose-only server rejections. Strictly additive, one per
@@ -0,0 +1,156 @@
1
+ /**
2
+ * `@civitai/app-sdk/save-zip` — the App Blocks `SAVE_IMAGE { bytes }` `.zip` validator.
3
+ *
4
+ * 🔴 THE ONE COPY. The civitai.com host (top frame, before it starts the download) and
5
+ * `@civitai/blocks-react`'s `createMockHost` both import this module, so the mock accepts and
6
+ * refuses exactly the zips production does. There is no second copy to keep in step: change the
7
+ * rules here, release, and bump the host's `@civitai/app-sdk` dependency.
8
+ *
9
+ * Runtime-agnostic and dependency-free: plain `DataView` / `Uint8Array` / `TextDecoder`, plus
10
+ * `DecompressionStream('deflate-raw')` for {@link verifySaveZipInflate} only (every current
11
+ * browser, Node >= 18). No `node:` import, so it is safe in a browser bundle.
12
+ *
13
+ * An app can save a zip (e.g. an image dataset plus caption files) through the host save path; it
14
+ * gets no `allow-downloads` / `allow-popups` sandbox token for it. A zip is recognised by its
15
+ * STRUCTURE, never its filename, and is saved only after this module has accounted for every byte
16
+ * of it:
17
+ *
18
+ * [local header + name + extra + data (+ data descriptor)] × N · central directory · EOCD
19
+ *
20
+ * laid end to end with no gap, no prefix, no trailing data and no archive comment. Each central-
21
+ * directory record is cross-checked against the local header it points at (name bytes, flags,
22
+ * method, CRC, sizes), so a reader that walks local headers and one that reads the central
23
+ * directory see the same entries — the polyglot / central-directory-vs-local-header smuggling
24
+ * routes. Then every entry must pass the name and type rules below.
25
+ *
26
+ * Hand-written rather than jszip: jszip's API does not expose the local headers it skips over, and
27
+ * the checks here are about exactly those bytes. No copy of the buffer is made; everything reads
28
+ * through one `DataView` / `Uint8Array` over it.
29
+ *
30
+ * Sizes are the DECLARED ones (central directory), bounded by {@link SAVE_ZIP_LIMITS}. Declared
31
+ * sizes can lie for a deflated entry, so {@link verifySaveZipInflate} then inflates each deflated
32
+ * entry, stopping as soon as it produces more than it declared, and refuses any entry that does not
33
+ * inflate to exactly its declared size. Stored entries need no inflate: their data IS their size.
34
+ *
35
+ * Zip64 is REFUSED, not parsed: a 256 MB save never needs it (it exists for > 4 GiB or > 65,535
36
+ * entries, both far over the caps here), and refusing every zip64 marker — EOCD sentinels, the
37
+ * zip64 EOCD locator, per-entry 0xFFFFFFFF sentinels, the 0x0001 extra field — is simpler to get
38
+ * right than validating a second set of size fields that can disagree with the first.
39
+ */
40
+ /** The largest zip a `bytes` save accepts. A dataset of ~200 MB fits with room. */
41
+ export declare const SAVE_ZIP_MAX_BYTES: number;
42
+ /**
43
+ * The validator's bounds. Each is checked on the DECLARED (central-directory) values before
44
+ * anything is inflated.
45
+ * - maxEntries 10,000: a large captioned training set (5,000 images + 5,000 captions) still
46
+ * fits; parsing 10k records is a few ms. Checked on the EOCD count BEFORE the walk.
47
+ * - maxTotalUncompressedBytes 1 GiB: images (the bulk of a dataset) do not compress, so a real
48
+ * 256 MB zip unpacks to about 256 MB; four times the file cap leaves room for text and bounds
49
+ * what an extractor writes to the viewer's disk.
50
+ * - maxEntryRatio 100 above ratioFloorBytes 1 MiB: an entry declaring over 100× its compressed
51
+ * size is a bomb shape (ordinary text deflates 3–10×). Small entries are exempt — a 4 KB
52
+ * caption of repeated characters can exceed 100× and is harmless; the total cap bounds them.
53
+ */
54
+ export declare const SAVE_ZIP_LIMITS: {
55
+ readonly maxEntries: 10000;
56
+ readonly maxTotalUncompressedBytes: number;
57
+ readonly maxEntryRatio: 100;
58
+ readonly ratioFloorBytes: number;
59
+ };
60
+ /** Entry extensions a zip may contain (lowercase, after the last `.`). Directories need none. */
61
+ export declare const SAVE_ZIP_ALLOWED_EXTENSIONS: ReadonlySet<string>;
62
+ export declare const SAVE_ZIP_NO_EOCD_ERROR = "zip end of central directory not found (archive comments are not allowed)";
63
+ export declare const SAVE_ZIP_MULTIDISK_ERROR = "zip spans multiple disks";
64
+ export declare const SAVE_ZIP64_ERROR = "zip64 archives are not supported";
65
+ export declare const SAVE_ZIP_EMPTY_ERROR = "zip has no entries";
66
+ export declare const SAVE_ZIP_TOO_MANY_ENTRIES_ERROR = "zip has too many entries";
67
+ export declare const SAVE_ZIP_LAYOUT_ERROR = "zip layout is not contiguous";
68
+ export declare const SAVE_ZIP_TRUNCATED_ERROR = "zip is truncated";
69
+ export declare const SAVE_ZIP_CENTRAL_DIRECTORY_ERROR = "zip central directory is malformed";
70
+ export declare const SAVE_ZIP_EXTRA_FIELD_ERROR = "zip extra field is malformed";
71
+ export declare const SAVE_ZIP_LOCAL_HEADER_ERROR = "zip local header is malformed";
72
+ export declare const SAVE_ZIP_HEADER_MISMATCH_ERROR = "zip local header does not match the central directory";
73
+ export declare const SAVE_ZIP_DATA_DESCRIPTOR_ERROR = "zip data descriptor does not match the central directory";
74
+ export declare const SAVE_ZIP_ENCRYPTED_ERROR = "zip entry is encrypted";
75
+ export declare const SAVE_ZIP_FLAGS_ERROR = "zip entry uses an unsupported feature";
76
+ export declare const SAVE_ZIP_METHOD_NOT_ALLOWED_ERROR = "zip compression method is not allowed";
77
+ export declare const SAVE_ZIP_ENTRY_TYPE_NOT_ALLOWED_ERROR = "zip entry type is not allowed";
78
+ export declare const SAVE_ZIP_NAME_ENCODING_ERROR = "zip entry name is not valid UTF-8 or ASCII";
79
+ export declare const SAVE_ZIP_ALTERNATE_PATH_ERROR = "zip entry carries an alternate path field";
80
+ export declare const SAVE_ZIP_CONTROL_CHAR_ERROR = "zip entry name contains control or bidi characters";
81
+ export declare const SAVE_ZIP_ABSOLUTE_PATH_ERROR = "zip entry path is absolute";
82
+ export declare const SAVE_ZIP_BACKSLASH_ERROR = "zip entry path contains a backslash";
83
+ export declare const SAVE_ZIP_DRIVE_OR_COLON_ERROR = "zip entry path contains a drive letter or colon";
84
+ export declare const SAVE_ZIP_TRAVERSAL_ERROR = "zip entry path contains a .. segment";
85
+ export declare const SAVE_ZIP_EMPTY_SEGMENT_ERROR = "zip entry path contains an empty or . segment";
86
+ export declare const SAVE_ZIP_DUPLICATE_NAME_ERROR = "zip has duplicate entry names";
87
+ export declare const SAVE_ZIP_PATH_CONFLICT_ERROR = "zip entry is inside a path that is a file";
88
+ export declare const SAVE_ZIP_SPECIAL_FILE_ERROR = "zip entry is not a regular file or directory";
89
+ export declare const SAVE_ZIP_DIRECTORY_DATA_ERROR = "zip directory entry has data";
90
+ export declare const SAVE_ZIP_STORED_SIZE_ERROR = "zip stored entry sizes disagree";
91
+ export declare const SAVE_ZIP_TOTAL_SIZE_ERROR = "zip total uncompressed size exceeds the limit";
92
+ export declare const SAVE_ZIP_RATIO_ERROR = "zip entry compression ratio exceeds the limit";
93
+ export declare const SAVE_ZIP_INFLATE_ERROR = "zip entry does not inflate to its declared size";
94
+ export declare const SAVE_ZIP_INFLATE_TRAILING_ERROR = "zip entry has data after the end of its deflate stream";
95
+ export declare const SAVE_ZIP_CRC_ERROR = "zip entry does not match its CRC-32";
96
+ export declare const SAVE_ZIP_VERIFY_ABORTED_ERROR = "zip verification was aborted";
97
+ /** What {@link verifySaveZipInflate} rejects with when its `AbortSignal` fires. */
98
+ export declare class SaveZipVerifyAbortedError extends Error {
99
+ constructor();
100
+ }
101
+ /**
102
+ * How much compressed input {@link verifySaveZipInflate} hands the inflater at a time: 16 KiB.
103
+ * The overshoot check runs between reads, and one slice can expand by deflate's maximum (~1032:1)
104
+ * before it does, so the slice bounds the output produced past an entry's declared size: ~16.5 MiB
105
+ * here, where 1 MiB slices allowed ~1 GiB. Smaller slices cost more `write()` round trips:
106
+ * measured on Node 24, verifying one honest 256 MiB entry (both inflates + CRC) took ~2.0 s at
107
+ * 16 KiB against ~1.3-1.8 s at 1 MiB.
108
+ */
109
+ export declare const SAVE_ZIP_INFLATE_SLICE_BYTES: number;
110
+ export declare const SAVE_ZIP_STORED_DESCRIPTOR_SIGNATURE_ERROR = "zip stored entry with a data descriptor contains a data-descriptor signature (PK\\x07\\x08); save it with DEFLATE or without streamFiles";
111
+ export declare const SAVE_ZIP_STORED_LOCAL_SIGNATURE_ERROR = "zip stored entry with a data descriptor contains a local-header signature (PK\\x03\\x04); save it with DEFLATE or without streamFiles";
112
+ export declare const SAVE_ZIP_SEGMENT_DOT_SPACE_ERROR = "zip entry path has a segment that ends in a dot or space";
113
+ export declare const SAVE_ZIP_EXTRA_FIELD_NOT_ALLOWED_ERROR = "zip extra field is not allowed";
114
+ /** `zip compression method is not allowed: 12` */
115
+ export declare function saveZipMethodError(method: number): string;
116
+ /** `zip extra field is not allowed: 0x000d`. */
117
+ export declare function saveZipExtraFieldError(id: number): string;
118
+ /** `zip entry type is not allowed: exe` (`(none)` for a file with no extension). */
119
+ export declare function saveZipEntryTypeError(ext: string): string;
120
+ /**
121
+ * A deflated entry {@link verifySaveZipInflate} must inflate: where its data is, and the size and
122
+ * CRC-32 its central record declares.
123
+ */
124
+ export type SaveZipDeflatedEntry = {
125
+ dataOffset: number;
126
+ compressedSize: number;
127
+ size: number;
128
+ crc: number;
129
+ };
130
+ export type SaveZipValidation = {
131
+ ok: true;
132
+ entryCount: number;
133
+ deflated: SaveZipDeflatedEntry[];
134
+ } | {
135
+ ok: false;
136
+ error: string;
137
+ };
138
+ /** True when the bytes START like a zip (a local header, or the 22-byte empty archive). */
139
+ export declare function looksLikeSaveZip(u8: Uint8Array): boolean;
140
+ /**
141
+ * Validate a zip's structure, names and declared sizes. Synchronous and allocation-light (views
142
+ * over the caller's buffer). The caller has already applied the byte cap
143
+ * ({@link SAVE_ZIP_MAX_BYTES}). A pass still needs {@link verifySaveZipInflate} before the save.
144
+ */
145
+ export declare function validateSaveZip(bytes: ArrayBuffer): SaveZipValidation;
146
+ /**
147
+ * Inflate every deflated entry {@link validateSaveZip} returned and refuse the zip unless each
148
+ * yields exactly its declared size and CRC-32, with nothing after its end-of-stream marker — so the
149
+ * declared-size bounds cannot be walked by lying about them, and no bytes ride along unchecked.
150
+ * Work is bounded by twice the declared total ({@link SAVE_ZIP_LIMITS}; two inflates per entry)
151
+ * plus one {@link SAVE_ZIP_INFLATE_SLICE_BYTES} slice each. Returns the error string, or `null`
152
+ * when every entry checks out. When `signal` fires (or has already) it stops promptly and REJECTS
153
+ * with {@link SaveZipVerifyAbortedError} — a caller's deadline, not a verdict on the zip.
154
+ */
155
+ export declare function verifySaveZipInflate(bytes: ArrayBuffer, deflated: readonly SaveZipDeflatedEntry[], signal?: AbortSignal): Promise<string | null>;
156
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1,650 @@
1
+ /**
2
+ * `@civitai/app-sdk/save-zip` — the App Blocks `SAVE_IMAGE { bytes }` `.zip` validator.
3
+ *
4
+ * 🔴 THE ONE COPY. The civitai.com host (top frame, before it starts the download) and
5
+ * `@civitai/blocks-react`'s `createMockHost` both import this module, so the mock accepts and
6
+ * refuses exactly the zips production does. There is no second copy to keep in step: change the
7
+ * rules here, release, and bump the host's `@civitai/app-sdk` dependency.
8
+ *
9
+ * Runtime-agnostic and dependency-free: plain `DataView` / `Uint8Array` / `TextDecoder`, plus
10
+ * `DecompressionStream('deflate-raw')` for {@link verifySaveZipInflate} only (every current
11
+ * browser, Node >= 18). No `node:` import, so it is safe in a browser bundle.
12
+ *
13
+ * An app can save a zip (e.g. an image dataset plus caption files) through the host save path; it
14
+ * gets no `allow-downloads` / `allow-popups` sandbox token for it. A zip is recognised by its
15
+ * STRUCTURE, never its filename, and is saved only after this module has accounted for every byte
16
+ * of it:
17
+ *
18
+ * [local header + name + extra + data (+ data descriptor)] × N · central directory · EOCD
19
+ *
20
+ * laid end to end with no gap, no prefix, no trailing data and no archive comment. Each central-
21
+ * directory record is cross-checked against the local header it points at (name bytes, flags,
22
+ * method, CRC, sizes), so a reader that walks local headers and one that reads the central
23
+ * directory see the same entries — the polyglot / central-directory-vs-local-header smuggling
24
+ * routes. Then every entry must pass the name and type rules below.
25
+ *
26
+ * Hand-written rather than jszip: jszip's API does not expose the local headers it skips over, and
27
+ * the checks here are about exactly those bytes. No copy of the buffer is made; everything reads
28
+ * through one `DataView` / `Uint8Array` over it.
29
+ *
30
+ * Sizes are the DECLARED ones (central directory), bounded by {@link SAVE_ZIP_LIMITS}. Declared
31
+ * sizes can lie for a deflated entry, so {@link verifySaveZipInflate} then inflates each deflated
32
+ * entry, stopping as soon as it produces more than it declared, and refuses any entry that does not
33
+ * inflate to exactly its declared size. Stored entries need no inflate: their data IS their size.
34
+ *
35
+ * Zip64 is REFUSED, not parsed: a 256 MB save never needs it (it exists for > 4 GiB or > 65,535
36
+ * entries, both far over the caps here), and refusing every zip64 marker — EOCD sentinels, the
37
+ * zip64 EOCD locator, per-entry 0xFFFFFFFF sentinels, the 0x0001 extra field — is simpler to get
38
+ * right than validating a second set of size fields that can disagree with the first.
39
+ */
40
+ /** The largest zip a `bytes` save accepts. A dataset of ~200 MB fits with room. */
41
+ export const SAVE_ZIP_MAX_BYTES = 256 * 1024 * 1024; // 256 MB
42
+ /**
43
+ * The validator's bounds. Each is checked on the DECLARED (central-directory) values before
44
+ * anything is inflated.
45
+ * - maxEntries 10,000: a large captioned training set (5,000 images + 5,000 captions) still
46
+ * fits; parsing 10k records is a few ms. Checked on the EOCD count BEFORE the walk.
47
+ * - maxTotalUncompressedBytes 1 GiB: images (the bulk of a dataset) do not compress, so a real
48
+ * 256 MB zip unpacks to about 256 MB; four times the file cap leaves room for text and bounds
49
+ * what an extractor writes to the viewer's disk.
50
+ * - maxEntryRatio 100 above ratioFloorBytes 1 MiB: an entry declaring over 100× its compressed
51
+ * size is a bomb shape (ordinary text deflates 3–10×). Small entries are exempt — a 4 KB
52
+ * caption of repeated characters can exceed 100× and is harmless; the total cap bounds them.
53
+ */
54
+ export const SAVE_ZIP_LIMITS = {
55
+ maxEntries: 10_000,
56
+ maxTotalUncompressedBytes: 1024 * 1024 * 1024,
57
+ maxEntryRatio: 100,
58
+ ratioFloorBytes: 1024 * 1024,
59
+ };
60
+ /** Entry extensions a zip may contain (lowercase, after the last `.`). Directories need none. */
61
+ export const SAVE_ZIP_ALLOWED_EXTENSIONS = new Set([
62
+ 'png',
63
+ 'jpg',
64
+ 'jpeg',
65
+ 'webp',
66
+ 'txt',
67
+ 'json',
68
+ 'csv',
69
+ ]);
70
+ export const SAVE_ZIP_NO_EOCD_ERROR = 'zip end of central directory not found (archive comments are not allowed)';
71
+ export const SAVE_ZIP_MULTIDISK_ERROR = 'zip spans multiple disks';
72
+ export const SAVE_ZIP64_ERROR = 'zip64 archives are not supported';
73
+ export const SAVE_ZIP_EMPTY_ERROR = 'zip has no entries';
74
+ export const SAVE_ZIP_TOO_MANY_ENTRIES_ERROR = 'zip has too many entries';
75
+ export const SAVE_ZIP_LAYOUT_ERROR = 'zip layout is not contiguous';
76
+ export const SAVE_ZIP_TRUNCATED_ERROR = 'zip is truncated';
77
+ export const SAVE_ZIP_CENTRAL_DIRECTORY_ERROR = 'zip central directory is malformed';
78
+ export const SAVE_ZIP_EXTRA_FIELD_ERROR = 'zip extra field is malformed';
79
+ export const SAVE_ZIP_LOCAL_HEADER_ERROR = 'zip local header is malformed';
80
+ export const SAVE_ZIP_HEADER_MISMATCH_ERROR = 'zip local header does not match the central directory';
81
+ export const SAVE_ZIP_DATA_DESCRIPTOR_ERROR = 'zip data descriptor does not match the central directory';
82
+ export const SAVE_ZIP_ENCRYPTED_ERROR = 'zip entry is encrypted';
83
+ export const SAVE_ZIP_FLAGS_ERROR = 'zip entry uses an unsupported feature';
84
+ export const SAVE_ZIP_METHOD_NOT_ALLOWED_ERROR = 'zip compression method is not allowed';
85
+ export const SAVE_ZIP_ENTRY_TYPE_NOT_ALLOWED_ERROR = 'zip entry type is not allowed';
86
+ export const SAVE_ZIP_NAME_ENCODING_ERROR = 'zip entry name is not valid UTF-8 or ASCII';
87
+ export const SAVE_ZIP_ALTERNATE_PATH_ERROR = 'zip entry carries an alternate path field';
88
+ export const SAVE_ZIP_CONTROL_CHAR_ERROR = 'zip entry name contains control or bidi characters';
89
+ export const SAVE_ZIP_ABSOLUTE_PATH_ERROR = 'zip entry path is absolute';
90
+ export const SAVE_ZIP_BACKSLASH_ERROR = 'zip entry path contains a backslash';
91
+ export const SAVE_ZIP_DRIVE_OR_COLON_ERROR = 'zip entry path contains a drive letter or colon';
92
+ export const SAVE_ZIP_TRAVERSAL_ERROR = 'zip entry path contains a .. segment';
93
+ export const SAVE_ZIP_EMPTY_SEGMENT_ERROR = 'zip entry path contains an empty or . segment';
94
+ export const SAVE_ZIP_DUPLICATE_NAME_ERROR = 'zip has duplicate entry names';
95
+ export const SAVE_ZIP_PATH_CONFLICT_ERROR = 'zip entry is inside a path that is a file';
96
+ export const SAVE_ZIP_SPECIAL_FILE_ERROR = 'zip entry is not a regular file or directory';
97
+ export const SAVE_ZIP_DIRECTORY_DATA_ERROR = 'zip directory entry has data';
98
+ export const SAVE_ZIP_STORED_SIZE_ERROR = 'zip stored entry sizes disagree';
99
+ export const SAVE_ZIP_TOTAL_SIZE_ERROR = 'zip total uncompressed size exceeds the limit';
100
+ export const SAVE_ZIP_RATIO_ERROR = 'zip entry compression ratio exceeds the limit';
101
+ export const SAVE_ZIP_INFLATE_ERROR = 'zip entry does not inflate to its declared size';
102
+ export const SAVE_ZIP_INFLATE_TRAILING_ERROR = 'zip entry has data after the end of its deflate stream';
103
+ export const SAVE_ZIP_CRC_ERROR = 'zip entry does not match its CRC-32';
104
+ export const SAVE_ZIP_VERIFY_ABORTED_ERROR = 'zip verification was aborted';
105
+ /** What {@link verifySaveZipInflate} rejects with when its `AbortSignal` fires. */
106
+ export class SaveZipVerifyAbortedError extends Error {
107
+ constructor() {
108
+ super(SAVE_ZIP_VERIFY_ABORTED_ERROR);
109
+ this.name = 'SaveZipVerifyAbortedError';
110
+ }
111
+ }
112
+ /**
113
+ * How much compressed input {@link verifySaveZipInflate} hands the inflater at a time: 16 KiB.
114
+ * The overshoot check runs between reads, and one slice can expand by deflate's maximum (~1032:1)
115
+ * before it does, so the slice bounds the output produced past an entry's declared size: ~16.5 MiB
116
+ * here, where 1 MiB slices allowed ~1 GiB. Smaller slices cost more `write()` round trips:
117
+ * measured on Node 24, verifying one honest 256 MiB entry (both inflates + CRC) took ~2.0 s at
118
+ * 16 KiB against ~1.3-1.8 s at 1 MiB.
119
+ */
120
+ export const SAVE_ZIP_INFLATE_SLICE_BYTES = 16 * 1024;
121
+ export const SAVE_ZIP_STORED_DESCRIPTOR_SIGNATURE_ERROR = 'zip stored entry with a data descriptor contains a data-descriptor signature (PK\\x07\\x08); save it with DEFLATE or without streamFiles';
122
+ export const SAVE_ZIP_STORED_LOCAL_SIGNATURE_ERROR = 'zip stored entry with a data descriptor contains a local-header signature (PK\\x03\\x04); save it with DEFLATE or without streamFiles';
123
+ export const SAVE_ZIP_SEGMENT_DOT_SPACE_ERROR = 'zip entry path has a segment that ends in a dot or space';
124
+ export const SAVE_ZIP_EXTRA_FIELD_NOT_ALLOWED_ERROR = 'zip extra field is not allowed';
125
+ /** `zip compression method is not allowed: 12` */
126
+ export function saveZipMethodError(method) {
127
+ return `${SAVE_ZIP_METHOD_NOT_ALLOWED_ERROR}: ${method}`;
128
+ }
129
+ /** `zip extra field is not allowed: 0x000d`. */
130
+ export function saveZipExtraFieldError(id) {
131
+ return `${SAVE_ZIP_EXTRA_FIELD_NOT_ALLOWED_ERROR}: 0x${id.toString(16).padStart(4, '0')}`;
132
+ }
133
+ /** `zip entry type is not allowed: exe` (`(none)` for a file with no extension). */
134
+ export function saveZipEntryTypeError(ext) {
135
+ return `${SAVE_ZIP_ENTRY_TYPE_NOT_ALLOWED_ERROR}: ${ext.length > 0 ? ext : '(none)'}`;
136
+ }
137
+ const SIG_LOCAL = 0x04034b50;
138
+ const SIG_CENTRAL = 0x02014b50;
139
+ const SIG_EOCD = 0x06054b50;
140
+ const SIG_ZIP64_LOCATOR = 0x07064b50;
141
+ const SIG_DATA_DESCRIPTOR = 0x08074b50;
142
+ const EOCD_LEN = 22;
143
+ const ZIP64_LOCATOR_LEN = 20;
144
+ const CENTRAL_LEN = 46;
145
+ const LOCAL_LEN = 30;
146
+ const METHOD_STORED = 0;
147
+ const METHOD_DEFLATE = 8;
148
+ const FLAG_ENCRYPTED = 1 << 0;
149
+ const FLAG_DATA_DESCRIPTOR = 1 << 3;
150
+ const FLAG_STRONG_ENCRYPTION = 1 << 6;
151
+ const FLAG_UTF8 = 1 << 11;
152
+ const FLAG_MASKED_HEADERS = 1 << 13;
153
+ /** Bits 1–2 are deflate option hints, 3 the data descriptor, 11 UTF-8 names. Anything else is refused. */
154
+ const FLAGS_ALLOWED = (1 << 1) | (1 << 2) | FLAG_DATA_DESCRIPTOR | FLAG_UTF8;
155
+ const EXTRA_ZIP64 = 0x0001;
156
+ const EXTRA_STRONG_ENCRYPTION = 0x0017;
157
+ const EXTRA_UNICODE_PATH = 0x7075;
158
+ const EXTRA_AES = 0x9901;
159
+ /**
160
+ * The extra fields an entry MAY carry; every other id is refused. An allow-list, not a block-list:
161
+ * an extractor honours fields this validator never looked at — 0x000d (PKWARE Unix: mode and a
162
+ * symlink target) and 0x5855 / 0x6c78 can turn an entry into a link or an executable on extraction.
163
+ * - 0x5455 extended timestamp, 0x000a NTFS times: timestamps only (Info-ZIP `zip`, 7-Zip, Windows).
164
+ * - 0x7875 Info-ZIP Unix UID/GID: ownership only (no mode, no link), and the Info-ZIP `zip` CLI
165
+ * writes it on every Unix entry, so refusing it would refuse ordinary command-line zips.
166
+ * - 0x7075 Unicode Path: only in the exact shape {@link checkUnicodePath} accepts.
167
+ * zip64 (0x0001) and the encryption fields are refused first, with their own reasons.
168
+ */
169
+ const EXTRA_ALLOWED = new Set([0x5455, 0x000a, 0x7875, EXTRA_UNICODE_PATH]);
170
+ const S_IFMT = 0o170000;
171
+ const S_IFREG = 0o100000;
172
+ const S_IFDIR = 0o040000;
173
+ /** True when the bytes START like a zip (a local header, or the 22-byte empty archive). */
174
+ export function looksLikeSaveZip(u8) {
175
+ if (u8.length < 4 || u8[0] !== 0x50 || u8[1] !== 0x4b)
176
+ return false;
177
+ return (u8[2] === 0x03 && u8[3] === 0x04) || (u8[2] === 0x05 && u8[3] === 0x06);
178
+ }
179
+ class ZipRefusal extends Error {
180
+ }
181
+ function refuse(error) {
182
+ throw new ZipRefusal(error);
183
+ }
184
+ // `ignoreBOM: true` keeps a leading U+FEFF in the decoded name (the default STRIPS it), so the
185
+ // control/format-character rule below sees it.
186
+ const utf8 = new TextDecoder('utf-8', { fatal: true, ignoreBOM: true });
187
+ let crcTable;
188
+ /**
189
+ * Running CRC-32 (IEEE 802.3, the zip one): start from `0`, feed chunks in order, the last return
190
+ * value is the CRC of the whole. Measured on Node 24: ~0.5 s for 256 MiB.
191
+ */
192
+ function crc32(bytes, previous = 0) {
193
+ if (!crcTable) {
194
+ crcTable = new Uint32Array(256);
195
+ for (let n = 0; n < 256; n++) {
196
+ let c = n;
197
+ for (let k = 0; k < 8; k++)
198
+ c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1;
199
+ crcTable[n] = c >>> 0;
200
+ }
201
+ }
202
+ const t = crcTable;
203
+ let c = (previous ^ 0xffffffff) >>> 0;
204
+ for (let i = 0; i < bytes.length; i++)
205
+ c = t[(c ^ bytes[i]) & 0xff] ^ (c >>> 8);
206
+ return (c ^ 0xffffffff) >>> 0;
207
+ }
208
+ /**
209
+ * Refuse STORED data behind a data descriptor that contains a data-descriptor (`PK\x07\x08`) or
210
+ * local-header (`PK\x03\x04`) signature. Such an entry has no size in its local header (jszip's
211
+ * `streamFiles` writes zeros), so a STREAMING reader cannot know where it ends and may stop at a
212
+ * signature inside it — after which a fake local header hidden in the data is extracted under a
213
+ * name nothing here checked. Deflated data ends at its own end-of-stream marker, so it is not
214
+ * scanned. For random bytes (image data) the odds of a false refusal are ~2 matches per 2^32 bytes:
215
+ * measured 2 in 4 GiB of random bytes, so ~12% for one 256 MiB stored + streamed zip — the error
216
+ * says how to avoid it (DEFLATE, or no streamFiles).
217
+ */
218
+ function checkStoredStreamedData(u8, start, end) {
219
+ for (let i = u8.indexOf(0x50, start); i >= 0 && i + 3 < end; i = u8.indexOf(0x50, i + 1)) {
220
+ if (u8[i + 1] !== 0x4b)
221
+ continue;
222
+ if (u8[i + 2] === 0x07 && u8[i + 3] === 0x08)
223
+ refuse(SAVE_ZIP_STORED_DESCRIPTOR_SIGNATURE_ERROR);
224
+ if (u8[i + 2] === 0x03 && u8[i + 3] === 0x04)
225
+ refuse(SAVE_ZIP_STORED_LOCAL_SIGNATURE_ERROR);
226
+ }
227
+ }
228
+ /**
229
+ * The Info-ZIP Unicode Path extra field (0x7075): `version (1) · CRC-32 of the header name (4) ·
230
+ * the name in UTF-8`. An extractor may take the entry's path from HERE instead of the header, so it
231
+ * is the one extra field that can make two readers see two different names. jszip writes it for
232
+ * every non-ASCII name — with the UTF-8 flag set and the SAME name in both places — so it is
233
+ * accepted in exactly that shape and refused in every other: the entry sets the UTF-8 flag,
234
+ * version is 1, the CRC is the header name's, and the UTF-8 name is byte-identical to the header
235
+ * name (which {@link decodeName} then holds to valid UTF-8). Any reader therefore extracts the one
236
+ * name every rule below was applied to.
237
+ */
238
+ function checkUnicodePath(view, p, size, name, flags) {
239
+ if (!(flags & FLAG_UTF8) || size < 5 || view.getUint8(p) !== 1) {
240
+ refuse(SAVE_ZIP_ALTERNATE_PATH_ERROR);
241
+ }
242
+ if (view.getUint32(p + 1, true) !== crc32(name))
243
+ refuse(SAVE_ZIP_ALTERNATE_PATH_ERROR);
244
+ const alt = new Uint8Array(view.buffer, view.byteOffset + p + 5, size - 5);
245
+ if (alt.length !== name.length || alt.some((b, i) => b !== name[i])) {
246
+ refuse(SAVE_ZIP_ALTERNATE_PATH_ERROR);
247
+ }
248
+ }
249
+ /**
250
+ * Walk the extra field block of the header whose name bytes and flags are `name` / `flags`; refuse
251
+ * a malformed block, zip64, encryption, any field not in {@link EXTRA_ALLOWED}, or a Unicode Path
252
+ * field that does not restate `name`.
253
+ */
254
+ function checkExtraFields(view, start, len, name, flags) {
255
+ let p = start;
256
+ const end = start + len;
257
+ while (p < end) {
258
+ if (p + 4 > end)
259
+ refuse(SAVE_ZIP_EXTRA_FIELD_ERROR);
260
+ const id = view.getUint16(p, true);
261
+ const size = view.getUint16(p + 2, true);
262
+ p += 4;
263
+ if (p + size > end)
264
+ refuse(SAVE_ZIP_EXTRA_FIELD_ERROR);
265
+ if (id === EXTRA_ZIP64)
266
+ refuse(SAVE_ZIP64_ERROR);
267
+ if (id === EXTRA_STRONG_ENCRYPTION || id === EXTRA_AES)
268
+ refuse(SAVE_ZIP_ENCRYPTED_ERROR);
269
+ if (!EXTRA_ALLOWED.has(id))
270
+ refuse(saveZipExtraFieldError(id));
271
+ if (id === EXTRA_UNICODE_PATH)
272
+ checkUnicodePath(view, p, size, name, flags);
273
+ p += size;
274
+ }
275
+ }
276
+ function decodeName(bytes, flags) {
277
+ if (flags & FLAG_UTF8) {
278
+ try {
279
+ return utf8.decode(bytes);
280
+ }
281
+ catch {
282
+ refuse(SAVE_ZIP_NAME_ENCODING_ERROR);
283
+ }
284
+ }
285
+ // No UTF-8 flag: the name is in an unstated legacy code page, which readers decode differently.
286
+ // Only ASCII means the same thing to all of them.
287
+ for (const b of bytes)
288
+ if (b >= 0x80)
289
+ refuse(SAVE_ZIP_NAME_ENCODING_ERROR);
290
+ return utf8.decode(bytes);
291
+ }
292
+ /** Name rules. Returns whether the entry is a directory. */
293
+ function checkName(name) {
294
+ if (name.length === 0)
295
+ refuse(SAVE_ZIP_EMPTY_SEGMENT_ERROR);
296
+ // \p{Cc} = C0/C1 controls incl. NUL; \p{Cf} = every bidi override/isolate and zero-width mark.
297
+ if (/[\p{Cc}\p{Cf}]/u.test(name))
298
+ refuse(SAVE_ZIP_CONTROL_CHAR_ERROR);
299
+ if (name.includes('\\'))
300
+ refuse(SAVE_ZIP_BACKSLASH_ERROR);
301
+ if (name.startsWith('/'))
302
+ refuse(SAVE_ZIP_ABSOLUTE_PATH_ERROR);
303
+ // A colon is a drive letter (`C:x`) or an NTFS alternate data stream (`a.txt:evil.exe`).
304
+ if (name.includes(':'))
305
+ refuse(SAVE_ZIP_DRIVE_OR_COLON_ERROR);
306
+ const isDir = name.endsWith('/');
307
+ const segments = (isDir ? name.slice(0, -1) : name).split('/');
308
+ for (const seg of segments) {
309
+ if (seg === '..')
310
+ refuse(SAVE_ZIP_TRAVERSAL_ERROR);
311
+ if (seg === '' || seg === '.')
312
+ refuse(SAVE_ZIP_EMPTY_SEGMENT_ERROR);
313
+ // Windows drops a trailing dot or space, so `a.txt.` / `a.txt ` land on `a.txt` (and `...`
314
+ // or `. .` on nothing): refused, rather than added to the duplicate key.
315
+ if (seg.endsWith('.') || seg.endsWith(' '))
316
+ refuse(SAVE_ZIP_SEGMENT_DOT_SPACE_ERROR);
317
+ }
318
+ if (!isDir) {
319
+ const last = segments[segments.length - 1] ?? '';
320
+ const dot = last.lastIndexOf('.');
321
+ const ext = dot >= 0 ? last.slice(dot + 1).toLowerCase() : '';
322
+ if (!SAVE_ZIP_ALLOWED_EXTENSIONS.has(ext))
323
+ refuse(saveZipEntryTypeError(ext));
324
+ }
325
+ return { isDir };
326
+ }
327
+ function validate(bytes) {
328
+ const u8 = new Uint8Array(bytes);
329
+ const view = new DataView(bytes);
330
+ const len = u8.length;
331
+ // ── EOCD: exactly the last 22 bytes (so no archive comment and nothing after it) ──────────────
332
+ if (len < EOCD_LEN)
333
+ refuse(SAVE_ZIP_TRUNCATED_ERROR);
334
+ const eocd = len - EOCD_LEN;
335
+ if (view.getUint32(eocd, true) !== SIG_EOCD)
336
+ refuse(SAVE_ZIP_NO_EOCD_ERROR);
337
+ if (eocd >= ZIP64_LOCATOR_LEN &&
338
+ view.getUint32(eocd - ZIP64_LOCATOR_LEN, true) === SIG_ZIP64_LOCATOR) {
339
+ refuse(SAVE_ZIP64_ERROR);
340
+ }
341
+ const diskNumber = view.getUint16(eocd + 4, true);
342
+ const cdDisk = view.getUint16(eocd + 6, true);
343
+ const entriesOnDisk = view.getUint16(eocd + 8, true);
344
+ const totalEntries = view.getUint16(eocd + 10, true);
345
+ const cdSize = view.getUint32(eocd + 12, true);
346
+ const cdOffset = view.getUint32(eocd + 16, true);
347
+ const commentLen = view.getUint16(eocd + 20, true);
348
+ if (totalEntries === 0xffff || cdSize === 0xffffffff || cdOffset === 0xffffffff) {
349
+ refuse(SAVE_ZIP64_ERROR);
350
+ }
351
+ if (commentLen !== 0)
352
+ refuse(SAVE_ZIP_NO_EOCD_ERROR);
353
+ if (diskNumber !== 0 || cdDisk !== 0 || entriesOnDisk !== totalEntries) {
354
+ refuse(SAVE_ZIP_MULTIDISK_ERROR);
355
+ }
356
+ if (totalEntries === 0)
357
+ refuse(SAVE_ZIP_EMPTY_ERROR);
358
+ if (totalEntries > SAVE_ZIP_LIMITS.maxEntries)
359
+ refuse(SAVE_ZIP_TOO_MANY_ENTRIES_ERROR);
360
+ // The central directory ends exactly where the EOCD starts.
361
+ if (cdOffset + cdSize !== eocd)
362
+ refuse(SAVE_ZIP_LAYOUT_ERROR);
363
+ // ── Central directory ─────────────────────────────────────────────────────────────────────────
364
+ const entries = [];
365
+ let p = cdOffset;
366
+ for (let i = 0; i < totalEntries; i++) {
367
+ if (p + CENTRAL_LEN > eocd)
368
+ refuse(SAVE_ZIP_CENTRAL_DIRECTORY_ERROR);
369
+ if (view.getUint32(p, true) !== SIG_CENTRAL)
370
+ refuse(SAVE_ZIP_CENTRAL_DIRECTORY_ERROR);
371
+ const flags = view.getUint16(p + 8, true);
372
+ const method = view.getUint16(p + 10, true);
373
+ const crc = view.getUint32(p + 16, true);
374
+ const compressedSize = view.getUint32(p + 20, true);
375
+ const size = view.getUint32(p + 24, true);
376
+ const nameLen = view.getUint16(p + 28, true);
377
+ const extraLen = view.getUint16(p + 30, true);
378
+ const commentLength = view.getUint16(p + 32, true);
379
+ const diskStart = view.getUint16(p + 34, true);
380
+ const externalAttrs = view.getUint32(p + 38, true);
381
+ const localOffset = view.getUint32(p + 42, true);
382
+ const recordEnd = p + CENTRAL_LEN + nameLen + extraLen + commentLength;
383
+ if (recordEnd > eocd)
384
+ refuse(SAVE_ZIP_CENTRAL_DIRECTORY_ERROR);
385
+ if (compressedSize === 0xffffffff || size === 0xffffffff || localOffset === 0xffffffff) {
386
+ refuse(SAVE_ZIP64_ERROR);
387
+ }
388
+ if (diskStart !== 0)
389
+ refuse(SAVE_ZIP_MULTIDISK_ERROR);
390
+ checkExtraFields(view, p + CENTRAL_LEN + nameLen, extraLen, u8.subarray(p + CENTRAL_LEN, p + CENTRAL_LEN + nameLen), flags);
391
+ if (flags & (FLAG_ENCRYPTED | FLAG_STRONG_ENCRYPTION | FLAG_MASKED_HEADERS)) {
392
+ refuse(SAVE_ZIP_ENCRYPTED_ERROR);
393
+ }
394
+ if (flags & ~FLAGS_ALLOWED)
395
+ refuse(SAVE_ZIP_FLAGS_ERROR);
396
+ if (method !== METHOD_STORED && method !== METHOD_DEFLATE)
397
+ refuse(saveZipMethodError(method));
398
+ // Unix mode in the high 16 bits (any host that sets it): only a regular file or a directory.
399
+ // A symlink entry would let a later entry write through it outside the extraction folder.
400
+ const fileType = (externalAttrs >>> 16) & S_IFMT;
401
+ if (fileType !== 0 && fileType !== S_IFREG && fileType !== S_IFDIR) {
402
+ refuse(SAVE_ZIP_SPECIAL_FILE_ERROR);
403
+ }
404
+ entries.push({
405
+ name: u8.subarray(p + CENTRAL_LEN, p + CENTRAL_LEN + nameLen),
406
+ flags,
407
+ method,
408
+ crc,
409
+ compressedSize,
410
+ size,
411
+ localOffset,
412
+ });
413
+ p = recordEnd;
414
+ }
415
+ // Every central-directory byte belongs to a record.
416
+ if (p !== eocd)
417
+ refuse(SAVE_ZIP_CENTRAL_DIRECTORY_ERROR);
418
+ // ── Names, types, sizes ───────────────────────────────────────────────────────────────────────
419
+ const seen = new Set();
420
+ const files = new Set();
421
+ const paths = [];
422
+ let total = 0;
423
+ for (const e of entries) {
424
+ const name = decodeName(e.name, e.flags);
425
+ const { isDir } = checkName(name);
426
+ // Case- and normalisation-insensitive, and a dir `a/` equals a file `a`: on a case-
427
+ // insensitive or NFD file system these are the same path, and one silently overwrites the other.
428
+ const key = (isDir ? name.slice(0, -1) : name).normalize('NFC').toLowerCase();
429
+ if (seen.has(key))
430
+ refuse(SAVE_ZIP_DUPLICATE_NAME_ERROR);
431
+ seen.add(key);
432
+ if (!isDir)
433
+ files.add(key);
434
+ paths.push({ key, isDir });
435
+ if (isDir && (e.size !== 0 || e.compressedSize !== 0))
436
+ refuse(SAVE_ZIP_DIRECTORY_DATA_ERROR);
437
+ if (e.method === METHOD_STORED && e.compressedSize !== e.size) {
438
+ refuse(SAVE_ZIP_STORED_SIZE_ERROR);
439
+ }
440
+ total += e.size;
441
+ if (total > SAVE_ZIP_LIMITS.maxTotalUncompressedBytes)
442
+ refuse(SAVE_ZIP_TOTAL_SIZE_ERROR);
443
+ if (e.size > SAVE_ZIP_LIMITS.ratioFloorBytes &&
444
+ e.size > SAVE_ZIP_LIMITS.maxEntryRatio * e.compressedSize) {
445
+ refuse(SAVE_ZIP_RATIO_ERROR);
446
+ }
447
+ }
448
+ // No entry may sit under a path another entry claims as a FILE (`a.txt` and `a.txt/b.txt`).
449
+ for (const { key } of paths) {
450
+ let slash = key.indexOf('/');
451
+ while (slash >= 0) {
452
+ if (files.has(key.slice(0, slash)))
453
+ refuse(SAVE_ZIP_PATH_CONFLICT_ERROR);
454
+ slash = key.indexOf('/', slash + 1);
455
+ }
456
+ }
457
+ // ── Local headers: contiguous from byte 0, each agreeing with its central record ──────────────
458
+ const deflated = [];
459
+ let cursor = 0;
460
+ for (const [i, e] of entries.entries()) {
461
+ if (e.localOffset !== cursor)
462
+ refuse(SAVE_ZIP_LAYOUT_ERROR);
463
+ if (cursor + LOCAL_LEN > cdOffset)
464
+ refuse(SAVE_ZIP_TRUNCATED_ERROR);
465
+ if (view.getUint32(cursor, true) !== SIG_LOCAL)
466
+ refuse(SAVE_ZIP_LOCAL_HEADER_ERROR);
467
+ const flags = view.getUint16(cursor + 6, true);
468
+ const method = view.getUint16(cursor + 8, true);
469
+ const crc = view.getUint32(cursor + 14, true);
470
+ const compressedSize = view.getUint32(cursor + 18, true);
471
+ const size = view.getUint32(cursor + 22, true);
472
+ const nameLen = view.getUint16(cursor + 26, true);
473
+ const extraLen = view.getUint16(cursor + 28, true);
474
+ const nameStart = cursor + LOCAL_LEN;
475
+ const dataOffset = nameStart + nameLen + extraLen;
476
+ if (dataOffset > cdOffset)
477
+ refuse(SAVE_ZIP_TRUNCATED_ERROR);
478
+ const localName = u8.subarray(nameStart, nameStart + nameLen);
479
+ if (localName.length !== e.name.length || localName.some((b, j) => b !== e.name[j])) {
480
+ refuse(SAVE_ZIP_HEADER_MISMATCH_ERROR);
481
+ }
482
+ if (flags !== e.flags || method !== e.method)
483
+ refuse(SAVE_ZIP_HEADER_MISMATCH_ERROR);
484
+ checkExtraFields(view, nameStart + nameLen, extraLen, localName, flags);
485
+ const hasDescriptor = (e.flags & FLAG_DATA_DESCRIPTOR) !== 0;
486
+ const localZero = crc === 0 && compressedSize === 0 && size === 0;
487
+ const localMatches = crc === e.crc && compressedSize === e.compressedSize && size === e.size;
488
+ // With a data descriptor the local header may carry zeros (written before the data was known).
489
+ if (!localMatches && !(hasDescriptor && localZero))
490
+ refuse(SAVE_ZIP_HEADER_MISMATCH_ERROR);
491
+ const dataEnd = dataOffset + e.compressedSize;
492
+ if (dataEnd > cdOffset)
493
+ refuse(SAVE_ZIP_TRUNCATED_ERROR);
494
+ // Where the next record must start pins the descriptor's length: 0 without one, else 12, or
495
+ // 16 with its optional signature. (A zip64 descriptor is 20 / 24 and lands here as a mismatch.)
496
+ const next = entries[i + 1]?.localOffset ?? cdOffset;
497
+ const descriptorLen = next - dataEnd;
498
+ if (!hasDescriptor) {
499
+ if (descriptorLen !== 0)
500
+ refuse(SAVE_ZIP_LAYOUT_ERROR);
501
+ }
502
+ else {
503
+ let d = dataEnd;
504
+ if (descriptorLen === 16) {
505
+ if (view.getUint32(d, true) !== SIG_DATA_DESCRIPTOR)
506
+ refuse(SAVE_ZIP_DATA_DESCRIPTOR_ERROR);
507
+ d += 4;
508
+ }
509
+ else if (descriptorLen !== 12) {
510
+ refuse(SAVE_ZIP_DATA_DESCRIPTOR_ERROR);
511
+ }
512
+ if (view.getUint32(d, true) !== e.crc ||
513
+ view.getUint32(d + 4, true) !== e.compressedSize ||
514
+ view.getUint32(d + 8, true) !== e.size) {
515
+ refuse(SAVE_ZIP_DATA_DESCRIPTOR_ERROR);
516
+ }
517
+ }
518
+ if (e.method === METHOD_DEFLATE) {
519
+ deflated.push({ dataOffset, compressedSize: e.compressedSize, size: e.size, crc: e.crc });
520
+ }
521
+ else {
522
+ // STORED: the data IS the content, so its CRC is checked here (a deflated entry's output is
523
+ // checked by verifySaveZipInflate, chunk by chunk).
524
+ if (hasDescriptor)
525
+ checkStoredStreamedData(u8, dataOffset, dataEnd);
526
+ if (crc32(u8.subarray(dataOffset, dataEnd)) !== e.crc)
527
+ refuse(SAVE_ZIP_CRC_ERROR);
528
+ }
529
+ // For the last entry `next` is cdOffset, so the walk ends exactly where the directory starts.
530
+ cursor = next;
531
+ }
532
+ return { ok: true, entryCount: entries.length, deflated };
533
+ }
534
+ /**
535
+ * Validate a zip's structure, names and declared sizes. Synchronous and allocation-light (views
536
+ * over the caller's buffer). The caller has already applied the byte cap
537
+ * ({@link SAVE_ZIP_MAX_BYTES}). A pass still needs {@link verifySaveZipInflate} before the save.
538
+ */
539
+ export function validateSaveZip(bytes) {
540
+ try {
541
+ return validate(bytes);
542
+ }
543
+ catch (err) {
544
+ if (err instanceof ZipRefusal)
545
+ return { ok: false, error: err.message };
546
+ // A RangeError from a DataView read past the end is a truncated archive, nothing else.
547
+ if (err instanceof RangeError)
548
+ return { ok: false, error: SAVE_ZIP_TRUNCATED_ERROR };
549
+ throw err;
550
+ }
551
+ }
552
+ /**
553
+ * Inflate `data` (raw deflate), stopping as soon as it yields more than `limit` bytes. Resolves to
554
+ * `{ produced, crc }` when the stream ENDED cleanly, or `null` when it errored (corrupt, truncated,
555
+ * or — on an engine that reports it — data after its end-of-stream marker) or overshot `limit`.
556
+ */
557
+ async function inflate(data, limit, signal) {
558
+ if (signal?.aborted)
559
+ throw new SaveZipVerifyAbortedError();
560
+ const ds = new DecompressionStream('deflate-raw');
561
+ const writer = ds.writable.getWriter();
562
+ const reader = ds.readable.getReader();
563
+ // Feed in slices so a bomb is caught after the first slice that overshoots, not after all of it.
564
+ const CHUNK = SAVE_ZIP_INFLATE_SLICE_BYTES;
565
+ const feed = (async () => {
566
+ for (let off = 0; off < data.length; off += CHUNK) {
567
+ await writer.write(data.subarray(off, Math.min(off + CHUNK, data.length)));
568
+ }
569
+ await writer.close();
570
+ })();
571
+ feed.catch(() => undefined);
572
+ // An abort cancels both ends at once, so the pending read settles promptly.
573
+ const onAbort = () => {
574
+ void reader.cancel().catch(() => undefined);
575
+ void writer.abort().catch(() => undefined);
576
+ };
577
+ signal?.addEventListener('abort', onAbort, { once: true });
578
+ let produced = 0;
579
+ let crc = 0;
580
+ try {
581
+ for (;;) {
582
+ const { done, value } = await reader.read();
583
+ if (done)
584
+ break;
585
+ produced += value.byteLength;
586
+ if (produced > limit) {
587
+ await reader.cancel().catch(() => undefined);
588
+ await writer.abort().catch(() => undefined);
589
+ return null;
590
+ }
591
+ crc = crc32(value, crc);
592
+ }
593
+ await feed;
594
+ }
595
+ catch {
596
+ if (signal?.aborted)
597
+ throw new SaveZipVerifyAbortedError();
598
+ return null;
599
+ }
600
+ finally {
601
+ signal?.removeEventListener('abort', onAbort);
602
+ }
603
+ if (signal?.aborted)
604
+ throw new SaveZipVerifyAbortedError();
605
+ return { produced, crc };
606
+ }
607
+ /**
608
+ * Check one deflated entry: it inflates to exactly `e.size` bytes whose CRC-32 is `e.crc`, and its
609
+ * deflate stream ends at the LAST of its `compressedSize` bytes. The last part is what catches bytes
610
+ * hidden after the end-of-stream marker (a streaming reader would read them as the next record)
611
+ * on an engine whose DecompressionStream does not throw on trailing data: the same stream WITHOUT
612
+ * its last byte must fail to complete (the Compression Streams spec errors a truncated stream). If
613
+ * it completes, the stream ended earlier and the remaining bytes are not deflate data. That costs a
614
+ * second inflate, run alongside the first.
615
+ */
616
+ async function checkDeflatedEntry(u8, e, signal) {
617
+ const data = u8.subarray(e.dataOffset, e.dataOffset + e.compressedSize);
618
+ const [full, short] = await Promise.all([
619
+ inflate(data, e.size, signal),
620
+ data.length > 0 ? inflate(data.subarray(0, data.length - 1), e.size, signal) : Promise.resolve(null),
621
+ ]);
622
+ if (!full || full.produced !== e.size)
623
+ return SAVE_ZIP_INFLATE_ERROR;
624
+ if (short && short.produced === e.size)
625
+ return SAVE_ZIP_INFLATE_TRAILING_ERROR;
626
+ if (full.crc !== e.crc)
627
+ return SAVE_ZIP_CRC_ERROR;
628
+ return null;
629
+ }
630
+ /**
631
+ * Inflate every deflated entry {@link validateSaveZip} returned and refuse the zip unless each
632
+ * yields exactly its declared size and CRC-32, with nothing after its end-of-stream marker — so the
633
+ * declared-size bounds cannot be walked by lying about them, and no bytes ride along unchecked.
634
+ * Work is bounded by twice the declared total ({@link SAVE_ZIP_LIMITS}; two inflates per entry)
635
+ * plus one {@link SAVE_ZIP_INFLATE_SLICE_BYTES} slice each. Returns the error string, or `null`
636
+ * when every entry checks out. When `signal` fires (or has already) it stops promptly and REJECTS
637
+ * with {@link SaveZipVerifyAbortedError} — a caller's deadline, not a verdict on the zip.
638
+ */
639
+ export async function verifySaveZipInflate(bytes, deflated, signal) {
640
+ if (signal?.aborted)
641
+ throw new SaveZipVerifyAbortedError();
642
+ const u8 = new Uint8Array(bytes);
643
+ for (const e of deflated) {
644
+ const error = await checkDeflatedEntry(u8, e, signal);
645
+ if (error)
646
+ return error;
647
+ }
648
+ return null;
649
+ }
650
+ //# sourceMappingURL=index.js.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@civitai/app-sdk",
3
- "version": "0.84.1",
3
+ "version": "0.86.0",
4
4
  "description": "OAuth + PKCE, encrypted-cookie sessions, scopes, and orchestrator helpers for building third-party Civitai apps.",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -51,6 +51,10 @@
51
51
  "types": "./dist/vite/index.d.ts",
52
52
  "import": "./dist/vite/index.js"
53
53
  },
54
+ "./save-zip": {
55
+ "types": "./dist/save-zip/index.d.ts",
56
+ "import": "./dist/save-zip/index.js"
57
+ },
54
58
  "./schemas/app-block/v1.json": "./schemas/app-block/v1.json"
55
59
  },
56
60
  "comment-packaging": "`!dist/**/*.map` keeps dangling sourcemaps out of the tarball (#376). Rationale: scripts/check-shipped-sourcemaps.mjs.",
@@ -125,6 +129,7 @@
125
129
  "@civitai/client": "0.2.0-beta.98",
126
130
  "@types/node": "^25.9.1",
127
131
  "ajv": "^8.17.1",
132
+ "jszip": "^3.10.1",
128
133
  "typescript": "^5.9.2",
129
134
  "vite": "^8.0.14",
130
135
  "vitest": "^4.1.11"
@@ -42,6 +42,13 @@
42
42
  "maxLength": 200,
43
43
  "pattern": "^https://(github\\.com|gitlab\\.com|codeberg\\.org)/[^/]+/[^/]+/?$"
44
44
  },
45
+ "bugs": {
46
+ "type": "string",
47
+ "description": "Optional PUBLIC ISSUE-TRACKER / SUPPORT link: a URL string, like `repository`. The npm-style object form (`{ \"url\": ..., \"email\": ... }`) is NOT supported and is refused. Rendered as a `Support` row on the app's `/apps` store DETAIL page. Manifest-governed like `repository`: it flows to the store listing on moderator-approve and is re-synced on every approved version; remove the key and the link is cleared. Must be an `https://` URL, carry no embedded credentials and no port, and be at most 200 characters (MAX_ISSUE_TRACKER_URL_LENGTH in src/server/schema/blocks/external-app.schema.ts). Any host is accepted. Treat passing local validation as necessary, not sufficient — `validateIssueTrackerUrl` in that file is authoritative.",
48
+ "minLength": 1,
49
+ "maxLength": 200,
50
+ "pattern": "^https://"
51
+ },
45
52
  "type": {
46
53
  "type": "string",
47
54
  "description": "Free-form descriptor used by some examples (e.g. \"block\"). Not validated by the platform.",
@@ -194,7 +201,7 @@
194
201
  },
195
202
  "page": {
196
203
  "type": "object",
197
- "description": "Full-page surface descriptor (W10). Page apps mount at /apps/run/<slug>.",
204
+ "description": "Full-page surface descriptor (W10). Page apps mount at /apps/run/<slug>. A manifest without non-empty `targets` must declare `page`.",
198
205
  "additionalProperties": false,
199
206
  "required": ["path", "title"],
200
207
  "properties": {
@@ -607,7 +614,7 @@
607
614
  },
608
615
  "targets": {
609
616
  "type": "array",
610
- "description": "Model-page slot targets. Each target's slotId must be a known registered model slot (not the page slot). Optional for page-only apps.",
617
+ "description": "Model-page slot targets. Each target's slotId must be a known registered model slot (not the page slot). Optional for a page app; a manifest without `page` must declare at least one target.",
611
618
  "maxItems": 16,
612
619
  "items": {
613
620
  "type": "object",
@@ -774,6 +781,20 @@
774
781
  "then": {
775
782
  "required": ["outputDir"]
776
783
  }
784
+ },
785
+ {
786
+ "$comment": "A manifest must declare at least one surface: a non-empty `targets` array (model-page slots) or a `page` object (a full-page app). The platform refuses a submission with neither, and the build would fail it.",
787
+ "anyOf": [
788
+ {
789
+ "required": ["targets"],
790
+ "properties": {
791
+ "targets": { "minItems": 1 }
792
+ }
793
+ },
794
+ {
795
+ "required": ["page"]
796
+ }
797
+ ]
777
798
  }
778
799
  ]
779
800
  }