Skip to content

プリザンターをCMSにした静的サイト生成 ​

第1版作成 最終更新 (日本時間)
確認バージョン1.5.9.1

プリザンターで記事を編集・承認し、公開専用のテーブルをAPIで取得して、AstroまたはVitePressで静的サイトを生成します。閲覧者のブラウザーはプリザンターへ接続せず、APIキーも受け取りません。外部向けのお知らせや製品情報など、更新と閲覧を分けられるコンテンツに向く構成です。

配布例はNode.js 24、Astro 7.4.8、VitePress 1.6.4を使います。Pleasanter APIの型は固定した公式ソースで照合し、再現用の取得・生成は合成APIで行います。実CMSでの承認画面の自動化や本番導入を済ませた事例ではありません。

編集する場所と配信する場所を分ける ​

ヘッドレスCMSは、編集・承認・データ管理と、閲覧画面を別々にする構成です。ここではプリザンターを編集側、静的サイトを配信側に使います。

図を読み込み中…

原稿テーブルには未承認文書や社内メモが混ざります。公開用テーブルは別に作り、承認したタイトル・本文・公開期間・添付だけを転記します。公開用テーブルと承認項目の更新は承認担当に限定し、一般の執筆者の直接更新を許可しません。承認担当と、読取り専用のビルド担当を分けます。

認証が必要なページ、保護ダウンロード、閲覧履歴の記録、問い合わせ送信は、認証と権限判定を持つ別の動的サービスへ残します。静的ファイルとして配信した内容を、プリザンター側の権限で後から保護することはできません。

API専用ユーザーの読取り範囲を絞る ​

APIキーはユーザーの権限で動作します。「読取り専用キー」という名前を付けるだけで操作を限定できるわけではありません。APIを利用できる専用ユーザーを用意し、公開用テーブルと必要な項目だけに読取りを許可します。原稿テーブル、コメント、個人情報を含む項目へのアクセスや、作成・更新・削除・権限管理は許可しません。

原稿を読む権限を持つキーで全件を取得し、ビルドの最後だけで隠す構成にしません。APIのView.ColumnFilterHashも、読取り権限の代わりにはなりません。返却する列はユーザー・列のアクセス制御で絞り、さらに生成側でも公開するプロパティだけを新しいオブジェクトへ詰め直します。

キーはビルドサーバーのsecretへ保存し、取得ステップだけへ渡します。フレームワークの公開用環境変数、設定ファイル、ブラウザー用JavaScript、生成物、ログへ入れません。本例はNode.jsで動くため標準のfetchを使い、C#クライアントを呼ぶためだけの.NETプロセスは追加しません。

公開用テーブルの項目を決める ​

サンプルは記録テーブルを対象とし、ResultIdで識別します。期限付きテーブルのIssueIdとは取り違えないでください。編集画面の項目名は任意ですが、API側の物理名を次のように設定します。

物理名内容入力・選択肢
Title公開タイトル必須、120文字以内
Body本文プレーンテキスト、20,000文字以内
ClassAURLのslug小文字英数字と単語間のハイフン、先頭は英字
ClassB公開状態draft、review、published、withdrawn、private
ClassC公開範囲public、private
ClassD公開開始UTC例2026-11-10T00:00:00Z
ClassE公開終了UTC同じ形式、期限なしは空文字
ClassF確定した公開版例release-example
CheckA公開承認チェックを入れたものだけ対象
AttachmentsA公開画像別途承認台帳に登録したPNGのみ

分類項目は単一値で使い、公開状態・公開範囲の選択肢を上記の保存値で登録します。slug、UTC日時、公開版は文字列として入力します。開始・終了に文字列を使うのは、日付項目のAPI値がユーザー設定でローカル時刻へ変換される挙動から区別するためです。日付入力欄を使う編集画面を別に作る場合は、承認時にUTCへ変換して公開用の値を確定します。

状態・条件生成側の扱い
下書き・承認待ち取得権限を与えない。防御処理でも除外
承認済み・公開範囲public・期間内現在の確定版と一致するものだけ公開
予約・開始前除外
終了時刻と同時または終了後除外
公開取消・非公開除外
削除済み通常テーブルの取得対象に含めない
必須項目・型・slug・添付承認が不正生成を失敗させ、配信へ進めない

公開版を確定したら、取得中は内容を書き換えません。APIのページ送りはDBの一括トランザクションではないためです。本例は公開DTOを2回読み比べますが、それだけで任意の同時更新に対する完全な一貫性を保証するものではありません。

サンプルを合成APIで動かす ​

サンプル一式をダウンロードして展開し、pleasanter-public-static-sampleへ移動します。コードはMITです。依存版とpackage-lock.jsonも一緒に保持しています。

sh
npm ci --ignore-scripts
npm test
npm run fixture
npm run prepare
npm run build:astro
npm run build:vitepress
npm run check:html

