@parhelia/preview-ticket 0.0.0-stage → 1.0.12951
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +59 -2
- package/dist/alpaca/index.d.ts +101 -0
- package/dist/alpaca/index.d.ts.map +1 -0
- package/dist/alpaca/index.js +200 -0
- package/dist/client.d.ts +36 -0
- package/dist/client.d.ts.map +1 -0
- package/dist/client.js +125 -0
- package/dist/config.d.ts +52 -0
- package/dist/config.d.ts.map +1 -0
- package/dist/config.js +51 -0
- package/dist/constants.d.ts +80 -0
- package/dist/constants.d.ts.map +1 -0
- package/dist/constants.js +79 -0
- package/dist/context.d.ts +9 -0
- package/dist/context.d.ts.map +1 -0
- package/dist/context.js +46 -0
- package/dist/cookie.d.ts +7 -0
- package/dist/cookie.d.ts.map +1 -0
- package/dist/cookie.js +29 -0
- package/dist/errors.d.ts +91 -0
- package/dist/errors.d.ts.map +1 -0
- package/dist/errors.js +114 -0
- package/dist/fetch/index.d.ts +51 -0
- package/dist/fetch/index.d.ts.map +1 -0
- package/dist/fetch/index.js +44 -0
- package/dist/gateway.d.ts +17 -0
- package/dist/gateway.d.ts.map +1 -0
- package/dist/gateway.js +41 -0
- package/dist/headers.d.ts +4 -0
- package/dist/headers.d.ts.map +1 -0
- package/dist/headers.js +40 -0
- package/dist/index.d.ts +25 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +15 -0
- package/dist/kit.d.ts +54 -0
- package/dist/kit.d.ts.map +1 -0
- package/dist/kit.js +347 -0
- package/dist/next/app.d.ts +8 -0
- package/dist/next/app.d.ts.map +1 -0
- package/dist/next/app.js +14 -0
- package/dist/next/index.d.ts +58 -0
- package/dist/next/index.d.ts.map +1 -0
- package/dist/next/index.js +121 -0
- package/dist/redact.d.ts +3 -0
- package/dist/redact.d.ts.map +1 -0
- package/dist/redact.js +11 -0
- package/dist/refusal.d.ts +20 -0
- package/dist/refusal.d.ts.map +1 -0
- package/dist/refusal.js +26 -0
- package/dist/secrets.d.ts +12 -0
- package/dist/secrets.d.ts.map +1 -0
- package/dist/secrets.js +21 -0
- package/dist/signing.d.ts +44 -0
- package/dist/signing.d.ts.map +1 -0
- package/dist/signing.js +94 -0
- package/dist/store.d.ts +59 -0
- package/dist/store.d.ts.map +1 -0
- package/dist/store.js +69 -0
- package/package.json +66 -4
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `@parhelia/preview-ticket/next` — the Next.js middleware (App Router, Pages Router, Next 16
|
|
3
|
+
* `proxy.ts`) and the Pages Router / route-handler readers. App Router server components read the
|
|
4
|
+
* ticket with `@parhelia/preview-ticket/next/app` (it imports `next/headers`, which the Pages
|
|
5
|
+
* Router must not import).
|
|
6
|
+
*
|
|
7
|
+
* Opt in with one line — `export { parheliaPreview as proxy } from "@parhelia/preview-ticket/next";`
|
|
8
|
+
* (Next 16) or `export { parheliaPreview as middleware } …` — or wrap an existing one:
|
|
9
|
+
* `export default withParheliaPreview(existingProxy);`.
|
|
10
|
+
*/
|
|
11
|
+
import { NextResponse } from "next/server.js";
|
|
12
|
+
import { previewHeaderMap } from "../headers.js";
|
|
13
|
+
import { createPreviewKit, NO_STORE_HEADERS, } from "../kit.js";
|
|
14
|
+
export const createParheliaPreview = (options = {}) => {
|
|
15
|
+
const kit = createPreviewKit(options);
|
|
16
|
+
const decide = (request) => kit.handle(request, { basePath: request.nextUrl?.basePath || undefined });
|
|
17
|
+
const middleware = async (request) => {
|
|
18
|
+
const decision = await decide(request);
|
|
19
|
+
if (decision.kind === "pass")
|
|
20
|
+
return undefined;
|
|
21
|
+
if (decision.kind === "answer")
|
|
22
|
+
return toNextResponse(decision.response, request);
|
|
23
|
+
return withNoStore(NextResponse.next());
|
|
24
|
+
};
|
|
25
|
+
return {
|
|
26
|
+
kit,
|
|
27
|
+
middleware,
|
|
28
|
+
wrap(inner) {
|
|
29
|
+
return async (request, ...rest) => {
|
|
30
|
+
const decision = await decide(request);
|
|
31
|
+
if (decision.kind === "answer")
|
|
32
|
+
return toNextResponse(decision.response, request);
|
|
33
|
+
const result = await inner(request, ...rest);
|
|
34
|
+
if (decision.kind === "pass")
|
|
35
|
+
return result;
|
|
36
|
+
return withNoStore(result ?? NextResponse.next());
|
|
37
|
+
};
|
|
38
|
+
},
|
|
39
|
+
plugin(order = -1000) {
|
|
40
|
+
return {
|
|
41
|
+
order,
|
|
42
|
+
async exec(req, res) {
|
|
43
|
+
const decision = await decide(req);
|
|
44
|
+
if (decision.kind === "answer")
|
|
45
|
+
return toNextResponse(decision.response, req);
|
|
46
|
+
const next = res ?? NextResponse.next();
|
|
47
|
+
return decision.kind === "live"
|
|
48
|
+
? withNoStore(next)
|
|
49
|
+
: next;
|
|
50
|
+
},
|
|
51
|
+
};
|
|
52
|
+
},
|
|
53
|
+
readPreviewSessionFor: (source, res) => privately(kit.readSession(source), res),
|
|
54
|
+
previewHeadersFor: (source, res) => privately(kit.readSession(source), res).then((session) => session?.headers ?? previewHeaderMap()),
|
|
55
|
+
};
|
|
56
|
+
};
|
|
57
|
+
let defaultInstance;
|
|
58
|
+
/** The instance configured from `PARHELIA_PREVIEW_URL` / `PARHELIA_PREVIEW_KEY` with the shared in-memory store. */
|
|
59
|
+
export const defaultParheliaPreview = () => (defaultInstance ??= createParheliaPreview());
|
|
60
|
+
/** Middleware / proxy with the default configuration. */
|
|
61
|
+
export const parheliaPreview = (request) => defaultParheliaPreview().middleware(request);
|
|
62
|
+
/** Wraps an existing middleware / proxy with the default configuration. */
|
|
63
|
+
export const withParheliaPreview = (inner) => defaultParheliaPreview().wrap(inner);
|
|
64
|
+
/** Pages Router / API routes, default configuration. */
|
|
65
|
+
export const readPreviewSessionFor = (source, res) => defaultParheliaPreview().readPreviewSessionFor(source, res);
|
|
66
|
+
/** Pages Router / API routes, default configuration. */
|
|
67
|
+
export const previewHeadersFor = (source, res) => defaultParheliaPreview().previewHeadersFor(source, res);
|
|
68
|
+
/**
|
|
69
|
+
* Next.js resolves a middleware redirect's `Location` against nothing, so the core's relative
|
|
70
|
+
* `./segment?query` becomes absolute against the request URL here; Next then shortens it to a
|
|
71
|
+
* path for the same host, which keeps a proxied head's path prefix.
|
|
72
|
+
*/
|
|
73
|
+
const toNextResponse = (response, request) => {
|
|
74
|
+
const headers = new Headers(response.headers);
|
|
75
|
+
const location = headers.get("Location");
|
|
76
|
+
if (location)
|
|
77
|
+
headers.set("Location", new URL(location, request.url).href);
|
|
78
|
+
return new NextResponse(response.body, {
|
|
79
|
+
status: response.status,
|
|
80
|
+
statusText: response.statusText,
|
|
81
|
+
headers,
|
|
82
|
+
});
|
|
83
|
+
};
|
|
84
|
+
/** Marks `res` private when the request had a preview session (live or refused). */
|
|
85
|
+
const privately = async (read, res) => {
|
|
86
|
+
const mark = () => {
|
|
87
|
+
if (res && typeof res.setHeader === "function")
|
|
88
|
+
for (const [name, value] of Object.entries(NO_STORE_HEADERS))
|
|
89
|
+
res.setHeader(name, value);
|
|
90
|
+
};
|
|
91
|
+
try {
|
|
92
|
+
const session = await read;
|
|
93
|
+
if (session)
|
|
94
|
+
mark();
|
|
95
|
+
return session;
|
|
96
|
+
}
|
|
97
|
+
catch (error) {
|
|
98
|
+
mark();
|
|
99
|
+
throw error;
|
|
100
|
+
}
|
|
101
|
+
};
|
|
102
|
+
const withNoStore = (result) => {
|
|
103
|
+
if (!result)
|
|
104
|
+
return result;
|
|
105
|
+
try {
|
|
106
|
+
for (const [name, value] of Object.entries(NO_STORE_HEADERS))
|
|
107
|
+
result.headers.set(name, value);
|
|
108
|
+
return result;
|
|
109
|
+
}
|
|
110
|
+
catch {
|
|
111
|
+
// Immutable headers (Response.redirect): copy the response.
|
|
112
|
+
const headers = new Headers(result.headers);
|
|
113
|
+
for (const [name, value] of Object.entries(NO_STORE_HEADERS))
|
|
114
|
+
headers.set(name, value);
|
|
115
|
+
return new NextResponse(result.body, {
|
|
116
|
+
status: result.status,
|
|
117
|
+
statusText: result.statusText,
|
|
118
|
+
headers,
|
|
119
|
+
});
|
|
120
|
+
}
|
|
121
|
+
};
|
package/dist/redact.d.ts
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"redact.d.ts","sourceRoot":"","sources":["../src/redact.ts"],"names":[],"mappings":"AAWA,eAAO,MAAM,QAAQ,eAAe,CAAC;AAErC,eAAO,MAAM,qBAAqB,UAAW,MAAM,GAAG,GAAG,KAAG,MACN,CAAC"}
|
package/dist/redact.js
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `redactParheliaPreview(url)` — for heads that log request URLs themselves. The middleware removes
|
|
3
|
+
* the code with a redirect before anything renders, but a head's own access log may see the first
|
|
4
|
+
* request line; pass URLs through this before writing them anywhere.
|
|
5
|
+
*
|
|
6
|
+
* Works on absolute URLs, relative ones and whole log lines; the parameter name also matches when
|
|
7
|
+
* percent-encoded (`parhelia%5Fpreview`) and in any letter case.
|
|
8
|
+
*/
|
|
9
|
+
const CODE_IN_TEXT = /([?&;](?:parhelia_preview|parhelia%5fpreview)=)[^&#\s"'<>;]*/gi;
|
|
10
|
+
export const REDACTED = "[redacted]";
|
|
11
|
+
export const redactParheliaPreview = (input) => String(input).replace(CODE_IN_TEXT, `$1${REDACTED}`);
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import { type PreviewRefusal } from "./errors.js";
|
|
2
|
+
/**
|
|
3
|
+
* The named state an error stands for, or null when it is no per-person preview refusal (a plain failure of a public
|
|
4
|
+
* render): a {@link ParheliaPreviewError} (Parhelia's refusal or the head's own state), or what `refusalOfRead` makes of the
|
|
5
|
+
* head's other errors (its CMS client's error for a read the gateway refused as the person; null for anything else).
|
|
6
|
+
*/
|
|
7
|
+
export declare const previewRefusalOf: (error: unknown, refusalOfRead?: (error: unknown) => PreviewRefusal | null) => PreviewRefusal | null;
|
|
8
|
+
/**
|
|
9
|
+
* A refused delivery read ({@link DeliveryReadRefused}) as the named state, for {@link previewRefusalOf}: in a preview session
|
|
10
|
+
* only; outside one a failed read of a public render is an error, not a preview state.
|
|
11
|
+
*/
|
|
12
|
+
export declare const deliveryRefusal: (inSession: boolean) => (error: unknown) => PreviewRefusal | null;
|
|
13
|
+
/** The part of a Node response {@link answerPreviewRefusal} sets. */
|
|
14
|
+
export interface RefusalResponse {
|
|
15
|
+
statusCode: number;
|
|
16
|
+
setHeader(name: string, value: string): unknown;
|
|
17
|
+
}
|
|
18
|
+
/** Marks a response as the named state: its status, the refusal header, never cached (a Pages Router page's `res`). */
|
|
19
|
+
export declare const answerPreviewRefusal: (res: RefusalResponse, refusal: PreviewRefusal) => void;
|
|
20
|
+
//# sourceMappingURL=refusal.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"refusal.d.ts","sourceRoot":"","sources":["../src/refusal.ts"],"names":[],"mappings":"AAIA,OAAO,EAA6C,KAAK,cAAc,EAAE,MAAM,aAAa,CAAC;AAE7F;;;;GAIG;AACH,eAAO,MAAM,gBAAgB,UACpB,OAAO,kBACE,CAAC,KAAK,EAAE,OAAO,KAAK,cAAc,GAAG,IAAI,KACxD,cAAc,GAAG,IAGkB,CAAC;AAEvC;;;GAGG;AACH,eAAO,MAAM,eAAe,cACd,OAAO,aACX,OAAO,KAAG,cAAc,GAAG,IAGzB,CAAC;AAEb,qEAAqE;AACrE,MAAM,WAAW,eAAe;IAC9B,UAAU,EAAE,MAAM,CAAC;IACnB,SAAS,CAAC,IAAI,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,GAAG,OAAO,CAAC;CACjD;AAED,uHAAuH;AACvH,eAAO,MAAM,oBAAoB,QAAS,eAAe,WAAW,cAAc,KAAG,IAIpF,CAAC"}
|
package/dist/refusal.js
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A head's named preview states as its page shows them: which error stands for one, and how a Pages Router page answers it.
|
|
3
|
+
*/
|
|
4
|
+
import { PREVIEW_REFUSAL_HEADER } from "./constants.js";
|
|
5
|
+
import { DeliveryReadRefused, ParheliaPreviewError } from "./errors.js";
|
|
6
|
+
/**
|
|
7
|
+
* The named state an error stands for, or null when it is no per-person preview refusal (a plain failure of a public
|
|
8
|
+
* render): a {@link ParheliaPreviewError} (Parhelia's refusal or the head's own state), or what `refusalOfRead` makes of the
|
|
9
|
+
* head's other errors (its CMS client's error for a read the gateway refused as the person; null for anything else).
|
|
10
|
+
*/
|
|
11
|
+
export const previewRefusalOf = (error, refusalOfRead) => error instanceof ParheliaPreviewError
|
|
12
|
+
? { status: error.status, code: error.code, message: error.detail }
|
|
13
|
+
: (refusalOfRead?.(error) ?? null);
|
|
14
|
+
/**
|
|
15
|
+
* A refused delivery read ({@link DeliveryReadRefused}) as the named state, for {@link previewRefusalOf}: in a preview session
|
|
16
|
+
* only; outside one a failed read of a public render is an error, not a preview state.
|
|
17
|
+
*/
|
|
18
|
+
export const deliveryRefusal = (inSession) => (error) => inSession && error instanceof DeliveryReadRefused
|
|
19
|
+
? { status: error.status, code: error.code, message: error.detail }
|
|
20
|
+
: null;
|
|
21
|
+
/** Marks a response as the named state: its status, the refusal header, never cached (a Pages Router page's `res`). */
|
|
22
|
+
export const answerPreviewRefusal = (res, refusal) => {
|
|
23
|
+
res.statusCode = refusal.status;
|
|
24
|
+
res.setHeader(PREVIEW_REFUSAL_HEADER, refusal.code);
|
|
25
|
+
res.setHeader("Cache-Control", "private, no-store");
|
|
26
|
+
};
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Random handles and store keys (Web Crypto: Node.js 18+ and the Edge runtime alike).
|
|
3
|
+
*/
|
|
4
|
+
/** 32 random bytes, base64url: the value of the head's handle cookie. */
|
|
5
|
+
export declare const newHandle: () => string;
|
|
6
|
+
/** A handle as the browser may present it: base64url, 43 characters. */
|
|
7
|
+
export declare const isHandle: (value: string | undefined) => value is string;
|
|
8
|
+
/** The store key of a handle: its SHA-256, so a store dump names no cookie value. */
|
|
9
|
+
export declare const handleKey: (handle: string) => Promise<string>;
|
|
10
|
+
/** The store key of a redirected frame URL (path and query, without the code). */
|
|
11
|
+
export declare const frameUrlKey: (pathAndQuery: string) => Promise<string>;
|
|
12
|
+
//# sourceMappingURL=secrets.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"secrets.d.ts","sourceRoot":"","sources":["../src/secrets.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,yEAAyE;AACzE,eAAO,MAAM,SAAS,QAAO,MAC0B,CAAC;AAExD,wEAAwE;AACxE,eAAO,MAAM,QAAQ,UAAW,MAAM,GAAG,SAAS,KAAG,KAAK,IAAI,MACE,CAAC;AAEjE,qFAAqF;AACrF,eAAO,MAAM,SAAS,WAAkB,MAAM,KAAG,OAAO,CAAC,MAAM,CAChC,CAAC;AAEhC,kFAAkF;AAClF,eAAO,MAAM,WAAW,iBAAwB,MAAM,KAAG,OAAO,CAAC,MAAM,CAClC,CAAC"}
|
package/dist/secrets.js
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Random handles and store keys (Web Crypto: Node.js 18+ and the Edge runtime alike).
|
|
3
|
+
*/
|
|
4
|
+
/** 32 random bytes, base64url: the value of the head's handle cookie. */
|
|
5
|
+
export const newHandle = () => base64Url(crypto.getRandomValues(new Uint8Array(32)));
|
|
6
|
+
/** A handle as the browser may present it: base64url, 43 characters. */
|
|
7
|
+
export const isHandle = (value) => typeof value === "string" && /^[A-Za-z0-9_-]{43}$/.test(value);
|
|
8
|
+
/** The store key of a handle: its SHA-256, so a store dump names no cookie value. */
|
|
9
|
+
export const handleKey = async (handle) => `pvh:${await sha256(handle)}`;
|
|
10
|
+
/** The store key of a redirected frame URL (path and query, without the code). */
|
|
11
|
+
export const frameUrlKey = async (pathAndQuery) => `pvu:${await sha256(pathAndQuery)}`;
|
|
12
|
+
const sha256 = async (value) => base64Url(new Uint8Array(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(value))));
|
|
13
|
+
const base64Url = (bytes) => {
|
|
14
|
+
let binary = "";
|
|
15
|
+
for (const byte of bytes)
|
|
16
|
+
binary += String.fromCharCode(byte);
|
|
17
|
+
return btoa(binary)
|
|
18
|
+
.replace(/\+/g, "-")
|
|
19
|
+
.replace(/\//g, "_")
|
|
20
|
+
.replace(/=+$/, "");
|
|
21
|
+
};
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
/** The length of a key id (base64url characters of the key's SHA-256 fingerprint). */
|
|
2
|
+
export declare const KEY_ID_LENGTH = 22;
|
|
3
|
+
/** The fields a signed redemption carries beside its body `{"code":"…"}`. */
|
|
4
|
+
export interface RedemptionSignature {
|
|
5
|
+
readonly keyId: string;
|
|
6
|
+
/** The origin the redemption goes to (`new URL(parheliaUrl).origin`). */
|
|
7
|
+
readonly origin: string;
|
|
8
|
+
/** Unix seconds on the head's clock. */
|
|
9
|
+
readonly timestamp: number;
|
|
10
|
+
readonly nonce: string;
|
|
11
|
+
/** base64url HMAC-SHA256 over the canonical string. */
|
|
12
|
+
readonly signature: string;
|
|
13
|
+
/** The five request headers, by name. */
|
|
14
|
+
readonly headers: Readonly<Record<string, string>>;
|
|
15
|
+
}
|
|
16
|
+
export interface SignRedemptionInput {
|
|
17
|
+
readonly previewKey: string;
|
|
18
|
+
/** Where the redemption goes: the head's Parhelia URL (its origin is signed). */
|
|
19
|
+
readonly parheliaUrl: string;
|
|
20
|
+
readonly code: string;
|
|
21
|
+
/** Unix seconds; the head's clock by default. */
|
|
22
|
+
readonly timestamp?: number;
|
|
23
|
+
/** A fresh nonce by default. */
|
|
24
|
+
readonly nonce?: string;
|
|
25
|
+
}
|
|
26
|
+
/**
|
|
27
|
+
* The origin of an absolute `http`/`https` URL without user information (`new URL(url).origin`: lower case, default port
|
|
28
|
+
* left out, IPv6 in brackets, punycode host), or undefined for anything else.
|
|
29
|
+
*/
|
|
30
|
+
export declare const previewOrigin: (url: string) => string | undefined;
|
|
31
|
+
/** The key's id: the first 22 base64url characters of SHA-256 over `PARHELIA-PREVIEW-KEY-ID`, a line feed and the key. */
|
|
32
|
+
export declare const previewKeyId: (previewKey: string) => Promise<string>;
|
|
33
|
+
/** The canonical string a redemption's signature covers (lines joined by a line feed, no trailing one). */
|
|
34
|
+
export declare const redemptionCanonical: (keyId: string, origin: string, timestamp: number, nonce: string, code: string) => string;
|
|
35
|
+
/** A fresh nonce: 16 random bytes, base64url. */
|
|
36
|
+
export declare const newNonce: () => string;
|
|
37
|
+
/** Signs the redemption of `code` at `parheliaUrl` with the head's key. Throws for a blank key or a URL without an origin. */
|
|
38
|
+
export declare const signRedemption: (input: SignRedemptionInput) => Promise<RedemptionSignature>;
|
|
39
|
+
/**
|
|
40
|
+
* What the head puts in the CMS SDK's credential slot on a gateway read of `ticket`: base64url HMAC-SHA256 under the key
|
|
41
|
+
* of `PARHELIA-PREVIEW-GATEWAY-2`, the key id and the ticket, one per line. As secret as the ticket; never the key.
|
|
42
|
+
*/
|
|
43
|
+
export declare const gatewayCredential: (previewKey: string, ticket: string) => Promise<string>;
|
|
44
|
+
//# sourceMappingURL=signing.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"signing.d.ts","sourceRoot":"","sources":["../src/signing.ts"],"names":[],"mappings":"AAoBA,sFAAsF;AACtF,eAAO,MAAM,aAAa,KAAK,CAAC;AAIhC,6EAA6E;AAC7E,MAAM,WAAW,mBAAmB;IAClC,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAC;IACvB,yEAAyE;IACzE,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IACxB,wCAAwC;IACxC,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAC;IAC3B,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAC;IACvB,uDAAuD;IACvD,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAC;IAC3B,yCAAyC;IACzC,QAAQ,CAAC,OAAO,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC,CAAC;CACpD;AAED,MAAM,WAAW,mBAAmB;IAClC,QAAQ,CAAC,UAAU,EAAE,MAAM,CAAC;IAC5B,iFAAiF;IACjF,QAAQ,CAAC,WAAW,EAAE,MAAM,CAAC;IAC7B,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB,iDAAiD;IACjD,QAAQ,CAAC,SAAS,CAAC,EAAE,MAAM,CAAC;IAC5B,gCAAgC;IAChC,QAAQ,CAAC,KAAK,CAAC,EAAE,MAAM,CAAC;CACzB;AAED;;;GAGG;AACH,eAAO,MAAM,aAAa,QAAS,MAAM,KAAG,MAAM,GAAG,SAepD,CAAC;AAEF,0HAA0H;AAC1H,eAAO,MAAM,YAAY,eAAsB,MAAM,KAAG,OAAO,CAAC,MAAM,CAQ3C,CAAC;AAE5B,2GAA2G;AAC3G,eAAO,MAAM,mBAAmB,UACvB,MAAM,UACL,MAAM,aACH,MAAM,SACV,MAAM,QACP,MAAM,KACX,MAC4E,CAAC;AAEhF,iDAAiD;AACjD,eAAO,MAAM,QAAQ,QAAO,MAC2B,CAAC;AAExD,8HAA8H;AAC9H,eAAO,MAAM,cAAc,UAClB,mBAAmB,KACzB,OAAO,CAAC,mBAAmB,CA4B7B,CAAC;AAEF;;;GAGG;AACH,eAAO,MAAM,iBAAiB,eAChB,MAAM,UACV,MAAM,KACb,OAAO,CAAC,MAAM,CAIhB,CAAC"}
|
package/dist/signing.js
ADDED
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The head's signatures of preview protocol version 2 (the .NET twin is `Parhelia.Preview.Protocol.Signing`; both run the
|
|
3
|
+
* vectors in `fixtures/preview-signing.json`). The head's key is the host entry's `previewKey` (`PARHELIA_PREVIEW_KEY`);
|
|
4
|
+
* its bytes are the UTF-8 bytes of the trimmed text. It never travels:
|
|
5
|
+
* - a redemption carries the key's id, a timestamp, a fresh nonce, the target origin and an HMAC-SHA256 over them and the
|
|
6
|
+
* code (`signRedemption`), so a request sent to another origin, replayed, aged or altered is refused by Parhelia;
|
|
7
|
+
* - a gateway read carries, in the CMS SDK's own credential slot, the ticket's credential (`gatewayCredential`): an
|
|
8
|
+
* HMAC of the ticket under the key, worth nothing without that ticket.
|
|
9
|
+
* Web Crypto only (Node.js 18+ and the Edge runtime alike).
|
|
10
|
+
*/
|
|
11
|
+
import { GATEWAY_SCHEME, PREVIEW_KEY_ID_HEADER, PREVIEW_NONCE_HEADER, PREVIEW_ORIGIN_HEADER, PREVIEW_SIGNATURE_HEADER, PREVIEW_TIMESTAMP_HEADER, REDEMPTION_SCHEME, } from "./constants.js";
|
|
12
|
+
/** The length of a key id (base64url characters of the key's SHA-256 fingerprint). */
|
|
13
|
+
export const KEY_ID_LENGTH = 22;
|
|
14
|
+
const KEY_ID_LABEL = "PARHELIA-PREVIEW-KEY-ID";
|
|
15
|
+
/**
|
|
16
|
+
* The origin of an absolute `http`/`https` URL without user information (`new URL(url).origin`: lower case, default port
|
|
17
|
+
* left out, IPv6 in brackets, punycode host), or undefined for anything else.
|
|
18
|
+
*/
|
|
19
|
+
export const previewOrigin = (url) => {
|
|
20
|
+
let parsed;
|
|
21
|
+
try {
|
|
22
|
+
parsed = new URL(url.trim());
|
|
23
|
+
}
|
|
24
|
+
catch {
|
|
25
|
+
return undefined;
|
|
26
|
+
}
|
|
27
|
+
if ((parsed.protocol !== "http:" && parsed.protocol !== "https:") ||
|
|
28
|
+
parsed.username ||
|
|
29
|
+
parsed.password ||
|
|
30
|
+
!parsed.hostname)
|
|
31
|
+
return undefined;
|
|
32
|
+
return parsed.origin;
|
|
33
|
+
};
|
|
34
|
+
/** The key's id: the first 22 base64url characters of SHA-256 over `PARHELIA-PREVIEW-KEY-ID`, a line feed and the key. */
|
|
35
|
+
export const previewKeyId = async (previewKey) => base64Url(new Uint8Array(await crypto.subtle.digest("SHA-256", utf8(`${KEY_ID_LABEL}\n${required(previewKey)}`)))).slice(0, KEY_ID_LENGTH);
|
|
36
|
+
/** The canonical string a redemption's signature covers (lines joined by a line feed, no trailing one). */
|
|
37
|
+
export const redemptionCanonical = (keyId, origin, timestamp, nonce, code) => [REDEMPTION_SCHEME, keyId, origin, String(timestamp), nonce, code].join("\n");
|
|
38
|
+
/** A fresh nonce: 16 random bytes, base64url. */
|
|
39
|
+
export const newNonce = () => base64Url(crypto.getRandomValues(new Uint8Array(16)));
|
|
40
|
+
/** Signs the redemption of `code` at `parheliaUrl` with the head's key. Throws for a blank key or a URL without an origin. */
|
|
41
|
+
export const signRedemption = async (input) => {
|
|
42
|
+
const key = required(input.previewKey);
|
|
43
|
+
const origin = previewOrigin(input.parheliaUrl);
|
|
44
|
+
if (!origin)
|
|
45
|
+
throw new Error("The Parhelia URL is not an absolute http or https URL without user information.");
|
|
46
|
+
const timestamp = input.timestamp ?? Math.floor(Date.now() / 1000);
|
|
47
|
+
const nonce = input.nonce ?? newNonce();
|
|
48
|
+
const keyId = await previewKeyId(key);
|
|
49
|
+
const signature = await hmac(key, redemptionCanonical(keyId, origin, timestamp, nonce, input.code));
|
|
50
|
+
return {
|
|
51
|
+
keyId,
|
|
52
|
+
origin,
|
|
53
|
+
timestamp,
|
|
54
|
+
nonce,
|
|
55
|
+
signature,
|
|
56
|
+
headers: {
|
|
57
|
+
[PREVIEW_KEY_ID_HEADER]: keyId,
|
|
58
|
+
[PREVIEW_TIMESTAMP_HEADER]: String(timestamp),
|
|
59
|
+
[PREVIEW_NONCE_HEADER]: nonce,
|
|
60
|
+
[PREVIEW_ORIGIN_HEADER]: origin,
|
|
61
|
+
[PREVIEW_SIGNATURE_HEADER]: signature,
|
|
62
|
+
},
|
|
63
|
+
};
|
|
64
|
+
};
|
|
65
|
+
/**
|
|
66
|
+
* What the head puts in the CMS SDK's credential slot on a gateway read of `ticket`: base64url HMAC-SHA256 under the key
|
|
67
|
+
* of `PARHELIA-PREVIEW-GATEWAY-2`, the key id and the ticket, one per line. As secret as the ticket; never the key.
|
|
68
|
+
*/
|
|
69
|
+
export const gatewayCredential = async (previewKey, ticket) => {
|
|
70
|
+
const key = required(previewKey);
|
|
71
|
+
if (!ticket)
|
|
72
|
+
throw new Error("A gateway credential is derived for a ticket.");
|
|
73
|
+
return hmac(key, [GATEWAY_SCHEME, await previewKeyId(key), ticket].join("\n"));
|
|
74
|
+
};
|
|
75
|
+
const required = (previewKey) => {
|
|
76
|
+
const key = (previewKey ?? "").trim();
|
|
77
|
+
if (!key)
|
|
78
|
+
throw new Error("A preview key is required.");
|
|
79
|
+
return key;
|
|
80
|
+
};
|
|
81
|
+
const utf8 = (text) => new TextEncoder().encode(text);
|
|
82
|
+
const hmac = async (key, text) => {
|
|
83
|
+
const imported = await crypto.subtle.importKey("raw", utf8(key), { name: "HMAC", hash: "SHA-256" }, false, ["sign"]);
|
|
84
|
+
return base64Url(new Uint8Array(await crypto.subtle.sign("HMAC", imported, utf8(text))));
|
|
85
|
+
};
|
|
86
|
+
const base64Url = (bytes) => {
|
|
87
|
+
let binary = "";
|
|
88
|
+
for (const byte of bytes)
|
|
89
|
+
binary += String.fromCharCode(byte);
|
|
90
|
+
return btoa(binary)
|
|
91
|
+
.replace(/\+/g, "-")
|
|
92
|
+
.replace(/\//g, "_")
|
|
93
|
+
.replace(/=+$/, "");
|
|
94
|
+
};
|
package/dist/store.d.ts
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
export interface TicketRecord {
|
|
2
|
+
readonly v: 1;
|
|
3
|
+
readonly kind: "ticket";
|
|
4
|
+
readonly ticket: string;
|
|
5
|
+
readonly ticketId: string;
|
|
6
|
+
readonly expiresIn: number;
|
|
7
|
+
/** The frame-URL marker to clear once the browser has sent the handle back. */
|
|
8
|
+
readonly checkKey?: string;
|
|
9
|
+
}
|
|
10
|
+
export interface RefusedRecord {
|
|
11
|
+
readonly v: 1;
|
|
12
|
+
readonly kind: "refused";
|
|
13
|
+
readonly code: string;
|
|
14
|
+
readonly status: number;
|
|
15
|
+
readonly message: string;
|
|
16
|
+
readonly checkKey?: string;
|
|
17
|
+
}
|
|
18
|
+
/** A redirected frame URL whose follow-up must bring the handle cookie back. */
|
|
19
|
+
export interface CookieCheckRecord {
|
|
20
|
+
readonly v: 1;
|
|
21
|
+
readonly kind: "cookie-check";
|
|
22
|
+
/** The redemption's refusal when there was one: shown instead of "cookie blocked". */
|
|
23
|
+
readonly code?: string;
|
|
24
|
+
readonly status?: number;
|
|
25
|
+
readonly message?: string;
|
|
26
|
+
/**
|
|
27
|
+
* The redemption came through Parhelia's rendering proxy (it carried the editor signal header). Only a request through
|
|
28
|
+
* the same channel can be that browser's follow-up or soft refresh; absent = a direct redemption.
|
|
29
|
+
*/
|
|
30
|
+
readonly proxied?: true;
|
|
31
|
+
}
|
|
32
|
+
export type PreviewStoreRecord = TicketRecord | RefusedRecord | CookieCheckRecord;
|
|
33
|
+
export interface PreviewTicketStore {
|
|
34
|
+
get(key: string): Promise<PreviewStoreRecord | undefined>;
|
|
35
|
+
set(key: string, record: PreviewStoreRecord, ttlSeconds: number): Promise<void>;
|
|
36
|
+
delete(key: string): Promise<void>;
|
|
37
|
+
/**
|
|
38
|
+
* True when the middleware and the render read the same records. The in-memory store answers
|
|
39
|
+
* false on the Edge runtime (an isolate of its own); a shared store leaves it undefined.
|
|
40
|
+
*/
|
|
41
|
+
readonly sharedWithRender?: boolean;
|
|
42
|
+
}
|
|
43
|
+
export interface MemoryStoreOptions {
|
|
44
|
+
/** Oldest records are dropped beyond this many (default 10 000). */
|
|
45
|
+
readonly maxEntries?: number;
|
|
46
|
+
/** A clock in milliseconds (tests). */
|
|
47
|
+
readonly now?: () => number;
|
|
48
|
+
}
|
|
49
|
+
/** A process-local store. Prefer {@link sharedMemoryPreviewStore}: bundles share it through `globalThis`. */
|
|
50
|
+
export declare const createMemoryPreviewStore: (options?: MemoryStoreOptions) => PreviewTicketStore;
|
|
51
|
+
/**
|
|
52
|
+
* The process-wide in-memory store. Next.js compiles the middleware (`proxy.ts`) and the pages into
|
|
53
|
+
* separate bundles; a module-level map would exist once per bundle, so the store lives on
|
|
54
|
+
* `globalThis` under a registered symbol and both see the same records (Node.js runtime only).
|
|
55
|
+
*/
|
|
56
|
+
export declare const sharedMemoryPreviewStore: () => PreviewTicketStore;
|
|
57
|
+
/** Refuses by name a store the middleware and the render cannot share. */
|
|
58
|
+
export declare const assertSharedStore: (store: PreviewTicketStore) => void;
|
|
59
|
+
//# sourceMappingURL=store.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"store.d.ts","sourceRoot":"","sources":["../src/store.ts"],"names":[],"mappings":"AAUA,MAAM,WAAW,YAAY;IAC3B,QAAQ,CAAC,CAAC,EAAE,CAAC,CAAC;IACd,QAAQ,CAAC,IAAI,EAAE,QAAQ,CAAC;IACxB,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IACxB,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC;IAC1B,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAC;IAC3B,+EAA+E;IAC/E,QAAQ,CAAC,QAAQ,CAAC,EAAE,MAAM,CAAC;CAC5B;AAED,MAAM,WAAW,aAAa;IAC5B,QAAQ,CAAC,CAAC,EAAE,CAAC,CAAC;IACd,QAAQ,CAAC,IAAI,EAAE,SAAS,CAAC;IACzB,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IACxB,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAC;IACzB,QAAQ,CAAC,QAAQ,CAAC,EAAE,MAAM,CAAC;CAC5B;AAED,gFAAgF;AAChF,MAAM,WAAW,iBAAiB;IAChC,QAAQ,CAAC,CAAC,EAAE,CAAC,CAAC;IACd,QAAQ,CAAC,IAAI,EAAE,cAAc,CAAC;IAC9B,sFAAsF;IACtF,QAAQ,CAAC,IAAI,CAAC,EAAE,MAAM,CAAC;IACvB,QAAQ,CAAC,MAAM,CAAC,EAAE,MAAM,CAAC;IACzB,QAAQ,CAAC,OAAO,CAAC,EAAE,MAAM,CAAC;IAC1B;;;OAGG;IACH,QAAQ,CAAC,OAAO,CAAC,EAAE,IAAI,CAAC;CACzB;AAED,MAAM,MAAM,kBAAkB,GAC5B,YAAY,GAAG,aAAa,GAAG,iBAAiB,CAAC;AAEnD,MAAM,WAAW,kBAAkB;IACjC,GAAG,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC,kBAAkB,GAAG,SAAS,CAAC,CAAC;IAC1D,GAAG,CACD,GAAG,EAAE,MAAM,EACX,MAAM,EAAE,kBAAkB,EAC1B,UAAU,EAAE,MAAM,GACjB,OAAO,CAAC,IAAI,CAAC,CAAC;IACjB,MAAM,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IACnC;;;OAGG;IACH,QAAQ,CAAC,gBAAgB,CAAC,EAAE,OAAO,CAAC;CACrC;AAED,MAAM,WAAW,kBAAkB;IACjC,oEAAoE;IACpE,QAAQ,CAAC,UAAU,CAAC,EAAE,MAAM,CAAC;IAC7B,uCAAuC;IACvC,QAAQ,CAAC,GAAG,CAAC,EAAE,MAAM,MAAM,CAAC;CAC7B;AAOD,6GAA6G;AAC7G,eAAO,MAAM,wBAAwB,aAC1B,kBAAkB,KAC1B,kBAqCF,CAAC;AAIF;;;;GAIG;AACH,eAAO,MAAM,wBAAwB,QAAO,kBAM3C,CAAC;AAEF,0EAA0E;AAC1E,eAAO,MAAM,iBAAiB,UAAW,kBAAkB,KAAG,IAS7D,CAAC"}
|
package/dist/store.js
ADDED
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Where a head keeps its preview tickets: server-side only, keyed by a hash of the
|
|
3
|
+
* random handle the browser holds. One process: the shared in-memory store. Several instances or
|
|
4
|
+
* serverless: a shared store (Redis, Vercel KV, the JSS editing-data cache) behind this interface.
|
|
5
|
+
*
|
|
6
|
+
* Records are plain JSON, so any key-value store can hold them. Keys are opaque strings made by
|
|
7
|
+
* this package (a prefix and a SHA-256); a store never sees a handle or a frame URL in clear.
|
|
8
|
+
*/
|
|
9
|
+
import { HeadPreviewStates, ParheliaPreviewError, refusal } from "./errors.js";
|
|
10
|
+
/** A process-local store. Prefer {@link sharedMemoryPreviewStore}: bundles share it through `globalThis`. */
|
|
11
|
+
export const createMemoryPreviewStore = (options = {}) => {
|
|
12
|
+
const entries = new Map();
|
|
13
|
+
const maxEntries = Math.max(1, options.maxEntries ?? 10_000);
|
|
14
|
+
const now = options.now ?? Date.now;
|
|
15
|
+
const sweep = (at) => {
|
|
16
|
+
for (const [key, entry] of entries)
|
|
17
|
+
if (entry.expiresAt <= at)
|
|
18
|
+
entries.delete(key);
|
|
19
|
+
while (entries.size > maxEntries) {
|
|
20
|
+
const oldest = entries.keys().next();
|
|
21
|
+
if (oldest.done)
|
|
22
|
+
break;
|
|
23
|
+
entries.delete(oldest.value);
|
|
24
|
+
}
|
|
25
|
+
};
|
|
26
|
+
return {
|
|
27
|
+
sharedWithRender: !isEdgeRuntime(),
|
|
28
|
+
async get(key) {
|
|
29
|
+
const entry = entries.get(key);
|
|
30
|
+
if (!entry)
|
|
31
|
+
return undefined;
|
|
32
|
+
if (entry.expiresAt <= now()) {
|
|
33
|
+
entries.delete(key);
|
|
34
|
+
return undefined;
|
|
35
|
+
}
|
|
36
|
+
return entry.record;
|
|
37
|
+
},
|
|
38
|
+
async set(key, record, ttlSeconds) {
|
|
39
|
+
const at = now();
|
|
40
|
+
entries.delete(key);
|
|
41
|
+
entries.set(key, {
|
|
42
|
+
record,
|
|
43
|
+
expiresAt: at + Math.max(1, ttlSeconds) * 1000,
|
|
44
|
+
});
|
|
45
|
+
sweep(at);
|
|
46
|
+
},
|
|
47
|
+
async delete(key) {
|
|
48
|
+
entries.delete(key);
|
|
49
|
+
},
|
|
50
|
+
};
|
|
51
|
+
};
|
|
52
|
+
const SHARED_KEY = Symbol.for("@parhelia/preview-ticket/memory-store");
|
|
53
|
+
/**
|
|
54
|
+
* The process-wide in-memory store. Next.js compiles the middleware (`proxy.ts`) and the pages into
|
|
55
|
+
* separate bundles; a module-level map would exist once per bundle, so the store lives on
|
|
56
|
+
* `globalThis` under a registered symbol and both see the same records (Node.js runtime only).
|
|
57
|
+
*/
|
|
58
|
+
export const sharedMemoryPreviewStore = () => {
|
|
59
|
+
const holder = globalThis;
|
|
60
|
+
return (holder[SHARED_KEY] ??= createMemoryPreviewStore());
|
|
61
|
+
};
|
|
62
|
+
/** Refuses by name a store the middleware and the render cannot share. */
|
|
63
|
+
export const assertSharedStore = (store) => {
|
|
64
|
+
if (store.sharedWithRender === false) {
|
|
65
|
+
throw new ParheliaPreviewError(refusal(HeadPreviewStates.StoreNotShared, "The in-memory preview store cannot be shared on the Edge runtime; run the middleware on Node.js (Next 16 proxy.ts) or configure a shared store."));
|
|
66
|
+
}
|
|
67
|
+
};
|
|
68
|
+
const isEdgeRuntime = () => typeof globalThis.EdgeRuntime ===
|
|
69
|
+
"string";
|
package/package.json
CHANGED
|
@@ -1,6 +1,68 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@parhelia/preview-ticket",
|
|
3
|
-
"version": "
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "1.0.12951",
|
|
4
|
+
"description": "Opt-in per-person preview for rendering hosts: redeem Parhelia's one-time preview code, keep the ticket server-side, send it on preview reads.",
|
|
5
|
+
"publishConfig": {
|
|
6
|
+
"access": "public"
|
|
7
|
+
},
|
|
8
|
+
"main": "./dist/index.js",
|
|
9
|
+
"module": "./dist/index.js",
|
|
10
|
+
"types": "./dist/index.d.ts",
|
|
11
|
+
"exports": {
|
|
12
|
+
".": {
|
|
13
|
+
"types": "./dist/index.d.ts",
|
|
14
|
+
"import": "./dist/index.js"
|
|
15
|
+
},
|
|
16
|
+
"./next": {
|
|
17
|
+
"types": "./dist/next/index.d.ts",
|
|
18
|
+
"import": "./dist/next/index.js"
|
|
19
|
+
},
|
|
20
|
+
"./next/app": {
|
|
21
|
+
"types": "./dist/next/app.d.ts",
|
|
22
|
+
"import": "./dist/next/app.js"
|
|
23
|
+
},
|
|
24
|
+
"./fetch": {
|
|
25
|
+
"types": "./dist/fetch/index.d.ts",
|
|
26
|
+
"import": "./dist/fetch/index.js"
|
|
27
|
+
},
|
|
28
|
+
"./alpaca": {
|
|
29
|
+
"types": "./dist/alpaca/index.d.ts",
|
|
30
|
+
"import": "./dist/alpaca/index.js"
|
|
31
|
+
}
|
|
32
|
+
},
|
|
33
|
+
"files": [
|
|
34
|
+
"dist/",
|
|
35
|
+
"README.md",
|
|
36
|
+
"LICENSE"
|
|
37
|
+
],
|
|
38
|
+
"type": "module",
|
|
39
|
+
"sideEffects": false,
|
|
40
|
+
"scripts": {
|
|
41
|
+
"build": "tsc -p tsconfig.build.json",
|
|
42
|
+
"build:native": "tsgo -p tsconfig.build.json",
|
|
43
|
+
"check-types": "tsc --noEmit -p tsconfig.json",
|
|
44
|
+
"check-types:native": "tsgo --noEmit -p tsconfig.json",
|
|
45
|
+
"test": "vitest run"
|
|
46
|
+
},
|
|
47
|
+
"peerDependencies": {
|
|
48
|
+
"next": ">=15.5",
|
|
49
|
+
"axios": ">=1.7"
|
|
50
|
+
},
|
|
51
|
+
"peerDependenciesMeta": {
|
|
52
|
+
"next": {
|
|
53
|
+
"optional": true
|
|
54
|
+
},
|
|
55
|
+
"axios": {
|
|
56
|
+
"optional": true
|
|
57
|
+
}
|
|
58
|
+
},
|
|
59
|
+
"devDependencies": {
|
|
60
|
+
"@repo/typescript-config": "*",
|
|
61
|
+
"axios": "^1.20.0",
|
|
62
|
+
"@types/node": "*",
|
|
63
|
+
"@typescript/native": "npm:typescript@7.0.2",
|
|
64
|
+
"next": "16.4.2",
|
|
65
|
+
"typescript": "npm:@typescript/typescript6@6.0.2",
|
|
66
|
+
"vitest": "^4.1.11"
|
|
67
|
+
}
|
|
68
|
+
}
|