Repository navigation
Expand file tree
/
Copy pathoauth-server.js
More file actions
2467 lines (2198 loc) · 88.2 KB
/
Copy pathoauth-server.js
File metadata and controls
2467 lines (2198 loc) · 88.2 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
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* Dedicated OAuth Server
* Handles GitHub OAuth flow with clean separation from AI bridge
* Neuroplastic architecture - each server has one clear purpose
*/
import express from 'express';
import cors from 'cors';
import crypto from 'crypto';
import rateLimit from 'express-rate-limit';
import fetch from 'node-fetch';
import dotenv from 'dotenv';
import jwt from 'jsonwebtoken';
import { existsSync, readFileSync, realpathSync } from 'fs';
import { fileURLToPath } from 'url';
import { resolve as pathResolve } from 'path';
import tokenVault from './src/services/server/tokenVault.js';
import userAnalytics from './src/services/UserAnalytics.js';
// Load environment variables
dotenv.config();
// Load GitHub App credentials from github.env.local if present (local dev only)
if (existsSync('github.env.local')) {
dotenv.config({ path: 'github.env.local', override: false });
}
// If GITHUB_APP_PRIVATE_KEY is not set but PRIVATE_KEY_PATH is, read the PEM file
if (!process.env.GITHUB_APP_PRIVATE_KEY && process.env.PRIVATE_KEY_PATH) {
const pemPath = process.env.PRIVATE_KEY_PATH;
if (existsSync(pemPath)) {
process.env.GITHUB_APP_PRIVATE_KEY = readFileSync(pemPath, 'utf8');
console.log(`[OAuth] Loaded GitHub App private key from ${pemPath}`);
} else {
console.warn(`[OAuth] PRIVATE_KEY_PATH set to "${pemPath}" but file not found`);
}
}
// Load dev private key from PRIVATE_KEY_PATH_DEV (for Electron dev with a separate GitHub App)
if (!process.env.GITHUB_APP_PRIVATE_KEY_DEV && process.env.PRIVATE_KEY_PATH_DEV) {
const devPemPath = process.env.PRIVATE_KEY_PATH_DEV;
if (existsSync(devPemPath)) {
process.env.GITHUB_APP_PRIVATE_KEY_DEV = readFileSync(devPemPath, 'utf8');
console.log(`[OAuth] Loaded dev GitHub App private key from ${devPemPath}`);
} else {
console.warn(`[OAuth] PRIVATE_KEY_PATH_DEV set to "${devPemPath}" but file not found`);
}
}
// STATELESS MODE: User data stays in browser localStorage, not server
// Server only facilitates OAuth exchange, does NOT persist tokens
const ENABLE_SERVER_PERSISTENCE = process.env.ENABLE_SERVER_PERSISTENCE === 'true' || false;
// Environment-based logging control
const isProduction = process.env.NODE_ENV === 'production';
const LOG_LEVEL = process.env.LOG_LEVEL || (isProduction ? 'warn' : 'info');
// Create a logger that respects environment settings
const logger = {
info: (...args) => {
if (LOG_LEVEL === 'info' || LOG_LEVEL === 'debug') {
console.log(...args);
}
},
warn: (...args) => {
if (LOG_LEVEL === 'warn' || LOG_LEVEL === 'info' || LOG_LEVEL === 'debug') {
console.warn(...args);
}
},
error: (...args) => {
// Always log errors
console.error(...args);
},
debug: (...args) => {
if (LOG_LEVEL === 'debug') {
console.log('[DEBUG]', ...args);
}
}
};
const app = express();
const PORT = process.env.OAUTH_PORT || 3002;
// Trust the first proxy hop so rate limiting sees the real client IP behind
// GCP Cloud Run / the load balancer (this server may run on its own service).
app.set('trust proxy', 1);
// CORS: restrict to known origins. Defaults to the production domain; extend
// via CORS_ORIGINS env (comma-separated) for dev/staging. Same allowlist as
// app-semantic-server.js so the two stay in sync.
const allowedOrigins = new Set(
(process.env.CORS_ORIGINS || 'https://redstring.io,https://www.redstring.io')
.split(',')
.map((s) => s.trim())
.filter(Boolean)
);
app.use(cors({
origin: (origin, callback) => {
if (!origin) return callback(null, true);
if (allowedOrigins.has(origin)) return callback(null, true);
// Local development: the app is served from a Vite port (e.g.
// http://localhost:4001) and calls this server directly at :3002, which
// is cross-origin. Auto-allow localhost/127.0.0.1 origins when NOT in
// production so onboarding/auth work out of the box without needing
// CORS_ORIGINS set. Production (NODE_ENV=production) never takes this path.
if ((process.env.NODE_ENV || 'development').toLowerCase() !== 'production') {
try {
const host = new URL(origin).hostname;
if (host === 'localhost' || host === '127.0.0.1' || host === '[::1]' || host === '::1') {
return callback(null, true);
}
} catch { /* invalid Origin */ }
}
// Cloud Run domains are shared/registrable infrastructure, so this broad
// allowance is opt-in via ALLOW_CLOUDRUN_ORIGINS=true. Prefer setting
// CORS_ORIGINS to the exact staging/prod hosts instead.
if (process.env.ALLOW_CLOUDRUN_ORIGINS === 'true') {
try {
const host = new URL(origin).hostname;
if (host.endsWith('.a.run.app') || host.endsWith('.run.app')) {
return callback(null, true);
}
} catch { /* invalid Origin */ }
}
// Silently omit CORS headers instead of throwing 500. Same-origin loads
// (browser sends Origin for `<script type="module" crossorigin>` even
// when same-origin) need to succeed; cross-origin gets blocked correctly
// by the missing Access-Control-Allow-Origin header.
return callback(null, false);
},
credentials: false,
}));
// Capture raw bytes so the webhook handler can verify HMAC signatures.
app.use(express.json({
verify: (req, _res, buf) => { req.rawBody = buf; },
}));
// Rate limiters
const oauthSensitiveLimiter = rateLimit({
windowMs: 60 * 1000,
max: 10,
standardHeaders: true,
legacyHeaders: false,
message: { error: 'Rate limit exceeded for OAuth endpoint.' },
});
const oauthGlobalLimiter = rateLimit({
windowMs: 60 * 1000,
max: 120,
standardHeaders: true,
legacyHeaders: false,
skip: (req) => req.path === '/health',
message: { error: 'Too many requests, slow down.' },
});
app.use(oauthGlobalLimiter);
// Enhanced health check with detailed configuration status
app.get('/health', (req, res) => {
const clientId = process.env.GITHUB_CLIENT_ID;
const clientSecret = process.env.GITHUB_CLIENT_SECRET;
// S-09: configuration details stay in the server log, not the response.
if (!(clientId && clientSecret)) logger.warn('[OAuth] Health: OAuth client id/secret not configured');
res.json({
status: 'healthy',
service: 'oauth-server'
});
});
// Helper to detect if this server is running in a dev/test environment.
// Host-header detection used to live here, but the OAuth server is reached via
// an in-container proxy (app-semantic-server.js → http://localhost:3002), so
// every request looks "local" regardless of the original request's hostname.
// NODE_ENV is set per Cloud Run service (production for redstring-prod,
// development for redstring-test, development locally) — deterministic and
// proxy-safe.
function isLocalRequest(_req) {
const env = (process.env.NODE_ENV || 'development').toLowerCase();
return env !== 'production';
}
const GITHUB_USER_INSTALLATIONS_URL = 'https://api.github.com/user/installations';
function resolveGitHubAppIdentifiers() {
const ids = [];
const idCandidates = [
process.env.GITHUB_APP_ID,
process.env.GITHUB_APP_ID_DEV
];
for (const value of idCandidates) {
if (!value) continue;
const numeric = Number(value);
if (!Number.isNaN(numeric)) {
ids.push(numeric);
}
}
const prodSlug = process.env.GITHUB_APP_SLUG || 'redstring-semantic-sync';
const devSlug = process.env.GITHUB_APP_SLUG_DEV || prodSlug;
const slugs = Array.from(new Set(
[prodSlug, devSlug]
.map((slug) => (slug || '').trim())
.filter((slug) => slug.length > 0)
));
return { ids, slugs };
}
// =============================================================================
// Installation ownership (contract C-9) — the same algorithm as
// functions/_lib/ownership.ts, which is what redstring.io runs. Fail closed:
// GET /user (caller token) → GET /app/installations/{id} (App JWT) → a User
// install must belong to the caller; an Organization install needs an active
// membership. Any GitHub error, unexpected shape, suspended install, other
// App's install or other target type is a denial — never "mint anyway".
// =============================================================================
const GH_API = 'https://api.github.com';
const OWNERSHIP_USER_AGENT = 'Redstring-GitHubApp-Server/1.0';
const isPositiveSafeInt = (v) => typeof v === 'number' && Number.isSafeInteger(v) && v > 0;
function parseInstallationId(raw) {
if (typeof raw === 'number') return isPositiveSafeInt(raw) ? raw : null;
if (typeof raw !== 'string' || !/^[1-9][0-9]{0,15}$/.test(raw)) return null;
const n = Number(raw);
return isPositiveSafeInt(n) ? n : null;
}
async function ownershipGetJson(url, authorization) {
let res;
try {
res = await fetch(url, {
headers: {
'Accept': 'application/vnd.github+json',
'Authorization': authorization,
'User-Agent': OWNERSHIP_USER_AGENT,
'X-GitHub-Api-Version': '2022-11-28'
},
redirect: 'manual'
});
} catch {
return null;
}
if (!res.ok) {
try { await res.text(); } catch { /* ignore */ }
return { status: res.status, body: null };
}
try {
return { status: res.status, body: await res.json() };
} catch {
return { status: 0, body: null };
}
}
async function verifyInstallOwnership(rawId, oauthToken, appJwtStr, configuredAppId) {
const deny = (code, status) => ({ ok: false, code, status });
const installationId = parseInstallationId(rawId);
if (installationId == null) return deny('invalid_installation_id', 400);
if (typeof oauthToken !== 'string' || !oauthToken || oauthToken.length > 512 || !/^[\x21-\x7e]+$/.test(oauthToken)) {
return deny('oauth_required', 401);
}
if (oauthToken.startsWith('ghs_')) return deny('wrong_token_type', 400);
const appId = typeof configuredAppId === 'string' && /^[1-9][0-9]{0,15}$/.test(configuredAppId.trim())
? Number(configuredAppId.trim())
: configuredAppId;
if (!isPositiveSafeInt(appId)) return deny('app_not_configured', 500);
if (typeof appJwtStr !== 'string' || !appJwtStr) return deny('app_not_configured', 500);
const userRes = await ownershipGetJson(`${GH_API}/user`, `token ${oauthToken}`);
if (!userRes) return deny('github_error', 502);
if (userRes.status === 401) return deny('oauth_invalid', 401);
if (userRes.status !== 200) return deny('github_error', 502);
const user = userRes.body;
if (!isPositiveSafeInt(user?.id) || typeof user?.login !== 'string') return deny('github_error', 502);
const instRes = await ownershipGetJson(`${GH_API}/app/installations/${installationId}`, `Bearer ${appJwtStr}`);
if (!instRes) return deny('github_error', 502);
if (instRes.status === 404) return deny('installation_not_found', 404);
if (instRes.status === 401) return deny('github_app_auth_failed', 502);
if (instRes.status !== 200) return deny('github_error', 502);
const inst = instRes.body;
if (!inst || typeof inst !== 'object' || inst.id !== installationId) return deny('github_error', 502);
if (!isPositiveSafeInt(inst.app_id) || inst.app_id !== appId) return deny('app_credentials_mismatch', 409);
if (inst.suspended_at) return deny('installation_suspended', 403);
const account = inst.account;
if (!account || !isPositiveSafeInt(account.id) || typeof account.login !== 'string' || !account.login) {
return deny('github_error', 502);
}
if (account.type != null && account.type !== inst.target_type) return deny('unsupported_target', 403);
const ok = () => ({ ok: true, installationId: inst.id, installation: inst, user: { id: user.id, login: user.login } });
if (inst.target_type === 'User') {
return account.id === user.id ? ok() : deny('account_mismatch', 403);
}
if (inst.target_type === 'Organization') {
const memRes = await ownershipGetJson(
`${GH_API}/user/memberships/orgs/${encodeURIComponent(account.login)}`,
`token ${oauthToken}`
);
if (!memRes) return deny('github_error', 502);
if (memRes.status === 401) return deny('oauth_invalid', 401);
if (memRes.status === 403 || memRes.status === 404) return deny('not_org_member', 403);
if (memRes.status !== 200) return deny('github_error', 502);
const m = memRes.body;
if (m?.state === 'active' && isPositiveSafeInt(m?.organization?.id) && m.organization.id === account.id) {
return ok();
}
return deny('not_org_member', 403);
}
return deny('unsupported_target', 403);
}
const OWNERSHIP_MESSAGES = {
invalid_installation_id: 'Invalid installation ID',
oauth_required: 'OAuth token required',
wrong_token_type: 'Wrong token type',
app_not_configured: 'GitHub App not configured',
oauth_invalid: 'GitHub OAuth token is invalid or expired. Please reconnect OAuth and retry.',
installation_not_found: 'Installation not found',
app_credentials_mismatch: 'GitHub App credential mismatch',
installation_suspended: 'Installation suspended',
account_mismatch: 'GitHub App installation not accessible for the connected OAuth account',
not_org_member: 'GitHub App installation not accessible for the connected OAuth account',
unsupported_target: 'GitHub App installation not accessible for the connected OAuth account',
github_app_auth_failed: 'GitHub App authentication failed',
github_error: 'GitHub request failed'
};
function configuredAppSlots() {
return [
{
slot: 'prod',
appId: process.env.GITHUB_APP_ID ? Number(process.env.GITHUB_APP_ID) : null,
privateKey: process.env.GITHUB_APP_PRIVATE_KEY || null,
slug: process.env.GITHUB_APP_SLUG || null
},
{
slot: 'dev',
appId: process.env.GITHUB_APP_ID_DEV ? Number(process.env.GITHUB_APP_ID_DEV) : null,
privateKey: process.env.GITHUB_APP_PRIVATE_KEY_DEV || null,
slug: process.env.GITHUB_APP_SLUG_DEV || null
}
].filter((c) => isPositiveSafeInt(c.appId) && c.privateKey);
}
function signAppJwt(appId, privateKey) {
const now = Math.floor(Date.now() / 1000);
return jwt.sign({ iat: now - 60, exp: now + (10 * 60), iss: appId }, privateKey, { algorithm: 'RS256' });
}
// Route gate: requires `Authorization: token <oauth_token>` from the caller
// and proves ownership against whichever configured App (prod/dev slot) owns
// the installation. Sends the refusal itself and returns null, or returns
// { installationId, installation, user, appJWT, slot }.
async function requireInstallOwnership(req, res, rawInstallationId) {
const authHeader = req.headers.authorization || '';
const match = authHeader.match(/^(?:token|Bearer)\s+(.+)$/i);
const oauthToken = match ? match[1].trim() : null;
if (!oauthToken) {
res.status(401).json({ error: OWNERSHIP_MESSAGES.oauth_required, code: 'oauth_required', service: 'oauth-server' });
return null;
}
const slots = configuredAppSlots();
if (slots.length === 0) {
res.status(500).json({ error: OWNERSHIP_MESSAGES.app_not_configured, code: 'app_not_configured', service: 'oauth-server' });
return null;
}
let result = null;
for (const slot of slots) {
let appJWT;
try {
appJWT = signAppJwt(slot.appId, slot.privateKey);
} catch (e) {
logger.error('[GitHubApp] JWT signing failed for slot', slot.slot, e?.message || e);
result = { ok: false, code: 'app_not_configured', status: 500 };
continue;
}
result = await verifyInstallOwnership(rawInstallationId, oauthToken, appJWT, slot.appId);
if (result.ok) return { ...result, appJWT, slot };
// Only "this App has no such install" moves on to the next configured App.
if (result.code !== 'installation_not_found') break;
}
logger.warn('[GitHubApp] Installation access denied:', { code: result.code });
res.status(result.status).json({ error: OWNERSHIP_MESSAGES[result.code], code: result.code, service: 'oauth-server' });
return null;
}
async function findInstallationViaOAuth(accessToken, installationId) {
if (!accessToken) {
return { ok: false, status: 0, reason: 'missing_token' };
}
const perPage = 100;
const targetId = installationId != null ? Number(installationId) : null;
if (targetId == null || Number.isNaN(targetId)) {
return { ok: false, status: 0, reason: 'invalid_installation_id' };
}
let page = 1;
const maxPages = 10; // Safety cap
let lastStatus = null;
while (page <= maxPages) {
const url = `${GITHUB_USER_INSTALLATIONS_URL}?per_page=${perPage}&page=${page}`;
let response;
try {
response = await fetch(url, {
headers: {
'Accept': 'application/vnd.github.v3+json',
'Authorization': `token ${accessToken}`,
'User-Agent': 'Redstring-OAuth-Server/1.0'
}
});
} catch (networkError) {
return { ok: false, status: 0, reason: 'network_error', error: networkError };
}
lastStatus = response.status;
if (!response.ok) {
const text = await response.text().catch(() => '');
return {
ok: false,
status: response.status,
reason: 'github_error',
details: text
};
}
let data;
try {
data = await response.json();
} catch (parseError) {
return {
ok: false,
status: response.status,
reason: 'parse_error',
error: parseError
};
}
const installations = Array.isArray(data?.installations) ? data.installations : [];
const match = installations.find((installation) => Number(installation?.id) === targetId);
if (match) {
return { ok: true, installation: match };
}
const linkHeader = response.headers.get('link') || '';
if (!/\brel="next"/.test(linkHeader) || installations.length === 0) {
break;
}
page += 1;
}
return { ok: true, installation: null, status: lastStatus };
}
async function listInstallationsViaOAuth(accessToken) {
if (!accessToken) {
return { ok: false, status: 0, reason: 'missing_token', installations: [] };
}
const allInstallations = [];
const perPage = 100;
let page = 1;
const maxPages = 10;
while (page <= maxPages) {
const url = `${GITHUB_USER_INSTALLATIONS_URL}?per_page=${perPage}&page=${page}`;
let response;
try {
response = await fetch(url, {
headers: {
'Accept': 'application/vnd.github.v3+json',
'Authorization': `token ${accessToken}`,
'User-Agent': 'Redstring-OAuth-Server/1.0'
}
});
} catch (networkError) {
return { ok: false, status: 0, reason: 'network_error', error: networkError, installations: [] };
}
if (!response.ok) {
const text = await response.text().catch(() => '');
return {
ok: false,
status: response.status,
reason: 'github_error',
details: text,
installations: []
};
}
let data;
try {
data = await response.json();
} catch (parseError) {
return {
ok: false,
status: response.status,
reason: 'parse_error',
error: parseError,
installations: []
};
}
const installations = Array.isArray(data?.installations) ? data.installations : [];
allInstallations.push(...installations);
const linkHeader = response.headers.get('link') || '';
if (!/\brel="next"/.test(linkHeader) || installations.length === 0) {
break;
}
page += 1;
}
return { ok: true, installations: allInstallations };
}
async function fetchInstallationRepositoriesViaOAuth(accessToken, installationId) {
if (!accessToken || !installationId) {
return [];
}
try {
const response = await fetch(`https://api.github.com/user/installations/${installationId}/repositories`, {
headers: {
'Accept': 'application/vnd.github.v3+json',
'Authorization': `token ${accessToken}`,
'User-Agent': 'Redstring-OAuth-Server/1.0'
}
});
if (!response.ok) {
const text = await response.text().catch(() => '');
logger.warn('[GitHubApp] OAuth repository listing failed:', {
installationId,
status: response.status,
reason: text
});
return [];
}
const repoData = await response.json();
if (Array.isArray(repoData?.repositories)) {
return repoData.repositories;
}
} catch (error) {
logger.warn('[GitHubApp] OAuth repository listing error:', {
installationId,
error: error.message
});
}
return [];
}
async function discoverInstallationViaOAuth(accessToken) {
const { ids, slugs } = resolveGitHubAppIdentifiers();
if (!accessToken || (ids.length === 0 && slugs.length === 0)) {
return null;
}
const listResult = await listInstallationsViaOAuth(accessToken);
if (!listResult.ok) {
logger.debug('[GitHubApp] Installation discovery failed via OAuth:', {
status: listResult.status,
reason: listResult.reason || null,
details: listResult.details || null
});
return null;
}
const matches = listResult.installations || [];
const match = matches.find((installation) => {
const slug = installation?.app_slug;
const appId = Number(installation?.app_id);
const slugMatch = slug && slugs.includes(slug);
const idMatch = !Number.isNaN(appId) && ids.includes(appId);
return slugMatch || idMatch;
});
if (!match) {
return null;
}
const repositories = await fetchInstallationRepositoriesViaOAuth(accessToken, match.id);
return {
installationId: match.id,
account: match.account || null,
permissions: match.permissions || null,
repositories,
installation: match
};
}
function createVerificationRecord(result, oauthCredentials) {
if (!result) {
return null;
}
const oauthLogin = result.oauthUser?.login || oauthCredentials?.user?.login || null;
const trimmedDetails = typeof result.details === 'string'
? result.details.slice(0, 2000)
: null;
return {
status: result.status,
reason: result.reason || null,
installationId: result.installation?.id ?? result.checkedInstallationId ?? null,
installationAccount: result.installation?.account?.login ?? null,
targetType: result.installation?.target_type ?? null,
// Capture which GitHub App the install actually belongs to. Without this,
// a deployment configured for a different App than the install will mint
// with the wrong key and GitHub returns an opaque 404. Surfacing app_id
// and app_slug to the client lets the diagnostic panel say exactly which
// App owns the install vs. which one the deployment is configured for.
appId: result.installation?.app_id ?? null,
appSlug: result.installation?.app_slug ?? null,
oauthLogin,
statusCode: result.statusCode ?? null,
details: trimmedDetails,
checkedInstallationId: result.checkedInstallationId ?? (result.installation?.id ?? null),
checkedAt: Date.now()
};
}
function formatVerificationForResponse(record) {
if (!record) {
return null;
}
const response = {
status: record.status || null,
reason: record.reason || null,
oauthLogin: record.oauthLogin || null,
installationId: record.installationId ?? null,
checkedInstallationId: record.checkedInstallationId ?? null,
installationAccount: record.installationAccount || null,
targetType: record.targetType || null,
appId: record.appId ?? null,
appSlug: record.appSlug || null,
statusCode: record.statusCode ?? null,
details: record.details || null,
checkedAt: record.checkedAt ? new Date(record.checkedAt).toISOString() : null
};
Object.keys(response).forEach((key) => {
if (response[key] == null) {
delete response[key];
}
});
return response;
}
function verificationRecordsEqual(a, b) {
if (!a && !b) return true;
if (!a || !b) return false;
return (
(a.status || null) === (b.status || null) &&
(a.reason || null) === (b.reason || null) &&
(a.installationId ?? null) === (b.installationId ?? null) &&
(a.checkedInstallationId ?? null) === (b.checkedInstallationId ?? null) &&
(a.installationAccount || null) === (b.installationAccount || null) &&
(a.targetType || null) === (b.targetType || null) &&
(a.oauthLogin || null) === (b.oauthLogin || null) &&
(a.statusCode ?? null) === (b.statusCode ?? null) &&
(a.details || null) === (b.details || null)
);
}
async function verifyInstallationWithOAuth(installationId, oauthCredentials, { enforceAccountMatch = true } = {}) {
const numericInstallationId = installationId != null ? Number(installationId) : null;
if (numericInstallationId == null || Number.isNaN(numericInstallationId)) {
return {
status: 'missing_installation',
reason: 'missing_installation_id',
installation: null,
oauthUser: oauthCredentials?.user || null,
checkedInstallationId: null
};
}
if (!oauthCredentials?.accessToken) {
return {
status: 'skipped',
reason: 'oauth_not_connected',
installation: null,
oauthUser: oauthCredentials?.user || null,
checkedInstallationId: numericInstallationId
};
}
const lookup = await findInstallationViaOAuth(oauthCredentials.accessToken, numericInstallationId);
const oauthUser = oauthCredentials.user || null;
if (!lookup.ok) {
if (lookup.status === 401) {
return {
status: 'oauth_invalid',
reason: 'oauth_token_invalid',
installation: null,
oauthUser,
statusCode: lookup.status,
details: lookup.details || null,
checkedInstallationId: numericInstallationId
};
}
if (lookup.status === 404) {
return {
status: 'not_found',
reason: 'installation_not_found',
installation: null,
oauthUser,
statusCode: lookup.status,
details: lookup.details || null,
checkedInstallationId: numericInstallationId
};
}
// 403: token is valid but lacks scope to list installations. GitHub
// requires `read:org` on /user/installations even for personal installs
// in some configurations. This is NOT an indictment of the install
// itself — the mint API is the authoritative source. Mark as
// 'unverified' so the mint endpoint can choose to proceed instead of
// failing closed on a verification step that can't even run.
if (lookup.status === 403) {
return {
status: 'unverified',
reason: 'oauth_scope_insufficient',
installation: null,
oauthUser,
statusCode: lookup.status,
details: lookup.details || 'OAuth token lacks read:org scope required by /user/installations',
checkedInstallationId: numericInstallationId
};
}
return {
status: 'error',
reason: lookup.reason || 'github_request_failed',
installation: null,
oauthUser,
statusCode: lookup.status || null,
details: lookup.details || null,
checkedInstallationId: numericInstallationId
};
}
if (!lookup.installation) {
const defaultDetail = 'GitHub did not include this installation in /user/installations for the current OAuth token. Tokens without read:org scope cannot enumerate organization installs.';
return {
status: 'unverified',
reason: lookup.reason || 'installation_not_listed',
installation: null,
oauthUser,
statusCode: lookup.status || null,
details: lookup.details || defaultDetail,
checkedInstallationId: numericInstallationId
};
}
const installation = lookup.installation;
if (
enforceAccountMatch &&
installation?.target_type === 'User' &&
oauthUser?.id &&
installation?.account?.id &&
installation.account.id !== oauthUser.id
) {
return {
status: 'account_mismatch',
reason: 'installation_account_mismatch',
installation,
oauthUser,
checkedInstallationId: numericInstallationId
};
}
return {
status: 'verified',
reason: null,
installation,
oauthUser,
checkedInstallationId: numericInstallationId
};
}
// Get GitHub OAuth client ID with enhanced validation and dev/prod selection
app.get('/api/github/oauth/client-id', (req, res) => {
try {
const useDev = isLocalRequest(req);
const clientId = useDev
? (process.env.GITHUB_CLIENT_ID_DEV || process.env.GITHUB_CLIENT_ID || null)
: (process.env.GITHUB_CLIENT_ID || null);
const clientSecret = useDev
? (process.env.GITHUB_CLIENT_SECRET_DEV || process.env.GITHUB_CLIENT_SECRET || null)
: (process.env.GITHUB_CLIENT_SECRET || null);
// Enhanced validation
const isConfigured = !!(clientId && clientSecret);
const clientIdValid = clientId && clientId.trim().length > 0;
const clientSecretValid = clientSecret && clientSecret.trim().length > 0;
logger.debug('[OAuth] Client ID request:', {
configured: isConfigured,
clientIdValid,
clientSecretValid,
clientIdLength: clientId ? clientId.length : 0,
clientSecretLength: clientSecret ? clientSecret.length : 0,
selection: useDev ? 'dev' : 'prod'
});
res.json({
clientId: clientIdValid ? clientId.trim() : null,
configured: isConfigured,
clientIdValid,
clientSecretValid,
selection: useDev ? 'dev' : 'prod',
service: 'oauth-server'
});
} catch (error) {
logger.error('[OAuth] Failed to get client ID:', error);
res.status(500).json({
error: 'Failed to get client ID',
service: 'oauth-server',
details: error.message
});
}
});
// OAuth callback handler — GitHub redirects here after user authorizes.
// Detects Electron vs browser via state prefix and redirects accordingly.
app.get('/oauth/callback', (req, res) => {
const { code, state, error } = req.query;
if (error) {
logger.error('[OAuth] GitHub callback error:', error);
// Plain text: `error` comes straight from the query string.
return res.status(400).type('text/plain').send('GitHub OAuth error');
}
if (!code || !state) {
return res.status(400).send('Missing code or state from GitHub OAuth callback');
}
// Browser flow: redirect back to the frontend app with code/state as query params
const frontendPort = process.env.PORT || 4001;
const frontendUrl = `http://localhost:${frontendPort}?code=${encodeURIComponent(code)}&state=${encodeURIComponent(state)}`;
logger.info('[OAuth] Redirecting to frontend app');
return res.redirect(frontendUrl);
});
// Refresh OAuth access token
app.post('/api/github/oauth/refresh', oauthSensitiveLimiter, async (req, res) => {
try {
const { refresh_token, redirect_uri } = req.body;
logger.debug('[OAuth] Refresh token request:', {
hasRefreshToken: !!refresh_token,
refreshTokenLength: refresh_token ? refresh_token.length : 0
});
if (!refresh_token) {
return res.status(400).json({
error: 'Missing refresh token',
service: 'oauth-server'
});
}
// Select dev/prod OAuth credentials based on redirect_uri or request origin
const redirectHost = (() => {
try { return new URL(redirect_uri).host.toLowerCase(); } catch { return ''; }
})();
const isLocal = redirectHost.includes('localhost') || isLocalRequest(req);
const clientId = isLocal
? (process.env.GITHUB_CLIENT_ID_DEV || process.env.GITHUB_CLIENT_ID)
: process.env.GITHUB_CLIENT_ID;
const clientSecret = isLocal
? (process.env.GITHUB_CLIENT_SECRET_DEV || process.env.GITHUB_CLIENT_SECRET)
: process.env.GITHUB_CLIENT_SECRET;
if (!clientId || !clientSecret) {
return res.status(500).json({
error: 'GitHub OAuth not configured',
service: 'oauth-server'
});
}
logger.debug('[OAuth] Refreshing access token...');
// GitHub doesn't actually support refresh tokens in the traditional sense
// But we can validate the existing token and return it if still valid
// In a real implementation, you'd store refresh tokens and manage them properly
// For now, we'll treat the "refresh_token" as an indication to validate current auth
// This is a simplified implementation - in production you'd want proper refresh token flow
res.status(501).json({
error: 'Token refresh not yet implemented',
message: 'GitHub OAuth uses long-lived tokens. Please re-authenticate if your token has expired.',
service: 'oauth-server'
});
} catch (error) {
console.error('[OAuth] Token refresh failed:', error);
res.status(500).json({
error: error.message,
service: 'oauth-server'
});
}
});
// Validate an OAuth access token against GitHub OAuth App API
app.post('/api/github/oauth/validate', oauthSensitiveLimiter, async (req, res) => {
try {
const { access_token } = req.body || {};
console.log('[OAuth] Validate request received, token length:', access_token ? access_token.length : 0);
if (!access_token) {
console.log('[OAuth] No access token provided');
return res.status(400).json({
error: 'Missing access_token',
service: 'oauth-server'
});
}
// Select dev/prod credentials based on request origin
const useDev = isLocalRequest(req);
const clientId = useDev
? (process.env.GITHUB_CLIENT_ID_DEV || process.env.GITHUB_CLIENT_ID)
: process.env.GITHUB_CLIENT_ID;
const clientSecret = useDev
? (process.env.GITHUB_CLIENT_SECRET_DEV || process.env.GITHUB_CLIENT_SECRET)
: process.env.GITHUB_CLIENT_SECRET;
console.log('[OAuth] Using credentials:', { useDev, clientIdLength: clientId ? clientId.length : 0, clientSecretLength: clientSecret ? clientSecret.length : 0 });
if (!clientId || !clientSecret) {
console.log('[OAuth] Missing OAuth credentials');
return res.status(500).json({
error: 'GitHub OAuth not configured',
service: 'oauth-server'
});
}
const basic = Buffer.from(`${clientId}:${clientSecret}`).toString('base64');
console.log('[OAuth] Making GitHub validation request...');
const ghResp = await fetch(`https://api.github.com/applications/${clientId}/token`, {
method: 'POST',
headers: {
'Accept': 'application/vnd.github.v3+json',
'Authorization': `Basic ${basic}`,
'User-Agent': 'Redstring-OAuth-Server/1.0',
'Content-Type': 'application/json'
},
body: JSON.stringify({ access_token })
});
console.log('[OAuth] GitHub validation response:', ghResp.status, ghResp.statusText);
if (!ghResp.ok) {
const text = await ghResp.text();
console.log('[OAuth] GitHub validation failed:', text);
const status = ghResp.status === 404 || ghResp.status === 401 ? 401 : ghResp.status;
return res.status(status).json({
valid: false,
error: 'Token invalid or revoked',
details: text,
service: 'oauth-server'
});
}
const data = await ghResp.json();
console.log('[OAuth] GitHub validation success, data keys:', Object.keys(data));
// GitHub may return scopes as array or string
let scopes = [];
if (Array.isArray(data.scopes)) scopes = data.scopes;
else if (typeof data.scopes === 'string') scopes = data.scopes.split(',').map(s => s.trim()).filter(Boolean);
else if (typeof data.scope === 'string') scopes = data.scope.split(',').map(s => s.trim()).filter(Boolean);
console.log('[OAuth] Extracted scopes:', scopes);
return res.json({
valid: true,