@zibyn/polaris 0.0.0-stage → 0.1.5

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 CHANGED
@@ -1,3 +1,129 @@
1
- # Temporary Holding Version
1
+ # Polaris Node SDK
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ `@zibyn/polaris`:给有后端的 Web Application 做登录(OIDC 授权码 + PKCE,登录状态存在 SDK 的会话 cookie 里),给 API 后端校验 access token。底层是 `openid-client` 和 `jose`。范围见 [ADR 0035](../../docs/adr/0035-node-and-go-sdk-scope.md)。
4
+
5
+ SDK 0.x 支持服务端 API v1。Node 20+。
6
+
7
+ ```sh
8
+ pnpm add @zibyn/polaris
9
+ ```
10
+
11
+ ## 在 Polaris 里登记 Application
12
+
13
+ - 类型:Web Application(confidential),认证方式 `client_secret_basic`;
14
+ - **开启 refresh token**:SDK 靠它续期,回调时拿不到 refresh token 会直接报配置错误;
15
+ - redirect URI:`{baseURL}/auth/callback`;
16
+ - post logout redirect URI:`{baseURL}`(与 `baseURL` 配置逐字相同);
17
+ - 配好默认 API:`getSession()` 拿到的 access token 就是给它的。
18
+
19
+ ## Web 登录
20
+
21
+ ```ts
22
+ // lib/polaris.ts
23
+ import { createPolaris } from "@zibyn/polaris";
24
+
25
+ export const polaris = createPolaris({
26
+ issuer: "https://auth.example.com",
27
+ clientId: process.env.POLARIS_CLIENT_ID!,
28
+ clientSecret: process.env.POLARIS_CLIENT_SECRET!,
29
+ baseURL: "https://app.example.com",
30
+ secret: process.env.POLARIS_SECRET!, // 至少 32 个随机字符,加密会话 cookie
31
+ // scope 默认 "openid profile email phone"
32
+ });
33
+ ```
34
+
35
+ 挂上 handler,得到四个路由:
36
+
37
+ | 路由 | 作用 |
38
+ |---|---|
39
+ | `GET /auth/login?returnTo=/path` | 跳 Polaris 登录;`returnTo` 只接受本站路径 |
40
+ | `GET /auth/callback` | 换令牌、写会话 cookie,跳回 `returnTo` |
41
+ | `POST /auth/logout` | 清 cookie,跳 Polaris 退出(RP-Initiated Logout;只收 POST,别的站点不能用一个链接让 User 退出),Polaris 请 User 确认后回到 `baseURL` |
42
+ | `GET /auth/session` | 给前端的 JSON:`{ user }` 或 `null`;access token 不出服务端 |
43
+
44
+ ```ts
45
+ // Next.js:app/auth/[...polaris]/route.ts
46
+ export const { GET, POST } = polaris.handler;
47
+
48
+ // Hono
49
+ app.on(["GET", "POST"], "/auth/*", (c) => polaris.handler(c.req.raw));
50
+
51
+ // TanStack Start:src/routes/auth/$.ts
52
+ export const Route = createFileRoute("/auth/$")({
53
+ server: { handlers: { GET: ({ request }) => polaris.handler(request), POST: ({ request }) => polaris.handler(request) } },
54
+ });
55
+
56
+ // Express、node:http
57
+ import { toNodeHandler } from "@zibyn/polaris";
58
+ app.all("/auth/*splat", toNodeHandler(polaris.handler));
59
+ ```
60
+
61
+ ### 读取 session
62
+
63
+ ```ts
64
+ const { session, headers } = await polaris.getSession(request);
65
+ // session: { user, accessToken } | null
66
+ // 把 headers 里的 Set-Cookie 加到响应上(有就必须加)
67
+ ```
68
+
69
+ - `user` 是 ID token 里关于 User 的 claim(`sub`、`name`、`email`……),每次刷新时更新,不调 `/userinfo`。
70
+ - `accessToken` 只有一个,`aud` 是 Application 的默认 API。快过期(剩不到 60 秒)时自动刷新;Polaris 拒绝刷新(Session 已终止)就清掉 cookie、返回 `null`。网络错误会抛出,cookie 保留,下次再试。
71
+ - **刷新后的 cookie 必须写回浏览器**:refresh token 每次刷新都轮换,旧的超过 60 秒宽限期再用就算重用,整个 Session 会被终止(ADR 0019)。所以 `getSession` 一旦刷新,`headers` 里就带着新的 `Set-Cookie`,调用方要把它加到响应上。
72
+
73
+ 不能写 cookie 的地方(Next 的 Server Component)用只读模式,它绝不刷新:
74
+
75
+ ```ts
76
+ import { headers } from "next/headers";
77
+ const { session } = await polaris.getSession(await headers(), { readOnly: true }); // 过期即 null
78
+ ```
79
+
80
+ Next.js 配 `proxy.ts`,在 Server Component 之前刷新,新 cookie 同时写进响应和转发给后续处理的请求:
81
+
82
+ ```ts
83
+ // proxy.ts
84
+ import type { NextRequest } from "next/server";
85
+ export const proxy = (request: NextRequest) => polaris.middleware(request);
86
+ export const config = { matcher: ["/((?!auth/|_next/|favicon.ico).*)"] };
87
+ ```
88
+
89
+ 账号中心链接:`polaris.accountUrl()`,即 `{issuer}/account?client_id=<id>`(ADR 0034)。
90
+
91
+ ### 会话 cookie
92
+
93
+ `polaris.session`:用 `secret` 加密(A256GCM),存 access token、refresh token 和 user claims,不存 ID token;超过约 3.8 KB 自动拆成 `polaris.session.0`、`.1`……;`HttpOnly`、`SameSite=Lax`,`baseURL` 为 https 时带 `Secure`;30 天有效,每次刷新重新计时。登录途中另有一个 10 分钟的 `polaris.tx`。换 `secret` 等于让所有人退出。
94
+
95
+ 不实现 Back-Channel Logout:Polaris 的 Session 终止后,SDK 要等 access token 过期去刷新时才发现,所以最多滞后 10 分钟(ADR 0035)。
96
+
97
+ ## API 后端:校验 access token
98
+
99
+ ```ts
100
+ import { accessTokenVerifier, PolarisAuthError, requireEntitlements } from "@zibyn/polaris";
101
+
102
+ const verifyAccessToken = accessTokenVerifier({
103
+ issuer: "https://auth.example.com",
104
+ audience: "api://orders", // API 标识符
105
+ });
106
+
107
+ try {
108
+ const claims = await verifyAccessToken(req.headers.authorization?.replace(/^Bearer /, ""));
109
+ requireEntitlements(claims, "orders:read", "orders:write"); // 全部持有才通过
110
+ // claims.sub、claims.client_id、claims.entitlements
111
+ } catch (err) {
112
+ if (err instanceof PolarisAuthError) return new Response(null, { status: err.status }); // 401 或 403
113
+ throw err;
114
+ }
115
+ ```
116
+
117
+ 按 JWKS 本地验签,检查 `iss`、`aud`、`typ: at+jwt`、过期时间;权限只看 `entitlements`,不看 `roles`。M2M Application 的 token(`client_credentials`)照常通过,`sub` 就是它的 `client_id`。
118
+
119
+ ## 示例
120
+
121
+ `examples/` 下有 Next.js(App Router + proxy)和 TanStack Start 的最小应用;Hono 与 Express 的用法由 `src/` 下的测试覆盖。冒烟测试会起一个假的 Polaris,走一遍登录 → 刷新 → 读 session → 退出:
122
+
123
+ ```sh
124
+ pnpm build
125
+ cd examples/next && pnpm install && pnpm dev # 或 examples/tanstack-start,端口 3001
126
+ node ../smoke.ts http://localhost:3000
127
+ ```
128
+
129
+ 本地 issuer 允许 `http://localhost` / `127.0.0.1`,其余必须 https。
@@ -0,0 +1,20 @@
1
+ import { type JWTPayload } from "jose";
2
+ export type CookieOptions = {
3
+ secure: boolean;
4
+ path: string;
5
+ };
6
+ export declare function deriveKey(secret: string): Promise<Uint8Array<ArrayBuffer>>;
7
+ export declare const seal: (payload: JWTPayload, key: Uint8Array, maxAge: number) => Promise<string>;
8
+ /** The payload, or null when the value is missing, tampered with, from another secret or expired. */
9
+ export declare function unseal<T>(value: string | undefined, key: Uint8Array): Promise<T | null>;
10
+ export declare function parseCookies(header: string | null): Map<string, string>;
11
+ /** Reads name, whole or reassembled from name.0, name.1, … */
12
+ export declare function readChunked(jar: Map<string, string>, name: string): string | undefined;
13
+ export declare function serialize(name: string, value: string, maxAge: number, o: CookieOptions): string;
14
+ /**
15
+ * The Set-Cookie values that store value (or, when null, clear it) under
16
+ * name, also clearing the chunks of it the request had that are not reused.
17
+ */
18
+ export declare function writeChunked(jar: Map<string, string>, name: string, value: string | null, maxAge: number, o: CookieOptions): string[];
19
+ /** The Cookie request header after applying setCookies to jar. */
20
+ export declare function applyToJar(jar: Map<string, string>, setCookies: string[]): string;
@@ -0,0 +1,88 @@
1
+ // The SDK's session cookie: encrypted with the integrator's secret, split
2
+ // into numbered chunks when it outgrows one cookie.
3
+ import { EncryptJWT, jwtDecrypt } from "jose";
4
+ // A browser keeps about 4096 bytes per cookie, name and attributes included.
5
+ const chunkSize = 3800;
6
+ export async function deriveKey(secret) {
7
+ if (secret.length < 32)
8
+ throw new Error("polaris: secret must be at least 32 characters");
9
+ const raw = await crypto.subtle.importKey("raw", new TextEncoder().encode(secret), "HKDF", false, ["deriveBits"]);
10
+ const bits = await crypto.subtle.deriveBits({
11
+ name: "HKDF",
12
+ hash: "SHA-256",
13
+ salt: new Uint8Array(),
14
+ info: new TextEncoder().encode("polaris session cookie"),
15
+ }, raw, 256);
16
+ return new Uint8Array(bits);
17
+ }
18
+ export const seal = (payload, key, maxAge) => new EncryptJWT(payload)
19
+ .setProtectedHeader({ alg: "dir", enc: "A256GCM" })
20
+ .setExpirationTime(Math.floor(Date.now() / 1000) + maxAge)
21
+ .encrypt(key);
22
+ /** The payload, or null when the value is missing, tampered with, from another secret or expired. */
23
+ export async function unseal(value, key) {
24
+ if (!value)
25
+ return null;
26
+ try {
27
+ return (await jwtDecrypt(value, key)).payload;
28
+ }
29
+ catch {
30
+ return null;
31
+ }
32
+ }
33
+ export function parseCookies(header) {
34
+ const jar = new Map();
35
+ for (const part of (header ?? "").split(";")) {
36
+ const i = part.indexOf("=");
37
+ if (i > 0)
38
+ jar.set(part.slice(0, i).trim(), part.slice(i + 1).trim());
39
+ }
40
+ return jar;
41
+ }
42
+ const isChunk = (name, cookie) => cookie === name ||
43
+ new RegExp(`^${name.replaceAll(".", "\\.")}\\.\\d+$`).test(cookie);
44
+ /** Reads name, whole or reassembled from name.0, name.1, … */
45
+ export function readChunked(jar, name) {
46
+ if (jar.has(name))
47
+ return jar.get(name);
48
+ let value = "";
49
+ for (let i = 0; jar.has(`${name}.${i}`); i++)
50
+ value += jar.get(`${name}.${i}`);
51
+ return value || undefined;
52
+ }
53
+ export function serialize(name, value, maxAge, o) {
54
+ return `${name}=${value}; Path=${o.path}; Max-Age=${maxAge}; HttpOnly; SameSite=Lax${o.secure ? "; Secure" : ""}`;
55
+ }
56
+ /**
57
+ * The Set-Cookie values that store value (or, when null, clear it) under
58
+ * name, also clearing the chunks of it the request had that are not reused.
59
+ */
60
+ export function writeChunked(jar, name, value, maxAge, o) {
61
+ const out = new Map();
62
+ for (const cookie of jar.keys())
63
+ if (isChunk(name, cookie))
64
+ out.set(cookie, serialize(cookie, "", 0, o));
65
+ if (value !== null) {
66
+ if (value.length <= chunkSize)
67
+ out.set(name, serialize(name, value, maxAge, o));
68
+ else
69
+ for (let i = 0; i * chunkSize < value.length; i++) {
70
+ out.set(`${name}.${i}`, serialize(`${name}.${i}`, value.slice(i * chunkSize, (i + 1) * chunkSize), maxAge, o));
71
+ }
72
+ }
73
+ return [...out.values()];
74
+ }
75
+ /** The Cookie request header after applying setCookies to jar. */
76
+ export function applyToJar(jar, setCookies) {
77
+ const next = new Map(jar);
78
+ for (const c of setCookies) {
79
+ const [pair] = c.split(";");
80
+ const i = pair.indexOf("=");
81
+ const value = pair.slice(i + 1);
82
+ if (/Max-Age=0(;|$)/.test(c))
83
+ next.delete(pair.slice(0, i));
84
+ else
85
+ next.set(pair.slice(0, i), value);
86
+ }
87
+ return [...next].map(([k, v]) => `${k}=${v}`).join("; ");
88
+ }
@@ -0,0 +1,3 @@
1
+ export { toNodeHandler } from "./node.ts";
2
+ export { type AccessTokenClaims, accessTokenVerifier, PolarisAuthError, requireEntitlements, } from "./verify.ts";
3
+ export { createPolaris, type GetSessionOptions, type Polaris, type PolarisConfig, type Session, type User, } from "./web.ts";
package/dist/index.js ADDED
@@ -0,0 +1,3 @@
1
+ export { toNodeHandler } from "./node.js";
2
+ export { accessTokenVerifier, PolarisAuthError, requireEntitlements, } from "./verify.js";
3
+ export { createPolaris, } from "./web.js";
package/dist/node.d.ts ADDED
@@ -0,0 +1,4 @@
1
+ import type { IncomingMessage, ServerResponse } from "node:http";
2
+ export declare function toNodeHandler(handler: (request: Request) => Promise<Response>): (req: IncomingMessage & {
3
+ originalUrl?: string;
4
+ }, res: ServerResponse) => Promise<void>;
package/dist/node.js ADDED
@@ -0,0 +1,39 @@
1
+ import { Readable } from "node:stream";
2
+ export function toNodeHandler(handler) {
3
+ return async (req, res) => {
4
+ try {
5
+ const headers = new Headers();
6
+ for (const [k, v] of Object.entries(req.headers)) {
7
+ if (v !== undefined)
8
+ for (const one of [v].flat())
9
+ headers.append(k, one);
10
+ }
11
+ const hasBody = req.method !== "GET" && req.method !== "HEAD";
12
+ // The routes are found by path; the host is only a placeholder.
13
+ const request = new Request(new URL(req.originalUrl ?? req.url ?? "/", "http://localhost"), {
14
+ method: req.method,
15
+ headers,
16
+ body: hasBody ? Readable.toWeb(req) : undefined,
17
+ // @ts-expect-error Node's fetch needs this for a streamed body; not yet in the DOM types.
18
+ duplex: hasBody ? "half" : undefined,
19
+ });
20
+ const response = await handler(request);
21
+ const out = {};
22
+ response.headers.forEach((v, k) => {
23
+ if (k !== "set-cookie")
24
+ out[k] = v;
25
+ });
26
+ const setCookies = response.headers.getSetCookie();
27
+ if (setCookies.length)
28
+ out["set-cookie"] = setCookies;
29
+ res.writeHead(response.status, out);
30
+ res.end(Buffer.from(await response.arrayBuffer()));
31
+ }
32
+ catch (err) {
33
+ if (!res.headersSent)
34
+ res.writeHead(500, { "content-type": "text/plain" });
35
+ res.end("internal error");
36
+ console.error("polaris:", err);
37
+ }
38
+ };
39
+ }
@@ -0,0 +1,24 @@
1
+ import { type JWTPayload } from "jose";
2
+ export type AccessTokenClaims = JWTPayload & {
3
+ sub: string;
4
+ client_id: string;
5
+ /** The Entitlements held at this API; empty when none, as for most M2M tokens. */
6
+ entitlements: string[];
7
+ sid?: string;
8
+ roles?: string[];
9
+ };
10
+ /** 401: no valid access token. 403: valid, but missing an Entitlement. */
11
+ export declare class PolarisAuthError extends Error {
12
+ readonly status: 401 | 403;
13
+ constructor(status: 401 | 403, message: string, options?: ErrorOptions);
14
+ }
15
+ /**
16
+ * Makes verifyAccessToken for one API. audience is the API's identifier;
17
+ * tokens for any other API are refused.
18
+ */
19
+ export declare function accessTokenVerifier({ issuer, audience, }: {
20
+ issuer: string;
21
+ audience: string;
22
+ }): (token: string | null | undefined) => Promise<AccessTokenClaims>;
23
+ /** Throws PolarisAuthError(403) unless claims hold every one of names. */
24
+ export declare function requireEntitlements(claims: AccessTokenClaims, ...names: string[]): void;
package/dist/verify.js ADDED
@@ -0,0 +1,60 @@
1
+ // For API backends: Polaris access tokens (RFC 9068) checked locally against
2
+ // the JWKS; permissions come from entitlements only (ADR 0035).
3
+ import { createRemoteJWKSet, jwtVerify } from "jose";
4
+ /** 401: no valid access token. 403: valid, but missing an Entitlement. */
5
+ export class PolarisAuthError extends Error {
6
+ status;
7
+ constructor(status, message, options) {
8
+ super(message, options);
9
+ this.name = "PolarisAuthError";
10
+ this.status = status;
11
+ }
12
+ }
13
+ /**
14
+ * Makes verifyAccessToken for one API. audience is the API's identifier;
15
+ * tokens for any other API are refused.
16
+ */
17
+ export function accessTokenVerifier({ issuer, audience, }) {
18
+ let jwks;
19
+ const keys = () => {
20
+ jwks ??= fetch(new URL(".well-known/openid-configuration", `${issuer.replace(/\/$/, "")}/`))
21
+ .then(async (res) => {
22
+ if (!res.ok)
23
+ throw new Error(`polaris: discovery: ${res.status}`);
24
+ return createRemoteJWKSet(new URL((await res.json()).jwks_uri));
25
+ })
26
+ .catch((err) => {
27
+ jwks = undefined; // try again on the next token
28
+ throw err;
29
+ });
30
+ return jwks;
31
+ };
32
+ /** The token's claims; throws PolarisAuthError(401) when it is not valid. */
33
+ return async function verifyAccessToken(token) {
34
+ if (!token)
35
+ throw new PolarisAuthError(401, "no access token");
36
+ const jwks = await keys();
37
+ try {
38
+ const { payload } = await jwtVerify(token, jwks, {
39
+ issuer,
40
+ audience,
41
+ typ: "at+jwt",
42
+ algorithms: ["RS256"],
43
+ requiredClaims: ["sub", "client_id"],
44
+ });
45
+ const entitlements = Array.isArray(payload.entitlements)
46
+ ? payload.entitlements
47
+ : [];
48
+ return { ...payload, entitlements };
49
+ }
50
+ catch (err) {
51
+ throw new PolarisAuthError(401, "invalid access token", { cause: err });
52
+ }
53
+ };
54
+ }
55
+ /** Throws PolarisAuthError(403) unless claims hold every one of names. */
56
+ export function requireEntitlements(claims, ...names) {
57
+ const missing = names.filter((n) => !claims.entitlements.includes(n));
58
+ if (missing.length)
59
+ throw new PolarisAuthError(403, `missing entitlements: ${missing.join(", ")}`);
60
+ }
package/dist/web.d.ts ADDED
@@ -0,0 +1,42 @@
1
+ export type PolarisConfig = {
2
+ /** The Polaris instance, e.g. https://auth.example.com */
3
+ issuer: string;
4
+ clientId: string;
5
+ clientSecret: string;
6
+ /** Where this app is served; the handler answers under {baseURL}/auth/. */
7
+ baseURL: string;
8
+ /** Encrypts the session cookie: at least 32 random characters, kept server side. */
9
+ secret: string;
10
+ /** Defaults to "openid profile email phone". */
11
+ scope?: string;
12
+ };
13
+ /** The ID token's claims about the User: sub, name, email, … */
14
+ export type User = {
15
+ sub: string;
16
+ [claim: string]: unknown;
17
+ };
18
+ export type Session = {
19
+ user: User;
20
+ accessToken: string;
21
+ };
22
+ export type GetSessionOptions = {
23
+ /**
24
+ * Never refresh: for callers that cannot write cookies, like a Next
25
+ * Server Component. An expired access token then reads as signed out,
26
+ * since a consumed refresh token must make it back to the cookie.
27
+ */
28
+ readOnly?: boolean;
29
+ };
30
+ export declare function createPolaris(config: PolarisConfig): {
31
+ handler: ((request: Request) => Promise<Response>) & {
32
+ GET: (request: Request) => Promise<Response>;
33
+ POST: (request: Request) => Promise<Response>;
34
+ };
35
+ getSession: (request: Request | Headers, options?: GetSessionOptions) => Promise<{
36
+ session: Session | null;
37
+ headers: Headers;
38
+ }>;
39
+ middleware: (request: Request) => Promise<Response>;
40
+ accountUrl: () => string;
41
+ };
42
+ export type Polaris = ReturnType<typeof createPolaris>;
package/dist/web.js ADDED
@@ -0,0 +1,254 @@
1
+ // Web Application login (ADR 0035): a confidential client on the
2
+ // authorization code flow, its tokens kept in the SDK's session cookie.
3
+ import * as oidc from "openid-client";
4
+ import { applyToJar, deriveKey, parseCookies, readChunked, seal, serialize, unseal, writeChunked, } from "./cookies.js";
5
+ const sessionCookie = "polaris.session";
6
+ const txCookie = "polaris.tx";
7
+ // shortcut: the default browser Session idle time, not the Application's own; a
8
+ // longer one at Polaris still ends here, take it from config when someone asks.
9
+ const sessionMaxAge = 30 * 24 * 3600;
10
+ const txMaxAge = 600;
11
+ // Refresh this long before the access token expires, so that it still holds
12
+ // for the calls made with it in this request.
13
+ const refreshMargin = 60;
14
+ // Claims about the token itself, not the User.
15
+ const protocolClaims = [
16
+ "iss",
17
+ "aud",
18
+ "exp",
19
+ "iat",
20
+ "nbf",
21
+ "nonce",
22
+ "at_hash",
23
+ "c_hash",
24
+ "azp",
25
+ "jti",
26
+ ];
27
+ const now = () => Math.floor(Date.now() / 1000);
28
+ export function createPolaris(config) {
29
+ const base = new URL(config.baseURL);
30
+ const prefix = `${base.pathname.replace(/\/$/, "")}/auth`;
31
+ const redirectURI = new URL(`${prefix}/callback`, base).href;
32
+ const cookieOpts = {
33
+ secure: base.protocol === "https:",
34
+ path: "/",
35
+ };
36
+ const key = deriveKey(config.secret);
37
+ const issuer = new URL(config.issuer);
38
+ // Like redirect URIs (ADR 0034): https, except on localhost.
39
+ const insecure = issuer.protocol === "http:" &&
40
+ ["localhost", "127.0.0.1", "[::1]"].includes(issuer.hostname);
41
+ let discovered;
42
+ const configuration = () => {
43
+ discovered ??= oidc
44
+ .discovery(issuer, config.clientId, undefined, oidc.ClientSecretBasic(config.clientSecret), {
45
+ execute: insecure ? [oidc.allowInsecureRequests] : [],
46
+ })
47
+ .catch((err) => {
48
+ discovered = undefined; // try again on the next request
49
+ throw err;
50
+ });
51
+ return discovered;
52
+ };
53
+ // Concurrent requests of one browser carry the same refresh token: send it once.
54
+ // shortcut: one process only; several instances lean on the 60 s grace (ADR 0019), add a shared store if that shows in audits.
55
+ const inflight = new Map();
56
+ const userOf = (claims) => {
57
+ if (!claims)
58
+ return undefined;
59
+ const user = { ...claims };
60
+ for (const c of protocolClaims)
61
+ delete user[c];
62
+ return user;
63
+ };
64
+ const stored = (tokens, user) => {
65
+ if (!tokens.refresh_token) {
66
+ throw new Error("polaris: no refresh token; turn on refresh tokens for this Application");
67
+ }
68
+ return {
69
+ at: tokens.access_token,
70
+ rt: tokens.refresh_token,
71
+ // Polaris always sends expires_in (600); without it every request would refresh.
72
+ expiresAt: now() + (tokens.expiresIn() ?? 600),
73
+ user,
74
+ };
75
+ };
76
+ /** Appends to headers the Set-Cookie values that store s, or clear the session when null. */
77
+ const writeSession = async (headers, jar, s) => {
78
+ const value = s && (await seal(s, await key, sessionMaxAge));
79
+ for (const c of writeChunked(jar, sessionCookie, value, sessionMaxAge, cookieOpts)) {
80
+ headers.append("set-cookie", c);
81
+ }
82
+ };
83
+ /** The refreshed session, or null when Polaris refused the refresh token. */
84
+ const refresh = (s) => {
85
+ let p = inflight.get(s.rt);
86
+ if (!p) {
87
+ p = (async () => {
88
+ try {
89
+ const tokens = await oidc.refreshTokenGrant(await configuration(), s.rt);
90
+ return stored(tokens, userOf(tokens.claims()) ?? s.user);
91
+ }
92
+ catch (err) {
93
+ // Polaris said no (the Session ended): signed out. Anything else,
94
+ // like the network, keeps the cookie for the next try.
95
+ if (err instanceof oidc.ResponseBodyError)
96
+ return null;
97
+ throw err;
98
+ }
99
+ })().finally(() => inflight.delete(s.rt));
100
+ inflight.set(s.rt, p);
101
+ }
102
+ return p;
103
+ };
104
+ /**
105
+ * Reads the session, refreshing it when due. The Set-Cookie headers in
106
+ * headers must reach the browser whenever there are any.
107
+ */
108
+ async function getSession(request, options = {}) {
109
+ const headers = new Headers();
110
+ const jar = parseCookies((request instanceof Request ? request.headers : request).get("cookie"));
111
+ const raw = readChunked(jar, sessionCookie);
112
+ let s = await unseal(raw, await key);
113
+ if (!s) {
114
+ if (raw && !options.readOnly)
115
+ await writeSession(headers, jar, null);
116
+ return { session: null, headers };
117
+ }
118
+ if (options.readOnly) {
119
+ return {
120
+ session: s.expiresAt > now() ? { user: s.user, accessToken: s.at } : null,
121
+ headers,
122
+ };
123
+ }
124
+ if (s.expiresAt - refreshMargin <= now()) {
125
+ s = await refresh(s);
126
+ await writeSession(headers, jar, s);
127
+ }
128
+ return { session: s && { user: s.user, accessToken: s.at }, headers };
129
+ }
130
+ const login = async (request) => {
131
+ const returnTo = new URL(request.url).searchParams.get("returnTo") ?? "/";
132
+ const tx = {
133
+ state: oidc.randomState(),
134
+ nonce: oidc.randomNonce(),
135
+ verifier: oidc.randomPKCECodeVerifier(),
136
+ returnTo: localPath(returnTo, base),
137
+ };
138
+ const url = oidc.buildAuthorizationUrl(await configuration(), {
139
+ redirect_uri: redirectURI,
140
+ scope: config.scope ?? "openid profile email phone",
141
+ state: tx.state,
142
+ nonce: tx.nonce,
143
+ code_challenge: await oidc.calculatePKCECodeChallenge(tx.verifier),
144
+ code_challenge_method: "S256",
145
+ });
146
+ const res = redirect(url.href);
147
+ res.headers.append("set-cookie", serialize(txCookie, await seal(tx, await key, txMaxAge), txMaxAge, cookieOpts));
148
+ return res;
149
+ };
150
+ const callback = async (request) => {
151
+ const jar = parseCookies(request.headers.get("cookie"));
152
+ const tx = await unseal(jar.get(txCookie), await key);
153
+ if (!tx)
154
+ return text(400, "login expired or not started here; sign in again");
155
+ let tokens;
156
+ try {
157
+ // Rebuilt on baseURL: behind a proxy request.url names an internal host.
158
+ tokens = await oidc.authorizationCodeGrant(await configuration(), new URL(new URL(request.url).search, redirectURI), {
159
+ pkceCodeVerifier: tx.verifier,
160
+ expectedState: tx.state,
161
+ expectedNonce: tx.nonce,
162
+ idTokenExpected: true,
163
+ });
164
+ }
165
+ catch (err) {
166
+ if (err instanceof oidc.AuthorizationResponseError ||
167
+ err instanceof oidc.ResponseBodyError) {
168
+ return text(400, `login failed: ${err.error}${err.error_description ? `: ${err.error_description}` : ""}`);
169
+ }
170
+ throw err;
171
+ }
172
+ const user = userOf(tokens.claims());
173
+ if (!user)
174
+ throw new Error("polaris: no ID token in the token response");
175
+ const res = redirect(tx.returnTo);
176
+ await writeSession(res.headers, jar, stored(tokens, user));
177
+ res.headers.append("set-cookie", serialize(txCookie, "", 0, cookieOpts));
178
+ return res;
179
+ };
180
+ // RP-Initiated Logout without id_token_hint, which is not kept: Polaris asks
181
+ // the User to confirm, then sends them back to baseURL.
182
+ const logout = async (request) => {
183
+ const url = oidc.buildEndSessionUrl(await configuration(), {
184
+ client_id: config.clientId,
185
+ post_logout_redirect_uri: config.baseURL,
186
+ });
187
+ const res = redirect(url.href);
188
+ await writeSession(res.headers, parseCookies(request.headers.get("cookie")), null);
189
+ return res;
190
+ };
191
+ const sessionRoute = async (request) => {
192
+ const { session, headers } = await getSession(request);
193
+ headers.set("content-type", "application/json");
194
+ headers.set("cache-control", "no-store");
195
+ // The access token stays server side, out of reach of page scripts.
196
+ return new Response(JSON.stringify(session && { user: session.user }), {
197
+ headers,
198
+ });
199
+ };
200
+ const routes = {
201
+ "GET /login": login,
202
+ "GET /callback": callback,
203
+ "POST /logout": logout,
204
+ "GET /session": sessionRoute,
205
+ };
206
+ /** The login, callback, logout and session routes, as a web-standard handler. */
207
+ const handle = async (request) => {
208
+ const path = new URL(request.url).pathname;
209
+ const route = path.startsWith(`${prefix}/`) &&
210
+ routes[`${request.method} ${path.slice(prefix.length)}`];
211
+ return route ? route(request) : text(404, "not found");
212
+ };
213
+ const handler = Object.assign(handle, { GET: handle, POST: handle });
214
+ /**
215
+ * For a Next.js proxy.ts (formerly middleware.ts): refreshes the session
216
+ * when due, putting the new cookie both on the response and on the request
217
+ * the app goes on to handle, so that Server Components read the new tokens.
218
+ */
219
+ async function middleware(request) {
220
+ const { NextResponse } = await import("next/server.js");
221
+ const { headers } = await getSession(request);
222
+ const setCookies = headers.getSetCookie();
223
+ if (!setCookies.length)
224
+ return NextResponse.next();
225
+ const forwarded = new Headers(request.headers);
226
+ forwarded.set("cookie", applyToJar(parseCookies(request.headers.get("cookie")), setCookies));
227
+ const res = NextResponse.next({ request: { headers: forwarded } });
228
+ for (const c of setCookies)
229
+ res.headers.append("set-cookie", c);
230
+ return res;
231
+ }
232
+ /** The account center link, branded for this Application (ADR 0034). */
233
+ const accountUrl = () => {
234
+ const url = new URL("account", `${config.issuer.replace(/\/$/, "")}/`);
235
+ url.searchParams.set("client_id", config.clientId);
236
+ return url.href;
237
+ };
238
+ return { handler, getSession, middleware, accountUrl };
239
+ }
240
+ /**
241
+ * returnTo as a path on base's origin, else "/": no open redirect. Resolving
242
+ * it as the browser will catches "//x", "/\\x" and "/\t/x" alike.
243
+ */
244
+ function localPath(returnTo, base) {
245
+ const url = new URL(returnTo, base);
246
+ return url.origin === base.origin
247
+ ? url.pathname + url.search + url.hash
248
+ : "/";
249
+ }
250
+ const redirect = (location) => new Response(null, { status: 302, headers: { location } });
251
+ const text = (status, body) => new Response(body, {
252
+ status,
253
+ headers: { "content-type": "text/plain; charset=utf-8" },
254
+ });
package/package.json CHANGED
@@ -1,6 +1,51 @@
1
1
  {
2
2
  "name": "@zibyn/polaris",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.5",
4
+ "description": "Polaris SDK for Node: Web Application login and access token verification",
5
+ "license": "Apache-2.0",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "https://github.com/zibyn/polaris",
9
+ "directory": "sdk/node"
10
+ },
11
+ "type": "module",
12
+ "exports": {
13
+ ".": {
14
+ "types": "./dist/index.d.ts",
15
+ "default": "./dist/index.js"
16
+ }
17
+ },
18
+ "files": [
19
+ "dist"
20
+ ],
21
+ "engines": {
22
+ "node": ">=20"
23
+ },
24
+ "scripts": {
25
+ "build": "tsc -p tsconfig.build.json",
26
+ "typecheck": "tsc --noEmit",
27
+ "check": "biome check",
28
+ "test": "node --test 'src/**/*.test.ts'"
29
+ },
30
+ "dependencies": {
31
+ "jose": "^6.2.15",
32
+ "openid-client": "^6.8.9"
33
+ },
34
+ "devDependencies": {
35
+ "@biomejs/biome": "2.4.5",
36
+ "@types/node": "^24.19.2",
37
+ "hono": "^4.13.16",
38
+ "next": "^16.4.5",
39
+ "react": "^19.3.1",
40
+ "react-dom": "^19.3.1",
41
+ "typescript": "^6.0.3"
42
+ },
43
+ "peerDependencies": {
44
+ "next": ">=15"
45
+ },
46
+ "peerDependenciesMeta": {
47
+ "next": {
48
+ "optional": true
49
+ }
50
+ }
51
+ }