Skip to content
Closed
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
2 changes: 1 addition & 1 deletion api/generated-schema.graphql
Original file line number Diff line number Diff line change
Expand Up @@ -3567,4 +3567,4 @@ type Subscription {
systemMetricsTemperature: TemperatureMetrics
upsUpdates: UPSDevice!
pluginInstallUpdates(operationId: ID!): PluginInstallEvent!
}
}
5 changes: 4 additions & 1 deletion api/src/unraid-api/cli/generated/graphql.ts
Original file line number Diff line number Diff line change
Expand Up @@ -414,6 +414,8 @@ export type BrandingConfig = {
background?: Maybe<Scalars['String']['output']>;
/** Banner image source. Supports local path, remote URL, or data URI/base64. */
bannerImage?: Maybe<Scalars['String']['output']>;
/** Built-in case model value written to case-model.cfg when no custom override is supplied. */
caseModel?: Maybe<Scalars['String']['output']>;
/** Case model image source. Supports local path, remote URL, or data URI/base64. */
caseModelImage?: Maybe<Scalars['String']['output']>;
/** Indicates if a partner logo exists */
Expand Down Expand Up @@ -451,6 +453,7 @@ export type BrandingConfig = {
export type BrandingConfigInput = {
background?: InputMaybe<Scalars['String']['input']>;
bannerImage?: InputMaybe<Scalars['String']['input']>;
caseModel?: InputMaybe<Scalars['String']['input']>;
caseModelImage?: InputMaybe<Scalars['String']['input']>;
hasPartnerLogo?: InputMaybe<Scalars['Boolean']['input']>;
header?: InputMaybe<Scalars['String']['input']>;
Expand Down Expand Up @@ -3548,4 +3551,4 @@ export const GetSsoUsersDocument = {"kind":"Document","definitions":[{"kind":"Op
export const SystemReportDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"SystemReport"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"info"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"machineId"}},{"kind":"Field","name":{"kind":"Name","value":"system"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"manufacturer"}},{"kind":"Field","name":{"kind":"Name","value":"model"}},{"kind":"Field","name":{"kind":"Name","value":"version"}},{"kind":"Field","name":{"kind":"Name","value":"sku"}},{"kind":"Field","name":{"kind":"Name","value":"serial"}},{"kind":"Field","name":{"kind":"Name","value":"uuid"}}]}},{"kind":"Field","name":{"kind":"Name","value":"versions"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"core"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"unraid"}},{"kind":"Field","name":{"kind":"Name","value":"kernel"}}]}},{"kind":"Field","name":{"kind":"Name","value":"packages"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"openssl"}}]}}]}}]}},{"kind":"Field","name":{"kind":"Name","value":"config"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"valid"}},{"kind":"Field","name":{"kind":"Name","value":"error"}}]}},{"kind":"Field","name":{"kind":"Name","value":"server"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"name"}}]}}]}}]} as unknown as DocumentNode<SystemReportQuery, SystemReportQueryVariables>;
export const ConnectStatusDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"ConnectStatus"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"connect"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"dynamicRemoteAccess"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"enabledType"}},{"kind":"Field","name":{"kind":"Name","value":"runningType"}},{"kind":"Field","name":{"kind":"Name","value":"error"}}]}}]}}]}}]} as unknown as DocumentNode<ConnectStatusQuery, ConnectStatusQueryVariables>;
export const ServicesDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"Services"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"services"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"online"}},{"kind":"Field","name":{"kind":"Name","value":"uptime"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"timestamp"}}]}},{"kind":"Field","name":{"kind":"Name","value":"version"}}]}}]}}]} as unknown as DocumentNode<ServicesQuery, ServicesQueryVariables>;
export const ValidateOidcSessionDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"ValidateOidcSession"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"token"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"String"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"validateOidcSession"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"token"},"value":{"kind":"Variable","name":{"kind":"Name","value":"token"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"valid"}},{"kind":"Field","name":{"kind":"Name","value":"username"}}]}}]}}]} as unknown as DocumentNode<ValidateOidcSessionQuery, ValidateOidcSessionQueryVariables>;
export const ValidateOidcSessionDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"ValidateOidcSession"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"token"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"String"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"validateOidcSession"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"token"},"value":{"kind":"Variable","name":{"kind":"Name","value":"token"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"valid"}},{"kind":"Field","name":{"kind":"Name","value":"username"}}]}}]}}]} as unknown as DocumentNode<ValidateOidcSessionQuery, ValidateOidcSessionQueryVariables>;
41 changes: 41 additions & 0 deletions api/src/unraid-api/config/onboarding-tracker.service.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -87,3 +87,44 @@ describe('OnboardingTrackerService write retries', () => {
expect(mockAtomicWriteFile).toHaveBeenCalledTimes(3);
});
});

