toiljs 0.0.127 → 0.0.129
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/CHANGELOG.md +29 -0
- package/assets/image-codec-LICENSES.txt +4599 -0
- package/assets/image-codec-build.json +10 -0
- package/assets/image-codec.wasm +0 -0
- package/build/backend/index.d.ts +1 -0
- package/build/backend/index.js +8 -3
- package/build/backend/security.d.ts +4 -0
- package/build/backend/security.js +31 -0
- package/build/cli/index.js +11 -39
- package/build/client/components/Script.js +28 -17
- package/build/client/files.d.ts +17 -0
- package/build/client/files.js +119 -0
- package/build/client/html.d.ts +1 -0
- package/build/client/html.js +8 -0
- package/build/client/index.d.ts +1 -0
- package/build/client/index.js +1 -0
- package/build/client/security.d.ts +4 -0
- package/build/client/security.js +55 -0
- package/build/client/ssr/markers.js +6 -1
- package/build/compiler/config.d.ts +2 -0
- package/build/compiler/config.js +1 -0
- package/build/compiler/generate.d.ts +1 -1
- package/build/compiler/generate.js +1 -37
- package/build/compiler/index.d.ts +1 -0
- package/build/compiler/index.js +56 -1
- package/build/compiler/security-deployment.d.ts +3 -0
- package/build/compiler/security-deployment.js +88 -0
- package/build/compiler/security.d.ts +7 -0
- package/build/compiler/security.js +74 -0
- package/build/compiler/sri.js +10 -3
- package/build/compiler/toil-docs.generated.js +35 -28
- package/build/compiler/vite.js +2 -0
- package/build/devserver/config/env.d.ts +6 -0
- package/build/devserver/config/env.js +10 -2
- package/build/devserver/daemon/catalog.d.ts +1 -0
- package/build/devserver/daemon/catalog.js +10 -4
- package/build/devserver/daemon/host.d.ts +5 -1
- package/build/devserver/daemon/host.js +8 -4
- package/build/devserver/daemon/http.d.ts +14 -0
- package/build/devserver/daemon/http.js +90 -0
- package/build/devserver/daemon/index.d.ts +21 -1
- package/build/devserver/daemon/index.js +109 -21
- package/build/devserver/db/atomic.d.ts +8 -0
- package/build/devserver/db/atomic.js +133 -0
- package/build/devserver/db/catalog.d.ts +7 -0
- package/build/devserver/db/catalog.js +17 -0
- package/build/devserver/db/changes.d.ts +5 -0
- package/build/devserver/db/changes.js +49 -0
- package/build/devserver/db/database.d.ts +7 -0
- package/build/devserver/db/database.js +251 -41
- package/build/devserver/db/derives.d.ts +4 -5
- package/build/devserver/db/derives.js +7 -76
- package/build/devserver/db/document-scan.d.ts +2 -0
- package/build/devserver/db/document-scan.js +123 -0
- package/build/devserver/db/limits.d.ts +16 -0
- package/build/devserver/db/limits.js +92 -14
- package/build/devserver/db/types.d.ts +15 -0
- package/build/devserver/db/types.js +9 -0
- package/build/devserver/files/dev.d.ts +3 -0
- package/build/devserver/files/dev.js +29 -0
- package/build/devserver/files/disk.d.ts +17 -0
- package/build/devserver/files/disk.js +369 -0
- package/build/devserver/files/signatures.d.ts +16 -0
- package/build/devserver/files/signatures.js +151 -0
- package/build/devserver/http/proxy.js +11 -3
- package/build/devserver/http/runtime.js +36 -9
- package/build/devserver/images/index.d.ts +9 -0
- package/build/devserver/images/index.js +87 -0
- package/build/devserver/images/worker.d.mts +1 -0
- package/build/devserver/images/worker.mjs +24 -0
- package/build/devserver/index.d.ts +3 -1
- package/build/devserver/production.js +5 -3
- package/build/devserver/runtime/host.d.ts +4 -0
- package/build/devserver/runtime/host.js +6 -2
- package/build/devserver/runtime/module.d.ts +15 -0
- package/build/devserver/runtime/module.js +105 -7
- package/build/devserver/server.js +13 -1
- package/build/devserver/stream/host.d.ts +2 -0
- package/build/devserver/stream/host.js +2 -1
- package/build/devserver/stream/index.js +2 -0
- package/build/io/derive-metadata.d.ts +7 -0
- package/build/io/derive-metadata.js +44 -0
- package/build/io/index.d.ts +1 -0
- package/build/io/index.js +1 -0
- package/build/shared/index.d.ts +1 -0
- package/build/shared/index.js +1 -0
- package/build/shared/security.d.ts +5 -0
- package/build/shared/security.js +80 -0
- package/docs/auth/vectors-v1.json +41 -0
- package/examples/basic/client/routes/rest.tsx +1 -1
- package/examples/basic/server/routes/Guestbook.ts +1 -1
- package/package.json +20 -7
- package/scripts/build-image-codec.mjs +79 -0
- package/scripts/gen-auth-vectors.mjs +132 -0
- package/scripts/gen-native-atomic-fixture.mjs +39 -0
- package/scripts/gen-native-blob-fixture.mjs +42 -0
- package/scripts/gen-native-image-fixture.mjs +65 -0
- package/scripts/gen-native-staging-fixture.mjs +41 -0
- package/scripts/gen-server-types.mjs +82 -0
- package/scripts/gen-toil-docs.mjs +19 -7
- package/server/auth/AuthController.ts +15 -234
- package/server/auth/AuthMaintenance.ts +177 -0
- package/server/auth/AuthStore.ts +198 -0
- package/server/auth/SessionEpochs.ts +38 -9
- package/server/globals/auth.ts +56 -0
- package/server/globals/userid.ts +4 -5
- package/server/globals.d.ts +37 -0
- package/server/runtime/envelope.ts +2 -1
- package/server/runtime/exports/index.ts +2 -1
- package/server/runtime/files/blobs.ts +341 -0
- package/server/runtime/files/images.ts +36 -0
- package/server/runtime/http/percent.ts +5 -4
- package/server/runtime/index.ts +5 -0
- package/server/runtime/response.ts +20 -0
- package/server/runtime/rest/RouteContext.ts +5 -4
- package/std/server/abort/abort.d.ts +25 -0
- package/std/server/env/Server.d.ts +47 -0
- package/std/server/envelope.d.ts +38 -0
- package/std/server/exports/index.d.ts +20 -0
- package/std/server/exports/render.d.ts +15 -0
- package/std/server/files/blobs.d.ts +50 -0
- package/std/server/files/images.d.ts +36 -0
- package/std/server/handlers/ToilHandler.d.ts +29 -0
- package/std/server/http/base64.d.ts +21 -0
- package/std/server/http/cookie.d.ts +127 -0
- package/std/server/http/cookies.d.ts +56 -0
- package/std/server/http/date.d.ts +17 -0
- package/std/server/http/percent.d.ts +19 -0
- package/std/server/http/securecookies.d.ts +55 -0
- package/std/server/index.d.ts +34 -0
- package/std/server/lang/Potential.d.ts +6 -0
- package/std/server/memory.d.ts +42 -0
- package/std/server/request.d.ts +47 -0
- package/std/server/response.d.ts +90 -0
- package/std/server/rest/Rest.d.ts +23 -0
- package/std/server/rest/RestHandler.d.ts +14 -0
- package/std/server/rest/RouteContext.d.ts +33 -0
- package/std/server/rest/match.d.ts +14 -0
- package/std/server/rpc/Rpc.d.ts +37 -0
- package/std/server/ssr/Ssr.d.ts +27 -0
- package/std/server/ssr/encode.d.ts +26 -0
- package/std/server/ssr/escape.d.ts +22 -0
- package/std/server/ssr/slots.d.ts +91 -0
- package/std/server/time.d.ts +24 -0
- package/tsconfig.json +11 -2
|
@@ -0,0 +1,341 @@
|
|
|
1
|
+
import { Environment } from '../../globals/environment';
|
|
2
|
+
import { HmacImportParams, HmacParams, ALG_SHA_256, FMT_RAW, USAGE_SIGN } from 'crypto';
|
|
3
|
+
import { base64UrlEncode } from '../http/base64';
|
|
4
|
+
|
|
5
|
+
function utf8(text: string): Uint8Array {
|
|
6
|
+
return Uint8Array.wrap(String.UTF8.encode(text));
|
|
7
|
+
}
|
|
8
|
+
function hmac(key: Uint8Array, text: string): Uint8Array {
|
|
9
|
+
const imported = crypto.subtle.importKey(
|
|
10
|
+
FMT_RAW,
|
|
11
|
+
key,
|
|
12
|
+
new HmacImportParams(ALG_SHA_256),
|
|
13
|
+
false,
|
|
14
|
+
USAGE_SIGN,
|
|
15
|
+
);
|
|
16
|
+
return crypto.subtle.sign(new HmacParams(), imported, utf8(text));
|
|
17
|
+
}
|
|
18
|
+
function uri(text: string): string {
|
|
19
|
+
return encodeURIComponent(text)
|
|
20
|
+
.replaceAll('!', '%21')
|
|
21
|
+
.replaceAll("'", '%27')
|
|
22
|
+
.replaceAll('(', '%28')
|
|
23
|
+
.replaceAll(')', '%29')
|
|
24
|
+
.replaceAll('*', '%2A');
|
|
25
|
+
}
|
|
26
|
+
function pathUri(text: string): string {
|
|
27
|
+
const parts = text.split('/');
|
|
28
|
+
for (let i = 0; i < parts.length; i++) {
|
|
29
|
+
if (parts[i] == '.' || parts[i] == '..') throw new Error('Invalid blob path');
|
|
30
|
+
parts[i] = uri(parts[i]);
|
|
31
|
+
}
|
|
32
|
+
return parts.join('/');
|
|
33
|
+
}
|
|
34
|
+
function safePath(text: string, allowSlash: bool): bool {
|
|
35
|
+
for (let i = 0; i < text.length; i++) {
|
|
36
|
+
const c = text.charCodeAt(i);
|
|
37
|
+
if (
|
|
38
|
+
(c >= 48 && c <= 57) ||
|
|
39
|
+
(c >= 65 && c <= 90) ||
|
|
40
|
+
(c >= 97 && c <= 122) ||
|
|
41
|
+
c == 45 ||
|
|
42
|
+
c == 95 ||
|
|
43
|
+
(allowSlash && (c == 47 || c == 46 || c == 126))
|
|
44
|
+
)
|
|
45
|
+
continue;
|
|
46
|
+
return false;
|
|
47
|
+
}
|
|
48
|
+
return true;
|
|
49
|
+
}
|
|
50
|
+
function required(name: string, secure: bool = false): string {
|
|
51
|
+
const value = secure ? Environment.getSecure(name) : Environment.get(name);
|
|
52
|
+
if (value == null || value.length == 0)
|
|
53
|
+
throw new Error('Blob storage is not configured: ' + name);
|
|
54
|
+
return value;
|
|
55
|
+
}
|
|
56
|
+
function ttl(seconds: i32): void {
|
|
57
|
+
if (seconds < 1 || seconds > 900) throw new Error('Blob URL lifetime must be 1..900 seconds');
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
@data
|
|
61
|
+
export class BlobField {
|
|
62
|
+
name: string = '';
|
|
63
|
+
value: string = '';
|
|
64
|
+
constructor(name: string = '', value: string = '') {
|
|
65
|
+
this.name = name;
|
|
66
|
+
this.value = value;
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/** Send these fields first and the file last as multipart/form-data. */
|
|
71
|
+
@data
|
|
72
|
+
export class BlobUpload {
|
|
73
|
+
url: string = '';
|
|
74
|
+
fields: BlobField[] = [];
|
|
75
|
+
size: f64 = 0;
|
|
76
|
+
expiresAt: f64 = 0;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/** Server-only credentials for a bucket endpoint supporting SigV4 POST policies.
|
|
80
|
+
* The endpoint includes the bucket, e.g. https://bucket.s3.region.amazonaws.com
|
|
81
|
+
* or https://storage.example/bucket. Use credentials limited to this bucket/prefix. */
|
|
82
|
+
export class BlobStorage {
|
|
83
|
+
private origin: string = '';
|
|
84
|
+
private host: string = '';
|
|
85
|
+
private basePath: string = '';
|
|
86
|
+
private cachedDate: string = '';
|
|
87
|
+
private cachedKey: Uint8Array = new Uint8Array(0);
|
|
88
|
+
constructor(
|
|
89
|
+
public readonly endpoint: string,
|
|
90
|
+
public readonly bucket: string,
|
|
91
|
+
public readonly region: string,
|
|
92
|
+
private accessKey: string,
|
|
93
|
+
private secretKey: string,
|
|
94
|
+
public readonly prefix: string = '',
|
|
95
|
+
private sessionToken: string = '',
|
|
96
|
+
) {
|
|
97
|
+
while (endpoint.endsWith('/')) endpoint = endpoint.slice(0, endpoint.length - 1);
|
|
98
|
+
this.endpoint = endpoint;
|
|
99
|
+
const scheme = endpoint.startsWith('https://')
|
|
100
|
+
? 8
|
|
101
|
+
: endpoint.startsWith('http://127.0.0.1:')
|
|
102
|
+
? 7
|
|
103
|
+
: 0;
|
|
104
|
+
if (scheme == 0)
|
|
105
|
+
throw new Error('Blob endpoint must use HTTPS (loopback HTTP is allowed in dev)');
|
|
106
|
+
const slash = endpoint.indexOf('/', scheme);
|
|
107
|
+
this.origin = slash < 0 ? endpoint : endpoint.slice(0, slash);
|
|
108
|
+
this.host = this.origin.slice(scheme);
|
|
109
|
+
this.basePath = slash < 0 ? '' : endpoint.slice(slash);
|
|
110
|
+
if (this.host != this.host.toLowerCase() || this.host.length == 0 || this.host.length > 260)
|
|
111
|
+
throw new Error('Invalid blob endpoint host');
|
|
112
|
+
for (let i = 0; i < this.host.length; i++) {
|
|
113
|
+
const c = this.host.charCodeAt(i);
|
|
114
|
+
if (!((c >= 97 && c <= 122) || (c >= 48 && c <= 57) || c == 45 || c == 46 || c == 58))
|
|
115
|
+
throw new Error('Invalid blob endpoint host');
|
|
116
|
+
}
|
|
117
|
+
if (
|
|
118
|
+
!safePath(this.basePath, true) ||
|
|
119
|
+
!safePath(prefix, true) ||
|
|
120
|
+
prefix.length > 256 ||
|
|
121
|
+
prefix.startsWith('/') ||
|
|
122
|
+
prefix.endsWith('/') ||
|
|
123
|
+
prefix.includes('//')
|
|
124
|
+
)
|
|
125
|
+
throw new Error('Invalid blob prefix or endpoint path');
|
|
126
|
+
pathUri(this.basePath);
|
|
127
|
+
pathUri(prefix);
|
|
128
|
+
if (
|
|
129
|
+
endpoint.length > 1024 ||
|
|
130
|
+
sessionToken.length > 4096 ||
|
|
131
|
+
accessKey.length > 128 ||
|
|
132
|
+
secretKey.length > 1024 ||
|
|
133
|
+
region.length > 64
|
|
134
|
+
)
|
|
135
|
+
throw new Error('Blob configuration exceeds size limits');
|
|
136
|
+
if (
|
|
137
|
+
bucket.length == 0 ||
|
|
138
|
+
bucket.length > 63 ||
|
|
139
|
+
bucket.includes('/') ||
|
|
140
|
+
bucket.includes('"') ||
|
|
141
|
+
region.length == 0 ||
|
|
142
|
+
!safePath(region, false) ||
|
|
143
|
+
accessKey.length == 0 ||
|
|
144
|
+
accessKey.includes('/') ||
|
|
145
|
+
secretKey.length == 0
|
|
146
|
+
)
|
|
147
|
+
throw new Error('Invalid blob credentials');
|
|
148
|
+
}
|
|
149
|
+
static fromEnvironment(): BlobStorage {
|
|
150
|
+
const prefix = Environment.get('BLOB_PREFIX');
|
|
151
|
+
const token = Environment.getSecure('BLOB_SESSION_TOKEN');
|
|
152
|
+
return new BlobStorage(
|
|
153
|
+
required('BLOB_ENDPOINT'),
|
|
154
|
+
required('BLOB_BUCKET'),
|
|
155
|
+
required('BLOB_REGION'),
|
|
156
|
+
required('BLOB_ACCESS_KEY_ID', true),
|
|
157
|
+
required('BLOB_SECRET_ACCESS_KEY', true),
|
|
158
|
+
prefix == null ? '' : prefix,
|
|
159
|
+
token == null ? '' : token,
|
|
160
|
+
);
|
|
161
|
+
}
|
|
162
|
+
private key(date: string): Uint8Array {
|
|
163
|
+
if (this.cachedDate != date) {
|
|
164
|
+
this.cachedKey = hmac(
|
|
165
|
+
hmac(hmac(hmac(utf8('AWS4' + this.secretKey), date), this.region), 's3'),
|
|
166
|
+
'aws4_request',
|
|
167
|
+
);
|
|
168
|
+
this.cachedDate = date;
|
|
169
|
+
}
|
|
170
|
+
return this.cachedKey;
|
|
171
|
+
}
|
|
172
|
+
private stamp(atMillis: i64): string {
|
|
173
|
+
const iso = new Date(atMillis).toISOString();
|
|
174
|
+
if (iso.length != 24) throw new Error('Invalid blob signing clock');
|
|
175
|
+
return iso.slice(0, 19).replaceAll('-', '').replaceAll(':', '') + 'Z';
|
|
176
|
+
}
|
|
177
|
+
/** Useful for server-side storage adapters; application ACLs run before signing. */
|
|
178
|
+
presign(method: string, objectKey: string, atMillis: i64, expiresSecs: i32 = 60): string {
|
|
179
|
+
if (expiresSecs < 1 || expiresSecs > 604800) throw new Error('Invalid blob URL lifetime');
|
|
180
|
+
if (method != 'GET' && method != 'HEAD' && method != 'DELETE')
|
|
181
|
+
throw new Error('Invalid blob URL method');
|
|
182
|
+
if (objectKey.length == 0 || utf8(objectKey).length > 1024)
|
|
183
|
+
throw new Error('Invalid blob object key');
|
|
184
|
+
const date = this.stamp(atMillis),
|
|
185
|
+
day = date.slice(0, 8);
|
|
186
|
+
const scope = day + '/' + this.region + '/s3/aws4_request';
|
|
187
|
+
const fields = new Array<string>();
|
|
188
|
+
fields.push('X-Amz-Algorithm=AWS4-HMAC-SHA256');
|
|
189
|
+
fields.push('X-Amz-Credential=' + uri(this.accessKey + '/' + scope));
|
|
190
|
+
fields.push('X-Amz-Date=' + date);
|
|
191
|
+
fields.push('X-Amz-Expires=' + expiresSecs.toString());
|
|
192
|
+
if (this.sessionToken.length > 0)
|
|
193
|
+
fields.push('X-Amz-Security-Token=' + uri(this.sessionToken));
|
|
194
|
+
fields.push('X-Amz-SignedHeaders=host');
|
|
195
|
+
const query = fields.join('&');
|
|
196
|
+
const path = this.basePath + '/' + pathUri(objectKey);
|
|
197
|
+
const canonical =
|
|
198
|
+
method +
|
|
199
|
+
'\n' +
|
|
200
|
+
path +
|
|
201
|
+
'\n' +
|
|
202
|
+
query +
|
|
203
|
+
'\nhost:' +
|
|
204
|
+
this.host +
|
|
205
|
+
'\n\nhost\nUNSIGNED-PAYLOAD';
|
|
206
|
+
const toSign =
|
|
207
|
+
'AWS4-HMAC-SHA256\n' +
|
|
208
|
+
date +
|
|
209
|
+
'\n' +
|
|
210
|
+
scope +
|
|
211
|
+
'\n' +
|
|
212
|
+
crypto.toHex(crypto.sha256(utf8(canonical)));
|
|
213
|
+
return (
|
|
214
|
+
this.origin +
|
|
215
|
+
path +
|
|
216
|
+
'?' +
|
|
217
|
+
query +
|
|
218
|
+
'&X-Amz-Signature=' +
|
|
219
|
+
crypto.toHex(hmac(this.key(day), toSign))
|
|
220
|
+
);
|
|
221
|
+
}
|
|
222
|
+
upload(
|
|
223
|
+
objectKey: string,
|
|
224
|
+
size: f64,
|
|
225
|
+
contentType: string,
|
|
226
|
+
atMillis: i64,
|
|
227
|
+
expiresSecs: i32 = 300,
|
|
228
|
+
): BlobUpload {
|
|
229
|
+
ttl(expiresSecs);
|
|
230
|
+
if (size < 0 || size > 1073741824 || Math.floor(size) != size || !isFinite(size))
|
|
231
|
+
throw new Error('Blob upload size must be 0..1 GiB');
|
|
232
|
+
if (contentType.length == 0 || contentType.length > 128 || !contentType.includes('/'))
|
|
233
|
+
throw new Error('Invalid blob content type');
|
|
234
|
+
for (let i = 0; i < contentType.length; i++) {
|
|
235
|
+
const c = contentType.charCodeAt(i);
|
|
236
|
+
if (c < 32 || c > 126) throw new Error('Invalid blob content type');
|
|
237
|
+
}
|
|
238
|
+
if (objectKey.length == 0 || utf8(objectKey).length > 1024)
|
|
239
|
+
throw new Error('Invalid blob object key');
|
|
240
|
+
const date = this.stamp(atMillis),
|
|
241
|
+
day = date.slice(0, 8),
|
|
242
|
+
scope = day + '/' + this.region + '/s3/aws4_request';
|
|
243
|
+
const ticket = new BlobUpload();
|
|
244
|
+
ticket.url = this.endpoint;
|
|
245
|
+
ticket.size = size;
|
|
246
|
+
ticket.expiresAt = <f64>(atMillis + <i64>expiresSecs * 1000);
|
|
247
|
+
ticket.fields.push(new BlobField('key', objectKey));
|
|
248
|
+
ticket.fields.push(new BlobField('Content-Type', contentType));
|
|
249
|
+
ticket.fields.push(new BlobField('Content-Disposition', 'attachment'));
|
|
250
|
+
ticket.fields.push(new BlobField('success_action_status', '204'));
|
|
251
|
+
ticket.fields.push(new BlobField('x-amz-algorithm', 'AWS4-HMAC-SHA256'));
|
|
252
|
+
ticket.fields.push(new BlobField('x-amz-credential', this.accessKey + '/' + scope));
|
|
253
|
+
ticket.fields.push(new BlobField('x-amz-date', date));
|
|
254
|
+
if (this.sessionToken.length > 0)
|
|
255
|
+
ticket.fields.push(new BlobField('x-amz-security-token', this.sessionToken));
|
|
256
|
+
let conditions = '{"bucket":' + JSON.stringify<string>(this.bucket) + '}';
|
|
257
|
+
for (let i = 0; i < ticket.fields.length; i++) {
|
|
258
|
+
const field = ticket.fields[i];
|
|
259
|
+
conditions +=
|
|
260
|
+
',{' +
|
|
261
|
+
JSON.stringify<string>(field.name) +
|
|
262
|
+
':' +
|
|
263
|
+
JSON.stringify<string>(field.value) +
|
|
264
|
+
'}';
|
|
265
|
+
}
|
|
266
|
+
conditions +=
|
|
267
|
+
',["content-length-range",' +
|
|
268
|
+
(<u64>size).toString() +
|
|
269
|
+
',' +
|
|
270
|
+
(<u64>size).toString() +
|
|
271
|
+
']';
|
|
272
|
+
const policyText =
|
|
273
|
+
'{"expiration":' +
|
|
274
|
+
JSON.stringify<string>(new Date(atMillis + <i64>expiresSecs * 1000).toISOString()) +
|
|
275
|
+
',"conditions":[' +
|
|
276
|
+
conditions +
|
|
277
|
+
']}';
|
|
278
|
+
let policy = base64UrlEncode(utf8(policyText)).replaceAll('-', '+').replaceAll('_', '/');
|
|
279
|
+
while (policy.length % 4 != 0) policy += '=';
|
|
280
|
+
ticket.fields.push(new BlobField('policy', policy));
|
|
281
|
+
ticket.fields.push(
|
|
282
|
+
new BlobField('x-amz-signature', crypto.toHex(hmac(this.key(day), policy))),
|
|
283
|
+
);
|
|
284
|
+
return ticket;
|
|
285
|
+
}
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
/** A typed file namespace. Bytes stream directly between client and storage;
|
|
289
|
+
* keys remain ordinary @data values, with access controlled by application routes. */
|
|
290
|
+
export class Blobs<K> {
|
|
291
|
+
private storage: BlobStorage | null;
|
|
292
|
+
constructor(
|
|
293
|
+
private namespace: string,
|
|
294
|
+
storage: BlobStorage | null = null,
|
|
295
|
+
) {
|
|
296
|
+
if (namespace.length == 0 || namespace.length > 64 || !safePath(namespace, false))
|
|
297
|
+
throw new Error('Invalid blob namespace');
|
|
298
|
+
this.storage = storage;
|
|
299
|
+
}
|
|
300
|
+
private config(): BlobStorage {
|
|
301
|
+
let storage = this.storage;
|
|
302
|
+
if (storage == null) {
|
|
303
|
+
storage = BlobStorage.fromEnvironment();
|
|
304
|
+
this.storage = storage;
|
|
305
|
+
}
|
|
306
|
+
return storage;
|
|
307
|
+
}
|
|
308
|
+
private objectKey(key: K): string {
|
|
309
|
+
const storage = this.config();
|
|
310
|
+
const prefix = storage.prefix.length == 0 ? '' : storage.prefix + '/';
|
|
311
|
+
const bytes = key.encode();
|
|
312
|
+
if (bytes.length > 4096) throw new Error('Encoded blob key exceeds 4096 bytes');
|
|
313
|
+
return prefix + this.namespace + '/' + crypto.toHex(crypto.sha256(bytes));
|
|
314
|
+
}
|
|
315
|
+
upload(
|
|
316
|
+
key: K,
|
|
317
|
+
size: f64,
|
|
318
|
+
contentType: string = 'application/octet-stream',
|
|
319
|
+
expiresSecs: i32 = 300,
|
|
320
|
+
): BlobUpload {
|
|
321
|
+
return this.config().upload(
|
|
322
|
+
this.objectKey(key),
|
|
323
|
+
size,
|
|
324
|
+
contentType,
|
|
325
|
+
Date.now(),
|
|
326
|
+
expiresSecs,
|
|
327
|
+
);
|
|
328
|
+
}
|
|
329
|
+
downloadUrl(key: K, expiresSecs: i32 = 60): string {
|
|
330
|
+
ttl(expiresSecs);
|
|
331
|
+
return this.config().presign('GET', this.objectKey(key), Date.now(), expiresSecs);
|
|
332
|
+
}
|
|
333
|
+
headUrl(key: K, expiresSecs: i32 = 60): string {
|
|
334
|
+
ttl(expiresSecs);
|
|
335
|
+
return this.config().presign('HEAD', this.objectKey(key), Date.now(), expiresSecs);
|
|
336
|
+
}
|
|
337
|
+
deleteUrl(key: K, expiresSecs: i32 = 60): string {
|
|
338
|
+
ttl(expiresSecs);
|
|
339
|
+
return this.config().presign('DELETE', this.objectKey(key), Date.now(), expiresSecs);
|
|
340
|
+
}
|
|
341
|
+
}
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
@external('env','image.process')
|
|
2
|
+
declare function imageProcess(ptr:usize,len:i32,mode:i32,width:i32,height:i32,quality:i32):i32;
|
|
3
|
+
@external('env','image.take_result')
|
|
4
|
+
declare function imageTake(ptr:usize,cap:i32):i32;
|
|
5
|
+
|
|
6
|
+
export enum ImageError {None=0,Invalid=2,Unsupported=3,Limit=4,Busy=5,Timeout=6,Unavailable=7,Options=8,Kind=9,Quota=10}
|
|
7
|
+
export enum ImageFormat {Png=1,Jpeg=2}
|
|
8
|
+
export class ImageResult {
|
|
9
|
+
error:ImageError=ImageError.None;
|
|
10
|
+
bytes:Uint8Array=new Uint8Array(0);
|
|
11
|
+
width:u32=0;
|
|
12
|
+
height:u32=0;
|
|
13
|
+
format:ImageFormat=ImageFormat.Png;
|
|
14
|
+
get ok():bool {return this.error==ImageError.None;}
|
|
15
|
+
get contentType():string {return this.format==ImageFormat.Jpeg?'image/jpeg':'image/png';}
|
|
16
|
+
}
|
|
17
|
+
export class Images {
|
|
18
|
+
private static run(input:Uint8Array,mode:i32,width:i32,height:i32,quality:i32):ImageResult {
|
|
19
|
+
const result=new ImageResult();
|
|
20
|
+
const status=imageProcess(input.dataStart,input.byteLength,mode,width,height,quality);
|
|
21
|
+
if(status<0){result.error=<ImageError>(-status);return result;}
|
|
22
|
+
const frame=new Uint8Array(status);
|
|
23
|
+
if(imageTake(frame.dataStart,status)!=status||status<14||frame[0]!=1){result.error=ImageError.Unavailable;return result;}
|
|
24
|
+
result.width=load<u32>(frame.dataStart+1);result.height=load<u32>(frame.dataStart+5);result.format=<ImageFormat>frame[9];
|
|
25
|
+
const length=load<u32>(frame.dataStart+10);
|
|
26
|
+
if(length!=<u32>(status-14)){result.error=ImageError.Unavailable;return result;}
|
|
27
|
+
result.bytes=frame.subarray(14);return result;
|
|
28
|
+
}
|
|
29
|
+
/** Re-encode without EXIF/XMP/IPTC/text/comments, applying orientation.
|
|
30
|
+
* Retains ICC profiles and PNG color descriptors. JPEG is re-encoded. */
|
|
31
|
+
static stripExif(input:Uint8Array,quality:i32=90):ImageResult {return Images.run(input,0,0,0,quality);}
|
|
32
|
+
/** Fit inside the box, retaining aspect ratio and avoiding enlargement. */
|
|
33
|
+
static resize(input:Uint8Array,width:i32,height:i32,quality:i32=90):ImageResult {return Images.run(input,1,width,height,quality);}
|
|
34
|
+
/** Center crop to the requested aspect ratio, avoiding enlargement. */
|
|
35
|
+
static thumbnail(input:Uint8Array,width:i32,height:i32,quality:i32=90):ImageResult {return Images.run(input,2,width,height,quality);}
|
|
36
|
+
}
|
|
@@ -52,15 +52,16 @@ export function percentEncode(s: string): string {
|
|
|
52
52
|
* form-encoded, so `+` is not a space).
|
|
53
53
|
*/
|
|
54
54
|
export function percentDecode(s: string): string {
|
|
55
|
-
const
|
|
55
|
+
const input = Uint8Array.wrap(String.UTF8.encode(s));
|
|
56
|
+
const n = input.length;
|
|
56
57
|
const bytes = new Array<u8>();
|
|
57
58
|
let i = 0;
|
|
58
59
|
while (i < n) {
|
|
59
|
-
const c =
|
|
60
|
+
const c = input[i];
|
|
60
61
|
if (c == 37 && i + 2 < n) {
|
|
61
62
|
// '%'
|
|
62
|
-
const hi = hexVal(
|
|
63
|
-
const lo = hexVal(
|
|
63
|
+
const hi = hexVal(input[i + 1]);
|
|
64
|
+
const lo = hexVal(input[i + 2]);
|
|
64
65
|
if (hi >= 0 && lo >= 0) {
|
|
65
66
|
bytes.push(<u8>((hi << 4) | lo));
|
|
66
67
|
i += 3;
|
package/server/runtime/index.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
/// <reference path="../globals.d.ts" />
|
|
1
2
|
/**
|
|
2
3
|
* Public surface of the toiljs server runtime. The user does
|
|
3
4
|
*
|
|
@@ -41,3 +42,7 @@ export { Cookie, SameSite, CookieEncoding, CookiePrefix, CookieValidation } from
|
|
|
41
42
|
export { Cookies, CookieMap } from './http/cookies';
|
|
42
43
|
export { SecureCookies } from './http/securecookies';
|
|
43
44
|
export { base64UrlEncode, base64UrlDecode } from './http/base64';
|
|
45
|
+
|
|
46
|
+
export { Blobs, BlobStorage, BlobUpload, BlobField } from './files/blobs';
|
|
47
|
+
|
|
48
|
+
export { Images, ImageResult, ImageFormat, ImageError } from './files/images';
|
|
@@ -58,6 +58,11 @@ export class Response {
|
|
|
58
58
|
return r;
|
|
59
59
|
}
|
|
60
60
|
|
|
61
|
+
/** A JSON @data value with an explicit HTTP status. */
|
|
62
|
+
public static data<T>(value: T, status: u16 = 200): Response {
|
|
63
|
+
return Response.json(value.toJSON().toString(), status);
|
|
64
|
+
}
|
|
65
|
+
|
|
61
66
|
/**
|
|
62
67
|
* A raw binary body, defaulting to `application/octet-stream`. Used by `@route`
|
|
63
68
|
* methods with `stream: DataStream.Binary` to ship a `@data` `encode()`.
|
|
@@ -200,3 +205,18 @@ export class Response {
|
|
|
200
205
|
return this.cache(minutes);
|
|
201
206
|
}
|
|
202
207
|
}
|
|
208
|
+
|
|
209
|
+
/** Fill browser security headers at the HTTP serialization boundary. */
|
|
210
|
+
export function ensureSecurityHeaders(response: Response): void {
|
|
211
|
+
// Mirror toiljs/shared's defaults for native edge hosts as well as Node.
|
|
212
|
+
let hasCsp = false;
|
|
213
|
+
let hasCoop = false;
|
|
214
|
+
for (let i = 0; i < response.headers.length; i++) {
|
|
215
|
+
const name = response.headers[i].name.toLowerCase();
|
|
216
|
+
if (name == 'content-security-policy') hasCsp = true;
|
|
217
|
+
if (name == 'cross-origin-opener-policy') hasCoop = true;
|
|
218
|
+
}
|
|
219
|
+
if (!hasCsp) response.setHeader('content-security-policy',
|
|
220
|
+
"default-src 'self'; base-uri 'none'; object-src 'none'; frame-ancestors 'self'; script-src 'none'; script-src-attr 'none'; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob:; font-src 'self' data:; connect-src 'self'; worker-src 'self' blob:; require-trusted-types-for 'script'; trusted-types toil-script dompurify");
|
|
221
|
+
if (!hasCoop) response.setHeader('cross-origin-opener-policy', 'same-origin');
|
|
222
|
+
}
|
|
@@ -6,6 +6,7 @@
|
|
|
6
6
|
*/
|
|
7
7
|
|
|
8
8
|
import { Request } from '../request';
|
|
9
|
+
import { percentDecode } from '../http/percent';
|
|
9
10
|
|
|
10
11
|
// Host import: write the request's UNSPOOFABLE peer IP (the socket's remote
|
|
11
12
|
// address, NOT a client-supplied header) into a guest buffer. Returns the byte
|
|
@@ -40,7 +41,7 @@ export class RouteContext {
|
|
|
40
41
|
return '';
|
|
41
42
|
}
|
|
42
43
|
|
|
43
|
-
/** A query
|
|
44
|
+
/** A decoded query value, or "" if absent. Percent escapes and form `+` are decoded once. */
|
|
44
45
|
query(name: string): string {
|
|
45
46
|
this.ensureQuery();
|
|
46
47
|
const keys = this.queryKeys!;
|
|
@@ -90,11 +91,11 @@ export class RouteContext {
|
|
|
90
91
|
if (pair.length == 0) continue;
|
|
91
92
|
const eq = pair.indexOf('=');
|
|
92
93
|
if (eq < 0) {
|
|
93
|
-
keys.push(pair);
|
|
94
|
+
keys.push(percentDecode(pair.replaceAll('+', ' ')));
|
|
94
95
|
vals.push('');
|
|
95
96
|
} else {
|
|
96
|
-
keys.push(pair.substring(0, eq));
|
|
97
|
-
vals.push(pair.substring(eq + 1));
|
|
97
|
+
keys.push(percentDecode(pair.substring(0, eq).replaceAll('+', ' ')));
|
|
98
|
+
vals.push(percentDecode(pair.substring(eq + 1).replaceAll('+', ' ')));
|
|
98
99
|
}
|
|
99
100
|
}
|
|
100
101
|
}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
// Generated from server/runtime by scripts/gen-server-types.mjs.
|
|
2
|
+
/**
|
|
3
|
+
* AssemblyScript runtime panic hook.
|
|
4
|
+
*
|
|
5
|
+
* Any unhandled `assert()`, out-of-bounds array access, or other
|
|
6
|
+
* runtime failure in the compiled wasm reaches the host's `env::abort`
|
|
7
|
+
* import (see toil-backend's `AbortImport`). For that import to be
|
|
8
|
+
* satisfied at link time the compiled module needs an exported
|
|
9
|
+
* `abort` function with the AS-standard signature; the user's
|
|
10
|
+
* `main.ts` re-exports it as:
|
|
11
|
+
*
|
|
12
|
+
* ```ts
|
|
13
|
+
* export function abort(message: string, fileName: string, line: u32, column: u32): void {
|
|
14
|
+
* revertOnError(message, fileName, line, column);
|
|
15
|
+
* }
|
|
16
|
+
* ```
|
|
17
|
+
*
|
|
18
|
+
* We just call `unreachable()` after recording the location: wasmer
|
|
19
|
+
* traps the call, the edge's pump catches the trap, marks the
|
|
20
|
+
* instance poisoned, and returns 502 to the client. The location
|
|
21
|
+
* fields are deliberately left untouched in case a future host
|
|
22
|
+
* import wants to read them off the message/fileName strings; today
|
|
23
|
+
* the edge's `AbortImport::execute` only logs `line`/`column`.
|
|
24
|
+
*/
|
|
25
|
+
export declare function revertOnError(_message: string, _fileName: string, _line: u32, _column: u32): void;
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
// Generated from server/runtime by scripts/gen-server-types.mjs.
|
|
2
|
+
/**
|
|
3
|
+
* Server: the runtime singleton.
|
|
4
|
+
*
|
|
5
|
+
* The user's `main.ts` assigns `Server.handler = () => new MyHandler()`.
|
|
6
|
+
* The `handle(req_ofs, req_len)` wasm export in `runtime/exports`
|
|
7
|
+
* calls that factory once per request.
|
|
8
|
+
*/
|
|
9
|
+
import { Potential } from '../lang/Potential';
|
|
10
|
+
import { ToilHandler } from '../handlers/ToilHandler';
|
|
11
|
+
import { Request } from '../request';
|
|
12
|
+
export declare class ServerEnvironment {
|
|
13
|
+
/**
|
|
14
|
+
* The user-supplied handler factory. Assigned at module init by
|
|
15
|
+
* the contract's `main.ts`. We use a factory rather than a
|
|
16
|
+
* pre-built instance so the user gets fresh state per request
|
|
17
|
+
* (the alternative would be threading reset logic through every
|
|
18
|
+
* handler class).
|
|
19
|
+
*/
|
|
20
|
+
handler: () => ToilHandler;
|
|
21
|
+
/**
|
|
22
|
+
* Cached handler instance for the current request. Cleared at the
|
|
23
|
+
* end of every dispatch so the next request runs the factory
|
|
24
|
+
* again. Exposed for tests; user code should not touch it.
|
|
25
|
+
*/
|
|
26
|
+
_current: Potential<ToilHandler>;
|
|
27
|
+
/**
|
|
28
|
+
* The request being dispatched right now. Set by `runtime/exports::handle`
|
|
29
|
+
* immediately after decode and cleared in {@link resetCurrentHandler}, so an
|
|
30
|
+
* ambient accessor like `AuthService.getUser()` can read the current
|
|
31
|
+
* request's cookies with no argument. Strictly single-request lifetime (the
|
|
32
|
+
* wasm processes one request per `handle` and memory resets between them);
|
|
33
|
+
* never cache it across requests.
|
|
34
|
+
*/
|
|
35
|
+
currentRequest: Request | null;
|
|
36
|
+
/**
|
|
37
|
+
* Build (or reuse) the handler for this request. Called once per
|
|
38
|
+
* dispatch from `runtime/exports::handle`.
|
|
39
|
+
*/
|
|
40
|
+
currentHandler(): ToilHandler;
|
|
41
|
+
/**
|
|
42
|
+
* Drop the cached handler so the next request gets a fresh one.
|
|
43
|
+
* Called at the tail of `runtime/exports::handle`.
|
|
44
|
+
*/
|
|
45
|
+
resetCurrentHandler(): void;
|
|
46
|
+
}
|
|
47
|
+
export declare const Server: ServerEnvironment;
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
// Generated from server/runtime by scripts/gen-server-types.mjs.
|
|
2
|
+
/**
|
|
3
|
+
* Wire envelope codec, byte-for-byte compatible with
|
|
4
|
+
* `toil-backend/src/http/envelope.rs`.
|
|
5
|
+
*
|
|
6
|
+
* Layout (LE, no padding):
|
|
7
|
+
*
|
|
8
|
+
* request:
|
|
9
|
+
* u8 method (0=GET, 1=POST, 2=PUT, 3=DELETE,
|
|
10
|
+
* 4=PATCH, 5=HEAD, 6=OPTIONS)
|
|
11
|
+
* u16 path_len
|
|
12
|
+
* [u8] path
|
|
13
|
+
* u16 n_headers
|
|
14
|
+
* for each header: u16 name_len, u16 val_len, [u8] name, [u8] val
|
|
15
|
+
* u32 body_len
|
|
16
|
+
* [u8] body
|
|
17
|
+
*
|
|
18
|
+
* response: same shape but the first u8+u16 (method + path_len)
|
|
19
|
+
* is replaced by `u16 status`.
|
|
20
|
+
*/
|
|
21
|
+
import { Request } from './request';
|
|
22
|
+
import { Response } from './response';
|
|
23
|
+
/**
|
|
24
|
+
* Decode the request envelope the host wrote at `req_ofs`. Returns
|
|
25
|
+
* a populated `Request` on success or `null` on truncation /
|
|
26
|
+
* malformed bytes.
|
|
27
|
+
*/
|
|
28
|
+
export declare function decodeRequest(req_ofs: usize, req_len: usize): Request | null;
|
|
29
|
+
/**
|
|
30
|
+
* Serialise `resp` into linear memory starting at `dst_ofs`.
|
|
31
|
+
* Returns the total byte length written. Status, header count and
|
|
32
|
+
* body length are bounds-checked: header names and values must each
|
|
33
|
+
* fit in u16, the body must fit in u32, the header count must fit in
|
|
34
|
+
* u16. A handler returning an unrepresentable response gets a
|
|
35
|
+
* minimal 500 envelope written instead so the host never sees an
|
|
36
|
+
* encoder fault.
|
|
37
|
+
*/
|
|
38
|
+
export declare function encodeResponse(resp: Response, dst_ofs: usize): u32;
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
// Generated from server/runtime by scripts/gen-server-types.mjs.
|
|
2
|
+
/**
|
|
3
|
+
* Wasm exports the edge calls.
|
|
4
|
+
*
|
|
5
|
+
* The user's `main.ts` does
|
|
6
|
+
*
|
|
7
|
+
* ```ts
|
|
8
|
+
* export * from './runtime/exports';
|
|
9
|
+
* ```
|
|
10
|
+
*
|
|
11
|
+
* to surface `handle(i32, i32) -> i64` (and any future entry points)
|
|
12
|
+
* as wasm exports. The actual work — decode the envelope, run the
|
|
13
|
+
* user's handler via `Server.currentHandler()`, encode the response —
|
|
14
|
+
* lives here.
|
|
15
|
+
*/
|
|
16
|
+
import '../http/cookie';
|
|
17
|
+
import '../http/cookies';
|
|
18
|
+
import '../http/securecookies';
|
|
19
|
+
export { render } from './render';
|
|
20
|
+
export declare function handle(req_ofs: i32, req_len: i32): i64;
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
// Generated from server/runtime by scripts/gen-server-types.mjs.
|
|
2
|
+
/**
|
|
3
|
+
* The `render(i32, i32) -> i64` wasm export: the edge-SSR entrypoint.
|
|
4
|
+
*
|
|
5
|
+
* Mirrors `handle` (see `./index.ts`) but returns a **values envelope** (the
|
|
6
|
+
* hole values) instead of a full HTTP response. The host has the precompiled
|
|
7
|
+
* template mmap'd and splices these values into it, so `render` does NO page
|
|
8
|
+
* rendering: it runs the matched route's generated stamping and serialises a
|
|
9
|
+
* compact list of `(slot_id, kind, bytes)`.
|
|
10
|
+
*
|
|
11
|
+
* The user's `main.ts` surfaces this by re-exporting `./runtime/exports`. A
|
|
12
|
+
* module with no SSR routes simply registers nothing; the host treats a
|
|
13
|
+
* missing `render` export as "no template routes".
|
|
14
|
+
*/
|
|
15
|
+
export declare function render(req_ofs: i32, req_len: i32): i64;
|