forked from Prompt-Hash-Stellar/prompt-hash
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathkms.ts
More file actions
386 lines (337 loc) · 9.79 KB
/
Copy pathkms.ts
File metadata and controls
386 lines (337 loc) · 9.79 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
import crypto from "crypto";
import { Buffer } from "buffer";
// GF(256) Tables for Shamir's Secret Sharing
const expTable = new Uint8Array(256);
const logTable = new Uint8Array(256);
let x = 1;
for (let i = 0; i < 255; i++) {
expTable[i] = x;
logTable[x] = i;
x <<= 1;
if (x & 0x100) {
x ^= 0x11d; // Irreducible polynomial x^8 + x^4 + x^3 + x^2 + 1 (285)
}
}
expTable[255] = expTable[0];
function gfAdd(a: number, b: number): number {
return a ^ b;
}
function gfMul(a: number, b: number): number {
if (a === 0 || b === 0) return 0;
return expTable[(logTable[a] + logTable[b]) % 255];
}
function gfDiv(a: number, b: number): number {
if (b === 0) throw new Error("Division by zero in GF(256)");
if (a === 0) return 0;
let diff = logTable[a] - logTable[b];
if (diff < 0) diff += 255;
return expTable[diff];
}
function ipow(base: number, exp: number): number {
let res = 1;
for (let i = 0; i < exp; i++) {
res = gfMul(res, base);
}
return res;
}
export interface KeyShare {
x: number;
y: string; // base64 encoded y value
}
/**
* Splits a secret byte array into N shares, with a threshold T.
*/
export function splitSecret(
secret: Uint8Array,
threshold: number,
totalShares: number,
): KeyShare[] {
if (threshold < 1 || threshold > totalShares) {
throw new Error("Invalid threshold");
}
if (totalShares > 255) {
throw new Error("Total shares cannot exceed 255");
}
const shares: KeyShare[] = [];
const shareBuffers: Uint8Array[] = [];
for (let i = 0; i < totalShares; i++) {
shareBuffers.push(new Uint8Array(secret.length));
}
for (let byteIdx = 0; byteIdx < secret.length; byteIdx++) {
const coeffs = new Uint8Array(threshold);
coeffs[0] = secret[byteIdx];
for (let j = 1; j < threshold; j++) {
coeffs[j] = Math.floor(Math.random() * 255) + 1;
}
for (let xVal = 1; xVal <= totalShares; xVal++) {
let val = 0;
for (let degree = 0; degree < threshold; degree++) {
const term = gfMul(coeffs[degree], ipow(xVal, degree));
val = gfAdd(val, term);
}
shareBuffers[xVal - 1][byteIdx] = val;
}
}
for (let i = 0; i < totalShares; i++) {
shares.push({
x: i + 1,
y: Buffer.from(shareBuffers[i]).toString("base64"),
});
}
return shares;
}
/**
* Reconstructs the secret byte array from a subset of T shares.
*/
export function reconstructSecret(shares: KeyShare[]): Uint8Array {
if (shares.length === 0) {
throw new Error("No shares provided");
}
const k = shares.length;
const secretLen = Buffer.from(shares[0].y, "base64").length;
const result = new Uint8Array(secretLen);
const parsedShares = shares.map((s) => ({
x: s.x,
y: new Uint8Array(Buffer.from(s.y, "base64")),
}));
for (let byteIdx = 0; byteIdx < secretLen; byteIdx++) {
let sum = 0;
for (let i = 0; i < k; i++) {
const xi = parsedShares[i].x;
const yi = parsedShares[i].y[byteIdx];
let li = 1;
for (let j = 0; j < k; j++) {
if (i === j) continue;
const xj = parsedShares[j].x;
const num = xj;
const den = gfAdd(xj, xi);
if (den === 0) {
throw new Error("Duplicate or invalid share X coordinates detected");
}
const term = gfDiv(num, den);
li = gfMul(li, term);
}
sum = gfAdd(sum, gfMul(yi, li));
}
result[byteIdx] = sum;
}
return result;
}
// Symmetric encryption helpers
export function encryptSymmetricSync(
plaintext: Uint8Array,
key: Uint8Array,
associatedData?: Uint8Array,
): { ciphertext: string; iv: string; tag: string } {
const iv = crypto.randomBytes(12);
const cipher = crypto.createCipheriv("aes-256-gcm", key, iv);
if (associatedData) {
cipher.setAAD(associatedData);
}
const ciphertext = Buffer.concat([cipher.update(plaintext), cipher.final()]);
const tag = cipher.getAuthTag();
return {
ciphertext: ciphertext.toString("base64"),
iv: iv.toString("base64"),
tag: tag.toString("base64"),
};
}
export function decryptSymmetricSync(
ciphertextB64: string,
ivB64: string,
tagB64: string,
key: Uint8Array,
associatedData?: Uint8Array,
): Uint8Array {
const iv = Buffer.from(ivB64, "base64");
const ciphertext = Buffer.from(ciphertextB64, "base64");
const tag = Buffer.from(tagB64, "base64");
const decipher = crypto.createDecipheriv("aes-256-gcm", key, iv);
decipher.setAuthTag(tag);
if (associatedData) {
decipher.setAAD(associatedData);
}
return new Uint8Array(
Buffer.concat([decipher.update(ciphertext), decipher.final()]),
);
}
// Global active in-memory break-glass key
let breakGlassMasterKey: Uint8Array | null = null;
export function getKmsMasterKeySync(version: string): Uint8Array {
if (breakGlassMasterKey) {
return breakGlassMasterKey;
}
const keyEnvName = `KMS_MASTER_KEY_V${version}`;
const envVal = process.env[keyEnvName];
if (envVal) {
if (envVal.length === 64) {
return new Uint8Array(Buffer.from(envVal, "hex"));
}
return new Uint8Array(Buffer.from(envVal, "base64"));
}
// Cryptographically secure deterministic fallback key for testing environments
const baseSecret =
process.env.CHALLENGE_TOKEN_SECRET || "default-secret-key-kms";
return new Uint8Array(
crypto
.createHash("sha256")
.update(baseSecret + ":" + version)
.digest(),
);
}
export function setBreakGlassKey(key: Uint8Array | null) {
breakGlassMasterKey = key;
}
export function wrapServerPrivateKey(
privateKey: string,
kmsVersion: string,
): string {
const masterKey = getKmsMasterKeySync(kmsVersion);
const secretBytes = Buffer.from(privateKey, "base64");
const { ciphertext, iv, tag } = encryptSymmetricSync(secretBytes, masterKey);
return `pk:v2:${kmsVersion}:${iv}:${tag}:${ciphertext}`;
}
export function unwrapServerPrivateKey(envelope: string): string {
if (!envelope.startsWith("pk:v2:")) {
return envelope;
}
const [, , kmsVersion, iv, tag, ciphertext] = envelope.split(":");
const masterKey = getKmsMasterKeySync(kmsVersion);
const decryptedBytes = decryptSymmetricSync(ciphertext, iv, tag, masterKey);
return Buffer.from(decryptedBytes).toString("base64");
}
export interface AadContext {
promptId: string;
creator: string;
contentHash: string;
version: string;
nonce: string;
wrappedKey: string;
ciphertext: string;
}
export function buildAAD(ctx: AadContext): Uint8Array {
const parts = [
ctx.promptId,
ctx.creator,
ctx.contentHash,
ctx.version,
ctx.nonce,
ctx.wrappedKey,
ctx.ciphertext,
];
return new TextEncoder().encode(parts.join("|"));
}
export interface PromptAadContext {
promptId: string;
creator: string;
contentHash: string;
version: string;
nonce: string;
}
export function buildPromptAAD(ctx: PromptAadContext): Uint8Array {
const parts = [
ctx.promptId,
ctx.creator,
ctx.contentHash,
ctx.version,
ctx.nonce,
];
return new TextEncoder().encode(parts.join("|"));
}
export interface KmsAadContext {
promptId: string;
creator: string;
contentHash: string;
version: string;
nonce: string;
ciphertext: string;
}
export function buildKmsAAD(ctx: KmsAadContext): Uint8Array {
const parts = [
ctx.promptId,
ctx.creator,
ctx.contentHash,
ctx.version,
ctx.nonce,
ctx.ciphertext,
];
return new TextEncoder().encode(parts.join("|"));
}
export type KeyPolicyStatus = "active" | "suspended" | "revoked";
export interface KeyMetadata {
promptId: string;
status: KeyPolicyStatus;
leaseExpiresAt?: number;
}
const keyRegistry = new Map<string, KeyMetadata>();
export function setKeyPolicy(
promptId: string,
status: KeyPolicyStatus,
leaseExpiresAt?: number,
) {
keyRegistry.set(promptId, { promptId, status, leaseExpiresAt });
}
export function getKeyPolicy(promptId: string): KeyMetadata {
return keyRegistry.get(promptId) || { promptId, status: "active" };
}
export function validateKeyPolicy(promptId: string) {
const policy = getKeyPolicy(promptId);
if (policy.status === "revoked") {
throw new Error(
`Key for prompt ${promptId} has been revoked (delisted/deleted).`,
);
}
if (policy.status === "suspended") {
throw new Error(
`Key for prompt ${promptId} is suspended (disputed/on hold).`,
);
}
if (policy.leaseExpiresAt && Date.now() > policy.leaseExpiresAt) {
throw new Error(`Key for prompt ${promptId} lease has expired.`);
}
}
export function decryptPromptCiphertextWithAADSync(
encryptedPromptB64: string,
ivB64: string,
rawKey: Uint8Array,
associatedData: Uint8Array,
): string {
const iv = Buffer.from(ivB64, "base64");
const fullCipher = Buffer.from(encryptedPromptB64, "base64");
const ciphertext = fullCipher.slice(0, -16);
const tag = fullCipher.slice(-16);
const decipher = crypto.createDecipheriv("aes-256-gcm", rawKey, iv);
decipher.setAuthTag(tag);
decipher.setAAD(associatedData);
const decrypted = Buffer.concat([
decipher.update(ciphertext),
decipher.final(),
]);
return decrypted.toString("utf8");
}
export function encryptPromptPlaintextWithAADSync(
plaintext: string,
rawKey: Uint8Array,
ctx: Omit<PromptAadContext, "nonce">,
): { encryptedPrompt: string; encryptionIv: string; contentHash: string } {
const iv = crypto.randomBytes(12);
const encryptionIv = iv.toString("base64");
const promptAad = buildPromptAAD({
...ctx,
nonce: encryptionIv,
});
const cipher = crypto.createCipheriv("aes-256-gcm", rawKey, iv);
cipher.setAAD(promptAad);
const ciphertext = Buffer.concat([
cipher.update(Buffer.from(plaintext, "utf8")),
cipher.final(),
]);
const tag = cipher.getAuthTag();
const fullCipher = Buffer.concat([ciphertext, tag]);
const hash = crypto.createHash("sha256").update(plaintext).digest("hex");
return {
encryptedPrompt: fullCipher.toString("base64"),
encryptionIv,
contentHash: hash,
};
}