Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
24 commits
Select commit Hold shift + click to select a range
fc5c851
feat(recipher-js): every value type, arrays and JSON documents
coderdan Nov 25, 2026
85c1fc8
Merge branch 'next' into feat/recipher-js-values
coderdan Nov 27, 2026
f99259a
refactor(recipher-js): name the wrapper classes RcDate, RcTimestamp, …
coderdan Nov 28, 2026
27b7ac1
docs(recipher-js): the value bridge defines the value mapping, not vi…
coderdan Nov 28, 2026
1e200d6
refactor(recipher-js): declare each wrapper class beside its type, wi…
coderdan Nov 28, 2026
dab69c5
fix(recipher-js): a stand-in wrapper class constructs as the addon's …
coderdan Nov 28, 2026
cceea6a
docs(recipher-js): a plain object is json(..) today, and opaque(..) w…
coderdan Nov 28, 2026
c001978
feat(recipher-js): the value bridge reads and builds JSON documents
coderdan Nov 28, 2026
e0cc1c6
refactor(recipher-js): the addon passes a JSON document between the b…
coderdan Nov 28, 2026
7602062
fix(recipher-js): refuse a hole in the array given to encrypt or decrypt
coderdan Nov 28, 2026
bb51af7
fix(recipher-js): Ciphertext.fromBytes takes only a kind the package …
coderdan Nov 28, 2026
629362b
test(recipher-js): pin the help of every error the addon defines
coderdan Nov 28, 2026
b1a38b0
docs(recipher-js): only Rust's keyset.encrypt writes the single-value…
coderdan Nov 28, 2026
4f8179a
docs(recipher-js): the JSON rules as the bridge implements them
coderdan Nov 28, 2026
e69aba2
test(recipher-js): pin the depth limit of a JSON document the bridge …
coderdan Nov 28, 2026
c378520
docs(recipher-js): "An RcUuid", in the doc of the addon's uuid error
coderdan Nov 28, 2026
e9ad2aa
docs(recipher-js): plain language for the values and JSON prose
coderdan Nov 28, 2026
1cf2f55
fix(recipher-js): error messages for values in the SDK's own words
coderdan Nov 28, 2026
78c2c78
fix(recipher-js): bump the binding interface, and say why a UUID is r…
coderdan Nov 28, 2026
89a3b27
docs(recipher-js): give the bigint range in the json() docs
coderdan Nov 28, 2026
5c78ecf
fix(recipher-js): refuse a number below -2^63 without asking for a bi…
coderdan Nov 29, 2026
f489f4a
Merge next into feat/recipher-js-values
coderdan Nov 29, 2026
2dbc9fd
feat(recipher-js)!: encrypt one value through dynamic::value, with a …
coderdan Nov 29, 2026
6b52b68
fix(recipher-js): give a refused null value the code recipher_js::nul…
coderdan Nov 29, 2026
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion AGENTS.md

Large diffs are not rendered by default.

10 changes: 5 additions & 5 deletions conformance/vitaminc-aead/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -63,11 +63,11 @@ than skipping the row:

- `js_reencode`: Node has two projections. A Float32 becomes a Number and
re-encodes as Float64. A timestamp that is a whole number of milliseconds
is read as a `Date` and re-encodes as the `Timestamp(Millis)` envelope; a
finer one is read as a `VcTimestamp` and re-encodes in the nanosecond
shorthand. As for Go, this is safe because `LeafTypeAad` binds the kind and
the logical id but not the unit, and the equality terms put every unit in
one timestamp domain.
is read as a `Date`, and re-encodes as the `Timestamp(Millis)` envelope. A
finer timestamp is read as an `RcTimestamp`, and re-encodes in the
nanosecond shorthand. As for Go, the timestamp projection is safe for two
reasons. `LeafTypeAad` binds the kind and the logical id, but not the
unit. The equality terms put every unit in one timestamp domain.
- `go_reencode`: Go has two projections. `undefined` becomes nil and
re-encodes as null. A timestamp in the envelope (seconds, milliseconds or
microseconds) is read as a `time.Time` and re-encodes in the nanosecond
Expand Down
6 changes: 6 additions & 0 deletions languages/typescript/packages/recipher-js/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

