@kokuin/vault 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 +73 -2
- package/lib/branch.d.ts +4 -0
- package/lib/branch.js +12 -0
- package/lib/canonical-token.d.ts +1 -0
- package/lib/canonical-token.js +10 -0
- package/lib/digest.d.ts +31 -0
- package/lib/digest.js +60 -0
- package/lib/errors.d.ts +43 -0
- package/lib/errors.js +91 -0
- package/lib/factors.d.ts +17 -0
- package/lib/factors.js +59 -0
- package/lib/id.d.ts +7 -0
- package/lib/id.js +24 -0
- package/lib/index.d.ts +12 -0
- package/lib/index.js +12 -0
- package/lib/key-cache.d.ts +17 -0
- package/lib/key-cache.js +65 -0
- package/lib/pin-throttle.d.ts +16 -0
- package/lib/pin-throttle.js +40 -0
- package/lib/record-types.d.ts +44 -0
- package/lib/record-types.js +339 -0
- package/lib/records.d.ts +91 -0
- package/lib/records.js +258 -0
- package/lib/suite.d.ts +89 -0
- package/lib/suite.js +267 -0
- package/lib/wrappable.d.ts +4 -0
- package/lib/wrappable.js +4 -0
- package/package.json +49 -3
package/README.md
CHANGED
|
@@ -1,3 +1,74 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @kokuin/vault
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Database-free content keys, ordered factor wrapping, and authenticated encryption of opaque bytes.
|
|
4
|
+
|
|
5
|
+
```ts
|
|
6
|
+
import { getSuite, SUITE_VAULT_1, wrappableDID } from '@kokuin/vault'
|
|
7
|
+
import { createRuntime } from '@sozai/runtime'
|
|
8
|
+
|
|
9
|
+
const runtime = createRuntime()
|
|
10
|
+
const suite = getSuite(SUITE_VAULT_1)
|
|
11
|
+
const keyID = 'host-content-key'
|
|
12
|
+
const keyVersion = 1
|
|
13
|
+
const wrappingID = 'device-wrapping'
|
|
14
|
+
const contentKey = suite.generateContentKey(runtime)
|
|
15
|
+
const wrapped = await suite.wrap({
|
|
16
|
+
runtime,
|
|
17
|
+
keyID,
|
|
18
|
+
keyVersion,
|
|
19
|
+
wrappingID,
|
|
20
|
+
contentKey,
|
|
21
|
+
factors: [{ kind: 'did', recipientDID: wrappableDID(deviceIdentity) }],
|
|
22
|
+
})
|
|
23
|
+
|
|
24
|
+
// Keep this digest in trusted local state or independently authenticated metadata.
|
|
25
|
+
const trustedDigest = wrapped.descriptorDigest
|
|
26
|
+
const openedKey = await suite.unwrap({
|
|
27
|
+
...wrapped,
|
|
28
|
+
keyID,
|
|
29
|
+
keyVersion,
|
|
30
|
+
wrappingID,
|
|
31
|
+
identity: deviceIdentity,
|
|
32
|
+
expectedDescriptorDigest: trustedDigest,
|
|
33
|
+
})
|
|
34
|
+
const entryID = 'current-state'
|
|
35
|
+
const encrypted = suite.encryptEntry({
|
|
36
|
+
runtime,
|
|
37
|
+
keyID,
|
|
38
|
+
keyVersion,
|
|
39
|
+
entryID,
|
|
40
|
+
contentKey: openedKey,
|
|
41
|
+
plaintext: hostBytes,
|
|
42
|
+
})
|
|
43
|
+
const recovered = suite.decryptEntry({
|
|
44
|
+
...encrypted,
|
|
45
|
+
keyID,
|
|
46
|
+
keyVersion,
|
|
47
|
+
entryID,
|
|
48
|
+
contentKey: openedKey,
|
|
49
|
+
})
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
`deviceIdentity` supplies an already available agreement key. The host must ensure `agreeKey` never prompts on its message path.
|
|
53
|
+
The host owns persistence and atomically replaces the current ciphertext with its journal or outbox transaction.
|
|
54
|
+
The host also owns device binding, rollback protection, and refusal to sync, export, or retain historical MLS state.
|
|
55
|
+
|
|
56
|
+
`VAULT_1` uses X25519 agreement, HKDF-SHA256, Argon2id, and AES-256-GCM.
|
|
57
|
+
Descriptors preserve factor order. A PIN requires a DID factor in the same wrapping.
|
|
58
|
+
The default Argon2id cost is `{ m: 19456, t: 2, p: 1 }`, with memory measured in KiB.
|
|
59
|
+
IVs are 12 bytes. Encrypted values contain ciphertext followed by the 16-byte authentication tag.
|
|
60
|
+
Entry AAD binds the suite, key ID, version, and entry ID.
|
|
61
|
+
|
|
62
|
+
`expectedDescriptorDigest` is optional. A trusted mismatch throws `VaultTampered` before agreement, KDF work, or decryption.
|
|
63
|
+
The `descriptorDigest` carried beside a presented wrapping is informational and cannot establish trust by itself.
|
|
64
|
+
GCM unwrap failures throw `VaultSecretRejected` with the original failure as `cause`, including for DID-only wrappings.
|
|
65
|
+
Missing factors and malformed descriptors retain their distinct validation errors.
|
|
66
|
+
Entry authentication failures throw `VaultTampered` with the original cause.
|
|
67
|
+
|
|
68
|
+
`createVaultKeyID(owner, unique)` hashes the exact owner bytes concatenated with unique bytes using BLAKE3.
|
|
69
|
+
Its base36 multibase encoding frames unsigned varints for namespace `0xb6`, key type `31`, and digest length `32`.
|
|
70
|
+
Callers normalise owner DIDs before minting IDs used as equality keys.
|
|
71
|
+
Recipient DIDs retain their resolvable long form. `wrappableDID` selects that form when available.
|
|
72
|
+
|
|
73
|
+
The package also exports the public key, wrapping, entry-set and descriptor digest helpers,
|
|
74
|
+
pure factor reconstruction and eligibility checks, a cloning TTL key cache, and an optional in-memory PIN throttle.
|
package/lib/branch.d.ts
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import type { VerifiedRecordOp } from '@kokuin/records';
|
|
2
|
+
/** Compare authenticated introducing ops by claim digest, then op hash. */
|
|
3
|
+
export declare function compareVaultBranches(left: VerifiedRecordOp, right: VerifiedRecordOp): number;
|
|
4
|
+
export declare function selectWinningBranch(branches: ReadonlyArray<VerifiedRecordOp>): VerifiedRecordOp;
|
package/lib/branch.js
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import { recordClaimDigest } from '@kokuin/records';
|
|
2
|
+
/** Compare authenticated introducing ops by claim digest, then op hash. */ export function compareVaultBranches(left, right) {
|
|
3
|
+
const a = recordClaimDigest(left.claim);
|
|
4
|
+
const b = recordClaimDigest(right.claim);
|
|
5
|
+
return a < b ? -1 : a > b ? 1 : left.opHash < right.opHash ? -1 : left.opHash > right.opHash ? 1 : 0;
|
|
6
|
+
}
|
|
7
|
+
export function selectWinningBranch(branches) {
|
|
8
|
+
if (branches.length === 0) throw new RangeError('At least one authenticated branch is required');
|
|
9
|
+
return branches.reduce((winner, candidate)=>{
|
|
10
|
+
return compareVaultBranches(candidate, winner) > 0 ? candidate : winner;
|
|
11
|
+
});
|
|
12
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare function isCanonicalCompactToken(token: string): boolean;
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import { fromB64U, toB64U } from '@sozai/codec';
|
|
2
|
+
export function isCanonicalCompactToken(token) {
|
|
3
|
+
const segments = token.split('.');
|
|
4
|
+
if (segments.length !== 3) return false;
|
|
5
|
+
try {
|
|
6
|
+
return segments.every((segment)=>toB64U(fromB64U(segment)) === segment);
|
|
7
|
+
} catch {
|
|
8
|
+
return false;
|
|
9
|
+
}
|
|
10
|
+
}
|
package/lib/digest.d.ts
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import type { FactorDescriptor } from './factors.js';
|
|
2
|
+
export declare function digestParts(parts: Array<string>): string;
|
|
3
|
+
export type VaultKeyDigestInput = {
|
|
4
|
+
ownerDID: string;
|
|
5
|
+
suite: number;
|
|
6
|
+
version: number;
|
|
7
|
+
state: string;
|
|
8
|
+
};
|
|
9
|
+
export type VaultWrappingDigestInput = {
|
|
10
|
+
wrappingID: string;
|
|
11
|
+
recipientDID: string | null;
|
|
12
|
+
iv: string;
|
|
13
|
+
wrappedKey: string;
|
|
14
|
+
factors: Array<FactorDescriptor>;
|
|
15
|
+
};
|
|
16
|
+
export type VaultEntryDigestInput = {
|
|
17
|
+
entryID: string;
|
|
18
|
+
iv: string;
|
|
19
|
+
ciphertext: string;
|
|
20
|
+
hlc: string;
|
|
21
|
+
};
|
|
22
|
+
export declare function vaultKeyDigest(key: VaultKeyDigestInput): string;
|
|
23
|
+
export declare function vaultWrappingDigest(wrapping: VaultWrappingDigestInput): string;
|
|
24
|
+
export declare function vaultEntriesDigest(entries: ReadonlyArray<VaultEntryDigestInput>): string;
|
|
25
|
+
export declare function vaultEntryDigest(entry: VaultEntryDigestInput): string;
|
|
26
|
+
/** Same canonical descriptor encoding and length framing as the wrapping digest. */
|
|
27
|
+
export declare function descriptorDigest(descriptors: Array<FactorDescriptor>): string;
|
|
28
|
+
export declare function checkDescriptorDigest(params: {
|
|
29
|
+
descriptors: Array<FactorDescriptor>;
|
|
30
|
+
expectedDescriptorDigest: string;
|
|
31
|
+
}): void;
|
package/lib/digest.js
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
import { blake3 } from '@noble/hashes/blake3.js';
|
|
2
|
+
import { fromUTF, toB64U } from '@sozai/codec';
|
|
3
|
+
import { canonicalize } from '@sozai/json';
|
|
4
|
+
import { VaultTampered } from './errors.js';
|
|
5
|
+
function descriptorJSON(descriptors) {
|
|
6
|
+
const json = canonicalize(descriptors);
|
|
7
|
+
if (json == null) throw new TypeError('Factor descriptors have no JSON representation');
|
|
8
|
+
return json;
|
|
9
|
+
}
|
|
10
|
+
export function digestParts(parts) {
|
|
11
|
+
const framed = parts.map((part)=>`${part.length}:${part}`).join('');
|
|
12
|
+
return toB64U(blake3(fromUTF(framed), {
|
|
13
|
+
dkLen: 32
|
|
14
|
+
}));
|
|
15
|
+
}
|
|
16
|
+
export function vaultKeyDigest(key) {
|
|
17
|
+
return digestParts([
|
|
18
|
+
key.ownerDID,
|
|
19
|
+
String(key.suite),
|
|
20
|
+
String(key.version),
|
|
21
|
+
key.state
|
|
22
|
+
]);
|
|
23
|
+
}
|
|
24
|
+
export function vaultWrappingDigest(wrapping) {
|
|
25
|
+
return digestParts([
|
|
26
|
+
wrapping.wrappingID,
|
|
27
|
+
wrapping.recipientDID ?? '',
|
|
28
|
+
wrapping.iv,
|
|
29
|
+
wrapping.wrappedKey,
|
|
30
|
+
descriptorJSON(wrapping.factors)
|
|
31
|
+
]);
|
|
32
|
+
}
|
|
33
|
+
export function vaultEntriesDigest(entries) {
|
|
34
|
+
const ordered = [
|
|
35
|
+
...entries
|
|
36
|
+
].sort((left, right)=>{
|
|
37
|
+
return left.entryID < right.entryID ? -1 : left.entryID > right.entryID ? 1 : 0;
|
|
38
|
+
});
|
|
39
|
+
return digestParts(ordered.flatMap((entry)=>[
|
|
40
|
+
entry.entryID,
|
|
41
|
+
entry.iv,
|
|
42
|
+
entry.ciphertext,
|
|
43
|
+
entry.hlc
|
|
44
|
+
]));
|
|
45
|
+
}
|
|
46
|
+
export function vaultEntryDigest(entry) {
|
|
47
|
+
return vaultEntriesDigest([
|
|
48
|
+
entry
|
|
49
|
+
]);
|
|
50
|
+
}
|
|
51
|
+
/** Same canonical descriptor encoding and length framing as the wrapping digest. */ export function descriptorDigest(descriptors) {
|
|
52
|
+
return digestParts([
|
|
53
|
+
descriptorJSON(descriptors)
|
|
54
|
+
]);
|
|
55
|
+
}
|
|
56
|
+
export function checkDescriptorDigest(params) {
|
|
57
|
+
if (descriptorDigest(params.descriptors) !== params.expectedDescriptorDigest) {
|
|
58
|
+
throw new VaultTampered('Vault factor descriptors differ from the trusted digest');
|
|
59
|
+
}
|
|
60
|
+
}
|
package/lib/errors.d.ts
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
export type VaultErrorCode = 'VAULT_ERROR' | 'VAULT_FACTOR_UNAVAILABLE' | 'VAULT_FACTORS_INVALID' | 'VAULT_SUITE_UNSUPPORTED' | 'VAULT_TAMPERED' | 'VAULT_SECRET_REJECTED' | 'VAULT_PIN_REJECTED';
|
|
2
|
+
export type VaultErrorOptions = ErrorOptions & {
|
|
3
|
+
code: VaultErrorCode;
|
|
4
|
+
};
|
|
5
|
+
export declare class VaultError extends Error {
|
|
6
|
+
#private;
|
|
7
|
+
constructor(message: string, options: VaultErrorOptions);
|
|
8
|
+
get code(): VaultErrorCode;
|
|
9
|
+
}
|
|
10
|
+
export declare class NoAvailableFactor extends VaultError {
|
|
11
|
+
#private;
|
|
12
|
+
constructor(kind: string);
|
|
13
|
+
get kind(): string;
|
|
14
|
+
}
|
|
15
|
+
export declare class InvalidVaultFactors extends VaultError {
|
|
16
|
+
constructor(reason: string);
|
|
17
|
+
}
|
|
18
|
+
export declare class UnsupportedVaultSuite extends VaultError {
|
|
19
|
+
#private;
|
|
20
|
+
constructor(suite: number);
|
|
21
|
+
get suite(): number;
|
|
22
|
+
}
|
|
23
|
+
export declare class VaultTampered extends VaultError {
|
|
24
|
+
constructor(message: string, options?: ErrorOptions);
|
|
25
|
+
}
|
|
26
|
+
/** Authentication failed. The original GCM error is retained as cause. */
|
|
27
|
+
export declare class VaultSecretRejected extends VaultError {
|
|
28
|
+
#private;
|
|
29
|
+
constructor(kinds: Array<string>, options?: ErrorOptions & {
|
|
30
|
+
keyID?: string;
|
|
31
|
+
code?: VaultErrorCode;
|
|
32
|
+
});
|
|
33
|
+
get kinds(): Array<string>;
|
|
34
|
+
}
|
|
35
|
+
export declare class VaultPinRejected extends VaultSecretRejected {
|
|
36
|
+
#private;
|
|
37
|
+
constructor(keyID: string, options: ErrorOptions & {
|
|
38
|
+
attemptsRemaining: number;
|
|
39
|
+
retryAfter: number;
|
|
40
|
+
});
|
|
41
|
+
get attemptsRemaining(): number;
|
|
42
|
+
get retryAfter(): number;
|
|
43
|
+
}
|
package/lib/errors.js
ADDED
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
export class VaultError extends Error {
|
|
2
|
+
#code;
|
|
3
|
+
constructor(message, options){
|
|
4
|
+
super(message, options);
|
|
5
|
+
this.name = 'VaultError';
|
|
6
|
+
this.#code = options.code;
|
|
7
|
+
}
|
|
8
|
+
get code() {
|
|
9
|
+
return this.#code;
|
|
10
|
+
}
|
|
11
|
+
}
|
|
12
|
+
export class NoAvailableFactor extends VaultError {
|
|
13
|
+
#kind;
|
|
14
|
+
constructor(kind){
|
|
15
|
+
super(`No available vault factor of kind "${kind}" on this device`, {
|
|
16
|
+
code: 'VAULT_FACTOR_UNAVAILABLE'
|
|
17
|
+
});
|
|
18
|
+
this.name = 'NoAvailableFactor';
|
|
19
|
+
this.#kind = kind;
|
|
20
|
+
}
|
|
21
|
+
get kind() {
|
|
22
|
+
return this.#kind;
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
export class InvalidVaultFactors extends VaultError {
|
|
26
|
+
constructor(reason){
|
|
27
|
+
super(`Invalid vault factor list: ${reason}`, {
|
|
28
|
+
code: 'VAULT_FACTORS_INVALID'
|
|
29
|
+
});
|
|
30
|
+
this.name = 'InvalidVaultFactors';
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
export class UnsupportedVaultSuite extends VaultError {
|
|
34
|
+
#suite;
|
|
35
|
+
constructor(suite){
|
|
36
|
+
super(`Unsupported vault suite ${suite}`, {
|
|
37
|
+
code: 'VAULT_SUITE_UNSUPPORTED'
|
|
38
|
+
});
|
|
39
|
+
this.name = 'UnsupportedVaultSuite';
|
|
40
|
+
this.#suite = suite;
|
|
41
|
+
}
|
|
42
|
+
get suite() {
|
|
43
|
+
return this.#suite;
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
export class VaultTampered extends VaultError {
|
|
47
|
+
constructor(message, options){
|
|
48
|
+
super(message, {
|
|
49
|
+
...options,
|
|
50
|
+
code: 'VAULT_TAMPERED'
|
|
51
|
+
});
|
|
52
|
+
this.name = 'VaultTampered';
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
/** Authentication failed. The original GCM error is retained as cause. */ export class VaultSecretRejected extends VaultError {
|
|
56
|
+
#kinds;
|
|
57
|
+
constructor(kinds, options){
|
|
58
|
+
const keyID = options?.keyID;
|
|
59
|
+
super(`Vault ${kinds.join(' and ')} rejected${keyID == null ? '' : ` for key ${keyID}`}. If the secret is known to be correct, the wrapping's factor descriptors or ciphertext may have been altered -- the two are indistinguishable at this point.`, {
|
|
60
|
+
...options,
|
|
61
|
+
code: options?.code ?? 'VAULT_SECRET_REJECTED'
|
|
62
|
+
});
|
|
63
|
+
this.name = 'VaultSecretRejected';
|
|
64
|
+
this.#kinds = kinds;
|
|
65
|
+
}
|
|
66
|
+
get kinds() {
|
|
67
|
+
return this.#kinds;
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
export class VaultPinRejected extends VaultSecretRejected {
|
|
71
|
+
#attemptsRemaining;
|
|
72
|
+
#retryAfter;
|
|
73
|
+
constructor(keyID, options){
|
|
74
|
+
super([
|
|
75
|
+
'pin'
|
|
76
|
+
], {
|
|
77
|
+
cause: options.cause,
|
|
78
|
+
keyID,
|
|
79
|
+
code: 'VAULT_PIN_REJECTED'
|
|
80
|
+
});
|
|
81
|
+
this.name = 'VaultPinRejected';
|
|
82
|
+
this.#attemptsRemaining = options.attemptsRemaining;
|
|
83
|
+
this.#retryAfter = options.retryAfter;
|
|
84
|
+
}
|
|
85
|
+
get attemptsRemaining() {
|
|
86
|
+
return this.#attemptsRemaining;
|
|
87
|
+
}
|
|
88
|
+
get retryAfter() {
|
|
89
|
+
return this.#retryAfter;
|
|
90
|
+
}
|
|
91
|
+
}
|
package/lib/factors.d.ts
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import type { KeyAgreementIdentity } from '@kokuin/token';
|
|
2
|
+
import type { FactorInput, FactorInputs, SecretFactorKind } from './suite.js';
|
|
3
|
+
/** Ordered public descriptors. Unknown kinds are retained for fail-closed suite dispatch. */
|
|
4
|
+
export type FactorDescriptor = {
|
|
5
|
+
kind: string;
|
|
6
|
+
params: Record<string, unknown>;
|
|
7
|
+
};
|
|
8
|
+
export declare const SECRET_FACTOR_KINDS: ReadonlyArray<SecretFactorKind>;
|
|
9
|
+
export declare function isSecretFactorKind(kind: string): kind is SecretFactorKind;
|
|
10
|
+
export declare function wrappingNamesExcludedRecipient(wrapping: {
|
|
11
|
+
recipientDID: string | null;
|
|
12
|
+
factors: ReadonlyArray<FactorDescriptor>;
|
|
13
|
+
}, excluded: ReadonlySet<string>): boolean;
|
|
14
|
+
export declare function satisfiableFactors(descriptors: Array<FactorDescriptor>, identity: KeyAgreementIdentity | null): Array<SecretFactorKind> | null;
|
|
15
|
+
export declare function factorsFromDescriptors(descriptors: Array<FactorDescriptor>, inputs?: FactorInputs): Array<FactorInput>;
|
|
16
|
+
/** Public recipient metadata uses equality form. Descriptors retain resolvable long forms. */
|
|
17
|
+
export declare function recipientDIDForFactors(factors: ReadonlyArray<FactorInput>): string | null;
|
package/lib/factors.js
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
import { normalizeDID } from '@kokuin/token';
|
|
2
|
+
import { NoAvailableFactor, VaultTampered } from './errors.js';
|
|
3
|
+
export const SECRET_FACTOR_KINDS = [
|
|
4
|
+
'passphrase',
|
|
5
|
+
'pin'
|
|
6
|
+
];
|
|
7
|
+
export function isSecretFactorKind(kind) {
|
|
8
|
+
return SECRET_FACTOR_KINDS.includes(kind);
|
|
9
|
+
}
|
|
10
|
+
export function wrappingNamesExcludedRecipient(wrapping, excluded) {
|
|
11
|
+
return [
|
|
12
|
+
wrapping.recipientDID,
|
|
13
|
+
...wrapping.factors.filter((factor)=>factor.kind === 'did').map((factor)=>factor.params.recipient)
|
|
14
|
+
].some((recipient)=>typeof recipient === 'string' && excluded.has(normalizeDID(recipient)));
|
|
15
|
+
}
|
|
16
|
+
export function satisfiableFactors(descriptors, identity) {
|
|
17
|
+
const needed = [];
|
|
18
|
+
for (const descriptor of descriptors){
|
|
19
|
+
if (isSecretFactorKind(descriptor.kind)) {
|
|
20
|
+
needed.push(descriptor.kind);
|
|
21
|
+
continue;
|
|
22
|
+
}
|
|
23
|
+
if (descriptor.kind !== 'did') return null;
|
|
24
|
+
const recipient = descriptor.params.recipient;
|
|
25
|
+
if (identity === null || typeof recipient !== 'string') return null;
|
|
26
|
+
if (normalizeDID(recipient) !== normalizeDID(identity.id)) return null;
|
|
27
|
+
}
|
|
28
|
+
return needed;
|
|
29
|
+
}
|
|
30
|
+
export function factorsFromDescriptors(descriptors, inputs) {
|
|
31
|
+
return descriptors.map((descriptor)=>{
|
|
32
|
+
if (descriptor.kind === 'did') {
|
|
33
|
+
const recipient = descriptor.params.recipient;
|
|
34
|
+
if (typeof recipient !== 'string') throw new VaultTampered('did factor descriptor carries no recipient');
|
|
35
|
+
return {
|
|
36
|
+
kind: 'did',
|
|
37
|
+
recipientDID: recipient
|
|
38
|
+
};
|
|
39
|
+
}
|
|
40
|
+
if (!isSecretFactorKind(descriptor.kind)) throw new NoAvailableFactor(descriptor.kind);
|
|
41
|
+
const input = inputs?.[descriptor.kind];
|
|
42
|
+
if (input == null) throw new NoAvailableFactor(descriptor.kind);
|
|
43
|
+
const { m, t, p } = descriptor.params;
|
|
44
|
+
const cost = typeof m === 'number' && typeof t === 'number' && typeof p === 'number' ? {
|
|
45
|
+
m,
|
|
46
|
+
t,
|
|
47
|
+
p
|
|
48
|
+
} : undefined;
|
|
49
|
+
return {
|
|
50
|
+
kind: descriptor.kind,
|
|
51
|
+
input,
|
|
52
|
+
cost
|
|
53
|
+
};
|
|
54
|
+
});
|
|
55
|
+
}
|
|
56
|
+
/** Public recipient metadata uses equality form. Descriptors retain resolvable long forms. */ export function recipientDIDForFactors(factors) {
|
|
57
|
+
const factor = factors[0];
|
|
58
|
+
return factors.length === 1 && factor?.kind === 'did' ? normalizeDID(factor.recipientDID) : null;
|
|
59
|
+
}
|
package/lib/id.d.ts
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
/** Owner binding uses the exact owner bytes; callers normalise equality DIDs before minting. */
|
|
2
|
+
export declare function createVaultKeyID(owner: string | Uint8Array, unique: Uint8Array): string;
|
|
3
|
+
/** Pair the owner commitment with the canonical unique bytes used by signed key metadata. */
|
|
4
|
+
export declare function createVaultKeyReference(owner: string, unique: Uint8Array): {
|
|
5
|
+
keyID: string;
|
|
6
|
+
keyUnique: string;
|
|
7
|
+
};
|
package/lib/id.js
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import { blake3 } from '@noble/hashes/blake3.js';
|
|
2
|
+
import { concatBytes } from '@noble/hashes/utils.js';
|
|
3
|
+
import { fromUTF, toB64U } from '@sozai/codec';
|
|
4
|
+
// Unsigned varints: namespace 0xb6, key type 31, BLAKE3 digest length 32.
|
|
5
|
+
const KEY_ID_PREFIX = new Uint8Array([
|
|
6
|
+
0xb6,
|
|
7
|
+
0x01,
|
|
8
|
+
31,
|
|
9
|
+
32
|
|
10
|
+
]);
|
|
11
|
+
/** Owner binding uses the exact owner bytes; callers normalise equality DIDs before minting. */ export function createVaultKeyID(owner, unique) {
|
|
12
|
+
const ownerBytes = typeof owner === 'string' ? fromUTF(owner) : owner;
|
|
13
|
+
const digest = blake3(concatBytes(ownerBytes, unique));
|
|
14
|
+
const bytes = concatBytes(KEY_ID_PREFIX, digest);
|
|
15
|
+
let value = 0n;
|
|
16
|
+
for (const byte of bytes)value = value << 8n | BigInt(byte);
|
|
17
|
+
return `k${value.toString(36)}`;
|
|
18
|
+
}
|
|
19
|
+
/** Pair the owner commitment with the canonical unique bytes used by signed key metadata. */ export function createVaultKeyReference(owner, unique) {
|
|
20
|
+
return {
|
|
21
|
+
keyID: createVaultKeyID(owner, unique),
|
|
22
|
+
keyUnique: toB64U(unique)
|
|
23
|
+
};
|
|
24
|
+
}
|
package/lib/index.d.ts
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
export * from './branch.js';
|
|
2
|
+
export * from './canonical-token.js';
|
|
3
|
+
export * from './digest.js';
|
|
4
|
+
export * from './errors.js';
|
|
5
|
+
export * from './factors.js';
|
|
6
|
+
export * from './id.js';
|
|
7
|
+
export * from './key-cache.js';
|
|
8
|
+
export * from './pin-throttle.js';
|
|
9
|
+
export * from './record-types.js';
|
|
10
|
+
export * from './records.js';
|
|
11
|
+
export * from './suite.js';
|
|
12
|
+
export * from './wrappable.js';
|
package/lib/index.js
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
export * from './branch.js';
|
|
2
|
+
export * from './canonical-token.js';
|
|
3
|
+
export * from './digest.js';
|
|
4
|
+
export * from './errors.js';
|
|
5
|
+
export * from './factors.js';
|
|
6
|
+
export * from './id.js';
|
|
7
|
+
export * from './key-cache.js';
|
|
8
|
+
export * from './pin-throttle.js';
|
|
9
|
+
export * from './record-types.js';
|
|
10
|
+
export * from './records.js';
|
|
11
|
+
export * from './suite.js';
|
|
12
|
+
export * from './wrappable.js';
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
export declare const DEFAULT_UNLOCK_TTL: number;
|
|
2
|
+
export type KeyCacheParams = {
|
|
3
|
+
ttl?: number;
|
|
4
|
+
now?: () => number;
|
|
5
|
+
};
|
|
6
|
+
export type KeyCache = {
|
|
7
|
+
get(keyID: string, keyVersion: number): {
|
|
8
|
+
contentKey: Uint8Array;
|
|
9
|
+
branchID: string;
|
|
10
|
+
} | null;
|
|
11
|
+
has(keyID: string, keyVersion: number): boolean;
|
|
12
|
+
set(keyID: string, contentKey: Uint8Array, keyVersion: number, branchID: string): void;
|
|
13
|
+
evictVersion(keyID: string, keyVersion: number): void;
|
|
14
|
+
evict(keyID: string): void;
|
|
15
|
+
evictAll(): void;
|
|
16
|
+
};
|
|
17
|
+
export declare function createKeyCache(params?: KeyCacheParams): KeyCache;
|
package/lib/key-cache.js
ADDED
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
export const DEFAULT_UNLOCK_TTL = 15 * 60 * 1000;
|
|
2
|
+
export function createKeyCache(params = {}) {
|
|
3
|
+
const ttl = params.ttl ?? DEFAULT_UNLOCK_TTL;
|
|
4
|
+
const now = params.now ?? Date.now;
|
|
5
|
+
const entries = new Map();
|
|
6
|
+
function evict(keyID) {
|
|
7
|
+
const versions = entries.get(keyID);
|
|
8
|
+
if (versions == null) return;
|
|
9
|
+
for (const cached of versions.values())cached.contentKey.fill(0);
|
|
10
|
+
entries.delete(keyID);
|
|
11
|
+
}
|
|
12
|
+
function evictVersion(keyID, keyVersion) {
|
|
13
|
+
const versions = entries.get(keyID);
|
|
14
|
+
const cached = versions?.get(keyVersion);
|
|
15
|
+
if (cached == null) return;
|
|
16
|
+
cached.contentKey.fill(0);
|
|
17
|
+
versions?.delete(keyVersion);
|
|
18
|
+
if (versions?.size === 0) entries.delete(keyID);
|
|
19
|
+
}
|
|
20
|
+
function live(keyID, keyVersion) {
|
|
21
|
+
const cached = entries.get(keyID)?.get(keyVersion);
|
|
22
|
+
if (cached == null) {
|
|
23
|
+
return null;
|
|
24
|
+
}
|
|
25
|
+
if (now() - cached.unlockedAt >= ttl) {
|
|
26
|
+
evictVersion(keyID, keyVersion);
|
|
27
|
+
return null;
|
|
28
|
+
}
|
|
29
|
+
return cached;
|
|
30
|
+
}
|
|
31
|
+
return {
|
|
32
|
+
get (keyID, keyVersion) {
|
|
33
|
+
const cached = live(keyID, keyVersion);
|
|
34
|
+
if (cached == null) {
|
|
35
|
+
return null;
|
|
36
|
+
}
|
|
37
|
+
return {
|
|
38
|
+
contentKey: cached.contentKey.slice(),
|
|
39
|
+
branchID: cached.branchID
|
|
40
|
+
};
|
|
41
|
+
},
|
|
42
|
+
has (keyID, keyVersion) {
|
|
43
|
+
return live(keyID, keyVersion) != null;
|
|
44
|
+
},
|
|
45
|
+
set (keyID, contentKey, keyVersion, branchID) {
|
|
46
|
+
evictVersion(keyID, keyVersion);
|
|
47
|
+
const versions = entries.get(keyID) ?? new Map();
|
|
48
|
+
versions.set(keyVersion, {
|
|
49
|
+
contentKey: contentKey.slice(),
|
|
50
|
+
branchID,
|
|
51
|
+
unlockedAt: now()
|
|
52
|
+
});
|
|
53
|
+
entries.set(keyID, versions);
|
|
54
|
+
},
|
|
55
|
+
evict,
|
|
56
|
+
evictVersion,
|
|
57
|
+
evictAll () {
|
|
58
|
+
for (const keyID of [
|
|
59
|
+
...entries.keys()
|
|
60
|
+
]){
|
|
61
|
+
evict(keyID);
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
};
|
|
65
|
+
}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
export declare const DEFAULT_FREE_ATTEMPTS = 3;
|
|
2
|
+
export declare const DEFAULT_BASE_DELAY = 1000;
|
|
3
|
+
export declare const DEFAULT_MAX_DELAY: number;
|
|
4
|
+
export type PinThrottleParams = {
|
|
5
|
+
freeAttempts?: number;
|
|
6
|
+
baseDelay?: number;
|
|
7
|
+
maxDelay?: number;
|
|
8
|
+
now?: () => number;
|
|
9
|
+
};
|
|
10
|
+
export type PinThrottle = {
|
|
11
|
+
retryAfter(keyID: string): number;
|
|
12
|
+
attemptsRemaining(keyID: string): number;
|
|
13
|
+
recordFailure(keyID: string): void;
|
|
14
|
+
recordSuccess(keyID: string): void;
|
|
15
|
+
};
|
|
16
|
+
export declare function createPinThrottle(params?: PinThrottleParams): PinThrottle;
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
export const DEFAULT_FREE_ATTEMPTS = 3;
|
|
2
|
+
export const DEFAULT_BASE_DELAY = 1000;
|
|
3
|
+
export const DEFAULT_MAX_DELAY = 15 * 60 * 1000;
|
|
4
|
+
export function createPinThrottle(params = {}) {
|
|
5
|
+
const freeAttempts = params.freeAttempts ?? DEFAULT_FREE_ATTEMPTS;
|
|
6
|
+
const baseDelay = params.baseDelay ?? DEFAULT_BASE_DELAY;
|
|
7
|
+
const maxDelay = params.maxDelay ?? DEFAULT_MAX_DELAY;
|
|
8
|
+
const now = params.now ?? Date.now;
|
|
9
|
+
const attempts = new Map();
|
|
10
|
+
function delayAfter(failures) {
|
|
11
|
+
if (failures < freeAttempts) {
|
|
12
|
+
return 0;
|
|
13
|
+
}
|
|
14
|
+
return Math.min(baseDelay * 2 ** (failures - freeAttempts), maxDelay);
|
|
15
|
+
}
|
|
16
|
+
return {
|
|
17
|
+
retryAfter (keyID) {
|
|
18
|
+
const record = attempts.get(keyID);
|
|
19
|
+
if (record == null) {
|
|
20
|
+
return 0;
|
|
21
|
+
}
|
|
22
|
+
const elapsed = now() - record.lastFailureAt;
|
|
23
|
+
return Math.max(0, delayAfter(record.failures) - elapsed);
|
|
24
|
+
},
|
|
25
|
+
attemptsRemaining (keyID) {
|
|
26
|
+
const record = attempts.get(keyID);
|
|
27
|
+
return Math.max(0, freeAttempts - (record?.failures ?? 0));
|
|
28
|
+
},
|
|
29
|
+
recordFailure (keyID) {
|
|
30
|
+
const record = attempts.get(keyID);
|
|
31
|
+
attempts.set(keyID, {
|
|
32
|
+
failures: (record?.failures ?? 0) + 1,
|
|
33
|
+
lastFailureAt: now()
|
|
34
|
+
});
|
|
35
|
+
},
|
|
36
|
+
recordSuccess (keyID) {
|
|
37
|
+
attempts.delete(keyID);
|
|
38
|
+
}
|
|
39
|
+
};
|
|
40
|
+
}
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import type { RecordKey, RecordStoreAdapter, RecordTypeDefinition, SignedRecord, VerifiedRecordOp, VisibilityContext } from '@kokuin/records';
|
|
2
|
+
import type { MethodRegistry } from '@kokuin/token';
|
|
3
|
+
export type CredentialRecordReadPort = Pick<RecordStoreAdapter, 'get' | 'getMany' | 'list'>;
|
|
4
|
+
export type CredentialAuthorityRequest = {
|
|
5
|
+
source: 'record';
|
|
6
|
+
op: VerifiedRecordOp;
|
|
7
|
+
owner: string;
|
|
8
|
+
issuer: string;
|
|
9
|
+
verb: 'read' | 'administer';
|
|
10
|
+
recordKey: RecordKey;
|
|
11
|
+
transportContext: unknown;
|
|
12
|
+
record: SignedRecord;
|
|
13
|
+
store: CredentialRecordReadPort;
|
|
14
|
+
};
|
|
15
|
+
export type CredentialAuthority = {
|
|
16
|
+
authorize(request: CredentialAuthorityRequest): Promise<boolean>;
|
|
17
|
+
};
|
|
18
|
+
export type VaultKeyAddress = {
|
|
19
|
+
ownerDID: string;
|
|
20
|
+
keyID: string;
|
|
21
|
+
};
|
|
22
|
+
export type VaultRecordPorts = {
|
|
23
|
+
retainEntryCandidate(record: SignedRecord): Promise<void>;
|
|
24
|
+
listRevocations(address: VaultKeyAddress): Promise<Array<string>>;
|
|
25
|
+
dropRevokedWrappings(address: VaultKeyAddress): Promise<void>;
|
|
26
|
+
};
|
|
27
|
+
export type VaultRecordHooks = {
|
|
28
|
+
authority: CredentialAuthority;
|
|
29
|
+
validateConsumerMetadata(value: unknown, request: CredentialAuthorityRequest): Promise<boolean>;
|
|
30
|
+
/** Must resolve ports bound to this adapter's transaction, including routed adapters. */
|
|
31
|
+
portsFor(store: RecordStoreAdapter): VaultRecordPorts;
|
|
32
|
+
};
|
|
33
|
+
export type VaultRecordTypeParams = VaultRecordHooks & {
|
|
34
|
+
opKind: string;
|
|
35
|
+
methods?: MethodRegistry;
|
|
36
|
+
};
|
|
37
|
+
/** One explicit replay domain and consumer policy for the five generic record types. */
|
|
38
|
+
export declare function vaultRecordTypes(params: VaultRecordTypeParams): Map<string, RecordTypeDefinition>;
|
|
39
|
+
/** Only wrappings can prove key holding, regardless of other records' metadata. */
|
|
40
|
+
export declare function vaultHolderTypes(types: ReadonlyMap<string, RecordTypeDefinition>): ReadonlyMap<string, RecordTypeDefinition>;
|
|
41
|
+
/** Read a live, owner-qualified key version in the explicit replay domain. */
|
|
42
|
+
export declare function vaultKeyVersionReader(store: RecordStoreAdapter, params: Pick<VaultRecordTypeParams, 'opKind' | 'methods'>): VisibilityContext['currentKeyVersion'];
|
|
43
|
+
/** Proofs retain consumer authority checks but are never addressed to the local receiver. */
|
|
44
|
+
export declare function vaultProofAuthorizer(params: VaultRecordTypeParams, store: RecordStoreAdapter, transportContext?: unknown): VisibilityContext['authorizeProof'];
|