Repository navigation
Conversation
|
|
Important Draft PR not reviewedDraft PRs are not automatically reviewed by default.
To automatically review draft PRs, update your CodeRabbit configuration: reviews:
auto_review:
drafts: true |
coderdan
left a comment
There was a problem hiding this comment.
This is an automated code review, run at the PR author's request. It covers only this PR's own diff (base feat/recipher-js-values).
Summary. The core of this PR is sound. Each field's context is exactly [record name, field name]. Every row goes through dynamic::Planned, so the bytes are the engine's. A forged c node cannot be slipped in: ciphertext must be bytes that parse as a ciphertext, and a term can never land under c. Integer range checks are right at every width and sign, and the errors name the field, never the value. encryptField and a whole row's field are interchangeable in both directions, and every index kind round-trips. I found nothing blocking. The findings below are about error reporting, one spec deviation, a dual-package dispatch problem, and one test that does not prove what its name says.
What I ran. I built the debug addon. cargo test --locked --all-features passed (40 tests), and so did test:addon (50 tests). I wrote throwaway vitest probes (not committed) for about 60 cases: wrong field, wrong record, null and missing and extra and undefined fields, every integer width boundary, float32 narrowing, bad and reserved names, altered stored rows, and every index on every kind it allows. I also ran a CJS-plus-ESM script against a tsup build. To check the @ts-expect-error lines, I loosened StoredField and Plaintext and confirmed tsc fails (the type tests are real).
Should fix
- A declaration refusal does not name the record. See the inline comment on
crates/core/src/record.rs:177. The spec says the refusal names the record, the field and the reason. - Record calls dispatch on
instanceof RecordDeclaration. With the dual CJS/ESM build, a declaration from the other copy falls through to the value path, and the row is ignored. Inline onsrc/cipher.ts:244. - The "a field opened as another field" test does not test the context. It also shows that a wrong-context open comes back as kind
zerokms. Inline on__tests__/addon/records.test.ts:167. encryptField/decryptFieldtake one value only, and rebuild the field plan on every call. Inline onsrc/cipher.ts:254.- The plan's output keys are hand-written strings. Inline on
crates/core/src/record.rs:45.
Question / design
- A decrypted row prints its plaintext.
util.inspect(opened)prints{ n: 5n }, andconsole.log(opened)shows every decrypted field. The plan's "Results and errors" section says "a decrypted row'sinspectoutput names its fields and hides their values, as Go'sRedacteddoes." This PR returns a plain object. If the plan still holds, the record decrypt path is where that wrapper (or a non-enumerableutil.inspect.custom) belongs. If it is deferred, please list it under "Deviations from the plan". - Wrong-context opens report
zerokms. Opening a field under another field's plan, or a row under another record's name, returnskind: 'zerokms',code: 'stack_kms::retrieve_key_failed'("Forbidden: the data key is bound to another context"). A caller who switches onkindtreats that as an outage or a credential problem, and may retry.kind_ofcomes from #1775, but this PR makes the case easy to reach. Should the SDK map it tocontext_mismatch(oropen)?
Nits
- A
bigintoutside 128 bits gets no field name.2n ** 128nin auint128field, or-(2n ** 127n) - 1nin anint128field, is refused by vitaminc's reader inread_all, asERR_INTEGER_RANGEwith nofield. Inside 128 bits the refusal isrecipher::out_of_rangewith the field. Inline oncrates/node/src/lib.rs:347. - Refusals in
stored_treeandRecordPlan::fielddo not name the field. A stored index is also checked against all four index names, not the field's own. Inline oncrates/core/src/record.rs:687. one_field_opens_alone_and_a_field_alone_opens_in_a_rowchecks keys, not the value. It asserts the opened row's keys only (crates/core/tests/records.rs:272), not that the field opens to"ada@example.com". The TypeScript test covers the value, but the Rust test reads stronger than it is.
Not reported, because the ADR lists them as known non-findings: altered or removed index terms and passthrough values are not authenticated, and an SQL-null field removed in storage opens as null. My probes confirmed both still decrypt (equality replaced with garbage still opens), which is the documented behaviour.
| ) | ||
| })?; | ||
| let plan = record::plan(frame.as_protected_ref()) | ||
| .map_err(|error| Refusal::of(Kind::Declaration, &error, Some(error.payload())))?; |
There was a problem hiding this comment.
Should fix: a declaration refusal does not name the record, and a bad record name is blamed on a field.
The plan's "A record" section says a refusal "names the record, the field and the reason". Here the engine's refusal is passed on as it is, and the record name is lost. From Cipher.create({ records: [a, b, c] }) a caller cannot tell which record failed. What I saw from checkDeclarations:
record('a/b', { x }),record('', { x }),record('1x', { x })and a record name with a control character all givefield: 'x',reason: 'context_not_label'. The fault is the record's name, but the error blames fieldx.- A field named
bindorcontext_fieldis refused, but with nofieldat all (reason: 'bind'/'context_field'). Thecontext_fieldmessage ("the context field is not a string passthrough…") also reads as nonsense to someone who only named a field.
Fix: add the record's name to every Kind::Declaration refusal from build (a record property on Refusal/RecipherError, or at least in the message). Check the two reserved names in the SDK before the engine sees them, with field set. For context_not_label, saying "the record name or the field name is not a plain segment" would point at both.
There was a problem hiding this comment.
Fixed in the rewrite (ce0079f). Every refusal of a declaration now names the record (crate/src/record.rs:278-282 and :357-363).
A record name that is not a plain segment is recipher_js::record_name, with no field. The names bind and context_field are refused before the addon builds the engine's plan. The code is recipher_js::reserved_field, with field set (record.rs:72-73 and :283-285). Tests: __tests__/addon/records.test.ts:303-322.
| first: unknown, | ||
| second?: unknown, | ||
| ): Promise<Result<unknown, RecipherError>> { | ||
| if (first instanceof RecordDeclaration) { |
There was a problem hiding this comment.
Should fix: dispatching on instanceof RecordDeclaration breaks across the CJS and ESM builds, and the row is silently ignored.
The package ships both dist/index.cjs and dist/index.js, and each has its own RecordDeclaration class. Suppose a library declares its records through require and the app uses import (the plan's "a library reads a record's name, its fields…" case). Then first instanceof RecordDeclaration is false, and encrypt(user, row) goes to #encryptValues(user): it tries to encrypt the declaration as a value and drops row. I ran this against a tsup build:
encrypt with CJS declaration via ESM cipher: {"kind":"value","code":"recipher::plain_object","message":"an object is not a value: wrap it in json(..)"}
decrypt: {"kind":"value","code":"recipher::not_a_ciphertext","message":"decrypt takes a Ciphertext"}
checkDeclarations: "recipher::not_a_record"
It fails closed, but the error points the user the wrong way. Fix: brand declarations with Symbol.for('@cipherstash/recipher.record') and check the brand here, in decryptAny (line 415) and in planOf (record.ts:247). Also, when a second argument is given and the first is not a declaration, return recipher::not_a_record rather than falling through to the value path.
There was a problem hiding this comment.
Fixed in the rewrite (ce0079f). A declaration is no longer a class instance. record(..) returns a frozen plain object, { type: 'record', name, fields } (src/record.ts:97-106). The addon checks only its type property (crate/src/js.rs:209-222), so a declaration from either build works.
A plain object followed by a second argument is recipher_js::not_a_record (crate/src/js.rs:224-245), not the value path. Tests: __tests__/addon/builds.test.ts:39-42 uses a CommonJS declaration with the ECMAScript module (ESM) cipher, and __tests__/addon/records.test.ts:325-330.
| const c = await cipher() | ||
| const row = (await c.defaultKeyset().encrypt(user, ada)).unwrap() | ||
| // @ts-expect-error: a match field's stored form has no equality term. | ||
| const result = await c.decryptField(user, 'email', row.name) |
There was a problem hiding this comment.
Should fix: this test does not show that each field is sealed under its own path.
email stores equality and name stores match. The @ts-expect-error is about that shape difference, and the test asserts only isErr(). At run time stored_tree accepts the match output, and the refusal comes from key retrieval:
{"kind":"zerokms","code":"stack_kms::retrieve_key_failed","message":"Failed to send request: Forbidden: the data key is bound to another context"}
So the claim in the name holds, but nothing pins it. If the context binding broke, a refusal for some other reason would still pass. Fix: declare two fields with the same shape (two string fields with equality), open one's stored form as the other, and assert the kind and code. Add the same check for a row opened under a record with another name: record('people', user.fields) refuses today with the same error.
Separately, see the review body: zerokms is a misleading kind for "this value was sealed under another context". A caller who switches on kind would treat it as an outage.
There was a problem hiding this comment.
Fixed in the rewrite (ce0079f). The test now declares the fields a and b with the same shape: a string with equality. The test opens the stored form of b as a, and asserts the code. The test also opens a row under a record of another name, and asserts the code and the record (__tests__/addon/records.test.ts:165-187).
The code is stack_kms::retrieve_key_failed in both cases. Whether the SDK should give this case a code of its own is still open: see the comment on the review.
| * Encrypt one field of a record, for an update of that field: its stored | ||
| * form, as the field has it in a whole stored row. | ||
| */ | ||
| async encryptField< |
There was a problem hiding this comment.
Should fix: encryptField/decryptField have no array form, and the field plan is rebuilt on every call.
- The plan's "The shape of a call" section says "Every call takes one value or an array of them … and makes at most one key request however long it is". Here an update of one field across N rows is N calls and N key requests. An array does not compile (
value: Plaintext<R>[F]), and at run time it is refused as a wrong-type value. Please either takereadonly Plaintext<R>[F][](andreadonly Stored<R>[F][]) and send them as N one-field rows throughrunRecords/openRows, which is already one request, or list this under "Deviations from the plan". fieldPlanOfcallsplan.field(field)each time. That writes a plan frame and runs the engine'srecord::planon everyencryptFieldanddecryptField. The PR says "a plan is built once per declaration and cached", but that is true of whole-record plans only. Cache the field plans too, for example aMap<string, NativePlan>held in a secondWeakMapkeyed by the declaration.
There was a problem hiding this comment.
Fixed in the rewrite (ce0079f).
-
encryptFieldanddecryptFieldtake an array, in one key request (native.d.ts:247-248and:254-255). Tests:__tests__/addon/records.test.ts:189andcrate/src/record_tests.rs:333. -
The plan of each encrypted field is built once, with the record's plan, and kept with it (
crate/src/record.rs:107-108and:220-236). The addon keeps each declaration's plans for the life of the process (record.rs:171-209), tested atrecord_tests.rs:370. Each call still reads the declaration to find its plans (record.rs:184-191).
|
|
||
| /// An index a sealed field stores: the SDK's name for it, and the engine's | ||
| /// output key. | ||
| const INDEXES: [(&str, &str); 4] = [ |
There was a problem hiding this comment.
Should fix (low): the plan's output keys are hand-written strings, where the engine offers types.
INDEXES maps SDK names to "eq", "match", "ore", "ope", and "c" and "passthrough" are literals here (lines 266, 270, 599, 609, 657, 681). The null mode is copied through as an unchecked string. The engine already has these spellings as frozen wire format: dynamic::record::Output (Output::Ciphertext.key(), Output::Passthrough.key(), Output::parse) and NullMode::name(). The bytes are right today. But the brief for this step is that the plan is "written from the declaration … through the engine's types". Using Output/IndexSpec and NullMode would make a typo here a compile error rather than a refused plan. It would also let stored_row/stored_tree match on Output::Ciphertext.key() instead of "c". Only the SDK-name side (equality → eq) needs a table of its own.
There was a problem hiding this comment.
Fixed in the rewrite (ce0079f). The plan is built with the engine's types Output, IndexSpec, and NullMode (crate/src/record.rs:55-59 and :303-318). The code for stored rows matches on Output::parse, Output::Ciphertext, Output::Term, and Output::Passthrough.key() (record.rs:497-608). The null mode is read through NullMode::name().
Only the SDK's own names are written out. The index names equality, match, ore, and ope are at record.rs:76-97. The ciphertext key of a stored field is at record.rs:70.
| fn read_all(values: Vec<Unknown<'_>>) -> Result<Vec<vitaminc_protected::Buffer>> { | ||
| values | ||
| .into_iter() | ||
| .map(|value| JsRef::new(value).to_frame()) |
There was a problem hiding this comment.
Nit: a bigint outside 128 bits is refused here, with no field name.
2n ** 128n in a uint128 field, or -(2n ** 127n) - 1n in an int128 field, never reaches conform. vitaminc's reader throws, and the result is { kind: 'value', code: 'ERR_INTEGER_RANGE', message: 'BigInt is outside the signed/unsigned 128-bit range' }, with no field. One bit inside that range, the same mistake gives recipher::out_of_range with field set. The value is not leaked, so this is only about consistency. You could check bigint ranges per field in TypeScript before the call, or map the reader's error onto the field it was reading, if JsRef can report the path.
There was a problem hiding this comment.
Fixed in the rewrite (ce0079f). The refusal now names the field: 2n ** 128n in age gives ERR_INTEGER_RANGE with field: 'age' (__tests__/addon/records.test.ts:254-261). When the bridge refuses a row, read_row reads each field again to find the one at fault (crate/src/cipher.rs:609-623). From the code, a getter on a field of a refused row therefore runs a second time.
| .iter() | ||
| .find(|(index, _)| *index == key) | ||
| .map(|(_, output)| *output) | ||
| .ok_or_else(|| misfit("an output the record does not declare"))?; |
There was a problem hiding this comment.
Nit: several refusals in stored_tree and RecordPlan::field do not name the field.
misfit(..)never setsfield. "a field the record does not declare", "an output that is not bytes" and "an output the record does not declare" all come back withfield: undefined. The same goes for theCiphertext::from_bytesrefusal at line 680.RecordPlan::field(line 200) refuses an unknown name withfield: None. The message names the record but not the field that was asked for.- This lookup checks the key against all four index names, not against the field's own
indexes. So{ email: { ciphertext, equality, match } }is accepted and opens, even thoughemaildeclares no match index. That is harmless, because terms are not read to decrypt. But the message "the record does not declare" suggests a per-field check that is not there. Either checkfield.indexesor reword the message.
There was a problem hiding this comment.
Fixed in the rewrite (ce0079f). The messages were reworded in ea69a41.
- Each refusal in
stored_treenames its field, except the one for a stored row that is not an object (crate/src/record.rs:541-604). TheCiphertext::from_bytesrefusal names the field too (record.rs:583-588). RecordPlan::fieldnames the field that was asked for (record.rs:263-268).- An index term is checked against the field's own indexes (
record.rs:595-604). Test:__tests__/addon/records.test.ts:332-342.
44064c7 to
a94a1a7
Compare
82b9483 to
6937e90
Compare
6937e90 to
a0479fc
Compare
a94a1a7 to
30f1d26
Compare
a0479fc to
17a20ff
Compare
30f1d26 to
a251427
Compare
17a20ff to
68dd83e
Compare
a251427 to
a5555b7
Compare
Encrypting one value at a time does not fit how applications store data: in rows, with some fields encrypted and searchable and some not. record(..), encrypt(..) and passthrough() declare a record as plain, frozen data, recognised by its type property, so a declaration from the CommonJS build works with a cipher from the ESM build. The addon builds the engine's plan from a declaration with the engine's own types, once for each declaration, and encrypts and decrypts whole rows, one field, or an array of one field through dynamic::Planned, so the stored bytes are the engine's and many rows make one key request. Each field is sealed under its field path, the record's name and then the field's name. A decrypted row goes through open_rows_in, beside the skeleton's open_in: both run the one confined! match, so whether a decrypt is confined to the default keyset is decided in one place for ciphertexts and rows alike, and a test pins it for rows. A refusal names the record and, where there is one, the field, with a recipher_js:: code. A decrypted row's inspect shows its field names and hides their values. RecordPlan derives Debug: it holds only declaration data. The record overloads of encrypt and decrypt, encryptField, decryptField, Cipher.create(options) and checkDeclarations are written on the Rust methods as ts_type strings, so native.d.ts stays the public type, and each returns its Result from Rust. src/record.ts never loads the addon, because the generated declarations import its types; checkDeclarations therefore lives with the other native entry points in src/cipher.ts, with a stand-in for an addon that did not load. Nothing is released, so the binding interface stays 1. Closes #1813 Closes #1803
a5555b7 to
fc5c851
Compare
68dd83e to
ce0079f
Compare
Value was Scalar | JsonMarker in src/value-types.ts, so passing a plain object to encrypt gave an error that named JsonMarker, a brand the package never exports, rather than the Json a caller should reach for. Value is now declared in native-header.d.ts as Scalar | Json, beside the generated Json class, which the header can name without an import, and src/values.ts re-exports it. The marker stays the brand, so a plain object is still not a Json or a Value, and value-types.ts still imports nothing, so the declarations do not import themselves. A type test pins both: the @ts-expect-error lines in type-tests/values.ts keep it as strict, and a unit test compiles a snippet with the TypeScript compiler and checks the messages name Value and Json and never JsonMarker.
…types are The header imported the record types from src/record.ts, so that module could not load the addon, and checkDeclarations had moved to src/cipher.ts, away from the declarations it checks. The values had solved the same problem another way, with an import-free value-types.ts. Records now follow the values: the types the generated signatures name (RecordDeclaration, Plaintext, Stored, SealedFieldName, CipherOptions and the field types) are in an import-free src/record-types.ts, which the header imports. checkDeclarations is back in src/record.ts, beside the declarations it checks, and loads the addon from there, with the same stand-in that returns the load error when the addon did not load. The package's exports are unchanged. AGENTS.md states the rule: one *-types.ts module per topic, imported by the header, never loading the addon.
Bring the records pull request up to date with the values branch, which now has next merged into it. next's engine replaced ValueFrame with vitaminc's Frame and OwnedFrame. What the resolution kept from each side: - cipher.rs: this branch's `confined!` form of `open_in`, and its new `open_rows_in`, with the values branch's OwnedFrame in place of ValueFrame. The values branch's `with_engine!` match is the same logic that `confined!` already holds, so it is dropped. - The records feature is kept whole: plans from declarations, rows through the engine's Planned, stored rows, encryptField and their tests. frames.rs, record.rs, record_tests.rs and the rest of cipher.rs did not conflict but named ValueFrame, so they now use OwnedFrame: `OwnedFrame::from_buffer` for a split entry and a declaration's bytes, `frame().kind()` for a value's kind, `frame().as_bytes()` for a frame's bytes, and tests that compare two values through Frame's constant-time `==`. - AGENTS.md: this branch's recipher-js entry (records) and next's languages/golang entry (wasmtestrun). - Cargo.lock needed no change: `cargo metadata --locked` passes.
|
I merged the updated What the merge changed:
Checks run on the merge, all passing:
The UUID change is a draft pull request into this branch. |
Bring the records pull request up to date with the values pull request, which renamed the wrapper classes to RcDate, RcTimestamp, RcDecimal and RcUuid, and moved the JSON conversion from the addon into the value bridge. What the resolution kept from each side: - crate/Cargo.toml: this branch's napi9 feature, for the key of a decrypted row's `inspect`, with the values branch's wording: the walk is the value bridge's, and the serde is the frame's. - src/values.ts: the values branch's layout, each wrapper constant with its type beside it and the stand-in that constructs as the class does. This branch's `Value` stays the addon's `Native.Value`. - type-tests/values.ts: both sides' imports, under the new class names. - AGENTS.md: this branch's entry, with the values branch's two sentences: the bridge converts JSON documents, and a wrapper class's constructor throws for an argument that is not a string. What the merge changed in the records code, which did not conflict: - `__tests__/addon/records.test.ts` and `type-tests/records.ts` name the classes RcDate, RcDecimal and RcTimestamp. - The test that pins the help of every error has an entry for each error this branch adds. Its match has no wildcard, so it did not compile without them. - Three doc comments said vitaminc refuses a value or reads a `bigint`. The value bridge does, so they name it. The records code calls no JSON function: a record refuses a `json` field. Its arrays of records and rows go through `js::elements`, so a hole in one is now `recipher_js::sparse_array`. Cargo.lock and `native.d.ts` needed no change beyond the merge: `cargo metadata --locked` passes, and `build:debug` leaves the tree as it is.
Rewrite the comments, doc comments and Markdown that the records work added, so that each passes the plain-language checker. No code changes. - One idea in each sentence, and each sentence names its subject. - A doc defines "record declaration", "plan" and "stored row" where it first uses the term. - The user-facing docs say "encrypt" and "decrypt", and "accepts" for what a field or a function allows. - `native.d.ts` is regenerated, because the build copies the doc comments of the `#[napi]` items into it.
A TypeScript developer reads these messages without knowing the engine. Several messages stated a rule, such as "a row is an object of the record's fields". Each message now says what was wrong with the declaration, the row, or the stored row that was passed. The README says "encrypted field" and "index term", so the messages now use those words in place of "sealed field", "output", and "term". No error code, error field, or refusal changes. Only the text changes. - `not_a_record`, `declaration`, and `not_a_row` say what the value is not. - `record_name` and `context` name the record's name and the field path. The help of `record_name` says "contains". - `no_field` says "encrypted field". - `field_type` puts the field's declared kind in backticks. - Each detail of `not_a_stored_row` is a clause that says what is wrong with the stored row.
|
This replies to review 6030323967. Status of the automated review of 23 November, at ea69a41. Errors no longer have a Findings 1 to 5, 8, and 9 are fixed. Each inline comment has the details. Two more are fixed:
Finding 7 is not resolved. A field opened under another field's path still gives By the code alone, a caller cannot tell this case from a failure of the key service. Whether the SDK maps the case to a code of its own needs your decision. Nobody has checked whether the key service's error says which case it is. |
…and interface 2 This merge brings two fixes from the values branch. The docs and the error message now say that this version of the SDK does not encrypt a UUID yet. The text no longer says that the engine has no UUID type. The binding interface number is now 2, so the TypeScript refuses an older addon build when it loads. One file conflicted. In `type-tests/values.ts`, this branch adds checks for plain objects before the UUID check. The resolution keeps those checks and takes the new comment on the UUID check.
The second review of #2019 found the plan out of step with the code. - The wrapper classes are RcDate, RcTimestamp, RcDecimal, and RcUuid in #1775, #1776, and #1996. The plan used vitaminc's Vc names. The plan now uses the Rc names, and says once that #1775 renamed them. - The JSON number rules are now one table, with a row for each range of whole numbers. Each range includes both ends. The table shows the new refusal below -2^63. That refusal says the integer has no exact form. The plan also says that NaN and the infinities are refused. - The round trip of 2^64 - 1 is tested on the native build only. The plan now names that test, and says the wasm build is planned. - The UUID cell no longer repeats the refusal before #1996. - The header now gives the status. Step 1 is built. The next steps are in open pull requests.
This brings in two commits from #1775. The first gives the bigint range in the json() docs. The second refuses a whole number below -2^63 and above -2^64 with its own message, instead of asking for a bigint. The merge had no conflicts.
The values branch now has next, encrypts one value through the engine's
dynamic::value::encrypt, and takes a declared kind as encrypt's second
argument. On this branch encrypt's second argument is already the row of
a record. The merge keeps both: when the first argument is a record
declaration, the second is its row, or its array of rows. Otherwise the
second is the options of the value, { kind }. A plain object with a
second argument is still refused with recipher_js::not_a_record.
The value module is gone, since nothing on this branch used OneValue
outside the single-value path. native.d.ts is the build:debug output.
Summary
Closes #1813
Closes #1803
This PR adds records to
@cipherstash/recipher. A record is a declaration like a table's: a name, and for each field whether it is encrypted, encrypted with search indexes, or passed through unencrypted. A program declares a record once, then encrypts and decrypts whole rows, or one field at a time. Rows go through the engine'sdynamic::Planned, so the stored bytes are the engine's, and many rows make one key request.An index is a search term stored beside a field's ciphertext. Querying with those terms comes later.
It follows #1774's design: every native method builds its
Resultin Rust, and the record signatures are written on the Rust methods, so the generatednative.d.tsis the public type.The package is private and not published, so there is no changeset.
Changes
Declaring.
record(name, fields),encrypt(kinds.x, { index, null })andpassthrough<T>()make plain, frozen data:{ type: 'record', name, fields }. The addon recognises a declaration by itstype: 'record'property, so a declaration from the CommonJS build works with a cipher from the ESM build.The plan.
crate/src/record.rsreads a declaration through vitaminc's frame serde and builds the engine's plan with the engine's own types (FieldPlan,Plan,Output,IndexSpec,NullMode,ValueKind). The only table of the SDK's own maps the index names (equality,match,ore,ope) toIndexSpec. Each field is encrypted under its field path: the record's name, then the field's name. A plan is built once per declaration and kept.RecordPlanderivesDebug, because it holds only declaration data.Rows.
keyset.encrypt(user, row | rows),cipher.decrypt(user, stored | stored[])andkeyset.decrypt. The engine'sdynamic::readreads each value as its field's kind before the engine sees it.One field.
keyset.encryptField(user, 'email', value | values)anddecryptFieldrun the plan of that field alone, under the same field path. A field encrypted alone has the same bytes as in a whole row.Checking declarations.
checkDeclarations(records)checks declarations with no credentials, and returns aResult.Cipher.create({ records })checks them before it looks for credentials.Signatures. The record overloads of
encryptanddecrypt,encryptField,decryptField,Cipher.create(options?: CipherOptions)andcheckDeclarationsarets_type,ts_args_typeandts_return_typestrings on the Rust methods, and each returns itsResultfrom Rust.Record types, as the value types are. The types those signatures name (
RecordDeclaration,Plaintext,Stored,SealedFieldName,CipherOptionsand the field types) are in an import-freesrc/record-types.ts, whichnative-header.d.tsimports.src/record.tsholds the declaration builders andcheckDeclarations, which loads the addon from there, with a stand-in that returns the load error when the addon did not load. The package's exports are unchanged.AGENTS.mdstates the rule: one*-types.tsmodule per topic, imported by the header, never loading the addon, because a module that did would make the declarations import themselves.Type errors name
JsonandValue.Valueis now declared innative-header.d.tsasScalar | Json, beside the generatedJsonclass, instead of asScalar | JsonMarkerinsrc/value-types.ts. Passing a plain object toencryptnow gives an error that namesValueandJson, neverJsonMarker. The marker is still the brand, so a plain object is still not aJsonor aValue.Keyset confinement. A decrypted row goes through
open_rows_in, beside #1774'sopen_in. Both run oneconfined!match, so whether a decrypt is confined to the default keyset is decided in one place for ciphertexts and rows. A Rust test checks that a keyset refuses another keyset's row withstack_encrypt::foreign_keyset, and that the cipher opens it.AGENTS.md. The recipher-js entry now lists the record declarations insrc/record.ts.Errors. A refusal names the record in
error.recordand, where there is one, the field inerror.field. New codes includerecipher_js::not_a_record,declaration,reserved_field,record_name,no_field,not_a_row,field_type,not_a_stored_rowandengine_result.A decrypted row hides its values when inspected.
console.log(row)printsusers { email: [hidden], .. }. The crate turns on napi'snapi9feature forSymbol.for.The binding interface number stays 1: nothing is released.
Verification
Run locally on macOS (arm64), Rust 1.94.1, Node 24, pnpm 10.33.2, at this PR's head:
cargo fmt --all --check: clean.cargo test --locked --all-features:recipher-js44 unit tests and 2 boundary tests passed;recipher-value-napi33 unit tests andtests/node.rspassed.cargo clippy --locked --all-targets --all-features -- -D warnings: clean.build:debug:native.d.tsregenerated and committed; the build leaves no other change.test:addon: 81 passed.test(vitest, thentscwith the type tests): 27 passed, typecheck clean.build(tsup, including the declaration bundle): built. The type tests intype-tests/records.tsare unchanged and pass against the generated signatures.bench-index-expressions,migration-fixture-client, andcheck-auth-npm-changeset, which cannot load@changesets/parselocally).Not run: anything against a live ZeroKMS, and the conformance profiles (there is no TypeScript conformance runner yet, #1479). CI results are in the checks.
Review notes
New type tests.
type-tests/values.tsadds@ts-expect-errorlines:keyset.encrypt({ a: 1 }), and a plain object as aJsonand as aValue. It also checks thatjson(..)returns both.__tests__/unit/type-messages.test.tscompiles a snippet with the TypeScript compiler and checks that the messages nameValueandJsonand neverJsonMarker.No
jsonrecord field. The engine refuses a plan field of typejsonunless it names an EQL target. It comes with the EQL extension.Opening a field as another field fails at the key service, so the engine reports a key-retrieval failure, not a context mismatch. A check of the stored context before any key request would let the SDK say so.
The engine's
TargetResolveris not passed yet. The crate runsPlanned::new, which usesNoTargets.Related