@foliwake/server 0.7.0 → 0.9.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +33 -0
- package/README.md +225 -0
- package/dist/hook.d.ts +91 -0
- package/dist/hook.js +188 -0
- package/dist/page.js +6 -2
- package/package.json +6 -2
package/CHANGELOG.md
CHANGED
|
@@ -7,6 +7,39 @@ minor release may break; breaking changes are marked **BREAKING**.
|
|
|
7
7
|
|
|
8
8
|
Entries are written from the changesets of each pull request (`.changeset/`, CONTRIBUTING.md), newest first.
|
|
9
9
|
|
|
10
|
+
## 0.9.0
|
|
11
|
+
|
|
12
|
+
### Minor Changes
|
|
13
|
+
|
|
14
|
+
- 003f643: Apps can be told when the live site changes. `@foliwake/server/hook` verifies the signed hook a Foliwake server
|
|
15
|
+
sends once a change is live and the caches in front of the origin serve it (`verifyFoliwakeSignature`,
|
|
16
|
+
`parseFoliwakeHook`, `signFoliwakeHook` for tests, payload types). `@foliwake/next/revalidate` adds
|
|
17
|
+
`foliwakeRevalidateHandler({ secretEnv })`, a route handler that expires the live tag of every changed path, or
|
|
18
|
+
of the whole site when every page changed, with `{ expire: 0 }` by default (`mode: 'max'` for background
|
|
19
|
+
refresh), reads up to 20 changed pages again after answering (`warm`), accepts a previous secret while it is
|
|
20
|
+
rotated (`previousSecretEnv`) and calls `onDelivery(payload)`.
|
|
21
|
+
- 6dd1fd4: **BREAKING** `PageEnvelope.generation` is now a number (`X-Site-Generation`, the live generation, which only
|
|
22
|
+
grows), or null when the origin sends none; it was a string. An origin that sends a value that is not a
|
|
23
|
+
non-negative integer is refused (`FoliwakePageError` kind `invalid`). Code that compared or stored the string
|
|
24
|
+
needs updating.
|
|
25
|
+
|
|
26
|
+
`@foliwake/next/cache` adds `setGenerationFloor((site) => Promise<number | null>)`: the app's highest known live
|
|
27
|
+
generation (for example written by the hook's `onDelivery`). A cached live read whose generation is below the
|
|
28
|
+
floor no longer stays for `app.revalidate` seconds: it lives at most 15 seconds and is read again, and the old
|
|
29
|
+
page is shown meanwhile instead of an error. A floor that cannot be read turns the check off for that read and
|
|
30
|
+
logs; without a floor nothing changes.
|
|
31
|
+
|
|
32
|
+
### Patch Changes
|
|
33
|
+
|
|
34
|
+
- Updated dependencies [6dd1fd4]
|
|
35
|
+
- @foliwake/blocks-contract@0.9.0
|
|
36
|
+
|
|
37
|
+
## 0.8.0
|
|
38
|
+
|
|
39
|
+
### Patch Changes
|
|
40
|
+
|
|
41
|
+
- @foliwake/blocks-contract@0.8.0
|
|
42
|
+
|
|
10
43
|
## 0.7.0
|
|
11
44
|
|
|
12
45
|
### Patch Changes
|
package/README.md
CHANGED
|
@@ -18,6 +18,7 @@ directly with another server framework (a Vite or Remix server, Hono, Express wi
|
|
|
18
18
|
| `@foliwake/server/html` | the strict body check: `checkPlainBody`, `checkBody`, `serialize`, `srcsetCandidates` |
|
|
19
19
|
| `@foliwake/server/csp` | `foliwakeCsp` |
|
|
20
20
|
| `@foliwake/server/preload` | `preloadHints`: modulepreload and stylesheet hints for a page's blocks |
|
|
21
|
+
| `@foliwake/server/hook` | `verifyFoliwakeSignature`, `parseFoliwakeHook`: the signed hook a Foliwake server sends after a change |
|
|
21
22
|
| `@foliwake/server/schemas/remote-2.schema.json` | the JSON Schema of the config file |
|
|
22
23
|
|
|
23
24
|
## Install
|
|
@@ -119,6 +120,36 @@ export async function pageEndpoint(request: Request): Promise<Response> {
|
|
|
119
120
|
}
|
|
120
121
|
```
|
|
121
122
|
|
|
123
|
+
### Refresh the cache when the site changes
|
|
124
|
+
|
|
125
|
+
A Foliwake server whose site lists your app as a hook target POSTs `delivery.settled` once a change is live
|
|
126
|
+
and the caches in front of the origin serve it. The body names the live `generation`, and either the changed
|
|
127
|
+
paths (`pages`, at most 100: pages and other files such as an index) or `all: true`. Check the signature on
|
|
128
|
+
the raw body, then drop what you cached:
|
|
129
|
+
|
|
130
|
+
```ts
|
|
131
|
+
import { parseFoliwakeHook, verifyFoliwakeSignature } from '@foliwake/server/hook';
|
|
132
|
+
|
|
133
|
+
const cached = new Map<string, unknown>();
|
|
134
|
+
|
|
135
|
+
/** POST /api/webhooks/foliwake */
|
|
136
|
+
export async function hookEndpoint(request: Request): Promise<Response> {
|
|
137
|
+
const body = new Uint8Array(await request.arrayBuffer());
|
|
138
|
+
const signature = request.headers.get('foliwake-signature');
|
|
139
|
+
const secrets = [process.env.FOLIWAKE_HOOK_SECRET, process.env.FOLIWAKE_HOOK_SECRET_PREVIOUS];
|
|
140
|
+
if (!verifyFoliwakeSignature(body, signature, secrets).ok) return new Response(null, { status: 401 });
|
|
141
|
+
const payload = parseFoliwakeHook(body);
|
|
142
|
+
if (payload.event === 'ping') return Response.json({ ok: true, site: payload.site });
|
|
143
|
+
if (payload.all) cached.clear();
|
|
144
|
+
else for (const path of payload.pages ?? []) cached.delete(path);
|
|
145
|
+
return Response.json({ ok: true });
|
|
146
|
+
}
|
|
147
|
+
```
|
|
148
|
+
|
|
149
|
+
The signature is `t=<unix seconds>,v1=<hex HMAC-SHA256(secret, "<t>.<raw body>")>`, accepted within 300 s of
|
|
150
|
+
the app's clock. Answer 2xx only once the change is handled: anything else is sent again. Limit the body to
|
|
151
|
+
64 KiB (`HOOK_BODY_LIMIT`) and check that `payload.site` is yours.
|
|
152
|
+
|
|
122
153
|
### Code and media proxies
|
|
123
154
|
|
|
124
155
|
Mount the handlers under the prefixes of `app.proxies` and pass them the path segments after the prefix. They
|
|
@@ -189,6 +220,8 @@ Changes per version, breaking ones marked: `CHANGELOG.md` in the package
|
|
|
189
220
|
- Credentials never appear in messages; a missing or malformed password or key variable is a
|
|
190
221
|
`FoliwakeConfigError` that names the variable, not its value. The secret is read at each request, so a
|
|
191
222
|
rotated secret works without a restart. A private key whose own `kid` differs from the config's is refused.
|
|
223
|
+
- Rotating the hook secret: give the app the new secret as the previous one too (both accepted), switch the
|
|
224
|
+
server to it, then drop the old one.
|
|
192
225
|
- Rotating a service-token key: add the new public key to the delivery's key set first (both `kid`s listed),
|
|
193
226
|
then switch the app's `kid` and private key, then remove the old public key.
|
|
194
227
|
- `preparePage` leaves `page.preload` empty; `preloadHints` fills it from the release's
|
|
@@ -994,6 +1027,198 @@ function staticImports(source: string): string[]
|
|
|
994
1027
|
|
|
995
1028
|
- from `@foliwake/blocks-contract/page`: `PreloadHint`
|
|
996
1029
|
|
|
1030
|
+
### `@foliwake/server/hook`
|
|
1031
|
+
|
|
1032
|
+
**Functions and components**
|
|
1033
|
+
|
|
1034
|
+
#### `isFoliwakePagePath()`
|
|
1035
|
+
|
|
1036
|
+
Whether a path of `pages` is a page (`/lessons/a`), not another file such as `/lessons/query-index.json`.
|
|
1037
|
+
|
|
1038
|
+
```ts
|
|
1039
|
+
function isFoliwakePagePath(path: string): boolean
|
|
1040
|
+
```
|
|
1041
|
+
|
|
1042
|
+
**Returns** `boolean`
|
|
1043
|
+
|
|
1044
|
+
#### `parseFoliwakeHook()`
|
|
1045
|
+
|
|
1046
|
+
Parses a hook body (after its signature was checked). Unknown fields are ignored; an unknown operation kind is accepted, so a newer server's operations still refresh the app.
|
|
1047
|
+
|
|
1048
|
+
```ts
|
|
1049
|
+
function parseFoliwakeHook(body: Body): FoliwakeHookPayload
|
|
1050
|
+
```
|
|
1051
|
+
|
|
1052
|
+
| Parameter | Type | Description |
|
|
1053
|
+
| --- | --- | --- |
|
|
1054
|
+
| `body` | `Body` | The raw body. |
|
|
1055
|
+
|
|
1056
|
+
**Returns** `FoliwakeHookPayload`: The payload; throws FoliwakeHookError when it is not a version 1 `delivery.settled` or `ping`.
|
|
1057
|
+
|
|
1058
|
+
#### `signFoliwakeHook()`
|
|
1059
|
+
|
|
1060
|
+
The `Foliwake-Signature` value for a body: what a Foliwake server sends; useful in an app's tests.
|
|
1061
|
+
|
|
1062
|
+
```ts
|
|
1063
|
+
function signFoliwakeHook(body: Body, secret: string, t?: number): string
|
|
1064
|
+
```
|
|
1065
|
+
|
|
1066
|
+
| Parameter | Type | Description |
|
|
1067
|
+
| --- | --- | --- |
|
|
1068
|
+
| `body` | `Body` | The raw body, byte for byte as sent. |
|
|
1069
|
+
| `secret` | `string` | The shared secret. |
|
|
1070
|
+
| `t?` | `number` | The signature time in unix seconds (default: now). |
|
|
1071
|
+
|
|
1072
|
+
**Returns** `string`
|
|
1073
|
+
|
|
1074
|
+
#### `verifyFoliwakeSignature()`
|
|
1075
|
+
|
|
1076
|
+
Checks `Foliwake-Signature` against the raw body. Every secret is tried (the current one and, while it is rotated, the previous one); the comparison is constant-time.
|
|
1077
|
+
|
|
1078
|
+
```ts
|
|
1079
|
+
function verifyFoliwakeSignature(body: Body, header: string | null, secrets: readonly (string | null | undefined)[], options?: VerifySignatureOptions): SignatureCheck
|
|
1080
|
+
```
|
|
1081
|
+
|
|
1082
|
+
| Parameter | Type | Description |
|
|
1083
|
+
| --- | --- | --- |
|
|
1084
|
+
| `body` | `Body` | The raw request body, byte for byte as received. |
|
|
1085
|
+
| `header` | `string \| null` | The `Foliwake-Signature` header, or null. |
|
|
1086
|
+
| `secrets` | `readonly (string \| null \| undefined)[]` | The accepted secrets; empty or blank ones are ignored. |
|
|
1087
|
+
| `options?` | `VerifySignatureOptions` | `now` (ms) and `toleranceS` (default 300). |
|
|
1088
|
+
|
|
1089
|
+
**Returns** `SignatureCheck`: `{ ok: true }`, or `{ ok: false, reason }`: `malformed`, `expired`, `mismatch` or `no_secret`.
|
|
1090
|
+
|
|
1091
|
+
**Classes**
|
|
1092
|
+
|
|
1093
|
+
#### `FoliwakeHookError`
|
|
1094
|
+
|
|
1095
|
+
A hook body that is not a valid payload.
|
|
1096
|
+
|
|
1097
|
+
```ts
|
|
1098
|
+
class FoliwakeHookError extends Error
|
|
1099
|
+
```
|
|
1100
|
+
|
|
1101
|
+
| Member | Type | Description |
|
|
1102
|
+
| --- | --- | --- |
|
|
1103
|
+
| `name` | `string` | |
|
|
1104
|
+
|
|
1105
|
+
**Constants**
|
|
1106
|
+
|
|
1107
|
+
#### `HOOK_BODY_LIMIT`
|
|
1108
|
+
|
|
1109
|
+
The largest hook body an app accepts, in bytes.
|
|
1110
|
+
|
|
1111
|
+
```ts
|
|
1112
|
+
const HOOK_BODY_LIMIT: number
|
|
1113
|
+
```
|
|
1114
|
+
|
|
1115
|
+
#### `HOOK_PAGES_LIMIT`
|
|
1116
|
+
|
|
1117
|
+
The most `pages` a delivery lists; a larger change is sent as `all: true`.
|
|
1118
|
+
|
|
1119
|
+
```ts
|
|
1120
|
+
const HOOK_PAGES_LIMIT = 100
|
|
1121
|
+
```
|
|
1122
|
+
|
|
1123
|
+
#### `HOOK_TOLERANCE_SECONDS`
|
|
1124
|
+
|
|
1125
|
+
How far the signature time may be from the app's clock by default, in seconds.
|
|
1126
|
+
|
|
1127
|
+
```ts
|
|
1128
|
+
const HOOK_TOLERANCE_SECONDS = 300
|
|
1129
|
+
```
|
|
1130
|
+
|
|
1131
|
+
**Interfaces**
|
|
1132
|
+
|
|
1133
|
+
#### `FoliwakeDeliveryPayload`
|
|
1134
|
+
|
|
1135
|
+
`delivery.settled`: the live site is at `generation`, and the caches in front of the origin serve it.
|
|
1136
|
+
|
|
1137
|
+
```ts
|
|
1138
|
+
interface FoliwakeDeliveryPayload
|
|
1139
|
+
```
|
|
1140
|
+
|
|
1141
|
+
| Member | Type | Description |
|
|
1142
|
+
| --- | --- | --- |
|
|
1143
|
+
| `version` | `1` | |
|
|
1144
|
+
| `event` | `'delivery.settled'` | |
|
|
1145
|
+
| `site` | `string` | |
|
|
1146
|
+
| `generation` | `number` | The live generation; it only grows, except that `init` starts a new history. |
|
|
1147
|
+
| `release` | `string \| null` | The site release (`sr_…`), or null. |
|
|
1148
|
+
| `codeRelease` | `string \| null` | The code release (`cd_…`), or null. |
|
|
1149
|
+
| `operation` | `{ id: string; kind: FoliwakeOperationKind \| (string & {}); }` | |
|
|
1150
|
+
| `pages?` | `string[]` | The changed paths (pages, indexes); present only when `all` is false. A hint, at most 100. |
|
|
1151
|
+
| `all` | `boolean` | Every live page may have changed. |
|
|
1152
|
+
| `verified` | `boolean` | Whether the server read the new generation back through its own cache before sending. |
|
|
1153
|
+
| `sentAt` | `string` | |
|
|
1154
|
+
|
|
1155
|
+
#### `FoliwakePingPayload`
|
|
1156
|
+
|
|
1157
|
+
`ping`: the server checks the endpoint and its secret; the app changes nothing.
|
|
1158
|
+
|
|
1159
|
+
```ts
|
|
1160
|
+
interface FoliwakePingPayload
|
|
1161
|
+
```
|
|
1162
|
+
|
|
1163
|
+
| Member | Type | Description |
|
|
1164
|
+
| --- | --- | --- |
|
|
1165
|
+
| `version` | `1` | |
|
|
1166
|
+
| `event` | `'ping'` | |
|
|
1167
|
+
| `site` | `string` | |
|
|
1168
|
+
| `sentAt` | `string` | |
|
|
1169
|
+
|
|
1170
|
+
#### `VerifySignatureOptions`
|
|
1171
|
+
|
|
1172
|
+
Options of `verifyFoliwakeSignature`.
|
|
1173
|
+
|
|
1174
|
+
```ts
|
|
1175
|
+
interface VerifySignatureOptions
|
|
1176
|
+
```
|
|
1177
|
+
|
|
1178
|
+
| Member | Type | Description |
|
|
1179
|
+
| --- | --- | --- |
|
|
1180
|
+
| `now?` | `number` | The app's clock, in milliseconds since the epoch (default `Date.now()`). |
|
|
1181
|
+
| `toleranceS?` | `number` | The allowed distance between the signature time and `now`, in seconds (default 300). |
|
|
1182
|
+
|
|
1183
|
+
**Types**
|
|
1184
|
+
|
|
1185
|
+
#### `FoliwakeHookPayload`
|
|
1186
|
+
|
|
1187
|
+
Any hook body.
|
|
1188
|
+
|
|
1189
|
+
```ts
|
|
1190
|
+
type FoliwakeHookPayload = FoliwakeDeliveryPayload | FoliwakePingPayload
|
|
1191
|
+
```
|
|
1192
|
+
|
|
1193
|
+
#### `FoliwakeOperationKind`
|
|
1194
|
+
|
|
1195
|
+
The operations a delivery reports; a newer server may send others, which an app treats like any change.
|
|
1196
|
+
|
|
1197
|
+
```ts
|
|
1198
|
+
type FoliwakeOperationKind = 'content_publish' | 'unpublish' | 'rollback_full' | 'code_release' | 'rollback_code' | 'site_migration' | 'recovery_purge' | 'engine_update' | 'init'
|
|
1199
|
+
```
|
|
1200
|
+
|
|
1201
|
+
#### `SignatureCheck`
|
|
1202
|
+
|
|
1203
|
+
The result of `verifyFoliwakeSignature`.
|
|
1204
|
+
|
|
1205
|
+
```ts
|
|
1206
|
+
type SignatureCheck = {
|
|
1207
|
+
ok: true;
|
|
1208
|
+
} | {
|
|
1209
|
+
ok: false;
|
|
1210
|
+
reason: SignatureFailure;
|
|
1211
|
+
}
|
|
1212
|
+
```
|
|
1213
|
+
|
|
1214
|
+
#### `SignatureFailure`
|
|
1215
|
+
|
|
1216
|
+
Why a signature was refused.
|
|
1217
|
+
|
|
1218
|
+
```ts
|
|
1219
|
+
type SignatureFailure = 'malformed' | 'expired' | 'mismatch' | 'no_secret'
|
|
1220
|
+
```
|
|
1221
|
+
|
|
997
1222
|
### `@foliwake/server/schemas/remote-2.schema.json`
|
|
998
1223
|
|
|
999
1224
|
A file, not a module: `schemas/remote-2.schema.json` in the package.
|
package/dist/hook.d.ts
ADDED
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
/** The largest hook body an app accepts, in bytes. */
|
|
2
|
+
export declare const HOOK_BODY_LIMIT: number;
|
|
3
|
+
/** How far the signature time may be from the app's clock by default, in seconds. */
|
|
4
|
+
export declare const HOOK_TOLERANCE_SECONDS = 300;
|
|
5
|
+
/** The most `pages` a delivery lists; a larger change is sent as `all: true`. */
|
|
6
|
+
export declare const HOOK_PAGES_LIMIT = 100;
|
|
7
|
+
/** The operations a delivery reports; a newer server may send others, which an app treats like any change. */
|
|
8
|
+
export type FoliwakeOperationKind = 'content_publish' | 'unpublish' | 'rollback_full' | 'code_release' | 'rollback_code' | 'site_migration' | 'recovery_purge' | 'engine_update' | 'init';
|
|
9
|
+
/** `delivery.settled`: the live site is at `generation`, and the caches in front of the origin serve it. */
|
|
10
|
+
export interface FoliwakeDeliveryPayload {
|
|
11
|
+
version: 1;
|
|
12
|
+
event: 'delivery.settled';
|
|
13
|
+
site: string;
|
|
14
|
+
/** The live generation; it only grows, except that `init` starts a new history. */
|
|
15
|
+
generation: number;
|
|
16
|
+
/** The site release (`sr_…`), or null. */
|
|
17
|
+
release: string | null;
|
|
18
|
+
/** The code release (`cd_…`), or null. */
|
|
19
|
+
codeRelease: string | null;
|
|
20
|
+
operation: {
|
|
21
|
+
id: string;
|
|
22
|
+
kind: FoliwakeOperationKind | (string & {});
|
|
23
|
+
};
|
|
24
|
+
/** The changed paths (pages, indexes); present only when `all` is false. A hint, at most 100. */
|
|
25
|
+
pages?: string[];
|
|
26
|
+
/** Every live page may have changed. */
|
|
27
|
+
all: boolean;
|
|
28
|
+
/** Whether the server read the new generation back through its own cache before sending. */
|
|
29
|
+
verified: boolean;
|
|
30
|
+
sentAt: string;
|
|
31
|
+
}
|
|
32
|
+
/** `ping`: the server checks the endpoint and its secret; the app changes nothing. */
|
|
33
|
+
export interface FoliwakePingPayload {
|
|
34
|
+
version: 1;
|
|
35
|
+
event: 'ping';
|
|
36
|
+
site: string;
|
|
37
|
+
sentAt: string;
|
|
38
|
+
}
|
|
39
|
+
/** Any hook body. */
|
|
40
|
+
export type FoliwakeHookPayload = FoliwakeDeliveryPayload | FoliwakePingPayload;
|
|
41
|
+
/** Options of `verifyFoliwakeSignature`. */
|
|
42
|
+
export interface VerifySignatureOptions {
|
|
43
|
+
/** The app's clock, in milliseconds since the epoch (default `Date.now()`). */
|
|
44
|
+
now?: number;
|
|
45
|
+
/** The allowed distance between the signature time and `now`, in seconds (default 300). */
|
|
46
|
+
toleranceS?: number;
|
|
47
|
+
}
|
|
48
|
+
/** Why a signature was refused. */
|
|
49
|
+
export type SignatureFailure = 'malformed' | 'expired' | 'mismatch' | 'no_secret';
|
|
50
|
+
/** The result of `verifyFoliwakeSignature`. */
|
|
51
|
+
export type SignatureCheck = {
|
|
52
|
+
ok: true;
|
|
53
|
+
} | {
|
|
54
|
+
ok: false;
|
|
55
|
+
reason: SignatureFailure;
|
|
56
|
+
};
|
|
57
|
+
/** A hook body that is not a valid payload. */
|
|
58
|
+
export declare class FoliwakeHookError extends Error {
|
|
59
|
+
name: string;
|
|
60
|
+
}
|
|
61
|
+
type Body = string | Uint8Array;
|
|
62
|
+
/**
|
|
63
|
+
* The `Foliwake-Signature` value for a body: what a Foliwake server sends; useful in an app's tests.
|
|
64
|
+
*
|
|
65
|
+
* @param body - The raw body, byte for byte as sent.
|
|
66
|
+
* @param secret - The shared secret.
|
|
67
|
+
* @param t - The signature time in unix seconds (default: now).
|
|
68
|
+
*/
|
|
69
|
+
export declare function signFoliwakeHook(body: Body, secret: string, t?: number): string;
|
|
70
|
+
/**
|
|
71
|
+
* Checks `Foliwake-Signature` against the raw body. Every secret is tried (the current one and, while it is
|
|
72
|
+
* rotated, the previous one); the comparison is constant-time.
|
|
73
|
+
*
|
|
74
|
+
* @param body - The raw request body, byte for byte as received.
|
|
75
|
+
* @param header - The `Foliwake-Signature` header, or null.
|
|
76
|
+
* @param secrets - The accepted secrets; empty or blank ones are ignored.
|
|
77
|
+
* @param options - `now` (ms) and `toleranceS` (default 300).
|
|
78
|
+
* @returns `{ ok: true }`, or `{ ok: false, reason }`: `malformed`, `expired`, `mismatch` or `no_secret`.
|
|
79
|
+
*/
|
|
80
|
+
export declare function verifyFoliwakeSignature(body: Body, header: string | null, secrets: readonly (string | null | undefined)[], options?: VerifySignatureOptions): SignatureCheck;
|
|
81
|
+
/** Whether a path of `pages` is a page (`/lessons/a`), not another file such as `/lessons/query-index.json`. */
|
|
82
|
+
export declare function isFoliwakePagePath(path: string): boolean;
|
|
83
|
+
/**
|
|
84
|
+
* Parses a hook body (after its signature was checked). Unknown fields are ignored; an unknown operation kind is
|
|
85
|
+
* accepted, so a newer server's operations still refresh the app.
|
|
86
|
+
*
|
|
87
|
+
* @param body - The raw body.
|
|
88
|
+
* @returns The payload; throws FoliwakeHookError when it is not a version 1 `delivery.settled` or `ping`.
|
|
89
|
+
*/
|
|
90
|
+
export declare function parseFoliwakeHook(body: Body): FoliwakeHookPayload;
|
|
91
|
+
export {};
|
package/dist/hook.js
ADDED
|
@@ -0,0 +1,188 @@
|
|
|
1
|
+
// @foliwake/server/hook: the signed POST a Foliwake server sends an app once a change is live and the caches in
|
|
2
|
+
// front of the origin are refreshed (`delivery.settled`), or to check the app's endpoint (`ping`).
|
|
3
|
+
// Wire format, version 1:
|
|
4
|
+
// Foliwake-Event: delivery.settled | ping
|
|
5
|
+
// Foliwake-Delivery: <uuid v4>, new on every attempt
|
|
6
|
+
// Foliwake-Signature: t=<unix seconds>,v1=<hex HMAC-SHA256(secret, `${t}.${raw body}`)>
|
|
7
|
+
// No framework here: the Next.js route handler is `foliwakeRevalidateHandler` of `@foliwake/next/revalidate`.
|
|
8
|
+
import { createHmac, timingSafeEqual } from 'node:crypto';
|
|
9
|
+
import { PAGE_PATH_PATTERN } from './constants.js';
|
|
10
|
+
/** The largest hook body an app accepts, in bytes. */
|
|
11
|
+
export const HOOK_BODY_LIMIT = 64 * 1024;
|
|
12
|
+
/** How far the signature time may be from the app's clock by default, in seconds. */
|
|
13
|
+
export const HOOK_TOLERANCE_SECONDS = 300;
|
|
14
|
+
/** The most `pages` a delivery lists; a larger change is sent as `all: true`. */
|
|
15
|
+
export const HOOK_PAGES_LIMIT = 100;
|
|
16
|
+
/** A hook body that is not a valid payload. */
|
|
17
|
+
export class FoliwakeHookError extends Error {
|
|
18
|
+
name = 'FoliwakeHookError';
|
|
19
|
+
}
|
|
20
|
+
const SIGNATURE_TIME = /^\d{1,12}$/;
|
|
21
|
+
const SIGNATURE_HEX = /^[0-9a-f]{64}$/;
|
|
22
|
+
const TOKEN = /^[a-z][a-z0-9_.]{0,63}$/;
|
|
23
|
+
function bytesOf(body) {
|
|
24
|
+
return typeof body === 'string' ? new TextEncoder().encode(body) : body;
|
|
25
|
+
}
|
|
26
|
+
function hmacHex(secret, t, body) {
|
|
27
|
+
return createHmac('sha256', secret).update(`${t}.`).update(body).digest('hex');
|
|
28
|
+
}
|
|
29
|
+
/**
|
|
30
|
+
* The `Foliwake-Signature` value for a body: what a Foliwake server sends; useful in an app's tests.
|
|
31
|
+
*
|
|
32
|
+
* @param body - The raw body, byte for byte as sent.
|
|
33
|
+
* @param secret - The shared secret.
|
|
34
|
+
* @param t - The signature time in unix seconds (default: now).
|
|
35
|
+
*/
|
|
36
|
+
export function signFoliwakeHook(body, secret, t = Math.floor(Date.now() / 1000)) {
|
|
37
|
+
const time = String(Math.trunc(t));
|
|
38
|
+
return `t=${time},v1=${hmacHex(secret, time, bytesOf(body))}`;
|
|
39
|
+
}
|
|
40
|
+
function parseSignatureHeader(header) {
|
|
41
|
+
if (header === null)
|
|
42
|
+
return null;
|
|
43
|
+
let t = null;
|
|
44
|
+
const signatures = [];
|
|
45
|
+
for (const part of header.split(',')) {
|
|
46
|
+
const [key, value] = part.trim().split('=', 2);
|
|
47
|
+
if (key === 't' && value !== undefined && SIGNATURE_TIME.test(value))
|
|
48
|
+
t = value;
|
|
49
|
+
else if (key === 'v1' && value !== undefined && SIGNATURE_HEX.test(value))
|
|
50
|
+
signatures.push(value);
|
|
51
|
+
}
|
|
52
|
+
return t === null || signatures.length === 0 ? null : { t, signatures };
|
|
53
|
+
}
|
|
54
|
+
function sameHex(a, b) {
|
|
55
|
+
return timingSafeEqual(Buffer.from(a, 'hex'), Buffer.from(b, 'hex'));
|
|
56
|
+
}
|
|
57
|
+
function matchesAny(parsed, secrets, body) {
|
|
58
|
+
let matched = false;
|
|
59
|
+
for (const secret of secrets) {
|
|
60
|
+
const expected = hmacHex(secret, parsed.t, body);
|
|
61
|
+
for (const signature of parsed.signatures)
|
|
62
|
+
matched = sameHex(expected, signature) || matched;
|
|
63
|
+
}
|
|
64
|
+
return matched;
|
|
65
|
+
}
|
|
66
|
+
/**
|
|
67
|
+
* Checks `Foliwake-Signature` against the raw body. Every secret is tried (the current one and, while it is
|
|
68
|
+
* rotated, the previous one); the comparison is constant-time.
|
|
69
|
+
*
|
|
70
|
+
* @param body - The raw request body, byte for byte as received.
|
|
71
|
+
* @param header - The `Foliwake-Signature` header, or null.
|
|
72
|
+
* @param secrets - The accepted secrets; empty or blank ones are ignored.
|
|
73
|
+
* @param options - `now` (ms) and `toleranceS` (default 300).
|
|
74
|
+
* @returns `{ ok: true }`, or `{ ok: false, reason }`: `malformed`, `expired`, `mismatch` or `no_secret`.
|
|
75
|
+
*/
|
|
76
|
+
export function verifyFoliwakeSignature(body, header, secrets, options = {}) {
|
|
77
|
+
const usable = secrets.filter((s) => typeof s === 'string' && s.length > 0);
|
|
78
|
+
if (usable.length === 0)
|
|
79
|
+
return { ok: false, reason: 'no_secret' };
|
|
80
|
+
const parsed = parseSignatureHeader(header);
|
|
81
|
+
if (parsed === null)
|
|
82
|
+
return { ok: false, reason: 'malformed' };
|
|
83
|
+
const nowS = (options.now ?? Date.now()) / 1000;
|
|
84
|
+
const tolerance = options.toleranceS ?? HOOK_TOLERANCE_SECONDS;
|
|
85
|
+
if (Math.abs(nowS - Number(parsed.t)) > tolerance)
|
|
86
|
+
return { ok: false, reason: 'expired' };
|
|
87
|
+
if (!matchesAny(parsed, usable, bytesOf(body)))
|
|
88
|
+
return { ok: false, reason: 'mismatch' };
|
|
89
|
+
return { ok: true };
|
|
90
|
+
}
|
|
91
|
+
function fail(message) {
|
|
92
|
+
throw new FoliwakeHookError(message);
|
|
93
|
+
}
|
|
94
|
+
function objectOf(value, what) {
|
|
95
|
+
if (typeof value !== 'object' || value === null || Array.isArray(value))
|
|
96
|
+
fail(`${what} is not an object`);
|
|
97
|
+
return value;
|
|
98
|
+
}
|
|
99
|
+
function stringOf(fields, key) {
|
|
100
|
+
const value = fields[key];
|
|
101
|
+
if (typeof value !== 'string' || value.length === 0 || value.length > 256)
|
|
102
|
+
fail(`${key} is not a string`);
|
|
103
|
+
return value;
|
|
104
|
+
}
|
|
105
|
+
function nullableStringOf(fields, key) {
|
|
106
|
+
return fields[key] === null || fields[key] === undefined ? null : stringOf(fields, key);
|
|
107
|
+
}
|
|
108
|
+
function booleanOf(fields, key) {
|
|
109
|
+
if (typeof fields[key] !== 'boolean')
|
|
110
|
+
fail(`${key} is not a boolean`);
|
|
111
|
+
return fields[key];
|
|
112
|
+
}
|
|
113
|
+
function generationOf(fields) {
|
|
114
|
+
const value = fields.generation;
|
|
115
|
+
if (typeof value !== 'number' || !Number.isSafeInteger(value) || value < 0)
|
|
116
|
+
fail('generation is not an integer');
|
|
117
|
+
return value;
|
|
118
|
+
}
|
|
119
|
+
function operationOf(fields) {
|
|
120
|
+
const operation = objectOf(fields.operation, 'operation');
|
|
121
|
+
const kind = stringOf(operation, 'kind');
|
|
122
|
+
if (!TOKEN.test(kind))
|
|
123
|
+
fail('operation.kind is not a token');
|
|
124
|
+
return { id: stringOf(operation, 'id'), kind };
|
|
125
|
+
}
|
|
126
|
+
/** Whether a path of `pages` is a page (`/lessons/a`), not another file such as `/lessons/query-index.json`. */
|
|
127
|
+
export function isFoliwakePagePath(path) {
|
|
128
|
+
return PAGE_PATH_PATTERN.test(path);
|
|
129
|
+
}
|
|
130
|
+
function isHookPath(value) {
|
|
131
|
+
return typeof value === 'string' && value.startsWith('/') && value.length <= 1024;
|
|
132
|
+
}
|
|
133
|
+
function pagesOf(fields) {
|
|
134
|
+
const pages = fields.pages;
|
|
135
|
+
if (!Array.isArray(pages))
|
|
136
|
+
fail('pages is missing while all is false');
|
|
137
|
+
if (pages.length > HOOK_PAGES_LIMIT)
|
|
138
|
+
fail(`pages lists more than ${HOOK_PAGES_LIMIT} paths`);
|
|
139
|
+
if (!pages.every(isHookPath))
|
|
140
|
+
fail('pages holds a value that is not a path');
|
|
141
|
+
return [...new Set(pages)];
|
|
142
|
+
}
|
|
143
|
+
function deliveryOf(fields, site, sentAt) {
|
|
144
|
+
const all = booleanOf(fields, 'all');
|
|
145
|
+
const payload = {
|
|
146
|
+
version: 1,
|
|
147
|
+
event: 'delivery.settled',
|
|
148
|
+
site,
|
|
149
|
+
generation: generationOf(fields),
|
|
150
|
+
release: nullableStringOf(fields, 'release'),
|
|
151
|
+
codeRelease: nullableStringOf(fields, 'codeRelease'),
|
|
152
|
+
operation: operationOf(fields),
|
|
153
|
+
all,
|
|
154
|
+
verified: booleanOf(fields, 'verified'),
|
|
155
|
+
sentAt,
|
|
156
|
+
};
|
|
157
|
+
if (!all)
|
|
158
|
+
payload.pages = pagesOf(fields);
|
|
159
|
+
return payload;
|
|
160
|
+
}
|
|
161
|
+
function jsonOf(body) {
|
|
162
|
+
try {
|
|
163
|
+
const text = typeof body === 'string' ? body : new TextDecoder('utf-8', { fatal: true }).decode(body);
|
|
164
|
+
return JSON.parse(text);
|
|
165
|
+
}
|
|
166
|
+
catch {
|
|
167
|
+
return fail('the body is not JSON');
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
/**
|
|
171
|
+
* Parses a hook body (after its signature was checked). Unknown fields are ignored; an unknown operation kind is
|
|
172
|
+
* accepted, so a newer server's operations still refresh the app.
|
|
173
|
+
*
|
|
174
|
+
* @param body - The raw body.
|
|
175
|
+
* @returns The payload; throws FoliwakeHookError when it is not a version 1 `delivery.settled` or `ping`.
|
|
176
|
+
*/
|
|
177
|
+
export function parseFoliwakeHook(body) {
|
|
178
|
+
const fields = objectOf(jsonOf(body), 'the body');
|
|
179
|
+
if (fields.version !== 1)
|
|
180
|
+
fail('version is not 1');
|
|
181
|
+
const site = stringOf(fields, 'site');
|
|
182
|
+
const sentAt = stringOf(fields, 'sentAt');
|
|
183
|
+
if (fields.event === 'ping')
|
|
184
|
+
return { version: 1, event: 'ping', site, sentAt };
|
|
185
|
+
if (fields.event === 'delivery.settled')
|
|
186
|
+
return deliveryOf(fields, site, sentAt);
|
|
187
|
+
return fail('event is neither delivery.settled nor ping');
|
|
188
|
+
}
|
package/dist/page.js
CHANGED
|
@@ -12,7 +12,7 @@ export { pageImportMap } from '@foliwake/blocks-contract/import-map';
|
|
|
12
12
|
const HTML_CONTRACT = /^\d{1,4}$/;
|
|
13
13
|
const LANG = /^[A-Za-z]{1,8}(?:-[A-Za-z0-9]{1,8})*$/;
|
|
14
14
|
const PAGE_ID = /^[A-Za-z0-9_-]{1,128}$/;
|
|
15
|
-
const GENERATION =
|
|
15
|
+
const GENERATION = /^\d{1,15}$/;
|
|
16
16
|
const MODE = /^[a-z][a-z0-9-]{0,31}$/;
|
|
17
17
|
/** The origin URL path of a page's body (`/` → `/index.plain.html`). */
|
|
18
18
|
export function plainPath(pagePath) {
|
|
@@ -29,6 +29,10 @@ function header(response, name, pattern, required = false) {
|
|
|
29
29
|
throw new FoliwakePageError('invalid', `The origin answered an invalid ${name}.`);
|
|
30
30
|
return value;
|
|
31
31
|
}
|
|
32
|
+
/** `X-Site-Generation` as a number: a non-negative integer, or null when the origin sent none. */
|
|
33
|
+
function generationOf(value) {
|
|
34
|
+
return value === null ? null : Number(value);
|
|
35
|
+
}
|
|
32
36
|
const NO_CODE_RELEASE = 'The origin answered without X-Code-Release: it is not a plain/2 Foliwake origin.';
|
|
33
37
|
function codeReleaseOf(response, client, channel) {
|
|
34
38
|
const value = response.headers.get('x-code-release');
|
|
@@ -87,7 +91,7 @@ export async function readEnvelope(config, client, site, channel, path) {
|
|
|
87
91
|
const htmlContract = header(response, 'x-html-contract', HTML_CONTRACT, true);
|
|
88
92
|
const lang = header(response, 'content-language', LANG);
|
|
89
93
|
const pageId = header(response, 'x-page-id', PAGE_ID);
|
|
90
|
-
const generation = header(response, 'x-site-generation', GENERATION);
|
|
94
|
+
const generation = generationOf(header(response, 'x-site-generation', GENERATION));
|
|
91
95
|
const etag = response.headers.get('etag');
|
|
92
96
|
let bytes;
|
|
93
97
|
try {
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@foliwake/server",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.9.0",
|
|
4
4
|
"description": "Server toolkit for apps that show Foliwake pages: config v2, origin client, envelope read, page check and preparation, code/media proxy handlers, CSP. Web Request/Response, no framework.",
|
|
5
5
|
"license": "Apache-2.0",
|
|
6
6
|
"type": "module",
|
|
@@ -64,13 +64,17 @@
|
|
|
64
64
|
"types": "./dist/preload.d.ts",
|
|
65
65
|
"default": "./dist/preload.js"
|
|
66
66
|
},
|
|
67
|
+
"./hook": {
|
|
68
|
+
"types": "./dist/hook.d.ts",
|
|
69
|
+
"default": "./dist/hook.js"
|
|
70
|
+
},
|
|
67
71
|
"./schemas/remote-2.schema.json": "./schemas/remote-2.schema.json",
|
|
68
72
|
"./package.json": "./package.json"
|
|
69
73
|
},
|
|
70
74
|
"dependencies": {
|
|
71
75
|
"htmlparser2": "10.1.0",
|
|
72
76
|
"jose": "6.2.15",
|
|
73
|
-
"@foliwake/blocks-contract": "0.
|
|
77
|
+
"@foliwake/blocks-contract": "0.9.0"
|
|
74
78
|
},
|
|
75
79
|
"files": [
|
|
76
80
|
"dist/",
|