diff --git a/.changeset/20141-masked-on-read-field-types-declared.md b/.changeset/20141-masked-on-read-field-types-declared.md new file mode 100644 index 00000000000..e5efe4b67be --- /dev/null +++ b/.changeset/20141-masked-on-read-field-types-declared.md @@ -0,0 +1,34 @@ +--- +'@objectstack/spec': minor +'@objectstack/objectql': patch +--- + +`@objectstack/spec/data` declares which field types are masked on read — `MASKED_ON_READ_FIELD_TYPES` and `isMaskedOnReadFieldType(fieldType, managedBy)` (#20141) + +Clause-②: yes + +The protocol used to state this only in prose (the `FieldType` comments), so +two consumers each carried their own hand-written copy: objectql's +`collectMaskedReadFields` (the generic read mask and the echoed-mask write +guard) and the renderer's masked-type set. The fact is now declared once: + +- `MASKED_ON_READ_FIELD_TYPES` — a deep-frozen per-type rule table: + `secret` is masked on every object; `password` is masked on every object + except `managedBy: 'better-auth'` ones. Each masked type carries its own + `exemptManagedBy` list, typed against `ObjectSchema.managedBy`'s enum. +- `isMaskedOnReadFieldType(fieldType, managedBy)` — the one reading of that + table. `managedBy` is a required argument (pass `undefined` when the object + has none), and exemptions fail closed: an absent or unlisted `managedBy` + never unmasks a masked type. + +`@objectstack/objectql`: `collectMaskedReadFields` and +`collectMaskedPasswordFields` now ask `isMaskedOnReadFieldType` instead of +carrying their own `type === 'secret'` / `'password'` arms. No behaviour +change: the masked-on-read answer is identical for every `FieldType` × +`managedBy` cell, pinned by a table test. + +`@objectstack/spec`: `ObjectSchema.create()`'s author-time warning for a `password` field on a non-auth object now reads its `managedBy` exemption from `isMaskedOnReadFieldType` instead of hard-coding `'better-auth'`, so it follows the declaration; which objects and fields warn is unchanged. + +A client that renders credential fields (show the mask, offer no copy) should +derive its set from `isMaskedOnReadFieldType` rather than keep its own list, +so the server's mask and the client's cannot drift apart. diff --git a/packages/objectql/src/secret-fields.test.ts b/packages/objectql/src/secret-fields.test.ts index e55ae919286..96e0429ceea 100644 --- a/packages/objectql/src/secret-fields.test.ts +++ b/packages/objectql/src/secret-fields.test.ts @@ -21,7 +21,12 @@ import { collectMaskedPasswordFields, collectMaskedReadFields, } from './secret-fields.js'; -import { SECRET_MASK as SPEC_SECRET_MASK } from '@objectstack/spec/data'; +import { + SECRET_MASK as SPEC_SECRET_MASK, + FieldType, + ObjectSchema, + isMaskedOnReadFieldType, +} from '@objectstack/spec/data'; import type { ICryptoProvider, CryptoHandle, CryptoContext } from '@objectstack/spec/contracts'; // ---- minimal stub driver (equality-only WHERE) ---------------------------- @@ -659,3 +664,91 @@ describe('objectql aggregate() rejects credential fields (ADR-0100 / #3171)', () ).rejects.toThrow(/password/); }); }); + +/** + * [#20141] The masked-on-read answer for EVERY `FieldType × managedBy` cell — + * the security floor of lifting the fact into `@objectstack/spec`. + * + * Two pins, deliberately separate: + * + * - **The floor.** The expected column is written out here (secret always; + * password unless better-auth; nothing else), NOT read from the spec + * declaration: a pin that imported the answer to check the answer would be + * green through any edit to it. Which stored values leave the engine in + * clear is a security decision, so an edit to the declaration has to turn + * this red and be read. + * - **The agreement.** For every cell, the runtime collectors and the spec + * predicate give the same answer. This is what goes red when the runtime + * grows its own copy again (a `def.type === …` arm) instead of deriving. + * objectui keeps an interim copy until its re-bind card points it at the + * same declaration; from then on a runtime-only answer is a field masked + * by the server and drawn in clear by the client. + */ +describe('[#20141] masked-on-read: every FieldType × managedBy cell, derived from the spec declaration', () => { + const FIELD_TYPES: readonly string[] = FieldType.options; + const MANAGED_BY_BUCKETS: readonly string[] = ( + ObjectSchema.shape.managedBy as unknown as { unwrap(): { options: readonly string[] } } + ).unwrap().options; + const ABSENT = Symbol('managedBy key absent'); + const MANAGED_BY: readonly unknown[] = [ABSENT, ...MANAGED_BY_BUCKETS, undefined, null, 'system', 'not-a-bucket']; + // Unvalidated metadata reaches these collectors (stored rows, hand-built + // schemas), so the table also covers types no FieldType names. + const OFF_ENUM_TYPES: readonly unknown[] = [undefined, null, 42, ['secret'], '', 'constructor', 'toString', + '__proto__', 'SECRET', 'Password']; + + const objectWith = (type: unknown, managedBy: unknown): any => ({ + name: 'cell', + ...(managedBy === ABSENT ? {} : { managedBy }), + fields: { f: { type } }, + }); + const label = (type: unknown, managedBy: unknown) => + `${JSON.stringify(type) ?? String(type)} × ${managedBy === ABSENT ? '(absent)' : String(managedBy)}`; + const specManagedBy = (managedBy: unknown) => (managedBy === ABSENT ? undefined : managedBy); + + it('reads the live enums (the table below is not over an empty population)', () => { + expect(FIELD_TYPES).toContain('secret'); + expect(FIELD_TYPES).toContain('password'); + expect(FIELD_TYPES.length).toBeGreaterThan(40); + expect(MANAGED_BY_BUCKETS).toContain('better-auth'); + expect(MANAGED_BY_BUCKETS.length).toBeGreaterThan(1); + }); + + it('the floor: secret is masked on every object, password on every object but better-auth, nothing else anywhere', () => { + let cells = 0; + let masked = 0; + for (const type of [...FIELD_TYPES, ...OFF_ENUM_TYPES]) { + for (const managedBy of MANAGED_BY) { + const expected = type === 'secret' || (type === 'password' && managedBy !== 'better-auth'); + const schema = objectWith(type, managedBy); + expect(collectMaskedReadFields(schema).includes('f'), label(type, managedBy)).toBe(expected); + expect(collectMaskedPasswordFields(schema).includes('f'), `password half: ${label(type, managedBy)}`) + .toBe(expected && type === 'password'); + cells += 1; + if (expected) masked += 1; + } + } + expect(cells).toBe((FIELD_TYPES.length + OFF_ENUM_TYPES.length) * MANAGED_BY.length); + // secret: every managedBy row; password: every row but one. + expect(masked).toBe(MANAGED_BY.length * 2 - 1); + }); + + it('the agreement: collectMaskedReadFields answers exactly what the spec predicate answers, cell for cell', () => { + for (const type of [...FIELD_TYPES, ...OFF_ENUM_TYPES]) { + for (const managedBy of MANAGED_BY) { + const schema = objectWith(type, managedBy); + const spec = isMaskedOnReadFieldType(type, specManagedBy(managedBy)); + expect(collectMaskedReadFields(schema).includes('f'), label(type, managedBy)).toBe(spec); + expect(collectMaskedPasswordFields(schema).includes('f'), `password half: ${label(type, managedBy)}`) + .toBe(spec && type === 'password'); + } + } + }); + + it('keeps declaration order and skips empty field definitions on a mixed object', () => { + const fields = { a: { type: 'text' }, b: { type: 'secret' }, c: { type: 'password' }, d: null, e: { type: 'secret' } }; + expect(collectMaskedReadFields({ name: 'mixed', fields } as any)).toEqual(['b', 'c', 'e']); + expect(collectMaskedReadFields({ name: 'mixed', managedBy: 'better-auth', fields } as any)).toEqual(['b', 'e']); + expect(collectMaskedPasswordFields({ name: 'mixed', fields } as any)).toEqual(['c']); + expect(collectMaskedPasswordFields({ name: 'mixed', managedBy: 'better-auth', fields } as any)).toEqual([]); + }); +}); diff --git a/packages/objectql/src/secret-fields.ts b/packages/objectql/src/secret-fields.ts index 708318ed668..4a92749a5bc 100644 --- a/packages/objectql/src/secret-fields.ts +++ b/packages/objectql/src/secret-fields.ts @@ -37,7 +37,7 @@ * ruling of 2026-08-12 on #7728. */ -import type { ServiceObject } from '@objectstack/spec/data'; +import { isMaskedOnReadFieldType, type ServiceObject } from '@objectstack/spec/data'; /** * Prefix marking a persisted field value as a `sys_secret` handle ref rather @@ -160,6 +160,18 @@ export class EmptyCredentialWriteError extends Error { * generic read path: every `secret` field, plus every `password` field — the * latter only when the object is **not** `managedBy: 'better-auth'`. * + * [#20141] That sentence DESCRIBES the answer; it does not decide it. Which + * types are masked, and which `managedBy` buckets exempt which type, is declared + * once in `@objectstack/spec/data` (`MASKED_ON_READ_FIELD_TYPES`, read through + * `isMaskedOnReadFieldType`), and this collector asks that predicate per field. + * objectui keeps its interim `MASKED_FIELD_TYPES` copy until its own re-bind + * card lands; after that it reads this same declaration, and the server's mask + * and the client's cannot drift apart. ⛔ Do not add a `def.type === …` arm + * here: a type masked here and not in the declaration is a second copy, and + * once the renderer derives it is a field masked by the server and drawn in + * clear by the client. Change the declaration instead; the table test in + * `secret-fields.test.ts` pins every `FieldType × managedBy` answer. + * * The better-auth exemption is deliberate: the auth subsystem reads its identity * rows through the engine's find/findOne, and masking a credential column there * would break login. Today no identity object even declares a `password`-typed @@ -172,12 +184,10 @@ export class EmptyCredentialWriteError extends Error { export function collectMaskedReadFields(schema: ServiceObject | undefined | null): string[] { const fields = (schema as any)?.fields as Record | undefined; if (!fields) return []; - const isBetterAuth = (schema as any)?.managedBy === 'better-auth'; + const managedBy: unknown = (schema as any)?.managedBy; const out: string[] = []; for (const [name, def] of Object.entries(fields)) { - if (!def) continue; - if (def.type === 'secret') out.push(name); - else if (def.type === 'password' && !isBetterAuth) out.push(name); + if (def && isMaskedOnReadFieldType(def.type, managedBy)) out.push(name); } return out; } @@ -186,6 +196,10 @@ export function collectMaskedReadFields(schema: ServiceObject | undefined | null * [#8559] Collect the names of `password`-typed fields on a **generic** * (non-`better-auth`) object — exactly the `password` half of * {@link collectMaskedReadFields}, kept beside it so the two cannot drift. + * [#20141] It asks the same spec predicate (`isMaskedOnReadFieldType`) for the + * exemption rather than restating it, so "the password fields that are masked" + * has one answer; the `'password'` arm is this collector's own scope, not a + * copy of the masked set. * * This is the scope of the empty-string refusal's `password` arm * ({@link EmptyCredentialWriteError}): the ruling covers the fields that share @@ -202,10 +216,10 @@ export function collectMaskedReadFields(schema: ServiceObject | undefined | null export function collectMaskedPasswordFields(schema: ServiceObject | undefined | null): string[] { const fields = (schema as any)?.fields as Record | undefined; if (!fields) return []; - if ((schema as any)?.managedBy === 'better-auth') return []; + const managedBy: unknown = (schema as any)?.managedBy; const out: string[] = []; for (const [name, def] of Object.entries(fields)) { - if (def && def.type === 'password') out.push(name); + if (def && def.type === 'password' && isMaskedOnReadFieldType(def.type, managedBy)) out.push(name); } return out; } diff --git a/packages/spec/api-surface/data.json b/packages/spec/api-surface/data.json index d3ca08260d5..696401f4046 100644 --- a/packages/spec/api-surface/data.json +++ b/packages/spec/api-surface/data.json @@ -301,6 +301,7 @@ "FieldSchema (const)", "FieldType (const)", "FieldType (type)", + "FieldTypeReadMask (interface)", "FileLikeValue (type)", "FileLikeValueSchema (const)", "FilePersistenceConfig (type)", @@ -401,6 +402,7 @@ "LocationValueSchema (const)", "LogicalOperatorKey (type)", "MANAGED_WRITE_VERB_AFFORDANCE (const)", + "MASKED_ON_READ_FIELD_TYPES (const)", "MAX_BULK_PER_ROW_HOOK_ROWS (const)", "MEASURE_FIELD_TYPES (const)", "MONGO_OPTIONS_CREDENTIAL_PATHS (const)", @@ -793,6 +795,7 @@ "isInjectedColumnDefinition (function)", "isKnownFilterToken (function)", "isLegacyApiMethod (function)", + "isMaskedOnReadFieldType (function)", "isMultiValueField (function)", "isNowDefaultToken (function)", "isOrganizationUnique (function)", diff --git a/packages/spec/export-origins/data.json b/packages/spec/export-origins/data.json index f8eba3252ea..f258cf3e509 100644 --- a/packages/spec/export-origins/data.json +++ b/packages/spec/export-origins/data.json @@ -292,6 +292,7 @@ "FieldScaleMeta": "src/data/field-scale.ts#FieldScaleMeta (interface)", "FieldSchema": "src/data/field.zod.ts#FieldSchema (const)", "FieldType": "src/data/field.zod.ts#FieldType (type)", + "FieldTypeReadMask": "src/data/masked-field-types.ts#FieldTypeReadMask (interface)", "FileLikeValue": "src/data/field-value.zod.ts#FileLikeValue (type)", "FileLikeValueSchema": "src/data/field-value.zod.ts#FileLikeValueSchema (const)", "FilePersistenceConfig": "src/data/driver/memory.zod.ts#FilePersistenceConfig (type)", @@ -391,6 +392,7 @@ "LocationValueSchema": "src/data/field-value.zod.ts#LocationValueSchema (const)", "LogicalOperatorKey": "src/data/filter.zod.ts#LogicalOperatorKey (type)", "MANAGED_WRITE_VERB_AFFORDANCE": "src/data/managed-api-affordance.ts#MANAGED_WRITE_VERB_AFFORDANCE (const)", + "MASKED_ON_READ_FIELD_TYPES": "src/data/masked-field-types.ts#MASKED_ON_READ_FIELD_TYPES (const)", "MAX_BULK_PER_ROW_HOOK_ROWS": "src/data/bulk-write-hook-conformance.ts#MAX_BULK_PER_ROW_HOOK_ROWS (const)", "MEASURE_FIELD_TYPES": "src/data/aggregation-policy.ts#MEASURE_FIELD_TYPES (const)", "MONGO_OPTIONS_CREDENTIAL_PATHS": "src/data/driver/common.zod.ts#MONGO_OPTIONS_CREDENTIAL_PATHS (const)", @@ -780,6 +782,7 @@ "isInjectedColumnDefinition": "src/data/injected-system-column-provenance.ts#isInjectedColumnDefinition (function)", "isKnownFilterToken": "src/data/context-tokens.zod.ts#isKnownFilterToken (function)", "isLegacyApiMethod": "src/data/api-derivation.ts#isLegacyApiMethod (function)", + "isMaskedOnReadFieldType": "src/data/masked-field-types.ts#isMaskedOnReadFieldType (function)", "isMultiValueField": "src/data/field-value.zod.ts#isMultiValueField (function)", "isNowDefaultToken": "src/data/default-value-tokens.ts#isNowDefaultToken (function)", "isOrganizationUnique": "src/data/field.zod.ts#isOrganizationUnique (function)", diff --git a/packages/spec/src/data/field.zod.ts b/packages/spec/src/data/field.zod.ts index 47216c9bbec..1d564b908eb 100644 --- a/packages/spec/src/data/field.zod.ts +++ b/packages/spec/src/data/field.zod.ts @@ -44,15 +44,17 @@ export const FieldType = z.enum([ // rest but masked to SECRET_MASK on read — the auth subsystem's one-way // hashing applies only to its own identity tables, never to an authored // 'password' field. Prefer 'secret' for reversible machine credentials. See - // ADR-0100. + // ADR-0100. Which types are masked on read, and the `managedBy: 'better-auth'` + // exemption for 'password', is DECLARED in `MASKED_ON_READ_FIELD_TYPES` + // (`./masked-field-types`) — this prose describes it, the table decides it. 'text', 'textarea', 'email', 'url', 'phone', 'password', // Secret — reversible, encrypted-at-rest value (DB password, API key, token). // UNLIKE 'password' (masked-on-read but plaintext at rest, or one-way hashed // inside the auth subsystem), a 'secret' is round-tripped: the engine encrypts // it on write via the registered ICryptoProvider, stores the ciphertext handle // in `sys_secret`, persists only an opaque ref on the row, and masks it on - // read. Fail-closed: no provider ⇒ writes throw rather than persist cleartext. - // See ADR-0100. + // read (always — `MASKED_ON_READ_FIELD_TYPES`). Fail-closed: no provider ⇒ + // writes throw rather than persist cleartext. See ADR-0100. 'secret', // Rich Content 'markdown', 'html', 'richtext', diff --git a/packages/spec/src/data/index.ts b/packages/spec/src/data/index.ts index 8b5e9760cde..46cf2bf868c 100644 --- a/packages/spec/src/data/index.ts +++ b/packages/spec/src/data/index.ts @@ -136,6 +136,12 @@ export * from './field.zod'; // the encrypted-FIELD path cannot desynchronise from the mask it sees on the // settings REST path. export * from './secret-mask'; +// Which field types are masked on read (ADR-0100) — one per-type rule table, +// `managedBy` exemption included, read through one predicate (#20141). objectql's +// `collectMaskedReadFields` and `ObjectSchema.create()`'s password warning derive +// from it; objectui keeps its interim `MASKED_FIELD_TYPES` copy until its own +// re-bind card lands, and derives from it after that. +export * from './masked-field-types'; // The unknown-authoring-key lint's CORE — comparator, finding shape, curated // guidance tables (#3786). Kept frontend-safe: the stack WALKER that imports // every schema lives in kernel/metadata-authoring-lint.ts, so this subpath's diff --git a/packages/spec/src/data/masked-field-types.test.ts b/packages/spec/src/data/masked-field-types.test.ts new file mode 100644 index 00000000000..197142ddeb1 --- /dev/null +++ b/packages/spec/src/data/masked-field-types.test.ts @@ -0,0 +1,99 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [#20141] The masked-on-read field-type declaration (ADR-0100): its content, + * its vocabulary, its immutability, and the predicate that reads it. + * + * The content pin restates the table on purpose. Importing the constant to + * check the constant would be green by construction; which stored values leave + * the engine in clear is a security decision, so an edit to the table must + * show up here as a red line someone has to read. + */ + +import { describe, it, expect } from 'vitest'; + +import { FieldType } from './field.zod'; +import { ObjectSchema } from './object.zod'; +import { MASKED_ON_READ_FIELD_TYPES, isMaskedOnReadFieldType } from './masked-field-types'; + +const FIELD_TYPES: readonly string[] = FieldType.options; +const MANAGED_BY_BUCKETS: readonly string[] = ( + ObjectSchema.shape.managedBy as unknown as { unwrap(): { options: readonly string[] } } +).unwrap().options; + +describe('MASKED_ON_READ_FIELD_TYPES — the declaration (ADR-0100 / #20141)', () => { + it('declares exactly `secret` (always) and `password` (exempt on better-auth objects)', () => { + expect(JSON.parse(JSON.stringify(MASKED_ON_READ_FIELD_TYPES))).toEqual({ + secret: { exemptManagedBy: [] }, + password: { exemptManagedBy: ['better-auth'] }, + }); + }); + + it('every key is a FieldType member', () => { + expect(FIELD_TYPES.length).toBeGreaterThan(40); // the enum really was read + for (const type of Object.keys(MASKED_ON_READ_FIELD_TYPES)) { + expect(FIELD_TYPES).toContain(type); + } + }); + + it('every exemption is a value ObjectSchema.managedBy declares', () => { + expect(MANAGED_BY_BUCKETS).toContain('better-auth'); // the enum really was read + for (const rule of Object.values(MASKED_ON_READ_FIELD_TYPES)) { + for (const bucket of rule!.exemptManagedBy) { + expect(MANAGED_BY_BUCKETS).toContain(bucket); + } + } + }); + + it('is deep-frozen: no consumer can change what another one masks', () => { + expect(Object.isFrozen(MASKED_ON_READ_FIELD_TYPES)).toBe(true); + for (const rule of Object.values(MASKED_ON_READ_FIELD_TYPES)) { + expect(Object.isFrozen(rule)).toBe(true); + expect(Object.isFrozen(rule!.exemptManagedBy)).toBe(true); + } + expect(() => { + (MASKED_ON_READ_FIELD_TYPES.password!.exemptManagedBy as string[]).push('platform'); + }).toThrow(TypeError); + expect(MASKED_ON_READ_FIELD_TYPES.password!.exemptManagedBy).toEqual(['better-auth']); + }); +}); + +describe('isMaskedOnReadFieldType — the one reading of the declaration', () => { + const MANAGED_BY: readonly unknown[] = [...MANAGED_BY_BUCKETS, undefined, null, 'system', 'not-a-bucket']; + + it('answers every FieldType × managedBy cell: secret always, password unless better-auth, nothing else', () => { + let cells = 0; + for (const type of FIELD_TYPES) { + for (const managedBy of MANAGED_BY) { + const expected = type === 'secret' || (type === 'password' && managedBy !== 'better-auth'); + expect(isMaskedOnReadFieldType(type, managedBy), `${type} × ${String(managedBy)}`).toBe(expected); + cells += 1; + } + } + expect(cells).toBe(FIELD_TYPES.length * MANAGED_BY.length); + }); + + it('agrees with the table cell for cell (the predicate derives, it does not restate)', () => { + for (const type of FIELD_TYPES) { + for (const managedBy of MANAGED_BY) { + const rule = (MASKED_ON_READ_FIELD_TYPES as Record)[type]; + const fromTable = Object.prototype.hasOwnProperty.call(MASKED_ON_READ_FIELD_TYPES, type) + && !rule.exemptManagedBy.includes(managedBy); + expect(isMaskedOnReadFieldType(type, managedBy), `${type} × ${String(managedBy)}`).toBe(fromTable); + } + } + }); + + it('is total over unvalidated input: non-strings, prototype keys and case variants are not masked types', () => { + for (const type of [undefined, null, 42, ['secret'], { toString: () => 'secret' }, '', 'constructor', + 'toString', '__proto__', 'hasOwnProperty', 'SECRET', 'Password']) { + expect(isMaskedOnReadFieldType(type, undefined), String(type)).toBe(false); + } + }); + + it('fails closed on managedBy: an unlisted or malformed bucket never exempts', () => { + for (const managedBy of ['Better-Auth', 'better-auth ', ['better-auth'], 0, true]) { + expect(isMaskedOnReadFieldType('password', managedBy), String(managedBy)).toBe(true); + } + }); +}); diff --git a/packages/spec/src/data/masked-field-types.ts b/packages/spec/src/data/masked-field-types.ts new file mode 100644 index 00000000000..44fc16f29c4 --- /dev/null +++ b/packages/spec/src/data/masked-field-types.ts @@ -0,0 +1,123 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * Which field types are masked on read (ADR-0100) — declared ONCE, here. + * + * # The fact + * + * On the engine's generic read path (`find` / `findOne` / `$expand`), a + * credential-typed field is served as {@link SECRET_MASK} (or `null` when + * unset), never as its stored value: + * + * - `secret` — always. The column holds an opaque `sys_secret` ref; the + * plaintext is recoverable only through the engine's privileged + * dereference. + * - `password` — unless the object is `managedBy: 'better-auth'`. A generic + * `password` is plaintext at rest and masked on read; the auth subsystem + * reads its own identity rows through the same `find` / `findOne`, so + * masking there would break login. The exemption is part of the fact, not + * a consumer's special case, which is why it is declared beside the type + * it exempts. + * + * # Why it lives in `spec` + * + * Until #20141 the protocol stated this only in prose (the `FieldType` + * comments), and two consumers each carried a hand-written copy: + * `collectMaskedReadFields` in `@objectstack/objectql` (the read mask and the + * echoed-mask write guard) and objectui's `MASKED_FIELD_TYPES` (the renderer, + * which must not draw a masked value in clear or offer to copy it). A type + * added to one copy and not the other is masked by the server and drawn in + * clear by the client, or the reverse. `spec` is the contract both already + * depend on, so the fact is declared here. objectql's collectors and + * `ObjectSchema.create()`'s `password` warning derive from it now; objectui + * keeps its interim `MASKED_FIELD_TYPES` until its own re-bind card lands, and + * that card points it at {@link isMaskedOnReadFieldType}. + * + * # Shape — a per-type rule, read through one predicate + * + * Each masked type carries its OWN exemption list, keyed by the declared + * `managedBy` bucket. Three properties follow from that shape, and each one + * closes a way a consumer (human or AI) could get the answer wrong: + * + * - **An exemption cannot be separated from its type.** A bare type set + * plus a separate exemption table would let a reader take the set and + * drop the table, which masks `password` on better-auth objects and + * breaks login. Here there is nothing to forget: the exemption is a + * field of the rule. + * - **Exemptions fail closed.** The list names the buckets that are NOT + * masked. A `managedBy` value this table has never heard of — a future + * bucket, a typo in unvalidated metadata, `undefined` — exempts nothing, + * so the field stays masked. An allow-list ("masked when managedBy is + * …") would unmask on exactly those inputs. + * - **Nothing can be invented.** Keys are checked against `FieldType` and + * exemption values against `ObjectSchema.managedBy`'s own enum, at + * compile time; `masked-field-types.test.ts` holds the same two + * memberships at run time against the live schemas. + * + * Consumers ask {@link isMaskedOnReadFieldType}, which takes `managedBy` as a + * REQUIRED argument so a call site cannot leave the exemption out by omission. + * The table is exported for consumers that must enumerate the masked types + * (a renderer building its own lookup); ⛔ never re-derive the exemption from + * it by hand — ask the predicate. + * + * Changing this table changes which stored values leave the engine in clear. + * That is a security decision, not a refactor: the objectql table test pins + * the full `FieldType × managedBy` answer, and it goes red on any edit here. + */ + +import type { FieldType } from './field.zod'; +import type { ServiceObject } from './object.zod'; +import type { SECRET_MASK } from './secret-mask'; + +/** + * The read-mask rule for ONE masked field type. + */ +export interface FieldTypeReadMask { + /** + * The `managedBy` buckets whose objects are EXEMPT from this type's read + * mask. Empty ⇒ masked on every object. Each entry is a value + * `ObjectSchema.managedBy` declares; an object whose `managedBy` is absent, + * or is any value not listed here, is masked. + */ + readonly exemptManagedBy: readonly NonNullable[]; +} + +/** + * The field types masked on read (ADR-0100), each with the `managedBy` + * buckets exempt from its mask. Deep-frozen: a consumer that mutated it would + * change what every other consumer masks. + * + * Read it through {@link isMaskedOnReadFieldType}; see the module header for + * why the exemption is carried per type. + */ +export const MASKED_ON_READ_FIELD_TYPES: Readonly>> = + Object.freeze({ + // Reversible, encrypted-at-rest credential: the row holds a `sys_secret` + // ref, and neither the ref nor the plaintext leaves the generic read path. + secret: Object.freeze({ exemptManagedBy: Object.freeze([]) }), + // Plaintext at rest on a generic object, masked on read. better-auth's + // identity tables are exempt: the auth subsystem reads them through the + // same generic path, and a masked credential there breaks login. + password: Object.freeze({ exemptManagedBy: Object.freeze(['better-auth'] as const) }), + } satisfies Partial>); + +/** + * Whether a field of type `fieldType`, on an object declaring `managedBy`, is + * masked on read — served as {@link SECRET_MASK} (or `null` when unset) + * instead of its stored value. + * + * Total over its inputs, because consumers call it on stored, unvalidated + * metadata: a non-string or unknown `fieldType` is not masked (it is not a + * masked type), and a `managedBy` that is absent or not a listed exemption + * leaves a masked type masked (exemptions fail closed). Both parameters are + * required — pass `undefined` for an object with no `managedBy` — so a call + * site cannot drop the exemption by omission. + */ +export function isMaskedOnReadFieldType(fieldType: unknown, managedBy: unknown): boolean { + if (typeof fieldType !== 'string') return false; + // Own keys only: `'constructor'` / `'toString'` are properties of every + // object literal and name no field type. + if (!Object.prototype.hasOwnProperty.call(MASKED_ON_READ_FIELD_TYPES, fieldType)) return false; + const rule = MASKED_ON_READ_FIELD_TYPES[fieldType as FieldType] as FieldTypeReadMask; + return !(rule.exemptManagedBy as readonly unknown[]).includes(managedBy); +} diff --git a/packages/spec/src/data/object.test.ts b/packages/spec/src/data/object.test.ts index c4ee4371ef2..ece2371d359 100644 --- a/packages/spec/src/data/object.test.ts +++ b/packages/spec/src/data/object.test.ts @@ -11,6 +11,7 @@ import { resolveInjectedSystemColumns } from './injected-system-columns'; import { projectPublishedJsonSchema } from '../../scripts/lib/refinement-projection'; import { collectDroppedRefinements } from '../../scripts/lib/dropped-refinements'; import { Field } from './field.zod'; +import { isMaskedOnReadFieldType } from './masked-field-types'; import type { StateMachineValidation } from './validation.zod'; describe('ObjectCapabilities', () => { @@ -2459,6 +2460,38 @@ describe('ObjectSchema.create() password-field author warning (ADR-0100)', () => const msg = warn.mock.calls[0]?.[0] as string; expect(msg).toContain('ackPlaintextMasking'); }); + + // [#20141] The warning's exemption is the masked-on-read declaration's, not a + // second copy: for every `managedBy` bucket (and none), an un-acknowledged + // `password` field warns exactly when `isMaskedOnReadFieldType('password', …)` + // says the read mask applies. If `MASKED_ON_READ_FIELD_TYPES.password + // .exemptManagedBy` changes, this stays green only because the warning follows; + // a warning that hard-codes its own bucket goes red here. + describe('[#20141] the exemption is read from MASKED_ON_READ_FIELD_TYPES', () => { + const buckets = ( + ObjectSchema.shape.managedBy as unknown as { unwrap(): { options: readonly string[] } } + ).unwrap().options; + const PW_WARNING = "use type 'password' on a non-auth object"; + const warnsFor = (managedBy: string | undefined): boolean => { + const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}); + ObjectSchema.create({ + name: `adr0100_decl_${(managedBy ?? 'absent').replace(/-/g, '_')}`, + ...(managedBy === undefined ? {} : { managedBy: managedBy as never }), + fields: { pw: { type: 'password' } }, + }); + const fired = warn.mock.calls.some((c) => String(c[0]).includes(PW_WARNING)); + warn.mockRestore(); + return fired; + }; + + it('warns on exactly the buckets where the declaration masks password (the agreement)', () => { + expect(buckets.length).toBeGreaterThan(1); // the enum really was read + for (const managedBy of [undefined, ...buckets]) { + expect(warnsFor(managedBy), `managedBy ${managedBy ?? '(absent)'}`) + .toBe(isMaskedOnReadFieldType('password', managedBy)); + } + }); + }); }); // --------------------------------------------------------------------------- diff --git a/packages/spec/src/data/object.zod.ts b/packages/spec/src/data/object.zod.ts index 1696bdf483e..76886c7afe5 100644 --- a/packages/spec/src/data/object.zod.ts +++ b/packages/spec/src/data/object.zod.ts @@ -18,6 +18,10 @@ import { retiredKey } from '../shared/retired-key'; import { refuseRecordProtoKey } from '../shared/record-proto-key-guard'; import { bannedKeys } from '../shared/refinement-projection'; import { FIELD_GROUP_KEY_PATTERN } from './field-group-layout'; +// The masked-on-read declaration (#20141); `warnGenericPasswordFields` reads its +// `password` exemption rather than restating it. No runtime cycle: that module's +// only imports are type-only. +import { isMaskedOnReadFieldType } from './masked-field-types'; export const ApiMethod = z.enum([ 'get', 'list', // Read 'create', 'update', 'delete', // Write @@ -2574,17 +2578,26 @@ const warnedPasswordObjects = new Set(); * A warning, not an error: `password` now has a defined generic-path contract, * and the field-zoo example intentionally exercises every field type — a hard * error would be self-inflicted breakage. Deduped per object name so a schema - * imported many times warns once. `managedBy: 'better-auth'` objects are exempt, - * as are fields that opt in with `ackPlaintextMasking: true` — the author's - * explicit "this is intended" acknowledgment (#3420), which lets a deliberate - * demo/design (e.g. the showcase field-zoo) start with zero warnings. + * imported many times warns once. Objects whose `managedBy` exempts `password` + * from the read mask are exempt (today `better-auth`), as are fields that opt in + * with `ackPlaintextMasking: true` — the author's explicit "this is intended" + * acknowledgment (#3420), which lets a deliberate demo/design (e.g. the showcase + * field-zoo) start with zero warnings. + * + * [#20141] The exemption is READ from the masked-on-read declaration + * (`MASKED_ON_READ_FIELD_TYPES`, via `isMaskedOnReadFieldType`), never restated: + * the warning describes a `password` that is masked on read yet plaintext at + * rest, so it fires exactly where the read mask applies to `password`. If that + * declaration's `exemptManagedBy` changes, this warning follows it. ⛔ Not + * widened to `secret` — a `secret` is encrypted at rest, which is the whole + * point of steering authors to it. */ function warnGenericPasswordFields( objectName: unknown, fields: unknown, managedBy: unknown, ): void { - if (managedBy === 'better-auth') return; + if (!isMaskedOnReadFieldType('password', managedBy)) return; if (!fields || typeof fields !== 'object') return; const passwordFields = Object.entries( fields as Record,