fixtureはローカルの合成APIを一時起動し、ダミーキーでページ送りと画像取得を行って停止します。公開判定時刻を2026-11-10T00:00:00Zへ固定し、下書き・予約・期限切れ・非公開・未承認・削除を含む素材から、公開可能な2件だけをスナップショットへ書きます。実APIのエクスポートは実行時刻で判定します。非公開行を混ぜるのは生成側の防御試験のためであり、実環境のキーへ原稿を読む権限を与える手順ではありません。

出力はastro/distとvitepress/.vitepress/distです。ブラウザーで表示するときも、これらの出力先だけを配信し、プロジェクト全体や.cmsを公開しません。check:htmlは、本文のHTMLとVue風の構文が実行コードへ変わらず、非公開のダミー値が混入しないことを生成HTMLで確認します。

合成APIと試験コードの全文
js
// SPDX-License-Identifier: MIT
import http from 'node:http';
import crypto from 'node:crypto';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import { exportPublic, options } from './export.mjs';
export const png = Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+jOz0AAAAASUVORK5CYII=', 'base64');
export const imageId = '11111111111111111111111111111111';
export const manifest = { [imageId]: { publish: true, sha256: crypto.createHash('sha256').update(png).digest('hex'), alt: '公開を承認した合成画像' } };
export function record(id, change = {}) {
  return {
    ResultId: id, SiteId: 100, Title: `公開記事 ${id}`, Body: '本文を文字列として配信します。',
    ClassHash: { ClassA: `post-${id}`, ClassB: 'published', ClassC: 'public', ClassD: '2020-01-01T00:00:00Z', ClassE: '', ClassF: 'release-example' },
    CheckHash: { CheckA: true }, AttachmentsHash: { AttachmentsA: [] },
    DescriptionHash: { DescriptionZ: 'INTERNAL_PRIVATE_NOTE' }, ...change
  };
}
export function fixtureRows() {
  const first = record(1, { Title: '公開記事と文字列', Body: '<script>globalThis.CMS_EXECUTED=1</script>\n{{ 7 * 7 }}\n<img src=x onerror=alert(1)>' });
  const image = record(2, { AttachmentsHash: { AttachmentsA: [{ Guid: imageId, Name: '../../not-a-public-name.png', Deleted: false }] } });
  return [first, image,
    record(3, { ClassHash: { ...record(3).ClassHash, ClassB: 'draft' }, Body: 'PRIVATE_DRAFT_MARKER' }),
    record(4, { ClassHash: { ...record(4).ClassHash, ClassB: 'review' } }),
    record(5, { ClassHash: { ...record(5).ClassHash, ClassD: '2030-01-01T00:00:00Z' } }),
    record(6, { ClassHash: { ...record(6).ClassHash, ClassE: '2021-01-01T00:00:00Z' } }),
    record(7, { ClassHash: { ...record(7).ClassHash, ClassB: 'withdrawn' } }),
    record(8, { ClassHash: { ...record(8).ClassHash, ClassC: 'private' }, Body: 'PRIVATE_VISIBILITY_MARKER' }),
    record(9, { CheckHash: { CheckA: false } }), record(10, { _deleted: true })];
}
export async function startFixture({ rows = fixtureRows(), alterPage, mediaType = 'image/png', mediaBytes = png } = {}) {
  const state = { rows, requests: [], pageCalls: 0, binaryCalls: 0 };
  const server = http.createServer(async (req, res) => {
    const chunks = []; for await (const chunk of req) chunks.push(chunk);
    const request = JSON.parse(Buffer.concat(chunks).toString());
    if (request.ApiKey !== 'fixture-only-key' || request.ApiVersion !== 1.1) { res.writeHead(403).end(); return; }
    if (req.url === '/pleasanter/api/items/100/get') {
      state.requests.push({ Offset: request.Offset, PageSize: request.PageSize, TableType: request.TableType, View: request.View });
      state.pageCalls++;
      const visible = state.rows.filter(row => !row._deleted).map(({ _deleted, ...row }) => row);
      const response = { Offset: request.Offset, PageSize: 2, TotalCount: visible.length, Data: visible.slice(request.Offset, request.Offset + 2) };
      res.writeHead(200, { 'Content-Type': 'application/json' }).end(JSON.stringify({ StatusCode: 200, Response: alterPage ? alterPage(response, state) : response }));
    } else if (req.url === `/pleasanter/api/binaries/${imageId}/getstream`) {
      state.binaryCalls++;
      res.writeHead(200, { 'Content-Type': mediaType }).end(mediaBytes);
    } else res.writeHead(404).end();
  });
  await new Promise(resolve => server.listen(0, '127.0.0.1', resolve));
  const env = { CMS_BASE_URL: `http://127.0.0.1:${server.address().port}/pleasanter/`, CMS_SITE_ID: '100', CMS_API_KEY: 'fixture-only-key', CMS_RELEASE: 'release-example', CMS_LOCAL_FIXTURE: '1' };
  return { state, env, config: options(env), close: () => new Promise(resolve => { server.close(resolve); server.closeAllConnections(); }) };
}
if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
  const api = await startFixture();
  try { const snapshot = await exportPublic({ config: api.config, manifest, now: Date.parse('2026-11-10T00:00:00Z') }); console.log(`Fixture public posts: ${snapshot.posts.length}`); }
  finally { await api.close(); }
}
js
// SPDX-License-Identifier: MIT
import { test } from 'node:test';
import assert from 'node:assert/strict';
import fs from 'node:fs/promises';
import os from 'node:os';
import path from 'node:path';
import { exportPublic, options, publicPosts } from './export.mjs';
import { readSnapshot } from './snapshot.mjs';
import { startFixture, record, fixtureRows, manifest } from './fixture.mjs';
const now = Date.parse('2026-11-10T00:00:00Z');
async function context(t, fixtureOptions) {
  const root = await fs.mkdtemp(path.join(os.tmpdir(), 'cms-static-test-'));
  const api = await startFixture(fixtureOptions);
  t.after(async () => { await api.close(); await fs.rm(root, { recursive: true, force: true }); });
  return { root, api, run: opts => exportPublic({ root, config: api.config, manifest, now, ...opts }) };
}
test('pagination, publication boundary and public DTO', async t => {
  const { root, api, run } = await context(t);
  const output = await run();
  assert.deepEqual(output.posts.map(p => p.slug), ['post-1', 'post-2']);
  assert.equal(api.state.requests[1].Offset, 2); // Requested100, returned2.
  assert.equal(api.state.requests[0].TableType, 0);
  assert.equal(api.state.requests[0].View.ColumnSorterHash.ResultId, 'asc');
  const json = JSON.stringify(output);
  for (const forbidden of ['PRIVATE_DRAFT_MARKER', 'PRIVATE_VISIBILITY_MARKER', 'INTERNAL_PRIVATE_NOTE', 'fixture-only-key', 'ResultId', 'SiteId', '../../', '11111111111111111111111111111111']) assert.ok(!json.includes(forbidden), forbidden);
  assert.ok(output.posts[1].images[0].src.startsWith('/media/'));
  assert.deepEqual((await readSnapshot(root)).snapshot, output);
});
test('slug traversal, reserved and duplicate slugs fail', async t => {
  const { api } = await context(t);
  for (const slug of ['../escape', 'a/b', '%2e%2e', 'index', 'Upper', 'a\\b']) {
    const row = record(1); row.ClassHash.ClassA = slug;
    assert.throws(() => publicPosts([row], api.config, manifest, now));
  }
  const duplicate = record(2); duplicate.ClassHash.ClassA = record(1).ClassHash.ClassA;
  assert.throws(() => publicPosts([record(1), duplicate], api.config, manifest, now));
});
test('unsafe integers, changed count and repeated pages fail closed', async t => {
  for (const modify of [
    page => ({ ...page, TotalCount: 1001 }),
    (page, state) => ({ ...page, TotalCount: page.TotalCount + (state.pageCalls > 1 ? 1 : 0) }),
    page => ({ ...page, Data: [record(1), record(1)] }),
    page => ({ ...page, Data: [record(Number.MAX_SAFE_INTEGER + 1)] })
  ]) {
    const { run } = await context(t, { alterPage: modify });
    await assert.rejects(run());
  }
});
test('publication instants are explicit UTC and end is exclusive', async t => {
  const { api } = await context(t);
  const row = record(1);
  row.ClassHash.ClassD = '2026-02-30T00:00:00Z';
  assert.throws(() => publicPosts([row], api.config, manifest, now));
  row.ClassHash.ClassD = '2026-11-10T00:00:00';
  assert.throws(() => publicPosts([row], api.config, manifest, now));
  row.ClassHash.ClassD = '2020-01-01T00:00:00Z'; row.ClassHash.ClassE = '2026-11-10T00:00:00Z';
  assert.equal(publicPosts([row], api.config, manifest, now).length, 0);
});
test('attachment approval/hash/MIME failure retains last snapshot', async t => {
  const { root, api, run } = await context(t);
  await run(); const before = await fs.readFile(path.join(root, '.cms/CURRENT'), 'utf8');
  await assert.rejects(run({ manifest: {} }));
  const badManifest = structuredClone(manifest); Object.values(badManifest)[0].sha256 = '0'.repeat(64);
  await assert.rejects(run({ manifest: badManifest }));
  assert.equal(await fs.readFile(path.join(root, '.cms/CURRENT'), 'utf8'), before);
  const wrongType = await context(t, { mediaType: 'image/svg+xml' });
  await assert.rejects(wrongType.run());
  assert.ok(api.state.binaryCalls > 0);
});
test('withdrawal/deletion replaces the complete collection', async t => {
  const { api, run } = await context(t);
  assert.equal((await run()).posts.length, 2);
  api.state.rows[0].ClassHash.ClassB = 'withdrawn'; api.state.rows[1]._deleted = true;
  assert.equal((await run()).posts.length, 0);
});
test('missing flags, changed collection and concurrent export fail', async t => {
  const { root, api, run } = await context(t);
  const bad = record(1); bad.CheckHash = {};
  assert.throws(() => publicPosts([bad], api.config, manifest, now));
  await fs.mkdir(path.join(root, '.cms'), { recursive: true });
  await fs.writeFile(path.join(root, '.cms/export.lock'), '');
  await assert.rejects(run());
  await fs.unlink(path.join(root, '.cms/export.lock'));
  const changing = await context(t, { alterPage: (page, state) => {
    if (state.pageCalls > 5 && page.Offset === 0) page.Data[0].Body = 'Changed after first scan';
    return page;
  } });
  await assert.rejects(changing.run());
});
test('live URL guards and preview separation', async t => {
  const { api } = await context(t);
  for (const base of ['http://cms.example.invalid/', 'https://user:pass@cms.example.invalid/', 'https://cms.example.invalid/?key=x', 'file:///tmp/']) assert.throws(() => options({ ...api.env, CMS_BASE_URL: base }));
  assert.throws(() => options({ ...api.env, CMS_PREVIEW: '1' }));
  assert.throws(() => options({ ...api.env, CMS_SITE_ID: '9007199254740993' }));
});
js
// SPDX-License-Identifier: MIT
import fs from 'node:fs/promises';
import assert from 'node:assert/strict';
for (const file of ['astro/dist/posts/post-1/index.html', 'vitepress/.vitepress/dist/posts/post-1.html']) {
  const html = await fs.readFile(new URL(file, import.meta.url), 'utf8');
  assert.ok(html.includes('&lt;script&gt;globalThis.CMS_EXECUTED=1&lt;/script&gt;'), file);
  assert.ok(html.includes('{{ 7 * 7 }}'), 'Vue syntax stays text');
  assert.ok(!html.includes('<script>globalThis.CMS_EXECUTED'), file);
  for (const denied of ['PRIVATE_DRAFT_MARKER', 'PRIVATE_VISIBILITY_MARKER', 'INTERNAL_PRIVATE_NOTE', 'fixture-only-key']) assert.ok(!html.includes(denied), denied);
}
console.log('Both framework outputs escape the synthetic payload and omit private fields.');

