@zanii/insurance 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 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,54 @@
1
+ # @zanii/insurance
2
+
3
+ Machine-verifiable underwriting for agent liability. The commercial unlock for a
4
+ transparency ledger is an **insurable agent**: an insurer prices a policy off the
5
+ agent's ledger history, and a claim resolves against Merkle-proven receipts instead
6
+ of a dispute.
7
+
8
+ ```sh
9
+ npm install @zanii/insurance @zanii/core @zanii/a2a-directory @zanii/payments
10
+ ```
11
+
12
+ ```ts
13
+ import { riskProfile, buildPolicyBody, signPolicy, assemblePolicy, buildClaimBody, signClaim, assembleClaim, assessClaim } from '@zanii/insurance';
14
+
15
+ // 1. Risk FACTS from the ledger's own un-inflatable aggregate — never a score.
16
+ const profile = await riskProfile(agent.did, { asOf: now, delegation: certs });
17
+ profile.facts; // receipts, counterparties, age_days, revoked, anchored, scopes…
18
+ profile.flags; // ['THIN_HISTORY', 'WILDCARD_AUTHORITY', …] — named conditions, not numbers
19
+
20
+ // 2. A policy insurer and holder co-sign. Money in integer minor units.
21
+ const body = buildPolicyBody({
22
+ insurer: insurer.did, holder: owner.did, subject: agent.did,
23
+ premium: '120.00', coverageLimit: '50000.00', currency: 'USD',
24
+ coveredScopes: ['deploy.*', 'email.send'],
25
+ period: { start, end }, riskProfileHash: riskProfileHash(profile), // pin the underwriting basis
26
+ createdAt: now,
27
+ });
28
+ const policy = assemblePolicy(body, [signPolicy(body, insurer.did, insurerKey), signPolicy(body, owner.did, ownerKey)]);
29
+
30
+ // 3. A claim cites incident receipts by hash; assessment is deterministic.
31
+ const claim = assembleClaim(claimBody, [signClaim(claimBody, owner.did, ownerKey)]);
32
+ const a = assessClaim(claim, policy, { [receiptHash]: { receipt, sth, index, proof } });
33
+ a.ok; // terms verdict: holder-signed, within limit, every incident in-period + in-scope
34
+ a.proven; // incidents proven in the log by supplied evidence
35
+ a.unproven; // cited but unproven — a fact for the adjuster, not a failure
36
+ ```
37
+
38
+ Python: `from zanii.insurance import build_risk_profile, verify_policy, assess_claim, ...`
39
+ — byte-identical JCS objects and hashes.
40
+
41
+ ## Why facts, never a score
42
+
43
+ A score Zanii invents gets gamed and creates liability — insurers price, we state
44
+ facts and raise deterministic flags (`REVOKED`, `NOT_FULLY_ANCHORED`, `THIN_HISTORY`,
45
+ `STALE`, `WILDCARD_AUTHORITY`). The profile derives from the same `/v1/reputation`
46
+ aggregate AgentCV uses: counted by the log, not asserted by the agent.
47
+
48
+ ## The limit, stated up front
49
+
50
+ **Ledger silence is unknown, not good.** An agent that never receipts its failures
51
+ looks safer than it is — thin or stale history is flagged, not rewarded, and an
52
+ underwriter must treat uncovered activity as unknown risk. Cryptography verifies
53
+ attestations, not reality: a proven incident receipt shows what was recorded, not
54
+ everything that happened.
@@ -0,0 +1,152 @@
1
+ import { type AgentTrust, type FetchLike } from '@zanii/a2a-directory';
2
+ import { type DelegationCert, type Receipt, type SignedTreeHead } from '@zanii/core';
3
+ import { type Money } from '@zanii/payments';
4
+ export declare const SILENCE_NOTE = "ledger silence is unknown, not good \u2014 an agent that never receipts failures looks safer than it is";
5
+ export interface RiskFacts {
6
+ receipts: number;
7
+ distinct_counterparties: number;
8
+ /** Whole days from first receipt to `as_of`. null when there is no history. */
9
+ age_days: number | null;
10
+ /** Whole days from the last receipt to `as_of`. null when there is no history. */
11
+ days_since_last: number | null;
12
+ revoked: boolean;
13
+ fully_anchored: boolean;
14
+ /** Scopes currently delegated to the agent, when certs were supplied. */
15
+ scopes?: string[];
16
+ /** true when any supplied cert grants `*` — unbounded authority is an underwriting fact. */
17
+ wildcard_authority?: boolean;
18
+ }
19
+ export interface RiskProfile {
20
+ v: 1;
21
+ type: 'insurance.risk_profile';
22
+ did: string;
23
+ owner: string;
24
+ as_of: string;
25
+ facts: RiskFacts;
26
+ /** Deterministic, named conditions — never a number. */
27
+ flags: string[];
28
+ note: string;
29
+ }
30
+ /** Derive the profile offline from a ledger aggregate you already hold. Pure and deterministic. */
31
+ export declare function buildRiskProfile(trust: AgentTrust, opts: {
32
+ asOf: string;
33
+ delegation?: DelegationCert[];
34
+ }): RiskProfile;
35
+ /** Pull the ledger's aggregate for `did` and derive the profile. Returns null if no history. */
36
+ export declare function riskProfile(did: string, opts: {
37
+ asOf: string;
38
+ server?: string;
39
+ fetchImpl?: FetchLike;
40
+ delegation?: DelegationCert[];
41
+ }): Promise<RiskProfile | null>;
42
+ /** Canonical hash — pin a policy to the exact profile it was underwritten on. */
43
+ export declare function riskProfileHash(profile: RiskProfile): string;
44
+ export interface PolicyBody {
45
+ v: 1;
46
+ type: 'insurance.policy';
47
+ /** Who underwrites. */
48
+ insurer: string;
49
+ /** Who holds the policy — the agent's owner. */
50
+ holder: string;
51
+ /** The insured agent. */
52
+ subject: string;
53
+ premium: Money;
54
+ coverage_limit: Money;
55
+ /** Incidents are covered only under these scopes. */
56
+ covered_scopes: string[];
57
+ period: {
58
+ start: string;
59
+ end: string;
60
+ };
61
+ /** Hash of the `RiskProfile` this was priced on — makes the underwriting basis auditable. */
62
+ risk_profile_hash?: string;
63
+ created_at: string;
64
+ }
65
+ export interface PolicySignature {
66
+ did: string;
67
+ /** `ed25519:<hex>` over the canonical (JCS) bytes of the body. */
68
+ sig: string;
69
+ }
70
+ export interface Policy {
71
+ body: PolicyBody;
72
+ signatures: PolicySignature[];
73
+ }
74
+ export interface PolicyInput {
75
+ insurer: string;
76
+ holder: string;
77
+ subject: string;
78
+ /** Decimal strings — never floats. */
79
+ premium: string;
80
+ coverageLimit: string;
81
+ currency: string;
82
+ coveredScopes: string[];
83
+ period: {
84
+ start: string;
85
+ end: string;
86
+ };
87
+ riskProfileHash?: string;
88
+ createdAt: string;
89
+ }
90
+ export declare function buildPolicyBody(input: PolicyInput): PolicyBody;
91
+ /** One party signs the policy. Collect one from the insurer and one from the holder. */
92
+ export declare function signPolicy(body: PolicyBody, did: string, privateKey: Uint8Array): PolicySignature;
93
+ export declare function assemblePolicy(body: PolicyBody, signatures: PolicySignature[]): Policy;
94
+ export declare function policyHash(policy: Policy): string;
95
+ export interface InsuranceCheck {
96
+ ok: boolean;
97
+ reasons: string[];
98
+ }
99
+ /** Verify the policy: structure sane, premium/limit in the same currency, BOTH insurer and holder signed. */
100
+ export declare function verifyPolicy(policy: Policy | undefined): InsuranceCheck;
101
+ /** One incident the claim is about — a receipt on the ledger, cited by hash. */
102
+ export interface Incident {
103
+ /** JCS hash of the incident receipt. */
104
+ receipt: string;
105
+ ts: string;
106
+ target: string;
107
+ }
108
+ export interface ClaimBody {
109
+ v: 1;
110
+ type: 'insurance.claim';
111
+ policy_hash: string;
112
+ /** Must be the policy's holder. */
113
+ claimant: string;
114
+ amount: Money;
115
+ incidents: Incident[];
116
+ ts: string;
117
+ }
118
+ export interface Claim {
119
+ body: ClaimBody;
120
+ signatures: PolicySignature[];
121
+ }
122
+ export declare function buildClaimBody(policy: Policy, fields: {
123
+ amount: string;
124
+ incidents: Incident[];
125
+ ts: string;
126
+ }): ClaimBody;
127
+ export declare function signClaim(body: ClaimBody, did: string, privateKey: Uint8Array): PolicySignature;
128
+ export declare function assembleClaim(body: ClaimBody, signatures: PolicySignature[]): Claim;
129
+ /** Full receipt + Merkle evidence proving one cited incident is really in the log. */
130
+ export interface IncidentEvidence {
131
+ receipt: Receipt;
132
+ sth: SignedTreeHead;
133
+ index: number;
134
+ /** Audit path, hex-encoded. */
135
+ proof: string[];
136
+ }
137
+ export interface ClaimAssessment {
138
+ /** Terms verdict: policy valid, claim signed by the holder, amount within limit, every incident in-period and in-scope. */
139
+ ok: boolean;
140
+ reasons: string[];
141
+ /** Incident receipt hashes proven in the log by supplied evidence. */
142
+ proven: string[];
143
+ /** Incident receipt hashes cited but not (or not validly) proven. Unproven is a fact, not a failure — the adjuster decides. */
144
+ unproven: string[];
145
+ }
146
+ /**
147
+ * Deterministic claim assessment — facts for the adjuster, not a payout decision.
148
+ * `evidence` maps an incident's receipt hash to the full receipt + inclusion proof;
149
+ * incidents without valid evidence land in `unproven`.
150
+ */
151
+ export declare function assessClaim(claim: Claim | undefined, policy: Policy, evidence?: Record<string, IncidentEvidence>): ClaimAssessment;
152
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AA8BA,OAAO,EAAgB,KAAK,UAAU,EAAE,KAAK,SAAS,EAAE,MAAM,sBAAsB,CAAC;AACrF,OAAO,EASL,KAAK,cAAc,EACnB,KAAK,OAAO,EACZ,KAAK,cAAc,EACpB,MAAM,aAAa,CAAC;AACrB,OAAO,EAAc,KAAK,KAAK,EAAE,MAAM,iBAAiB,CAAC;AAEzD,eAAO,MAAM,YAAY,4GAC6E,CAAC;AAEvG,MAAM,WAAW,SAAS;IACxB,QAAQ,EAAE,MAAM,CAAC;IACjB,uBAAuB,EAAE,MAAM,CAAC;IAChC,+EAA+E;IAC/E,QAAQ,EAAE,MAAM,GAAG,IAAI,CAAC;IACxB,kFAAkF;IAClF,eAAe,EAAE,MAAM,GAAG,IAAI,CAAC;IAC/B,OAAO,EAAE,OAAO,CAAC;IACjB,cAAc,EAAE,OAAO,CAAC;IACxB,yEAAyE;IACzE,MAAM,CAAC,EAAE,MAAM,EAAE,CAAC;IAClB,4FAA4F;IAC5F,kBAAkB,CAAC,EAAE,OAAO,CAAC;CAC9B;AAED,MAAM,WAAW,WAAW;IAC1B,CAAC,EAAE,CAAC,CAAC;IACL,IAAI,EAAE,wBAAwB,CAAC;IAC/B,GAAG,EAAE,MAA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,WAAW,CACzB,KAAK,EAAE,KAAK,GAAG,SAAS,EACxB,MAAM,EAAE,MAAM,EACd,QAAQ,GAAE,MAAM,CAAC,MAAM,EAAE,gBAAgB,CAAM,GAC9C,eAAe,CAmDjB"}
package/dist/index.js ADDED
@@ -0,0 +1,247 @@
1
+ /**
2
+ * @zanii/insurance — machine-verifiable underwriting for agent liability.
3
+ *
4
+ * The commercial unlock for a transparency ledger is an **insurable agent**: an insurer
5
+ * prices a policy off the agent's ledger history, and a claim resolves against
6
+ * Merkle-proven receipts instead of a dispute. This package is the three artifacts that
7
+ * make that work:
8
+ *
9
+ * 1. **A risk profile** (`riskProfile`) — underwriting FACTS derived from the ledger's own
10
+ * un-inflatable aggregate (the same `/v1/reputation` count AgentCV uses) plus the
11
+ * agent's delegated authority. Deliberately **never a score**: a score Zanii invents
12
+ * gets gamed and creates liability; insurers price, we state facts and raise flags.
13
+ * 2. **A policy** both insurer and holder co-sign — premium and coverage limit in integer
14
+ * minor units, covered scopes, coverage period, optionally pinned to the exact risk
15
+ * profile it was underwritten on.
16
+ * 3. **A claim + a deterministic assessment** (`assessClaim`) — the claim cites incident
17
+ * receipts by hash; the assessment checks terms (period, scope, limit, signatures)
18
+ * and, where the full receipt + inclusion proof is supplied, proves each incident is
19
+ * really in the log. Facts for the adjuster, not a payout decision.
20
+ *
21
+ * ## The limit, stated up front
22
+ *
23
+ * **Ledger silence is unknown, not good.** An agent that never receipts its failures
24
+ * looks safer than it is — the profile flags thin or stale history instead of rewarding
25
+ * it, and an underwriter must treat uncovered activity as unknown risk. Cryptography
26
+ * verifies attestations, not reality: a proven incident receipt shows what was recorded,
27
+ * not everything that happened.
28
+ */
29
+ import { ed25519 } from '@noble/curves/ed25519';
30
+ import { bytesToHex, hexToBytes } from '@noble/hashes/utils';
31
+ import { resolveAgent } from '@zanii/a2a-directory';
32
+ import { canonicalBytes, jcsHash, leafHash, publicKeyFromDid, scopeCovers, verifyInclusion, verifyReceipt, verifySTH, } from '@zanii/core';
33
+ import { parseMoney } from '@zanii/payments';
34
+ export const SILENCE_NOTE = 'ledger silence is unknown, not good — an agent that never receipts failures looks safer than it is';
35
+ const DAY_MS = 86_400_000;
36
+ const daysBetween = (from, to) => Math.floor((Date.parse(to) - Date.parse(from)) / DAY_MS);
37
+ /** Derive the profile offline from a ledger aggregate you already hold. Pure and deterministic. */
38
+ export function buildRiskProfile(trust, opts) {
39
+ if (Number.isNaN(Date.parse(opts.asOf)))
40
+ throw new Error('asOf must be an ISO timestamp');
41
+ const facts = {
42
+ receipts: trust.receipts,
43
+ distinct_counterparties: trust.distinct_counterparties,
44
+ age_days: trust.first_ts ? daysBetween(trust.first_ts, opts.asOf) : null,
45
+ days_since_last: trust.last_ts ? daysBetween(trust.last_ts, opts.asOf) : null,
46
+ revoked: trust.revoked,
47
+ fully_anchored: trust.fully_anchored,
48
+ };
49
+ if (opts.delegation) {
50
+ const scopes = [...new Set(opts.delegation.flatMap((c) => c.scopes))].sort();
51
+ facts.scopes = scopes;
52
+ facts.wildcard_authority = scopes.includes('*');
53
+ }
54
+ const flags = [];
55
+ if (facts.revoked)
56
+ flags.push('REVOKED');
57
+ if (!facts.fully_anchored)
58
+ flags.push('NOT_FULLY_ANCHORED');
59
+ if (facts.receipts < 50)
60
+ flags.push('THIN_HISTORY');
61
+ if (facts.days_since_last !== null && facts.days_since_last > 30)
62
+ flags.push('STALE');
63
+ if (facts.wildcard_authority)
64
+ flags.push('WILDCARD_AUTHORITY');
65
+ return {
66
+ v: 1,
67
+ type: 'insurance.risk_profile',
68
+ did: trust.agent_id,
69
+ owner: trust.owner,
70
+ as_of: opts.asOf,
71
+ facts,
72
+ flags,
73
+ note: SILENCE_NOTE,
74
+ };
75
+ }
76
+ /** Pull the ledger's aggregate for `did` and derive the profile. Returns null if no history. */
77
+ export async function riskProfile(did, opts) {
78
+ const trust = await resolveAgent(did, { server: opts.server, fetchImpl: opts.fetchImpl });
79
+ if (!trust)
80
+ return null;
81
+ return buildRiskProfile(trust, { asOf: opts.asOf, delegation: opts.delegation });
82
+ }
83
+ /** Canonical hash — pin a policy to the exact profile it was underwritten on. */
84
+ export function riskProfileHash(profile) {
85
+ return jcsHash(profile);
86
+ }
87
+ export function buildPolicyBody(input) {
88
+ if (!input.insurer || !input.holder || !input.subject)
89
+ throw new Error('insurer, holder, and subject are required');
90
+ if (input.insurer === input.holder)
91
+ throw new Error('insurer and holder must differ (no self-insurance)');
92
+ if (input.coveredScopes.length === 0)
93
+ throw new Error('covered_scopes must not be empty');
94
+ if (Number.isNaN(Date.parse(input.period.start)) || Number.isNaN(Date.parse(input.period.end))) {
95
+ throw new Error('period start/end must be ISO timestamps');
96
+ }
97
+ if (Date.parse(input.period.start) >= Date.parse(input.period.end))
98
+ throw new Error('period start must be before end');
99
+ if (Number.isNaN(Date.parse(input.createdAt)))
100
+ throw new Error('createdAt must be an ISO timestamp');
101
+ const body = {
102
+ v: 1,
103
+ type: 'insurance.policy',
104
+ insurer: input.insurer,
105
+ holder: input.holder,
106
+ subject: input.subject,
107
+ premium: parseMoney(input.premium, input.currency),
108
+ coverage_limit: parseMoney(input.coverageLimit, input.currency),
109
+ covered_scopes: [...input.coveredScopes].sort(),
110
+ period: input.period,
111
+ created_at: input.createdAt,
112
+ };
113
+ if (input.riskProfileHash !== undefined)
114
+ body.risk_profile_hash = input.riskProfileHash;
115
+ return body;
116
+ }
117
+ const sign = (obj, priv) => `ed25519:${bytesToHex(ed25519.sign(canonicalBytes(obj), priv))}`;
118
+ const sigValid = (obj, did, sig) => {
119
+ const pub = publicKeyFromDid(did);
120
+ const hex = typeof sig === 'string' && sig.startsWith('ed25519:') ? sig.slice(8) : '';
121
+ if (!pub || !/^[0-9a-f]{128}$/.test(hex))
122
+ return false;
123
+ try {
124
+ return ed25519.verify(hexToBytes(hex), canonicalBytes(obj), pub);
125
+ }
126
+ catch {
127
+ return false;
128
+ }
129
+ };
130
+ /** One party signs the policy. Collect one from the insurer and one from the holder. */
131
+ export function signPolicy(body, did, privateKey) {
132
+ return { did, sig: sign(body, privateKey) };
133
+ }
134
+ export function assemblePolicy(body, signatures) {
135
+ return { body, signatures };
136
+ }
137
+ export function policyHash(policy) {
138
+ return jcsHash(policy);
139
+ }
140
+ /** Verify the policy: structure sane, premium/limit in the same currency, BOTH insurer and holder signed. */
141
+ export function verifyPolicy(policy) {
142
+ const reasons = [];
143
+ const p = policy ?? {};
144
+ const b = p.body ?? {};
145
+ if (b.v !== 1 || b.type !== 'insurance.policy')
146
+ reasons.push('not an insurance policy (v1)');
147
+ if (!b.insurer || !b.holder || !b.subject || b.insurer === b.holder)
148
+ reasons.push('missing/invalid parties');
149
+ for (const [label, m] of [['premium', b.premium], ['coverage_limit', b.coverage_limit]]) {
150
+ if (!m?.minor || !/^\d+$/.test(m.minor) || BigInt(m.minor) <= 0n)
151
+ reasons.push(`invalid ${label} (integer minor units required)`);
152
+ }
153
+ if (b.premium?.currency && b.coverage_limit?.currency && b.premium.currency !== b.coverage_limit.currency) {
154
+ reasons.push('premium and coverage_limit must be in the same currency');
155
+ }
156
+ if (!b.covered_scopes?.length)
157
+ reasons.push('covered_scopes must not be empty');
158
+ if (Number.isNaN(Date.parse(b.period?.start ?? '')) ||
159
+ Number.isNaN(Date.parse(b.period?.end ?? '')) ||
160
+ Date.parse(b.period?.start ?? '') >= Date.parse(b.period?.end ?? '')) {
161
+ reasons.push('invalid period');
162
+ }
163
+ if (reasons.length === 0) {
164
+ for (const [party, role] of [[b.insurer, 'insurer'], [b.holder, 'holder']]) {
165
+ const s = (p.signatures ?? []).find((x) => x.did === party);
166
+ if (!s)
167
+ reasons.push(`missing signature from ${role}`);
168
+ else if (!sigValid(b, s.did, s.sig))
169
+ reasons.push(`invalid signature from ${role}`);
170
+ }
171
+ }
172
+ return { ok: reasons.length === 0, reasons };
173
+ }
174
+ export function buildClaimBody(policy, fields) {
175
+ if (fields.incidents.length === 0)
176
+ throw new Error('a claim must cite at least one incident receipt');
177
+ return {
178
+ v: 1,
179
+ type: 'insurance.claim',
180
+ policy_hash: policyHash(policy),
181
+ claimant: policy.body.holder,
182
+ amount: parseMoney(fields.amount, policy.body.coverage_limit.currency),
183
+ incidents: fields.incidents,
184
+ ts: fields.ts,
185
+ };
186
+ }
187
+ export function signClaim(body, did, privateKey) {
188
+ return { did, sig: sign(body, privateKey) };
189
+ }
190
+ export function assembleClaim(body, signatures) {
191
+ return { body, signatures };
192
+ }
193
+ /**
194
+ * Deterministic claim assessment — facts for the adjuster, not a payout decision.
195
+ * `evidence` maps an incident's receipt hash to the full receipt + inclusion proof;
196
+ * incidents without valid evidence land in `unproven`.
197
+ */
198
+ export function assessClaim(claim, policy, evidence = {}) {
199
+ const pol = verifyPolicy(policy);
200
+ if (!pol.ok)
201
+ return { ok: false, reasons: pol.reasons.map((r) => `policy: ${r}`), proven: [], unproven: [] };
202
+ const reasons = [];
203
+ const c = claim ?? {};
204
+ const b = c.body ?? {};
205
+ const pb = policy.body;
206
+ if (b.v !== 1 || b.type !== 'insurance.claim')
207
+ reasons.push('not an insurance claim (v1)');
208
+ if (b.policy_hash !== policyHash(policy))
209
+ reasons.push('claim references a different policy');
210
+ if (b.claimant !== pb.holder)
211
+ reasons.push('claimant is not the policy holder');
212
+ const holderSig = (c.signatures ?? []).find((s) => s.did === pb.holder);
213
+ if (!holderSig || !sigValid(b, holderSig.did, holderSig.sig)) {
214
+ reasons.push('claim is not signed by the policy holder');
215
+ }
216
+ if (!b.amount?.minor || b.amount.currency !== pb.coverage_limit.currency) {
217
+ reasons.push('claim amount must be in the policy currency');
218
+ }
219
+ else if (BigInt(b.amount.minor) > BigInt(pb.coverage_limit.minor)) {
220
+ reasons.push(`claim ${b.amount.display} exceeds the coverage limit ${pb.coverage_limit.display}`);
221
+ }
222
+ const incidents = b.incidents ?? [];
223
+ if (incidents.length === 0)
224
+ reasons.push('claim cites no incidents');
225
+ for (const [i, inc] of incidents.entries()) {
226
+ const its = Date.parse(inc.ts);
227
+ if (Number.isNaN(its) || its < Date.parse(pb.period.start) || its > Date.parse(pb.period.end)) {
228
+ reasons.push(`incident #${i} at ${inc.ts} is outside the coverage period`);
229
+ }
230
+ if (!pb.covered_scopes.some((s) => scopeCovers(s, inc.target))) {
231
+ reasons.push(`incident #${i} target '${inc.target}' is not within the covered scopes`);
232
+ }
233
+ }
234
+ const proven = [];
235
+ const unproven = [];
236
+ for (const inc of incidents) {
237
+ const ev = evidence[inc.receipt];
238
+ let good = false;
239
+ if (ev && jcsHash(ev.receipt) === inc.receipt && verifyReceipt(ev.receipt).ok && verifySTH(ev.sth)) {
240
+ const root = hexToBytes(ev.sth.root.replace('sha256:', ''));
241
+ good = verifyInclusion(leafHash(canonicalBytes(ev.receipt)), ev.index, ev.sth.size, ev.proof.map((h) => hexToBytes(h)), root);
242
+ }
243
+ (good ? proven : unproven).push(inc.receipt);
244
+ }
245
+ return { ok: reasons.length === 0, reasons, proven, unproven };
246
+ }
247
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;GA2BG;AACH,OAAO,EAAE,OAAO,EAAE,MAAM,uBAAuB,CAAC;AAChD,OAAO,EAAE,UAAU,EAAE,UAAU,EAAE,MAAM,qBAAqB,CAAC;AAC7D,OAAO,EAAE,YAAY,EAAmC,MAAM,sBAAsB,CAAC;AACrF,OAAO,EACL,cAAc,EACd,OAAO,EACP,QAAQ,EACR,gBAAgB,EAChB,WAAW,EACX,eAAe,EACf,aAAa,EACb,SAAS,GAIV,MAAM,aAAa,CAAC;AACrB,OAAO,EAAE,UAAU,EAAc,MAAM,iBAAiB,CAAC;AAEzD,MAAM,CAAC,MAAM,YAAY,GACvB,oGAAoG,CAAC;AA6BvG,MAAM,MAAM,GAAG,UAAU,CAAC;AAC1B,MAAM,WAAW,GAAG,CAAC,IAAY,EAAE,EAAU,EAAU,EAAE,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,IAA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AED,MAAM,MAAM,GAAa,EAAE,CAAC;IAC5B,MAAM,QAAQ,GAAa,EAAE,CAAC;IAC9B,KAAK,MAAM,GAAG,IAAI,SAAS,EAAE,CAAC;QAC5B,MAAM,EAAE,GAAG,QAAQ,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC;QACjC,IAAI,IAAI,GAAG,KAAK,CAAC;QACjB,IAAI,EAAE,IAAI,OAAO,CAAC,EAAE,CAAC,OAA6C,CAAC,KAAK,GAAG,CAAC,OAAO,IAAI,aAAa,CAAC,EAAE,CAAC,OAAO,CAAC,CAAC,EAAE,IAAI,SAAS,CAAC,EAAE,CAAC,GAAG,CAAC,EAAE,CAAC;YACzI,MAAM,IAAI,GAAG,UAAU,CAAC,EAAE,CAAC,GAAG,CAAC,IAAI,CAAC,OAAO,CAAC,SAAS,EAAE,EAAE,CAAC,CAAC,CAAC;YAC5D,IAAI,GAAG,eAAe,CACpB,QAAQ,CAAC,cAAc,CAAC,EAAE,CAAC,OAA6C,CAAC,CAAC,EAC1E,EAAE,CAAC,KAAK,EACR,EAAE,CAAC,GAAG,CAAC,IAAI,EACX,EAAE,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC,EAClC,IAAI,CACL,CAAC;QACJ,CAAC;QACD,CAAC,IAAI,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,QAAQ,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC;IAC/C,CAAC;IAED,OAAO,EAAE,EAAE,EAAE,OAAO,CAAC,MAAM,KAAK,CAAC,EAAE,OAAO,EAAE,MAAM,EAAE,QAAQ,EAAE,CAAC;AACjE,CAAC"}
package/package.json ADDED
@@ -0,0 +1,45 @@
1
+ {
2
+ "name": "@zanii/insurance",
3
+ "version": "0.1.0",
4
+ "description": "Machine-verifiable underwriting for agent liability - risk FACTS from the ledger's own un-inflatable aggregate (never a score), a co-signed policy, and claims that resolve against Merkle-proven receipts instead of disputes. Zanii states facts; insurers price. Ledger silence is unknown, not good.",
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
+ "@noble/curves": "^1.8.1",
35
+ "@noble/hashes": "^1.7.1",
36
+ "@zanii/core": "0.4.0",
37
+ "@zanii/a2a-directory": "0.1.0",
38
+ "@zanii/payments": "0.1.0"
39
+ },
40
+ "scripts": {
41
+ "build": "tsc -p tsconfig.build.json",
42
+ "test": "vitest run",
43
+ "typecheck": "tsc --noEmit"
44
+ }
45
+ }
package/src/index.ts ADDED
@@ -0,0 +1,388 @@
1
+ /**
2
+ * @zanii/insurance — machine-verifiable underwriting for agent liability.
3
+ *
4
+ * The commercial unlock for a transparency ledger is an **insurable agent**: an insurer
5
+ * prices a policy off the agent's ledger history, and a claim resolves against
6
+ * Merkle-proven receipts instead of a dispute. This package is the three artifacts that
7
+ * make that work:
8
+ *
9
+ * 1. **A risk profile** (`riskProfile`) — underwriting FACTS derived from the ledger's own
10
+ * un-inflatable aggregate (the same `/v1/reputation` count AgentCV uses) plus the
11
+ * agent's delegated authority. Deliberately **never a score**: a score Zanii invents
12
+ * gets gamed and creates liability; insurers price, we state facts and raise flags.
13
+ * 2. **A policy** both insurer and holder co-sign — premium and coverage limit in integer
14
+ * minor units, covered scopes, coverage period, optionally pinned to the exact risk
15
+ * profile it was underwritten on.
16
+ * 3. **A claim + a deterministic assessment** (`assessClaim`) — the claim cites incident
17
+ * receipts by hash; the assessment checks terms (period, scope, limit, signatures)
18
+ * and, where the full receipt + inclusion proof is supplied, proves each incident is
19
+ * really in the log. Facts for the adjuster, not a payout decision.
20
+ *
21
+ * ## The limit, stated up front
22
+ *
23
+ * **Ledger silence is unknown, not good.** An agent that never receipts its failures
24
+ * looks safer than it is — the profile flags thin or stale history instead of rewarding
25
+ * it, and an underwriter must treat uncovered activity as unknown risk. Cryptography
26
+ * verifies attestations, not reality: a proven incident receipt shows what was recorded,
27
+ * not everything that happened.
28
+ */
29
+ import { ed25519 } from '@noble/curves/ed25519';
30
+ import { bytesToHex, hexToBytes } from '@noble/hashes/utils';
31
+ import { resolveAgent, type AgentTrust, type FetchLike } from '@zanii/a2a-directory';
32
+ import {
33
+ canonicalBytes,
34
+ jcsHash,
35
+ leafHash,
36
+ publicKeyFromDid,
37
+ scopeCovers,
38
+ verifyInclusion,
39
+ verifyReceipt,
40
+ verifySTH,
41
+ type DelegationCert,
42
+ type Receipt,
43
+ type SignedTreeHead,
44
+ } from '@zanii/core';
45
+ import { parseMoney, type Money } from '@zanii/payments';
46
+
47
+ export const SILENCE_NOTE =
48
+ 'ledger silence is unknown, not good — an agent that never receipts failures looks safer than it is';
49
+
50
+ export interface RiskFacts {
51
+ receipts: number;
52
+ distinct_counterparties: number;
53
+ /** Whole days from first receipt to `as_of`. null when there is no history. */
54
+ age_days: number | null;
55
+ /** Whole days from the last receipt to `as_of`. null when there is no history. */
56
+ days_since_last: number | null;
57
+ revoked: boolean;
58
+ fully_anchored: boolean;
59
+ /** Scopes currently delegated to the agent, when certs were supplied. */
60
+ scopes?: string[];
61
+ /** true when any supplied cert grants `*` — unbounded authority is an underwriting fact. */
62
+ wildcard_authority?: boolean;
63
+ }
64
+
65
+ export interface RiskProfile {
66
+ v: 1;
67
+ type: 'insurance.risk_profile';
68
+ did: string;
69
+ owner: string;
70
+ as_of: string;
71
+ facts: RiskFacts;
72
+ /** Deterministic, named conditions — never a number. */
73
+ flags: string[];
74
+ note: string;
75
+ }
76
+
77
+ const DAY_MS = 86_400_000;
78
+ const daysBetween = (from: string, to: string): number => Math.floor((Date.parse(to) - Date.parse(from)) / DAY_MS);
79
+
80
+ /** Derive the profile offline from a ledger aggregate you already hold. Pure and deterministic. */
81
+ export function buildRiskProfile(trust: AgentTrust, opts: { asOf: string; delegation?: DelegationCert[] }): RiskProfile {
82
+ if (Number.isNaN(Date.parse(opts.asOf))) throw new Error('asOf must be an ISO timestamp');
83
+ const facts: RiskFacts = {
84
+ receipts: trust.receipts,
85
+ distinct_counterparties: trust.distinct_counterparties,
86
+ age_days: trust.first_ts ? daysBetween(trust.first_ts, opts.asOf) : null,
87
+ days_since_last: trust.last_ts ? daysBetween(trust.last_ts, opts.asOf) : null,
88
+ revoked: trust.revoked,
89
+ fully_anchored: trust.fully_anchored,
90
+ };
91
+ if (opts.delegation) {
92
+ const scopes = [...new Set(opts.delegation.flatMap((c) => c.scopes))].sort();
93
+ facts.scopes = scopes;
94
+ facts.wildcard_authority = scopes.includes('*');
95
+ }
96
+ const flags: string[] = [];
97
+ if (facts.revoked) flags.push('REVOKED');
98
+ if (!facts.fully_anchored) flags.push('NOT_FULLY_ANCHORED');
99
+ if (facts.receipts < 50) flags.push('THIN_HISTORY');
100
+ if (facts.days_since_last !== null && facts.days_since_last > 30) flags.push('STALE');
101
+ if (facts.wildcard_authority) flags.push('WILDCARD_AUTHORITY');
102
+ return {
103
+ v: 1,
104
+ type: 'insurance.risk_profile',
105
+ did: trust.agent_id,
106
+ owner: trust.owner,
107
+ as_of: opts.asOf,
108
+ facts,
109
+ flags,
110
+ note: SILENCE_NOTE,
111
+ };
112
+ }
113
+
114
+ /** Pull the ledger's aggregate for `did` and derive the profile. Returns null if no history. */
115
+ export async function riskProfile(
116
+ did: string,
117
+ opts: { asOf: string; server?: string; fetchImpl?: FetchLike; delegation?: DelegationCert[] },
118
+ ): Promise<RiskProfile | null> {
119
+ const trust = await resolveAgent(did, { server: opts.server, fetchImpl: opts.fetchImpl });
120
+ if (!trust) return null;
121
+ return buildRiskProfile(trust, { asOf: opts.asOf, delegation: opts.delegation });
122
+ }
123
+
124
+ /** Canonical hash — pin a policy to the exact profile it was underwritten on. */
125
+ export function riskProfileHash(profile: RiskProfile): string {
126
+ return jcsHash(profile as unknown as Record<string, unknown>);
127
+ }
128
+
129
+ export interface PolicyBody {
130
+ v: 1;
131
+ type: 'insurance.policy';
132
+ /** Who underwrites. */
133
+ insurer: string;
134
+ /** Who holds the policy — the agent's owner. */
135
+ holder: string;
136
+ /** The insured agent. */
137
+ subject: string;
138
+ premium: Money;
139
+ coverage_limit: Money;
140
+ /** Incidents are covered only under these scopes. */
141
+ covered_scopes: string[];
142
+ period: { start: string; end: string };
143
+ /** Hash of the `RiskProfile` this was priced on — makes the underwriting basis auditable. */
144
+ risk_profile_hash?: string;
145
+ created_at: string;
146
+ }
147
+
148
+ export interface PolicySignature {
149
+ did: string;
150
+ /** `ed25519:<hex>` over the canonical (JCS) bytes of the body. */
151
+ sig: string;
152
+ }
153
+
154
+ export interface Policy {
155
+ body: PolicyBody;
156
+ signatures: PolicySignature[];
157
+ }
158
+
159
+ export interface PolicyInput {
160
+ insurer: string;
161
+ holder: string;
162
+ subject: string;
163
+ /** Decimal strings — never floats. */
164
+ premium: string;
165
+ coverageLimit: string;
166
+ currency: string;
167
+ coveredScopes: string[];
168
+ period: { start: string; end: string };
169
+ riskProfileHash?: string;
170
+ createdAt: string;
171
+ }
172
+
173
+ export function buildPolicyBody(input: PolicyInput): PolicyBody {
174
+ if (!input.insurer || !input.holder || !input.subject) throw new Error('insurer, holder, and subject are required');
175
+ if (input.insurer === input.holder) throw new Error('insurer and holder must differ (no self-insurance)');
176
+ if (input.coveredScopes.length === 0) throw new Error('covered_scopes must not be empty');
177
+ if (Number.isNaN(Date.parse(input.period.start)) || Number.isNaN(Date.parse(input.period.end))) {
178
+ throw new Error('period start/end must be ISO timestamps');
179
+ }
180
+ if (Date.parse(input.period.start) >= Date.parse(input.period.end)) throw new Error('period start must be before end');
181
+ if (Number.isNaN(Date.parse(input.createdAt))) throw new Error('createdAt must be an ISO timestamp');
182
+ const body: PolicyBody = {
183
+ v: 1,
184
+ type: 'insurance.policy',
185
+ insurer: input.insurer,
186
+ holder: input.holder,
187
+ subject: input.subject,
188
+ premium: parseMoney(input.premium, input.currency),
189
+ coverage_limit: parseMoney(input.coverageLimit, input.currency),
190
+ covered_scopes: [...input.coveredScopes].sort(),
191
+ period: input.period,
192
+ created_at: input.createdAt,
193
+ };
194
+ if (input.riskProfileHash !== undefined) body.risk_profile_hash = input.riskProfileHash;
195
+ return body;
196
+ }
197
+
198
+ const sign = (obj: Record<string, unknown>, priv: Uint8Array): string =>
199
+ `ed25519:${bytesToHex(ed25519.sign(canonicalBytes(obj), priv))}`;
200
+
201
+ const sigValid = (obj: Record<string, unknown>, did: string, sig: unknown): boolean => {
202
+ const pub = publicKeyFromDid(did);
203
+ const hex = typeof sig === 'string' && sig.startsWith('ed25519:') ? sig.slice(8) : '';
204
+ if (!pub || !/^[0-9a-f]{128}$/.test(hex)) return false;
205
+ try {
206
+ return ed25519.verify(hexToBytes(hex), canonicalBytes(obj), pub);
207
+ } catch {
208
+ return false;
209
+ }
210
+ };
211
+
212
+ /** One party signs the policy. Collect one from the insurer and one from the holder. */
213
+ export function signPolicy(body: PolicyBody, did: string, privateKey: Uint8Array): PolicySignature {
214
+ return { did, sig: sign(body as unknown as Record<string, unknown>, privateKey) };
215
+ }
216
+
217
+ export function assemblePolicy(body: PolicyBody, signatures: PolicySignature[]): Policy {
218
+ return { body, signatures };
219
+ }
220
+
221
+ export function policyHash(policy: Policy): string {
222
+ return jcsHash(policy as unknown as Record<string, unknown>);
223
+ }
224
+
225
+ export interface InsuranceCheck {
226
+ ok: boolean;
227
+ reasons: string[];
228
+ }
229
+
230
+ /** Verify the policy: structure sane, premium/limit in the same currency, BOTH insurer and holder signed. */
231
+ export function verifyPolicy(policy: Policy | undefined): InsuranceCheck {
232
+ const reasons: string[] = [];
233
+ const p = policy ?? ({} as Policy);
234
+ const b = p.body ?? ({} as PolicyBody);
235
+ if (b.v !== 1 || b.type !== 'insurance.policy') reasons.push('not an insurance policy (v1)');
236
+ if (!b.insurer || !b.holder || !b.subject || b.insurer === b.holder) reasons.push('missing/invalid parties');
237
+ for (const [label, m] of [['premium', b.premium], ['coverage_limit', b.coverage_limit]] as const) {
238
+ if (!m?.minor || !/^\d+$/.test(m.minor) || BigInt(m.minor) <= 0n) reasons.push(`invalid ${label} (integer minor units required)`);
239
+ }
240
+ if (b.premium?.currency && b.coverage_limit?.currency && b.premium.currency !== b.coverage_limit.currency) {
241
+ reasons.push('premium and coverage_limit must be in the same currency');
242
+ }
243
+ if (!b.covered_scopes?.length) reasons.push('covered_scopes must not be empty');
244
+ if (
245
+ Number.isNaN(Date.parse(b.period?.start ?? '')) ||
246
+ Number.isNaN(Date.parse(b.period?.end ?? '')) ||
247
+ Date.parse(b.period?.start ?? '') >= Date.parse(b.period?.end ?? '')
248
+ ) {
249
+ reasons.push('invalid period');
250
+ }
251
+ if (reasons.length === 0) {
252
+ for (const [party, role] of [[b.insurer, 'insurer'], [b.holder, 'holder']] as const) {
253
+ const s = (p.signatures ?? []).find((x) => x.did === party);
254
+ if (!s) reasons.push(`missing signature from ${role}`);
255
+ else if (!sigValid(b as unknown as Record<string, unknown>, s.did, s.sig)) reasons.push(`invalid signature from ${role}`);
256
+ }
257
+ }
258
+ return { ok: reasons.length === 0, reasons };
259
+ }
260
+
261
+ /** One incident the claim is about — a receipt on the ledger, cited by hash. */
262
+ export interface Incident {
263
+ /** JCS hash of the incident receipt. */
264
+ receipt: string;
265
+ ts: string;
266
+ target: string;
267
+ }
268
+
269
+ export interface ClaimBody {
270
+ v: 1;
271
+ type: 'insurance.claim';
272
+ policy_hash: string;
273
+ /** Must be the policy's holder. */
274
+ claimant: string;
275
+ amount: Money;
276
+ incidents: Incident[];
277
+ ts: string;
278
+ }
279
+
280
+ export interface Claim {
281
+ body: ClaimBody;
282
+ signatures: PolicySignature[];
283
+ }
284
+
285
+ export function buildClaimBody(
286
+ policy: Policy,
287
+ fields: { amount: string; incidents: Incident[]; ts: string },
288
+ ): ClaimBody {
289
+ if (fields.incidents.length === 0) throw new Error('a claim must cite at least one incident receipt');
290
+ return {
291
+ v: 1,
292
+ type: 'insurance.claim',
293
+ policy_hash: policyHash(policy),
294
+ claimant: policy.body.holder,
295
+ amount: parseMoney(fields.amount, policy.body.coverage_limit.currency),
296
+ incidents: fields.incidents,
297
+ ts: fields.ts,
298
+ };
299
+ }
300
+
301
+ export function signClaim(body: ClaimBody, did: string, privateKey: Uint8Array): PolicySignature {
302
+ return { did, sig: sign(body as unknown as Record<string, unknown>, privateKey) };
303
+ }
304
+
305
+ export function assembleClaim(body: ClaimBody, signatures: PolicySignature[]): Claim {
306
+ return { body, signatures };
307
+ }
308
+
309
+ /** Full receipt + Merkle evidence proving one cited incident is really in the log. */
310
+ export interface IncidentEvidence {
311
+ receipt: Receipt;
312
+ sth: SignedTreeHead;
313
+ index: number;
314
+ /** Audit path, hex-encoded. */
315
+ proof: string[];
316
+ }
317
+
318
+ export interface ClaimAssessment {
319
+ /** Terms verdict: policy valid, claim signed by the holder, amount within limit, every incident in-period and in-scope. */
320
+ ok: boolean;
321
+ reasons: string[];
322
+ /** Incident receipt hashes proven in the log by supplied evidence. */
323
+ proven: string[];
324
+ /** Incident receipt hashes cited but not (or not validly) proven. Unproven is a fact, not a failure — the adjuster decides. */
325
+ unproven: string[];
326
+ }
327
+
328
+ /**
329
+ * Deterministic claim assessment — facts for the adjuster, not a payout decision.
330
+ * `evidence` maps an incident's receipt hash to the full receipt + inclusion proof;
331
+ * incidents without valid evidence land in `unproven`.
332
+ */
333
+ export function assessClaim(
334
+ claim: Claim | undefined,
335
+ policy: Policy,
336
+ evidence: Record<string, IncidentEvidence> = {},
337
+ ): ClaimAssessment {
338
+ const pol = verifyPolicy(policy);
339
+ if (!pol.ok) return { ok: false, reasons: pol.reasons.map((r) => `policy: ${r}`), proven: [], unproven: [] };
340
+ const reasons: string[] = [];
341
+ const c = claim ?? ({} as Claim);
342
+ const b = c.body ?? ({} as ClaimBody);
343
+ const pb = policy.body;
344
+
345
+ if (b.v !== 1 || b.type !== 'insurance.claim') reasons.push('not an insurance claim (v1)');
346
+ if (b.policy_hash !== policyHash(policy)) reasons.push('claim references a different policy');
347
+ if (b.claimant !== pb.holder) reasons.push('claimant is not the policy holder');
348
+ const holderSig = (c.signatures ?? []).find((s) => s.did === pb.holder);
349
+ if (!holderSig || !sigValid(b as unknown as Record<string, unknown>, holderSig.did, holderSig.sig)) {
350
+ reasons.push('claim is not signed by the policy holder');
351
+ }
352
+ if (!b.amount?.minor || b.amount.currency !== pb.coverage_limit.currency) {
353
+ reasons.push('claim amount must be in the policy currency');
354
+ } else if (BigInt(b.amount.minor) > BigInt(pb.coverage_limit.minor)) {
355
+ reasons.push(`claim ${b.amount.display} exceeds the coverage limit ${pb.coverage_limit.display}`);
356
+ }
357
+ const incidents = b.incidents ?? [];
358
+ if (incidents.length === 0) reasons.push('claim cites no incidents');
359
+ for (const [i, inc] of incidents.entries()) {
360
+ const its = Date.parse(inc.ts);
361
+ if (Number.isNaN(its) || its < Date.parse(pb.period.start) || its > Date.parse(pb.period.end)) {
362
+ reasons.push(`incident #${i} at ${inc.ts} is outside the coverage period`);
363
+ }
364
+ if (!pb.covered_scopes.some((s) => scopeCovers(s, inc.target))) {
365
+ reasons.push(`incident #${i} target '${inc.target}' is not within the covered scopes`);
366
+ }
367
+ }
368
+
369
+ const proven: string[] = [];
370
+ const unproven: string[] = [];
371
+ for (const inc of incidents) {
372
+ const ev = evidence[inc.receipt];
373
+ let good = false;
374
+ if (ev && jcsHash(ev.receipt as unknown as Record<string, unknown>) === inc.receipt && verifyReceipt(ev.receipt).ok && verifySTH(ev.sth)) {
375
+ const root = hexToBytes(ev.sth.root.replace('sha256:', ''));
376
+ good = verifyInclusion(
377
+ leafHash(canonicalBytes(ev.receipt as unknown as Record<string, unknown>)),
378
+ ev.index,
379
+ ev.sth.size,
380
+ ev.proof.map((h) => hexToBytes(h)),
381
+ root,
382
+ );
383
+ }
384
+ (good ? proven : unproven).push(inc.receipt);
385
+ }
386
+
387
+ return { ok: reasons.length === 0, reasons, proven, unproven };
388
+ }