192 changes: 181 additions & 11 deletions languages/typescript/packages/recipher-js/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ const stored = sealed.value.toBytes() // a Uint8Array to keep
const opened = await cipher.decrypt(sealed.value)
```

- `encrypt` returns a `Ciphertext`. A ciphertext is one encrypted value.
- Encrypting needs a keyset. Decrypting does not.
- `cipher.decrypt` decrypts a value from any of the cipher's keysets.
`keyset.decrypt` refuses a value from another keyset.
Expand All @@ -43,7 +44,164 @@ const opened = await cipher.decrypt(sealed.value)
This package decrypts what Rust encrypted.
- You cannot make a `Cipher`, a `Keyset`, or a `Ciphertext` with a constructor.
Get a cipher from `Cipher.create()`, a keyset from `cipher.defaultKeyset()`, and a ciphertext from `encrypt` or `Ciphertext.fromBytes`.
- This build encrypts a `string` only.

## Values

A value's type decides how it is encrypted.
The value bridge defines the mapping.
The value bridge is the `recipher-value-napi` crate, in `value-napi/`.
The value bridge converts JavaScript values in both directions:

| Value | Encrypted as | Decrypts as |
|---|---|---|
| `string` | text | `string` |
| `boolean` | a boolean | `boolean` |
| `number` | a 64-bit float | `number` |
| `bigint` | an integer, at the narrowest width that fits it | `bigint` |
| `Uint8Array`, `Buffer` | bytes | `Uint8Array` |
| `Date` | a timestamp | `Date` |
| `new RcTimestamp('2026-11-23T01:02:03.000000001Z')` | a timestamp, in nanoseconds | `Date` when it is whole milliseconds, else `RcTimestamp` |
| `new RcDate('2026-11-23')` | a calendar date | `RcDate` |
| `new RcDecimal('1.50')` | a decimal, with its scale | `RcDecimal` |
| `null` | refused with no kind: see [A declared kind](#a-declared-kind) | not applicable |
| `json(value)` | a JSON document, as its JSON text | the document, from the `Ciphertext` that `encrypt` returned or one read with `kinds.json` |

- `RcTimestamp`, `RcDate`, `RcDecimal`, and `RcUuid` are wrapper classes.
A wrapper class represents a type that JavaScript does not have.
The constructor of a wrapper class accepts the value as text.
- Integers are a `bigint`.
A `number` is a float.
The `number` `5` does not equal the integer `5n`.
- A plain object is refused, because an object has no single stored form.
You choose the form.
`json(..)` encrypts the object as a JSON document.
`opaque(..)`, for a whole object in the engine's own format, is not built yet.
- The package exports `RcUuid`, for a universally unique identifier (UUID).
This version of the SDK does not encrypt a UUID yet.
Encrypting an `RcUuid` is an `Err` with the code `recipher_js::uuid`.
- The value bridge refuses each of these values, with an error code for each:
- a `Map` or a `Set`;
- a class instance;
- a sparse array;
- a typed array other than a `Uint8Array`;
- a string with an unpaired surrogate;
- a property named `__proto__`, `constructor`, or `prototype`.

If you encrypt an array, you get back an array of ciphertexts in the same order.
The whole array needs one key request to ZeroKMS, however long it is:

```ts
const sealed = await keyset.encrypt(['first secret', 'second secret'])
const opened = await cipher.decrypt(sealed.unwrap())
```

### A declared kind

`encrypt` takes a kind in its options, as in `{ kind: kinds.uint64 }`.
The value is stored as that kind, and its ciphertext decrypts as that kind.
For an array of values, the kind applies to each value.

```ts
import { kinds } from '@cipherstash/recipher'

