|
| 1 | +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. |
| 2 | + |
| 3 | +/** |
| 4 | + * [#25522 cut 5] The secret and internal-field bodies of `ObjectQL`, moved out |
| 5 | + * of `engine.ts` whole: the write-side credential pass (`encryptSecretFields`, |
| 6 | + * `refuseEmptyPasswordFields`), the read-side strips (`maskSecretFields`, |
| 7 | + * `omitInternalFields`, `stripSearchCompanionFromRead`), and the three |
| 8 | + * privileged read verbs with the driver options they share (`resolveSecret`, |
| 9 | + * `resolveSecretField`, `resolveInternalField`, `privilegedReadDriverOptions`). |
| 10 | + * |
| 11 | + * A MOVE, not a redesign. Each exported function below is the body of the |
| 12 | + * `ObjectQL` method of the same name as it stood, re-indented one level and |
| 13 | + * otherwise unedited: the same fail-closed throws, the same echoed-mask drop, |
| 14 | + * the same mask-then-omit order, the same refusals before any driver read, and |
| 15 | + * the same ambient-transaction rule for the privileged reads. Each method's |
| 16 | + * docblock stays on the method in `engine.ts`, which is still the contract. |
| 17 | + * |
| 18 | + * ## How the moved bodies reach the class |
| 19 | + * |
| 20 | + * The shape #23050 set for `rest-server.ts` (its `data-action-routes.ts` |
| 21 | + * header carries the full reasoning), applied per method as |
| 22 | + * `engine-realtime-publish.ts` applies it. The class keeps all nine methods — |
| 23 | + * the published `.d.ts` lists each one's name and position — and each body is |
| 24 | + * one literal of exactly the {@link SecretInternalFieldsHost} members that |
| 25 | + * method reads, plus a `.call`. The three fields the bodies read |
| 26 | + * (`_registry`, `cryptoProvider`, `txStore`) go as GETTERS, so each read |
| 27 | + * happens when the body makes it: `setCryptoProvider` replaces the provider at |
| 28 | + * any time, and a body sees whatever is installed at the moment it reads, as |
| 29 | + * it did. The five methods they call (`getDriver`, |
| 30 | + * `transactionCoversDriverFor`, `omitInternalFields`, |
| 31 | + * `privilegedReadDriverOptions`, `resolveSecret`) go as late-bound closures |
| 32 | + * over the instance, so a double or spy set on the engine — tests replace |
| 33 | + * `resolveInternalField` and `resolveSecretField` on the instance — is still |
| 34 | + * the one a call reaches. `stripSearchCompanionFromRead` reads no member and |
| 35 | + * is called directly. |
| 36 | + * |
| 37 | + * This module imports the engine only as a TYPE, so there is no module cycle |
| 38 | + * at run time, and nothing re-exports it, so the published surface does not |
| 39 | + * move. |
| 40 | + */ |
| 41 | + |
| 42 | +import type { CryptoHandle } from '@objectstack/spec/contracts'; |
| 43 | +import type { ExecutionContext } from '@objectstack/spec/kernel'; |
| 44 | +import { redactPropagatedDriverFault } from '@objectstack/types'; |
| 45 | +import { |
| 46 | + collectSecretFields, |
| 47 | + collectMaskedReadFields, |
| 48 | + collectMaskedPasswordFields, |
| 49 | + collectInternalReadFields, |
| 50 | + makeSecretRef, |
| 51 | + parseSecretRef, |
| 52 | + isSecretRef, |
| 53 | + EmptyCredentialWriteError, |
| 54 | + SECRET_MASK, |
| 55 | +} from './secret-fields.js'; |
| 56 | +import { isSearchCompanionRequested, stripSearchCompanion } from './search-companion.js'; |
| 57 | +import type { ObjectQL } from './engine.js'; |
| 58 | + |
| 59 | +/** |
| 60 | + * The `ObjectQL` members the functions below read — every one of them, and no |
| 61 | + * other; each function's `this` is the `Pick` of the members IT reads. Each is |
| 62 | + * typed AS the class member (an indexed access on the class), so a change to a |
| 63 | + * member's type on the class is a change here too, and naming a member the |
| 64 | + * class does not have is a compile error. See the module header for which |
| 65 | + * members are getters. |
| 66 | + */ |
| 67 | +export interface SecretInternalFieldsHost { |
| 68 | + readonly _registry: ObjectQL['_registry']; |
| 69 | + readonly cryptoProvider: ObjectQL['cryptoProvider']; |
| 70 | + readonly txStore: ObjectQL['txStore']; |
| 71 | + getDriver: ObjectQL['getDriver']; |
| 72 | + transactionCoversDriverFor: ObjectQL['transactionCoversDriverFor']; |
| 73 | + omitInternalFields: ObjectQL['omitInternalFields']; |
| 74 | + privilegedReadDriverOptions: ObjectQL['privilegedReadDriverOptions']; |
| 75 | + resolveSecret: ObjectQL['resolveSecret']; |
| 76 | +} |
| 77 | + |
| 78 | +/** The body of `ObjectQL#encryptSecretFields`; the method's docblock there is its contract. */ |
| 79 | +export async function encryptSecretFields( |
| 80 | + this: Pick<SecretInternalFieldsHost, '_registry' | 'cryptoProvider' | 'getDriver'>, |
| 81 | + object: string, |
| 82 | + row: Record<string, unknown>, |
| 83 | + context: ExecutionContext | undefined, |
| 84 | + driverOptions: unknown, |
| 85 | +): Promise<void> { |
| 86 | + if (!row || typeof row !== 'object') return; |
| 87 | + const schema = this._registry.getObject(object); |
| 88 | + |
| 89 | + // Echoed-mask drop for every field the read path masks (secret + generic |
| 90 | + // password). The read path returns SECRET_MASK; a client that PATCHes it |
| 91 | + // back means "unchanged", so drop the key rather than persist the literal |
| 92 | + // mask. Doing this up front keeps the better-auth exemption in one place |
| 93 | + // (collectMaskedReadFields) and covers objects that have a password field |
| 94 | + // but no secret field. (#2036, ADR-0100) |
| 95 | + for (const field of collectMaskedReadFields(schema)) { |
| 96 | + if (field in row && row[field] === SECRET_MASK) delete row[field]; |
| 97 | + } |
| 98 | + |
| 99 | + const secretFields = collectSecretFields(schema); |
| 100 | + if (secretFields.length === 0) return; |
| 101 | + |
| 102 | + for (const field of secretFields) { |
| 103 | + if (!(field in row)) continue; |
| 104 | + const value = row[field]; |
| 105 | + |
| 106 | + if (value === null || typeof value === 'undefined') continue; // clear |
| 107 | + // [#8559] The empty string is neither a clear (`null` is) nor a storable |
| 108 | + // credential — refuse it BEFORE the crypto gates below: this is a verdict |
| 109 | + // on the payload, so it must not depend on whether a CryptoProvider or |
| 110 | + // sys_secret store happens to be wired. |
| 111 | + if (value === '') throw new EmptyCredentialWriteError(object, field, 'secret'); |
| 112 | + if (isSecretRef(value)) continue; // already encrypted ref |
| 113 | + |
| 114 | + if (!this.cryptoProvider) { |
| 115 | + throw new Error( |
| 116 | + `Cannot persist secret field "${object}.${field}": no CryptoProvider is registered. ` |
| 117 | + + 'Wire one via engine.setCryptoProvider(...) (e.g. LocalCryptoProvider in dev, ' |
| 118 | + + 'a KMS/Vault provider in production). Refusing to store cleartext (fail-closed).', |
| 119 | + ); |
| 120 | + } |
| 121 | + |
| 122 | + const plain = typeof value === 'string' ? value : JSON.stringify(value); |
| 123 | + // ADR-0128 D1: this producer's own scope, so the AAD names the |
| 124 | + // object-secret-field vocabulary and no other producer's context opens it. |
| 125 | + const handle: CryptoHandle = await this.cryptoProvider.encrypt(plain, { |
| 126 | + scope: 'object_secret_field', |
| 127 | + namespace: object, |
| 128 | + key: field, |
| 129 | + tenantId: context?.tenantId, |
| 130 | + }); |
| 131 | + |
| 132 | + let secretDriver; |
| 133 | + try { |
| 134 | + secretDriver = this.getDriver('sys_secret'); |
| 135 | + } catch { |
| 136 | + throw new Error( |
| 137 | + `Cannot persist secret field "${object}.${field}": the sys_secret store is not available. ` |
| 138 | + + 'Ensure the platform-objects (sys_secret) are registered before writing secret fields (fail-closed).', |
| 139 | + ); |
| 140 | + } |
| 141 | + |
| 142 | + await secretDriver.create( |
| 143 | + 'sys_secret', |
| 144 | + { |
| 145 | + id: handle.id, |
| 146 | + namespace: object, |
| 147 | + key: field, |
| 148 | + kms_key_id: handle.kmsKeyId, |
| 149 | + alg: handle.alg, |
| 150 | + version: handle.version, |
| 151 | + ciphertext: handle.ciphertext, |
| 152 | + created_at: new Date().toISOString(), |
| 153 | + }, |
| 154 | + driverOptions as any, |
| 155 | + ); |
| 156 | + |
| 157 | + row[field] = makeSecretRef(handle.id); |
| 158 | + } |
| 159 | +} |
| 160 | + |
| 161 | +/** The body of `ObjectQL#refuseEmptyPasswordFields`; the method's docblock there is its contract. */ |
| 162 | +export function refuseEmptyPasswordFields( |
| 163 | + this: Pick<SecretInternalFieldsHost, '_registry'>, |
| 164 | + object: string, |
| 165 | + row: Record<string, unknown>, |
| 166 | +): void { |
| 167 | + if (!row || typeof row !== 'object') return; |
| 168 | + const schema = this._registry.getObject(object); |
| 169 | + for (const field of collectMaskedPasswordFields(schema)) { |
| 170 | + if (field in row && row[field] === '') { |
| 171 | + throw new EmptyCredentialWriteError(object, field, 'password'); |
| 172 | + } |
| 173 | + } |
| 174 | +} |
| 175 | + |
| 176 | +/** The body of `ObjectQL#maskSecretFields`; the method's docblock there is its contract. */ |
| 177 | +export function maskSecretFields( |
| 178 | + this: Pick<SecretInternalFieldsHost, '_registry' | 'omitInternalFields'>, |
| 179 | + object: string, |
| 180 | + rows: any, |
| 181 | +): void { |
| 182 | + if (!rows) return; |
| 183 | + const schema = this._registry.getObject(object); |
| 184 | + const maskedFields = collectMaskedReadFields(schema); |
| 185 | + if (maskedFields.length > 0) { |
| 186 | + const list = Array.isArray(rows) ? rows : [rows]; |
| 187 | + for (const row of list) { |
| 188 | + if (!row || typeof row !== 'object') continue; |
| 189 | + for (const field of maskedFields) { |
| 190 | + if (!(field in row)) continue; |
| 191 | + row[field] = row[field] == null ? null : SECRET_MASK; |
| 192 | + } |
| 193 | + } |
| 194 | + } |
| 195 | + // Runs AFTER the mask, so a field that is somehow both `secret`-typed and |
| 196 | + // `internal` ends up omitted rather than masked — the stricter disposition |
| 197 | + // wins, which is the only safe way for the two to compose. |
| 198 | + this.omitInternalFields(object, rows); |
| 199 | +} |
| 200 | + |
| 201 | +/** The body of `ObjectQL#omitInternalFields`; the method's docblock there is its contract. */ |
| 202 | +export function omitInternalFields( |
| 203 | + this: Pick<SecretInternalFieldsHost, '_registry'>, |
| 204 | + object: string, |
| 205 | + rows: any, |
| 206 | +): void { |
| 207 | + if (!rows) return; |
| 208 | + const schema = this._registry.getObject(object); |
| 209 | + const internalFields = collectInternalReadFields(schema); |
| 210 | + if (internalFields.length === 0) return; |
| 211 | + const list = Array.isArray(rows) ? rows : [rows]; |
| 212 | + for (const row of list) { |
| 213 | + if (!row || typeof row !== 'object') continue; |
| 214 | + for (const field of internalFields) delete row[field]; |
| 215 | + } |
| 216 | +} |
| 217 | + |
| 218 | +/** The body of `ObjectQL#stripSearchCompanionFromRead`; the method's docblock there is its contract. */ |
| 219 | +export function stripSearchCompanionFromRead( |
| 220 | + rows: unknown, |
| 221 | + requestedFields: readonly string[] | undefined, |
| 222 | + context: ExecutionContext | undefined, |
| 223 | +): void { |
| 224 | + if (context?.isSystem && isSearchCompanionRequested(requestedFields)) return; |
| 225 | + stripSearchCompanion(rows); |
| 226 | +} |
| 227 | + |
| 228 | +/** The body of `ObjectQL#privilegedReadDriverOptions`; the method's docblock there is its contract. */ |
| 229 | +export function privilegedReadDriverOptions( |
| 230 | + this: Pick<SecretInternalFieldsHost, 'txStore' | 'transactionCoversDriverFor'>, |
| 231 | + object: string, |
| 232 | +): { transaction: unknown } | undefined { |
| 233 | + const tx = this.txStore.getStore()?.transaction; |
| 234 | + if (tx === undefined) return undefined; |
| 235 | + if (!this.transactionCoversDriverFor(object, tx)) return undefined; |
| 236 | + return { transaction: tx }; |
| 237 | +} |
| 238 | + |
| 239 | +/** The body of `ObjectQL#resolveSecret`; the method's docblock there is its contract. */ |
| 240 | +export async function resolveSecret( |
| 241 | + this: Pick<SecretInternalFieldsHost, 'cryptoProvider' | 'getDriver' | 'privilegedReadDriverOptions'>, |
| 242 | + ref: unknown, |
| 243 | + opts?: { tenantId?: string }, |
| 244 | +): Promise<string | null> { |
| 245 | + const id = parseSecretRef(ref); |
| 246 | + if (!id) return null; |
| 247 | + if (!this.cryptoProvider) { |
| 248 | + throw new Error('Cannot resolve secret: no CryptoProvider is registered (fail-closed).'); |
| 249 | + } |
| 250 | + const secretDriver = this.getDriver('sys_secret'); |
| 251 | + const found = await secretDriver.find( |
| 252 | + 'sys_secret', |
| 253 | + { where: { id } }, |
| 254 | + this.privilegedReadDriverOptions('sys_secret'), |
| 255 | + ); |
| 256 | + const secret: any = Array.isArray(found) ? found[0] : found; |
| 257 | + if (!secret) { |
| 258 | + throw new Error(`Cannot resolve secret: sys_secret row "${id}" not found (fail-closed).`); |
| 259 | + } |
| 260 | + const handle: CryptoHandle = { |
| 261 | + id: secret.id, |
| 262 | + kmsKeyId: secret.kms_key_id, |
| 263 | + alg: secret.alg, |
| 264 | + version: secret.version, |
| 265 | + ciphertext: secret.ciphertext, |
| 266 | + }; |
| 267 | + // ADR-0128 D1: a `secret:` ref is the object-secret-field producer's |
| 268 | + // holder, so the scope is that producer's. A row another producer sealed |
| 269 | + // under a scoped derivation therefore does not open here. |
| 270 | + return this.cryptoProvider.decrypt(handle, { |
| 271 | + scope: 'object_secret_field', |
| 272 | + namespace: secret.namespace, |
| 273 | + key: secret.key, |
| 274 | + tenantId: opts?.tenantId, |
| 275 | + }); |
| 276 | +} |
| 277 | + |
| 278 | +/** The body of `ObjectQL#resolveSecretField`; the method's docblock there is its contract. */ |
| 279 | +export async function resolveSecretField( |
| 280 | + this: Pick<SecretInternalFieldsHost, '_registry' | 'getDriver' | 'privilegedReadDriverOptions' | 'resolveSecret'>, |
| 281 | + object: string, |
| 282 | + recordId: string, |
| 283 | + field: string, |
| 284 | + opts?: { tenantId?: string }, |
| 285 | +): Promise<string | null> { |
| 286 | + const schema = this._registry.getObject(object); |
| 287 | + if (!collectSecretFields(schema).includes(field)) { |
| 288 | + throw new Error( |
| 289 | + `Cannot resolve secret field "${object}.${field}": it is not declared as type 'secret'. ` |
| 290 | + + 'Only the encrypted secret channel is dereferenceable — a `password` field is stored as ' |
| 291 | + + 'plaintext at rest and is masked deliberately (ADR-0100), so dereferencing one here ' |
| 292 | + + 'would be a mask bypass, not a decrypt.', |
| 293 | + ); |
| 294 | + } |
| 295 | + const driver = this.getDriver(object); |
| 296 | + let found: unknown; |
| 297 | + try { |
| 298 | + found = await driver.find( |
| 299 | + object, |
| 300 | + { where: { id: recordId } }, |
| 301 | + this.privilegedReadDriverOptions(object), |
| 302 | + ); |
| 303 | + } catch (e) { |
| 304 | + // [#21274] A boundary outside the middleware seam: the record id is bound. |
| 305 | + throw redactPropagatedDriverFault(e); |
| 306 | + } |
| 307 | + const row: any = Array.isArray(found) ? found[0] : found; |
| 308 | + if (!row) return null; |
| 309 | + return this.resolveSecret(row[field], opts); |
| 310 | +} |
| 311 | + |
| 312 | +/** The body of `ObjectQL#resolveInternalField`; the method's docblock there is its contract. */ |
| 313 | +export async function resolveInternalField( |
| 314 | + this: Pick<SecretInternalFieldsHost, '_registry' | 'getDriver' | 'privilegedReadDriverOptions'>, |
| 315 | + object: string, |
| 316 | + recordIds: readonly string[], |
| 317 | + field: string, |
| 318 | +): Promise<Map<string, unknown>> { |
| 319 | + const schema = this._registry.getObject(object); |
| 320 | + if (!collectInternalReadFields(schema).includes(field)) { |
| 321 | + const err: Error & { code?: string; status?: number; httpStatus?: number; object?: string; field?: string } = |
| 322 | + new Error( |
| 323 | + `Cannot resolve internal field "${object}.${field}": it is not declared \`internal: true\`. ` |
| 324 | + + 'Only fields the engine omits from the generic read path are dereferenceable here — ' |
| 325 | + + 'anything else either comes back on find/findOne already, or is protected by its own ' |
| 326 | + + 'channel (`secret` refs via resolveSecretField; `password` is masked deliberately, ' |
| 327 | + + 'ADR-0100, so dereferencing one here would be a mask bypass).', |
| 328 | + ); |
| 329 | + err.code = 'INVALID_FIELD'; |
| 330 | + err.status = 400; |
| 331 | + err.httpStatus = 400; |
| 332 | + err.object = object; |
| 333 | + err.field = field; |
| 334 | + throw err; |
| 335 | + } |
| 336 | + const out = new Map<string, unknown>(); |
| 337 | + if (recordIds.length === 0) return out; |
| 338 | + const driver = this.getDriver(object); |
| 339 | + let found: unknown; |
| 340 | + try { |
| 341 | + found = await driver.find( |
| 342 | + object, |
| 343 | + { |
| 344 | + where: { id: { $in: [...recordIds] } }, |
| 345 | + fields: ['id', field], |
| 346 | + }, |
| 347 | + this.privilegedReadDriverOptions(object), |
| 348 | + ); |
| 349 | + } catch (e) { |
| 350 | + // [#21274] A boundary outside the middleware seam: the record ids are bound. |
| 351 | + throw redactPropagatedDriverFault(e); |
| 352 | + } |
| 353 | + for (const row of Array.isArray(found) ? found : [found]) { |
| 354 | + if (!row || typeof row !== 'object') continue; |
| 355 | + const id = (row as Record<string, unknown>).id; |
| 356 | + if (typeof id !== 'string' && typeof id !== 'number') continue; |
| 357 | + out.set(String(id), (row as Record<string, unknown>)[field] ?? null); |
| 358 | + } |
| 359 | + return out; |
| 360 | +} |
0 commit comments