@kokuin/token 0.3.0 → 0.5.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/lib/cache.js +8 -1
- package/lib/did.d.ts +102 -6
- package/lib/did.js +169 -12
- package/lib/identity.d.ts +35 -14
- package/lib/identity.js +51 -34
- package/lib/index.d.ts +4 -6
- package/lib/index.js +4 -5
- package/lib/method.d.ts +70 -0
- package/lib/method.js +8 -0
- package/lib/peer4.d.ts +7 -2
- package/lib/peer4.js +12 -0
- package/lib/schemas.d.ts +22 -4
- package/lib/schemas.js +16 -3
- package/lib/token.d.ts +25 -2
- package/lib/token.js +76 -24
- package/lib/types.d.ts +1 -0
- package/package.json +18 -16
- package/lib/jwe.d.ts +0 -67
- package/lib/jwe.js +0 -281
- package/lib/rotation.d.ts +0 -15
- package/lib/rotation.js +0 -12
package/lib/jwe.js
DELETED
|
@@ -1,281 +0,0 @@
|
|
|
1
|
-
import { gcm } from '@noble/ciphers/aes.js';
|
|
2
|
-
import { randomBytes } from '@noble/ciphers/utils.js';
|
|
3
|
-
import { ed25519, x25519 } from '@noble/curves/ed25519.js';
|
|
4
|
-
import { sha256 } from '@noble/hashes/sha2.js';
|
|
5
|
-
import { b64uFromJSON, b64uToJSON, fromB64U, toB64U } from '@sozai/codec';
|
|
6
|
-
import { getAgreementKey, getSignatureInfo } from './did.js';
|
|
7
|
-
import { decodePeer4, getPeer4ShortForm, isPeer4 } from './peer4.js';
|
|
8
|
-
import { createUnsignedToken, isUnsignedToken, verifyToken } from './token.js';
|
|
9
|
-
import { stringifyToken } from './utils.js';
|
|
10
|
-
function uint32BE(value) {
|
|
11
|
-
const buf = new Uint8Array(4);
|
|
12
|
-
const view = new DataView(buf.buffer);
|
|
13
|
-
view.setUint32(0, value, false);
|
|
14
|
-
return buf;
|
|
15
|
-
}
|
|
16
|
-
function lengthPrefixed(data) {
|
|
17
|
-
const prefix = uint32BE(data.length);
|
|
18
|
-
const result = new Uint8Array(4 + data.length);
|
|
19
|
-
result.set(prefix);
|
|
20
|
-
result.set(data, 4);
|
|
21
|
-
return result;
|
|
22
|
-
}
|
|
23
|
-
/**
|
|
24
|
-
* Concat KDF per RFC 7518 Section 4.6.2.
|
|
25
|
-
* Single SHA-256 iteration (sufficient for 256-bit keys).
|
|
26
|
-
*/ export function concatKDF(params) {
|
|
27
|
-
const { sharedSecret, keyLength, algorithmID, partyUInfo, partyVInfo } = params;
|
|
28
|
-
const encoder = new TextEncoder();
|
|
29
|
-
const algID = lengthPrefixed(encoder.encode(algorithmID));
|
|
30
|
-
const apu = lengthPrefixed(partyUInfo);
|
|
31
|
-
const apv = lengthPrefixed(partyVInfo);
|
|
32
|
-
const keyDataLen = uint32BE(keyLength);
|
|
33
|
-
// round = 1 (single iteration for 256-bit key)
|
|
34
|
-
const round = uint32BE(1);
|
|
35
|
-
// Hash(round || sharedSecret || algID || apu || apv || keyDataLen)
|
|
36
|
-
const parts = [
|
|
37
|
-
round,
|
|
38
|
-
sharedSecret,
|
|
39
|
-
algID,
|
|
40
|
-
apu,
|
|
41
|
-
apv,
|
|
42
|
-
keyDataLen
|
|
43
|
-
];
|
|
44
|
-
let totalLength = 0;
|
|
45
|
-
for (const part of parts){
|
|
46
|
-
totalLength += part.length;
|
|
47
|
-
}
|
|
48
|
-
const hashInput = new Uint8Array(totalLength);
|
|
49
|
-
let offset = 0;
|
|
50
|
-
for (const part of parts){
|
|
51
|
-
hashInput.set(part, offset);
|
|
52
|
-
offset += part.length;
|
|
53
|
-
}
|
|
54
|
-
return sha256(hashInput).slice(0, keyLength / 8);
|
|
55
|
-
}
|
|
56
|
-
function encryptWithX25519(recipientPublicKey, plaintext) {
|
|
57
|
-
// Generate ephemeral X25519 key pair
|
|
58
|
-
const ephemeralPrivateKey = x25519.utils.randomSecretKey();
|
|
59
|
-
const ephemeralPublicKey = x25519.getPublicKey(ephemeralPrivateKey);
|
|
60
|
-
// Compute shared secret via ECDH
|
|
61
|
-
const sharedSecret = x25519.getSharedSecret(ephemeralPrivateKey, recipientPublicKey);
|
|
62
|
-
// Derive content encryption key via Concat KDF
|
|
63
|
-
const cek = concatKDF({
|
|
64
|
-
sharedSecret,
|
|
65
|
-
keyLength: 256,
|
|
66
|
-
algorithmID: 'A256GCM',
|
|
67
|
-
partyUInfo: new Uint8Array(0),
|
|
68
|
-
partyVInfo: new Uint8Array(0)
|
|
69
|
-
});
|
|
70
|
-
// Generate random 96-bit IV for AES-GCM
|
|
71
|
-
const iv = randomBytes(12);
|
|
72
|
-
// Build protected header
|
|
73
|
-
const protectedHeader = {
|
|
74
|
-
alg: 'ECDH-ES',
|
|
75
|
-
enc: 'A256GCM',
|
|
76
|
-
epk: {
|
|
77
|
-
kty: 'OKP',
|
|
78
|
-
crv: 'X25519',
|
|
79
|
-
x: toB64U(ephemeralPublicKey)
|
|
80
|
-
}
|
|
81
|
-
};
|
|
82
|
-
// Encode protected header
|
|
83
|
-
const encodedHeader = b64uFromJSON(protectedHeader);
|
|
84
|
-
// AAD is the ASCII bytes of the encoded header (per RFC 7516 Section 5.1 step 14)
|
|
85
|
-
const aad = new TextEncoder().encode(encodedHeader);
|
|
86
|
-
// Encrypt with AES-256-GCM (tag is appended to ciphertext)
|
|
87
|
-
const cipher = gcm(cek, iv, aad);
|
|
88
|
-
const ciphertextWithTag = cipher.encrypt(plaintext);
|
|
89
|
-
// Split ciphertext and tag (GCM tag is last 16 bytes)
|
|
90
|
-
const ciphertext = ciphertextWithTag.slice(0, ciphertextWithTag.length - 16);
|
|
91
|
-
const tag = ciphertextWithTag.slice(ciphertextWithTag.length - 16);
|
|
92
|
-
// JWE Compact Serialization: header.encryptedKey.iv.ciphertext.tag
|
|
93
|
-
// For ECDH-ES direct, encrypted key is empty
|
|
94
|
-
return [
|
|
95
|
-
encodedHeader,
|
|
96
|
-
'',
|
|
97
|
-
toB64U(iv),
|
|
98
|
-
toB64U(ciphertext),
|
|
99
|
-
toB64U(tag)
|
|
100
|
-
].join('.');
|
|
101
|
-
}
|
|
102
|
-
function resolveX25519Key(recipient) {
|
|
103
|
-
if (typeof recipient !== 'string') {
|
|
104
|
-
return {
|
|
105
|
-
key: recipient
|
|
106
|
-
};
|
|
107
|
-
}
|
|
108
|
-
if (isPeer4(recipient)) {
|
|
109
|
-
const shortForm = getPeer4ShortForm(recipient);
|
|
110
|
-
if (recipient === shortForm) {
|
|
111
|
-
// The doc lives in the long form. Resolving a short form needs a DIDResolver, which
|
|
112
|
-
// this sync constructor cannot await — so say so, rather than failing as a bad DID.
|
|
113
|
-
throw new Error(`Cannot encrypt to a did:peer:4 short form: ${shortForm}. Pass the long form, which carries the document.`);
|
|
114
|
-
}
|
|
115
|
-
const { doc } = decodePeer4(recipient);
|
|
116
|
-
const key = getAgreementKey(doc);
|
|
117
|
-
if (key == null) {
|
|
118
|
-
throw new Error(`Recipient publishes no X25519 keyAgreement key: ${shortForm}`);
|
|
119
|
-
}
|
|
120
|
-
return {
|
|
121
|
-
key,
|
|
122
|
-
id: shortForm
|
|
123
|
-
};
|
|
124
|
-
}
|
|
125
|
-
const [algorithm, publicKey] = getSignatureInfo(recipient);
|
|
126
|
-
if (algorithm === 'EdDSA') {
|
|
127
|
-
return {
|
|
128
|
-
key: ed25519.utils.toMontgomery(publicKey),
|
|
129
|
-
id: recipient
|
|
130
|
-
};
|
|
131
|
-
}
|
|
132
|
-
throw new Error(`Unsupported DID algorithm for encryption: ${algorithm}`);
|
|
133
|
-
}
|
|
134
|
-
export function createTokenEncrypter(recipient, options) {
|
|
135
|
-
if (typeof recipient !== 'string' && options?.algorithm !== 'X25519') {
|
|
136
|
-
throw new Error(`Unsupported algorithm: ${options?.algorithm}`);
|
|
137
|
-
}
|
|
138
|
-
const { key, id } = resolveX25519Key(recipient);
|
|
139
|
-
return {
|
|
140
|
-
recipientID: id,
|
|
141
|
-
async encrypt (plaintext) {
|
|
142
|
-
return encryptWithX25519(key, plaintext);
|
|
143
|
-
}
|
|
144
|
-
};
|
|
145
|
-
}
|
|
146
|
-
/**
|
|
147
|
-
* Encrypt plaintext to JWE compact serialization using the given encrypter.
|
|
148
|
-
*/ export async function encryptToken(encrypter, plaintext) {
|
|
149
|
-
return encrypter.encrypt(plaintext);
|
|
150
|
-
}
|
|
151
|
-
/**
|
|
152
|
-
* Decrypt a JWE compact serialization string.
|
|
153
|
-
*/ export async function decryptToken(decrypter, jwe) {
|
|
154
|
-
const parts = jwe.split('.');
|
|
155
|
-
if (parts.length !== 5) {
|
|
156
|
-
throw new Error(`Invalid JWE format: expected 5 parts, got ${parts.length}`);
|
|
157
|
-
}
|
|
158
|
-
const [encodedHeader, _encryptedKey, encodedIV, encodedCiphertext, encodedTag] = parts;
|
|
159
|
-
// Parse protected header
|
|
160
|
-
const header = b64uToJSON(encodedHeader);
|
|
161
|
-
if (header.alg !== 'ECDH-ES') {
|
|
162
|
-
throw new Error(`Unsupported JWE algorithm: ${header.alg}`);
|
|
163
|
-
}
|
|
164
|
-
if (header.enc !== 'A256GCM') {
|
|
165
|
-
throw new Error(`Unsupported JWE encryption: ${header.enc}`);
|
|
166
|
-
}
|
|
167
|
-
// Extract ephemeral public key from header
|
|
168
|
-
const ephemeralPublicKey = fromB64U(header.epk.x);
|
|
169
|
-
// Compute shared secret via ECDH key agreement
|
|
170
|
-
const sharedSecret = await decrypter.agreeKey(ephemeralPublicKey);
|
|
171
|
-
// Derive content encryption key
|
|
172
|
-
const cek = concatKDF({
|
|
173
|
-
sharedSecret,
|
|
174
|
-
keyLength: 256,
|
|
175
|
-
algorithmID: 'A256GCM',
|
|
176
|
-
partyUInfo: header.apu != null ? fromB64U(header.apu) : new Uint8Array(0),
|
|
177
|
-
partyVInfo: header.apv != null ? fromB64U(header.apv) : new Uint8Array(0)
|
|
178
|
-
});
|
|
179
|
-
// Decode components
|
|
180
|
-
const iv = fromB64U(encodedIV);
|
|
181
|
-
const ciphertext = fromB64U(encodedCiphertext);
|
|
182
|
-
const tag = fromB64U(encodedTag);
|
|
183
|
-
// Reconstruct ciphertext+tag (GCM expects them concatenated)
|
|
184
|
-
const ciphertextWithTag = new Uint8Array(ciphertext.length + tag.length);
|
|
185
|
-
ciphertextWithTag.set(ciphertext);
|
|
186
|
-
ciphertextWithTag.set(tag, ciphertext.length);
|
|
187
|
-
// AAD is the ASCII bytes of the encoded header
|
|
188
|
-
const aad = new TextEncoder().encode(encodedHeader);
|
|
189
|
-
// Decrypt with AES-256-GCM
|
|
190
|
-
const cipher = gcm(cek, iv, aad);
|
|
191
|
-
return cipher.decrypt(ciphertextWithTag);
|
|
192
|
-
}
|
|
193
|
-
/**
|
|
194
|
-
* Wrap a payload into a token string according to the specified envelope mode.
|
|
195
|
-
*/ export async function wrapEnvelope(mode, payload, options) {
|
|
196
|
-
switch(mode){
|
|
197
|
-
case 'plain':
|
|
198
|
-
{
|
|
199
|
-
const token = createUnsignedToken(payload, options.header);
|
|
200
|
-
// Append empty signature segment for RFC 7519 unsecured JWT format (header.payload.)
|
|
201
|
-
return `${stringifyToken(token)}.`;
|
|
202
|
-
}
|
|
203
|
-
case 'jws':
|
|
204
|
-
{
|
|
205
|
-
if (options.signer == null) throw new Error('Signer required for jws mode');
|
|
206
|
-
const token = await options.signer.signToken(payload, {
|
|
207
|
-
header: options.header
|
|
208
|
-
});
|
|
209
|
-
return stringifyToken(token);
|
|
210
|
-
}
|
|
211
|
-
case 'jws-in-jwe':
|
|
212
|
-
{
|
|
213
|
-
if (options.signer == null) throw new Error('Signer required for jws-in-jwe mode');
|
|
214
|
-
if (options.encrypter == null) throw new Error('Encrypter required for jws-in-jwe mode');
|
|
215
|
-
const signed = await options.signer.signToken(payload, {
|
|
216
|
-
header: options.header
|
|
217
|
-
});
|
|
218
|
-
const jwsString = stringifyToken(signed);
|
|
219
|
-
return encryptToken(options.encrypter, new TextEncoder().encode(jwsString));
|
|
220
|
-
}
|
|
221
|
-
case 'jwe-in-jws':
|
|
222
|
-
{
|
|
223
|
-
if (options.signer == null) throw new Error('Signer required for jwe-in-jws mode');
|
|
224
|
-
if (options.encrypter == null) throw new Error('Encrypter required for jwe-in-jws mode');
|
|
225
|
-
const plaintext = new TextEncoder().encode(JSON.stringify(payload));
|
|
226
|
-
const jwe = await encryptToken(options.encrypter, plaintext);
|
|
227
|
-
const signed = await options.signer.signToken({
|
|
228
|
-
jwe
|
|
229
|
-
}, {
|
|
230
|
-
header: options.header
|
|
231
|
-
});
|
|
232
|
-
return stringifyToken(signed);
|
|
233
|
-
}
|
|
234
|
-
}
|
|
235
|
-
}
|
|
236
|
-
/**
|
|
237
|
-
* Unwrap a token string, auto-detecting the envelope mode from its structure.
|
|
238
|
-
*/ export async function unwrapEnvelope(message, options) {
|
|
239
|
-
const parts = message.split('.');
|
|
240
|
-
if (parts.length === 5) {
|
|
241
|
-
// JWE outer → jws-in-jwe mode
|
|
242
|
-
if (options.decrypter == null) throw new Error('Decrypter required for JWE message');
|
|
243
|
-
const decrypted = await decryptToken(options.decrypter, message);
|
|
244
|
-
const jwsString = new TextDecoder().decode(decrypted);
|
|
245
|
-
const token = await verifyToken(jwsString, {
|
|
246
|
-
verifiers: options.verifiers
|
|
247
|
-
});
|
|
248
|
-
return {
|
|
249
|
-
payload: token.payload,
|
|
250
|
-
mode: 'jws-in-jwe'
|
|
251
|
-
};
|
|
252
|
-
}
|
|
253
|
-
if (parts.length === 3) {
|
|
254
|
-
// JWT: could be plain, jws, or jwe-in-jws
|
|
255
|
-
const token = await verifyToken(message, {
|
|
256
|
-
verifiers: options.verifiers,
|
|
257
|
-
allowUnsigned: true
|
|
258
|
-
});
|
|
259
|
-
if (isUnsignedToken(token)) {
|
|
260
|
-
return {
|
|
261
|
-
payload: token.payload,
|
|
262
|
-
mode: 'plain'
|
|
263
|
-
};
|
|
264
|
-
}
|
|
265
|
-
// Check if payload contains a JWE (jwe-in-jws)
|
|
266
|
-
if ('jwe' in token.payload && typeof token.payload.jwe === 'string') {
|
|
267
|
-
if (options.decrypter == null) throw new Error('Decrypter required for jwe-in-jws message');
|
|
268
|
-
const decrypted = await decryptToken(options.decrypter, token.payload.jwe);
|
|
269
|
-
const innerPayload = JSON.parse(new TextDecoder().decode(decrypted));
|
|
270
|
-
return {
|
|
271
|
-
payload: innerPayload,
|
|
272
|
-
mode: 'jwe-in-jws'
|
|
273
|
-
};
|
|
274
|
-
}
|
|
275
|
-
return {
|
|
276
|
-
payload: token.payload,
|
|
277
|
-
mode: 'jws'
|
|
278
|
-
};
|
|
279
|
-
}
|
|
280
|
-
throw new Error(`Invalid envelope format: expected 3 or 5 dot-separated parts, got ${parts.length}`);
|
|
281
|
-
}
|
package/lib/rotation.d.ts
DELETED
|
@@ -1,15 +0,0 @@
|
|
|
1
|
-
import type { MultiKeyIdentity } from './identity.js';
|
|
2
|
-
import type { SignedToken } from './types.js';
|
|
3
|
-
export type RotationPayload = {
|
|
4
|
-
type: 'did-rotation';
|
|
5
|
-
iss?: string;
|
|
6
|
-
to: string;
|
|
7
|
-
toLongForm: string;
|
|
8
|
-
issuedAt: number;
|
|
9
|
-
};
|
|
10
|
-
/**
|
|
11
|
-
* Sign a rotation assertion linking an old identity to a new one.
|
|
12
|
-
* The assertion is a regular signed token whose `iss` is the old DID.
|
|
13
|
-
* Verifiers walking a rotation chain can use this to link related identities.
|
|
14
|
-
*/
|
|
15
|
-
export declare function createRotationAssertion(oldIdentity: MultiKeyIdentity, newIdentity: MultiKeyIdentity, issuedAt?: number): Promise<SignedToken<RotationPayload>>;
|
package/lib/rotation.js
DELETED
|
@@ -1,12 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Sign a rotation assertion linking an old identity to a new one.
|
|
3
|
-
* The assertion is a regular signed token whose `iss` is the old DID.
|
|
4
|
-
* Verifiers walking a rotation chain can use this to link related identities.
|
|
5
|
-
*/ export async function createRotationAssertion(oldIdentity, newIdentity, issuedAt = Math.floor(Date.now() / 1000)) {
|
|
6
|
-
return oldIdentity.signToken({
|
|
7
|
-
type: 'did-rotation',
|
|
8
|
-
to: newIdentity.id,
|
|
9
|
-
toLongForm: newIdentity.longForm,
|
|
10
|
-
issuedAt
|
|
11
|
-
});
|
|
12
|
-
}
|