ページ送りと公開DTOを確定する ​

実APIへ切り替えるときは、CMS_BASE_URL、CMS_SITE_ID、CMS_RELEASEと、secretのCMS_API_KEYを設定してnpm run exportします。CMS_BASE_URLは末尾にスラッシュを付け、サブディレクトリも含めます。たとえばhttps://cms.example.invalid/pleasanter/なら、そこを基準にapi/items/100/getを組み立てます。公開用の実サイトIDへ置き換えてください。

リクエストにはApiVersion: 1.1を必ず指定します。Api.jsonのCompatibility_1_3_12はfalseを前提とし、View.ApiDataTypeは標準の0を使います。TableType: 0は通常テーブルで、履歴や削除済みを混ぜません。

APIのPageSizeは要求値より小さくなることがあるため、Offsetは**返されたData.length**だけ進めます。返却されたTotalCountの変化、途中の空ページ、IDの重複、数値の精度不足、過大な件数は中止条件です。ResultIdで昇順に並べて取得します。サンプルは最大1,000件、1応答4MiB、1要求15秒で打ち切ります。

公開状態・承認・公開範囲・公開期間・確定版を検査した後、slug、title、body、公開期間、公開画像のURLと代替テキストだけを作ります。raw応答、作成者ID、コメント、APIキー、添付の元ファイル名は保存しません。slugはASCIIの小文字に限定し、重複、パス区切り、相対パス、予約名を拒否します。

