@gramlot/gramlot 0.2.12 → 0.2.14
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/dist/gramlot.js +257 -53
- package/dist/gramlot.min.js +17 -17
- package/package.json +1 -1
- package/src/binding/installation.js +14 -7
- package/src/binding/providers.js +69 -6
- package/src/binding/runtime.js +3 -3
- package/src/bootstrap.js +3 -3
- package/src/builder/binding.json +87 -0
- package/src/builder/gramlot-builder.js +2 -2
- package/src/builder/source.js +3 -1
- package/src/gramlot.d.ts +10 -8
- package/src/gramlot.js +7 -6
- package/src/handlers/rpc-handler.d.ts +42 -5
- package/src/handlers/rpc-handler.js +30 -3
- package/src/handlers/source-handler.js +4 -2
- package/src/http-transport.d.ts +27 -0
- package/src/{transport.js → http-transport.js} +11 -18
- package/src/index.d.ts +4 -2
- package/src/index.js +2 -1
- package/src/renderer/gramlot-renderer.js +1 -1
- package/src/server/assets.js +3 -3
- package/src/server/conformance.d.ts +1 -1
- package/src/server/conformance.js +100 -51
- package/src/server/gramlot-server.d.ts +29 -17
- package/src/server/gramlot-server.js +86 -20
- package/src/server/index.d.ts +2 -1
- package/src/server/index.js +2 -1
- package/src/server/page.d.ts +13 -3
- package/src/server/page.js +41 -12
- package/src/view/button.js +7 -7
- package/src/transport.d.ts +0 -34
|
@@ -1,32 +1,25 @@
|
|
|
1
|
-
/* @ts-self-types="./transport.d.ts" */
|
|
1
|
+
/* @ts-self-types="./http-transport.d.ts" */
|
|
2
2
|
/**
|
|
3
|
-
*
|
|
3
|
+
* The HTTP realisation of the Gramlot envelope; application pages do not issue fetch calls.
|
|
4
4
|
*
|
|
5
5
|
* @module
|
|
6
6
|
*/
|
|
7
|
-
/** The page-to-server transport:
|
|
8
|
-
export class
|
|
9
|
-
constructor(
|
|
10
|
-
|
|
11
|
-
this.
|
|
7
|
+
/** The page-to-server transport over HTTP: sends the envelope to the rpc URL and closes the server page. */
|
|
8
|
+
export class HttpTransport {
|
|
9
|
+
constructor(rpcUrl, {fetcher = globalThis.fetch?.bind(globalThis), closeUrl = '/gramlot/close',
|
|
10
|
+
navigator = globalThis.navigator} = {}) {
|
|
11
|
+
this.rpcUrl = rpcUrl;
|
|
12
12
|
this.fetcher = fetcher;
|
|
13
|
-
this.sourceUrl = sourceUrl;
|
|
14
13
|
this.closeUrl = closeUrl;
|
|
15
14
|
this.navigator = navigator;
|
|
16
15
|
}
|
|
17
|
-
async
|
|
18
|
-
|
|
19
|
-
}
|
|
20
|
-
async source(pageId, method, params, signal) {
|
|
21
|
-
return this.request('source', this.sourceUrl, {pageId, method, params}, signal);
|
|
22
|
-
}
|
|
23
|
-
async request(operation, url, payload, signal) {
|
|
24
|
-
const response = await this.fetcher(url, {
|
|
16
|
+
async call(text, signal) {
|
|
17
|
+
const response = await this.fetcher(this.rpcUrl, {
|
|
25
18
|
method: 'POST', credentials: 'same-origin', signal,
|
|
26
19
|
headers: {'Content-Type': 'application/json'},
|
|
27
|
-
body:
|
|
20
|
+
body: text,
|
|
28
21
|
});
|
|
29
|
-
if (
|
|
22
|
+
if (response.status !== 200) throw new Error(`rpc failed: HTTP ${response.status}`);
|
|
30
23
|
return response.text();
|
|
31
24
|
}
|
|
32
25
|
close(pageId, {beacon = false} = {}) {
|
package/src/index.d.ts
CHANGED
|
@@ -22,7 +22,9 @@ export {GramlotSvgRenderer} from './renderer/gramlot-svg-renderer.js';
|
|
|
22
22
|
export {Bag, BagNode} from '@genrojs/bag';
|
|
23
23
|
export {References} from './references.js';
|
|
24
24
|
export type {SourceReference} from './references.js';
|
|
25
|
-
export {
|
|
26
|
-
export type {Fetcher} from './transport.js';
|
|
25
|
+
export {HttpTransport} from './http-transport.js';
|
|
26
|
+
export type {Fetcher} from './http-transport.js';
|
|
27
|
+
export {RpcError} from './handlers/rpc-handler.js';
|
|
28
|
+
export type {RpcErrorOutcome, RpcTransport} from './handlers/rpc-handler.js';
|
|
27
29
|
export {InOut} from './inout.js';
|
|
28
30
|
export type {BeaconNavigator, DomDocument, DomElement, DomEvent, DomFragment, DomNode, DomWindow} from './dom.d.ts';
|
package/src/index.js
CHANGED
|
@@ -21,5 +21,6 @@ export {GramlotHtmlRenderer} from './renderer/gramlot-html-renderer.js';
|
|
|
21
21
|
export {GramlotSvgRenderer} from './renderer/gramlot-svg-renderer.js';
|
|
22
22
|
export {Bag, BagNode} from '@genrojs/bag';
|
|
23
23
|
export {References} from './references.js';
|
|
24
|
-
export {
|
|
24
|
+
export {HttpTransport} from './http-transport.js';
|
|
25
|
+
export {RpcError} from './handlers/rpc-handler.js';
|
|
25
26
|
export {InOut} from './inout.js';
|
|
@@ -361,7 +361,7 @@ export class GramlotRenderer extends GramlotHtmlRenderer {
|
|
|
361
361
|
insert(node) {
|
|
362
362
|
if (!this.attached(node) || this.records.has(node)) return;
|
|
363
363
|
if (node._getMeta('data_element')) {
|
|
364
|
-
// A `dataController` inserted in a button may give it a mechanism, or an ambiguous one (S12).
|
|
364
|
+
// A `dataController` or `dataRpc` inserted in a button may give it a mechanism, or an ambiguous one (S12).
|
|
365
365
|
this.records.get(node.parentBag?.parentNode)?.button?.refresh();
|
|
366
366
|
this.binding.branchBuilt(node);
|
|
367
367
|
return;
|
package/src/server/assets.js
CHANGED
|
@@ -1,16 +1,16 @@
|
|
|
1
1
|
/* @ts-self-types="./assets.d.ts" */
|
|
2
2
|
/**
|
|
3
|
-
* Development mode and the runtime file to serve
|
|
3
|
+
* Development mode and the runtime file to serve. `gramlotDev` imports nothing from Node.js, so the
|
|
4
|
+
* neutral `GramlotServer` can read it in a serverless Worker, where it is null without `process`.
|
|
4
5
|
*
|
|
5
6
|
* @module
|
|
6
7
|
*/
|
|
7
|
-
import process from 'node:process';
|
|
8
8
|
|
|
9
9
|
const DEV_MODES = ['YES', 'DEBUG'];
|
|
10
10
|
|
|
11
11
|
/** GRAMLOT_DEV: null when unset (deploy), 'YES' or 'DEBUG'; any other value throws a TypeError. */
|
|
12
12
|
export function gramlotDev() {
|
|
13
|
-
const value = process
|
|
13
|
+
const value = globalThis.process?.env?.GRAMLOT_DEV;
|
|
14
14
|
if (value === undefined) return null;
|
|
15
15
|
if (!DEV_MODES.includes(value)) {
|
|
16
16
|
throw new TypeError(`GRAMLOT_DEV must be unset, YES or DEBUG, not ${JSON.stringify(value)}`);
|
|
@@ -4,6 +4,6 @@
|
|
|
4
4
|
* @module
|
|
5
5
|
*/
|
|
6
6
|
|
|
7
|
-
/** Run the checks of GC-230 §
|
|
7
|
+
/** Run the checks of GC-230 §150 against the adapter at `baseUrl` (mount prefix included) with the page
|
|
8
8
|
* `pagePath`; reject with an `AssertionError` naming the rule of the first failure. */
|
|
9
9
|
export function checkProtocol(baseUrl: string, pagePath: string): Promise<void>;
|
|
@@ -5,9 +5,10 @@
|
|
|
5
5
|
* @module
|
|
6
6
|
*/
|
|
7
7
|
import {AssertionError} from 'node:assert';
|
|
8
|
+
import {isDeepStrictEqual} from 'node:util';
|
|
9
|
+
import {fromTytx, toTytx} from '@genrojs/tytx';
|
|
8
10
|
|
|
9
11
|
const OWNER_COOKIE = 'gramlot_owner';
|
|
10
|
-
const MAX_REQUEST_BYTES = 4096;
|
|
11
12
|
const BOOTSTRAP = /<script type="module" nonce="([^"]+)">import \{PageBootstrap\} from ("[^"]*");await new PageBootstrap\((\{.*?\})\)\.run\(\);<\/script>/;
|
|
12
13
|
|
|
13
14
|
const expect = (rule, condition, message) => {
|
|
@@ -16,7 +17,7 @@ const expect = (rule, condition, message) => {
|
|
|
16
17
|
|
|
17
18
|
const mediaType = headers => (headers.get('content-type') ?? '').split(';')[0].trim().toLowerCase();
|
|
18
19
|
|
|
19
|
-
/** Run the checks of GC-230 §
|
|
20
|
+
/** Run the checks of GC-230 §150 against the adapter at baseUrl (mount prefix included) with
|
|
20
21
|
* the page pagePath; throw an AssertionError naming the rule of the first failure. The Python
|
|
21
22
|
* counterpart is src/gramlot/server/conformance.py: both run the same list in the same order. */
|
|
22
23
|
export async function checkProtocol(baseUrl, pagePath) {
|
|
@@ -30,34 +31,36 @@ export async function checkProtocol(baseUrl, pagePath) {
|
|
|
30
31
|
const response = await fetch(base.origin + path, {method, body, headers, redirect: 'manual'});
|
|
31
32
|
return {status: response.status, headers: response.headers, body: await response.text()};
|
|
32
33
|
};
|
|
33
|
-
const post = (url, payload, options = {}) => request('POST', url, {...options, body: JSON.stringify(payload)});
|
|
34
34
|
|
|
35
35
|
if (prefix) {
|
|
36
36
|
const {status, headers} = await request('GET', prefix);
|
|
37
|
-
expect('GC-230-
|
|
37
|
+
expect('GC-230-105', status === 301 && (headers.get('location') ?? '').endsWith(`${prefix}/`),
|
|
38
38
|
`GET ${prefix} answers ${status}, not 301 to ${prefix}/`);
|
|
39
39
|
}
|
|
40
40
|
|
|
41
41
|
const pageUrl = prefix + pagePath;
|
|
42
42
|
const page = await request('GET', pageUrl);
|
|
43
|
-
expect('GC-230-
|
|
43
|
+
expect('GC-230-115', page.status === 200 && mediaType(page.headers) === 'text/html',
|
|
44
44
|
`GET ${pageUrl} answers ${page.status} ${page.headers.get('content-type')}, not 200 text/html`);
|
|
45
45
|
const match = BOOTSTRAP.exec(page.body);
|
|
46
|
-
expect('GC-230-
|
|
46
|
+
expect('GC-230-115', match !== null, `GET ${pageUrl} has no bootstrap module script`);
|
|
47
47
|
const [, nonce, runtimeJson, bootstrapJson] = match;
|
|
48
48
|
const runtimeUrl = JSON.parse(runtimeJson);
|
|
49
49
|
const {config, resources} = JSON.parse(bootstrapJson);
|
|
50
|
-
expect('GC-230-
|
|
50
|
+
expect('GC-230-115', page.body.includes(`<script type="importmap" nonce="${nonce}">`),
|
|
51
51
|
'the import map does not carry the bootstrap nonce');
|
|
52
|
-
|
|
53
|
-
|
|
52
|
+
expect('GC-230-115', typeof config.rpcUrl === 'string' && typeof config.closeUrl === 'string'
|
|
53
|
+
&& Array.isArray(config.capabilities),
|
|
54
|
+
`bootstrap config ${JSON.stringify(config)} lacks rpcUrl, closeUrl or a capabilities array`);
|
|
55
|
+
const expected = {runtime: [runtimeUrl, '/assets/gramlot.js'], rpc: [config.rpcUrl, '/gramlot/rpc'],
|
|
56
|
+
close: [config.closeUrl, '/gramlot/close']};
|
|
54
57
|
for (const [name, [url, path]] of Object.entries(expected)) {
|
|
55
|
-
expect('GC-230-
|
|
58
|
+
expect('GC-230-105', url === prefix + path, `bootstrap ${name} URL ${url}, not ${prefix + path}`);
|
|
56
59
|
}
|
|
57
60
|
|
|
58
61
|
const policy = page.headers.get('content-security-policy');
|
|
59
62
|
if (policy !== null) {
|
|
60
|
-
expect('GC-230-
|
|
63
|
+
expect('GC-230-140', policy.includes(`'nonce-${nonce}'`), 'the Content-Security-Policy lacks the bootstrap nonce');
|
|
61
64
|
}
|
|
62
65
|
|
|
63
66
|
for (const line of page.headers.getSetCookie()) {
|
|
@@ -67,72 +70,118 @@ export async function checkProtocol(baseUrl, pagePath) {
|
|
|
67
70
|
const [key, value = ''] = attribute.split('=');
|
|
68
71
|
return [key.toLowerCase(), value];
|
|
69
72
|
}));
|
|
70
|
-
expect('GC-230-
|
|
73
|
+
expect('GC-230-135', 'httponly' in named && named.samesite?.toLowerCase() === 'lax' && named.path === (prefix || '/'),
|
|
71
74
|
`owner cookie without HttpOnly, SameSite=Lax and Path=${prefix || '/'}`);
|
|
72
75
|
owner = pair.slice(OWNER_COOKIE.length + 1);
|
|
73
76
|
}
|
|
74
77
|
|
|
75
78
|
let response = await request('GET', runtimeUrl);
|
|
76
|
-
expect('GC-230-
|
|
79
|
+
expect('GC-230-110', response.status === 200 && mediaType(response.headers) === 'text/javascript',
|
|
77
80
|
`GET ${runtimeUrl} answers ${response.status} ${response.headers.get('content-type')}, not 200 text/javascript`);
|
|
78
81
|
response = await request('POST', runtimeUrl, {body: '{}'});
|
|
79
|
-
expect('GC-230-
|
|
82
|
+
expect('GC-230-110', response.status === 405, `POST ${runtimeUrl} answers ${response.status}, not 405`);
|
|
80
83
|
|
|
81
84
|
const files = [...resources.css.map(url => [url, 'text/css']), ...resources.js.map(({url}) => [url, 'text/javascript'])];
|
|
82
85
|
for (const [url, type] of files) {
|
|
83
86
|
if (!url.startsWith('/') || url.startsWith('//')) continue;
|
|
84
87
|
response = await request('GET', url);
|
|
85
|
-
expect('GC-230-
|
|
88
|
+
expect('GC-230-145', response.status === 200 && mediaType(response.headers) === type,
|
|
86
89
|
`GET ${url} answers ${response.status} ${response.headers.get('content-type')}, not 200 ${type}`);
|
|
87
90
|
}
|
|
88
91
|
|
|
89
92
|
response = await request('GET', `${prefix}/gramlot-conformance-missing-page`);
|
|
90
|
-
expect('GC-230-
|
|
93
|
+
expect('GC-230-115', response.status === 404, `an unknown page answers ${response.status}, not 404`);
|
|
91
94
|
response = await request('POST', pageUrl, {body: '{}'});
|
|
92
|
-
expect('GC-230-
|
|
95
|
+
expect('GC-230-115', response.status === 405, `POST ${pageUrl} answers ${response.status}, not 405`);
|
|
93
96
|
if (pagePath.endsWith('/')) {
|
|
94
97
|
response = await request('GET', `${pageUrl}index.html`);
|
|
95
|
-
expect('GC-230-
|
|
98
|
+
expect('GC-230-115', response.status === 200 && mediaType(response.headers) === 'text/html',
|
|
96
99
|
`GET ${pageUrl}index.html answers ${response.status}, not the page ${pageUrl}`);
|
|
97
100
|
}
|
|
98
101
|
|
|
99
|
-
const {pageId,
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
102
|
+
const {pageId, rpcUrl: rpc} = config;
|
|
103
|
+
const envelope = (contentType, name, params = {}, fields = {}) =>
|
|
104
|
+
({id: crypto.randomUUID(), pageId, contentType, name, params, ...fields});
|
|
105
|
+
const parse = (text, decode) => {
|
|
106
|
+
try { return decode(text); } catch { return null; }
|
|
107
|
+
};
|
|
108
|
+
/** POST the envelope sent to rpc; the response with the decoded envelope as `received`. */
|
|
109
|
+
const call = async (sent, options = {}) => {
|
|
110
|
+
const answer = await request('POST', rpc, {...options, body: toTytx(sent)});
|
|
111
|
+
return {...answer, received: parse(answer.body, fromTytx)};
|
|
112
|
+
};
|
|
113
|
+
const outcome = async (rule, sent, code, label, options = {}) => {
|
|
114
|
+
const {status, body, received} = await call(sent, options);
|
|
115
|
+
const error = received?.error;
|
|
116
|
+
expect(rule, status === 200 && error?.code === code,
|
|
117
|
+
`${label} answers ${status} ${body.slice(0, 200)}, not 200 with the outcome ${code}`);
|
|
118
|
+
return error;
|
|
119
|
+
};
|
|
120
|
+
|
|
121
|
+
response = await request('GET', rpc);
|
|
122
|
+
expect('GC-230-120', response.status === 405, `GET ${rpc} answers ${response.status}, not 405`);
|
|
123
|
+
response = await request('POST', rpc, {body: toTytx(envelope('source', 'main')), contentType: 'text/plain'});
|
|
124
|
+
expect('GC-230-120', response.status === 415, `rpc as text/plain answers ${response.status}, not 415`);
|
|
125
|
+
response = await request('POST', rpc, {body: '{'});
|
|
126
|
+
expect('GC-230-120', response.status === 400, `rpc with invalid JSON answers ${response.status}, not 400`);
|
|
127
|
+
const {pageId: omitted, ...withoutPageId} = envelope('source', 'main');
|
|
128
|
+
const invalid = {'without pageId': withoutPageId, 'with params null': envelope('source', 'main', null),
|
|
129
|
+
'with array params': envelope('source', 'main', []), 'with an unknown contentType': envelope('other', 'main')};
|
|
130
|
+
for (const [label, sent] of Object.entries(invalid)) {
|
|
131
|
+
response = await call(sent);
|
|
132
|
+
expect('GC-230-120', response.status === 400, `rpc ${label} answers ${response.status}, not 400`);
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
const sent = envelope('source', 'main');
|
|
136
|
+
response = await call(sent);
|
|
137
|
+
const received = parse(response.body, JSON.parse);
|
|
138
|
+
expect('GC-230-020', response.status === 200 && mediaType(response.headers) === 'application/json'
|
|
139
|
+
&& received?.id === sent.id && received?.contentType === 'source' && typeof received?.value === 'string',
|
|
140
|
+
`main answers ${response.status} ${response.headers.get('content-type')} ${response.body.slice(0, 200)}, not 200 `
|
|
141
|
+
+ 'application/json with an envelope echoing id and contentType and carrying the fragment document as a string');
|
|
115
142
|
if (owner !== null) {
|
|
116
|
-
|
|
117
|
-
|
|
143
|
+
await outcome('GC-230-135', envelope('source', 'main'), 'page_expired', 'main without the owner cookie',
|
|
144
|
+
{withOwner: false});
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
await outcome('GC-230-025', envelope('source', 'main', {}, {pageId: '0'.repeat(32)}), 'page_expired',
|
|
148
|
+
'main of an unknown page');
|
|
149
|
+
await outcome('GC-230-025', envelope('source', 'gramlot_conformance_missing'), 'not_found', 'an unknown fragment');
|
|
150
|
+
await outcome('GC-230-025', envelope('data', 'gramlot_conformance_missing'), 'not_found', 'an unknown endpoint');
|
|
151
|
+
await outcome('GC-230-025', envelope('data', 'main'), 'not_found', 'data main');
|
|
152
|
+
|
|
153
|
+
response = await call(envelope('source', 'check_fragment', {text: 'gramlot-conformance'}));
|
|
154
|
+
const fragment = parse(response.body, JSON.parse)?.value;
|
|
155
|
+
expect('GC-230-015', response.status === 200 && typeof fragment === 'string' && fragment.includes('gramlot-conformance'),
|
|
156
|
+
`check_fragment answers ${response.status} ${response.body.slice(0, 200)}, not a fragment document with its params`);
|
|
157
|
+
// The date crosses the wire typed (::D) and comes back as the same typed value.
|
|
158
|
+
for (const value of [3, 'x', new Date(Date.UTC(2020, 0, 1))]) {
|
|
159
|
+
response = await call(envelope('data', 'check_endpoint', {value}));
|
|
160
|
+
expect('GC-230-015', response.status === 200 && isDeepStrictEqual(response.received?.value, value),
|
|
161
|
+
`check_endpoint of ${JSON.stringify(value)} answers ${response.status} ${response.body.slice(0, 200)}, `
|
|
162
|
+
+ `not ${JSON.stringify(value)}`);
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
if (config.capabilities.includes('auth')) {
|
|
166
|
+
response = await call(envelope('data', 'check_endpoint_auth'));
|
|
167
|
+
const {received: answer} = response;
|
|
168
|
+
expect('GC-230-030', response.status === 200 && answer !== null && typeof answer === 'object' && (!('error' in answer)
|
|
169
|
+
? 'value' in answer : ['not_authenticated', 'not_authorized'].includes(answer.error?.code)),
|
|
170
|
+
`check_endpoint_auth answers ${response.status} ${response.body.slice(0, 200)}, not 200 with not_authenticated, `
|
|
171
|
+
+ 'not_authorized or a value');
|
|
172
|
+
} else {
|
|
173
|
+
await outcome('GC-230-030', envelope('data', 'check_endpoint_auth'), 'not_authenticated', 'check_endpoint_auth');
|
|
118
174
|
}
|
|
119
|
-
response = await post(main, {pageId: '0'.repeat(32)});
|
|
120
|
-
expect('GC-230-035', response.status === 404, `main of an unknown page answers ${response.status}, not 404`);
|
|
121
175
|
|
|
122
|
-
const
|
|
123
|
-
|
|
124
|
-
expect('GC-230-025',
|
|
125
|
-
|
|
126
|
-
expect('GC-230-025', response.status === 400, `Source with array params answers ${response.status}, not 400`);
|
|
127
|
-
response = await post(source, {pageId, method: 'gramlot_conformance_missing'});
|
|
128
|
-
expect('GC-230-035', response.status === 404, `an unknown Source method answers ${response.status}, not 404`);
|
|
176
|
+
const error = await outcome('GC-230-025', envelope('data', 'check_endpoint_raise'), 'application_error',
|
|
177
|
+
'check_endpoint_raise');
|
|
178
|
+
expect('GC-230-025', typeof error.name === 'string' && error.name !== '' && error.message === 'check',
|
|
179
|
+
`check_endpoint_raise answers the error ${JSON.stringify(error)}, not the exception name and the message 'check'`);
|
|
129
180
|
|
|
130
181
|
const close = config.closeUrl;
|
|
131
|
-
response = await
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
expect('GC-230-030', response.status === 200 && mediaType(response.headers) === 'application/json' && closed?.ok === true,
|
|
182
|
+
response = await request('POST', close, {body: JSON.stringify({pageId})});
|
|
183
|
+
const closed = parse(response.body, JSON.parse);
|
|
184
|
+
expect('GC-230-125', response.status === 200 && mediaType(response.headers) === 'application/json' && isDeepStrictEqual(closed, {ok: true}),
|
|
135
185
|
`close answers ${response.status} ${response.body}, not 200 {"ok": true}`);
|
|
136
|
-
|
|
137
|
-
expect('GC-230-030', response.status === 404, `main after close answers ${response.status}, not 404`);
|
|
186
|
+
await outcome('GC-230-125', envelope('source', 'main'), 'page_expired', 'main after close');
|
|
138
187
|
}
|
|
@@ -20,19 +20,36 @@ export class PageNotFound extends Error {
|
|
|
20
20
|
export class SourceNotFound extends Error {
|
|
21
21
|
name: 'SourceNotFound';
|
|
22
22
|
}
|
|
23
|
+
/** No endpoint of that name, as the Python `EndpointNotFound`. */
|
|
24
|
+
export class EndpointNotFound extends Error {
|
|
25
|
+
name: 'EndpointNotFound';
|
|
26
|
+
}
|
|
27
|
+
/** The `auth` evaluator answered `not_authenticated`. */
|
|
28
|
+
export class NotAuthenticated extends Error {
|
|
29
|
+
name: 'NotAuthenticated';
|
|
30
|
+
}
|
|
31
|
+
/** The `auth` evaluator answered `not_authorized`. */
|
|
32
|
+
export class NotAuthorized extends Error {
|
|
33
|
+
name: 'NotAuthorized';
|
|
34
|
+
}
|
|
35
|
+
/** A request envelope that is not `{id, pageId, contentType, name, params}`, as the Python `InvalidRequest`. */
|
|
36
|
+
export class InvalidRequest extends Error {
|
|
37
|
+
name: 'InvalidRequest';
|
|
38
|
+
}
|
|
23
39
|
/** The page registry is full. */
|
|
24
40
|
export class ServerCapacity extends Error {
|
|
25
41
|
name: 'ServerCapacity';
|
|
26
42
|
}
|
|
27
43
|
|
|
44
|
+
/** The outcome of a refused `auth` rule, or null when the call may proceed. */
|
|
45
|
+
export type AuthOutcome = 'not_authenticated' | 'not_authorized' | null;
|
|
46
|
+
|
|
28
47
|
/** The options of a `GramlotServer`. */
|
|
29
48
|
export interface GramlotServerOptions {
|
|
30
49
|
/** URL of the runtime bundle. */
|
|
31
50
|
runtimeUrl?: string;
|
|
32
|
-
/** URL of the
|
|
33
|
-
|
|
34
|
-
/** URL of the remote Source endpoint. */
|
|
35
|
-
sourceUrl?: string;
|
|
51
|
+
/** URL of the request envelopes. */
|
|
52
|
+
rpcUrl?: string;
|
|
36
53
|
/** URL of the page close endpoint. */
|
|
37
54
|
closeUrl?: string;
|
|
38
55
|
/** Id of the root element of the page. */
|
|
@@ -70,10 +87,8 @@ export interface OpenedPage {
|
|
|
70
87
|
export class GramlotServer {
|
|
71
88
|
/** URL of the runtime bundle. */
|
|
72
89
|
runtimeUrl: string;
|
|
73
|
-
/** URL of the
|
|
74
|
-
|
|
75
|
-
/** URL of the remote Source endpoint. */
|
|
76
|
-
sourceUrl: string;
|
|
90
|
+
/** URL of the request envelopes. */
|
|
91
|
+
rpcUrl: string;
|
|
77
92
|
/** URL of the page close endpoint. */
|
|
78
93
|
closeUrl: string;
|
|
79
94
|
/** Id of the root element of the page. */
|
|
@@ -90,21 +105,18 @@ export class GramlotServer {
|
|
|
90
105
|
resolvePage(path: string): Promise<typeof Page>;
|
|
91
106
|
/** The resources of the page at `path` in load order and without mount prefix, or `PageNotFound`. */
|
|
92
107
|
resolveResources(path: string, PageClass: typeof Page): Promise<Resources>;
|
|
108
|
+
/** The capabilities announced in the bootstrap; none in the base server. */
|
|
109
|
+
get capabilities(): string[];
|
|
110
|
+
/** null when a target with `rule` may run for `owner`; the base server refuses any rule. */
|
|
111
|
+
evaluateAuth(rule: string | null, options?: {owner?: unknown}): AuthOutcome;
|
|
93
112
|
/** Drop the expired pages. */
|
|
94
113
|
prune(): void;
|
|
95
114
|
/** Register a page independently of its HTTP or Worker transport. */
|
|
96
115
|
registerPage(path: string, options?: {owner?: unknown}): Promise<RegisteredPage>;
|
|
97
116
|
/** Register the page and return its bootstrap; `prefix` is the mount prefix added to root-relative URLs. */
|
|
98
117
|
openPage(path: string, options?: {owner?: unknown; prefix?: string}): Promise<OpenedPage>;
|
|
99
|
-
/**
|
|
100
|
-
|
|
101
|
-
/** A remote Source of a registered page, as TYTX text; `params` null or omitted is `{}`. */
|
|
102
|
-
source(pageId: string, method: string, params?: Record<string, unknown> | null,
|
|
103
|
-
options?: {owner?: unknown}): Promise<string>;
|
|
104
|
-
/** Build the Source of a page by calling its `main` (`method` `'main'`) or a registered Source method;
|
|
105
|
-
* the Source builder is named after `method`. */
|
|
106
|
-
buildSource(pageId: string, method: string, params: Record<string, unknown>,
|
|
107
|
-
owner: unknown): Promise<string>;
|
|
118
|
+
/** Answer the request envelope `text` (TYTX) with the response envelope (TYTX); throws only `InvalidRequest`. */
|
|
119
|
+
call(text: string, options?: {owner?: unknown}): Promise<string>;
|
|
108
120
|
/** Forget a registered page when `owner` owns it. */
|
|
109
121
|
closePage(pageId: string, options?: {owner?: unknown}): void;
|
|
110
122
|
/** Forget every registered page; adapters call it on shutdown. */
|
|
@@ -4,16 +4,48 @@
|
|
|
4
4
|
*
|
|
5
5
|
* @module
|
|
6
6
|
*/
|
|
7
|
+
import {fromTytx, toTytx} from '@genrojs/tytx';
|
|
7
8
|
import {GramlotBuilder} from '../builder/gramlot-builder.js';
|
|
8
|
-
import {
|
|
9
|
+
import {gramlotDev} from './assets.js';
|
|
10
|
+
import {ENDPOINT_METHOD, Page, SOURCE_METHOD, endpointMethod, sourceMethod} from './page.js';
|
|
9
11
|
import {loadOrder} from './resources.js';
|
|
10
12
|
|
|
11
13
|
export class PageExpired extends Error { name = 'PageExpired'; }
|
|
12
14
|
export class PageNotFound extends Error { name = 'PageNotFound'; }
|
|
13
15
|
/** An unknown remote Source method, as the Python `SourceNotFound`. */
|
|
14
16
|
export class SourceNotFound extends Error { name = 'SourceNotFound'; }
|
|
17
|
+
export class EndpointNotFound extends Error { name = 'EndpointNotFound'; }
|
|
18
|
+
export class NotAuthenticated extends Error { name = 'NotAuthenticated'; }
|
|
19
|
+
export class NotAuthorized extends Error { name = 'NotAuthorized'; }
|
|
20
|
+
/** A request envelope that is not `{id, pageId, contentType, name, params}`, as the Python `InvalidRequest`. */
|
|
21
|
+
export class InvalidRequest extends Error { name = 'InvalidRequest'; }
|
|
15
22
|
export class ServerCapacity extends Error { name = 'ServerCapacity'; }
|
|
16
23
|
|
|
24
|
+
/** The single place the outcome codes are spelled; any other error is application_error. */
|
|
25
|
+
const OUTCOME_CODES = new Map([[PageExpired, 'page_expired'], [SourceNotFound, 'not_found'],
|
|
26
|
+
[EndpointNotFound, 'not_found'], [NotAuthenticated, 'not_authenticated'], [NotAuthorized, 'not_authorized']]);
|
|
27
|
+
|
|
28
|
+
const isMapping = value => value !== null && typeof value === 'object' && Object.getPrototypeOf(value) === Object.prototype;
|
|
29
|
+
|
|
30
|
+
/** Decode and check the request envelope {id, pageId, contentType, name, params}. */
|
|
31
|
+
function parseRequest(text) {
|
|
32
|
+
let request;
|
|
33
|
+
try {
|
|
34
|
+
request = fromTytx(text);
|
|
35
|
+
} catch (error) {
|
|
36
|
+
throw new InvalidRequest('Request is not TYTX text', {cause: error});
|
|
37
|
+
}
|
|
38
|
+
if (!isMapping(request)) throw new InvalidRequest('Request must be a mapping');
|
|
39
|
+
for (const field of ['id', 'pageId', 'contentType', 'name']) {
|
|
40
|
+
if (typeof request[field] !== 'string') throw new InvalidRequest(`Request ${field} must be a string`);
|
|
41
|
+
}
|
|
42
|
+
if (!['source', 'data'].includes(request.contentType)) {
|
|
43
|
+
throw new InvalidRequest('Request contentType must be source or data');
|
|
44
|
+
}
|
|
45
|
+
if (!isMapping(request.params)) throw new InvalidRequest('Request params must be a mapping');
|
|
46
|
+
return request;
|
|
47
|
+
}
|
|
48
|
+
|
|
17
49
|
const scriptJson = value => JSON.stringify(value).replaceAll('<', '\\u003c');
|
|
18
50
|
|
|
19
51
|
/** 16 random bytes in URL-safe base64 without padding, as Python secrets.token_urlsafe(16). */
|
|
@@ -31,15 +63,14 @@ const prefixed = (prefix, url) => url.startsWith('/') && !url.startsWith('//') ?
|
|
|
31
63
|
* GramlotFileServer implements them on one pages folder. Adapters supply request ownership.
|
|
32
64
|
*/
|
|
33
65
|
export class GramlotServer {
|
|
34
|
-
constructor({runtimeUrl = '/assets/gramlot.js',
|
|
35
|
-
closeUrl = '/gramlot/close',
|
|
66
|
+
constructor({runtimeUrl = '/assets/gramlot.js', rpcUrl = '/gramlot/rpc', closeUrl = '/gramlot/close',
|
|
36
67
|
rootId = 'gramlot-root', pageTtl = 1800, maxPages = 1000} = {}) {
|
|
37
68
|
if (typeof pageTtl !== 'number' || pageTtl <= 0 ||
|
|
38
69
|
!Number.isFinite(performance.now() + pageTtl * 1000) ||
|
|
39
70
|
!Number.isSafeInteger(maxPages) || maxPages < 1) {
|
|
40
71
|
throw new TypeError('Page TTL must be finite and positive; capacity must be a positive safe integer');
|
|
41
72
|
}
|
|
42
|
-
Object.assign(this, {runtimeUrl,
|
|
73
|
+
Object.assign(this, {runtimeUrl, rpcUrl, closeUrl, rootId, pageTtl, maxPages});
|
|
43
74
|
this.pages = new Map();
|
|
44
75
|
}
|
|
45
76
|
|
|
@@ -49,6 +80,17 @@ export class GramlotServer {
|
|
|
49
80
|
/** {css: [url], js: [{url, group}]} in load order and without mount prefix, or PageNotFound. */
|
|
50
81
|
async resolveResources(path, PageClass) { throw new PageNotFound(`Page resources not found: ${path}`); }
|
|
51
82
|
|
|
83
|
+
/** The capabilities announced in the bootstrap; none in the base server. */
|
|
84
|
+
get capabilities() {
|
|
85
|
+
return [];
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/** null when a target with `rule` may run for `owner`, else 'not_authenticated' or
|
|
89
|
+
* 'not_authorized'. The base server knows no identity: any rule is closed. */
|
|
90
|
+
evaluateAuth(rule, {owner = null} = {}) {
|
|
91
|
+
return rule === null ? null : 'not_authenticated';
|
|
92
|
+
}
|
|
93
|
+
|
|
52
94
|
prune() {
|
|
53
95
|
const now = performance.now();
|
|
54
96
|
for (const [id, record] of this.pages) if (record.expires <= now) this.pages.delete(id);
|
|
@@ -77,8 +119,8 @@ export class GramlotServer {
|
|
|
77
119
|
const nonce = createNonce();
|
|
78
120
|
// The CSS links and the JS modules reach the page through PageBootstrap (§4.12, D9).
|
|
79
121
|
const bootstrap = scriptJson({
|
|
80
|
-
config: {pageId,
|
|
81
|
-
|
|
122
|
+
config: {pageId, rpcUrl: prefixed(prefix, this.rpcUrl), closeUrl: prefixed(prefix, this.closeUrl),
|
|
123
|
+
rootId: this.rootId, capabilities: this.capabilities},
|
|
82
124
|
resources: {css: resources.css.map(url => prefixed(prefix, url)),
|
|
83
125
|
js: resources.js.map(({url, group}) => ({url: prefixed(prefix, url), group}))},
|
|
84
126
|
});
|
|
@@ -103,28 +145,52 @@ export class GramlotServer {
|
|
|
103
145
|
}
|
|
104
146
|
}
|
|
105
147
|
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
148
|
+
/** Answer the request envelope `text` (TYTX) with the response envelope (TYTX).
|
|
149
|
+
* Throws only InvalidRequest; every other failure is an outcome in the response,
|
|
150
|
+
* a value that TYTX cannot serialise included. */
|
|
151
|
+
async call(text, {owner = null} = {}) {
|
|
152
|
+
const request = parseRequest(text);
|
|
153
|
+
const response = {id: request.id, contentType: request.contentType};
|
|
154
|
+
try {
|
|
155
|
+
response.value = (await this.#run(request, owner)) ?? null;
|
|
156
|
+
return toTytx(response);
|
|
157
|
+
} catch (error) {
|
|
158
|
+
delete response.value;
|
|
159
|
+
response.error = {code: OUTCOME_CODES.get(error?.constructor) ?? 'application_error',
|
|
160
|
+
name: error?.name ?? 'Error', message: error?.message ?? String(error)};
|
|
161
|
+
if (gramlotDev() === 'DEBUG') response.error.details = error?.stack;
|
|
115
162
|
}
|
|
116
|
-
return
|
|
163
|
+
return toTytx(response);
|
|
117
164
|
}
|
|
118
165
|
|
|
119
|
-
|
|
166
|
+
/** Run the fragment or endpoint of a checked request: the value of the response. */
|
|
167
|
+
async #run({pageId, contentType, name, params}, owner) {
|
|
120
168
|
this.prune();
|
|
121
169
|
const record = this.pages.get(pageId);
|
|
122
170
|
if (!record || record.owner !== owner) throw new PageExpired('Unknown, expired or unowned page');
|
|
123
171
|
const page = new record.PageClass();
|
|
124
172
|
page.pageId = pageId;
|
|
125
|
-
const
|
|
126
|
-
|
|
127
|
-
|
|
173
|
+
const source = contentType === 'source';
|
|
174
|
+
let callable = page.main;
|
|
175
|
+
let rule = null;
|
|
176
|
+
if (!source || name !== 'main') {
|
|
177
|
+
callable = (source ? sourceMethod : endpointMethod)(page, name);
|
|
178
|
+
if (!callable) {
|
|
179
|
+
throw source ? new SourceNotFound(`Unknown Source method: ${name}`)
|
|
180
|
+
: new EndpointNotFound(`Unknown endpoint: ${name}`);
|
|
181
|
+
}
|
|
182
|
+
rule = callable[source ? SOURCE_METHOD : ENDPOINT_METHOD].auth;
|
|
183
|
+
}
|
|
184
|
+
const refused = this.evaluateAuth(rule, {owner});
|
|
185
|
+
if (![null, 'not_authenticated', 'not_authorized'].includes(refused)) {
|
|
186
|
+
throw new TypeError("evaluateAuth must return null, 'not_authenticated' or 'not_authorized'");
|
|
187
|
+
}
|
|
188
|
+
if (refused !== null) {
|
|
189
|
+
const Refusal = [NotAuthenticated, NotAuthorized].find(ErrorClass => OUTCOME_CODES.get(ErrorClass) === refused);
|
|
190
|
+
throw new Refusal(`Access refused: ${name}`);
|
|
191
|
+
}
|
|
192
|
+
if (!source) return callable.call(page, params);
|
|
193
|
+
const builder = new record.PageClass.sourceBuilder(name);
|
|
128
194
|
const result = await callable.call(page, builder.root, params);
|
|
129
195
|
if (result !== undefined && result !== null) throw new TypeError('Source methods populate root and return no value');
|
|
130
196
|
return builder.toTytx();
|
package/src/server/index.d.ts
CHANGED
|
@@ -5,7 +5,8 @@
|
|
|
5
5
|
* @module
|
|
6
6
|
*/
|
|
7
7
|
export {Page} from './page.js';
|
|
8
|
-
export {GramlotServer,
|
|
8
|
+
export {GramlotServer, EndpointNotFound, InvalidRequest, NotAuthenticated, NotAuthorized, PageExpired, PageNotFound,
|
|
9
|
+
SourceNotFound, ServerCapacity} from './gramlot-server.js';
|
|
9
10
|
export type {GramlotServerOptions, OpenedPage, RegisteredPage} from './gramlot-server.js';
|
|
10
11
|
export {GramlotBuilder} from '../builder/gramlot-builder.js';
|
|
11
12
|
export {GramlotFileServer} from './gramlot-file-server.js';
|
package/src/server/index.js
CHANGED
|
@@ -7,7 +7,8 @@
|
|
|
7
7
|
*/
|
|
8
8
|
// Server entry point: deliberately not re-exported by the browser entry point.
|
|
9
9
|
export {Page} from './page.js';
|
|
10
|
-
export {GramlotServer,
|
|
10
|
+
export {GramlotServer, EndpointNotFound, InvalidRequest, NotAuthenticated, NotAuthorized, PageExpired, PageNotFound,
|
|
11
|
+
SourceNotFound, ServerCapacity} from './gramlot-server.js';
|
|
11
12
|
export {GramlotBuilder} from '../builder/gramlot-builder.js';
|
|
12
13
|
export {GramlotFileServer} from './gramlot-file-server.js';
|
|
13
14
|
export {gramlotDev, runtimeAsset} from './assets.js';
|