@zanii/health 0.1.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.
- package/LICENSE +159 -0
- package/README.md +117 -0
- package/dist/index.d.ts +190 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +247 -0
- package/dist/index.js.map +1 -0
- package/package.json +42 -0
- package/src/index.ts +366 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,159 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or Derivative
|
|
95
|
+
Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work; and
|
|
103
|
+
|
|
104
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
105
|
+
distribution, then any Derivative Works that You distribute must
|
|
106
|
+
include a readable copy of the attribution notices contained
|
|
107
|
+
within such NOTICE file.
|
|
108
|
+
|
|
109
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
110
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
111
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
112
|
+
this License, without any additional terms or conditions.
|
|
113
|
+
|
|
114
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
115
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
116
|
+
except as required for reasonable and customary use in describing the
|
|
117
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
118
|
+
|
|
119
|
+
7. Disclaimer of Warranty. Unless required by applicable law or agreed
|
|
120
|
+
to in writing, Licensor provides the Work (and each Contributor
|
|
121
|
+
provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES
|
|
122
|
+
OR CONDITIONS OF ANY KIND, either express or implied, including,
|
|
123
|
+
without limitation, any warranties or conditions of TITLE,
|
|
124
|
+
NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE.
|
|
125
|
+
|
|
126
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
127
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
128
|
+
unless required by applicable law (such as deliberate and grossly
|
|
129
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
130
|
+
liable to You for damages, including any direct, indirect, special,
|
|
131
|
+
incidental, or consequential damages of any character arising as a
|
|
132
|
+
result of this License or out of the use or inability to use the
|
|
133
|
+
Work.
|
|
134
|
+
|
|
135
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
136
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
137
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
138
|
+
or other liability obligations and/or rights consistent with this
|
|
139
|
+
License. However, in accepting such obligations, You may act only
|
|
140
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
141
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
142
|
+
defend, and hold each Contributor harmless for any liability
|
|
143
|
+
incurred by, or claims asserted against, such Contributor.
|
|
144
|
+
|
|
145
|
+
END OF TERMS AND CONDITIONS
|
|
146
|
+
|
|
147
|
+
Copyright 2026 Zanii
|
|
148
|
+
|
|
149
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
150
|
+
you may not use this file except in compliance with the License.
|
|
151
|
+
You may obtain a copy of the License at
|
|
152
|
+
|
|
153
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
154
|
+
|
|
155
|
+
Unless required by applicable law or agreed to in writing, software
|
|
156
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
157
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
158
|
+
See the License for the specific language governing permissions and
|
|
159
|
+
limitations under the License.
|
package/README.md
ADDED
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
# @zanii/health
|
|
2
|
+
|
|
3
|
+
**Medical audit trails without leaking the pattern.**
|
|
4
|
+
|
|
5
|
+
For medicine, **the metadata *is* the sensitive data.** Zanii's usual privacy story ("we store
|
|
6
|
+
only hashes; payloads never leave your systems") is what makes it safe everywhere else — and it
|
|
7
|
+
is exactly what fails here. A stable public subject slice leaks *that* a record was opened, by
|
|
8
|
+
how many parties, how often, and when. **Access frequency to an oncology or psychiatric record
|
|
9
|
+
is itself PHI.**
|
|
10
|
+
|
|
11
|
+
So this package deliberately breaks the one property Zanii otherwise relies on — a single,
|
|
12
|
+
stable, linkable identifier per subject.
|
|
13
|
+
|
|
14
|
+
> **Design target: an episode is verifiable; a life is not linkable except by the patient.**
|
|
15
|
+
|
|
16
|
+
**Threat model** (it decides everything): we do **not** need to hide the encounter from the
|
|
17
|
+
treating provider — they hold the chart. We must stop *everyone else* — a second provider, an
|
|
18
|
+
insurer, **the log operator** — from **linking encounters into a history**.
|
|
19
|
+
|
|
20
|
+
## 🔴 The rule that makes or breaks this
|
|
21
|
+
|
|
22
|
+
> **The patient supplies the TAG. The patient never supplies the SEED.**
|
|
23
|
+
|
|
24
|
+
If a provider held the seed it could enumerate `n = 1, 2, 3…` and reconstruct the patient's
|
|
25
|
+
**entire cross-institution history** — the privacy gain would be zero, and *illusory*. The
|
|
26
|
+
patient's app derives the tag for **this** encounter and hands over one opaque string.
|
|
27
|
+
|
|
28
|
+
There is a **red test** (`the seed must never reach a provider`) in both languages, existing
|
|
29
|
+
purely so nobody "optimises" the seed into the provider's hands later.
|
|
30
|
+
|
|
31
|
+
```sh
|
|
32
|
+
npm install @zanii/health @zanii/core
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
```ts
|
|
36
|
+
import { episodeSeed, episodeTag, buildAccessReceipt, buildRecommendation,
|
|
37
|
+
buildClinicianConfirmation, buildBreakGlass, fetchEpisodes } from '@zanii/health';
|
|
38
|
+
|
|
39
|
+
// patient app (device keystore) — the seed never leaves here
|
|
40
|
+
const seed = episodeSeed();
|
|
41
|
+
const tag = episodeTag(seed, 12); // hand THIS to the provider, and nothing else
|
|
42
|
+
|
|
43
|
+
// provider side — learns one encounter, nothing about any other
|
|
44
|
+
await zanii.record({ ...buildAccessReceipt({ episodeTag: tag, actor: clinician.did,
|
|
45
|
+
purpose: 'treatment', consentRef, ts }), subjectTag: tag });
|
|
46
|
+
|
|
47
|
+
// patient side — the only party who can link the chain
|
|
48
|
+
const history = await fetchEpisodes(seed);
|
|
49
|
+
history.pendingBreakGlass; // emergency access on my record that nobody reviewed
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
## The four-party question (what a malpractice case actually turns on)
|
|
53
|
+
|
|
54
|
+
| Question | Receipt |
|
|
55
|
+
|---|---|
|
|
56
|
+
| **Who accessed the record?** | `health.access` — actor `did:key`, **purpose** (limitation is not optional), consent ref |
|
|
57
|
+
| **Which model recommended what?** | `health.recommendation` — `model_id` + `runtime_hash` |
|
|
58
|
+
| **Under which clinical protocol?** | same receipt — **`manifest_hash` is required**; a recommendation with no protocol on record is rejected |
|
|
59
|
+
| **Which *named human* took responsibility?** | `health.confirmation` — the **clinician signs personally**. The model did not decide; a person did. |
|
|
60
|
+
|
|
61
|
+
## `protocolTrail` is **not** `ruleConsistency` — and that distinction is clinical
|
|
62
|
+
|
|
63
|
+
In `@zanii/gov`, *"the same rulebook decided everyone"* is the fairness property and
|
|
64
|
+
**interleaved rulebooks are a red flag**. **That does not transfer to medicine.**
|
|
65
|
+
|
|
66
|
+
**Individualised care is correct.** Protocols legitimately coexist — comorbidities, cohorts,
|
|
67
|
+
trial arms. Flagging interleaved protocols would false-alarm on *good medicine* and train
|
|
68
|
+
clinicians to ignore the tool. So `protocolTrail` reports **disclosure and change**, and passes
|
|
69
|
+
**no verdict on uniformity** (there is no `consistent` field to fail):
|
|
70
|
+
|
|
71
|
+
- **which** protocol governed each recommendation,
|
|
72
|
+
- **when** protocols changed,
|
|
73
|
+
- **deviation** — recorded, *never* prevented, and **never treated as a defect** (departing from
|
|
74
|
+
a protocol is legitimate and common),
|
|
75
|
+
- **`unprotocolled`** — a recommendation with **no** protocol. *That* is the defect.
|
|
76
|
+
|
|
77
|
+
## Break-glass: **loud, not impossible**
|
|
78
|
+
|
|
79
|
+
An unconscious patient supplies no tag — yet care must proceed **and be recorded**. Break-glass
|
|
80
|
+
is the classic PHI-snooping vector (the celebrity-record case), so:
|
|
81
|
+
|
|
82
|
+
- **every break-glass emits a receipt** — a `reason` is mandatory;
|
|
83
|
+
- the **acting clinician signs it personally** — a named human puts their name on it, and *that
|
|
84
|
+
signature is the deterrent*;
|
|
85
|
+
- **`pendingBreakGlass()`** counts events with no review on record — visible in the
|
|
86
|
+
institution's own audit **and to the patient**.
|
|
87
|
+
|
|
88
|
+
**We ship the metric, not the mandate.** We do not enforce a review policy we have no power to
|
|
89
|
+
enforce — we make **ignoring it undeniable**. A regulator can *require* review; the institution
|
|
90
|
+
**cannot hide that it didn't do it.**
|
|
91
|
+
|
|
92
|
+
> **This is a hole we deliberately keep open — a closed one kills patients.**
|
|
93
|
+
|
|
94
|
+
## Honest limits (read these)
|
|
95
|
+
|
|
96
|
+
- **We hide linkage, not existence.** An episode is verifiable; a life is not linkable except by
|
|
97
|
+
the patient. Anyone who obtains **one** tag still learns **that encounter's provider** — and
|
|
98
|
+
for a single-specialty clinic, that lone inference is itself sensitive. **Cannot be
|
|
99
|
+
eliminated; must be disclosed.**
|
|
100
|
+
- **Seed loss ≠ record loss.** Lose the seed and you lose *linkability of past episodes* — the
|
|
101
|
+
chart persists, care is unaffected. The system degrades to *unlinkable*, never *lost*. This is
|
|
102
|
+
precisely why we can refuse dangerous recovery schemes.
|
|
103
|
+
- **No social/Shamir recovery — deliberately.** In health, **the guardians are frequently the
|
|
104
|
+
adversary** (coercion, abuse, an employer who is also a relative). Social recovery is right for
|
|
105
|
+
a wallet and wrong for a medical history. Use a device keystore + an offline recovery code.
|
|
106
|
+
- **Institution-held seed escrow is a labelled downgrade, never a default.** If your provider can
|
|
107
|
+
decrypt the seed, they can link your history. Say it in those words.
|
|
108
|
+
- **A permissioned slice reintroduces server trust for confidentiality.** It stops opportunistic
|
|
109
|
+
pattern-mining, **not the operator**. Deploy sovereign where that matters.
|
|
110
|
+
- **This proves the process, not the medicine.** Which model, which protocol, which clinician
|
|
111
|
+
signed — never that the treatment was *right*.
|
|
112
|
+
|
|
113
|
+
## Changelog
|
|
114
|
+
- **0.1.0** — initial release: `episodeSeed`/`episodeTag`/`episodeTags` (unlinkable per-episode identity), `buildAccessReceipt`, `buildRecommendation` (protocol required), `buildClinicianConfirmation`, `buildBreakGlass` + `pendingBreakGlass`/`markReviewed`, `protocolTrail` (**not** `ruleConsistency`), `fetchEpisodes`.
|
|
115
|
+
|
|
116
|
+
## License
|
|
117
|
+
Apache-2.0.
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,190 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @zanii/health — medical audit trails **without leaking the pattern**.
|
|
3
|
+
*
|
|
4
|
+
* For medicine, the metadata IS the sensitive data. Zanii's usual privacy story ("we store
|
|
5
|
+
* only hashes") is what makes it safe everywhere else — and it is exactly what fails here:
|
|
6
|
+
* a stable public `subject_tag` slice leaks *that* a record was opened, by how many parties,
|
|
7
|
+
* how often, and when. **Access frequency to an oncology or psychiatric record is itself
|
|
8
|
+
* PHI.** So this package breaks the one property Zanii otherwise relies on: a single, stable,
|
|
9
|
+
* linkable identifier per subject.
|
|
10
|
+
*
|
|
11
|
+
* **Design target: an episode is verifiable; a life is not linkable except by the patient.**
|
|
12
|
+
*
|
|
13
|
+
* Threat model (it decides everything): we do NOT need to hide the encounter from the
|
|
14
|
+
* treating provider — they hold the chart. We must stop *anyone else* — a second provider,
|
|
15
|
+
* an insurer, the log operator — from **linking encounters into a history**.
|
|
16
|
+
*
|
|
17
|
+
* ## The rule that makes or breaks this
|
|
18
|
+
*
|
|
19
|
+
* **The patient supplies the TAG. The patient never supplies the SEED.**
|
|
20
|
+
*
|
|
21
|
+
* If a provider held the seed it could enumerate `n = 1, 2, 3…` and reconstruct the patient's
|
|
22
|
+
* entire cross-institution history — the privacy gain would be zero, and *illusory*. The
|
|
23
|
+
* patient's app derives the tag for THIS encounter and hands over one opaque string. There is
|
|
24
|
+
* a red test guarding this (`a provider holding the seed can link everything`) so nobody
|
|
25
|
+
* "optimises" the seed into the provider's hands later.
|
|
26
|
+
*
|
|
27
|
+
* Answers the four-party question that actually decides a malpractice case:
|
|
28
|
+
* **who accessed the record, which model recommended what, under which protocol version, and
|
|
29
|
+
* which named human took responsibility.**
|
|
30
|
+
*/
|
|
31
|
+
import { type ActionConfirmation } from '@zanii/core';
|
|
32
|
+
export type FetchLike = (input: string, init?: RequestInit) => Promise<Response>;
|
|
33
|
+
/**
|
|
34
|
+
* The patient's episode seed. **Never leaves the patient.** Held in a device keystore with
|
|
35
|
+
* an offline recovery code — deliberately NOT social/Shamir recovery: in health the
|
|
36
|
+
* guardians are frequently the adversary (coercion, abuse, an employer who is also a
|
|
37
|
+
* relative). We can refuse it because **seed loss ≠ record loss**: you lose linkability of
|
|
38
|
+
* past episodes, never the chart.
|
|
39
|
+
*/
|
|
40
|
+
export interface EpisodeSeed {
|
|
41
|
+
v: 1;
|
|
42
|
+
/** 32 bytes of entropy, hex. The secret. */
|
|
43
|
+
secret: string;
|
|
44
|
+
}
|
|
45
|
+
/** Generate a patient seed. Store in a device keystore; back up with an offline code. */
|
|
46
|
+
export declare function episodeSeed(secretHex?: string): EpisodeSeed;
|
|
47
|
+
/**
|
|
48
|
+
* The tag for encounter `n`. Derived by the PATIENT and handed to the provider as one opaque
|
|
49
|
+
* string. Unlinkable: two tags from the same patient are not relatable without the seed.
|
|
50
|
+
*/
|
|
51
|
+
export declare function episodeTag(seed: EpisodeSeed, n: number): string;
|
|
52
|
+
/** The patient's own chain — only they can enumerate it. */
|
|
53
|
+
export declare function episodeTags(seed: EpisodeSeed, from: number, to: number): string[];
|
|
54
|
+
export interface HealthReceipt {
|
|
55
|
+
target: string;
|
|
56
|
+
payload: Record<string, unknown>;
|
|
57
|
+
/** Stamp this as the receipt's `subjectTag` — it is the episode tag, not a patient id. */
|
|
58
|
+
subjectTag: string;
|
|
59
|
+
/** Keep to disclose committed details later (dispute/audit). */
|
|
60
|
+
nonce: string;
|
|
61
|
+
}
|
|
62
|
+
export interface AccessInput {
|
|
63
|
+
episodeTag: string;
|
|
64
|
+
/** The clinician or system that opened the record (`did:key`). */
|
|
65
|
+
actor: string;
|
|
66
|
+
/** Why — `treatment`, `billing`, `research`. Purpose limitation is a PDPL/HIPAA hinge. */
|
|
67
|
+
purpose: string;
|
|
68
|
+
/** Reference to the consent receipt in force at access time (`@zanii/consent`). */
|
|
69
|
+
consentRef?: string;
|
|
70
|
+
/** Details that must not sit in the clear (department, record section). Salt-committed. */
|
|
71
|
+
details?: Record<string, unknown>;
|
|
72
|
+
ts: string;
|
|
73
|
+
}
|
|
74
|
+
/** Who accessed the record. `health.access` */
|
|
75
|
+
export declare function buildAccessReceipt(input: AccessInput): HealthReceipt;
|
|
76
|
+
export interface RecommendationInput {
|
|
77
|
+
episodeTag: string;
|
|
78
|
+
/** The model that produced the recommendation. */
|
|
79
|
+
modelId: string;
|
|
80
|
+
/** The deployed runtime that ran it. */
|
|
81
|
+
runtimeHash?: string;
|
|
82
|
+
/** REQUIRED — the clinical protocol/guideline version that governed this. */
|
|
83
|
+
manifestHash: string;
|
|
84
|
+
/** The recommendation itself, e.g. `{ code: 'CHEMO-A', line: 2 }`. */
|
|
85
|
+
outcome: Record<string, unknown>;
|
|
86
|
+
/**
|
|
87
|
+
* Departing from the governing protocol is **legitimate and common** in medicine. It is
|
|
88
|
+
* recorded, never prevented — and never treated as a defect.
|
|
89
|
+
*/
|
|
90
|
+
deviation?: {
|
|
91
|
+
from: string;
|
|
92
|
+
rationale: string;
|
|
93
|
+
};
|
|
94
|
+
ts: string;
|
|
95
|
+
}
|
|
96
|
+
/** Which model recommended what, under which protocol. `health.recommendation` */
|
|
97
|
+
export declare function buildRecommendation(input: RecommendationInput): HealthReceipt;
|
|
98
|
+
/**
|
|
99
|
+
* Which **named human** took responsibility. `health.confirmation`
|
|
100
|
+
*
|
|
101
|
+
* The clinician signs the recommendation with their own key — the model did not decide, a
|
|
102
|
+
* person did. This is the artifact a malpractice case turns on.
|
|
103
|
+
*/
|
|
104
|
+
export declare function buildClinicianConfirmation(input: {
|
|
105
|
+
episodeTag: string;
|
|
106
|
+
clinicianDid: string;
|
|
107
|
+
recommendationHash: string;
|
|
108
|
+
confirmedAt: string;
|
|
109
|
+
}, clinicianPrivateKey: Uint8Array): HealthReceipt & {
|
|
110
|
+
confirmation: ActionConfirmation;
|
|
111
|
+
};
|
|
112
|
+
/** A clinician's confirmation is valid only if signed by that clinician. */
|
|
113
|
+
export declare function verifyClinicianConfirmation(payload: Record<string, unknown> | undefined): boolean;
|
|
114
|
+
export interface BreakGlassInput {
|
|
115
|
+
/** Provider-derived, because an unconscious patient supplies no tag. Claimable later. */
|
|
116
|
+
episodeTag: string;
|
|
117
|
+
/** The clinician who is personally accountable. NOT merely the system. */
|
|
118
|
+
clinicianDid: string;
|
|
119
|
+
reason: string;
|
|
120
|
+
ts: string;
|
|
121
|
+
}
|
|
122
|
+
/**
|
|
123
|
+
* Emergency access. `health.break_glass`
|
|
124
|
+
*
|
|
125
|
+
* **A hole we deliberately keep open — a closed one kills patients. We make it LOUD, not
|
|
126
|
+
* impossible.** Break-glass is the classic PHI-snooping vector (the celebrity-record case),
|
|
127
|
+
* so: the acting clinician signs it **personally** — a named human puts their name on it, and
|
|
128
|
+
* that signature is the deterrent. Un-reviewed break-glass is a countable defect
|
|
129
|
+
* (`pendingBreakGlass`), visible in the institution's own audit and to the patient on claim.
|
|
130
|
+
*
|
|
131
|
+
* We ship the **metric, not the mandate**: we do not enforce a review policy we have no power
|
|
132
|
+
* to enforce — we make **ignoring it undeniable**.
|
|
133
|
+
*/
|
|
134
|
+
export declare function buildBreakGlass(input: BreakGlassInput, clinicianPrivateKey: Uint8Array): HealthReceipt & {
|
|
135
|
+
confirmation: ActionConfirmation;
|
|
136
|
+
};
|
|
137
|
+
/** Mark a break-glass reviewed — the institution's own audit artifact. */
|
|
138
|
+
export declare function markReviewed(payload: Record<string, unknown>, reviewer: string, ts: string): Record<string, unknown>;
|
|
139
|
+
/**
|
|
140
|
+
* **The metric, not the mandate.** Break-glass events with no review on record.
|
|
141
|
+
* A regulator can *require* review; the institution cannot hide that it didn't.
|
|
142
|
+
*/
|
|
143
|
+
export declare function pendingBreakGlass(payloads: Array<Record<string, unknown>>): Array<Record<string, unknown>>;
|
|
144
|
+
export interface ProtocolWindow {
|
|
145
|
+
manifest_hash: string;
|
|
146
|
+
count: number;
|
|
147
|
+
first_ts: string;
|
|
148
|
+
last_ts: string;
|
|
149
|
+
}
|
|
150
|
+
export interface ProtocolTrail {
|
|
151
|
+
protocols: ProtocolWindow[];
|
|
152
|
+
/** Recommendations that departed from their governing protocol — legitimate, recorded, NOT a defect. */
|
|
153
|
+
deviations: number;
|
|
154
|
+
/** Recommendations with NO protocol on record. THIS is the defect. */
|
|
155
|
+
unprotocolled: number;
|
|
156
|
+
}
|
|
157
|
+
/**
|
|
158
|
+
* Which protocol governed what, and when protocols changed.
|
|
159
|
+
*
|
|
160
|
+
* **Deliberately NOT `ruleConsistency`.** In government, "the same rulebook decided everyone"
|
|
161
|
+
* is the fairness property and interleaving is a red flag. **In medicine, individualised care
|
|
162
|
+
* is CORRECT** — protocols legitimately coexist (comorbidities, cohorts, trial arms). Flagging
|
|
163
|
+
* interleaved protocols would false-alarm on *good medicine* and train clinicians to ignore
|
|
164
|
+
* the tool. So we report **disclosure and change**, and pass **no verdict on uniformity**.
|
|
165
|
+
*/
|
|
166
|
+
export declare function protocolTrail(payloads: Array<Record<string, unknown>>): ProtocolTrail;
|
|
167
|
+
export interface EpisodeHistory {
|
|
168
|
+
episodes: Array<{
|
|
169
|
+
n: number;
|
|
170
|
+
tag: string;
|
|
171
|
+
receipts: Array<Record<string, unknown>>;
|
|
172
|
+
}>;
|
|
173
|
+
/** Total receipts across the chain. */
|
|
174
|
+
total: number;
|
|
175
|
+
/** Break-glass events on this patient with no review recorded. */
|
|
176
|
+
pendingBreakGlass: number;
|
|
177
|
+
protocols: ProtocolTrail;
|
|
178
|
+
}
|
|
179
|
+
/**
|
|
180
|
+
* Fetch and merge the patient's episode chain. **Only the seed-holder can do this** — which
|
|
181
|
+
* is the entire point. `@zanii/subject`'s `fetchSubjectHistory` is one-tag-at-a-time; this is
|
|
182
|
+
* the multi-tag fetch it lacks.
|
|
183
|
+
*/
|
|
184
|
+
export declare function fetchEpisodes(seed: EpisodeSeed, opts?: {
|
|
185
|
+
server?: string;
|
|
186
|
+
fetchImpl?: FetchLike;
|
|
187
|
+
from?: number;
|
|
188
|
+
to?: number;
|
|
189
|
+
}): Promise<EpisodeHistory>;
|
|
190
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA6BG;AACH,OAAO,EAAsE,KAAK,kBAAkB,EAAE,MAAM,aAAa,C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AAC;IAAC,IAAI,CAAC,EAAE,MAAM,CAAC;IAAC,EAAE,CAAC,EAAE,MAAM,CAAA;CAAO,GAChF,OAAO,CAAC,cAAc,CAAC,CA2BzB"}
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,247 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @zanii/health — medical audit trails **without leaking the pattern**.
|
|
3
|
+
*
|
|
4
|
+
* For medicine, the metadata IS the sensitive data. Zanii's usual privacy story ("we store
|
|
5
|
+
* only hashes") is what makes it safe everywhere else — and it is exactly what fails here:
|
|
6
|
+
* a stable public `subject_tag` slice leaks *that* a record was opened, by how many parties,
|
|
7
|
+
* how often, and when. **Access frequency to an oncology or psychiatric record is itself
|
|
8
|
+
* PHI.** So this package breaks the one property Zanii otherwise relies on: a single, stable,
|
|
9
|
+
* linkable identifier per subject.
|
|
10
|
+
*
|
|
11
|
+
* **Design target: an episode is verifiable; a life is not linkable except by the patient.**
|
|
12
|
+
*
|
|
13
|
+
* Threat model (it decides everything): we do NOT need to hide the encounter from the
|
|
14
|
+
* treating provider — they hold the chart. We must stop *anyone else* — a second provider,
|
|
15
|
+
* an insurer, the log operator — from **linking encounters into a history**.
|
|
16
|
+
*
|
|
17
|
+
* ## The rule that makes or breaks this
|
|
18
|
+
*
|
|
19
|
+
* **The patient supplies the TAG. The patient never supplies the SEED.**
|
|
20
|
+
*
|
|
21
|
+
* If a provider held the seed it could enumerate `n = 1, 2, 3…` and reconstruct the patient's
|
|
22
|
+
* entire cross-institution history — the privacy gain would be zero, and *illusory*. The
|
|
23
|
+
* patient's app derives the tag for THIS encounter and hands over one opaque string. There is
|
|
24
|
+
* a red test guarding this (`a provider holding the seed can link everything`) so nobody
|
|
25
|
+
* "optimises" the seed into the provider's hands later.
|
|
26
|
+
*
|
|
27
|
+
* Answers the four-party question that actually decides a malpractice case:
|
|
28
|
+
* **who accessed the record, which model recommended what, under which protocol version, and
|
|
29
|
+
* which named human took responsibility.**
|
|
30
|
+
*/
|
|
31
|
+
import { createConfirmation, jcsHash, saltedPayloadHash, verifyConfirmation } from '@zanii/core';
|
|
32
|
+
/** Generate a patient seed. Store in a device keystore; back up with an offline code. */
|
|
33
|
+
export function episodeSeed(secretHex) {
|
|
34
|
+
const secret = secretHex ?? bytesToHexLocal(cryptoRandom(32));
|
|
35
|
+
if (!/^[0-9a-f]{64}$/.test(secret))
|
|
36
|
+
throw new Error('seed secret must be 32 bytes of hex');
|
|
37
|
+
return { v: 1, secret };
|
|
38
|
+
}
|
|
39
|
+
function cryptoRandom(n) {
|
|
40
|
+
const out = new Uint8Array(n);
|
|
41
|
+
globalThis.crypto.getRandomValues(out);
|
|
42
|
+
return out;
|
|
43
|
+
}
|
|
44
|
+
function bytesToHexLocal(b) {
|
|
45
|
+
return [...b].map((x) => x.toString(16).padStart(2, '0')).join('');
|
|
46
|
+
}
|
|
47
|
+
/**
|
|
48
|
+
* The tag for encounter `n`. Derived by the PATIENT and handed to the provider as one opaque
|
|
49
|
+
* string. Unlinkable: two tags from the same patient are not relatable without the seed.
|
|
50
|
+
*/
|
|
51
|
+
export function episodeTag(seed, n) {
|
|
52
|
+
if (!Number.isInteger(n) || n < 0)
|
|
53
|
+
throw new Error('n must be a non-negative integer');
|
|
54
|
+
return jcsHash({ v: 1, type: 'episode_tag', secret: seed.secret, n });
|
|
55
|
+
}
|
|
56
|
+
/** The patient's own chain — only they can enumerate it. */
|
|
57
|
+
export function episodeTags(seed, from, to) {
|
|
58
|
+
const out = [];
|
|
59
|
+
for (let n = from; n <= to; n++)
|
|
60
|
+
out.push(episodeTag(seed, n));
|
|
61
|
+
return out;
|
|
62
|
+
}
|
|
63
|
+
/** Who accessed the record. `health.access` */
|
|
64
|
+
export function buildAccessReceipt(input) {
|
|
65
|
+
if (!input.episodeTag)
|
|
66
|
+
throw new Error('episodeTag is required');
|
|
67
|
+
if (!input.actor)
|
|
68
|
+
throw new Error('actor is required');
|
|
69
|
+
if (!input.purpose)
|
|
70
|
+
throw new Error('purpose is required — purpose limitation is not optional');
|
|
71
|
+
const { payload_hash, nonce } = saltedPayloadHash(JSON.stringify(input.details ?? {}));
|
|
72
|
+
return {
|
|
73
|
+
target: 'health.access',
|
|
74
|
+
subjectTag: input.episodeTag,
|
|
75
|
+
nonce,
|
|
76
|
+
payload: {
|
|
77
|
+
_zr_kind: 'health', _zr_domain: 'health', v: 1, kind: 'access',
|
|
78
|
+
actor: input.actor, purpose: input.purpose,
|
|
79
|
+
consent_ref: input.consentRef, details_commitment: payload_hash, ts: input.ts,
|
|
80
|
+
},
|
|
81
|
+
};
|
|
82
|
+
}
|
|
83
|
+
/** Which model recommended what, under which protocol. `health.recommendation` */
|
|
84
|
+
export function buildRecommendation(input) {
|
|
85
|
+
if (!input.episodeTag)
|
|
86
|
+
throw new Error('episodeTag is required');
|
|
87
|
+
if (!input.modelId)
|
|
88
|
+
throw new Error('modelId is required');
|
|
89
|
+
if (!input.manifestHash) {
|
|
90
|
+
throw new Error('manifestHash is required — a clinical recommendation with no governing protocol on record is not auditable');
|
|
91
|
+
}
|
|
92
|
+
const { payload_hash, nonce } = saltedPayloadHash(JSON.stringify(input.outcome));
|
|
93
|
+
return {
|
|
94
|
+
target: 'health.recommendation',
|
|
95
|
+
subjectTag: input.episodeTag,
|
|
96
|
+
nonce,
|
|
97
|
+
payload: {
|
|
98
|
+
_zr_kind: 'health', _zr_domain: 'health', v: 1, kind: 'recommendation',
|
|
99
|
+
model_id: input.modelId, runtime_hash: input.runtimeHash,
|
|
100
|
+
manifest_hash: input.manifestHash,
|
|
101
|
+
outcome_commitment: payload_hash,
|
|
102
|
+
deviation: input.deviation,
|
|
103
|
+
ts: input.ts,
|
|
104
|
+
},
|
|
105
|
+
};
|
|
106
|
+
}
|
|
107
|
+
/**
|
|
108
|
+
* Which **named human** took responsibility. `health.confirmation`
|
|
109
|
+
*
|
|
110
|
+
* The clinician signs the recommendation with their own key — the model did not decide, a
|
|
111
|
+
* person did. This is the artifact a malpractice case turns on.
|
|
112
|
+
*/
|
|
113
|
+
export function buildClinicianConfirmation(input, clinicianPrivateKey) {
|
|
114
|
+
const confirmation = createConfirmation({ ownerId: input.clinicianDid, actionHash: input.recommendationHash, confirmedAt: input.confirmedAt }, clinicianPrivateKey);
|
|
115
|
+
return {
|
|
116
|
+
target: 'health.confirmation',
|
|
117
|
+
subjectTag: input.episodeTag,
|
|
118
|
+
nonce: '',
|
|
119
|
+
confirmation,
|
|
120
|
+
payload: {
|
|
121
|
+
_zr_kind: 'health', _zr_domain: 'health', v: 1, kind: 'confirmation',
|
|
122
|
+
clinician: input.clinicianDid,
|
|
123
|
+
recommendation_hash: input.recommendationHash,
|
|
124
|
+
confirmation,
|
|
125
|
+
ts: input.confirmedAt,
|
|
126
|
+
},
|
|
127
|
+
};
|
|
128
|
+
}
|
|
129
|
+
/** A clinician's confirmation is valid only if signed by that clinician. */
|
|
130
|
+
export function verifyClinicianConfirmation(payload) {
|
|
131
|
+
const c = (payload ?? {}).confirmation;
|
|
132
|
+
if (!c || payload.clinician !== c.owner_id)
|
|
133
|
+
return false;
|
|
134
|
+
return verifyConfirmation(c);
|
|
135
|
+
}
|
|
136
|
+
/**
|
|
137
|
+
* Emergency access. `health.break_glass`
|
|
138
|
+
*
|
|
139
|
+
* **A hole we deliberately keep open — a closed one kills patients. We make it LOUD, not
|
|
140
|
+
* impossible.** Break-glass is the classic PHI-snooping vector (the celebrity-record case),
|
|
141
|
+
* so: the acting clinician signs it **personally** — a named human puts their name on it, and
|
|
142
|
+
* that signature is the deterrent. Un-reviewed break-glass is a countable defect
|
|
143
|
+
* (`pendingBreakGlass`), visible in the institution's own audit and to the patient on claim.
|
|
144
|
+
*
|
|
145
|
+
* We ship the **metric, not the mandate**: we do not enforce a review policy we have no power
|
|
146
|
+
* to enforce — we make **ignoring it undeniable**.
|
|
147
|
+
*/
|
|
148
|
+
export function buildBreakGlass(input, clinicianPrivateKey) {
|
|
149
|
+
if (!input.reason)
|
|
150
|
+
throw new Error('reason is required — an unexplained break-glass is exactly the abuse this exists to catch');
|
|
151
|
+
const actionHash = jcsHash({ v: 1, type: 'break_glass', tag: input.episodeTag, ts: input.ts });
|
|
152
|
+
const confirmation = createConfirmation({ ownerId: input.clinicianDid, actionHash, confirmedAt: input.ts }, clinicianPrivateKey);
|
|
153
|
+
return {
|
|
154
|
+
target: 'health.break_glass',
|
|
155
|
+
subjectTag: input.episodeTag,
|
|
156
|
+
nonce: '',
|
|
157
|
+
confirmation,
|
|
158
|
+
payload: {
|
|
159
|
+
_zr_kind: 'health', _zr_domain: 'health', v: 1, kind: 'break_glass',
|
|
160
|
+
clinician: input.clinicianDid, reason: input.reason,
|
|
161
|
+
confirmation, reviewed: false, ts: input.ts,
|
|
162
|
+
},
|
|
163
|
+
};
|
|
164
|
+
}
|
|
165
|
+
/** Mark a break-glass reviewed — the institution's own audit artifact. */
|
|
166
|
+
export function markReviewed(payload, reviewer, ts) {
|
|
167
|
+
return { ...payload, reviewed: true, reviewed_by: reviewer, reviewed_at: ts };
|
|
168
|
+
}
|
|
169
|
+
/**
|
|
170
|
+
* **The metric, not the mandate.** Break-glass events with no review on record.
|
|
171
|
+
* A regulator can *require* review; the institution cannot hide that it didn't.
|
|
172
|
+
*/
|
|
173
|
+
export function pendingBreakGlass(payloads) {
|
|
174
|
+
return payloads.filter((p) => p._zr_kind === 'health' && p.kind === 'break_glass' && p.reviewed !== true);
|
|
175
|
+
}
|
|
176
|
+
/**
|
|
177
|
+
* Which protocol governed what, and when protocols changed.
|
|
178
|
+
*
|
|
179
|
+
* **Deliberately NOT `ruleConsistency`.** In government, "the same rulebook decided everyone"
|
|
180
|
+
* is the fairness property and interleaving is a red flag. **In medicine, individualised care
|
|
181
|
+
* is CORRECT** — protocols legitimately coexist (comorbidities, cohorts, trial arms). Flagging
|
|
182
|
+
* interleaved protocols would false-alarm on *good medicine* and train clinicians to ignore
|
|
183
|
+
* the tool. So we report **disclosure and change**, and pass **no verdict on uniformity**.
|
|
184
|
+
*/
|
|
185
|
+
export function protocolTrail(payloads) {
|
|
186
|
+
const recs = payloads.filter((p) => p._zr_kind === 'health' && p.kind === 'recommendation');
|
|
187
|
+
const windows = new Map();
|
|
188
|
+
let deviations = 0;
|
|
189
|
+
let unprotocolled = 0;
|
|
190
|
+
for (const p of [...recs].sort((a, b) => String(a.ts).localeCompare(String(b.ts)))) {
|
|
191
|
+
if (p.deviation)
|
|
192
|
+
deviations += 1;
|
|
193
|
+
const h = p.manifest_hash;
|
|
194
|
+
if (!h) {
|
|
195
|
+
unprotocolled += 1;
|
|
196
|
+
continue;
|
|
197
|
+
}
|
|
198
|
+
const ts = p.ts;
|
|
199
|
+
const w = windows.get(h);
|
|
200
|
+
if (w) {
|
|
201
|
+
w.count += 1;
|
|
202
|
+
w.last_ts = ts;
|
|
203
|
+
}
|
|
204
|
+
else {
|
|
205
|
+
windows.set(h, { manifest_hash: h, count: 1, first_ts: ts, last_ts: ts });
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
return {
|
|
209
|
+
protocols: [...windows.values()].sort((a, b) => a.first_ts.localeCompare(b.first_ts)),
|
|
210
|
+
deviations,
|
|
211
|
+
unprotocolled,
|
|
212
|
+
};
|
|
213
|
+
}
|
|
214
|
+
/**
|
|
215
|
+
* Fetch and merge the patient's episode chain. **Only the seed-holder can do this** — which
|
|
216
|
+
* is the entire point. `@zanii/subject`'s `fetchSubjectHistory` is one-tag-at-a-time; this is
|
|
217
|
+
* the multi-tag fetch it lacks.
|
|
218
|
+
*/
|
|
219
|
+
export async function fetchEpisodes(seed, opts = {}) {
|
|
220
|
+
const server = (opts.server ?? 'https://ledger.zanii.agency').replace(/\/$/, '');
|
|
221
|
+
const fetchImpl = opts.fetchImpl ?? ((u, i) => fetch(u, i));
|
|
222
|
+
const from = opts.from ?? 0;
|
|
223
|
+
const to = opts.to ?? 50;
|
|
224
|
+
const episodes = [];
|
|
225
|
+
const all = [];
|
|
226
|
+
for (let n = from; n <= to; n++) {
|
|
227
|
+
const tag = episodeTag(seed, n);
|
|
228
|
+
const res = await fetchImpl(`${server}/v1/subjects/${encodeURIComponent(tag)}`);
|
|
229
|
+
if (res.status === 404)
|
|
230
|
+
continue; // no encounter at this index
|
|
231
|
+
if (!res.ok)
|
|
232
|
+
throw new Error(`episode lookup failed: HTTP ${res.status}`);
|
|
233
|
+
const body = (await res.json());
|
|
234
|
+
const payloads = (body.receipts ?? [])
|
|
235
|
+
.map((r) => r.receipt.payload)
|
|
236
|
+
.filter((p) => !!p);
|
|
237
|
+
episodes.push({ n, tag, receipts: payloads });
|
|
238
|
+
all.push(...payloads);
|
|
239
|
+
}
|
|
240
|
+
return {
|
|
241
|
+
episodes,
|
|
242
|
+
total: all.length,
|
|
243
|
+
pendingBreakGlass: pendingBreakGlass(all).length,
|
|
244
|
+
protocols: protocolTrail(all),
|
|
245
|
+
};
|
|
246
|
+
}
|
|
247
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA6BG;AACH,OAAO,EAAE,kBAAkB,EAAE,OAAO,EAAE,iBAAiB,EAAE,kBAAkB,EAA2B,MAAM,aAAa,CAAC;AAqB1H,yFAAyF;AACzF,MAAM,UAAU,WAAW,CAAC,SAAkB;IAC5C,MAAM,MAAM,GAAG,SAAS,IAAI,eAAe,CAAC,YAAY,CAAC,EAAE,CAAC,CAAC,CAAC;IAC9D,IAAI,CAAC,gBAAgB,CAAC,IAAI,CAAC,MAAM,CAAC;QAAE,MAAM,IAAI,KAAK,CAAC,qCAAqC,CAAC,CAAC;IAC3F,OAAO,EAAE,CAAC,EAAE,CAAC,EAAE,MAAM,EAAE,CAAC;AAC1B,CAAC;AAED,SAAS,YAAY,CAAC,CAAS;IAC7B,MAAM,GAAG,GAAG,IAAI,UAAU,CAAC,CAAC,CAAC,CAAC;IAC9B,UAAU,CAAC,MAAM,CAAC,eAAe,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AAM,EAAE,CAAC,CAAC;QAC1E,MAAM,IAAI,GAAG,CAAC,MAAM,GAAG,CAAC,IAAI,EAAE,CAA6E,CAAC;QAC5G,MAAM,QAAQ,GAAG,CAAC,IAAI,CAAC,QAAQ,IAAI,EAAE,CAAC;aACnC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,OAAO,CAAC,OAAO,CAAC;aAC7B,MAAM,CAAC,CAAC,CAAC,EAAgC,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;QACpD,QAAQ,CAAC,IAAI,CAAC,EAAE,CAAC,EAAE,GAAG,EAAE,QAAQ,EAAE,QAAQ,EAAE,CAAC,CAAC;QAC9C,GAAG,CAAC,IAAI,CAAC,GAAG,QAAQ,CAAC,CAAC;IACxB,CAAC;IAED,OAAO;QACL,QAAQ;QACR,KAAK,EAAE,GAAG,CAAC,MAAM;QACjB,iBAAiB,EAAE,iBAAiB,CAAC,GAAG,CAAC,CAAC,MAAM;QAChD,SAAS,EAAE,aAAa,CAAC,GAAG,CAAC;KAC9B,CAAC;AACJ,CAAC"}
|
package/package.json
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@zanii/health",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Medical audit trails without leaking the pattern: per-episode unlinkable tags (the patient supplies the tag, never the seed), plus who accessed the record, which model recommended what under which protocol, and which named clinician took responsibility. Break-glass is loud, not impossible.",
|
|
5
|
+
"license": "Apache-2.0",
|
|
6
|
+
"homepage": "https://ledger.zanii.agency",
|
|
7
|
+
"type": "module",
|
|
8
|
+
"main": "./dist/index.js",
|
|
9
|
+
"types": "./dist/index.d.ts",
|
|
10
|
+
"exports": {
|
|
11
|
+
".": {
|
|
12
|
+
"types": "./dist/index.d.ts",
|
|
13
|
+
"import": "./dist/index.js"
|
|
14
|
+
}
|
|
15
|
+
},
|
|
16
|
+
"files": [
|
|
17
|
+
"dist",
|
|
18
|
+
"src",
|
|
19
|
+
"README.md",
|
|
20
|
+
"LICENSE"
|
|
21
|
+
],
|
|
22
|
+
"publishConfig": {
|
|
23
|
+
"access": "public"
|
|
24
|
+
},
|
|
25
|
+
"engines": {
|
|
26
|
+
"node": ">=18"
|
|
27
|
+
},
|
|
28
|
+
"devDependencies": {
|
|
29
|
+
"@types/node": "^26.1.0",
|
|
30
|
+
"typescript": "^5.8.2",
|
|
31
|
+
"vitest": "^3.0.9"
|
|
32
|
+
},
|
|
33
|
+
"dependencies": {
|
|
34
|
+
"@zanii/core": "0.4.0",
|
|
35
|
+
"@zanii/subject": "0.1.0"
|
|
36
|
+
},
|
|
37
|
+
"scripts": {
|
|
38
|
+
"build": "tsc -p tsconfig.build.json",
|
|
39
|
+
"test": "vitest run",
|
|
40
|
+
"typecheck": "tsc --noEmit"
|
|
41
|
+
}
|
|
42
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,366 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @zanii/health — medical audit trails **without leaking the pattern**.
|
|
3
|
+
*
|
|
4
|
+
* For medicine, the metadata IS the sensitive data. Zanii's usual privacy story ("we store
|
|
5
|
+
* only hashes") is what makes it safe everywhere else — and it is exactly what fails here:
|
|
6
|
+
* a stable public `subject_tag` slice leaks *that* a record was opened, by how many parties,
|
|
7
|
+
* how often, and when. **Access frequency to an oncology or psychiatric record is itself
|
|
8
|
+
* PHI.** So this package breaks the one property Zanii otherwise relies on: a single, stable,
|
|
9
|
+
* linkable identifier per subject.
|
|
10
|
+
*
|
|
11
|
+
* **Design target: an episode is verifiable; a life is not linkable except by the patient.**
|
|
12
|
+
*
|
|
13
|
+
* Threat model (it decides everything): we do NOT need to hide the encounter from the
|
|
14
|
+
* treating provider — they hold the chart. We must stop *anyone else* — a second provider,
|
|
15
|
+
* an insurer, the log operator — from **linking encounters into a history**.
|
|
16
|
+
*
|
|
17
|
+
* ## The rule that makes or breaks this
|
|
18
|
+
*
|
|
19
|
+
* **The patient supplies the TAG. The patient never supplies the SEED.**
|
|
20
|
+
*
|
|
21
|
+
* If a provider held the seed it could enumerate `n = 1, 2, 3…` and reconstruct the patient's
|
|
22
|
+
* entire cross-institution history — the privacy gain would be zero, and *illusory*. The
|
|
23
|
+
* patient's app derives the tag for THIS encounter and hands over one opaque string. There is
|
|
24
|
+
* a red test guarding this (`a provider holding the seed can link everything`) so nobody
|
|
25
|
+
* "optimises" the seed into the provider's hands later.
|
|
26
|
+
*
|
|
27
|
+
* Answers the four-party question that actually decides a malpractice case:
|
|
28
|
+
* **who accessed the record, which model recommended what, under which protocol version, and
|
|
29
|
+
* which named human took responsibility.**
|
|
30
|
+
*/
|
|
31
|
+
import { createConfirmation, jcsHash, saltedPayloadHash, verifyConfirmation, type ActionConfirmation } from '@zanii/core';
|
|
32
|
+
|
|
33
|
+
export type FetchLike = (input: string, init?: RequestInit) => Promise<Response>;
|
|
34
|
+
|
|
35
|
+
// ---------------------------------------------------------------------------
|
|
36
|
+
// Episode identity — unlinkable by construction
|
|
37
|
+
// ---------------------------------------------------------------------------
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* The patient's episode seed. **Never leaves the patient.** Held in a device keystore with
|
|
41
|
+
* an offline recovery code — deliberately NOT social/Shamir recovery: in health the
|
|
42
|
+
* guardians are frequently the adversary (coercion, abuse, an employer who is also a
|
|
43
|
+
* relative). We can refuse it because **seed loss ≠ record loss**: you lose linkability of
|
|
44
|
+
* past episodes, never the chart.
|
|
45
|
+
*/
|
|
46
|
+
export interface EpisodeSeed {
|
|
47
|
+
v: 1;
|
|
48
|
+
/** 32 bytes of entropy, hex. The secret. */
|
|
49
|
+
secret: string;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/** Generate a patient seed. Store in a device keystore; back up with an offline code. */
|
|
53
|
+
export function episodeSeed(secretHex?: string): EpisodeSeed {
|
|
54
|
+
const secret = secretHex ?? bytesToHexLocal(cryptoRandom(32));
|
|
55
|
+
if (!/^[0-9a-f]{64}$/.test(secret)) throw new Error('seed secret must be 32 bytes of hex');
|
|
56
|
+
return { v: 1, secret };
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
function cryptoRandom(n: number): Uint8Array {
|
|
60
|
+
const out = new Uint8Array(n);
|
|
61
|
+
globalThis.crypto.getRandomValues(out);
|
|
62
|
+
return out;
|
|
63
|
+
}
|
|
64
|
+
function bytesToHexLocal(b: Uint8Array): string {
|
|
65
|
+
return [...b].map((x) => x.toString(16).padStart(2, '0')).join('');
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/**
|
|
69
|
+
* The tag for encounter `n`. Derived by the PATIENT and handed to the provider as one opaque
|
|
70
|
+
* string. Unlinkable: two tags from the same patient are not relatable without the seed.
|
|
71
|
+
*/
|
|
72
|
+
export function episodeTag(seed: EpisodeSeed, n: number): string {
|
|
73
|
+
if (!Number.isInteger(n) || n < 0) throw new Error('n must be a non-negative integer');
|
|
74
|
+
return jcsHash({ v: 1, type: 'episode_tag', secret: seed.secret, n });
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/** The patient's own chain — only they can enumerate it. */
|
|
78
|
+
export function episodeTags(seed: EpisodeSeed, from: number, to: number): string[] {
|
|
79
|
+
const out: string[] = [];
|
|
80
|
+
for (let n = from; n <= to; n++) out.push(episodeTag(seed, n));
|
|
81
|
+
return out;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
// ---------------------------------------------------------------------------
|
|
85
|
+
// The four receipts
|
|
86
|
+
// ---------------------------------------------------------------------------
|
|
87
|
+
|
|
88
|
+
export interface HealthReceipt {
|
|
89
|
+
target: string;
|
|
90
|
+
payload: Record<string, unknown>;
|
|
91
|
+
/** Stamp this as the receipt's `subjectTag` — it is the episode tag, not a patient id. */
|
|
92
|
+
subjectTag: string;
|
|
93
|
+
/** Keep to disclose committed details later (dispute/audit). */
|
|
94
|
+
nonce: string;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
export interface AccessInput {
|
|
98
|
+
episodeTag: string;
|
|
99
|
+
/** The clinician or system that opened the record (`did:key`). */
|
|
100
|
+
actor: string;
|
|
101
|
+
/** Why — `treatment`, `billing`, `research`. Purpose limitation is a PDPL/HIPAA hinge. */
|
|
102
|
+
purpose: string;
|
|
103
|
+
/** Reference to the consent receipt in force at access time (`@zanii/consent`). */
|
|
104
|
+
consentRef?: string;
|
|
105
|
+
/** Details that must not sit in the clear (department, record section). Salt-committed. */
|
|
106
|
+
details?: Record<string, unknown>;
|
|
107
|
+
ts: string;
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/** Who accessed the record. `health.access` */
|
|
111
|
+
export function buildAccessReceipt(input: AccessInput): HealthReceipt {
|
|
112
|
+
if (!input.episodeTag) throw new Error('episodeTag is required');
|
|
113
|
+
if (!input.actor) throw new Error('actor is required');
|
|
114
|
+
if (!input.purpose) throw new Error('purpose is required — purpose limitation is not optional');
|
|
115
|
+
const { payload_hash, nonce } = saltedPayloadHash(JSON.stringify(input.details ?? {}));
|
|
116
|
+
return {
|
|
117
|
+
target: 'health.access',
|
|
118
|
+
subjectTag: input.episodeTag,
|
|
119
|
+
nonce,
|
|
120
|
+
payload: {
|
|
121
|
+
_zr_kind: 'health', _zr_domain: 'health', v: 1, kind: 'access',
|
|
122
|
+
actor: input.actor, purpose: input.purpose,
|
|
123
|
+
consent_ref: input.consentRef, details_commitment: payload_hash, ts: input.ts,
|
|
124
|
+
},
|
|
125
|
+
};
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
export interface RecommendationInput {
|
|
129
|
+
episodeTag: string;
|
|
130
|
+
/** The model that produced the recommendation. */
|
|
131
|
+
modelId: string;
|
|
132
|
+
/** The deployed runtime that ran it. */
|
|
133
|
+
runtimeHash?: string;
|
|
134
|
+
/** REQUIRED — the clinical protocol/guideline version that governed this. */
|
|
135
|
+
manifestHash: string;
|
|
136
|
+
/** The recommendation itself, e.g. `{ code: 'CHEMO-A', line: 2 }`. */
|
|
137
|
+
outcome: Record<string, unknown>;
|
|
138
|
+
/**
|
|
139
|
+
* Departing from the governing protocol is **legitimate and common** in medicine. It is
|
|
140
|
+
* recorded, never prevented — and never treated as a defect.
|
|
141
|
+
*/
|
|
142
|
+
deviation?: { from: string; rationale: string };
|
|
143
|
+
ts: string;
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
/** Which model recommended what, under which protocol. `health.recommendation` */
|
|
147
|
+
export function buildRecommendation(input: RecommendationInput): HealthReceipt {
|
|
148
|
+
if (!input.episodeTag) throw new Error('episodeTag is required');
|
|
149
|
+
if (!input.modelId) throw new Error('modelId is required');
|
|
150
|
+
if (!input.manifestHash) {
|
|
151
|
+
throw new Error('manifestHash is required — a clinical recommendation with no governing protocol on record is not auditable');
|
|
152
|
+
}
|
|
153
|
+
const { payload_hash, nonce } = saltedPayloadHash(JSON.stringify(input.outcome));
|
|
154
|
+
return {
|
|
155
|
+
target: 'health.recommendation',
|
|
156
|
+
subjectTag: input.episodeTag,
|
|
157
|
+
nonce,
|
|
158
|
+
payload: {
|
|
159
|
+
_zr_kind: 'health', _zr_domain: 'health', v: 1, kind: 'recommendation',
|
|
160
|
+
model_id: input.modelId, runtime_hash: input.runtimeHash,
|
|
161
|
+
manifest_hash: input.manifestHash,
|
|
162
|
+
outcome_commitment: payload_hash,
|
|
163
|
+
deviation: input.deviation,
|
|
164
|
+
ts: input.ts,
|
|
165
|
+
},
|
|
166
|
+
};
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
/**
|
|
170
|
+
* Which **named human** took responsibility. `health.confirmation`
|
|
171
|
+
*
|
|
172
|
+
* The clinician signs the recommendation with their own key — the model did not decide, a
|
|
173
|
+
* person did. This is the artifact a malpractice case turns on.
|
|
174
|
+
*/
|
|
175
|
+
export function buildClinicianConfirmation(
|
|
176
|
+
input: { episodeTag: string; clinicianDid: string; recommendationHash: string; confirmedAt: string },
|
|
177
|
+
clinicianPrivateKey: Uint8Array,
|
|
178
|
+
): HealthReceipt & { confirmation: ActionConfirmation } {
|
|
179
|
+
const confirmation = createConfirmation(
|
|
180
|
+
{ ownerId: input.clinicianDid, actionHash: input.recommendationHash, confirmedAt: input.confirmedAt },
|
|
181
|
+
clinicianPrivateKey,
|
|
182
|
+
);
|
|
183
|
+
return {
|
|
184
|
+
target: 'health.confirmation',
|
|
185
|
+
subjectTag: input.episodeTag,
|
|
186
|
+
nonce: '',
|
|
187
|
+
confirmation,
|
|
188
|
+
payload: {
|
|
189
|
+
_zr_kind: 'health', _zr_domain: 'health', v: 1, kind: 'confirmation',
|
|
190
|
+
clinician: input.clinicianDid,
|
|
191
|
+
recommendation_hash: input.recommendationHash,
|
|
192
|
+
confirmation,
|
|
193
|
+
ts: input.confirmedAt,
|
|
194
|
+
},
|
|
195
|
+
};
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
/** A clinician's confirmation is valid only if signed by that clinician. */
|
|
199
|
+
export function verifyClinicianConfirmation(payload: Record<string, unknown> | undefined): boolean {
|
|
200
|
+
const c = (payload ?? {}).confirmation as ActionConfirmation | undefined;
|
|
201
|
+
if (!c || (payload as { clinician?: string }).clinician !== c.owner_id) return false;
|
|
202
|
+
return verifyConfirmation(c);
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
export interface BreakGlassInput {
|
|
206
|
+
/** Provider-derived, because an unconscious patient supplies no tag. Claimable later. */
|
|
207
|
+
episodeTag: string;
|
|
208
|
+
/** The clinician who is personally accountable. NOT merely the system. */
|
|
209
|
+
clinicianDid: string;
|
|
210
|
+
reason: string;
|
|
211
|
+
ts: string;
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
/**
|
|
215
|
+
* Emergency access. `health.break_glass`
|
|
216
|
+
*
|
|
217
|
+
* **A hole we deliberately keep open — a closed one kills patients. We make it LOUD, not
|
|
218
|
+
* impossible.** Break-glass is the classic PHI-snooping vector (the celebrity-record case),
|
|
219
|
+
* so: the acting clinician signs it **personally** — a named human puts their name on it, and
|
|
220
|
+
* that signature is the deterrent. Un-reviewed break-glass is a countable defect
|
|
221
|
+
* (`pendingBreakGlass`), visible in the institution's own audit and to the patient on claim.
|
|
222
|
+
*
|
|
223
|
+
* We ship the **metric, not the mandate**: we do not enforce a review policy we have no power
|
|
224
|
+
* to enforce — we make **ignoring it undeniable**.
|
|
225
|
+
*/
|
|
226
|
+
export function buildBreakGlass(
|
|
227
|
+
input: BreakGlassInput,
|
|
228
|
+
clinicianPrivateKey: Uint8Array,
|
|
229
|
+
): HealthReceipt & { confirmation: ActionConfirmation } {
|
|
230
|
+
if (!input.reason) throw new Error('reason is required — an unexplained break-glass is exactly the abuse this exists to catch');
|
|
231
|
+
const actionHash = jcsHash({ v: 1, type: 'break_glass', tag: input.episodeTag, ts: input.ts });
|
|
232
|
+
const confirmation = createConfirmation(
|
|
233
|
+
{ ownerId: input.clinicianDid, actionHash, confirmedAt: input.ts },
|
|
234
|
+
clinicianPrivateKey,
|
|
235
|
+
);
|
|
236
|
+
return {
|
|
237
|
+
target: 'health.break_glass',
|
|
238
|
+
subjectTag: input.episodeTag,
|
|
239
|
+
nonce: '',
|
|
240
|
+
confirmation,
|
|
241
|
+
payload: {
|
|
242
|
+
_zr_kind: 'health', _zr_domain: 'health', v: 1, kind: 'break_glass',
|
|
243
|
+
clinician: input.clinicianDid, reason: input.reason,
|
|
244
|
+
confirmation, reviewed: false, ts: input.ts,
|
|
245
|
+
},
|
|
246
|
+
};
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
/** Mark a break-glass reviewed — the institution's own audit artifact. */
|
|
250
|
+
export function markReviewed(payload: Record<string, unknown>, reviewer: string, ts: string): Record<string, unknown> {
|
|
251
|
+
return { ...payload, reviewed: true, reviewed_by: reviewer, reviewed_at: ts };
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
/**
|
|
255
|
+
* **The metric, not the mandate.** Break-glass events with no review on record.
|
|
256
|
+
* A regulator can *require* review; the institution cannot hide that it didn't.
|
|
257
|
+
*/
|
|
258
|
+
export function pendingBreakGlass(payloads: Array<Record<string, unknown>>): Array<Record<string, unknown>> {
|
|
259
|
+
return payloads.filter((p) => p._zr_kind === 'health' && p.kind === 'break_glass' && p.reviewed !== true);
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
// ---------------------------------------------------------------------------
|
|
263
|
+
// Protocol trail — NOT ruleConsistency
|
|
264
|
+
// ---------------------------------------------------------------------------
|
|
265
|
+
|
|
266
|
+
export interface ProtocolWindow {
|
|
267
|
+
manifest_hash: string;
|
|
268
|
+
count: number;
|
|
269
|
+
first_ts: string;
|
|
270
|
+
last_ts: string;
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
export interface ProtocolTrail {
|
|
274
|
+
protocols: ProtocolWindow[];
|
|
275
|
+
/** Recommendations that departed from their governing protocol — legitimate, recorded, NOT a defect. */
|
|
276
|
+
deviations: number;
|
|
277
|
+
/** Recommendations with NO protocol on record. THIS is the defect. */
|
|
278
|
+
unprotocolled: number;
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
/**
|
|
282
|
+
* Which protocol governed what, and when protocols changed.
|
|
283
|
+
*
|
|
284
|
+
* **Deliberately NOT `ruleConsistency`.** In government, "the same rulebook decided everyone"
|
|
285
|
+
* is the fairness property and interleaving is a red flag. **In medicine, individualised care
|
|
286
|
+
* is CORRECT** — protocols legitimately coexist (comorbidities, cohorts, trial arms). Flagging
|
|
287
|
+
* interleaved protocols would false-alarm on *good medicine* and train clinicians to ignore
|
|
288
|
+
* the tool. So we report **disclosure and change**, and pass **no verdict on uniformity**.
|
|
289
|
+
*/
|
|
290
|
+
export function protocolTrail(payloads: Array<Record<string, unknown>>): ProtocolTrail {
|
|
291
|
+
const recs = payloads.filter((p) => p._zr_kind === 'health' && p.kind === 'recommendation');
|
|
292
|
+
const windows = new Map<string, ProtocolWindow>();
|
|
293
|
+
let deviations = 0;
|
|
294
|
+
let unprotocolled = 0;
|
|
295
|
+
for (const p of [...recs].sort((a, b) => String(a.ts).localeCompare(String(b.ts)))) {
|
|
296
|
+
if (p.deviation) deviations += 1;
|
|
297
|
+
const h = p.manifest_hash as string | undefined;
|
|
298
|
+
if (!h) {
|
|
299
|
+
unprotocolled += 1;
|
|
300
|
+
continue;
|
|
301
|
+
}
|
|
302
|
+
const ts = p.ts as string;
|
|
303
|
+
const w = windows.get(h);
|
|
304
|
+
if (w) {
|
|
305
|
+
w.count += 1;
|
|
306
|
+
w.last_ts = ts;
|
|
307
|
+
} else {
|
|
308
|
+
windows.set(h, { manifest_hash: h, count: 1, first_ts: ts, last_ts: ts });
|
|
309
|
+
}
|
|
310
|
+
}
|
|
311
|
+
return {
|
|
312
|
+
protocols: [...windows.values()].sort((a, b) => a.first_ts.localeCompare(b.first_ts)),
|
|
313
|
+
deviations,
|
|
314
|
+
unprotocolled,
|
|
315
|
+
};
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
// ---------------------------------------------------------------------------
|
|
319
|
+
// The patient's view — the only party who can link the chain
|
|
320
|
+
// ---------------------------------------------------------------------------
|
|
321
|
+
|
|
322
|
+
export interface EpisodeHistory {
|
|
323
|
+
episodes: Array<{ n: number; tag: string; receipts: Array<Record<string, unknown>> }>;
|
|
324
|
+
/** Total receipts across the chain. */
|
|
325
|
+
total: number;
|
|
326
|
+
/** Break-glass events on this patient with no review recorded. */
|
|
327
|
+
pendingBreakGlass: number;
|
|
328
|
+
protocols: ProtocolTrail;
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
/**
|
|
332
|
+
* Fetch and merge the patient's episode chain. **Only the seed-holder can do this** — which
|
|
333
|
+
* is the entire point. `@zanii/subject`'s `fetchSubjectHistory` is one-tag-at-a-time; this is
|
|
334
|
+
* the multi-tag fetch it lacks.
|
|
335
|
+
*/
|
|
336
|
+
export async function fetchEpisodes(
|
|
337
|
+
seed: EpisodeSeed,
|
|
338
|
+
opts: { server?: string; fetchImpl?: FetchLike; from?: number; to?: number } = {},
|
|
339
|
+
): Promise<EpisodeHistory> {
|
|
340
|
+
const server = (opts.server ?? 'https://ledger.zanii.agency').replace(/\/$/, '');
|
|
341
|
+
const fetchImpl = opts.fetchImpl ?? ((u: string, i?: RequestInit) => fetch(u, i));
|
|
342
|
+
const from = opts.from ?? 0;
|
|
343
|
+
const to = opts.to ?? 50;
|
|
344
|
+
const episodes: EpisodeHistory['episodes'] = [];
|
|
345
|
+
const all: Array<Record<string, unknown>> = [];
|
|
346
|
+
|
|
347
|
+
for (let n = from; n <= to; n++) {
|
|
348
|
+
const tag = episodeTag(seed, n);
|
|
349
|
+
const res = await fetchImpl(`${server}/v1/subjects/${encodeURIComponent(tag)}`);
|
|
350
|
+
if (res.status === 404) continue; // no encounter at this index
|
|
351
|
+
if (!res.ok) throw new Error(`episode lookup failed: HTTP ${res.status}`);
|
|
352
|
+
const body = (await res.json()) as { receipts?: Array<{ receipt: { payload?: Record<string, unknown> } }> };
|
|
353
|
+
const payloads = (body.receipts ?? [])
|
|
354
|
+
.map((r) => r.receipt.payload)
|
|
355
|
+
.filter((p): p is Record<string, unknown> => !!p);
|
|
356
|
+
episodes.push({ n, tag, receipts: payloads });
|
|
357
|
+
all.push(...payloads);
|
|
358
|
+
}
|
|
359
|
+
|
|
360
|
+
return {
|
|
361
|
+
episodes,
|
|
362
|
+
total: all.length,
|
|
363
|
+
pendingBreakGlass: pendingBreakGlass(all).length,
|
|
364
|
+
protocols: protocolTrail(all),
|
|
365
|
+
};
|
|
366
|
+
}
|