取得と確定処理の全文
js
// SPDX-License-Identifier: MIT
import fs from 'node:fs/promises';
import path from 'node:path';
import crypto from 'node:crypto';
import { fileURLToPath } from 'node:url';

const home = path.dirname(fileURLToPath(import.meta.url));
const fail = message => { throw new Error(message); };
const digest = bytes => crypto.createHash('sha256').update(bytes).digest('hex');
const guid = value => typeof value === 'string' && /^[a-f0-9]{32}$/i.test(value);
const str = (value, max) => typeof value === 'string' && value.length <= max && !/[\u0000-\u0008\u000b\u000c\u000e-\u001f]/u.test(value);

export function options(env = process.env) {
  const base = new URL(env.CMS_BASE_URL || 'https://cms.example.invalid/pleasanter/');
  const fixture = env.CMS_LOCAL_FIXTURE === '1' && base.hostname === '127.0.0.1' && base.protocol === 'http:';
  if ((!fixture && base.protocol !== 'https:') || base.username || base.password || base.search || base.hash) fail('Invalid CMS base URL');
  if (!base.pathname.endsWith('/')) fail('CMS base URL must end with /');
  const site = Number(env.CMS_SITE_ID);
  if (!Number.isSafeInteger(site) || site < 1 || !env.CMS_API_KEY) fail('Missing CMS settings');
  if (!/^[a-z0-9-]{1,64}$/.test(env.CMS_RELEASE || '')) fail('Invalid release');
  if (env.CMS_PREVIEW) fail('This exporter only supports public releases');
  return { base, site, key: env.CMS_API_KEY, release: env.CMS_RELEASE };
}

