@nodii/dsar 0.16.0 → 0.18.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,5 +1,8 @@
1
- // resolveHoldFailureMode — the one place that decides what a FAILED hold
2
- // consult means.
1
+ // The hold-gate refusal vocabulary + the ONE bind-time validator that survives
2
+ // the removal of the fail-open leg (`resolveFailClosedHolds`). Nothing here
3
+ // DECIDES open-vs-closed any more — the gate has exactly one mode. This module
4
+ // owns: the two refusal reason codes, the memoization rule that keeps an
5
+ // infrastructure refusal retryable, and the shared refusal-audit payload.
3
6
  //
4
7
  // THE DEFAULT WAS BACKWARDS (fixed in 0.16.0)
5
8
  // -------------------------------------------
@@ -22,22 +25,207 @@
22
25
  //
23
26
  // So the doctrine's own worked example was live and fail-open in production.
24
27
  //
25
- // THE FIX
26
- // -------
27
- // Fail-CLOSED is now the DEFAULT. Opting OUT is the explicit act, via a
28
- // differently-named flag whose name states what it does:
29
- // `allowFailOpenHolds: true`.
28
+ // 0.16.0 flipped the DEFAULT to fail-closed but kept an explicit opt-out
29
+ // (`allowFailOpenHolds: true`).
30
+ //
31
+ // THE OPT-OUT IS GONE (operator ruling 2026-07-30)
32
+ // ------------------------------------------------
33
+ // The fail-open escape hatch itself is REMOVED. Operator ruling, verbatim:
34
+ //
35
+ // "all three MUST HAVE THE SAME POSTURE. If holds is inaccessible - we deny
36
+ // the write. ... if there is a hold and we fail open - then information
37
+ // that would be required for courts or an investigation gets lost. But if
38
+ // there isn't a hold and we fail closed - it's just a matter of a retry
39
+ // when holds is accessible. Safer. Fail CLOSED."
40
+ //
41
+ // The hold gate is now UNCONDITIONALLY fail-closed, in all three language
42
+ // twins (ts / python / go). There is no configuration that makes a hold-read
43
+ // error (or a HELD terminal-write error) let the operation proceed. A
44
+ // dev/CI environment with no holds table gets the holds migration
45
+ // (`applyDsarMigrations`), not a bypass flag.
30
46
  //
31
47
  // `failClosedHolds` survives as a DEPRECATED alias so the six services that
32
48
  // correctly set `true` keep compiling and behaving identically. Passing
33
- // `failClosedHolds: false` — the value that used to mean "fail open" — now
34
- // THROWS at bind time rather than silently re-opening the gate. That is loud
35
- // on purpose: an explicit `false` is now ambiguous between "I want fail-open"
36
- // and "I pinned the old default and never revisited it", and the compliance
37
- // cost of guessing wrong is an unrecoverable erasure. Zero services in the
38
- // fleet pass `false` today, so nothing regresses; anyone who genuinely wants
39
- // fail-open says so in the new vocabulary.
49
+ // `failClosedHolds: false` — the value that used to mean "fail open" — still
50
+ // THROWS at bind time: fail-open no longer exists, so an explicit `false`
51
+ // cannot be honored and must not be silently reinterpreted.
40
52
  import { DsarError } from "./types.js";
