@hamur/image 0.0.2 → 0.0.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/src/index.js CHANGED
@@ -66,7 +66,10 @@ ${blob}
66
66
  }
67
67
 
68
68
  // packages/image/src/build/platform.ts
69
- import { presetFeatures as presetFeatures2 } from "hamur/kit";
69
+ import { readdir } from "node:fs/promises";
70
+ import { join, sep } from "node:path";
71
+ import { DiagnosticError, presetFeatures as presetFeatures2 } from "hamur/kit";
72
+ import { accessRuleOf } from "hamur/server/internal";
70
73
 
71
74
  // packages/image/src/domains.ts
72
75
  var LABEL = "[a-z0-9](?:[a-z0-9-]*[a-z0-9])?";
@@ -122,6 +125,7 @@ function matchesDomain(matcher, url) {
122
125
 
123
126
  // packages/image/src/build/platform.ts
124
127
  var MIME = { avif: "image/avif", webp: "image/webp" };
128
+ var IMAGE_FILE = /\.(?:png|jpe?g|gif|webp|avif|svg)$/i;
125
129
  var MINIMUM_CACHE_TTL = 14400;
126
130
  var DEFAULT_QUALITY = 75;
127
131
  function remotePatterns({ domains, alias }) {
@@ -189,14 +193,24 @@ function setupPlatform(options, hamur) {
189
193
  return;
190
194
  const config = hamur.options[service].config;
191
195
  config.images = mergeImages(config.images, service === "vercel" ? vercelImages(options) : netlifyImages(options));
196
+ hamur.hooks.hook("prerender:done", async () => {
197
+ const files = await readdir(join(hamur.options.outputDir, "public"), { recursive: true }).catch(() => []);
198
+ const ruleOf = accessRuleOf(hamur.routeRules);
199
+ for (const file of files.filter((name) => IMAGE_FILE.test(name)).toSorted()) {
200
+ const path = `/${file.split(sep).map(encodeURIComponent).join("/")}`;
201
+ const found = ruleOf(path);
202
+ if (found)
203
+ throw new DiagnosticError("HAMUR_E6008", `Route rule ${JSON.stringify(found.pattern)} ${found.key} does not protect ${path}, which the ${service} image service reads itself; move the image out of public/ or set image.provider to "none"`);
204
+ }
205
+ });
192
206
  }
193
207
 
194
208
  // packages/image/src/build/runtime.ts
195
209
  import { createHash } from "node:crypto";
196
- import { readdir } from "node:fs/promises";
197
- import { join, relative, sep } from "node:path";
210
+ import { readdir as readdir2 } from "node:fs/promises";
211
+ import { join as join2, relative, sep as sep2 } from "node:path";
198
212
  import { addTemplate as addTemplate2, createResolver as createResolver2, diagnostic as diagnostic2, readImageMeta, useLogger as useLogger2 } from "hamur/kit";
199
- var IMAGE_FILE = /\.(png|jpe?g|gif|webp|avif|svg)$/i;
213
+ var IMAGE_FILE2 = /\.(png|jpe?g|gif|webp|avif|svg)$/i;
200
214
  var normalizedBase = (baseURL) => `${baseURL.replace(/\/+$/, "")}/`;
201
215
  function providerNames(options) {
202
216
  const names = new Set(["none", options.provider, ...Object.keys(options.providers)]);
@@ -208,10 +222,10 @@ function providerNames(options) {
208
222
  async function readSources(dirs, warn = () => {}) {
209
223
  const sources = {};
210
224
  for (const dir of dirs) {
211
- const entries = await readdir(dir, { recursive: true, withFileTypes: true }).catch(() => []);
212
- for (const entry of entries.filter((item) => item.isFile() && IMAGE_FILE.test(item.name)).sort((a, b) => join(a.parentPath, a.name).localeCompare(join(b.parentPath, b.name)))) {
213
- const file = join(entry.parentPath, entry.name);
214
- const key = `/${relative(dir, file).split(sep).join("/")}`;
225
+ const entries = await readdir2(dir, { recursive: true, withFileTypes: true }).catch(() => []);
226
+ for (const entry of entries.filter((item) => item.isFile() && IMAGE_FILE2.test(item.name)).sort((a, b) => join2(a.parentPath, a.name).localeCompare(join2(b.parentPath, b.name)))) {
227
+ const file = join2(entry.parentPath, entry.name);
228
+ const key = `/${relative(dir, file).split(sep2).join("/")}`;
215
229
  if (Object.hasOwn(sources, key))
216
230
  continue;
217
231
  if (key.includes(":")) {
@@ -320,7 +334,7 @@ function setupTypes(options) {
320
334
 
321
335
  // packages/image/src/build/variants.ts
322
336
  import { mkdir, readFile, writeFile } from "node:fs/promises";
323
- import { join as join2 } from "node:path";
337
+ import { join as join3 } from "node:path";
324
338
  import { emitPublicAsset, useLogger as useLogger3 } from "hamur/kit";
325
339
 
326
340
  // packages/image/src/server/endpoint.ts
@@ -605,6 +619,7 @@ var NOT_MADE = { gif: "GIF", svg: "SVG", avif: "AVIF", heic: "HEIC", tiff: "TIFF
605
619
  var SOURCE_FILE = /\.(?:png|jpe?g|gif|webp|avif|svg)$/i;
606
620
  var IMMUTABLE = "public, max-age=31536000, immutable";
607
621
  var HOUR = "public, max-age=3600";
622
+ var PRIVATE = "private, no-store";
608
623
  var REMOTE_TIMEOUT = 1e4;
609
624
  var REMOTE_CONNECT_TIMEOUT = 2500;
610
625
  var REMOTE_FRESH = 3600000;
@@ -863,7 +878,7 @@ ${got.tag}`, pinned: false, shown: url.href, load: async () => got.bytes };
863
878
  let bytes;
864
879
  return { tag: `${shown}@${entry[3]}`, width: entry[0], pinned, shown, load: async () => bytes ??= await read() };
865
880
  }
866
- async function produce(key, request, found) {
881
+ async function produce(key, request, found, guarded) {
867
882
  const bytes = await found.load();
868
883
  if (!bytes)
869
884
  return refuse(404, `source ${JSON.stringify(found.shown)} not found`);
@@ -878,6 +893,8 @@ ${got.tag}`, pinned: false, shown: url.href, load: async () => got.bytes };
878
893
  } catch (error) {
879
894
  return refusalOf(error);
880
895
  }
896
+ if (guarded)
897
+ return output;
881
898
  try {
882
899
  await env.cache().setItemRaw(key, output);
883
900
  } catch (error) {
@@ -888,10 +905,10 @@ ${got.tag}`, pinned: false, shown: url.href, load: async () => got.bytes };
888
905
  }
889
906
  return output;
890
907
  }
891
- async function answerFound(parsed, found, incoming, head) {
908
+ async function answerFound(parsed, found, incoming, head, guarded) {
892
909
  const again = async (reread) => {
893
910
  const fresh = await reread();
894
- return isRefusal(fresh) ? answerText(fresh, head) : answerFound(parsed, fresh, incoming, head);
911
+ return isRefusal(fresh) ? answerText(fresh, head) : answerFound(parsed, fresh, incoming, head, guarded);
895
912
  };
896
913
  if (parsed.w !== undefined && !options.widths.includes(parsed.w)) {
897
914
  if (found.width === undefined && found.reread)
@@ -918,18 +935,18 @@ ${parsed.extension}`))).slice(0, 16)}`;
918
935
  const headers = {
919
936
  "content-type": TYPES[parsed.extension],
920
937
  etag,
921
- "cache-control": endpoint.dev ? "no-cache" : found.pinned ? IMMUTABLE : HOUR,
938
+ "cache-control": guarded ? PRIVATE : endpoint.dev ? "no-cache" : found.pinned ? IMMUTABLE : HOUR,
922
939
  "x-content-type-options": "nosniff"
923
940
  };
924
941
  if (matchesTag(incoming.headers.get("if-none-match"), etag))
925
942
  return new Response(null, { status: 304, headers });
926
- let output = await env.cache().getItemRaw(key);
943
+ let output = guarded ? undefined : await env.cache().getItemRaw(key);
927
944
  if (!output && found.reread)
928
945
  return again(found.reread);
929
946
  if (!output) {
930
947
  let work = running.get(key);
931
948
  if (work === undefined) {
932
- work = produce(key, parsed, found).finally(() => running.delete(key));
949
+ work = produce(key, parsed, found, guarded).finally(() => running.delete(key));
933
950
  running.set(key, work);
934
951
  }
935
952
  output = await work;
@@ -938,21 +955,23 @@ ${parsed.extension}`))).slice(0, 16)}`;
938
955
  return answerText(output, head);
939
956
  return new Response(head ? null : owned(output), { status: 200, headers });
940
957
  }
941
- return async (incoming) => {
958
+ return async (incoming, access) => {
942
959
  const head = incoming.method === "HEAD";
943
960
  const { pathname, search } = new URL(incoming.url);
944
961
  const parsed = pathname.startsWith(prefix) ? parseImagePath(pathname.slice(prefix.length)) : refuse(404, "not found");
945
962
  if (isRefusal(parsed))
946
963
  return answerText(parsed, head);
964
+ const guarded = parsed.path !== undefined && access !== undefined && await access(`/${parsed.path.split("/").map(encodeURIComponent).join("/")}`);
947
965
  const found = parsed.remote === undefined ? await findLocal(parsed) : await findRemote(parsed.remote, search);
948
966
  if (isRefusal(found))
949
967
  return answerText(found, head);
950
- return answerFound(parsed, found, incoming, head);
968
+ return answerFound(parsed, found, incoming, head, guarded);
951
969
  };
952
970
  }
953
971
 
954
972
  // packages/image/src/build/variants.ts
955
- import { DiagnosticError } from "hamur/kit";
973
+ import { DiagnosticError as DiagnosticError2 } from "hamur/kit";
974
+ import { accessRuleOf as accessRuleOf2, hasPlatformFiles } from "hamur/server/internal";
956
975
  var ATTRIBUTE = /\s(src|srcset|imagesrcset|href|style)\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'=<>`]+))/gi;
