Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
50 changes: 47 additions & 3 deletions src/github-auth.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,8 @@
const GITHUB_CONFIG = {
apiBaseUrl: 'https://api.github.com',
owner: 'super3',
repo: 'dashban'
repo: 'dashban',
appSlug: 'dashban'
};

// Origin of the backend API. The frontend can be served three ways:
Expand Down Expand Up @@ -72,6 +73,36 @@ async function githubFetch(path, options = {}) {
return fetch(url, { ...options, headers });
}

// "Manage GitHub access" deep link. GitHub's only page that lands directly on an
// app's repository access is /settings/installations/<installation-id>, and that
// id is unique to each user's installation — it can't be hardcoded. So we look it
// up once (via the authenticated proxy: GET /user/installations) and cache it,
// falling back to the app's public page until/unless the lookup succeeds.
const MANAGE_ACCESS_FALLBACK_URL = `https://github.com/apps/${GITHUB_CONFIG.appSlug}`;
let manageAccessUrl = MANAGE_ACCESS_FALLBACK_URL;

async function refreshManageAccessUrl() {
// Already resolved to a real installation, or no session to look it up with.
if (manageAccessUrl !== MANAGE_ACCESS_FALLBACK_URL || !isGitHubAuthed()) {
return manageAccessUrl;
}
try {
const response = await githubFetch('/user/installations');
if (response.ok) {
const data = await response.json();
const installation = (data.installations || []).find(
(entry) => entry.app_slug === GITHUB_CONFIG.appSlug
);
if (installation) {
manageAccessUrl = `https://github.com/settings/installations/${installation.id}`;
}
}
} catch {
// Network/parse error — keep the fallback URL.
}
return manageAccessUrl;
}