53
+ // ── THE REFUSAL VOCABULARY (two distinguishable corners) ───────────────────
54
+ //
55
+ // A fail-closed refusal has TWO causes with OPPOSITE remedies, and until now
56
+ // both reported the same `reason` with the raw driver error stuffed into
57
+ // `statute_citation` — so a caller could not tell them apart, and an automated
58
+ // retry loop treated the futile one as the transient one:
59
+ //
60
+ // (a) the CONSULT failed — missing table, dead connection, permission error.
61
+ // Hold existence is UNKNOWN. Transient: RETRY once holds are reachable.
62
+ // (b) the consult SUCCEEDED and positively identified an active hold, but the
63
+ // HELD terminal record (aggregator row / refusal audit) could not be
64
+ // written. The hold is KNOWN. Retrying is futile until the write path is
65
+ // repaired — and the hold's REAL statutory citation is in hand and must
66
+ // not be discarded.
67
+ //
68
+ // Both refuse. Neither is memoizable (see below). `statute_citation` is
69
+ // CITATION-ONLY on both: "" for (a) (nothing is known), the identified hold's
70
+ // citation for (b). The raw driver error rides `LifecycleResponse.hold_gate_error`
71
+ // (diagnostic; NOT a proto field) + the refusal audit payload — never the
72
+ // compliance-facing citation field a consumer may render to a data subject.
73
+ /**
74
+ * Corner (a) — the hold CONSULT itself failed; hold existence is UNKNOWN.
75
+ * The value is load-bearing across the three twins and the fleet's
76
+ * fail-closed compliance suites: do NOT rename it.
77
+ */
78
+ export const HOLD_CONSULT_FAILED_REASON = "hold_consult_failed_fail_closed";
79
+ /**
80
+ * Corner (b) — a hold WAS positively identified; only its HELD terminal record
81
+ * failed. Distinct from {@link HOLD_CONSULT_FAILED_REASON} so a caller can tell
82
+ * "unknown, retry" from "known hold, recording broken".
83
+ */
84
+ export const HELD_WRITE_FAILED_REASON = "held_write_failed_fail_closed";
85
+ /**
86
+ * The hold-gate refusal codes that are INFRASTRUCTURE failures rather than
87
+ * business outcomes. Exported so consumers can classify a refusal without
88
+ * string-matching, and so the go/python twins have one list to mirror.
89
+ */
90
+ export const HOLD_GATE_INFRA_REFUSAL_REASONS = [
91
+ HOLD_CONSULT_FAILED_REASON,
92
+ HELD_WRITE_FAILED_REASON,
93
+ ];
94
+ /**
95
+ * THE MEMOIZATION RULE (operator ruling 2026-07-30 — "it's just a matter of a
96
+ * retry when holds is accessible").
97
+ *
98
+ * The ruling's safety argument rests entirely on the refusal being RETRYABLE.
99
+ * It was not: `withLifecycleIdempotency` wrote every resolved response into
100
+ * `lifecycle_requests.response_cached`, and `request_id` IS the DSAR
101
+ * idempotency key — so the natural idempotent retry replayed the cached
102
+ * refusal without ever re-consulting holds. One transient holds outage poisoned
103
+ * that statutory request identity FOREVER; the only escapes were minting a new
104
+ * request_id (new SLA clock, new audit lineage) or hand-deleting the row.
105
+ *
106
+ * So: an infrastructure refusal is NOT a terminal business outcome. It is not
107
+ * memoized, and it does not hold the idempotency claim — an identical
108
+ * subsequent request RE-CONSULTS holds. Genuine business outcomes (COMPLETED /
109
+ * PARTIAL / NO_DATA / HELD / a FAILED produced by a handler or a sibling) are
110
+ * memoized exactly as before: replaying those must NOT re-run the side effect.
111
+ *
112
+ * The rule is deliberately keyed on the two library-generated gate codes and
113
+ * NOT on "status === FAILED" — a handler's FAILED (a real attempt that really
114
+ * failed) stays memoized, because re-running an erase is not free.
115
+ *
116
+ * SCOPE: this is the CONSUMER-FACING classifier — the exported half of the wire
117
+ * contract, so a consumer that receives `{status, reason}` off the wire (where
118
+ * nothing but those two strings survives) can still tell an infrastructure
119
+ * refusal from a business outcome. It is deliberately string-only, and it is
120
+ * therefore NOT what the idempotency wrap decides on: see
121
+ * {@link isLibraryHoldGateRefusal}.
122
+ */
123
+ export function isNonMemoizableOutcome(response) {
124
+ return (response.status === "FAILED" &&
125
+ HOLD_GATE_INFRA_REFUSAL_REASONS.includes(response.reason ?? ""));
126
+ }
127
+ // ── THE MEMOIZATION DECISION IS UNFORGEABLE ────────────────────────────────
128
+ //
129
+ // `isNonMemoizableOutcome` keys on the `reason` STRING, and every participant
130
+ // catch puts the RAW handler error text into `reason` (bind-pattern-a.ts's five
131
+ // handler catches: `reason: err instanceof Error ? err.message : String(err)`).
132
+ // So the two reserved codes lived in the SAME namespace as arbitrary handler
133
+ // error strings, and a handler that raised `new Error(
134
+ // "hold_consult_failed_fail_closed")` — a copy-pasted constant, a re-thrown
135
+ // upstream refusal, a log line echoed into an exception — got the library's
136
+ // non-memoized treatment: its idempotency claim DELETED and the erase RE-RUN on
137
+ // the idempotent retry. Measured (2026-07-30 panel probe S12, real pg, all
138
+ // three twins): claim_rows_after_r1 = 0, handler_runs after replay = 2.
139
+ //
140
+ // The classification therefore cannot key on handler-supplied DATA. It keys on
141
+ // a BRAND that only this module can apply, and which only the library's own
142
+ // gate-construction paths (bind-pattern-a.ts `checkHold`, orchestrator.ts's two
143
+ // corner responses) ever apply.
144
+ //
145
+ // WHY IT CANNOT BE SPOOFED
146
+ // * The brand key is a `Symbol()` — a fresh, unique symbol created at module
147
+ // load. It is NOT `Symbol.for()`, so it is absent from the global symbol
148
+ // registry and cannot be re-derived by name. The binding is module-private
149
+ // (never exported, never re-exported from `index.ts`), so no consumer holds
150
+ // a reference to the only key that would set or read it.
151
+ // * The property is `enumerable: false, writable: false, configurable: false`:
152
+ // invisible to `Object.keys`, object spread, `JSON.stringify`, structural
153
+ // equality — so it never reaches the wire, `response_cached`, or a test's
154
+ // `toEqual`, and it cannot be overwritten once set.
155
+ // * `reason` stays EXACTLY as before on the wire, and
156
+ // `isNonMemoizableOutcome` (the exported classifier) is unchanged — the
157
+ // reason-code vocabulary is still the contract consumers match on. Only the
158
+ // memoization DECISION moved to the brand.
159
+ /**
160
+ * Module-private brand for a refusal THIS LIBRARY constructed at a hold gate.
161
+ * Deliberately `Symbol()` (unique, unregistered) rather than `Symbol.for()`.
162
+ */
163
+ const HOLD_GATE_REFUSAL_BRAND = Symbol("nodii.dsar.libraryHoldGateRefusal");
164
+ /**
165
+ * Brand a hold-gate refusal the library itself constructed. Internal — exported
166
+ * for `bind-pattern-a.ts` / `orchestrator.ts` only, and NOT re-exported from
167
+ * `index.ts`.
168
+ */
169
+ export function brandHoldGateRefusal(response) {
170
+ Object.defineProperty(response, HOLD_GATE_REFUSAL_BRAND, {
171
+ value: true,
172
+ enumerable: false,
173
+ writable: false,
174
+ configurable: false,
175
+ });
176
+ return response;
177
+ }
178
+ function hasHoldGateRefusalBrand(value) {
179
+ return (typeof value === "object" &&
180
+ value !== null &&
181
+ value[HOLD_GATE_REFUSAL_BRAND] === true);
182
+ }
183
+ /**
184
+ * Carry the brand across a copy. The participant gate sites re-stamp
185
+ * `request_id` onto the refusal with `{ ...held, request_id }`, and a
186
+ * non-enumerable property is NOT copied by spread — so the brand has to be
187
+ * carried explicitly. `from` unbranded (e.g. a HELD outcome, which IS
188
+ * memoizable) leaves `to` unbranded.
189
+ */
190
+ export function carryHoldGateRefusalBrand(from, to) {
191
+ return hasHoldGateRefusalBrand(from) ? brandHoldGateRefusal(to) : to;
192
+ }
193
+ /**
194
+ * THE MEMOIZATION DECISION — the predicate `withLifecycleIdempotency` uses.
195
+ *
196
+ * Requires BOTH the library's own brand AND one of the two reserved reason
197
+ * codes. A handler's FAILED can carry either reserved string as its `reason`
198
+ * (deliberately, accidentally, or by echoing an upstream refusal) and is still
199
+ * memoized, because it carries no brand.
200
+ *
201
+ * Internal — not re-exported from `index.ts`. Consumers classify with
202
+ * {@link isNonMemoizableOutcome} / {@link HOLD_GATE_INFRA_REFUSAL_REASONS}.
203
+ */
204
+ export function isLibraryHoldGateRefusal(response) {
205
+ return hasHoldGateRefusalBrand(response) && isNonMemoizableOutcome(response);
206
+ }
207
+ /**
208
+ * The shared hold-gate refusal AUDIT payload — one shape for every refusal, on
209
+ * both the participant (`<svc>.dsar.<verb>_failed`) and the orchestrator
210
+ * (`tenant.dsar.<verb>_failed`) sides, for all three refusal kinds (HELD,
211
+ * consult-failed, HELD-write-failed).
212
+ *
213
+ * This is where the technical detail lives. The audit row is operator-facing
214
+ * and tamper-evident; the response envelope is compliance-facing. Keeping the
215
+ * driver error here (and out of `statute_citation`) is what lets the citation
216
+ * field mean only ever "a statute".
217
+ */
218
+ export function holdGateRefusalAuditPayload(args) {
219
+ return {
220
+ gate: "hold",
221
+ // The load-bearing compliance fact: the operation did NOT proceed.
222
+ blocked: true,
223
+ reason: args.reason,
224
+ ...(args.holdKind ? { hold_kind: args.holdKind } : {}),
225
+ ...(args.statuteCitation ? { statute_citation: args.statuteCitation } : {}),
226
+ ...(args.error !== undefined ? { hold_gate_error: args.error } : {}),
227
+ };
228
+ }
41
229
  /**
42
230
  * The invariant half of {@link AmbiguousHoldFailureMode}'s message.
43
231
  *
@@ -47,32 +235,47 @@ import { DsarError } from "./types.js";
47
235
  * single 700-column one. Literal-to-literal `+` is not a `useTemplate`
48
236
  * violation — only concatenation with an interpolation is.
49
237
  */