async function readBounded(response, max) {
  const length = Number(response.headers.get('content-length'));
  if (length > max) fail('Response too large');
  const chunks = []; let size = 0;
  for await (const chunk of response.body) {
    size += chunk.length;
    if (size > max) fail('Response too large');
    chunks.push(chunk);
  }
  return Buffer.concat(chunks);
}

async function post(config, relative, data, binary = false) {
  const response = await fetch(new URL(relative, config.base), {
    method: 'POST', redirect: 'error', signal: AbortSignal.timeout(15000),
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ ApiVersion: 1.1, ApiKey: config.key, ...data })
  });
  if (response.status !== 200) fail('CMS request failed');
  const bytes = await readBounded(response, binary ? 2 * 1024 * 1024 : 4 * 1024 * 1024);
  if (binary) {
    if (response.headers.get('content-type')?.split(';')[0] !== 'image/png' || !bytes.subarray(0, 8).equals(Buffer.from('89504e470d0a1a0a', 'hex'))) fail('Only approved PNG is supported');
    return bytes;
  }
  if (!response.headers.get('content-type')?.includes('application/json')) fail('Expected JSON');
  const result = JSON.parse(bytes);
  if (result.StatusCode !== 200) fail('CMS API failed');
  return result.Response;
}

export async function readRows(config) {
  const all = [], seen = new Set(); let total;
  for (let offset = 0; ; ) {
    const page = await post(config, `api/items/${config.site}/get`, {
      Offset: offset, PageSize: 100, TableType: 0,
      View: { ApiDataType: 0, ColumnFilterHash: { ClassF: JSON.stringify([config.release]) }, ColumnSorterHash: { ResultId: 'asc' } }
    });
    if (!page || page.Offset !== offset || !Number.isSafeInteger(page.TotalCount) || page.TotalCount < 0 || page.TotalCount > 1000 || !Number.isSafeInteger(page.PageSize) || page.PageSize < 1 || !Array.isArray(page.Data) || page.Data.length > page.PageSize) fail('Invalid page contract');
    total ??= page.TotalCount;
    if (total !== page.TotalCount || offset + page.Data.length > total || (!page.Data.length && offset < total)) fail('Collection changed during pagination');
    for (const row of page.Data) {
      if (!row || !Number.isSafeInteger(row.ResultId) || row.ResultId < 1 || row.SiteId !== config.site || seen.has(row.ResultId)) fail('Invalid or duplicate record');
      seen.add(row.ResultId); all.push(row);
    }
    offset += page.Data.length; // The server may return fewer than requested.
    if (offset === total) return all;
  }
}

function instant(value) {
  if (typeof value !== 'string' || !/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z$/.test(value)) fail('UTC publication instant required');
  const parsed = Date.parse(value);
  if (!Number.isFinite(parsed) || new Date(parsed).toISOString().replace('.000Z', 'Z') !== value) fail('Invalid publication instant');
  return parsed;
}

export function publicPosts(rows, config, manifest, now) {
  const slugs = new Set();
  return rows.flatMap(row => {
    const c = row.ClassHash;
    if (!c || !['draft', 'review', 'published', 'withdrawn', 'private'].includes(c.ClassB) || !['public', 'private'].includes(c.ClassC) || typeof row.CheckHash?.CheckA !== 'boolean') fail('Missing publication fields');
    if (c.ClassB !== 'published' || c.ClassC !== 'public' || !row.CheckHash.CheckA || c.ClassF !== config.release) return [];
    const start = instant(c.ClassD), end = c.ClassE ? instant(c.ClassE) : null;
    if (end !== null && end <= start) fail('Invalid publication interval');
    if (start > now || (end !== null && now >= end)) return [];
    if (!str(row.Title, 120) || !row.Title.trim() || !str(row.Body, 20000)) fail('Invalid public text');
    const slug = c.ClassA;
    if (typeof slug !== 'string' || slug.length > 64 || !/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/.test(slug) || ['index', 'assets', 'media'].includes(slug) || slugs.has(slug)) fail('Invalid or duplicate slug');
    slugs.add(slug);
    const attachments = row.AttachmentsHash?.AttachmentsA ?? [];
    if (!Array.isArray(attachments) || attachments.length > 8) fail('Invalid attachments');
    const images = attachments.filter(a => a.Deleted !== true).map(a => {
      if (!guid(a.Guid)) fail('Invalid attachment GUID');
      const approved = manifest[a.Guid.toLowerCase()];
      if (approved?.publish !== true || !/^[a-f0-9]{64}$/.test(approved.sha256 || '') || !str(approved.alt, 120)) fail('Attachment lacks public approval');
      return { guid: a.Guid.toLowerCase(), sha256: approved.sha256, alt: approved.alt };
    });
    // Construct an allowlisted DTO. No spread of raw API rows.
    return [{ slug, title: row.Title, body: row.Body, startsAt: c.ClassD, endsAt: c.ClassE || null, images }];
  }).sort((a, b) => a.slug.localeCompare(b.slug, 'en'));
}