const age = (await keyset.encrypt(34, { kind: kinds.uint64 })).unwrap()
const opened = (await cipher.decrypt(age)).unwrap()
// 34n
```

- A value converts to the declared kind only when the conversion is exact.
A record field converts a value by the same rules.
`34` declared as `uint64` is stored as the integer `34`.
`34.5` declared as `uint64` is refused.
- A value declared as `kinds.json` must be a `json(..)` value.
A `json(..)` value declared as another kind is refused.
Each is an `Err` with the code `recipher_js::json_kind`.
- The options take only `kind`.
Any other key is an `Err` with the code `recipher_js::options`, so an option that this version does not have is never ignored.
- A ciphertext contains one value, and `null` is the absence of a value.
So a lone `null` is an `Err` with the code `recipher_js::null_value`.
Store a value that is not there as a database `NULL`.
- A lone `null` needs a declared kind.
The kind must be fixed-width: a boolean, an integer, a float, a decimal, a date, or a timestamp.
The engine will encrypt it as a typed null, padded to the size of a value, as a record field with `"null": "sealed"` stores one.
Issue #2023 makes that engine change.
The change has not merged yet.
Until then, a `null` with a kind is refused too.
- A `null` of a variable-width kind, such as `kinds.string` or `kinds.bytes`, is always refused.
A value of that kind has no fixed size, so a null cannot be padded to look like a value.

### JSON documents

`json(value)` encrypts a whole document as one ciphertext.
The document is encrypted as its JSON text, as the engine's `JsonPlaintext` type does.
Rust code that calls `keyset.decrypt::<JsonPlaintext>` decrypts it.

```ts
import { json } from '@cipherstash/recipher'

const profile = json({ name: 'Ada', visits: 3, id: 2n ** 64n - 1n })
const sealed = (await keyset.encrypt(profile)).unwrap()