50
- const AMBIGUOUS_HOLD_FAILURE_MODE_DETAIL = "the hold consult is fail-CLOSED by DEFAULT — a hold-read error BLOCKS the erase " +
51
- "(status FAILED, reason `hold_consult_failed_fail_closed`) instead of letting it " +
52
- "proceed. `false` used to be the default value, so it cannot be distinguished from " +
53
- "an un-revisited pin, and guessing wrong destroys data under a statutory hold. " +
54
- "If you genuinely want the old fail-OPEN behaviour, say so explicitly: pass " +
55
- "`allowFailOpenHolds: true` (and record why — it is a compliance-gate bypass). " +
56
- "Otherwise DELETE the option: the new default is what you want.";
238
+ const AMBIGUOUS_HOLD_FAILURE_MODE_DETAIL = "the hold consult is UNCONDITIONALLY fail-CLOSED — a hold-read error BLOCKS the " +
239
+ "erase (status FAILED, reason `hold_consult_failed_fail_closed`) instead of " +
240
+ "letting it proceed. Per the operator ruling of 2026-07-30 there is NO fail-open " +
241
+ "opt-out (the former `allowFailOpenHolds` flag is removed): if holds are " +
242
+ "inaccessible the write is denied — a spurious denial is just a retry once holds " +
243
+ "are reachable again, while a spurious erase under a hold destroys information " +
244
+ "that courts or an investigation may require. DELETE the option: fail-closed is " +
245
+ "the only behaviour.";
57
246
  /**
58
247
  * Thrown at BIND time when a caller passes the deprecated
59
- * `failClosedHolds: false`. R1 fail-fast: we refuse to silently interpret the
60
- * old default as an opt-out of the compliance-safe behaviour.
248
+ * `failClosedHolds: false`. R1 fail-fast: fail-open no longer exists
249
+ * (operator ruling 2026-07-30 — fail CLOSED, all twins), so an explicit
250
+ * `false` cannot be honored and must not be silently reinterpreted.
61
251
  */
62
252
  export class AmbiguousHoldFailureMode extends DsarError {
63
253
  constructor(who) {
64
- super(`${who}: \`failClosedHolds: false\` is no longer accepted. As of @nodii/dsar 0.16.0 ${AMBIGUOUS_HOLD_FAILURE_MODE_DETAIL}`);
254
+ super(
255
+ // VERSION ATTRIBUTION (corrected): 0.16.0 flipped the DEFAULT to
256
+ // fail-closed but KEPT the `allowFailOpenHolds` opt-out — it was never
257
+ // unconditional. The unconditional posture ships in THIS release, with
258
+ // the opt-out removed. The old wording ("As of @nodii/dsar 0.16.0 the
259
+ // hold consult is UNCONDITIONALLY fail-CLOSED") asserted a version fact
260
+ // this file contradicts 60 lines up, to the one audience — a booting
261
+ // operator — that cannot check.
262
+ `${who}: \`failClosedHolds: false\` is no longer accepted. @nodii/dsar 0.16.0 flipped the DEFAULT to fail-closed but still accepted an \`allowFailOpenHolds\` opt-out; as of THIS release ${AMBIGUOUS_HOLD_FAILURE_MODE_DETAIL}`);
65
263
  this.name = "AmbiguousHoldFailureMode";
66
264
  }
67
265
  }
68
266
  /**
69
- * Resolve whether a hold-consult ERROR should block the operation.
267
+ * Validate the (deprecated) hold-failure-mode options.
268
+ *
269
+ * The hold gate is UNCONDITIONALLY fail-closed (operator ruling 2026-07-30 —
270
+ * "If holds is inaccessible - we deny the write. ... Fail CLOSED."). This
271
+ * function survives only to reject the deprecated `failClosedHolds: false`
272
+ * loudly at bind time.
70
273
  *
71
- * @returns `true` when a consult error must BLOCK (fail-closed — the default).
274
+ * @returns `true`, always — a consult error ALWAYS blocks the operation.
72
275
  */
73
276
  export function resolveFailClosedHolds(who, opts) {
74
277
  if (opts.failClosedHolds === false)
75
278
  throw new AmbiguousHoldFailureMode(who);
76
- return opts.allowFailOpenHolds !== true;
279
+ return true;
77
280
  }
