@horizonwing/engine 0.0.0-stage → 0.1.0
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/README.md +32 -2
- package/drizzle/pg/schema.ts +100 -0
- package/drizzle/postgres/0000_smooth_princess_powerful.sql +34 -0
- package/drizzle/postgres/0001_colossal_morbius.sql +50 -0
- package/drizzle/postgres/README.md +23 -0
- package/drizzle/postgres/meta/0000_snapshot.json +244 -0
- package/drizzle/postgres/meta/0001_snapshot.json +545 -0
- package/drizzle/postgres/meta/_journal.json +20 -0
- package/drizzle/schema.ts +128 -0
- package/drizzle/sqlite/0000_cooing_jackpot.sql +34 -0
- package/drizzle/sqlite/0001_living_ben_urich.sql +49 -0
- package/drizzle/sqlite/meta/0000_snapshot.json +231 -0
- package/drizzle/sqlite/meta/0001_snapshot.json +554 -0
- package/drizzle/sqlite/meta/_journal.json +20 -0
- package/package.json +79 -4
- package/src/account-pages.tsx +151 -0
- package/src/auth.tsx +264 -0
- package/src/cache.ts +199 -0
- package/src/content.ts +448 -0
- package/src/db.ts +107 -0
- package/src/feeds.ts +376 -0
- package/src/guard.ts +126 -0
- package/src/html.ts +20 -0
- package/src/i18n.ts +304 -0
- package/src/index.ts +27 -0
- package/src/md.ts +278 -0
- package/src/media.ts +70 -0
- package/src/password.ts +59 -0
- package/src/platform.node.ts +75 -0
- package/src/platform.postgres.ts +61 -0
- package/src/platform.shared.ts +114 -0
- package/src/platform.ts +24 -0
- package/src/platform.workers.ts +94 -0
- package/src/ratelimit.ts +144 -0
- package/src/section.ts +123 -0
- package/src/sections/blog/index.tsx +92 -0
- package/src/sections/blog/schema.ts +12 -0
- package/src/sections/blog/views/pages.tsx +166 -0
- package/src/sections/docs/index.tsx +66 -0
- package/src/sections/docs/schema.ts +16 -0
- package/src/sections/docs/views/pages.tsx +180 -0
- package/src/sections/landing/index.tsx +41 -0
- package/src/sections/landing/views/pages.tsx +217 -0
- package/src/seo.ts +193 -0
- package/src/server.ts +122 -0
- package/src/services/content.ts +342 -0
- package/src/turnstile.ts +62 -0
- package/src/types.ts +192 -0
- package/src/views/error.tsx +35 -0
- package/src/views/index.tsx +12 -0
- package/src/views/layout.tsx +88 -0
- package/themes/warm/tokens.css +119 -0
package/src/feeds.ts
ADDED
|
@@ -0,0 +1,376 @@
|
|
|
1
|
+
import type { Context, Hono } from 'hono';
|
|
2
|
+
import type { ContentListItem, EngineConfig } from './types';
|
|
3
|
+
import { listPublishedAll } from './services/content';
|
|
4
|
+
import type { ContentVersionResolver } from './cache';
|
|
5
|
+
import type { SeoDeclaration } from './section';
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* SEO feeds(总设计 §5):sitemap.xml / robots.txt / rss.xml / atom.xml / llms.txt。
|
|
9
|
+
* 全部由 content 表驱动;栏目页条目来自 section seo 声明(M2 Section 协议收集),
|
|
10
|
+
* 无 sections 时退回内置默认(/ + /blog + /docs,兼容无 section 的极简站点)。
|
|
11
|
+
* Etag = content_version,Last-Modified = max(updated_at),
|
|
12
|
+
* If-None-Match / If-Modified-Since 命中回 304。
|
|
13
|
+
* RSS/Atom XML 形状参考 bbs src/routes/feeds.ts(xmlEscape / atom:link 自声明等惯例)。
|
|
14
|
+
*/
|
|
15
|
+
|
|
16
|
+
/** 无 seo 声明时的内置栏目页默认(M1 行为) */
|
|
17
|
+
const DEFAULT_LIST_PAGES: SeoDeclaration['listPage'][] = [
|
|
18
|
+
{ path: '/', title: 'Home', changefreq: 'daily', priority: 1.0 },
|
|
19
|
+
{ path: '/blog', title: 'Blog', changefreq: 'daily', priority: 0.9 },
|
|
20
|
+
{ path: '/docs', title: 'Docs', changefreq: 'weekly', priority: 0.8 },
|
|
21
|
+
];
|
|
22
|
+
|
|
23
|
+
function xmlEscape(input: string): string {
|
|
24
|
+
return input
|
|
25
|
+
.replace(/&/g, '&')
|
|
26
|
+
.replace(/</g, '<')
|
|
27
|
+
.replace(/>/g, '>')
|
|
28
|
+
.replace(/"/g, '"')
|
|
29
|
+
.replace(/'/g, ''');
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** HTTP 日期(Last-Modified/If-Modified-Since 用,秒精度) */
|
|
33
|
+
function httpDate(ms: number): string {
|
|
34
|
+
return new Date(ms).toUTCString();
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
interface FeedContext {
|
|
38
|
+
origin: string;
|
|
39
|
+
siteName: string;
|
|
40
|
+
tagline: string;
|
|
41
|
+
items: ContentListItem[];
|
|
42
|
+
lastUpdatedMs: number;
|
|
43
|
+
/** 内容语言(RSS language / xml:lang / 单语言 sitemap 默认) */
|
|
44
|
+
locale?: string;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
function itemUrl(origin: string, item: ContentListItem): string {
|
|
48
|
+
return `${origin}/${item.section}/${item.slug}`;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/* ------------------------------------------------------------------ RSS */
|
|
52
|
+
|
|
53
|
+
function rssXml(ctx: FeedContext, selfPath: string, alternatePath: string, locale: string): string {
|
|
54
|
+
const entries = ctx.items
|
|
55
|
+
.map(
|
|
56
|
+
(i) => ` <item>
|
|
57
|
+
<title>${xmlEscape(i.title)}</title>
|
|
58
|
+
<link>${itemUrl(ctx.origin, i)}</link>
|
|
59
|
+
<guid isPermaLink="true">${itemUrl(ctx.origin, i)}</guid>
|
|
60
|
+
<pubDate>${new Date(i.publishedAt).toUTCString()}</pubDate>
|
|
61
|
+
<description>${xmlEscape(i.description)}</description>${i.author ? `\n <author>${xmlEscape(i.author)}</author>` : ''}${(i.tags ?? []).map((t: string) => `\n <category>${xmlEscape(t)}</category>`).join('')}
|
|
62
|
+
</item>`,
|
|
63
|
+
)
|
|
64
|
+
.join('\n');
|
|
65
|
+
|
|
66
|
+
return `<?xml version="1.0" encoding="UTF-8"?>
|
|
67
|
+
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
|
|
68
|
+
<channel>
|
|
69
|
+
<title>${xmlEscape(ctx.siteName)}</title>
|
|
70
|
+
<link>${ctx.origin}/</link>
|
|
71
|
+
<atom:link href="${ctx.origin}${selfPath}" rel="self" type="application/rss+xml" />
|
|
72
|
+
<atom:link href="${ctx.origin}${alternatePath}" rel="alternate" type="application/atom+xml" />
|
|
73
|
+
<description>${xmlEscape(ctx.tagline)}</description>
|
|
74
|
+
<language>${locale}</language>
|
|
75
|
+
<lastBuildDate>${new Date(ctx.lastUpdatedMs).toUTCString()}</lastBuildDate>
|
|
76
|
+
${entries}
|
|
77
|
+
</channel>
|
|
78
|
+
</rss>`;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/* ------------------------------------------------------------------ Atom */
|
|
82
|
+
|
|
83
|
+
function atomXml(ctx: FeedContext, selfPath: string, alternatePath: string, locale: string): string {
|
|
84
|
+
const entries = ctx.items
|
|
85
|
+
.map(
|
|
86
|
+
(i) => ` <entry>
|
|
87
|
+
<title>${xmlEscape(i.title)}</title>
|
|
88
|
+
<link href="${itemUrl(ctx.origin, i)}" />
|
|
89
|
+
<id>${itemUrl(ctx.origin, i)}</id>
|
|
90
|
+
<published>${new Date(i.publishedAt).toISOString()}</published>
|
|
91
|
+
<updated>${new Date(i.updatedAt).toISOString()}</updated>${i.author ? `\n <author><name>${xmlEscape(i.author)}</name></author>` : ''}
|
|
92
|
+
<summary type="text">${xmlEscape(i.description)}</summary>
|
|
93
|
+
</entry>`,
|
|
94
|
+
)
|
|
95
|
+
.join('\n');
|
|
96
|
+
|
|
97
|
+
return `<?xml version="1.0" encoding="UTF-8"?>
|
|
98
|
+
<feed xmlns="http://www.w3.org/2005/Atom" xml:lang="${locale}">
|
|
99
|
+
<title>${xmlEscape(ctx.siteName)}</title>
|
|
100
|
+
<subtitle>${xmlEscape(ctx.tagline)}</subtitle>
|
|
101
|
+
<link href="${ctx.origin}/" rel="alternate" />
|
|
102
|
+
<link href="${ctx.origin}${selfPath}" rel="self" />
|
|
103
|
+
<link href="${ctx.origin}${alternatePath}" rel="alternate" type="application/rss+xml" />
|
|
104
|
+
<id>${ctx.origin}/</id>
|
|
105
|
+
<updated>${new Date(ctx.lastUpdatedMs).toISOString()}</updated>
|
|
106
|
+
${entries}
|
|
107
|
+
</feed>`;
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/* ------------------------------------------------------------------ sitemap / robots / llms */
|
|
111
|
+
|
|
112
|
+
interface LocaleSitemapData {
|
|
113
|
+
/** locale 全集([0] = base) */
|
|
114
|
+
locales: string[];
|
|
115
|
+
/** locale → 已发布内容(sitemap/llms 多语言段) */
|
|
116
|
+
byLocale: Map<string, ContentListItem[]>;
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/** locale 页面前缀:base 无前缀,variant '/en' */
|
|
120
|
+
function localePrefixOf(locale: string, locales: string[]): string {
|
|
121
|
+
return locale !== (locales[0] ?? '') ? `/${locale}` : '';
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/**
|
|
125
|
+
* xhtml:link alternates(含 x-default;单语言返回空串不输出)。
|
|
126
|
+
* 只输出实际存在的语言版本:缺翻译的 locale 不产 href="" 空壳(Google hreflang
|
|
127
|
+
* 集群必须是完整双向集合,空 href 无效);base 版本缺失时连 x-default 一起省略。
|
|
128
|
+
*/
|
|
129
|
+
function xhtmlAlternates(hrefByLocale: { locale: string; href: string }[], locales: string[]): string {
|
|
130
|
+
if (locales.length <= 1) return '';
|
|
131
|
+
const existing = hrefByLocale.filter((h) => h.href !== '');
|
|
132
|
+
if (existing.length === 0) return '';
|
|
133
|
+
const base = locales[0] ?? '';
|
|
134
|
+
const baseHref = existing.find((h) => h.locale === base)?.href ?? '';
|
|
135
|
+
const lines = existing.map(
|
|
136
|
+
(h) => `<xhtml:link rel="alternate" hreflang="${h.locale}" href="${xmlEscape(h.href)}"/>`,
|
|
137
|
+
);
|
|
138
|
+
if (baseHref !== '') {
|
|
139
|
+
lines.unshift(`<xhtml:link rel="alternate" hreflang="x-default" href="${xmlEscape(baseHref)}"/>`);
|
|
140
|
+
}
|
|
141
|
+
return lines.join('');
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
function sitemapXml(ctx: FeedContext, listPages: SeoDeclaration['listPage'][], multi?: LocaleSitemapData): string {
|
|
145
|
+
const locales = multi?.locales ?? [ctx.locale ?? 'zh-CN'];
|
|
146
|
+
const i18n = locales.length > 1;
|
|
147
|
+
|
|
148
|
+
const urls: string[] = [];
|
|
149
|
+
|
|
150
|
+
// 栏目页:全 locale 都有(虚拟页面),每条带全 locale alternates;
|
|
151
|
+
// 首页 variant 地址无尾斜杠('/en'),base 保持 '/' 惯例
|
|
152
|
+
for (const p of listPages) {
|
|
153
|
+
const path = p.path === '/' ? '/' : p.path;
|
|
154
|
+
const hrefs = locales.map((l) => {
|
|
155
|
+
const prefix = localePrefixOf(l, locales);
|
|
156
|
+
const suffix = path === '/' ? (prefix === '' ? '/' : '') : path;
|
|
157
|
+
return { locale: l, href: `${ctx.origin}${prefix}${suffix}` };
|
|
158
|
+
});
|
|
159
|
+
const alts = i18n ? xhtmlAlternates(hrefs, locales) : '';
|
|
160
|
+
for (const h of hrefs) {
|
|
161
|
+
urls.push(
|
|
162
|
+
`<url><loc>${h.href}</loc><changefreq>${p.changefreq}</changefreq><priority>${p.priority.toFixed(1)}</priority>${alts}</url>`,
|
|
163
|
+
);
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
// 内容页:union of locales;alternates 只列实际存在的语言兄弟页
|
|
168
|
+
if (multi) {
|
|
169
|
+
const key = (i: ContentListItem): string => `${i.section}/${i.slug}`;
|
|
170
|
+
const existing = new Map<string, Set<string>>();
|
|
171
|
+
for (const [locale, items] of multi.byLocale) {
|
|
172
|
+
for (const i of items) {
|
|
173
|
+
const set = existing.get(key(i)) ?? new Set<string>();
|
|
174
|
+
set.add(locale);
|
|
175
|
+
existing.set(key(i), set);
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
const seen = new Set<string>();
|
|
179
|
+
for (const [locale, items] of multi.byLocale) {
|
|
180
|
+
for (const i of items) {
|
|
181
|
+
const k = `${locale}:${key(i)}`;
|
|
182
|
+
if (seen.has(k)) continue;
|
|
183
|
+
seen.add(k);
|
|
184
|
+
const prefix = localePrefixOf(locale, locales);
|
|
185
|
+
const selfHref = `${ctx.origin}${prefix}/${i.section}/${i.slug}`;
|
|
186
|
+
const siblings = locales
|
|
187
|
+
.filter((l) => existing.get(key(i))?.has(l))
|
|
188
|
+
.map((l) => ({
|
|
189
|
+
locale: l,
|
|
190
|
+
href: `${ctx.origin}${localePrefixOf(l, locales)}/${i.section}/${i.slug}`,
|
|
191
|
+
}));
|
|
192
|
+
const alts = xhtmlAlternates(siblings, locales);
|
|
193
|
+
urls.push(
|
|
194
|
+
`<url><loc>${selfHref}</loc><lastmod>${new Date(i.updatedAt).toISOString()}</lastmod><priority>0.7</priority>${alts}</url>`,
|
|
195
|
+
);
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
} else {
|
|
199
|
+
for (const i of ctx.items) {
|
|
200
|
+
urls.push(
|
|
201
|
+
`<url><loc>${itemUrl(ctx.origin, i)}</loc><lastmod>${new Date(i.updatedAt).toISOString()}</lastmod><priority>0.7</priority></url>`,
|
|
202
|
+
);
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
const ns = i18n ? ' xmlns:xhtml="http://www.w3.org/1999/xhtml"' : '';
|
|
207
|
+
return `<?xml version="1.0" encoding="UTF-8"?>
|
|
208
|
+
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"${ns}>
|
|
209
|
+
${urls.join('\n')}
|
|
210
|
+
</urlset>`;
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
function robotsTxt(origin: string): string {
|
|
214
|
+
return `# 搜索引擎
|
|
215
|
+
User-agent: *
|
|
216
|
+
Allow: /
|
|
217
|
+
Disallow: /api/
|
|
218
|
+
Disallow: /healthz
|
|
219
|
+
|
|
220
|
+
Sitemap: ${origin}/sitemap.xml
|
|
221
|
+
`;
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
function llmsTxt(ctx: FeedContext, listPages: SeoDeclaration['listPage'][], multi?: LocaleSitemapData): string {
|
|
225
|
+
const locales = multi?.locales ?? ['zh-CN'];
|
|
226
|
+
const i18n = locales.length > 1;
|
|
227
|
+
|
|
228
|
+
const sectionBlock = (locale: string, items: ContentListItem[]): string[] => {
|
|
229
|
+
const prefix = localePrefixOf(locale, locales);
|
|
230
|
+
const bySection = new Map<string, ContentListItem[]>();
|
|
231
|
+
for (const i of items) {
|
|
232
|
+
const list = bySection.get(i.section) ?? [];
|
|
233
|
+
list.push(i);
|
|
234
|
+
bySection.set(i.section, list);
|
|
235
|
+
}
|
|
236
|
+
const lines: string[] = [];
|
|
237
|
+
for (const [section, sectionItems] of bySection) {
|
|
238
|
+
lines.push(`## ${section}${i18n ? ` (${locale})` : ''}`, '');
|
|
239
|
+
for (const i of sectionItems) {
|
|
240
|
+
lines.push(`- [${i.title}](${ctx.origin}${prefix}/${section}/${i.slug}): ${i.description}`);
|
|
241
|
+
}
|
|
242
|
+
lines.push('');
|
|
243
|
+
}
|
|
244
|
+
return lines;
|
|
245
|
+
};
|
|
246
|
+
|
|
247
|
+
const lines: string[] = [
|
|
248
|
+
`> ${ctx.siteName}: ${ctx.tagline}`,
|
|
249
|
+
'',
|
|
250
|
+
ctx.origin === '' ? '' : `Site: ${ctx.origin}`,
|
|
251
|
+
'',
|
|
252
|
+
];
|
|
253
|
+
|
|
254
|
+
// Sections 清单:多语言时按 locale 分组输出(双语段)
|
|
255
|
+
if (i18n && multi) {
|
|
256
|
+
for (const locale of locales) {
|
|
257
|
+
lines.push(`## Sections (${locale})`, '');
|
|
258
|
+
for (const p of listPages) {
|
|
259
|
+
const prefix = localePrefixOf(locale, locales);
|
|
260
|
+
const suffix = p.path === '/' ? (prefix === '' ? '/' : '') : p.path;
|
|
261
|
+
lines.push(`- ${p.title}: ${ctx.origin}${prefix}${suffix}`);
|
|
262
|
+
}
|
|
263
|
+
lines.push('');
|
|
264
|
+
}
|
|
265
|
+
for (const locale of locales) {
|
|
266
|
+
lines.push(...sectionBlock(locale, multi.byLocale.get(locale) ?? []));
|
|
267
|
+
}
|
|
268
|
+
} else {
|
|
269
|
+
lines.push('## Sections', '', ...listPages.map((p) => `- ${p.title}: ${p.path}`), '');
|
|
270
|
+
lines.push(...sectionBlock(locales[0] ?? 'zh-CN', ctx.items));
|
|
271
|
+
}
|
|
272
|
+
return lines.filter((l) => l !== undefined).join('\n');
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
/* ------------------------------------------------------------------ 路由注册 */
|
|
276
|
+
|
|
277
|
+
const FEED_CACHE = 'public, max-age=300';
|
|
278
|
+
|
|
279
|
+
export function registerFeeds(app: Hono, config: EngineConfig, resolveVersion: ContentVersionResolver, seo: SeoDeclaration[] = []): void {
|
|
280
|
+
const db = config.platform.db;
|
|
281
|
+
const locale = config.site.locale || 'zh-CN';
|
|
282
|
+
// M3 i18n:locale 全集([0] = base);单语言 = 原 M1/M2 行为(无 alternates、单段 llms)
|
|
283
|
+
const locales = config.site.locales && config.site.locales.length > 0 ? config.site.locales : [locale];
|
|
284
|
+
const i18n = locales.length > 1;
|
|
285
|
+
// 栏目页条目:section seo 声明(path/标题/changefreq/priority);无声明退回内置默认
|
|
286
|
+
const listPages = seo.length ? seo.map((s) => s.listPage) : DEFAULT_LIST_PAGES;
|
|
287
|
+
|
|
288
|
+
const buildContext = async (c: { req: { url: string } }, limit?: number): Promise<FeedContext> => {
|
|
289
|
+
const origin = new URL(c.req.url).origin;
|
|
290
|
+
const items = await listPublishedAll(db, { locale, limit });
|
|
291
|
+
// Last-Modified = max(updated_at):必须只由内容决定(请求间稳定),
|
|
292
|
+
// 混入 Date.now() 会让 If-Modified-Since 永远打不中 304;空内容才退回当前时间
|
|
293
|
+
const lastUpdatedMs = items.reduce((max, i) => Math.max(max, i.updatedAt.getTime()), 0) || Date.now();
|
|
294
|
+
return {
|
|
295
|
+
origin,
|
|
296
|
+
siteName: config.site.name,
|
|
297
|
+
tagline: config.site.tagline ?? config.site.description ?? config.site.name,
|
|
298
|
+
items,
|
|
299
|
+
lastUpdatedMs,
|
|
300
|
+
locale,
|
|
301
|
+
};
|
|
302
|
+
};
|
|
303
|
+
|
|
304
|
+
/** sitemap/llms 用:全 locale 已发布内容(i18n 关闭时只取 base,行为不变) */
|
|
305
|
+
const buildLocaleItems = async (limit?: number): Promise<LocaleSitemapData> => {
|
|
306
|
+
const byLocale = new Map<string, ContentListItem[]>();
|
|
307
|
+
for (const l of locales) {
|
|
308
|
+
byLocale.set(l, await listPublishedAll(db, { locale: l, limit }));
|
|
309
|
+
}
|
|
310
|
+
return { locales, byLocale };
|
|
311
|
+
};
|
|
312
|
+
|
|
313
|
+
/**
|
|
314
|
+
* 条件请求:Etag(content_version) / Last-Modified(max updated_at) 命中回 304。
|
|
315
|
+
* 304 与 200 共用同一组缓存头。
|
|
316
|
+
*/
|
|
317
|
+
const withConditional = async (
|
|
318
|
+
c: Context,
|
|
319
|
+
body: string,
|
|
320
|
+
contentType: string,
|
|
321
|
+
contentVersion: string,
|
|
322
|
+
lastUpdatedMs: number,
|
|
323
|
+
): Promise<Response> => {
|
|
324
|
+
const etag = `"cv-${contentVersion}"`;
|
|
325
|
+
const lastModified = httpDate(lastUpdatedMs);
|
|
326
|
+
const headers: Record<string, string> = {
|
|
327
|
+
'content-type': contentType,
|
|
328
|
+
'cache-control': FEED_CACHE,
|
|
329
|
+
etag,
|
|
330
|
+
'last-modified': lastModified,
|
|
331
|
+
};
|
|
332
|
+
|
|
333
|
+
const req = c.req.raw;
|
|
334
|
+
const inm = req.headers.get('if-none-match');
|
|
335
|
+
if (inm && (inm === '*' || inm.split(',').some((t) => t.trim() === etag))) {
|
|
336
|
+
return new Response(null, { status: 304, headers });
|
|
337
|
+
}
|
|
338
|
+
const ims = req.headers.get('if-modified-since');
|
|
339
|
+
if (!inm && ims) {
|
|
340
|
+
const since = Date.parse(ims);
|
|
341
|
+
if (!Number.isNaN(since) && Math.floor(lastUpdatedMs / 1000) * 1000 <= since) {
|
|
342
|
+
return new Response(null, { status: 304, headers });
|
|
343
|
+
}
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
return new Response(body, { status: 200, headers });
|
|
347
|
+
};
|
|
348
|
+
|
|
349
|
+
const feed = (kind: 'rss' | 'atom') => async (c: Context): Promise<Response> => {
|
|
350
|
+
const [ctx, version] = await Promise.all([buildContext(c, 30), resolveVersion()]);
|
|
351
|
+
const selfPath = kind === 'rss' ? '/rss.xml' : '/atom.xml';
|
|
352
|
+
const alternatePath = kind === 'rss' ? '/atom.xml' : '/rss.xml';
|
|
353
|
+
const body =
|
|
354
|
+
kind === 'rss' ? rssXml(ctx, selfPath, alternatePath, locale) : atomXml(ctx, selfPath, alternatePath, locale);
|
|
355
|
+
const contentType = kind === 'rss' ? 'application/rss+xml; charset=utf-8' : 'application/atom+xml; charset=utf-8';
|
|
356
|
+
return withConditional(c, body, contentType, version, ctx.lastUpdatedMs);
|
|
357
|
+
};
|
|
358
|
+
|
|
359
|
+
app.get('/rss.xml', feed('rss'));
|
|
360
|
+
app.get('/atom.xml', feed('atom'));
|
|
361
|
+
|
|
362
|
+
app.get('/sitemap.xml', async (c) => {
|
|
363
|
+
const [ctx, version, multi] = await Promise.all([buildContext(c), resolveVersion(), i18n ? buildLocaleItems() : Promise.resolve(undefined)]);
|
|
364
|
+
return withConditional(c, sitemapXml(ctx, listPages, multi), 'application/xml; charset=utf-8', version, ctx.lastUpdatedMs);
|
|
365
|
+
});
|
|
366
|
+
|
|
367
|
+
app.get('/robots.txt', async (c) => {
|
|
368
|
+
const [ctx, version] = await Promise.all([buildContext(c, 1), resolveVersion()]);
|
|
369
|
+
return withConditional(c, robotsTxt(ctx.origin), 'text/plain; charset=utf-8', version, ctx.lastUpdatedMs);
|
|
370
|
+
});
|
|
371
|
+
|
|
372
|
+
app.get('/llms.txt', async (c) => {
|
|
373
|
+
const [ctx, version, multi] = await Promise.all([buildContext(c), resolveVersion(), i18n ? buildLocaleItems() : Promise.resolve(undefined)]);
|
|
374
|
+
return withConditional(c, llmsTxt(ctx, listPages, multi), 'text/plain; charset=utf-8', version, ctx.lastUpdatedMs);
|
|
375
|
+
});
|
|
376
|
+
}
|
package/src/guard.ts
ADDED
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
import type { Context, MiddlewareHandler } from 'hono';
|
|
2
|
+
import type { ContentfulStatusCode } from 'hono/utils/http-status';
|
|
3
|
+
import { ApiError } from './types';
|
|
4
|
+
import type { EngineConfig } from './types';
|
|
5
|
+
|
|
6
|
+
export { ApiError };
|
|
7
|
+
|
|
8
|
+
/* ------------------------------------------------------------ 安全头 */
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* CSP 收紧到「零第三方源」:零客户端框架起步,script 只允许自源 island
|
|
12
|
+
* (public/js/*.js)。JSON-LD 是 data block(不执行),不受 script-src 限制。
|
|
13
|
+
* 这条常量同时被 scripts/check-budget.mjs 断言(无第三方源)。
|
|
14
|
+
*
|
|
15
|
+
* Turnstile(M2 可选)启用时由 securityHeaders 运行时追加其脚本/iframe 源——
|
|
16
|
+
* 只扩展本常量的运行时拷贝,红线断言仍读这里的自源字面量。
|
|
17
|
+
*/
|
|
18
|
+
export const CSP =
|
|
19
|
+
"default-src 'self'; img-src 'self' data:; style-src 'self' 'unsafe-inline'; script-src 'self'; font-src 'self'; connect-src 'self'; frame-ancestors 'none'; base-uri 'self'; form-action 'self'; object-src 'none'";
|
|
20
|
+
|
|
21
|
+
/** securityHeaders 的可选扩展(M2 Turnstile:脚本 + widget iframe 源) */
|
|
22
|
+
export interface SecurityHeaderOptions {
|
|
23
|
+
/** 追加进 script-src 的源(如 Turnstile api.js 源) */
|
|
24
|
+
cspScriptSrcExtra?: string[];
|
|
25
|
+
/** 追加进 frame-src 的源(Turnstile widget 跑在 iframe 里) */
|
|
26
|
+
cspFrameSrcExtra?: string[];
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export const SECURITY_HEADERS: Record<string, string> = {
|
|
30
|
+
'x-content-type-options': 'nosniff',
|
|
31
|
+
'x-frame-options': 'DENY',
|
|
32
|
+
'referrer-policy': 'strict-origin-when-cross-origin',
|
|
33
|
+
'permissions-policy': 'camera=(), microphone=(), geolocation=(), interest-cohort=()',
|
|
34
|
+
'content-security-policy': CSP,
|
|
35
|
+
};
|
|
36
|
+
|
|
37
|
+
function buildCsp(options?: SecurityHeaderOptions): string {
|
|
38
|
+
const scriptExtra = options?.cspScriptSrcExtra ?? [];
|
|
39
|
+
const frameExtra = options?.cspFrameSrcExtra ?? [];
|
|
40
|
+
if (!scriptExtra.length && !frameExtra.length) return CSP;
|
|
41
|
+
let csp = CSP.replace(/script-src 'self'/, `script-src 'self' ${scriptExtra.join(' ')}`);
|
|
42
|
+
if (frameExtra.length) {
|
|
43
|
+
csp += `; frame-src ${frameExtra.join(' ')}`;
|
|
44
|
+
}
|
|
45
|
+
return csp;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/** 已有同名头时不覆盖(幂等;缓存命中的存储体已带安全头) */
|
|
49
|
+
function withSecurityHeaders(res: Response, options?: SecurityHeaderOptions): Response {
|
|
50
|
+
const headers = new Headers(res.headers);
|
|
51
|
+
for (const [k, v] of Object.entries(SECURITY_HEADERS)) {
|
|
52
|
+
if (!headers.has(k)) headers.set(k, v);
|
|
53
|
+
}
|
|
54
|
+
if (options && (options.cspScriptSrcExtra?.length || options.cspFrameSrcExtra?.length)) {
|
|
55
|
+
headers.set('content-security-policy', buildCsp(options));
|
|
56
|
+
}
|
|
57
|
+
if (!headers.has('strict-transport-security')) {
|
|
58
|
+
headers.set('strict-transport-security', 'max-age=31536000; includeSubDomains');
|
|
59
|
+
}
|
|
60
|
+
return new Response(res.body, { status: res.status, statusText: res.statusText, headers });
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/** 出口包装:给所有响应补安全头 + HSTS */
|
|
64
|
+
export function securityHeaders(options?: SecurityHeaderOptions): MiddlewareHandler {
|
|
65
|
+
return async (c, next) => {
|
|
66
|
+
await next();
|
|
67
|
+
c.res = withSecurityHeaders(c.res, options);
|
|
68
|
+
};
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/* ------------------------------------------------------------ 错误 envelope */
|
|
72
|
+
|
|
73
|
+
function patchHeaders(res: Response, patch: Record<string, string>): Response {
|
|
74
|
+
const headers = new Headers(res.headers);
|
|
75
|
+
for (const [k, v] of Object.entries(patch)) headers.set(k, v);
|
|
76
|
+
return new Response(res.body, { status: res.status, statusText: res.statusText, headers });
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/** 引擎内置兜底错误页(站点层未注入 renderError 时使用) */
|
|
80
|
+
function builtinErrorPage(c: Context, status: number, message?: string): Response {
|
|
81
|
+
const titles: Record<number, string> = {
|
|
82
|
+
404: '页面不存在',
|
|
83
|
+
429: '请求过于频繁',
|
|
84
|
+
500: '服务暂时不可用',
|
|
85
|
+
};
|
|
86
|
+
const title = titles[status] ?? `错误 ${status}`;
|
|
87
|
+
const body = message ?? '请稍后重试,或返回首页继续浏览。';
|
|
88
|
+
const html =
|
|
89
|
+
'<!doctype html><html lang="zh-CN"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">' +
|
|
90
|
+
`<title>${status} - Sitkit</title><link rel="stylesheet" href="/css/tokens.css"><link rel="stylesheet" href="/css/base.css"></head>` +
|
|
91
|
+
'<body><main class="error-page">' +
|
|
92
|
+
`<p class="error-status">${status}</p><h1 class="error-title">${title}</h1><p class="error-message">${body}</p>` +
|
|
93
|
+
'<p><a class="button" href="/">返回首页</a></p>' +
|
|
94
|
+
'</main></body></html>';
|
|
95
|
+
return new Response(html, {
|
|
96
|
+
status: status as ContentfulStatusCode,
|
|
97
|
+
headers: { 'content-type': 'text/html; charset=utf-8' },
|
|
98
|
+
});
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/** onError:/api/* 返回 JSON envelope;页面路由渲染 errorPage */
|
|
102
|
+
export function errorEnvelope(config: EngineConfig) {
|
|
103
|
+
return async (err: Error, c: Context): Promise<Response> => {
|
|
104
|
+
const status = err instanceof ApiError ? err.status : 500;
|
|
105
|
+
const code = err instanceof ApiError ? err.code : 'server_error';
|
|
106
|
+
console.error('unhandled_error', c.req.method, c.req.path, err);
|
|
107
|
+
if (c.req.path.startsWith('/api/')) {
|
|
108
|
+
return c.json({ ok: false, error: code }, status as ContentfulStatusCode, { 'cache-control': 'no-store' });
|
|
109
|
+
}
|
|
110
|
+
if (config.renderError) {
|
|
111
|
+
return await config.renderError(c, status, err instanceof ApiError ? err.message : undefined);
|
|
112
|
+
}
|
|
113
|
+
return builtinErrorPage(c, status);
|
|
114
|
+
};
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/** 404:/api/* 返回 JSON envelope;页面渲染 errorPage;一律 no-store */
|
|
118
|
+
export function notFoundHandler(config: EngineConfig) {
|
|
119
|
+
return async (c: Context): Promise<Response> => {
|
|
120
|
+
if (c.req.path.startsWith('/api/')) {
|
|
121
|
+
return c.json({ ok: false, error: 'not_found' }, 404, { 'cache-control': 'no-store' });
|
|
122
|
+
}
|
|
123
|
+
const page = config.renderError ? await config.renderError(c, 404) : builtinErrorPage(c, 404);
|
|
124
|
+
return patchHeaders(page, { 'cache-control': 'no-store' });
|
|
125
|
+
};
|
|
126
|
+
}
|
package/src/html.ts
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
/** HTML 转义(md 渲染器与 seo 构造器共用) */
|
|
2
|
+
const ESCAPE_MAP: Record<string, string> = {
|
|
3
|
+
'&': '&',
|
|
4
|
+
'<': '<',
|
|
5
|
+
'>': '>',
|
|
6
|
+
'"': '"',
|
|
7
|
+
"'": ''',
|
|
8
|
+
};
|
|
9
|
+
|
|
10
|
+
export function escapeHtml(input: string): string {
|
|
11
|
+
return String(input ?? '').replace(/[&<>"']/g, (ch) => ESCAPE_MAP[ch] ?? ch);
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* JSON-LD 内嵌安全化:把 `<` 替换为 unicode 转义,
|
|
16
|
+
* 防止数据里出现 `</script>` 提前闭合标签。
|
|
17
|
+
*/
|
|
18
|
+
export function safeJsonForScript(obj: unknown): string {
|
|
19
|
+
return JSON.stringify(obj).replace(/</g, '\\u003c');
|
|
20
|
+
}
|