957
976
  var STYLE_URL = /url\(\s*(?:"([^"]*)"|'([^']*)'|([^)\s]*))\s*\)/gi;
958
977
  var ENTITY = /&(?:#(\d+)|#x([0-9a-f]+)|(amp|quot|apos|lt|gt));/gi;
@@ -994,7 +1013,7 @@ function sourceUrls(path, entry, options, baseURL) {
994
1013
  return widths.flatMap((width) => extensions.map((extension) => `${baseURL}_hamur/image/${modifiers(width)}/${path.split("/").map(encodeURIComponent).join("/")}.${extension}`));
995
1014
  }
996
1015
  function fileCache(dir, onWrite) {
997
- const file = (key) => join2(dir, key.replace(/[^a-z0-9-]/gi, "-"));
1016
+ const file = (key) => join3(dir, key.replace(/[^a-z0-9-]/gi, "-"));
998
1017
  return {
999
1018
  async getItemRaw(key) {
1000
1019
  try {
@@ -1039,7 +1058,7 @@ function setupVariants(options, hamur) {
1039
1058
  const path = entry.slice(1);
1040
1059
  const matched = Object.entries(sources).filter(([key, source]) => !source[4] && TRANSFORMABLE.test(key) && new Bun.Glob(path).match(key.slice(1)));
1041
1060
  if (!matched.length && !isGlob(path))
1042
- throw new DiagnosticError("HAMUR_E6003", `image: image.prerender ${JSON.stringify(entry)}: source ${JSON.stringify(entry)} not found`);
1061
+ throw new DiagnosticError2("HAMUR_E6003", `image: image.prerender ${JSON.stringify(entry)}: source ${JSON.stringify(entry)} not found`);
1043
1062
  for (const [key, source] of matched)
1044
1063
  for (const url of sourceUrls(key.slice(1), source, options, baseURL))
1045
1064
  if (!where.has(url))
@@ -1047,10 +1066,22 @@ function setupVariants(options, hamur) {
1047
1066
  }
1048
1067
  if (!where.size)
1049
1068
  return;
1069
+ const ruleOf = accessRuleOf2(hamur.routeRules);
1070
+ const alone = hasPlatformFiles(hamur);
1071
+ for (const url of where.keys()) {
1072
+ const variant = new URL(url, "http://localhost").pathname;
1073
+ const parsed = parseImagePath(variant.slice(prefix.length));
1074
+ if (isRefusal(parsed) || parsed.path === undefined)
1075
+ continue;
1076
+ const source = `/${parsed.path.split("/").map(encodeURIComponent).join("/")}`;
1077
+ const found = ruleOf(source, alone ? undefined : `/${variant.slice(baseURL.length)}`);
1078
+ if (found)
1079
+ throw new DiagnosticError2("HAMUR_E6008", `Route rule ${JSON.stringify(found.pattern)} ${found.key} does not protect the variants of ${source} (in ${where.get(url)}), which are public files; use the "none" provider for this image`);
1080
+ }
1050
1081
  Bun.Image.backend = "bun";
1051
1082
  let created = 0;
1052
- const cache = fileCache(join2(hamur.options.rootDir, "node_modules/.cache/hamur/image"), () => created++);
1053
- const publicDir = join2(hamur.options.outputDir, "public");
1083
+ const cache = fileCache(join3(hamur.options.rootDir, "node_modules/.cache/hamur/image"), () => created++);
1084
+ const publicDir = join3(hamur.options.outputDir, "public");
1054
1085
  const answer = createImageEndpoint({
1055
1086
  options: { baseURL, widths: options.widths, domains: options.domains, alias: options.alias },
1056
1087
  sources,
@@ -1064,7 +1095,7 @@ function setupVariants(options, hamur) {
1064
1095
  },
1065
1096
  readSource: readFromDirs(options.dirs),
1066
1097
  readAsset: async (path) => {
1067
- const file = Bun.file(join2(publicDir, path));
1098
+ const file = Bun.file(join3(publicDir, path));
1068
1099
  return await file.exists() ? file.bytes() : undefined;
1069
1100
  },
1070
1101
  cache: () => cache,
@@ -1092,7 +1123,7 @@ function setupVariants(options, hamur) {
1092
1123
  await Promise.all(Array.from({ length: Math.min(CONCURRENCY, urls.length) }, work));
1093
1124
  const failed = failures.find((message) => message !== undefined);
1094
1125
  if (failed !== undefined)
1095
- throw new DiagnosticError("HAMUR_E6004", failed);
1126
+ throw new DiagnosticError2("HAMUR_E6004", failed);
1096
1127
  urls.forEach((url, i) => emitPublicAsset(`/${new URL(url, "http://localhost").pathname.slice(baseURL.length)}`, bytes[i]));
1097
1128
  log.info(`[image] ${urls.length} variants (${created} new, ${urls.length - created} from cache)`);
1098
1129
  });
@@ -1100,7 +1131,7 @@ function setupVariants(options, hamur) {
1100
1131
 
1101
1132
  // packages/image/src/options.ts
1102
1133
  import { resolve } from "node:path";
1103
- import { DiagnosticError as DiagnosticError2 } from "hamur/kit";
1134
+ import { DiagnosticError as DiagnosticError3 } from "hamur/kit";
1104
1135
  var BUILT_IN_PROVIDERS = [
1105
1136
  "hamur",
1106
1137
  "none",
@@ -1152,7 +1183,7 @@ var SECRET_OPTIONS = ["key", "secret", "salt"];
1152
1183
  var MAX_WIDTH = 16384;
1153
1184
  var SCREEN_NAME = /^[a-z0-9]+$/i;
1154
1185
  function fail(message) {
1155
- throw new DiagnosticError2("HAMUR_E6001", message);
1186
+ throw new DiagnosticError3("HAMUR_E6001", message);
1156
1187
  }
1157
1188
  function shown(value) {
1158
1189
  if (Array.isArray(value))
@@ -1418,7 +1449,7 @@ function resolveOptions(input, env) {
1418
1449
  }
1419
1450
 
1420
1451
  // packages/image/src/module.ts
1421
- import { DiagnosticError as DiagnosticError3 } from "hamur/kit";
1452
+ import { DiagnosticError as DiagnosticError4 } from "hamur/kit";
1422
1453
  var module_default = defineModule({
1423
1454
  meta: { name: "image", configKey: "image" },
1424
1455
  async setup(input, hamur) {
@@ -1429,7 +1460,7 @@ var module_default = defineModule({
1429
1460
  });
1430
1461
  const options = { ...resolved, provider: resolveProvider(resolved.provider, hamur) };
1431
1462
  if (options.sources.blob && !hasModule("@hamur/blob"))
1432
- throw new DiagnosticError3("HAMUR_E6002", 'image.sources.blob needs "@hamur/blob" in modules');
1463
+ throw new DiagnosticError4("HAMUR_E6002", 'image.sources.blob needs "@hamur/blob" in modules');
1433
1464
  setupRuntime(options, hamur);
1434
1465
  setupEndpoint(options, hamur);
1435
1466
  setupVariants(options, hamur);
@@ -0,0 +1,33 @@
1
+ <script lang="ts">
2
+ import type { Snippet } from "svelte"
3
+ import type { HTMLImgAttributes } from "svelte/elements"
4
+ import { useHead } from "@hamur/adapter-svelte"
5
+ import { imgAttributes } from "../runtime/index.ts"
6
+ import { applyPlaceholder, imagePreloadLink, type ImgOptions, type ImgState } from "../runtime/img.ts"
7
+
8
+ type Props = ImgOptions & {
9
+ fetchpriority?: "high" | "low" | "auto"
10
+ children?: Snippet<[ImgState]>
11
+ } & Omit<HTMLImgAttributes, keyof ImgOptions | "srcset" | "fetchpriority" | "children">
12
+
13
+ let { children, onload, onerror, ...props }: Props = $props()
14
+ let isLoaded = $state(false)
15
+ if (props.preload) useHead(() => ({ link: [imagePreloadLink(imgAttributes(props))] }))
16
+ const attrs = $derived({
17
+ ...applyPlaceholder(imgAttributes(props), props, isLoaded),
18
+ onload: (event: Event) => {
19
+ isLoaded = true
20
+ ;(onload as ((event: Event) => void) | null | undefined)?.(event)
21
+ },
22
+ onerror: (event: Event) => {
23
+ isLoaded = false
24
+ ;(onerror as ((event: Event) => void) | null | undefined)?.(event)
25
+ },
26
+ })
27
+ </script>
28
+
29
+ {#if children}
30
+ {@render children({ imgAttrs: attrs, src: String(attrs.src), isLoaded })}
31
+ {:else}
32
+ <img {...attrs} />
33
+ {/if}
@@ -0,0 +1,39 @@
1
+ <script lang="ts">
2
+ import type { HTMLImgAttributes } from "svelte/elements"
3
+ import { useHead } from "@hamur/adapter-svelte"
4
+ import { pictureAttributes } from "../runtime/index.ts"
5
+ import { applyPlaceholder } from "../runtime/img.ts"
6
+ import { picturePreloadLink, type PictureOptions } from "../runtime/picture.ts"
7
+
8
+ type Props = PictureOptions & { fetchpriority?: "high" | "low" | "auto" } & Omit<
9
+ HTMLImgAttributes,
10
+ keyof PictureOptions | "srcset" | "fetchpriority"
11
+ >
12
+
13
+ let { onload, onerror, ...props }: Props = $props()
14
+ let isLoaded = $state(false)
15
+ const parts = $derived(pictureAttributes(props))
16
+ const img = $derived({
17
+ ...applyPlaceholder(parts.img, props, isLoaded),
18
+ onload: (event: Event) => {
19
+ isLoaded = true
20
+ ;(onload as ((event: Event) => void) | null | undefined)?.(event)
21
+ },
22
+ onerror: (event: Event) => {
23
+ isLoaded = false
24
+ ;(onerror as ((event: Event) => void) | null | undefined)?.(event)
25
+ },
26
+ })
27
+ if (props.preload) useHead(() => ({ link: [picturePreloadLink(parts)] }))
28
+ </script>
29
+
30
+ {#if parts.sources.length === 0}
31
+ <img {...img} />
32
+ {:else}
33
+ <picture>
34
+ {#each parts.sources as source (source.type)}
35
+ <source {...source} />
36
+ {/each}
37
+ <img {...img} />
38
+ </picture>
39
+ {/if}
@@ -42,5 +42,7 @@ export declare function readFromDirs(dirs: readonly string[]): (path: string) =>
42
42
  export declare function checkSource(bytes: Uint8Array, maxPixels: number): SourceSize | ImageRefusal;
43
43
  /** With `Bun.Image`: `rot`, `flip`, `flop`, then the resize, then the encoder of the extension. */
44
44
  export declare const transformImage: ImageTransform;
45
- /** The `/_hamur/image/**` answer. Every 200 is bytes this endpoint encoded, never a source's own. */
46
- export declare function createImageEndpoint(env: EndpointEnvironment): (request: Request) => Promise<Response>;
45
+ /** Throws the refusal of the access rule on the public file at `path`; true when a rule covers it. */
46
+ export type SourceAccess = (path: string) => Promise<boolean>;
47
+ /** The `/_hamur/image/**` answer. Every 200 is bytes this endpoint encoded, never a source's own. An image has the access of its source. */
48
+ export declare function createImageEndpoint(env: EndpointEnvironment): (request: Request, access?: SourceAccess) => Promise<Response>;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hamur/image",
3
- "version": "0.0.2",
3
+ "version": "0.0.4",
4
4
  "type": "module",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -80,14 +80,14 @@
80
80
  ],
81
81
  "dependencies": {},
82
82
  "peerDependencies": {
83
- "hamur": "~0.0.2",
84
- "@hamur/adapter-react": "^0.0.2",
85
- "@hamur/adapter-vue": "^0.0.2",
86
- "@hamur/adapter-preact": "^0.0.2",
87
- "@hamur/adapter-svelte": "^0.0.2",
88
- "@hamur/adapter-solid": "^0.0.2",
89
- "@hamur/adapter-html": "^0.0.2",
90
- "@hamur/adapter-angular": "^0.0.2",
83
+ "hamur": "0.0.4",
84
+ "@hamur/adapter-react": ">=0.0.4 <0.1.0",
85
+ "@hamur/adapter-vue": ">=0.0.4 <0.1.0",
86
+ "@hamur/adapter-preact": ">=0.0.4 <0.1.0",
87
+ "@hamur/adapter-svelte": ">=0.0.4 <0.1.0",
88
+ "@hamur/adapter-solid": ">=0.0.4 <0.1.0",
89
+ "@hamur/adapter-html": ">=0.0.4 <0.1.0",
90
+ "@hamur/adapter-angular": ">=0.0.4 <0.1.0",
91
91
  "react": "^19.3.1",
92
92
  "preact": "^11.0.2",
93
93
  "vue": "^3.5.44",
@@ -1,9 +1,13 @@
1
- import { presetFeatures, type HamurContext } from "hamur/kit"
1
+ import { readdir } from "node:fs/promises"
2
+ import { join, sep } from "node:path"
3
+ import { DiagnosticError, presetFeatures, type HamurContext } from "hamur/kit"
4
+ import { accessRuleOf } from "hamur/server/internal"
2
5
  import { hostSource, parseDomain, pathSource } from "../domains.ts"
3
6
  import type { ImageBuildOptions, ImageFormat } from "../types.ts"
4
7
  import { providersUsed } from "./endpoint.ts"
5
8
 
6
9
  const MIME: Partial<Record<ImageFormat, string>> = { avif: "image/avif", webp: "image/webp" }
10
+ const IMAGE_FILE = /\.(?:png|jpe?g|gif|webp|avif|svg)$/i
7
11
  const MINIMUM_CACHE_TTL = 14400
8
12
  const DEFAULT_QUALITY = 75
9
13
 
@@ -96,4 +100,17 @@ export function setupPlatform(options: ImageBuildOptions, hamur: HamurContext):
96
100
  if (service === undefined || !providersUsed(options).has(service)) return
97
101
  const config = hamur.options[service].config
98
102
  config.images = mergeImages(config.images, service === "vercel" ? vercelImages(options) : netlifyImages(options))
103
+ hamur.hooks.hook("prerender:done", async () => {
104
+ const files = await readdir(join(hamur.options.outputDir, "public"), { recursive: true }).catch(() => [])
105
+ const ruleOf = accessRuleOf(hamur.routeRules)
106
+ for (const file of files.filter((name) => IMAGE_FILE.test(name)).toSorted()) {
107
+ const path = `/${file.split(sep).map(encodeURIComponent).join("/")}`
108
+ const found = ruleOf(path)
109
+ if (found)
110
+ throw new DiagnosticError(
111
+ "HAMUR_E6008",
112
+ `Route rule ${JSON.stringify(found.pattern)} ${found.key} does not protect ${path}, which the ${service} image service reads itself; move the image out of public/ or set image.provider to "none"`,
113
+ )
114
+ }
115
+ })
99
116
  }
@@ -6,6 +6,8 @@ import type { ImageBuildOptions, ImageFormat, ImageSources, ResolvedImageOptions
6
6
  import { providersUsed, transformsAtRunTime } from "./endpoint.ts"
7
7
  import { normalizedBase, readSources } from "./runtime.ts"
8
8
  import { DiagnosticError } from "hamur/kit"
9
+ import { accessRuleOf, hasPlatformFiles } from "hamur/server/internal"
10
+ import { isRefusal, parseImagePath } from "../server/parse.ts"
9
11
 
10
12
  const ATTRIBUTE = /\s(src|srcset|imagesrcset|href|style)\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'=<>`]+))/gi
11
13
  const STYLE_URL = /url\(\s*(?:"([^"]*)"|'([^']*)'|([^)\s]*))\s*\)/gi
@@ -122,6 +124,21 @@ export function setupVariants(options: ImageBuildOptions, hamur: HamurContext):
122
124
  }
123
125
  if (!where.size) return
124
126
 
127
+ const ruleOf = accessRuleOf(hamur.routeRules)
128
+ const alone = hasPlatformFiles(hamur)
129
+ for (const url of where.keys()) {
130
+ const variant = new URL(url, "http://localhost").pathname
131
+ const parsed = parseImagePath(variant.slice(prefix.length))
132
+ if (isRefusal(parsed) || parsed.path === undefined) continue
133
+ const source = `/${parsed.path.split("/").map(encodeURIComponent).join("/")}`
134
+ const found = ruleOf(source, alone ? undefined : `/${variant.slice(baseURL.length)}`)
135
+ if (found)
136
+ throw new DiagnosticError(
137
+ "HAMUR_E6008",
138
+ `Route rule ${JSON.stringify(found.pattern)} ${found.key} does not protect the variants of ${source} (in ${where.get(url)}), which are public files; use the "none" provider for this image`,
139
+ )
140
+ }
141
+
125
142
  Bun.Image.backend = "bun"
126
143
  let created = 0
127
144
  const cache = fileCache(join(hamur.options.rootDir, "node_modules/.cache/hamur/image"), () => created++)
@@ -59,6 +59,7 @@ const NOT_MADE: Record<string, string> = { gif: "GIF", svg: "SVG", avif: "AVIF",
59
59
  const SOURCE_FILE = /\.(?:png|jpe?g|gif|webp|avif|svg)$/i
60
60
  const IMMUTABLE = "public, max-age=31536000, immutable"
61
61
  const HOUR = "public, max-age=3600"
62
+ const PRIVATE = "private, no-store"
62
63
  const REMOTE_TIMEOUT = 10_000
63
64
  const REMOTE_CONNECT_TIMEOUT = 2_500
64
65
  /** How long a remote URL's source ETag is trusted without asking upstream, as long as `HOUR` lets a browser keep it. */
@@ -197,8 +198,13 @@ interface Fetched {
197
198
  tag: string
198
199
  }
199
200
 
200
- /** The `/_hamur/image/**` answer. Every 200 is bytes this endpoint encoded, never a source's own. */
201
- export function createImageEndpoint(env: EndpointEnvironment): (request: Request) => Promise<Response> {
201
+ /** Throws the refusal of the access rule on the public file at `path`; true when a rule covers it. */
202
+ export type SourceAccess = (path: string) => Promise<boolean>
203
+
204
+ /** The `/_hamur/image/**` answer. Every 200 is bytes this endpoint encoded, never a source's own. An image has the access of its source. */
205
+ export function createImageEndpoint(
206
+ env: EndpointEnvironment,
207
+ ): (request: Request, access?: SourceAccess) => Promise<Response> {
202
208
  const { options, sources, endpoint } = env
203
209
  const transform = env.transform ?? transformImage
204
210
  const prefix = `${options.baseURL}_hamur/image/`
@@ -342,7 +348,12 @@ export function createImageEndpoint(env: EndpointEnvironment): (request: Request
342
348
  return { tag: `${shown}@${entry[3]}`, width: entry[0], pinned, shown, load: async () => (bytes ??= await read()) }
343
349
  }
344
350
 
345
- async function produce(key: string, request: ImageRequest, found: Found): Promise<Uint8Array | ImageRefusal> {
351
+ async function produce(
352
+ key: string,
353
+ request: ImageRequest,
354
+ found: Found,
355
+ guarded: boolean,
356
+ ): Promise<Uint8Array | ImageRefusal> {
346
357
  const bytes = await found.load()
347
358
  if (!bytes) return refuse(404, `source ${JSON.stringify(found.shown)} not found`)
348
359
  if (isRefusal(bytes)) return bytes
@@ -354,6 +365,7 @@ export function createImageEndpoint(env: EndpointEnvironment): (request: Request
354
365
  } catch (error) {
355
366
  return refusalOf(error)
356
367
  }
368
+ if (guarded) return output
357
369
  try {
358
370
  await env.cache().setItemRaw(key, output)
359
371
  } catch (error) {
@@ -367,10 +379,16 @@ export function createImageEndpoint(env: EndpointEnvironment): (request: Request
367
379
  return output
368
380
  }
369
381
 
370
- async function answerFound(parsed: ImageRequest, found: Found, incoming: Request, head: boolean): Promise<Response> {
382
+ async function answerFound(
383
+ parsed: ImageRequest,
384
+ found: Found,
385
+ incoming: Request,
386
+ head: boolean,
387
+ guarded: boolean,
388
+ ): Promise<Response> {
371
389
  const again = async (reread: NonNullable<Found["reread"]>) => {
372
390
  const fresh = await reread()
373
- return isRefusal(fresh) ? answerText(fresh, head) : answerFound(parsed, fresh, incoming, head)
391
+ return isRefusal(fresh) ? answerText(fresh, head) : answerFound(parsed, fresh, incoming, head, guarded)
374
392
  }
375
393
  if (parsed.w !== undefined && !options.widths.includes(parsed.w)) {
376
394
  if (found.width === undefined && found.reread) return again(found.reread)
@@ -395,17 +413,17 @@ export function createImageEndpoint(env: EndpointEnvironment): (request: Request
395
413
  const headers = {
396
414
  "content-type": TYPES[parsed.extension],
397
415
  etag,
398
- "cache-control": endpoint.dev ? "no-cache" : found.pinned ? IMMUTABLE : HOUR,
416
+ "cache-control": guarded ? PRIVATE : endpoint.dev ? "no-cache" : found.pinned ? IMMUTABLE : HOUR,
399
417
  "x-content-type-options": "nosniff",
400
418
  }
401
419
  if (matchesTag(incoming.headers.get("if-none-match"), etag)) return new Response(null, { status: 304, headers })
402
420
 
403
- let output: Uint8Array | ImageRefusal | undefined = await env.cache().getItemRaw(key)
421
+ let output: Uint8Array | ImageRefusal | undefined = guarded ? undefined : await env.cache().getItemRaw(key)
404
422
  if (!output && found.reread) return again(found.reread)
405
423
  if (!output) {
406
424
  let work = running.get(key)
407
425
  if (work === undefined) {
408
- work = produce(key, parsed, found).finally(() => running.delete(key))
426
+ work = produce(key, parsed, found, guarded).finally(() => running.delete(key))
409
427
  running.set(key, work)
410
428
  }
411
429
  output = await work
@@ -414,15 +432,19 @@ export function createImageEndpoint(env: EndpointEnvironment): (request: Request
414
432
  return new Response(head ? null : owned(output), { status: 200, headers })
415
433
  }
416
434
 
417
- return async (incoming) => {
435
+ return async (incoming, access) => {
418
436
  const head = incoming.method === "HEAD"
419
437
  const { pathname, search } = new URL(incoming.url)
420
438
  const parsed = pathname.startsWith(prefix)
421
439
  ? parseImagePath(pathname.slice(prefix.length))
422
440
  : refuse(404, "not found")
423
441
  if (isRefusal(parsed)) return answerText(parsed, head)
442
+ const guarded =
443
+ parsed.path !== undefined &&
444
+ access !== undefined &&
445
+ (await access(`/${parsed.path.split("/").map(encodeURIComponent).join("/")}`))
424
446
  const found = parsed.remote === undefined ? await findLocal(parsed) : await findRemote(parsed.remote, search)
425
447
  if (isRefusal(found)) return answerText(found, head)
426
- return answerFound(parsed, found, incoming, head)
448
+ return answerFound(parsed, found, incoming, head, guarded)
427
449
  }
428
450
  }
@@ -3,6 +3,7 @@ import endpoint, { useBlob } from "#hamur/image/endpoint"
3
3
  import options from "#hamur/image/options"
4
4
  import sources from "#hamur/image/sources"
5
5
  import { defineHandler, readAsset, useLogger, useStorage } from "hamur/server"
6
+ import { requireFileAccess } from "hamur/server/internal"
6
7
  import { createImageEndpoint, readFromDirs } from "./endpoint.ts"
7
8
 
8
9
  const bytesOf = async (response: Response): Promise<Uint8Array | undefined> =>
@@ -29,5 +30,5 @@ export const imageEndpoint = defineHandler({
29
30
  route: "/_hamur/image/**:path",
30
31
  method: "GET",
31
32
  raw: true,
32
- handler: (_, { event }) => answer(event.request),
33
+ handler: (_, { event }) => answer(event.request, (path) => requireFileAccess(event, path)),
33
34
  })