78
281
  //# sourceMappingURL=hold-failure-mode.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"hold-failure-mode.js","sourceRoot":"","sources":["../src/hold-failure-mode.ts"],"names":[],"mappings":"AAAA,yEAAyE;AACzE,iBAAiB;AACjB,EAAE;AACF,8CAA8C;AAC9C,8CAA8C;AAC9C,qEAAqE;AACrE,6EAA6E;AAC7E,2EAA2E;AAC3E,2EAA2E;AAC3E,uEAAuE;AACvE,EAAE;AACF,6EAA6E;AAC7E,wEAAwE;AACxE,+EAA+E;AAC/E,+EAA+E;AAC/E,2EAA2E;AAC3E,kEAAkE;AAClE,EAAE;AACF,iEAAiE;AACjE,mEAAmE;AACnE,mEAAmE;AACnE,EAAE;AACF,6EAA6E;AAC7E,EAAE;AACF,UAAU;AACV,UAAU;AACV,wEAAwE;AACxE,yDAAyD;AACzD,8BAA8B;AAC9B,EAAE;AACF,4EAA4E;AAC5E,wEAAwE;AACxE,2EAA2E;AAC3E,6EAA6E;AAC7E,8EAA8E;AAC9E,4EAA4E;AAC5E,2EAA2E;AAC3E,6EAA6E;AAC7E,2CAA2C;AAE3C,OAAO,EAAE,SAAS,EAAE,MAAM,YAAY,CAAC;AAEvC;;;;;;;;GAQG;AACH,MAAM,kCAAkC,GACtC,kFAAkF;IAClF,kFAAkF;IAClF,oFAAoF;IACpF,gFAAgF;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E,CAAC;QACtD,GAAG,CAAC,IAAI,CAAC,eAAe,CAAC,CAAC,CAAC,EAAE,gBAAgB,EAAE,IAAI,CAAC,eAAe,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;QAC3E,GAAG,CAAC,IAAI,CAAC,KAAK,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,eAAe,EAAE,IAAI,CAAC,KAAK,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;KACrE,CAAC;AACJ,CAAC;AAED;;;;;;;;GAQG;AACH,MAAM,kCAAkC,GACtC,iFAAiF;IACjF,6EAA6E;IAC7E,kFAAkF;IAClF,0EAA0E;IAC1E,kFAAkF;IAClF,gFAAgF;IAChF,iFAAiF;IACjF,qBAAqB,CAAC;AAExB;;;;;GAKG;AACH,MAAM,OAAO,wBAAyB,SAAQ,SAAS;IACrD,YAAY,GAAW;QACrB,KAAK;QACH,iEAAiE;QACjE,uEAAuE;QACvE,uEAAuE;QACvE,sEAAsE;QACtE,wEAAwE;QACxE,qEAAqE;QACrE,gCAAgC;QAChC,GAAG,GAAG,sLAAsL,kCAAkC,EAAE,CACjO,CAAC;QACF,IAAI,CAAC,IAAI,GAAG,0BAA0B,CAAC;IACzC,CAAC;CACF;AAaD;;;;;;;;;GASG;AACH,MAAM,UAAU,sBAAsB,CACpC,GAAW,EACX,IAAyB;IAEzB,IAAI,IAAI,CAAC,eAAe,KAAK,KAAK;QAAE,MAAM,IAAI,wBAAwB,CAAC,GAAG,CAAC,CAAC;IAC5E,OAAO,IAAI,CAAC;AACd,CAAC"}
