@pontive/pontkit-nextjs 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs ADDED
@@ -0,0 +1,2 @@
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const t=require("@pontive/pontkit-react");Object.keys(t).forEach(e=>{e!=="default"&&!Object.prototype.hasOwnProperty.call(exports,e)&&Object.defineProperty(exports,e,{enumerable:!0,get:()=>t[e]})});
2
+ //# sourceMappingURL=index.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.cjs","sources":[],"sourcesContent":[],"names":[],"mappings":""}
@@ -0,0 +1,8 @@
1
+ /**
2
+ * The React bindings, re-exported.
3
+ *
4
+ * Client-side usage in a Next.js app is exactly @pontive/pontkit-react; what
5
+ * this package adds is the server-side auth proxy, which lives under the
6
+ * `/server` subpath because it must never reach the browser bundle.
7
+ */
8
+ export * from '@pontive/pontkit-react';
package/dist/index.js ADDED
@@ -0,0 +1,2 @@
1
+ export * from "@pontive/pontkit-react";
2
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sources":[],"sourcesContent":[],"names":[],"mappings":";"}
@@ -0,0 +1,30 @@
1
+ /**
2
+ * What a proxy is allowed to change about the headers passing through it.
3
+ *
4
+ * Almost nothing, is the answer, and the exceptions are all cases where passing
5
+ * a header on unchanged would be a lie about the hop it describes.
6
+ */
7
+ /**
8
+ * The headers to send upstream, given the ones that arrived.
9
+ *
10
+ * `cookie` is passed through untouched, which is the entire point of the
11
+ * exercise: the browser attached it because the endpoints are on the app's own
12
+ * origin, and this hop is what carries it to the server that can read it.
13
+ */
14
+ export declare function upstreamHeaders(request: Request): Headers;
15
+ /**
16
+ * The headers to send back, given what the auth server answered with.
17
+ *
18
+ * `set-cookie` is the load-bearing one, in two ways. It is copied header by
19
+ * header rather than through the bulk copy, because `new Headers(...)` folds
20
+ * repeated headers into one comma-joined value — and a cookie with an `Expires`
21
+ * date contains a comma, so the fold produces two cookies where the browser can
22
+ * only parse one. That is the classic proxy bug, and it presents as a session
23
+ * that works until the first rotation.
24
+ *
25
+ * And its attributes are passed on untouched. The server wrote the cookie with
26
+ * no `Domain`, which makes it host-only — on THIS origin, because that is where
27
+ * the browser thinks it came from. Rewriting or scoping it here would undo the
28
+ * only thing this proxy exists to achieve.
29
+ */
30
+ export declare function downstreamHeaders(response: Response): Headers;
@@ -0,0 +1,25 @@
1
+ /**
2
+ * Proxying the auth endpoints under an app's own origin.
3
+ *
4
+ * Three integrations, one idea. Whichever is used, the SDK is then pointed at
5
+ * the base path rather than the auth hostname:
6
+ *
7
+ * ```ts
8
+ * <Provider env={{ domain: "/__auth", appId, ... }} />
9
+ * ```
10
+ *
11
+ * - `viteAuthProxy` — a Vite dev server, which has a proxy of its own.
12
+ * - `authProxyRewrites` — Next.js, through `next.config.js` rewrites.
13
+ * - `createAuthProxy` — anywhere `Request`/`Response` run: Next middleware and
14
+ * route handlers, Cloudflare Workers, Hono, Deno, Bun.
15
+ *
16
+ * A static host with no runtime — GitHub Pages, plain S3 — can do none of them,
17
+ * and needs the auth server on a hostname of its own instead.
18
+ */
19
+ export { createAuthProxy } from './proxy';
20
+ export type { AuthProxy, AuthProxyOptions } from './proxy';
21
+ export { viteAuthProxy } from './vite';
22
+ export type { ViteAuthProxyOptions, ViteProxyEntry } from './vite';
23
+ export { authProxyRewrites } from './next';
24
+ export type { AuthProxyRewritesOptions, NextRewrite } from './next';
25
+ export { DEFAULT_BASE_PATH, DEFAULT_FORWARDED_PATHS } from './target';
@@ -0,0 +1,25 @@
1
+ export interface NextRewrite {
2
+ source: string;
3
+ destination: string;
4
+ }
5
+ export interface AuthProxyRewritesOptions {
6
+ authHost: string;
7
+ basePath?: string;
8
+ paths?: readonly string[];
9
+ }
10
+ /**
11
+ * The auth endpoints, proxied by Next's own rewrites.
12
+ *
13
+ * ```js
14
+ * // next.config.js
15
+ * rewrites: async () => authProxyRewrites({ authHost: process.env.SB_AUTH_DOMAIN })
16
+ * ```
17
+ *
18
+ * The cheapest Next integration there is, and the one to reach for first: a
19
+ * rewrite to an external destination sends the destination's Host upstream,
20
+ * which is exactly what the auth server needs, so there is no header to
21
+ * configure and nothing to get wrong. Middleware (`createAuthProxy`) is for when
22
+ * something else has to happen on the way through — a client IP to resolve, a
23
+ * header to add, a path to decide at runtime.
24
+ */
25
+ export declare function authProxyRewrites(options: AuthProxyRewritesOptions): NextRewrite[];
@@ -0,0 +1,54 @@
1
+ export interface AuthProxyOptions {
2
+ /**
3
+ * The auth server, as a hostname or an origin — the value the SDK's `domain`
4
+ * used to hold, e.g. `tenant.idp.us.pontive.app`.
5
+ */
6
+ authHost: string;
7
+ /**
8
+ * Where the endpoints hang off this app's origin. Defaults to `/__auth`; `"/"`
9
+ * mounts them at the root, which is the shape a dev server uses.
10
+ *
11
+ * Whatever this is, it is also what the SDK's `domain` must be set to.
12
+ */
13
+ basePath?: string;
14
+ /** Which upstream prefixes may be forwarded. Defaults to the SDK's surface. */
15
+ paths?: readonly string[];
16
+ /** The fetch to send upstream requests with. For tests and custom agents. */
17
+ fetch?: typeof globalThis.fetch;
18
+ }
19
+ export interface AuthProxy {
20
+ /** Whether this request is one the proxy should carry. */
21
+ handles(request: Request): boolean;
22
+ /** Carries it, and answers with whatever the auth server said. */
23
+ forward(request: Request): Promise<Response>;
24
+ /** The normalised base path, for building the SDK's `domain`. */
25
+ readonly basePath: string;
26
+ /** The upstream origin. */
27
+ readonly origin: string;
28
+ /** Path patterns for a framework that routes by them, e.g. Next's matcher. */
29
+ readonly matcher: string[];
30
+ }
31
+ /**
32
+ * A reverse proxy for the auth endpoints, as a Web-standard request handler.
33
+ *
34
+ * Why an app would run one: a browser only treats a cookie as first-party when
35
+ * it comes from the origin the page is on. An app on `app.acme.com` talking to
36
+ * an auth server on another hostname is cross-site, so the refresh cookie is a
37
+ * third-party cookie — blocked outright in Safari, and on borrowed time
38
+ * everywhere else. Proxying the endpoints under the app's own origin makes them
39
+ * first-party, and `SameSite=Lax` holds with no DNS record, no certificate, and
40
+ * nothing to verify.
41
+ *
42
+ * What it deliberately does NOT do is rewrite anything. It does not touch the
43
+ * cookies in either direction, does not follow redirects, and does not present
44
+ * the app's own Host upstream — the auth server resolves which project it is
45
+ * answering as from Host, so the canonical one has to arrive intact. That is
46
+ * also why this needs no secret: unlike Clerk's equivalent, whose Frontend API
47
+ * is multi-tenant on one hostname and must be told which instance to be, the
48
+ * hostname here already says it.
49
+ *
50
+ * Runs anywhere `Request` and `Response` do: Next.js middleware and route
51
+ * handlers, Cloudflare Workers, Hono, Deno, Bun. A Vite dev server does not need
52
+ * it — see `viteAuthProxy`, which configures Vite's own proxy instead.
53
+ */
54
+ export declare function createAuthProxy(options: AuthProxyOptions): AuthProxy;
@@ -0,0 +1,67 @@
1
+ /**
2
+ * Where a proxied request is sent, and which requests are sent at all.
3
+ *
4
+ * Deliberately not shared with `resolveAuthBaseUrl` in the SDK, which answers a
5
+ * different question. That one resolves what the BROWSER should call and its
6
+ * most useful answer — a bare path like `/__auth` — is meaningless here: a
7
+ * proxy runs on a server, where there is no page origin for a path to be
8
+ * relative to. Sharing them would mean one function with a mode flag, and the
9
+ * mode that is wrong in either direction is silent.
10
+ */
11
+ /**
12
+ * The endpoints an app-level proxy has to carry, and the reason the list is
13
+ * short.
14
+ *
15
+ * These are the requests the browser makes with `fetch` — the auth flow, the
16
+ * token endpoint, userinfo, logout, branding CSS. They are the ones that need
17
+ * to be same-origin, because they are the ones carrying cookies under
18
+ * `SameSite=Lax`.
19
+ *
20
+ * Everything else on the auth server is a top-level navigation — `/authorize`,
21
+ * the hosted sign-in page, `/end_session` as a redirect — and a `Lax` cookie is
22
+ * sent on those already, whatever origin they are served from. Proxying them
23
+ * would not help, and it would break: the authorization server builds those
24
+ * URLs absolute, on its own hostname, so the browser leaves the proxy at the
25
+ * first redirect anyway.
26
+ *
27
+ * The two prefixes are the same pair the dev-server proxy uses (auth-api,
28
+ * `docs/auth-domains-and-token-storage.md` §3). That is not a coincidence to be
29
+ * tidied away: local development against a shared sandbox domain is the same
30
+ * cross-site problem this solves in production, and the two configurations
31
+ * being identical is what makes the local one a rehearsal.
32
+ */
33
+ export declare const DEFAULT_FORWARDED_PATHS: readonly ["/auth/v1", "/oauth2"];
34
+ /**
35
+ * Where the endpoints hang off the app's own origin.
36
+ *
37
+ * `__`-prefixed by convention — Clerk uses `/__clerk`, Firebase `/__/auth` —
38
+ * because it has to be a path no real route of the app will ever want.
39
+ */
40
+ export declare const DEFAULT_BASE_PATH = "/__auth";
41
+ /**
42
+ * The auth server, as an origin.
43
+ *
44
+ * Accepts `tenant.idp.us.pontive.app` or `https://tenant.idp.us.pontive.app`,
45
+ * and nothing with a path: the upstream path comes from the incoming request,
46
+ * and a base path here would be silently prepended to endpoints the auth server
47
+ * does not serve.
48
+ *
49
+ * `http://` is inferred for loopback only, and accepted only there. A proxy is
50
+ * the one hop a refresh token cannot be carried over in the clear — it is the
51
+ * hop that exists precisely so the cookie is first-party — and the failure is
52
+ * invisible from the browser, which sees its own `https://` origin either way.
53
+ */
54
+ export declare function authOrigin(authHost: string): string;
55
+ /**
56
+ * A base path with a leading slash and no trailing one, so joining is
57
+ * unambiguous.
58
+ *
59
+ * `"/"` normalises to `""`, which mounts the endpoints at the origin root —
60
+ * `/auth/v1/...` and `/oauth2/...` where the app itself is served. That is the
61
+ * shape a Vite dev server has always used, and it stays available because in
62
+ * development the app owns the whole origin and there is nothing to collide
63
+ * with. A deployed app usually does not, which is what the prefix is for.
64
+ */
65
+ export declare function normaliseBasePath(basePath: string): string;
66
+ /** Whether `pathname` is `prefix` itself or something under it. */
67
+ export declare function isUnder(pathname: string, prefix: string): boolean;
@@ -0,0 +1,38 @@
1
+ /**
2
+ * The shape of one entry in Vite's `server.proxy`.
3
+ *
4
+ * Declared here rather than imported from Vite so that nothing which imports
5
+ * this module needs Vite installed, and so the published types do not depend on
6
+ * a particular version of it. It is structural: Vite accepts this object.
7
+ */
8
+ export interface ViteProxyEntry {
9
+ target: string;
10
+ changeOrigin: boolean;
11
+ rewrite: (path: string) => string;
12
+ }
13
+ export interface ViteAuthProxyOptions {
14
+ authHost: string;
15
+ basePath?: string;
16
+ paths?: readonly string[];
17
+ }
18
+ /**
19
+ * The auth endpoints, proxied through a Vite dev server.
20
+ *
21
+ * ```ts
22
+ * // vite.config.ts
23
+ * server: { proxy: viteAuthProxy({ authHost: env.VITE_SB_AUTH_DOMAIN }) }
24
+ * ```
25
+ *
26
+ * Vite already has a proxy; what it does not have is the knowledge of which
27
+ * paths to carry and what to do with Host, and both of those are easy to get
28
+ * wrong in ways that fail silently. So this is a config generator rather than a
29
+ * request handler — `createAuthProxy` is for runtimes that have no proxy of
30
+ * their own.
31
+ *
32
+ * Worth doing even where the browser would tolerate the cross-site setup,
33
+ * because it is the same topology production runs on: a dev server that proxies
34
+ * is rehearsing the deployment, and a dev server that does not is testing a
35
+ * configuration no user will ever have. It is also the only way an embedded
36
+ * sign-in flow works in Safari, which blocks third-party cookies outright.
37
+ */
38
+ export declare function viteAuthProxy(options: ViteAuthProxyOptions): Record<string, ViteProxyEntry>;
@@ -0,0 +1,2 @@
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const w=["connection","keep-alive","proxy-authenticate","proxy-authorization","te","trailer","transfer-encoding","upgrade"];function g(e){const t=new Headers(e.headers);for(const a of w)t.delete(a);t.delete("host"),t.delete("content-length"),t.delete("accept-encoding");const r=new URL(e.url);return t.has("x-forwarded-proto")||t.set("x-forwarded-proto",r.protocol.replace(":","")),t.has("x-forwarded-host")||t.set("x-forwarded-host",r.host),t.set("x-forwarded-for",y(e)),t}function y(e){const t=e.headers.get("x-forwarded-for"),r=e.headers.get("x-real-ip");return t||(r??"")}function $(e){const t=new Headers;e.headers.forEach((r,a)=>{a.toLowerCase()!=="set-cookie"&&t.set(a,r)});for(const r of w)t.delete(r);t.delete("content-encoding"),t.delete("content-length");for(const r of P(e.headers))t.append("set-cookie",r);return t}function P(e){if(typeof e.getSetCookie=="function")return e.getSetCookie();const t=e.get("set-cookie");return t?[t]:[]}const u=["/auth/v1","/oauth2"],d="/__auth";function f(e){const t=(e??"").trim();if(!t)throw new TypeError("authHost is required");const r=/^(localhost|127\.0\.0\.1|\[::1\])(:\d+)?$/i.test(t.replace(/^https?:\/\//i,"").split("/")[0]),a=/^https?:\/\//i.test(t)?"":`${r?"http":"https"}://`;let n;try{n=new URL(`${a}${t}`)}catch{throw new TypeError(`authHost "${t}" is not a hostname or an origin`)}if(n.pathname!=="/"||n.search||n.hash)throw new TypeError(`authHost "${t}" must be a bare origin — the path comes from the request being proxied`);if(n.protocol!=="https:"&&!r)throw new TypeError(`authHost "${t}" must be https outside loopback`);return n.origin}function l(e){const t=(e??"").trim().replace(/\/+$/,"");if(t==="")return"";if(!t.startsWith("/"))throw new TypeError(`basePath "${e}" must start with "/"`);return t}function p(e,t){return e===t||e.startsWith(`${t}/`)}function x(e){const t=f(e.authHost),r=l(e.basePath??d),a=e.paths??u,n=e.fetch??globalThis.fetch;function c(o){const h=new URL(o.url);if(!p(h.pathname,r))return null;const i=h.pathname.slice(r.length)||"/",s=new URL(`${i}${h.search}`,t);return s.origin!==t?null:a.some(m=>p(s.pathname,m))?s:null}return{basePath:r,origin:t,matcher:a.map(o=>`${r}${o}/:path*`),handles(o){return c(o)!==null},async forward(o){const h=c(o);if(!h)return new Response("Not Found",{status:404});const i=o.method==="GET"||o.method==="HEAD"?void 0:o.body;try{const s=await n(h,{method:o.method,headers:g(o),body:i,redirect:"manual",...i?{duplex:"half"}:{}});return new Response(s.body,{status:s.status,statusText:s.statusText,headers:$(s)})}catch(s){return console.warn(`Could not reach the auth server at ${t}:`,s),new Response("Bad Gateway",{status:502})}}}}function b(e){const t=f(e.authHost),r=l(e.basePath??d),a=e.paths??u,n={};for(const c of a)n[`${r}${c}`]={target:t,changeOrigin:!0,rewrite:o=>r?o.replace(r,""):o};return n}function H(e){const t=f(e.authHost),r=l(e.basePath??d);return(e.paths??u).map(n=>({source:`${r}${n}/:path*`,destination:`${t}${n}/:path*`}))}exports.DEFAULT_BASE_PATH=d;exports.DEFAULT_FORWARDED_PATHS=u;exports.authProxyRewrites=H;exports.createAuthProxy=x;exports.viteAuthProxy=b;
2
+ //# sourceMappingURL=server.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"server.cjs","sources":["../src/server/headers.ts","../src/server/target.ts","../src/server/proxy.ts","../src/server/vite.ts","../src/server/next.ts"],"sourcesContent":["/**\n * What a proxy is allowed to change about the headers passing through it.\n *\n * Almost nothing, is the answer, and the exceptions are all cases where passing\n * a header on unchanged would be a lie about the hop it describes.\n */\n\n/**\n * Headers that describe the connection rather than the message (RFC 9110 §7.6.1).\n *\n * They belong to the hop they arrived on and mean nothing on the next one. The\n * one that actually bites is `transfer-encoding`: forwarded onto a body the\n * runtime has already dechunked, it describes an encoding that is no longer\n * there and the response is truncated or rejected.\n */\nconst HOP_BY_HOP = [\n \"connection\",\n \"keep-alive\",\n \"proxy-authenticate\",\n \"proxy-authorization\",\n \"te\",\n \"trailer\",\n \"transfer-encoding\",\n \"upgrade\",\n];\n\n/**\n * The headers to send upstream, given the ones that arrived.\n *\n * `cookie` is passed through untouched, which is the entire point of the\n * exercise: the browser attached it because the endpoints are on the app's own\n * origin, and this hop is what carries it to the server that can read it.\n */\nexport function upstreamHeaders(request: Request): Headers {\n const headers = new Headers(request.headers);\n\n for (const name of HOP_BY_HOP) {\n headers.delete(name);\n }\n\n // Set from the upstream URL by the runtime. Carrying the app's own Host would\n // be worse than useless: the authorization server resolves which project it is\n // answering as from Host, so the app's hostname reaches it as \"no such\n // project\" — a CORS refusal and an empty issuer, with nothing saying why.\n headers.delete(\"host\");\n\n // Recomputed from the body that is actually sent.\n headers.delete(\"content-length\");\n\n // Left to the runtime. Requesting an encoding here and then handing the caller\n // a body the runtime has already decoded is how a proxy ends up serving\n // gzip-labelled plaintext.\n headers.delete(\"accept-encoding\");\n\n const url = new URL(request.url);\n\n // The scheme the BROWSER used, which is the only one that matters to a cookie.\n // auth-api reads this and defaults to https when it is missing, so the case it\n // has to be right for is local development over http — where getting it wrong\n // mints an http:// issuer and every __Host- cookie is dropped on the floor.\n if (!headers.has(\"x-forwarded-proto\")) {\n headers.set(\"x-forwarded-proto\", url.protocol.replace(\":\", \"\"));\n }\n\n // Where the browser thinks it is. Nothing upstream routes on it — the point of\n // this proxy is that Host is the canonical auth host — but it is what makes a\n // proxied request identifiable in a log.\n if (!headers.has(\"x-forwarded-host\")) {\n headers.set(\"x-forwarded-host\", url.host);\n }\n\n headers.set(\"x-forwarded-for\", forwardedFor(request));\n\n return headers;\n}\n\n/**\n * The client IP chain.\n *\n * Passed through rather than replaced. A proxy that sets this to its immediate\n * peer forwards the address of whatever CDN or load balancer sits in front of\n * it — so rate limiting and audit logs upstream see one address for every user,\n * which is worse than the header being absent. Clerk documents the same trap.\n *\n * Where nothing has set it, there is nothing honest to put: a Web `Request`\n * carries no socket address, and inventing one is the failure above. Callers\n * that can see the peer pass it in with `clientIp`.\n */\nfunction forwardedFor(request: Request): string {\n const chain = request.headers.get(\"x-forwarded-for\");\n const ip = request.headers.get(\"x-real-ip\");\n\n if (chain) {\n return chain;\n }\n\n return ip ?? \"\";\n}\n\n/**\n * The headers to send back, given what the auth server answered with.\n *\n * `set-cookie` is the load-bearing one, in two ways. It is copied header by\n * header rather than through the bulk copy, because `new Headers(...)` folds\n * repeated headers into one comma-joined value — and a cookie with an `Expires`\n * date contains a comma, so the fold produces two cookies where the browser can\n * only parse one. That is the classic proxy bug, and it presents as a session\n * that works until the first rotation.\n *\n * And its attributes are passed on untouched. The server wrote the cookie with\n * no `Domain`, which makes it host-only — on THIS origin, because that is where\n * the browser thinks it came from. Rewriting or scoping it here would undo the\n * only thing this proxy exists to achieve.\n */\nexport function downstreamHeaders(response: Response): Headers {\n const headers = new Headers();\n\n // forEach rather than iteration, because this package's `lib` does not include\n // DOM.Iterable. It walks the same entries, and folds repeated headers the same\n // way — which is why set-cookie is skipped here and appended below.\n response.headers.forEach((value, name) => {\n if (name.toLowerCase() !== \"set-cookie\") {\n headers.set(name, value);\n }\n });\n\n for (const name of HOP_BY_HOP) {\n headers.delete(name);\n }\n\n // The body handed on has already been decoded, so both of these now describe\n // something that is not true of it.\n headers.delete(\"content-encoding\");\n headers.delete(\"content-length\");\n\n for (const cookie of setCookies(response.headers)) {\n headers.append(\"set-cookie\", cookie);\n }\n\n return headers;\n}\n\n/**\n * Every `set-cookie` as its own string.\n *\n * `getSetCookie` is the only API that can express this — everything else on\n * `Headers` joins repeated values — and it is present on every runtime this\n * proxy targets. The fallback is for the ones that are not: one joined value is\n * wrong for multiple cookies, but it is what the header already said, and the\n * common case of a single cookie survives it.\n */\nfunction setCookies(headers: Headers): string[] {\n if (typeof headers.getSetCookie === \"function\") {\n return headers.getSetCookie();\n }\n\n const joined = headers.get(\"set-cookie\");\n\n return joined ? [joined] : [];\n}\n","/**\n * Where a proxied request is sent, and which requests are sent at all.\n *\n * Deliberately not shared with `resolveAuthBaseUrl` in the SDK, which answers a\n * different question. That one resolves what the BROWSER should call and its\n * most useful answer — a bare path like `/__auth` — is meaningless here: a\n * proxy runs on a server, where there is no page origin for a path to be\n * relative to. Sharing them would mean one function with a mode flag, and the\n * mode that is wrong in either direction is silent.\n */\n\n/**\n * The endpoints an app-level proxy has to carry, and the reason the list is\n * short.\n *\n * These are the requests the browser makes with `fetch` — the auth flow, the\n * token endpoint, userinfo, logout, branding CSS. They are the ones that need\n * to be same-origin, because they are the ones carrying cookies under\n * `SameSite=Lax`.\n *\n * Everything else on the auth server is a top-level navigation — `/authorize`,\n * the hosted sign-in page, `/end_session` as a redirect — and a `Lax` cookie is\n * sent on those already, whatever origin they are served from. Proxying them\n * would not help, and it would break: the authorization server builds those\n * URLs absolute, on its own hostname, so the browser leaves the proxy at the\n * first redirect anyway.\n *\n * The two prefixes are the same pair the dev-server proxy uses (auth-api,\n * `docs/auth-domains-and-token-storage.md` §3). That is not a coincidence to be\n * tidied away: local development against a shared sandbox domain is the same\n * cross-site problem this solves in production, and the two configurations\n * being identical is what makes the local one a rehearsal.\n */\nexport const DEFAULT_FORWARDED_PATHS = [\"/auth/v1\", \"/oauth2\"] as const;\n\n/**\n * Where the endpoints hang off the app's own origin.\n *\n * `__`-prefixed by convention — Clerk uses `/__clerk`, Firebase `/__/auth` —\n * because it has to be a path no real route of the app will ever want.\n */\nexport const DEFAULT_BASE_PATH = \"/__auth\";\n\n/**\n * The auth server, as an origin.\n *\n * Accepts `tenant.idp.us.pontive.app` or `https://tenant.idp.us.pontive.app`,\n * and nothing with a path: the upstream path comes from the incoming request,\n * and a base path here would be silently prepended to endpoints the auth server\n * does not serve.\n *\n * `http://` is inferred for loopback only, and accepted only there. A proxy is\n * the one hop a refresh token cannot be carried over in the clear — it is the\n * hop that exists precisely so the cookie is first-party — and the failure is\n * invisible from the browser, which sees its own `https://` origin either way.\n */\nexport function authOrigin(authHost: string): string {\n const configured = (authHost ?? \"\").trim();\n\n if (!configured) {\n throw new TypeError(\"authHost is required\");\n }\n\n const loopback = /^(localhost|127\\.0\\.0\\.1|\\[::1\\])(:\\d+)?$/i.test(\n configured.replace(/^https?:\\/\\//i, \"\").split(\"/\")[0],\n );\n\n const scheme = /^https?:\\/\\//i.test(configured) ? \"\" : `${loopback ? \"http\" : \"https\"}://`;\n\n let url: URL;\n try {\n url = new URL(`${scheme}${configured}`);\n } catch {\n throw new TypeError(`authHost \"${configured}\" is not a hostname or an origin`);\n }\n\n if (url.pathname !== \"/\" || url.search || url.hash) {\n throw new TypeError(\n `authHost \"${configured}\" must be a bare origin — the path comes from the request being proxied`,\n );\n }\n\n if (url.protocol !== \"https:\" && !loopback) {\n throw new TypeError(`authHost \"${configured}\" must be https outside loopback`);\n }\n\n return url.origin;\n}\n\n/**\n * A base path with a leading slash and no trailing one, so joining is\n * unambiguous.\n *\n * `\"/\"` normalises to `\"\"`, which mounts the endpoints at the origin root —\n * `/auth/v1/...` and `/oauth2/...` where the app itself is served. That is the\n * shape a Vite dev server has always used, and it stays available because in\n * development the app owns the whole origin and there is nothing to collide\n * with. A deployed app usually does not, which is what the prefix is for.\n */\nexport function normaliseBasePath(basePath: string): string {\n const trimmed = (basePath ?? \"\").trim().replace(/\\/+$/, \"\");\n\n if (trimmed === \"\") {\n return \"\";\n }\n\n if (!trimmed.startsWith(\"/\")) {\n throw new TypeError(`basePath \"${basePath}\" must start with \"/\"`);\n }\n\n return trimmed;\n}\n\n/** Whether `pathname` is `prefix` itself or something under it. */\nexport function isUnder(pathname: string, prefix: string): boolean {\n return pathname === prefix || pathname.startsWith(`${prefix}/`);\n}\n","import { downstreamHeaders, upstreamHeaders } from \"./headers\";\nimport {\n DEFAULT_BASE_PATH,\n DEFAULT_FORWARDED_PATHS,\n authOrigin,\n isUnder,\n normaliseBasePath,\n} from \"./target\";\n\nexport interface AuthProxyOptions {\n /**\n * The auth server, as a hostname or an origin — the value the SDK's `domain`\n * used to hold, e.g. `tenant.idp.us.pontive.app`.\n */\n authHost: string;\n /**\n * Where the endpoints hang off this app's origin. Defaults to `/__auth`; `\"/\"`\n * mounts them at the root, which is the shape a dev server uses.\n *\n * Whatever this is, it is also what the SDK's `domain` must be set to.\n */\n basePath?: string;\n /** Which upstream prefixes may be forwarded. Defaults to the SDK's surface. */\n paths?: readonly string[];\n /** The fetch to send upstream requests with. For tests and custom agents. */\n fetch?: typeof globalThis.fetch;\n}\n\nexport interface AuthProxy {\n /** Whether this request is one the proxy should carry. */\n handles(request: Request): boolean;\n /** Carries it, and answers with whatever the auth server said. */\n forward(request: Request): Promise<Response>;\n /** The normalised base path, for building the SDK's `domain`. */\n readonly basePath: string;\n /** The upstream origin. */\n readonly origin: string;\n /** Path patterns for a framework that routes by them, e.g. Next's matcher. */\n readonly matcher: string[];\n}\n\n/**\n * A reverse proxy for the auth endpoints, as a Web-standard request handler.\n *\n * Why an app would run one: a browser only treats a cookie as first-party when\n * it comes from the origin the page is on. An app on `app.acme.com` talking to\n * an auth server on another hostname is cross-site, so the refresh cookie is a\n * third-party cookie — blocked outright in Safari, and on borrowed time\n * everywhere else. Proxying the endpoints under the app's own origin makes them\n * first-party, and `SameSite=Lax` holds with no DNS record, no certificate, and\n * nothing to verify.\n *\n * What it deliberately does NOT do is rewrite anything. It does not touch the\n * cookies in either direction, does not follow redirects, and does not present\n * the app's own Host upstream — the auth server resolves which project it is\n * answering as from Host, so the canonical one has to arrive intact. That is\n * also why this needs no secret: unlike Clerk's equivalent, whose Frontend API\n * is multi-tenant on one hostname and must be told which instance to be, the\n * hostname here already says it.\n *\n * Runs anywhere `Request` and `Response` do: Next.js middleware and route\n * handlers, Cloudflare Workers, Hono, Deno, Bun. A Vite dev server does not need\n * it — see `viteAuthProxy`, which configures Vite's own proxy instead.\n */\nexport function createAuthProxy(options: AuthProxyOptions): AuthProxy {\n const origin = authOrigin(options.authHost);\n const basePath = normaliseBasePath(options.basePath ?? DEFAULT_BASE_PATH);\n const paths = options.paths ?? DEFAULT_FORWARDED_PATHS;\n const send = options.fetch ?? globalThis.fetch;\n\n /**\n * The upstream URL, or null when this is not a request to carry.\n *\n * Resolved through `URL` before the prefix check, not after, so a path that\n * climbs out of the base — `/__auth/../admin` — is tested as what it actually\n * addresses rather than as what it looks like. It cannot leave the origin;\n * this is what stops it reaching a path the caller did not open up.\n */\n function upstreamFor(request: Request): URL | null {\n const url = new URL(request.url);\n\n if (!isUnder(url.pathname, basePath)) {\n return null;\n }\n\n const rest = url.pathname.slice(basePath.length) || \"/\";\n const upstream = new URL(`${rest}${url.search}`, origin);\n\n if (upstream.origin !== origin) {\n return null;\n }\n\n return paths.some((prefix) => isUnder(upstream.pathname, prefix)) ? upstream : null;\n }\n\n return {\n basePath,\n origin,\n\n matcher: paths.map((prefix) => `${basePath}${prefix}/:path*`),\n\n handles(request: Request): boolean {\n return upstreamFor(request) !== null;\n },\n\n async forward(request: Request): Promise<Response> {\n const upstream = upstreamFor(request);\n\n if (!upstream) {\n // The caller routed something here that this proxy does not carry.\n // Answered rather than passed through, because passing it through would\n // mean the app's own router handling a URL under a prefix it has\n // otherwise given away.\n return new Response(\"Not Found\", { status: 404 });\n }\n\n // A GET or HEAD has no body to stream, and `duplex` is required by the\n // fetch spec for the ones that do.\n const body = request.method === \"GET\" || request.method === \"HEAD\" ? undefined : request.body;\n\n try {\n const response = await send(upstream, {\n method: request.method,\n headers: upstreamHeaders(request),\n body,\n // Passed to the browser as-is. Followed here, a 302 from /authorize\n // would be resolved server-side and the browser would never see the\n // navigation it is supposed to make.\n redirect: \"manual\",\n ...(body ? { duplex: \"half\" } : {}),\n } as RequestInit);\n\n return new Response(response.body, {\n status: response.status,\n statusText: response.statusText,\n headers: downstreamHeaders(response),\n });\n } catch (error) {\n // The auth server is unreachable from here. 502 rather than 500: the\n // failure is upstream, and the distinction is the first thing anyone\n // debugging a proxy wants to know.\n console.warn(`Could not reach the auth server at ${origin}:`, error);\n\n return new Response(\"Bad Gateway\", { status: 502 });\n }\n },\n };\n}\n","import {\n DEFAULT_BASE_PATH,\n DEFAULT_FORWARDED_PATHS,\n authOrigin,\n normaliseBasePath,\n} from \"./target\";\n\n/**\n * The shape of one entry in Vite's `server.proxy`.\n *\n * Declared here rather than imported from Vite so that nothing which imports\n * this module needs Vite installed, and so the published types do not depend on\n * a particular version of it. It is structural: Vite accepts this object.\n */\nexport interface ViteProxyEntry {\n target: string;\n changeOrigin: boolean;\n rewrite: (path: string) => string;\n}\n\nexport interface ViteAuthProxyOptions {\n authHost: string;\n basePath?: string;\n paths?: readonly string[];\n}\n\n/**\n * The auth endpoints, proxied through a Vite dev server.\n *\n * ```ts\n * // vite.config.ts\n * server: { proxy: viteAuthProxy({ authHost: env.VITE_SB_AUTH_DOMAIN }) }\n * ```\n *\n * Vite already has a proxy; what it does not have is the knowledge of which\n * paths to carry and what to do with Host, and both of those are easy to get\n * wrong in ways that fail silently. So this is a config generator rather than a\n * request handler — `createAuthProxy` is for runtimes that have no proxy of\n * their own.\n *\n * Worth doing even where the browser would tolerate the cross-site setup,\n * because it is the same topology production runs on: a dev server that proxies\n * is rehearsing the deployment, and a dev server that does not is testing a\n * configuration no user will ever have. It is also the only way an embedded\n * sign-in flow works in Safari, which blocks third-party cookies outright.\n */\nexport function viteAuthProxy(\n options: ViteAuthProxyOptions,\n): Record<string, ViteProxyEntry> {\n const target = authOrigin(options.authHost);\n const basePath = normaliseBasePath(options.basePath ?? DEFAULT_BASE_PATH);\n const paths = options.paths ?? DEFAULT_FORWARDED_PATHS;\n\n const proxy: Record<string, ViteProxyEntry> = {};\n\n for (const prefix of paths) {\n proxy[`${basePath}${prefix}`] = {\n target,\n // The single most important line, and the one a hand-written config\n // leaves out. Without it the auth server is asked to answer as\n // `localhost:5173` — a Host it has no project for — and the reply is a\n // CORS refusal and an empty issuer rather than anything that says so.\n changeOrigin: true,\n // Only the base path comes off. The prefix below it is the path the auth\n // server actually serves.\n rewrite: (path: string) => (basePath ? path.replace(basePath, \"\") : path),\n };\n }\n\n return proxy;\n}\n","import {\n DEFAULT_BASE_PATH,\n DEFAULT_FORWARDED_PATHS,\n authOrigin,\n normaliseBasePath,\n} from \"./target\";\n\nexport interface NextRewrite {\n source: string;\n destination: string;\n}\n\nexport interface AuthProxyRewritesOptions {\n authHost: string;\n basePath?: string;\n paths?: readonly string[];\n}\n\n/**\n * The auth endpoints, proxied by Next's own rewrites.\n *\n * ```js\n * // next.config.js\n * rewrites: async () => authProxyRewrites({ authHost: process.env.SB_AUTH_DOMAIN })\n * ```\n *\n * The cheapest Next integration there is, and the one to reach for first: a\n * rewrite to an external destination sends the destination's Host upstream,\n * which is exactly what the auth server needs, so there is no header to\n * configure and nothing to get wrong. Middleware (`createAuthProxy`) is for when\n * something else has to happen on the way through — a client IP to resolve, a\n * header to add, a path to decide at runtime.\n */\nexport function authProxyRewrites(options: AuthProxyRewritesOptions): NextRewrite[] {\n const origin = authOrigin(options.authHost);\n const basePath = normaliseBasePath(options.basePath ?? DEFAULT_BASE_PATH);\n const paths = options.paths ?? DEFAULT_FORWARDED_PATHS;\n\n return paths.map((prefix) => ({\n source: `${basePath}${prefix}/:path*`,\n destination: `${origin}${prefix}/:path*`,\n }));\n}\n"],"names":["HOP_BY_HOP","upstreamHeaders","request","headers","name","url","forwardedFor","chain","ip","downstreamHeaders","response","value","cookie","setCookies","joined","DEFAULT_FORWARDED_PATHS","DEFAULT_BASE_PATH","authOrigin","authHost","configured","loopback","scheme","normaliseBasePath","basePath","trimmed","isUnder","pathname","prefix","createAuthProxy","options","origin","paths","send","upstreamFor","rest","upstream","body","error","viteAuthProxy","target","proxy","path","authProxyRewrites"],"mappings":"gFAeA,MAAMA,EAAa,CACjB,aACA,aACA,qBACA,sBACA,KACA,UACA,oBACA,SACF,EASO,SAASC,EAAgBC,EAA2B,CACzD,MAAMC,EAAU,IAAI,QAAQD,EAAQ,OAAO,EAE3C,UAAWE,KAAQJ,EACjBG,EAAQ,OAAOC,CAAI,EAOrBD,EAAQ,OAAO,MAAM,EAGrBA,EAAQ,OAAO,gBAAgB,EAK/BA,EAAQ,OAAO,iBAAiB,EAEhC,MAAME,EAAM,IAAI,IAAIH,EAAQ,GAAG,EAM/B,OAAKC,EAAQ,IAAI,mBAAmB,GAClCA,EAAQ,IAAI,oBAAqBE,EAAI,SAAS,QAAQ,IAAK,EAAE,CAAC,EAM3DF,EAAQ,IAAI,kBAAkB,GACjCA,EAAQ,IAAI,mBAAoBE,EAAI,IAAI,EAG1CF,EAAQ,IAAI,kBAAmBG,EAAaJ,CAAO,CAAC,EAE7CC,CACT,CAcA,SAASG,EAAaJ,EAA0B,CAC9C,MAAMK,EAAQL,EAAQ,QAAQ,IAAI,iBAAiB,EAC7CM,EAAKN,EAAQ,QAAQ,IAAI,WAAW,EAE1C,OAAIK,IAIGC,GAAM,GACf,CAiBO,SAASC,EAAkBC,EAA6B,CAC7D,MAAMP,EAAU,IAAI,QAKpBO,EAAS,QAAQ,QAAQ,CAACC,EAAOP,IAAS,CACpCA,EAAK,Y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AQjC,EAAQ,OAChB,QAASD,EAAgBC,CAAO,EAChC,KAAAkC,EAIA,SAAU,SACV,GAAIA,EAAO,CAAE,OAAQ,QAAW,CAAA,CAAC,CACnB,EAEhB,OAAO,IAAI,SAAS1B,EAAS,KAAM,CACjC,OAAQA,EAAS,OACjB,WAAYA,EAAS,WACrB,QAASD,EAAkBC,CAAQ,CAAA,CACpC,CACH,OAAS2B,EAAO,CAId,eAAQ,KAAK,sCAAsCP,CAAM,IAAKO,CAAK,EAE5D,IAAI,SAAS,cAAe,CAAE,OAAQ,IAAK,CACpD,CACF,CAAA,CAEJ,CCrGO,SAASC,EACdT,EACgC,CAChC,MAAMU,EAAStB,EAAWY,EAAQ,QAAQ,EACpCN,EAAWD,EAAkBO,EAAQ,UAAYb,CAAiB,EAClEe,EAAQF,EAAQ,OAASd,EAEzByB,EAAwC,CAAA,EAE9C,UAAWb,KAAUI,EACnBS,EAAM,GAAGjB,CAAQ,GAAGI,CAAM,EAAE,EAAI,CAC9B,OAAAY,EAKA,aAAc,GAGd,QAAUE,GAAkBlB,EAAWkB,EAAK,QAAQlB,EAAU,EAAE,EAAIkB,CAAA,EAIxE,OAAOD,CACT,CCrCO,SAASE,EAAkBb,EAAkD,CAClF,MAAMC,EAASb,EAAWY,EAAQ,QAAQ,EACpCN,EAAWD,EAAkBO,EAAQ,UAAYb,CAAiB,EAGxE,OAFca,EAAQ,OAASd,GAElB,IAAKY,IAAY,CAC5B,OAAQ,GAAGJ,CAAQ,GAAGI,CAAM,UAC5B,YAAa,GAAGG,CAAM,GAAGH,CAAM,SAAA,EAC/B,CACJ"}
package/dist/server.js ADDED
@@ -0,0 +1,147 @@
1
+ const w = [
2
+ "connection",
3
+ "keep-alive",
4
+ "proxy-authenticate",
5
+ "proxy-authorization",
6
+ "te",
7
+ "trailer",
8
+ "transfer-encoding",
9
+ "upgrade"
10
+ ];
11
+ function g(e) {
12
+ const t = new Headers(e.headers);
13
+ for (const a of w)
14
+ t.delete(a);
15
+ t.delete("host"), t.delete("content-length"), t.delete("accept-encoding");
16
+ const r = new URL(e.url);
17
+ return t.has("x-forwarded-proto") || t.set("x-forwarded-proto", r.protocol.replace(":", "")), t.has("x-forwarded-host") || t.set("x-forwarded-host", r.host), t.set("x-forwarded-for", $(e)), t;
18
+ }
19
+ function $(e) {
20
+ const t = e.headers.get("x-forwarded-for"), r = e.headers.get("x-real-ip");
21
+ return t || (r ?? "");
22
+ }
23
+ function y(e) {
24
+ const t = new Headers();
25
+ e.headers.forEach((r, a) => {
26
+ a.toLowerCase() !== "set-cookie" && t.set(a, r);
27
+ });
28
+ for (const r of w)
29
+ t.delete(r);
30
+ t.delete("content-encoding"), t.delete("content-length");
31
+ for (const r of x(e.headers))
32
+ t.append("set-cookie", r);
33
+ return t;
34
+ }
35
+ function x(e) {
36
+ if (typeof e.getSetCookie == "function")
37
+ return e.getSetCookie();
38
+ const t = e.get("set-cookie");
39
+ return t ? [t] : [];
40
+ }
41
+ const u = ["/auth/v1", "/oauth2"], d = "/__auth";
42
+ function f(e) {
43
+ const t = (e ?? "").trim();
44
+ if (!t)
45
+ throw new TypeError("authHost is required");
46
+ const r = /^(localhost|127\.0\.0\.1|\[::1\])(:\d+)?$/i.test(
47
+ t.replace(/^https?:\/\//i, "").split("/")[0]
48
+ ), a = /^https?:\/\//i.test(t) ? "" : `${r ? "http" : "https"}://`;
49
+ let n;
50
+ try {
51
+ n = new URL(`${a}${t}`);
52
+ } catch {
53
+ throw new TypeError(`authHost "${t}" is not a hostname or an origin`);
54
+ }
55
+ if (n.pathname !== "/" || n.search || n.hash)
56
+ throw new TypeError(
57
+ `authHost "${t}" must be a bare origin — the path comes from the request being proxied`
58
+ );
59
+ if (n.protocol !== "https:" && !r)
60
+ throw new TypeError(`authHost "${t}" must be https outside loopback`);
61
+ return n.origin;
62
+ }
63
+ function p(e) {
64
+ const t = (e ?? "").trim().replace(/\/+$/, "");
65
+ if (t === "")
66
+ return "";
67
+ if (!t.startsWith("/"))
68
+ throw new TypeError(`basePath "${e}" must start with "/"`);
69
+ return t;
70
+ }
71
+ function l(e, t) {
72
+ return e === t || e.startsWith(`${t}/`);
73
+ }
74
+ function b(e) {
75
+ const t = f(e.authHost), r = p(e.basePath ?? d), a = e.paths ?? u, n = e.fetch ?? globalThis.fetch;
76
+ function c(o) {
77
+ const h = new URL(o.url);
78
+ if (!l(h.pathname, r))
79
+ return null;
80
+ const i = h.pathname.slice(r.length) || "/", s = new URL(`${i}${h.search}`, t);
81
+ return s.origin !== t ? null : a.some((m) => l(s.pathname, m)) ? s : null;
82
+ }
83
+ return {
84
+ basePath: r,
85
+ origin: t,
86
+ matcher: a.map((o) => `${r}${o}/:path*`),
87
+ handles(o) {
88
+ return c(o) !== null;
89
+ },
90
+ async forward(o) {
91
+ const h = c(o);
92
+ if (!h)
93
+ return new Response("Not Found", { status: 404 });
94
+ const i = o.method === "GET" || o.method === "HEAD" ? void 0 : o.body;
95
+ try {
96
+ const s = await n(h, {
97
+ method: o.method,
98
+ headers: g(o),
99
+ body: i,
100
+ // Passed to the browser as-is. Followed here, a 302 from /authorize
101
+ // would be resolved server-side and the browser would never see the
102
+ // navigation it is supposed to make.
103
+ redirect: "manual",
104
+ ...i ? { duplex: "half" } : {}
105
+ });
106
+ return new Response(s.body, {
107
+ status: s.status,
108
+ statusText: s.statusText,
109
+ headers: y(s)
110
+ });
111
+ } catch (s) {
112
+ return console.warn(`Could not reach the auth server at ${t}:`, s), new Response("Bad Gateway", { status: 502 });
113
+ }
114
+ }
115
+ };
116
+ }
117
+ function H(e) {
118
+ const t = f(e.authHost), r = p(e.basePath ?? d), a = e.paths ?? u, n = {};
119
+ for (const c of a)
120
+ n[`${r}${c}`] = {
121
+ target: t,
122
+ // The single most important line, and the one a hand-written config
123
+ // leaves out. Without it the auth server is asked to answer as
124
+ // `localhost:5173` — a Host it has no project for — and the reply is a
125
+ // CORS refusal and an empty issuer rather than anything that says so.
126
+ changeOrigin: !0,
127
+ // Only the base path comes off. The prefix below it is the path the auth
128
+ // server actually serves.
129
+ rewrite: (o) => r ? o.replace(r, "") : o
130
+ };
131
+ return n;
132
+ }
133
+ function P(e) {
134
+ const t = f(e.authHost), r = p(e.basePath ?? d);
135
+ return (e.paths ?? u).map((n) => ({
136
+ source: `${r}${n}/:path*`,
137
+ destination: `${t}${n}/:path*`
138
+ }));
139
+ }
140
+ export {
141
+ d as DEFAULT_BASE_PATH,
142
+ u as DEFAULT_FORWARDED_PATHS,
143
+ P as authProxyRewrites,
144
+ b as createAuthProxy,
145
+ H as viteAuthProxy
146
+ };
147
+ //# sourceMappingURL=server.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"server.js","sources":["../src/server/headers.ts","../src/server/target.ts","../src/server/proxy.ts","../src/server/vite.ts","../src/server/next.ts"],"sourcesContent":["/**\n * What a proxy is allowed to change about the headers passing through it.\n *\n * Almost nothing, is the answer, and the exceptions are all cases where passing\n * a header on unchanged would be a lie about the hop it describes.\n */\n\n/**\n * Headers that describe the connection rather than the message (RFC 9110 §7.6.1).\n *\n * They belong to the hop they arrived on and mean nothing on the next one. The\n * one that actually bites is `transfer-encoding`: forwarded onto a body the\n * runtime has already dechunked, it describes an encoding that is no longer\n * there and the response is truncated or rejected.\n */\nconst HOP_BY_HOP = [\n \"connection\",\n \"keep-alive\",\n \"proxy-authenticate\",\n \"proxy-authorization\",\n \"te\",\n \"trailer\",\n \"transfer-encoding\",\n \"upgrade\",\n];\n\n/**\n * The headers to send upstream, given the ones that arrived.\n *\n * `cookie` is passed through untouched, which is the entire point of the\n * exercise: the browser attached it because the endpoints are on the app's own\n * origin, and this hop is what carries it to the server that can read it.\n */\nexport function upstreamHeaders(request: Request): Headers {\n const headers = new Headers(request.headers);\n\n for (const name of HOP_BY_HOP) {\n headers.delete(name);\n }\n\n // Set from the upstream URL by the runtime. Carrying the app's own Host would\n // be worse than useless: the authorization server resolves which project it is\n // answering as from Host, so the app's hostname reaches it as \"no such\n // project\" — a CORS refusal and an empty issuer, with nothing saying why.\n headers.delete(\"host\");\n\n // Recomputed from the body that is actually sent.\n headers.delete(\"content-length\");\n\n // Left to the runtime. Requesting an encoding here and then handing the caller\n // a body the runtime has already decoded is how a proxy ends up serving\n // gzip-labelled plaintext.\n headers.delete(\"accept-encoding\");\n\n const url = new URL(request.url);\n\n // The scheme the BROWSER used, which is the only one that matters to a cookie.\n // auth-api reads this and defaults to https when it is missing, so the case it\n // has to be right for is local development over http — where getting it wrong\n // mints an http:// issuer and every __Host- cookie is dropped on the floor.\n if (!headers.has(\"x-forwarded-proto\")) {\n headers.set(\"x-forwarded-proto\", url.protocol.replace(\":\", \"\"));\n }\n\n // Where the browser thinks it is. Nothing upstream routes on it — the point of\n // this proxy is that Host is the canonical auth host — but it is what makes a\n // proxied request identifiable in a log.\n if (!headers.has(\"x-forwarded-host\")) {\n headers.set(\"x-forwarded-host\", url.host);\n }\n\n headers.set(\"x-forwarded-for\", forwardedFor(request));\n\n return headers;\n}\n\n/**\n * The client IP chain.\n *\n * Passed through rather than replaced. A proxy that sets this to its immediate\n * peer forwards the address of whatever CDN or load balancer sits in front of\n * it — so rate limiting and audit logs upstream see one address for every user,\n * which is worse than the header being absent. Clerk documents the same trap.\n *\n * Where nothing has set it, there is nothing honest to put: a Web `Request`\n * carries no socket address, and inventing one is the failure above. Callers\n * that can see the peer pass it in with `clientIp`.\n */\nfunction forwardedFor(request: Request): string {\n const chain = request.headers.get(\"x-forwarded-for\");\n const ip = request.headers.get(\"x-real-ip\");\n\n if (chain) {\n return chain;\n }\n\n return ip ?? \"\";\n}\n\n/**\n * The headers to send back, given what the auth server answered with.\n *\n * `set-cookie` is the load-bearing one, in two ways. It is copied header by\n * header rather than through the bulk copy, because `new Headers(...)` folds\n * repeated headers into one comma-joined value — and a cookie with an `Expires`\n * date contains a comma, so the fold produces two cookies where the browser can\n * only parse one. That is the classic proxy bug, and it presents as a session\n * that works until the first rotation.\n *\n * And its attributes are passed on untouched. The server wrote the cookie with\n * no `Domain`, which makes it host-only — on THIS origin, because that is where\n * the browser thinks it came from. Rewriting or scoping it here would undo the\n * only thing this proxy exists to achieve.\n */\nexport function downstreamHeaders(response: Response): Headers {\n const headers = new Headers();\n\n // forEach rather than iteration, because this package's `lib` does not include\n // DOM.Iterable. It walks the same entries, and folds repeated headers the same\n // way — which is why set-cookie is skipped here and appended below.\n response.headers.forEach((value, name) => {\n if (name.toLowerCase() !== \"set-cookie\") {\n headers.set(name, value);\n }\n });\n\n for (const name of HOP_BY_HOP) {\n headers.delete(name);\n }\n\n // The body handed on has already been decoded, so both of these now describe\n // something that is not true of it.\n headers.delete(\"content-encoding\");\n headers.delete(\"content-length\");\n\n for (const cookie of setCookies(response.headers)) {\n headers.append(\"set-cookie\", cookie);\n }\n\n return headers;\n}\n\n/**\n * Every `set-cookie` as its own string.\n *\n * `getSetCookie` is the only API that can express this — everything else on\n * `Headers` joins repeated values — and it is present on every runtime this\n * proxy targets. The fallback is for the ones that are not: one joined value is\n * wrong for multiple cookies, but it is what the header already said, and the\n * common case of a single cookie survives it.\n */\nfunction setCookies(headers: Headers): string[] {\n if (typeof headers.getSetCookie === \"function\") {\n return headers.getSetCookie();\n }\n\n const joined = headers.get(\"set-cookie\");\n\n return joined ? [joined] : [];\n}\n","/**\n * Where a proxied request is sent, and which requests are sent at all.\n *\n * Deliberately not shared with `resolveAuthBaseUrl` in the SDK, which answers a\n * different question. That one resolves what the BROWSER should call and its\n * most useful answer — a bare path like `/__auth` — is meaningless here: a\n * proxy runs on a server, where there is no page origin for a path to be\n * relative to. Sharing them would mean one function with a mode flag, and the\n * mode that is wrong in either direction is silent.\n */\n\n/**\n * The endpoints an app-level proxy has to carry, and the reason the list is\n * short.\n *\n * These are the requests the browser makes with `fetch` — the auth flow, the\n * token endpoint, userinfo, logout, branding CSS. They are the ones that need\n * to be same-origin, because they are the ones carrying cookies under\n * `SameSite=Lax`.\n *\n * Everything else on the auth server is a top-level navigation — `/authorize`,\n * the hosted sign-in page, `/end_session` as a redirect — and a `Lax` cookie is\n * sent on those already, whatever origin they are served from. Proxying them\n * would not help, and it would break: the authorization server builds those\n * URLs absolute, on its own hostname, so the browser leaves the proxy at the\n * first redirect anyway.\n *\n * The two prefixes are the same pair the dev-server proxy uses (auth-api,\n * `docs/auth-domains-and-token-storage.md` §3). That is not a coincidence to be\n * tidied away: local development against a shared sandbox domain is the same\n * cross-site problem this solves in production, and the two configurations\n * being identical is what makes the local one a rehearsal.\n */\nexport const DEFAULT_FORWARDED_PATHS = [\"/auth/v1\", \"/oauth2\"] as const;\n\n/**\n * Where the endpoints hang off the app's own origin.\n *\n * `__`-prefixed by convention — Clerk uses `/__clerk`, Firebase `/__/auth` —\n * because it has to be a path no real route of the app will ever want.\n */\nexport const DEFAULT_BASE_PATH = \"/__auth\";\n\n/**\n * The auth server, as an origin.\n *\n * Accepts `tenant.idp.us.pontive.app` or `https://tenant.idp.us.pontive.app`,\n * and nothing with a path: the upstream path comes from the incoming request,\n * and a base path here would be silently prepended to endpoints the auth server\n * does not serve.\n *\n * `http://` is inferred for loopback only, and accepted only there. A proxy is\n * the one hop a refresh token cannot be carried over in the clear — it is the\n * hop that exists precisely so the cookie is first-party — and the failure is\n * invisible from the browser, which sees its own `https://` origin either way.\n */\nexport function authOrigin(authHost: string): string {\n const configured = (authHost ?? \"\").trim();\n\n if (!configured) {\n throw new TypeError(\"authHost is required\");\n }\n\n const loopback = /^(localhost|127\\.0\\.0\\.1|\\[::1\\])(:\\d+)?$/i.test(\n configured.replace(/^https?:\\/\\//i, \"\").split(\"/\")[0],\n );\n\n const scheme = /^https?:\\/\\//i.test(configured) ? \"\" : `${loopback ? \"http\" : \"https\"}://`;\n\n let url: URL;\n try {\n url = new URL(`${scheme}${configured}`);\n } catch {\n throw new TypeError(`authHost \"${configured}\" is not a hostname or an origin`);\n }\n\n if (url.pathname !== \"/\" || url.search || url.hash) {\n throw new TypeError(\n `authHost \"${configured}\" must be a bare origin — the path comes from the request being proxied`,\n );\n }\n\n if (url.protocol !== \"https:\" && !loopback) {\n throw new TypeError(`authHost \"${configured}\" must be https outside loopback`);\n }\n\n return url.origin;\n}\n\n/**\n * A base path with a leading slash and no trailing one, so joining is\n * unambiguous.\n *\n * `\"/\"` normalises to `\"\"`, which mounts the endpoints at the origin root —\n * `/auth/v1/...` and `/oauth2/...` where the app itself is served. That is the\n * shape a Vite dev server has always used, and it stays available because in\n * development the app owns the whole origin and there is nothing to collide\n * with. A deployed app usually does not, which is what the prefix is for.\n */\nexport function normaliseBasePath(basePath: string): string {\n const trimmed = (basePath ?? \"\").trim().replace(/\\/+$/, \"\");\n\n if (trimmed === \"\") {\n return \"\";\n }\n\n if (!trimmed.startsWith(\"/\")) {\n throw new TypeError(`basePath \"${basePath}\" must start with \"/\"`);\n }\n\n return trimmed;\n}\n\n/** Whether `pathname` is `prefix` itself or something under it. */\nexport function isUnder(pathname: string, prefix: string): boolean {\n return pathname === prefix || pathname.startsWith(`${prefix}/`);\n}\n","import { downstreamHeaders, upstreamHeaders } from \"./headers\";\nimport {\n DEFAULT_BASE_PATH,\n DEFAULT_FORWARDED_PATHS,\n authOrigin,\n isUnder,\n normaliseBasePath,\n} from \"./target\";\n\nexport interface AuthProxyOptions {\n /**\n * The auth server, as a hostname or an origin — the value the SDK's `domain`\n * used to hold, e.g. `tenant.idp.us.pontive.app`.\n */\n authHost: string;\n /**\n * Where the endpoints hang off this app's origin. Defaults to `/__auth`; `\"/\"`\n * mounts them at the root, which is the shape a dev server uses.\n *\n * Whatever this is, it is also what the SDK's `domain` must be set to.\n */\n basePath?: string;\n /** Which upstream prefixes may be forwarded. Defaults to the SDK's surface. */\n paths?: readonly string[];\n /** The fetch to send upstream requests with. For tests and custom agents. */\n fetch?: typeof globalThis.fetch;\n}\n\nexport interface AuthProxy {\n /** Whether this request is one the proxy should carry. */\n handles(request: Request): boolean;\n /** Carries it, and answers with whatever the auth server said. */\n forward(request: Request): Promise<Response>;\n /** The normalised base path, for building the SDK's `domain`. */\n readonly basePath: string;\n /** The upstream origin. */\n readonly origin: string;\n /** Path patterns for a framework that routes by them, e.g. Next's matcher. */\n readonly matcher: string[];\n}\n\n/**\n * A reverse proxy for the auth endpoints, as a Web-standard request handler.\n *\n * Why an app would run one: a browser only treats a cookie as first-party when\n * it comes from the origin the page is on. An app on `app.acme.com` talking to\n * an auth server on another hostname is cross-site, so the refresh cookie is a\n * third-party cookie — blocked outright in Safari, and on borrowed time\n * everywhere else. Proxying the endpoints under the app's own origin makes them\n * first-party, and `SameSite=Lax` holds with no DNS record, no certificate, and\n * nothing to verify.\n *\n * What it deliberately does NOT do is rewrite anything. It does not touch the\n * cookies in either direction, does not follow redirects, and does not present\n * the app's own Host upstream — the auth server resolves which project it is\n * answering as from Host, so the canonical one has to arrive intact. That is\n * also why this needs no secret: unlike Clerk's equivalent, whose Frontend API\n * is multi-tenant on one hostname and must be told which instance to be, the\n * hostname here already says it.\n *\n * Runs anywhere `Request` and `Response` do: Next.js middleware and route\n * handlers, Cloudflare Workers, Hono, Deno, Bun. A Vite dev server does not need\n * it — see `viteAuthProxy`, which configures Vite's own proxy instead.\n */\nexport function createAuthProxy(options: AuthProxyOptions): AuthProxy {\n const origin = authOrigin(options.authHost);\n const basePath = normaliseBasePath(options.basePath ?? DEFAULT_BASE_PATH);\n const paths = options.paths ?? DEFAULT_FORWARDED_PATHS;\n const send = options.fetch ?? globalThis.fetch;\n\n /**\n * The upstream URL, or null when this is not a request to carry.\n *\n * Resolved through `URL` before the prefix check, not after, so a path that\n * climbs out of the base — `/__auth/../admin` — is tested as what it actually\n * addresses rather than as what it looks like. It cannot leave the origin;\n * this is what stops it reaching a path the caller did not open up.\n */\n function upstreamFor(request: Request): URL | null {\n const url = new URL(request.url);\n\n if (!isUnder(url.pathname, basePath)) {\n return null;\n }\n\n const rest = url.pathname.slice(basePath.length) || \"/\";\n const upstream = new URL(`${rest}${url.search}`, origin);\n\n if (upstream.origin !== origin) {\n return null;\n }\n\n return paths.some((prefix) => isUnder(upstream.pathname, prefix)) ? upstream : null;\n }\n\n return {\n basePath,\n origin,\n\n matcher: paths.map((prefix) => `${basePath}${prefix}/:path*`),\n\n handles(request: Request): boolean {\n return upstreamFor(request) !== null;\n },\n\n async forward(request: Request): Promise<Response> {\n const upstream = upstreamFor(request);\n\n if (!upstream) {\n // The caller routed something here that this proxy does not carry.\n // Answered rather than passed through, because passing it through would\n // mean the app's own router handling a URL under a prefix it has\n // otherwise given away.\n return new Response(\"Not Found\", { status: 404 });\n }\n\n // A GET or HEAD has no body to stream, and `duplex` is required by the\n // fetch spec for the ones that do.\n const body = request.method === \"GET\" || request.method === \"HEAD\" ? undefined : request.body;\n\n try {\n const response = await send(upstream, {\n method: request.method,\n headers: upstreamHeaders(request),\n body,\n // Passed to the browser as-is. Followed here, a 302 from /authorize\n // would be resolved server-side and the browser would never see the\n // navigation it is supposed to make.\n redirect: \"manual\",\n ...(body ? { duplex: \"half\" } : {}),\n } as RequestInit);\n\n return new Response(response.body, {\n status: response.status,\n statusText: response.statusText,\n headers: downstreamHeaders(response),\n });\n } catch (error) {\n // The auth server is unreachable from here. 502 rather than 500: the\n // failure is upstream, and the distinction is the first thing anyone\n // debugging a proxy wants to know.\n console.warn(`Could not reach the auth server at ${origin}:`, error);\n\n return new Response(\"Bad Gateway\", { status: 502 });\n }\n },\n };\n}\n","import {\n DEFAULT_BASE_PATH,\n DEFAULT_FORWARDED_PATHS,\n authOrigin,\n normaliseBasePath,\n} from \"./target\";\n\n/**\n * The shape of one entry in Vite's `server.proxy`.\n *\n * Declared here rather than imported from Vite so that nothing which imports\n * this module needs Vite installed, and so the published types do not depend on\n * a particular version of it. It is structural: Vite accepts this object.\n */\nexport interface ViteProxyEntry {\n target: string;\n changeOrigin: boolean;\n rewrite: (path: string) => string;\n}\n\nexport interface ViteAuthProxyOptions {\n authHost: string;\n basePath?: string;\n paths?: readonly string[];\n}\n\n/**\n * The auth endpoints, proxied through a Vite dev server.\n *\n * ```ts\n * // vite.config.ts\n * server: { proxy: viteAuthProxy({ authHost: env.VITE_SB_AUTH_DOMAIN }) }\n * ```\n *\n * Vite already has a proxy; what it does not have is the knowledge of which\n * paths to carry and what to do with Host, and both of those are easy to get\n * wrong in ways that fail silently. So this is a config generator rather than a\n * request handler — `createAuthProxy` is for runtimes that have no proxy of\n * their own.\n *\n * Worth doing even where the browser would tolerate the cross-site setup,\n * because it is the same topology production runs on: a dev server that proxies\n * is rehearsing the deployment, and a dev server that does not is testing a\n * configuration no user will ever have. It is also the only way an embedded\n * sign-in flow works in Safari, which blocks third-party cookies outright.\n */\nexport function viteAuthProxy(\n options: ViteAuthProxyOptions,\n): Record<string, ViteProxyEntry> {\n const target = authOrigin(options.authHost);\n const basePath = normaliseBasePath(options.basePath ?? DEFAULT_BASE_PATH);\n const paths = options.paths ?? DEFAULT_FORWARDED_PATHS;\n\n const proxy: Record<string, ViteProxyEntry> = {};\n\n for (const prefix of paths) {\n proxy[`${basePath}${prefix}`] = {\n target,\n // The single most important line, and the one a hand-written config\n // leaves out. Without it the auth server is asked to answer as\n // `localhost:5173` — a Host it has no project for — and the reply is a\n // CORS refusal and an empty issuer rather than anything that says so.\n changeOrigin: true,\n // Only the base path comes off. The prefix below it is the path the auth\n // server actually serves.\n rewrite: (path: string) => (basePath ? path.replace(basePath, \"\") : path),\n };\n }\n\n return proxy;\n}\n","import {\n DEFAULT_BASE_PATH,\n DEFAULT_FORWARDED_PATHS,\n authOrigin,\n normaliseBasePath,\n} from \"./target\";\n\nexport interface NextRewrite {\n source: string;\n destination: string;\n}\n\nexport interface AuthProxyRewritesOptions {\n authHost: string;\n basePath?: string;\n paths?: readonly string[];\n}\n\n/**\n * The auth endpoints, proxied by Next's own rewrites.\n *\n * ```js\n * // next.config.js\n * rewrites: async () => authProxyRewrites({ authHost: process.env.SB_AUTH_DOMAIN })\n * ```\n *\n * The cheapest Next integration there is, and the one to reach for first: a\n * rewrite to an external destination sends the destination's Host upstream,\n * which is exactly what the auth server needs, so there is no header to\n * configure and nothing to get wrong. Middleware (`createAuthProxy`) is for when\n * something else has to happen on the way through — a client IP to resolve, a\n * header to add, a path to decide at runtime.\n */\nexport function authProxyRewrites(options: AuthProxyRewritesOptions): NextRewrite[] {\n const origin = authOrigin(options.authHost);\n const basePath = normaliseBasePath(options.basePath ?? DEFAULT_BASE_PATH);\n const paths = options.paths ?? DEFAULT_FORWARDED_PATHS;\n\n return paths.map((prefix) => ({\n source: `${basePath}${prefix}/:path*`,\n destination: `${origin}${prefix}/:path*`,\n }));\n}\n"],"names":["HOP_BY_HOP","upstreamHeaders","request","headers","name","url","forwardedFor","chain","ip","downstreamHeaders","response","value","cookie","setCookies","joined","DEFAULT_FORWARDED_PATHS","DEFAULT_BASE_PATH","authOrigin","authHost","configured","loopback","scheme","normaliseBasePath","basePath","trimmed","isUnder","pathname","prefix","createAuthProxy","options","origin","paths","send","upstreamFor","rest","upstream","body","error","viteAuthProxy","target","proxy","path","authProxyRewrites"],"mappings":"AAeA,MAAMA,IAAa;AAAA,EACjB;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AASO,SAASC,EAAgBC,GAA2B;AACzD,QAAMC,IAAU,IAAI,QAAQD,EAAQ,OAAO;AAE3C,aAAWE,KAAQJ;AACjB,IAAAG,EAAQ,OAAOC,CAAI;AAOrB,EAAAD,EAAQ,OAAO,MAAM,GAGrBA,EAAQ,OAAO,gBAAgB,GAK/BA,EAAQ,OAAO,iBAAiB;AAEhC,QAAME,IAAM,IAAI,IAAIH,EAAQ,GAAG;AAM/B,SAAKC,EAAQ,IAAI,mBAAmB,KAClCA,EAAQ,IAAI,qBAAqBE,EAAI,SAAS,QAAQ,KAAK,EAAE,CAAC,GAM3DF,EAAQ,IAAI,kBAAkB,KACjCA,EAAQ,IAAI,oBAAoBE,EAAI,IAAI,GAG1CF,EAAQ,IAAI,mBAAmBG,EAAaJ,CAAO,CAAC,GAE7CC;AACT;AAcA,SAASG,EAAaJ,GAA0B;AAC9C,QAAMK,IAAQL,EAAQ,QA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;AAIxE,SAAOD;AACT;ACrCO,SAASE,EAAkBb,GAAkD;AAClF,QAAMC,IAASb,EAAWY,EAAQ,QAAQ,GACpCN,IAAWD,EAAkBO,EAAQ,YAAYb,CAAiB;AAGxE,UAFca,EAAQ,SAASd,GAElB,IAAI,CAACY,OAAY;AAAA,IAC5B,QAAQ,GAAGJ,CAAQ,GAAGI,CAAM;AAAA,IAC5B,aAAa,GAAGG,CAAM,GAAGH,CAAM;AAAA,EAAA,EAC/B;AACJ;"}
package/package.json ADDED
@@ -0,0 +1,42 @@
1
+ {
2
+ "name": "@pontive/pontkit-nextjs",
3
+ "version": "1.0.0",
4
+ "license": "MIT",
5
+ "description": "The React bindings plus the server-side auth proxy for Next.js.",
6
+ "type": "module",
7
+ "main": "./dist/index.cjs",
8
+ "module": "./dist/index.js",
9
+ "types": "./dist/index.d.ts",
10
+ "exports": {
11
+ ".": {
12
+ "types": "./dist/index.d.ts",
13
+ "import": "./dist/index.js",
14
+ "require": "./dist/index.cjs"
15
+ },
16
+ "./server": {
17
+ "types": "./dist/server/index.d.ts",
18
+ "import": "./dist/server.js",
19
+ "require": "./dist/server.cjs"
20
+ }
21
+ },
22
+ "files": [
23
+ "dist"
24
+ ],
25
+ "sideEffects": false,
26
+ "scripts": {
27
+ "build": "vite build",
28
+ "test": "vitest run",
29
+ "typecheck": "tsc --noEmit"
30
+ },
31
+ "publishConfig": {
32
+ "access": "public"
33
+ },
34
+ "peerDependencies": {
35
+ "next": ">=13",
36
+ "react": "^18 || ^19",
37
+ "react-dom": "^18 || ^19"
38
+ },
39
+ "dependencies": {
40
+ "@pontive/pontkit-react": "^1.0.0"
41
+ }
42
+ }