feat(files): @shade/files 0.3.0 — E2EE filesystem RPC primitive
Some checks failed
Test / test (push) Has been cancelled
Some checks failed
Test / test (push) Has been cancelled
M-Files-1..6 land the full files-RPC layer + everything 0.3.0 needs to
ship. Apps keep their own UI; this layer ships the typed RPC, the
streams bridge for content I/O, and production hooks (rate limit,
retention, fingerprint gate, metrics).
@shade/files (NEW)
- Standard ops: list/stat/mkdir/delete/move/read/write/getThumbnail with
Zod-validated wire schemas + clean user-handler types.
- Custom ops: typed via TypeScript declaration merging on CustomOpsMap
+ per-op Zod schemas; client.custom('app.foo', {...}) is fully typed.
- Content I/O: inline (≤ 256 KiB plaintext) base64-in-RPC; streams
(> 256 KiB) ride @shade/transfer via userMetadata.shadeFilesWriteId
/ shadeFilesReadStreamId correlation. Server-side TransformStream
bridges accept inbound transfers immediately (engine rejects chunks
that arrive before accept) and park the readable for the matching
RPC.
- Directory ops: walk(path, opts) async-iterable depth-first walker;
uploadDirectory()/downloadDirectory() with bounded concurrency pool
(default 4, cap 16), aggregated progress, abort.
- Production hooks (callback-based, vendor-neutral): rate-limit (op +
byte), idempotency cache (LRU + TTL + in-flight de-dupe), path
policy (traversal + percent-decode hardening), fingerprint gate
(required/optional/reject), pluggable Ed25519 sig verification with
±5 min replay window, onMetric sink (standard names).
- React hooks (subpath @shade/files/react): ShadeFilesProvider,
useShadeFiles, useFileList, useFileTransfer/Upload/Download.
- Shade.files.serve(handler) + Shade.files.client(peer) high-level
entrypoint in @shade/sdk; lazy + memoized; one handler per Shade.
Wire format bump
- @shade/proto wire VERSION 0x01 → 0x02. Length prefixes changed from
u16 to u32. The previous u16 silently truncated payloads above
64 KiB — a hard correctness ceiling that blocked inline file ops
up to 256 KiB. Wire-incompatible with 0.2.x peers; new sessions
only. Cross-platform Kotlin port (android/shade-android) updated to
match; test-vectors/wire-format.json regenerated.
Concurrency safety
- ShadeSessionManager.encrypt/.decrypt now run under per-peer mutex.
Concurrent decryptions of the same peer raced ratchet state
(manifested as sporadic "Failed to decrypt — wrong key or tampered
data" under load — surfaced once concurrent uploadDirectory pumped
many writes in flight). Encrypt was already serialized via
Shade.send's encryptChains; decrypt is now serialized at the
manager layer too.
@shade/streams extension
- StreamMetadata.userMetadata?: Record<string, string> for
application-level key/value pairs that round-trip verbatim through
stream-init plaintext. Used by @shade/files for write/read
correlation; available to any consumer.
@shade/sdk extension
- Shade.files getter (lazy + memoized).
- BackgroundHooks.onPruneFiles + periodic timer (default 5 min) +
BackgroundTasks.setHook(name, fn) for runtime hook registration.
Bundles in-flight 0.2.0 work
- packages/shade-streams/, packages/shade-transfer/, related
shade-sdk streams-bridge + shade-widgets transfer hooks were
uncommitted prior to this session. Including them keeps the
workspace consistent at 0.3.0 since @shade/files depends on them.
Tests
- 74 new tests in @shade/files (572 → 646 workspace pass; 0 fail;
3× stable). Coverage spans unit (inline-threshold + concurrency),
integration (read-write inline + streams up to 1 MiB, walk +
upload/download directory, custom-op, metrics, SDK namespace
end-to-end), and security (tampered-envelope sig verification,
replay window, fingerprint gate, rate-limit + quota).
Release artifacts
- All packages bumped to 0.3.0 via scripts/bump-version.ts.
- scripts/publish-all.ts PACKAGES updated with shade-files in
topological order (after shade-transfer, before shade-sdk).
- bun run publish:dry clean (14 packed, 0 failed).
- examples/08-files-browser/ — three-process CLI demo (prekey + Bob
server + Alice CLI) covering list/stat/mkdir/delete/upload/download.
- docs/files.md — full API + design doc.
- CHANGELOG.md 0.3.0 entry.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
218
packages/shade-files/src/client/inline-threshold.ts
Normal file
218
packages/shade-files/src/client/inline-threshold.ts
Normal file
@@ -0,0 +1,218 @@
|
||||
/**
|
||||
* Decide whether a write should travel inline (base64 inside the RPC
|
||||
* envelope) or via a dedicated `@shade/transfer` stream.
|
||||
*
|
||||
* Threshold: 256 KiB plaintext. Anything strictly above goes through the
|
||||
* stream path; anything ≤ goes inline.
|
||||
*
|
||||
* For known-size inputs (`Uint8Array`, `Blob`, `File`) the decision is
|
||||
* cheap: compare `byteLength`/`size` against the threshold.
|
||||
*
|
||||
* For `ReadableStream` we cannot know the size up front. We pull chunks
|
||||
* into a temporary buffer until we either:
|
||||
* - hit EOF before the threshold → inline (we have all the bytes)
|
||||
* - cross the threshold → streams (the buffered prefix + the rest of the
|
||||
* stream are returned via a fresh `ReadableStream` so the caller can
|
||||
* feed it to `shade.upload`).
|
||||
*/
|
||||
/** Plaintext size at which inline transitions to streams. */
|
||||
export const INLINE_THRESHOLD = 256 * 1024;
|
||||
|
||||
export type InlineDecision =
|
||||
| {
|
||||
kind: 'inline';
|
||||
bytes: Uint8Array;
|
||||
contentType?: string;
|
||||
}
|
||||
| {
|
||||
kind: 'streams';
|
||||
stream: ReadableStream<Uint8Array>;
|
||||
/** Plaintext size when known (Blob/File). undefined for raw streams. */
|
||||
size?: number;
|
||||
contentType?: string;
|
||||
};
|
||||
|
||||
/**
|
||||
* Public input shape for `FileClient.write`. Runtime discriminator helper.
|
||||
*/
|
||||
export type WriteSource =
|
||||
| Uint8Array
|
||||
| Blob
|
||||
| File
|
||||
| ReadableStream<Uint8Array>
|
||||
| { stream: ReadableStream<Uint8Array>; size: number; contentType?: string };
|
||||
|
||||
export async function decideInline(input: WriteSource): Promise<InlineDecision> {
|
||||
// 1. Uint8Array — direct size check
|
||||
if (input instanceof Uint8Array) {
|
||||
if (input.byteLength <= INLINE_THRESHOLD) {
|
||||
return { kind: 'inline', bytes: input };
|
||||
}
|
||||
return {
|
||||
kind: 'streams',
|
||||
stream: uint8ArrayToStream(input),
|
||||
size: input.byteLength,
|
||||
};
|
||||
}
|
||||
|
||||
// 2. Blob / File — known size (Blob.type is a string; File extends Blob)
|
||||
if (typeof Blob !== 'undefined' && input instanceof Blob) {
|
||||
const blob: Blob = input;
|
||||
const contentType = blob.type === '' ? undefined : blob.type;
|
||||
if (blob.size <= INLINE_THRESHOLD) {
|
||||
const bytes = new Uint8Array(await blob.arrayBuffer());
|
||||
return contentType !== undefined
|
||||
? { kind: 'inline', bytes, contentType }
|
||||
: { kind: 'inline', bytes };
|
||||
}
|
||||
return contentType !== undefined
|
||||
? { kind: 'streams', stream: blob.stream(), size: blob.size, contentType }
|
||||
: { kind: 'streams', stream: blob.stream(), size: blob.size };
|
||||
}
|
||||
|
||||
// 3. Pre-wrapped { stream, size } — trust caller's declared size
|
||||
if (
|
||||
typeof input === 'object' &&
|
||||
input !== null &&
|
||||
'stream' in input &&
|
||||
'size' in input &&
|
||||
(input as { stream: unknown }).stream instanceof ReadableStream
|
||||
) {
|
||||
const wrapped = input as { stream: ReadableStream<Uint8Array>; size: number; contentType?: string };
|
||||
if (wrapped.size <= INLINE_THRESHOLD) {
|
||||
const bytes = await drainStream(wrapped.stream, wrapped.size);
|
||||
const contentType = wrapped.contentType;
|
||||
return contentType !== undefined
|
||||
? { kind: 'inline', bytes, contentType }
|
||||
: { kind: 'inline', bytes };
|
||||
}
|
||||
const contentType = wrapped.contentType;
|
||||
return contentType !== undefined
|
||||
? { kind: 'streams', stream: wrapped.stream, size: wrapped.size, contentType }
|
||||
: { kind: 'streams', stream: wrapped.stream, size: wrapped.size };
|
||||
}
|
||||
|
||||
// 4. Bare ReadableStream — peek until threshold or EOF
|
||||
if (input instanceof ReadableStream) {
|
||||
return await peekStream(input);
|
||||
}
|
||||
|
||||
throw new TypeError(
|
||||
`decideInline: unsupported input type ${Object.prototype.toString.call(input)}`,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Drain a stream into a Uint8Array, with a soft cap at `expected` + slack.
|
||||
* Used for the inline path when the caller declared a size.
|
||||
*/
|
||||
async function drainStream(
|
||||
stream: ReadableStream<Uint8Array>,
|
||||
expected: number,
|
||||
): Promise<Uint8Array> {
|
||||
const reader = stream.getReader();
|
||||
const chunks: Uint8Array[] = [];
|
||||
let total = 0;
|
||||
try {
|
||||
while (true) {
|
||||
const { value, done } = await reader.read();
|
||||
if (done) break;
|
||||
if (value === undefined) continue;
|
||||
chunks.push(value);
|
||||
total += value.byteLength;
|
||||
if (total > expected + INLINE_THRESHOLD) {
|
||||
throw new Error(
|
||||
`decideInline: stream produced more bytes (${total}) than declared size (${expected})`,
|
||||
);
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
reader.releaseLock();
|
||||
}
|
||||
return concat(chunks, total);
|
||||
}
|
||||
|
||||
/**
|
||||
* Peek a `ReadableStream` of unknown length: buffer up to `INLINE_THRESHOLD + 1`
|
||||
* bytes. If EOF first, return inline. Otherwise reconstruct a stream that
|
||||
* yields the buffered prefix followed by the remainder.
|
||||
*/
|
||||
async function peekStream(stream: ReadableStream<Uint8Array>): Promise<InlineDecision> {
|
||||
const reader = stream.getReader();
|
||||
const buffered: Uint8Array[] = [];
|
||||
let total = 0;
|
||||
try {
|
||||
while (total <= INLINE_THRESHOLD) {
|
||||
const { value, done } = await reader.read();
|
||||
if (done) {
|
||||
reader.releaseLock();
|
||||
return { kind: 'inline', bytes: concat(buffered, total) };
|
||||
}
|
||||
if (value === undefined) continue;
|
||||
buffered.push(value);
|
||||
total += value.byteLength;
|
||||
}
|
||||
// We have at least INLINE_THRESHOLD + 1 bytes buffered. Promote to streams.
|
||||
const reconstructed = reconstructStream(buffered, reader);
|
||||
return { kind: 'streams', stream: reconstructed };
|
||||
} catch (err) {
|
||||
reader.releaseLock();
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
interface MinimalReader {
|
||||
read(): Promise<{ value: Uint8Array | undefined; done: boolean }>;
|
||||
cancel(reason?: unknown): Promise<void>;
|
||||
releaseLock(): void;
|
||||
}
|
||||
|
||||
function reconstructStream(
|
||||
prefix: Uint8Array[],
|
||||
reader: MinimalReader,
|
||||
): ReadableStream<Uint8Array> {
|
||||
let prefixIdx = 0;
|
||||
return new ReadableStream<Uint8Array>({
|
||||
async pull(controller) {
|
||||
if (prefixIdx < prefix.length) {
|
||||
controller.enqueue(prefix[prefixIdx]!);
|
||||
prefixIdx++;
|
||||
return;
|
||||
}
|
||||
const { value, done } = await reader.read();
|
||||
if (done) {
|
||||
controller.close();
|
||||
reader.releaseLock();
|
||||
return;
|
||||
}
|
||||
if (value !== undefined) controller.enqueue(value);
|
||||
},
|
||||
async cancel(reason) {
|
||||
try {
|
||||
await reader.cancel(reason);
|
||||
} finally {
|
||||
reader.releaseLock();
|
||||
}
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
function uint8ArrayToStream(bytes: Uint8Array): ReadableStream<Uint8Array> {
|
||||
return new ReadableStream<Uint8Array>({
|
||||
start(controller) {
|
||||
controller.enqueue(bytes);
|
||||
controller.close();
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
function concat(chunks: Uint8Array[], total: number): Uint8Array {
|
||||
const out = new Uint8Array(total);
|
||||
let offset = 0;
|
||||
for (const c of chunks) {
|
||||
out.set(c, offset);
|
||||
offset += c.byteLength;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user