めも: Sveltekit x Cloudflare

Platform えらび

Netlify, Vercel, Cloudflare etc. でデプロイできるんだけど、R2 を使っていたので Cloudflare にした。Worker vs Pages だと、Pages の方が github 連携できて便利だよ、って書いてあったので Pages にした。

nodejs_compat 問題

crypto を使っていたので出た。これはシンプルにダッシュボードで、 Workers & Pages > Functions からフラグを設定すればおk

Buffer is not defined

vite.config.js を入れるとか pollyfil パッケージを入れるとか色々でてきたんだけど、polyfill パッケージが deprecated になっていたり[1]、development でコケ始めたりして面倒になったので一番シンプルな方法[2]にした。

[1] https://github.com/remorses/esbuild-plugins
[2] https://github.com/vitejs/vite/discussions/2785

i.e.

  1. run npm i buffer
  2. add import { Buffer } from 'buffer' in your file

entrypoint に globals.Buffer = Buffer ってかくのが元のリンクには書いてあったのだが、Sveltekit の entrypoint とは..? から始まるのでいったん該当ファイルに記述した。

しかし、nodejs_compat もオンにして +pages.server.ts からしか呼ばないファイルなのに、なんで "Buffer is not defined" が出るのかよくわかんない

Retry build

Cloudflare Pages でビルドがコケると Retry build っていうボタンを押されるんだけど、どうやら環境変数は元のビルドと同じものが使われるっぽい。なので、「環境変数を設定し忘れてたからビルドがコケた」っていうときは Retry だとだめ。

Environment Variables

Cloudflare Pages/Workers/Functions には Environment Variables が設定できる.. っていうのはだいたいのホスティングプラットフォームにあるけど、Environment Variables を "encrypt" できるのが Cloudflare Pages/Workers/Functions の特徴。

encrypt された environment variable = secret

Secrets are environment variables.

The difference is secret values are not visible within Wrangler or dashboard interfaces after you define them. This means that sensitive data, including passwords or API tokens, should always be encrypted to prevent data leaks.

なんだが、アプリケーションから見ると同じで、とくに derypt したりする必要はない

To your Worker, there is no difference between an environment variable and a secret. The secret’s value is passed through as defined.

https://blog.cloudflare.com/secrets-store:

Sveltekit では、PUBLIC_xx 系は Environment Variables にそのまま保存して、private variables は encrypt するっていうのがいいかも? (自分はそうした)

Secret Store との違いでいうと、 Secret Store は「secrets が Workers でしか使えない・複数の Workers をまたがって共有できない」という問題を解決するためのサービス。

念のため Discord で聞いてみたら、cloudflare の人が答えてくれた

1) No, the service will automatically decrypt the variable at runtime for use in your application. Only invocations of your application can retrieve the secret, it can't be accessed by other means

2) Yes, that is the use-case it's designed for and has the required security in place that it should be fine. Just keep note of the fact it's available at runtime and so anyone who can change the code of the project can theoretically exfiltrate the key. Usually that isn't worth worrying about however

調べた結果の考えとあってて、

  • app での decrypt はいらない
  • secret を保存するためのもの