static-site

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Static Site (Certified Assets)

静态站点(Certified Assets)

What This Is

这是什么

The
@dfinity/static-site
recipe
deploys a static site — a built frontend, docs, or any folder of files — to the certified-assets canister on the Internet Computer, which serves it over HTTP with response certification. The canister certifies every response (certification v2 only, never the
no_certification
escape hatch, no way to turn it off), and a verifying HTTP gateway checks that proof before handing the response to the browser: visitors get content the canister provably committed to, not something altered in transit. Whether the proof is checked depends on the gateway the visitor goes through:
https://<canister-id>.icp.net
verifies,
https://<canister-id>.raw.icp.net
does not (Pitfall 14).
This is the recommended way to host a frontend on the IC going forward. The recipe bundles a matched pair — the canister and its sync plugin — pinned together by one version. You point it at your build directory;
icp deploy
uploads, certifies, and serves.
The older
@dfinity/asset-canister
recipe
(the SDK asset canister, configured with
.ic-assets.json5
) is still supported for existing projects but is no longer the recommended path. It is a different canister with a different config format and API — see
references/legacy-asset-canister.md
. To move an existing project over, see
references/migrating-from-asset-canister.md
.
@dfinity/static-site
recipe
会将静态站点——一个已构建的前端、文档或任意文件目录——部署到 Internet Computer 上的 certified-assets canister,并通过带有 response certification 的 HTTP 提供服务。canister 会认证 每一个响应(仅支持 certification v2,绝不会使用
no_certification
逃生通道,也无法关闭),verifying HTTP gateway 则会在将响应交给浏览器前检查证明:访问者获得的是 canister 可证明已提交的内容,而不是在传输途中被篡改的内容。证明是否会被 检查 取决于访问者使用的 gateway:
https://<canister-id>.icp.net
会验证,
https://<canister-id>.raw.icp.net
不会(陷阱 14)。
这是今后在 IC 上托管前端的推荐方式。 recipe 将匹配的一对组件打包在一起——canister 及其 sync plugin——并通过同一版本锁定。你只需将 build 目录指向它;
icp deploy
会上传、认证并提供内容。
较旧的
@dfinity/asset-canister
recipe
(SDK asset canister,使用
.ic-assets.json5
配置)仍受现有项目支持,但已不再是推荐路径。它是一个 不同的 canister,具有不同的配置格式和 API——请参阅
references/legacy-asset-canister.md
。如需迁移现有项目,请参阅
references/migrating-from-asset-canister.md
。

Prerequisites

前置条件

  • icp-cli
    —
    npm install -g @icp-sdk/icp-cli
    . The recipe pins the canister + sync-plugin pair, both pre-built, so a plain
    dir
    /
    build
    /
    presync
    deploy needs nothing else.
  • ic-wasm
    —
    npm install -g @icp-sdk/ic-wasm
    . A separate binary, not bundled with
    icp-cli
    . This recipe shells out to it only when you set the
    metadata
    field (the generated build guards on
    command -v ic-wasm
    and fails with "ic-wasm not found"); other official recipes need it unconditionally, so installing both up front is the safe default — see the
    icp-cli
    skill.
  • Your frontend's build toolchain (e.g. Node.js >= 22 for a Vite/React app).
  • icp-cli
    —
    npm install -g @icp-sdk/icp-cli
    。recipe 会锁定 canister + sync-plugin 配对,两者均已预构建,因此普通的
    dir
    /
    build
    /
    presync
    部署不需要其他依赖。
  • ic-wasm
    —
    npm install -g @icp-sdk/ic-wasm
    。这是一个 独立 二进制文件,不包含在
    icp-cli
    中。只有在设置
    metadata
    字段时,此 recipe 才会调用它(生成的构建脚本会检查
    command -v ic-wasm
    ,如果未找到则报“ic-wasm not found”);其他官方 recipe 则无条件需要它,因此预先安装两者是更稳妥的默认选择——请参阅
    icp-cli
    skill。
  • 前端的 build toolchain(例如,Vite/React 应用需要 Node.js >= 22)。

Canister IDs and URLs

Canister ID 与 URL

Static-site canisters are created per-project — there is no global canister ID. After deployment the canister ID is stored in
.icp/<cache|data>/mappings/<environment>.ids.json
. Managed networks (the local replica) are cache —
.icp/cache/mappings/local.ids.json
; connected networks (mainnet
ic
) are data —
.icp/data/mappings/ic.ids.json
.
EnvironmentBrowser URL
Local
http://<canister-name>.<environment>.localhost:8000
— the middle label is the environment name,
local
by default, so
http://frontend.local.localhost:8000
(this is the URL
icp deploy
prints;
http://<canister-id>.localhost:8000
also works —
<canister-name>.localhost
with no environment label does not)
Mainnet
https://<canister-id>.icp.net
Custom domain
https://yourdomain.com
(with DNS configuration)
静态站点 canister 按项目创建——不存在全局 canister ID。部署后,canister ID 会存储在
.icp/<cache|data>/mappings/<environment>.ids.json
中。托管网络(本地 replica)属于 cache —
.icp/cache/mappings/local.ids.json
;已连接的网络(主网
ic
)属于 data —
.icp/data/mappings/ic.ids.json
。
环境浏览器 URL
本地
http://<canister-name>.<environment>.localhost:8000
— 中间的标签是 环境名称,默认为
local
,因此为
http://frontend.local.localhost:8000
(这是
icp deploy
输出的 URL;
http://<canister-id>.localhost:8000
同样有效——不带环境标签的
<canister-name>.localhost
无效)
主网
https://<canister-id>.icp.net
自定义域名
https://yourdomain.com
(需要配置 DNS)

icp.yaml Configuration

icp.yaml
配置

yaml
canisters:
  - name: frontend
    recipe:
      type: "@dfinity/static-site@v0.4.3"
      configuration:
        build:
          - npm ci
          - npm run build
        dir: dist
