forked from Adamantine-guild/guildpass-mobile
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathguildIssuerKey.ts
More file actions
417 lines (362 loc) · 12.1 KB
/
Copy pathguildIssuerKey.ts
File metadata and controls
417 lines (362 loc) · 12.1 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
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
import { sha256, toHex } from "viem";
import { guildPassClient } from "../../lib/guildpassClient";
import { migratingSecureStorage } from "../../lib/storage";
import { QrSignatureError, QR_SIGNATURE_ERROR_CODES } from "./qrSignature";
/**
* Key Registry & Issuer Public Key Manager
*
* Manages versioned issuer public keys and key revocation state per guild.
* Supports:
* - Key ID (kid) lookup for rotating keys with rotation overlap.
* - Tracking and rejection of revoked key IDs.
* - Bounded TTL cache for key registry data.
* - Safe offline-fallback behavior (re-uses cached registry within a trust window,
* refuses unverifiable payloads if expired or uncached).
*/
export type IssuerKeyEntry = {
kid: string;
publicKey: string;
status?: "active" | "revoked";
};
export type GuildConfigWithIssuerKeys = {
guildId: string;
issuerPublicKey?: string;
issuerKeys?:
| Record<string, string>
| Array<IssuerKeyEntry>;
revokedKids?: string[];
[key: string]: unknown;
};
export type GuildKeyRegistry = {
guildId: string;
keys: Map<string, string>;
revokedKids: Set<string>;
fetchedAt: number;
legacyPublicKey?: string;
};
/** Default bounded TTL for key registry cache: 15 minutes */
export const DEFAULT_KEY_REGISTRY_CACHE_TTL_MS = 15 * 60 * 1000;
/** Default offline trust window for cached registry fallback: 24 hours */
export const DEFAULT_KEY_REGISTRY_OFFLINE_TRUST_WINDOW_MS = 24 * 60 * 60 * 1000;
let currentCacheTtlMs = DEFAULT_KEY_REGISTRY_CACHE_TTL_MS;
let currentOfflineTrustWindowMs = DEFAULT_KEY_REGISTRY_OFFLINE_TRUST_WINDOW_MS;
const registryCache = new Map<string, GuildKeyRegistry>();
type SerializedGuildKeyRegistry = {
version: 1;
guildId: string;
keys: Array<[string, string]>;
revokedKids: string[];
fetchedAt: number;
legacyPublicKey?: string;
checksum: string;
};
type RegistryChecksumPayload = Omit<SerializedGuildKeyRegistry, "checksum">;
const GUILD_KEY_REGISTRY_STORAGE_PREFIX = "guildpass:access-key-registry:v1:";
const getPersistentRegistryStorageKey = (guildId: string): string =>
`${GUILD_KEY_REGISTRY_STORAGE_PREFIX}${guildId}`;
const buildRegistryChecksumPayload = (
registry: GuildKeyRegistry,
): RegistryChecksumPayload => ({
version: 1,
guildId: registry.guildId,
keys: Array.from(registry.keys.entries()).sort(([left], [right]) => left.localeCompare(right)),
revokedKids: Array.from(registry.revokedKids.values()).sort(),
fetchedAt: registry.fetchedAt,
...(registry.legacyPublicKey ? { legacyPublicKey: registry.legacyPublicKey } : {}),
});
const createRegistryChecksum = (payload: RegistryChecksumPayload): string =>
sha256(toHex(JSON.stringify(payload)));
const serializeRegistry = (registry: GuildKeyRegistry): string => {
const payload = buildRegistryChecksumPayload(registry);
const serialized: SerializedGuildKeyRegistry = {
...payload,
checksum: createRegistryChecksum(payload),
};
return JSON.stringify(serialized);
};
const deserializeRegistry = (raw: string, expectedGuildId: string): GuildKeyRegistry | null => {
try {
const parsed = JSON.parse(raw) as Partial<SerializedGuildKeyRegistry>;
const guildId = parsed.guildId;
const fetchedAt = parsed.fetchedAt;
const serializedKeys = parsed.keys;
const serializedRevokedKids = parsed.revokedKids;
const checksum = parsed.checksum;
if (
parsed.version !== 1 ||
typeof guildId !== "string" ||
guildId !== expectedGuildId ||
typeof fetchedAt !== "number" ||
!Number.isFinite(fetchedAt) ||
!Array.isArray(serializedKeys) ||
!Array.isArray(serializedRevokedKids) ||
typeof checksum !== "string"
) {
return null;
}
const keys = new Map<string, string>();
for (const entry of serializedKeys) {
if (
!Array.isArray(entry) ||
entry.length !== 2 ||
typeof entry[0] !== "string" ||
typeof entry[1] !== "string"
) {
return null;
}
keys.set(entry[0], entry[1]);
}
const revokedKids = new Set<string>();
for (const kid of serializedRevokedKids) {
if (typeof kid !== "string") return null;
revokedKids.add(kid);
keys.delete(kid);
}
const payload: RegistryChecksumPayload = {
version: 1,
guildId,
keys: Array.from(keys.entries()).sort(([left], [right]) => left.localeCompare(right)),
revokedKids: Array.from(revokedKids.values()).sort(),
fetchedAt,
...(typeof parsed.legacyPublicKey === "string"
? { legacyPublicKey: parsed.legacyPublicKey }
: {}),
};
if (createRegistryChecksum(payload) !== checksum) {
return null;
}
return {
guildId,
keys,
revokedKids,
fetchedAt,
...(typeof parsed.legacyPublicKey === "string"
? { legacyPublicKey: parsed.legacyPublicKey }
: {}),
};
} catch {
return null;
}
};
const loadPersistedRegistry = async (guildId: string): Promise<GuildKeyRegistry | null> => {
const storageKey = getPersistentRegistryStorageKey(guildId);
try {
const raw = await migratingSecureStorage.getItem(storageKey);
if (raw === null) return null;
const registry = deserializeRegistry(raw, guildId);
if (registry === null) {
await migratingSecureStorage.removeItem(storageKey);
}
return registry;
} catch (error) {
console.warn(`Failed to load persisted key registry for guild ${guildId}:`, error);
return null;
}
};
const persistRegistry = async (registry: GuildKeyRegistry): Promise<void> => {
try {
await migratingSecureStorage.setItem(
getPersistentRegistryStorageKey(registry.guildId),
serializeRegistry(registry),
);
} catch (error) {
console.warn(`Failed to persist key registry for guild ${registry.guildId}:`, error);
}
};
const cacheRegistry = async (registry: GuildKeyRegistry): Promise<GuildKeyRegistry> => {
registryCache.set(registry.guildId, registry);
await persistRegistry(registry);
return registry;
};
export const clearIssuerKeyCache = (): void => {
registryCache.clear();
};
export const setKeyRegistryCacheTtlMs = (ttlMs: number): void => {
currentCacheTtlMs = ttlMs;
};
export const setKeyRegistryOfflineTrustWindowMs = (trustWindowMs: number): void => {
currentOfflineTrustWindowMs = trustWindowMs;
};
export const resetKeyRegistryTimeouts = (): void => {
currentCacheTtlMs = DEFAULT_KEY_REGISTRY_CACHE_TTL_MS;
currentOfflineTrustWindowMs = DEFAULT_KEY_REGISTRY_OFFLINE_TRUST_WINDOW_MS;
};
const parseKeyRegistryConfig = (
config: GuildConfigWithIssuerKeys,
fetchedAt: number,
): GuildKeyRegistry => {
const keys = new Map<string, string>();
const revokedKids = new Set<string>();
// Process issuerKeys if provided
if (config.issuerKeys) {
if (Array.isArray(config.issuerKeys)) {
for (const entry of config.issuerKeys) {
if (entry && typeof entry.kid === "string" && typeof entry.publicKey === "string") {
const kid = entry.kid.trim();
const pubKey = entry.publicKey.trim();
if (entry.status === "revoked") {
revokedKids.add(kid);
} else {
keys.set(kid, pubKey);
}
}
}
} else if (typeof config.issuerKeys === "object" && config.issuerKeys !== null) {
for (const [kid, pubKey] of Object.entries(config.issuerKeys)) {
if (typeof pubKey === "string" && pubKey.trim().length > 0) {
keys.set(kid.trim(), pubKey.trim());
}
}
}
}
// Process revokedKids list if provided
if (Array.isArray(config.revokedKids)) {
for (const kid of config.revokedKids) {
if (typeof kid === "string" && kid.trim().length > 0) {
const trimmedKid = kid.trim();
revokedKids.add(trimmedKid);
keys.delete(trimmedKid); // Revocation takes precedence
}
}
}
let legacyPublicKey: string | undefined;
if (typeof config.issuerPublicKey === "string" && config.issuerPublicKey.trim().length > 0) {
legacyPublicKey = config.issuerPublicKey.trim();
}
return {
guildId: config.guildId,
keys,
revokedKids,
fetchedAt,
legacyPublicKey,
};
};
/**
* Fetch fresh key registry from SDK for a guild.
*/
const fetchGuildKeyRegistry = async (
guildId: string,
now: Date = new Date(),
): Promise<GuildKeyRegistry> => {
let config: GuildConfigWithIssuerKeys;
try {
config = (await guildPassClient.guilds.getGuildConfig({
guildId,
})) as GuildConfigWithIssuerKeys;
} catch (err) {
throw new QrSignatureError(
QR_SIGNATURE_ERROR_CODES.PUBLIC_KEY_UNAVAILABLE,
"Unable to fetch guild issuer key registry.",
);
}
if (!config) {
throw new QrSignatureError(
QR_SIGNATURE_ERROR_CODES.PUBLIC_KEY_UNAVAILABLE,
"Guild config returned empty or invalid data.",
);
}
return parseKeyRegistryConfig(config, now.getTime());
};
/**
* Get key registry for a guild, enforcing TTL and offline fallback policy.
*/
export const getGuildKeyRegistry = async (
guildId: string,
now: Date = new Date(),
): Promise<GuildKeyRegistry> => {
const cached = registryCache.get(guildId);
const nowMs = now.getTime();
if (cached !== undefined) {
const age = nowMs - cached.fetchedAt;
if (age < currentCacheTtlMs) {
return cached;
}
// Cache expired: try to refresh
try {
const freshRegistry = await fetchGuildKeyRegistry(guildId, now);
return cacheRegistry(freshRegistry);
} catch (error) {
// Refresh failed (e.g. offline)
if (age <= currentOfflineTrustWindowMs) {
// Safe offline fallback: cached registry is still within trust window
return cached;
}
// Past trust window: reject
throw new QrSignatureError(
QR_SIGNATURE_ERROR_CODES.KEY_REGISTRY_EXPIRED,
"Guild key registry cache expired and could not be refreshed offline.",
);
}
}
const persisted = await loadPersistedRegistry(guildId);
if (persisted !== null) {
registryCache.set(guildId, persisted);
const age = nowMs - persisted.fetchedAt;
if (age < currentCacheTtlMs) {
return persisted;
}
try {
const freshRegistry = await fetchGuildKeyRegistry(guildId, now);
return cacheRegistry(freshRegistry);
} catch (error) {
if (age <= currentOfflineTrustWindowMs) {
return persisted;
}
throw new QrSignatureError(
QR_SIGNATURE_ERROR_CODES.KEY_REGISTRY_EXPIRED,
"Persisted guild key registry cache expired and could not be refreshed offline.",
);
}
}
// No memory or persisted entry: must fetch online
const freshRegistry = await fetchGuildKeyRegistry(guildId, now);
return cacheRegistry(freshRegistry);
};
/**
* Resolve the public key for a guild payload by `kid` or legacy fallback.
* Checks key revocation and unknown key errors.
*/
export const getGuildIssuerPublicKey = async (
guildId: string,
kid?: string,
now: Date = new Date(),
): Promise<string> => {
const registry = await getGuildKeyRegistry(guildId, now);
if (kid !== undefined && kid.trim().length > 0) {
const cleanKid = kid.trim();
// 1. Check if kid is revoked
if (registry.revokedKids.has(cleanKid)) {
throw new QrSignatureError(
QR_SIGNATURE_ERROR_CODES.REVOKED_KEY,
`QR code was signed with a revoked key (kid: ${cleanKid}).`,
);
}
// 2. Look up public key for kid
const pubKey = registry.keys.get(cleanKid);
if (pubKey !== undefined) {
return pubKey;
}
// 3. Kid not found in active keys
throw new QrSignatureError(
QR_SIGNATURE_ERROR_CODES.UNKNOWN_KEY,
`QR code was signed with an unknown or unrecognized key ID (kid: ${cleanKid}).`,
);
}
// Kid is omitted: check legacy / single-key fallbacks
if (registry.legacyPublicKey !== undefined) {
return registry.legacyPublicKey;
}
if (registry.keys.size === 1) {
return registry.keys.values().next().value!;
}
if (registry.keys.size > 1) {
throw new QrSignatureError(
QR_SIGNATURE_ERROR_CODES.MISSING_KID,
"QR code is missing a key ID (kid) required to select among multiple active issuer keys.",
);
}
throw new QrSignatureError(
QR_SIGNATURE_ERROR_CODES.PUBLIC_KEY_UNAVAILABLE,
"Guild config does not publish a usable issuer public key.",
);
};