const opened = (await cipher.decrypt(sealed)).unwrap()
// { id: 18446744073709551615n, name: 'Ada', visits: 3 }
```

A document is a plain object, an array, a string, a number, a `bigint`, a boolean, or `null`.
A document can nest 127 levels of arrays and objects.

These rules decide how a number is stored and decrypted:

| In the document | Stored as | Decrypts as |
|---|---|---|
| a whole `number` within 2^53 - 1 of zero, such as `5000000000` | the integer `5000000000` | `number` |
| a whole `number` from 2^53 up to 2^64, or from -2^53 down to -2^63 | refused: pass a `bigint` | not applicable |
| a whole `number` below -2^63 and above -2^64 | refused: no exact form | not applicable |
| any other `number`, such as `1.5` or `1e20` | a float | `number` |
| a `bigint` within 2^53 - 1 of zero, such as `5n` | the integer `5` | `number` |
| any other `bigint` from `-(2n ** 63n)` to `2n ** 64n - 1n` | an integer, with its exact digits | `bigint` |
| a `bigint` outside that range | refused | not applicable |

- A whole `number` is stored as an integer, as `JSON.stringify` writes it.
A millisecond timestamp from `Date.now()`, such as `1764288000000`, is stored as `1764288000000`.
The timestamp is never stored as `1764288000000.0`.
Code in Rust or Go refuses that form for an integer field.
- A whole `number` from 2^53 up to 2^64, or from -2^53 down to -2^63, is refused.
A `number` that large may not keep the digits you wrote.
Use a `bigint` instead.
- A whole `number` below -2^63 and above -2^64 is refused too.
An integer in that range has no exact form in a document, because a `bigint` that size is refused as well.
- A `bigint` must be in the 64-bit range that the engine's parser reads.
- An integer decrypts as a `number` when it is within 2^53 - 1 of zero, and as a `bigint` otherwise.
So no digit is lost, and `json({ a: 5n })` decrypts as `{ a: 5 }`.
- The engine stores the members of an object sorted by key.
A decrypted object lists its members in that order, not in the order you wrote them.
- `undefined`, `NaN`, the infinities, bytes, a `Date`, and the wrapper classes have no JSON form.
Each is an `Err` with the code `recipher_js::not_json`.
The package does not call a `toJSON` method.
- A document nested deeper than 127 levels is an `Err` with the code `recipher_js::too_deep`.
- The same rules apply to a document as to any value.
A `Map`, a class instance, a sparse array, and a string with an unpaired surrogate are refused.
- A property named `__proto__`, `constructor`, or `prototype` cannot be encrypted.
Another SDK can write a document with one of these properties.
Decrypting that document here gives an `Err` with the code `recipher_js::reserved_key`.
The reason is that the value bridge does not build those properties in JavaScript.
- **Read a stored document back with `kinds.json`.**
A kind names the type that a stored ciphertext decrypts to.
The bytes do not record that a value is JSON.
`Ciphertext.fromBytes(bytes, kinds.json)` decrypts to the document.
With no kind, the document decrypts to its JSON text.
`JSON.parse` of that text loses the digits of a large integer.

### Stored bytes

A kind names the type a stored ciphertext decrypts to, such as `kinds.string`.

`Ciphertext.fromBytes(bytes)` decrypts to whatever type was encrypted.
The ciphertext's TypeScript type allows any scalar: any type in the table above except a JSON document.

`Ciphertext.fromBytes(bytes, kinds.string)` has the kind's type.
Decrypting it refuses a value that was encrypted as another type.
An integer kind accepts an integer encrypted at any width, if the value fits the kind.

## Results, not exceptions

Expand All @@ -61,6 +219,7 @@ The other calls return an `Err` in these cases too:

- an argument of the wrong type, or a missing argument;
- a native addon that did not load.
The native addon is the compiled Rust code that Node loads.

One call throws: a method called without its object.
`ciphertexts.map(cipher.decrypt)` passes `decrypt` on its own, without its cipher.
Expand All @@ -75,6 +234,11 @@ const opened = await Promise.all(

A static method, such as `Ciphertext.fromBytes`, works on its own.

A wrapper class's constructor throws too.
The constructor accepts only a string, so `new RcDate(20261123)` throws a `TypeError`.
The constructor does not check the text.
`encrypt` returns an `Err` for text that is not a date.

A `RecipherError` is an error report that a call returns as a value.
Most errors come from the engine.
The SDK's own errors have a code that starts with `recipher_js::`.
Expand All @@ -91,9 +255,9 @@ if (opened.isErr()) {

| Property | What it contains |
| --- | --- |
| `code` | The code to switch on. It is stable. It is the engine's code (`stack_encrypt::aead`), vitaminc's code for a value it refused (`ERR_INTEGER_RANGE`), or the SDK's own (`recipher_js::not_a_ciphertext`). |
| `code` | The code to switch on. It is stable. It is the engine's code (`stack_encrypt::aead`), the value bridge's code for a scalar it refused (`ERR_INTEGER_RANGE`), or the SDK's own (`recipher_js::not_a_ciphertext`). |
| `message` | What went wrong, in one line. |
| `help` | What to do about it, where the error knows. |
| `help` | What to do about the failure, when the error has that advice. |
| `url` | A documentation page for the error, where it has one. |
| `severity` | `error`, unless the engine's report states `warning` or `advice`. |
| `fields` | The error's structured fields, by `snake_case` name. An example is a ZeroKMS failure's `request_kind`. |
Expand Down Expand Up @@ -130,13 +294,22 @@ The value bridge is the `recipher-value-napi` crate in `value-napi/`.
napi-rs's command-line tool builds the addon.
The tool also writes the addon's TypeScript declarations to `native.d.ts`.
Those declarations are the package's public types.
Each method's signature is written in Rust, in the method's `ts_type`, `ts_args_type` or `ts_return_type` attribute.
The documentation comments on the Rust code become the declarations' documentation.
`native-header.d.ts` is the start of `native.d.ts`: it imports the TypeScript types the signatures name, and gives `Ciphertext` its type parameter.
`native.d.ts` is committed.

Each method's signature is written in Rust, in the method's `ts_type`, `ts_args_type`, or `ts_return_type` attribute.
The tool copies the Rust documentation comments into the declarations.

`native-header.d.ts` is the start of `native.d.ts`.
The header does three things:

- it imports the TypeScript types that the signatures name;
- it gives `Ciphertext` its type parameter;
- it marks `Json` so that no other object type-checks as one.

The modules that the header imports types from never load the addon, so the declarations never import themselves.

Each native method returns a `Result` itself.
The package's TypeScript gives the addon the `Ok`, `Err` and `RecipherError` classes when it loads the addon.
The package's TypeScript gives the addon the `Ok`, `Err`, and `RecipherError` classes when it loads the addon.
The package's TypeScript contains what Rust cannot provide: `Result`, `RecipherError`, the loader, and stand-in classes for when the addon did not load.

The package's `build` and `test` scripts never run cargo.
Expand All @@ -151,15 +324,12 @@ The package's `build` and `test` scripts never run cargo.
| `test:cargo` | Runs `cargo test`, `cargo fmt --check`, and clippy over the crate. |

The addon is loaded when the package is imported.
The ESM build and the CommonJS build load the same addon, so the two builds share its classes.
The ECMAScript module (ESM) build and the CommonJS build load the same addon, so the two builds share its classes.

## What is not here yet

These features are not built yet:

- values other than a `string`;
- arrays;
- JSON documents;
- `opaque(..)`, for a whole object;
- records;
- search terms;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,12 +1,19 @@
/**
* The ESM and the CommonJS builds in one process: an application that
* imports the package and a dependency that requires it. Both load the one
* addon, so they share its classes, and a ciphertext from either opens in
* the other. Runs the built `dist/`, in a Node process of its own;
* `test:addon` builds it first.
* Two cases:
*
* - The ECMAScript module (ESM) build and the CommonJS build in one process.
* An application imports the package, and a dependency requires it. Both
* builds load the same addon, so they share its classes. A ciphertext from
* either build decrypts in the other.
* - The package with no native build at all.
*
* Each case runs the built `dist/` in a Node process of its own.
* `test:addon` builds `dist/` first.
*/
import { execFileSync } from 'node:child_process'
import { existsSync } from 'node:fs'
import { cpSync, existsSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { fileURLToPath } from 'node:url'
import { describe, expect, it } from 'vitest'

Expand Down Expand Up @@ -48,6 +55,59 @@ const out = {
console.log(JSON.stringify(out))
`

