@drakkar.software/starfish-client 3.0.0-alpha.16 → 3.0.0-alpha.18
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/dist/append.d.ts +50 -0
- package/dist/bindings/broadcast.d.ts +19 -0
- package/dist/bindings/broadcast.js +65 -0
- package/dist/bindings/react.d.ts +12 -0
- package/dist/bindings/react.js +25 -0
- package/dist/client.js +37 -316
- package/dist/crypto.js +49 -0
- package/dist/entitlements.js +41 -0
- package/dist/group-crypto.d.ts +111 -0
- package/dist/group-crypto.js +205 -0
- package/dist/group-crypto.js.map +7 -0
- package/dist/identity.d.ts +82 -4
- package/dist/identity.js +354 -2
- package/dist/identity.js.map +4 -4
- package/dist/mobile-lifecycle.js +2 -41
- package/dist/polling.js +2 -2
- package/dist/sync.js +14 -68
- package/package.json +2 -2
- package/dist/_crypto_helpers.d.ts +0 -4
- package/dist/append-log.js +0 -267
- package/dist/cap-mint.d.ts +0 -20
- package/dist/cap-mint.js +0 -12
- package/dist/cap-mint.js.map +0 -7
- package/dist/directory.d.ts +0 -9
- package/dist/directory.js +0 -24
- package/dist/directory.js.map +0 -7
- package/dist/keyring.d.ts +0 -6
- package/dist/keyring.js +0 -26
- package/dist/keyring.js.map +0 -7
- package/dist/pairing.d.ts +0 -6
- package/dist/pairing.js +0 -26
- package/dist/pairing.js.map +0 -7
- package/dist/recipients.d.ts +0 -6
- package/dist/recipients.js +0 -16
- package/dist/recipients.js.map +0 -7
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import { StarfishHttpError } from "./types.js";
|
|
2
|
+
/**
|
|
3
|
+
* Fetches the list of feature slugs from a user's entitlement document.
|
|
4
|
+
*
|
|
5
|
+
* Returns an empty array if the document does not exist yet or the features
|
|
6
|
+
* field is absent — so callers never need to handle a 404.
|
|
7
|
+
*
|
|
8
|
+
* ```ts
|
|
9
|
+
* import { pullEntitlements } from "@drakkar.software/starfish-client"
|
|
10
|
+
*
|
|
11
|
+
* const features = await pullEntitlements(client, userId)
|
|
12
|
+
* // e.g. ["premium-package-1", "paid-cloud-sync"]
|
|
13
|
+
*
|
|
14
|
+
* if (features.includes("paid-cloud-sync")) {
|
|
15
|
+
* // unlock cloud sync UI
|
|
16
|
+
* }
|
|
17
|
+
* ```
|
|
18
|
+
*
|
|
19
|
+
* The path template must match the server-side collection's `storagePath`.
|
|
20
|
+
* With the recommended default config:
|
|
21
|
+
* ```ts
|
|
22
|
+
* { storagePath: "users/{identity}/entitlements" }
|
|
23
|
+
* // → path: "/pull/users/{userId}/entitlements" (default)
|
|
24
|
+
* ```
|
|
25
|
+
*/
|
|
26
|
+
export async function pullEntitlements(client, userId, opts) {
|
|
27
|
+
const path = (opts?.path ?? "/pull/users/{userId}/entitlements").replace("{userId}", userId);
|
|
28
|
+
const field = opts?.field ?? "features";
|
|
29
|
+
try {
|
|
30
|
+
const result = await client.pull(path);
|
|
31
|
+
const list = result.data?.[field];
|
|
32
|
+
if (!Array.isArray(list))
|
|
33
|
+
return [];
|
|
34
|
+
return list.filter((s) => typeof s === "string");
|
|
35
|
+
}
|
|
36
|
+
catch (err) {
|
|
37
|
+
if (err instanceof StarfishHttpError && err.status === 404)
|
|
38
|
+
return [];
|
|
39
|
+
throw err;
|
|
40
|
+
}
|
|
41
|
+
}
|
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Group encryption utilities for Starfish.
|
|
3
|
+
*
|
|
4
|
+
* Enables multiple users to share a common encrypted collection without sharing
|
|
5
|
+
* a passphrase. Each member holds their own credentials; a Group Encryption Key
|
|
6
|
+
* (GEK) is distributed per-member using X25519 ECDH key agreement.
|
|
7
|
+
*
|
|
8
|
+
* Typical flow:
|
|
9
|
+
* 1. Each user calls `deriveCredentials(passphrase)` — now includes groupPublicKey / groupPrivateKey.
|
|
10
|
+
* 2. Admin calls `createGroupKeyring(...)` to create a keyring document.
|
|
11
|
+
* 3. Members call `createGroupEncryptor(keyringData, myIdentity, myPrivateKey)` to get an Encryptor.
|
|
12
|
+
* 4. The Encryptor is passed to SyncManager via the `encryptor` option.
|
|
13
|
+
*/
|
|
14
|
+
import type { Encryptor } from "./crypto.js";
|
|
15
|
+
/** An ECDH key pair used for group encryption. Hex-encoded for easy serialization. */
|
|
16
|
+
export interface GroupKeyPair {
|
|
17
|
+
/** Hex-encoded X25519 private key (32 bytes). Keep secret — never store on server. */
|
|
18
|
+
privateKey: string;
|
|
19
|
+
/** Hex-encoded X25519 public key (32 bytes). Safe to publish. */
|
|
20
|
+
publicKey: string;
|
|
21
|
+
}
|
|
22
|
+
/** One epoch's wrapped keys: each member's GEK encrypted to their public key. */
|
|
23
|
+
export interface EpochKeyring {
|
|
24
|
+
/** The admin's hex-encoded X25519 public key (used for ECDH by members). */
|
|
25
|
+
adminPublicKey: string;
|
|
26
|
+
/** Map from member identity (userId) → base64(IV || AES-GCM(GEK)) */
|
|
27
|
+
wrappedKeys: Record<string, string>;
|
|
28
|
+
}
|
|
29
|
+
/** The full keyring document stored in a Starfish collection. Push this with any SyncManager. */
|
|
30
|
+
export interface GroupKeyring {
|
|
31
|
+
/** The epoch number currently used for new encryptions. */
|
|
32
|
+
currentEpoch: number;
|
|
33
|
+
/** All epochs. Members unwrap the GEK for whichever epoch a document was encrypted with. */
|
|
34
|
+
epochs: Record<string, EpochKeyring>;
|
|
35
|
+
}
|
|
36
|
+
/**
|
|
37
|
+
* Derives a deterministic X25519 key pair from a passphrase + userId.
|
|
38
|
+
*
|
|
39
|
+
* The derivation uses SHA-256 with a fixed domain separator so it is distinct
|
|
40
|
+
* from the auth token and encryption key derivations. Same passphrase + userId
|
|
41
|
+
* always produces the same key pair on any device (stateless).
|
|
42
|
+
*/
|
|
43
|
+
export declare function deriveGroupKeyPair(passphrase: string, userId: string): Promise<GroupKeyPair>;
|
|
44
|
+
/** Generates a random 256-bit Group Encryption Key as a hex string. */
|
|
45
|
+
export declare function generateGroupKey(): string;
|
|
46
|
+
/**
|
|
47
|
+
* Wraps a GEK for a specific member using ECDH key agreement.
|
|
48
|
+
*
|
|
49
|
+
* The wrapper (admin) and member each have an X25519 key pair. ECDH between
|
|
50
|
+
* `wrapperPrivateKey` and `memberPublicKey` produces a shared secret, which is
|
|
51
|
+
* used to derive an AES-256-GCM key that encrypts the GEK.
|
|
52
|
+
*
|
|
53
|
+
* @returns base64(IV || AES-GCM-ciphertext)
|
|
54
|
+
*/
|
|
55
|
+
export declare function wrapGroupKey(gek: string, memberPublicKey: string, wrapperPrivateKey: string): Promise<string>;
|
|
56
|
+
/**
|
|
57
|
+
* Unwraps a GEK using the member's own private key and the admin's public key.
|
|
58
|
+
*
|
|
59
|
+
* ECDH between `memberPrivateKey` and `adminPublicKey` yields the same shared
|
|
60
|
+
* secret as the wrapping step, so the same AES key is derived and the GEK is
|
|
61
|
+
* recovered.
|
|
62
|
+
*
|
|
63
|
+
* @returns GEK as a hex string
|
|
64
|
+
*/
|
|
65
|
+
export declare function unwrapGroupKey(wrapped: string, memberPrivateKey: string, adminPublicKey: string): Promise<string>;
|
|
66
|
+
/**
|
|
67
|
+
* Creates a new group keyring document with epoch 1.
|
|
68
|
+
*
|
|
69
|
+
* @param adminKeyPair The admin's key pair (from `deriveGroupKeyPair` or `deriveCredentials`)
|
|
70
|
+
* @param members Map from member identity (userId) → hex public key
|
|
71
|
+
* @param gek Optional GEK to use; generated randomly if omitted
|
|
72
|
+
* @returns The keyring document and the raw GEK (admin keeps the GEK to add future members)
|
|
73
|
+
*/
|
|
74
|
+
export declare function createGroupKeyring(adminKeyPair: GroupKeyPair, members: Record<string, string>, gek?: string): Promise<{
|
|
75
|
+
keyring: GroupKeyring;
|
|
76
|
+
gek: string;
|
|
77
|
+
}>;
|
|
78
|
+
/**
|
|
79
|
+
* Adds a new member to the current epoch of an existing keyring.
|
|
80
|
+
*
|
|
81
|
+
* The admin supplies the current GEK (returned by `createGroupKeyring` or
|
|
82
|
+
* `rotateGroupKey`) and their key pair to wrap it for the new member.
|
|
83
|
+
* This does NOT rotate the GEK — the new member can read all existing
|
|
84
|
+
* documents encrypted with the current epoch key.
|
|
85
|
+
*
|
|
86
|
+
* Only the admin (whose `publicKey` matches `epochKeyring.adminPublicKey`) can
|
|
87
|
+
* add members, because all wrapped entries must use the same ECDH key pair.
|
|
88
|
+
*/
|
|
89
|
+
export declare function addGroupMember(keyring: GroupKeyring, adminKeyPair: GroupKeyPair, currentGek: string, newMemberId: string, newMemberPublicKey: string): Promise<GroupKeyring>;
|
|
90
|
+
/**
|
|
91
|
+
* Rotates the group key, creating a new epoch.
|
|
92
|
+
*
|
|
93
|
+
* Used when removing a member. The removed member retains their old epoch key
|
|
94
|
+
* (and can still read old documents), but cannot read new documents.
|
|
95
|
+
*
|
|
96
|
+
* @param remainingMembers Map from identity → hex public key for members who keep access
|
|
97
|
+
*/
|
|
98
|
+
export declare function rotateGroupKey(keyring: GroupKeyring, adminKeyPair: GroupKeyPair, remainingMembers: Record<string, string>, newGek?: string): Promise<{
|
|
99
|
+
keyring: GroupKeyring;
|
|
100
|
+
gek: string;
|
|
101
|
+
}>;
|
|
102
|
+
/**
|
|
103
|
+
* Creates an Encryptor that can decrypt any epoch and encrypts with the current epoch.
|
|
104
|
+
*
|
|
105
|
+
* Wire format: `{ _encrypted: "base64(IV || ciphertext)", _epoch: N }`
|
|
106
|
+
*
|
|
107
|
+
* @param keyring The keyring document fetched from Starfish
|
|
108
|
+
* @param myIdentity The caller's userId (to locate their wrapped key in each epoch)
|
|
109
|
+
* @param myPrivateKey The caller's hex-encoded X25519 private key
|
|
110
|
+
*/
|
|
111
|
+
export declare function createGroupEncryptor(keyring: GroupKeyring, myIdentity: string, myPrivateKey: string): Promise<Encryptor>;
|
|
@@ -0,0 +1,205 @@
|
|
|
1
|
+
// src/group-crypto.ts
|
|
2
|
+
import { x25519 } from "@noble/curves/ed25519.js";
|
|
3
|
+
import { getCrypto as getCrypto2, getBase64 as getBase642, IV_BYTES as IV_BYTES2, deriveKey as deriveKey2 } from "@drakkar.software/starfish-protocol";
|
|
4
|
+
|
|
5
|
+
// src/crypto.ts
|
|
6
|
+
import { getCrypto, getBase64, IV_BYTES, ENCRYPTED_KEY, deriveKey } from "@drakkar.software/starfish-protocol";
|
|
7
|
+
var ALGO = "AES-GCM";
|
|
8
|
+
function createEncryptor(secret, salt, info = "starfish-e2e") {
|
|
9
|
+
if (!secret) throw new Error("encryptionSecret must not be empty");
|
|
10
|
+
if (!salt) throw new Error("encryptionSalt must not be empty");
|
|
11
|
+
const keyPromise = deriveKey(secret, salt, info);
|
|
12
|
+
return {
|
|
13
|
+
async encrypt(data) {
|
|
14
|
+
const key = await keyPromise;
|
|
15
|
+
const c = getCrypto();
|
|
16
|
+
const b64 = getBase64();
|
|
17
|
+
const plaintext = new TextEncoder().encode(JSON.stringify(data));
|
|
18
|
+
const iv = c.getRandomValues(new Uint8Array(IV_BYTES));
|
|
19
|
+
const ciphertext = await c.subtle.encrypt({ name: ALGO, iv }, key, plaintext);
|
|
20
|
+
const combined = new Uint8Array(iv.length + ciphertext.byteLength);
|
|
21
|
+
combined.set(iv);
|
|
22
|
+
combined.set(new Uint8Array(ciphertext), iv.length);
|
|
23
|
+
return { [ENCRYPTED_KEY]: b64.encode(combined) };
|
|
24
|
+
},
|
|
25
|
+
async decrypt(wrapper) {
|
|
26
|
+
const encoded = wrapper[ENCRYPTED_KEY];
|
|
27
|
+
if (typeof encoded !== "string") {
|
|
28
|
+
throw new Error("Expected encrypted data but received unencrypted document");
|
|
29
|
+
}
|
|
30
|
+
const key = await keyPromise;
|
|
31
|
+
const c = getCrypto();
|
|
32
|
+
const b64 = getBase64();
|
|
33
|
+
const combined = b64.decode(encoded);
|
|
34
|
+
if (combined.length < IV_BYTES) {
|
|
35
|
+
throw new Error("Encrypted data is too short");
|
|
36
|
+
}
|
|
37
|
+
const iv = combined.slice(0, IV_BYTES);
|
|
38
|
+
const ciphertext = combined.slice(IV_BYTES);
|
|
39
|
+
try {
|
|
40
|
+
const plaintext = await c.subtle.decrypt({ name: ALGO, iv }, key, ciphertext);
|
|
41
|
+
return JSON.parse(new TextDecoder().decode(plaintext));
|
|
42
|
+
} catch (err) {
|
|
43
|
+
throw new Error("Decryption failed: data may be tampered or key is incorrect", { cause: err });
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
};
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
// src/group-crypto.ts
|
|
50
|
+
function bytesToHex(bytes) {
|
|
51
|
+
return Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("");
|
|
52
|
+
}
|
|
53
|
+
function hexToBytes(hex) {
|
|
54
|
+
const bytes = new Uint8Array(hex.length / 2);
|
|
55
|
+
for (let i = 0; i < bytes.length; i++) {
|
|
56
|
+
bytes[i] = parseInt(hex.slice(i * 2, i * 2 + 2), 16);
|
|
57
|
+
}
|
|
58
|
+
return bytes;
|
|
59
|
+
}
|
|
60
|
+
var ALGO2 = "AES-GCM";
|
|
61
|
+
var GROUP_WRAP_SALT = "starfish-group-wrap";
|
|
62
|
+
var GROUP_WRAP_INFO = "starfish-group-wrap";
|
|
63
|
+
var GROUP_ECDH_DOMAIN = "starfish-group-ecdh";
|
|
64
|
+
var GROUP_DATA_INFO = "starfish-group";
|
|
65
|
+
var GEK_BYTES = 32;
|
|
66
|
+
async function deriveGroupKeyPair(passphrase, userId) {
|
|
67
|
+
const c = getCrypto2();
|
|
68
|
+
const enc = new TextEncoder();
|
|
69
|
+
const input = enc.encode(`${passphrase}:${userId}:${GROUP_ECDH_DOMAIN}`);
|
|
70
|
+
const hash = await c.subtle.digest("SHA-256", input);
|
|
71
|
+
const privateKeyBytes = new Uint8Array(hash);
|
|
72
|
+
const publicKeyBytes = x25519.getPublicKey(privateKeyBytes);
|
|
73
|
+
return { privateKey: bytesToHex(privateKeyBytes), publicKey: bytesToHex(publicKeyBytes) };
|
|
74
|
+
}
|
|
75
|
+
function generateGroupKey() {
|
|
76
|
+
const c = getCrypto2();
|
|
77
|
+
return bytesToHex(c.getRandomValues(new Uint8Array(GEK_BYTES)));
|
|
78
|
+
}
|
|
79
|
+
async function wrapGroupKey(gek, memberPublicKey, wrapperPrivateKey) {
|
|
80
|
+
const sharedSecret = x25519.getSharedSecret(hexToBytes(wrapperPrivateKey), hexToBytes(memberPublicKey));
|
|
81
|
+
const wrappingKey = await deriveKey2(bytesToHex(sharedSecret), GROUP_WRAP_SALT, GROUP_WRAP_INFO);
|
|
82
|
+
const c = getCrypto2();
|
|
83
|
+
const b64 = getBase642();
|
|
84
|
+
const iv = c.getRandomValues(new Uint8Array(IV_BYTES2));
|
|
85
|
+
const encrypted = await c.subtle.encrypt({ name: ALGO2, iv }, wrappingKey, hexToBytes(gek).buffer);
|
|
86
|
+
const combined = new Uint8Array(IV_BYTES2 + encrypted.byteLength);
|
|
87
|
+
combined.set(iv);
|
|
88
|
+
combined.set(new Uint8Array(encrypted), IV_BYTES2);
|
|
89
|
+
return b64.encode(combined);
|
|
90
|
+
}
|
|
91
|
+
async function unwrapGroupKey(wrapped, memberPrivateKey, adminPublicKey) {
|
|
92
|
+
const sharedSecret = x25519.getSharedSecret(hexToBytes(memberPrivateKey), hexToBytes(adminPublicKey));
|
|
93
|
+
const wrappingKey = await deriveKey2(bytesToHex(sharedSecret), GROUP_WRAP_SALT, GROUP_WRAP_INFO);
|
|
94
|
+
const b64 = getBase642();
|
|
95
|
+
const c = getCrypto2();
|
|
96
|
+
const combined = b64.decode(wrapped);
|
|
97
|
+
const iv = combined.slice(0, IV_BYTES2);
|
|
98
|
+
const ciphertext = combined.slice(IV_BYTES2);
|
|
99
|
+
try {
|
|
100
|
+
const decrypted = await c.subtle.decrypt({ name: ALGO2, iv }, wrappingKey, ciphertext);
|
|
101
|
+
return bytesToHex(new Uint8Array(decrypted));
|
|
102
|
+
} catch {
|
|
103
|
+
throw new Error("Failed to unwrap group key: decryption failed (wrong keys or corrupted data)");
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
async function createGroupKeyring(adminKeyPair, members, gek) {
|
|
107
|
+
const resolvedGek = gek ?? generateGroupKey();
|
|
108
|
+
const wrappedKeys = {};
|
|
109
|
+
for (const [memberId, memberPublicKey] of Object.entries(members)) {
|
|
110
|
+
wrappedKeys[memberId] = await wrapGroupKey(resolvedGek, memberPublicKey, adminKeyPair.privateKey);
|
|
111
|
+
}
|
|
112
|
+
const keyring = {
|
|
113
|
+
currentEpoch: 1,
|
|
114
|
+
epochs: {
|
|
115
|
+
"1": { adminPublicKey: adminKeyPair.publicKey, wrappedKeys }
|
|
116
|
+
}
|
|
117
|
+
};
|
|
118
|
+
return { keyring, gek: resolvedGek };
|
|
119
|
+
}
|
|
120
|
+
async function addGroupMember(keyring, adminKeyPair, currentGek, newMemberId, newMemberPublicKey) {
|
|
121
|
+
const epochKey = String(keyring.currentEpoch);
|
|
122
|
+
const epochKeyring = keyring.epochs[epochKey];
|
|
123
|
+
if (!epochKeyring) throw new Error(`Epoch ${keyring.currentEpoch} not found in keyring`);
|
|
124
|
+
if (epochKeyring.adminPublicKey !== adminKeyPair.publicKey) {
|
|
125
|
+
throw new Error(`Provided key pair does not match the admin public key stored in epoch ${keyring.currentEpoch}`);
|
|
126
|
+
}
|
|
127
|
+
const wrapped = await wrapGroupKey(currentGek, newMemberPublicKey, adminKeyPair.privateKey);
|
|
128
|
+
return {
|
|
129
|
+
...keyring,
|
|
130
|
+
epochs: {
|
|
131
|
+
...keyring.epochs,
|
|
132
|
+
[epochKey]: {
|
|
133
|
+
...epochKeyring,
|
|
134
|
+
wrappedKeys: { ...epochKeyring.wrappedKeys, [newMemberId]: wrapped }
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
};
|
|
138
|
+
}
|
|
139
|
+
async function rotateGroupKey(keyring, adminKeyPair, remainingMembers, newGek) {
|
|
140
|
+
const epochKey = String(keyring.currentEpoch);
|
|
141
|
+
const epochKeyring = keyring.epochs[epochKey];
|
|
142
|
+
if (epochKeyring && epochKeyring.adminPublicKey !== adminKeyPair.publicKey) {
|
|
143
|
+
throw new Error(
|
|
144
|
+
`Provided key pair does not match the admin public key stored in epoch ${keyring.currentEpoch}`
|
|
145
|
+
);
|
|
146
|
+
}
|
|
147
|
+
const resolvedGek = newGek ?? generateGroupKey();
|
|
148
|
+
const newEpoch = keyring.currentEpoch + 1;
|
|
149
|
+
const wrappedKeys = {};
|
|
150
|
+
for (const [memberId, memberPublicKey] of Object.entries(remainingMembers)) {
|
|
151
|
+
wrappedKeys[memberId] = await wrapGroupKey(resolvedGek, memberPublicKey, adminKeyPair.privateKey);
|
|
152
|
+
}
|
|
153
|
+
const newKeyring = {
|
|
154
|
+
currentEpoch: newEpoch,
|
|
155
|
+
epochs: {
|
|
156
|
+
...keyring.epochs,
|
|
157
|
+
[String(newEpoch)]: { adminPublicKey: adminKeyPair.publicKey, wrappedKeys }
|
|
158
|
+
}
|
|
159
|
+
};
|
|
160
|
+
return { keyring: newKeyring, gek: resolvedGek };
|
|
161
|
+
}
|
|
162
|
+
async function createGroupEncryptor(keyring, myIdentity, myPrivateKey) {
|
|
163
|
+
const epochEncryptors = /* @__PURE__ */ new Map();
|
|
164
|
+
for (const [epochStr, epochKeyring] of Object.entries(keyring.epochs)) {
|
|
165
|
+
const epoch = parseInt(epochStr, 10);
|
|
166
|
+
const wrapped = epochKeyring.wrappedKeys[myIdentity];
|
|
167
|
+
if (!wrapped) continue;
|
|
168
|
+
const gek = await unwrapGroupKey(wrapped, myPrivateKey, epochKeyring.adminPublicKey);
|
|
169
|
+
epochEncryptors.set(epoch, createEncryptor(gek, `epoch-${epoch}`, GROUP_DATA_INFO));
|
|
170
|
+
}
|
|
171
|
+
const currentEpoch = keyring.currentEpoch;
|
|
172
|
+
const currentEncryptor = epochEncryptors.get(currentEpoch);
|
|
173
|
+
if (!currentEncryptor) {
|
|
174
|
+
throw new Error(
|
|
175
|
+
`No wrapped key found for identity "${myIdentity}" in epoch ${currentEpoch}. Ensure the admin has added this member to the keyring.`
|
|
176
|
+
);
|
|
177
|
+
}
|
|
178
|
+
return {
|
|
179
|
+
async encrypt(data) {
|
|
180
|
+
const encrypted = await currentEncryptor.encrypt(data);
|
|
181
|
+
return { ...encrypted, _epoch: currentEpoch };
|
|
182
|
+
},
|
|
183
|
+
async decrypt(wrapper) {
|
|
184
|
+
const epoch = typeof wrapper._epoch === "number" ? wrapper._epoch : currentEpoch;
|
|
185
|
+
const encryptor = epochEncryptors.get(epoch);
|
|
186
|
+
if (!encryptor) {
|
|
187
|
+
throw new Error(
|
|
188
|
+
`No key available for epoch ${epoch}. This document was encrypted in a different epoch. Ensure your keyring is up to date.`
|
|
189
|
+
);
|
|
190
|
+
}
|
|
191
|
+
return encryptor.decrypt(wrapper);
|
|
192
|
+
}
|
|
193
|
+
};
|
|
194
|
+
}
|
|
195
|
+
export {
|
|
196
|
+
addGroupMember,
|
|
197
|
+
createGroupEncryptor,
|
|
198
|
+
createGroupKeyring,
|
|
199
|
+
deriveGroupKeyPair,
|
|
200
|
+
generateGroupKey,
|
|
201
|
+
rotateGroupKey,
|
|
202
|
+
unwrapGroupKey,
|
|
203
|
+
wrapGroupKey
|
|
204
|
+
};
|
|
205
|
+
//# sourceMappingURL=group-crypto.js.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../src/group-crypto.ts", "../src/crypto.ts"],
|
|
4
|
+
"sourcesContent": ["/**\n * Group encryption utilities for Starfish.\n *\n * Enables multiple users to share a common encrypted collection without sharing\n * a passphrase. Each member holds their own credentials; a Group Encryption Key\n * (GEK) is distributed per-member using X25519 ECDH key agreement.\n *\n * Typical flow:\n * 1. Each user calls `deriveCredentials(passphrase)` \u2014 now includes groupPublicKey / groupPrivateKey.\n * 2. Admin calls `createGroupKeyring(...)` to create a keyring document.\n * 3. Members call `createGroupEncryptor(keyringData, myIdentity, myPrivateKey)` to get an Encryptor.\n * 4. The Encryptor is passed to SyncManager via the `encryptor` option.\n */\n\nimport { x25519 } from \"@noble/curves/ed25519.js\"\nimport { getCrypto, getBase64, IV_BYTES, deriveKey } from \"@drakkar.software/starfish-protocol\"\nimport type { Encryptor } from \"./crypto.js\"\nimport { createEncryptor } from \"./crypto.js\"\n\n// \u2500\u2500 Internal helpers \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nfunction bytesToHex(bytes: Uint8Array): string {\n return Array.from(bytes, (b) => b.toString(16).padStart(2, \"0\")).join(\"\")\n}\n\nfunction hexToBytes(hex: string): Uint8Array {\n const bytes = new Uint8Array(hex.length / 2)\n for (let i = 0; i < bytes.length; i++) {\n bytes[i] = parseInt(hex.slice(i * 2, i * 2 + 2), 16)\n }\n return bytes\n}\n\nconst ALGO = \"AES-GCM\"\nconst GROUP_WRAP_SALT = \"starfish-group-wrap\"\nconst GROUP_WRAP_INFO = \"starfish-group-wrap\"\nconst GROUP_ECDH_DOMAIN = \"starfish-group-ecdh\"\nconst GROUP_DATA_INFO = \"starfish-group\"\nconst GEK_BYTES = 32\n\n// \u2500\u2500 Types \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/** An ECDH key pair used for group encryption. Hex-encoded for easy serialization. */\nexport interface GroupKeyPair {\n /** Hex-encoded X25519 private key (32 bytes). Keep secret \u2014 never store on server. */\n privateKey: string\n /** Hex-encoded X25519 public key (32 bytes). Safe to publish. */\n publicKey: string\n}\n\n/** One epoch's wrapped keys: each member's GEK encrypted to their public key. */\nexport interface EpochKeyring {\n /** The admin's hex-encoded X25519 public key (used for ECDH by members). */\n adminPublicKey: string\n /** Map from member identity (userId) \u2192 base64(IV || AES-GCM(GEK)) */\n wrappedKeys: Record<string, string>\n}\n\n/** The full keyring document stored in a Starfish collection. Push this with any SyncManager. */\nexport interface GroupKeyring {\n /** The epoch number currently used for new encryptions. */\n currentEpoch: number\n /** All epochs. Members unwrap the GEK for whichever epoch a document was encrypted with. */\n epochs: Record<string, EpochKeyring>\n}\n\n// \u2500\u2500 Key derivation \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/**\n * Derives a deterministic X25519 key pair from a passphrase + userId.\n *\n * The derivation uses SHA-256 with a fixed domain separator so it is distinct\n * from the auth token and encryption key derivations. Same passphrase + userId\n * always produces the same key pair on any device (stateless).\n */\nexport async function deriveGroupKeyPair(passphrase: string, userId: string): Promise<GroupKeyPair> {\n const c = getCrypto()\n const enc = new TextEncoder()\n const input = enc.encode(`${passphrase}:${userId}:${GROUP_ECDH_DOMAIN}`)\n const hash = await c.subtle.digest(\"SHA-256\", input)\n const privateKeyBytes = new Uint8Array(hash)\n const publicKeyBytes = x25519.getPublicKey(privateKeyBytes)\n return { privateKey: bytesToHex(privateKeyBytes), publicKey: bytesToHex(publicKeyBytes) }\n}\n\n// \u2500\u2500 GEK generation \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/** Generates a random 256-bit Group Encryption Key as a hex string. */\nexport function generateGroupKey(): string {\n const c = getCrypto()\n return bytesToHex(c.getRandomValues(new Uint8Array(GEK_BYTES)))\n}\n\n// \u2500\u2500 Key wrapping / unwrapping \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/**\n * Wraps a GEK for a specific member using ECDH key agreement.\n *\n * The wrapper (admin) and member each have an X25519 key pair. ECDH between\n * `wrapperPrivateKey` and `memberPublicKey` produces a shared secret, which is\n * used to derive an AES-256-GCM key that encrypts the GEK.\n *\n * @returns base64(IV || AES-GCM-ciphertext)\n */\nexport async function wrapGroupKey(\n gek: string,\n memberPublicKey: string,\n wrapperPrivateKey: string,\n): Promise<string> {\n const sharedSecret = x25519.getSharedSecret(hexToBytes(wrapperPrivateKey), hexToBytes(memberPublicKey))\n const wrappingKey = await deriveKey(bytesToHex(sharedSecret), GROUP_WRAP_SALT, GROUP_WRAP_INFO)\n\n const c = getCrypto()\n const b64 = getBase64()\n const iv = c.getRandomValues(new Uint8Array(IV_BYTES))\n const encrypted = await c.subtle.encrypt({ name: ALGO, iv }, wrappingKey, hexToBytes(gek).buffer as ArrayBuffer)\n\n const combined = new Uint8Array(IV_BYTES + encrypted.byteLength)\n combined.set(iv)\n combined.set(new Uint8Array(encrypted), IV_BYTES)\n return b64.encode(combined)\n}\n\n/**\n * Unwraps a GEK using the member's own private key and the admin's public key.\n *\n * ECDH between `memberPrivateKey` and `adminPublicKey` yields the same shared\n * secret as the wrapping step, so the same AES key is derived and the GEK is\n * recovered.\n *\n * @returns GEK as a hex string\n */\nexport async function unwrapGroupKey(\n wrapped: string,\n memberPrivateKey: string,\n adminPublicKey: string,\n): Promise<string> {\n const sharedSecret = x25519.getSharedSecret(hexToBytes(memberPrivateKey), hexToBytes(adminPublicKey))\n const wrappingKey = await deriveKey(bytesToHex(sharedSecret), GROUP_WRAP_SALT, GROUP_WRAP_INFO)\n\n const b64 = getBase64()\n const c = getCrypto()\n const combined = b64.decode(wrapped)\n const iv = combined.slice(0, IV_BYTES)\n const ciphertext = combined.slice(IV_BYTES)\n try {\n const decrypted = await c.subtle.decrypt({ name: ALGO, iv }, wrappingKey, ciphertext)\n return bytesToHex(new Uint8Array(decrypted))\n } catch {\n throw new Error(\"Failed to unwrap group key: decryption failed (wrong keys or corrupted data)\")\n }\n}\n\n// \u2500\u2500 Keyring management \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/**\n * Creates a new group keyring document with epoch 1.\n *\n * @param adminKeyPair The admin's key pair (from `deriveGroupKeyPair` or `deriveCredentials`)\n * @param members Map from member identity (userId) \u2192 hex public key\n * @param gek Optional GEK to use; generated randomly if omitted\n * @returns The keyring document and the raw GEK (admin keeps the GEK to add future members)\n */\nexport async function createGroupKeyring(\n adminKeyPair: GroupKeyPair,\n members: Record<string, string>,\n gek?: string,\n): Promise<{ keyring: GroupKeyring; gek: string }> {\n const resolvedGek = gek ?? generateGroupKey()\n const wrappedKeys: Record<string, string> = {}\n for (const [memberId, memberPublicKey] of Object.entries(members)) {\n wrappedKeys[memberId] = await wrapGroupKey(resolvedGek, memberPublicKey, adminKeyPair.privateKey)\n }\n const keyring: GroupKeyring = {\n currentEpoch: 1,\n epochs: {\n \"1\": { adminPublicKey: adminKeyPair.publicKey, wrappedKeys },\n },\n }\n return { keyring, gek: resolvedGek }\n}\n\n/**\n * Adds a new member to the current epoch of an existing keyring.\n *\n * The admin supplies the current GEK (returned by `createGroupKeyring` or\n * `rotateGroupKey`) and their key pair to wrap it for the new member.\n * This does NOT rotate the GEK \u2014 the new member can read all existing\n * documents encrypted with the current epoch key.\n *\n * Only the admin (whose `publicKey` matches `epochKeyring.adminPublicKey`) can\n * add members, because all wrapped entries must use the same ECDH key pair.\n */\nexport async function addGroupMember(\n keyring: GroupKeyring,\n adminKeyPair: GroupKeyPair,\n currentGek: string,\n newMemberId: string,\n newMemberPublicKey: string,\n): Promise<GroupKeyring> {\n const epochKey = String(keyring.currentEpoch)\n const epochKeyring = keyring.epochs[epochKey]\n if (!epochKeyring) throw new Error(`Epoch ${keyring.currentEpoch} not found in keyring`)\n if (epochKeyring.adminPublicKey !== adminKeyPair.publicKey) {\n throw new Error(`Provided key pair does not match the admin public key stored in epoch ${keyring.currentEpoch}`)\n }\n\n const wrapped = await wrapGroupKey(currentGek, newMemberPublicKey, adminKeyPair.privateKey)\n\n return {\n ...keyring,\n epochs: {\n ...keyring.epochs,\n [epochKey]: {\n ...epochKeyring,\n wrappedKeys: { ...epochKeyring.wrappedKeys, [newMemberId]: wrapped },\n },\n },\n }\n}\n\n/**\n * Rotates the group key, creating a new epoch.\n *\n * Used when removing a member. The removed member retains their old epoch key\n * (and can still read old documents), but cannot read new documents.\n *\n * @param remainingMembers Map from identity \u2192 hex public key for members who keep access\n */\nexport async function rotateGroupKey(\n keyring: GroupKeyring,\n adminKeyPair: GroupKeyPair,\n remainingMembers: Record<string, string>,\n newGek?: string,\n): Promise<{ keyring: GroupKeyring; gek: string }> {\n const epochKey = String(keyring.currentEpoch)\n const epochKeyring = keyring.epochs[epochKey]\n if (epochKeyring && epochKeyring.adminPublicKey !== adminKeyPair.publicKey) {\n throw new Error(\n `Provided key pair does not match the admin public key stored in epoch ${keyring.currentEpoch}`,\n )\n }\n const resolvedGek = newGek ?? generateGroupKey()\n const newEpoch = keyring.currentEpoch + 1\n const wrappedKeys: Record<string, string> = {}\n for (const [memberId, memberPublicKey] of Object.entries(remainingMembers)) {\n wrappedKeys[memberId] = await wrapGroupKey(resolvedGek, memberPublicKey, adminKeyPair.privateKey)\n }\n const newKeyring: GroupKeyring = {\n currentEpoch: newEpoch,\n epochs: {\n ...keyring.epochs,\n [String(newEpoch)]: { adminPublicKey: adminKeyPair.publicKey, wrappedKeys },\n },\n }\n return { keyring: newKeyring, gek: resolvedGek }\n}\n\n// \u2500\u2500 Encryptor factory \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/**\n * Creates an Encryptor that can decrypt any epoch and encrypts with the current epoch.\n *\n * Wire format: `{ _encrypted: \"base64(IV || ciphertext)\", _epoch: N }`\n *\n * @param keyring The keyring document fetched from Starfish\n * @param myIdentity The caller's userId (to locate their wrapped key in each epoch)\n * @param myPrivateKey The caller's hex-encoded X25519 private key\n */\nexport async function createGroupEncryptor(\n keyring: GroupKeyring,\n myIdentity: string,\n myPrivateKey: string,\n): Promise<Encryptor> {\n // Unwrap GEK for each epoch we have a key for\n const epochEncryptors = new Map<number, Encryptor>()\n for (const [epochStr, epochKeyring] of Object.entries(keyring.epochs)) {\n const epoch = parseInt(epochStr, 10)\n const wrapped = epochKeyring.wrappedKeys[myIdentity]\n if (!wrapped) continue\n const gek = await unwrapGroupKey(wrapped, myPrivateKey, epochKeyring.adminPublicKey)\n epochEncryptors.set(epoch, createEncryptor(gek, `epoch-${epoch}`, GROUP_DATA_INFO))\n }\n\n const currentEpoch = keyring.currentEpoch\n const currentEncryptor = epochEncryptors.get(currentEpoch)\n if (!currentEncryptor) {\n throw new Error(\n `No wrapped key found for identity \"${myIdentity}\" in epoch ${currentEpoch}. ` +\n `Ensure the admin has added this member to the keyring.`,\n )\n }\n\n return {\n async encrypt(data: Record<string, unknown>): Promise<Record<string, unknown>> {\n const encrypted = await currentEncryptor.encrypt(data)\n return { ...encrypted, _epoch: currentEpoch }\n },\n\n async decrypt(wrapper: Record<string, unknown>): Promise<Record<string, unknown>> {\n const epoch = typeof wrapper._epoch === \"number\" ? wrapper._epoch : currentEpoch\n const encryptor = epochEncryptors.get(epoch)\n if (!encryptor) {\n throw new Error(\n `No key available for epoch ${epoch}. ` +\n `This document was encrypted in a different epoch. ` +\n `Ensure your keyring is up to date.`,\n )\n }\n return encryptor.decrypt(wrapper)\n },\n }\n}\n", "import { getCrypto, getBase64, IV_BYTES, ENCRYPTED_KEY, deriveKey } from \"@drakkar.software/starfish-protocol\"\n\nconst ALGO = \"AES-GCM\"\n\nexport { ENCRYPTED_KEY }\n\n/** Encrypt/decrypt interface for client-side E2E encryption. */\nexport interface Encryptor {\n encrypt(data: Record<string, unknown>): Promise<Record<string, unknown>>\n decrypt(wrapper: Record<string, unknown>): Promise<Record<string, unknown>>\n}\n\n/**\n * Creates an Encryptor that uses AES-256-GCM with HKDF-derived keys.\n */\nexport function createEncryptor(secret: string, salt: string, info: string = \"starfish-e2e\"): Encryptor {\n if (!secret) throw new Error(\"encryptionSecret must not be empty\")\n if (!salt) throw new Error(\"encryptionSalt must not be empty\")\n const keyPromise = deriveKey(secret, salt, info)\n\n return {\n async encrypt(data: Record<string, unknown>): Promise<Record<string, unknown>> {\n const key = await keyPromise\n const c = getCrypto()\n const b64 = getBase64()\n const plaintext = new TextEncoder().encode(JSON.stringify(data))\n const iv = c.getRandomValues(new Uint8Array(IV_BYTES))\n const ciphertext = await c.subtle.encrypt({ name: ALGO, iv }, key, plaintext)\n\n const combined = new Uint8Array(iv.length + ciphertext.byteLength)\n combined.set(iv)\n combined.set(new Uint8Array(ciphertext), iv.length)\n\n return { [ENCRYPTED_KEY]: b64.encode(combined) }\n },\n\n async decrypt(wrapper: Record<string, unknown>): Promise<Record<string, unknown>> {\n const encoded = wrapper[ENCRYPTED_KEY]\n if (typeof encoded !== \"string\") {\n throw new Error(\"Expected encrypted data but received unencrypted document\")\n }\n\n const key = await keyPromise\n const c = getCrypto()\n const b64 = getBase64()\n const combined = b64.decode(encoded)\n if (combined.length < IV_BYTES) {\n throw new Error(\"Encrypted data is too short\")\n }\n const iv = combined.slice(0, IV_BYTES)\n const ciphertext = combined.slice(IV_BYTES)\n try {\n const plaintext = await c.subtle.decrypt({ name: ALGO, iv }, key, ciphertext)\n return JSON.parse(new TextDecoder().decode(plaintext))\n } catch (err) {\n throw new Error(\"Decryption failed: data may be tampered or key is incorrect\", { cause: err })\n }\n },\n }\n}\n"],
|
|
5
|
+
"mappings": ";AAcA,SAAS,cAAc;AACvB,SAAS,aAAAA,YAAW,aAAAC,YAAW,YAAAC,WAAU,aAAAC,kBAAiB;;;ACf1D,SAAS,WAAW,WAAW,UAAU,eAAe,iBAAiB;AAEzE,IAAM,OAAO;AAaN,SAAS,gBAAgB,QAAgB,MAAc,OAAe,gBAA2B;AACtG,MAAI,CAAC,OAAQ,OAAM,IAAI,MAAM,oCAAoC;AACjE,MAAI,CAAC,KAAM,OAAM,IAAI,MAAM,kCAAkC;AAC7D,QAAM,aAAa,UAAU,QAAQ,MAAM,IAAI;AAE/C,SAAO;AAAA,IACL,MAAM,QAAQ,MAAiE;AAC7E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,KAAK,YAAY;AACjD;AAaA,eAAsB,qBACpB,SACA,YACA,cACoB;AAEpB,QAAM,kBAAkB,oBAAI,IAAuB;AACnD,aAAW,CAAC,UAAU,YAAY,KAAK,OAAO,QAAQ,QAAQ,MAAM,GAAG;AACrE,UAAM,QAAQ,SAAS,UAAU,EAAE;AACnC,UAAM,UAAU,aAAa,YAAY,UAAU;AACnD,QAAI,CAAC,QAAS;AACd,UAAM,MAAM,MAAM,eAAe,SAAS,cAAc,aAAa,cAAc;AACnF,oBAAgB,IAAI,OAAO,gBAAgB,KAAK,SAAS,KAAK,IAAI,eAAe,CAAC;AAAA,EACpF;AAEA,QAAM,eAAe,QAAQ;AAC7B,QAAM,mBAAmB,gBAAgB,IAAI,YAAY;AACzD,MAAI,CAAC,kBAAkB;AACrB,UAAM,IAAI;AAAA,MACR,sCAAsC,UAAU,cAAc,YAAY;AAAA,IAE5E;AAAA,EACF;AAEA,SAAO;AAAA,IACL,MAAM,QAAQ,MAAiE;AAC7E,YAAM,YAAY,MAAM,iBAAiB,QAAQ,IAAI;AACrD,aAAO,EAAE,GAAG,WAAW,QAAQ,aAAa;AAAA,IAC9C;AAAA,IAEA,MAAM,QAAQ,SAAoE;AAChF,YAAM,QAAQ,OAAO,QAAQ,WAAW,WAAW,QAAQ,SAAS;AACpE,YAAM,YAAY,gBAAgB,IAAI,KAAK;AAC3C,UAAI,CAAC,WAAW;AACd,cAAM,IAAI;AAAA,UACR,8BAA8B,KAAK;AAAA,QAGrC;AAAA,MACF;AACA,aAAO,UAAU,QAAQ,OAAO;AAAA,IAClC;AAAA,EACF;AACF;",
|
|
6
|
+
"names": ["getCrypto", "getBase64", "IV_BYTES", "deriveKey", "ALGO", "getCrypto", "deriveKey", "getBase64", "IV_BYTES"]
|
|
7
|
+
}
|
package/dist/identity.d.ts
CHANGED
|
@@ -1,6 +1,84 @@
|
|
|
1
|
+
declare const WORDLIST: string[];
|
|
2
|
+
/** Credentials derived from a passphrase. Pass directly to SyncManager / StarfishClient. */
|
|
3
|
+
export interface DerivedCredentials {
|
|
4
|
+
/** Hex-encoded auth token. Use as `Bearer ${authToken}` in request headers. */
|
|
5
|
+
authToken: string;
|
|
6
|
+
/**
|
|
7
|
+
* Short identifier derived from the auth token (first 16 hex chars = 8 bytes).
|
|
8
|
+
* Used as the user/namespace segment in collection paths.
|
|
9
|
+
*/
|
|
10
|
+
userId: string;
|
|
11
|
+
/**
|
|
12
|
+
* Hex-encoded key suitable as `encryptionSecret` for SyncManager.
|
|
13
|
+
* Combined with `encryptionSalt` to derive the AES-256-GCM key via HKDF.
|
|
14
|
+
*/
|
|
15
|
+
encryptionSecret: string;
|
|
16
|
+
/**
|
|
17
|
+
* Value suitable as `encryptionSalt` for SyncManager. Equals `userId`.
|
|
18
|
+
* Using a per-identity salt ensures that even if two users share a passphrase,
|
|
19
|
+
* their encryption keys are different.
|
|
20
|
+
*/
|
|
21
|
+
encryptionSalt: string;
|
|
22
|
+
/**
|
|
23
|
+
* Hex-encoded X25519 public key for group encryption.
|
|
24
|
+
* Publish this so group admins can wrap the Group Encryption Key (GEK) for you.
|
|
25
|
+
* Safe to store in a public Starfish document.
|
|
26
|
+
*/
|
|
27
|
+
groupPublicKey: string;
|
|
28
|
+
/**
|
|
29
|
+
* Hex-encoded X25519 private key for group encryption.
|
|
30
|
+
* Used to unwrap the GEK from a keyring document.
|
|
31
|
+
* Never transmit this — keep it in memory or derive it from the passphrase.
|
|
32
|
+
*/
|
|
33
|
+
groupPrivateKey: string;
|
|
34
|
+
}
|
|
1
35
|
/**
|
|
2
|
-
*
|
|
3
|
-
*
|
|
36
|
+
* Generates a cryptographically random passphrase from the built-in 256-word list.
|
|
37
|
+
*
|
|
38
|
+
* Each word represents one byte of entropy (256 words = one byte per word, zero modulo bias).
|
|
39
|
+
* A 12-word passphrase gives 96 bits of entropy — stronger than a random UUID.
|
|
40
|
+
*
|
|
41
|
+
* @param wordCount Number of words (default: 12).
|
|
42
|
+
* @param wordlist Custom word list (must have exactly 256 entries).
|
|
4
43
|
*/
|
|
5
|
-
export
|
|
6
|
-
|
|
44
|
+
export declare function generatePassphrase(wordCount?: number, wordlist?: string[]): string;
|
|
45
|
+
/**
|
|
46
|
+
* Derives auth credentials from a passphrase.
|
|
47
|
+
*
|
|
48
|
+
* All derivations are deterministic — the same passphrase always produces the same credentials.
|
|
49
|
+
* Sharing the passphrase grants access on any device.
|
|
50
|
+
*
|
|
51
|
+
* The returned values map directly to Starfish options:
|
|
52
|
+
* ```ts
|
|
53
|
+
* const creds = await deriveCredentials(passphrase)
|
|
54
|
+
*
|
|
55
|
+
* const client = new StarfishClient({
|
|
56
|
+
* baseUrl: serverUrl,
|
|
57
|
+
* auth: () => ({ Authorization: `Bearer ${creds.authToken}` }),
|
|
58
|
+
* })
|
|
59
|
+
* const syncManager = new SyncManager({
|
|
60
|
+
* client,
|
|
61
|
+
* pullPath: `/pull/${creds.userId}/wedding`,
|
|
62
|
+
* pushPath: `/push/${creds.userId}/wedding`,
|
|
63
|
+
* encryptionSecret: creds.encryptionSecret,
|
|
64
|
+
* encryptionSalt: creds.encryptionSalt,
|
|
65
|
+
* })
|
|
66
|
+
* ```
|
|
67
|
+
*/
|
|
68
|
+
export declare function deriveCredentials(passphrase: string): Promise<DerivedCredentials>;
|
|
69
|
+
/**
|
|
70
|
+
* Encodes an invite payload as a URL-safe token and appends it as `?t=<token>`.
|
|
71
|
+
*
|
|
72
|
+
* ```ts
|
|
73
|
+
* const url = buildInviteUrl("myapp://join", { name: "Alice & Bob", p: passphrase })
|
|
74
|
+
* // → "myapp://join?t=eyJuYW1lIjoiQWxpY2UgJiBCb2IifQ"
|
|
75
|
+
* ```
|
|
76
|
+
*/
|
|
77
|
+
export declare function buildInviteUrl(baseUrl: string, payload: Record<string, unknown>): string;
|
|
78
|
+
/**
|
|
79
|
+
* Decodes an invite URL produced by `buildInviteUrl`.
|
|
80
|
+
*
|
|
81
|
+
* Returns the decoded payload, or `null` if the URL is missing or malformed.
|
|
82
|
+
*/
|
|
83
|
+
export declare function parseInviteUrl(url: string): Record<string, unknown> | null;
|
|
84
|
+
export { WORDLIST as DEFAULT_WORDLIST };
|