WebAssembly と WebSockets による SFTP とブラウザーの橋渡し
Node.js ゲートウェイを使い、SSH 認証情報をサーバー側に保持したまま、アクセスを許可された小規模な SFTP カタログの一覧表示とダウンロードをブラウザーから行います。このチュートリアルには使い捨ての OpenSSH サーバーとローカルトークン発行機能が含まれ、ブラウザーから SFTP までの経路全体を手元のマシンで試せます。
SSH の終端の選択
SFTP は通常、TCP 上の SSH 内で動作します。ブラウザーの WebSocket は HTTP ハンドシェイクを使い、WebSocket フレームを転送します。ポート 22 に接続しても SSH ソケットにはなりません。WebAssembly で SSH コードを実行することはできますが、通常の Web ページにネイティブ TCP ソケットが提供されるわけではありません。
ブラウザー側で SSH を実行する場合、トランスポートプロキシがネットワーク接続を提供し、ブラウザーが SSH ホストとユーザーを認証します。HTTP API ゲートウェイでは、SSH はゲートウェイで終端し、ゲートウェイがアプリケーションの各操作を認可します。以下の例では後者を採用します。公開ファイル ID を 1 つ持つ固定カタログを使い、ブラウザーからパスや接続先を指定することはできず、sftp:read スコープを必須とします。
ゲートウェイプロジェクトの作成
このローカル実行例は Linux 上で、Node.js 24.22.1 と
26.12.1、Yarn 4.12.0、OpenSSH 9.2、Chromium 152 を使って検証しました。この構成はメンテナンス中の Node 24 または 26 リリースを対象とし、上記のパッチ番号は検証済みのバージョンを示します。ランチャーは Node 組み込みの TypeScript サポートを使います。Docker Engine と OpenSSH クライアントツールを別途インストールし、node、curl、docker、ssh-keygen に PATH が通っていることを確認してください。ランチャーは /var/run/docker.sock にあるローカルの Docker ソケットを使い、ホストの SSH デーモンを起動することはありません。
以下を POSIX シェルに貼り付けてください。新しいディレクトリを作成し、親が Yarn プロジェクトの場合も専用の Yarn キャッシュとロックファイルを使います。サブシェルを使うため、現在のディレクトリとオプションは変わりません。sftp-browser-demo ディレクトリがすでに存在する場合は処理を拒否します。
(
command -v node >/dev/null && command -v curl >/dev/null &&
command -v docker >/dev/null && command -v ssh-keygen >/dev/null &&
mkdir sftp-browser-demo && cd sftp-browser-demo &&
printf '%s\n' '{"private":true,"type":"module","packageManager":"yarn@4.12.0","dependencies":{"express":"5.2.1","helmet":"8.3.0","jose":"6.2.12","ssh2-sftp-client":"12.1.1"}}' > package.json &&
printf '%s\n' 'nodeLinker: node-modules' 'ignorePath: true' 'enableGlobalCache: false' 'cacheFolder: .yarn/cache' 'globalFolder: .yarn/global' 'installStatePath: .yarn/install-state.gz' 'enableTelemetry: false' 'injectEnvironmentFiles: []' > .yarnrc.yml &&
touch yarn.lock &&
curl -fsSLo yarn-4.12.0.cjs https://repo.yarnpkg.com/4.12.0/packages/yarnpkg-cli/bin/yarn.js &&
node yarn-4.12.0.cjs install
)
以降のファイルをすべて sftp-browser-demo 内に作成してください。インストールに失敗した場合はパッケージファイルを残し、報告された依存関係またはネットワークの問題を修正して、親ディレクトリからインストールを再試行してください。
(cd sftp-browser-demo &&
curl -fsSLo yarn-4.12.0.cjs https://repo.yarnpkg.com/4.12.0/packages/yarnpkg-cli/bin/yarn.js &&
node yarn-4.12.0.cjs install)
初回の CLI ダウンロードが失敗した場合は、再試行時に CLI も再ダウンロードします。上位の ES モジュールプロジェクトによって解釈が変わらないよう、CLI は .cjs として保存します。
固定カタログの認可と読み取り
以下を index.mjs として保存してください。バージョンを固定した SFTP ライブラリ が、正規パス、ファイル属性、ストリームの API を提供します。ファイルは空でも構いませんが、上限は 5 MiB です。ゲートウェイはプロセスごとに 2 件の同時ダウンロードを許可します。各ダウンロードでは、SFTP 接続、読み取り、HTTP 配信に合計 30 秒を割り当てます。サイズ制限内のファイルをバッファーに格納してから HTTP の成功応答を送るため、途中まで進んでから SFTP エラーが発生した場合も、ダウンロードは失敗として扱われます。
import { randomUUID } from 'node:crypto'
import { createConnection } from 'node:net'
import { Readable, Transform, Writable } from 'node:stream'
import { pipeline } from 'node:stream/promises'
import { fileURLToPath } from 'node:url'
import express from 'express'
import helmet from 'helmet'
import { importSPKI, jwtVerify } from 'jose'
import SftpClient from 'ssh2-sftp-client'
const {
APP_ORIGIN, JWT_PUBLIC_KEY, JWT_ISSUER, JWT_AUDIENCE,
SFTP_HOST, SFTP_USERNAME, SFTP_PRIVATE_KEY, SFTP_HOST_SHA256,
} = process.env
if (!APP_ORIGIN || !JWT_PUBLIC_KEY || !JWT_ISSUER || !JWT_AUDIENCE ||
!SFTP_HOST || !SFTP_USERNAME || !SFTP_PRIVATE_KEY ||
!/^[a-f0-9]{64}$/.test(SFTP_HOST_SHA256 ?? '')) {
throw new Error('Gateway configuration is incomplete')
}
const sshPort = Number(process.env.SFTP_PORT ?? 22)
if (!Number.isInteger(sshPort) || sshPort < 1 || sshPort > 65535) {
throw new Error('Invalid SFTP port')
}
const key = await importSPKI(JWT_PUBLIC_KEY, 'RS256')
const webOrigin = new URL(APP_ORIGIN)
const localHttp = webOrigin.protocol === 'http:' &&
['localhost', '127.0.0.1', '[::1]'].includes(webOrigin.hostname)
if (webOrigin.origin !== APP_ORIGIN || (!localHttp && webOrigin.protocol !== 'https:')) {
throw new Error('Use an HTTPS origin or loopback HTTP for local development')
}
const catalog = new Map([
['report', { label: 'Sample file', path: '/exports/report.bin' }],
])
const maxBytes = 5 * 1024 * 1024
let active = 0
export const app = express()
app.disable('x-powered-by')
app.use(helmet({
contentSecurityPolicy: {
// Keep local Safari from upgrading this demo's HTTP assets to HTTPS.
directives: { 'upgrade-insecure-requests': localHttp ? null : [] },
},
strictTransportSecurity: localHttp ? false : undefined,
}))
app.use((_req, res, next) => {
res.locals.requestId = randomUUID()
res.set('X-Request-ID', res.locals.requestId)
res.set('Cache-Control', 'no-store')
next()
})
app.use('/files', async (req, res, next) => {
// Same-origin fetches may omit Origin on GET. Require a custom header and disable CORS.
const origin = req.get('origin')
if ((origin && origin !== APP_ORIGIN) || req.get('X-SFTP-Client') !== 'browser' ||
req.get('sec-fetch-site') === 'cross-site' || Object.keys(req.query).length !== 0) {
return res.status(403).json({ error: 'Request not allowed' })
}
try {
const match = /^Bearer ([A-Za-z0-9_.-]+)$/.exec(req.get('authorization') ?? '')
if (!match) return res.status(401).json({ error: 'Authentication required' })
const { payload } = await jwtVerify(match[1], key, {
algorithms: ['RS256'], issuer: JWT_ISSUER, audience: JWT_AUDIENCE,
requiredClaims: ['sub', 'exp', 'iat'], maxTokenAge: '15m',
})
if (typeof payload.scope !== 'string' || !payload.scope.split(' ').includes('sftp:read')) {
return res.status(403).json({ error: 'Permission denied' })
}
} catch {
return res.status(401).json({ error: 'Invalid access token' })
}
next()
})
app.get('/files', (_req, res) => {
res.json(Array.from(catalog, ([id, item]) => ({ id, label: item.label })))
})
app.get('/files/:id', async (req, res) => {
const item = catalog.get(req.params.id)
if (!item) return res.status(404).json({ error: 'File not found' })
if (active >= 2) return res.status(503).json({ error: 'Gateway busy' })
active += 1
const abort = new AbortController()
const sftp = new SftpClient('gateway', {
error: () => abort.abort(),
end: () => abort.abort(),
close: () => abort.abort(),
})
const timer = setTimeout(() => abort.abort(), 30_000)
const disconnect = () => { if (!res.writableFinished) abort.abort() }
res.once('close', disconnect)
const socket = createConnection({ host: SFTP_HOST, port: sshPort })
socket.on('error', () => {})
const cancelSocket = () => socket.destroy()
abort.signal.addEventListener('abort', cancelSocket)
try {
await sftp.connect({
sock: socket, username: SFTP_USERNAME, privateKey: SFTP_PRIVATE_KEY,
hostHash: 'sha256', hostVerifier: (hash) => hash === SFTP_HOST_SHA256,
readyTimeout: 10_000,
})
if (await sftp.realPath(item.path) !== item.path) throw new Error('Unexpected path')
const info = await sftp.lstat(item.path)
if (!info.isFile || info.isSymbolicLink || !Number.isSafeInteger(info.size) ||
info.size < 0 || info.size > maxBytes) throw new Error('Invalid file')
abort.signal.throwIfAborted()
let received = 0
const limit = new Transform({
transform(chunk, _encoding, callback) {
received += chunk.length
callback(received > info.size ? new Error('Byte limit exceeded') : null, chunk)
},
flush(callback) {
callback(received !== info.size ? new Error('Incomplete file') : null)
},
})
// With files this small, finish SFTP before committing an HTTP success response.
const chunks = []
const sink = new Writable({
write(chunk, _encoding, callback) { chunks.push(chunk); callback() },
})
await pipeline(sftp.createReadStream(item.path), limit, sink, { signal: abort.signal })
abort.signal.throwIfAborted()
res.set('Content-Type', 'application/octet-stream')
res.set('Content-Disposition', 'attachment; filename="' + req.params.id + '.bin"')
res.set('Content-Length', String(received))
await pipeline(Readable.from([Buffer.concat(chunks, received)]), res, { signal: abort.signal })
} catch {
console.error(JSON.stringify({ event: 'download_failed', requestId: res.locals.requestId }))
if (!res.headersSent && !res.destroyed) {
res.removeHeader('Content-Length')
res.removeHeader('Content-Disposition')
res.status(502).json({ error: 'Download failed', requestId: res.locals.requestId })
} else {
res.destroy()
}
} finally {
socket.destroy()
await sftp.end().catch(() => {})
clearTimeout(timer)
res.off('close', disconnect)
abort.signal.removeEventListener('abort', cancelSocket)
active -= 1
}
})
app.use(express.static(fileURLToPath(new URL('./public/', import.meta.url))))
app.use((_error, _req, res, _next) => {
if (!res.headersSent) res.status(500).json({ error: 'Request failed' })
})
const port = Number(process.env.PORT ?? 3000)
if (!Number.isInteger(port) || port < 0 || port > 65535) throw new Error('Invalid HTTP port')
const server = app.listen(port, '127.0.0.1', (error) => {
if (error) {
console.error('Gateway could not listen; check PORT and whether it is in use')
process.exitCode = 1
return
}
console.log('Open ' + APP_ORIGIN)
})
server.requestTimeout = 35_000
server.headersTimeout = 10_000
ブラウザーの接続
先に public ディレクトリを作成してから、以下を public/index.html として保存してください。トークン欄はこのローカル演習用です。ページに共有 SSH 認証情報は埋め込まれていません。
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="color-scheme" content="light dark" />
<title>SFTP file browser</title>
</head>
<body>
<h1>SFTP files</h1>
<label>Your access token <input id="token" type="password" autocomplete="off" /></label>
<button id="list" type="button">List available files</button>
<ul id="files"></ul>
<p id="status" role="status"></p>
<script src="/files.js" defer></script>
</body>
</html>
以下を public/files.js として保存してください。ページは各リクエスト中に入力欄を無効化し、ダウンロード用オブジェクト URL を最大 1 つ保持します。カタログのリクエストが失敗すると、前の一覧を消去します。
const token = document.getElementById('token')
const list = document.getElementById('list')
const files = document.getElementById('files')
const status = document.getElementById('status')
let busy = false
let downloadUrl
function setBusy(value) {
busy = value
token.disabled = value
for (const button of document.querySelectorAll('button')) button.disabled = value
}
window.addEventListener('pagehide', () => {
if (downloadUrl) URL.revokeObjectURL(downloadUrl)
})
async function api(path) {
const response = await fetch(path, {
headers: {
Authorization: 'Bearer ' + token.value,
'X-SFTP-Client': 'browser',
},
signal: AbortSignal.timeout(35_000),
})
if (!response.ok) throw new Error('Request rejected')
return response
}
list.addEventListener('click', async () => {
if (busy) return
setBusy(true)
status.textContent = 'Loading files…'
files.replaceChildren()
try {
const response = await api('/files')
const catalog = await response.json()
for (const item of catalog) {
const li = document.createElement('li')
const button = document.createElement('button')
button.type = 'button'
button.textContent = 'Download ' + item.label
button.addEventListener('click', async () => {
if (busy) return
setBusy(true)
status.textContent = 'Downloading…'
try {
const result = await api('/files/' + encodeURIComponent(item.id))
const blob = await result.blob()
if (downloadUrl) URL.revokeObjectURL(downloadUrl)
downloadUrl = URL.createObjectURL(blob)
const link = document.createElement('a')
link.href = downloadUrl
link.download = item.id + '.bin'
link.click()
status.textContent = 'Download received.'
} catch {
status.textContent = 'Download failed.'
} finally {
setBusy(false)
}
})
li.append(button)
files.append(li)
}
status.textContent = 'Available files loaded.'
} catch {
status.textContent = 'Could not load files.'
} finally {
setBusy(false)
}
})
ローカル SFTP サーバーとトークンの用意
以下を sftp-server.Dockerfile として保存してください。パッケージのインストールは自分で管理するコンテナーイメージ内で行い、ランチャーはこの Dockerfile と SSH 設定だけをビルドコンテキストにコピーします。鍵とトークンは後で生成され、イメージには一切入りません。
FROM node:26.12.1-bookworm-slim
RUN apt-get update && apt-get install -y --no-install-recommends openssh-server && \
rm -rf /var/lib/apt/lists/* /etc/ssh/ssh_host_* && \
useradd --uid 10001 --home-dir /exports --shell /usr/sbin/nologin fixture && \
passwd -d fixture && mkdir -p /srv/sftp/exports && chmod 755 /srv/sftp
COPY sshd_config /etc/ssh/demo_config
CMD ["sh", "-c", "mkdir -p /run/sshd && cp /fixture/host-key /run/host-key && chmod 600 /run/host-key && cp /fixture/client-key.pub /run/authorized_keys && chmod 644 /run/authorized_keys && timeout --signal=TERM --kill-after=5 600 /usr/sbin/sshd -D -e -f /etc/ssh/demo_config"]
以下を sshd_config として保存してください。デモコンテナーの SSH 設定全体を置き換えるため、ディストリビューションの設定ファイルは読み込みません。アカウントには chroot を適用し、internal-sftp -R が書き込みを拒否します。
Port 22
ListenAddress 0.0.0.0
HostKey /run/host-key
PidFile /run/sshd.pid
AuthorizedKeysFile /run/authorized_keys
StrictModes yes
AllowUsers fixture
PermitRootLogin no
PubkeyAuthentication yes
AuthenticationMethods publickey
PasswordAuthentication no
KbdInteractiveAuthentication no
UsePAM no
AllowAgentForwarding no
AllowTcpForwarding no
PermitTunnel no
X11Forwarding no
PermitTTY no
PermitUserRC no
Subsystem sftp internal-sftp
Match User fixture
ChrootDirectory /srv/sftp
ForceCommand internal-sftp -R -d /exports
以下を demo.ts として保存してください。新しい SSH 鍵を作成し、信頼するローカルホスト鍵のピン留め値を計算し、有効期間 5 分の RS256 トークンを発行して、両サービスを空いているループバックポートで起動します。トークンは非公開ファイルに保持します。追加の 2 つのトークンで、スコープ不正と期限切れを試します。この発行機能は JWT の仕様を実演するもので、ホスト型 ID プロバイダーとの連携を検証するものではありません。
import { type ChildProcess, execFile, spawn } from 'node:child_process'
import { createHash, randomUUID } from 'node:crypto'
import { chmod, copyFile, mkdir, readFile, rm, writeFile } from 'node:fs/promises'
import { createConnection, createServer } from 'node:net'
import { join } from 'node:path'
import { setTimeout as pause } from 'node:timers/promises'
import { promisify } from 'node:util'
import { exportSPKI, generateKeyPair, SignJWT } from 'jose'
const root = import.meta.dirname
const state = join(root, '.demo')
const owner = randomUUID()
const name = 'sftp-browser-' + owner
const exec = promisify(execFile)
await mkdir(state, { mode: 0o700 }) // Refuse an existing directory; never clear someone else's state.
const environment = { PATH: process.env.PATH, DOCKER_HOST: 'unix:///var/run/docker.sock',
DOCKER_CONFIG: join(state, 'docker') }
async function command(file: string, args: string[]): Promise<{ stdout: string; stderr: string }> {
return exec(file, args, { cwd: root, env: environment, timeout: 240_000, maxBuffer: 8 * 1024 * 1024 })
}
const docker = (args: string[]) => command('docker', args)
let gateway: ChildProcess | undefined
let imageBuilt = false
let stopped = false
const stop = () => { stopped = true; gateway?.kill('SIGTERM') }
process.once('SIGINT', stop)
process.once('SIGTERM', stop)
const lifetime = setTimeout(stop, 10 * 60_000)
try {
await writeFile(join(state, 'resources.json'), JSON.stringify({ owner, name }) + '\n', { mode: 0o600 })
for (const dir of ['docker', 'build', 'exports']) await mkdir(join(state, dir))
await copyFile(join(root, 'sftp-server.Dockerfile'), join(state, 'build', 'Dockerfile'))
await copyFile(join(root, 'sshd_config'), join(state, 'build', 'sshd_config'))
await docker(['build', '--tag', name, join(state, 'build')])
imageBuilt = true
if (stopped) throw new Error('Demo was stopped during startup')
for (const key of ['host-key', 'client-key']) {
await command('ssh-keygen', ['-q', '-t', 'ed25519', '-N', '', '-f', join(state, key)])
}
if (stopped) throw new Error('Demo was stopped during startup')
// A deterministic binary sample, including NUL bytes and content beyond the first read.
const sample = Buffer.from(Array.from({ length: 65_568 }, (_, i) => i % 251))
await writeFile(join(state, 'exports', 'report.bin'), sample, { mode: 0o644 })
await chmod(join(state, 'exports'), 0o755)
const publicHost = (await readFile(join(state, 'host-key.pub'), 'utf8')).split(' ')[1]
if (!publicHost) throw new Error('Missing host public key')
const pin = createHash('sha256').update(Buffer.from(publicHost, 'base64')).digest('hex')
await docker(['run', '--detach', '--rm', '--name', name, '--label', 'sftp.demo.owner=' + owner,
'--read-only', '--tmpfs', '/run', '-p', '127.0.0.1::22',
'--mount', `type=bind,src=${state},dst=/fixture,readonly`,
'--mount', `type=bind,src=${join(state, 'exports')},dst=/srv/sftp/exports,readonly`, name])
const sshPort = Number((await docker(['port', name, '22/tcp'])).stdout.trim().split(':').at(-1))
if (!Number.isInteger(sshPort) || sshPort < 1 || sshPort > 65535) throw new Error('Invalid published SSH port')
let ready = false
for (let attempt = 0; attempt < 40 && !stopped; attempt++) {
ready = await new Promise<boolean>((resolve) => {
const socket = createConnection({ host: '127.0.0.1', port: sshPort })
socket.setTimeout(500)
const done = (ok: boolean) => { socket.destroy(); resolve(ok) }
socket.once('data', (data) => done(data.toString().startsWith('SSH-2.0-OpenSSH_')))
socket.once('error', () => done(false))
socket.once('timeout', () => done(false))
})
if (ready) break
await pause(100)
}
if (!ready || stopped) throw new Error('Demo SSH server did not become ready')
const probe = createServer()
await new Promise<void>((resolve) => probe.listen(0, '127.0.0.1', resolve))
const address = probe.address()
if (!address || typeof address === 'string') throw new Error('Missing HTTP port')
const port = address.port
await new Promise<void>((resolve) => probe.close(() => resolve()))
const { publicKey, privateKey } = await generateKeyPair('RS256')
const now = Math.floor(Date.now() / 1000)
for (const [file, scope, expiry] of [
['token.txt', 'sftp:read', now + 300],
['wrong-scope.txt', 'sftp:upload', now + 300],
['expired.txt', 'sftp:read', now - 60],
] satisfies [string, string, number][]) {
const access = await new SignJWT({ scope }).setProtectedHeader({ alg: 'RS256' })
.setSubject('local-reader').setIssuer('urn:sftp-browser-demo').setAudience('sftp-browser')
.setIssuedAt(now).setExpirationTime(expiry).sign(privateKey)
await writeFile(join(state, file), access + '\n', { mode: 0o600 })
}
const jwtPublicKey = await exportSPKI(publicKey)
await writeFile(join(state, 'jwt-public.pem'), jwtPublicKey, { mode: 0o600 })
console.log('Copy the token from ' + join(state, 'token.txt'))
console.log('Sample SHA-256: ' + createHash('sha256').update(sample).digest('hex'))
if (stopped) throw new Error('Demo was stopped before gateway startup')
gateway = spawn(process.execPath, [join(root, 'index.mjs')], { stdio: 'inherit', env: {
PATH: process.env.PATH, APP_ORIGIN: 'http://127.0.0.1:' + port, PORT: String(port),
JWT_PUBLIC_KEY: jwtPublicKey, JWT_ISSUER: 'urn:sftp-browser-demo',
JWT_AUDIENCE: 'sftp-browser', SFTP_HOST: '127.0.0.1', SFTP_PORT: String(sshPort),
SFTP_USERNAME: 'fixture', SFTP_PRIVATE_KEY: await readFile(join(state, 'client-key'), 'utf8'),
SFTP_HOST_SHA256: pin,
} })
const child = gateway
const exit = await new Promise<number | null>((resolve, reject) => {
child.once('error', reject)
child.once('exit', (code) => resolve(code))
})
if (!stopped && exit !== 0) throw new Error('Gateway exited unsuccessfully')
} finally {
clearTimeout(lifetime)
process.off('SIGINT', stop)
process.off('SIGTERM', stop)
gateway?.kill('SIGTERM')
// The UUID and label restrict cleanup to the container this invocation created.
const existing = await docker(['inspect', '--format', '{{ index .Config.Labels "sftp.demo.owner" }}', name]).catch(() => null)
if (existing?.stdout.trim() === owner) await docker(['rm', '--force', name])
if (imageBuilt) await docker(['image', 'rm', name])
await rm(state, { recursive: true })
}
親ディレクトリから、ランチャーをフォアグラウンドで実行してください。
node sftp-browser-demo/demo.ts
ゲートウェイが出力した URL を開いてください。sftp-browser-demo/.demo/token.txt からトークンをコピーして
Your access token に貼り付け、List available files、Download Sample file の順にクリックしてください。Download received. は、ブラウザーが HTTP 本文全体を受信し、ダウンロードを開始したことを示します。ブラウザーのダウンロード一覧で保存されたファイルを確認してください。ページからは、ファイルをディスクに保存したかどうかを確認できません。
サンプルは 65,568 バイトのバイナリデータです。保存した report.bin の SHA-256 を、ランチャーが出力した Sample SHA-256: と比較してください。以下をプロジェクト内に verify-download.ts として保存してください。
import { createHash } from 'node:crypto'
import { readFile } from 'node:fs/promises'
const path = process.argv[2]
const expected = process.argv[3]
if (!path || !/^[a-f0-9]{64}$/.test(expected ?? '')) throw new Error('Supply a file and SHA-256')
const actual = createHash('sha256').update(await readFile(path)).digest('hex')
if (actual !== expected) throw new Error('Downloaded bytes do not match')
console.log('Downloaded bytes match')
実際のダウンロード先パスと、出力されたダイジェストを引数として渡してください。
node sftp-browser-demo/verify-download.ts "$HOME/Downloads/report.bin" YOUR_PRINTED_SHA256
401 は、トークンの期限切れなどにより認証が拒否されたことを示します。403 は、リクエストのオリジン、クライアントヘッダー、クエリ、スコープのいずれかが拒否されたことを示します。502 は、ホスト鍵の不一致、シンボリックリンク、サイズ超過、接続切断などにより、ゲートウェイが SFTP の読み取りを確認できなかったことを示します。.demo/wrong-scope.txt と .demo/expired.txt のトークンを試してください。どちらのカタログリクエストも失敗しなければなりません。トークンの期限が切れたら、デモを停止して再起動し、新しいトークンを取得してください。
ランチャーのターミナルで Ctrl+C を押すと、ゲートウェイを停止し、コンテナー、イメージタグ、鍵、トークンを削除します。デモは 10 分後にも停止します。プロジェクトと保存したダウンロードファイルは残ります。起動中のクリーンアップでは、実行中のビルドまたは Docker コマンドが完了するまで待機します。各コマンドのタイムアウトは 4 分です。通常の即時終了を行うには、起動が完了してからデモを停止してください。クリーンアップが中断されると、.demo が残る場合があります。.demo/resources.json を調べ、コンテナーの sftp.demo.owner ラベルを確認してから、そのコンテナーとイメージタグを手動で削除してください。続いて .demo を削除してください。残っていると、ランチャーは次回実行時に上書きを拒否します。
自分の SFTP アカウントへのゲートウェイの適用
demo.ts と同じサーバー専用の環境変数に、検証済みの発行者、オーディエンス、公開鍵を設定してください。SFTP_HOST_SHA256 には、ssh2 のホスト検証機能 が要求する形式で、管理者が検証した SSH ホスト公開鍵の生データの SHA-256 を、小文字の 64 文字の 16 進数で設定してください。OpenSSH の SHA256:base64 フィンガープリントはエンコーディングが異なるため、このフィールドには貼り付けられません。
カタログのファイルを変更できるのは、信頼できる公開者だけに限定し、不変のファイルをアトミックに公開してください。正規パスと lstat() のチェックでは、悪意のある書き込み元が後続のオープン処理との競合を仕掛けることを防げません。また、バイト数では同じ長さのコンテンツへの置換を検出できません。有効な sftp:read トークンはすべて、設定済みのカタログ全体を読み取れます。複数のテナントに対応するには、検証済みのサーバー側認可レコードに基づく、テナントごとに分離したカタログと SSH アカウントが必要です。
ブラウザーとの接続境界では HTTPS を使い、SSH ホスト鍵の検証を維持してください。ブラウザーはカスタムヘッダーを付けて同一オリジンの API にリクエストし、ゲートウェイは CORS アクセスを一切許可しません。オリジンチェックはトークンによる認可を補完しますが、ブラウザー以外の呼び出し元を認証するものではありません。同時ダウンロード 2 件という制限は、単一の Node プロセスに適用されます。バッファリングには、これらのファイルに加え、コピーとプロトコルのオーバーヘッド分のメモリが必要です。デプロイ全体のクォータとコンテンツのセキュリティスキャンは、別途検討する必要があります。
ブラウザー側 SSH という代替案の選択
ユーザーごとに独自の SSH セッションが必要な場合、hullarb/ssheasy は、Go/WebAssembly クライアントと WebSocket から TCP へのプロキシ、フロントエンドをまとめて構築します。c2FmZQ/sshterm は、SFTP アップロードとダウンロード、SSH 鍵管理、tlsproxy WebSocket エンドポイントを備えた、完全な Go/WASM アプリケーションです。各アプリケーションのデプロイ仕様とホスト検証仕様に従ってください。これらはアーキテクチャの参考例であり、この例でインストールしたり動作検証したりするライブラリではありません。ここではベンチマークを行っていません。実際のワークロードで起動コストと転送遅延を測定してください。
以前の sftp-ws プロジェクトは、SSH ではなく WebSockets 上で SFTP v3 を転送し、README ではテストが不十分であると警告しています。既存の SSH サーバーにそのまま接続できるトランスポートプロキシではありません。このチュートリアルで実際に動作させるのは、上記の認証付き HTTP ゲートウェイです。
Transloadit の Assembly に SFTP からインポートする方法は、🤖 /sftp/import のドキュメントを参照してください。ブラウザーからのアップロードについては、Uppy を参照してください。