// Initialize auth UI. Clerk (clerk-auth.js, kicked off by github.js) drives the
// actual sign-in and calls back into updateGitHubSignInUI() when the session
// changes; here we just render the initial signed-out state.
Expand Down Expand Up @@ -182,8 +213,14 @@ function toggleUserDropdown() {

// Create dropdown
const dropdown = document.createElement('div');
dropdown.className = 'user-dropdown absolute right-0 top-full mt-2 w-48 bg-white rounded-lg shadow-lg border border-gray-200 py-1 z-50';
dropdown.className = 'user-dropdown absolute right-0 top-full mt-2 w-56 bg-white rounded-lg shadow-lg border border-gray-200 py-1 z-50';
dropdown.innerHTML = `
<a id="manage-github-access" href="${manageAccessUrl}" target="_blank" rel="noopener noreferrer"
class="px-4 py-2 text-sm text-gray-700 hover:bg-gray-100 flex items-center space-x-2 whitespace-nowrap">
<i class="fas fa-key text-xs"></i>
<span>Manage GitHub access</span>
</a>
<div class="border-t border-gray-100 my-1"></div>
<button class="w-full text-left px-4 py-2 text-sm text-gray-700 hover:bg-gray-100 flex items-center space-x-2">
<i class="fas fa-sign-out-alt text-xs"></i>
<span>Sign out</span>
Expand All @@ -207,6 +244,12 @@ function toggleUserDropdown() {
}, 0);

container.appendChild(dropdown);

// Look up the user's exact installation and upgrade the access link in place
// (and cache it, so the next open renders the direct link immediately).
refreshManageAccessUrl().then((url) => {
dropdown.querySelector('#manage-github-access').setAttribute('href', url);
});
}

// Function to update the header with repo name
Expand Down Expand Up @@ -241,5 +284,6 @@ window.GitHubAuth = {

// UI functions
toggleUserDropdown,
updateHeaderRepoName
updateHeaderRepoName,
refreshManageAccessUrl
};
90 changes: 89 additions & 1 deletion tests/github-auth.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ describe('GitHub Authentication (Clerk-only)', () => {
document.body.appendChild(container);

delete window.ClerkAuth;
delete require.cache[require.resolve('../src/github-auth.js')];
jest.resetModules();
require('../src/github-auth.js');

// Start signed out.
Expand Down Expand Up @@ -305,6 +305,31 @@ describe('GitHub Authentication (Clerk-only)', () => {
expect(container.querySelector('.user-dropdown')).toBeNull();
});

test('includes a Manage GitHub access link (app page by default)', () => {
window.GitHubAuth.toggleUserDropdown();

const link = container.querySelector('.user-dropdown #manage-github-access');
expect(link).not.toBeNull();
expect(link.getAttribute('href')).toBe('https://github.com/apps/dashban');
expect(link.getAttribute('target')).toBe('_blank');
expect(link.textContent).toContain('Manage GitHub access');
});

test('upgrades the access link to the exact installation page once resolved', async () => {
window.ClerkAuth = { getToken: jest.fn().mockResolvedValue('jwt') };
global.fetch = jest.fn().mockResolvedValue({
ok: true,
json: async () => ({ installations: [{ app_slug: 'dashban', id: 9999 }] })
});

window.GitHubAuth.toggleUserDropdown();
// Let refreshManageAccessUrl()'s promise and the in-place href update settle.
await new Promise((resolve) => setTimeout(resolve, 0));

const link = container.querySelector('.user-dropdown #manage-github-access');
expect(link.getAttribute('href')).toBe('https://github.com/settings/installations/9999');
});

test('Sign out triggers Clerk sign-out', () => {
window.ClerkAuth = { signOut: jest.fn() };
window.GitHubAuth.toggleUserDropdown();
Expand Down Expand Up @@ -339,6 +364,69 @@ describe('GitHub Authentication (Clerk-only)', () => {
});
});

describe('refreshManageAccessUrl', () => {
const FALLBACK = 'https://github.com/apps/dashban';

test('returns the app-page fallback when signed out', async () => {
await expect(window.GitHubAuth.refreshManageAccessUrl()).resolves.toBe(FALLBACK);
});

test('resolves to the exact installation settings page when found', async () => {
signInClerk();
window.ClerkAuth = { getToken: jest.fn().mockResolvedValue('jwt') };
global.fetch = jest.fn().mockResolvedValue({
ok: true,
json: async () => ({ installations: [{ app_slug: 'other', id: 1 }, { app_slug: 'dashban', id: 42 }] })
});

const url = await window.GitHubAuth.refreshManageAccessUrl();

expect(url).toBe('https://github.com/settings/installations/42');
expect(global.fetch).toHaveBeenCalledWith(
'/api/github/user/installations',
expect.objectContaining({ headers: expect.objectContaining({ Authorization: 'Bearer jwt' }) })
);
});

test('keeps the fallback when the dashban installation is not in the list', async () => {
signInClerk();
window.ClerkAuth = { getToken: jest.fn().mockResolvedValue('jwt') };
global.fetch = jest.fn().mockResolvedValue({ ok: true, json: async () => ({}) });

await expect(window.GitHubAuth.refreshManageAccessUrl()).resolves.toBe(FALLBACK);
});

test('keeps the fallback when the request is not ok', async () => {
signInClerk();
window.ClerkAuth = { getToken: jest.fn().mockResolvedValue('jwt') };
global.fetch = jest.fn().mockResolvedValue({ ok: false });

await expect(window.GitHubAuth.refreshManageAccessUrl()).resolves.toBe(FALLBACK);
});

test('keeps the fallback when the request throws', async () => {
signInClerk();
window.ClerkAuth = { getToken: jest.fn().mockResolvedValue('jwt') };
global.fetch = jest.fn().mockRejectedValue(new Error('network'));

await expect(window.GitHubAuth.refreshManageAccessUrl()).resolves.toBe(FALLBACK);
});

test('caches the resolved URL and does not look it up again', async () => {
signInClerk();
window.ClerkAuth = { getToken: jest.fn().mockResolvedValue('jwt') };
global.fetch = jest.fn().mockResolvedValue({
ok: true,
json: async () => ({ installations: [{ app_slug: 'dashban', id: 7 }] })
});

await window.GitHubAuth.refreshManageAccessUrl();
await window.GitHubAuth.refreshManageAccessUrl();

expect(global.fetch).toHaveBeenCalledTimes(1);
});
});

describe('updateHeaderRepoName', () => {
test('writes the repo name into the header', () => {
document.getElementById('repo-name').textContent = 'stale';
Expand Down
Loading