Skip to content
Draft
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
204 changes: 17 additions & 187 deletions apps/server/src/assets/NativeAppIconResolver.ts
Original file line number Diff line number Diff line change
@@ -1,34 +1,32 @@
import { expandHomePath } from "@t3tools/provider-core/server/pathExpansion";
import type { NativeAppIconReference } from "@t3tools/contracts";
import * as Cache from "effect/Cache";
import * as Cause from "effect/Cause";
import * as Digest from "effect/crypto/Digest";
import * as SecureRandom from "effect/crypto/SecureRandom";
import * as Effect from "effect/Effect";
import * as Clock from "effect/Clock";
import type * as Cause from "effect/Cause";
import * as Context from "effect/Context";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as Exit from "effect/Exit";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Path from "effect/Path";
import * as PlatformError from "effect/PlatformError";
import type * as PlatformError from "effect/PlatformError";
import * as Semaphore from "effect/Semaphore";
import * as Hex from "effect/encoding/Hex";
import { ChildProcess, ChildProcessSpawner } from "effect/process";
import * as HostProcess from "@t3tools/shared/HostProcess";

import * as ServerConfig from "../config.ts";
import { darwinSource } from "./nativeAppIcons/darwin.ts";
import { linuxSource } from "./nativeAppIcons/linux.ts";
import { win32Source } from "./nativeAppIcons/win32.ts";
import type { NativeAppIconSource } from "./nativeAppIcons/source.ts";

const ICON_SIZE = 128;
const COMMAND_TIMEOUT = "5 seconds";
const RESOLUTION_CACHE_TTL = Duration.hours(1);
const RESOLUTION_CACHE_MAX_ENTRIES = 256;

/** One source per platform; a platform without one resolves nothing. */
const SOURCES: ReadonlyArray<NativeAppIconSource> = [darwinSource, linuxSource, win32Source];

/** Resolves and caches host application icons without exposing host paths to clients. */
export class NativeAppIconResolver extends Context.Service<
NativeAppIconResolver,
{
/** Returns a cached image path for the application, or `null` when no icon is available. */
readonly resolve: (app: NativeAppIconReference) => Effect.Effect<string | null>;
}
>()("t3/assets/NativeAppIconResolver") {}
Expand All @@ -41,193 +39,28 @@ function appFromCacheKey(key: string): NativeAppIconReference {
return JSON.parse(key) as NativeAppIconReference;
}

const existingFile = Effect.fn("NativeAppIconResolver.existingFile")(function* (filePath: string) {
const fileSystem = yield* FileSystem.FileSystem;
const info = yield* fileSystem.stat(filePath).pipe(
Effect.asSome,
Effect.catchTags({
PlatformError: (error) =>
error.reason._tag === "NotFound" ? Effect.succeedNone : Effect.fail(error),
}),
);
return Option.isSome(info) && info.value.type === "File" ? filePath : null;
});

const commandOutput = Effect.fn("NativeAppIconResolver.commandOutput")(function* (
command: string,
args: ReadonlyArray<string>,
) {
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
return yield* spawner
.string(ChildProcess.make(command, args, { stdin: "ignore", stderr: "ignore" }))
.pipe(Effect.timeout(COMMAND_TIMEOUT));
});

const plistValue = Effect.fn("NativeAppIconResolver.plistValue")(function* (
infoPlistPath: string,
key: string,
) {
return yield* commandOutput("/usr/bin/plutil", [
"-extract",
key,
"raw",
"-o",
"-",
infoPlistPath,
]).pipe(
Effect.map((value) => value.trim()),
Effect.orElseSucceed(() => ""),
);
});

