@foliwake/next 0.9.0 → 0.10.2

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.
@@ -0,0 +1,110 @@
1
+ {
2
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
3
+ "$id": "https://foliwake.org/schemas/remote-2.schema.json",
4
+ "title": "foliwake.remote.json version 2",
5
+ "description": "Which Foliwake site an app (or `foliwake dev --remote`) reads, the NAMES of the variables holding its credentials, and the app's settings. No secrets: values are read from the environment on the server. The TypeScript parser (@foliwake/server/config) is the authority; test/packages/server-config-schema.test.js keeps both in step.",
6
+ "type": "object",
7
+ "additionalProperties": false,
8
+ "required": ["version", "site"],
9
+ "anyOf": [{ "required": ["live"] }, { "required": ["preview"] }],
10
+ "properties": {
11
+ "$schema": { "type": "string" },
12
+ "$comment": { "type": "string" },
13
+ "version": { "const": 2 },
14
+ "site": { "type": "string", "pattern": "^[a-z0-9][a-z0-9-]{0,62}$" },
15
+ "live": { "$ref": "#/$defs/endpoint" },
16
+ "preview": { "$ref": "#/$defs/endpoint" },
17
+ "app": {
18
+ "type": "object",
19
+ "additionalProperties": false,
20
+ "required": ["pages"],
21
+ "properties": {
22
+ "pages": {
23
+ "description": "Page globs the app may read (query-index grammar: [a-z0-9_-] literals, * within a segment, ** as a whole segment; /x/** also matches /x).",
24
+ "type": "array", "minItems": 1, "maxItems": 20,
25
+ "items": { "type": "string", "maxLength": 200, "pattern": "^/(?:(?:\\*\\*|[a-z0-9_*-]+)(?:/(?:\\*\\*|[a-z0-9_*-]+))*)?$" }
26
+ },
27
+ "proxies": {
28
+ "description": "App-origin URL prefixes of the proxies. Not /, /_next, /api, /code, /media or below them; code and media differ and neither is inside the other.",
29
+ "type": "object", "additionalProperties": false,
30
+ "properties": {
31
+ "code": { "$ref": "#/$defs/prefix", "default": "/foliwake-code" },
32
+ "media": { "$ref": "#/$defs/prefix", "default": "/foliwake-media" },
33
+ "pages": { "type": "null" }
34
+ }
35
+ },
36
+ "blocks": {
37
+ "type": "object", "additionalProperties": false,
38
+ "properties": {
39
+ "entry": {
40
+ "description": "Path of the blocks module inside a code release; absent or null: bodies stay static.",
41
+ "type": ["string", "null"],
42
+ "pattern": "^(?:scripts|components|_foliwake)(?:/[A-Za-z0-9_][A-Za-z0-9_.-]*){1,7}\\.js$"
43
+ },
44
+ "contract": { "type": "string", "pattern": "^foliwake-blocks/[1-9][0-9]{0,2}$", "default": "foliwake-blocks/2" },
45
+ "eventPrefix": { "type": "string", "pattern": "^[a-z][a-z0-9-]{0,31}$", "default": "block" }
46
+ }
47
+ },
48
+ "media": {
49
+ "description": "Live pictures through a transforming host (preview pictures always go through the media proxy).",
50
+ "type": ["object", "null"], "additionalProperties": false, "required": ["base"],
51
+ "properties": {
52
+ "base": { "type": "string", "pattern": "^https://[^/?#@]+$" },
53
+ "transform": { "enum": ["cloudflare-images", null] }
54
+ }
55
+ },
56
+ "revalidate": { "description": "Seconds before a cached envelope is stale (stale-while-revalidate; expire is 24 h).", "type": "integer", "minimum": 1, "maximum": 86400, "default": 300 }
57
+ }
58
+ }
59
+ },
60
+ "$defs": {
61
+ "prefix": { "type": "string", "pattern": "^(?:/[a-z0-9-]+)+$" },
62
+ "basicAuth": {
63
+ "type": "object", "additionalProperties": false, "required": ["type", "username", "passwordEnv"],
64
+ "properties": {
65
+ "type": { "const": "basic" },
66
+ "username": { "type": "string", "minLength": 1, "maxLength": 128, "pattern": "^[^:\\u0000-\\u001f\\u007f]+$" },
67
+ "passwordEnv": {
68
+ "type": "string",
69
+ "pattern": "^[A-Z_][A-Z0-9_]{0,127}$",
70
+ "description": "The NAME of the environment variable holding the password."
71
+ }
72
+ }
73
+ },
74
+ "serviceTokenAuth": {
75
+ "description": "Each request carries a fresh ES256 JWT for its exact path (exp = iat + 60), signed with the private key in privateKeyEnv; the delivery checks it with the public key of kid.",
76
+ "type": "object", "additionalProperties": false, "required": ["type", "issuer", "kid", "privateKeyEnv"],
77
+ "properties": {
78
+ "type": { "const": "service-token" },
79
+ "issuer": {
80
+ "type": "string",
81
+ "pattern": "^[A-Za-z0-9._:/-]{1,256}$",
82
+ "description": "The iss the delivery expects (its TOKEN_ISSUER)."
83
+ },
84
+ "kid": {
85
+ "type": "string",
86
+ "pattern": "^[A-Za-z0-9._-]{1,128}$",
87
+ "description": "The key id of the public key the delivery holds."
88
+ },
89
+ "privateKeyEnv": {
90
+ "type": "string",
91
+ "pattern": "^[A-Z_][A-Z0-9_]{0,127}$",
92
+ "description": "The NAME of the environment variable holding the ES256 private key as JWK JSON text."
93
+ }
94
+ }
95
+ },
96
+ "endpoint": {
97
+ "type": "object", "additionalProperties": false, "required": ["url"],
98
+ "properties": {
99
+ "url": { "type": "string", "description": "Site origin only: https (http only for loopback hosts), no credentials, path, query or fragment." },
100
+ "auth": {
101
+ "oneOf": [
102
+ { "type": "null" },
103
+ { "$ref": "#/$defs/basicAuth" },
104
+ { "$ref": "#/$defs/serviceTokenAuth" }
105
+ ]
106
+ }
107
+ }
108
+ }
109
+ }
110
+ }
@@ -0,0 +1,204 @@
1
+ {
2
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
3
+ "$id": "https://foliwake.org/schemas/remote-3.schema.json",
4
+ "title": "foliwake.remote.json version 3",
5
+ "description": "Optional overrides of an app configured by FOLIWAKE_URL: the site's discovery document (/.well-known/foliwake.json) gives its origins and media CDN; this file holds the app's own settings and the NAMES of the variables holding credentials. No secrets. The TypeScript parser (@foliwake/server/resolve) is the authority; test/server-config-v3.test.js keeps both in step.",
6
+ "type": "object",
7
+ "additionalProperties": false,
8
+ "required": [
9
+ "version"
10
+ ],
11
+ "properties": {
12
+ "$schema": {
13
+ "type": "string"
14
+ },
15
+ "$comment": {
16
+ "type": "string"
17
+ },
18
+ "version": {
19
+ "const": 3
20
+ },
21
+ "site": {
22
+ "type": "string",
23
+ "description": "Checked against the discovery document's site."
24
+ },
25
+ "live": {
26
+ "$ref": "#/$defs/channel"
27
+ },
28
+ "preview": {
29
+ "$ref": "#/$defs/channel",
30
+ "description": "Default auth: Basic, user preview, password from FOLIWAKE_PREVIEW_TOKEN."
31
+ },
32
+ "app": {
33
+ "type": "object",
34
+ "additionalProperties": false,
35
+ "properties": {
36
+ "pages": {
37
+ "description": "Page globs the app may read (query-index grammar: [a-z0-9_-] literals, * within a segment, ** as a whole segment; /x/** also matches /x).",
38
+ "type": "array",
39
+ "minItems": 1,
40
+ "maxItems": 20,
41
+ "items": {
42
+ "type": "string",
43
+ "maxLength": 200,
44
+ "pattern": "^/(?:(?:\\*\\*|[a-z0-9_*-]+)(?:/(?:\\*\\*|[a-z0-9_*-]+))*)?$"
45
+ }
46
+ },
47
+ "proxies": {
48
+ "description": "App-origin URL prefixes of the proxies. Not /, /_next, /api, /code, /media or below them; code and media differ and neither is inside the other.",
49
+ "type": "object",
50
+ "additionalProperties": false,
51
+ "properties": {
52
+ "code": {
53
+ "$ref": "#/$defs/prefix",
54
+ "default": "/foliwake/code"
55
+ },
56
+ "media": {
57
+ "$ref": "#/$defs/prefix",
58
+ "default": "/foliwake/media"
59
+ },
60
+ "pages": {
61
+ "type": "null"
62
+ }
63
+ }
64
+ },
65
+ "blocks": {
66
+ "type": "object",
67
+ "additionalProperties": false,
68
+ "properties": {
69
+ "entry": {
70
+ "description": "Path of the blocks module inside a code release; absent or null: bodies stay static.",
71
+ "type": [
72
+ "string",
73
+ "null"
74
+ ],
75
+ "pattern": "^(?:scripts|components|_foliwake)(?:/[A-Za-z0-9_][A-Za-z0-9_.-]*){1,7}\\.js$"
76
+ },
77
+ "contract": {
78
+ "type": "string",
79
+ "pattern": "^foliwake-blocks/[1-9][0-9]{0,2}$",
80
+ "default": "foliwake-blocks/2"
81
+ },
82
+ "eventPrefix": {
83
+ "type": "string",
84
+ "pattern": "^[a-z][a-z0-9-]{0,31}$",
85
+ "default": "block"
86
+ }
87
+ }
88
+ },
89
+ "media": {
90
+ "description": "Live pictures through a transforming host (preview pictures always go through the media proxy).",
91
+ "type": [
92
+ "object",
93
+ "null"
94
+ ],
95
+ "additionalProperties": false,
96
+ "required": [
97
+ "base"
98
+ ],
99
+ "properties": {
100
+ "base": {
101
+ "type": "string",
102
+ "pattern": "^https://[^/?#@]+$"
103
+ },
104
+ "transform": {
105
+ "enum": [
106
+ "cloudflare-images",
107
+ null
108
+ ]
109
+ }
110
+ }
111
+ },
112
+ "revalidate": {
113
+ "description": "Seconds before a cached envelope is stale (stale-while-revalidate; expire is 24 h).",
114
+ "type": "integer",
115
+ "minimum": 1,
116
+ "maximum": 86400,
117
+ "default": 300
118
+ }
119
+ },
120
+ "description": "The app's own decisions; every key is optional. Without pages: [\"/**\"] (required when live uses a service token). Without blocks: each page's code release names its blocks module (X-Foliwake-Blocks). Without media: the discovery document's media CDN, if any."
121
+ }
122
+ },
123
+ "$defs": {
124
+ "prefix": {
125
+ "type": "string",
126
+ "pattern": "^(?:/[a-z0-9-]+)+$"
127
+ },
128
+ "basicAuth": {
129
+ "type": "object",
130
+ "additionalProperties": false,
131
+ "required": [
132
+ "type",
133
+ "username",
134
+ "passwordEnv"
135
+ ],
136
+ "properties": {
137
+ "type": {
138
+ "const": "basic"
139
+ },
140
+ "username": {
141
+ "type": "string",
142
+ "minLength": 1,
143
+ "maxLength": 128,
144
+ "pattern": "^[^:\\u0000-\\u001f\\u007f]+$"
145
+ },
146
+ "passwordEnv": {
147
+ "type": "string",
148
+ "pattern": "^[A-Z_][A-Z0-9_]{0,127}$",
149
+ "description": "The NAME of the environment variable holding the password."
150
+ }
151
+ }
152
+ },
153
+ "serviceTokenAuth": {
154
+ "description": "Each request carries a fresh ES256 JWT for its exact path (exp = iat + 60), signed with the private key in privateKeyEnv; the delivery checks it with the public key of kid.",
155
+ "type": "object",
156
+ "additionalProperties": false,
157
+ "required": [
158
+ "type",
159
+ "issuer",
160
+ "kid",
161
+ "privateKeyEnv"
162
+ ],
163
+ "properties": {
164
+ "type": {
165
+ "const": "service-token"
166
+ },
167
+ "issuer": {
168
+ "type": "string",
169
+ "pattern": "^[A-Za-z0-9._:/-]{1,256}$",
170
+ "description": "The iss the delivery expects (its TOKEN_ISSUER)."
171
+ },
172
+ "kid": {
173
+ "type": "string",
174
+ "pattern": "^[A-Za-z0-9._-]{1,128}$",
175
+ "description": "The key id of the public key the delivery holds."
176
+ },
177
+ "privateKeyEnv": {
178
+ "type": "string",
179
+ "pattern": "^[A-Z_][A-Z0-9_]{0,127}$",
180
+ "description": "The NAME of the environment variable holding the ES256 private key as JWK JSON text."
181
+ }
182
+ }
183
+ },
184
+ "channel": {
185
+ "type": "object",
186
+ "additionalProperties": false,
187
+ "properties": {
188
+ "auth": {
189
+ "oneOf": [
190
+ {
191
+ "type": "null"
192
+ },
193
+ {
194
+ "$ref": "#/$defs/basicAuth"
195
+ },
196
+ {
197
+ "$ref": "#/$defs/serviceTokenAuth"
198
+ }
199
+ ]
200
+ }
201
+ }
202
+ }
203
+ }
204
+ }
@@ -1,33 +0,0 @@
1
- import { type FoliwakeDeliveryPayload } from '@foliwake/server/hook';
2
- /** At most this many pages are read again right after a delivery (`warm`); never on `all`. */
3
- export declare const WARM_LIMIT = 20;
4
- /** What the endpoint needs from Next and from the app. */
5
- export interface RevalidateDeps {
6
- /** The configured site. */
7
- site: string;
8
- /** The accepted secrets, read per request (current, then previous). */
9
- secrets(): (string | undefined)[];
10
- /** The live tag of the site (no path) or of one path. */
11
- liveTag(path?: string): string;
12
- /** Expires one tag (revalidateTag with the chosen profile). */
13
- expire(tag: string): void;
14
- /** Reads one page into the cache again. */
15
- warm(path: string): Promise<unknown>;
16
- /** Runs work after the response is sent. */
17
- schedule(task: () => Promise<void>): void;
18
- /** Whether pages are read again after a delivery. */
19
- warmPages: boolean;
20
- onDelivery?: (payload: FoliwakeDeliveryPayload) => void | Promise<void>;
21
- toleranceS?: number;
22
- now?: () => number;
23
- log: Pick<Console, 'warn' | 'error'>;
24
- }
25
- /** The tags a delivery expires: the site's live tag on `all`, else one tag per listed path. */
26
- export declare function deliveryTags(payload: FoliwakeDeliveryPayload, liveTag: (path?: string) => string): string[];
27
- /** The pages read again after a delivery: none on `all`, page paths only, at most WARM_LIMIT. */
28
- export declare function warmPaths(payload: FoliwakeDeliveryPayload): string[];
29
- /**
30
- * The hook endpoint as a function of a Request: 413 over 64 KiB, 401 on a bad or expired signature, 400 on a
31
- * body that is not a payload or names another site, 200 otherwise.
32
- */
33
- export declare function createRevalidateHandler(deps: RevalidateDeps): (request: Request) => Promise<Response>;
@@ -1,144 +0,0 @@
1
- // The hook endpoint without Next: verify, parse, expire tags, answer. `revalidate.ts` wires it to next/cache,
2
- // next/server and the app's config; tests drive it directly with plain Request objects.
3
- import { FoliwakeHookError, HOOK_BODY_LIMIT, isFoliwakePagePath, parseFoliwakeHook, verifyFoliwakeSignature, } from '@foliwake/server/hook';
4
- /** Replaced by the package's version when it is built (tools/build.mjs). */
5
- const SDK = '@foliwake/next/0.9.0';
6
- /** At most this many pages are read again right after a delivery (`warm`); never on `all`. */
7
- export const WARM_LIMIT = 20;
8
- class TooLarge extends Error {
9
- }
10
- function answer(status, body) {
11
- return Response.json(body, { status, headers: { 'Cache-Control': 'no-store' } });
12
- }
13
- function refuse(status, error) {
14
- return answer(status, { ok: false, error });
15
- }
16
- function declaredTooLarge(request) {
17
- const length = Number(request.headers.get('content-length') ?? '0');
18
- return Number.isFinite(length) && length > HOOK_BODY_LIMIT;
19
- }
20
- function joined(chunks, total) {
21
- const out = new Uint8Array(total);
22
- let at = 0;
23
- for (const chunk of chunks) {
24
- out.set(chunk, at);
25
- at += chunk.byteLength;
26
- }
27
- return out;
28
- }
29
- /** The body, cut at HOOK_BODY_LIMIT whatever Content-Length says. */
30
- async function readBody(request) {
31
- if (declaredTooLarge(request))
32
- throw new TooLarge();
33
- if (!request.body)
34
- return new Uint8Array();
35
- const reader = request.body.getReader();
36
- const chunks = [];
37
- let total = 0;
38
- for (let read = await reader.read(); !read.done; read = await reader.read()) {
39
- total += read.value.byteLength;
40
- if (total > HOOK_BODY_LIMIT) {
41
- await reader.cancel().catch(() => { });
42
- throw new TooLarge();
43
- }
44
- chunks.push(read.value);
45
- }
46
- return joined(chunks, total);
47
- }
48
- /** The tags a delivery expires: the site's live tag on `all`, else one tag per listed path. */
49
- export function deliveryTags(payload, liveTag) {
50
- if (payload.all)
51
- return [liveTag()];
52
- return (payload.pages ?? []).map((path) => liveTag(path));
53
- }
54
- /** The pages read again after a delivery: none on `all`, page paths only, at most WARM_LIMIT. */
55
- export function warmPaths(payload) {
56
- if (payload.all)
57
- return [];
58
- return (payload.pages ?? []).filter(isFoliwakePagePath).slice(0, WARM_LIMIT);
59
- }
60
- function scheduleWarm(deps, payload) {
61
- const paths = warmPaths(payload);
62
- if (!deps.warmPages || paths.length === 0)
63
- return;
64
- deps.schedule(async () => {
65
- const results = await Promise.allSettled(paths.map((path) => deps.warm(path)));
66
- const failed = results.filter((r) => r.status === 'rejected').length;
67
- if (failed > 0)
68
- deps.log.warn(`[foliwake] hook: ${failed} of ${paths.length} pages were not read again`);
69
- });
70
- }
71
- async function deliver(deps, payload) {
72
- const tags = deliveryTags(payload, deps.liveTag);
73
- for (const tag of tags)
74
- deps.expire(tag);
75
- try {
76
- await deps.onDelivery?.(payload);
77
- }
78
- catch (error) {
79
- deps.log.error('[foliwake] hook: onDelivery failed; the server will send the delivery again', error);
80
- return refuse(500, 'on_delivery_failed');
81
- }
82
- scheduleWarm(deps, payload);
83
- return answer(200, { ok: true, revalidated: tags });
84
- }
85
- function verified(deps, body, request) {
86
- const check = verifyFoliwakeSignature(body, request.headers.get('foliwake-signature'), deps.secrets(), {
87
- now: deps.now?.(),
88
- toleranceS: deps.toleranceS,
89
- });
90
- if (check.ok)
91
- return null;
92
- if (check.reason !== 'no_secret')
93
- return refuse(401, `signature_${check.reason}`);
94
- deps.log.error('[foliwake] hook: no secret is set; every delivery is refused');
95
- return refuse(500, 'no_secret');
96
- }
97
- function payloadOf(body) {
98
- try {
99
- return parseFoliwakeHook(body);
100
- }
101
- catch (error) {
102
- if (error instanceof FoliwakeHookError)
103
- return refuse(400, error.message);
104
- throw error;
105
- }
106
- }
107
- function eventMismatch(request, payload) {
108
- const event = request.headers.get('foliwake-event');
109
- return event !== null && event !== payload.event;
110
- }
111
- async function handle(deps, request) {
112
- if (request.method !== 'POST')
113
- return refuse(405, 'method_not_allowed');
114
- const body = await readBody(request);
115
- const refused = verified(deps, body, request);
116
- if (refused)
117
- return refused;
118
- const payload = payloadOf(body);
119
- if (payload instanceof Response)
120
- return payload;
121
- if (eventMismatch(request, payload))
122
- return refuse(400, 'Foliwake-Event does not match the body');
123
- if (payload.site !== deps.site)
124
- return refuse(400, `this app serves the site ${deps.site}`);
125
- if (payload.event === 'ping')
126
- return answer(200, { ok: true, site: deps.site, sdk: SDK });
127
- return deliver(deps, payload);
128
- }
129
- /**
130
- * The hook endpoint as a function of a Request: 413 over 64 KiB, 401 on a bad or expired signature, 400 on a
131
- * body that is not a payload or names another site, 200 otherwise.
132
- */
133
- export function createRevalidateHandler(deps) {
134
- return async (request) => {
135
- try {
136
- return await handle(deps, request);
137
- }
138
- catch (error) {
139
- if (error instanceof TooLarge)
140
- return refuse(413, 'body_too_large');
141
- throw error;
142
- }
143
- };
144
- }