@passflow/node 0.1.3 → 0.3.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.d.mts CHANGED
@@ -1,4 +1,4 @@
1
- import { a as verifiedBy, i as rolesOf, n as TenantMembership, r as Verifier, t as PassflowClaims } from "./claims-BHJhnzch.mjs";
1
+ import { a as ResourceChallenge, c as authenticateRequest, d as TenantMembership, f as Verifier, i as Requirement, l as evaluate, m as verifiedBy, n as ProtectedResource, o as ResourceMetadata, p as rolesOf, r as Rejection, s as authenticate, t as Decision, u as PassflowClaims } from "./evaluate-BAJUQu_Z.mjs";
2
2
  export declare const ACR_NONE = "0";
3
3
  export declare const AAL1 = "1";
4
4
  export declare const AAL2 = "2";
@@ -44,7 +44,7 @@ export declare const CHALLENGE_HEADER = "WWW-Authenticate";
44
44
  export declare const CORS_EXPOSED_HEADERS: readonly string[];
45
45
  type PassflowAuthErrorCode = 'missing_token' | 'invalid_token' | 'jwks_unavailable';
46
46
  /** Why a token was refused. Only `invalid_token` carries one. */
47
- type InvalidTokenReason = 'expired' | 'not_yet_valid' | 'exp_missing' | 'issuer' | 'audience' | 'type' | 'signature' | 'alg' | 'kid_missing' | 'key_unknown' | 'crit' | 'malformed';
47
+ type InvalidTokenReason = 'expired' | 'not_yet_valid' | 'exp_missing' | 'issuer' | 'audience' | 'type' | 'signature' | 'alg' | 'kid_missing' | 'key_unknown' | 'crit' | 'typ' | 'malformed';
48
48
  /**
49
49
  * An authentication failure. The message is fixed per code and carries nothing from the token, the
50
50
  * request or the JWKS URL. A jose error is never attached as `cause`: jose's claim errors keep the
@@ -69,45 +69,17 @@ export declare class PassflowUsageError extends Error {
69
69
  * and CJS builds are both loaded, where `instanceof` alone would say no.
70
70
  */
71
71
  export declare function isPassflowAuthError(e: unknown): e is PassflowAuthError;
