@zintrust/cloudflare-kv-proxy 0.7.9
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.
- package/README.md +78 -0
- package/dist/SignedRequest.d.ts +38 -0
- package/dist/SignedRequest.js +144 -0
- package/dist/build-manifest.json +45 -0
- package/dist/index.d.ts +43 -0
- package/dist/index.js +336 -0
- package/package.json +36 -0
package/README.md
ADDED
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
# @zintrust/cloudflare-kv-proxy
|
|
2
|
+
|
|
3
|
+
Cloudflare Worker service that exposes a small HTTPS API for KV operations.
|
|
4
|
+
|
|
5
|
+
Docs: https://zintrust.com/package-cloudflare-kv-proxy
|
|
6
|
+
|
|
7
|
+
This is intended for **server-to-server** use (e.g. a Node app running outside Cloudflare), via ZinTrust’s `kv-remote` cache driver.
|
|
8
|
+
|
|
9
|
+
## Endpoints
|
|
10
|
+
|
|
11
|
+
All endpoints are `POST` and require signed request headers.
|
|
12
|
+
|
|
13
|
+
- `/zin/kv/get` → `{ namespace?, key, type? }` → `{ value }`
|
|
14
|
+
- `/zin/kv/put` → `{ namespace?, key, value, ttlSeconds? }` → `{ ok: true }`
|
|
15
|
+
- `/zin/kv/delete` → `{ namespace?, key }` → `{ ok: true }`
|
|
16
|
+
- `/zin/kv/list` → `{ namespace?, prefix?, cursor?, limit? }` → `{ keys, cursor, listComplete }`
|
|
17
|
+
|
|
18
|
+
## Required bindings
|
|
19
|
+
|
|
20
|
+
- KV binding: `CACHE`
|
|
21
|
+
|
|
22
|
+
If your binding name is not `CACHE`, set Worker var `KV_NAMESPACE` to your binding name.
|
|
23
|
+
|
|
24
|
+
Optional (recommended):
|
|
25
|
+
|
|
26
|
+
- KV binding: `ZT_NONCES` (nonce replay protection)
|
|
27
|
+
|
|
28
|
+
## Required secrets / vars
|
|
29
|
+
|
|
30
|
+
**Secret (required):**
|
|
31
|
+
|
|
32
|
+
- `KV_REMOTE_SECRET` – shared signing secret used to verify requests.
|
|
33
|
+
- `APP_KEY` – fallback shared signing secret if `KV_REMOTE_SECRET` is not set.
|
|
34
|
+
|
|
35
|
+
Example:
|
|
36
|
+
|
|
37
|
+
```json
|
|
38
|
+
{
|
|
39
|
+
"k1": { "secret": "super-secret-shared-key" }
|
|
40
|
+
}
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
**Vars (optional):**
|
|
44
|
+
|
|
45
|
+
- `ZT_PROXY_SIGNING_WINDOW_MS` (default `60000`)
|
|
46
|
+
- `ZT_MAX_BODY_BYTES` (default `131072`)
|
|
47
|
+
- `ZT_KV_PREFIX` (default empty) – prefix used when storing keys
|
|
48
|
+
- `ZT_KV_LIST_LIMIT` (default `100`) – upper bound for list limit
|
|
49
|
+
|
|
50
|
+
## Deploy
|
|
51
|
+
|
|
52
|
+
From this package directory:
|
|
53
|
+
|
|
54
|
+
```bash
|
|
55
|
+
wrangler deploy
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
Set secrets:
|
|
59
|
+
|
|
60
|
+
```bash
|
|
61
|
+
wrangler secret put KV_REMOTE_SECRET
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
## Use from ZinTrust (Node app)
|
|
65
|
+
|
|
66
|
+
Configure your app:
|
|
67
|
+
|
|
68
|
+
- `CACHE_DRIVER=kv-remote`
|
|
69
|
+
- `KV_REMOTE_URL=https://<your-worker-host>`
|
|
70
|
+
- `KV_REMOTE_KEY_ID=k1`
|
|
71
|
+
- `KV_REMOTE_SECRET=super-secret-shared-key`
|
|
72
|
+
- `KV_REMOTE_NAMESPACE=CACHE` (or empty)
|
|
73
|
+
|
|
74
|
+
Then use `Cache.get/set/delete` as normal.
|
|
75
|
+
|
|
76
|
+
## License
|
|
77
|
+
|
|
78
|
+
This package and its dependencies are MIT licensed, permitting free commercial use.
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
export type SignedRequestHeaders = {
|
|
2
|
+
'x-zt-key-id': string;
|
|
3
|
+
'x-zt-timestamp': string;
|
|
4
|
+
'x-zt-nonce': string;
|
|
5
|
+
'x-zt-body-sha256': string;
|
|
6
|
+
'x-zt-signature': string;
|
|
7
|
+
};
|
|
8
|
+
export type SignedRequestVerifyParams = {
|
|
9
|
+
method: string;
|
|
10
|
+
url: string | URL;
|
|
11
|
+
body?: string | Uint8Array | null;
|
|
12
|
+
headers: Headers | Record<string, string | undefined>;
|
|
13
|
+
getSecretForKeyId: (keyId: string) => string | undefined | Promise<string | undefined>;
|
|
14
|
+
nowMs?: number;
|
|
15
|
+
windowMs?: number;
|
|
16
|
+
verifyNonce?: (keyId: string, nonce: string, ttlMs: number) => Promise<boolean>;
|
|
17
|
+
};
|
|
18
|
+
export type SignedRequestVerifyResult = {
|
|
19
|
+
ok: true;
|
|
20
|
+
keyId: string;
|
|
21
|
+
timestampMs: number;
|
|
22
|
+
nonce: string;
|
|
23
|
+
} | {
|
|
24
|
+
ok: false;
|
|
25
|
+
code: 'MISSING_HEADER' | 'INVALID_TIMESTAMP' | 'EXPIRED' | 'INVALID_BODY_SHA' | 'INVALID_SIGNATURE' | 'UNKNOWN_KEY' | 'REPLAYED';
|
|
26
|
+
message: string;
|
|
27
|
+
};
|
|
28
|
+
export declare const SignedRequest: Readonly<{
|
|
29
|
+
sha256Hex: (data: string | Uint8Array) => Promise<string>;
|
|
30
|
+
canonicalString: (params: {
|
|
31
|
+
method: string;
|
|
32
|
+
url: string | URL;
|
|
33
|
+
timestampMs: number;
|
|
34
|
+
nonce: string;
|
|
35
|
+
bodySha256Hex: string;
|
|
36
|
+
}) => string;
|
|
37
|
+
verify(params: SignedRequestVerifyParams): Promise<SignedRequestVerifyResult>;
|
|
38
|
+
}>;
|
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
const getHeader = (headers, name) => {
|
|
2
|
+
if (typeof headers.get === 'function') {
|
|
3
|
+
const value = headers.get(name);
|
|
4
|
+
return value ?? undefined;
|
|
5
|
+
}
|
|
6
|
+
return headers[name];
|
|
7
|
+
};
|
|
8
|
+
const timingSafeEquals = (a, b) => {
|
|
9
|
+
if (a.length !== b.length)
|
|
10
|
+
return false;
|
|
11
|
+
let result = 0;
|
|
12
|
+
for (let i = 0; i < a.length; i++) {
|
|
13
|
+
result |= (a.codePointAt(i) ?? 0) ^ (b.codePointAt(i) ?? 0);
|
|
14
|
+
}
|
|
15
|
+
return result === 0;
|
|
16
|
+
};
|
|
17
|
+
const getSubtleOrNull = () => {
|
|
18
|
+
if (typeof crypto === 'undefined' || crypto.subtle === undefined)
|
|
19
|
+
return null;
|
|
20
|
+
return crypto.subtle;
|
|
21
|
+
};
|
|
22
|
+
const toBytes = (data) => {
|
|
23
|
+
const bytes = typeof data === 'string' ? new TextEncoder().encode(data) : data;
|
|
24
|
+
return new Uint8Array(bytes);
|
|
25
|
+
};
|
|
26
|
+
const toHex = (bytes) => {
|
|
27
|
+
const view = bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes);
|
|
28
|
+
let out = '';
|
|
29
|
+
for (const element of view) {
|
|
30
|
+
out += element.toString(16).padStart(2, '0');
|
|
31
|
+
}
|
|
32
|
+
return out;
|
|
33
|
+
};
|
|
34
|
+
const sha256Hex = async (data) => {
|
|
35
|
+
const subtle = getSubtleOrNull();
|
|
36
|
+
if (subtle === null)
|
|
37
|
+
return '';
|
|
38
|
+
const digest = await subtle.digest('SHA-256', toBytes(data));
|
|
39
|
+
return toHex(digest);
|
|
40
|
+
};
|
|
41
|
+
const canonicalString = (params) => {
|
|
42
|
+
const u = typeof params.url === 'string' ? new URL(params.url) : params.url;
|
|
43
|
+
const method = params.method.toUpperCase();
|
|
44
|
+
return [
|
|
45
|
+
method,
|
|
46
|
+
u.pathname,
|
|
47
|
+
u.search,
|
|
48
|
+
String(params.timestampMs),
|
|
49
|
+
params.nonce,
|
|
50
|
+
params.bodySha256Hex,
|
|
51
|
+
].join('\n');
|
|
52
|
+
};
|
|
53
|
+
const parseAndValidateHeaders = (headers) => {
|
|
54
|
+
const keyId = getHeader(headers, 'x-zt-key-id');
|
|
55
|
+
const ts = getHeader(headers, 'x-zt-timestamp');
|
|
56
|
+
const nonce = getHeader(headers, 'x-zt-nonce');
|
|
57
|
+
const bodySha = getHeader(headers, 'x-zt-body-sha256');
|
|
58
|
+
const signature = getHeader(headers, 'x-zt-signature');
|
|
59
|
+
if (keyId === undefined ||
|
|
60
|
+
ts === undefined ||
|
|
61
|
+
nonce === undefined ||
|
|
62
|
+
bodySha === undefined ||
|
|
63
|
+
signature === undefined) {
|
|
64
|
+
return { ok: false, code: 'MISSING_HEADER', message: 'Missing required signing headers' };
|
|
65
|
+
}
|
|
66
|
+
const timestampMs = Number.parseInt(ts, 10);
|
|
67
|
+
if (!Number.isFinite(timestampMs)) {
|
|
68
|
+
return { ok: false, code: 'INVALID_TIMESTAMP', message: 'Invalid x-zt-timestamp' };
|
|
69
|
+
}
|
|
70
|
+
return { ok: true, keyId, timestampMs, nonce, bodySha, signature };
|
|
71
|
+
};
|
|
72
|
+
const validateTimestampWindow = (params) => {
|
|
73
|
+
if (Math.abs(params.nowMs - params.timestampMs) > params.windowMs) {
|
|
74
|
+
return { ok: false, code: 'EXPIRED', message: 'Request timestamp outside allowed window' };
|
|
75
|
+
}
|
|
76
|
+
return { ok: true };
|
|
77
|
+
};
|
|
78
|
+
const validateBodyHash = async (params) => {
|
|
79
|
+
const computedBodySha = await sha256Hex(params.body);
|
|
80
|
+
if (computedBodySha === '' || !timingSafeEquals(computedBodySha, params.bodyShaHeader)) {
|
|
81
|
+
return { ok: false, code: 'INVALID_BODY_SHA', message: 'Body hash mismatch' };
|
|
82
|
+
}
|
|
83
|
+
return { ok: true };
|
|
84
|
+
};
|
|
85
|
+
const validateSignature = async (params) => {
|
|
86
|
+
const subtle = getSubtleOrNull();
|
|
87
|
+
if (subtle === null) {
|
|
88
|
+
return { ok: false, code: 'INVALID_SIGNATURE', message: 'WebCrypto is not available' };
|
|
89
|
+
}
|
|
90
|
+
const canonical = canonicalString({
|
|
91
|
+
method: params.method,
|
|
92
|
+
url: params.url,
|
|
93
|
+
timestampMs: params.timestampMs,
|
|
94
|
+
nonce: params.nonce,
|
|
95
|
+
bodySha256Hex: params.bodySha,
|
|
96
|
+
});
|
|
97
|
+
const key = await subtle.importKey('raw', toBytes(params.secret), { name: 'HMAC', hash: 'SHA-256' }, false, ['sign']);
|
|
98
|
+
const expectedBytes = await subtle.sign('HMAC', key, toBytes(canonical));
|
|
99
|
+
const expected = toHex(expectedBytes);
|
|
100
|
+
if (!timingSafeEquals(expected, params.signature)) {
|
|
101
|
+
return { ok: false, code: 'INVALID_SIGNATURE', message: 'Invalid signature' };
|
|
102
|
+
}
|
|
103
|
+
return { ok: true };
|
|
104
|
+
};
|
|
105
|
+
export const SignedRequest = Object.freeze({
|
|
106
|
+
sha256Hex,
|
|
107
|
+
canonicalString,
|
|
108
|
+
async verify(params) {
|
|
109
|
+
const parsed = parseAndValidateHeaders(params.headers);
|
|
110
|
+
if (parsed.ok === false)
|
|
111
|
+
return parsed;
|
|
112
|
+
const { keyId, timestampMs, nonce, bodySha, signature } = parsed;
|
|
113
|
+
const nowMs = params.nowMs ?? Date.now();
|
|
114
|
+
const windowMs = params.windowMs ?? 60_000;
|
|
115
|
+
const windowCheck = validateTimestampWindow({ nowMs, timestampMs, windowMs });
|
|
116
|
+
if (windowCheck.ok === false)
|
|
117
|
+
return windowCheck;
|
|
118
|
+
const bodyCheck = await validateBodyHash({ body: params.body ?? '', bodyShaHeader: bodySha });
|
|
119
|
+
if (bodyCheck.ok === false)
|
|
120
|
+
return bodyCheck;
|
|
121
|
+
const secret = await params.getSecretForKeyId(keyId);
|
|
122
|
+
if (secret === undefined || secret.trim() === '') {
|
|
123
|
+
return { ok: false, code: 'UNKNOWN_KEY', message: 'Unknown key id' };
|
|
124
|
+
}
|
|
125
|
+
const sigCheck = await validateSignature({
|
|
126
|
+
method: params.method,
|
|
127
|
+
url: params.url,
|
|
128
|
+
timestampMs,
|
|
129
|
+
nonce,
|
|
130
|
+
bodySha,
|
|
131
|
+
signature,
|
|
132
|
+
secret,
|
|
133
|
+
});
|
|
134
|
+
if (sigCheck.ok === false)
|
|
135
|
+
return sigCheck;
|
|
136
|
+
if (params.verifyNonce !== undefined) {
|
|
137
|
+
const ok = await params.verifyNonce(keyId, nonce, windowMs);
|
|
138
|
+
if (ok === false) {
|
|
139
|
+
return { ok: false, code: 'REPLAYED', message: 'Nonce replayed or rejected' };
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
return { ok: true, keyId, timestampMs, nonce };
|
|
143
|
+
},
|
|
144
|
+
});
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@zintrust/cloudflare-kv-proxy",
|
|
3
|
+
"version": "0.7.9",
|
|
4
|
+
"buildDate": "2026-04-20T20:59:45.308Z",
|
|
5
|
+
"buildEnvironment": {
|
|
6
|
+
"node": "v22.22.1",
|
|
7
|
+
"platform": "darwin",
|
|
8
|
+
"arch": "arm64"
|
|
9
|
+
},
|
|
10
|
+
"git": {
|
|
11
|
+
"commit": "e04d1cae",
|
|
12
|
+
"branch": "release"
|
|
13
|
+
},
|
|
14
|
+
"package": {
|
|
15
|
+
"engines": {
|
|
16
|
+
"node": ">=20.0.0"
|
|
17
|
+
},
|
|
18
|
+
"dependencies": [],
|
|
19
|
+
"peerDependencies": [
|
|
20
|
+
"@zintrust/core"
|
|
21
|
+
]
|
|
22
|
+
},
|
|
23
|
+
"files": {
|
|
24
|
+
"SignedRequest.d.ts": {
|
|
25
|
+
"size": 1270,
|
|
26
|
+
"sha256": "961adc3b27574e480dfaa478b20e5fae421f59500b3fcdf2e10414550a963f6f"
|
|
27
|
+
},
|
|
28
|
+
"SignedRequest.js": {
|
|
29
|
+
"size": 5398,
|
|
30
|
+
"sha256": "5be1bc4b1ad88b1980c28e5ca45c1e564f44466bd5d0cda8bc07403031ce87a1"
|
|
31
|
+
},
|
|
32
|
+
"build-manifest.json": {
|
|
33
|
+
"size": 1112,
|
|
34
|
+
"sha256": "16ecf8e9daae610fd9d1fc8367fe00c315e3c93ffa9e79d6b884fbfb04213982"
|
|
35
|
+
},
|
|
36
|
+
"index.d.ts": {
|
|
37
|
+
"size": 1352,
|
|
38
|
+
"sha256": "549fb10f7f52c85ed38ee9f6627c43579b77b164f2791747b5daa760e50aab53"
|
|
39
|
+
},
|
|
40
|
+
"index.js": {
|
|
41
|
+
"size": 12757,
|
|
42
|
+
"sha256": "d2db5b641bc317c4296d81e90f72aa45d8fa460a2c94129f613cad3ee3aacdbd"
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
type KVNamespacePutOptions = {
|
|
2
|
+
expirationTtl?: number;
|
|
3
|
+
};
|
|
4
|
+
type KvGetType = 'text' | 'json' | 'arrayBuffer';
|
|
5
|
+
type KVListResult = {
|
|
6
|
+
keys: Array<{
|
|
7
|
+
name: string;
|
|
8
|
+
}>;
|
|
9
|
+
cursor: string;
|
|
10
|
+
list_complete: boolean;
|
|
11
|
+
};
|
|
12
|
+
type KVNamespace = {
|
|
13
|
+
get: {
|
|
14
|
+
(key: string): Promise<string | null>;
|
|
15
|
+
(key: string, type: 'json'): Promise<unknown | null>;
|
|
16
|
+
(key: string, type: 'arrayBuffer'): Promise<ArrayBuffer | null>;
|
|
17
|
+
(key: string, type: KvGetType): Promise<unknown | ArrayBuffer | string | null>;
|
|
18
|
+
};
|
|
19
|
+
put: (key: string, value: string, options?: KVNamespacePutOptions) => Promise<void>;
|
|
20
|
+
delete: (key: string) => Promise<void>;
|
|
21
|
+
list: (options: {
|
|
22
|
+
prefix?: string;
|
|
23
|
+
limit?: number;
|
|
24
|
+
cursor?: string;
|
|
25
|
+
}) => Promise<KVListResult>;
|
|
26
|
+
};
|
|
27
|
+
type KvEnv = {
|
|
28
|
+
CACHE?: KVNamespace;
|
|
29
|
+
KV_NAMESPACE?: string;
|
|
30
|
+
APP_KEY?: string;
|
|
31
|
+
KV_REMOTE_SECRET?: string;
|
|
32
|
+
ZT_PROXY_SIGNING_WINDOW_MS?: string;
|
|
33
|
+
ZT_NONCES?: KVNamespace;
|
|
34
|
+
ZT_MAX_BODY_BYTES?: string;
|
|
35
|
+
ZT_KV_PREFIX?: string;
|
|
36
|
+
ZT_KV_LIST_LIMIT?: string;
|
|
37
|
+
};
|
|
38
|
+
export declare const ZintrustKvProxy: Readonly<{
|
|
39
|
+
_ZINTRUST_CLOUDFLARE_KV_PROXY_VERSION: "0.1.15";
|
|
40
|
+
_ZINTRUST_CLOUDFLARE_KV_PROXY_BUILD_DATE: "__BUILD_DATE__";
|
|
41
|
+
fetch(request: Request, env: KvEnv): Promise<Response>;
|
|
42
|
+
}>;
|
|
43
|
+
export default ZintrustKvProxy;
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,336 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @zintrust/cloudflare-kv-proxy v0.7.9
|
|
3
|
+
*
|
|
4
|
+
* Cloudflare KV proxy package for ZinTrust.
|
|
5
|
+
*
|
|
6
|
+
* Build Information:
|
|
7
|
+
* Built: 2026-04-20T20:59:45.237Z
|
|
8
|
+
* Node: >=20.0.0
|
|
9
|
+
* License: MIT
|
|
10
|
+
*
|
|
11
|
+
*/
|
|
12
|
+
import { ErrorHandler, RequestValidator, SigningService } from '@zintrust/core/proxy';
|
|
13
|
+
const DEFAULT_SIGNING_WINDOW_MS = 60_000;
|
|
14
|
+
const DEFAULT_MAX_BODY_BYTES = 128 * 1024;
|
|
15
|
+
const DEFAULT_LIST_LIMIT = 100;
|
|
16
|
+
const json = (status, body) => {
|
|
17
|
+
return new Response(JSON.stringify(body), {
|
|
18
|
+
status,
|
|
19
|
+
headers: {
|
|
20
|
+
'Content-Type': 'application/json; charset=utf-8',
|
|
21
|
+
'Cache-Control': 'no-store',
|
|
22
|
+
},
|
|
23
|
+
});
|
|
24
|
+
};
|
|
25
|
+
const toErrorResponse = (status, code, message) => {
|
|
26
|
+
const error = ErrorHandler.toProxyError(status, code, message);
|
|
27
|
+
return json(error.status, error.body);
|
|
28
|
+
};
|
|
29
|
+
const getEnvInt = (env, name, fallback) => {
|
|
30
|
+
const raw = env[name];
|
|
31
|
+
if (typeof raw !== 'string')
|
|
32
|
+
return fallback;
|
|
33
|
+
const parsed = Number.parseInt(raw, 10);
|
|
34
|
+
return Number.isFinite(parsed) ? parsed : fallback;
|
|
35
|
+
};
|
|
36
|
+
const isRecord = (value) => typeof value === 'object' && value !== null;
|
|
37
|
+
const isString = (value) => typeof value === 'string';
|
|
38
|
+
const normalizeBindingName = (value) => {
|
|
39
|
+
if (!isString(value))
|
|
40
|
+
return null;
|
|
41
|
+
const trimmed = value.trim();
|
|
42
|
+
return trimmed === '' ? null : trimmed;
|
|
43
|
+
};
|
|
44
|
+
const readBodyBytes = async (request, maxBytes) => {
|
|
45
|
+
const buf = await request.arrayBuffer();
|
|
46
|
+
if (buf.byteLength > maxBytes) {
|
|
47
|
+
return {
|
|
48
|
+
ok: false,
|
|
49
|
+
response: toErrorResponse(413, 'PAYLOAD_TOO_LARGE', 'Body too large'),
|
|
50
|
+
};
|
|
51
|
+
}
|
|
52
|
+
const bytes = new Uint8Array(buf);
|
|
53
|
+
const text = new TextDecoder().decode(bytes);
|
|
54
|
+
return { ok: true, bytes, text };
|
|
55
|
+
};
|
|
56
|
+
const parseOptionalJson = (text) => {
|
|
57
|
+
if (text.trim() === '')
|
|
58
|
+
return { ok: true, payload: null };
|
|
59
|
+
const parsed = RequestValidator.parseJson(text);
|
|
60
|
+
if (!parsed.ok) {
|
|
61
|
+
// Type guard: we know parsed has 'error' property when ok is false
|
|
62
|
+
const errorResult = parsed;
|
|
63
|
+
let message = errorResult.error.message;
|
|
64
|
+
if (errorResult.error.code === 'INVALID_JSON') {
|
|
65
|
+
message = 'Invalid JSON body';
|
|
66
|
+
}
|
|
67
|
+
else if (errorResult.error.code === 'VALIDATION_ERROR') {
|
|
68
|
+
message = 'Invalid body';
|
|
69
|
+
}
|
|
70
|
+
return { ok: false, response: toErrorResponse(400, errorResult.error.code, message) };
|
|
71
|
+
}
|
|
72
|
+
// Type guard: we know parsed has 'value' property when ok is true
|
|
73
|
+
const successResult = parsed;
|
|
74
|
+
return { ok: true, payload: successResult.value };
|
|
75
|
+
};
|
|
76
|
+
const loadSigningSecret = (env) => {
|
|
77
|
+
const direct = typeof env.KV_REMOTE_SECRET === 'string' ? env.KV_REMOTE_SECRET.trim() : '';
|
|
78
|
+
if (direct !== '')
|
|
79
|
+
return direct;
|
|
80
|
+
const fallback = typeof env.APP_KEY === 'string' ? env.APP_KEY.trim() : '';
|
|
81
|
+
if (fallback !== '')
|
|
82
|
+
return fallback;
|
|
83
|
+
return null;
|
|
84
|
+
};
|
|
85
|
+
const verifyNonceKv = async (kv, keyId, nonce, ttlMs) => {
|
|
86
|
+
const ttlSeconds = Math.max(1, Math.ceil(ttlMs / 1000));
|
|
87
|
+
const storageKey = `nonce:${keyId}:${nonce}`;
|
|
88
|
+
const existing = await kv.get(storageKey);
|
|
89
|
+
if (existing !== null)
|
|
90
|
+
return false;
|
|
91
|
+
await kv.put(storageKey, '1', { expirationTtl: ttlSeconds });
|
|
92
|
+
return true;
|
|
93
|
+
};
|
|
94
|
+
const verifySignedRequest = async (request, env, bodyBytes) => {
|
|
95
|
+
const secret = loadSigningSecret(env);
|
|
96
|
+
if (secret === null) {
|
|
97
|
+
return toErrorResponse(500, 'CONFIG_ERROR', 'Missing signing secret (KV_REMOTE_SECRET or APP_KEY)');
|
|
98
|
+
}
|
|
99
|
+
const windowMs = getEnvInt(env, 'ZT_PROXY_SIGNING_WINDOW_MS', DEFAULT_SIGNING_WINDOW_MS);
|
|
100
|
+
const verifyResult = await SigningService.verifyWithKeyProvider({
|
|
101
|
+
method: request.method,
|
|
102
|
+
url: request.url,
|
|
103
|
+
body: bodyBytes,
|
|
104
|
+
headers: request.headers,
|
|
105
|
+
windowMs,
|
|
106
|
+
getSecretForKeyId: async (_keyId) => secret,
|
|
107
|
+
verifyNonce: env.ZT_NONCES === undefined
|
|
108
|
+
? undefined
|
|
109
|
+
: async (keyId, nonce, ttlMs) => verifyNonceKv(env.ZT_NONCES, keyId, nonce, ttlMs),
|
|
110
|
+
});
|
|
111
|
+
if (verifyResult.ok === false) {
|
|
112
|
+
return toErrorResponse(verifyResult.status, verifyResult.code, verifyResult.message);
|
|
113
|
+
}
|
|
114
|
+
return { ok: true };
|
|
115
|
+
};
|
|
116
|
+
const requireCache = (env) => {
|
|
117
|
+
if (env.CACHE !== undefined && env.CACHE !== null)
|
|
118
|
+
return env.CACHE;
|
|
119
|
+
const bindingName = normalizeBindingName(env.KV_NAMESPACE);
|
|
120
|
+
if (bindingName !== null) {
|
|
121
|
+
const record = env;
|
|
122
|
+
const kv = record[bindingName];
|
|
123
|
+
if (kv !== undefined && kv !== null)
|
|
124
|
+
return kv;
|
|
125
|
+
}
|
|
126
|
+
return toErrorResponse(500, 'CONFIG_ERROR', 'Missing KV binding (CACHE)');
|
|
127
|
+
};
|
|
128
|
+
const normalizeNamespace = (value) => {
|
|
129
|
+
if (!isString(value))
|
|
130
|
+
return undefined;
|
|
131
|
+
const trimmed = value.trim();
|
|
132
|
+
return trimmed === '' ? undefined : trimmed;
|
|
133
|
+
};
|
|
134
|
+
const buildStorageKey = (env, params) => {
|
|
135
|
+
const prefix = typeof env.ZT_KV_PREFIX === 'string' ? env.ZT_KV_PREFIX : '';
|
|
136
|
+
const ns = normalizeNamespace(params.namespace);
|
|
137
|
+
const parts = [];
|
|
138
|
+
if (prefix.trim() !== '')
|
|
139
|
+
parts.push(prefix.trim());
|
|
140
|
+
if (ns !== undefined)
|
|
141
|
+
parts.push(ns);
|
|
142
|
+
parts.push(params.key);
|
|
143
|
+
return parts.join(':');
|
|
144
|
+
};
|
|
145
|
+
const readAndVerifyJson = async (request, env) => {
|
|
146
|
+
const maxBodyBytes = getEnvInt(env, 'ZT_MAX_BODY_BYTES', DEFAULT_MAX_BODY_BYTES);
|
|
147
|
+
const bodyResult = await readBodyBytes(request, maxBodyBytes);
|
|
148
|
+
if (bodyResult.ok === false)
|
|
149
|
+
return { ok: false, response: bodyResult.response };
|
|
150
|
+
const auth = await verifySignedRequest(request, env, bodyResult.bytes);
|
|
151
|
+
if (auth instanceof Response)
|
|
152
|
+
return { ok: false, response: auth };
|
|
153
|
+
const parsed = parseOptionalJson(bodyResult.text);
|
|
154
|
+
if (parsed.ok === false)
|
|
155
|
+
return { ok: false, response: parsed.response };
|
|
156
|
+
return { ok: true, payload: parsed.payload, bodyBytes: bodyResult.bytes };
|
|
157
|
+
};
|
|
158
|
+
const parseGetPayload = (payload) => {
|
|
159
|
+
if (!isRecord(payload)) {
|
|
160
|
+
return {
|
|
161
|
+
ok: false,
|
|
162
|
+
response: toErrorResponse(400, 'VALIDATION_ERROR', 'Invalid body'),
|
|
163
|
+
};
|
|
164
|
+
}
|
|
165
|
+
const key = payload['key'];
|
|
166
|
+
const type = payload['type'];
|
|
167
|
+
if (!isString(key) || key.trim() === '') {
|
|
168
|
+
return {
|
|
169
|
+
ok: false,
|
|
170
|
+
response: toErrorResponse(400, 'VALIDATION_ERROR', 'key is required'),
|
|
171
|
+
};
|
|
172
|
+
}
|
|
173
|
+
const typeValue = type === 'text' || type === 'arrayBuffer' || type === 'json' ? type : 'text';
|
|
174
|
+
return { ok: true, namespace: normalizeNamespace(payload['namespace']), key, type: typeValue };
|
|
175
|
+
};
|
|
176
|
+
const handleGet = async (request, env) => {
|
|
177
|
+
const check = await readAndVerifyJson(request, env);
|
|
178
|
+
if (check.ok === false)
|
|
179
|
+
return check.response;
|
|
180
|
+
const cache = requireCache(env);
|
|
181
|
+
if (cache instanceof Response)
|
|
182
|
+
return cache;
|
|
183
|
+
const parsed = parseGetPayload(check.payload);
|
|
184
|
+
if (parsed.ok === false)
|
|
185
|
+
return parsed.response;
|
|
186
|
+
const storageKey = buildStorageKey(env, { namespace: parsed.namespace, key: parsed.key });
|
|
187
|
+
if (parsed.type === 'json') {
|
|
188
|
+
const value = await cache.get(storageKey, 'json');
|
|
189
|
+
return json(200, { value: value ?? null });
|
|
190
|
+
}
|
|
191
|
+
if (parsed.type === 'arrayBuffer') {
|
|
192
|
+
const value = await cache.get(storageKey, 'arrayBuffer');
|
|
193
|
+
return json(200, { value: value ?? null });
|
|
194
|
+
}
|
|
195
|
+
const value = await cache.get(storageKey);
|
|
196
|
+
return json(200, { value: value ?? null });
|
|
197
|
+
};
|
|
198
|
+
const parsePutPayload = (payload) => {
|
|
199
|
+
if (!isRecord(payload)) {
|
|
200
|
+
return {
|
|
201
|
+
ok: false,
|
|
202
|
+
response: toErrorResponse(400, 'VALIDATION_ERROR', 'Invalid body'),
|
|
203
|
+
};
|
|
204
|
+
}
|
|
205
|
+
const key = payload['key'];
|
|
206
|
+
if (!isString(key) || key.trim() === '') {
|
|
207
|
+
return {
|
|
208
|
+
ok: false,
|
|
209
|
+
response: toErrorResponse(400, 'VALIDATION_ERROR', 'key is required'),
|
|
210
|
+
};
|
|
211
|
+
}
|
|
212
|
+
const ttlSeconds = payload['ttlSeconds'];
|
|
213
|
+
const ttl = typeof ttlSeconds === 'number' && Number.isFinite(ttlSeconds) && ttlSeconds > 0
|
|
214
|
+
? ttlSeconds
|
|
215
|
+
: undefined;
|
|
216
|
+
return {
|
|
217
|
+
ok: true,
|
|
218
|
+
namespace: normalizeNamespace(payload['namespace']),
|
|
219
|
+
key,
|
|
220
|
+
value: payload['value'],
|
|
221
|
+
ttlSeconds: ttl,
|
|
222
|
+
};
|
|
223
|
+
};
|
|
224
|
+
const handlePut = async (request, env) => {
|
|
225
|
+
const check = await readAndVerifyJson(request, env);
|
|
226
|
+
if (check.ok === false)
|
|
227
|
+
return check.response;
|
|
228
|
+
const cache = requireCache(env);
|
|
229
|
+
if (cache instanceof Response)
|
|
230
|
+
return cache;
|
|
231
|
+
const parsed = parsePutPayload(check.payload);
|
|
232
|
+
if (parsed.ok === false)
|
|
233
|
+
return parsed.response;
|
|
234
|
+
const storageKey = buildStorageKey(env, { namespace: parsed.namespace, key: parsed.key });
|
|
235
|
+
const value = JSON.stringify(parsed.value);
|
|
236
|
+
const options = {};
|
|
237
|
+
if (parsed.ttlSeconds !== undefined) {
|
|
238
|
+
options.expirationTtl = Math.floor(parsed.ttlSeconds);
|
|
239
|
+
}
|
|
240
|
+
await cache.put(storageKey, value, options);
|
|
241
|
+
return json(200, { ok: true });
|
|
242
|
+
};
|
|
243
|
+
const parseDeletePayload = (payload) => {
|
|
244
|
+
if (!isRecord(payload)) {
|
|
245
|
+
return {
|
|
246
|
+
ok: false,
|
|
247
|
+
response: toErrorResponse(400, 'VALIDATION_ERROR', 'Invalid body'),
|
|
248
|
+
};
|
|
249
|
+
}
|
|
250
|
+
const key = payload['key'];
|
|
251
|
+
if (!isString(key) || key.trim() === '') {
|
|
252
|
+
return {
|
|
253
|
+
ok: false,
|
|
254
|
+
response: toErrorResponse(400, 'VALIDATION_ERROR', 'key is required'),
|
|
255
|
+
};
|
|
256
|
+
}
|
|
257
|
+
return { ok: true, namespace: normalizeNamespace(payload['namespace']), key };
|
|
258
|
+
};
|
|
259
|
+
const handleDelete = async (request, env) => {
|
|
260
|
+
const check = await readAndVerifyJson(request, env);
|
|
261
|
+
if (check.ok === false)
|
|
262
|
+
return check.response;
|
|
263
|
+
const cache = requireCache(env);
|
|
264
|
+
if (cache instanceof Response)
|
|
265
|
+
return cache;
|
|
266
|
+
const parsed = parseDeletePayload(check.payload);
|
|
267
|
+
if (parsed.ok === false)
|
|
268
|
+
return parsed.response;
|
|
269
|
+
const storageKey = buildStorageKey(env, { namespace: parsed.namespace, key: parsed.key });
|
|
270
|
+
await cache.delete(storageKey);
|
|
271
|
+
return json(200, { ok: true });
|
|
272
|
+
};
|
|
273
|
+
const parseListPayload = (payload) => {
|
|
274
|
+
if (payload === null)
|
|
275
|
+
return { ok: true, params: {} };
|
|
276
|
+
if (!isRecord(payload)) {
|
|
277
|
+
return {
|
|
278
|
+
ok: false,
|
|
279
|
+
response: toErrorResponse(400, 'VALIDATION_ERROR', 'Invalid body'),
|
|
280
|
+
};
|
|
281
|
+
}
|
|
282
|
+
const namespace = normalizeNamespace(payload['namespace']);
|
|
283
|
+
const prefix = isString(payload['prefix']) ? payload['prefix'] : undefined;
|
|
284
|
+
const cursor = isString(payload['cursor']) ? payload['cursor'] : undefined;
|
|
285
|
+
const limitRaw = payload['limit'];
|
|
286
|
+
const limitParsed = typeof limitRaw === 'number' && Number.isFinite(limitRaw) ? Math.floor(limitRaw) : undefined;
|
|
287
|
+
return { ok: true, params: { namespace, prefix, cursor, limit: limitParsed } };
|
|
288
|
+
};
|
|
289
|
+
const handleList = async (request, env) => {
|
|
290
|
+
const check = await readAndVerifyJson(request, env);
|
|
291
|
+
if (check.ok === false)
|
|
292
|
+
return check.response;
|
|
293
|
+
const cache = requireCache(env);
|
|
294
|
+
if (cache instanceof Response)
|
|
295
|
+
return cache;
|
|
296
|
+
const parsed = parseListPayload(check.payload);
|
|
297
|
+
if (parsed.ok === false)
|
|
298
|
+
return parsed.response;
|
|
299
|
+
const envLimit = getEnvInt(env, 'ZT_KV_LIST_LIMIT', DEFAULT_LIST_LIMIT);
|
|
300
|
+
const requested = parsed.params.limit ?? envLimit;
|
|
301
|
+
const limit = Math.max(1, Math.min(requested, envLimit));
|
|
302
|
+
const prefixKey = parsed.params.prefix;
|
|
303
|
+
const nsPrefix = normalizeNamespace(parsed.params.namespace);
|
|
304
|
+
const basePrefix = buildStorageKey(env, { namespace: nsPrefix, key: '' });
|
|
305
|
+
const fullPrefix = prefixKey === undefined ? basePrefix : `${basePrefix}${prefixKey}`;
|
|
306
|
+
const out = await cache.list({ prefix: fullPrefix, limit, cursor: parsed.params.cursor });
|
|
307
|
+
return json(200, {
|
|
308
|
+
keys: out.keys.map((k) => k.name),
|
|
309
|
+
cursor: out.cursor,
|
|
310
|
+
listComplete: out.list_complete,
|
|
311
|
+
});
|
|
312
|
+
};
|
|
313
|
+
export const ZintrustKvProxy = Object.freeze({
|
|
314
|
+
_ZINTRUST_CLOUDFLARE_KV_PROXY_VERSION: '0.1.15',
|
|
315
|
+
_ZINTRUST_CLOUDFLARE_KV_PROXY_BUILD_DATE: '2026-04-20T20:59:45.272Z',
|
|
316
|
+
async fetch(request, env) {
|
|
317
|
+
const url = new URL(request.url);
|
|
318
|
+
const methodError = RequestValidator.requirePost(request.method);
|
|
319
|
+
if (methodError !== null) {
|
|
320
|
+
return toErrorResponse(405, methodError.code, 'Method not allowed');
|
|
321
|
+
}
|
|
322
|
+
switch (url.pathname) {
|
|
323
|
+
case '/zin/kv/get':
|
|
324
|
+
return handleGet(request, env);
|
|
325
|
+
case '/zin/kv/put':
|
|
326
|
+
return handlePut(request, env);
|
|
327
|
+
case '/zin/kv/delete':
|
|
328
|
+
return handleDelete(request, env);
|
|
329
|
+
case '/zin/kv/list':
|
|
330
|
+
return handleList(request, env);
|
|
331
|
+
default:
|
|
332
|
+
return toErrorResponse(404, 'NOT_FOUND', 'Not found');
|
|
333
|
+
}
|
|
334
|
+
},
|
|
335
|
+
});
|
|
336
|
+
export default ZintrustKvProxy;
|
package/package.json
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@zintrust/cloudflare-kv-proxy",
|
|
3
|
+
"version": "0.7.9",
|
|
4
|
+
"description": "Cloudflare KV proxy package for ZinTrust.",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"private": false,
|
|
7
|
+
"exports": {
|
|
8
|
+
".": {
|
|
9
|
+
"types": "./dist/index.d.ts",
|
|
10
|
+
"default": "./dist/index.js"
|
|
11
|
+
}
|
|
12
|
+
},
|
|
13
|
+
"files": [
|
|
14
|
+
"dist"
|
|
15
|
+
],
|
|
16
|
+
"engines": {
|
|
17
|
+
"node": ">=20.0.0"
|
|
18
|
+
},
|
|
19
|
+
"publishConfig": {
|
|
20
|
+
"access": "public"
|
|
21
|
+
},
|
|
22
|
+
"peerDependencies": {
|
|
23
|
+
"@zintrust/core": "^0.7.9"
|
|
24
|
+
},
|
|
25
|
+
"keywords": [
|
|
26
|
+
"zintrust",
|
|
27
|
+
"cloudflare",
|
|
28
|
+
"kv",
|
|
29
|
+
"proxy",
|
|
30
|
+
"workers"
|
|
31
|
+
],
|
|
32
|
+
"scripts": {
|
|
33
|
+
"build": "tsc -p tsconfig.json && tsc-alias -p tsconfig.json",
|
|
34
|
+
"type-check": "tsc -p tsconfig.json --noEmit"
|
|
35
|
+
}
|
|
36
|
+
}
|