Check the static-site releases for the latest version and pin it in the
type
field. Because the recipe pins a matched canister + plugin pair, there is no separate canister version to choose — the recipe version is the canister version.
The recipe takes four configuration fields:
FieldRequiredDescription
dir
YesThe single directory of built files to serve. The canister owns its whole URL space, so this is one directory, not a list. Vite →
dist
, Next.js export →
out
.
build
NoShell commands run before the canister exists to produce
dir
(e.g.
npm run build
). No canister IDs are available yet.
presync
NoShell commands run at sync time, after the canister exists, with deployed canister IDs exported as env vars. Use this to bake a canister ID into a frontend build (see below).
metadata
No
name
/
value
/
visibility
entries baked into the canister wasm via
ic-wasm
.
visibility
is optional,
public
or
private
; omitted means
private
(ic-wasm's default), and only
public
sections are readable by anyone via
icp canister metadata
. Values are interpolated in a shell at build time, so
$(…)
works.
yaml
canisters:
  - name: frontend
    recipe:
      type: "@dfinity/static-site@v0.4.3"
      configuration:
        build:
          - npm ci
          - npm run build
        dir: dist
请查看 static-site releases 获取最新版本,并在
type
字段中锁定该版本。由于 recipe 会锁定匹配的 canister + plugin 配对,因此 无需单独选择 canister 版本——recipe 版本 就是 canister 版本。
此 recipe 接受四个配置字段:
字段必需说明
dir
是要提供服务的构建文件所在的单一目录。canister 拥有其整个 URL 空间,因此这里是单个目录,而不是列表。Vite →
dist
,Next.js export →
out
。
build
否在 canister 存在 之前 运行的 Shell 命令,用于生成
dir
(例如
npm run build
)。此时尚无可用的 canister ID。
presync
否在 sync 时、canister 已存在 之后 运行的 Shell 命令,已部署的 canister ID 会作为环境变量导出。可用此方式将 canister ID 写入前端构建产物(请参阅下文)。
metadata
否通过
ic-wasm
写入 canister wasm 的
name
/
value
/
visibility
条目。
visibility
为可选值,可取
public
或
private
;省略时默认为
private
(ic-wasm 的默认值),且只有
public
section 可由任何人通过
icp canister metadata
读取。值会在构建时通过 Shell 插值,因此可以使用
$(…)
。

Pitfalls

常见陷阱

  1. Using
    .ic-assets.json5
    with the static-site recipe.
    .ic-assets.json5
    is the legacy asset canister's config file. The certified-assets canister does not read it — and because the plugin skips every dotfile and dot-directory (only
    .well-known/
    is exempt, Pitfall 12), a
    .ic-assets.json5
    in your
    dir
    is not even uploaded. It is silently absent, so SPA fallback, headers, and security policy do nothing. Configure this canister with
    _redirects
    and
    _headers
    instead (below).
  2. Wrong SPA fallback rule. For client-side routing, the fallback is a rewrite in
    _redirects
    :
    /*  /index.html  200
    . The
    200
    status is what makes it a rewrite (serve the shell's contents at the requested URL, no visible redirect) so deep links work on fresh load and reload. Do not use a
    301
    /
    302
    redirect, and do not reach for
    enable_aliasing
    — that is a legacy asset-canister setting and has no effect here.
  3. Relative asset paths in a SPA. Link assets with absolute paths (
    /assets/app.js
    ), never relative (
    assets/app.js
    ). Under a
    /*
    rewrite, a relative URL resolves against the client route: at
    /dashboard/settings
    the browser requests
    /dashboard/settings/assets/app.js
    , which
    /*
    answers with the HTML shell — producing a confusing MIME-type error instead of loading your script.
  4. Expecting
    AssetManager
    /
    @icp-sdk/canisters
    to work.
    The certified-assets canister's upload API is
    upload_chunks
    +
    execute_operations
    , not the SDK asset canister's
    store
    /
    create_batch
    /
    commit_batch
    .
    AssetManager
    from
    @icp-sdk/canisters/assets
    targets the legacy canister and does not work against static-site. Uploads happen through the recipe's sync plugin on
    icp deploy
    ; there is no drop-in JS
    AssetManager
    equivalent for this canister. (If you need programmatic uploads, you are almost certainly on the legacy canister — see the legacy reference.)
  5. _headers
    /
    _redirects
    in the wrong place.
    These two files must sit at the root of your
    dir
    (e.g.
    dist/_redirects
    ). They are read as configuration and never served as assets. Put them in your
    public/
    (Vite) or
    static/
    folder so the build copies them into
    dir
    automatically — a file left at the project root but not copied into
    dir
    is simply absent at deploy time.
  6. Setting a reserved header in
    _headers
    .
    The sync plugin rejects these at deploy time with an explanatory error:
    Content-Length
    ,
    Content-Encoding
    ,
    ETag
    ,
    Transfer-Encoding
    ,
    Accept-Ranges
    ,
    Content-Range
    ,
    IC-Certificate
    ,
    IC-CertificateExpression
    ,
    Location
    . To set an asset's media type use the bare
    Content-Type:
    form (it routes to asset metadata, not a response header). To redirect, use
    _redirects
    — a
    Location
    header in
    _headers
    would not redirect (status stays
    200
    ).
  7. Assuming default security headers. Unlike the legacy canister's
    security_policy: "standard"
    , the certified-assets canister adds no default headers — no
    Cache-Control
    , no CSP, no
    X-Frame-Options
    . If you want them, declare them in
    _headers
    (baseline below). The only headers it manages itself are the certification/serving ones and its
    ic_env
    cookie.
  8. A
    404
    /
    410
    rule pointing at a large file.
    An error-page target must be a small, single-chunk file (under ~1.9 MB). Large files are served as certified
    206
    range responses that can't carry a 4xx status, so the plugin rejects such a rule at deploy time, naming it. (A
    200
    rewrite to a large file is fine.)
  9. Expecting dynamic redirect captures. There is no
    :splat
    or
    :placeholder
    — you can't forward a captured segment (
    /old/:rest → /new/:rest
    ). Every certifiable response must be enumerable ahead of time, so
    _redirects
    /
    _headers
    support only exact paths, a trailing
    /*
    subtree wildcard, and fixed destinations.
  10. Switching an existing project from the legacy asset canister to static-site. Repointing
    recipe:
    at
    @dfinity/static-site
    and running a plain
    icp deploy
    fails before anything is installed: these are two unrelated canisters with unrelated Candid interfaces, so icp-cli's pre-install check aborts with
    Candid interface compatibility check failed: '<canister>' … You are making a BREAKING change
    . Run
    icp deploy --mode reinstall
    instead. That replaces the wasm with the certified-assets canister, discards the old stable memory — every legacy asset, permission, and
    .ic-assets.json5
    -derived setting is gone — and leaves the canister with empty state, after which the sync plugin uploads your whole
    dir
    from scratch. Deploying static-site as a brand-new canister avoids the question entirely. Do not silence the check with
    --yes
    : that pushes the in-place upgrade through onto stable memory certified-assets cannot read, leaving a live canister that serves nothing. See the migration reference.
  11. Assuming a recipe version bump re-installs itself. Moving between certified-assets' own releases is gentler than the legacy switch above — the Candid interface is stable across a release series, so nothing blocks the deploy — but a breaking bump still needs a reinstall you run yourself. The canister and plugin are version-locked, so after bumping the recipe
    icp deploy
    upgrades in place and the sync plugin then refuses, reporting
    assets canister version mismatch: canister is X, this plugin is Y
    plus the fix:
    icp canister install --mode upgrade
    for a patch bump (state preserved) or
    icp canister install --mode reinstall
    for a breaking (pre-1.0 minor, post-1.0 major) bump, which wipes state so the next sync re-uploads every asset and redirect rule. (
    v0.3.x
    →
    v0.4.0
    is breaking
    : reinstall, then
    icp deploy
    .
    v0.4.x
    →
    v0.4.3
    is a patch: upgrade, then
    icp deploy
    .) A failed sync right after a version bump is expected — this, not a bug.
  12. .well-known/
    is uploaded automatically — no config needed.
    The plugin skips dotfiles and dot-directories except
    .well-known/
    , which it traverses normally. So
    dir/.well-known/ic-domains
    is served at
    /.well-known/ic-domains
    with no extra setting. (This is the opposite of the legacy canister, which needed an explicit
    .ic-assets.json5
    un-ignore rule.)
  13. Access protection ordering. The recipe's
    icp deploy
    installs the canister and syncs assets together, so a plain deploy-then-
    enable_protection
    briefly serves your content publicly. For a brand-new private app, enable protection before your real assets are synced — deploy a
    dir
    containing only
    login.html
    ,
    enable_protection
    , then deploy the full site — so assets are never world-readable. The login page must be fully self-contained (inline CSS/JS,
    data:
    URIs) — it is the only gate-exempt path, and any external subresource it references would itself be gated. See Access protection.
  14. Sharing or linking a
    raw.icp.net
    URL.
    <canister-id>.raw.icp.net
    serves the same site as
    <canister-id>.icp.net
    , but the gateway forwards responses without checking the certificate, so the visitor gets no more assurance than from an ordinary web host. There is no canister setting to refuse
    raw
    requests (unlike the legacy canister's
    allow_raw_access
    ): the only clue is the unauthenticated
    Host
    header, and which hostnames verify is a gateway deployment detail, not protocol. Link to
    https://<canister-id>.icp.net
    (or a custom domain on a verifying gateway) and treat
    raw
    as a debugging tool only. With access protection on, a
    raw
    URL is actively dangerous: the redirect and login page arrive unverified, so a non-verifying gateway could serve a fake login form and harvest tokens. The access cookie is host-only, so a session on the certified host does not carry over to
    raw
    .
  1. 在 static-site recipe 中使用
    .ic-assets.json5
    。
    .ic-assets.json5
    是 legacy asset canister 的配置文件。certified-assets canister 不会读取它——而且由于 plugin 会跳过每个 dotfile 和 dot-directory(只有
    .well-known/
    除外,见陷阱 12),位于
    dir
    中的
    .ic-assets.json5
    甚至不会被上传。它会被静默忽略,因此 SPA fallback、标头和安全策略都不会生效。请改用
    _redirects
    和
    _headers
    配置此 canister(见下文)。
  2. 使用错误的 SPA fallback 规则。 对于客户端路由,fallback 必须是
    _redirects
    中的 rewrite:
    /*  /index.html  200
    。
    200
    状态码使其成为 rewrite(在请求的 URL 提供 shell 内容,不产生可见重定向),因此深层链接在首次加载和刷新时都能正常工作。不要使用
    301
    /
    302
    redirect,也不要使用
    enable_aliasing
    ——后者是 legacy asset-canister 的设置,在这里不起作用。
  3. 在 SPA 中使用相对资源路径。 应使用 绝对 路径链接资源(
    /assets/app.js
    ),绝不要使用相对路径(
    assets/app.js
    )。在
    /*
    rewrite 下,相对 URL 会根据 客户端路由 进行解析:在
    /dashboard/settings
    处,浏览器会请求
    /dashboard/settings/assets/app.js
    ,而
    /*
    会以 HTML shell 响应它,最终产生令人困惑的 MIME 类型错误,而不是正常加载脚本。
  4. 以为
    AssetManager
    /
    @icp-sdk/canisters
    可以直接使用。
    certified-assets canister 的上传 API 是
    upload_chunks
    +
    execute_operations
    ,不是 SDK asset canister 的
    store
    /
    create_batch
    /
    commit_batch
    。
    @icp-sdk/canisters/assets
    中的
    AssetManager
    面向 legacy canister,不能用于 static-site。上传通过
    icp deploy
    时 recipe 的 sync plugin 完成;此 canister 没有可直接替代的 JavaScript
    AssetManager
    。(如果需要编程式上传,你几乎肯定应该使用 legacy canister——请参阅旧版参考。)
  5. 将
    _headers
    /
    _redirects
    放在错误位置。
    这两个文件必须位于
    dir
    的 根目录(例如
    dist/_redirects
    )。它们会被当作配置读取,绝不会作为资源提供。请将它们放入
    public/
    (Vite)或
    static/
    目录,使构建过程自动将其复制到
    dir
    ;如果文件仍留在项目根目录且未被复制到
    dir
    ,部署时便不会出现。
  6. 在
    _headers
    中设置保留标头。
    sync plugin 会在部署时拒绝以下标头并给出说明性错误:
    Content-Length
    、
    Content-Encoding
    、
    ETag
    、
    Transfer-Encoding
    、
    Accept-Ranges
    、
    Content-Range
    、
    IC-Certificate
    、
    IC-CertificateExpression
    、
    Location
    。如需设置资源的媒体类型,请使用不带附加标头的
    Content-Type:
    形式(它会路由到资源元数据,而不是普通响应标头)。如需重定向,请使用
    _redirects
    ——在
    _headers
    中设置
    Location
    标头不会产生重定向(状态仍为
    200
    )。
  7. 假设存在默认安全标头。 与 legacy canister 的
    security_policy: "standard"
    不同,certified-assets canister 不会添加任何默认标头——没有
    Cache-Control
    、CSP 或
    X-Frame-Options
    。如需这些标头,请在
    _headers
    中声明(见下方基线配置)。它自行管理的标头只有认证/服务相关标头及其
    ic_env
    cookie。
  8. 让
    404
    /
    410
    规则指向大型文件。
    错误页面目标必须是 小型单块文件(约小于 1.9 MB)。大型文件会作为经过认证的
    206
    range response 提供,无法携带 4xx 状态,因此 plugin 会在部署时拒绝此类规则,并指出对应规则。(使用
    200
    rewrite 指向大型文件没有问题。)
  9. 期待动态重定向捕获。 不支持
    :splat
    或
    :placeholder
    ——无法转发捕获的路径段(
    /old/:rest → /new/:rest
    )。每个可认证响应都必须预先枚举,因此
    _redirects
    /
    _headers
    仅支持精确路径、末尾带
    /*
    的子树通配符以及固定目标。
  10. 将现有项目从 legacy asset canister 切换到 static-site。 仅将
    recipe:
    指向
    @dfinity/static-site
    并运行普通的
    icp deploy
    ,会在安装任何内容 之前 失败:这是两个互不相关的 canister,其 Candid 接口也互不相关,因此 icp-cli 的预安装检查会中止并提示
    Candid interface compatibility check failed: '<canister>' … You are making a BREAKING change
    。请改用
    icp deploy --mode reinstall
    。该命令会用 certified-assets canister 替换 wasm,丢弃旧的 stable memory——所有 legacy 资源、权限以及从
    .ic-assets.json5
    派生的设置都会消失——并使 canister 处于空状态,随后 sync plugin 会从头上传整个
    dir
    。将 static-site 作为全新 canister 部署可以完全避免此问题。不要用
    --yes
    跳过检查;否则会尝试在 stable memory 上执行原地升级,而 certified-assets 无法读取该内存,最终留下一个无法提供任何内容的在线 canister。请参阅迁移参考。
  11. 以为 recipe 版本升级会自动重新安装自身。 在 certified-assets 自身的各版本之间升级比上述 legacy 切换更温和——Candid 接口在同一发布系列内保持稳定,因此不会阻止部署——但破坏性升级仍需你手动执行重新安装。canister 与 plugin 版本相互锁定,因此升级 recipe 后,
    icp deploy
    会原地升级 canister,随后 sync plugin 会拒绝继续并报告
    assets canister version mismatch: canister is X, this plugin is Y
    ,同时给出修复方式:对于 补丁 升级,运行
    icp canister install --mode upgrade
    (保留状态);对于 破坏性 升级(1.0 之前的 minor 版本、1.0 之后的 major 版本),运行
    icp canister install --mode reinstall
    ,这会清除状态,使下一次 sync 重新上传所有资源和重定向规则。(
    v0.3.x
    →
    v0.4.0
    属于破坏性升级
    :先重新安装,再执行
    icp deploy
    。
    v0.4.x
    →
    v0.4.3
    属于补丁升级:先升级,再执行
    icp deploy
    。)版本升级后 sync 失败属于预期行为,并非 bug。
  12. .well-known/
    会自动上传,无需额外配置。
    plugin 会跳过 dotfile 和 dot-directory,但
    .well-known/
    除外
    ,它会正常遍历该目录。因此
    dir/.well-known/ic-domains
    无需任何额外设置即可在
    /.well-known/ic-domains
    提供服务。(这与 legacy canister 正好相反,后者需要通过
    .ic-assets.json5
    显式设置 un-ignore 规则。)
  13. 访问保护的启用顺序。 recipe 的
    icp deploy
    会同时安装 canister 并同步资源,因此普通的“部署后再调用
    enable_protection
    ”流程会在短时间内公开提供内容。对于全新的 私有 应用,应在同步真实资源 之前 启用保护——先部署一个仅包含
    login.html
    的
    dir
    ,执行
    enable_protection
    ,然后再部署完整站点——这样资源在任何时候都不会被公众读取。登录页必须 完全自包含(内联 CSS/JS、
    data:
    URI)——它是唯一不受访问门禁保护的路径,而它引用的任何外部子资源本身也会受到门禁保护。请参阅访问保护。
  14. 共享或链接
    raw.icp.net
    URL。
    <canister-id>.raw.icp.net
    与
    <canister-id>.icp.net
    提供的是同一站点,但 gateway 在转发响应时 不会检查证书,因此访问者获得的保障不会超过普通 Web 主机。与 legacy canister 的
    allow_raw_access
    不同,canister 没有拒绝
    raw
    请求的设置:唯一的线索是未经认证的
    Host
    标头,而哪些主机名会进行验证属于 gateway 部署细节,并非协议的一部分。请链接到
    https://<canister-id>.icp.net
    (或使用 verifying gateway 的自定义域名),并将
    raw
    仅视为调试工具。启用访问保护后,使用
    raw
    URL 会非常危险:重定向和登录页都未经验证,因此不进行验证的 gateway 可能提供伪造的登录表单并窃取 token。访问 cookie 为 host-only,因此认证主机上的会话不会延续到
    raw
    。

SPA Routing and Redirects:
_redirects

SPA 路由与重定向:
_redirects

Add a
_redirects
file to the root of your
dir
. Syntax follows Netlify's
_redirects
— one rule per line, three whitespace-separated fields (
from
,
to
,
status
); blank lines and
#
comments are ignored.
undefined
在
dir
的根目录添加
_redirects
文件。语法遵循 Netlify 的
_redirects
——每行一条规则,由三个以空白分隔的字段组成(
from
、
to
、
status
);空行和
#
注释会被忽略。
undefined

Single-page-app fallback: serve the shell for any unmatched path (a rewrite, status 200)

Single-page-app fallback: serve the shell for any unmatched path (a rewrite, status 200)

/* /index.html 200
/* /index.html 200

Permanent redirect to a new internal path

Permanent redirect to a new internal path

/old-blog /blog 301
/old-blog /blog 301

Redirect to an external site

Redirect to an external site

Rewrite: serve /content/article.html at a pretty URL, no visible redirect

Rewrite: serve /content/article.html at a pretty URL, no visible redirect

/article /content/article.html 200
/article /content/article.html 200

Subtree redirect: everything under /docs/v1/ moves to /docs/v2/

Subtree redirect: everything under /docs/v1/ moves to /docs/v2/

/docs/v1/* /docs/v2/ 301
/docs/v1/* /docs/v2/ 301

Custom error pages (target must be a small single-chunk file)

Custom error pages (target must be a small single-chunk file)

/secret /403.html 404 /retired-feature /sunset.html 410

Status codes: `301`/`302`/`307`/`308` redirect; `200` is a **rewrite**; `404`/`410` serve an error page. `from` is always absolute and its only wildcard is a trailing `/*`. Precedence, first match wins: **real files** > automatic **clean-URL** rules > your `_redirects` (in file order) > the 404 fallback. Because a real file always wins, a `/*` SPA rule only catches paths nothing else claimed.

**SPA caveat — missing assets return HTML.** With `/*  /index.html  200`, a typo'd `/assets/app-old.js` also matches `/*` and serves the shell as `text/html`. To give real 404s under a build-output folder, scope a narrower rule *above* the catch-all (rules match in file order):
/assets/* /404.html 404 /* /index.html 200

This needs a `404.html` in your `dir`; declaring `/*` means the built-in default 404 is not added.
/secret /403.html 404 /retired-feature /sunset.html 410

状态码:`301`/`302`/`307`/`308` 表示重定向;`200` 表示 **rewrite**;`404`/`410` 用于提供错误页面。`from` 始终为绝对路径,唯一支持的通配符是末尾的 `/*`。优先级按“首个匹配项胜出”计算:**真实文件** > 自动 **clean URL** 规则 > 你的 `_redirects`(按文件顺序)> 404 fallback。由于真实文件始终优先,因此 `/*` SPA 规则只会处理未被其他规则匹配的路径。

**SPA 注意事项——缺失的资源会返回 HTML。** 使用 `/*  /index.html  200` 时,拼写错误的 `/assets/app-old.js` 也会匹配 `/*` 并以 `text/html` 返回 shell。若要让构建输出目录下的真实 404 生效,请在 catch-all 规则 **上方** 设置范围更窄的规则(规则按文件顺序匹配):
/assets/* /404.html 404 /* /index.html 200

这要求 `dir` 中存在 `404.html`;声明 `/*` 后,系统将不再添加内置的默认 404 页面。

Custom Headers:
_headers

自定义标头:
_headers

Add a
_headers
file to the root of your
dir
. Syntax follows Netlify's
_headers
: a path pattern on its own line, followed by indented
Name: value
lines; a blank line or
#
ends a block. Patterns are absolute paths with an optional single
*
wildcard (which matches
/
too; there is no
**
or
?
).
A useful baseline — act like a senior security engineer and tighten the CSP for your app:
/*
  X-Frame-Options: DENY
  X-Content-Type-Options: nosniff
  Referrer-Policy: strict-origin-when-cross-origin
  Content-Security-Policy: default-src 'self'; img-src 'self' data:; style-src 'self' 'unsafe-inline'
在
dir
的根目录添加
_headers
文件。语法遵循 Netlify 的
_headers
:第一行是路径模式,随后是缩进的
Name: value
行;空行或
#
会结束当前块。模式为绝对路径,可包含一个可选的
*
通配符(它也能匹配
/
;不支持
**
或
?
)。
下面是一套实用的基线配置——应像资深安全工程师一样为应用收紧 CSP:
/*
  X-Frame-Options: DENY
  X-Content-Type-Options: nosniff
  Referrer-Policy: strict-origin-when-cross-origin
  Content-Security-Policy: default-src 'self'; img-src 'self' data:; style-src 'self' 'unsafe-inline'

Fingerprinted build assets never change — cache them hard

Fingerprinted build assets never change — cache them hard

/assets/* Cache-Control: public, max-age=31536000, immutable
/assets/* Cache-Control: public, max-age=31536000, immutable

HTML should revalidate so deploys are picked up

HTML should revalidate so deploys are picked up

/*.html Cache-Control: public, max-age=0, must-revalidate

Key rules:
- **Patterns match the file (asset key), not the visitor's URL.** Write `/index.html`, not `/`. For a SPA, a `Cache-Control` on `/index.html` (or `/*.html`) is what every `/*`-rewritten client route gets; a block written against a route like `/dashboard/*` matches no file and does nothing.
- **All matching blocks contribute** — a file matching several blocks gets every block's headers (same-name values are combined comma-separated; `Set-Cookie` stays separate).
- **`Content-Type` is special** — the bare `Content-Type: <type>` form overrides the stored media type of the matching file (use it for extension-less files like `/llms.txt`); it is single-valued, first-match-wins, and is *not* emitted as an ordinary header.
- **`Set-Cookie` is allowed, but don't use the name `ic_env`.** The canister adds its own `ic_env` cookie to HTML responses as **two** `Set-Cookie` headers with the same name and value: one `SameSite=Lax`, one `SameSite=None; Partitioned` (so it survives in a cross-site iframe). Seeing two `ic_env` headers is expected, not a duplicate-header bug.
- Reserved headers are rejected at deploy time — see Pitfall 6.
/*.html Cache-Control: public, max-age=0, must-revalidate

关键规则:
- **模式匹配的是文件(asset key),而不是访问者的 URL。** 应编写 `/index.html`,而不是 `/`。对于 SPA,在 `/index.html`(或 `/*.html`)上设置 `Cache-Control` 才能作用于所有经 `/*` rewrite 的客户端路由;针对 `/dashboard/*` 等路由编写的块不会匹配任何文件,因此不起作用。
- **所有匹配块都会生效**——一个文件匹配多个块时,会获得每个块中的所有标头(同名值以逗号连接;`Set-Cookie` 保持独立)。
- **`Content-Type` 特殊处理**——不带附加标头的 `Content-Type: <type>` 形式会覆盖匹配文件的已存储媒体类型(适用于 `/llms.txt` 等无扩展名文件);它是单值、首个匹配项胜出,并且 *不会* 作为普通标头发出。
- **允许使用 `Set-Cookie`,但不要使用名称 `ic_env`。** canister 会以 **两个** `Set-Cookie` 标头向 HTML 响应添加自己的 `ic_env` cookie,二者名称和值相同:一个使用 `SameSite=Lax`,另一个使用 `SameSite=None; Partitioned`(因此可在跨站 iframe 中保留)。看到两个 `ic_env` 标头属于预期现象,并非重复标头 bug。
- 保留标头会在部署时被拒绝——请参阅陷阱 6。

Clean URLs and the 404 Page

Clean URL 与 404 页面

You don't link to
.html
files — the canister maps each HTML file to a clean, extension-less canonical URL and
307
-redirects the other forms to it:
Your fileCanonical URLAlso handled (→
307
)
dist/index.html
/
/index
dist/about.html
/about
/about/
,
/about/index
dist/blog/index.html
/blog/
/blog
,
/blog/index
Requesting the underlying
/about.html
directly currently serves it
200
(a file always beats a routing rule). For a custom 404, put a
404.html
at the root of your
dir
; otherwise a certified default is served. A SPA
/*
rule takes over the whole path space, so it replaces the default 404 with your shell.
你无需直接链接
.html
文件——canister 会将每个 HTML 文件映射到一个无扩展名的规范 URL,并通过
307
将其他形式重定向到该 URL:
你的文件规范 URL同样会处理(→
307
)
dist/index.html
/
/index
dist/about.html
/about
/about/
、
/about/index
dist/blog/index.html
/blog/
/blog
、
/blog/index
当前直接请求底层
/about.html
会以
200
提供内容(真实文件始终优先于路由规则)。如需自定义 404 页面,请将
404.html
放在
dir
的根目录;否则系统会提供经过认证的默认页面。SPA 的
/*
规则会接管整个路径空间,因此会用你的 shell 替换默认 404 页面。

Custom Domains

自定义域名

To serve from your own domain, add a
.well-known/ic-domains
file to your
dir
, one domain per line:
example.com
www.example.com
.well-known/
is uploaded automatically (Pitfall 12), so the file is served where the IC boundary nodes look. Registering the domain itself (DNS records, ACME challenge, TLS provisioning) is a separate IC platform step — see the
custom-domains
skill.
如需通过自有域名提供内容,请在
dir
中添加
.well-known/ic-domains
文件,每行写入一个域名:
example.com
www.example.com
.well-known/
会自动上传(见陷阱 12),因此该文件会出现在 IC boundary nodes 查找它的位置。域名本身的注册(DNS 记录、ACME challenge、TLS 配置)是独立的 IC 平台步骤——请参阅
custom-domains
skill。

Access Protection (private apps)

访问保护(私有应用)

Put a login gate in front of an in-progress or preview app. Unauthenticated visitors get a certified
307 → <login_page>
(HTML) or
401
(other assets). Configure it through controller-only canister methods:
sh
undefined
可以在开发中或预览应用前放置登录门禁。未通过认证的访问者会收到经过认证的
307 → <login_page>
(HTML),或针对其他资源收到
401
。请通过仅限 controller 调用的 canister 方法进行配置:
sh
undefined

1. Add a self-contained /login.html to your dir and deploy.

1. Add a self-contained /login.html to your dir and deploy.

icp deploy
icp deploy

2. Turn the gate on, naming your login page.

2. Turn the gate on, naming your login page.

icp canister call frontend enable_protection '("/login.html")'
icp canister call frontend enable_protection '("/login.html")'

3. Mint a credential (here: a chosen passphrase valid ~1 year). Pass value = null for a random token.

3. Mint a credential (here: a chosen passphrase valid ~1 year). Pass value = null for a random token.

issue_token takes a record (IssueTokenArgs), not positional args.

issue_token takes a record (IssueTokenArgs), not positional args.

icp canister call frontend issue_token '(record { label = "owner"; ttl_secs = 31536000 : nat32; value = opt "my-passphrase" })'

> **Ordering & the public window.** The `static-site` recipe's `icp deploy` **installs the canister and syncs your assets in one step**, so the sequence above serves your content publicly for the brief window between that first deploy and `enable_protection` — fine when gating an existing or preview app. To avoid *any* public exposure for a **brand-new private app**, enable protection **before your real assets are synced**: run the first `icp deploy` with a `dir` containing only `login.html`, then `enable_protection '("/login.html")'`, then `icp deploy` again with the full site. The login page is gate-exempt, so nothing private is ever served unauthenticated (Pitfall 13). (Enabling on a truly empty canister also works — the canister reports `EnabledLoginPageMissing` and self-heals to `Enabled` once `login.html` is synced.)

| Method | Effect |
|--------|--------|
| `issue_token '(record { label = "<label>"; ttl_secs = <secs> : nat32; value = opt "<value>" })'` | Mints a token, returns its value. `value = null` → high-entropy random token. |
| `revoke_token '("<label>")'` | Removes every token with that label, live. |
| `list_tokens '()'` | Live tokens `{ label; expires_at }` (controller-only). |
| `check_protection_status '()'` | `Disabled`, `Enabled`, or `EnabledLoginPageMissing`. |
| `disable_protection '()'` | Gate off, drops all tokens. |

Always pass the argument explicitly — `'()'` for the methods that take none. Called with no argument, `icp canister call` opens an interactive prompt instead of sending an empty one.

This is **access gating, not confidentiality**: node operators can read asset bytes and the token store, there is no rate-limiting, and it relies on the honest-replica/honest-gateway assumption. The gate runs canister-side on every hostname, but its redirect and login page are only verified through a verifying gateway, so never send people to a `raw` URL of a protected app (Pitfall 14). Use high-entropy random tokens for share links; enable *before* the first sync for a new private app (Pitfall 13). Full details in the [certified-assets access-protection docs](https://github.com/dfinity/certified-assets/blob/v0.4.3/docs/access-protection.md).
icp canister call frontend issue_token '(record { label = "owner"; ttl_secs = 31536000 : nat32; value = opt "my-passphrase" })'

> **顺序与公开窗口。** `static-site` recipe 的 `icp deploy` 会在一个步骤中 **安装 canister 并同步资源**,因此上述顺序会在首次部署与 `enable_protection` 之间的短暂窗口内公开提供内容——对于已有应用或预览应用通常没有问题。若要确保全新的 **私有应用** 绝不出现公开暴露,应在同步真实资源 **之前** 启用保护:首次 `icp deploy` 时让 `dir` 仅包含 `login.html`,然后执行 `enable_protection '("/login.html")'`,最后使用完整站点再次执行 `icp deploy`。登录页不受门禁限制,因此任何私有内容都不会在未经认证的情况下提供(陷阱 13)。(在完全为空的 canister 上启用保护同样可行——canister 会报告 `EnabledLoginPageMissing`,并在同步 `login.html` 后自动恢复为 `Enabled`。)

| 方法 | 效果 |
|--------|--------|
| `issue_token '(record { label = "<label>"; ttl_secs = <secs> : nat32; value = opt "<value>" })'` | 创建一个 token 并返回其值。`value = null` → 生成高熵随机 token。 |
| `revoke_token '("<label>")'` | 立即删除具有该标签的所有 token。 |
| `list_tokens '()'` | 获取当前有效的 token `{ label; expires_at }`(仅限 controller)。 |
| `check_protection_status '()'` | 返回 `Disabled`、`Enabled` 或 `EnabledLoginPageMissing`。 |
| `disable_protection '()'` | 关闭门禁并删除所有 token。 |

始终显式传入参数——对于不需要参数的方法,传入 `'()'`。如果不带参数调用,`icp canister call` 会打开交互式提示,而不会发送空参数。

这是 **访问门禁,而非保密机制**:节点运营者可以读取资源字节和 token 存储,系统没有速率限制,并且依赖 honest-replica/honest-gateway 假设。门禁在 canister 端对每个主机名运行,但其重定向和登录页只有通过 verifying gateway 时才会得到验证,因此绝不要将用户引导至受保护应用的 `raw` URL(陷阱 14)。如需创建分享链接,请使用高熵随机 token;对于新的私有应用,应在首次 sync 之前启用保护(陷阱 13)。完整详情请参阅 [certified-assets 访问保护文档](https://github.com/dfinity/certified-assets/blob/v0.4.3/docs/access-protection.md)。

Authorizing Uploaders

授权上传者

Uploads (sync) are performed by canister controllers and by a separate set of authorized syncer principals. To let a CI/deploy principal sync without giving it full canister control,
authorize
it — do not
--add-controller
, which grants upgrade/settings/delete power far beyond uploading.
bash
undefined
上传(sync)由 canister controllers 和一组独立的 authorized syncer principals 执行。若希望 CI/deploy principal 具备同步权限,而无需授予其完整的 canister 控制权,应使用
authorize
进行授权——不要使用
--add-controller
,因为后者会授予升级、设置和删除等远超上传所需的权限。
bash
undefined

Allow a principal to sync assets (upload), without making it a controller

Allow a principal to sync assets (upload), without making it a controller

icp canister call frontend authorize '(principal "<principal-id>")'
icp canister call frontend authorize '(principal "<principal-id>")'

List authorized syncers

List authorized syncers

icp canister call frontend list_authorized '()'
icp canister call frontend list_authorized '()'

Revoke

Revoke

icp canister call frontend deauthorize '(principal "<principal-id>")'

> **Security Warning:** `icp canister settings update frontend --add-controller <principal-id>` grants full canister control (upgrade wasm, change settings, delete, drain cycles) — not just upload access. Prefer `authorize` for deploy pipelines.
icp canister call frontend deauthorize '(principal "<principal-id>")'

> **安全警告:** `icp canister settings update frontend --add-controller <principal-id>` 会授予完整的 canister 控制权(升级 wasm、修改设置、删除、消耗 cycles),而不仅仅是上传权限。对于部署流水线,应优先使用 `authorize`。

Building Against Canister IDs (
presync
vs
build
)

基于 Canister ID 构建(
presync
与
build
)

build
runs before the canister exists, so it can't know any canister IDs. When a client-side app must bake in the ID of a canister it calls, build it in
presync
— that runs at sync time, once IDs exist, and exports them:
yaml
canisters:
  - name: frontend
    recipe:
      type: "@dfinity/static-site@v0.4.3"
      configuration:
        dir: dist
        presync:
          - npm ci
          # $ICP_CLI_CID_BACKEND is the `backend` canister's principal.
          - VITE_CANISTER_ID_BACKEND=$ICP_CLI_CID_BACKEND npm run build
Variables available to
presync
:
ICP_CLI_CID
(this canister),
ICP_CLI_CID_<NAME>
(each project canister — name upper-cased, non-alphanumerics →
_
, e.g.
backend
→
ICP_CLI_CID_BACKEND
),
ICP_CLI_NETWORK
,
ICP_CLI_ENVIRONMENT
.
Alternatively, read canister IDs at runtime in the browser from the
ic_env
cookie the canister sets on every HTML response (works both locally and on mainnet with no environment branching) — see the
user-sign-in
and
icp-cli
skills for the
safeGetCanisterEnv()
pattern. Prefer the cookie over
fetchRootKey()
.
build
在 canister 存在之前运行,因此无法获知任何 canister ID。如果客户端应用必须写入其所调用 canister 的 ID,应在
presync
中构建——它会在 sync 时、ID 已存在之后运行,并导出这些 ID:
yaml
canisters:
  - name: frontend
    recipe:
      type: "@dfinity/static-site@v0.4.3"
      configuration:
        dir: dist
        presync:
          - npm ci
          # $ICP_CLI_CID_BACKEND is the `backend` canister's principal.
          - VITE_CANISTER_ID_BACKEND=$ICP_CLI_CID_BACKEND npm run build
presync
可用的变量包括:
ICP_CLI_CID
(当前 canister)、
ICP_CLI_CID_<NAME>
(项目中的每个 canister——名称转为大写,非字母数字字符替换为
_
,例如
backend
→
ICP_CLI_CID_BACKEND
)、
ICP_CLI_NETWORK
、
ICP_CLI_ENVIRONMENT
。
另一种方式是在浏览器中于 运行时 从 canister 为每个 HTML 响应设置的
ic_env
cookie 读取 canister ID(本地和主网均适用,无需判断环境)——请参阅
user-sign-in
和
icp-cli
skill,了解
safeGetCanisterEnv()
模式。应优先使用 cookie,而不是
fetchRootKey()
。

What You Get Automatically

自动获得的功能

No configuration needed — on by default:
  • Response certification — every response is certified; a verifying gateway (not
    raw
    ) checks the proof.
  • Clean URLs —
    307
    canonicalization (above).
  • Compression — compressible assets are stored gzip + Brotli alongside the original and negotiated per request via
    Accept-Encoding
    . Compressible means: any
    text/*
    ; any
    +json
    or
    +xml
    suffix (so
    image/svg+xml
    ,
    application/xhtml+xml
    );
    application/javascript
    ,
    application/json
    ,
    application/xml
    ,
    application/wasm
    ; and
    font/*
    except
    woff
    /
    woff2
    (already compressed). An encoding is kept only if it actually came out smaller than the original.
  • ETag /
    304 Not Modified
    — content-hash ETag; unchanged files aren't re-downloaded.
  • A default certified
    404
    — replaceable with your own
    /404.html
    .
  • The
    ic_env
    cookie
    — on HTML responses (as two
    Set-Cookie
    headers,
    Lax
    and
    None; Partitioned
    ), carrying
    PUBLIC_*
    env vars (canister IDs) and the root key for the frontend.
无需任何配置,以下功能默认启用:
  • Response certification——每个响应都会经过认证;verifying gateway(而不是
    raw
    )会检查证明。
  • Clean URL——执行
    307
    规范化(见上文)。
  • 压缩——可压缩资源会以 gzip + Brotli 形式与原文件一并存储,并根据每次请求的
    Accept-Encoding
    进行协商。可压缩内容包括:任意
    text/*
    ;任意以
    +json
    或
    +xml
    结尾的类型(因此包括
    image/svg+xml
    、
    application/xhtml+xml
    );
    application/javascript
    、
    application/json
    、
    application/xml
    、
    application/wasm
    ;以及除
    woff
    /
    woff2
    (已压缩)之外的
    font/*
    。只有当编码后的结果确实小于原文件时,才会保留该编码。
  • ETag /
    304 Not Modified
    ——使用内容哈希 ETag;未变化的文件不会重复下载。
  • 默认的经过认证的
    404
    ——可替换为你自己的
    /404.html
    。
  • ic_env
    cookie
    ——添加到 HTML 响应中(以两个
    Set-Cookie
    标头发出,分别为
    Lax
    和
    None; Partitioned
    ),其中携带
    PUBLIC_*
    环境变量(canister ID)以及前端的 root key。

Deploy & Verify

部署与验证

bash
undefined
bash
undefined

Start the local network

Start the local network

icp network start -d
icp network start -d

Build + deploy everything (or just the frontend)

Build + deploy everything (or just the frontend)

icp deploy icp deploy frontend
icp deploy icp deploy frontend

Mainnet (needs cycles)

Mainnet (needs cycles)

icp deploy -e ic frontend

Re-running `icp deploy` re-syncs: the plugin diffs your directory against the canister and uploads only what changed.

```bash
icp deploy -e ic frontend

再次运行 `icp deploy` 会重新同步:plugin 会比较你的目录与 canister,仅上传发生变化的资源。

```bash

Canister is running

Canister is running

icp canister status frontend # Status: Running, non-zero memory
icp canister status frontend # Status: Running, non-zero memory

Get the canister ID (there is no
icp canister id
; use status --id-only)

Get the canister ID (there is no
icp canister id
; use status --id-only)

icp canister status frontend --id-only
icp canister status frontend --id-only

Fetch the index page (certified)

Fetch the index page (certified)

icp canister call frontend http_request '(record { url = "/"; method = "GET"; body = vec {}; headers = vec {}; certificate_version = opt 2; })' # → status_code = 200
icp canister call frontend http_request '(record { url = "/"; method = "GET"; body = vec {}; headers = vec {}; certificate_version = opt 2; })' # → status_code = 200

SPA fallback returns the shell, not 404

SPA fallback returns the shell, not 404

icp canister call frontend http_request '(record { url = "/dashboard/settings"; method = "GET"; body = vec {}; headers = vec {}; certificate_version = opt 2; })' # → 200 (index.html), NOT 404
icp canister call frontend http_request '(record { url = "/dashboard/settings"; method = "GET"; body = vec {}; headers = vec {}; certificate_version = opt 2; })' # → 200 (index.html), NOT 404

Open in a browser (this is the URL
icp deploy
prints)

Open in a browser (this is the URL
icp deploy
prints)

Mainnet: https://<frontend-canister-id>.icp.net

Mainnet: https://<frontend-canister-id>.icp.net

undefined
undefined

Verifying Deployed Contents (state hash)

验证已部署内容(state hash)

Certification proves responses match what the canister committed to; the state hash proves what it committed to matches a build reproduced from public source. The hash
icp deploy
prints (
canister reports state hash <hex>
) comes from the canister itself — a deploy self-consistency check, not third-party verification. To verify a canister:
bash
undefined
Certification 证明响应与 canister 已提交的内容一致;state hash 则证明 canister 提交的内容 与根据公开源代码复现出的构建结果一致。
icp deploy
输出的哈希(
canister reports state hash <hex>
)来自 canister 本身——这是部署期间的自一致性检查,不是第三方验证。如需验证 canister:
bash
undefined

1. Reproduce the build from source at the deployed version → ./dist (incl. _headers/_redirects)

1. Reproduce the build from source at the deployed version → ./dist (incl. _headers/_redirects)

2. Ask the canister its release, then build the verifier from THAT tag.

2. Ask the canister its release, then build the verifier from THAT tag.

Not published as a binary or on crates.io. --locked is required: Cargo.lock pins the

Not published as a binary or on crates.io. --locked is required: Cargo.lock pins the

compressor builds whose output bytes the hash covers; without it the hash differs.

compressor builds whose output bytes the hash covers; without it the hash differs.

icp canister call <canister-id> version '()' -n ic --query
icp canister call <canister-id> version '()' -n ic --query

(record { major = 0 : nat32; minor = 4 : nat32; patch = 3 : nat32 })

(record { major = 0 : nat32; minor = 4 : nat32; patch = 3 : nat32 })

cargo install --git https://github.com/dfinity/certified-assets --tag v0.4.3 --locked state-hash-cli
cargo install --git https://github.com/dfinity/certified-assets --tag v0.4.3 --locked state-hash-cli

3. Compute the hash locally (prints 64 hex chars)

3. Compute the hash locally (prints 64 hex chars)

state-hash ./dist
state-hash ./dist

4. Read the canister's hash (an update call, so consensus-backed); the hash is the last 32 bytes

4. Read the canister's hash (an update call, so consensus-backed); the hash is the last 32 bytes

icp canister call <canister-id> state_hash '()' -n ic -o hex | tail -c 65

- Target the canister by **principal** with `-n <network>`; `-e <environment>` resolves a canister *name* from a local project, which a third-party verifier doesn't have. Pass `'()'` explicitly.
- **32 zero bytes is not a hash**: the canister has never finished a sync, or one is in progress (a sync drops the cached hash when it starts). Re-read after the deploy completes.
- A mismatch means content, headers, or redirects differ from the source — or the canister was prepared with non-standard compressors (platforms embedding the crates may do this; the tool only reproduces what `icp deploy` does).
- **Not covered by the hash:** the `ic_env` cookie (a controller can repoint a frontend's backend canister ID via env vars with a byte-identical build) and access protection (a matching hash says the canister holds your build, not that a visitor can reach it).
icp canister call <canister-id> state_hash '()' -n ic -o hex | tail -c 65

- 使用 `-n <network>` 通过 **principal** 定位 canister;`-e <environment>` 会从本地项目中解析 canister *名称*,而第三方验证者没有这些名称。请显式传入 `'()'`。
- **32 个零字节不是哈希**:说明 canister 从未完成 sync,或 sync 正在进行(sync 开始时会清除缓存的哈希)。请在部署完成后重新读取。
- 哈希不匹配意味着内容、标头或重定向与源代码存在差异——或者 canister 使用非标准 compressor 进行了准备(嵌入这些 crate 的平台可能会这样做;该工具只会复现 `icp deploy` 的行为)。
- **哈希不涵盖以下内容:** `ic_env` cookie(controller 可以通过环境变量重新指向前端后端 canister 的 ID,同时保持构建结果逐字节相同)以及访问保护(匹配的哈希表示 canister 持有你的构建结果,并不表示访问者一定能够访问它)。

Legacy Asset Canister and Migration

Legacy Asset Canister 与迁移

  • Maintaining an existing
    @dfinity/asset-canister
    project
    (
    .ic-assets.json5
    ,
    AssetManager
    uploads,
    grant_permission
    roles,
    allow_raw_access
    ): see
    references/legacy-asset-canister.md
    .
  • Moving an existing asset-canister project to certified-assets / static-site: see
    references/migrating-from-asset-canister.md
    for the config mapping and the reinstall-mode caveat.
  • 维护现有
    @dfinity/asset-canister
    项目
    (
    .ic-assets.json5
    、
    AssetManager
    上传、
    grant_permission
    角色、
    allow_raw_access
    ):请参阅
    references/legacy-asset-canister.md
    。
  • 将现有 asset-canister 项目迁移到 certified-assets / static-site:有关配置映射和 reinstall-mode 注意事项,请参阅
    references/migrating-from-asset-canister.md
    。

Additional References

其他参考

  • Load
    icp-cli
    for the recipe system,
    icp.yaml
    structure, canister-ID injection, and the
    ic_env
    cookie /
    safeGetCanisterEnv()
    pattern.
  • Load
    custom-domains
    for DNS records, ACME challenge, and TLS provisioning of a custom domain.
  • Load
    user-sign-in
    for reading the root key and canister IDs from
    ic_env
    in a frontend.
  • Full upstream user docs: certified-assets docs.
  • 加载
    icp-cli
    ,了解 recipe 系统、
    icp.yaml
    结构、canister ID 注入以及
    ic_env
    cookie /
    safeGetCanisterEnv()
    模式。
  • 加载
    custom-domains
    ,了解自定义域名的 DNS 记录、ACME challenge 和 TLS 配置。
  • 加载
    user-sign-in
    ,了解如何在前端从
    ic_env
    读取 root key 和 canister ID。
  • 完整的上游用户文档:certified-assets docs。