@fleetmesh/leaf 0.0.0-stage → 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/README.md +103 -2
- package/dist/constants.d.ts +27 -0
- package/dist/constants.js +32 -0
- package/dist/descriptor.d.ts +29 -0
- package/dist/descriptor.js +73 -0
- package/dist/did.d.ts +59 -0
- package/dist/did.js +221 -0
- package/dist/didcomm.d.ts +59 -0
- package/dist/didcomm.js +176 -0
- package/dist/encoding.d.ts +14 -0
- package/dist/encoding.js +68 -0
- package/dist/event.d.ts +22 -0
- package/dist/event.js +42 -0
- package/dist/giftwrap.d.ts +29 -0
- package/dist/giftwrap.js +100 -0
- package/dist/index.d.ts +17 -0
- package/dist/index.js +20 -0
- package/dist/keys.d.ts +6 -0
- package/dist/keys.js +31 -0
- package/dist/mediation/leaf.d.ts +121 -0
- package/dist/mediation/leaf.js +238 -0
- package/dist/mediation/messages.d.ts +96 -0
- package/dist/mediation/messages.js +79 -0
- package/dist/negentropy.d.ts +81 -0
- package/dist/negentropy.js +352 -0
- package/dist/nip44.d.ts +18 -0
- package/dist/nip44.js +119 -0
- package/dist/pwa/browser-leaf.d.ts +15 -0
- package/dist/pwa/browser-leaf.js +91 -0
- package/dist/pwa/hub.d.ts +51 -0
- package/dist/pwa/hub.js +137 -0
- package/dist/pwa/store.d.ts +39 -0
- package/dist/pwa/store.js +157 -0
- package/dist/relay.d.ts +67 -0
- package/dist/relay.js +232 -0
- package/dist/seal.d.ts +56 -0
- package/dist/seal.js +146 -0
- package/dist/session.d.ts +75 -0
- package/dist/session.js +230 -0
- package/package.json +45 -4
- package/src/constants.ts +36 -0
- package/src/descriptor.ts +88 -0
- package/src/did.ts +222 -0
- package/src/didcomm.ts +196 -0
- package/src/encoding.ts +67 -0
- package/src/event.ts +56 -0
- package/src/giftwrap.ts +108 -0
- package/src/index.ts +20 -0
- package/src/keys.ts +33 -0
- package/src/mediation/leaf.ts +292 -0
- package/src/mediation/messages.ts +124 -0
- package/src/negentropy.ts +357 -0
- package/src/nip44.ts +110 -0
- package/src/pwa/browser-leaf.ts +99 -0
- package/src/pwa/hub.ts +173 -0
- package/src/pwa/store.ts +173 -0
- package/src/relay.ts +273 -0
- package/src/seal.ts +154 -0
- package/src/session.ts +255 -0
package/src/did.ts
ADDED
|
@@ -0,0 +1,222 @@
|
|
|
1
|
+
// DIDs: did:nostr is the identity; did:key and did:peer are derived views of
|
|
2
|
+
// it (core fleetmesh_core/identity/did.py, constants.json#did, profile
|
|
3
|
+
// did-aliases). Neither adds a key, a curve or a trust root.
|
|
4
|
+
//
|
|
5
|
+
// did:key did:key:z<base58btc(multicodec || raw key)>; one per key kind.
|
|
6
|
+
// The node key is secp256k1-pub over the COMPRESSED point
|
|
7
|
+
// (02 || x, even y as BIP-340 implies).
|
|
8
|
+
// did:peer numalgo 2: V = the node key, E = the agreement key, S = the
|
|
9
|
+
// DIDCommMessaging service, abbreviated, base64url-nopad
|
|
10
|
+
// canonical JSON. A snapshot of the descriptor, never the truth.
|
|
11
|
+
import { schnorr } from '@noble/curves/secp256k1.js';
|
|
12
|
+
import { base58 } from '@scure/base';
|
|
13
|
+
import { DESCRIPTOR, DID } from './constants.ts';
|
|
14
|
+
import { b64u, b64uDec, bytesToHex, canonicalJson, fromUtf8, hexToBytes, isHex, utf8 } from './encoding.ts';
|
|
15
|
+
import { type KeyKind, KEY_KINDS, multikey, parseMultikey } from './keys.ts';
|
|
16
|
+
|
|
17
|
+
export interface ServiceEndpoint { uri?: string; accept?: string[]; routingKeys?: string[] }
|
|
18
|
+
export interface Service { id?: string; type?: string; serviceEndpoint?: ServiceEndpoint | string }
|
|
19
|
+
export interface PeerParts { node: string | null; agreement: string | null; service: Service | null }
|
|
20
|
+
export interface Parsed { method: 'nostr' | 'key' | 'peer'; kind?: KeyKind; node: string | null }
|
|
21
|
+
export interface VerificationMethod { id: string; type: 'Multikey'; controller: string; publicKeyMultibase: string }
|
|
22
|
+
export interface Document {
|
|
23
|
+
'@context': string[];
|
|
24
|
+
id: string;
|
|
25
|
+
alsoKnownAs: string[];
|
|
26
|
+
verificationMethod: VerificationMethod[];
|
|
27
|
+
authentication: string[];
|
|
28
|
+
assertionMethod: string[];
|
|
29
|
+
keyAgreement: string[];
|
|
30
|
+
service: Service[];
|
|
31
|
+
}
|
|
32
|
+
/** A kind 11801 descriptor, as far as this module reads it. */
|
|
33
|
+
export interface Descriptor { pubkey: string; tags: string[][] }
|
|
34
|
+
|
|
35
|
+
const CODEC: Record<KeyKind, Uint8Array> = {
|
|
36
|
+
node: hexToBytes(DID.multicodec.node),
|
|
37
|
+
agreement: hexToBytes(DID.multicodec.agreement),
|
|
38
|
+
transport: hexToBytes(DID.multicodec.transport),
|
|
39
|
+
};
|
|
40
|
+
const ABBREV = DID.peer.service_abbreviations;
|
|
41
|
+
const UNABBREV: Record<string, string> = Object.fromEntries(Object.entries(ABBREV).map(([k, v]) => [v, k]));
|
|
42
|
+
|
|
43
|
+
const startsWith = (b: Uint8Array, p: Uint8Array) => b.length >= p.length && p.every((x, i) => b[i] === x);
|
|
44
|
+
|
|
45
|
+
/** 02 || x: the even-y point BIP-340 x-only keys stand for. */
|
|
46
|
+
export function compressedNodeKey(xOnlyHex: string): Uint8Array {
|
|
47
|
+
if (!isHex(xOnlyHex, 64, true)) throw new Error('a public key is 32 bytes of hex');
|
|
48
|
+
try {
|
|
49
|
+
schnorr.utils.lift_x(BigInt('0x' + xOnlyHex));
|
|
50
|
+
} catch {
|
|
51
|
+
throw new Error('not an x-only secp256k1 public key');
|
|
52
|
+
}
|
|
53
|
+
const out = new Uint8Array(33);
|
|
54
|
+
out[0] = 0x02;
|
|
55
|
+
out.set(hexToBytes(xOnlyHex.toLowerCase()), 1);
|
|
56
|
+
return out;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
export function didKey(kind: KeyKind, raw: Uint8Array): string {
|
|
60
|
+
if (!KEY_KINDS.includes(kind)) throw new Error('did:key kinds are agreement, node, transport');
|
|
61
|
+
const want = kind === 'node' ? 33 : 32;
|
|
62
|
+
if (raw.length !== want) throw new Error(`${kind} key is ${want} bytes`);
|
|
63
|
+
const body = new Uint8Array(CODEC[kind].length + raw.length);
|
|
64
|
+
body.set(CODEC[kind]);
|
|
65
|
+
body.set(raw, CODEC[kind].length);
|
|
66
|
+
return 'did:key:z' + base58.encode(body);
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/** [kind, raw bytes] of a did:key this profile emits; refuses other codecs. */
|
|
70
|
+
export function parseDidKey(did: string): [KeyKind, Uint8Array] {
|
|
71
|
+
if (!did.startsWith('did:key:z')) throw new Error('did:key is base58btc (z) here');
|
|
72
|
+
let body: Uint8Array;
|
|
73
|
+
try {
|
|
74
|
+
body = base58.decode(did.slice('did:key:z'.length));
|
|
75
|
+
} catch {
|
|
76
|
+
throw new Error('not base58btc');
|
|
77
|
+
}
|
|
78
|
+
for (const kind of KEY_KINDS) {
|
|
79
|
+
const codec = CODEC[kind];
|
|
80
|
+
if (!startsWith(body, codec)) continue;
|
|
81
|
+
const raw = body.slice(codec.length);
|
|
82
|
+
if (raw.length !== (kind === 'node' ? 33 : 32)) throw new Error(`${kind} did:key has the wrong length`);
|
|
83
|
+
if (kind === 'node' && raw[0] !== 0x02) throw new Error('node did:key must be the even-y compressed point');
|
|
84
|
+
return [kind, raw];
|
|
85
|
+
}
|
|
86
|
+
throw new Error('a different curve is a different network: codec ' + bytesToHex(body.slice(0, 2)));
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
export const nodeDidKey = (xOnlyHex: string): string => didKey('node', compressedNodeKey(xOnlyHex));
|
|
90
|
+
|
|
91
|
+
// One value of a did:peer:2 service, abbreviated or expanded. `id` is dropped
|
|
92
|
+
// only at the top level - the one did:peer:2 assigns - never from a nested
|
|
93
|
+
// object, which is somebody else's id.
|
|
94
|
+
function abbrValue(v: unknown, table: Record<string, string>, dropId: boolean): unknown {
|
|
95
|
+
if (typeof v === 'string') return table[v] ?? v;
|
|
96
|
+
if (Array.isArray(v)) return v.map((x) => abbrValue(x, table, false));
|
|
97
|
+
if (v && typeof v === 'object') {
|
|
98
|
+
const out: Record<string, unknown> = {};
|
|
99
|
+
for (const [k, vv] of Object.entries(v)) {
|
|
100
|
+
if (dropId && k === 'id') continue;
|
|
101
|
+
out[table[k] ?? k] = abbrValue(vv, table, false);
|
|
102
|
+
}
|
|
103
|
+
return out;
|
|
104
|
+
}
|
|
105
|
+
return v;
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/** did:peer:2 of a node: V = the node key, E = the agreement key, S = the DIDComm service. */
|
|
109
|
+
export function didPeer(nodePkHex: string, agreementRaw: Uint8Array | null, service: Service | null): string {
|
|
110
|
+
let out = 'did:peer:2.V' + nodeDidKey(nodePkHex).slice('did:key:'.length);
|
|
111
|
+
if (agreementRaw !== null) out += '.E' + didKey('agreement', agreementRaw).slice('did:key:'.length);
|
|
112
|
+
if (service !== null) out += '.S' + b64u(utf8(canonicalJson(abbrValue(service, ABBREV, true))));
|
|
113
|
+
return out;
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
export function parseDidPeer(did: string): PeerParts {
|
|
117
|
+
if (!did.startsWith('did:peer:2.')) throw new Error('only did:peer numalgo 2 is spoken here');
|
|
118
|
+
const out: PeerParts = { node: null, agreement: null, service: null };
|
|
119
|
+
for (const el of did.slice('did:peer:2.'.length).split('.')) {
|
|
120
|
+
if (!el) throw new Error('empty did:peer:2 element');
|
|
121
|
+
const purpose = el[0], body = el.slice(1);
|
|
122
|
+
if (purpose === 'V') {
|
|
123
|
+
const [kind, raw] = parseDidKey('did:key:' + body);
|
|
124
|
+
if (kind !== 'node') throw new Error('V must be the node key');
|
|
125
|
+
out.node = bytesToHex(raw.slice(1));
|
|
126
|
+
} else if (purpose === 'E') {
|
|
127
|
+
const [kind, raw] = parseDidKey('did:key:' + body);
|
|
128
|
+
if (kind !== 'agreement') throw new Error('E must be the agreement key');
|
|
129
|
+
out.agreement = bytesToHex(raw);
|
|
130
|
+
} else if (purpose === 'S') {
|
|
131
|
+
let doc: unknown;
|
|
132
|
+
try {
|
|
133
|
+
doc = JSON.parse(fromUtf8(b64uDec(body)));
|
|
134
|
+
} catch (e) {
|
|
135
|
+
throw new Error('S element is not JSON: ' + (e as Error).message);
|
|
136
|
+
}
|
|
137
|
+
if (!doc || typeof doc !== 'object' || Array.isArray(doc)) throw new Error('S element must be a JSON object');
|
|
138
|
+
out.service = { ...(abbrValue(doc, UNABBREV, false) as Service), id: '#didcomm' };
|
|
139
|
+
} else {
|
|
140
|
+
throw new Error('unknown did:peer:2 purpose ' + JSON.stringify(purpose));
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
if (out.node === null) throw new Error('did:peer:2 without a V element names no node');
|
|
144
|
+
return out;
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
/** {method, node} for any DID this profile speaks; node is the x-only hex when it names one. */
|
|
148
|
+
export function parse(did: string): Parsed {
|
|
149
|
+
if (did.startsWith('did:nostr:')) {
|
|
150
|
+
const pk = did.slice('did:nostr:'.length);
|
|
151
|
+
compressedNodeKey(pk);
|
|
152
|
+
return { method: 'nostr', node: pk };
|
|
153
|
+
}
|
|
154
|
+
if (did.startsWith('did:key:')) {
|
|
155
|
+
const [kind, raw] = parseDidKey(did);
|
|
156
|
+
return { method: 'key', kind, node: kind === 'node' ? bytesToHex(raw.slice(1)) : null };
|
|
157
|
+
}
|
|
158
|
+
if (did.startsWith('did:peer:')) return { method: 'peer', node: parseDidPeer(did).node };
|
|
159
|
+
throw new Error('did methods here are nostr, key and peer');
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
export const didNostr = (pubkey: string): string => 'did:nostr:' + pubkey.toLowerCase();
|
|
163
|
+
|
|
164
|
+
/** The 64-hex node pubkey a did:nostr, did:key or did:peer (or a kid of one) names. */
|
|
165
|
+
export function nodeOfDid(didOrKid: string): string {
|
|
166
|
+
const body = didOrKid.split('#', 1)[0]!;
|
|
167
|
+
if (body.startsWith('did:nostr:')) {
|
|
168
|
+
const pk = body.slice('did:nostr:'.length).toLowerCase();
|
|
169
|
+
if (isHex(pk, 64)) return pk;
|
|
170
|
+
}
|
|
171
|
+
const node = parse(body).node;
|
|
172
|
+
if (!node) throw new Error(`DID ${JSON.stringify(didOrKid)} names no node pubkey`);
|
|
173
|
+
return node;
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
const tagsNamed = (desc: Descriptor, name: string) => desc.tags.filter((t) => t.length && t[0] === name);
|
|
177
|
+
const byPriority = (a: string[], b: string[]) => (a.length > 3 ? +a[3]! : 50) - (b.length > 3 ? +b[3]! : 50);
|
|
178
|
+
|
|
179
|
+
export function didcommService(desc: Descriptor): Service | null {
|
|
180
|
+
const wss = tagsNamed(desc, 'endpoint').sort(byPriority).filter((e) => e[1] === 'wss' || e[1] === 'https');
|
|
181
|
+
if (!wss.length) return null;
|
|
182
|
+
const se: ServiceEndpoint = { uri: wss[0]![2]!, accept: ['didcomm/v2'] };
|
|
183
|
+
const med = tagsNamed(desc, 'mediator');
|
|
184
|
+
if (med.length) se.routingKeys = [med[0]![1] + '#agree'];
|
|
185
|
+
return { id: '#didcomm', type: 'DIDCommMessaging', serviceEndpoint: se };
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
/** The node profile a did:nostr resolver emits for a kind 11801, with its aliases. */
|
|
189
|
+
export function document(desc: Descriptor): Document {
|
|
190
|
+
const did = 'did:nostr:' + desc.pubkey;
|
|
191
|
+
const vm: VerificationMethod[] = [
|
|
192
|
+
{ id: '#nostr', type: 'Multikey', controller: did, publicKeyMultibase: multikey('node', hexToBytes(desc.pubkey)) },
|
|
193
|
+
];
|
|
194
|
+
let agreementName: string | null = null;
|
|
195
|
+
let agreementRaw: Uint8Array | null = null;
|
|
196
|
+
for (const k of tagsNamed(desc, 'key')) {
|
|
197
|
+
const name = ({ agreement: '#agree', transport: '#wire' } as Record<string, string>)[k[1]!];
|
|
198
|
+
if (!name) throw new Error('unknown key tag ' + JSON.stringify(k[1]));
|
|
199
|
+
vm.push({ id: name, type: 'Multikey', controller: did, publicKeyMultibase: k[2]! });
|
|
200
|
+
if (k[1] === 'agreement') {
|
|
201
|
+
agreementName = name;
|
|
202
|
+
agreementRaw = parseMultikey(k[2]!)[1];
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
const service = didcommService(desc);
|
|
206
|
+
const services: Service[] = service ? [service] : [];
|
|
207
|
+
const caps = new Set(tagsNamed(desc, 'c').map((t) => t[1]));
|
|
208
|
+
for (const e of tagsNamed(desc, 'endpoint').sort(byPriority)) {
|
|
209
|
+
if (e[1] === 'wss' && caps.has('relay')) services.push({ id: '#relay', type: 'NostrRelay', serviceEndpoint: e[2]! });
|
|
210
|
+
else if (e[1] === 'iroh') services.push({ id: '#iroh', type: 'IrohNode', serviceEndpoint: e[2]! });
|
|
211
|
+
}
|
|
212
|
+
return {
|
|
213
|
+
'@context': [...DESCRIPTOR.did_contexts],
|
|
214
|
+
id: did,
|
|
215
|
+
alsoKnownAs: [nodeDidKey(desc.pubkey), didPeer(desc.pubkey, agreementRaw, service)],
|
|
216
|
+
verificationMethod: vm,
|
|
217
|
+
authentication: ['#nostr'],
|
|
218
|
+
assertionMethod: ['#nostr'],
|
|
219
|
+
keyAgreement: agreementName ? [agreementName] : [],
|
|
220
|
+
service: services,
|
|
221
|
+
};
|
|
222
|
+
}
|
package/src/didcomm.ts
ADDED
|
@@ -0,0 +1,196 @@
|
|
|
1
|
+
// DIDComm v2 encrypted envelopes (core fleetmesh_core/identity/didcomm.py):
|
|
2
|
+
//
|
|
3
|
+
// authcrypt alg ECDH-1PU+A256KW, enc A256CBC-HS512. The sender's static
|
|
4
|
+
// key is in the agreement, so the recipient knows who wrote it.
|
|
5
|
+
// Every message after first contact.
|
|
6
|
+
// anoncrypt alg ECDH-ES+A256KW, enc A256CBC-HS512. First contact only.
|
|
7
|
+
//
|
|
8
|
+
// JWE JSON serialisation, general form, one or more recipients, all over
|
|
9
|
+
// X25519. The Concat KDF is NIST SP 800-56A one-step with SHA-256 as RFC 7518
|
|
10
|
+
// uses it; ECDH-1PU adds the sender's static agreement to Z and, in
|
|
11
|
+
// key-wrapping mode, the content tag to the KDF input so a recipient cannot
|
|
12
|
+
// re-target the message.
|
|
13
|
+
import { aeskw, cbc } from '@noble/ciphers/aes.js';
|
|
14
|
+
import { x25519 } from '@noble/curves/ed25519.js';
|
|
15
|
+
import { concatBytes, equalBytes, randomBytes } from '@noble/curves/utils.js';
|
|
16
|
+
import { hmac } from '@noble/hashes/hmac.js';
|
|
17
|
+
import { sha256, sha512 } from '@noble/hashes/sha2.js';
|
|
18
|
+
import { b64u, b64uDec, canonicalJson, fromUtf8, utf8 } from './encoding.ts';
|
|
19
|
+
|
|
20
|
+
export const TYP = 'application/didcomm-encrypted+json';
|
|
21
|
+
export const ENC = 'A256CBC-HS512';
|
|
22
|
+
export const AUTHCRYPT = 'ECDH-1PU+A256KW';
|
|
23
|
+
export const ANONCRYPT = 'ECDH-ES+A256KW';
|
|
24
|
+
const KEK_BITS: Record<string, number> = { A128KW: 128, A192KW: 192, A256KW: 256 };
|
|
25
|
+
|
|
26
|
+
export interface JWERecipient { header: { kid: string }; encrypted_key: string }
|
|
27
|
+
export interface JWE { protected: string; recipients: JWERecipient[]; iv: string; ciphertext: string; tag: string }
|
|
28
|
+
export interface ProtectedHeader {
|
|
29
|
+
alg: string;
|
|
30
|
+
enc: string;
|
|
31
|
+
typ?: string;
|
|
32
|
+
apv?: string;
|
|
33
|
+
apu?: string;
|
|
34
|
+
skid?: string;
|
|
35
|
+
epk?: { kty?: string; crv?: string; x?: string };
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export class EnvelopeError extends Error {}
|
|
39
|
+
|
|
40
|
+
const u32 = (n: number) => Uint8Array.of(n >>> 24, (n >>> 16) & 0xff, (n >>> 8) & 0xff, n & 0xff);
|
|
41
|
+
const len32 = (b: Uint8Array) => concatBytes(u32(b.length), b);
|
|
42
|
+
|
|
43
|
+
/** X25519 agreement; refuses the all-zero secret a low-order point yields. */
|
|
44
|
+
export function x25519Shared(priv: Uint8Array, theirPub: Uint8Array): Uint8Array {
|
|
45
|
+
let z: Uint8Array;
|
|
46
|
+
try {
|
|
47
|
+
z = x25519.getSharedSecret(priv, theirPub);
|
|
48
|
+
} catch (e) {
|
|
49
|
+
throw new EnvelopeError('X25519 agreement failed: ' + (e as Error).message);
|
|
50
|
+
}
|
|
51
|
+
if (z.every((b) => b === 0)) throw new EnvelopeError('X25519 agreement is all zero');
|
|
52
|
+
return z;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
export const agreementPublic = (priv: Uint8Array): Uint8Array => x25519.getPublicKey(priv);
|
|
56
|
+
|
|
57
|
+
/** NIST SP 800-56A one-step KDF, SHA-256, one round (every key here is <= 256 bits). */
|
|
58
|
+
export function concatKdf(z: Uint8Array, alg: string, apu: Uint8Array, apv: Uint8Array, keydatalenBits: number,
|
|
59
|
+
cctag?: Uint8Array): Uint8Array {
|
|
60
|
+
const suppPub = concatBytes(u32(keydatalenBits), cctag ? len32(cctag) : new Uint8Array(0));
|
|
61
|
+
const fixed = concatBytes(len32(utf8(alg)), len32(apu), len32(apv), suppPub);
|
|
62
|
+
return sha256(concatBytes(u32(1), z, fixed)).slice(0, keydatalenBits / 8);
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
function macOf(macKey: Uint8Array, aad: Uint8Array, iv: Uint8Array, ct: Uint8Array): Uint8Array {
|
|
66
|
+
const al = new Uint8Array(8);
|
|
67
|
+
new DataView(al.buffer).setBigUint64(0, BigInt(aad.length) * 8n);
|
|
68
|
+
return hmac(sha512, macKey, concatBytes(aad, iv, ct, al)).slice(0, 32);
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/** RFC 7518 5.2.5. The CEK is 64 bytes: MAC key first, then the AES key. */
|
|
72
|
+
export function cbcHs512Encrypt(cek: Uint8Array, iv: Uint8Array, plaintext: Uint8Array, aad: Uint8Array): [Uint8Array, Uint8Array] {
|
|
73
|
+
if (cek.length !== 64 || iv.length !== 16) throw new EnvelopeError('A256CBC-HS512 needs a 64-byte CEK and a 16-byte IV');
|
|
74
|
+
const ct = cbc(cek.subarray(32), iv).encrypt(plaintext);
|
|
75
|
+
return [ct, macOf(cek.subarray(0, 32), aad, iv, ct)];
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
export function cbcHs512Decrypt(cek: Uint8Array, iv: Uint8Array, ct: Uint8Array, tag: Uint8Array, aad: Uint8Array): Uint8Array {
|
|
79
|
+
if (cek.length !== 64 || iv.length !== 16) throw new EnvelopeError('A256CBC-HS512 needs a 64-byte CEK and a 16-byte IV');
|
|
80
|
+
if (!equalBytes(tag, macOf(cek.subarray(0, 32), aad, iv, ct))) throw new EnvelopeError('authentication tag does not verify');
|
|
81
|
+
try {
|
|
82
|
+
return cbc(cek.subarray(32), iv).decrypt(ct);
|
|
83
|
+
} catch (e) {
|
|
84
|
+
throw new EnvelopeError('ciphertext does not decrypt: ' + (e as Error).message);
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
const kekBits = (alg: string) => KEK_BITS[alg.split('+')[1]!]!;
|
|
89
|
+
|
|
90
|
+
/** ECDH-1PU key-wrapping KEK: Z = Ze || Zs, tag in the KDF. */
|
|
91
|
+
export const kek1pu = (alg: string, ze: Uint8Array, zs: Uint8Array, apu: Uint8Array, apv: Uint8Array, tag: Uint8Array) =>
|
|
92
|
+
concatKdf(concatBytes(ze, zs), alg, apu, apv, kekBits(alg), tag);
|
|
93
|
+
|
|
94
|
+
export const kekEs = (alg: string, ze: Uint8Array, apu: Uint8Array, apv: Uint8Array) =>
|
|
95
|
+
concatKdf(ze, alg, apu, apv, kekBits(alg));
|
|
96
|
+
|
|
97
|
+
/** DIDComm v2: SHA-256 of the sorted recipient kids joined by '.'. */
|
|
98
|
+
export const apvFor = (kids: string[]): Uint8Array => sha256(utf8([...kids].sort().join('.')));
|
|
99
|
+
|
|
100
|
+
export interface EncryptOptions {
|
|
101
|
+
/** [skid, X25519 private key] for authcrypt; absent for anoncrypt. */
|
|
102
|
+
sender?: [string, Uint8Array];
|
|
103
|
+
/** For vectors only; a leaf never passes these. */
|
|
104
|
+
ephPriv?: Uint8Array;
|
|
105
|
+
cek?: Uint8Array;
|
|
106
|
+
iv?: Uint8Array;
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/** A JWE for one plaintext message to [kid, X25519 public key] recipients. */
|
|
110
|
+
export function encrypt(message: unknown, recipients: [string, Uint8Array][], opts: EncryptOptions = {}): JWE {
|
|
111
|
+
if (!recipients.length) throw new EnvelopeError('a message needs a recipient');
|
|
112
|
+
const { sender } = opts;
|
|
113
|
+
const body = utf8(canonicalJson(message));
|
|
114
|
+
const ephPriv = opts.ephPriv ?? x25519.utils.randomSecretKey();
|
|
115
|
+
const apv = apvFor(recipients.map(([k]) => k));
|
|
116
|
+
const alg = sender ? AUTHCRYPT : ANONCRYPT;
|
|
117
|
+
const prot: ProtectedHeader = {
|
|
118
|
+
alg, enc: ENC, typ: TYP, apv: b64u(apv),
|
|
119
|
+
epk: { kty: 'OKP', crv: 'X25519', x: b64u(agreementPublic(ephPriv)) },
|
|
120
|
+
};
|
|
121
|
+
let apu: Uint8Array = new Uint8Array(0);
|
|
122
|
+
if (sender) {
|
|
123
|
+
prot.skid = sender[0];
|
|
124
|
+
prot.apu = b64u(utf8(sender[0]));
|
|
125
|
+
apu = utf8(sender[0]);
|
|
126
|
+
}
|
|
127
|
+
const protectedB64 = b64u(utf8(canonicalJson(prot)));
|
|
128
|
+
const cek = opts.cek ?? randomBytes(64);
|
|
129
|
+
const iv = opts.iv ?? randomBytes(16);
|
|
130
|
+
const [ct, tag] = cbcHs512Encrypt(cek, iv, body, utf8(protectedB64));
|
|
131
|
+
const recs = recipients.map(([kid, pub]): JWERecipient => {
|
|
132
|
+
const ze = x25519Shared(ephPriv, pub);
|
|
133
|
+
const kek = sender ? kek1pu(alg, ze, x25519Shared(sender[1], pub), apu, apv, tag) : kekEs(alg, ze, apu, apv);
|
|
134
|
+
return { header: { kid }, encrypted_key: b64u(aeskw(kek).encrypt(cek)) };
|
|
135
|
+
});
|
|
136
|
+
return { protected: protectedB64, recipients: recs, iv: b64u(iv), ciphertext: b64u(ct), tag: b64u(tag) };
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
const dec = (s: unknown, what: string): Uint8Array => {
|
|
140
|
+
if (typeof s !== 'string') throw new EnvelopeError(`${what} is missing`);
|
|
141
|
+
try {
|
|
142
|
+
return b64uDec(s);
|
|
143
|
+
} catch {
|
|
144
|
+
throw new EnvelopeError(`${what} is not base64url`);
|
|
145
|
+
}
|
|
146
|
+
};
|
|
147
|
+
|
|
148
|
+
/** Open a JWE addressed to myKid: [message, skid or null]. For authcrypt,
|
|
149
|
+
* resolveSender(skid) must return the sender's static X25519 public key; the
|
|
150
|
+
* sender is then authenticated by the agreement itself. */
|
|
151
|
+
export function decrypt(jwe: JWE, myKid: string, myPriv: Uint8Array,
|
|
152
|
+
resolveSender?: (skid: string) => Uint8Array | null | undefined): [any, string | null] {
|
|
153
|
+
let prot: ProtectedHeader;
|
|
154
|
+
try {
|
|
155
|
+
prot = JSON.parse(fromUtf8(b64uDec(jwe.protected)));
|
|
156
|
+
} catch {
|
|
157
|
+
throw new EnvelopeError('protected header is not JSON');
|
|
158
|
+
}
|
|
159
|
+
const { alg, enc } = prot;
|
|
160
|
+
if (enc !== ENC || (alg !== AUTHCRYPT && alg !== ANONCRYPT)) throw new EnvelopeError(`unsupported alg/enc ${alg}/${enc}`);
|
|
161
|
+
const rec = (jwe.recipients ?? []).find((r) => r?.header?.kid === myKid);
|
|
162
|
+
if (!rec) throw new EnvelopeError('not addressed to ' + myKid);
|
|
163
|
+
const epk = prot.epk ?? {};
|
|
164
|
+
if (epk.kty !== 'OKP' || epk.crv !== 'X25519') throw new EnvelopeError('epk must be an X25519 OKP key');
|
|
165
|
+
const ephPub = dec(epk.x, 'epk');
|
|
166
|
+
if (ephPub.length !== 32) throw new EnvelopeError('epk is not an X25519 key');
|
|
167
|
+
const apv = prot.apv === undefined ? new Uint8Array(0) : dec(prot.apv, 'apv');
|
|
168
|
+
const apu = prot.apu === undefined ? new Uint8Array(0) : dec(prot.apu, 'apu');
|
|
169
|
+
const tag = dec(jwe.tag, 'tag'), iv = dec(jwe.iv, 'iv'), ct = dec(jwe.ciphertext, 'ciphertext');
|
|
170
|
+
const wrapped = dec(rec.encrypted_key, 'encrypted_key');
|
|
171
|
+
const ze = x25519Shared(myPriv, ephPub);
|
|
172
|
+
let skid: string | null = null;
|
|
173
|
+
let kek: Uint8Array;
|
|
174
|
+
if (alg === AUTHCRYPT) {
|
|
175
|
+
skid = prot.skid ?? null;
|
|
176
|
+
if (!skid || !resolveSender) throw new EnvelopeError('authcrypt needs a skid and a way to resolve it');
|
|
177
|
+
if (!equalBytes(apu, utf8(skid))) throw new EnvelopeError('apu does not name the skid');
|
|
178
|
+
const senderPub = resolveSender(skid);
|
|
179
|
+
if (!senderPub) throw new EnvelopeError('unknown sender ' + skid);
|
|
180
|
+
kek = kek1pu(alg, ze, x25519Shared(myPriv, senderPub), apu, apv, tag);
|
|
181
|
+
} else {
|
|
182
|
+
kek = kekEs(alg, ze, apu, apv);
|
|
183
|
+
}
|
|
184
|
+
let cek: Uint8Array;
|
|
185
|
+
try {
|
|
186
|
+
cek = aeskw(kek).decrypt(wrapped);
|
|
187
|
+
} catch {
|
|
188
|
+
throw new EnvelopeError('key unwrap failed: wrong recipient key or tampered envelope');
|
|
189
|
+
}
|
|
190
|
+
const body = cbcHs512Decrypt(cek, iv, ct, tag, utf8(jwe.protected));
|
|
191
|
+
try {
|
|
192
|
+
return [JSON.parse(fromUtf8(body)), skid];
|
|
193
|
+
} catch {
|
|
194
|
+
throw new EnvelopeError('plaintext is not a JSON message');
|
|
195
|
+
}
|
|
196
|
+
}
|
package/src/encoding.ts
ADDED
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
// Byte and text spellings shared by every module: hex, strict base64url and
|
|
2
|
+
// the canonical JSON the Python reference writes with
|
|
3
|
+
// json.dumps(sort_keys=True, separators=(',', ':'), ensure_ascii=False).
|
|
4
|
+
import { bytesToHex, hexToBytes } from '@noble/hashes/utils.js';
|
|
5
|
+
|
|
6
|
+
export { bytesToHex, hexToBytes };
|
|
7
|
+
|
|
8
|
+
const utf8Enc = new TextEncoder();
|
|
9
|
+
const utf8Dec = new TextDecoder('utf-8', { fatal: true });
|
|
10
|
+
|
|
11
|
+
export const utf8 = (s: string): Uint8Array => utf8Enc.encode(s);
|
|
12
|
+
export const fromUtf8 = (b: Uint8Array): string => utf8Dec.decode(b);
|
|
13
|
+
|
|
14
|
+
/** A string of exactly `length` hex digits; lowercase only unless `upper`. */
|
|
15
|
+
export function isHex(value: unknown, length?: number, upper = false): value is string {
|
|
16
|
+
if (typeof value !== 'string' || !value) return false;
|
|
17
|
+
if (length !== undefined && value.length !== length) return false;
|
|
18
|
+
return (upper ? /^[0-9a-fA-F]+$/ : /^[0-9a-f]+$/).test(value);
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
const B64URL = /^[A-Za-z0-9_-]*$/;
|
|
22
|
+
|
|
23
|
+
export function b64u(b: Uint8Array): string {
|
|
24
|
+
let s = '';
|
|
25
|
+
for (const byte of b) s += String.fromCharCode(byte);
|
|
26
|
+
return btoa(s).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** Strict base64url without padding: the alphabet only, and canonical (no
|
|
30
|
+
* trailing bits), so two strings never decode to the same bytes. */
|
|
31
|
+
export function b64uDec(s: string): Uint8Array {
|
|
32
|
+
if (!B64URL.test(s) || s.length % 4 === 1) throw new Error('not base64url');
|
|
33
|
+
const bin = atob(s.replace(/-/g, '+').replace(/_/g, '/') + '='.repeat((4 - (s.length % 4)) % 4));
|
|
34
|
+
const out = new Uint8Array(bin.length);
|
|
35
|
+
for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i);
|
|
36
|
+
if (b64u(out) !== s) throw new Error('not canonical base64url');
|
|
37
|
+
return out;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
// Python sorts keys by code point; JS's default sort is by UTF-16 unit, which
|
|
41
|
+
// differs above the BMP.
|
|
42
|
+
function byCodePoint(a: string, b: string): number {
|
|
43
|
+
const x = [...a], y = [...b];
|
|
44
|
+
for (let i = 0; i < Math.min(x.length, y.length); i++) {
|
|
45
|
+
const d = x[i]!.codePointAt(0)! - y[i]!.codePointAt(0)!;
|
|
46
|
+
if (d) return d;
|
|
47
|
+
}
|
|
48
|
+
return x.length - y.length;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/** Canonical JSON: sorted keys, no whitespace, non-ASCII left as is. Numbers
|
|
52
|
+
* must be integers: Python spells 1.0 as "1.0" and JS as "1", so a float
|
|
53
|
+
* cannot be made to agree and is refused. */
|
|
54
|
+
export function canonicalJson(v: unknown): string {
|
|
55
|
+
if (v === null || typeof v === 'boolean' || typeof v === 'string') return JSON.stringify(v);
|
|
56
|
+
if (typeof v === 'number') {
|
|
57
|
+
if (!Number.isSafeInteger(v)) throw new Error('canonical JSON carries integers only');
|
|
58
|
+
return String(v);
|
|
59
|
+
}
|
|
60
|
+
if (Array.isArray(v)) return '[' + v.map((el) => canonicalJson(el === undefined ? null : el)).join(',') + ']';
|
|
61
|
+
if (typeof v === 'object') {
|
|
62
|
+
const o = v as Record<string, unknown>;
|
|
63
|
+
return '{' + Object.keys(o).filter((k) => o[k] !== undefined).sort(byCodePoint)
|
|
64
|
+
.map((k) => JSON.stringify(k) + ':' + canonicalJson(o[k])).join(',') + '}';
|
|
65
|
+
}
|
|
66
|
+
throw new Error('not JSON: ' + typeof v);
|
|
67
|
+
}
|
package/src/event.ts
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
// NIP-01 events (core fleetmesh_core/storage/store.py): the id is sha256 over
|
|
2
|
+
// the serialised [0, pubkey, created_at, kind, tags, content], and the
|
|
3
|
+
// signature is BIP-340 over that id by the event's pubkey.
|
|
4
|
+
import { schnorr } from '@noble/curves/secp256k1.js';
|
|
5
|
+
import { randomBytes } from '@noble/curves/utils.js';
|
|
6
|
+
import { sha256 } from '@noble/hashes/sha2.js';
|
|
7
|
+
import { bytesToHex, hexToBytes, isHex, utf8 } from './encoding.ts';
|
|
8
|
+
|
|
9
|
+
export type Tags = string[][];
|
|
10
|
+
|
|
11
|
+
export interface UnsignedEvent {
|
|
12
|
+
pubkey: string;
|
|
13
|
+
created_at: number;
|
|
14
|
+
kind: number;
|
|
15
|
+
tags: Tags;
|
|
16
|
+
content: string;
|
|
17
|
+
}
|
|
18
|
+
export interface NostrEvent extends UnsignedEvent { id: string; sig: string }
|
|
19
|
+
|
|
20
|
+
// JSON.stringify of this array is the NIP-01 serialisation, and the one
|
|
21
|
+
// Python's json.dumps(separators=(',', ':'), ensure_ascii=False) writes.
|
|
22
|
+
export function eventId(pubkey: string, createdAt: number, kind: number, tags: Tags, content: string): string {
|
|
23
|
+
return bytesToHex(sha256(utf8(JSON.stringify([0, pubkey, createdAt, kind, tags, content]))));
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export const pubkeyOf = (skHex: string): string => bytesToHex(schnorr.getPublicKey(hexToBytes(skHex)));
|
|
27
|
+
|
|
28
|
+
/** A complete signed event. `aux` is BIP-340's auxiliary randomness: random
|
|
29
|
+
* by default; the reference signs with 32 zero bytes, which tests pass to
|
|
30
|
+
* reproduce its signatures. */
|
|
31
|
+
export function signEvent(skHex: string, createdAt: number, kind: number, tags: Tags = [], content = '',
|
|
32
|
+
aux: Uint8Array = randomBytes(32)): NostrEvent {
|
|
33
|
+
const pubkey = pubkeyOf(skHex);
|
|
34
|
+
const id = eventId(pubkey, createdAt, kind, tags, content);
|
|
35
|
+
const sig = bytesToHex(schnorr.sign(hexToBytes(id), hexToBytes(skHex), aux));
|
|
36
|
+
return { id, pubkey, created_at: createdAt, kind, tags, content, sig };
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** Every NIP-01 field with the right primitive type. */
|
|
40
|
+
export function isEventShaped(o: unknown): o is NostrEvent {
|
|
41
|
+
if (!o || typeof o !== 'object') return false;
|
|
42
|
+
const e = o as Record<string, unknown>;
|
|
43
|
+
return typeof e.id === 'string' && typeof e.pubkey === 'string' && Number.isSafeInteger(e.created_at)
|
|
44
|
+
&& Number.isSafeInteger(e.kind) && Array.isArray(e.tags) && typeof e.content === 'string' && typeof e.sig === 'string';
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/** False for anything malformed; never throws. */
|
|
48
|
+
export function verifyEvent(ev: unknown): boolean {
|
|
49
|
+
if (!isEventShaped(ev) || !isHex(ev.pubkey, 64) || !isHex(ev.id, 64) || ev.created_at < 0) return false;
|
|
50
|
+
try {
|
|
51
|
+
const want = eventId(ev.pubkey, ev.created_at, ev.kind, ev.tags, ev.content);
|
|
52
|
+
return ev.id === want && isHex(ev.sig, 128) && schnorr.verify(hexToBytes(ev.sig), hexToBytes(want), hexToBytes(ev.pubkey));
|
|
53
|
+
} catch {
|
|
54
|
+
return false;
|
|
55
|
+
}
|
|
56
|
+
}
|
package/src/giftwrap.ts
ADDED
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
// NIP-59 gift wraps (core fleetmesh_core/crypto/giftwrap.py): the control
|
|
2
|
+
// transport that always works, and the one a leaf uses to its mediator.
|
|
3
|
+
//
|
|
4
|
+
// A DIDComm envelope travels as the content of a kind 13 seal signed by the
|
|
5
|
+
// sender, itself the content of a kind 21059 wrap signed by a key used once.
|
|
6
|
+
// Both layers are nip44/2 to the recipient's node key. Kind 1059 is the
|
|
7
|
+
// stored variant, for store-and-forward.
|
|
8
|
+
//
|
|
9
|
+
// The seal's created_at, and a stored wrap's, are skewed into the past so a
|
|
10
|
+
// relay keeping the wrap cannot line messages up by time. A live wrap is
|
|
11
|
+
// dated now: relays drop an ephemeral event older than about a minute.
|
|
12
|
+
import { randomBytes } from '@noble/curves/utils.js';
|
|
13
|
+
import { GRANT } from './constants.ts';
|
|
14
|
+
import { bytesToHex, canonicalJson } from './encoding.ts';
|
|
15
|
+
import { type NostrEvent, pubkeyOf, signEvent, verifyEvent } from './event.ts';
|
|
16
|
+
import * as nip44 from './nip44.ts';
|
|
17
|
+
|
|
18
|
+
export const SEAL = 13;
|
|
19
|
+
export const WRAP_LIVE = 21059;
|
|
20
|
+
export const WRAP_STORED = 1059;
|
|
21
|
+
export const TWO_DAYS = 2 * 86400;
|
|
22
|
+
// The skew stops twice the clock tolerance short of a receiver's two-day
|
|
23
|
+
// `since`, so a sender whose clock is behind never lands outside it.
|
|
24
|
+
export const SKEW_MAX = TWO_DAYS - 2 * GRANT.max_clock_skew_seconds;
|
|
25
|
+
// How long a wrap or seal stays openable: a week past the skew, for a node
|
|
26
|
+
// that was down. Older is a wrap being replayed from a store.
|
|
27
|
+
export const RETENTION = 7 * 86400;
|
|
28
|
+
|
|
29
|
+
export class GiftWrapError extends Error {}
|
|
30
|
+
|
|
31
|
+
/** The source of the skew, the one-time key and both nonces, drawn in the
|
|
32
|
+
* reference's order, so the same rng yields the reference's bytes. */
|
|
33
|
+
export type Rng = (n: number) => Uint8Array;
|
|
34
|
+
|
|
35
|
+
export interface WrapOptions {
|
|
36
|
+
kind?: number;
|
|
37
|
+
rng?: Rng;
|
|
38
|
+
/** BIP-340 aux for both signatures; fresh random per signature when absent.
|
|
39
|
+
* The reference signs with 32 zero bytes, which parity tests pass. */
|
|
40
|
+
aux?: Uint8Array;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
function skew(now: number, rng: Rng): number {
|
|
44
|
+
const b = rng(4);
|
|
45
|
+
const n = ((b[0]! << 24) >>> 0) + (b[1]! << 16) + (b[2]! << 8) + b[3]!;
|
|
46
|
+
return now - (n % (SKEW_MAX + 1));
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** Live: now. Stored: skewed. The rng is drawn either way, as the reference
|
|
50
|
+
* does, so the same rng yields the same bytes. */
|
|
51
|
+
export function wrapCreatedAt(now: number, kind: number, rng: Rng): number {
|
|
52
|
+
const skewed = skew(now, rng);
|
|
53
|
+
return kind === WRAP_LIVE ? now : skewed;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/** Wrap any JSON payload (a DIDComm JWE here) from sender to recipient. */
|
|
57
|
+
export function wrap(payload: unknown, senderSk: string, recipientPk: string, now: number,
|
|
58
|
+
{ kind = WRAP_LIVE, rng = randomBytes, aux }: WrapOptions = {}): NostrEvent {
|
|
59
|
+
if (kind !== WRAP_LIVE && kind !== WRAP_STORED) throw new GiftWrapError('a wrap is kind 21059 or kind 1059');
|
|
60
|
+
const body = canonicalJson(payload);
|
|
61
|
+
try {
|
|
62
|
+
const conv = nip44.conversationKey(senderSk, recipientPk);
|
|
63
|
+
const sealAt = skew(now, rng);
|
|
64
|
+
const seal = signEvent(senderSk, sealAt, SEAL, [], nip44.encrypt(body, conv, rng(32)), aux ?? randomBytes(32));
|
|
65
|
+
const once = bytesToHex(rng(32));
|
|
66
|
+
const convW = nip44.conversationKey(once, recipientPk);
|
|
67
|
+
const at = wrapCreatedAt(now, kind, rng);
|
|
68
|
+
return signEvent(once, at, kind, [['p', recipientPk]], nip44.encrypt(canonicalJson(seal), convW, rng(32)), aux ?? randomBytes(32));
|
|
69
|
+
} catch (e) {
|
|
70
|
+
if (!(e instanceof nip44.Nip44Error)) throw e;
|
|
71
|
+
throw new GiftWrapError(`a payload of ${body.length} bytes does not fit one wrap (${e.message}); fragment it`);
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
function inDate(ev: { created_at?: unknown }, now: number | undefined, what: string): void {
|
|
76
|
+
if (now === undefined) return;
|
|
77
|
+
const created = ev.created_at;
|
|
78
|
+
if (typeof created !== 'number' || !Number.isSafeInteger(created)) throw new GiftWrapError(`${what} has no created_at`);
|
|
79
|
+
if (created < now - SKEW_MAX - RETENTION) throw new GiftWrapError(`${what} is older than ${SKEW_MAX + RETENTION} seconds`);
|
|
80
|
+
if (created > now + SKEW_MAX) throw new GiftWrapError(`${what} is dated more than ${SKEW_MAX} seconds ahead`);
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
function open(content: string, conv: Uint8Array, what: string): any {
|
|
84
|
+
try {
|
|
85
|
+
return JSON.parse(nip44.decrypt(content, conv));
|
|
86
|
+
} catch (e) {
|
|
87
|
+
throw new GiftWrapError(`${what} does not open: ${(e as Error).message}`);
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/** [payload, senderPk]. Every layer is checked: the wrap's signature and
|
|
92
|
+
* addressing, the seal's signature, and that the seal's author is the key
|
|
93
|
+
* the inner ciphertext was agreed with. With `now`, both dates must lie in
|
|
94
|
+
* the retention window; without it age is not judged. */
|
|
95
|
+
export function unwrap(wrapEvent: NostrEvent, recipientSk: string, now?: number): [unknown, string] {
|
|
96
|
+
const myPk = pubkeyOf(recipientSk);
|
|
97
|
+
if (wrapEvent.kind !== WRAP_LIVE && wrapEvent.kind !== WRAP_STORED) throw new GiftWrapError('not a gift wrap');
|
|
98
|
+
inDate(wrapEvent, now, 'wrap');
|
|
99
|
+
if (!(wrapEvent.tags ?? []).some((t) => t[0] === 'p' && t[1] === myPk)) throw new GiftWrapError('not addressed to me');
|
|
100
|
+
if (!verifyEvent(wrapEvent)) throw new GiftWrapError('wrap signature does not verify');
|
|
101
|
+
const seal = open(wrapEvent.content, nip44.conversationKey(recipientSk, wrapEvent.pubkey), 'wrap');
|
|
102
|
+
if (!seal || typeof seal !== 'object' || seal.kind !== SEAL || (Array.isArray(seal.tags) ? seal.tags.length : seal.tags))
|
|
103
|
+
throw new GiftWrapError('inner event is not a seal');
|
|
104
|
+
if (!verifyEvent(seal)) throw new GiftWrapError('seal signature does not verify');
|
|
105
|
+
inDate(seal, now, 'seal');
|
|
106
|
+
const payload = open(seal.content, nip44.conversationKey(recipientSk, seal.pubkey), 'seal');
|
|
107
|
+
return [payload, seal.pubkey];
|
|
108
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
// @fleetmesh/leaf: the leaf profile (spec § "The leaf profile and mobile
|
|
2
|
+
// operational limits") for browsers and PWAs. One wss:// connection to a
|
|
3
|
+
// mediator, gift-wrapped DIDComm, NIP-77 range reconciliation, a bounded store.
|
|
4
|
+
export * as descriptor from './descriptor.ts';
|
|
5
|
+
export * as did from './did.ts';
|
|
6
|
+
export * as didcomm from './didcomm.ts';
|
|
7
|
+
export * as encoding from './encoding.ts';
|
|
8
|
+
export * as event from './event.ts';
|
|
9
|
+
export * as giftwrap from './giftwrap.ts';
|
|
10
|
+
export * as keys from './keys.ts';
|
|
11
|
+
export * as mediation from './mediation/leaf.ts';
|
|
12
|
+
export * as mediationMessages from './mediation/messages.ts';
|
|
13
|
+
export * as negentropy from './negentropy.ts';
|
|
14
|
+
export * as nip44 from './nip44.ts';
|
|
15
|
+
export * as relay from './relay.ts';
|
|
16
|
+
export * as seal from './seal.ts';
|
|
17
|
+
export { LeafSession, type LeafSessionOptions, SessionError } from './session.ts';
|
|
18
|
+
export { type BrowserLeafOptions, startBrowserLeaf, SW_PICKUP } from './pwa/browser-leaf.ts';
|
|
19
|
+
export { type HubEvent, LeafHub, type LeafStatus } from './pwa/hub.ts';
|
|
20
|
+
export { LeafStore } from './pwa/store.ts';
|