export async function exportPublic({ config = options(), root = home, manifest, now = Date.now() } = {}) {
  manifest ??= JSON.parse(await fs.readFile(path.join(root, 'public-media.json'), 'utf8'));
  const target = path.join(root, '.cms');
  await fs.mkdir(path.join(target, 'releases'), { recursive: true, mode: 0o700 });
  const lockPath = path.join(target, 'export.lock');
  const lock = await fs.open(lockPath, 'wx', 0o600); // No concurrent writers.
  let stage, committed = false;
  try {
    const first = publicPosts(await readRows(config), config, manifest, now);
    const second = publicPosts(await readRows(config), config, manifest, now);
    if (JSON.stringify(first) !== JSON.stringify(second)) fail('Public collection changed between scans');
    const assets = new Map();
    for (const post of first) for (const image of post.images) {
      const bytes = await postBinary(image);
      assets.set(image.sha256 + '.png', bytes);
    }
    async function postBinary(image) {
      const bytes = await post(config, `api/binaries/${image.guid}/getstream`, {}, true);
      if (digest(bytes) !== image.sha256) fail('Public attachment hash changed');
      return bytes;
    }
    stage = await fs.mkdtemp(path.join(target, 'releases', 'release-'));
    await fs.mkdir(path.join(stage, 'media'));
    for (const [file, bytes] of assets) await fs.writeFile(path.join(stage, 'media', file), bytes, { mode: 0o600 });
    const snapshot = { schemaVersion: 1, posts: first.map(post => ({
      slug: post.slug, title: post.title, body: post.body, startsAt: post.startsAt, endsAt: post.endsAt,
      images: post.images.map(image => ({ src: `/media/${image.sha256}.png`, alt: image.alt }))
    })) };
    await fs.writeFile(path.join(stage, 'snapshot.json'), JSON.stringify(snapshot) + '\n', { mode: 0o600 });
    const pointer = path.join(target, `CURRENT.${process.pid}.tmp`);
    await fs.writeFile(pointer, path.basename(stage) + '\n', { mode: 0o600 });
    await fs.rename(pointer, path.join(target, 'CURRENT')); // Commit only after all pages/assets succeed.
    committed = true;
    return snapshot;
  } finally {
    await lock.close(); await fs.unlink(lockPath);
    if (stage && !committed) await fs.rm(stage, { recursive: true, force: true });
  }
}

if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
  try { const result = await exportPublic(); console.log(`Public posts: ${result.posts.length}`); }
  catch { console.error('CMS export failed; current snapshot retained; do not deploy.'); process.exitCode = 1; }
}

添付は読取り許可と公開承認を分ける ​

APIで取得できるファイルでも、インターネットへ公開してよいとは限りません。原稿に添付した契約資料や個人情報を自動で配信しないよう、公開画像のGUID・SHA-256・代替テキストをpublic-media.jsonで別途承認します。サンプルの台帳は合成PNGの値なので、実画像の承認済み値へ置き換えます。

取得先は同じCMSのapi/binaries/{GUID}/getstreamに固定します。CMS本文の任意URLへキーを送ったり、認証付きの元URLを公開ページへ埋めたりしません。リダイレクトも追いません。返却MIME、PNGの先頭バイト、2MiB上限、承認済みSHA-256を検査し、元ファイル名を使わずハッシュ名で保存します。PNG以外の画像・PDF・保護ダウンロードの自動公開は、このサンプルへ含めません。

公開承認には、画像の権利、写っている情報、埋め込まれたメタデータの扱いも含めます。添付を編集・差替えしたら、承認台帳も更新してから生成します。

スナップショットを完成してから切り替える ​

公開DTOの照合と全画像の取得が成功するまで、.cms/CURRENTを変更しません。完成した専用ディレクトリの名前を、一時ファイルからのrenameで確定します。失敗時は非0で終了し、古いスナップショットを残しますが、その失敗を無視してビルドへ進めてはいけません。

並行取得はlockで拒否します。プロセスが異常終了してlockが残った場合は、該当プロセスがいないことを確認してlockだけを外します。旧版へ自動でfallbackして「今回の公開も成功」と扱う処理は入れていません。

全件取消・全件削除を表現できるよう、公開集合0件は許可しています。権限設定の事故などによる想定外の0件まで防ぎたい場合は、確定版の承認件数・slug一覧との照合を追加します。公開する意思の確認と、APIが空集合を返すことは別の判定です。