function escapeSpotlightString(value: string): string {
return value.replace(/([\\'*?])/gu, "\\$1");
}

function containsControlCharacter(value: string): boolean {
return [...value].some((character) => {
const codePoint = character.codePointAt(0) ?? 0;
return codePoint <= 31 || codePoint === 127;
});
}

const resolveApplicationPath = Effect.fn("NativeAppIconResolver.resolveApplicationPath")(function* (
app: NativeAppIconReference,
) {
const path = yield* Path.Path;
if (app._tag === "app-path") {
const appPath = expandHomePath(app.path, yield* HostProcess.HomeDirectory);
return path.isAbsolute(appPath) && appPath.endsWith(".app") ? appPath : null;
}
const query =
app._tag === "app-id"
? `kMDItemCFBundleIdentifier == '${app.appId}'`
: `kMDItemContentType == 'com.apple.application-bundle' && kMDItemDisplayName == '${escapeSpotlightString(app.displayName)}'`;
const spotlightOutput = yield* commandOutput("/usr/bin/mdfind", [query]);
const candidates = spotlightOutput
.split(/\r?\n/u)
.map((value) => value.trim())
.filter((value) => value.endsWith(".app"));
const matchingCandidates =
app._tag === "app-id"
? candidates
: candidates.filter(
(value) =>
path.basename(value, ".app").toLocaleLowerCase() ===
app.displayName.toLocaleLowerCase(),
);
const rankedCandidates = matchingCandidates.length > 0 ? matchingCandidates : candidates;
let mostRecentlyUsed: { readonly path: string; readonly lastUsed: string } | null = null;
for (const candidate of rankedCandidates) {
const lastUsed = yield* commandOutput("/usr/bin/mdls", [
"-raw",
"-name",
"kMDItemLastUsedDate",
candidate,
]).pipe(
Effect.map((value) => value.trim()),
Effect.orElseSucceed(() => ""),
);
if (!mostRecentlyUsed || lastUsed > mostRecentlyUsed.lastUsed) {
mostRecentlyUsed = { path: candidate, lastUsed };
}
}
return mostRecentlyUsed?.path ?? null;
});

const resolveNativeAppIconUncached = Effect.fn("NativeAppIconResolver.resolveUncached")(function* (
app: NativeAppIconReference,
) {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const config = yield* ServerConfig.ServerConfig;
const appPath = yield* resolveApplicationPath(app);
if (!appPath) return null;

const canonicalAppPath = yield* fileSystem.realPath(appPath);
const infoPlistPath = path.join(canonicalAppPath, "Contents", "Info.plist");
const resourcesDirectory = path.join(canonicalAppPath, "Contents", "Resources");
const iconName =
(yield* plistValue(infoPlistPath, "CFBundleIconFile")) ||
(yield* plistValue(infoPlistPath, "CFBundleIconName"));
if (iconName && path.basename(iconName) !== iconName) return null;
const iconFileName = iconName ? (path.extname(iconName) ? iconName : `${iconName}.icns`) : null;
const resourceEntries = yield* fileSystem
.readDirectory(resourcesDirectory)
.pipe(Effect.orElseSucceed(() => []));
const sourceIconCandidate =
(iconFileName ? yield* existingFile(path.join(resourcesDirectory, iconFileName)) : null) ??
(yield* existingFile(path.join(resourcesDirectory, "AppIcon.icns"))) ??
(resourceEntries.find((entry) => entry.toLowerCase().endsWith(".icns"))
? yield* existingFile(
path.join(
resourcesDirectory,
resourceEntries.find((entry) => entry.toLowerCase().endsWith(".icns"))!,
),
)
: null);
if (!sourceIconCandidate) return null;
const sourceIconPath = yield* fileSystem.realPath(sourceIconCandidate);
const relativeSource = path.relative(resourcesDirectory, sourceIconPath);
if (
relativeSource === ".." ||
relativeSource.startsWith(`..${path.sep}`) ||
path.isAbsolute(relativeSource)
) {
return null;
}

const appVersion =
(yield* plistValue(infoPlistPath, "CFBundleVersion")) ||
(yield* plistValue(infoPlistPath, "CFBundleShortVersionString"));
const random = yield* SecureRandom.SecureRandom;
const digest = yield* Digest.Digest;
const cacheKey = yield* digest
.digest(
Digest.sha256,
new TextEncoder().encode(`${canonicalAppPath}\0${appVersion}\0${sourceIconPath}`),
)
.pipe(Effect.map(Hex.encode), Effect.orDie);
const cacheDirectory = path.join(config.providerStatusCacheDir, "native-app-icons");
const cachePath = path.join(cacheDirectory, `${cacheKey}-${ICON_SIZE}.png`);
if (yield* existingFile(cachePath)) return cachePath;

yield* fileSystem.makeDirectory(cacheDirectory, { recursive: true });
const temporaryPath = path.join(
cacheDirectory,
`.${cacheKey}-${process.pid}-${(yield* Clock.currentTimeMillis).toString(36)}-${yield* random.uuidV4()}.png`,
);
yield* commandOutput("/usr/bin/sips", [
"-z",
String(ICON_SIZE),
String(ICON_SIZE),
"-s",
"format",
"png",
sourceIconPath,
"--out",
temporaryPath,
]).pipe(
Effect.tap(() => fileSystem.rename(temporaryPath, cachePath)),
Effect.ensuring(
fileSystem.remove(temporaryPath).pipe(Effect.catchTags({ PlatformError: () => Effect.void })),
),
);
return yield* existingFile(cachePath);
});

/** @public */
export const make = Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const hostPlatform = yield* HostProcess.Platform;
const source = SOURCES.find((candidate) => candidate.platform === hostPlatform);
const resolutionSemaphore = yield* Semaphore.make(2);
const resolutionCache: Cache.Cache<
string,
string | null,
PlatformError.PlatformError | Cause.TimeoutError
> = yield* Cache.makeWith(
(key: string) =>
resolutionSemaphore.withPermits(1)(resolveNativeAppIconUncached(appFromCacheKey(key))),
source
? resolutionSemaphore.withPermits(1)(source.resolve(appFromCacheKey(key)))
: Effect.succeed(null),
{
capacity: RESOLUTION_CACHE_MAX_ENTRIES,
timeToLive: Exit.match({
Expand All @@ -249,10 +82,7 @@ export const make = Effect.gen(function* () {
const resolveAttempt = Effect.fn("NativeAppIconResolver.resolve")(function* (
app: NativeAppIconReference,
) {
if (
hostPlatform !== "darwin" ||
(app._tag === "display-name" && containsControlCharacter(app.displayName))
) {
if (!source || (app._tag === "display-name" && containsControlCharacter(app.displayName))) {
return null;
}

Expand Down
Loading
Loading