@git-stunts/git-cas 7.2.0 → 8.0.0-rc.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +29 -0
- package/README.md +30 -1
- package/UPGRADING.md +20 -0
- package/build-info.json +2 -2
- package/docs/API.md +35 -0
- package/docs/releases/v7.2.0.md +7 -1
- package/docs/releases/v8.0.0-rc.1.md +25 -0
- package/files.d.ts +20 -0
- package/files.js +2 -0
- package/index.js +5 -4
- package/package.json +10 -3
- package/scripts/migrate-encryption.js +2 -4
- package/src/infrastructure/adapters/FileIOHelper.js +2 -68
- package/src/infrastructure/adapters/GitPersistenceAdapter.js +16 -6
- package/src/infrastructure/adapters/RestorePath.js +144 -0
- package/src/infrastructure/adapters/RuntimeJsonCodec.js +30 -0
- package/src/infrastructure/adapters/materializeFile.js +172 -0
- package/src/package-version.js +16 -1
package/CHANGELOG.md
CHANGED
|
@@ -7,6 +7,35 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|
|
7
7
|
|
|
8
8
|
## [Unreleased]
|
|
9
9
|
|
|
10
|
+
## [8.0.0-rc.1] — 2026-12-01
|
|
11
|
+
|
|
12
|
+
### Breaking Changes
|
|
13
|
+
|
|
14
|
+
- git-cas depends on `@git-stunts/plumbing` 4 (`^4.0.0-rc.1`) instead of 3.x. Plumbing 4 itself changes behavior for applications that also call it directly; see `UPGRADING.md`.
|
|
15
|
+
- An application that passes its own plumbing instance to git-cas must use plumbing 4, installed as the same copy git-cas uses. git-cas recognises plumbing's errors by class, so an instance from a separate 3.x copy turns, for example, a missing object into plumbing's `GitObjectMissingError` instead of git-cas's `GIT_OBJECT_NOT_FOUND`.
|
|
16
|
+
- `GitPersistenceAdapter.readBlobStream()` starts its one-shot `git cat-file blob` command when the caller first reads the returned stream, not when the stream is returned. A stream that is never read starts no git process, and a stream first read after the adapter closed fails with `RESOURCE_CLOSED`.
|
|
17
|
+
|
|
18
|
+
### Added
|
|
19
|
+
|
|
20
|
+
- Optional `@git-stunts/git-cas/files` helper `materializeFile()` streams an async byte source to a private sibling file, then renames on success, and resolves if and only if the file was published. It does not fsync. It supports cancellation, which rejects with `signal.reason` until the rename starts, and optional whole-plaintext SHA-256 verification. It follows a destination symlink, including a dangling one, that resolves inside the base and replaces or creates the file it names. It reuses restore path confinement, rejects an output path that resolves to the base directory before reading the source, rejects source chunks that are not `Uint8Array` with `INVALID_OPTIONS`, and leaves the core byte-stream and buffer APIs unchanged. `restoreFile()` changes only by the path fixes listed under Fixed.
|
|
21
|
+
|
|
22
|
+
### Changed
|
|
23
|
+
|
|
24
|
+
- `@git-stunts/plumbing` moves from `^3.3.3` to `^4.0.0-rc.1`, which accepts the first 4.0.0 release candidate (npm `next` tag) and every later 4.x release, including 4.0.0 final. The lockfile resolves `4.0.0-rc.1`. An application that passes its own plumbing instance to git-cas must use plumbing 4 resolved to the same installed copy, so that git-cas recognises plumbing's errors; see `UPGRADING.md`. git-cas already accepts 40- and 64-digit object ids, installs no signal handlers, supplies no custom command runner, and does not retry on plumbing timeouts. The unit and integration suites pass on Node, Bun and Deno, and 500 consecutive two-writer guarded root-set replacements (`scripts/diagnostics/stress-root-set-replacement.js`) each accept exactly one winner.
|
|
25
|
+
- With 4.0.0-rc.1, a guarded `update-ref` that loses a compare-and-swap race through `plumbing.execute()` reports git's complete stderr and arrives as `GitRepositoryLockedError` (git-stunts/plumbing#9). Root-set persistence keeps its fallback that treats an exit-128 failure with empty stderr and an observed head advance as a conflict.
|
|
26
|
+
- Manifests record `formatVersion` as the `MAJOR.MINOR.PATCH` core of the package version, so 8.0.0-rc.1 writes `"8.0.0"`. The manifest schema, in this release and every release since 6.0.0, accepts only three numeric components; stamping `8.0.0-rc.1` would have made every new manifest fail validation. The encryption migration script stamps the same value. Stable versions are unchanged.
|
|
27
|
+
- The release workflow publishes a version that contains a hyphen, such as `8.0.0-rc.1`, to npm under the `next` dist-tag and marks its GitHub Release as a prerelease. A plain version publishes under `latest` as before. The publish step refuses to run if the dist-tag does not match the version.
|
|
28
|
+
|
|
29
|
+
### Performance
|
|
30
|
+
|
|
31
|
+
- The default JSON façade uses a runtime adapter for native UTF-8 decoding; the exported portable JsonCodec stays unchanged. `test/benchmark/json-decode.bench.js` measured decoding of generated manifest-shaped metadata 2.6x to 6x faster on Node 22, rising with payload size. Runtimes whose `TextDecoder` rejects the `fatal` option, such as Node builds without ICU, use the portable decoder. Malformed-byte fallback, BOM handling, JSON parsing, validation and stored encoding remain compatible.
|
|
32
|
+
|
|
33
|
+
### Fixed
|
|
34
|
+
|
|
35
|
+
- `restoreFile()` and `materializeFile()` accept output names inside the base directory that begin with two dots, such as `..cache`. Only `..` and paths that begin with `..` plus a separator are treated as escapes.
|
|
36
|
+
- `restoreFile()` rejects an output path that is a dangling symlink to a location outside the base directory with `SECURITY_BOUNDARY_VIOLATION`. Before, the boundary check treated the missing link target as an ordinary new file inside the base, and the restore wrote through the link to the outside location. A dangling link to a path inside the base is now followed in every restore mode, creating the file it names and keeping the link; before, a bounded (buffered) restore replaced such a link with a regular file. Link text is resolved one component at a time, as the kernel resolves it, so in `dir/../file` the `..` applies after the symlink `dir` is followed. Link text that passes through a regular file, such as `file.txt/../x` or `file.txt/`, is rejected with `ENOTDIR`.
|
|
37
|
+
- When `GitPersistenceAdapter.readBlobStream()` reads a blob with a one-shot `git cat-file blob` command, it now starts that command when the caller first reads the stream, not when the stream is returned. It uses that command for a blob over 10 MiB, when its `cat-file` session cannot report the object's type and size, reports a type other than blob, or fails to read the blob, and with plumbing that has no object sessions. Plumbing 4 fails a command's stdout with `UnreadOutputLimitError` once more than 10 MiB arrives unread, so with the old eager start a blob over 10 MiB whose caller waited before reading would fail. Such a stream starts no `git cat-file blob` if it is never read, and fails with `RESOURCE_CLOSED` if first read after the adapter closed. A blob of 10 MiB or less that the adapter's `cat-file` session reads is still read into memory before `readBlobStream()` returns, and its stream still yields after close.
|
|
38
|
+
|
|
10
39
|
## [7.2.0] — 2026-11-06
|
|
11
40
|
|
|
12
41
|
### Changed
|
package/README.md
CHANGED
|
@@ -64,12 +64,14 @@ bounded recovery/inspection. See the [release notes](./docs/releases/v7.1.0.md)
|
|
|
64
64
|
and [publication and fresh registry-consumer evidence](https://github.com/git-stunts/git-cas/issues/162).
|
|
65
65
|
The signed tag, npm gitHead and successful release workflow agree on `18f87dd`.
|
|
66
66
|
|
|
67
|
-
|
|
67
|
+
Published v7.2.0 path-compresses the reservation index, so a ledger
|
|
68
68
|
update writes about log16(records) trees instead of 64. A 7.1.0 index still
|
|
69
69
|
reads and updates, but 7.1.0 refuses an index 7.2.0 has written; see the
|
|
70
70
|
[release notes](./docs/releases/v7.2.0.md) and
|
|
71
71
|
[#169](https://github.com/git-stunts/git-cas/issues/169).
|
|
72
72
|
|
|
73
|
+
The v8.0.0-rc.1 release candidate moves git-cas to `@git-stunts/plumbing` 4 and is bound for npm's `next` dist-tag; `latest` stays on 7.2.0. An application that passes its own plumbing instance must use plumbing 4 too, and `readBlobStream()` now starts git on first read. See the [migration guidance](./UPGRADING.md#v720-to-v800-rc1) and [release notes](./docs/releases/v8.0.0-rc.1.md).
|
|
74
|
+
|
|
73
75
|
The published v6.5.12 release bounds object-metadata requests so root sets with more than 1000 targets (936 for SHA-256) validate within Plumbing's cat-file request limits. Admission still rejects missing and mismatched targets before publication; see [v6.5.12 Release Notes](./docs/releases/v6.5.12.md).
|
|
74
76
|
|
|
75
77
|
### 1. CLI Usage
|
|
@@ -123,6 +125,33 @@ retention witness identifies the exact Git generation and tree edge that made
|
|
|
123
125
|
the asset reachable. `close()` releases local resources only; it never deletes
|
|
124
126
|
objects, updates refs, or changes retention.
|
|
125
127
|
|
|
128
|
+
### Optional atomic file output
|
|
129
|
+
|
|
130
|
+
Byte streaming remains the default. Applications that want a complete file
|
|
131
|
+
published only after streaming succeeds can opt into a separate helper.
|
|
132
|
+
The CAS session must stay open until the helper finishes:
|
|
133
|
+
|
|
134
|
+
```js
|
|
135
|
+
import ContentAddressableStore from '@git-stunts/git-cas';
|
|
136
|
+
import { materializeFile } from '@git-stunts/git-cas/files';
|
|
137
|
+
|
|
138
|
+
// `handle` is the content locator returned by an earlier cas.assets.put().
|
|
139
|
+
async function materializeAsset(handle) {
|
|
140
|
+
const cas = await ContentAddressableStore.open({ cwd: '.' });
|
|
141
|
+
try {
|
|
142
|
+
await materializeFile({
|
|
143
|
+
source: cas.assets.open({ handle }),
|
|
144
|
+
baseDirectory: '/existing/cache',
|
|
145
|
+
outputPath: 'asset.bin',
|
|
146
|
+
});
|
|
147
|
+
} finally {
|
|
148
|
+
await cas.close();
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
```
|
|
152
|
+
|
|
153
|
+
The helper stages beside the destination, renames on success, and resolves if and only if the file was published. It does not fsync, so after a crash or power loss the destination can hold the old contents, the new contents, or an empty or truncated file on some filesystems. After cancellation, a source that was blocked in a pull may finish that one pull after the helper settles; its result or error is discarded, so closing the session once the helper settles, as above, is safe. See the [contract, cancellation and optional SHA-256 check](./docs/API.md#optional-file-materialization-git-stuntsgit-casfiles). The application owns cache policy and durability requirements.
|
|
154
|
+
|
|
126
155
|
## Capability Map
|
|
127
156
|
|
|
128
157
|
The README is the front door. Detailed mechanics live in the guide set:
|
package/UPGRADING.md
CHANGED
|
@@ -2,6 +2,26 @@
|
|
|
2
2
|
|
|
3
3
|
This guide covers breaking changes and migration steps for git-cas releases.
|
|
4
4
|
|
|
5
|
+
## v7.2.0 To v8.0.0-rc.1
|
|
6
|
+
|
|
7
|
+
git-cas 8.0.0-rc.1 is a release candidate on npm's `next` dist-tag (`npm install @git-stunts/git-cas@next`); `latest` stays on 7.2.0. It depends on `@git-stunts/plumbing` `^4.0.0-rc.1`, which accepts plumbing 4.0.0 final and later 4.x releases. The stored data format and the public API's signatures do not change, but three behaviors are breaking for consumers. See the [release notes](./docs/releases/v8.0.0-rc.1.md).
|
|
8
|
+
|
|
9
|
+
### Plumbing 4
|
|
10
|
+
|
|
11
|
+
If your application also uses plumbing directly, read the plumbing 4.0.0 changelog: a deadline now kills git's whole process group and is not retried, more than 10 MiB of unread stdout fails with `UnreadOutputLimitError`, `GitSha` accepts SHA-256 ids, and plumbing forwards `SIGINT`, `SIGTERM` and `SIGHUP` to running git commands (declare a handler plumbing cannot see with `declareSignalHandler()`).
|
|
12
|
+
|
|
13
|
+
### Injected plumbing instances
|
|
14
|
+
|
|
15
|
+
If you pass your own plumbing instance to `ContentAddressableStore` (or to `GitPersistenceAdapter`, `GitRefAdapter` or `GitRepositoryInspectionAdapter`), change your application's `@git-stunts/plumbing` dependency to a plumbing 4 range that resolves to the same version git-cas uses, such as `^4.0.0-rc.1`, so that your package manager installs one copy shared with git-cas. Check with `npm ls @git-stunts/plumbing` or `pnpm why @git-stunts/plumbing` that only one copy is installed. git-cas recognises plumbing's errors (`GitObjectMissingError`, `GitProtocolError`, `InvalidArgumentError`) by class. An instance from a separately installed 3.x copy throws errors of other classes, so, for example, reading a missing object reports plumbing's `GitObjectMissingError` instead of git-cas's `GIT_OBJECT_NOT_FOUND`, and git-cas's one-time recovery of a failed object session does not run.
|
|
16
|
+
|
|
17
|
+
### Lazy `readBlobStream()`
|
|
18
|
+
|
|
19
|
+
`GitPersistenceAdapter.readBlobStream()` now starts its one-shot `git cat-file blob` command when you first read the returned stream, not when the call returns. This path serves blobs over 10 MiB, blobs the adapter's `cat-file` session cannot describe or read, and plumbing without object sessions. Code that obtained such a stream and read it only after closing the adapter (or the store that owns it) now gets `RESOURCE_CLOSED`; read the stream before closing. A stream you never read no longer starts a git process. Blobs of 10 MiB or less that the session reads are unchanged: they are read into memory before the call returns, and their streams still yield after close.
|
|
20
|
+
|
|
21
|
+
### Manifest `formatVersion`
|
|
22
|
+
|
|
23
|
+
New manifests record `formatVersion: "8.0.0"`, the `MAJOR.MINOR.PATCH` core of the package version, not `8.0.0-rc.1`. The manifest schema accepts only three numeric components, so 7.x readers accept manifests this candidate writes.
|
|
24
|
+
|
|
5
25
|
## v6.5.12 To v7.0.0 (candidate)
|
|
6
26
|
|
|
7
27
|
This is a breaking migration because the
|
package/build-info.json
CHANGED
package/docs/API.md
CHANGED
|
@@ -1035,6 +1035,41 @@ Encrypted restore behavior follows the existing streaming matrix; explicit
|
|
|
1035
1035
|
Missing transferred objects fail with `HANDLE_TARGET_MISSING`. A handle created
|
|
1036
1036
|
for a different manifest codec fails with `HANDLE_CODEC_MISMATCH`.
|
|
1037
1037
|
|
|
1038
|
+
### Optional file materialization (`@git-stunts/git-cas/files`)
|
|
1039
|
+
|
|
1040
|
+
```javascript
|
|
1041
|
+
import { materializeFile } from '@git-stunts/git-cas/files';
|
|
1042
|
+
|
|
1043
|
+
const result = await materializeFile({
|
|
1044
|
+
source: cas.assets.open({ handle, encryptionKey }),
|
|
1045
|
+
baseDirectory: '/existing/cache',
|
|
1046
|
+
outputPath: 'document.md',
|
|
1047
|
+
// Optional extra whole-plaintext verification, for example from a catalog:
|
|
1048
|
+
expectedSha256: catalog.sha256,
|
|
1049
|
+
signal: controller.signal,
|
|
1050
|
+
});
|
|
1051
|
+
// result: { bytesWritten }
|
|
1052
|
+
```
|
|
1053
|
+
|
|
1054
|
+
This opt-in filesystem helper consumes an `AsyncIterable<Uint8Array>` with
|
|
1055
|
+
backpressure. It works with `assets.open()` and `restoreStream()` or another
|
|
1056
|
+
byte source. `assets.open()`, `restoreStream()`, `restore()` and the existing
|
|
1057
|
+
`restoreFile()` keep their contracts. No caller is switched to file output.
|
|
1058
|
+
|
|
1059
|
+
`source`, `baseDirectory` and `outputPath` are required. The base and output parent must exist. Absolute output paths must remain inside the base. The output path must name a file inside the base, not the base directory itself; that path is rejected before the source is read. Existing symlink prefixes are resolved using the same path boundary as `restoreFile()`. Parent directories are trusted local application directories; this check does not make concurrent hostile path replacement safe.
|
|
1060
|
+
|
|
1061
|
+
If `outputPath` itself is a symlink, the helper follows it, even when it dangles: the path it names must resolve inside the base, the file there is replaced or created, and the link is left in place. A link that names a path outside the base is rejected with `SECURITY_BOUNDARY_VIOLATION` before the source is read, and a symlink loop is rejected with the runtime's `ELOOP` error. Link text is resolved one component at a time, as the kernel resolves it; text that passes through a regular file, such as `file.txt/../x`, is rejected with `ENOTDIR` before the source is read. The helper never replaces the link itself.
|
|
1062
|
+
|
|
1063
|
+
The helper writes a private, uniquely named sibling temporary file, waits for the source and write pipeline to complete, optionally compares the plaintext SHA-256, checks cancellation, then renames into place. It does not collect the whole file. Encryption authentication and existing buffering limits belong to the source: whole-object `assets.open()` retains its existing buffer limits. Without `expectedSha256`, there is no additional whole-file digest check beyond what the source provides. Digest hex is case-insensitive. Each chunk is copied when it is pulled, so the published file, and any digest check, hold exactly the bytes the source yielded, even if the source reuses a buffer after yielding it.
|
|
1064
|
+
|
|
1065
|
+
The helper does not iterate the source until the options and path checks have passed, so a rejected call starts no read. `assets.open()` does no work, and starts no `git cat-file`, before its first pull. Once started, the helper pulls continuously, limited only by write backpressure.
|
|
1066
|
+
|
|
1067
|
+
The call resolves if and only if the file was published. Rename is the publication point. Source, authentication, write, digest and cancellation failures before rename reject and leave an existing destination untouched. Cancellation and write failures settle the call even while the source is waiting to produce its next chunk; the helper then asks the source to return, without waiting for it to resume. A source that was blocked in a pull may therefore finish that one pull after the call settles, and that late pull's bytes or error are discarded, so closing the CAS session once the call settles is safe. Temporary output is removed on success and failure. If removing the empty temporary directory fails after publication, the call still resolves and the directory can remain. If cleanup also fails after an earlier failure, the earlier failure is reported and the private temporary directory can remain. The final file has permissions no broader than `0600`. Concurrent successful publishers use last-rename-wins behavior.
|
|
1068
|
+
|
|
1069
|
+
This guarantees atomic visibility of one file on filesystems supporting atomic same-filesystem rename. It does not fsync the file or its directory. After a crash or power loss, the destination can therefore hold the previous contents, the new contents, or, on some filesystems, an empty or truncated file, and a private `.git-cas-materialize-*` temporary directory can remain beside it. An application that needs durability must fsync itself; it may delete leftover `.git-cas-materialize-*` directories after establishing that no active writer owns them. The helper does not create parents, transfer retention, change Git refs, enforce cache quotas, manage eviction, or transact a whole directory. Applications own those policies.
|
|
1070
|
+
|
|
1071
|
+
Errors: malformed options, digest syntax, a `signal` that is not an `AbortSignal` or a source chunk that is not a `Uint8Array` use `INVALID_OPTIONS`; an escaping path or an output path that resolves to the base directory uses `SECURITY_BOUNDARY_VIOLATION`; a full-file digest mismatch uses `INTEGRITY_ERROR`. Cancellation observed before the rename rejects with `signal.reason`. The helper checks the signal last just before the rename; once the rename has started, cancellation cannot stop publication, and the call resolves with the published file. Source errors are propagated unchanged, including falsy rejection values; filesystem errors retain their underlying runtime error forms.
|
|
1072
|
+
|
|
1038
1073
|
### `assets.adopt()`
|
|
1039
1074
|
|
|
1040
1075
|
```javascript
|
package/docs/releases/v7.2.0.md
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# git-cas v7.2.0: path-compressed reservation index
|
|
2
2
|
|
|
3
|
-
This release
|
|
3
|
+
This release makes each reservation ledger update write about log16(records) index trees instead of 64. The change merged in [PR #168](https://github.com/git-stunts/git-cas/pull/168) for [#167](https://github.com/git-stunts/git-cas/issues/167). [Issue #169](https://github.com/git-stunts/git-cas/issues/169) tracks the release, and its [verification record](https://github.com/git-stunts/git-cas/issues/169#issuecomment-7308539667) holds the gate results and publication identity. Signed tag `v7.2.0`, npm gitHead and the successful [release workflow](https://github.com/git-stunts/git-cas/actions/runs/42249242979) identify source `3008b4a17603c44e0cf191e37f65db6f79409be3`. The [GitHub Release](https://github.com/git-stunts/git-cas/releases/tag/v7.2.0) is published.
|
|
4
4
|
|
|
5
5
|
## Change
|
|
6
6
|
|
|
@@ -13,3 +13,9 @@ Measured in a native repository after 400 prior records, one `reserve` wrote 68
|
|
|
13
13
|
The public API is unchanged. An index written by 7.1.0 places every record at full depth, which is a valid uncompressed trie: it reads, updates and lists without migration, and new keys branch off early.
|
|
14
14
|
|
|
15
15
|
git-cas 7.1.0 refuses an index written by this release as `RESERVATION_CORRUPT` on read, list and recovery. The failure is loud rather than silent, but every process that reads or writes a clone's reservation ledger must upgrade together, and downgrading after 7.2.0 has written a ledger is not supported.
|
|
16
|
+
|
|
17
|
+
## Evidence
|
|
18
|
+
|
|
19
|
+
All 14 release verifier steps pass at the tag on merged main, with the test suites in Docker: lint, 2,416 unit tests on Node and Bun (3 skips each) and 2,407 on Deno (12 skips), the three examples, public type compatibility, 353 integration tests on each runtime, the build stamp, npm pack and the JSR dry-run ([verification record](https://github.com/git-stunts/git-cas/issues/169#issuecomment-7308539667)). PR #168 also had an independent correctness review, whose probe of insertion-order independence, final-digit splits and paging across a later split passed.
|
|
20
|
+
|
|
21
|
+
git-warp installed the published artifact by its registry integrity and passed 333 custody, `Warp` and migration-golden tests ([git-stunts/git-warp#1083](https://github.com/git-stunts/git-warp/pull/1083)). A Docker probe there, which was not committed, measured 53 loose objects per retained `Warp` write across 100 writes, down from about 301 per write on 7.1.0 ([git-stunts/git-warp#1080](https://github.com/git-stunts/git-warp/issues/1080)).
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
# git-cas v8.0.0-rc.1: plumbing 4 release candidate
|
|
2
|
+
|
|
3
|
+
This release candidate moves git-cas onto `@git-stunts/plumbing` 4. It is a major release because applications that share a plumbing instance with git-cas must move to plumbing 4 with it, and because `GitPersistenceAdapter.readBlobStream()` now starts git lazily. Plumbing 4.0.0 is itself only a release candidate, so this version publishes to npm under the `next` dist-tag and leaves `latest` on 7.2.0. The plumbing upgrade merged in [PR #177](https://github.com/git-stunts/git-cas/pull/177). This document claims no published 8.0.0-rc.1 artifact. See [UPGRADING.md](../../UPGRADING.md#v720-to-v800-rc1) before adopting it.
|
|
4
|
+
|
|
5
|
+
## Breaking changes
|
|
6
|
+
|
|
7
|
+
git-cas depends on `@git-stunts/plumbing` `^4.0.0-rc.1` instead of `^3.3.3`. The range accepts plumbing 4.0.0 final and later 4.x releases without a new git-cas release. Plumbing 4 changes behavior for applications that also call it directly: a deadline kills git's whole process group and is not retried, more than 10 MiB of unread stdout fails with `UnreadOutputLimitError`, `GitSha` accepts SHA-256 ids, and plumbing forwards `SIGINT`, `SIGTERM` and `SIGHUP` to running git commands.
|
|
8
|
+
|
|
9
|
+
An application that passes its own plumbing instance to `ContentAddressableStore`, `GitPersistenceAdapter`, `GitRefAdapter` or `GitRepositoryInspectionAdapter` must use plumbing 4, installed as the same copy git-cas uses. git-cas recognises plumbing's errors by class. An instance from a separate 3.x copy throws errors of other classes, so a missing object reports plumbing's `GitObjectMissingError` instead of git-cas's `GIT_OBJECT_NOT_FOUND`, and git-cas's one-time recovery of a failed object session does not run.
|
|
10
|
+
|
|
11
|
+
`GitPersistenceAdapter.readBlobStream()` starts its one-shot `git cat-file blob` command when the caller first reads the returned stream, not when the stream is returned. That path serves a blob over 10 MiB, a blob the adapter's `cat-file` session cannot describe or read, and plumbing without object sessions. A stream that is never read starts no git process. A stream first read after the adapter closed fails with `RESOURCE_CLOSED`. A blob of 10 MiB or less that the session reads is still read into memory before the call returns, and its stream still yields after close.
|
|
12
|
+
|
|
13
|
+
## Other changes
|
|
14
|
+
|
|
15
|
+
The optional `@git-stunts/git-cas/files` entrypoint adds `materializeFile()`, which streams an async byte source to a private sibling file and renames it on success. `restoreFile()` and `materializeFile()` resolve destination symlinks one component at a time, refuse a dangling link that points outside the base directory, and accept names such as `..cache`. The default JSON façade decodes UTF-8 natively, 2.6x to 6x faster on Node 22 for manifest-shaped metadata. [CHANGELOG.md](../../CHANGELOG.md) lists each change.
|
|
16
|
+
|
|
17
|
+
## Stored data
|
|
18
|
+
|
|
19
|
+
Stored objects, refs and manifests keep their format. New manifests record `formatVersion: "8.0.0"`, the `MAJOR.MINOR.PATCH` core of the package version. The manifest schema has accepted only three numeric components since 6.0.0, so stamping `8.0.0-rc.1` would have made every new manifest fail validation, and 6.x and 7.x readers would refuse it. With the core version, 7.x readers accept manifests written by this candidate.
|
|
20
|
+
|
|
21
|
+
## Publication
|
|
22
|
+
|
|
23
|
+
The release workflow now chooses the npm dist-tag from the version. A version that contains a hyphen publishes with `npm publish --access public --tag next`, and its GitHub Release is marked as a prerelease. A plain version publishes under `latest`. The publish step refuses to run if the dist-tag and the version disagree.
|
|
24
|
+
|
|
25
|
+
This candidate does not contain the planned v8.0.0 Cleave workspace split ([#133](https://github.com/git-stunts/git-cas/issues/133)). Merge approval, a signed tag, a successful release workflow and registry-consumer evidence remain required before any claim of publication.
|
package/files.d.ts
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
export interface MaterializeFileOptions {
|
|
2
|
+
/** Stream completion must include any required source authentication. */
|
|
3
|
+
source: AsyncIterable<Uint8Array>;
|
|
4
|
+
/** Existing directory boundary for the caller-selected destination. */
|
|
5
|
+
baseDirectory: string;
|
|
6
|
+
/** Relative to baseDirectory, or an absolute path inside it. Parent must exist. */
|
|
7
|
+
outputPath: string;
|
|
8
|
+
/** Optional whole-plaintext SHA-256, checked before the rename. */
|
|
9
|
+
expectedSha256?: string;
|
|
10
|
+
/** Cancellation before the rename starts rejects with `signal.reason`; after that, publication completes. */
|
|
11
|
+
signal?: AbortSignal;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* Stream to a private sibling temporary file, then atomically replace the destination.
|
|
16
|
+
* Resolves if and only if the file was published. A destination symlink, even a dangling
|
|
17
|
+
* one, is followed: the in-base file it names is replaced or created and the link is kept.
|
|
18
|
+
* Does not fsync, create parents, manage retention or make a directory transaction.
|
|
19
|
+
*/
|
|
20
|
+
export function materializeFile(options: MaterializeFileOptions): Promise<{ bytesWritten: number }>;
|
package/files.js
ADDED
package/index.js
CHANGED
|
@@ -36,13 +36,14 @@ import createCryptoAdapter from './src/infrastructure/adapters/createCryptoAdapt
|
|
|
36
36
|
import { createGitPlumbing } from './src/infrastructure/createGitPlumbing.js';
|
|
37
37
|
import { storeFile, restoreFile } from './src/infrastructure/adapters/FileIOHelper.js';
|
|
38
38
|
import JsonCodec from './src/infrastructure/codecs/JsonCodec.js';
|
|
39
|
+
import RuntimeJsonCodec from './src/infrastructure/adapters/RuntimeJsonCodec.js';
|
|
39
40
|
import CborCodec from './src/infrastructure/codecs/CborCodec.js';
|
|
40
41
|
import SilentObserver from './src/infrastructure/adapters/SilentObserver.js';
|
|
41
42
|
import resolveChunker from './src/infrastructure/chunkers/resolveChunker.js';
|
|
42
43
|
import { CasError, createCasError, ErrorCodes } from './src/domain/errors/index.js';
|
|
43
44
|
import FixedChunker from './src/infrastructure/chunkers/FixedChunker.js';
|
|
44
45
|
import NodeCompressionAdapter from './src/infrastructure/adapters/NodeCompressionAdapter.js';
|
|
45
|
-
import { PACKAGE_VERSION } from './src/package-version.js';
|
|
46
|
+
import { MANIFEST_FORMAT_VERSION, PACKAGE_VERSION } from './src/package-version.js';
|
|
46
47
|
import parseApplicationHandle from './src/domain/value-objects/ApplicationHandle.js';
|
|
47
48
|
|
|
48
49
|
/** @typedef {import('./src/domain/value-objects/Manifest.js').default} Manifest */
|
|
@@ -326,7 +327,7 @@ export default class ContentAddressableStore {
|
|
|
326
327
|
this.service = new CasService({
|
|
327
328
|
persistence,
|
|
328
329
|
chunkSize,
|
|
329
|
-
codec: cfg.codec || new
|
|
330
|
+
codec: cfg.codec || new RuntimeJsonCodec(),
|
|
330
331
|
crypto,
|
|
331
332
|
observability: cfg.observability || new SilentObserver(),
|
|
332
333
|
merkleThreshold: cfg.merkleThreshold,
|
|
@@ -335,7 +336,7 @@ export default class ContentAddressableStore {
|
|
|
335
336
|
maxRestoreBufferSize: cfg.maxRestoreBufferSize,
|
|
336
337
|
maxBlobSize: cfg.maxBlobSize,
|
|
337
338
|
compressionAdapter: cfg.compressionAdapter || new NodeCompressionAdapter(),
|
|
338
|
-
formatVersion:
|
|
339
|
+
formatVersion: MANIFEST_FORMAT_VERSION,
|
|
339
340
|
});
|
|
340
341
|
|
|
341
342
|
const ref = new GitRefAdapter({
|
|
@@ -745,7 +746,7 @@ export default class ContentAddressableStore {
|
|
|
745
746
|
* @returns {ContentAddressableStore}
|
|
746
747
|
*/
|
|
747
748
|
static createJson({ plumbing, ...options }) {
|
|
748
|
-
return new ContentAddressableStore({ ...options, plumbing, codec: new
|
|
749
|
+
return new ContentAddressableStore({ ...options, plumbing, codec: new RuntimeJsonCodec() });
|
|
749
750
|
}
|
|
750
751
|
|
|
751
752
|
/**
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@git-stunts/git-cas",
|
|
3
|
-
"version": "
|
|
3
|
+
"version": "8.0.0-rc.1",
|
|
4
4
|
"description": "Content-addressed storage backed by Git's object database, with optional encryption and pluggable codecs",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "index.js",
|
|
@@ -9,12 +9,18 @@
|
|
|
9
9
|
},
|
|
10
10
|
"exports": {
|
|
11
11
|
".": "./index.js",
|
|
12
|
+
"./files": {
|
|
13
|
+
"types": "./files.d.ts",
|
|
14
|
+
"import": "./files.js"
|
|
15
|
+
},
|
|
12
16
|
"./service": "./src/domain/services/CasService.js",
|
|
13
17
|
"./schema": "./src/domain/schemas/ManifestSchema.js"
|
|
14
18
|
},
|
|
15
19
|
"files": [
|
|
16
20
|
"index.js",
|
|
17
21
|
"index.d.ts",
|
|
22
|
+
"files.js",
|
|
23
|
+
"files.d.ts",
|
|
18
24
|
"build-info.json",
|
|
19
25
|
"bin/",
|
|
20
26
|
"src/",
|
|
@@ -60,7 +66,8 @@
|
|
|
60
66
|
"docs/releases/v6.5.12.md",
|
|
61
67
|
"docs/releases/v7.0.0.md",
|
|
62
68
|
"docs/releases/v7.1.0.md",
|
|
63
|
-
"docs/releases/v7.2.0.md"
|
|
69
|
+
"docs/releases/v7.2.0.md",
|
|
70
|
+
"docs/releases/v8.0.0-rc.1.md"
|
|
64
71
|
],
|
|
65
72
|
"engines": {
|
|
66
73
|
"node": ">=22.0.0"
|
|
@@ -117,7 +124,7 @@
|
|
|
117
124
|
"@flyingrobots/bijou-tui": "^7.2.0",
|
|
118
125
|
"@flyingrobots/bijou-tui-app": "^7.2.0",
|
|
119
126
|
"@git-stunts/alfred": "^0.10.0",
|
|
120
|
-
"@git-stunts/plumbing": "^
|
|
127
|
+
"@git-stunts/plumbing": "^4.0.0-rc.1",
|
|
121
128
|
"@git-stunts/vault": "^1.0.1",
|
|
122
129
|
"cbor-x": "^1.6.0",
|
|
123
130
|
"commander": "14.0.3",
|
|
@@ -489,9 +489,7 @@ async function buildLegacyDeps(plumbing) {
|
|
|
489
489
|
const { default: NodeCompressionAdapter } = await import(
|
|
490
490
|
'../src/infrastructure/adapters/NodeCompressionAdapter.js'
|
|
491
491
|
);
|
|
492
|
-
const {
|
|
493
|
-
const require = createRequire(import.meta.url);
|
|
494
|
-
const { version } = require('../package.json');
|
|
492
|
+
const { MANIFEST_FORMAT_VERSION } = await import('../src/package-version.js');
|
|
495
493
|
|
|
496
494
|
return {
|
|
497
495
|
persistence: new GitPersistenceAdapter({ plumbing }),
|
|
@@ -500,7 +498,7 @@ async function buildLegacyDeps(plumbing) {
|
|
|
500
498
|
chunker: new FixedChunker({ chunkSize: 256 * 1024 }),
|
|
501
499
|
compressionAdapter: new NodeCompressionAdapter(),
|
|
502
500
|
chunkSize: 256 * 1024,
|
|
503
|
-
formatVersion:
|
|
501
|
+
formatVersion: MANIFEST_FORMAT_VERSION,
|
|
504
502
|
};
|
|
505
503
|
}
|
|
506
504
|
|
|
@@ -6,14 +6,13 @@
|
|
|
6
6
|
* @typedef {import('../../domain/value-objects/Manifest.js').EncryptionMeta} EncryptionMeta
|
|
7
7
|
*/
|
|
8
8
|
import { createReadStream, createWriteStream } from 'node:fs';
|
|
9
|
-
import { mkdtemp,
|
|
9
|
+
import { mkdtemp, rename, rm } from 'node:fs/promises';
|
|
10
10
|
import path from 'node:path';
|
|
11
11
|
import { Readable, Transform } from 'node:stream';
|
|
12
12
|
import { pipeline } from 'node:stream/promises';
|
|
13
13
|
import CasError from '../../domain/errors/CasError.js';
|
|
14
14
|
import { ErrorCodes } from '../../domain/errors/index.js';
|
|
15
|
-
|
|
16
|
-
const FILE_NOT_FOUND_CODE = 'ENOENT';
|
|
15
|
+
import { resolveSafeRestorePath } from './RestorePath.js';
|
|
17
16
|
|
|
18
17
|
/**
|
|
19
18
|
* Reads a file from disk and stores it in Git as chunked blobs via
|
|
@@ -117,53 +116,6 @@ export async function restoreFile(
|
|
|
117
116
|
return { bytesWritten };
|
|
118
117
|
}
|
|
119
118
|
|
|
120
|
-
/**
|
|
121
|
-
* @param {{ baseDirectory: string, outputPath: string }} options
|
|
122
|
-
* @returns {Promise<string>}
|
|
123
|
-
*/
|
|
124
|
-
async function resolveSafeRestorePath({ baseDirectory, outputPath }) {
|
|
125
|
-
const resolvedBase = path.resolve(baseDirectory);
|
|
126
|
-
const resolvedPath = path.resolve(resolvedBase, outputPath);
|
|
127
|
-
const canonicalBase = await realpath(resolvedBase);
|
|
128
|
-
const canonicalPath = await canonicalizeTargetPath(resolvedPath);
|
|
129
|
-
|
|
130
|
-
if (!isInsideBaseDirectory(canonicalPath, canonicalBase)) {
|
|
131
|
-
throw new CasError(
|
|
132
|
-
`Restoration path "${outputPath}" escapes base directory "${baseDirectory}"`,
|
|
133
|
-
ErrorCodes.SECURITY_BOUNDARY_VIOLATION,
|
|
134
|
-
{ outputPath, baseDirectory }
|
|
135
|
-
);
|
|
136
|
-
}
|
|
137
|
-
return canonicalPath;
|
|
138
|
-
}
|
|
139
|
-
|
|
140
|
-
/**
|
|
141
|
-
* Resolves symlinks in the existing path prefix while allowing the leaf path
|
|
142
|
-
* not to exist yet.
|
|
143
|
-
*
|
|
144
|
-
* @param {string} targetPath
|
|
145
|
-
* @returns {Promise<string>}
|
|
146
|
-
*/
|
|
147
|
-
async function canonicalizeTargetPath(targetPath) {
|
|
148
|
-
const missingParts = [];
|
|
149
|
-
let current = targetPath;
|
|
150
|
-
while (true) {
|
|
151
|
-
try {
|
|
152
|
-
return path.join(await realpath(current), ...missingParts.reverse());
|
|
153
|
-
} catch (err) {
|
|
154
|
-
if (!isNotFoundError(err)) {
|
|
155
|
-
throw err;
|
|
156
|
-
}
|
|
157
|
-
const parent = path.dirname(current);
|
|
158
|
-
if (parent === current) {
|
|
159
|
-
throw err;
|
|
160
|
-
}
|
|
161
|
-
missingParts.push(path.basename(current));
|
|
162
|
-
current = parent;
|
|
163
|
-
}
|
|
164
|
-
}
|
|
165
|
-
}
|
|
166
|
-
|
|
167
119
|
/**
|
|
168
120
|
* Restores buffered modes through a temp-file path so whole-object auth can
|
|
169
121
|
* stay intact without publishing partial output.
|
|
@@ -203,24 +155,6 @@ async function restoreBufferedFile(service, { manifest, outputPath, source, encr
|
|
|
203
155
|
}
|
|
204
156
|
}
|
|
205
157
|
|
|
206
|
-
/**
|
|
207
|
-
* @param {string} resolvedPath
|
|
208
|
-
* @param {string} resolvedBase
|
|
209
|
-
* @returns {boolean}
|
|
210
|
-
*/
|
|
211
|
-
function isInsideBaseDirectory(resolvedPath, resolvedBase) {
|
|
212
|
-
const relativePath = path.relative(resolvedBase, resolvedPath);
|
|
213
|
-
return relativePath === '' || (!relativePath.startsWith('..') && !path.isAbsolute(relativePath));
|
|
214
|
-
}
|
|
215
|
-
|
|
216
|
-
/**
|
|
217
|
-
* @param {unknown} err
|
|
218
|
-
* @returns {boolean}
|
|
219
|
-
*/
|
|
220
|
-
function isNotFoundError(err) {
|
|
221
|
-
return Boolean(err && typeof err === 'object' && err.code === FILE_NOT_FOUND_CODE);
|
|
222
|
-
}
|
|
223
|
-
|
|
224
158
|
function createByteCounter(onChunk) {
|
|
225
159
|
return new Transform({
|
|
226
160
|
transform(chunk, _encoding, cb) {
|
|
@@ -289,22 +289,22 @@ export default class GitPersistenceAdapter extends GitPersistencePort {
|
|
|
289
289
|
async readBlobStream(oid) {
|
|
290
290
|
return await this.#runOperation(async () => {
|
|
291
291
|
if (!this.#sessions.supports('catFile')) {
|
|
292
|
-
return
|
|
292
|
+
return this.#openBlobStream(oid);
|
|
293
293
|
}
|
|
294
294
|
let info;
|
|
295
295
|
try {
|
|
296
296
|
info = await this.#readObjectInfo(oid);
|
|
297
297
|
} catch {
|
|
298
|
-
return
|
|
298
|
+
return this.#openBlobStream(oid);
|
|
299
299
|
}
|
|
300
300
|
if (info.type !== 'blob' || info.size > MAX_SESSION_STREAM_BLOB_BYTES) {
|
|
301
|
-
return
|
|
301
|
+
return this.#openBlobStream(oid);
|
|
302
302
|
}
|
|
303
303
|
try {
|
|
304
304
|
const content = await this.#readBlobFromSession(oid, MAX_SESSION_STREAM_BLOB_BYTES);
|
|
305
305
|
return GitPersistenceAdapter.#singleBufferStream(content);
|
|
306
306
|
} catch {
|
|
307
|
-
return
|
|
307
|
+
return this.#openBlobStream(oid);
|
|
308
308
|
}
|
|
309
309
|
});
|
|
310
310
|
}
|
|
@@ -327,8 +327,18 @@ export default class GitPersistenceAdapter extends GitPersistencePort {
|
|
|
327
327
|
return GitPersistenceAdapter.#toBuffer(object.content);
|
|
328
328
|
}
|
|
329
329
|
|
|
330
|
-
|
|
331
|
-
|
|
330
|
+
/**
|
|
331
|
+
* Returns a blob stream whose `git cat-file blob` starts on the first read.
|
|
332
|
+
*
|
|
333
|
+
* Plumbing drains a command's stdout while nobody reads it and fails the
|
|
334
|
+
* stream once more than 10 MiB is unread, so starting the command before
|
|
335
|
+
* the caller reads would fail a large blob read by a caller that waits.
|
|
336
|
+
*
|
|
337
|
+
* @param {string} oid
|
|
338
|
+
* @returns {AsyncIterable<Buffer>}
|
|
339
|
+
*/
|
|
340
|
+
async *#openBlobStream(oid) {
|
|
341
|
+
yield* await this.#runOperation(() => this.#openBufferStream(['cat-file', 'blob', oid]));
|
|
332
342
|
}
|
|
333
343
|
|
|
334
344
|
/**
|
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
import { lstat, readlink, realpath } from 'node:fs/promises';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import CasError from '../../domain/errors/CasError.js';
|
|
4
|
+
import { ErrorCodes } from '../../domain/errors/index.js';
|
|
5
|
+
|
|
6
|
+
const FILE_NOT_FOUND_CODE = 'ENOENT';
|
|
7
|
+
/** Matches the usual kernel limit on symlinks followed while resolving one path. */
|
|
8
|
+
const MAX_SYMLINK_HOPS = 40;
|
|
9
|
+
/** Marks a path component that does not exist. */
|
|
10
|
+
const MISSING = Symbol('missing');
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* @param {{ baseDirectory: string, outputPath: string }} options
|
|
14
|
+
* @returns {Promise<string>}
|
|
15
|
+
*/
|
|
16
|
+
export async function resolveSafeRestorePath({ baseDirectory, outputPath }) {
|
|
17
|
+
const resolvedBase = path.resolve(baseDirectory);
|
|
18
|
+
const resolvedPath = path.resolve(resolvedBase, outputPath);
|
|
19
|
+
const canonicalBase = await realpath(resolvedBase);
|
|
20
|
+
const canonicalPath = await canonicalizeTargetPath(resolvedPath);
|
|
21
|
+
|
|
22
|
+
if (!isInsideBaseDirectory(canonicalPath, canonicalBase)) {
|
|
23
|
+
throw new CasError(
|
|
24
|
+
`Restoration path "${outputPath}" escapes base directory "${baseDirectory}"`,
|
|
25
|
+
ErrorCodes.SECURITY_BOUNDARY_VIOLATION,
|
|
26
|
+
{ outputPath, baseDirectory }
|
|
27
|
+
);
|
|
28
|
+
}
|
|
29
|
+
return canonicalPath;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* Resolves a target path one component at a time, as the kernel does: every
|
|
34
|
+
* symlink, including a dangling one, is followed before any later `..` is
|
|
35
|
+
* applied, and `..` steps to the physical parent. The leaf, and any missing
|
|
36
|
+
* components after it, need not exist yet. A dangling link resolves to the
|
|
37
|
+
* path it names, so that path is what the boundary check sees.
|
|
38
|
+
*
|
|
39
|
+
* @param {string} targetPath - Absolute, lexically normalised path.
|
|
40
|
+
* @returns {Promise<string>}
|
|
41
|
+
*/
|
|
42
|
+
async function canonicalizeTargetPath(targetPath) {
|
|
43
|
+
const walk = { resolved: path.parse(targetPath).root, isDirectory: true, pending: splitPath(targetPath), hops: 0 };
|
|
44
|
+
while (walk.pending.length > 0) {
|
|
45
|
+
const part = walk.pending.shift();
|
|
46
|
+
// Any further component, including `.` and `..`, needs the path so far to be a directory.
|
|
47
|
+
if (!walk.isDirectory) { throw fsError('ENOTDIR', `Not a directory: "${walk.resolved}"`); }
|
|
48
|
+
if (part === '..') {
|
|
49
|
+
walk.resolved = path.dirname(walk.resolved);
|
|
50
|
+
} else if (part !== '.') {
|
|
51
|
+
const next = path.join(walk.resolved, part);
|
|
52
|
+
const entry = await inspect(next);
|
|
53
|
+
if (entry === MISSING) { return joinMissing(next, walk.pending); }
|
|
54
|
+
if (typeof entry === 'string') {
|
|
55
|
+
followLink(walk, entry, targetPath);
|
|
56
|
+
} else {
|
|
57
|
+
// `next` is not a symlink and its parent is canonical, so realpath() only
|
|
58
|
+
// returns the filesystem's own spelling, which case-insensitive volumes need.
|
|
59
|
+
walk.resolved = await realpath(next);
|
|
60
|
+
walk.isDirectory = entry.isDirectory();
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
return walk.resolved;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* @param {string} candidate
|
|
69
|
+
* @returns {Promise<string | import('node:fs').Stats | typeof MISSING>} Link text for a
|
|
70
|
+
* symlink, the stats of anything else, or MISSING.
|
|
71
|
+
*/
|
|
72
|
+
async function inspect(candidate) {
|
|
73
|
+
let stats;
|
|
74
|
+
try {
|
|
75
|
+
stats = await lstat(candidate);
|
|
76
|
+
} catch (err) {
|
|
77
|
+
if (isNotFoundError(err)) { return MISSING; }
|
|
78
|
+
throw err;
|
|
79
|
+
}
|
|
80
|
+
return stats.isSymbolicLink() ? readlink(candidate) : stats;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/** Queues the link's own components ahead of the rest, from the root if it is absolute. */
|
|
84
|
+
function followLink(walk, linkText, targetPath) {
|
|
85
|
+
walk.hops += 1;
|
|
86
|
+
if (walk.hops > MAX_SYMLINK_HOPS) {
|
|
87
|
+
throw fsError('ELOOP', `Too many symbolic links resolving "${targetPath}"`);
|
|
88
|
+
}
|
|
89
|
+
if (path.isAbsolute(linkText)) { walk.resolved = path.parse(path.resolve(linkText)).root; }
|
|
90
|
+
// A trailing separator requires a directory, as `/.` does.
|
|
91
|
+
const endsWithSeparator = linkText.endsWith('/') || (path.sep === '\\' && linkText.endsWith('\\'));
|
|
92
|
+
const trailing = endsWithSeparator && splitPath(linkText).length > 0 ? ['.'] : [];
|
|
93
|
+
walk.pending.unshift(...splitPath(linkText), ...trailing);
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/**
|
|
97
|
+
* Past a missing component the kernel cannot look further, so the remaining
|
|
98
|
+
* names are appended as they are. A `.` or `..` there would need a missing directory.
|
|
99
|
+
*/
|
|
100
|
+
function joinMissing(missing, rest) {
|
|
101
|
+
if (rest.includes('..') || rest.includes('.')) {
|
|
102
|
+
throw fsError(FILE_NOT_FOUND_CODE, `No such directory: "${missing}"`);
|
|
103
|
+
}
|
|
104
|
+
return path.join(missing, ...rest);
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/**
|
|
108
|
+
* Splits without normalising: link text such as `dir/../x` must keep its `..`
|
|
109
|
+
* until `dir` has been followed.
|
|
110
|
+
*
|
|
111
|
+
* @param {string} value
|
|
112
|
+
*/
|
|
113
|
+
function splitPath(value) {
|
|
114
|
+
const separators = path.sep === '\\' ? /[\\/]/u : /\//u;
|
|
115
|
+
return value.slice(path.parse(value).root.length).split(separators).filter((part) => part.length > 0);
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/**
|
|
119
|
+
* @param {string} resolvedPath
|
|
120
|
+
* @param {string} resolvedBase
|
|
121
|
+
* @returns {boolean}
|
|
122
|
+
*/
|
|
123
|
+
function isInsideBaseDirectory(resolvedPath, resolvedBase) {
|
|
124
|
+
const relativePath = path.relative(resolvedBase, resolvedPath);
|
|
125
|
+
const escapes = relativePath === '..' || relativePath.startsWith(`..${path.sep}`);
|
|
126
|
+
return !escapes && !path.isAbsolute(relativePath);
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
/**
|
|
130
|
+
* @param {unknown} err
|
|
131
|
+
* @returns {boolean}
|
|
132
|
+
*/
|
|
133
|
+
function isNotFoundError(err) {
|
|
134
|
+
return Boolean(err && typeof err === 'object' && err.code === FILE_NOT_FOUND_CODE);
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
/**
|
|
139
|
+
* @param {string} code - The errno-style code the kernel would report.
|
|
140
|
+
* @param {string} message
|
|
141
|
+
*/
|
|
142
|
+
function fsError(code, message) {
|
|
143
|
+
return Object.assign(new Error(message), { code });
|
|
144
|
+
}
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import JsonCodec from '../codecs/JsonCodec.js';
|
|
2
|
+
|
|
3
|
+
const decoder = createFatalDecoder();
|
|
4
|
+
|
|
5
|
+
/** Builds without ICU reject `fatal`; the portable decoder then handles all input. */
|
|
6
|
+
function createFatalDecoder() {
|
|
7
|
+
if (typeof globalThis.TextDecoder !== 'function') { return null; }
|
|
8
|
+
try {
|
|
9
|
+
return new globalThis.TextDecoder('utf-8', { fatal: true, ignoreBOM: true });
|
|
10
|
+
} catch {
|
|
11
|
+
return null;
|
|
12
|
+
}
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
/** Runtime text conversion over the unchanged portable JSON codec contract. */
|
|
16
|
+
export default class RuntimeJsonCodec extends JsonCodec {
|
|
17
|
+
decode(buffer) {
|
|
18
|
+
if (decoder && buffer instanceof Uint8Array) {
|
|
19
|
+
let text;
|
|
20
|
+
try {
|
|
21
|
+
text = decoder.decode(buffer);
|
|
22
|
+
} catch {
|
|
23
|
+
// Preserve legacy consumption of malformed UTF-8.
|
|
24
|
+
return super.decode(buffer);
|
|
25
|
+
}
|
|
26
|
+
return JSON.parse(text);
|
|
27
|
+
}
|
|
28
|
+
return super.decode(buffer);
|
|
29
|
+
}
|
|
30
|
+
}
|
|
@@ -0,0 +1,172 @@
|
|
|
1
|
+
import { createWriteStream } from 'node:fs';
|
|
2
|
+
import { mkdtemp, realpath, rename, rm } from 'node:fs/promises';
|
|
3
|
+
import { createHash } from 'node:crypto';
|
|
4
|
+
import path from 'node:path';
|
|
5
|
+
import { types } from 'node:util';
|
|
6
|
+
import { Readable, Transform } from 'node:stream';
|
|
7
|
+
import { pipeline } from 'node:stream/promises';
|
|
8
|
+
import { setImmediate as nextMacrotask } from 'node:timers/promises';
|
|
9
|
+
import CasError from '../../domain/errors/CasError.js';
|
|
10
|
+
import { ErrorCodes } from '../../domain/errors/index.js';
|
|
11
|
+
import { resolveSafeRestorePath } from './RestorePath.js';
|
|
12
|
+
|
|
13
|
+
/** @param {import('../../../files.js').MaterializeFileOptions} options */
|
|
14
|
+
export async function materializeFile(options = {}) {
|
|
15
|
+
const { source, baseDirectory, outputPath, expectedSha256, signal } = validateOptions(options);
|
|
16
|
+
signal?.throwIfAborted();
|
|
17
|
+
const destination = await resolveSafeRestorePath({ baseDirectory, outputPath });
|
|
18
|
+
if (destination === await realpath(path.resolve(baseDirectory))) {
|
|
19
|
+
throw new CasError(`Materialization path "${outputPath}" names base directory "${baseDirectory}"`,
|
|
20
|
+
ErrorCodes.SECURITY_BOUNDARY_VIOLATION, { outputPath, baseDirectory });
|
|
21
|
+
}
|
|
22
|
+
const temporary = await mkdtemp(path.join(path.dirname(destination), '.git-cas-materialize-'));
|
|
23
|
+
const staged = path.join(temporary, 'content');
|
|
24
|
+
const hash = expectedSha256 ? createHash('sha256') : null;
|
|
25
|
+
let bytesWritten = 0;
|
|
26
|
+
const counter = new Transform({
|
|
27
|
+
transform(chunk, _encoding, done) {
|
|
28
|
+
bytesWritten += chunk.length;
|
|
29
|
+
hash?.update(chunk);
|
|
30
|
+
done(null, chunk);
|
|
31
|
+
},
|
|
32
|
+
});
|
|
33
|
+
try {
|
|
34
|
+
await writeStaged({ source, staged, counter, signal });
|
|
35
|
+
if (hash && hash.digest('hex') !== expectedSha256.toLowerCase()) {
|
|
36
|
+
throw new CasError('Materialized file SHA-256 does not match expectedSha256', ErrorCodes.INTEGRITY_ERROR);
|
|
37
|
+
}
|
|
38
|
+
signal?.throwIfAborted();
|
|
39
|
+
await rename(staged, destination);
|
|
40
|
+
} catch (error) {
|
|
41
|
+
// The original failure is the diagnosis; a leftover private directory is documented.
|
|
42
|
+
await rm(temporary, { recursive: true, force: true }).catch(() => {});
|
|
43
|
+
throw error;
|
|
44
|
+
}
|
|
45
|
+
// Rename is the publication point: resolve if and only if the file was published.
|
|
46
|
+
// An empty private directory left by a failed cleanup is documented reclaimable residue.
|
|
47
|
+
await rm(temporary, { recursive: true, force: true }).catch(() => {});
|
|
48
|
+
return { bytesWritten };
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* Pulls stop when the caller aborts or the file fails, so neither has to wait
|
|
53
|
+
* for a blocked producer before the pipeline can settle.
|
|
54
|
+
*/
|
|
55
|
+
async function writeStaged({ source, staged, counter, signal }) {
|
|
56
|
+
const pulls = new globalThis.AbortController();
|
|
57
|
+
const forward = () => pulls.abort(signal.reason);
|
|
58
|
+
signal?.addEventListener('abort', forward, { once: true });
|
|
59
|
+
const file = createWriteStream(staged, { flags: 'wx', mode: 0o600 });
|
|
60
|
+
file.once('error', (error) => pulls.abort(error));
|
|
61
|
+
let sourceFailure = null;
|
|
62
|
+
const chunks = byteChunks(source, pulls.signal, (error) => { sourceFailure = { error }; });
|
|
63
|
+
try {
|
|
64
|
+
await pipeline(Readable.from(chunks, { objectMode: false }), counter, file, { signal });
|
|
65
|
+
} catch (error) {
|
|
66
|
+
// Cancellation always rejects with the caller's reason, not the pipeline's own AbortError.
|
|
67
|
+
if (signal?.aborted) { throw signal.reason; }
|
|
68
|
+
// Streams report a falsy error as a premature close; keep the value the source threw.
|
|
69
|
+
throw sourceFailure ? sourceFailure.error : error;
|
|
70
|
+
} finally {
|
|
71
|
+
signal?.removeEventListener('abort', forward);
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/**
|
|
76
|
+
* Reads each option once and returns that snapshot, so a getter cannot pass validation
|
|
77
|
+
* and then change. The source is bound to the iterator method read here, as for await does.
|
|
78
|
+
*/
|
|
79
|
+
function validateOptions(options) {
|
|
80
|
+
const { source, baseDirectory, outputPath, expectedSha256, signal } = options ?? {};
|
|
81
|
+
const iteratorMethod = source?.[Symbol.asyncIterator];
|
|
82
|
+
if (!options || !isPath(baseDirectory) || !isPath(outputPath) || typeof iteratorMethod !== 'function') {
|
|
83
|
+
throw new CasError('source, baseDirectory and outputPath are required', ErrorCodes.INVALID_OPTIONS);
|
|
84
|
+
}
|
|
85
|
+
validateSignal(signal);
|
|
86
|
+
validateDigest(expectedSha256);
|
|
87
|
+
return {
|
|
88
|
+
source: { [Symbol.asyncIterator]: () => Reflect.apply(iteratorMethod, source, []) },
|
|
89
|
+
baseDirectory, outputPath, expectedSha256, signal,
|
|
90
|
+
};
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
const readAborted = Object.getOwnPropertyDescriptor(globalThis.AbortSignal.prototype, 'aborted').get;
|
|
94
|
+
|
|
95
|
+
/** A brand check: the platform getter rejects objects that only inherit from AbortSignal. */
|
|
96
|
+
function validateSignal(signal) {
|
|
97
|
+
if (signal === undefined) { return; }
|
|
98
|
+
try {
|
|
99
|
+
readAborted.call(signal);
|
|
100
|
+
} catch {
|
|
101
|
+
throw new CasError('signal must be an AbortSignal', ErrorCodes.INVALID_OPTIONS);
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/**
|
|
106
|
+
* Rejects anything but byte chunks, so a misbehaving source cannot publish text.
|
|
107
|
+
* Each pull races the abort signal: cancellation settles even while the producer
|
|
108
|
+
* is blocked. The source is then asked to return without waiting for it.
|
|
109
|
+
*/
|
|
110
|
+
async function* byteChunks(source, signal, onSourceFailure) {
|
|
111
|
+
let iterator;
|
|
112
|
+
let finished = false;
|
|
113
|
+
try {
|
|
114
|
+
iterator = source[Symbol.asyncIterator]();
|
|
115
|
+
// Captured once, as for await does, so the iterator may replace its own next.
|
|
116
|
+
const next = iterator.next;
|
|
117
|
+
const pull = () => Reflect.apply(next, iterator, []);
|
|
118
|
+
while (true) {
|
|
119
|
+
const step = await nextChunk(pull, signal);
|
|
120
|
+
if (step.done) { finished = true; return; }
|
|
121
|
+
// Read once, so a getter cannot pass validation and then yield something else.
|
|
122
|
+
const chunk = step.value;
|
|
123
|
+
// Realm-independent: a Uint8Array from another context is still bytes.
|
|
124
|
+
if (!types.isUint8Array(chunk)) {
|
|
125
|
+
throw new CasError('source must yield Uint8Array chunks', ErrorCodes.INVALID_OPTIONS);
|
|
126
|
+
}
|
|
127
|
+
// Copied before the next pull: streams queue references, and a producer may reuse its buffer.
|
|
128
|
+
// The typed-array constructor reads the bytes directly; Buffer.from(chunk) would honour valueOf().
|
|
129
|
+
const bytes = Buffer.from(new Uint8Array(chunk).buffer);
|
|
130
|
+
// Empty chunks never fill a stream buffer, so yield to the event loop for cancellation and I/O.
|
|
131
|
+
if (bytes.length === 0) { await nextMacrotask(); }
|
|
132
|
+
yield bytes;
|
|
133
|
+
}
|
|
134
|
+
} catch (error) {
|
|
135
|
+
if (!signal.aborted) { onSourceFailure(error); }
|
|
136
|
+
throw error;
|
|
137
|
+
} finally {
|
|
138
|
+
// Deferred, so a return() that throws synchronously cannot replace the pull's error.
|
|
139
|
+
if (!finished) { Promise.resolve().then(() => iterator?.return?.()).catch(() => {}); }
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
/** One abort race per pull, so completed pulls leave no reactions on a long-lived promise. */
|
|
144
|
+
async function nextChunk(pull, signal) {
|
|
145
|
+
const abort = abortRejection(signal);
|
|
146
|
+
try {
|
|
147
|
+
return await (abort ? Promise.race([pull(), abort.promise]) : pull());
|
|
148
|
+
} finally {
|
|
149
|
+
abort?.dispose();
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
/** A rejection that follows `signal`, marked handled so a late abort is not reported. */
|
|
154
|
+
function abortRejection(signal) {
|
|
155
|
+
if (!signal) { return null; }
|
|
156
|
+
let onAbort;
|
|
157
|
+
const promise = new Promise((_resolve, reject) => {
|
|
158
|
+
onAbort = () => reject(signal.reason);
|
|
159
|
+
if (signal.aborted) { onAbort(); } else { signal.addEventListener('abort', onAbort, { once: true }); }
|
|
160
|
+
});
|
|
161
|
+
promise.catch(() => {});
|
|
162
|
+
return { promise, dispose: () => signal.removeEventListener('abort', onAbort) };
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
function isPath(value) { return typeof value === 'string' && value.length > 0; }
|
|
166
|
+
|
|
167
|
+
function validateDigest(expectedSha256) {
|
|
168
|
+
if (expectedSha256 !== undefined
|
|
169
|
+
&& (typeof expectedSha256 !== 'string' || !/^[a-f0-9]{64}$/iu.test(expectedSha256))) {
|
|
170
|
+
throw new CasError('expectedSha256 must be a 64-digit hexadecimal digest', ErrorCodes.INVALID_OPTIONS);
|
|
171
|
+
}
|
|
172
|
+
}
|
package/src/package-version.js
CHANGED
|
@@ -1 +1,16 @@
|
|
|
1
|
-
export const PACKAGE_VERSION = '
|
|
1
|
+
export const PACKAGE_VERSION = '8.0.0-rc.1';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Returns the `MAJOR.MINOR.PATCH` core of a package version. Manifests record
|
|
5
|
+
* this as `formatVersion`, whose schema (and every earlier reader) accepts
|
|
6
|
+
* only three numeric components, so a prerelease such as `8.0.0-rc.1` stamps
|
|
7
|
+
* `8.0.0`.
|
|
8
|
+
*
|
|
9
|
+
* @param {string} version
|
|
10
|
+
* @returns {string}
|
|
11
|
+
*/
|
|
12
|
+
export function manifestFormatVersion(version) {
|
|
13
|
+
return version.replace(/[-+].*$/u, '');
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
export const MANIFEST_FORMAT_VERSION = manifestFormatVersion(PACKAGE_VERSION);
|