スナップショットの読み込みと公開画像の準備
js
// SPDX-License-Identifier: MIT
import fs from 'node:fs/promises';
import path from 'node:path';
// Framework bundlers relocate this module. npm scripts run from the sample root.
export const home = process.cwd();
export async function readSnapshot(root = home) {
  const id = (await fs.readFile(path.join(root, '.cms/CURRENT'), 'utf8')).trim();
  if (!/^release-[a-zA-Z0-9_-]+$/.test(id)) throw Error('Invalid snapshot pointer');
  const directory = path.join(root, '.cms/releases', id);
  const snapshot = JSON.parse(await fs.readFile(path.join(directory, 'snapshot.json'), 'utf8'));
  if (snapshot.schemaVersion !== 1 || !Array.isArray(snapshot.posts)) throw Error('Invalid snapshot');
  return { snapshot, directory };
}
js
// SPDX-License-Identifier: MIT
import fs from 'node:fs/promises';
import path from 'node:path';
import { home, readSnapshot } from './snapshot.mjs';
const { directory } = await readSnapshot();
for (const site of ['astro', 'vitepress']) {
  const media = path.join(home, site, 'public/media');
  // These two directories contain generated public assets only; never use a live deployment path.
  await fs.rm(media, { recursive: true, force: true });
  await fs.mkdir(media, { recursive: true });
  await fs.cp(path.join(directory, 'media'), media, { recursive: true });
  for (const file of await fs.readdir(media)) await fs.chmod(path.join(media, file), 0o644);
}

prepareはサンプル内の2つのpublic/mediaを生成専用として置き換えます。手動の画像を混ぜないでください。CIは新しい作業ディレクトリで全件生成し、その回の配信物だけをアップロードします。前回の配信ディレクトリへ追加コピーする方式では、取消済みページや画像が残ります。

Astroは文字列として描画する ​

Astroはビルド時のgetStaticPaths()で公開slugを列挙します。本文は通常の文字列式へ渡し、set:htmlやMDXへ渡しません。CMS本文のタグは文字として表示されます。

サンプルはルートURLへ置く構成です。プロジェクト配備などでURLにprefixが付く場合は、Astroのbaseと記事リンク・画像URLのprefixを揃えてください。

Astroの設定とページ全文
js
import { defineConfig } from 'astro/config';
export default defineConfig({ output: 'static', site: 'https://www.example.invalid/' });
astro
---
import { readSnapshot } from '../../../snapshot.mjs';
const { snapshot } = await readSnapshot();
---
<!doctype html><html lang="ja"><head><meta charset="utf-8" /><title>公開記事</title></head>
<body><h1>公開記事</h1><ul>{snapshot.posts.map(post => <li><a href={`/posts/${post.slug}/`}>{post.title}</a></li>)}</ul></body></html>
astro
---
import { readSnapshot } from '../../../../snapshot.mjs';
export async function getStaticPaths() {
  const { snapshot } = await readSnapshot();
  return snapshot.posts.map(post => ({ params: { slug: post.slug }, props: { post } }));
}
const { post } = Astro.props;
---
<!doctype html><html lang="ja"><head><meta charset="utf-8" /><title>{post.title}</title></head>
<body><main><h1>{post.title}</h1><p style="white-space:pre-wrap">{post.body}</p>
{post.images.map(image => <img src={image.src} alt={image.alt} />)}</main></body></html>

VitePressは本文をMarkdownへ展開しない ​

VitePressのMarkdownはVueとして処理されるため、CMS本文をそのまま.mdへ書き出すと、HTMLやVueのコードまでビルド対象に入り得ます。信頼できない本文を正規表現で取り除くだけの方法にも依存しません。

動的ルートの.paths.jsは検証済みのslugだけを渡します。本文やタイトルはルートパラメーターへ埋めず、data loaderの公開DTOから対応する記事を引き、信頼できる固定テンプレートのv-textで表示します。本文をv-html、コンポーネント名、eval、テンプレートソースへ渡しません。data loaderの返値は最終JavaScriptへシリアライズされるため、ここでキーやraw応答を返さないことが必要です。

VitePressの設定とページ全文
js
export default { title: '公開記事', cleanUrls: true };
js
import { readSnapshot } from '../snapshot.mjs';
export default { async load() { return (await readSnapshot()).snapshot; } };
md
---
layout: page
---

<script setup>
import { data } from './public.data.js'
</script>

<h1>公開記事</h1>
<ul><li v-for="post in data.posts" :key="post.slug"><a :href="`/posts/${post.slug}`" v-text="post.title"></a></li></ul>
js
import { readSnapshot } from '../../snapshot.mjs';
export default {
  async paths() {
    const { snapshot } = await readSnapshot();
    return snapshot.posts.map(post => ({ params: { slug: post.slug } }));
  }
};
md
---
layout: page
---

<script setup>
import { useData } from 'vitepress'
import { computed } from 'vue'
import { data } from '../public.data.js'
const { params } = useData()
const post = computed(() => data.posts.find(post => post.slug === params.value.slug))
</script>

