Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
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
1 change: 1 addition & 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.

17 changes: 12 additions & 5 deletions languages/typescript/packages/recipher-js/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,7 @@ The value bridge converts JavaScript values in both directions:
| `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` |
| `new RcUuid('123e4567-e89b-12d3-a456-426614174000')` | a universally unique identifier (UUID) | `RcUuid` |
| `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` |

Expand All @@ -76,9 +77,11 @@ The value bridge converts JavaScript values in both directions:
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`.
- A UUID is an `RcUuid`, not a string.
A string that contains a UUID is encrypted as text.
The text of an `RcUuid` must be hyphenated hex, in upper or lower case.
Encrypting an `RcUuid` with other text, such as text in braces, is an `Err` with the code `ERR_INVALID_UUID`.
A decrypted `RcUuid` contains lowercase hyphenated hex, whatever case it was built with.
- The value bridge refuses each of these values, with an error code for each:
- a `Map` or a `Set`;
- a class instance;
Expand Down Expand Up @@ -122,7 +125,7 @@ const opened = (await cipher.decrypt(age)).unwrap()
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 kind must be fixed-width: a boolean, an integer, a float, a decimal, a date, a timestamp, or a UUID.
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.
Expand Down Expand Up @@ -231,7 +234,7 @@ const opened = await cipher.decrypt(user, stored.unwrap())
- The package has an ECMAScript module (ESM) build and a CommonJS build.
A declaration made by either build works with a cipher from the other.
- Each encrypted field names its kind, by the engine's name for it.
The kinds are `kinds.string`, `kinds.boolean`, `kinds.int8` to `kinds.int128`, `kinds.uint8` to `kinds.uint128`, `kinds.float32`, `kinds.float64`, `kinds.decimal`, `kinds.date`, `kinds.timestamp`, and `kinds.bytes`.
The kinds are `kinds.string`, `kinds.boolean`, `kinds.int8` to `kinds.int128`, `kinds.uint8` to `kinds.uint128`, `kinds.float32`, `kinds.float64`, `kinds.decimal`, `kinds.date`, `kinds.timestamp`, `kinds.bytes`, and `kinds.uuid`.
- An integer field accepts a `bigint` at every width.
The field refuses a `bigint` outside its range.
- A context is data that a ciphertext is bound to.
Expand All @@ -243,6 +246,10 @@ const opened = await cipher.decrypt(user, stored.unwrap())
`equality` finds exact matches.
`match` finds text matches.
`ore` and `ope` compare order.
A field's kind decides which indexes the field accepts.
For example, a `kinds.uuid` field accepts `equality` only.
When the engine checks the declaration, it refuses any other index on that field.
The refusal has the reason `index_not_admitted` in `error.fields`.
- The stored row has one object for each encrypted field.
The object has a `ciphertext` property.
The object also has one property for each index the field declares: `equality`, `match`, `ore`, or `ope`.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import {
passthrough,
RcDate,
RcDecimal,
RcUuid,
record,
} from '../../src/index'
import { testCipher } from '../../src/testing'
Expand Down Expand Up @@ -128,6 +129,129 @@ describe('a record', () => {
})
})

describe('a UUID field', () => {
Comment thread
coderdan marked this conversation as resolved.
Resolved
const device = record('devices', {
id: encrypt(kinds.uuid, { index: ['equality'] }),
name: encrypt(kinds.string),
})
const text = '123e4567-e89b-12d3-a456-426614174000'

it('is stored, found by equality, and read back as an RcUuid', async () => {
const c = await cipher()
const keyset = c.defaultKeyset()
const row = { id: new RcUuid(text), name: 'sensor' }
const stored = (await keyset.encrypt(device, row)).unwrap()
expect(Object.keys(stored.id).sort()).toEqual(['ciphertext', 'equality'])

// A query term for the same UUID matches the stored term. A query term
// for another UUID does not.
const same = (
await keyset.encryptField(device, 'id', new RcUuid(text))
).unwrap()
const other = (
await keyset.encryptField(
device,
'id',
new RcUuid('123e4567-e89b-12d3-a456-426614174001'),
)
).unwrap()
expect(Buffer.from(same.equality)).toEqual(Buffer.from(stored.id.equality))
expect(Buffer.from(other.equality)).not.toEqual(
Buffer.from(stored.id.equality),
)

const opened = (await c.decrypt(device, stored)).unwrap()
expect(opened.id).toBeInstanceOf(RcUuid)
expect(opened.id.value).toBe(text)
expect(opened.name).toBe('sensor')
})

it('refuses UUID text that is not hyphenated hex, naming the field', async () => {
const keyset = (await cipher()).defaultKeyset()
for (const bad of [
'123e4567-e89b-12d3-a456-42661417400',
'{123e4567-e89b-12d3-a456-426614174000}',
'123e4567-e89b-12d3-a456-42661417400g',
]) {
const result = await keyset.encrypt(device, {
id: new RcUuid(bad),
name: 'sensor',
})
expect(result.isErr(), bad).toBe(true)
expect(result.err()?.code, bad).toBe('ERR_INVALID_UUID')
expect(result.err()?.field, bad).toBe('id')
expect(result.err()?.record, bad).toBe('devices')
}
})

it('stores and decrypts a null under each null setting, and refuses one by default', async () => {
const nullable = record('nullable_devices', {
sealed: encrypt(kinds.uuid, { index: ['equality'], null: 'sealed' }),
sql: encrypt(kinds.uuid, { null: 'sql' }),
required: encrypt(kinds.uuid),
})
const c = await cipher()
const keyset = c.defaultKeyset()
const id = new RcUuid(text)

const empty = { sealed: null, sql: null, required: id }
const stored = (await keyset.encrypt(nullable, empty)).unwrap()
// A sealed null is stored like a value, padded to a value's length.
// A SQL null is stored as null.
const full = (
await keyset.encrypt(nullable, { sealed: id, sql: id, required: id })
).unwrap()
expect(stored.sealed).not.toBeNull()
expect(stored.sealed.ciphertext.length).toBe(full.sealed.ciphertext.length)
expect(Buffer.from(stored.sealed.equality)).not.toEqual(
Buffer.from(full.sealed.equality),
)
expect(stored.sql).toBeNull()

const opened = (await c.decrypt(nullable, stored)).unwrap()
expect(opened.sealed).toBeNull()
expect(opened.sql).toBeNull()
expect(opened.required.value).toBe(text)

// A field with the default null setting accepts no null.
const row = { sealed: id, sql: id, required: null }
// @ts-expect-error: `required` has no null setting, so it accepts no null.
const refused = await keyset.encrypt(nullable, row)
expect(refused.err()?.code).toBe('stack_encrypt::dynamic_source')
expect(refused.err()?.field).toBe('required')
expect(refused.err()?.record).toBe('nullable_devices')
})

it('refuses the UUID as a string', async () => {
const keyset = (await cipher()).defaultKeyset()
const result = await keyset.encrypt(device, {
// @ts-expect-error: a UUID field accepts an RcUuid, not its text.
id: text,
name: 'sensor',
})
expect(result.isErr()).toBe(true)
expect(result.err()?.code).toBe('recipher_js::field_type')
expect(result.err()?.field).toBe('id')

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

minor This test checks only isErr() and field, so any refusal of id passes it, such as a later stack_encrypt::dynamic_source. Also assert expect(result.err()?.code).toBe('recipher_js::field_type') and record === 'devices', as the sibling refusal tests do.

Source: code-review, mattpocock-skills:code-review · claude-opus-5-5


Generated by Claude Code

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in a868956. The test now also asserts the code recipher_js::field_type, which I checked by running it, and record === 'devices'. The addon refuses the value before it reaches the engine, so there is no engine reason in fields.reason, as in the sibling test for an integer outside its field.

expect(result.err()?.record).toBe('devices')
})

it('refuses an order index when the declaration is checked', async () => {
for (const index of ['ore', 'ope'] as const) {
const ordered = record('devices', {
id: encrypt(kinds.uuid, { index: [index] }),
})
const checked = checkDeclarations([ordered])
expect(checked.err()?.code).toBe('stack_encrypt::dynamic_plan')
expect(checked.err()?.fields.reason).toBe('index_not_admitted')
expect(checked.err()?.field).toBe('id')
expect(checked.err()?.record).toBe('devices')

const result = await Cipher.create({ records: [ordered] })
expect(result.err()?.fields.reason).toBe('index_not_admitted')
}
})
})

describe('one field', () => {
it('encrypts alone to the form it has in a whole row', async () => {
const c = await cipher()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,8 @@ async function encryptOne(
| Date
| RcDate
| RcTimestamp
| RcDecimal,
| RcDecimal
| RcUuid,
) {
return (await c.defaultKeyset().encrypt(value)).unwrap()
}
Expand Down Expand Up @@ -104,6 +105,22 @@ describe('every value in the mapping round-trips', () => {
expect(price).toBeInstanceOf(RcDecimal)
expect((price as RcDecimal).value).toBe('1.50')
})

it('a UUID, as an RcUuid', async () => {
const id = await roundTrip(
new RcUuid('123e4567-e89b-12d3-a456-426614174000'),
)
expect(id).toBeInstanceOf(RcUuid)
expect((id as RcUuid).value).toBe('123e4567-e89b-12d3-a456-426614174000')
})

it('a UUID built in uppercase, which decrypts as lowercase', async () => {
const id = await roundTrip(
new RcUuid('123E4567-E89B-12D3-A456-426614174ABC'),
)
expect(id).toBeInstanceOf(RcUuid)
expect((id as RcUuid).value).toBe('123e4567-e89b-12d3-a456-426614174abc')
})
})

describe('a wrapper class', () => {
Expand Down Expand Up @@ -635,6 +652,23 @@ describe('a ciphertext read back with a kind', () => {
expect(opened).toBe(42n)
})

it('opens a UUID with kinds.uuid, and refuses its text', async () => {
const c = await cipher()
const keyset = c.defaultKeyset()
const text = '123e4567-e89b-12d3-a456-426614174000'
const sealed = (await keyset.encrypt(new RcUuid(text))).unwrap()
const stored = Ciphertext.fromBytes(sealed.toBytes(), kinds.uuid).unwrap()
const opened: RcUuid = (await c.decrypt(stored)).unwrap()
expect(opened.value).toBe(text)

// The same UUID as a string is text, not a UUID.
const asText = (await keyset.encrypt(text)).unwrap()
const refused = await c.decrypt(
Ciphertext.fromBytes(asText.toBytes(), kinds.uuid).unwrap(),
)
expect(refused.err()?.code).toBe('recipher_js::opened_type')
})

it('refuses a value sealed as another type', async () => {
const c = await cipher()
const sealed = (await c.defaultKeyset().encrypt('text')).unwrap()
Expand Down Expand Up @@ -715,7 +749,12 @@ describe('a declared kind', () => {
// refuses it. When it merges, this test fails: change it to check that
// the null encrypts and decrypts as null.
const keyset = (await cipher()).defaultKeyset()
for (const kind of [kinds.int64, kinds.boolean, kinds.timestamp]) {
for (const kind of [
kinds.int64,
kinds.boolean,
kinds.timestamp,
kinds.uuid,
]) {
const result = await keyset.encrypt(null, { kind })
expect(result.err()?.code).toBe('recipher_js::null_value')
}
Expand Down Expand Up @@ -747,21 +786,33 @@ describe('a declared kind', () => {
}
// The type checker takes any `{ name }` as a kind, so this check is
// made when the call runs.
const unknown = await keyset.encrypt(34, { kind: { name: 'uuid' } })
const unknown = await keyset.encrypt(34, { kind: { name: 'text' } })
expect(unknown.err()?.code).toBe('recipher_js::not_a_kind')
})
})

describe('refusals', () => {
Comment thread
coderdan marked this conversation as resolved.
Resolved
it('a UUID: this version of the SDK does not encrypt one yet', async () => {
it('UUID text that is not hyphenated hex, as an Err', async () => {
const keyset = (await cipher()).defaultKeyset()
const uuid = new RcUuid('123e4567-e89b-12d3-a456-426614174000')
// @ts-expect-error: a UUID is not a `Scalar` in this version of the SDK.
const result = await keyset.encrypt(uuid)
expect(result.err()?.code).toBe('recipher_js::uuid')
expect(result.err()?.message).toContain(
'this version of the SDK does not encrypt a UUID yet',
)
for (const text of [
// One digit short.
'123e4567-e89b-12d3-a456-42661417400',
// In braces.
'{123e4567-e89b-12d3-a456-426614174000}',
// A digit that is not hex.
'123e4567-e89b-12d3-a456-42661417400g',
]) {
const pending = keyset.encrypt(new RcUuid(text))
// A synchronous throw would fail the line above. This line fails if
// `encrypt` returns a settled `Result` instead of a promise. `await`
// passes a value that is not a promise through unchanged, so the
// assertions below would still pass.
expect(pending, text).toBeInstanceOf(Promise)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

minor Add a comment to say why this assertion is here. It catches encrypt returning a settled Result synchronously: await passes a non-thenable through unchanged, so every later assertion would still pass. Without the comment, it reads as if it guards against a synchronous throw, which would already fail on line 342.

Source: mattpocock-skills:code-review · claude-opus-5-5


Generated by Claude Code

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in a868956. A comment above the assertion says it catches encrypt returning a settled Result instead of a promise. await passes a non-thenable through unchanged, so the later assertions would still pass. A synchronous throw would already fail the line before.

const result = await pending
expect(result.isErr(), text).toBe(true)
expect(result.err()?.code, text).toBe('ERR_INVALID_UUID')
expect(result.err()?.message, text).not.toContain(text)
}
})

it('a bigint outside 128 bits, with the code ERR_INTEGER_RANGE', async () => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,9 @@ serde_json = "1"
serde = { version = "1", features = ["derive"] }

[dev-dependencies]
stack-encrypt = { path = "../../../../../packages/stack-encrypt", default-features = false, features = ["dynamic", "http", "test-support"] }
# `uuid` gives the tests the engine's UUID type. The tests encrypt and decrypt
# a UUID through the engine's typed API.
stack-encrypt = { path = "../../../../../packages/stack-encrypt", default-features = false, features = ["dynamic", "http", "test-support", "uuid"] }
tokio = { version = "1", features = ["rt", "macros"] }
# The values the engine-interop tests encrypt through the engine's typed API,
# and the types the counting key source names. The versions the engine
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -227,6 +227,7 @@ fn readable(kind: ValueKind) -> bool {
| ValueKind::Date
| ValueKind::Timestamp
| ValueKind::Bytes
| ValueKind::Uuid
| ValueKind::Json
)
}
Expand Down Expand Up @@ -311,12 +312,13 @@ mod tests {
"date",
"timestamp",
"bytes",
"uuid",
"json",
] {
assert!(readable(name.parse::<ValueKind>().unwrap()), "{name}");
}
// The engine names these kinds, and no ciphertext decrypts as one.
for kind in [ValueKind::Uuid, ValueKind::Array, ValueKind::Object] {
for kind in [ValueKind::Array, ValueKind::Object] {
assert!(!readable(kind), "{kind}");
}
}
Expand Down
Loading
Loading