Repository navigation
Expand file tree
/
Copy pathoidc-auth.ts
More file actions
743 lines (652 loc) · 27 KB
/
Copy pathoidc-auth.ts
File metadata and controls
743 lines (652 loc) · 27 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
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
// OIDC Authentication API endpoints
// Handles OAuth flow for external Identity Providers
import { Hono } from 'hono';
import type { Context } from 'hono';
import type { AppEnv } from '../types';
import type { OAuthEndpoints, OIDCUserClaims } from '../services/oidc';
import {
fetchOIDCDiscovery,
fetchJWKS,
buildAuthorizationUrl,
exchangeCodeForTokens,
validateIDToken,
generateRandomString,
deriveUsername,
buildOAuthAuthorizationUrl,
exchangeOAuthCode,
fetchOAuthUserInfo,
} from '../services/oidc';
import { formatUserId } from '../utils/ids';
import { generateAccessToken, generateDeviceId } from '../utils/ids';
import { hashToken } from '../utils/crypto';
import { createUser, getUserById, createDevice, createAccessToken } from '../services/database';
import { requireAuth } from '../middleware/auth';
import { generateOpaqueId } from '../utils/ids';
const app = new Hono<AppEnv>();
export interface IdPProvider {
id: string;
name: string;
issuer_url: string;
client_id: string;
client_secret_encrypted: string;
scopes: string;
enabled: number;
auto_create_users: number;
username_claim: string;
display_order: number;
icon_url: string | null;
provider_type: string;
authorization_endpoint: string | null;
token_endpoint: string | null;
userinfo_endpoint: string | null;
emails_endpoint: string | null;
}
interface IdPUserLink {
id: number;
provider_id: string;
external_id: string;
user_id: string;
external_email: string | null;
external_name: string | null;
}
// Generic OAuth2 providers store their endpoints on the provider row instead
// of advertising an OIDC discovery document. A partially configured provider
// fails closed rather than silently redirecting to a missing endpoint.
function getOAuthEndpoints(provider: IdPProvider): OAuthEndpoints {
const { authorization_endpoint, token_endpoint, userinfo_endpoint, emails_endpoint } = provider;
if (!authorization_endpoint || !token_endpoint || !userinfo_endpoint) {
throw new Error('OAuth2 provider is missing required endpoint configuration');
}
return {
authorization_endpoint,
token_endpoint,
userinfo_endpoint,
...(emails_endpoint ? { emails_endpoint } : {}),
};
}
interface OAuthState {
providerId: string;
nonce: string;
redirectUri: string;
returnTo?: string;
// Set for spec SSO login (/login/sso/redirect): the callback finishes by
// redirecting here with a one-time loginToken instead of rendering a page.
ssoRedirectUrl?: string;
}
// Version byte for encrypted secrets
// 0x01 = legacy (SERVER_NAME-based key) - INSECURE, kept for migration
// 0x02 = secure (OIDC_ENCRYPTION_KEY)
const ENCRYPTION_VERSION_LEGACY = 0x01;
const ENCRYPTION_VERSION_SECURE = 0x02;
// Get the encryption key (prefer OIDC_ENCRYPTION_KEY, fall back to SERVER_NAME for legacy)
async function getEncryptionKey(
env: { SERVER_NAME: string; OIDC_ENCRYPTION_KEY?: string },
version: number
): Promise<CryptoKey> {
const encoder = new TextEncoder();
if (version === ENCRYPTION_VERSION_SECURE && env.OIDC_ENCRYPTION_KEY) {
// Use the secure key (base64-encoded 32 bytes)
const keyBytes = Uint8Array.from(atob(env.OIDC_ENCRYPTION_KEY), (c) => c.charCodeAt(0));
if (keyBytes.length !== 32) {
throw new Error('OIDC_ENCRYPTION_KEY must be 32 bytes (base64 encoded)');
}
return crypto.subtle.importKey('raw', keyBytes, 'AES-GCM', false, ['encrypt', 'decrypt']);
}
// Legacy key derivation (INSECURE - only for decrypting old secrets)
console.warn('Using legacy OIDC encryption - please set OIDC_ENCRYPTION_KEY');
return crypto.subtle.importKey(
'raw',
encoder.encode(env.SERVER_NAME.padEnd(32, '0').slice(0, 32)),
'AES-GCM',
false,
['encrypt', 'decrypt']
);
}
// Encrypt a secret using AES-GCM
// Encrypt a secret using AES-GCM with the secure OIDC_ENCRYPTION_KEY.
// Refuses to encrypt with the legacy SERVER_NAME-based key — new secrets
// must use a proper encryption key.
async function encryptSecret(
secret: string,
env: { SERVER_NAME: string; OIDC_ENCRYPTION_KEY?: string }
): Promise<string> {
const encoder = new TextEncoder();
if (!env.OIDC_ENCRYPTION_KEY) {
throw new Error(
'OIDC_ENCRYPTION_KEY is required for OIDC client registration. ' +
'Generate with: openssl rand -base64 32 | npx wrangler secret put OIDC_ENCRYPTION_KEY'
);
}
const version = ENCRYPTION_VERSION_SECURE;
const keyMaterial = await getEncryptionKey(env, version);
const iv = crypto.getRandomValues(new Uint8Array(12));
const encrypted = await crypto.subtle.encrypt({ name: 'AES-GCM', iv }, keyMaterial, encoder.encode(secret));
// Combine version byte, IV, and ciphertext
const encryptedBytes = new Uint8Array(encrypted);
const combined = new Uint8Array(1 + iv.length + encryptedBytes.length);
combined[0] = version;
combined.set(iv, 1);
combined.set(encryptedBytes, 1 + iv.length);
return btoa(String.fromCharCode(...combined));
}
// Decrypt a secret
// Automatically detects version and uses appropriate key
async function decryptSecret(
encryptedSecret: string,
env: { SERVER_NAME: string; OIDC_ENCRYPTION_KEY?: string }
): Promise<string> {
const combined = Uint8Array.from(atob(encryptedSecret), (c) => c.charCodeAt(0));
// Check if this is a versioned secret (starts with 0x01 or 0x02)
let version: number;
let iv: Uint8Array;
let ciphertext: Uint8Array;
if (combined[0] === ENCRYPTION_VERSION_LEGACY || combined[0] === ENCRYPTION_VERSION_SECURE) {
// New format with version byte
version = combined[0];
iv = combined.slice(1, 13);
ciphertext = combined.slice(13);
} else {
// Old format without version byte (legacy)
version = ENCRYPTION_VERSION_LEGACY;
iv = combined.slice(0, 12);
ciphertext = combined.slice(12);
}
const keyMaterial = await getEncryptionKey(env, version);
const decrypted = await crypto.subtle.decrypt({ name: 'AES-GCM', iv }, keyMaterial, ciphertext);
return new TextDecoder().decode(decrypted);
}
// GET /auth/oidc/providers - List enabled IdP providers (public)
app.get('/auth/oidc/providers', async (c) => {
const db = c.env.DB;
const result = await db.prepare(`
SELECT id, name, icon_url, display_order
FROM idp_providers
WHERE enabled = 1
ORDER BY display_order ASC, name ASC
`).all<{ id: string; name: string; icon_url: string | null; display_order: number }>();
return c.json({
providers: result.results.map(p => ({
id: p.id,
name: p.name,
icon_url: p.icon_url,
login_url: `/auth/oidc/${p.id}/login`,
})),
});
});
// Start the OAuth flow against a configured IdP. Shared by the dashboard
// login (/auth/oidc/:providerId/login) and the spec SSO login redirect
// (/login/sso/redirect): the latter stores ssoRedirectUrl so the callback
// completes with a one-time login token instead of an HTML page.
export async function initiateIdpLogin(
c: Context<AppEnv>,
provider: IdPProvider,
opts: { returnTo?: string; ssoRedirectUrl?: string } = {}
): Promise<Response> {
try {
if (provider.provider_type === 'oauth2') {
const endpoints = getOAuthEndpoints(provider);
// Generate state and nonce. The nonce is still stored in OAuthState so
// the state shape stays identical; generic OAuth2 has no nonce param.
const state = generateRandomString(32);
const nonce = generateRandomString(32);
const host = c.req.header('host') || c.env.SERVER_NAME;
const redirectUri = `https://${host}/auth/oidc/${provider.id}/callback`;
const stateData: OAuthState = {
providerId: provider.id,
nonce,
redirectUri,
returnTo: opts.returnTo,
ssoRedirectUrl: opts.ssoRedirectUrl,
};
await c.env.SESSIONS.put(`oidc_state:${state}`, JSON.stringify(stateData), {
expirationTtl: 600,
});
const authUrl = buildOAuthAuthorizationUrl(
endpoints,
provider.client_id,
redirectUri,
provider.scopes,
state
);
return c.redirect(authUrl);
}
// Fetch OIDC discovery
const discovery = await fetchOIDCDiscovery(provider.issuer_url);
// Generate state and nonce
const state = generateRandomString(32);
const nonce = generateRandomString(32);
// Build redirect URI
const host = c.req.header('host') || c.env.SERVER_NAME;
const redirectUri = `https://${host}/auth/oidc/${provider.id}/callback`;
// Store state in KV (expires in 10 minutes)
const stateData: OAuthState = {
providerId: provider.id,
nonce,
redirectUri,
returnTo: opts.returnTo,
ssoRedirectUrl: opts.ssoRedirectUrl,
};
await c.env.SESSIONS.put(`oidc_state:${state}`, JSON.stringify(stateData), {
expirationTtl: 600,
});
// Build authorization URL and redirect
const authUrl = buildAuthorizationUrl(
discovery,
provider.client_id,
redirectUri,
provider.scopes,
state,
nonce
);
return c.redirect(authUrl);
} catch (err) {
console.error('OIDC login error:', err);
return c.json({ errcode: 'M_UNKNOWN', error: 'Failed to initiate login' }, 500);
}
}
// GET /auth/oidc/:providerId/login - Initiate OAuth flow
app.get('/auth/oidc/:providerId/login', async (c) => {
const providerId = c.req.param('providerId');
const returnTo = c.req.query('return_to') || '/';
const db = c.env.DB;
// Get provider config
const provider = await db.prepare(`
SELECT * FROM idp_providers WHERE id = ? AND enabled = 1
`).bind(providerId).first<IdPProvider>();
if (!provider) {
return c.json({ errcode: 'M_NOT_FOUND', error: 'Identity provider not found' }, 404);
}
return initiateIdpLogin(c, provider, { returnTo });
});
// GET /auth/oidc/:providerId/callback - Handle OAuth callback
app.get('/auth/oidc/:providerId/callback', async (c) => {
const providerId = c.req.param('providerId');
const code = c.req.query('code');
const state = c.req.query('state');
const error = c.req.query('error');
const errorDescription = c.req.query('error_description');
const db = c.env.DB;
// Handle error from IdP
if (error) {
return c.html(generateErrorPage('Authentication Failed', errorDescription || error));
}
if (!code || !state) {
return c.html(generateErrorPage('Invalid Request', 'Missing code or state parameter'));
}
// Retrieve and validate state
const stateDataJson = await c.env.SESSIONS.get(`oidc_state:${state}`);
if (!stateDataJson) {
return c.html(generateErrorPage('Invalid State', 'The login session has expired. Please try again.'));
}
const stateData: OAuthState = JSON.parse(stateDataJson);
// Delete state (one-time use)
await c.env.SESSIONS.delete(`oidc_state:${state}`);
// Validate provider matches
if (stateData.providerId !== providerId) {
return c.html(generateErrorPage('Invalid State', 'Provider mismatch'));
}
// Get provider config
const provider = await db.prepare(`
SELECT * FROM idp_providers WHERE id = ? AND enabled = 1
`).bind(providerId).first<IdPProvider>();
if (!provider) {
return c.html(generateErrorPage('Provider Not Found', 'Identity provider not found or disabled'));
}
try {
let claims: OIDCUserClaims;
if (provider.provider_type === 'oauth2') {
const endpoints = getOAuthEndpoints(provider);
// Decrypt client secret (same scheme as OIDC providers)
const clientSecret = await decryptSecret(provider.client_secret_encrypted, c.env);
// Exchange the code and read the user profile from the OAuth2 endpoints.
// There is no ID token/JWKS/nonce validation for generic OAuth2.
const tokens = await exchangeOAuthCode(
endpoints,
provider.client_id,
clientSecret,
code,
stateData.redirectUri
);
claims = await fetchOAuthUserInfo(endpoints, tokens.access_token);
} else {
// Fetch OIDC discovery and JWKS
const discovery = await fetchOIDCDiscovery(provider.issuer_url);
const jwks = await fetchJWKS(discovery.jwks_uri);
// Decrypt client secret
const clientSecret = await decryptSecret(provider.client_secret_encrypted, c.env);
// Exchange code for tokens
const tokens = await exchangeCodeForTokens(
discovery,
provider.client_id,
clientSecret,
code,
stateData.redirectUri
);
// Validate ID token and extract claims
claims = await validateIDToken(
tokens.id_token,
provider.issuer_url,
provider.client_id,
stateData.nonce,
jwks
);
}
// Check if user link exists
let userLink = await db.prepare(`
SELECT * FROM idp_user_links WHERE provider_id = ? AND external_id = ?
`).bind(providerId, claims.sub).first<IdPUserLink>();
let userId: string;
if (userLink) {
// Existing user - update last login
userId = userLink.user_id;
await db.prepare(`
UPDATE idp_user_links SET last_login_at = ?, external_email = ?, external_name = ?
WHERE id = ?
`).bind(Date.now(), claims.email || null, claims.name || null, userLink.id).run();
} else {
// New user
if (!provider.auto_create_users) {
return c.html(generateErrorPage(
'Account Not Found',
'No account is linked to this identity. Please contact your administrator.'
));
}
// Derive username from claims
const username = deriveUsername(claims, provider.username_claim);
userId = formatUserId(username, c.env.SERVER_NAME);
// Check if Matrix user already exists
const existingUser = await getUserById(db, userId);
if (existingUser) {
// User exists but not linked - check if we should auto-link or error
// For now, auto-link if the user exists
await db.prepare(`
INSERT INTO idp_user_links (provider_id, external_id, user_id, external_email, external_name, last_login_at)
VALUES (?, ?, ?, ?, ?, ?)
`).bind(providerId, claims.sub, userId, claims.email || null, claims.name || null, Date.now()).run();
} else {
// Create new Matrix user
await createUser(db, userId, username, null, false);
// Set display name if available
if (claims.name) {
await db.prepare(`
UPDATE users SET display_name = ? WHERE user_id = ?
`).bind(claims.name, userId).run();
}
// Create user link
await db.prepare(`
INSERT INTO idp_user_links (provider_id, external_id, user_id, external_email, external_name, last_login_at)
VALUES (?, ?, ?, ?, ?, ?)
`).bind(providerId, claims.sub, userId, claims.email || null, claims.name || null, Date.now()).run();
}
}
// Spec SSO login: redirect back to the client with a one-time login
// token (exchanged at POST /login via m.login.token) rather than minting
// a session here — the client picks its own device_id that way.
if (stateData.ssoRedirectUrl) {
const loginToken = generateRandomString(32);
const loginTokenHash = await hashToken(loginToken);
await c.env.SESSIONS.put(
`login_token:${loginTokenHash}`,
JSON.stringify({ user_id: userId, expires_at: Date.now() + 2 * 60 * 1000 }),
{ expirationTtl: 120 }
);
const redirect = new URL(stateData.ssoRedirectUrl);
redirect.searchParams.set('loginToken', loginToken);
return c.redirect(redirect.toString());
}
// Generate Matrix access token
const deviceId = await generateDeviceId();
await createDevice(db, userId, deviceId, `SSO Login (${provider.name})`);
const accessToken = await generateAccessToken();
const tokenHash = await hashToken(accessToken);
const tokenId = await generateOpaqueId(16);
await createAccessToken(db, tokenId, tokenHash, userId, deviceId);
// Return success page with token (or redirect)
return c.html(generateSuccessPage(userId, accessToken, deviceId, c.env.SERVER_NAME, stateData.returnTo));
} catch (err) {
console.error('OIDC callback error:', err);
return c.html(generateErrorPage('Authentication Failed', String(err)));
}
});
// Helper to generate error page HTML
function generateErrorPage(title: string, message: string): string {
return `<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>${title}</title>
<style>
body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; background: #0f172a; color: #f1f5f9; display: flex; align-items: center; justify-content: center; min-height: 100vh; margin: 0; }
.container { background: #1e293b; padding: 40px; border-radius: 12px; max-width: 400px; text-align: center; border: 1px solid #334155; }
h1 { color: #ef4444; margin-bottom: 16px; }
p { color: #94a3b8; margin-bottom: 24px; }
a { color: #0d9488; text-decoration: none; }
a:hover { text-decoration: underline; }
</style>
</head>
<body>
<div class="container">
<h1>${title}</h1>
<p>${message}</p>
<a href="/">Return to login</a>
</div>
</body>
</html>`;
}
// Helper to generate success page HTML
function generateSuccessPage(userId: string, accessToken: string, deviceId: string, serverName: string, returnTo?: string): string {
return `<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Login Successful</title>
<style>
body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; background: #0f172a; color: #f1f5f9; display: flex; align-items: center; justify-content: center; min-height: 100vh; margin: 0; }
.container { background: #1e293b; padding: 40px; border-radius: 12px; max-width: 500px; text-align: center; border: 1px solid #334155; }
h1 { color: #22c55e; margin-bottom: 16px; }
p { color: #94a3b8; margin-bottom: 24px; }
.info { background: #0f172a; padding: 16px; border-radius: 8px; text-align: left; margin-bottom: 24px; }
.info label { font-size: 12px; color: #64748b; display: block; margin-bottom: 4px; }
.info .value { font-family: monospace; font-size: 13px; word-break: break-all; margin-bottom: 12px; }
.btn { display: inline-block; background: #0d9488; color: white; padding: 12px 24px; border-radius: 8px; text-decoration: none; margin: 8px; }
.btn:hover { background: #0f766e; }
.btn-secondary { background: #334155; }
</style>
</head>
<body>
<div class="container">
<h1>Login Successful!</h1>
<p>You are now logged in as:</p>
<div class="info">
<label>User ID</label>
<div class="value">${userId}</div>
<label>Homeserver</label>
<div class="value">https://${serverName}</div>
<label>Access Token</label>
<div class="value">${accessToken}</div>
<label>Device ID</label>
<div class="value">${deviceId}</div>
</div>
<p style="font-size: 13px; color: #64748b;">Copy these credentials to configure your Matrix client.</p>
<button class="btn" onclick="copyCredentials()">Copy Credentials</button>
<a href="${returnTo || '/'}" class="btn btn-secondary">Continue</a>
</div>
<script>
function copyCredentials() {
const text = \`Homeserver: https://${serverName}
User ID: ${userId}
Access Token: ${accessToken}
Device ID: ${deviceId}\`;
navigator.clipboard.writeText(text).then(() => {
alert('Credentials copied to clipboard!');
});
}
</script>
</body>
</html>`;
}
// GET /_matrix/client/v1/auth_metadata - Get authentication metadata
// Returns information about supported authentication methods (MSC2965 / Matrix v1.17)
// This is the STABLE endpoint as of Matrix v1.17
app.get('/_matrix/client/v1/auth_metadata', async (c) => {
const serverName = c.env.SERVER_NAME;
const baseUrl = `https://${serverName}`;
// Return proper OIDC metadata for this server acting as its own OIDC provider
// This is required for Element Web OIDC-native authentication to work
// All fields must be present for Element Web to accept the configuration
const response = {
issuer: baseUrl,
authorization_endpoint: `${baseUrl}/oauth/authorize`,
token_endpoint: `${baseUrl}/oauth/token`,
revocation_endpoint: `${baseUrl}/oauth/revoke`,
registration_endpoint: `${baseUrl}/oauth/register`,
// Required capabilities
response_types_supported: ['code'],
// js-sdk's isValidAuthMetadata requires both "query" and "fragment" here;
// without this key Element logs "Issuer configuration not valid" and
// disables OIDC/QR features.
response_modes_supported: ['query', 'fragment'],
grant_types_supported: ['authorization_code', 'refresh_token', 'urn:ietf:params:oauth:grant-type:device_code'],
code_challenge_methods_supported: ['S256', 'plain'],
// Additional optional fields that Element Web may check
token_endpoint_auth_methods_supported: ['client_secret_basic', 'client_secret_post', 'none'],
scopes_supported: [
'openid',
'profile',
'email',
'urn:matrix:org.matrix.msc2967.client:api:*',
'urn:matrix:org.matrix.msc2967.client:device:*',
'urn:matrix:client:api:*',
'urn:matrix:client:device:*',
],
// Matrix authentication service extension (MSC3861/MSC4191)
// account_management_uri is where users can manage their account
account_management_uri: `${baseUrl}/admin`,
// Supported account management actions per MSC4191. Only use values the
// matrix-dart-sdk enum knows (profile, cross_signing_reset, device_*,
// account_deactivate); unknown strings make FluffyChat's non-null enum
// lookup throw during discovery.
account_management_actions_supported: [
'org.matrix.profile',
'org.matrix.cross_signing_reset',
'org.matrix.devices_list',
'org.matrix.device_view',
'org.matrix.device_delete',
'org.matrix.account_deactivate',
],
// Device authorization endpoint for QR code login (MSC4108)
device_authorization_endpoint: `${baseUrl}/oauth/device`,
// Prompt values we support
prompt_values_supported: ['create'],
// Full OIDC fields: matrix_oidc_client (FluffyChat) parses the auth
// metadata with strict non-nullable types — jwks_uri absent made its
// client registration step crash with "null: type 'minified:W6' is not
// a subtype of type 'String" right after POST /oauth/register
// succeeded. Mirror the /.well-known/openid-configuration document so
// every OIDC consumer finds the same complete provider metadata here.
jwks_uri: `${baseUrl}/.well-known/jwks.json`,
userinfo_endpoint: `${baseUrl}/oauth/userinfo`,
introspection_endpoint: `${baseUrl}/oauth/introspect`,
id_token_signing_alg_values_supported: ['ES256'],
subject_types_supported: ['public'],
claims_supported: ['sub', 'iss', 'aud', 'exp', 'iat', 'nonce', 'preferred_username', 'name', 'picture'],
};
return c.json(response);
});
// ============================================
// MSC3861 Identity Reset Endpoint
// ============================================
// Helper to get next stream position (same pattern as keys.ts)
async function getNextStreamPosition(db: D1Database, streamName: string): Promise<number> {
await db.prepare(`
UPDATE stream_positions SET position = position + 1 WHERE stream_name = ?
`).bind(streamName).run();
const result = await db.prepare(`
SELECT position FROM stream_positions WHERE stream_name = ?
`).bind(streamName).first<{ position: number }>();
return result?.position || 1;
}
// Helper to get Durable Object for user keys
function getUserKeysDO(env: any, userId: string) {
const id = env.USER_KEYS.idFromName(userId);
return env.USER_KEYS.get(id);
}
// POST /_matrix/client/unstable/org.matrix.msc3861/account/identity/reset
// Allows OIDC users to reset their cross-signing identity
// Per MSC3861:
// 1. Requires OIDC re-authentication (valid access token)
// 2. Deletes all cross-signing keys for the user
// 3. Returns 200 on success
// Identity reset (MSC3861) hardening — audit 007.3: cross-signing resets are
// destructive to E2EE trust, so cap them per user. The device_key_changes
// INSERT inside the handler doubles as the durable audit trail this reads.
const IDENTITY_RESET_LIMIT = 3;
const IDENTITY_RESET_WINDOW_MS = 60 * 60 * 1000;
app.post('/_matrix/client/unstable/org.matrix.msc3861/account/identity/reset', requireAuth(), async (c) => {
const userId = c.get('userId');
const db = c.env.DB;
// Per-user rate limit: 3 resets per hour. D1-backed so the window holds
// across isolates — the shared RateLimit DO evicts windows older than
// ~2 minutes, so it cannot enforce an hourly limit.
try {
const recent = await db
.prepare(
`SELECT COUNT(*) as count, MIN(created_at) as oldest FROM device_key_changes
WHERE user_id = ? AND change_type = 'cross_signing_reset' AND created_at > ?`
)
.bind(userId, Date.now() - IDENTITY_RESET_WINDOW_MS)
.first<{ count: number; oldest: number | null }>();
const count = recent?.count ?? 0;
if (count >= IDENTITY_RESET_LIMIT) {
const retryAfterMs =
recent?.oldest != null
? recent.oldest + IDENTITY_RESET_WINDOW_MS - Date.now()
: IDENTITY_RESET_WINDOW_MS;
console.warn(`[OIDC] Identity reset rate-limited for ${userId} (${count} in window)`);
return c.json(
{
errcode: 'M_LIMIT_EXCEEDED',
error: 'Too many identity resets',
retry_after_ms: retryAfterMs,
},
429
);
}
} catch (err) {
// Fail open: if the count query fails, the destructive operations below
// surface the real D1 problem; blocking here would take identity reset
// down during a database blip.
console.warn('[OIDC] Identity reset rate-limit check failed:', err);
}
try {
// Delete cross-signing keys from Durable Object (primary storage)
const stub = getUserKeysDO(c.env, userId);
await stub.fetch(new Request('http://internal/cross-signing/delete', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
}));
// Delete cross-signing keys from D1 (backup storage)
await db.prepare('DELETE FROM cross_signing_keys WHERE user_id = ?').bind(userId).run();
// Delete cross-signing signatures
await db.prepare('DELETE FROM cross_signing_signatures WHERE user_id = ? OR signer_user_id = ?').bind(userId, userId).run();
// Delete from KV (cache)
await c.env.CROSS_SIGNING_KEYS.delete(`user:${userId}`);
// Record key change to trigger device list update for other users
const streamPosition = await getNextStreamPosition(db, 'device_keys');
await db.prepare(`
INSERT INTO device_key_changes (user_id, device_id, change_type, stream_position)
VALUES (?, NULL, 'cross_signing_reset', ?)
`).bind(userId, streamPosition).run();
console.log(`[OIDC] Cross-signing identity reset for user ${userId}`);
// Return empty object on success per MSC3861
return c.json({});
} catch (err) {
console.error(`[OIDC] Identity reset failed for ${userId}:`, err);
return c.json({ errcode: 'M_UNKNOWN', error: 'Failed to reset identity' }, 500);
}
});
// Export encryption helpers for admin API
export { encryptSecret, decryptSecret };
export default app;