package/dist/index.d.ts CHANGED
@@ -8,7 +8,7 @@ export { beginDsar, getDsar, listDsars, accessData, eraseData, portabilityExport
8
8
  export type { BeginDsarArgs, BeginDsarResult, GetDsarArgs, ListDsarsArgs, AccessDataArgs, AccessDataResult, EraseDataArgs, EraseDataResult, PortabilityExportArgs, PortabilityExportResult, RectifyArgs, RectifyResult, MarkCompleteArgs, MarkCompleteResult, AppealRejectionArgs, AppealRejectionResult, } from "./handlers.js";
9
9
  export { canonicalJson, CanonicalSerializationError, EventNonCanonical, } from "./canonical.js";
10
10
  export type { CanonicalValue } from "./canonical.js";
11
- export { AmbiguousHoldFailureMode, resolveFailClosedHolds, } from "./hold-failure-mode.js";
11
+ export { AmbiguousHoldFailureMode, HELD_WRITE_FAILED_REASON, HOLD_CONSULT_FAILED_REASON, HOLD_GATE_INFRA_REFUSAL_REASONS, holdGateRefusalAuditPayload, isNonMemoizableOutcome, resolveFailClosedHolds, } from "./hold-failure-mode.js";
12
12
  export type { HoldFailureModeOpts } from "./hold-failure-mode.js";
13
13
  export { applyRetention } from "./retention.js";
14
14
  export type { RetentionMatch } from "./retention.js";
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAoBA,eAAO,MAAM,QAAQ,SAAS,CAAC;AAC/B,eAAO,MAAM,OAAO,UAAU,CAAC;AAG/B,OAAO,EACL,QAAQ,EACR,aAAa,EACb,WAAW,EACX,cAAc,GACf,MAAM,WAAW,CAAC;AACnB,YAAY,EAAE,cAAc,EAAE,kBAAkB,EAAE,MAAM,WAAW,CAAC;AAEpE,OAAO,EAAE,iBAAiB,EAAE,MAAM,YAAY,CAAC;AAG/C,OAAO,EACL,oBAAoB,EACpB,qBAAqB,EACrB,sBAAsB,EACtB,kBAAkB,EAClB,mBAAmB,EACnB,oBAAoB,EACpB,sBAAsB,GACvB,MAAM,eAAe,CAAC;AAEvB,OAAO,EACL,SAAS,EACT,OAAO,EACP,SAAS,EACT,UAAU,EACV,SAAS,EACT,iBAAiB,EACjB,OAAO,EACP,YAAY,EACZ,eAAe,EACf,IAAI,EACJ,qBAAqB,EACrB,wBAAwB,GACzB,MAAM,eAAe,CAAC;AACvB,YAAY,EACV,aAAa,EACb,eAAe,EACf,WAAW,EACX,aAAa,EACb,cAAc,EACd,gBAAgB,EAChB,aAAa,EACb,eAAe,EACf,qBAAqB,EACrB,uBAAuB,EACvB,WAA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e,GAChB,MAAM,uBAAuB,CAAC;AAG/B,OAAO,EAAE,MAAM,EAAE,eAAe,EAAE,SAAS,EAAE,QAAQ,EAAE,MAAM,YAAY,CAAC;AAC1E,YAAY,EAAE,UAAU,EAAE,UAAU,EAAE,MAAM,YAAY,CAAC;AAGzD,OAAO,EACL,cAAc,EACd,mBAAmB,EACnB,0BAA0B,EAC1B,YAAY,EACZ,YAAY,EACZ,cAAc,EACd,kBAAkB,EAClB,kBAAkB,GACnB,MAAM,kBAAkB,CAAC;AAC1B,YAAY,EACV,kBAAkB,EAClB,oBAAoB,EACpB,kBAAkB,EAClB,kBAAkB,EAClB,cAAc,GACf,MAAM,kBAAkB,CAAC;AAG1B,OAAO,EAAE,UAAU,EAAE,WAAW,EAAE,MAAM,oBAAoB,CAAC;AAC7D,YAAY,EAAE,SAAS,EAAE,MAAM,oBAAoB,CAAC;AAGpD,OAAO,EACL,uBAAuB,EACvB,2BAA2B,EAC3B,uBAAuB,GACxB,MAAM,eAAe,CAAC"}
package/dist/index.js CHANGED
@@ -31,12 +31,21 @@ export { beginDsar, getDsar, listDsars, accessData, eraseData, portabilityExport
31
31
  // of that same class (so `instanceof` is unchanged) but is no longer a
32
32
  // `DsarError` subclass. See src/canonical.ts for the full rationale.
33
33
  export { canonicalJson, CanonicalSerializationError, EventNonCanonical, } from "./canonical.js";
34
- // 0.16.0 — the hold-consult failure mode. Fail-CLOSED is now the DEFAULT:
35
- // a hold-read error BLOCKS the erase. `allowFailOpenHolds: true` is the
36
- // explicit opt-out; the deprecated `failClosedHolds: false` throws
37
- // `AmbiguousHoldFailureMode` at bind time rather than silently re-opening
38
- // the compliance gate.
39
- export { AmbiguousHoldFailureMode, resolveFailClosedHolds, } from "./hold-failure-mode.js";
34
+ // The hold-consult failure mode. Fail-CLOSED, UNCONDITIONALLY (operator
35
+ // ruling 2026-07-30 — "If holds is inaccessible - we deny the write. ...
36
+ // Fail CLOSED.", all three twins): a hold-read error BLOCKS the erase. The
37
+ // former `allowFailOpenHolds` opt-out is REMOVED; the deprecated
38
+ // `failClosedHolds: false` throws `AmbiguousHoldFailureMode` at bind time —
39
+ // there is no fail-open to opt into.
40
+ //
41
+ // The refusal vocabulary is exported so a consumer can classify a refusal
42
+ // WITHOUT string-matching: `HOLD_CONSULT_FAILED_REASON` (holds unreadable —
43
+ // transient, retry) vs `HELD_WRITE_FAILED_REASON` (a hold is KNOWN, only its
44
+ // record failed — retrying is futile until the write path is fixed). Both are
45
+ // in `HOLD_GATE_INFRA_REFUSAL_REASONS`, and `isNonMemoizableOutcome` is the
46
+ // rule that keeps them out of the `lifecycle_requests` response cache so the
47
+ // ruling's "just a matter of a retry" is actually true.
48
+ export { AmbiguousHoldFailureMode, HELD_WRITE_FAILED_REASON, HOLD_CONSULT_FAILED_REASON, HOLD_GATE_INFRA_REFUSAL_REASONS, holdGateRefusalAuditPayload, isNonMemoizableOutcome, resolveFailClosedHolds, } from "./hold-failure-mode.js";
40
49
  export { applyRetention } from "./retention.js";
41
50
  export { DsarError, DsarNotInitialized, DsarNotFound, DsarStoreRequired, JustificationRequired, SubjectKindNotRegistered, DsarTerminalStateViolation, ExportGatherFailed, EraseExecutionFailed, HandlerAlreadyRegistered, CmkAdapterNotConfigured, CmkResolutionFailed, tenantCmkAliasAdapter, } from "./types.js";
42
51
  export { DEFAULT_ERASE_BLOCKING_HOLD_KINDS, STATUTORY_HOLD_KINDS, CITATION_REQUIRED_HOLD_KINDS,
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,sCAAsC;AACtC,EAAE;AACF,mEAAmE;AACnE,6CAA6C;AAC7C,EAAE;AACF,kBAAkB;AAClB,4DAA4D;AAC5D,4EAA4E;AAC5E,sEAAsE;AACtE,uEAAuE;AACvE,0EAA0E;AAC1E,0CAA0C;AAC1C,sDAAsD;AACtD,sEAAsE;AACtE,yEAAyE;AACzE,iFAAiF;AACjF,mDAAmD;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AC;AAE/B,mDAAmD;AACnD,OAAO,EAAE,MAAM,EAAE,eAAe,EAAE,SAAS,EAAE,QAAQ,EAAE,MAAM,YAAY,CAAC;AAG1E,yCAAyC;AACzC,OAAO,EACL,cAAc,EACd,mBAAmB,EACnB,0BAA0B,EAC1B,YAAY,EACZ,YAAY,EACZ,cAAc,EACd,kBAAkB,EAClB,kBAAkB,GACnB,MAAM,kBAAkB,CAAC;AAS1B,wCAAwC;AACxC,OAAO,EAAE,UAAU,EAAE,WAAW,EAAE,MAAM,oBAAoB,CAAC;AAG7D,gEAAgE;AAChE,OAAO,EACL,uBAAuB,EACvB,2BAA2B,EAC3B,uBAAuB,GACxB,MAAM,eAAe,CAAC"}
@@ -60,6 +60,48 @@ export declare function a1RlsDDL(table: string): string;
60
60
  */
61
61
  export declare function a1RlsMigrationBlock(table: string): string;
62
62
  export declare function getDsarMigrationSQL(): string;
63
+ /**
64
+ * THE DELIVERY UNIT — byte-equal inlined copy of `SESSION_FENCE_BOOTSTRAP_SQL`
65
+ * from `@nodii/db-rls`: the `auth.session_tenant_ids()` resolver that the
66
+ * policies below reference, plus the `auth.assert_tenant_fence()` gate.
67
+ *
68
+ * WHY THIS PACKAGE INSTALLS IT RATHER THAN DEMANDING SOMEBODY ELSE DID.
69
+ *
70
+ * The previous revision only CHECKED (`SESSION_RESOLVER_PRECONDITION_SQL`) and
71
+ * refused to migrate when the resolver was absent. That was correct as far as
72
+ * it went — it turned a silent, destructive half-migration into a clean refusal
73
+ * — but it left the service unable to boot, with no path to fix itself.
74
+ *
75
+ * There is no such path for most of the fleet. Measured, not assumed: of the
76
+ * ten services that call neither `applyAuthSchemaMigrations` nor
77
+ * `authSchemaHelpers`, SIX (billing, kyc, notification, task-tracking, tenant,
78
+ * geo) have NO database step in `deploy-dev.yml` at all — their `db:setup`
79
+ * runs only in `ci.yml`, against a throwaway Postgres. And a fleet-wide grep
80
+ * for `session_tenant_ids` across every service's vendored infra SQL returns
81
+ * ZERO files. So a refusal here is a service that cannot start and cannot be
82
+ * repaired by any pipeline that exists.
83
+ *
84
+ * Meanwhile THIS function already runs at boot in billing (`src/lib/bootstrap
85
+ * .ts`) and task-tracking (`src/bootstrap.ts`), against the real database, with
86
+ * owner privileges, immediately before the policies that need the resolver.
87
+ * That makes it the only reliable delivery channel these services have — so it
88
+ * delivers, rather than complaining that nobody else did.
89
+ *
90
+ * INLINED as a string constant, deliberately, so the published package carries
91
+ * NO dependency on `@nodii/db-rls` — the same posture as every other DDL
92
+ * constant in this module. The copy is asserted byte-equal to the db-rls
93
+ * original by `tests/fence-bootstrap-parity.test.ts`; it is not kept in step by
94
+ * anyone remembering to.
95
+ *
96
+ * SELF-CLASSIFYING. It installs the STRICT body where a real membership helper
97
+ * exists and the DEGRADED (fence-only, D415) body where `auth.user_tenant_ids`
98
+ * is absent or still the bootstrap stub. That distinction is derived from the
99
+ * catalog on every run, never from a per-service list — a list of exactly this
100
+ * kind was already wrong by six services on its first pass. It can upgrade
101
+ * degraded to strict once a mirror lands; it can never downgrade strict to
102
+ * degraded.
103
+ */
104
+ export declare const SESSION_FENCE_BOOTSTRAP_SQL = "CREATE SCHEMA IF NOT EXISTS auth;\nDO $fence_install$\nDECLARE\n v_src text;\n v_is_stub boolean;\nBEGIN\n SELECT p.prosrc INTO v_src\n FROM pg_proc p\n JOIN pg_namespace n ON n.oid = p.pronamespace\n WHERE n.nspname = 'auth' AND p.proname = 'user_tenant_ids'\n LIMIT 1;\n\n -- Structural, not an exact-string compare: the bootstrap stub is\n -- `SELECT NULL::uuid WHERE false` \u2014 an unsatisfiable WHERE and no FROM. A\n -- reformatted or re-indented copy of the same dead body still classifies as a\n -- stub. Mirrors isStubMembershipHelper() in tenant-fence.ts exactly; the two\n -- are asserted equivalent in the test-suite so a fix to one cannot leave the\n -- other behind.\n v_is_stub := v_src IS NULL\n OR (v_src ~* 'where\\s+false' AND v_src !~* 'from\\s+\\w');\n\n IF v_is_stub THEN\n EXECUTE $fence_degraded$CREATE OR REPLACE FUNCTION auth.session_tenant_ids() RETURNS SETOF uuid\nLANGUAGE plpgsql STABLE SECURITY DEFINER\nSET search_path = pg_catalog, public, pg_temp\nAS $session$\nDECLARE\n v_tenant uuid;\nBEGIN\n -- DB_RLS_DEGRADED_NO_MEMBERSHIP_MIRROR: no membership mirror in this service,\n -- so the session tenant is accepted WITHOUT proving the principal holds it.\n -- Replace with the strict resolver as soon as a mirror exists.\n IF nullif(current_setting('app.user_id', true), '') IS NULL THEN\n RAISE EXCEPTION 'db_rls_session_user_missing: app.user_id is not bound on this connection'\n USING ERRCODE = '42501',\n HINT = 'Open the session with withUserContext({ userId, tenantId }, fn) from @nodii/db-rls.';\n END IF;\n v_tenant := nullif(current_setting('app.tenant_id', true), '')::uuid;\n IF v_tenant IS NULL THEN\n RAISE EXCEPTION 'db_rls_session_tenant_missing: app.tenant_id is not bound on this connection'\n USING ERRCODE = '42501',\n HINT = 'Every authenticated-pool session must be EXPLICITLY tenant-scoped. Open it with withUserContext({ userId, tenantId }, fn) from @nodii/db-rls.';\n END IF;\n RETURN QUERY SELECT v_tenant;\nEND\n$session$;$fence_degraded$;\n ELSE\n EXECUTE $fence_strict$CREATE OR REPLACE FUNCTION auth.session_tenant_ids() RETURNS SETOF uuid\nLANGUAGE plpgsql STABLE SECURITY DEFINER\nSET search_path = pg_catalog, public, pg_temp\nAS $session$\nDECLARE\n v_user uuid;\n v_tenant uuid;\nBEGIN\n v_user := nullif(current_setting('app.user_id', true), '')::uuid;\n v_tenant := nullif(current_setting('app.tenant_id', true), '')::uuid;\n IF v_user IS NULL THEN\n RAISE EXCEPTION 'db_rls_session_user_missing: app.user_id is not bound on this connection'\n USING ERRCODE = '42501',\n HINT = 'The authenticated pool is the user-session pool; a session with no principal cannot be membership-checked. Open it with withUserContext({ userId, tenantId }, fn) from @nodii/db-rls.';\n END IF;\n IF v_tenant IS NULL THEN\n RAISE EXCEPTION 'db_rls_session_tenant_missing: app.tenant_id is not bound on this connection'\n USING ERRCODE = '42501',\n HINT = 'Every authenticated-pool session must be EXPLICITLY tenant-scoped. Open it with withUserContext({ userId, tenantId }, fn) from @nodii/db-rls.';\n END IF;\n RETURN QUERY SELECT v_tenant WHERE v_tenant IN (SELECT auth.user_tenant_ids(v_user));\nEND\n$session$;$fence_strict$;\n END IF;\nEND\n$fence_install$;\nCREATE SCHEMA IF NOT EXISTS auth;\nCREATE OR REPLACE FUNCTION auth._fence_reason(p_expr text) RETURNS text\nLANGUAGE sql IMMUTABLE\nSET search_path = pg_catalog, public, pg_temp\nAS $reason$\n SELECT CASE\n WHEN p_expr ~* '(auth\\s*\\.\\s*)?user_tenant_ids\\s*\\('\n THEN 'consults auth.user_tenant_ids directly instead of auth.session_tenant_ids() \u2014 resolves across EVERY tenant the principal belongs to'\n WHEN p_expr IS NULL OR btrim(p_expr) = '' OR p_expr ~* '^\\(?\\s*true\\s*\\)?$'\n THEN 'is permissive with no tenant reference at all \u2014 every tenant, every row'\n ELSE 'does not resolve through auth.session_tenant_ids() \u2014 it may be fenced some other way, but nothing here proves it, and an unrecognized shape is not a safe shape'\n END\n$reason$;\nCREATE OR REPLACE FUNCTION auth.assert_tenant_fence(\n p_schemas text[] DEFAULT ARRAY['public'],\n p_exempt_policies text[] DEFAULT ARRAY[]::text[],\n p_exempt_tables text[] DEFAULT ARRAY[]::text[],\n p_tenant_columns text[] DEFAULT ARRAY['tenant_id','org_id','organization_id'],\n p_allow_degraded boolean DEFAULT true\n) RETURNS void\nLANGUAGE plpgsql STABLE SECURITY DEFINER\nSET search_path = pg_catalog, public, pg_temp\nAS $fence_check$\nDECLARE\n v_offenders text[] := ARRAY[]::text[];\n v_row record;\n v_resolver record;\n v_membership record;\n v_degraded boolean := false;\nBEGIN\n -- ---------------------------------------------------------------------\n -- 1. The resolver itself. If it is missing, every policy referencing it is\n -- already broken, and nothing below can be interpreted.\n -- ---------------------------------------------------------------------\n SELECT p.prosrc, p.prosecdef INTO v_resolver\n FROM pg_proc p JOIN pg_namespace n ON n.oid = p.pronamespace\n WHERE n.nspname = 'auth' AND p.proname = 'session_tenant_ids' LIMIT 1;\n\n IF v_resolver IS NULL THEN\n RAISE EXCEPTION 'tenant_fence: auth.session_tenant_ids() is not installed'\n USING ERRCODE = 'P0001',\n HINT = 'Apply INSTALL_SESSION_RESOLVER_SQL (applyAuthSchemaMigrations ships it, and @nodii/saga + @nodii/dsar + @nodii/audit-chain install it before their policies).';\n END IF;\n\n v_degraded := v_resolver.prosrc LIKE '%DB_RLS_DEGRADED_NO_MEMBERSHIP_MIRROR%';\n\n IF v_resolver.prosrc !~* 'RAISE\\s+EXCEPTION' THEN\n v_offenders := v_offenders || 'auth.session_tenant_ids() [session_tenant_ids] does not RAISE on an unbound session \u2014 it was replaced with a NULL-returning getter, which restores silent failure';\n END IF;\n\n IF NOT v_resolver.prosecdef THEN\n v_offenders := v_offenders || 'auth.session_tenant_ids() [session_tenant_ids] is not SECURITY DEFINER \u2014 it cannot read the membership mirror (permission denied), or will recurse into the mirror''s own policy (54001)';\n END IF;\n\n IF v_degraded AND NOT p_allow_degraded THEN\n v_offenders := v_offenders || 'auth.session_tenant_ids() [session_tenant_ids] is the DEGRADED fence-only resolver \u2014 the session tenant is trusted WITHOUT proving membership';\n END IF;\n\n -- The stub check applies ONLY to the strict resolver. Under the degraded body\n -- auth.user_tenant_ids is never consulted, so a stub there is the expected,\n -- D415-sanctioned terminal state \u2014 not a defect. Flagging it would make every\n -- legitimately-degraded service permanently red, which is how a gate gets\n -- switched off.\n IF NOT v_degraded THEN\n SELECT p.prosrc INTO v_membership\n FROM pg_proc p JOIN pg_namespace n ON n.oid = p.pronamespace\n WHERE n.nspname = 'auth' AND p.proname = 'user_tenant_ids' LIMIT 1;\n IF v_membership IS NOT NULL\n AND v_membership.prosrc ~* 'where\\s+false'\n AND v_membership.prosrc !~* 'from\\s+\\w' THEN\n v_offenders := v_offenders || 'auth.user_tenant_ids(uuid) [user_tenant_ids] is still the bootstrap stub returning the empty set \u2014 the strict resolver intersects to nothing, so the authenticated pool is silently deny-all';\n END IF;\n END IF;\n\n -- ---------------------------------------------------------------------\n -- 2. The positive rule over every authenticated-applicable policy.\n -- ---------------------------------------------------------------------\n FOR v_row IN\n SELECT n.nspname AS schemaname,\n c.relname AS tablename,\n pol.polname AS policyname,\n CASE pol.polcmd WHEN 'r' THEN 'SELECT' WHEN 'a' THEN 'INSERT'\n WHEN 'w' THEN 'UPDATE' WHEN 'd' THEN 'DELETE'\n ELSE 'ALL' END AS cmd,\n pg_get_expr(pol.polqual, pol.polrelid) AS qual,\n pg_get_expr(pol.polwithcheck, pol.polrelid) AS with_check\n FROM pg_policy pol\n JOIN pg_class c ON c.oid = pol.polrelid\n JOIN pg_namespace n ON n.oid = c.relnamespace\n WHERE n.nspname = ANY(p_schemas)\n -- RESTRICTIVE policies are ANDed; they can only narrow access, so they\n -- cannot be the source of a cross-tenant grant.\n AND pol.polpermissive\n AND (\n EXISTS (SELECT 1 FROM unnest(pol.polroles) r WHERE r = 0)\n OR (\n EXISTS (SELECT 1 FROM pg_roles WHERE rolname = 'authenticated')\n AND EXISTS (\n SELECT 1 FROM unnest(pol.polroles) r\n WHERE pg_has_role('authenticated', r, 'USAGE')\n )\n )\n )\n AND NOT (pol.polname = ANY(p_exempt_policies))\n AND NOT ((c.relname || '.' || pol.polname) = ANY(p_exempt_policies))\n AND NOT (c.relname = ANY(p_exempt_tables))\n AND NOT ((n.nspname || '.' || c.relname) = ANY(p_exempt_tables))\n ORDER BY c.relname, pol.polname\n LOOP\n -- A policy with NEITHER clause is permissive-everything.\n IF v_row.qual IS NULL AND v_row.with_check IS NULL THEN\n v_offenders := v_offenders || format(\n '%s.%s [%s %s] is permissive with no tenant reference at all \u2014 every tenant, every row',\n v_row.schemaname, v_row.tablename, v_row.policyname, v_row.cmd);\n CONTINUE;\n END IF;\n\n -- EVERY clause present must resolve. A fenced read with an unfenced\n -- WITH CHECK is a cross-tenant WRITE, which is what the refund incident\n -- actually exercised.\n IF v_row.qual IS NOT NULL\n AND v_row.qual !~* '(auth\\s*\\.\\s*)?session_tenant_ids\\s*\\(' THEN\n v_offenders := v_offenders || format('%s.%s [%s %s USING] %s :: %s',\n v_row.schemaname, v_row.tablename, v_row.policyname, v_row.cmd,\n auth._fence_reason(v_row.qual), v_row.qual);\n END IF;\n\n IF v_row.with_check IS NOT NULL\n AND v_row.with_check !~* '(auth\\s*\\.\\s*)?session_tenant_ids\\s*\\(' THEN\n v_offenders := v_offenders || format('%s.%s [%s %s WITH CHECK] %s :: %s',\n v_row.schemaname, v_row.tablename, v_row.policyname, v_row.cmd,\n auth._fence_reason(v_row.with_check), v_row.with_check);\n END IF;\n END LOOP;\n\n -- ---------------------------------------------------------------------\n -- 3. Table coverage. THE HOLE A POLICY-LEVEL CHECK CANNOT SEE: a table with\n -- a tenant column and RLS switched off has no rows in pg_policy to\n -- inspect, and under the canonical blanket grants it is readable AND\n -- writable across every tenant \u2014 strictly more open than the union\n -- predicate this release removes.\n --\n -- Discovered FROM THE CATALOG, never from a caller-supplied list. The\n -- author who forgets ENABLE ROW LEVEL SECURITY is the same author who\n -- forgets the list entry, in the same migration.\n -- ---------------------------------------------------------------------\n FOR v_row IN\n SELECT n.nspname AS schemaname, c.relname AS tablename,\n c.relkind::text AS relkind, c.relrowsecurity,\n COALESCE((SELECT true FROM unnest(COALESCE(c.reloptions,'{}')) o\n WHERE lower(replace(o,' ','')) = 'security_invoker=true'), false) AS security_invoker\n FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace\n WHERE c.relkind = ANY('{r,p,v,m,f}')\n AND n.nspname = ANY(p_schemas)\n AND NOT (c.relname = ANY(p_exempt_tables))\n AND NOT ((n.nspname || '.' || c.relname) = ANY(p_exempt_tables))\n AND EXISTS (SELECT 1 FROM pg_attribute a\n WHERE a.attrelid = c.oid AND a.attnum > 0\n AND NOT a.attisdropped AND a.attname = ANY(p_tenant_columns))\n ORDER BY n.nspname, c.relname\n LOOP\n IF v_row.relkind IN ('v','m','f') THEN\n -- A view with security_invoker=true executes as the CALLER, so the\n -- underlying table's RLS applies and the view is genuinely safe.\n IF v_row.relkind = 'v' AND v_row.security_invoker THEN CONTINUE; END IF;\n v_offenders := v_offenders || format(\n '%s.%s exposes a tenant column but cannot enforce RLS (relkind=%s) \u2014 a materialized/foreign relation has no row policies at all, and a view without security_invoker=true runs as its OWNER and bypasses the underlying table''s policies',\n v_row.schemaname, v_row.tablename, v_row.relkind);\n ELSIF NOT v_row.relrowsecurity THEN\n v_offenders := v_offenders || format(\n '%s.%s has a tenant column but ROW LEVEL SECURITY is NOT ENABLED \u2014 with the canonical blanket grants this table is readable and writable across EVERY tenant, and no policy is ever consulted',\n v_row.schemaname, v_row.tablename);\n END IF;\n END LOOP;\n\n IF array_length(v_offenders, 1) > 0 THEN\n RAISE EXCEPTION 'tenant_fence: % authenticated-pool policy/helper defect(s). A user session must reach exactly ONE tenant \u2014 the one the edge resolved from the request \u2014 and nothing else, ever.%',\n array_length(v_offenders, 1),\n E'\\n - ' || array_to_string(v_offenders, E'\\n - ')\n USING ERRCODE = 'P0001',\n HINT = 'Regenerate policies with @nodii/db-rls withRls() / generateRlsPolicy(), which emit \"<col> IN (SELECT auth.session_tenant_ids())\". Nodii-staff cross-tenant access is a different path entirely: the platform_ops pool + withPlatformOpsContext.';\n END IF;\nEND\n$fence_check$;\nGRANT EXECUTE ON FUNCTION auth._fence_reason(text) TO PUBLIC;\n";
63
105
  /**
64
106
  * PRECONDITION. Fails the migration BEFORE it drops anything if the resolver
65
107
  * `auth.session_tenant_ids()` is absent.
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/migrations/index.ts"],"names":[],"mappings":"AAQA,KAAK,SAAS,GAAG;IAEf,MAAM,EAAE,CAAC,GAAG,EAAE,MAAM,EAAE,IAAI,CAAC,EAAE,OAAO,EAAE,KAAK,OAAO,CAAC,GAAG,CAAC,CAAC;CACzD,CAAC;AAwMF;;;;;;;;;;;;;;;;;;;;;;;;;;;GA2BG;AACH,wB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