@parhelia/preview-ticket 0.0.0-stage → 1.0.13030

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.
Files changed (59) hide show
  1. package/README.md +59 -2
  2. package/dist/alpaca/index.d.ts +101 -0
  3. package/dist/alpaca/index.d.ts.map +1 -0
  4. package/dist/alpaca/index.js +200 -0
  5. package/dist/client.d.ts +36 -0
  6. package/dist/client.d.ts.map +1 -0
  7. package/dist/client.js +125 -0
  8. package/dist/config.d.ts +52 -0
  9. package/dist/config.d.ts.map +1 -0
  10. package/dist/config.js +51 -0
  11. package/dist/constants.d.ts +80 -0
  12. package/dist/constants.d.ts.map +1 -0
  13. package/dist/constants.js +79 -0
  14. package/dist/context.d.ts +9 -0
  15. package/dist/context.d.ts.map +1 -0
  16. package/dist/context.js +46 -0
  17. package/dist/cookie.d.ts +7 -0
  18. package/dist/cookie.d.ts.map +1 -0
  19. package/dist/cookie.js +29 -0
  20. package/dist/errors.d.ts +91 -0
  21. package/dist/errors.d.ts.map +1 -0
  22. package/dist/errors.js +114 -0
  23. package/dist/fetch/index.d.ts +51 -0
  24. package/dist/fetch/index.d.ts.map +1 -0
  25. package/dist/fetch/index.js +44 -0
  26. package/dist/gateway.d.ts +17 -0
  27. package/dist/gateway.d.ts.map +1 -0
  28. package/dist/gateway.js +41 -0
  29. package/dist/headers.d.ts +4 -0
  30. package/dist/headers.d.ts.map +1 -0
  31. package/dist/headers.js +40 -0
  32. package/dist/index.d.ts +25 -0
  33. package/dist/index.d.ts.map +1 -0
  34. package/dist/index.js +15 -0
  35. package/dist/kit.d.ts +54 -0
  36. package/dist/kit.d.ts.map +1 -0
  37. package/dist/kit.js +347 -0
  38. package/dist/next/app.d.ts +8 -0
  39. package/dist/next/app.d.ts.map +1 -0
  40. package/dist/next/app.js +14 -0
  41. package/dist/next/index.d.ts +58 -0
  42. package/dist/next/index.d.ts.map +1 -0
  43. package/dist/next/index.js +121 -0
  44. package/dist/redact.d.ts +3 -0
  45. package/dist/redact.d.ts.map +1 -0
  46. package/dist/redact.js +11 -0
  47. package/dist/refusal.d.ts +20 -0
  48. package/dist/refusal.d.ts.map +1 -0
  49. package/dist/refusal.js +26 -0
  50. package/dist/secrets.d.ts +12 -0
  51. package/dist/secrets.d.ts.map +1 -0
  52. package/dist/secrets.js +21 -0
  53. package/dist/signing.d.ts +44 -0
  54. package/dist/signing.d.ts.map +1 -0
  55. package/dist/signing.js +94 -0
  56. package/dist/store.d.ts +59 -0
  57. package/dist/store.d.ts.map +1 -0
  58. package/dist/store.js +69 -0
  59. package/package.json +66 -4
