@zanii/subject 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,59 @@
1
+ # @zanii/subject
2
+
3
+ **Per-subject auditability.** A platform registers agents with Zanii; its millions of end
4
+ users are the **data subjects** those agents act on. This package gives every end user
5
+ their own key and their own independently verifiable slice of the ledger — *what agents
6
+ did on my account* — without seeing anyone else's.
7
+
8
+ Owner-scoped views can't do this: an end user isn't an agent or an owner, and data
9
+ subjects appear elsewhere only as salted, deliberately unqueryable commitments.
10
+
11
+ **How it works.** The platform stamps a pseudonymous, platform-scoped **`subject_tag`** on
12
+ each receipt (a signature-covered SPEC §3 field). The end user — holding their own
13
+ `did:key` the platform never sees — computes the same tag, pulls their slice from
14
+ `GET /v1/subjects/{tag}`, and verifies every receipt **offline**: signature, delegation
15
+ chain, scope, and tag match. Trust the maths, not the platform.
16
+
17
+ - The same user gets a **different tag on every platform** — no cross-platform linkage.
18
+ - A tag can't be reversed to an identity; receipts about other subjects aren't enumerable.
19
+ - Field-level payload disclosure composes with `@zanii/redact` (the subject sees their
20
+ fields, nothing else — payloads are off-ledger hashes).
21
+
22
+ ```sh
23
+ npm install @zanii/subject @zanii/core
24
+ ```
25
+
26
+ ## Platform side — stamp the tag
27
+
28
+ ```ts
29
+ import { subjectTag } from '@zanii/subject';
30
+
31
+ const tag = subjectTag(endUser.did, 'platform.example.com');
32
+ await agent.record({ target: 'feed.rank', payload, subjectTag: tag }); // SDK ≥0.4.0
33
+ ```
34
+
35
+ ## End-user side — audit your own slice
36
+
37
+ ```ts
38
+ import { subjectIdentity, fetchMyHistory, signSubjectClaim, verifySubjectClaim } from '@zanii/subject';
39
+
40
+ const me = subjectIdentity(); // your key — the platform never holds it
41
+ const history = await fetchMyHistory(me.did, 'platform.example.com');
42
+ history.verified; // every receipt checked offline
43
+ history.receipts.map((r) => r.receipt.target); // what agents did on YOUR account
44
+
45
+ // prove "this is my slice" to an app (sig by your key + the tag derives from your DID):
46
+ const claim = signSubjectClaim({ platform: 'platform.example.com', subjectDid: me.did, ts }, me.privateKey);
47
+ verifySubjectClaim(claim); // true
48
+ ```
49
+
50
+ **Honest limit:** the slice is only as complete as the platform's stamping — a platform
51
+ that omits `subject_tag` hides that receipt from the subject's view (never from the log
52
+ itself). Systematic omission is detectable via reconciliation and consent receipts;
53
+ per-subject auditability is verifiable, not magic.
54
+
55
+ ## Changelog
56
+ - **0.1.0** — initial release: `subjectTag`, `subjectIdentity`, `signSubjectClaim`/`verifySubjectClaim`, `fetchSubjectHistory`/`fetchMyHistory`.
57
+
58
+ ## License
59
+ Apache-2.0.
@@ -0,0 +1,58 @@
1
+ import { type Keypair, type Receipt, type VerifyResult } from '@zanii/core';
2
+ export type FetchLike = (input: string, init?: RequestInit) => Promise<Response>;
3
+ /** The end user's own identity — a plain `did:key` keypair they hold, never the platform. */
4
+ export declare function subjectIdentity(): Keypair;
5
+ /**
6
+ * Pseudonymous, platform-scoped tag for a data subject. Deterministic (RFC 8785), so the
7
+ * subject and the platform compute the same value — and cross-language identical. The same
8
+ * subject gets a different tag on every platform (no cross-platform linkage).
9
+ */
10
+ export declare function subjectTag(subjectDid: string, platformId: string): string;
11
+ export interface SubjectClaim {
12
+ v: 1;
13
+ type: 'subject_claim';
14
+ platform: string;
15
+ subject: string;
16
+ tag: string;
17
+ ts: string;
18
+ sig: string;
19
+ }
20
+ /** Prove "this is my slice": sign a claim with the subject's own key. */
21
+ export declare function signSubjectClaim(fields: {
22
+ platform: string;
23
+ subjectDid: string;
24
+ ts: string;
25
+ }, subjectPrivateKey: Uint8Array): SubjectClaim;
26
+ /** Verify a subject's claim to a tag: valid signature by `subject` AND the tag derives from it. */
27
+ export declare function verifySubjectClaim(claim: SubjectClaim): boolean;
28
+ export interface SubjectReceipt {
29
+ receipt: Receipt;
30
+ hash: string;
31
+ index: number;
32
+ /** Offline verification result for this receipt (signature + delegation + scope). */
33
+ check: VerifyResult;
34
+ }
35
+ export interface SubjectHistory {
36
+ tag: string;
37
+ /** Receipts stamped with this tag, each independently verified offline. */
38
+ receipts: SubjectReceipt[];
39
+ /** true iff every receipt verified AND carried the expected tag. */
40
+ verified: boolean;
41
+ failures: string[];
42
+ sth?: Record<string, unknown>;
43
+ }
44
+ /**
45
+ * Pull + verify the subject's slice. Every receipt is checked **offline** (signature,
46
+ * delegation chain, scope) and must carry the expected `subject_tag` — trust the maths,
47
+ * not the platform. Returns null if the tag has no history (404).
48
+ */
49
+ export declare function fetchSubjectHistory(tag: string, opts?: {
50
+ server?: string;
51
+ fetchImpl?: FetchLike;
52
+ }): Promise<SubjectHistory | null>;
53
+ /** Convenience: compute the tag from the subject's own identity, then fetch + verify. */
54
+ export declare function fetchMyHistory(subjectDid: string, platformId: string, opts?: {
55
+ server?: string;
56
+ fetchImpl?: FetchLike;
57
+ }): Promise<SubjectHistory | null>;
58
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAuBA,OAAO,EAEL,KAAK,OAAO,EAAE,KAAK,OAAO,EAAE,KAAK,YAAY,EAC9C,MAAM,aAAa,CAAC;AAIrB,MAAM,MAAM,SAAS,GAAG,CAAC,KAAK,EAAE,MAAM,EAAE,IAAI,CAAC,EAAE,WAAW,KAAK,OAAO,CAAC,QAAQ,CAAC,CAAC;AAEjF,6FAA6F;AAC7F,wBAAgB,eAAe,IAAI,OAAO,CAEzC;AAED;;;;GAIG;AACH,wBAAgB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AyF;AACzF,wBAAsB,cAAc,CAClC,UAAU,EAAE,MAAM,EAClB,UAAU,EAAE,MAAM,EAClB,IAAI,GAAE;IAAE,MAAM,CAAC,EAAE,MAAM,CAAC;IAAC,SAAS,CAAC,EAAE,SAAS,CAAA;CAAO,GACpD,OAAO,CAAC,cAAc,GAAG,IAAI,CAAC,CAEhC"}
package/dist/index.js ADDED
@@ -0,0 +1,111 @@
1
+ /**
2
+ * @zanii/subject — per-subject auditability: the end user's own slice of the ledger.
3
+ *
4
+ * A platform (the Zanii customer) registers agents; its millions of end users are the
5
+ * **data subjects** those agents act on. Owner-scoped views (`/v1/reputation`, audit
6
+ * bundles) can't serve them: an end user isn't a participant, and subjects appear
7
+ * elsewhere only as salted, unqueryable commitments. This package gives every end user
8
+ * their own key and their own independently verifiable slice — *what agents did on my
9
+ * account* — without seeing anyone else's.
10
+ *
11
+ * How: the platform stamps a **pseudonymous, platform-scoped `subject_tag`** on each
12
+ * receipt (`subjectTag(subjectDid, platformId)` — signature-covered, SPEC §3). The end
13
+ * user, holding their own `did:key`, computes the same tag, pulls their slice from
14
+ * `GET /v1/subjects/{tag}`, and verifies every receipt **offline** (signature +
15
+ * delegation + tag match). Different platforms yield different tags for the same user
16
+ * (no cross-platform linkage); outsiders can't reverse a tag to an identity.
17
+ *
18
+ * Honest limit: the slice is only as complete as the platform's stamping — a platform
19
+ * that omits the tag hides that receipt from the subject's view (though never from the
20
+ * log itself). Verifiable, not magic.
21
+ */
22
+ import { ed25519 } from '@noble/curves/ed25519';
23
+ import { bytesToHex, hexToBytes } from '@noble/hashes/utils';
24
+ import { canonicalBytes, generateKeypair, jcsHash, publicKeyFromDid, verifyReceipt, } from '@zanii/core';
25
+ const DEFAULT_SERVER = 'https://ledger.zanii.agency';
26
+ /** The end user's own identity — a plain `did:key` keypair they hold, never the platform. */
27
+ export function subjectIdentity() {
28
+ return generateKeypair();
29
+ }
30
+ /**
31
+ * Pseudonymous, platform-scoped tag for a data subject. Deterministic (RFC 8785), so the
32
+ * subject and the platform compute the same value — and cross-language identical. The same
33
+ * subject gets a different tag on every platform (no cross-platform linkage).
34
+ */
35
+ export function subjectTag(subjectDid, platformId) {
36
+ if (!subjectDid || !platformId)
37
+ throw new Error('subjectDid and platformId are required');
38
+ return jcsHash({ v: 1, type: 'subject_tag', platform: platformId, subject: subjectDid });
39
+ }
40
+ /** Prove "this is my slice": sign a claim with the subject's own key. */
41
+ export function signSubjectClaim(fields, subjectPrivateKey) {
42
+ if (Number.isNaN(Date.parse(fields.ts)))
43
+ throw new Error('ts must be an ISO timestamp');
44
+ const unsigned = {
45
+ v: 1,
46
+ type: 'subject_claim',
47
+ platform: fields.platform,
48
+ subject: fields.subjectDid,
49
+ tag: subjectTag(fields.subjectDid, fields.platform),
50
+ ts: fields.ts,
51
+ };
52
+ const sig = ed25519.sign(canonicalBytes(unsigned), subjectPrivateKey);
53
+ return { ...unsigned, sig: `ed25519:${bytesToHex(sig)}` };
54
+ }
55
+ /** Verify a subject's claim to a tag: valid signature by `subject` AND the tag derives from it. */
56
+ export function verifySubjectClaim(claim) {
57
+ if (claim?.v !== 1 || claim.type !== 'subject_claim')
58
+ return false;
59
+ if (typeof claim.sig !== 'string' || !claim.sig.startsWith('ed25519:'))
60
+ return false;
61
+ const hex = claim.sig.slice('ed25519:'.length);
62
+ if (!/^[0-9a-f]{128}$/.test(hex))
63
+ return false;
64
+ try {
65
+ if (subjectTag(claim.subject, claim.platform) !== claim.tag)
66
+ return false;
67
+ }
68
+ catch {
69
+ return false;
70
+ }
71
+ const pub = publicKeyFromDid(claim.subject);
72
+ if (!pub)
73
+ return false;
74
+ const { sig: _omitted, ...unsigned } = claim;
75
+ try {
76
+ return ed25519.verify(hexToBytes(hex), canonicalBytes(unsigned), pub);
77
+ }
78
+ catch {
79
+ return false;
80
+ }
81
+ }
82
+ /**
83
+ * Pull + verify the subject's slice. Every receipt is checked **offline** (signature,
84
+ * delegation chain, scope) and must carry the expected `subject_tag` — trust the maths,
85
+ * not the platform. Returns null if the tag has no history (404).
86
+ */
87
+ export async function fetchSubjectHistory(tag, opts = {}) {
88
+ const server = (opts.server ?? DEFAULT_SERVER).replace(/\/$/, '');
89
+ const fetchImpl = opts.fetchImpl ?? ((u, i) => fetch(u, i));
90
+ const res = await fetchImpl(`${server}/v1/subjects/${encodeURIComponent(tag)}`);
91
+ if (res.status === 404)
92
+ return null;
93
+ if (!res.ok)
94
+ throw new Error(`subject lookup failed: HTTP ${res.status}`);
95
+ const body = (await res.json());
96
+ const failures = [];
97
+ const receipts = (body.receipts ?? []).map((r) => {
98
+ const check = verifyReceipt(r.receipt);
99
+ if (!check.ok)
100
+ failures.push(`${r.hash}: ${check.error}`);
101
+ if (r.receipt.subject_tag !== tag)
102
+ failures.push(`${r.hash}: subject_tag does not match requested tag`);
103
+ return { ...r, check };
104
+ });
105
+ return { tag, receipts, verified: failures.length === 0, failures, sth: body.sth };
106
+ }
107
+ /** Convenience: compute the tag from the subject's own identity, then fetch + verify. */
108
+ export async function fetchMyHistory(subjectDid, platformId, opts = {}) {
109
+ return fetchSubjectHistory(subjectTag(subjectDid, platformId), opts);
110
+ }
111
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;GAoBG;AACH,OAAO,EAAE,OAAO,EAAE,MAAM,uBAAuB,CAAC;AAChD,OAAO,EAAE,UAAU,EAAE,UAAU,EAAE,MAAM,qBAAqB,CAAC;AAC7D,OAAO,EACL,cAAc,EAAE,eAAe,EAAE,OAAO,EAAE,gBAAgB,EAAE,aAAa,GAE1E,MAAM,aAAa,CAAC;AAErB,MAAM,cAAc,GAAG,6BAA6B,CAAC;AAIrD,6FAA6F;AAC7F,MAAM,UAAU,eAAe;IAC7B,OAAO,eAAe,EAAE,CAAC;AAC3B,CAAC;AAED;;;;GAIG;AACH,MAAM,UAAU,UAAU,CAAC,UAAkB,EAAE,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subject",
3
+ "version": "0.1.0",
4
+ "description": "Per-subject auditability: end users hold their own key and independently verify what agents did on their account — a pseudonymous, platform-scoped subject_tag receipt slice — without seeing anyone else's.",
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
+ },
38
+ "scripts": {
39
+ "build": "tsc -p tsconfig.build.json",
40
+ "test": "vitest run",
41
+ "typecheck": "tsc --noEmit"
42
+ }
43
+ }
package/src/index.ts ADDED
@@ -0,0 +1,147 @@
1
+ /**
2
+ * @zanii/subject — per-subject auditability: the end user's own slice of the ledger.
3
+ *
4
+ * A platform (the Zanii customer) registers agents; its millions of end users are the
5
+ * **data subjects** those agents act on. Owner-scoped views (`/v1/reputation`, audit
6
+ * bundles) can't serve them: an end user isn't a participant, and subjects appear
7
+ * elsewhere only as salted, unqueryable commitments. This package gives every end user
8
+ * their own key and their own independently verifiable slice — *what agents did on my
9
+ * account* — without seeing anyone else's.
10
+ *
11
+ * How: the platform stamps a **pseudonymous, platform-scoped `subject_tag`** on each
12
+ * receipt (`subjectTag(subjectDid, platformId)` — signature-covered, SPEC §3). The end
13
+ * user, holding their own `did:key`, computes the same tag, pulls their slice from
14
+ * `GET /v1/subjects/{tag}`, and verifies every receipt **offline** (signature +
15
+ * delegation + tag match). Different platforms yield different tags for the same user
16
+ * (no cross-platform linkage); outsiders can't reverse a tag to an identity.
17
+ *
18
+ * Honest limit: the slice is only as complete as the platform's stamping — a platform
19
+ * that omits the tag hides that receipt from the subject's view (though never from the
20
+ * log itself). Verifiable, not magic.
21
+ */
22
+ import { ed25519 } from '@noble/curves/ed25519';
23
+ import { bytesToHex, hexToBytes } from '@noble/hashes/utils';
24
+ import {
25
+ canonicalBytes, generateKeypair, jcsHash, publicKeyFromDid, verifyReceipt,
26
+ type Keypair, type Receipt, type VerifyResult,
27
+ } from '@zanii/core';
28
+
29
+ const DEFAULT_SERVER = 'https://ledger.zanii.agency';
30
+
31
+ export type FetchLike = (input: string, init?: RequestInit) => Promise<Response>;
32
+
33
+ /** The end user's own identity — a plain `did:key` keypair they hold, never the platform. */
34
+ export function subjectIdentity(): Keypair {
35
+ return generateKeypair();
36
+ }
37
+
38
+ /**
39
+ * Pseudonymous, platform-scoped tag for a data subject. Deterministic (RFC 8785), so the
40
+ * subject and the platform compute the same value — and cross-language identical. The same
41
+ * subject gets a different tag on every platform (no cross-platform linkage).
42
+ */
43
+ export function subjectTag(subjectDid: string, platformId: string): string {
44
+ if (!subjectDid || !platformId) throw new Error('subjectDid and platformId are required');
45
+ return jcsHash({ v: 1, type: 'subject_tag', platform: platformId, subject: subjectDid });
46
+ }
47
+
48
+ export interface SubjectClaim {
49
+ v: 1;
50
+ type: 'subject_claim';
51
+ platform: string;
52
+ subject: string;
53
+ tag: string;
54
+ ts: string;
55
+ sig: string;
56
+ }
57
+
58
+ /** Prove "this is my slice": sign a claim with the subject's own key. */
59
+ export function signSubjectClaim(
60
+ fields: { platform: string; subjectDid: string; ts: string },
61
+ subjectPrivateKey: Uint8Array,
62
+ ): SubjectClaim {
63
+ if (Number.isNaN(Date.parse(fields.ts))) throw new Error('ts must be an ISO timestamp');
64
+ const unsigned = {
65
+ v: 1 as const,
66
+ type: 'subject_claim' as const,
67
+ platform: fields.platform,
68
+ subject: fields.subjectDid,
69
+ tag: subjectTag(fields.subjectDid, fields.platform),
70
+ ts: fields.ts,
71
+ };
72
+ const sig = ed25519.sign(canonicalBytes(unsigned), subjectPrivateKey);
73
+ return { ...unsigned, sig: `ed25519:${bytesToHex(sig)}` };
74
+ }
75
+
76
+ /** Verify a subject's claim to a tag: valid signature by `subject` AND the tag derives from it. */
77
+ export function verifySubjectClaim(claim: SubjectClaim): boolean {
78
+ if (claim?.v !== 1 || claim.type !== 'subject_claim') return false;
79
+ if (typeof claim.sig !== 'string' || !claim.sig.startsWith('ed25519:')) return false;
80
+ const hex = claim.sig.slice('ed25519:'.length);
81
+ if (!/^[0-9a-f]{128}$/.test(hex)) return false;
82
+ try {
83
+ if (subjectTag(claim.subject, claim.platform) !== claim.tag) return false;
84
+ } catch {
85
+ return false;
86
+ }
87
+ const pub = publicKeyFromDid(claim.subject);
88
+ if (!pub) return false;
89
+ const { sig: _omitted, ...unsigned } = claim;
90
+ try {
91
+ return ed25519.verify(hexToBytes(hex), canonicalBytes(unsigned), pub);
92
+ } catch {
93
+ return false;
94
+ }
95
+ }
96
+
97
+ export interface SubjectReceipt {
98
+ receipt: Receipt;
99
+ hash: string;
100
+ index: number;
101
+ /** Offline verification result for this receipt (signature + delegation + scope). */
102
+ check: VerifyResult;
103
+ }
104
+
105
+ export interface SubjectHistory {
106
+ tag: string;
107
+ /** Receipts stamped with this tag, each independently verified offline. */
108
+ receipts: SubjectReceipt[];
109
+ /** true iff every receipt verified AND carried the expected tag. */
110
+ verified: boolean;
111
+ failures: string[];
112
+ sth?: Record<string, unknown>;
113
+ }
114
+
115
+ /**
116
+ * Pull + verify the subject's slice. Every receipt is checked **offline** (signature,
117
+ * delegation chain, scope) and must carry the expected `subject_tag` — trust the maths,
118
+ * not the platform. Returns null if the tag has no history (404).
119
+ */
120
+ export async function fetchSubjectHistory(
121
+ tag: string,
122
+ opts: { server?: string; fetchImpl?: FetchLike } = {},
123
+ ): Promise<SubjectHistory | null> {
124
+ const server = (opts.server ?? DEFAULT_SERVER).replace(/\/$/, '');
125
+ const fetchImpl = opts.fetchImpl ?? ((u: string, i?: RequestInit) => fetch(u, i));
126
+ const res = await fetchImpl(`${server}/v1/subjects/${encodeURIComponent(tag)}`);
127
+ if (res.status === 404) return null;
128
+ if (!res.ok) throw new Error(`subject lookup failed: HTTP ${res.status}`);
129
+ const body = (await res.json()) as { receipts?: Array<{ receipt: Receipt; hash: string; index: number }>; sth?: Record<string, unknown> };
130
+ const failures: string[] = [];
131
+ const receipts: SubjectReceipt[] = (body.receipts ?? []).map((r) => {
132
+ const check = verifyReceipt(r.receipt);
133
+ if (!check.ok) failures.push(`${r.hash}: ${check.error}`);
134
+ if (r.receipt.subject_tag !== tag) failures.push(`${r.hash}: subject_tag does not match requested tag`);
135
+ return { ...r, check };
136
+ });
137
+ return { tag, receipts, verified: failures.length === 0, failures, sth: body.sth };
138
+ }
139
+
140
+ /** Convenience: compute the tag from the subject's own identity, then fetch + verify. */
141
+ export async function fetchMyHistory(
142
+ subjectDid: string,
143
+ platformId: string,
144
+ opts: { server?: string; fetchImpl?: FetchLike } = {},
145
+ ): Promise<SubjectHistory | null> {
146
+ return fetchSubjectHistory(subjectTag(subjectDid, platformId), opts);
147
+ }