@snokam/auth 3.1.1 → 3.2.1

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/CHANGELOG.md CHANGED
@@ -3,6 +3,18 @@
3
3
  All notable changes to this project will be documented in this file.
4
4
  See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
5
5
 
6
+ ## [3.2.1](https://github.com/snokam/components/compare/@snokam/auth@3.2.0...@snokam/auth@3.2.1) (2026-10-02)
7
+
8
+ ### Bug Fixes
9
+
10
+ - **auth:** harden app sign-in after a security review, and give sign-in one home ([#2543](https://github.com/snokam/components/issues/2543)) ([7100eb7](https://github.com/snokam/components/commit/7100eb79ce278875eafe75228ab496dedc0ae151))
11
+
12
+ # [3.2.0](https://github.com/snokam/components/compare/@snokam/auth@3.1.1...@snokam/auth@3.2.0) (2026-10-02)
13
+
14
+ ### Features
15
+
16
+ - **auth:** let MCP clients sign in through the Snøsky login ([#2542](https://github.com/snokam/components/issues/2542)) ([5ea6750](https://github.com/snokam/components/commit/5ea67501bde43d999d518e41f98611af2536ff23))
17
+
6
18
  ## [3.1.1](https://github.com/snokam/components/compare/@snokam/auth@3.1.0...@snokam/auth@3.1.1) (2026-10-01)
7
19
 
8
20
  **Note:** Version bump only for package @snokam/auth
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@snokam/auth",
3
3
  "description": "Snøkam auth components",
4
- "version": "3.1.1",
4
+ "version": "3.2.1",
5
5
  "main": "src/index.ts",
6
6
  "types": "src/index.ts",
7
7
  "files": [
@@ -26,9 +26,9 @@
26
26
  "next-auth": "4.24.15",
27
27
  "path-to-regexp": "^8.4.2",
28
28
  "@snokam/identity": "1.1.0",
29
- "@snokam/platform-client": "3.0.0",
29
+ "@snokam/platform-client": "3.1.1",
30
30
  "@snokam/react-query": "1.1.0",
31
- "@snokam/tenant": "2.1.1",
31
+ "@snokam/tenant": "2.1.3",
32
32
  "@snokam/ui": "2.0.3"
33
33
  },
34
34
  "peerDependencies": {
@@ -0,0 +1,35 @@
1
+ import { open, seal } from "../ticket/seal";
2
+
3
+ export interface AuthorizationParams {
4
+ clientId: string;
5
+ redirectUri: string;
6
+ codeChallenge: string;
7
+ codeChallengeMethod: string;
8
+ resource: string;
9
+ }
10
+
11
+ export interface ConsentClaims extends AuthorizationParams {
12
+ business: string;
13
+ state: string;
14
+ clientName: string;
15
+ businessName: string;
16
+ email: string;
17
+ nonce: string;
18
+ }
19
+
20
+ const PURPOSE = "app-sign-in-consent";
21
+ export const CONSENT_TTL_SECONDS = 600;
22
+
23
+ export function sealConsent(claims: ConsentClaims, secret: string): string {
24
+ return seal(claims, secret, CONSENT_TTL_SECONDS, PURPOSE);
25
+ }
26
+
27
+ export function readAppSignInConsent(
28
+ ticket: string,
29
+ secret: string
30
+ ): ConsentClaims | null {
31
+ return open<ConsentClaims>(ticket, secret, PURPOSE, {
32
+ onReject: (reason) =>
33
+ console.warn(`[app-sign-in] consent rejected: ${reason}`),
34
+ });
35
+ }
@@ -0,0 +1,180 @@
1
+ import { randomUUID } from "crypto";
2
+ import { getToken } from "next-auth/jwt";
3
+ import {
4
+ getAuthUrl,
5
+ getSessionCookieSettings,
6
+ requestOrigin,
7
+ } from "../session";
8
+ import { resolveAccessToken } from "../route-handler/token";
9
+ import type { Auth } from "../types";
10
+ import {
11
+ type AuthorizationParams,
12
+ CONSENT_TTL_SECONDS,
13
+ readAppSignInConsent,
14
+ sealConsent,
15
+ } from "./consent";
16
+ import { approveAuthorization, previewAuthorization } from "./platform";
17
+
18
+ const ACCESS_DENIED = "access_denied";
19
+ const NONCE_COOKIE = "app-sign-in";
20
+
21
+ function invalidRequest(): Response {
22
+ return new Response("Invalid authorization request", { status: 400 });
23
+ }
24
+
25
+ function readParams(query: URLSearchParams): AuthorizationParams | null {
26
+ const params = {
27
+ clientId: query.get("client_id") ?? "",
28
+ redirectUri: query.get("redirect_uri") ?? "",
29
+ codeChallenge: query.get("code_challenge") ?? "",
30
+ codeChallengeMethod: query.get("code_challenge_method") ?? "",
31
+ resource: query.get("resource") ?? "",
32
+ };
33
+ const complete =
34
+ query.get("response_type") === "code" &&
35
+ Object.values(params).every(Boolean);
36
+ return complete && URL.canParse(params.resource) ? params : null;
37
+ }
38
+
39
+ async function signedInEmail(
40
+ request: Request,
41
+ secret: string
42
+ ): Promise<string | null> {
43
+ const { name: cookieName } = getSessionCookieSettings(getAuthUrl());
44
+ const token = await getToken({ req: request as never, secret, cookieName });
45
+ return token?.refreshToken && token.email ? String(token.email) : null;
46
+ }
47
+
48
+ function loginRedirect(request: Request, resource: string, prompt?: string) {
49
+ const url = new URL(request.url);
50
+ const resume = new URLSearchParams(url.searchParams);
51
+ resume.set("returnTo", new URL(resource).origin);
52
+ const login = new URL("/auth/login", requestOrigin(request));
53
+ login.searchParams.set("callbackUrl", `${url.pathname}?${resume}`);
54
+ if (prompt) login.searchParams.set("prompt", prompt);
55
+ return Response.redirect(login.toString(), 302);
56
+ }
57
+
58
+ function nonceCookie(request: Request, value: string, maxAge: number): string {
59
+ const secure = requestOrigin(request).startsWith("https://");
60
+ return [
61
+ `${NONCE_COOKIE}=${value}`,
62
+ "Path=/oauth",
63
+ `Max-Age=${maxAge}`,
64
+ "HttpOnly",
65
+ "SameSite=Lax",
66
+ secure ? "Secure" : "",
67
+ ]
68
+ .filter(Boolean)
69
+ .join("; ");
70
+ }
71
+
72
+ function nonceFrom(request: Request): string | null {
73
+ const cookies = request.headers.get("cookie") ?? "";
74
+ const match = cookies.match(new RegExp(`(?:^|;\\s*)${NONCE_COOKIE}=([^;]+)`));
75
+ return match ? match[1] : null;
76
+ }
77
+
78
+ function sameOrigin(request: Request): boolean {
79
+ return request.headers.get("origin") === requestOrigin(request);
80
+ }
81
+
82
+ function clientRedirect(
83
+ request: Request,
84
+ redirectUri: string,
85
+ state: string,
86
+ result: Record<string, string>
87
+ ): Response {
88
+ const target = new URL(redirectUri);
89
+ for (const [key, value] of Object.entries(result)) {
90
+ target.searchParams.set(key, value);
91
+ }
92
+ if (state) target.searchParams.set("state", state);
93
+ return new Response(null, {
94
+ status: 303,
95
+ headers: {
96
+ Location: target.toString(),
97
+ "Set-Cookie": nonceCookie(request, "", 0),
98
+ },
99
+ });
100
+ }
101
+
102
+ export function createAppSignInAuthorizeHandler(authConfig: Auth.Config) {
103
+ return async function GET(request: Request) {
104
+ const query = new URL(request.url).searchParams;
105
+ const params = readParams(query);
106
+ if (!params) return invalidRequest();
107
+
108
+ const email = await signedInEmail(request, authConfig.nextAuthSecret);
109
+ if (!email) return loginRedirect(request, params.resource);
110
+
111
+ const access = await resolveAccessToken(authConfig, request);
112
+ if ("error" in access) return loginRedirect(request, params.resource);
113
+
114
+ const preview = await previewAuthorization(params, access.accessToken);
115
+ if ("error" in preview) {
116
+ return preview.error === ACCESS_DENIED
117
+ ? loginRedirect(request, params.resource, "login")
118
+ : invalidRequest();
119
+ }
120
+
121
+ const nonce = randomUUID();
122
+ const ticket = sealConsent(
123
+ {
124
+ ...params,
125
+ ...preview.value,
126
+ business: new URL(params.resource).hostname,
127
+ state: query.get("state") ?? "",
128
+ email,
129
+ nonce,
130
+ },
131
+ authConfig.nextAuthSecret
132
+ );
133
+ const consent = new URL("/oauth/consent", requestOrigin(request));
134
+ consent.searchParams.set("ticket", ticket);
135
+ return new Response(null, {
136
+ status: 302,
137
+ headers: {
138
+ Location: consent.toString(),
139
+ "Set-Cookie": nonceCookie(request, nonce, CONSENT_TTL_SECONDS),
140
+ },
141
+ });
142
+ };
143
+ }
144
+
145
+ export function createAppSignInApproveHandler(authConfig: Auth.Config) {
146
+ return async function POST(request: Request) {
147
+ if (!sameOrigin(request)) return invalidRequest();
148
+
149
+ const form = await request.formData();
150
+ const consent = readAppSignInConsent(
151
+ String(form.get("ticket") ?? ""),
152
+ authConfig.nextAuthSecret
153
+ );
154
+ if (!consent || consent.nonce !== nonceFrom(request)) {
155
+ return invalidRequest();
156
+ }
157
+
158
+ const email = await signedInEmail(request, authConfig.nextAuthSecret);
159
+ if (email !== consent.email) return invalidRequest();
160
+
161
+ if (form.get("decision") !== "approve") {
162
+ return clientRedirect(request, consent.redirectUri, consent.state, {
163
+ error: ACCESS_DENIED,
164
+ });
165
+ }
166
+
167
+ const access = await resolveAccessToken(authConfig, request);
168
+ if ("error" in access) return invalidRequest();
169
+
170
+ const approved = await approveAuthorization(consent, access.accessToken);
171
+ return clientRedirect(
172
+ request,
173
+ consent.redirectUri,
174
+ consent.state,
175
+ "error" in approved
176
+ ? { error: approved.error }
177
+ : { code: approved.value.code }
178
+ );
179
+ };
180
+ }
@@ -0,0 +1,52 @@
1
+ import { getManagedBearer } from "@snokam/identity";
2
+ import type { AuthorizationParams } from "./consent";
3
+
4
+ export interface AuthorizationPreview {
5
+ clientName: string;
6
+ businessName: string;
7
+ }
8
+
9
+ type Outcome<T> = { value: T } | { error: string };
10
+
11
+ const UNAVAILABLE = "temporarily_unavailable";
12
+
13
+ function apiBase(): string {
14
+ return (process.env.NEXT_PUBLIC_PLATFORM_API_BASE_URL ?? "").replace(
15
+ /\/+$/,
16
+ ""
17
+ );
18
+ }
19
+
20
+ async function post<T>(
21
+ path: string,
22
+ params: AuthorizationParams,
23
+ userToken: string
24
+ ): Promise<Outcome<T>> {
25
+ const loginSite = await getManagedBearer();
26
+ if (!loginSite) return { error: UNAVAILABLE };
27
+
28
+ const response = await fetch(`${apiBase()}${path}`, {
29
+ method: "POST",
30
+ headers: { "Content-Type": "application/json", Authorization: loginSite },
31
+ body: JSON.stringify({ ...params, userToken }),
32
+ cache: "no-store",
33
+ });
34
+ const body = await response.json().catch(() => ({}));
35
+ return response.ok
36
+ ? { value: body as T }
37
+ : { error: String(body.error ?? "invalid_request") };
38
+ }
39
+
40
+ export function previewAuthorization(
41
+ params: AuthorizationParams,
42
+ userToken: string
43
+ ): Promise<Outcome<AuthorizationPreview>> {
44
+ return post("/v1.0/protected/oauth/authorization/preview", params, userToken);
45
+ }
46
+
47
+ export function approveAuthorization(
48
+ params: AuthorizationParams,
49
+ userToken: string
50
+ ): Promise<Outcome<{ code: string }>> {
51
+ return post("/v1.0/protected/oauth/authorization", params, userToken);
52
+ }
@@ -49,4 +49,9 @@ export {
49
49
  createHandoffFinishHandler,
50
50
  createHandoffLogoutHandler,
51
51
  } from "../handoff/handlers";
52
+ export {
53
+ createAppSignInAuthorizeHandler,
54
+ createAppSignInApproveHandler,
55
+ } from "../app-sign-in/handlers";
56
+ export { readAppSignInConsent } from "../app-sign-in/consent";
52
57
  export type { Auth } from "../types";