72
- type Requirement = {
73
- kind: 'acr';
74
- min: string;
75
- } | {
76
- kind: 'fresh';
77
- maxAgeSeconds: number;
78
- };
79
- type Decision = {
80
- kind: 'allow';
81
- } | {
82
- kind: 'reject';
83
- status: 401 | 500 | 503;
84
- headers: Record<string, string>;
85
- };
86
- /** A rejected `Decision`: a `ResponseInit` as it stands (`new Response(null, rejection)`). */
87
- type Rejection = Extract<Decision, {
88
- kind: 'reject';
89
- }>;
90
- /**
91
- * Decides one requirement against claims. No claims means the middleware was composed wrongly, so the answer
92
- * is a 500 with no challenge: never a step-up, which the SDK would try to satisfy, and never a 401, because a
93
- * wiring bug must not be reported as a bad token. Throws `TypeError` on an invalid requirement.
94
- */
95
- export declare function evaluate(claims: PassflowClaims | undefined, requirement: Requirement): Decision;
96
- /**
97
- * Authenticates a request. `existing` claims are reused only when `verifier` produced that exact object;
98
- * otherwise the presented header is verified with `verifier`, so a token outside this verifier's trust policy
99
- * is rejected as not valid here, never as insufficient. Never rejects: a failure is a `{ reject }` value.
100
- */
101
- export declare function authenticate(verifier: Verifier, authorization: string | undefined | null, existing?: PassflowClaims): Promise<{
102
- claims: PassflowClaims;
103
- } | {
104
- reject: Rejection;
105
- }>;
106
72
  type VerifierConfig = {
107
- /** Required, exact match against `iss`. */
108
- issuer: string;
109
- /** Required: the Passflow application IDs that may call this API. A token must name at least one. */
110
- audience: string | string[];
73
+ /**
74
+ * Required, exact match against `iss`. The type takes `undefined` so that a value read from the environment
75
+ * passes the type check; `createVerifier` throws a `TypeError` when it is missing or empty.
76
+ */
77
+ issuer: string | undefined;
78
+ /**
79
+ * Required: the Passflow application IDs that may call this API. A token must name at least one. `undefined`
80
+ * passes the type check, as for `issuer`, and `createVerifier` throws a `TypeError` for it.
81
+ */
82
+ audience: string | string[] | undefined;
111
83
  /** Default: `{issuer}/.well-known/jwks.json`, Passflow's fixed path. OIDC discovery is not fetched. */
112
84
  jwksUrl?: string;
113
85
  /** Permits `http://` on a non-loopback host, for private networks. Default false. */
@@ -142,4 +114,25 @@ type VerifierConfig = {
142
114
  * built per request would defeat it.
143
115
  */
144
116
  export declare function createVerifier(config: VerifierConfig): Verifier;
145
- export { type Decision, type PassflowAuthErrorCode, type PassflowClaims, type Rejection, type Requirement, type TenantMembership, type Verifier, type VerifierConfig, rolesOf, verifiedBy };
117
+ type ProtectedResourceConfig = Omit<VerifierConfig, 'audience'> & {
118
+ /**
119
+ * Required: the exact URL clients name as the resource, and the audience a token must carry. It must use https
120
+ * unless the host is loopback, with no userinfo and no fragment. `undefined` passes the type check, as for
121
+ * `issuer`, and `createProtectedResource` throws a `TypeError` for it.
122
+ */
123
+ resource: string | undefined;
124
+ /**
125
+ * The scopes a client needs to start: the 401 challenge and `scopes_supported` list them. `offline_access` is
126
+ * not a scope of a resource and throws.
127
+ */
128
+ scopes?: string[];
129
+ /** Served as `resource_name`. */
130
+ name?: string;
131
+ };
132
+ /**
133
+ * Builds an OAuth protected resource, such as an MCP server: a verifier whose only audience is the resource, the
134
+ * RFC 9728 metadata that tells a client where to get a token, and the challenge parameters that name that metadata.
135
+ * Pass it to an adapter in place of a verifier. Touches no network. Throws `TypeError` on an invalid configuration.
136
+ */
137
+ export declare function createProtectedResource(config: ProtectedResourceConfig): ProtectedResource;
138
+ export { type Decision, type PassflowAuthErrorCode, type PassflowClaims, type ProtectedResource, type ProtectedResourceConfig, type Rejection, type Requirement, type ResourceChallenge, type ResourceMetadata, type TenantMembership, type Verifier, type VerifierConfig, authenticate, authenticateRequest, evaluate, rolesOf, verifiedBy };
package/dist/index.mjs CHANGED
@@ -1,4 +1,5 @@
1
- import { C as acrLevel, S as ACR_NONE, _ as formatChallenge, b as AAL2, c as isPassflowAuthError, f as extractClaims, g as assertMaxAge, h as verifiedBy, i as evaluate, l as CHALLENGE_HEADER, m as rolesOf, o as PassflowAuthError, p as recordProvenance, r as authenticate, s as PassflowUsageError, u as CORS_EXPOSED_HEADERS, v as extractBearer, w as acrSatisfies, x as AAL3, y as AAL1 } from "./evaluate-BTuol-Oa.mjs";
1
+ import { C as AAL3, E as acrSatisfies, S as AAL2, T as acrLevel, _ as verifiedBy, a as authenticateRequest, b as extractBearer, c as PassflowAuthError, d as CHALLENGE_HEADER, f as CORS_EXPOSED_HEADERS, g as rolesOf, h as recordProvenance, i as authenticate, l as PassflowUsageError, m as extractClaims, n as assertScopes, o as evaluate, u as isPassflowAuthError, v as assertMaxAge, w as ACR_NONE, x as AAL1, y as formatChallenge } from "./evaluate-CHts4VKy.mjs";
2
+ import { t as isLoopbackHost } from "./loopback-CDiL_KzV.mjs";
2
3
  import { base64url, createLocalJWKSet, errors, importJWK, jwtVerify } from "jose";
3
4
  // src/header.ts
4
5
  const ALLOWED_ALGORITHMS = ["RS256", "ES256"];
@@ -6,6 +7,12 @@ const UTF8 = new TextDecoder("utf-8", {
6
7
  fatal: true,
7
8
  ignoreBOM: true
8
9
  });
10
+ /** The generic JWT media type and the access token one of RFC 9068. Media type names are case-insensitive. */
11
+ const ACCEPTED_TYP = [
12
+ "jwt",
13
+ "at+jwt",
14
+ "application/at+jwt"
15
+ ];
9
16
  const BASE64URL$1 = /^[A-Za-z0-9_-]+$/;
10
17
  function decodeProtectedHeader(segment) {
11
18
  if (!BASE64URL$1.test(segment) || segment.length % 4 === 1) return;
@@ -18,7 +25,7 @@ function decodeProtectedHeader(segment) {
18
25
  }
19
26
  /**
20
27
  * Header inspection, in the order Go and the corpus pin, before any key lookup: malformed, alg, crit,
21
- * kid. It has to run before jose, which reports a standard parameter in `crit` with the same code as a
28
+ * typ, kid. It has to run before jose, which reports a standard parameter in `crit` with the same code as a
22
29
  * malformed token. Throws `PassflowAuthError` with `invalid_token` and the reason.
23
30
  */
24
31
  function inspectHeader(token) {
@@ -29,6 +36,7 @@ function inspectHeader(token) {
29
36
  if (header === void 0) throw new PassflowAuthError("invalid_token", "malformed");
30
37
  if (typeof header.alg !== "string" || !ALLOWED_ALGORITHMS.includes(header.alg)) throw new PassflowAuthError("invalid_token", "alg");
31
38
  if (Object.hasOwn(header, "crit")) throw new PassflowAuthError("invalid_token", "crit");
39
+ if (Object.hasOwn(header, "typ") && !(typeof header.typ === "string" && ACCEPTED_TYP.includes(header.typ.toLowerCase()))) throw new PassflowAuthError("invalid_token", "typ");
32
40
  if (typeof header.kid !== "string" || header.kid === "") throw new PassflowAuthError("invalid_token", "kid_missing");
33
41
  }
34
42
  // src/jwks.ts
@@ -400,21 +408,6 @@ function requireAudiences(audience) {
400
408
  if (!Array.isArray(audiences) || audiences.length === 0 || !audiences.every(isNonEmptyString)) throw new TypeError("[passflow] audience must name one or more non-empty audiences");
401
409
  return [...audiences];
402
410
  }
403
- /** The host of an `http://` URL as written, without userinfo or port. A URL spelled any other way has none. */
404
- const WRITTEN_HOST = /^http:\/\/(?:[^/?#\\\s]*@)?(\[[^\]]*\]|[^/?#:@\\%\s]*)(?::\d*)?(?:[/?#]|$)/i;
405
- const LOOPBACK_IPV4 = /^127(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}$/;
406
- /**
407
- * Loopback by the host as written, the rule Go applies. WHATWG normalization would turn `127.1`, `2130706433`
408
- * and `0x7f.1` into `127.0.0.1`, so a config that starts here would fail to start a Go API. An IPv6 literal
409
- * takes the normalized form, which gives each address one spelling. A name that merely contains "localhost"
410
- * is not loopback.
411
- */
412
- function isLoopbackHost(raw, url) {
413
- const host = WRITTEN_HOST.exec(raw)?.[1]?.toLowerCase();
414
- if (host === void 0) return false;
415
- if (host.startsWith("[")) return url.hostname === "[::1]";
416
- return host === "localhost" || host.endsWith(".localhost") || LOOPBACK_IPV4.test(host);
417
- }
418
411
  /** The key set is the root of trust. The error names the rule, never the URL. */
419
412
  function requireJwksUrl(config, issuer) {
420
413
  const raw = config.jwksUrl ?? `${issuer.replace(/\/+$/, "")}/.well-known/jwks.json`;
@@ -536,4 +529,76 @@ function createVerifier(config) {
536
529
  };
537
530
  return verifier;
538
531
  }
539
- export { AAL1, AAL2, AAL3, ACR_NONE, CHALLENGE_HEADER, CORS_EXPOSED_HEADERS, PassflowAuthError, PassflowUsageError, acrLevel, acrSatisfies, assertMaxAge, authenticate, createVerifier, evaluate, extractBearer, formatChallenge, isPassflowAuthError, rolesOf, verifiedBy };
532
+ // src/resource.ts
533
+ const METADATA_WELL_KNOWN = "/.well-known/oauth-protected-resource";
534
+ const MAX_RESOURCE_BYTES = 2048;
535
+ /**
536
+ * Splits a resource into its origin, path and query. It admits no userinfo and no fragment, and nothing that needs
537
+ * escaping in a quoted challenge parameter.
538
+ */
539
+ const RESOURCE = /^([Hh][Tt][Tt][Pp][Ss]?:\/\/(?:\[[0-9A-Fa-f:.]+\]|[A-Za-z0-9._-]+)(?::[0-9]{1,5})?)(\/(?:[A-Za-z0-9._~:/@!$&'()*+,;=-]|%[0-9A-Fa-f]{2})*)?(\?(?:[A-Za-z0-9._~:/?@!$&'()*+,;=-]|%[0-9A-Fa-f]{2})*)?$/;
540
+ /** The error names the rule, never the URL. The pattern admits ASCII only, so length is bytes. */
541
+ function splitResource(resource) {
542
+ const parts = typeof resource === "string" && resource.length <= MAX_RESOURCE_BYTES ? RESOURCE.exec(resource) : null;
543
+ if (typeof resource !== "string" || parts === null) throw new TypeError("[passflow] resource must be an absolute http or https URL of at most 2048 bytes, without userinfo or a fragment");
544
+ let url;
545
+ try {
546
+ url = new URL(resource);
547
+ } catch {
548
+ throw new TypeError("[passflow] resource must be a valid URL");
549
+ }
550
+ if (url.protocol !== "https:" && !isLoopbackHost(resource, url)) throw new TypeError("[passflow] resource must use https unless the host is loopback");
551
+ return {
552
+ resource,
553
+ origin: parts[1] ?? "",
554
+ path: parts[2] ?? "",
555
+ query: parts[3] ?? ""
556
+ };
557
+ }
558
+ function requireScopeList(scopes) {
559
+ if (scopes === void 0) return [];
560
+ if (!Array.isArray(scopes)) throw new TypeError("[passflow] scopes must be an array");
561
+ const checked = scopes.length === 0 ? [] : assertScopes(scopes);
562
+ if (checked.includes("offline_access")) throw new TypeError("[passflow] scopes must not hold offline_access");
563
+ return checked;
564
+ }
565
+ /**
566
+ * Builds an OAuth protected resource, such as an MCP server: a verifier whose only audience is the resource, the
567
+ * RFC 9728 metadata that tells a client where to get a token, and the challenge parameters that name that metadata.
568
+ * Pass it to an adapter in place of a verifier. Touches no network. Throws `TypeError` on an invalid configuration.
569
+ */
570
+ function createProtectedResource(config) {
571
+ if (typeof config !== "object" || config === null) throw new TypeError("[passflow] config must be an object");
572
+ const { resource: rawResource, scopes: rawScopes, name, ...verifierConfig } = config;
573
+ const { audience } = verifierConfig;
574
+ if (audience !== void 0 && !(Array.isArray(audience) && audience.length === 0)) throw new TypeError("[passflow] audience must not be set: the audience is the resource");
575
+ const { resource, origin, path, query } = splitResource(rawResource);
576
+ const scopes = requireScopeList(rawScopes);
577
+ if (name !== void 0 && typeof name !== "string") throw new TypeError("[passflow] name must be a string");
578
+ const verifier = createVerifier({
579
+ ...verifierConfig,
580
+ audience: resource
581
+ });
582
+ const metadataPath = path === "/" ? METADATA_WELL_KNOWN : `${METADATA_WELL_KNOWN}${path}`;
583
+ const issuer = config.issuer;
584
+ return {
585
+ verifier,
586
+ metadataPath,
587
+ metadata: () => ({
588
+ resource,
589
+ authorization_servers: [issuer],
590
+ ...scopes.length > 0 ? { scopes_supported: [...scopes] } : {},
591
+ bearer_methods_supported: ["header"],
592
+ ...name ? { resource_name: name } : {}
593
+ }),
594
+ requireScopes: (...required) => ({
595
+ kind: "scope",
596
+ scopes: assertScopes(required)
597
+ }),
598
+ challenge: {
599
+ resourceMetadata: `${origin}${metadataPath}${query}`,
600
+ ...scopes.length > 0 ? { scope: scopes.join(" ") } : {}
601
+ }
602
+ };
603
+ }
604
+ export { AAL1, AAL2, AAL3, ACR_NONE, CHALLENGE_HEADER, CORS_EXPOSED_HEADERS, PassflowAuthError, PassflowUsageError, acrLevel, acrSatisfies, assertMaxAge, authenticate, authenticateRequest, createProtectedResource, createVerifier, evaluate, extractBearer, formatChallenge, isPassflowAuthError, rolesOf, verifiedBy };
@@ -0,0 +1,22 @@
1
+ // src/loopback.ts
2
+ /** The host of an `http://` URL as written, without userinfo or port. A URL spelled any other way has none. */
3
+ const WRITTEN_HOST = /^http:\/\/(?:[^/?#\\\s]*@)?(\[[^\]]*\]|[^/?#:@\\%\s]*)(?::\d*)?(?:[/?#]|$)/i;
4
+ const LOOPBACK_IPV4 = /^127(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}$/;
5
+ /**
6
+ * Loopback by the host as written, the rule Go applies. WHATWG normalization would turn `127.1`, `2130706433`
7
+ * and `0x7f.1` into `127.0.0.1`, so a config that starts here would fail to start a Go API. An IPv6 literal
8
+ * takes the normalized form, which gives each address one spelling. A name that merely contains "localhost"
9
+ * is not loopback.
10
+ */
11
+ function isLoopbackHost(raw, url) {
12
+ const host = WRITTEN_HOST.exec(raw)?.[1]?.toLowerCase();
13
+ if (host === void 0) return false;
14
+ if (host.startsWith("[")) return url.hostname === "[::1]";
15
+ return host === "localhost" || host.endsWith(".localhost") || LOOPBACK_IPV4.test(host);
16
+ }
17
+ Object.defineProperty(exports, "isLoopbackHost", {
18
+ enumerable: true,
19
+ get: function() {
20
+ return isLoopbackHost;
21
+ }
22
+ });
@@ -0,0 +1,17 @@
1
+ // src/loopback.ts
2
+ /** The host of an `http://` URL as written, without userinfo or port. A URL spelled any other way has none. */
3
+ const WRITTEN_HOST = /^http:\/\/(?:[^/?#\\\s]*@)?(\[[^\]]*\]|[^/?#:@\\%\s]*)(?::\d*)?(?:[/?#]|$)/i;
4
+ const LOOPBACK_IPV4 = /^127(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}$/;
5
+ /**
6
+ * Loopback by the host as written, the rule Go applies. WHATWG normalization would turn `127.1`, `2130706433`
7
+ * and `0x7f.1` into `127.0.0.1`, so a config that starts here would fail to start a Go API. An IPv6 literal
8
+ * takes the normalized form, which gives each address one spelling. A name that merely contains "localhost"
9
+ * is not loopback.
10
+ */
11
+ function isLoopbackHost(raw, url) {
12
+ const host = WRITTEN_HOST.exec(raw)?.[1]?.toLowerCase();
13
+ if (host === void 0) return false;
14
+ if (host.startsWith("[")) return url.hostname === "[::1]";
15
+ return host === "localhost" || host.endsWith(".localhost") || LOOPBACK_IPV4.test(host);
16
+ }
17
+ export { isLoopbackHost as t };
@@ -0,0 +1,93 @@
1
+ type SessionRoutes = {
2
+ /** Default `/auth/login`. */
3
+ login?: string;
4
+ /** Default `/auth/callback`. It is the redirect URI registered on the Passflow app, after `baseUrl`. */
5
+ callback?: string;
6
+ /** Default `/auth/logout`. */
7
+ logout?: string;
8
+ };
9
+ type SessionConfig = {
10
+ /** `PASSFLOW_ISSUER`. https, or http on a loopback host only. */
11
+ issuer?: string;
12
+ /** `PASSFLOW_CLIENT_ID`. */
13
+ clientId?: string;
14
+ /** `PASSFLOW_CLIENT_SECRET`. */
15
+ clientSecret?: string;
16
+ /** `PASSFLOW_SECRET`: at least 32 characters. The session cookies are encrypted with keys derived from it. */
17
+ secret?: string;
18
+ /** `APP_BASE_URL`: the app's origin, with no path. https, or http on a loopback host only. */
19
+ baseUrl?: string;
20
+ /** Default `openid profile email offline_access`. */
21
+ scopes?: string[];
22
+ routes?: SessionRoutes;
23
+ /** Replaces the global `fetch` for every call to Passflow. */
24
+ fetch?: typeof fetch;
25
+ /** The clock for session and token expiry. Default `new Date()`. */
26
+ now?: () => Date;
27
+ };
28
+ type Env = Record<string, string | undefined>;
29
+ /**
30
+ * The session settings from environment variables: `PASSFLOW_ISSUER`, `PASSFLOW_CLIENT_ID`,
31
+ * `PASSFLOW_CLIENT_SECRET`, `PASSFLOW_SECRET` and `APP_BASE_URL`. A variable that is unset or empty is left
32
+ * out, so an explicit value spread after this one wins. Reads `process.env` when `env` is not given.
33
+ */
34
+ declare function configFromEnv(env?: Env): SessionConfig;
35
+ /**
36
+ * The signed-in user, from UserInfo at sign-in. It has no index signature, so frameworks that check a server
37
+ * function's result type (TanStack Start) accept it as it is. Other claims are not kept: verify the access
38
+ * token from `getAccessToken()` with `createVerifier` to read roles or tenants.
39
+ */
40
+ type PassflowUser = {
41
+ sub: string;
42
+ email?: string;
43
+ emailVerified?: boolean;
44
+ name?: string;
45
+ picture?: string;
46
+ };
47
+ /**
48
+ * The signed-in user. Safe to pass to the browser: it holds no token.
49
+ * `expiresAt` is the session's `exp` in Unix seconds, the latest moment the session can last. It is not the
50
+ * access token's expiry.
51
+ */
52
+ type Session = {
53
+ user: PassflowUser;
54
+ expiresAt: number;
55
+ };
56
+ /**
57
+ * What `handle` decided. `response`: an auth route answered; send it as it is. `continue`: run the app.
58
+ * Append each of `setCookies` as its own `Set-Cookie` header, with `Cache-Control: no-store` when there is any.
59
+ * When `cookieHeader` is present, replace the request's `Cookie` header with it (`''` removes the header);
60
+ * when it is absent, the header is unchanged.
61
+ */
62
+ type HandleResult = {
63
+ kind: 'response';
64
+ response: Response;
65
+ } | {
66
+ kind: 'continue';
67
+ session: Session | null;
68
+ setCookies: string[];
69
+ cookieHeader?: string;
70
+ };
71
+ type SessionManager = {
72
+ /** Serves the auth routes, and refreshes the session when its access token is due. */
73
+ handle(request: Request): Promise<HandleResult>;
74
+ /** The session the `Cookie` header carries, or `null`. No network, no writes; `null` once the access token expired. */
75
+ getSession(cookieHeader: string | null | undefined): Promise<Session | null>;
76
+ /** The access token, for server code that calls an API. Never send it to the browser. */
77
+ getAccessToken(cookieHeader: string | null | undefined): Promise<string | null>;
78
+ /** The sign-in route with a checked `returnTo`: a same-origin relative path, else `/`. */
79
+ loginPath(returnTo?: string): string;
80
+ /** True when `Origin` is the app's own, or, with no `Origin`, when `Sec-Fetch-Site` is `same-origin` or `none`. */
81
+ isSameOrigin(request: Request): boolean;
82
+ /** True when the `Cookie` header carries the session cookie or any of its chunks. */
83
+ hasSessionCookie(cookieHeader: string | null | undefined): boolean;
84
+ /** 401 with `Cache-Control: no-store` and no body. */
85
+ unauthorized(): Response;
86
+ };
87
+ /**
88
+ * The server-side sign-in session for a web app: the auth routes, an encrypted and chunked session cookie,
89
+ * and refresh when the access token is due. Framework-neutral: it reads web `Request`s and returns web
90
+ * `Response`s. The config is checked on first use and throws `TypeError` naming what is missing.
91
+ */
92
+ declare function createSessionManager(config: SessionConfig): SessionManager;
93
+ export { createSessionManager as a, configFromEnv as c, SessionManager as i, PassflowUser as n, SessionConfig as o, Session as r, SessionRoutes as s, HandleResult as t };
@@ -0,0 +1,93 @@
1
+ type SessionRoutes = {
2
+ /** Default `/auth/login`. */
3
+ login?: string;
4
+ /** Default `/auth/callback`. It is the redirect URI registered on the Passflow app, after `baseUrl`. */
5
+ callback?: string;
6
+ /** Default `/auth/logout`. */
7
+ logout?: string;
8
+ };
9
+ type SessionConfig = {
10
+ /** `PASSFLOW_ISSUER`. https, or http on a loopback host only. */
11
+ issuer?: string;
12
+ /** `PASSFLOW_CLIENT_ID`. */
13
+ clientId?: string;
14
+ /** `PASSFLOW_CLIENT_SECRET`. */
15
+ clientSecret?: string;
16
+ /** `PASSFLOW_SECRET`: at least 32 characters. The session cookies are encrypted with keys derived from it. */
17
+ secret?: string;
18
+ /** `APP_BASE_URL`: the app's origin, with no path. https, or http on a loopback host only. */
19
+ baseUrl?: string;
20
+ /** Default `openid profile email offline_access`. */
21
+ scopes?: string[];
22
+ routes?: SessionRoutes;
23
+ /** Replaces the global `fetch` for every call to Passflow. */
24
+ fetch?: typeof fetch;
25
+ /** The clock for session and token expiry. Default `new Date()`. */
26
+ now?: () => Date;
27
+ };
28
+ type Env = Record<string, string | undefined>;
29
+ /**
30
+ * The session settings from environment variables: `PASSFLOW_ISSUER`, `PASSFLOW_CLIENT_ID`,
31
+ * `PASSFLOW_CLIENT_SECRET`, `PASSFLOW_SECRET` and `APP_BASE_URL`. A variable that is unset or empty is left
32
+ * out, so an explicit value spread after this one wins. Reads `process.env` when `env` is not given.
33
+ */
34
+ declare function configFromEnv(env?: Env): SessionConfig;
35
+ /**
36
+ * The signed-in user, from UserInfo at sign-in. It has no index signature, so frameworks that check a server
37
+ * function's result type (TanStack Start) accept it as it is. Other claims are not kept: verify the access
38
+ * token from `getAccessToken()` with `createVerifier` to read roles or tenants.
39
+ */
40
+ type PassflowUser = {
41
+ sub: string;
42
+ email?: string;
43
+ emailVerified?: boolean;
44
+ name?: string;
45
+ picture?: string;
46
+ };
47
+ /**
48
+ * The signed-in user. Safe to pass to the browser: it holds no token.
49
+ * `expiresAt` is the session's `exp` in Unix seconds, the latest moment the session can last. It is not the
50
+ * access token's expiry.
51
+ */
52
+ type Session = {
53
+ user: PassflowUser;
54
+ expiresAt: number;
55
+ };
56
+ /**
57
+ * What `handle` decided. `response`: an auth route answered; send it as it is. `continue`: run the app.
58
+ * Append each of `setCookies` as its own `Set-Cookie` header, with `Cache-Control: no-store` when there is any.
59
+ * When `cookieHeader` is present, replace the request's `Cookie` header with it (`''` removes the header);
60
+ * when it is absent, the header is unchanged.
61
+ */
62
+ type HandleResult = {
63
+ kind: 'response';
64
+ response: Response;
65
+ } | {
66
+ kind: 'continue';
67
+ session: Session | null;
68
+ setCookies: string[];
69
+ cookieHeader?: string;
70
+ };
71
+ type SessionManager = {
72
+ /** Serves the auth routes, and refreshes the session when its access token is due. */
73
+ handle(request: Request): Promise<HandleResult>;
74
+ /** The session the `Cookie` header carries, or `null`. No network, no writes; `null` once the access token expired. */
75
+ getSession(cookieHeader: string | null | undefined): Promise<Session | null>;
76
+ /** The access token, for server code that calls an API. Never send it to the browser. */
77
+ getAccessToken(cookieHeader: string | null | undefined): Promise<string | null>;
78
+ /** The sign-in route with a checked `returnTo`: a same-origin relative path, else `/`. */
79
+ loginPath(returnTo?: string): string;
80
+ /** True when `Origin` is the app's own, or, with no `Origin`, when `Sec-Fetch-Site` is `same-origin` or `none`. */
81
+ isSameOrigin(request: Request): boolean;
82
+ /** True when the `Cookie` header carries the session cookie or any of its chunks. */
83
+ hasSessionCookie(cookieHeader: string | null | undefined): boolean;
84
+ /** 401 with `Cache-Control: no-store` and no body. */
85
+ unauthorized(): Response;
86
+ };
87
+ /**
88
+ * The server-side sign-in session for a web app: the auth routes, an encrypted and chunked session cookie,
89
+ * and refresh when the access token is due. Framework-neutral: it reads web `Request`s and returns web
90
+ * `Response`s. The config is checked on first use and throws `TypeError` naming what is missing.
91
+ */
92
+ declare function createSessionManager(config: SessionConfig): SessionManager;
93
+ export { createSessionManager as a, configFromEnv as c, SessionManager as i, PassflowUser as n, SessionConfig as o, Session as r, SessionRoutes as s, HandleResult as t };
@@ -0,0 +1,17 @@
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
+ // src/session-browser.ts
3
+ function serverOnly() {
4
+ throw new Error("[passflow] @passflow/node/session runs on the server only");
5
+ }
6
+ function createSessionManager(_config) {
7
+ return serverOnly();
8
+ }
9
+ function configFromEnv(_env) {
10
+ return serverOnly();
11
+ }
12
+ function hasSessionCookie(_cookieHeader) {
13
+ return serverOnly();
14
+ }
15
+ exports.configFromEnv = configFromEnv;
16
+ exports.createSessionManager = createSessionManager;
17
+ exports.hasSessionCookie = hasSessionCookie;
@@ -0,0 +1,5 @@
1
+ import { i as SessionManager, n as PassflowUser, o as SessionConfig, r as Session, s as SessionRoutes, t as HandleResult } from "./manager-Bm3vM2Aw.cjs";
2
+ export declare function createSessionManager(_config: SessionConfig): SessionManager;
3
+ export declare function configFromEnv(_env?: Record<string, string | undefined>): SessionConfig;
4
+ export declare function hasSessionCookie(_cookieHeader: string | null | undefined): boolean;
5
+ export type { HandleResult, PassflowUser, Session, SessionConfig, SessionManager, SessionRoutes };
@@ -0,0 +1,5 @@
1
+ import { i as SessionManager, n as PassflowUser, o as SessionConfig, r as Session, s as SessionRoutes, t as HandleResult } from "./manager-Bm3vM2Aw.mjs";
2
+ export declare function createSessionManager(_config: SessionConfig): SessionManager;
3
+ export declare function configFromEnv(_env?: Record<string, string | undefined>): SessionConfig;
4
+ export declare function hasSessionCookie(_cookieHeader: string | null | undefined): boolean;
5
+ export type { HandleResult, PassflowUser, Session, SessionConfig, SessionManager, SessionRoutes };
@@ -0,0 +1,14 @@
1
+ // src/session-browser.ts
2
+ function serverOnly() {
3
+ throw new Error("[passflow] @passflow/node/session runs on the server only");
4
+ }
5
+ function createSessionManager(_config) {
6
+ return serverOnly();
7
+ }
8
+ function configFromEnv(_env) {
9
+ return serverOnly();
10
+ }
11
+ function hasSessionCookie(_cookieHeader) {
12
+ return serverOnly();
13
+ }
14
+ export { configFromEnv, createSessionManager, hasSessionCookie };