describe('OnboardingTrackerService tracker state availability', () => {
beforeEach(() => {
mockReadFile.mockReset();
mockAtomicWriteFile.mockReset();
});

it('keeps tracker state available when the tracker file does not exist yet', async () => {
const config = createConfigService();
const overrides = new OnboardingOverrideService();

mockReadFile.mockImplementation(async (filePath) => {
if (String(filePath).includes('unraid-version')) {
return 'version="7.2.0"\n';
}
throw Object.assign(new Error('Not found'), { code: 'ENOENT' });
});

const tracker = new OnboardingTrackerService(config, overrides);
await tracker.onApplicationBootstrap();

expect(tracker.didTrackerStateReadFail()).toBe(false);
});

it('marks tracker state unavailable when reading the tracker file fails', async () => {
const config = createConfigService();
const overrides = new OnboardingOverrideService();

mockReadFile.mockImplementation(async (filePath) => {
if (String(filePath).includes('unraid-version')) {
return 'version="7.2.0"\n';
}
throw new Error('permission denied');
});

const tracker = new OnboardingTrackerService(config, overrides);
await tracker.onApplicationBootstrap();

expect(tracker.didTrackerStateReadFail()).toBe(true);
});
});
13 changes: 13 additions & 0 deletions api/src/unraid-api/config/onboarding-tracker.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ export class OnboardingTrackerService implements OnApplicationBootstrap {
private state: TrackerState = {};
private currentVersion?: string;
private readonly versionFilePath: string;
private trackerStateReadFailed = false;

constructor(
private readonly configService: ConfigService,
Expand Down Expand Up @@ -84,6 +85,10 @@ export class OnboardingTrackerService implements OnApplicationBootstrap {
return this.currentVersion;
}

didTrackerStateReadFail(): boolean {
return this.trackerStateReadFailed;
}

/**
* Mark onboarding as completed for the current OS version.
*/
Expand Down Expand Up @@ -167,8 +172,16 @@ export class OnboardingTrackerService implements OnApplicationBootstrap {
private async readTrackerState(): Promise<TrackerState | undefined> {
try {
const content = await readFile(this.trackerPath, 'utf8');
this.trackerStateReadFailed = false;
return JSON.parse(content) as TrackerState;
} catch (error) {
if (error instanceof Error && 'code' in error && error.code === 'ENOENT') {
this.trackerStateReadFailed = false;
this.logger.debug(`Onboarding tracker state does not exist yet at ${this.trackerPath}.`);
return undefined;
}

this.trackerStateReadFailed = true;
this.logger.debug(
`Unable to read onboarding tracker state at ${this.trackerPath}: ${error}`
);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ describe('CustomizationResolver', () => {
getOnboardingState: vi.fn(),
} as unknown as OnboardingService;
const onboardingTracker = {
didTrackerStateReadFail: vi.fn(),
getState: vi.fn(),
getCurrentVersion: vi.fn(),
} as unknown as OnboardingTrackerService;
Expand All @@ -27,6 +28,7 @@ describe('CustomizationResolver', () => {

beforeEach(() => {
vi.clearAllMocks();
vi.mocked(onboardingTracker.didTrackerStateReadFail).mockReturnValue(false);
vi.mocked(onboardingTracker.getCurrentVersion).mockReturnValue('7.2.0');
vi.mocked(onboardingService.getPublicPartnerInfo).mockResolvedValue(null);
vi.mocked(onboardingService.getActivationDataForPublic).mockResolvedValue(null);
Expand Down Expand Up @@ -62,6 +64,15 @@ describe('CustomizationResolver', () => {
});
});

it('throws when tracker state could not be read', async () => {
vi.mocked(onboardingTracker.didTrackerStateReadFail).mockReturnValue(true);

await expect(resolver.resolveOnboarding()).rejects.toThrow(
'Onboarding tracker state is unavailable.'
);
expect(onboardingTracker.getState).not.toHaveBeenCalled();
});

it('returns COMPLETED status when completed on current version', async () => {
vi.mocked(onboardingTracker.getState).mockReturnValue({
completed: true,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { Query, ResolveField, Resolver } from '@nestjs/graphql';

import { AuthAction, Resource } from '@unraid/shared/graphql.model.js';
import { UsePermissions } from '@unraid/shared/use-permissions.directive.js';
import { GraphQLError } from 'graphql';

import { Public } from '@app/unraid-api/auth/public.decorator.js';
import { OnboardingTrackerService } from '@app/unraid-api/config/onboarding-tracker.module.js';
Expand Down Expand Up @@ -59,6 +60,10 @@ export class CustomizationResolver {
resource: Resource.CUSTOMIZATIONS,
})
async resolveOnboarding(): Promise<Onboarding> {
if (this.onboardingTracker.didTrackerStateReadFail()) {
throw new GraphQLError('Onboarding tracker state is unavailable.');
}

const state = this.onboardingTracker.getState();
const currentVersion = this.onboardingTracker.getCurrentVersion() ?? 'unknown';
const partnerInfo = await this.onboardingService.getPublicPartnerInfo();
Expand Down
6 changes: 6 additions & 0 deletions plugin/source/dynamix.unraid.net/install/doinst.sh
Original file line number Diff line number Diff line change
Expand Up @@ -37,3 +37,9 @@ cp usr/local/unraid-api/.env.production usr/local/unraid-api/.env
( cd usr/local/bin ; ln -sf ../lib/node_modules/npm/bin/npm-cli.js npm )
( cd usr/local/bin ; rm -rf npx )
( cd usr/local/bin ; ln -sf ../lib/node_modules/npm/bin/npx-cli.js npx )
( cd usr/local/bin ; rm -rf corepack )
( cd usr/local/bin ; ln -sf ../lib/node_modules/corepack/dist/corepack.js corepack )
( cd usr/local/bin ; rm -rf npm )
( cd usr/local/bin ; ln -sf ../lib/node_modules/npm/bin/npm-cli.js npm )
( cd usr/local/bin ; rm -rf npx )
( cd usr/local/bin ; ln -sf ../lib/node_modules/npm/bin/npx-cli.js npx )
Comment on lines +40 to +45
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

FILE="plugin/source/dynamix.unraid.net/install/doinst.sh"

echo "Pattern occurrences:"
rg -n '^\( cd usr/local/bin ; (rm -rf|ln -sf) ' "$FILE"

echo
python - <<'PY'
from pathlib import Path
p = Path("plugin/source/dynamix.unraid.net/install/doinst.sh")
lines = p.read_text().splitlines()
b1 = lines[27:33]  # Line 28-33
b2 = lines[33:39]  # Line 34-39
b3 = lines[39:45]  # Line 40-45
print("28-33 equals 34-39:", b1 == b2)
print("34-39 equals 40-45:", b2 == b3)
PY

Repository: unraid/api

Length of output: 1193


Remove duplicate relink blocks and use direct paths to prevent unsafe cd fallback execution

Lines 40–45 duplicate the exact same relink commands from lines 28–39 and 34–39. Additionally, the ( cd ... ; cmd ) pattern causes rm -rf/ln -sf to execute even if cd fails, which is unsafe in installer scripts.

Suggested fix
-( cd usr/local/bin ; rm -rf corepack )
-( cd usr/local/bin ; ln -sf ../lib/node_modules/corepack/dist/corepack.js corepack )
-( cd usr/local/bin ; rm -rf npm )
-( cd usr/local/bin ; ln -sf ../lib/node_modules/npm/bin/npm-cli.js npm )
-( cd usr/local/bin ; rm -rf npx )
-( cd usr/local/bin ; ln -sf ../lib/node_modules/npm/bin/npx-cli.js npx )
-( cd usr/local/bin ; rm -rf corepack )
-( cd usr/local/bin ; ln -sf ../lib/node_modules/corepack/dist/corepack.js corepack )
-( cd usr/local/bin ; rm -rf npm )
-( cd usr/local/bin ; ln -sf ../lib/node_modules/npm/bin/npm-cli.js npm )
-( cd usr/local/bin ; rm -rf npx )
-( cd usr/local/bin ; ln -sf ../lib/node_modules/npm/bin/npx-cli.js npx )
-( cd usr/local/bin ; rm -rf corepack )
-( cd usr/local/bin ; ln -sf ../lib/node_modules/corepack/dist/corepack.js corepack )
-( cd usr/local/bin ; rm -rf npm )
-( cd usr/local/bin ; ln -sf ../lib/node_modules/npm/bin/npm-cli.js npm )
-( cd usr/local/bin ; rm -rf npx )
-( cd usr/local/bin ; ln -sf ../lib/node_modules/npm/bin/npx-cli.js npx )
+rm -rf usr/local/bin/corepack
+ln -sf ../lib/node_modules/corepack/dist/corepack.js usr/local/bin/corepack
+rm -rf usr/local/bin/npm
+ln -sf ../lib/node_modules/npm/bin/npm-cli.js usr/local/bin/npm
+rm -rf usr/local/bin/npx
+ln -sf ../lib/node_modules/npm/bin/npx-cli.js usr/local/bin/npx
🧰 Tools
🪛 Shellcheck (0.11.0)

[warning] 40-40: Use 'cd ... || exit' or 'cd ... || return' in case cd fails.

(SC2164)


[warning] 41-41: Use 'cd ... || exit' or 'cd ... || return' in case cd fails.

(SC2164)


[warning] 42-42: Use 'cd ... || exit' or 'cd ... || return' in case cd fails.

(SC2164)


[warning] 43-43: Use 'cd ... || exit' or 'cd ... || return' in case cd fails.

(SC2164)


[warning] 44-44: Use 'cd ... || exit' or 'cd ... || return' in case cd fails.

(SC2164)


[warning] 45-45: Use 'cd ... || exit' or 'cd ... || return' in case cd fails.

(SC2164)

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@plugin/source/dynamix.unraid.net/install/doinst.sh` around lines 40 - 45,
Remove the duplicated relink blocks for corepack, npm, and npx and replace the
unsafe subshell cd pattern with direct-path operations: for each tool (corepack,
npm, npx) perform a single rm -rf on usr/local/bin/<name> and then a single ln
-sf to usr/local/bin/<name> pointing at ../lib/node_modules/<package>/... (e.g.
corepack -> ../lib/node_modules/corepack/dist/corepack.js, npm ->
../lib/node_modules/npm/bin/npm-cli.js, npx ->
../lib/node_modules/npm/bin/npx-cli.js); this eliminates redundant blocks and
avoids running rm/ln when a cd fails by explicitly acting on the target paths in
doinst.sh.

114 changes: 114 additions & 0 deletions web/__test__/store/onboardingStatus.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,114 @@
import { ref } from 'vue';
import { createPinia, setActivePinia } from 'pinia';

import { beforeEach, describe, expect, it, vi } from 'vitest';

import { useOnboardingStore } from '~/components/Onboarding/store/onboardingStatus';
import { useServerStore } from '~/store/server';

type OnboardingQueryResult = {
customization?: {
onboarding?: {
status?: 'INCOMPLETE' | 'UPGRADE' | 'DOWNGRADE' | 'COMPLETED';
isPartnerBuild?: boolean;
completed?: boolean;
completedAtVersion?: string | null;
};
};
};

const { state, refetchMock, useQueryMock } = vi.hoisted(() => ({
state: {
onboardingResult: null as unknown as ReturnType<typeof ref<OnboardingQueryResult | null>>,
onboardingLoading: null as unknown as ReturnType<typeof ref<boolean>>,
onboardingError: null as unknown as ReturnType<typeof ref<unknown>>,
osVersionRef: null as unknown as ReturnType<typeof ref<string>>,
},
refetchMock: vi.fn(),
useQueryMock: vi.fn(),
}));

const createOnboardingResult = (): OnboardingQueryResult => ({
customization: {
onboarding: {
status: 'INCOMPLETE',
isPartnerBuild: false,
completed: false,
completedAtVersion: null,
},
},
});

describe('onboardingStatus store', () => {
beforeEach(() => {
vi.clearAllMocks();
setActivePinia(createPinia());

state.onboardingResult = ref<OnboardingQueryResult | null>(createOnboardingResult());
state.onboardingLoading = ref(false);
state.onboardingError = ref(null);
state.osVersionRef = ref('7.3.0');
refetchMock.mockResolvedValue(undefined);

useQueryMock.mockReturnValue({
result: state.onboardingResult,
loading: state.onboardingLoading,
error: state.onboardingError,
refetch: refetchMock,
});

vi.mocked(useServerStore).mockReturnValue({
osVersion: state.osVersionRef,
} as unknown as ReturnType<typeof useServerStore>);
});

it('blocks onboarding modal while the onboarding query is still loading', () => {
state.onboardingResult.value = null;
state.onboardingLoading.value = true;

const store = useOnboardingStore();

expect(store.hasOnboardingState).toBe(false);
expect(store.canDisplayOnboardingModal).toBe(false);
expect(store.shouldShowOnboarding).toBe(false);
});

it('blocks onboarding modal when the onboarding query errors', () => {
state.onboardingResult.value = null;
state.onboardingError.value = new Error('Network error');

const store = useOnboardingStore();

expect(store.hasOnboardingState).toBe(false);
expect(store.hasOnboardingQueryError).toBe(true);
expect(store.canDisplayOnboardingModal).toBe(false);
expect(store.shouldShowOnboarding).toBe(false);
});

it('allows onboarding modal when the onboarding query succeeds', () => {
const store = useOnboardingStore();

expect(store.hasOnboardingQueryError).toBe(false);
expect(store.hasOnboardingState).toBe(true);
expect(store.canDisplayOnboardingModal).toBe(true);
expect(store.shouldShowOnboarding).toBe(true);
});

it('keeps onboarding modal display enabled during refetch when onboarding data already exists', () => {
state.onboardingLoading.value = true;

const store = useOnboardingStore();

expect(store.hasOnboardingState).toBe(true);
expect(store.canDisplayOnboardingModal).toBe(true);
expect(store.shouldShowOnboarding).toBe(true);
});
});

vi.mock('@vue/apollo-composable', () => ({
useQuery: () => useQueryMock(),
}));

vi.mock('~/store/server', () => ({
useServerStore: vi.fn(),
}));
11 changes: 10 additions & 1 deletion web/src/components/Onboarding/store/onboardingStatus.ts
Original file line number Diff line number Diff line change
Expand Up @@ -159,7 +159,14 @@ export const useOnboardingStore = defineStore('onboarding', () => {
const isUnauthenticated = computed(
() => mockUnauthenticated.value || isUnauthenticatedApolloError(onboardingError.value)
);
const canDisplayOnboardingModal = computed(() => isVersionSupported.value && !isUnauthenticated.value);
const hasOnboardingQueryError = computed(() => Boolean(onboardingError.value));
const hasOnboardingState = computed(() => onboardingData.value !== undefined);
const canDisplayOnboardingModal = computed(
() =>
isVersionSupported.value &&
!isUnauthenticated.value &&
(hasOnboardingState.value || (!onboardingLoading.value && !hasOnboardingQueryError.value))
);

// Automatic onboarding should only run for initial setup.
const shouldShowOnboarding = computed(() => {
Expand Down Expand Up @@ -189,6 +196,8 @@ export const useOnboardingStore = defineStore('onboarding', () => {
mockUnauthenticated,
mockOsVersion,
isUnauthenticated,
hasOnboardingQueryError,
hasOnboardingState,
canDisplayOnboardingModal,
shouldShowOnboarding,
// Actions
Expand Down
Loading
Loading