@kubohiroya/turbowarp-http-server 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (63) hide show
  1. package/LICENSE +373 -0
  2. package/README.ja.md +346 -0
  3. package/README.md +874 -0
  4. package/dist/auth/digest-file.d.ts +17 -0
  5. package/dist/auth/digest-file.js +90 -0
  6. package/dist/auth/digest-file.js.map +1 -0
  7. package/dist/auth/digest.d.ts +23 -0
  8. package/dist/auth/digest.js +139 -0
  9. package/dist/auth/digest.js.map +1 -0
  10. package/dist/cli.d.ts +1 -0
  11. package/dist/cli.js +156 -0
  12. package/dist/cli.js.map +1 -0
  13. package/dist/community.d.ts +81 -0
  14. package/dist/community.js +689 -0
  15. package/dist/community.js.map +1 -0
  16. package/dist/digest-cli.d.ts +1 -0
  17. package/dist/digest-cli.js +159 -0
  18. package/dist/digest-cli.js.map +1 -0
  19. package/dist/extension-manifest.json +441 -0
  20. package/dist/protocol.d.ts +59 -0
  21. package/dist/protocol.js +71 -0
  22. package/dist/protocol.js.map +1 -0
  23. package/dist/server.d.ts +89 -0
  24. package/dist/server.js +650 -0
  25. package/dist/server.js.map +1 -0
  26. package/dist/turbowarp-http-server.js +1110 -0
  27. package/docs/deployment-targets.ja.md +274 -0
  28. package/docs/turbowarp-http-server.architecture.html +15149 -0
  29. package/docs/turbowarp-http-server.architecture.json +1014 -0
  30. package/docs/turbowarp-http-server.architecture.visual-check.1440x900.dark.png +0 -0
  31. package/docs/turbowarp-http-server.architecture.visual-check.1440x900.light.png +0 -0
  32. package/docs/turbowarp-http-server.architecture.visual-check.2048x1320.dark.png +0 -0
  33. package/docs/turbowarp-http-server.architecture.visual-check.2048x1320.light.png +0 -0
  34. package/docs/turbowarp-http-server.architecture.visual-check.html +32 -0
  35. package/docs/turbowarp-http-server.architecture.visual-check.json +547 -0
  36. package/examples/01-hello-form/README.ja.md +46 -0
  37. package/examples/01-hello-form/server.mjs +59 -0
  38. package/examples/02-visitor-counter/README.ja.md +39 -0
  39. package/examples/02-visitor-counter/server.mjs +44 -0
  40. package/examples/03-message-board/README.ja.md +47 -0
  41. package/examples/03-message-board/server.mjs +72 -0
  42. package/examples/04-image-upload/README.ja.md +46 -0
  43. package/examples/04-image-upload/server.mjs +149 -0
  44. package/examples/05-live-camera/README.ja.md +47 -0
  45. package/examples/05-live-camera/server.mjs +147 -0
  46. package/examples/06-scratch-like-community/README.ja.md +82 -0
  47. package/examples/06-scratch-like-community/server.mjs +17 -0
  48. package/examples/README.ja.md +20 -0
  49. package/package.json +75 -0
  50. package/schemas/extension-manifest.schema.json +49 -0
  51. package/src/auth/digest-file.ts +115 -0
  52. package/src/auth/digest.ts +170 -0
  53. package/src/block-definitions.json +417 -0
  54. package/src/cli.ts +172 -0
  55. package/src/community.ts +815 -0
  56. package/src/config.ts +12 -0
  57. package/src/digest-cli.ts +178 -0
  58. package/src/extension-manifest.ts +149 -0
  59. package/src/extension.ts +713 -0
  60. package/src/globals.d.ts +30 -0
  61. package/src/index.ts +8 -0
  62. package/src/protocol.ts +132 -0
  63. package/src/server.ts +880 -0