const MISSING = `
const recipher = await import(process.argv[1])
const testing = await import(process.argv[2])
const out = {}
out.date = new recipher.RcDate('2026-11-23').value
out.dateFrozen = Object.isFrozen(new recipher.RcDate('2026-11-23'))
out.json = String(recipher.json({ a: 1 }))
out.create = (await recipher.Cipher.create()).err().code
out.testing = (await testing.testCipher()).err().code
out.fromBytes = recipher.Ciphertext.fromBytes(new Uint8Array(4)).err().code
out.notACipher = {} instanceof recipher.Cipher
console.log(JSON.stringify(out))
`

describe('the package without its native build', () => {
it('imports, constructs the wrapper classes, and resolves every call to the load error', () => {
const dir = mkdtempSync(join(tmpdir(), 'recipher-missing-'))
try {
cpSync(
fileURLToPath(new URL('../../dist', import.meta.url)),
join(dir, 'dist'),
{
recursive: true,
},
)
writeFileSync(join(dir, 'package.json'), '{"type":"module"}')
const output = execFileSync(
process.execPath,
[
'--input-type=module',
'--eval',
MISSING,
'--',
join(dir, 'dist', 'index.js'),
join(dir, 'dist', 'testing.js'),
],
{ encoding: 'utf8' },
)
expect(JSON.parse(output)).toEqual({
date: '2026-11-23',
dateFrozen: true,
json: 'Json(***)',
create: 'recipher_js::load',
testing: 'recipher_js::load',
fromBytes: 'recipher_js::load',
notACipher: false,
})
} finally {
rmSync(dir, { recursive: true, force: true })
}
})
})

describe('the ESM and CommonJS builds in one process', () => {
it('share the native classes, so each opens what the other sealed', () => {
const files = ['index.js', 'testing.js', 'index.cjs', 'testing.cjs'].map(
Expand Down
Loading
Loading