Files

352 lines
12 KiB
Markdown
Raw Permalink Normal View History

2026-05-03 10:44:02 +00:00
# @push.rocks/smartsamba
🦀 SMB/Samba for TypeScript, powered by a bundled Rust engine. `@push.rocks/smartsamba` gives Node.js projects a clean TypeScript API for running an SMB server, connecting to SMB shares, and doing real file operations without shelling out to `smbd` or `smbclient`.
## Issue Reporting and Security
For reporting bugs, issues, or security vulnerabilities, please visit [community.foss.global/](https://community.foss.global/). This is the central community hub for all issue reporting. Developers who sign and comply with our contribution agreement and go through identification can also get a [code.foss.global/](https://code.foss.global/) account to submit Pull Requests directly.
## What It Does
`smartsamba` is for code that needs SMB/CIFS behavior directly from TypeScript:
- Start an embedded SMB server that exposes local folders as shares.
- Connect to existing SMB servers with username, password, and optional domain credentials.
- List shares and directories.
- Read and write files as `Buffer` or string data.
- Create directories, rename paths, delete files, and inspect file metadata.
- Ship one TypeScript module with a native Rust helper instead of depending on host-level Samba daemons.
2026-05-03 10:44:02 +00:00
## Install
```sh
pnpm add @push.rocks/smartsamba
```
This package is ESM-only and intended for Node.js runtimes.
## Quick Start
Spin up a local SMB share and access it through the SMB client API:
2026-05-03 10:44:02 +00:00
```ts
import { SambaClient, SambaServer } from '@push.rocks/smartsamba';
2026-05-03 10:44:02 +00:00
const server = new SambaServer({
host: '127.0.0.1',
2026-05-03 10:44:02 +00:00
port: 0,
users: [{ username: 'alice', password: 'secret' }],
shares: [
{
name: 'files',
path: './shared',
createIfMissing: true,
},
],
2026-05-03 10:44:02 +00:00
});
const started = await server.start();
const client = new SambaClient({
host: started.host,
2026-05-03 10:44:02 +00:00
port: started.port,
auth: { username: 'alice', password: 'secret' },
});
try {
await client.writeFile('files', 'hello.txt', 'hello samba');
const content = await client.readFileAsString('files', 'hello.txt');
console.log(content); // "hello samba"
const entries = await client.listDirectory('files');
console.log(entries.map((entry) => entry.name));
} finally {
await client.stop();
await server.stop();
}
```
Use `port: 0` for tests and local tooling when you want the OS to choose a free port. Use a fixed port when you need a predictable endpoint.
## Architecture
The TypeScript layer talks to a bundled `rustsamba` binary through `@push.rocks/smartrust`. The Rust side implements the SMB engine and exposes a small JSON-lines management protocol to the TypeScript API.
That means:
- No dependency on system `smbd`.
- No dependency on system `smbclient`.
- No fragile shell parsing.
- The same TypeScript API controls both client and server operations.
- The native helper can be overridden with `SMARTSAMBA_RUST_BINARY` for debugging or custom builds.
During development, `@git.zone/tsrust` builds the Rust binary and places it in `dist_rust/`. Published packages include the built Rust artifact.
## Client Usage
Create a client for an existing SMB server:
```ts
import { SambaClient } from '@push.rocks/smartsamba';
const client = new SambaClient({
host: 'fileserver.internal',
port: 445,
auth: {
username: 'alice',
password: process.env.SAMBA_PASSWORD!,
domain: 'WORKGROUP',
},
});
try {
const shares = await client.listShares();
console.log(shares);
await client.createDirectory('documents', 'reports/2026');
await client.writeFile('documents', 'reports/2026/hello.txt', 'hello from TypeScript');
const buffer = await client.readFile('documents', 'reports/2026/hello.txt');
const text = await client.readFileAsString('documents', 'reports/2026/hello.txt');
const info = await client.stat('documents', 'reports/2026/hello.txt');
console.log(buffer.length, text, info.size);
await client.rename('documents', 'reports/2026/hello.txt', 'reports/2026/final.txt');
await client.deleteFile('documents', 'reports/2026/final.txt');
} finally {
await client.stop();
}
```
Paths are passed separately from the share name. Use `client.readFile('share', 'path/to/file.txt')`, not a combined SMB URL.
## Server Usage
Expose one or more local folders as SMB shares:
```ts
import { SambaServer } from '@push.rocks/smartsamba';
const server = new SambaServer({
host: '0.0.0.0',
port: 445,
netbiosName: 'SMARTSAMBA',
users: [
{ username: 'alice', password: 'secret' },
{ username: 'bob', password: 'hunter2' },
],
shares: [
{
name: 'public',
path: '/srv/samba/public',
public: true,
readOnly: true,
},
{
name: 'team',
path: '/srv/samba/team',
users: [
{ username: 'alice', access: 'readWrite' },
{ username: 'bob', access: 'read' },
],
},
],
});
const started = await server.start();
console.log(`SMB server listening on ${started.address}`);
const status = await server.status();
console.log(status);
2026-05-03 10:44:02 +00:00
await server.stop();
```
By default, `SambaServer` listens on `127.0.0.1:445`. Passing `port: 0` lets the OS assign a free port. Share folders are created automatically unless `createIfMissing: false` is set.
## API Reference
### `SambaClient`
```ts
const client = new SambaClient(options);
```
Client options:
| Option | Type | Description |
| --- | --- | --- |
| `host` | `string` | SMB server hostname or IP address. |
| `port` | `number` | SMB TCP port. Defaults to the Rust client's SMB default when omitted. |
| `auth.username` | `string` | Username for NTLM authentication. |
| `auth.password` | `string` | Password for NTLM authentication. |
| `auth.domain` | `string` | Optional NTLM domain/workgroup. |
| `timeoutMs` | `number` | Reserved API option. Currently accepted but not applied by the Rust client. |
| `compression` | `boolean` | Reserved API option. Currently accepted but not applied by the Rust client. |
| `dfsEnabled` | `boolean` | Reserved API option. Currently accepted but not applied by the Rust client. |
Client methods:
| Method | Returns | Description |
| --- | --- | --- |
| `start()` | `Promise<void>` | Starts the Rust bridge process early. Usually optional because operations start it lazily. |
| `stop()` | `Promise<void>` | Stops the Rust bridge process used by this client. |
| `listShares()` | `Promise<ISambaShareInfo[]>` | Lists shares exposed by the server. |
| `listDirectory(share, path?)` | `Promise<ISambaDirectoryEntry[]>` | Lists files and folders in a share directory. Use `''` for the share root. |
| `readFile(share, path)` | `Promise<Buffer>` | Reads a file as a Node.js `Buffer`. |
| `readFileAsString(share, path, encoding?)` | `Promise<string>` | Reads a file and decodes it as a string. Defaults to `utf8`. |
| `writeFile(share, path, data)` | `Promise<number>` | Writes `Buffer` or string data and returns the number of bytes written. |
| `deleteFile(share, path)` | `Promise<void>` | Deletes a file. |
| `createDirectory(share, path)` | `Promise<void>` | Creates a directory. |
| `rename(share, from, to)` | `Promise<void>` | Renames or moves a path inside the share. |
| `stat(share, path)` | `Promise<ISambaFileInfo>` | Reads file or directory metadata. |
### `SambaServer`
```ts
const server = new SambaServer(options);
```
Server options:
| Option | Type | Description |
| --- | --- | --- |
| `host` | `string` | Address to bind. Defaults to `127.0.0.1`. |
| `port` | `number` | TCP port to bind. Defaults to `445`. Use `0` for an ephemeral port. |
| `netbiosName` | `string` | Optional NetBIOS name. |
| `users` | `ISambaServerUser[]` | Server-level users available to shares. |
| `shares` | `ISambaServerShare[]` | Required list of local folders to expose. |
Share options:
| Option | Type | Description |
| --- | --- | --- |
| `name` | `string` | SMB share name. |
| `path` | `string` | Local filesystem path exposed by the share. |
| `readOnly` | `boolean` | Makes the backing folder read-only through SMB. |
| `public` | `boolean` | Allows public access to the share. |
| `users` | `ISambaServerShareUser[]` | Per-share user access rules. Defaults to all server users with `readWrite` access. |
| `createIfMissing` | `boolean` | Creates the local share directory before startup. Defaults to `true`. |
Server methods:
| Method | Returns | Description |
| --- | --- | --- |
| `start()` | `Promise<ISambaServerStartResult>` | Starts the embedded SMB server. |
| `stop()` | `Promise<void>` | Stops the SMB server and its Rust bridge process. |
| `status()` | `Promise<ISambaServerStatus>` | Returns current server status. |
| `getConnectionOptions(auth?)` | `ISambaClientOptions` | Builds client options for connecting to a started server. |
## Type Shapes
```ts
export type TSambaShareAccess = 'read' | 'readWrite';
export interface ISambaAuthOptions {
username: string;
password: string;
domain?: string;
}
export interface ISambaDirectoryEntry {
name: string;
size: number;
isDirectory: boolean;
createdFiletime: number;
modifiedFiletime: number;
}
export interface ISambaFileInfo {
size: number;
isDirectory: boolean;
createdFiletime: number;
modifiedFiletime: number;
accessedFiletime: number;
}
export interface ISambaShareInfo {
name: string;
shareType: number;
comment: string;
}
```
The `*Filetime` fields are Windows FILETIME values: 100-nanosecond ticks since `1601-01-01T00:00:00Z`.
Convert them to JavaScript dates like this:
```ts
const filetimeToDate = (filetime: number) => {
const unixMilliseconds = filetime / 10_000 - 11_644_473_600_000;
return new Date(unixMilliseconds);
};
```
## Path Rules
SMB paths are normalized internally. Use forward slashes in TypeScript for readability:
```ts
await client.writeFile('files', 'nested/path/report.txt', reportBuffer);
```
Use an empty path for the root of a share:
```ts
const entries = await client.listDirectory('files', '');
```
## Binary Resolution
`smartsamba` looks for the Rust helper in this order:
| Source | Purpose |
| --- | --- |
| `SMARTSAMBA_RUST_BINARY` | Explicit override for debugging or custom deployments. |
| `dist_rust/rustsamba_*` | Platform-specific binary generated by `@git.zone/tsrust`. |
| `dist_rust/rustsamba` | Generic bundled binary. |
| `rust/target/release/rustsamba` | Local release build fallback. |
| `rust/target/debug/rustsamba` | Local debug build fallback. |
If no helper can be started, operations throw an error asking you to run the build or test preparation step.
## Development
```sh
pnpm install
pnpm test
pnpm run build
```
`pnpm test` builds the Rust helper first, then runs the Node.js integration test. The test starts a local SMB server, writes a file through the SMB client, reads it back, lists the share, stats the file, renames it, and deletes it.
## Operational Notes
- Binding to port `445` may require elevated privileges on some systems. Use `port: 0` or a high port for development and tests.
- `SambaServer` manages one embedded server per instance.
- Call `stop()` in `finally` blocks to cleanly shut down bridge processes.
- `rust/target/`, `node_modules/`, `dist_ts/`, and `dist_rust/` are build artifacts or generated outputs and are not source history.
## License and Legal Information
This repository contains open-source code licensed under the MIT License. A copy of the license can be found in the [license](./license) file.
**Please note:** The MIT License does not grant permission to use the trade names, trademarks, service marks, or product names of the project, except as required for reasonable and customary use in describing the origin of the work and reproducing the content of the NOTICE file.
### Trademarks
This project is owned and maintained by Task Venture Capital GmbH. The names and logos associated with Task Venture Capital GmbH and any related products or services are trademarks of Task Venture Capital GmbH or third parties, and are not included within the scope of the MIT license granted herein.
Use of these trademarks must comply with Task Venture Capital GmbH's Trademark Guidelines or the guidelines of the respective third-party owners, and any usage must be approved in writing. Third-party trademarks used herein are the property of their respective owners and used only in a descriptive manner, e.g. for an implementation of an API or similar.
### Company Information
Task Venture Capital GmbH
Registered at District Court Bremen HRB 35230 HB, Germany
For any legal inquiries or further information, please contact us via email at hello@task.vc.
By using this repository, you acknowledge that you have read this section, agree to comply with its terms, and understand that the licensing of the code does not imply endorsement by Task Venture Capital GmbH of any derivative works.