Skip to content

Commit c014000

Browse files
committed
Validate --app-icon when parsing flags
The icon was only checked when the manifest was requested, so a broken or undersized PNG went unnoticed until a browser asked for it, and the PNG header was read on every request. The flag now parses into an AppIcon that holds the path, MIME type and manifest size. parse() checks that the file exists, is a PNG or SVG, and for a PNG that the header is valid and at least 144x144 pixels, so code-server refuses to start otherwise and names the config file when the flag came from it. The manifest uses the size read at startup.
1 parent c39b30b commit c014000

9 files changed

Lines changed: 168 additions & 70 deletions

File tree

‎docs/guide.md‎

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -549,9 +549,11 @@ app-name: My Editor
549549
app-icon: /home/coder/.config/code-server/icon.svg
550550
```
551551

552-
For the PWA to be installable, use an SVG or a PNG of at least 144x144 pixels.
553-
iOS does not use SVG files for home screen icons, so use a PNG of 180x180 pixels
554-
or larger if you add code-server to an iPhone or iPad home screen.
552+
A PNG must be at least 144x144 pixels, the smallest icon that browsers accept
553+
for an installable app; code-server refuses to start with a smaller one, a
554+
missing file, or any other file type. iOS does not use SVG files for home
555+
screen icons, so use a PNG of 180x180 pixels or larger if you add code-server to
556+
an iPhone or iPad home screen.
555557

556558
### Legacy flag
557559

‎src/node/appIcon.ts‎

Lines changed: 57 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
1-
import { promises as fs } from "fs"
1+
import * as fs from "fs"
2+
import * as path from "path"
23
import { getMediaMime } from "./util"
34

45
/**
@@ -13,34 +14,70 @@ export const bundledIconPaths = [
1314
]
1415

1516
/**
16-
* The web app manifest entry for a custom `--app-icon`. `src` is one of the
17-
* bundled icon paths, since those serve the custom icon.
17+
* The smallest PNG that browsers accept as the icon of an installable app.
1818
*/
19-
export async function appIconManifestEntry(iconPath: string, src: string) {
20-
const type = getMediaMime(iconPath.toLowerCase())
21-
return {
22-
src,
23-
type,
24-
sizes: type === "image/svg+xml" ? "any" : await pngSize(iconPath),
25-
purpose: "any",
19+
export const minPngSize = 144
20+
21+
/**
22+
* A custom `--app-icon`, checked when the flags are parsed so that a bad file
23+
* stops code-server at startup instead of failing a later request.
24+
*/
25+
export class AppIcon {
26+
public constructor(
27+
/** Absolute path to the icon file. */
28+
public readonly path: string,
29+
/** The icon's MIME type. */
30+
public readonly type: string,
31+
/** The web app manifest `sizes` value. */
32+
public readonly sizes: string,
33+
) {}
34+
35+
/**
36+
* Check that `iconPath` is an existing PNG or SVG file and, for a PNG, read
37+
* its dimensions from its header.
38+
*/
39+
public static read(iconPath: string): AppIcon {
40+
const extension = path.extname(iconPath).toLowerCase()
41+
if (extension !== ".png" && extension !== ".svg") {
42+
throw new Error("--app-icon must be a .png or .svg file")
43+
}
44+
let stat: fs.Stats
45+
try {
46+
stat = fs.statSync(iconPath)
47+
} catch (error: any) {
48+
throw new Error(`--app-icon ${iconPath} cannot be read: ${error.message}`)
49+
}
50+
if (!stat.isFile()) {
51+
throw new Error(`--app-icon ${iconPath} is not a file`)
52+
}
53+
return new AppIcon(iconPath, getMediaMime(`icon${extension}`), extension === ".svg" ? "any" : pngSize(iconPath))
2654
}
2755
}
2856

2957
/**
3058
* Read a PNG's dimensions from its header as a manifest `sizes` value. Browsers
3159
* only offer to install the app when the manifest declares a large enough icon.
3260
*/
33-
async function pngSize(pngPath: string): Promise<string> {
34-
const handle = await fs.open(pngPath)
61+
function pngSize(pngPath: string): string {
62+
const buffer = Buffer.alloc(24)
63+
const fd = fs.openSync(pngPath, "r")
64+
let bytesRead: number
3565
try {
36-
const { buffer, bytesRead } = await handle.read(Buffer.alloc(24), 0, 24, 0)
37-
// An 8-byte signature, then the IHDR chunk's length and type, then width
38-
// and height as 4-byte big-endian integers.
39-
if (bytesRead < 24 || buffer.toString("latin1", 1, 4) !== "PNG" || buffer.toString("latin1", 12, 16) !== "IHDR") {
40-
throw new Error(`--app-icon ${pngPath} is not a PNG file`)
41-
}
42-
return `${buffer.readUInt32BE(16)}x${buffer.readUInt32BE(20)}`
66+
bytesRead = fs.readSync(fd, buffer, 0, buffer.length, 0)
4367
} finally {
44-
await handle.close()
68+
fs.closeSync(fd)
69+
}
70+
// An 8-byte signature, then the IHDR chunk's length and type, then width
71+
// and height as 4-byte big-endian integers.
72+
if (bytesRead < 24 || buffer.toString("latin1", 1, 4) !== "PNG" || buffer.toString("latin1", 12, 16) !== "IHDR") {
73+
throw new Error(`--app-icon ${pngPath} is not a PNG file`)
74+
}
75+
const width = buffer.readUInt32BE(16)
76+
const height = buffer.readUInt32BE(20)
77+
if (width < minPngSize || height < minPngSize) {
78+
throw new Error(
79+
`--app-icon ${pngPath} is ${width}x${height} pixels but must be at least ${minPngSize}x${minPngSize} pixels`,
80+
)
4581
}
82+
return `${width}x${height}`
4683
}

‎src/node/cli.ts‎

Lines changed: 23 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ import * as crypto from "crypto"
33
import { promises as fs } from "fs"
44
import { load } from "js-yaml"
55
import * as path from "path"
6+
import { AppIcon } from "./appIcon"
67
import { expandTilde, generateCertificate, generatePassword, paths, splitOnFirstEquals } from "./util"
78
import { EditorSessionManagerClient } from "./vscodeSocket"
89

@@ -99,7 +100,7 @@ export interface UserProvidedArgs extends UserProvidedCodeArgs {
99100
"ignore-last-opened"?: boolean
100101
verbose?: boolean
101102
"app-name"?: string
102-
"app-icon"?: string
103+
"app-icon"?: AppIcon
103104
"welcome-text"?: string
104105
"abs-proxy-base-path"?: string
105106
i18n?: string
@@ -134,17 +135,19 @@ type OptionType<T> = T extends boolean
134135
? "boolean"
135136
: T extends OptionalString
136137
? typeof OptionalString
137-
: T extends LogLevel
138-
? typeof LogLevel
139-
: T extends AuthType
140-
? typeof AuthType
141-
: T extends number
142-
? "number"
143-
: T extends string
144-
? "string"
145-
: T extends string[]
146-
? "string[]"
147-
: "unknown"
138+
: T extends AppIcon
139+
? typeof AppIcon
140+
: T extends LogLevel
141+
? typeof LogLevel
142+
: T extends AuthType
143+
? typeof AuthType
144+
: T extends number
145+
? "number"
146+
: T extends string
147+
? "string"
148+
: T extends string[]
149+
? "string[]"
150+
: "unknown"
148151

149152
export type Options<T> = {
150153
[P in keyof T]: Option<OptionType<T[P]>>
@@ -328,7 +331,7 @@ export const options: Options<Required<UserProvidedArgs>> = {
328331
"Will replace the {{app}} placeholder in any strings, which by default includes the title bar and welcome message",
329332
},
330333
"app-icon": {
331-
type: "string",
334+
type: AppIcon,
332335
path: true,
333336
description: "Path to a PNG or SVG file to use as the favicon and PWA icon in place of the code-server logo.",
334337
},
@@ -515,6 +518,13 @@ export const parse = (
515518
case OptionalString:
516519
;(args[key] as OptionalString) = new OptionalString(value)
517520
break
521+
case AppIcon:
522+
try {
523+
;(args[key] as AppIcon) = AppIcon.read(value)
524+
} catch (e: any) {
525+
throw error(e.message)
526+
}
527+
break
518528
default: {
519529
if (!Object.values(option.type).includes(value)) {
520530
throw error(`--${key} valid values: [${Object.values(option.type).join(", ")}]`)
@@ -738,10 +748,6 @@ export async function setDefaults(cliArgs: UserProvidedArgs, configArgs?: Config
738748

739749
args["app-name"] ??= process.env.CODE_SERVER_APP_NAME || "code-server"
740750

741-
if (args["app-icon"] && ![".png", ".svg"].includes(path.extname(args["app-icon"]).toLowerCase())) {
742-
throw new Error("--app-icon must be a .png or .svg file.")
743-
}
744-
745751
args._ = getResolvedPathsFromArgs(args)
746752

747753
return {

‎src/node/routes/index.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -144,7 +144,7 @@ export const register = async (
144144
// serving the custom icon in their place replaces it everywhere.
145145
app.router.get(
146146
bundledIconPaths.map((iconPath) => `/_static/${iconPath}`),
147-
(_, res) => res.sendFile(appIcon, { dotfiles: "allow" }),
147+
(_, res) => res.sendFile(appIcon.path, { dotfiles: "allow" }),
148148
)
149149
}
150150

‎src/node/routes/vscode.ts‎

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,6 @@ import * as net from "net"
77
import * as os from "os"
88
import * as path from "path"
99
import { logError } from "../../common/util"
10-
import { appIconManifestEntry } from "../appIcon"
1110
import { CodeArgs, toCodeArgs } from "../cli"
1211
import { isDevMode, vsRootPath } from "../constants"
1312
import { authenticated, ensureAuthenticated, ensureOrigin, redirect, replaceTemplates, self } from "../http"
@@ -177,7 +176,14 @@ router.get("/manifest.json", async (req, res) => {
177176
// A custom icon gets no maskable variant: browsers crop maskable icons to a
178177
// shape, which would clip an icon that was not drawn for it.
179178
const icons = appIcon
180-
? [await appIconManifestEntry(appIcon, "{{BASE}}/_static/src/browser/media/pwa-icon-512.png")]
179+
? [
180+
{
181+
src: "{{BASE}}/_static/src/browser/media/pwa-icon-512.png",
182+
type: appIcon.type,
183+
sizes: appIcon.sizes,
184+
purpose: "any",
185+
},
186+
]
181187
: [192, 512]
182188
.map((size) => [
183189
{

‎test/unit/node/appIcon.test.ts‎

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
import { promises as fs } from "fs"
2+
import * as path from "path"
3+
import { AppIcon } from "../../../src/node/appIcon"
4+
import { clean, pngHeader, tmpdir } from "../../utils/helpers"
5+
6+
describe("AppIcon.read", () => {
7+
let dir: string
8+
9+
const testName = "app-icon-read"
10+
beforeAll(async () => {
11+
await clean(testName)
12+
dir = await tmpdir(testName)
13+
})
14+
15+
it("should read a PNG's dimensions", async () => {
16+
const icon = path.join(dir, "icon.png")
17+
await fs.writeFile(icon, pngHeader(512, 256))
18+
expect(AppIcon.read(icon)).toEqual(new AppIcon(icon, "image/png", "512x256"))
19+
})
20+
21+
it("should declare an SVG for any size", async () => {
22+
const icon = path.join(dir, "icon.svg")
23+
await fs.writeFile(icon, "<svg/>")
24+
expect(AppIcon.read(icon)).toEqual(new AppIcon(icon, "image/svg+xml", "any"))
25+
})
26+
27+
it("should reject a file that is not a PNG or SVG", async () => {
28+
const icon = path.join(dir, "icon.ico")
29+
await fs.writeFile(icon, "")
30+
expect(() => AppIcon.read(icon)).toThrow("--app-icon must be a .png or .svg file")
31+
})
32+
33+
it("should reject a missing file", () => {
34+
expect(() => AppIcon.read(path.join(dir, "missing.svg"))).toThrow(/cannot be read: ENOENT/)
35+
})
36+
37+
it("should reject a directory", async () => {
38+
const icon = path.join(dir, "directory.svg")
39+
await fs.mkdir(icon)
40+
expect(() => AppIcon.read(icon)).toThrow(`--app-icon ${icon} is not a file`)
41+
})
42+
43+
it("should reject a PNG with an invalid header", async () => {
44+
const icon = path.join(dir, "not-a.png")
45+
await fs.writeFile(icon, "not a png")
46+
expect(() => AppIcon.read(icon)).toThrow(`--app-icon ${icon} is not a PNG file`)
47+
})
48+
49+
it("should reject a PNG smaller than 144x144", async () => {
50+
const icon = path.join(dir, "small.png")
51+
await fs.writeFile(icon, pngHeader(144, 143))
52+
expect(() => AppIcon.read(icon)).toThrow(`--app-icon ${icon} is 144x143 pixels but must be at least 144x144 pixels`)
53+
})
54+
})

‎test/unit/node/cli.test.ts‎

Lines changed: 9 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ import { Level, logger } from "@coder/logger"
22
import { promises as fs } from "fs"
33
import * as os from "os"
44
import * as path from "path"
5+
import { AppIcon } from "../../../src/node/appIcon"
56
import {
67
UserProvidedArgs,
78
bindAddrFromArgs,
@@ -25,7 +26,7 @@ import {
2526
EditorSessionManagerClient,
2627
makeEditorSessionManagerServer,
2728
} from "../../../src/node/vscodeSocket"
28-
import { clean, useEnv, tmpdir, listenOn } from "../../utils/helpers"
29+
import { clean, useEnv, tmpdir, listenOn, pngHeader } from "../../utils/helpers"
2930

3031
// The parser should not set any defaults so the caller can determine what
3132
// values the user actually set. These are only set after explicitly calling
@@ -402,15 +403,16 @@ describe("parser", () => {
402403
})
403404
})
404405

405-
it("should resolve the app-icon path", async () => {
406-
expect(parse(["--app-icon", "icon.svg"])).toEqual({ "app-icon": path.resolve("icon.svg") })
406+
it("should read the app-icon", async () => {
407+
const icon = path.join(await tmpdir("cli-app-icon"), "ICON.PNG")
408+
await fs.writeFile(icon, pngHeader(300, 200))
409+
expect(parse(["--app-icon", icon])).toEqual({ "app-icon": new AppIcon(icon, "image/png", "300x200") })
407410
})
408411

409-
it("should reject an app-icon that is not a PNG or SVG", async () => {
410-
await expect(setDefaults(parse(["--app-icon", "icon.ico"]))).rejects.toThrow(
411-
"--app-icon must be a .png or .svg file.",
412+
it("should name the config file when the app-icon is invalid", async () => {
413+
expect(() => parseConfigFile("app-icon: /missing/icon.svg", "/fake-config-path")).toThrow(
414+
/^error reading \/fake-config-path: --app-icon \/missing\/icon.svg cannot be read/,
412415
)
413-
await expect(setDefaults(parse(["--app-icon", "ICON.PNG"]))).resolves.toBeTruthy()
414416
})
415417

416418
it("should use env var github token", async () => {

‎test/unit/node/routes/appIcon.test.ts‎

Lines changed: 1 addition & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -2,20 +2,10 @@ import { promises as fs } from "fs"
22
import * as path from "path"
33
import { bundledIconPaths } from "../../../../src/node/appIcon"
44
import { rootPath } from "../../../../src/node/constants"
5-
import { clean, mockLogger, tmpdir } from "../../../utils/helpers"
5+
import { clean, mockLogger, pngHeader, tmpdir } from "../../../utils/helpers"
66
import * as httpserver from "../../../utils/httpserver"
77
import * as integration from "../../../utils/integration"
88

9-
/** The PNG signature and an IHDR chunk declaring the given dimensions. */
10-
function pngHeader(width: number, height: number): Buffer {
11-
const ihdr = Buffer.alloc(25)
12-
ihdr.writeUInt32BE(13, 0)
13-
ihdr.write("IHDR", 4, "latin1")
14-
ihdr.writeUInt32BE(width, 8)
15-
ihdr.writeUInt32BE(height, 12)
16-
return Buffer.concat([Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]), ihdr])
17-
}
18-
199
describe("--app-icon", () => {
2010
let codeServer: httpserver.HttpServer | undefined
2111
let iconDir: string
@@ -73,15 +63,6 @@ describe("--app-icon", () => {
7363
])
7464
})
7565

76-
it("should fail the manifest request when the PNG is not a PNG", async () => {
77-
const icon = path.join(iconDir, "not-a.png")
78-
await fs.writeFile(icon, "not a png")
79-
codeServer = await integration.setup(["--auth=none", `--app-icon=${icon}`], "")
80-
81-
const resp = await codeServer.fetch("/manifest.json")
82-
expect(resp.status).toBe(500)
83-
})
84-
8566
it("should serve the bundled icons without the flag", async () => {
8667
codeServer = await integration.setup(["--auth=none"], "")
8768

‎test/utils/helpers.ts‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,16 @@ export async function tmpdir(testName: string): Promise<string> {
4646
return await fs.mkdtemp(path.join(dir, `${testName}-`), { encoding: "utf8" })
4747
}
4848

49+
/** The PNG signature and an IHDR chunk declaring the given dimensions. */
50+
export function pngHeader(width: number, height: number): Buffer {
51+
const ihdr = Buffer.alloc(25)
52+
ihdr.writeUInt32BE(13, 0)
53+
ihdr.write("IHDR", 4, "latin1")
54+
ihdr.writeUInt32BE(width, 8)
55+
ihdr.writeUInt32BE(height, 12)
56+
return Buffer.concat([Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]), ihdr])
57+
}
58+
4959
/**
5060
* @description Helper function to use an environment variable.
5161
*

0 commit comments

Comments
 (0)