@pontive/server 0.0.0-stage → 1.23.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/README.md +146 -2
- package/dist/auth.d.cts +34 -0
- package/dist/auth.d.ts +34 -0
- package/dist/authorization.cjs +2 -0
- package/dist/authorization.cjs.map +1 -0
- package/dist/authorization.d.cts +222 -0
- package/dist/authorization.d.ts +222 -0
- package/dist/authorization.js +153 -0
- package/dist/authorization.js.map +1 -0
- package/dist/browser-mode.d.cts +23 -0
- package/dist/browser-mode.d.ts +23 -0
- package/dist/config.d.cts +131 -0
- package/dist/config.d.ts +131 -0
- package/dist/cookies.d.cts +50 -0
- package/dist/cookies.d.ts +50 -0
- package/dist/env.d.cts +44 -0
- package/dist/env.d.ts +44 -0
- package/dist/index.cjs +5 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +20 -0
- package/dist/index.d.ts +20 -0
- package/dist/index.js +700 -0
- package/dist/index.js.map +1 -0
- package/dist/keyless.cjs +16 -0
- package/dist/keyless.cjs.map +1 -0
- package/dist/keyless.d.cts +244 -0
- package/dist/keyless.d.ts +244 -0
- package/dist/keyless.js +355 -0
- package/dist/keyless.js.map +1 -0
- package/dist/management-credential-BNyhHagG.cjs +2 -0
- package/dist/management-credential-BNyhHagG.cjs.map +1 -0
- package/dist/management-credential-VhmMzGDl.js +39 -0
- package/dist/management-credential-VhmMzGDl.js.map +1 -0
- package/dist/management-credential.d.cts +40 -0
- package/dist/management-credential.d.ts +40 -0
- package/dist/mcp-auth-info-BGyWua_9.js +19 -0
- package/dist/mcp-auth-info-BGyWua_9.js.map +1 -0
- package/dist/mcp-auth-info-jblMsSJo.cjs +2 -0
- package/dist/mcp-auth-info-jblMsSJo.cjs.map +1 -0
- package/dist/mcp-auth-info.d.cts +17 -0
- package/dist/mcp-auth-info.d.ts +17 -0
- package/dist/oidc--We55Nrh.cjs +2 -0
- package/dist/oidc--We55Nrh.cjs.map +1 -0
- package/dist/oidc-CB0FqjFz.js +131 -0
- package/dist/oidc-CB0FqjFz.js.map +1 -0
- package/dist/oidc.d.cts +80 -0
- package/dist/oidc.d.ts +80 -0
- package/dist/organization.d.cts +35 -0
- package/dist/organization.d.ts +35 -0
- package/dist/preview-hosts.d.cts +33 -0
- package/dist/preview-hosts.d.ts +33 -0
- package/dist/refresh.d.cts +28 -0
- package/dist/refresh.d.ts +28 -0
- package/dist/resource-server-express.cjs +2 -0
- package/dist/resource-server-express.cjs.map +1 -0
- package/dist/resource-server-express.d.cts +73 -0
- package/dist/resource-server-express.d.ts +73 -0
- package/dist/resource-server-express.js +57 -0
- package/dist/resource-server-express.js.map +1 -0
- package/dist/resource-server-mcp.cjs +2 -0
- package/dist/resource-server-mcp.cjs.map +1 -0
- package/dist/resource-server-mcp.d.cts +70 -0
- package/dist/resource-server-mcp.d.ts +70 -0
- package/dist/resource-server-mcp.js +59 -0
- package/dist/resource-server-mcp.js.map +1 -0
- package/dist/resource-server.cjs +2 -0
- package/dist/resource-server.cjs.map +1 -0
- package/dist/resource-server.d.cts +290 -0
- package/dist/resource-server.d.ts +290 -0
- package/dist/resource-server.js +301 -0
- package/dist/resource-server.js.map +1 -0
- package/dist/seal.d.cts +3 -0
- package/dist/seal.d.ts +3 -0
- package/dist/server-auth.d.cts +100 -0
- package/dist/server-auth.d.ts +100 -0
- package/package.json +96 -4
package/dist/config.d.ts
ADDED
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* What an app tells the SDK, and the defaults for everything it doesn't.
|
|
3
|
+
*
|
|
4
|
+
* Whether `clientSecret` is set picks the mode, and nothing else does:
|
|
5
|
+
*
|
|
6
|
+
* - **With a secret** (a confidential oauth app): the server holds the whole
|
|
7
|
+
* session in a sealed cookie, signs users in through its own routes, and
|
|
8
|
+
* refreshes in middleware. Needs `sessionSecret`.
|
|
9
|
+
* - **Without one** (a regular app, or a public oauth app): the browser SDK
|
|
10
|
+
* signs users in and is the only thing that refreshes. The server reads the
|
|
11
|
+
* access token cookie the auth server keeps current, through the auth proxy,
|
|
12
|
+
* and sends a lapsed navigation through the auth server's session handshake.
|
|
13
|
+
*
|
|
14
|
+
* Everything beyond the first few fields exists for the rare app that must
|
|
15
|
+
* differ, and its default is the decision the SDK makes for everyone else.
|
|
16
|
+
*
|
|
17
|
+
* **The environment** (pontive-spec 47 §6.1): `issuer`, `clientId`,
|
|
18
|
+
* `clientSecret` and `sessionSecret` fall back to `PONTIVE_ISSUER`,
|
|
19
|
+
* `PONTIVE_CLIENT_ID`, `PONTIVE_CLIENT_SECRET` and `PONTIVE_SESSION_SECRET`
|
|
20
|
+
* when not passed; a value passed always wins. With neither an `issuer` nor
|
|
21
|
+
* `PONTIVE_ISSUER`, development (`NODE_ENV=development`) runs in **keyless
|
|
22
|
+
* mode** (§6.2): the SDK creates an unclaimed development instance on first
|
|
23
|
+
* use and writes its settings to `.env.local`. `PONTIVE_KEYLESS=0` turns that
|
|
24
|
+
* off; outside development a missing issuer is an error.
|
|
25
|
+
*/
|
|
26
|
+
export interface ServerAuthConfig {
|
|
27
|
+
/** The Pontive auth domain, e.g. `https://acme.auth.us.pontive.com`. Default `PONTIVE_ISSUER`. */
|
|
28
|
+
issuer?: string;
|
|
29
|
+
/** The app's id. Default `PONTIVE_CLIENT_ID`. */
|
|
30
|
+
clientId?: string;
|
|
31
|
+
/**
|
|
32
|
+
* Set for a confidential app. It is sent on every token call, and is what
|
|
33
|
+
* lets the app hold its refresh token on its server at all. Default
|
|
34
|
+
* `PONTIVE_CLIENT_SECRET`.
|
|
35
|
+
*/
|
|
36
|
+
clientSecret?: string;
|
|
37
|
+
/**
|
|
38
|
+
* Encrypts the session cookie. At least 32 characters; rotating it signs
|
|
39
|
+
* everyone out. Required with a `clientSecret`; unused without one, where the
|
|
40
|
+
* server stores nothing. Default `PONTIVE_SESSION_SECRET`.
|
|
41
|
+
*/
|
|
42
|
+
sessionSecret?: string;
|
|
43
|
+
/**
|
|
44
|
+
* The app's public origin, e.g. `https://app.acme.com`. Set it for any
|
|
45
|
+
* deployment behind a proxy or in a container, where the request's own URL
|
|
46
|
+
* names the address the server binds to rather than the one a browser uses.
|
|
47
|
+
* Without it the origin comes from `x-forwarded-proto`/`x-forwarded-host`,
|
|
48
|
+
* then the request URL.
|
|
49
|
+
*/
|
|
50
|
+
baseUrl?: string;
|
|
51
|
+
/**
|
|
52
|
+
* Without a `clientSecret`: where the auth proxy serves the auth server on
|
|
53
|
+
* this app's origin. Default `/__pontive`, the auth proxy's own default.
|
|
54
|
+
*/
|
|
55
|
+
authPath?: string;
|
|
56
|
+
/** Default `openid email profile offline_access`. */
|
|
57
|
+
scopes?: string;
|
|
58
|
+
/** Where the SDK's sign-in routes live. Default `/api/auth`. */
|
|
59
|
+
basePath?: string;
|
|
60
|
+
/** Default `${origin}${basePath}/callback`; must be registered on the app verbatim. */
|
|
61
|
+
redirectUri?: string;
|
|
62
|
+
/** The app's own sign-in page: failed sign-ins and signed-out users land here. Default `/login`. */
|
|
63
|
+
signInPath?: string;
|
|
64
|
+
/** Where a sign-in lands when it did not start from a page. Default `/`. */
|
|
65
|
+
afterSignInPath?: string;
|
|
66
|
+
/** An OIDC `prompt` to send, e.g. `login`. */
|
|
67
|
+
prompt?: string;
|
|
68
|
+
/** Default `pontive_session`. */
|
|
69
|
+
cookieName?: string;
|
|
70
|
+
/** Default: whether the public origin is https. */
|
|
71
|
+
secureCookies?: boolean;
|
|
72
|
+
/**
|
|
73
|
+
* Whether the SDK's own cookies — the session and the sign-in transaction —
|
|
74
|
+
* are written `SameSite=None; Secure`, so the browser still sends them to a
|
|
75
|
+
* page inside an iframe on another site: an app builder's preview
|
|
76
|
+
* (pontive-spec 06, *SDK in builder previews*). `"auto"`, the default, does
|
|
77
|
+
* so when the public origin is a builder preview host (`*.lovable.app`,
|
|
78
|
+
* `*.lovableproject.com`, `*.vusercontent.net`, `*.v0.app`,
|
|
79
|
+
* `*.webcontainer-api.io`, `*.replit.dev`, …); `true` always, `false`
|
|
80
|
+
* never. Lax everywhere else. A browser that blocks third-party cookies
|
|
81
|
+
* (Safari, Firefox's partitioning) withholds them in the frame anyway.
|
|
82
|
+
*/
|
|
83
|
+
iframeSafe?: boolean | "auto";
|
|
84
|
+
/**
|
|
85
|
+
* Whether sign-in uses the auth domain's hosted preview callback as its
|
|
86
|
+
* `redirect_uri` (pontive-spec 06, *Builder previews*): for an app builder's
|
|
87
|
+
* preview, whose host changes per draft and cannot be registered. The app
|
|
88
|
+
* turns the builder on in its *Builder previews* setting, on a development
|
|
89
|
+
* instance. The sign-in then runs in a popup; the callback page hands the
|
|
90
|
+
* code back to this page, which forwards it to the `callback` route, and the
|
|
91
|
+
* code is redeemed here with `redirect_uri` the hosted callback. `"auto"`,
|
|
92
|
+
* the default, does so when the public origin is a preview host of a known
|
|
93
|
+
* builder (`*.lovableproject.com`, `*.vusercontent.net`,
|
|
94
|
+
* `*.<server>.replit.dev`, …); `"always"` everywhere, `"never"` never — for
|
|
95
|
+
* a preview whose exact callback is registered.
|
|
96
|
+
*/
|
|
97
|
+
previewCallback?: "auto" | "always" | "never";
|
|
98
|
+
/** The session cookie's lifetime. Default 7 days. */
|
|
99
|
+
sessionMaxAgeSeconds?: number;
|
|
100
|
+
/** Refresh when fewer than this many seconds remain. Default 60. */
|
|
101
|
+
refreshSkewSeconds?: number;
|
|
102
|
+
/** Defaults to the global `fetch`. */
|
|
103
|
+
fetch?: typeof fetch;
|
|
104
|
+
/** Where the SDK reports a failed refresh or sign-in. Defaults to `console`. */
|
|
105
|
+
logger?: Pick<Console, "warn">;
|
|
106
|
+
}
|
|
107
|
+
export interface ResolvedConfig {
|
|
108
|
+
/** `server`: a confidential app holding its own session. `browser`: the browser SDK's session, read. */
|
|
109
|
+
mode: "server" | "browser";
|
|
110
|
+
authPath: string;
|
|
111
|
+
issuer: string;
|
|
112
|
+
clientId: string;
|
|
113
|
+
clientSecret?: string;
|
|
114
|
+
sessionSecret: string;
|
|
115
|
+
baseUrl?: string;
|
|
116
|
+
scopes: string;
|
|
117
|
+
basePath: string;
|
|
118
|
+
redirectUri?: string;
|
|
119
|
+
signInPath: string;
|
|
120
|
+
afterSignInPath: string;
|
|
121
|
+
prompt?: string;
|
|
122
|
+
cookieName: string;
|
|
123
|
+
secureCookies?: boolean;
|
|
124
|
+
iframeSafe: boolean | "auto";
|
|
125
|
+
previewCallback: "auto" | "always" | "never";
|
|
126
|
+
sessionMaxAgeSeconds: number;
|
|
127
|
+
refreshSkewSeconds: number;
|
|
128
|
+
fetch: typeof fetch;
|
|
129
|
+
logger: Pick<Console, "warn">;
|
|
130
|
+
}
|
|
131
|
+
export declare function resolveConfig(config: ServerAuthConfig): ResolvedConfig;
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Cookie reading and writing, on plain header strings so it runs anywhere a
|
|
3
|
+
* Web `Request`/`Response` does.
|
|
4
|
+
*
|
|
5
|
+
* A sealed session outgrows one cookie (browsers cap each at about 4 KB, and an
|
|
6
|
+
* access token, a refresh token and a user fit in about 3–5), so it is split
|
|
7
|
+
* across numbered chunks: `name`, `name.1`, `name.2`, … and joined on read.
|
|
8
|
+
*/
|
|
9
|
+
/** Characters per chunk, leaving room under the ~4096-byte cap for the name and attributes. */
|
|
10
|
+
export declare const CHUNK_SIZE = 3500;
|
|
11
|
+
/** Upper bound on chunks probed when reading or clearing. */
|
|
12
|
+
export declare const MAX_CHUNKS = 16;
|
|
13
|
+
export interface CookieAttributes {
|
|
14
|
+
/** Seconds; 0 deletes the cookie. */
|
|
15
|
+
maxAge: number;
|
|
16
|
+
secure: boolean;
|
|
17
|
+
/**
|
|
18
|
+
* `Lax` unless said otherwise. `None` is for a page inside an app builder's
|
|
19
|
+
* preview iframe, where the browser withholds a Lax cookie from every
|
|
20
|
+
* request (`ServerAuthConfig.iframeSafe`); it is always `Secure`.
|
|
21
|
+
*/
|
|
22
|
+
sameSite?: "Lax" | "None";
|
|
23
|
+
}
|
|
24
|
+
/** Parses a `Cookie` request header into name → value. */
|
|
25
|
+
export declare function parseCookies(header: string | null | undefined): Map<string, string>;
|
|
26
|
+
/** Serialises a `Cookie` request header from name → value. */
|
|
27
|
+
export declare function formatCookieHeader(cookies: Map<string, string>): string;
|
|
28
|
+
/**
|
|
29
|
+
* A `Set-Cookie` value. Always HttpOnly, host-only and `Path=/`, and
|
|
30
|
+
* `SameSite=Lax` unless `attrs` say `None`: Lax is what lets the cookie ride
|
|
31
|
+
* the top-level redirect back from the sign-in page, and nothing here is ever
|
|
32
|
+
* for script. `SameSite=None` is always `Secure`, as browsers require.
|
|
33
|
+
*
|
|
34
|
+
* Never `Partitioned`: a preview signs in through a popup, a top-level window
|
|
35
|
+
* whose cookies are keyed to the app's own site, and a partitioned cookie
|
|
36
|
+
* written there would be invisible to the same app framed under the
|
|
37
|
+
* builder's site.
|
|
38
|
+
*/
|
|
39
|
+
export declare function serializeCookie(name: string, value: string, attrs: CookieAttributes): string;
|
|
40
|
+
export declare function chunkName(name: string, index: number): string;
|
|
41
|
+
/** Joins a chunked value, or null when its first chunk is absent. */
|
|
42
|
+
export declare function readChunked(cookies: Map<string, string>, name: string): string | null;
|
|
43
|
+
/**
|
|
44
|
+
* The `Set-Cookie` values that store `value` in chunks, and delete any chunk
|
|
45
|
+
* the request carried beyond what it now needs. Also updates `cookies` in
|
|
46
|
+
* place, so a caller can forward the new state on the same request.
|
|
47
|
+
*/
|
|
48
|
+
export declare function writeChunked(cookies: Map<string, string>, name: string, value: string, attrs: CookieAttributes): string[];
|
|
49
|
+
/** The `Set-Cookie` values that delete every chunk the request carried. */
|
|
50
|
+
export declare function clearChunked(cookies: Map<string, string>, name: string, attrs: Omit<CookieAttributes, "maxAge">): string[];
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Cookie reading and writing, on plain header strings so it runs anywhere a
|
|
3
|
+
* Web `Request`/`Response` does.
|
|
4
|
+
*
|
|
5
|
+
* A sealed session outgrows one cookie (browsers cap each at about 4 KB, and an
|
|
6
|
+
* access token, a refresh token and a user fit in about 3–5), so it is split
|
|
7
|
+
* across numbered chunks: `name`, `name.1`, `name.2`, … and joined on read.
|
|
8
|
+
*/
|
|
9
|
+
/** Characters per chunk, leaving room under the ~4096-byte cap for the name and attributes. */
|
|
10
|
+
export declare const CHUNK_SIZE = 3500;
|
|
11
|
+
/** Upper bound on chunks probed when reading or clearing. */
|
|
12
|
+
export declare const MAX_CHUNKS = 16;
|
|
13
|
+
export interface CookieAttributes {
|
|
14
|
+
/** Seconds; 0 deletes the cookie. */
|
|
15
|
+
maxAge: number;
|
|
16
|
+
secure: boolean;
|
|
17
|
+
/**
|
|
18
|
+
* `Lax` unless said otherwise. `None` is for a page inside an app builder's
|
|
19
|
+
* preview iframe, where the browser withholds a Lax cookie from every
|
|
20
|
+
* request (`ServerAuthConfig.iframeSafe`); it is always `Secure`.
|
|
21
|
+
*/
|
|
22
|
+
sameSite?: "Lax" | "None";
|
|
23
|
+
}
|
|
24
|
+
/** Parses a `Cookie` request header into name → value. */
|
|
25
|
+
export declare function parseCookies(header: string | null | undefined): Map<string, string>;
|
|
26
|
+
/** Serialises a `Cookie` request header from name → value. */
|
|
27
|
+
export declare function formatCookieHeader(cookies: Map<string, string>): string;
|
|
28
|
+
/**
|
|
29
|
+
* A `Set-Cookie` value. Always HttpOnly, host-only and `Path=/`, and
|
|
30
|
+
* `SameSite=Lax` unless `attrs` say `None`: Lax is what lets the cookie ride
|
|
31
|
+
* the top-level redirect back from the sign-in page, and nothing here is ever
|
|
32
|
+
* for script. `SameSite=None` is always `Secure`, as browsers require.
|
|
33
|
+
*
|
|
34
|
+
* Never `Partitioned`: a preview signs in through a popup, a top-level window
|
|
35
|
+
* whose cookies are keyed to the app's own site, and a partitioned cookie
|
|
36
|
+
* written there would be invisible to the same app framed under the
|
|
37
|
+
* builder's site.
|
|
38
|
+
*/
|
|
39
|
+
export declare function serializeCookie(name: string, value: string, attrs: CookieAttributes): string;
|
|
40
|
+
export declare function chunkName(name: string, index: number): string;
|
|
41
|
+
/** Joins a chunked value, or null when its first chunk is absent. */
|
|
42
|
+
export declare function readChunked(cookies: Map<string, string>, name: string): string | null;
|
|
43
|
+
/**
|
|
44
|
+
* The `Set-Cookie` values that store `value` in chunks, and delete any chunk
|
|
45
|
+
* the request carried beyond what it now needs. Also updates `cookies` in
|
|
46
|
+
* place, so a caller can forward the new state on the same request.
|
|
47
|
+
*/
|
|
48
|
+
export declare function writeChunked(cookies: Map<string, string>, name: string, value: string, attrs: CookieAttributes): string[];
|
|
49
|
+
/** The `Set-Cookie` values that delete every chunk the request carried. */
|
|
50
|
+
export declare function clearChunked(cookies: Map<string, string>, name: string, attrs: Omit<CookieAttributes, "maxAge">): string[];
|
package/dist/env.d.cts
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import { ServerAuthConfig } from './config.cjs';
|
|
2
|
+
/**
|
|
3
|
+
* The environment contract (pontive-spec 47 §6.1): the variables the SDK falls
|
|
4
|
+
* back to when the app does not pass a field. Explicit config always wins.
|
|
5
|
+
*
|
|
6
|
+
* | Variable | Holds |
|
|
7
|
+
* | ------------------------ | -------------------------------------------------- |
|
|
8
|
+
* | `PONTIVE_ISSUER` | the instance's issuer (its auth domain origin) |
|
|
9
|
+
* | `PONTIVE_CLIENT_ID` | the app's id |
|
|
10
|
+
* | `PONTIVE_CLIENT_SECRET` | a confidential (`web`) app's client secret |
|
|
11
|
+
* | `PONTIVE_SESSION_SECRET` | 32+ random characters, generated locally |
|
|
12
|
+
* | `PONTIVE_SECRET_KEY` | the instance's secret key (management calls; not read here) |
|
|
13
|
+
* | `PONTIVE_INSTANCE_ID` | the instance's id (not secret; not read here) |
|
|
14
|
+
*
|
|
15
|
+
* And for keyless mode (§6.2): `PONTIVE_KEYLESS` (`0` turns it off),
|
|
16
|
+
* `PONTIVE_API_URL` (where the provisioning routes live, default
|
|
17
|
+
* `https://api.pontive.com`) and `PONTIVE_REGION` (the region to provision in;
|
|
18
|
+
* default: the one nearest the caller).
|
|
19
|
+
*/
|
|
20
|
+
export declare const PONTIVE_ENV: {
|
|
21
|
+
readonly issuer: "PONTIVE_ISSUER";
|
|
22
|
+
readonly clientId: "PONTIVE_CLIENT_ID";
|
|
23
|
+
readonly clientSecret: "PONTIVE_CLIENT_SECRET";
|
|
24
|
+
readonly sessionSecret: "PONTIVE_SESSION_SECRET";
|
|
25
|
+
readonly secretKey: "PONTIVE_SECRET_KEY";
|
|
26
|
+
readonly instanceId: "PONTIVE_INSTANCE_ID";
|
|
27
|
+
readonly apiUrl: "PONTIVE_API_URL";
|
|
28
|
+
readonly region: "PONTIVE_REGION";
|
|
29
|
+
readonly keyless: "PONTIVE_KEYLESS";
|
|
30
|
+
};
|
|
31
|
+
export type Env = Readonly<Record<string, string | undefined>>;
|
|
32
|
+
/** `process.env`, or nothing where there is no `process` (a browser, some edge runtimes). */
|
|
33
|
+
export declare function processEnv(): Env;
|
|
34
|
+
/** The config with every field the app left out taken from the environment. */
|
|
35
|
+
export declare function withEnvFallback(config: ServerAuthConfig, env?: Env): ServerAuthConfig;
|
|
36
|
+
/** `NODE_ENV === "development"`: `next dev`, `vite`, and the like. Never a production build. */
|
|
37
|
+
export declare function isDevelopment(env?: Env): boolean;
|
|
38
|
+
/**
|
|
39
|
+
* Whether keyless mode applies (pontive-spec 47 §6.2, decision E3): in
|
|
40
|
+
* development only, with no issuer passed or in `PONTIVE_ISSUER`, unless
|
|
41
|
+
* `PONTIVE_KEYLESS=0`. Anywhere else a missing issuer is the usual
|
|
42
|
+
* `issuer is required` error.
|
|
43
|
+
*/
|
|
44
|
+
export declare function keylessApplies(config: ServerAuthConfig, env?: Env): boolean;
|
package/dist/env.d.ts
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import { ServerAuthConfig } from './config.js';
|
|
2
|
+
/**
|
|
3
|
+
* The environment contract (pontive-spec 47 §6.1): the variables the SDK falls
|
|
4
|
+
* back to when the app does not pass a field. Explicit config always wins.
|
|
5
|
+
*
|
|
6
|
+
* | Variable | Holds |
|
|
7
|
+
* | ------------------------ | -------------------------------------------------- |
|
|
8
|
+
* | `PONTIVE_ISSUER` | the instance's issuer (its auth domain origin) |
|
|
9
|
+
* | `PONTIVE_CLIENT_ID` | the app's id |
|
|
10
|
+
* | `PONTIVE_CLIENT_SECRET` | a confidential (`web`) app's client secret |
|
|
11
|
+
* | `PONTIVE_SESSION_SECRET` | 32+ random characters, generated locally |
|
|
12
|
+
* | `PONTIVE_SECRET_KEY` | the instance's secret key (management calls; not read here) |
|
|
13
|
+
* | `PONTIVE_INSTANCE_ID` | the instance's id (not secret; not read here) |
|
|
14
|
+
*
|
|
15
|
+
* And for keyless mode (§6.2): `PONTIVE_KEYLESS` (`0` turns it off),
|
|
16
|
+
* `PONTIVE_API_URL` (where the provisioning routes live, default
|
|
17
|
+
* `https://api.pontive.com`) and `PONTIVE_REGION` (the region to provision in;
|
|
18
|
+
* default: the one nearest the caller).
|
|
19
|
+
*/
|
|
20
|
+
export declare const PONTIVE_ENV: {
|
|
21
|
+
readonly issuer: "PONTIVE_ISSUER";
|
|
22
|
+
readonly clientId: "PONTIVE_CLIENT_ID";
|
|
23
|
+
readonly clientSecret: "PONTIVE_CLIENT_SECRET";
|
|
24
|
+
readonly sessionSecret: "PONTIVE_SESSION_SECRET";
|
|
25
|
+
readonly secretKey: "PONTIVE_SECRET_KEY";
|
|
26
|
+
readonly instanceId: "PONTIVE_INSTANCE_ID";
|
|
27
|
+
readonly apiUrl: "PONTIVE_API_URL";
|
|
28
|
+
readonly region: "PONTIVE_REGION";
|
|
29
|
+
readonly keyless: "PONTIVE_KEYLESS";
|
|
30
|
+
};
|
|
31
|
+
export type Env = Readonly<Record<string, string | undefined>>;
|
|
32
|
+
/** `process.env`, or nothing where there is no `process` (a browser, some edge runtimes). */
|
|
33
|
+
export declare function processEnv(): Env;
|
|
34
|
+
/** The config with every field the app left out taken from the environment. */
|
|
35
|
+
export declare function withEnvFallback(config: ServerAuthConfig, env?: Env): ServerAuthConfig;
|
|
36
|
+
/** `NODE_ENV === "development"`: `next dev`, `vite`, and the like. Never a production build. */
|
|
37
|
+
export declare function isDevelopment(env?: Env): boolean;
|
|
38
|
+
/**
|
|
39
|
+
* Whether keyless mode applies (pontive-spec 47 §6.2, decision E3): in
|
|
40
|
+
* development only, with no issuer passed or in `PONTIVE_ISSUER`, unless
|
|
41
|
+
* `PONTIVE_KEYLESS=0`. Anywhere else a missing issuer is the usual
|
|
42
|
+
* `issuer is required` error.
|
|
43
|
+
*/
|
|
44
|
+
export declare function keylessApplies(config: ServerAuthConfig, env?: Env): boolean;
|
package/dist/index.cjs
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const k=require("./keyless.cjs"),y=require("./oidc--We55Nrh.cjs"),F=require("jose"),ve=10080*60;function re(e){const t=e.clientSecret?"server":"browser",n=["issuer","clientId"];t==="server"&&n.push("sessionSecret");for(const s of n)if(!e[s]){const c={issuer:"PONTIVE_ISSUER",clientId:"PONTIVE_CLIENT_ID",sessionSecret:"PONTIVE_SESSION_SECRET"}[s];throw new Error(`@pontive/server: ${s} is required${c?` (pass it, or set ${c})`:""}`)}if(t==="server"&&e.sessionSecret.length<32)throw new Error("@pontive/server: sessionSecret must be at least 32 characters");if(e.baseUrl)try{new URL(e.baseUrl)}catch{throw new Error(`@pontive/server: baseUrl "${e.baseUrl}" is not an absolute URL`)}return{mode:t,authPath:(e.authPath??"/__pontive").replace(/\/+$/,""),issuer:e.issuer.replace(/\/+$/,""),clientId:e.clientId,clientSecret:e.clientSecret||void 0,sessionSecret:e.sessionSecret??"",baseUrl:e.baseUrl?new URL(e.baseUrl).origin:void 0,scopes:e.scopes??"openid email profile offline_access",basePath:(e.basePath??"/api/auth").replace(/\/+$/,""),redirectUri:e.redirectUri,signInPath:e.signInPath??"/login",afterSignInPath:e.afterSignInPath??"/",prompt:e.prompt,cookieName:e.cookieName??"pontive_session",secureCookies:e.secureCookies,iframeSafe:e.iframeSafe??"auto",previewCallback:e.previewCallback??"auto",sessionMaxAgeSeconds:e.sessionMaxAgeSeconds??ve,refreshSkewSeconds:e.refreshSkewSeconds??60,fetch:e.fetch??((...s)=>fetch(...s)),logger:e.logger??console}}const U={issuer:"PONTIVE_ISSUER",clientId:"PONTIVE_CLIENT_ID",clientSecret:"PONTIVE_CLIENT_SECRET",sessionSecret:"PONTIVE_SESSION_SECRET",secretKey:"PONTIVE_SECRET_KEY",instanceId:"PONTIVE_INSTANCE_ID",apiUrl:"PONTIVE_API_URL",region:"PONTIVE_REGION",keyless:"PONTIVE_KEYLESS"};function M(){try{return globalThis.process?.env??{}}catch{return{}}}const x=e=>e&&e.trim()?e.trim():void 0;function ye(e,t=M()){return{...e,issuer:e.issuer||x(t[U.issuer]),clientId:e.clientId||x(t[U.clientId]),clientSecret:e.clientSecret||x(t[U.clientSecret]),sessionSecret:e.sessionSecret||x(t[U.sessionSecret])}}function se(e=M()){return e.NODE_ENV==="development"}function ke(e,t=M()){return se(t)&&!e.issuer&&t[U.keyless]?.trim()!=="0"}const z=3500,K=16;function N(e){const t=new Map;if(!e)return t;for(const n of e.split(";")){const s=n.indexOf("=");if(s<0)continue;const c=n.slice(0,s).trim();!c||t.has(c)||t.set(c,n.slice(s+1).trim())}return t}function G(e){return[...e].map(([t,n])=>`${t}=${n}`).join("; ")}function A(e,t,n){const s=n.sameSite??"Lax",c=[`${e}=${t}`,"Path=/","HttpOnly",`SameSite=${s}`,`Max-Age=${n.maxAge}`];return(n.secure||s==="None")&&c.push("Secure"),c.join("; ")}function C(e,t){return t===0?e:`${e}.${t}`}function _e(e,t){const n=e.get(t);if(n===void 0)return null;let s=n;for(let c=1;c<K;c++){const a=e.get(C(t,c));if(a===void 0)break;s+=a}return s}function Ie(e,t,n,s){const c=[],a=Math.max(1,Math.ceil(n.length/z));for(let i=0;i<a;i++){const l=n.slice(i*z,(i+1)*z);e.set(C(t,i),l),c.push(A(C(t,i),l,s))}for(let i=a;i<K;i++){const l=C(t,i);if(!e.has(l))break;e.delete(l),c.push(A(l,"",{...s,maxAge:0}))}return c}function B(e,t,n){const s=[];for(let c=0;c<K;c++){const a=C(t,c);if(!e.has(a)){if(c>0)break;continue}e.delete(a),s.push(A(a,"",{...n,maxAge:0}))}return s}const H="switch-organization",oe="organization_error",J=e=>Array.isArray(e)?e.filter(t=>typeof t=="string"):[];function ie(e){const t=e.org_id;return typeof t!="string"||t===""?null:{id:t,roles:J(e.roles),permissions:J(e.permissions)}}function ge(e){try{return F.decodeJwt(e)}catch{return{}}}function Pe(e,t,n="/"){const s=new URLSearchParams({organization_id:t,returnTo:n});return`${e}/${H}?${s.toString()}`}const ae="__Host-pontive_access",ce="__Secure-pontive_session_state";function Te(e){const t=n=>typeof e[n]=="string"?e[n]:void 0;return{id:t("sub")??"",email:t("email"),name:t("name")??t("email"),username:t("preferred_username"),picture:t("picture"),emailVerified:e.email_verified===!0}}function be(e){const t={issuer:e.issuer,clientId:e.clientId},n=new Map;function s(i){for(const[l,d]of n)d.expiresAt<=i&&n.delete(l)}async function c(i,l){const d=Date.now();s(d);const u=await y.sha256Hex(i),h=n.get(u);if(h)return h.profile;const m=y.userInfo(t,e.fetch,i).catch(E=>(n.delete(u),e.logger.warn("[pontive] could not read the user's profile:",E instanceof Error?E.message:String(E)),null));return n.set(u,{expiresAt:l,profile:m}),m}async function a(i){const l=N(i).get(ae);if(!l)return null;let d;try{d=await y.verifyJwt(t,e.fetch,l)}catch(m){return m.code!=="ERR_JWT_EXPIRED"&&e.logger.warn("[pontive] access token cookie refused:",m instanceof Error?m.message:String(m)),null}const u=(d.exp??0)*1e3,h=await c(l,u);return{user:Te({...h,...d,sub:d.sub}),accessToken:l,expiresAt:u,sessionId:typeof d.sid=="string"?d.sid:void 0,organization:ie(d),claims:d}}return{async handle(i){const l=new URL(i.url);if(l.pathname!==`${e.basePath}/${H}`)return null;const d=l.searchParams.get("organization_id"),u=Re(l.searchParams.get("returnTo"));if(!d)return Y(u);const h=new URL(`${e.authPath}/oauth2/session`,l.origin);return h.searchParams.set("client_id",e.clientId),h.searchParams.set("return_to",u),h.searchParams.set("organization_id",d),Y(h.pathname+h.search)},getSession:a,async refresh(i){const l=i.headers.get("cookie"),d=await a(l),u={session:d,setCookies:[],cookieHeader:l??""};if(d||!N(l).has(ce))return u;const h=new URL(i.url),m=new URL(`${e.authPath}/oauth2/session`,h.origin);return m.searchParams.set("client_id",e.clientId),m.searchParams.set("return_to",h.pathname+h.search),{...u,handshake:m.pathname+m.search}}}}function Re(e){return e&&e.startsWith("/")&&!e.startsWith("//")&&!e.startsWith("/\\")?e:"/"}function Y(e){return new Response(null,{status:302,headers:{location:e,"cache-control":"no-store"}})}const Ne=["lovable.app","lovableproject.com","lovable.dev","vusercontent.net","v0.dev","v0.app","webcontainer-api.io","webcontainer.io","replit.dev","replit.app","lp.dev","bolt.host","csb.app"];function Ue(e){const t=e.toLowerCase().replace(/\.$/,"");return Ne.some(n=>t===n||t.endsWith(`.${n}`))}const Oe={lovable:["*.lovableproject.com","*.lovable.app","*.lovable.dev"],v0:["*.vusercontent.net","*.lite.vusercontent.net","*.v0.app","*.v0.dev"],vercel:["*.vercel.app"],replit:["*.replit.dev","*.*.replit.dev","*.replit.app"],bolt:["*.bolt.host","*.webcontainer-api.io","*.local-credentialless.webcontainer-api.io","*.local-corp.webcontainer-api.io"],codesandbox:["*.csb.app"]},Ce="/oauth2/preview-callback",Ae="pontive:authorization-response",Le=/^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$/;function $e(e){let t;try{t=new URL(e)}catch{return null}if(t.protocol!=="https:"||t.port!==""||t.origin!==e)return null;const n=t.hostname.split(".");for(const[s,c]of Object.entries(Oe))for(const a of c){const i=a.split(".");if(i.length===n.length&&i.every((l,d)=>l==="*"?Le.test(n[d]):l===n[d]))return s}return null}function xe(e,t){return`${e.replace(/\/$/,"")}${Ce}?origin=${encodeURIComponent(t)}`}const Ve=3e4;class Me{constructor(t=Ve){this.recentMs=t}recentMs;inFlight=new Map;recent=new Map;async run(t,n){const s=await y.sha256Hex(t);this.sweep();const c=this.recent.get(s);if(c)return c.result;let a=this.inFlight.get(s);return a||(a=n().then(i=>(this.recent.set(s,{at:Date.now(),result:i}),i)).finally(()=>this.inFlight.delete(s)),this.inFlight.set(s,a)),a}sweep(){const t=Date.now()-this.recentMs;for(const[n,s]of this.recent)s.at<t&&this.recent.delete(n)}}const Z=new Map;function le(e){let t=Z.get(e);return t||(t=crypto.subtle.digest("SHA-256",new TextEncoder().encode(e)).then(n=>new Uint8Array(n)),Z.set(e,t)),t}async function X(e,t,n){return new F.EncryptJWT(e).setProtectedHeader({alg:"dir",enc:"A256GCM"}).setIssuedAt().setExpirationTime(`${n}s`).encrypt(await le(t))}async function Q(e,t){try{const{payload:n}=await F.jwtDecrypt(e,await le(t));return n}catch{return null}}const He=900,q=600;function ee(e,t){return e&&e.startsWith("/")&&!e.startsWith("//")&&!e.startsWith("/\\")?e:t}function b(e,t=[]){const n=new Headers({location:e,"cache-control":"no-store"});for(const s of t)n.append("set-cookie",s);return new Response(null,{status:302,headers:n})}const De="pontive:popup-complete";function ze(e,t,n){const c=`<!doctype html><meta charset="utf-8"><title>Signing in</title><script type="application/json" id="pontive-popup">${JSON.stringify({message:{type:De,url:e},origin:t}).replace(/</g,"\\u003c")}<\/script><script>(function(){var d=JSON.parse(document.getElementById("pontive-popup").textContent);var go=function(){window.location.replace(d.message.url)};if(window.opener&&window.opener!==window){try{window.opener.postMessage(d.message,d.origin)}catch(e){}window.close();setTimeout(go,1000)}else{go()}})()<\/script>`,a=new Headers({"content-type":"text/html; charset=utf-8","cache-control":"no-store","content-security-policy":"default-src 'none'; script-src 'unsafe-inline'","x-content-type-options":"nosniff"});for(const i of n)a.append("set-cookie",i);return new Response(c,{status:200,headers:a})}function je(e){const t=y.randomValue(),s=`<!doctype html><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>Sign in</title><style>body{font-family:system-ui,sans-serif;margin:4rem auto;max-width:28rem;padding:0 1rem}</style><p>This preview signs in in a new window.</p><p><button id="go" type="button">Sign in</button></p><p id="status"></p><script type="application/json" id="pontive-preview-signin">${JSON.stringify({...e,type:Ae}).replace(/</g,"\\u003c")}<\/script><script nonce="${t}">(function(){var d=JSON.parse(document.getElementById("pontive-preview-signin").textContent);var s=document.getElementById("status");var w=null;window.addEventListener("message",function(e){if(!w||e.source!==w||e.origin!==d.authOrigin)return;var m=e.data;if(!m||m.type!==d.type||!m.response||typeof m.response!=="object")return;var u=new URL(d.callbackUrl);["code","state","iss","error","error_description","error_uri"].forEach(function(k){var v=m.response[k];if(typeof v==="string")u.searchParams.set(k,v)});try{w.close()}catch(x){}if(u.origin===location.origin)location.replace(u.toString())});document.getElementById("go").addEventListener("click",function(){w=window.open(d.popupUrl,"pontive_signin_popup","popup=yes,width=500,height=680");s.textContent=w?"Finish signing in in the new window.":"The sign-in window was blocked. Allow popups for this site and try again."})})()<\/script>`;return new Response(s,{status:200,headers:{"content-type":"text/html; charset=utf-8","cache-control":"no-store","content-security-policy":`default-src 'none'; script-src 'nonce-${t}'; style-src 'unsafe-inline'; base-uri 'none'; form-action 'none'`,"x-content-type-options":"nosniff","referrer-policy":"no-referrer"}})}function P(e,t){if(e.baseUrl)return e.baseUrl;const n=t.headers.get("x-forwarded-host")?.split(",")[0]?.trim()||t.headers.get("host")?.trim();if(n){const s=t.headers.get("x-forwarded-proto")?.split(",")[0]?.trim()||new URL(t.url).protocol.replace(":","");try{return new URL(`${s}://${n}`).origin}catch{}}return new URL(t.url).origin}function Fe(e){const t=s=>typeof e[s]=="string"?e[s]:void 0,n=t("name")??([t("given_name"),t("family_name")].filter(Boolean).join(" ")||void 0)??t("email");return{id:e.sub??"",email:t("email"),name:n,username:t("preferred_username"),picture:t("picture"),emailVerified:e.email_verified===!0}}function te(e){return Date.now()+(e.expires_in??He)*1e3}function ue(e){return e.mode==="browser"?be(e):Ke(e)}function Ke(e){const t={issuer:e.issuer,clientId:e.clientId,clientSecret:e.clientSecret},n=`${e.cookieName}_tx`,s=new Me,c=r=>e.secureCookies??P(e,r).startsWith("https:"),a=r=>e.iframeSafe===!0||e.iframeSafe==="auto"&&Ue(new URL(P(e,r)).hostname),i=(r,o)=>a(r)?{maxAge:o,secure:!0,sameSite:"None"}:{maxAge:o,secure:c(r)},l=r=>e.previewCallback==="always"||e.previewCallback==="auto"&&$e(P(e,r))!==null,d=r=>`${P(e,r)}${e.basePath}/callback`,u=r=>l(r)?xe(e.issuer,P(e,r)):e.redirectUri??d(r),h=(r,o)=>{const p=new URL(e.signInPath,P(e,r));return o&&p.searchParams.set("error",o),p.toString()};async function m(r){const o=_e(r,e.cookieName);if(o===null)return null;const p=await Q(o,e.sessionSecret);return p||e.logger.warn("[pontive] session cookie could not be read (sealed with another secret, or truncated)"),p}async function E(r,o,p){const f=await X({...o},e.sessionSecret,e.sessionMaxAgeSeconds);return Ie(r,e.cookieName,f,i(p,e.sessionMaxAgeSeconds))}function T(r){const{refreshToken:o,...p}=r,f=ge(r.accessToken);return{...p,organization:ie(f),claims:f}}async function O(r){const o=new URL(r.url),p=l(r),f=o.searchParams.get("popup")==="1";if(p&&!f){const S=new URL(`${e.basePath}/login`,P(e,r));return o.searchParams.forEach((_,R)=>S.searchParams.set(R,_)),S.searchParams.set("popup","1"),je({popupUrl:S.toString(),authOrigin:new URL(e.issuer).origin,callbackUrl:d(r)})}const v={state:y.randomValue(),verifier:y.randomValue(),nonce:y.randomValue(),returnTo:ee(o.searchParams.get("returnTo")??o.searchParams.get("next"),e.afterSignInPath),popup:f,redirectUri:u(r),previewCallback:p},w=await y.authorizationUrl(t,e.fetch,{redirectUri:v.redirectUri,scopes:e.scopes,state:v.state,nonce:v.nonce,codeChallenge:await y.pkceChallenge(v.verifier),prompt:e.prompt,organizationId:o.searchParams.get("organization_id")??void 0,loginHint:o.searchParams.get("login_hint")??void 0}),g=await X({...v},e.sessionSecret,q);return b(w,[A(n,g,i(r,q))])}async function L(r){const o=new URL(r.url),p=N(r.headers.get("cookie")),f=[A(n,"",i(r,0))],v=p.get(n),w=v?await Q(v,e.sessionSecret):null,g=o.searchParams.get("code"),S=I=>w?.popup&&!w.previewCallback?ze(I,P(e,r),f):b(I,f),_=o.searchParams.get("error");if(_)return S(h(r,_));if(!w||!g||o.searchParams.get("state")!==w.state)return S(h(r,"invalid_state"));const R=o.searchParams.get("iss");if(w.previewCallback&&R!==null&&R!==e.issuer)return S(h(r,"invalid_issuer"));try{const I=await y.exchangeCode(t,e.fetch,{code:g,codeVerifier:w.verifier,redirectUri:w.redirectUri??u(r)});if(!I.id_token)throw new Error("the token response carried no id_token; is the openid scope requested?");const D=await y.verifyIdToken(t,e.fetch,I.id_token,w.nonce),Ee={user:Fe(D),accessToken:I.access_token,refreshToken:I.refresh_token,expiresAt:te(I),sessionId:typeof D.sid=="string"?D.sid:void 0};f.push(...await E(p,Ee,r))}catch(I){return e.logger.warn("[pontive] sign-in failed:",I instanceof Error?I.message:String(I)),S(h(r,"exchange_failed"))}return S(new URL(w.returnTo,P(e,r)).toString())}async function $(r){const o=N(r.headers.get("cookie")),p=await m(o),f=B(o,e.cookieName,i(r,0));let v=h(r);try{v=await y.endSessionUrl(t,e.fetch,{postLogoutRedirectUri:h(r),sessionId:p?.sessionId})??v}catch(w){e.logger.warn("[pontive] could not reach the issuer to end its session:",w instanceof Error?w.message:String(w))}return b(v,f)}function W(r,o){return{...r,accessToken:o.access_token,refreshToken:o.refresh_token??r.refreshToken,expiresAt:te(o)}}async function me(r){const o=new URL(r.url),p=N(r.headers.get("cookie")),f=ee(o.searchParams.get("returnTo"),e.afterSignInPath),v=o.searchParams.get("organization_id"),w=_=>{const R=new URL(f,P(e,r));return _&&R.searchParams.set(oe,_),R.toString()},g=await m(p);if(!g?.refreshToken)return b(h(r));if(!v)return b(w("invalid_request"));let S;try{S=await y.refreshTokens(t,e.fetch,g.refreshToken,v)}catch(_){return _ instanceof y.TokenEndpointError&&_.code==="invalid_request"?b(w("not_a_member")):(e.logger.warn("[pontive] organization switch failed:",_ instanceof Error?_.message:String(_)),b(w("switch_failed")))}return b(w(),await E(p,W(g,S),r))}async function Se(r){try{const o=await y.refreshTokens(t,e.fetch,r.refreshToken);return W(r,o)}catch(o){if(o instanceof y.TokenEndpointError&&o.status>=400&&o.status<500)return e.logger.warn("[pontive] refresh refused; signing out:",o.message),null;throw o}}return{async handle(r){const{pathname:o}=new URL(r.url);if(!o.startsWith(`${e.basePath}/`))return null;const p=o.slice(e.basePath.length+1);return p==="login"&&r.method==="GET"?O(r):p==="callback"&&r.method==="GET"?L(r):p==="logout"&&(r.method==="GET"||r.method==="POST")?$(r):p===H&&(r.method==="GET"||r.method==="POST")?me(r):null},async getSession(r){const o=await m(N(r));return o?Date.now()>=o.expiresAt?(e.logger.warn("[pontive] the session's access token has expired and getSession cannot refresh it. Run the SDK's middleware on this path so it refreshes before the request is handled."),null):T(o):null},async refresh(r){const o=N(r.headers.get("cookie")),p=S=>({session:S,setCookies:[],cookieHeader:r.headers.get("cookie")??""}),f=await m(o);if(!f)return p(null);if(new URL(r.url).pathname.startsWith(`${e.basePath}/`))return p(Date.now()<f.expiresAt?T(f):null);if(Date.now()<f.expiresAt-e.refreshSkewSeconds*1e3)return p(T(f));const v=()=>({session:null,setCookies:B(o,e.cookieName,i(r,0)),cookieHeader:G(o)});if(!f.refreshToken)return v();let w;try{w=await s.run(f.refreshToken,()=>Se(f))}catch(S){return e.logger.warn("[pontive] refresh failed, will retry:",S instanceof Error?S.message:String(S)),p(Date.now()<f.expiresAt?T(f):null)}if(!w)return v();const g=await E(o,w,r);return{session:T(w),setCookies:g,cookieHeader:G(o)}}}}const he="1.23.0",pe="claim";function We(e={},t={}){const n=M(),s=ye(e,n);if(ke(s,n))return Ge(s,t);const c=re(s),a=se(n)?()=>fe(de(t),c.issuer):async()=>null;return we(c,ue(c),a)}function de(e){if(e.projectDir)return e.projectDir;const t=globalThis.process;if(typeof t?.cwd!="function")throw new k.KeylessUnavailableError("keyless mode needs a project directory (process.cwd)");return t.cwd()}async function fe(e,t){try{const n=await k.readKeylessRecord(e);return n?.claim_token&&n.issuer.replace(/\/+$/,"")===t?n:null}catch{return null}}function V(e,t){return new Response(`${t}
|
|
2
|
+
`,{status:e,headers:{"content-type":"text/plain; charset=utf-8","cache-control":"no-store"}})}function we(e,t,n){const s=`${e.basePath}/${pe}`;async function c(a){try{const i=await k.claimLinkFor(a,{fetch:e.fetch});return new Response(null,{status:302,headers:{location:i.url,"cache-control":"no-store","referrer-policy":"no-referrer"}})}catch(i){return i instanceof k.PontiveApiError&&i.status===409?V(409,"This Pontive instance has already been claimed. Nothing in your app changes; manage it in the Pontive dashboard."):i instanceof k.PontiveApiError&&i.status===404?V(410,k.goneMessage(a,"expired")):(e.logger.warn("[pontive] could not create a claim link:",i instanceof Error?i.message:String(i)),V(502,"Pontive could not create a claim link just now. Try again, or run `npx pontive claim`."))}}return{async handle(a){if(a.method==="GET"&&new URL(a.url).pathname===s){const i=await n();if(i)return c(i)}return t.handle(a)},getSession:a=>t.getSession(a),refresh:a=>t.refresh(a),async providerProps(){const a=await n();return{appId:e.clientId,domain:e.mode==="browser"?e.authPath:e.issuer,...a?{claimUrl:s}:{}}}}}const j=new Map,ne=new Set;function Ge(e,t){const n=e.logger??console;let s,c,a=!1;async function i(){const u=de(t),h=(e.basePath??"/api/auth").replace(/\/+$/,"");let m=j.get(u);m||(m=k.ensureKeylessInstance({dir:u,redirectUris:e.redirectUri?[e.redirectUri]:k.loopbackCallbacks(h),client:{name:t.clientName??"@pontive/server",version:he},fetch:e.fetch}),j.set(u,m),m.catch(()=>j.delete(u)));const E=await m;ne.has(u)||(ne.add(u),n.warn(`
|
|
3
|
+
${k.keylessMessage(E.record,{created:E.created})}
|
|
4
|
+
`));const T=globalThis.process;if(T?.env)for(const[L,$]of Object.entries(E.env))$!==void 0&&!T.env[L]&&(T.env[L]=$);if(!e.clientSecret&&!E.env.PONTIVE_CLIENT_SECRET)throw new Error(`@pontive/server: ${k.KEYLESS_FILE} names ${E.record.instance_id}, but PONTIVE_CLIENT_SECRET is neither in ${k.ENV_FILE} nor in the environment. Put it back, or run \`npx pontive init --reset\`.`);const O=re({...e,issuer:e.issuer||E.env.PONTIVE_ISSUER,clientId:e.clientId||E.env.PONTIVE_CLIENT_ID,clientSecret:e.clientSecret||E.env.PONTIVE_CLIENT_SECRET,sessionSecret:e.sessionSecret||E.env.PONTIVE_SESSION_SECRET,fetch:Be(e.fetch,E.record,n)});return we(O,ue(O),()=>fe(u,O.issuer))}function l(){return c?Promise.reject(c):(s??=i().catch(u=>{throw s=void 0,u instanceof k.KeylessInstanceGoneError&&(c=u),u}),s)}function d(u){return u instanceof k.KeylessUnavailableError?(a||(a=!0,n.warn(`[pontive] ${u.message}. Requests here proceed without a session until the dev server restarts with the PONTIVE_* variables keyless mode wrote to .env.local.`)),!0):!1}return{async handle(u){try{return await(await l()).handle(u)}catch(h){if(d(h))return V(503,"Pontive keyless mode can't run in this runtime; restart the dev server.");throw h}},async getSession(u){try{return await(await l()).getSession(u)}catch(h){if(d(h))return null;throw h}},async refresh(u){try{return await(await l()).refresh(u)}catch(h){if(d(h))return{session:null,setCookies:[],cookieHeader:u.headers.get("cookie")??""};throw h}},async providerProps(){return(await l()).providerProps()}}}function Be(e,t,n){const s=e??((...a)=>fetch(...a));let c=!1;return async(a,i)=>{const l=await s(a,i);return l.status===401&&!c&&(typeof a=="string"?a:a instanceof URL?a.toString():a.url).startsWith(t.issuer)&&(c=!0,n.warn(`[pontive] ${k.goneMessage(t,"refused")}`)),l}}exports.ACCESS_COOKIE=ae;exports.CLAIM_ROUTE=pe;exports.ORGANIZATION_ERROR_PARAM=oe;exports.PONTIVE_ENV=U;exports.PONTIVE_SERVER_VERSION=he;exports.SESSION_HINT_COOKIE=ce;exports.SWITCH_ORGANIZATION_ROUTE=H;exports.createServerAuth=We;exports.switchOrganizationPath=Pe;
|
|
5
|
+
//# sourceMappingURL=index.cjs.map
|