<main>
  <h1 v-text="post.title"></h1>
  <p style="white-space: pre-wrap" v-text="post.body"></p>
  <!-- The approved alt text is bound by Vue rather than a static HTML attribute. -->
  <!-- markdownlint-disable-next-line MD045 -->
  <img v-for="image in post.images" :key="image.src" :src="image.src" :alt="image.alt">
</main>

リッチな本文が必要なら、見出し・段落・リストなどを明示した許可済みの構造へ変換し、固定コンポーネントで描画する設計を別に用意します。プレーンテキスト版へ未検証のHTMLレンダラーを足すだけでは、同じ公開境界を保てません。

成功した生成物だけを配信する ​

配布workflowはAstro版をGitHub Pagesへ配信する設定例です。利用先リポジトリ直下の.github/workflows/publish.ymlへ置き、PagesのSourceをGitHub Actionsにします。cms-public-build環境へ公開用のvarsとsecretを登録し、公開版を更新する担当者・ブランチを制限します。依存インストール時とフレームワーク生成時にはCMSキーを渡しません。

buildが失敗したらdeployは開始せず、前回の配信を変更しません。公開環境のconcurrencyを1つにし、古い承認待ち・予約ジョブを新しい公開版より後に配信しない運用にします。15分ごとのscheduleは期限反映の補助で、実行時刻の保証ではありません。

workflowの全文
yaml
name: Public CMS static site
on:
  push:
    branches: [main]
  workflow_dispatch:
  schedule:
    - cron: '*/15 * * * *'
permissions:
  contents: read
concurrency:
  group: public-cms-release
  cancel-in-progress: false
jobs:
  build:
    if: github.ref == 'refs/heads/main'
    runs-on: ubuntu-latest
    environment: cms-public-build
    steps:
      - uses: actions/checkout@v4
        with:
          persist-credentials: false
      - uses: actions/setup-node@v4
        with:
          node-version: 24
          cache: npm
      - run: npm ci --ignore-scripts
      - run: npm test
      - name: Export approved public release only
        run: npm run export
        env:
          CMS_BASE_URL: ${{ vars.CMS_BASE_URL }}
          CMS_SITE_ID: ${{ vars.CMS_SITE_ID }}
          CMS_RELEASE: ${{ vars.CMS_RELEASE }}
          CMS_API_KEY: ${{ secrets.CMS_PUBLIC_READ_KEY }}
      # The key is absent from the framework build step.
      - run: npm run prepare && npm run build:astro
      - uses: actions/upload-pages-artifact@v3
        with:
          path: astro/dist
  deploy:
    needs: build
    if: github.ref == 'refs/heads/main'
    runs-on: ubuntu-latest
    permissions:
      pages: write
      id-token: write
    environment:
      name: github-pages
      url: ${{ steps.deploy.outputs.page_url }}
    steps:
      - uses: actions/deploy-pages@v4
        id: deploy

公開取消と保護preview ​

公開取消・非公開化・削除・期限切れの反映は、CMSの更新だけでは終わりません。新しい集合からサイトを全件生成し、古いページ・画像・検索索引・feedが配信物に残っていないことを調べ、配信後のURLとCDNキャッシュまで確認します。CDNを使う場合は提供元の失効・削除手順も実行します。既に取得された内容を回収することはできません。

緊急取消とビルド失敗が同時に起きると、旧版保持だけでは取消を守れません。その場合は配信側で対象URLを拒否し、キャッシュを削除してから、生成を修復します。承認した公開版・配信結果・取消担当を記録しておきます。

下書きのpreviewは公開用の配信先へ置かず、別の認証必須ホスト・別の読取り権限・別のartifactで構成します。未認証で401/403または認証画面へ遷移することを確かめ、原稿のHTMLや画像をpublic artifactや公開キャッシュへ残しません。noindexや推測困難なURLは認証の代わりになりません。

配布エクスポーターは公開専用で、preview指定を拒否します。PRでは実CMSのsecretを渡さず、合成APIの試験だけを実行します。プレビュー機能や認証サービスの配備は、このサンプルには実装していません。

APIの型と実装の根拠 ​

以下は公式ソースのコミット664c833b144d9da9b6bb58e60f7e48eb01141e58への固定リンクです。参照日は2026年11月10日です。

確かめる内容固定ソース
POSTの経路と認証結果による分岐ItemsController
ApiVersion・View・Offset・PageSizeRequests/Api
ClassHash・CheckHash・AttachmentsHash_BaseApiModel
ResultId・Title・BodyResultApiModel
サーバー側ページ件数と応答の形ResultUtilities
読取り可能列とローカル日時への変換ResultModel
通常・履歴・削除のテーブル区分Sqls.TableTypes
添付の取得経路と読取り条件BinariesController、FileContentResults

Astroのビルド時データ取得とルーティング、VitePressの動的ルートとdata loader、GitHub Pagesのカスタムworkflowに対応する構成です。

関連ページ ​

変更履歴

第1版プリザンターをCMSにした静的サイト生成手順とサンプルを追加