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
10 changes: 5 additions & 5 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

216 changes: 211 additions & 5 deletions web/__test__/store/callbackActions.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,13 +36,32 @@ const mockRefreshServerStateStatus = ref<'done' | 'ready' | 'refreshing' | 'time
const mockInstall = vi.fn();
const mockRefreshServerState = vi.fn();

vi.mock('@unraid/shared-callbacks', () => {
vi.mock('@unraid/shared-callbacks/client', () => {
const mockWatcher = vi.fn();
const mockSend = vi.fn();
const mockSend = vi.fn(
(
url: string,
payload: unknown,
redirectType: string | null | undefined,
sendType: string | undefined,
sender?: string,
nonce?: string
) => ({ url, payload, redirectType, sendType, sender, nonce })
);
const mockGenerateUrl = vi.fn(
(url: string, payload: unknown, sendType: string | undefined, sender?: string, nonce?: string) => ({
url,
payload,
sendType,
sender,
nonce,
})
);

return {
useCallback: vi.fn(({ encryptionKey: _encryptionKey }) => ({
createCallback: vi.fn(({ encryptionKey: _encryptionKey }) => ({
send: mockSend,
generateUrl: mockGenerateUrl,
watcher: mockWatcher,
parse: vi.fn(),
})),
Expand Down Expand Up @@ -146,9 +165,13 @@ describe('Callback Actions Store', () => {
let store: ReturnType<typeof useCallbackActionsStore>;
let preventClose: { addPreventClose: Mock; removePreventClose: Mock };
let mockWatcher: Mock;
let mockSend: Mock;
let mockGenerateUrl: Mock;

beforeEach(async () => {
setActivePinia(createPinia());
localStorage.clear();
window.history.replaceState(null, '', '/');
mockAccountActionStatus.value = 'success';
mockKeyInstallStatus.value = 'success';
mockRefreshServerStateStatus.value = 'done';
Expand All @@ -161,9 +184,12 @@ describe('Callback Actions Store', () => {
removePreventClose: vi.mocked(preventCloseModule.removePreventClose),
};

const { useCallback } = await import('@unraid/shared-callbacks');
const { createCallback } = await import('@unraid/shared-callbacks/client');

mockWatcher = vi.mocked(useCallback).mock.results[0].value.watcher;
const callbackMock = vi.mocked(createCallback).mock.results[0].value;
mockWatcher = callbackMock.watcher;
mockSend = callbackMock.send;
mockGenerateUrl = callbackMock.generateUrl;
vi.clearAllMocks();
});

Expand Down Expand Up @@ -213,6 +239,186 @@ describe('Callback Actions Store', () => {
});
});

describe('Callback Return Paths', () => {
it('passes a dedicated nonce and cleans the default return path', () => {
window.history.replaceState(null, '', '/Tools/Update');

store.send(
'https://example.com/callback',
[{ type: 'updateOs', sha256: 'test-sha256' } as ExternalUpdateOsAction],
undefined,
'forUpc'
);

const sender = mockSend.mock.calls[0][4] as string;
const senderUrl = new URL(sender);
const nonce = mockSend.mock.calls[0][5] as string;

expect(senderUrl.pathname).toBe('/Tools');
expect(senderUrl.searchParams.get('data')).toBeNull();
expect(senderUrl.searchParams.has('callback_nonce')).toBe(false);
expect(nonce).toMatch(/^[0-9a-f]{32}$/);
expect(localStorage.getItem(`unraid-callback-nonce:${nonce}`)).toBeTruthy();
});

it('preserves explicit return details without adding a nonce parameter', () => {
const sender = 'https://example.com/return?state=ready#section';

store.send(
'https://example.com/callback',
[{ type: 'updateOs', sha256: 'test-sha256' } as ExternalUpdateOsAction],
undefined,
'forUpc',
sender
);

const returnedUrl = new URL(mockSend.mock.calls[0][4] as string);

expect(returnedUrl.origin).toBe('https://example.com');
expect(returnedUrl.pathname).toBe('/return');
expect(returnedUrl.searchParams.get('state')).toBe('ready');
expect(returnedUrl.hash).toBe('');
expect(returnedUrl.searchParams.has('callback_nonce')).toBe(false);
expect(mockSend.mock.calls[0][5]).toMatch(/^[0-9a-f]{32}$/);
});

it('passes a dedicated nonce when creating a return link', () => {
const payload = [{ type: 'updateOs', sha256: 'test-sha256' } as ExternalUpdateOsAction];

store.generateUrl('https://example.com/callback', payload, 'forUpc');

const sender = mockGenerateUrl.mock.calls[0][3] as string;
const senderUrl = new URL(sender);

const nonce = mockGenerateUrl.mock.calls[0][4] as string;
expect(senderUrl.searchParams.has('callback_nonce')).toBe(false);
expect(nonce).toMatch(/^[0-9a-f]{32}$/);
expect(localStorage.getItem(`unraid-callback-nonce:${nonce}`)).toBeTruthy();
});
});

describe('Callback Return Validation', () => {
const updatePayload = (sender: string, nonce?: string): QueryPayloads => ({
type: 'forUpc',
actions: [
{
type: 'updateOs',
sha256: 'test-sha256',
} as ExternalUpdateOsAction,
],
sender,
nonce,
});

it('uses the fragment when the query value is blank', async () => {
window.history.replaceState(null, '', '/Tools?data=#data=fragment');
mockWatcher.mockReturnValue(updatePayload('/Tools'));

store.watcher();
await nextTick();
store.watcher();

expect(mockWatcher).toHaveBeenCalledTimes(1);
expect(store.callbackStatus).toBe('error');
expect(store.callbackError).toBeDefined();
});

it('consumes a dedicated return nonce once', async () => {
store.send(
'https://example.com/callback',
[{ type: 'updateOs', sha256: 'test-sha256' } as ExternalUpdateOsAction],
undefined,
'forUpc'
);
const sender = mockSend.mock.calls[0][4] as string;
const nonce = mockSend.mock.calls[0][5] as string;

await store.saveCallbackData(updatePayload(sender, nonce), { requireNonce: true });
await store.saveCallbackData(updatePayload(sender, nonce), { requireNonce: true });

expect(localStorage.getItem(`unraid-callback-nonce:${nonce}`)).toBeNull();
expect(store.callbackStatus).toBe('error');
expect(store.callbackError).toBeDefined();
});

it('round-trips the dedicated nonce through encrypted callback URLs', async () => {
const { createCallback } = await vi.importActual<typeof import('@unraid/shared-callbacks/client')>(
'@unraid/shared-callbacks/client'
);
const callback = createCallback({ encryptionKey: 'test-callback-key' });
mockGenerateUrl.mockImplementationOnce(callback.generateUrl);
const requestUrl = store.generateUrl(
'https://example.com/callback',
[{ type: 'updateOs', sha256: 'test-sha256' }],
'forUpc'
);
const request = callback.watcher({ baseUrl: requestUrl });
if (!request) {
throw new Error('Callback request was not parsed');
}
expect(request.nonce).toMatch(/^[0-9a-f]{32}$/);
expect(new URL(request.sender).searchParams.has('callback_nonce')).toBe(false);

const responseUrl = callback.generateUrl(
request.sender,
[{ type: 'updateOs', sha256: 'test-sha256' }],
'forUpc',
'https://example.com/callback',
request.nonce
);
mockWatcher.mockReturnValue(callback.watcher({ baseUrl: responseUrl }));
window.history.replaceState(null, '', responseUrl);
store.watcher();
await nextTick();

expect(store.callbackData?.nonce).toBe(request.nonce);
expect(store.callbackStatus).not.toBe('error');
expect(localStorage.getItem(`unraid-callback-nonce:${request.nonce}`)).toBeNull();
});

it('rejects a nonce carried only in the sender URL', async () => {
const nonce = 'b'.repeat(32);
localStorage.setItem(`unraid-callback-nonce:${nonce}`, String(Date.now() + 60_000));

await store.saveCallbackData(updatePayload(`/Tools?callback_nonce=${nonce}`), {
requireNonce: true,
});

expect(store.callbackStatus).toBe('error');
expect(store.callbackData).toBeUndefined();
expect(localStorage.getItem(`unraid-callback-nonce:${nonce}`)).toBeTruthy();
});

it.each(['', 'unknown', 'c'.repeat(32)])('rejects an inactive nonce %j', async (nonce) => {
await store.saveCallbackData(updatePayload('/Tools', nonce), { requireNonce: true });

expect(store.callbackStatus).toBe('error');
expect(store.callbackData).toBeUndefined();
});

it('rejects an expired return nonce', async () => {
const nonce = 'a'.repeat(32);
localStorage.setItem(`unraid-callback-nonce:${nonce}`, String(Date.now() - 1));

await store.saveCallbackData(updatePayload('/Tools', nonce), {
requireNonce: true,
});

expect(store.callbackStatus).toBe('error');
expect(store.callbackError).toBeDefined();
expect(localStorage.getItem(`unraid-callback-nonce:${nonce}`)).toBeNull();
});

it('rejects an external return path without a nonce', async () => {
await store.saveCallbackData(updatePayload('https://example.com/return'), {
requireNonce: true,
});

expect(store.callbackStatus).toBe('error');
expect(store.callbackError).toBeDefined();
});
});

describe('Save Callback Data', () => {
it('should save data and trigger redirect when valid data provided', () => {
const mockData: QueryPayloads = {
Expand Down
9 changes: 6 additions & 3 deletions web/__test__/store/updateOs.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,11 @@ import { useUpdateOsStore } from '~/store/updateOs';

const mockSend = vi.fn();

vi.mock('@unraid/shared-callbacks', () => ({
useCallback: vi.fn(() => ({
vi.mock('@unraid/shared-callbacks/client', () => ({
createCallback: vi.fn(() => ({
send: mockSend,
watcher: vi.fn(),
generateUrl: vi.fn(),
})),
}));

Expand Down Expand Up @@ -153,7 +154,9 @@ describe('UpdateOs Store', () => {
},
],
undefined,
'forUpc'
'forUpc',
'https://littlebox.tail45affd.ts.net/Plugins',
expect.stringMatching(/^[0-9a-f]{32}$/)
);

Object.defineProperty(window, 'location', {
Expand Down
2 changes: 1 addition & 1 deletion web/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -117,7 +117,7 @@
"@nuxt/ui": "4.8.2",
"@tanstack/vue-table": "8.21.3",
"@tiptap/y-tiptap": "3.0.7",
"@unraid/shared-callbacks": "3.1.0",
"@unraid/shared-callbacks": "3.4.0",
"@unraid/ui": "link:../unraid-ui",
"@vue/apollo-composable": "4.2.2",
"@vueuse/components": "13.8.0",
Expand Down
4 changes: 2 additions & 2 deletions web/src/components/Onboarding/OnboardingModal.vue
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ const allowActivationSkip = computed(
() => hasKeyfile.value || activationRequired.value || showActivationStep.value
);
const showKeyfileHint = computed(() => activationRequired.value && hasKeyfile.value);
const activateHref = computed(() => purchaseStore.generateUrl('activate'));
const getActivateHref = () => purchaseStore.generateUrl('activate');
const activateExternal = computed(() => purchaseStore.openInNewTab);

// Hardcoded step definitions - order matters for UI flow
Expand Down Expand Up @@ -591,7 +591,7 @@ const currentStepProps = computed<Record<string, unknown>>(() => {
modalDescription: modalDescription.value,
docsButtons: docsButtons.value,
canGoBack: canGoBack.value,
activateHref: activateHref.value,
activateHref: getActivateHref,
activateExternal: activateExternal.value,
allowSkip: allowActivationSkip.value,
showKeyfileHint: showKeyfileHint.value,
Expand Down
10 changes: 7 additions & 3 deletions web/src/components/Onboarding/steps/OnboardingLicenseStep.vue
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ interface Props {
onComplete?: () => void;
onBack?: () => void;
showBack?: boolean;
activateHref: string;
activateHref: string | (() => string);
activateExternal?: boolean;
allowSkip?: boolean;
}
Expand Down Expand Up @@ -88,14 +88,18 @@ const isSkipDialogOpen = ref(false);
const isRefreshing = ref(false);

// Methods
const resolveActivateHref = () =>
typeof props.activateHref === 'function' ? props.activateHref() : props.activateHref;

const openActivate = () => {
const activateHref = resolveActivateHref();
if (props.activateExternal) {
const opened = window.open(props.activateHref, '_blank', 'noopener,noreferrer');
const opened = window.open(activateHref, '_blank', 'noopener,noreferrer');
if (opened) {
opened.opener = null;
}
} else {
window.location.href = props.activateHref;
window.location.href = activateHref;
}
};

Expand Down
Loading
Loading