@@ -0,0 +1,82 @@
1
+ # 06-scratch-like-community
2
+
3
+ ユーザ登録、ログイン、作品投稿、作品一覧/詳細、SB3 ダウンロード、リミックス投稿の流れを示す Scratch 風コミュニティサイトの学習用ローカル実装です。
4
+
5
+ この example は production-ready な認証基盤ではありません。`src/community.ts` の optional community app をそのまま起動し、Hono 側安全対策として学習用に次の最小限だけを含めています。
6
+
7
+ - password は Node 標準 `crypto.scrypt` で hash 化して保存する。
8
+ - session cookie は `HttpOnly`、`SameSite=Lax` にする。
9
+ - state-changing request は CSRF token を検証する。
10
+ - upload は multipart body、`.sb3`、SB3/zip 系 MIME、file signature、size limit で検証する。
11
+ - owner だけが作品の metadata edit、SB3 replace、delete を実行できる。
12
+ - remix 作成時に元 project ID を保存する。
13
+ - OAuth demo route は環境変数で provider を設定した場合だけ有効になる。
14
+
15
+ ## 起動
16
+
17
+ ```bash
18
+ corepack pnpm exec tsx examples/06-scratch-like-community/server.mjs
19
+ ```
20
+
21
+ ブラウザで `http://127.0.0.1:9106/` を開きます。
22
+
23
+ ## HTTP route
24
+
25
+ | Method | Path | 期待されるレスポンス |
26
+ |---|---|---|
27
+ | `GET` | `/` | 作品一覧 |
28
+ | `GET` | `/signup` | 登録フォーム |
29
+ | `POST` | `/signup` | ユーザ作成とログイン |
30
+ | `GET` | `/login` | ログインフォーム |
31
+ | `POST` | `/login` | session 作成 |
32
+ | `POST` | `/logout` | session 破棄 |
33
+ | `GET` | `/auth/:provider/start` | configured OAuth demo flow の開始 |
34
+ | `GET` | `/auth/:provider/callback` | OAuth demo flow の完了 |
35
+ | `POST` | `/projects` | `.sb3` upload と作品作成 |
36
+ | `GET` | `/projects/:id` | 作品詳細 |
37
+ | `GET` | `/projects/:id.sb3` | SB3 download |
38
+ | `POST` | `/projects/:id/remix` | remix 作品作成 |
39
+ | `POST` | `/projects/:id/update` | owner-only metadata edit |
40
+ | `POST` | `/projects/:id/replace` | owner-only SB3 replace |
41
+ | `POST` | `/projects/:id/delete` | owner-only delete |
42
+
43
+ OAuth demo provider の設定例:
44
+
45
+ ```bash
46
+ COMMUNITY_OAUTH_DEMO_CLIENT_ID=demo-client
47
+ COMMUNITY_OAUTH_DEMO_AUTHORIZATION_URL=https://example.test/oauth/authorize
48
+ COMMUNITY_OAUTH_DEMO_REDIRECT_URI=http://127.0.0.1:9106/auth/demo/callback
49
+ COMMUNITY_OAUTH_DEMO_SCOPE=profile
50
+ ```
51
+
52
+ ## TurboWarp 側のブロック構成
53
+
54
+ ```text
55
+ when HTTP request received
56
+ use HTTP request [current request ID]
57
+ if <GET /> then
58
+ Markdown builder で作品一覧を作る
59
+ respond with HTML [一覧 page]
60
+ end
61
+
62
+ if <GET /projects/:id.sb3> then
63
+ 権限を確認する
64
+ set response header [content-type] to [application/x.scratch.sb3]
65
+ set response header [content-disposition] to [attachment; filename="project.sb3"]
66
+ send response [SB3 bytes を返す処理]
67
+ end
68
+
69
+ if <POST /projects/:id/remix> then
70
+ login/session と CSRF token を確認する
71
+ upload validation を行う
72
+ remix 元 ID を記録して新しい作品として保存する
73
+ end
74
+ ```
75
+
76
+ ## 動作確認
77
+
78
+ 1. `/signup` でユーザを作成します。
79
+ 2. `/` の投稿フォームから `.sb3` ファイルを投稿します。
80
+ 3. 作品詳細から download と remix を確認します。
81
+
82
+ `curl` で CSRF cookie と hidden input を扱うのは煩雑なため、通常はブラウザで確認してください。
@@ -0,0 +1,17 @@
1
+ import {serve} from '@hono/node-server';
2
+ import {createCommunityApp} from '../../src/community.ts';
3
+
4
+ const port = Number.parseInt(process.env.PORT ?? '9106', 10);
5
+ const hostname = process.env.HOST ?? '127.0.0.1';
6
+
7
+ if (!Number.isInteger(port) || port < 1 || port > 65535) {
8
+ throw new Error(`Invalid port: ${process.env.PORT}`);
9
+ }
10
+
11
+ serve({
12
+ fetch: createCommunityApp().fetch,
13
+ hostname,
14
+ port
15
+ });
16
+
17
+ console.log(`scratch-like community example listening on http://${hostname}:${port}`);
@@ -0,0 +1,20 @@
1
+ # Examples
2
+
3
+ このディレクトリには、TurboWarp HTTP Server の使い方を段階的に確認するためのサンプルを置いています。
4
+
5
+ 各サンプルは独立した Hono app です。リポジトリ root から次のように起動できます。
6
+
7
+ ```bash
8
+ corepack pnpm exec tsx examples/01-hello-form/server.mjs
9
+ ```
10
+
11
+ | Example | 内容 |
12
+ |---|---|
13
+ | `01-hello-form` | `GET /` のフォームと `POST /hello` の応答 |
14
+ | `02-visitor-counter` | 日付ごとの訪問者カウンタ |
15
+ | `03-message-board` | 投稿フォーム付きの簡易掲示板 |
16
+ | `04-image-upload` | 画像 upload と `@assets` named resource 参照 |
17
+ | `05-live-camera` | stable asset URL を atomic replace するライブカメラ |
18
+ | `06-scratch-like-community` | 登録、ログイン、作品投稿、SB3 download、remix の学習用コミュニティ |
19
+
20
+ TurboWarp 側は README の「TurboWarp 側のブロック構成」を参考に、HTTP request hat、response block、HTML/Markdown builder、Asset Manager block を組み合わせて同じ流れを再現できます。
package/package.json ADDED
@@ -0,0 +1,75 @@
1
+ {
2
+ "name": "@kubohiroya/turbowarp-http-server",
3
+ "version": "0.1.0",
4
+ "description": "A TurboWarp extension for connecting block programs to an HTTP bridge server.",
5
+ "author": "Hiroya Kubo <hiroya@cuc.ac.jp>",
6
+ "license": "MPL-2.0",
7
+ "homepage": "https://github.com/kubohiroya/turbowarp-http-server#readme",
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "git+https://github.com/kubohiroya/turbowarp-http-server.git"
11
+ },
12
+ "bugs": {
13
+ "url": "https://github.com/kubohiroya/turbowarp-http-server/issues"
14
+ },
15
+ "keywords": [
16
+ "turbowarp",
17
+ "scratch",
18
+ "extension",
19
+ "http",
20
+ "websocket",
21
+ "vite",
22
+ "typescript"
23
+ ],
24
+ "type": "module",
25
+ "bin": {
26
+ "turbowarp-http-digest": "dist/digest-cli.js",
27
+ "turbowarp-http-server": "dist/cli.js"
28
+ },
29
+ "files": [
30
+ "dist/",
31
+ "docs/",
32
+ "examples/",
33
+ "schemas/",
34
+ "src/",
35
+ "templates/",
36
+ "README.md",
37
+ "README.ja.md",
38
+ "LICENSE"
39
+ ],
40
+ "engines": {
41
+ "node": ">=22.18.0"
42
+ },
43
+ "dependencies": {
44
+ "@hono/node-server": "^1.19.6",
45
+ "hono": "^4.10.7",
46
+ "ws": "^8.18.3"
47
+ },
48
+ "devDependencies": {
49
+ "@eslint/js": "^9.39.5",
50
+ "@kubohiroya/vite-plugin-turbowarp-extension": "0.4.0",
51
+ "@types/node": "^24.13.3",
52
+ "@types/ws": "^8.18.1",
53
+ "eslint": "^9.39.5",
54
+ "tsx": "^4.21.0",
55
+ "typescript": "^5.9.3",
56
+ "typescript-eslint": "^8.66.0",
57
+ "vite": "^8.2.2",
58
+ "vitest": "^4.1.10"
59
+ },
60
+ "scripts": {
61
+ "dev": "vite build --watch",
62
+ "dev:server": "tsx watch src/cli.ts",
63
+ "typecheck": "tsc --noEmit",
64
+ "build": "vite build && tsc -p tsconfig.cli.json",
65
+ "lint": "eslint src tests vite.config.ts",
66
+ "test": "vitest run",
67
+ "examples:check": "node scripts/check-examples.ts",
68
+ "docs": "node scripts/generate-readme.ts",
69
+ "docs:check": "node scripts/generate-readme.ts --check",
70
+ "pack:check": "npm pack --dry-run --ignore-scripts",
71
+ "start": "node dist/cli.js",
72
+ "check:dist": "pnpm run build && node scripts/check-dist.ts",
73
+ "check": "pnpm run typecheck && pnpm run lint && pnpm run test && pnpm run examples:check && pnpm run docs:check && pnpm run check:dist && pnpm run pack:check"
74
+ }
75
+ }
@@ -0,0 +1,49 @@
1
+ {
2
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
3
+ "$id": "https://raw.githubusercontent.com/kubohiroya/turbowarp-extension-template/main/schemas/extension-manifest.schema.json",
4
+ "title": "TurboWarp Extension API Manifest",
5
+ "type": "object",
6
+ "additionalProperties": false,
7
+ "required": ["formatVersion", "id", "blocks", "menus"],
8
+ "properties": {
9
+ "formatVersion": {"const": 1},
10
+ "id": {"type": "string", "pattern": "^[a-z0-9]+$"},
11
+ "blocks": {
12
+ "type": "array",
13
+ "items": {
14
+ "type": "object",
15
+ "additionalProperties": false,
16
+ "required": ["opcode", "blockType", "arguments"],
17
+ "properties": {
18
+ "opcode": {"type": "string", "minLength": 1},
19
+ "blockType": {"type": "string", "minLength": 1},
20
+ "arguments": {
21
+ "type": "array",
22
+ "items": {
23
+ "type": "object",
24
+ "additionalProperties": false,
25
+ "required": ["id", "type"],
26
+ "properties": {
27
+ "id": {"type": "string", "minLength": 1},
28
+ "type": {"type": "string", "minLength": 1},
29
+ "menu": {"type": "string", "minLength": 1}
30
+ }
31
+ }
32
+ }
33
+ }
34
+ }
35
+ },
36
+ "menus": {
37
+ "type": "array",
38
+ "items": {
39
+ "type": "object",
40
+ "additionalProperties": false,
41
+ "required": ["id", "acceptReporters"],
42
+ "properties": {
43
+ "id": {"type": "string", "minLength": 1},
44
+ "acceptReporters": {"type": "boolean"}
45
+ }
46
+ }
47
+ }
48
+ }
49
+ }
@@ -0,0 +1,115 @@
1
+ import {readFile, rename, writeFile} from 'node:fs/promises';
2
+ import {createHa1} from './digest.js';
3
+ import type {DigestCredentialStore} from './digest.js';
4
+
5
+ export interface HtdigestEntry {
6
+ username: string;
7
+ realm: string;
8
+ ha1: string;
9
+ }
10
+
11
+ export class HtdigestFile implements DigestCredentialStore {
12
+ public constructor(private readonly path: string) {}
13
+
14
+ public async getHa1(username: string, realm: string): Promise<string | undefined> {
15
+ const entries = await readHtdigestFile(this.path);
16
+ return entries.find((entry) => entry.username === username && entry.realm === realm)?.ha1;
17
+ }
18
+ }
19
+
20
+ export async function readHtdigestFile(path: string): Promise<HtdigestEntry[]> {
21
+ let text = '';
22
+ try {
23
+ text = await readFile(path, 'utf8');
24
+ } catch (error) {
25
+ if (isNodeError(error) && error.code === 'ENOENT') return [];
26
+ throw error;
27
+ }
28
+
29
+ const entries: HtdigestEntry[] = [];
30
+ for (const [index, line] of text.split(/\r?\n/).entries()) {
31
+ if (!line.trim()) continue;
32
+ const parts = line.split(':');
33
+ const [username, realm, ha1] = parts;
34
+ if (parts.length !== 3 || !username || !realm || !ha1 || !/^[0-9a-f]{32}$/i.test(ha1)) {
35
+ throw new Error(`Invalid htdigest entry at ${path}:${index + 1}.`);
36
+ }
37
+ entries.push({
38
+ username,
39
+ realm,
40
+ ha1: ha1.toLowerCase()
41
+ });
42
+ }
43
+ return entries;
44
+ }
45
+
46
+ export async function writeHtdigestFile(path: string, entries: readonly HtdigestEntry[]): Promise<void> {
47
+ const body = entries
48
+ .map((entry) => `${entry.username}:${entry.realm}:${entry.ha1.toLowerCase()}`)
49
+ .join('\n');
50
+ const tmpPath = `${path}.${process.pid}.${Date.now()}.tmp`;
51
+ await writeFile(tmpPath, body ? `${body}\n` : '', {mode: 0o600});
52
+ await rename(tmpPath, path);
53
+ }
54
+
55
+ export async function setHtdigestPassword(
56
+ path: string,
57
+ username: string,
58
+ realm: string,
59
+ password: string
60
+ ): Promise<'created' | 'updated'> {
61
+ validateField('username', username);
62
+ validateField('realm', realm);
63
+ const entries = await readHtdigestFile(path);
64
+ const ha1 = createHa1(username, realm, password);
65
+ const existing = entries.find((entry) => entry.username === username && entry.realm === realm);
66
+ if (existing) {
67
+ existing.ha1 = ha1;
68
+ await writeHtdigestFile(path, entries);
69
+ return 'updated';
70
+ }
71
+ entries.push({username, realm, ha1});
72
+ entries.sort((left, right) =>
73
+ `${left.realm}\0${left.username}`.localeCompare(`${right.realm}\0${right.username}`)
74
+ );
75
+ await writeHtdigestFile(path, entries);
76
+ return 'created';
77
+ }
78
+
79
+ export async function updateHtdigestPassword(
80
+ path: string,
81
+ username: string,
82
+ realm: string,
83
+ password: string
84
+ ): Promise<boolean> {
85
+ validateField('username', username);
86
+ validateField('realm', realm);
87
+ const entries = await readHtdigestFile(path);
88
+ const existing = entries.find((entry) => entry.username === username && entry.realm === realm);
89
+ if (!existing) return false;
90
+ existing.ha1 = createHa1(username, realm, password);
91
+ await writeHtdigestFile(path, entries);
92
+ return true;
93
+ }
94
+
95
+ export async function deleteHtdigestUser(
96
+ path: string,
97
+ username: string,
98
+ realm: string
99
+ ): Promise<boolean> {
100
+ const entries = await readHtdigestFile(path);
101
+ const nextEntries = entries.filter((entry) => entry.username !== username || entry.realm !== realm);
102
+ if (nextEntries.length === entries.length) return false;
103
+ await writeHtdigestFile(path, nextEntries);
104
+ return true;
105
+ }
106
+
107
+ export function validateField(name: 'username' | 'realm', value: string): void {
108
+ if (!value || /[:\r\n]/.test(value)) {
109
+ throw new Error(`${name} must be non-empty and must not contain colon or line breaks.`);
110
+ }
111
+ }
112
+
113
+ function isNodeError(error: unknown): error is NodeJS.ErrnoException {
114
+ return error instanceof Error && 'code' in error;
115
+ }
@@ -0,0 +1,170 @@
1
+ import {createHash, randomBytes, timingSafeEqual} from 'node:crypto';
2
+
3
+ export const DIGEST_AUTH_USER_HEADER = 'x-turbowarp-http-auth-user';
4
+
5
+ export interface DigestCredentialStore {
6
+ getHa1(username: string, realm: string): string | undefined | Promise<string | undefined>;
7
+ }
8
+
9
+ export interface DigestAuthOptions {
10
+ realm: string;
11
+ credentials: DigestCredentialStore;
12
+ nonceMaxAgeMs?: number;
13
+ nonceSecret?: string;
14
+ }
15
+
16
+ export interface DigestAuthResult {
17
+ ok: boolean;
18
+ username?: string;
19
+ challenge?: string;
20
+ }
21
+
22
+ const DEFAULT_NONCE_MAX_AGE_MS = 5 * 60 * 1000;
23
+ const QOP = 'auth';
24
+ const ALGORITHM = 'MD5';
25
+
26
+ export function createHa1(username: string, realm: string, password: string): string {
27
+ return md5(`${username}:${realm}:${password}`);
28
+ }
29
+
30
+ export function createDigestChallenge(options: DigestAuthOptions): string {
31
+ const nonce = createNonce(options.nonceSecret ?? defaultNonceSecret(), Date.now());
32
+ const opaque = md5(options.realm);
33
+ return `Digest realm="${escapeQuoted(options.realm)}", qop="${QOP}", algorithm=${ALGORITHM}, nonce="${nonce}", opaque="${opaque}"`;
34
+ }
35
+
36
+ export async function verifyDigestAuth(
37
+ request: Request,
38
+ method: string,
39
+ options: DigestAuthOptions
40
+ ): Promise<DigestAuthResult> {
41
+ const challenge = createDigestChallenge(options);
42
+ const authorization = request.headers.get('authorization');
43
+ if (!authorization) return {ok: false, challenge};
44
+ const schemeMatch = authorization.match(/^Digest\s+/i);
45
+ if (!schemeMatch) return {ok: false, challenge};
46
+
47
+ const params = parseDigestAuthorization(authorization.slice(schemeMatch[0].length));
48
+ const username = params.username;
49
+ const realm = params.realm;
50
+ const nonce = params.nonce;
51
+ const uri = params.uri;
52
+ const response = params.response;
53
+ if (!username || realm !== options.realm || !nonce || !uri || !response) {
54
+ return {ok: false, challenge};
55
+ }
56
+
57
+ if (!verifyNonce(nonce, options.nonceSecret ?? defaultNonceSecret(), options.nonceMaxAgeMs)) {
58
+ return {ok: false, challenge};
59
+ }
60
+
61
+ const ha1 = await options.credentials.getHa1(username, realm);
62
+ if (!ha1 || !/^[0-9a-f]{32}$/i.test(ha1)) return {ok: false, challenge};
63
+
64
+ const requestUrl = new URL(request.url);
65
+ if (uri !== `${requestUrl.pathname}${requestUrl.search}`) return {ok: false, challenge};
66
+
67
+ const ha2 = md5(`${method.toUpperCase()}:${uri}`);
68
+ const expected =
69
+ params.qop === QOP && params.nc && params.cnonce
70
+ ? md5(`${ha1}:${nonce}:${params.nc}:${params.cnonce}:${QOP}:${ha2}`)
71
+ : md5(`${ha1}:${nonce}:${ha2}`);
72
+
73
+ if (!safeEqualHex(response, expected)) return {ok: false, challenge};
74
+
75
+ return {ok: true, username};
76
+ }
77
+
78
+ export function parseDigestAuthorization(value: string): Record<string, string> {
79
+ const params: Record<string, string> = {};
80
+ let index = 0;
81
+
82
+ while (index < value.length) {
83
+ while (value[index] === ' ' || value[index] === ',') index += 1;
84
+ const keyStart = index;
85
+ while (index < value.length && value[index] !== '=' && value[index] !== ',') index += 1;
86
+ const key = value.slice(keyStart, index).trim();
87
+ if (!key || value[index] !== '=') break;
88
+ index += 1;
89
+
90
+ let paramValue = '';
91
+ if (value[index] === '"') {
92
+ index += 1;
93
+ while (index < value.length) {
94
+ const char = value[index];
95
+ if (char === '\\') {
96
+ index += 1;
97
+ if (index < value.length) paramValue += value[index];
98
+ } else if (char === '"') {
99
+ index += 1;
100
+ break;
101
+ } else {
102
+ paramValue += char;
103
+ }
104
+ index += 1;
105
+ }
106
+ } else {
107
+ const valueStart = index;
108
+ while (index < value.length && value[index] !== ',') index += 1;
109
+ paramValue = value.slice(valueStart, index).trim();
110
+ }
111
+ params[key] = paramValue;
112
+ }
113
+
114
+ return params;
115
+ }
116
+
117
+ export function isLocalAddress(address: string | undefined): boolean {
118
+ if (!address) return false;
119
+ return (
120
+ address === '127.0.0.1' ||
121
+ address === '::1' ||
122
+ address === '::ffff:127.0.0.1' ||
123
+ address.startsWith('127.')
124
+ );
125
+ }
126
+
127
+ function createNonce(secret: string, timestamp: number): string {
128
+ const payload = `${timestamp.toString(36)}:${randomBytes(12).toString('base64url')}`;
129
+ const signature = md5(`${payload}:${secret}`);
130
+ return Buffer.from(`${payload}:${signature}`, 'utf8').toString('base64url');
131
+ }
132
+
133
+ function verifyNonce(nonce: string, secret: string, maxAgeMs = DEFAULT_NONCE_MAX_AGE_MS): boolean {
134
+ try {
135
+ const decoded = Buffer.from(nonce, 'base64url').toString('utf8');
136
+ const parts = decoded.split(':');
137
+ if (parts.length !== 3) return false;
138
+ const [timestampText, randomText, signature] = parts;
139
+ if (!timestampText || !randomText || !signature) return false;
140
+ const timestamp = Number.parseInt(timestampText, 36);
141
+ if (!Number.isFinite(timestamp) || Date.now() - timestamp > maxAgeMs) return false;
142
+ return safeEqualHex(signature, md5(`${timestampText}:${randomText}:${secret}`));
143
+ } catch {
144
+ return false;
145
+ }
146
+ }
147
+
148
+ function defaultNonceSecret(): string {
149
+ globalThis.__turbowarpHttpDigestNonceSecret ??= randomBytes(32).toString('base64url');
150
+ return globalThis.__turbowarpHttpDigestNonceSecret;
151
+ }
152
+
153
+ function md5(value: string): string {
154
+ return createHash('md5').update(value).digest('hex');
155
+ }
156
+
157
+ function safeEqualHex(left: string, right: string): boolean {
158
+ if (!/^[0-9a-f]+$/i.test(left) || !/^[0-9a-f]+$/i.test(right)) return false;
159
+ const leftBuffer = Buffer.from(left.toLowerCase(), 'hex');
160
+ const rightBuffer = Buffer.from(right.toLowerCase(), 'hex');
161
+ return leftBuffer.byteLength === rightBuffer.byteLength && timingSafeEqual(leftBuffer, rightBuffer);
162
+ }
163
+
164
+ function escapeQuoted(value: string): string {
165
+ return value.replace(/\\/g, '\\\\').replace(/"/g, '\\"');
166
+ }
167
+
168
+ declare global {
169
+ var __turbowarpHttpDigestNonceSecret: string | undefined;
170
+ }