package/README.md CHANGED
@@ -1,3 +1,60 @@
1
- # Temporary Holding Version
1
+ # @parhelia/preview-ticket
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Opt-in per-person preview for rendering hosts (heads) framed by the Parhelia editor. The head's server redeems the
4
+ one-time code Parhelia puts on the frame URL, keeps the resulting ticket server-side behind a random `HttpOnly; Secure;
5
+ SameSite=None; Partitioned` handle cookie, removes the code with a `303` before anything renders, and sends the ticket on
6
+ its preview reads to the Parhelia preview gateway. The ticket never reaches the browser.
7
+
8
+ Register the head in Parhelia with per-person preview turned on (Settings › Rendering Hosts): its **Head settings** give
9
+ the head the preview key and the gateway it reads through.
10
+
11
+ ```ts
12
+ // proxy.ts (Next 16) — or `as middleware` in middleware.ts (Next 15.5+, Node.js runtime)
13
+ export { parheliaPreview as proxy } from "@parhelia/preview-ticket/next";
14
+
15
+ // App Router server code
16
+ import { readPreviewSession } from "@parhelia/preview-ticket/next/app";
17
+ const session = await readPreviewSession(); // null without a preview session
18
+ // The ticket's credential (derived from the preview key; never the key itself) goes in the CMS SDK's own credential slot.
19
+ if (session) fetch(gatewayUrl, { headers: { ...session.headers, Authorization: `Bearer ${session.credential}` } });
20
+
21
+ // Pages Router
22
+ import { readPreviewSessionFor } from "@parhelia/preview-ticket/next";
23
+ export const getServerSideProps = async ({ req, res }) => {
24
+ const session = await readPreviewSessionFor(req, res);
25
+ // ...
26
+ };
27
+ ```
28
+
29
+ A code is redeemed only in the editor's frame (the editor-bound redemption rule, `redemptionContextRefusal`): through the
30
+ rendering proxy a same-origin frame, framed directly a cross-site frame whose `Referer` is `PARHELIA_ORIGIN` (or the
31
+ `editorOrigin` option); anything else is refused by name (`preview-frame-required`, `preview-editor-same-site`,
32
+ `preview-editor-origin-required`) without calling Parhelia.
33
+
34
+ Environment: `PARHELIA_PREVIEW_URL` (Parhelia's base URL as the head's server reaches it; `PARHELIA_ORIGIN` when unset), `PARHELIA_PREVIEW_KEY` (the
35
+ host entry's `previewKey`), optionally `PARHELIA_PREVIEW_ALLOW_HTTP=true` for a non-loopback `http:` URL; for the reads,
36
+ `PARHELIA_PREVIEW_STORE` (the store id the gateway serves; `PARHELIA_STORE` when unset). A session's client takes all of them
37
+ from one call:
38
+
39
+ ```ts
40
+ import { previewGatewayFromEnv } from "@parhelia/preview-ticket";
41
+
42
+ const gateway = previewGatewayFromEnv(); // { baseUrl, storeId }; throws the named preview-head-not-configured
43
+ const client = createClient({ baseUrl: gateway.baseUrl, apiKey: session.credential, headers: session.headers });
44
+ ```
45
+
46
+ **The key never travels (preview protocol 2).** The redemption is signed with the key (`signRedemption`: its id, a timestamp,
47
+ a fresh nonce, the origin of `PARHELIA_PREVIEW_URL` and the code; Parhelia refuses a tampered, stale, replayed or other-origin
48
+ redemption by name), and every gateway read carries `session.credential`, the ticket's credential derived from the key. A
49
+ Parhelia on protocol 1 (the key as a bearer) refuses this package's redemptions, and a protocol 2 Parhelia refuses the bearer
50
+ form by name (`preview-redemption-unsigned`): update the package and Parhelia together.
51
+
52
+ Entry points:
53
+
54
+ | Import | For |
55
+ |---|---|
56
+ | `@parhelia/preview-ticket` | the framework-neutral core: `createPreviewKit`, the store interface and in-memory store, `redeemPreviewCode`, `previewGatewayFromEnv`, `previewGatewayUrl`, `redactParheliaPreview`, `ParheliaPreviewError`; a head page's named states: `previewRefusalOf`, `answerPreviewRefusal`, and `DeliveryReadRefused` (a head's delivery client's refused read) with `deliveryRefusal(inSession)` (a named state inside a session only) |
57
+ | `@parhelia/preview-ticket/next` | `parheliaPreview`, `withParheliaPreview`, `createParheliaPreview` (custom store, JSS plugin form), `readPreviewSessionFor`, `previewHeadersFor` |
58
+ | `@parhelia/preview-ticket/next/app` | `previewHeaders()`, `readPreviewSession()` over `cookies()` |
59
+ | `@parhelia/preview-ticket/fetch` | a head whose server is a Web fetch handler (TanStack Start, React Router, Hono, Astro middleware): `withParheliaPreview(handler, { basePath })`, `readPreviewSession(request)`, `previewHeaders(request)`, `createParheliaPreviewFetch` (custom store) |
60
+ | `@parhelia/preview-ticket/alpaca` | `alpacaPreviewReads({ axios, cache, cookies })` for `@alpaca-headless` App Router heads: routes the package's draft reads to the gateway as the person (`resolve()` for the page's route read, named refusals, a per-render `edit_rev`) |
@@ -0,0 +1,101 @@
1
+ import { type PreviewRefusal } from "../errors.js";
2
+ import type { CookieSource, PreviewSession } from "../kit.js";
3
+ /** The environment variable naming the content store the head's preview reads are served from (`sitecore:master`). */
4
+ export declare const ENV_PREVIEW_STORE = "PARHELIA_PREVIEW_STORE";
5
+ /** The package's draft reads the runtime serves per person (the dictionary is public and stays the site's read). */
6
+ export declare const ALPACA_PREVIEW_ROUTES: readonly string[];
7
+ /** The alpaca wire's key slot: the gateway checks the ticket's credential here and strips it. */
8
+ export declare const ALPACA_KEY_HEADER = "x-api-key";
9
+ /** The named state a page shows instead of a render (plain words; never a code, ticket or handle). */
10
+ export type PreviewRefusalView = PreviewRefusal;
11
+ /** The request side of an axios request config, as far as this module touches it. */
12
+ export interface AlpacaReadConfig {
13
+ url?: string;
14
+ headers?: unknown;
15
+ auth?: unknown;
16
+ }
17
+ /** The response side of an axios response, as far as this module reads it. */
18
+ export interface AlpacaReadResponse {
19
+ readonly status: number;
20
+ readonly headers?: unknown;
21
+ readonly data?: unknown;
22
+ }
23
+ /**
24
+ * The axios instance the `@alpaca-headless` package makes its reads with — structurally, so this module imports no
25
+ * axios (the head's own copy is the one the package resolves). The callbacks are typed loosely on purpose: axios's
26
+ * interceptor managers take its own config / response types, which this module narrows to `AlpacaReadConfig` /
27
+ * `AlpacaReadResponse` inside.
28
+ */
29
+ export interface AxiosLike {
30
+ readonly interceptors: {
31
+ readonly request: {
32
+ use(onFulfilled: (config: any) => any): number;
33
+ };
34
+ readonly response: {
35
+ use(onFulfilled: (response: any) => any, onRejected: (error: any) => any): number;
36
+ };
37
+ };
38
+ }
39
+ /** React's `cache` (the head's own: per request in a server component, a plain call elsewhere). */
40
+ export type RenderCache = <F extends (...args: never[]) => unknown>(fn: F) => F;
41
+ export interface AlpacaPreviewReadsOptions {
42
+ /** The head's `axios` — the instance the `@alpaca-headless` package reads with. */
43
+ readonly axios: AxiosLike;
44
+ /** The head's React `cache`. */
45
+ readonly cache: RenderCache;
46
+ /** The head's `cookies` from `next/headers` (throws outside a request: no request, no person, no session). */
47
+ readonly cookies: () => CookieSource | Promise<CookieSource>;
48
+ /** Where sessions are read (default: the process-wide instance `src/proxy.ts` redeems into). */
49
+ readonly preview?: {
50
+ readPreviewSessionFor(source: CookieSource): Promise<PreviewSession | null>;
51
+ };
52
+ /** Where the settings are read (default `process.env`, at call time). */
53
+ readonly env?: Readonly<Record<string, string | undefined>>;
54
+ }
55
+ /** The outcome of one page read: the route data, or the named state the page shows instead. */
56
+ export type AlpacaPreviewRead<R> = {
57
+ readonly refusal: PreviewRefusalView;
58
+ readonly routeData?: undefined;
59
+ } | {
60
+ readonly refusal?: undefined;
61
+ readonly routeData: R;
62
+ };
63
+ /** What the package's `resolveRoute` answers, as far as this module reads it. */
64
+ export interface RouteDataLike {
65
+ readonly result: {
66
+ readonly type: string;
67
+ };
68
+ }
69
+ export interface AlpacaPreviewReads {
70
+ /** The live preview session of this render, or null (also outside a request); throws `ParheliaPreviewError` for a session that cannot serve. */
71
+ session(): Promise<PreviewSession | null>;
72
+ /**
73
+ * Reads the page for this render: without a session, `read(searchParams)` exactly as before. In a live session the
74
+ * search parameters get a fresh `edit_rev` (finding C: the package caches a layout for 5 s under a key without the
75
+ * person, so a per-render revision keeps every session read out of shared entries), and a refused or failed read
76
+ * is the named state — never a render with the site's own key. A page the person may not read stays the layout's
77
+ * own not-found, exactly like a page that does not exist.
78
+ */
79
+ resolve<P extends object, R extends RouteDataLike>(searchParams: P, read: (searchParams: P) => Promise<R>): Promise<AlpacaPreviewRead<R>>;
80
+ /** The refusal the gateway (or this module) named on a read of this render (the last one), if any. */
81
+ refusalOfThisRender(): PreviewRefusalView | undefined;
82
+ }
83
+ /** The gateway base of this head, or the named state a live session gets without its settings (the key included). */
84
+ export declare const alpacaPreviewSettings: (env: Readonly<Record<string, string | undefined>>) => {
85
+ readonly gateway: string;
86
+ };
87
+ /** The route below `layoutServiceUrl` when `url` is one of the package's draft reads (layout, partial, item query), else null. */
88
+ export declare const alpacaDraftRouteOf: (url: string | undefined, layoutServiceUrl: string | undefined) => string | null;
89
+ /** One draft read inside a live session: the gateway URL, the session's credential in the key slot, the ticket, no cookies, no Authorization. */
90
+ export declare const asAlpacaPreviewRead: <C extends AlpacaReadConfig>(config: C, route: string, session: PreviewSession, settings: {
91
+ readonly gateway: string;
92
+ }) => C;
93
+ /** The named refusal a gateway answer carries (`Parhelia-Preview-Refusal` + the kernel's `{ summary }`), if any. */
94
+ export declare const refusalOfAnswer: (response: AlpacaReadResponse | undefined) => PreviewRefusalView | undefined;
95
+ /**
96
+ * Creates the head's per-person preview reads and installs the routing interceptor on its axios instance (once per
97
+ * instance; a second call on the same instance reuses the first installation's reads).
98
+ */
99
+ export declare const alpacaPreviewReads: (options: AlpacaPreviewReadsOptions) => AlpacaPreviewReads;
100
+ export type { PreviewSession } from "../kit.js";
101
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/alpaca/index.ts"],"names":[],"mappings":"AA+BA,OAAO,EAKL,KAAK,cAAc,EACpB,MAAM,cAAc,CAAC;AACtB,OAAO,KAAK,EAAE,YAAY,EAAE,cAAc,EAAE,MAAM,WAAW,CAAC;AAI9D,sHAAsH;AACtH,eAAO,MAAM,iBAAiB,2BAA2B,CAAC;AAE1D,oHAAoH;AACpH,eAAO,MAAM,qBAAqB,EAAE,SAAS,MAAM,EAGjD,CAAC;AAEH,iGAAiG;AACjG,eAAO,MAAM,iBAAiB,cAAc,CAAC;AAE7C,sGAAsG;AACtG,MAAM,MAAM,kBAAkB,GAAG,cAAc,CAAC;AAEhD,qFAAqF;AACrF,MAAM,WAAW,gBAAgB;IAC/B,GAAG,CAAC,EAAE,MAAM,CAAC;IACb,OAAO,CAAC,EAAE,OAAO,CAAC;IAClB,IAAI,CAAC,EAAE,OAAO,CAAC;CAChB;AAED,8EAA8E;AAC9E,MAAM,WAAW,kBAAkB;IACjC,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IACxB,QAAQ,CAAC,OAAO,CAAC,EAAE,OAAO,CAAC;IAC3B,QAAQ,CAAC,IAAI,CAAC,EAAE,OAAO,CAAC;CACzB;AAED;;;;;GAKG;AACH,MAAM,WAAW,SAAS;IACxB,QAAQ,CAAC,YAAY,EAAE;QACrB,QAAQ,CAAC,OAAO,EAAE;YAEhB,GAAG,CAAC,WAAW,EAAE,CAAC,MAAM,EAAE,GAAG,KAAK,GAAG,GAAG,MAAM,CAAC;SAChD,CAAC;QACF,QAAQ,CAAC,QAAQ,EAAE;YAEjB,GAAG,CAAC,WAAW,EAAE,CAAC,QAAQ,EAAE,GAAG,KAAK,GAAG,EAAE,UAAU,EAAE,CAAC,KAAK,EAAE,GAAG,KAAK,GAAG,GAAG,MAAM,CAAC;SACnF,CAAC;KACH,CAAC;CACH;AAED,mGAAmG;AACnG,MAAM,MAAM,WAAW,GAAG,CAAC,CAAC,SAAS,CAAC,GAAG,IAAI,EAAE,KAAK,EAAE,KAAK,OAAO,EAAE,EAAE,EAAE,CAAC,KAAK,CAAC,CAAC;AAEhF,MAAM,WAAW,yBAAyB;IACxC,mFAAmF;IACnF,QAAQ,CAAC,KAAK,EAAE,SAAS,CAAC;IAC1B,gCAAgC;IAChC,QAAQ,CAAC,KAAK,EAAE,WAAW,CAAC;IAC5B,8GAA8G;IAC9G,QAAQ,CAAC,OAAO,EAAE,MAAM,YAAY,GAAG,OAAO,CAAC,YAAY,CAAC,CAAC;IAC7D,gGAAgG;IAChG,QAAQ,CAAC,OAAO,CAAC,EAAE;QAAE,qBAAqB,CAAC,MAAM,EAAE,YAAY,GAAG,OAAO,CAAC,cAAc,GAAG,IAAI,CAAC,CAAA;KAAE,CAAC;IACnG,yEAAyE;IACzE,QAAQ,CAAC,GAAG,CAAC,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,SAAS,CAAC,CAAC,CAAC;CAC7D;AAED,+FAA+F;AAC/F,MAAM,MAAM,iBAAiB,CAAC,CAAC,IAC3B;IAAE,QAAQ,CAAC,OAAO,EAAE,kBAAkB,CAAC;IAAC,QAAQ,CAAC,SAAS,CAAC,EAAE,SAAS,CAAA;CAAE,GACxE;IAAE,QAAQ,CAAC,OAAO,CAAC,EAAE,SAAS,CAAC;IAAC,QAAQ,CAAC,SAAS,EAAE,CAAC,CAAA;CAAE,CAAC;AAE5D,iFAAiF;AACjF,MAAM,WAAW,aAAa;IAC5B,QAAQ,CAAC,MAAM,EAAE;QAAE,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAA;KAAE,CAAC;CAC5C;AAED,MAAM,WAAW,kBAAkB;IACjC,gJAAgJ;IAChJ,OAAO,IAAI,OAAO,CAAC,cAAc,GAAG,IAAI,CAAC,CAAC;IAC1C;;;;;;OAMG;IACH,OAAO,CAAC,CAAC,SAAS,MAAM,EAAE,CAAC,SAAS,aAAa,EAC/C,YAAY,EAAE,CAAC,EACf,IAAI,EAAE,CAAC,YAAY,EAAE,CAAC,KAAK,OAAO,CAAC,CAAC,CAAC,GACpC,OAAO,CAAC,iBAAiB,CAAC,CAAC,CAAC,CAAC,CAAC;IACjC,sGAAsG;IACtG,mBAAmB,IAAI,kBAAkB,GAAG,SAAS,CAAC;CACvD;AAOD,qHAAqH;AACrH,eAAO,MAAM,qBAAqB,QAC3B,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,SAAS,CAAC,CAAC,KAChD;IAAE,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAA;CAa5B,CAAC;AAEF,kIAAkI;AAClI,eAAO,MAAM,kBAAkB,QACxB,MAAM,GAAG,SAAS,oBACL,MAAM,GAAG,SAAS,KACnC,MAAM,GAAG,IAMX,CAAC;AAeF,iJAAiJ;AACjJ,eAAO,MAAM,mBAAmB,GAAI,CAAC,SAAS,gBAAgB,UACpD,CAAC,SACF,MAAM,WACJ,cAAc,YACb;IAAE,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAA;CAAE,KACrC,CAqBF,CAAC;AAYF,oHAAoH;AACpH,eAAO,MAAM,eAAe,aAAc,kBAAkB,GAAG,SAAS,KAAG,kBAAkB,GAAG,SAM/F,CAAC;AAGF;;;GAGG;AACH,eAAO,MAAM,kBAAkB,YAAa,yBAAyB,KAAG,kBA2EvE,CAAC;AAEF,YAAY,EAAE,cAAc,EAAE,MAAM,WAAW,CAAC"}
@@ -0,0 +1,200 @@
1
+ /**
2
+ * `@parhelia/preview-ticket/alpaca` — per-person preview for Next.js App Router heads built on the
3
+ * `@alpaca-headless` packages: every such head opts in with the same three lines.
4
+ *
5
+ * While a render's request carries a live preview session, every draft read the `@alpaca-headless` package makes —
6
+ * the layout, the lazy placeholders, an item query — goes to the Parhelia preview gateway
7
+ * (`{PARHELIA_PREVIEW_URL}/parhelia/preview/{PARHELIA_PREVIEW_STORE}/alpaca/headless/…`) with the session's gateway
8
+ * credential (derived from the preview key, never the key) in the package's own key slot (`x-api-key`) and the ticket
9
+ * header, and never with the visitor's cookies or an
10
+ * `Authorization`. The gateway runs the kernel's own handler as the editing PERSON, so the canvas shows what that
11
+ * person may read. Outside a session nothing changes. The dictionary is not a draft read: the runtime serves it to
12
+ * anyone without a credential and the package caches it for every visitor, so it stays the site's public read.
13
+ *
14
+ * Why an axios interceptor: the package builds every URL from the process-wide `LAYOUT_SERVICE_URL` and calls some
15
+ * reads (the lazy placeholders) without the head's request configuration, so neither the base URL nor a header can
16
+ * be chosen per request through its API (U44 Q10: its source is not in this repository). The interceptor decides
17
+ * per call from the render's own cookies. A session that cannot serve, or a head without the settings, fails the
18
+ * read by name — never a read with the head's own key on the person's behalf.
19
+ *
20
+ * The head hands in its own `axios` (the copy the package resolves — one hoisted copy), React's `cache` and Next's
21
+ * `cookies` (both must be the head's own instances: they are request-scoped by the framework), so this module
22
+ * imports none of them:
23
+ *
24
+ * import axios from "axios";
25
+ * import { cookies } from "next/headers.js";
26
+ * import { cache } from "react";
27
+ * import { alpacaPreviewReads } from "@parhelia/preview-ticket/alpaca";
28
+ * export const alpacaPreview = alpacaPreviewReads({ axios, cache, cookies });
29
+ */
30
+ import { previewGatewayUrl } from "../client.js";
31
+ import { PREVIEW_REFUSAL_HEADER } from "../constants.js";
32
+ import { HeadPreviewStates, isRefusalName, ParheliaPreviewError, refusal, } from "../errors.js";
33
+ import { defaultParheliaPreview } from "../next/index.js";
34
+ import { previewRefusalOf } from "../refusal.js";
35
+ /** The environment variable naming the content store the head's preview reads are served from (`sitecore:master`). */
36
+ export const ENV_PREVIEW_STORE = "PARHELIA_PREVIEW_STORE";
37
+ /** The package's draft reads the runtime serves per person (the dictionary is public and stays the site's read). */
38
+ export const ALPACA_PREVIEW_ROUTES = Object.freeze([
39
+ "/alpaca/headless/layout",
40
+ "/alpaca/headless/graphql",
41
+ ]);
42
+ /** The alpaca wire's key slot: the gateway checks the ticket's credential here and strips it. */
43
+ export const ALPACA_KEY_HEADER = "x-api-key";
44
+ const INSTALLED = Symbol.for("parhelia.alpacaPreviewReads");
45
+ const envOf = (options) => options.env ?? (typeof process !== "undefined" && process.env ? process.env : {});
46
+ /** The gateway base of this head, or the named state a live session gets without its settings (the key included). */
47
+ export const alpacaPreviewSettings = (env) => {
48
+ const parhelia = env.PARHELIA_PREVIEW_URL?.trim();
49
+ const store = env[ENV_PREVIEW_STORE]?.trim();
50
+ const key = env.PARHELIA_PREVIEW_KEY?.trim();
51
+ if (!parhelia || !store || !key) {
52
+ throw new ParheliaPreviewError(refusal(HeadPreviewStates.HeadNotConfigured, `This site is not configured for per-person preview (PARHELIA_PREVIEW_URL, ${ENV_PREVIEW_STORE} and PARHELIA_PREVIEW_KEY are required).`));
53
+ }
54
+ return { gateway: previewGatewayUrl(parhelia, store) };
55
+ };
56
+ /** The route below `layoutServiceUrl` when `url` is one of the package's draft reads (layout, partial, item query), else null. */
57
+ export const alpacaDraftRouteOf = (url, layoutServiceUrl) => {
58
+ const base = (layoutServiceUrl ?? "").replace(/\/+$/, "");
59
+ if (!url || !base || !url.startsWith(base + "/"))
60
+ return null;
61
+ const route = url.slice(base.length);
62
+ const path = route.split("?")[0].toLowerCase();
63
+ return ALPACA_PREVIEW_ROUTES.some((served) => path === served || path.startsWith(served + "/")) ? route : null;
64
+ };
65
+ const isHeaderBag = (value) => !!value &&
66
+ typeof value.set === "function" &&
67
+ typeof value.delete === "function";
68
+ /** Headers a gateway read never carries from the incoming configuration (compared lower-case). */
69
+ const DROPPED = ["cookie", "authorization", ALPACA_KEY_HEADER];
70
+ /** One draft read inside a live session: the gateway URL, the session's credential in the key slot, the ticket, no cookies, no Authorization. */
71
+ export const asAlpacaPreviewRead = (config, route, session, settings) => {
72
+ const ticketHeaders = Object.entries(session.headers);
73
+ const current = config.headers;
74
+ if (isHeaderBag(current)) {
75
+ // axios >= 1 hands request interceptors an AxiosHeaders (case-insensitive set / delete).
76
+ for (const name of DROPPED)
77
+ current.delete(name);
78
+ for (const [name] of ticketHeaders)
79
+ current.delete(name);
80
+ current.set(ALPACA_KEY_HEADER, session.credential);
81
+ for (const [name, value] of ticketHeaders)
82
+ current.set(name, value);
83
+ }
84
+ else {
85
+ const replaced = new Set([...DROPPED, ...ticketHeaders.map(([name]) => name.toLowerCase())]);
86
+ const kept = {};
87
+ for (const [name, value] of Object.entries(current ?? {}))
88
+ if (!replaced.has(name.toLowerCase()))
89
+ kept[name] = value;
90
+ kept[ALPACA_KEY_HEADER] = session.credential;
91
+ for (const [name, value] of ticketHeaders)
92
+ kept[name] = value;
93
+ config.headers = kept;
94
+ }
95
+ delete config.auth;
96
+ config.url = settings.gateway + route;
97
+ return config;
98
+ };
99
+ const headerOf = (headers, name) => {
100
+ if (!headers)
101
+ return undefined;
102
+ const bag = headers;
103
+ if (typeof bag.get === "function") {
104
+ const value = bag.get(name);
105
+ if (value !== undefined && value !== null)
106
+ return value;
107
+ }
108
+ return bag[name.toLowerCase()] ?? bag[name];
109
+ };
110
+ /** The named refusal a gateway answer carries (`Parhelia-Preview-Refusal` + the kernel's `{ summary }`), if any. */
111
+ export const refusalOfAnswer = (response) => {
112
+ if (!response)
113
+ return undefined;
114
+ const code = headerOf(response.headers, PREVIEW_REFUSAL_HEADER);
115
+ if (!isRefusalName(code))
116
+ return undefined;
117
+ const summary = response.data?.summary;
118
+ return refusal(code, typeof summary === "string" ? summary : code, response.status);
119
+ };
120
+ /**
121
+ * Creates the head's per-person preview reads and installs the routing interceptor on its axios instance (once per
122
+ * instance; a second call on the same instance reuses the first installation's reads).
123
+ */
124
+ export const alpacaPreviewReads = (options) => {
125
+ const marked = options.axios;
126
+ const installed = marked[INSTALLED];
127
+ if (installed)
128
+ return installed;
129
+ const preview = () => options.preview ?? defaultParheliaPreview();
130
+ const session = options.cache(async () => {
131
+ let source;
132
+ try {
133
+ source = await options.cookies();
134
+ }
135
+ catch {
136
+ return null; // not inside a request: no person, no session
137
+ }
138
+ return preview().readPreviewSessionFor(source);
139
+ });
140
+ const renderRefusals = options.cache(() => ({}));
141
+ const record = (named) => {
142
+ if (named)
143
+ renderRefusals().last = named;
144
+ };
145
+ options.axios.interceptors.request.use(async (config) => {
146
+ const route = alpacaDraftRouteOf(config.url, envOf(options).LAYOUT_SERVICE_URL);
147
+ if (!route)
148
+ return config;
149
+ try {
150
+ const live = await session();
151
+ if (!live)
152
+ return config;
153
+ return asAlpacaPreviewRead(config, route, live, alpacaPreviewSettings(envOf(options)));
154
+ }
155
+ catch (error) {
156
+ record(previewRefusalOf(error));
157
+ throw error;
158
+ }
159
+ });
160
+ options.axios.interceptors.response.use((response) => {
161
+ record(refusalOfAnswer(response));
162
+ return response;
163
+ }, (error) => {
164
+ record(refusalOfAnswer(error?.response));
165
+ return Promise.reject(error);
166
+ });
167
+ const reads = {
168
+ session,
169
+ async resolve(searchParams, read) {
170
+ let live;
171
+ try {
172
+ live = await session();
173
+ }
174
+ catch (error) {
175
+ const named = previewRefusalOf(error);
176
+ if (named)
177
+ return { refusal: named };
178
+ throw error;
179
+ }
180
+ if (!live)
181
+ return { routeData: await read(searchParams) };
182
+ const routeData = await read({ ...searchParams, edit_rev: globalThis.crypto.randomUUID() });
183
+ const type = routeData.result.type;
184
+ if (type === "error" || type === "unauthorized") {
185
+ const errorCode = routeData.result.errorCode;
186
+ return {
187
+ refusal: renderRefusals().last ?? {
188
+ status: type === "error" && typeof errorCode === "number" ? errorCode : 401,
189
+ code: "preview-read-failed",
190
+ message: "The page could not be read with your own access.",
191
+ },
192
+ };
193
+ }
194
+ return { routeData };
195
+ },
196
+ refusalOfThisRender: () => renderRefusals().last,
197
+ };
198
+ marked[INSTALLED] = reads;
199
+ return reads;
200
+ };
@@ -0,0 +1,36 @@
1
+ import { type PreviewRefusal } from "./errors.js";
2
+ export interface RedeemedTicket {
3
+ readonly ok: true;
4
+ readonly ticket: string;
5
+ /** Seconds the ticket lives from now on Parhelia's clock (sliding there). */
6
+ readonly expiresIn: number;
7
+ /** A non-secret handle Parhelia names the ticket by in its logs and outcomes. */
8
+ readonly ticketId: string;
9
+ }
10
+ export interface RefusedRedemption {
11
+ readonly ok: false;
12
+ readonly refusal: PreviewRefusal;
13
+ }
14
+ export type RedemptionResult = RedeemedTicket | RefusedRedemption;
15
+ export interface RedeemInput {
16
+ /** Parhelia's base URL as the head's server reaches it (origin, optionally with a path base). */
17
+ readonly parheliaUrl: string;
18
+ /** The host entry's preview key (`PARHELIA_PREVIEW_KEY`): it signs the redemption and is never sent. */
19
+ readonly previewKey: string;
20
+ readonly code: string;
21
+ readonly fetch?: typeof fetch;
22
+ readonly timeoutMs?: number;
23
+ }
24
+ /** `{parhelia}/parhelia/preview/ticket` with any trailing slash of the base removed. */
25
+ export declare const previewTicketUrl: (parheliaUrl: string) => string;
26
+ /**
27
+ * The gateway base a head points its preview client at for one Parhelia store:
28
+ * `{parhelia}/parhelia/preview/{storeId}` (the store id is one percent-encoded segment).
29
+ */
30
+ export declare const previewGatewayUrl: (parheliaUrl: string, storeId: string) => string;
31
+ /**
32
+ * Redeems a one-time code back-channel, signed with the head's key (the key never travels). Never throws, never follows a
33
+ * redirect (the code goes to Parhelia only), never caches, never logs; every failure is a named refusal.
34
+ */
35
+ export declare const redeemPreviewCode: (input: RedeemInput) => Promise<RedemptionResult>;
36
+ //# sourceMappingURL=client.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"client.d.ts","sourceRoot":"","sources":["../src/client.ts"],"names":[],"mappings":"AAmBA,OAAO,EAIL,KAAK,cAAc,EACpB,MAAM,aAAa,CAAC;AAQrB,MAAM,WAAW,cAAc;IAC7B,QAAQ,CAAC,EAAE,EAAE,IAAI,CAAC;IAClB,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IACxB,6EAA6E;IAC7E,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAC;IAC3B,iFAAiF;IACjF,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC;CAC3B;AAED,MAAM,WAAW,iBAAiB;IAChC,QAAQ,CAAC,EAAE,EAAE,KAAK,CAAC;IACnB,QAAQ,CAAC,OAAO,EAAE,cAAc,CAAC;CAClC;AAED,MAAM,MAAM,gBAAgB,GAAG,cAAc,GAAG,iBAAiB,CAAC;AAElE,MAAM,WAAW,WAAW;IAC1B,iGAAiG;IACjG,QAAQ,CAAC,WAAW,EAAE,MAAM,CAAC;IAC7B,wGAAwG;IACxG,QAAQ,CAAC,UAAU,EAAE,MAAM,CAAC;IAC5B,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB,QAAQ,CAAC,KAAK,CAAC,EAAE,OAAO,KAAK,CAAC;IAC9B,QAAQ,CAAC,SAAS,CAAC,EAAE,MAAM,CAAC;CAC7B;AAED,wFAAwF;AACxF,eAAO,MAAM,gBAAgB,gBAAiB,MAAM,KAAG,MAClB,CAAC;AAEtC;;;GAGG;AACH,eAAO,MAAM,iBAAiB,gBACf,MAAM,WACV,MAAM,KACd,MAOF,CAAC;AAEF;;;GAGG;AACH,eAAO,MAAM,iBAAiB,UACrB,WAAW,KACjB,OAAO,CAAC,gBAAgB,CA+F1B,CAAC"}
package/dist/client.js ADDED
@@ -0,0 +1,125 @@
1
+ /**
2
+ * The one module that knows Parhelia's per-person preview routes as a head sees them. Everything else in this package
3
+ * talks to these functions; a route or shape change on the Parhelia side lands here.
4
+ *
5
+ * Assumed contract (Parhelia's preview endpoints, preview protocol version 2):
6
+ * - `POST {parhelia}/parhelia/preview/ticket`, body `{"code":"<code>"}`, signed with the host entry's preview key
7
+ * (`signing.ts`: the key id, a timestamp, a fresh nonce, the target origin and the code; the key never travels);
8
+ * cookies are ignored. A redemption without a signature (version 1's bearer key) is refused by name.
9
+ * - 200 `{"ticket":"pvt1_…","expiresIn":<seconds>,"ticketId":"<guid>"}`, `Cache-Control: no-store`.
10
+ * - otherwise a status (400 / 401 / 405 / 429) with `{"error":{"code":"preview-…","message":"…"}}`
11
+ * and the `Parhelia-Preview-Refusal: preview-…` header. A signed presentation spends the code.
12
+ * - the gateway: `{parhelia}/parhelia/preview/{storeId}/{vendorPath}` with the ticket in
13
+ * `X-Parhelia-Preview-Ticket` and the ticket's gateway credential (`gatewayCredential`) in the vendor's own
14
+ * credential slot.
15
+ */
16
+ import { PREVIEW_REFUSAL_HEADER, DEFAULT_REDEMPTION_TIMEOUT_MS, } from "./constants.js";
17
+ import { HeadPreviewStates, isRefusalName, refusal, } from "./errors.js";
18
+ import { signRedemption } from "./signing.js";
19
+ const PREVIEW_PREFIX = "/parhelia/preview";
20
+ const TICKET_ROUTE = `${PREVIEW_PREFIX}/ticket`;
21
+ const MAX_TICKET_LENGTH = 512;
22
+ const MAX_MESSAGE_LENGTH = 300;
23
+ /** `{parhelia}/parhelia/preview/ticket` with any trailing slash of the base removed. */
24
+ export const previewTicketUrl = (parheliaUrl) => joinBase(parheliaUrl, TICKET_ROUTE);
25
+ /**
26
+ * The gateway base a head points its preview client at for one Parhelia store:
27
+ * `{parhelia}/parhelia/preview/{storeId}` (the store id is one percent-encoded segment).
28
+ */
29
+ export const previewGatewayUrl = (parheliaUrl, storeId) => {
30
+ if (!storeId)
31
+ throw new Error("A store id is required for the preview gateway URL.");
32
+ return joinBase(parheliaUrl, `${PREVIEW_PREFIX}/${encodeURIComponent(storeId)}`);
33
+ };
34
+ /**
35
+ * Redeems a one-time code back-channel, signed with the head's key (the key never travels). Never throws, never follows a
36
+ * redirect (the code goes to Parhelia only), never caches, never logs; every failure is a named refusal.
37
+ */
38
+ export const redeemPreviewCode = async (input) => {
39
+ const doFetch = input.fetch ?? globalThis.fetch;
40
+ let signed;
41
+ try {
42
+ signed = await signRedemption({
43
+ previewKey: input.previewKey,
44
+ parheliaUrl: input.parheliaUrl,
45
+ code: input.code,
46
+ });
47
+ }
48
+ catch {
49
+ return refused(refusal(HeadPreviewStates.HeadNotConfigured, "This head is not configured for per-person preview."));
50
+ }
51
+ let response;
52
+ try {
53
+ response = await doFetch(previewTicketUrl(input.parheliaUrl), {
54
+ method: "POST",
55
+ headers: {
56
+ ...signed.headers,
57
+ "Content-Type": "application/json",
58
+ Accept: "application/json",
59
+ },
60
+ body: JSON.stringify({ code: input.code }),
61
+ redirect: "error",
62
+ cache: "no-store",
63
+ signal: AbortSignal.timeout(input.timeoutMs ?? DEFAULT_REDEMPTION_TIMEOUT_MS),
64
+ });
65
+ }
66
+ catch {
67
+ return refused(refusal(HeadPreviewStates.RedemptionUnreachable, "Parhelia could not be reached to redeem the preview code."));
68
+ }
69
+ const body = await readJson(response);
70
+ if (response.status === 200) {
71
+ const ticket = field(body, "ticket");
72
+ const ticketId = field(body, "ticketId");
73
+ const expiresIn = body && typeof body === "object"
74
+ ? body.expiresIn
75
+ : undefined;
76
+ if (typeof ticket === "string" &&
77
+ ticket.length > 0 &&
78
+ ticket.length <= MAX_TICKET_LENGTH &&
79
+ /^[\x21-\x7e]+$/.test(ticket) &&
80
+ typeof expiresIn === "number" &&
81
+ Number.isFinite(expiresIn) &&
82
+ expiresIn > 0) {
83
+ return {
84
+ ok: true,
85
+ ticket,
86
+ expiresIn,
87
+ ticketId: typeof ticketId === "string" ? ticketId : "",
88
+ };
89
+ }
90
+ return refused(refusal(HeadPreviewStates.RedemptionMalformed, "Parhelia's answer to the redemption carried no ticket."));
91
+ }
92
+ const error = body && typeof body === "object"
93
+ ? body.error
94
+ : undefined;
95
+ const namedInBody = field(error, "code");
96
+ const namedInHeader = response.headers.get(PREVIEW_REFUSAL_HEADER);
97
+ const code = isRefusalName(namedInBody)
98
+ ? namedInBody
99
+ : isRefusalName(namedInHeader)
100
+ ? namedInHeader
101
+ : HeadPreviewStates.RedemptionRefused;
102
+ const message = field(error, "message");
103
+ return refused(refusal(code, typeof message === "string" && message.length > 0
104
+ ? message.slice(0, MAX_MESSAGE_LENGTH)
105
+ : "Parhelia refused the preview code.", response.status >= 400 && response.status <= 599 ? response.status : 502));
106
+ };
107
+ const refused = (value) => ({
108
+ ok: false,
109
+ refusal: value,
110
+ });
111
+ const field = (value, name) => value && typeof value === "object"
112
+ ? value[name]
113
+ : undefined;
114
+ const readJson = async (response) => {
115
+ try {
116
+ const text = await response.text();
117
+ return text.length === 0 || text.length > 64 * 1024
118
+ ? undefined
119
+ : JSON.parse(text);
120
+ }
121
+ catch {
122
+ return undefined;
123
+ }
124
+ };
125
+ const joinBase = (base, path) => `${base.replace(/\/+$/, "")}${path}`;
@@ -0,0 +1,52 @@
1
+ import { type PreviewRefusal } from "./errors.js";
2
+ import type { PreviewTicketStore } from "./store.js";
3
+ export interface PreviewKitOptions {
4
+ /** Parhelia's base URL as the head's server reaches it. Default: `PARHELIA_PREVIEW_URL`, else `PARHELIA_ORIGIN`. */
5
+ readonly parheliaUrl?: string;
6
+ /**
7
+ * The host entry's preview key. Default: `PARHELIA_PREVIEW_KEY`. It signs the redemption and derives each session's
8
+ * gateway credential; it is never sent.
9
+ */
10
+ readonly previewKey?: string;
11
+ /**
12
+ * The origin people open Parhelia's editor at: a code in a frame the head is framed in directly is redeemed only when the
13
+ * frame's `Referer` names it (`redemptionContextRefusal`). Default: `PARHELIA_ORIGIN`. A head reached only through
14
+ * Parhelia's rendering proxy needs none.
15
+ */
16
+ readonly editorOrigin?: string;
17
+ /** Where tickets live. Default: the process-wide in-memory store (Node.js runtime, one instance). */
18
+ readonly store?: PreviewTicketStore;
19
+ /** How long the handle cookie and its record live (default 8 h, the ticket's cap on Parhelia's side). */
20
+ readonly sessionCapSeconds?: number;
21
+ /** How long a redirected frame URL is remembered to detect a dropped handle cookie (default 15 min). */
22
+ readonly cookieCheckSeconds?: number;
23
+ /** Redemption timeout (default 5 s). */
24
+ readonly redemptionTimeoutMs?: number;
25
+ /**
26
+ * Allow `http:` for a non-loopback Parhelia URL (a private network). Default: `PARHELIA_PREVIEW_ALLOW_HTTP=true`,
27
+ * else only `https:` and loopback hosts are accepted — the code, the ticket and its credential travel on these calls
28
+ * (the key does not).
29
+ */
30
+ readonly allowInsecureParheliaUrl?: boolean;
31
+ /** The fetch used for the redemption (tests, instrumentation). */
32
+ readonly fetch?: typeof fetch;
33
+ /** Where the defaults are read from (default `process.env`, at request time). */
34
+ readonly env?: Readonly<Record<string, string | undefined>>;
35
+ /**
36
+ * The answer for a named refusal (default: a minimal `private, no-store` page naming the state).
37
+ * Whatever it returns is made `private, no-store` and `no-referrer`; it must not render content.
38
+ */
39
+ readonly onRefusal?: (state: PreviewRefusal, request: Request) => Response | Promise<Response>;
40
+ }
41
+ export interface RedemptionConfig {
42
+ readonly parheliaUrl: string;
43
+ readonly previewKey: string;
44
+ }
45
+ /** The editor's origin a directly framed code must come from (`editorOrigin`, else `PARHELIA_ORIGIN`), or undefined. */
46
+ export declare const editorOriginOf: (options: PreviewKitOptions) => string | undefined;
47
+ export declare const sessionCapOf: (options: PreviewKitOptions) => number;
48
+ export declare const cookieCheckOf: (options: PreviewKitOptions) => number;
49
+ export declare const redemptionTimeoutOf: (options: PreviewKitOptions) => number;
50
+ /** The Parhelia URL and key, or the named reason the head cannot redeem. */
51
+ export declare const redemptionConfigOf: (options: PreviewKitOptions) => RedemptionConfig | PreviewRefusal;
52
+ //# sourceMappingURL=config.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"config.d.ts","sourceRoot":"","sources":["../src/config.ts"],"names":[],"mappings":"AAaA,OAAO,EAA8B,KAAK,cAAc,EAAE,MAAM,aAAa,CAAC;AAC9E,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,YAAY,CAAC;AAErD,MAAM,WAAW,iBAAiB;IAChC,oHAAoH;IACpH,QAAQ,CAAC,WAAW,CAAC,EAAE,MAAM,CAAC;IAC9B;;;OAGG;IACH,QAAQ,CAAC,UAAU,CAAC,EAAE,MAAM,CAAC;IAC7B;;;;OAIG;IACH,QAAQ,CAAC,YAAY,CAAC,EAAE,MAAM,CAAC;IAC/B,qGAAqG;IACrG,QAAQ,CAAC,KAAK,CAAC,EAAE,kBAAkB,CAAC;IACpC,yGAAyG;IACzG,QAAQ,CAAC,iBAAiB,CAAC,EAAE,MAAM,CAAC;IACpC,wGAAwG;IACxG,QAAQ,CAAC,kBAAkB,CAAC,EAAE,MAAM,CAAC;IACrC,wCAAwC;IACxC,QAAQ,CAAC,mBAAmB,CAAC,EAAE,MAAM,CAAC;IACtC;;;;OAIG;IACH,QAAQ,CAAC,wBAAwB,CAAC,EAAE,OAAO,CAAC;IAC5C,kEAAkE;IAClE,QAAQ,CAAC,KAAK,CAAC,EAAE,OAAO,KAAK,CAAC;IAC9B,iFAAiF;IACjF,QAAQ,CAAC,GAAG,CAAC,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,SAAS,CAAC,CAAC,CAAC;IAC5D;;;OAGG;IACH,QAAQ,CAAC,SAAS,CAAC,EAAE,CACnB,KAAK,EAAE,cAAc,EACrB,OAAO,EAAE,OAAO,KACb,QAAQ,GAAG,OAAO,CAAC,QAAQ,CAAC,CAAC;CACnC;AAED,MAAM,WAAW,gBAAgB;IAC/B,QAAQ,CAAC,WAAW,EAAE,MAAM,CAAC;IAC7B,QAAQ,CAAC,UAAU,EAAE,MAAM,CAAC;CAC7B;AAQD,wHAAwH;AACxH,eAAO,MAAM,cAAc,YAAa,iBAAiB,KAAG,MAAM,GAAG,SAE1D,CAAC;AAEZ,eAAO,MAAM,YAAY,YAAa,iBAAiB,KAAG,MACQ,CAAC;AAEnE,eAAO,MAAM,aAAa,YAAa,iBAAiB,KAAG,MACS,CAAC;AAErE,eAAO,MAAM,mBAAmB,YAAa,iBAAiB,KAAG,MACK,CAAC;AAEvE,4EAA4E;AAC5E,eAAO,MAAM,kBAAkB,YACpB,iBAAiB,KACzB,gBAAgB,GAAG,cA2CrB,CAAC"}
package/dist/config.js ADDED
@@ -0,0 +1,51 @@
1
+ /**
2
+ * The head's configuration, read lazily: nothing is read (and nothing can fail) for a request that
3
+ * carries neither a preview code nor the handle cookie.
4
+ */
5
+ import { DEFAULT_COOKIE_CHECK_SECONDS, DEFAULT_REDEMPTION_TIMEOUT_MS, DEFAULT_SESSION_CAP_SECONDS, ENV_ALLOW_HTTP, ENV_PARHELIA_ORIGIN, ENV_PARHELIA_URL, ENV_PREVIEW_KEY, } from "./constants.js";
6
+ import { HeadPreviewStates, refusal } from "./errors.js";
7
+ const envOf = (options) => options.env ??
8
+ (typeof process !== "undefined" && process.env ? process.env : {});
9
+ /** The editor's origin a directly framed code must come from (`editorOrigin`, else `PARHELIA_ORIGIN`), or undefined. */
10
+ export const editorOriginOf = (options) => (options.editorOrigin ?? envOf(options)[ENV_PARHELIA_ORIGIN] ?? "").trim() ||
11
+ undefined;
12
+ export const sessionCapOf = (options) => positive(options.sessionCapSeconds, DEFAULT_SESSION_CAP_SECONDS);
13
+ export const cookieCheckOf = (options) => positive(options.cookieCheckSeconds, DEFAULT_COOKIE_CHECK_SECONDS);
14
+ export const redemptionTimeoutOf = (options) => positive(options.redemptionTimeoutMs, DEFAULT_REDEMPTION_TIMEOUT_MS);
15
+ /** The Parhelia URL and key, or the named reason the head cannot redeem. */
16
+ export const redemptionConfigOf = (options) => {
17
+ const env = envOf(options);
18
+ const parheliaUrl = (options.parheliaUrl ??
19
+ // The server may reach Parhelia at another address than the browser does; by default it is the same origin.
20
+ (env[ENV_PARHELIA_URL] || env[ENV_PARHELIA_ORIGIN]) ??
21
+ "").trim();
22
+ const previewKey = (options.previewKey ?? env[ENV_PREVIEW_KEY] ?? "").trim();
23
+ if (!parheliaUrl || !previewKey) {
24
+ return refusal(HeadPreviewStates.HeadNotConfigured, `The head has no ${!parheliaUrl ? ENV_PARHELIA_URL : ENV_PREVIEW_KEY} configured for per-person preview.`);
25
+ }
26
+ let url;
27
+ try {
28
+ url = new URL(parheliaUrl);
29
+ }
30
+ catch {
31
+ return refusal(HeadPreviewStates.HeadNotConfigured, `${ENV_PARHELIA_URL} is not an absolute URL.`);
32
+ }
33
+ if (url.username || url.password || url.search || url.hash) {
34
+ return refusal(HeadPreviewStates.HeadNotConfigured, `${ENV_PARHELIA_URL} must be a base URL without credentials, query or fragment.`);
35
+ }
36
+ const allowHttp = options.allowInsecureParheliaUrl ??
37
+ env[ENV_ALLOW_HTTP]?.trim().toLowerCase() === "true";
38
+ const secure = url.protocol === "https:" ||
39
+ (url.protocol === "http:" && (allowHttp || isLoopback(url.hostname)));
40
+ if (!secure) {
41
+ return refusal(HeadPreviewStates.HeadNotConfigured, `${ENV_PARHELIA_URL} must use https (http only for a loopback host or with ${ENV_ALLOW_HTTP}=true).`);
42
+ }
43
+ return { parheliaUrl: url.href.replace(/\/+$/, ""), previewKey };
44
+ };
45
+ const isLoopback = (hostname) => hostname === "localhost" ||
46
+ hostname.endsWith(".localhost") ||
47
+ hostname === "[::1]" ||
48
+ /^127(?:\.\d{1,3}){3}$/.test(hostname);
49
+ const positive = (value, fallback) => typeof value === "number" && Number.isFinite(value) && value > 0
50
+ ? value
51
+ : fallback;