@thecodeorigin/auth 0.0.6 → 0.0.8

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/module.d.mts CHANGED
@@ -1,6 +1,7 @@
1
1
  import * as _nuxt_schema from '@nuxt/schema';
2
2
 
3
3
  interface AuthRoutes {
4
+ login: string;
4
5
  signIn: string;
5
6
  callback: string;
6
7
  signOut: string;
@@ -12,6 +13,7 @@ interface ModuleOptions {
12
13
  scopes?: string[];
13
14
  sessionStorageBase?: string;
14
15
  sessionCookieName?: string;
16
+ logoutIntentCookieName?: string;
15
17
  routes?: Partial<AuthRoutes>;
16
18
  }
17
19
  declare module '@nuxt/schema' {
@@ -20,6 +22,7 @@ declare module '@nuxt/schema' {
20
22
  clientSecret: string;
21
23
  sessionStorageBase: string;
22
24
  sessionCookieName: string;
25
+ logoutIntentCookieName: string;
23
26
  };
24
27
  }
25
28
  interface PublicRuntimeConfig {
@@ -27,6 +30,7 @@ declare module '@nuxt/schema' {
27
30
  domain: string;
28
31
  clientId: string;
29
32
  routes: AuthRoutes;
33
+ logoutIntentCookieName: string;
30
34
  scopes: string[];
31
35
  };
32
36
  }
package/dist/module.d.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  import * as _nuxt_schema from '@nuxt/schema';
2
2
 
3
3
  interface AuthRoutes {
4
+ login: string;
4
5
  signIn: string;
5
6
  callback: string;
6
7
  signOut: string;
@@ -12,6 +13,7 @@ interface ModuleOptions {
12
13
  scopes?: string[];
13
14
  sessionStorageBase?: string;
14
15
  sessionCookieName?: string;
16
+ logoutIntentCookieName?: string;
15
17
  routes?: Partial<AuthRoutes>;
16
18
  }
17
19
  declare module '@nuxt/schema' {
@@ -20,6 +22,7 @@ declare module '@nuxt/schema' {
20
22
  clientSecret: string;
21
23
  sessionStorageBase: string;
22
24
  sessionCookieName: string;
25
+ logoutIntentCookieName: string;
23
26
  };
24
27
  }
25
28
  interface PublicRuntimeConfig {
@@ -27,6 +30,7 @@ declare module '@nuxt/schema' {
27
30
  domain: string;
28
31
  clientId: string;
29
32
  routes: AuthRoutes;
33
+ logoutIntentCookieName: string;
30
34
  scopes: string[];
31
35
  };
32
36
  }
package/dist/module.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@thecodeorigin/auth",
3
3
  "configKey": "auth",
4
- "version": "0.0.6",
4
+ "version": "0.0.8",
5
5
  "builder": {
6
6
  "@nuxt/module-builder": "1.0.2",
7
7
  "unbuild": "3.6.1"
package/dist/module.mjs CHANGED
@@ -8,20 +8,34 @@ const module$1 = defineNuxtModule({
8
8
  scopes: ["openid", "profile", "email"],
9
9
  sessionStorageBase: "auth",
10
10
  sessionCookieName: "tco_auth",
11
- routes: { signIn: "/auth/sign-in", callback: "/auth/callback", signOut: "/auth/sign-out", home: "/", error: "/auth/sign-in" }
11
+ routes: { login: "/auth/login", signIn: "/auth/sign-in", callback: "/auth/callback", signOut: "/auth/sign-out", home: "/", error: "/auth/sign-in" }
12
12
  },
13
13
  setup(options, nuxt) {
14
14
  const resolver = createResolver(import.meta.url);
15
- const routes = { signIn: "/auth/sign-in", callback: "/auth/callback", signOut: "/auth/sign-out", home: "/", error: "/auth/sign-in", ...options.routes };
15
+ const routes = {
16
+ login: "/auth/login",
17
+ signIn: "/auth/sign-in",
18
+ callback: "/auth/callback",
19
+ signOut: "/auth/sign-out",
20
+ home: "/",
21
+ error: "/auth/sign-in",
22
+ ...options.routes
23
+ };
24
+ const logoutIntentCookieName = options.logoutIntentCookieName ?? `${options.sessionCookieName}_logout`;
25
+ if (routes.login === routes.signIn) {
26
+ throw new Error("[auth] routes.login and routes.signIn must use different paths");
27
+ }
16
28
  nuxt.options.runtimeConfig.auth = defu(nuxt.options.runtimeConfig.auth, {
17
29
  clientSecret: "",
18
30
  sessionStorageBase: options.sessionStorageBase,
19
- sessionCookieName: options.sessionCookieName
31
+ sessionCookieName: options.sessionCookieName,
32
+ logoutIntentCookieName
20
33
  });
21
34
  nuxt.options.runtimeConfig.public.auth = defu(nuxt.options.runtimeConfig.public.auth, {
22
35
  domain: options.domain,
23
36
  clientId: "",
24
37
  routes,
38
+ logoutIntentCookieName,
25
39
  scopes: options.scopes
26
40
  });
27
41
  addServerHandler({ route: routes.signIn, handler: resolver.resolve("./runtime/server/routes/sign-in.get") });
@@ -35,8 +49,13 @@ const module$1 = defineNuxtModule({
35
49
  ["/api/_auth/impersonatable-users", "impersonatable-users.get"],
36
50
  ["/api/_auth/impersonate", "impersonate.post"],
37
51
  ["/api/_auth/stop-impersonating", "stop-impersonating.post"]
38
- ])
39
- addServerHandler({ route, handler: resolver.resolve(`./runtime/server/api/_auth/${file}`) });
52
+ ]) {
53
+ addServerHandler({
54
+ route,
55
+ handler: resolver.resolve(`./runtime/server/api/_auth/${file}`),
56
+ method: file.endsWith(".post") ? "post" : "get"
57
+ });
58
+ }
40
59
  addServerImportsDir(resolver.resolve("./runtime/server/utils"));
41
60
  addImportsDir(resolver.resolve("./runtime/app/composables"));
42
61
  addRouteMiddleware({ name: "auth", path: resolver.resolve("./runtime/app/middleware/auth.global"), global: true });
@@ -42,7 +42,8 @@ export function useAuth() {
42
42
  return navigateTo(qs ? `${routes.signIn}?${qs}` : routes.signIn, { external: true });
43
43
  }
44
44
  async function signOut() {
45
- await $fetch("/api/_auth/sign-out", { method: "POST" }).catch(() => {
45
+ const signOutRoute = "/api/_auth/sign-out";
46
+ await $fetch(signOutRoute, { method: "POST" }).catch(() => {
46
47
  });
47
48
  session.value = null;
48
49
  }
@@ -1,11 +1,22 @@
1
- import { defineNuxtRouteMiddleware, navigateTo, useRuntimeConfig, useState } from "#app";
1
+ import { defineNuxtRouteMiddleware, navigateTo, useCookie, useRuntimeConfig, useState } from "#app";
2
+ import { resolveAuthRedirect } from "../utils/auth-redirect.js";
2
3
  export default defineNuxtRouteMiddleware((to) => {
3
4
  const session = useState("tco-auth-session", () => null);
4
- const routes = useRuntimeConfig().public.auth?.routes ?? {};
5
+ const authConfig = useRuntimeConfig().public.auth;
6
+ const routes = authConfig?.routes;
7
+ const logoutIntentCookieName = authConfig?.logoutIntentCookieName ?? "tco_auth_logout";
8
+ const logoutIntent = useCookie(logoutIntentCookieName);
5
9
  const authed = !!session.value;
6
10
  const isPublic = to.meta.public === true || to.meta.unauthenticatedOnly === true;
7
11
  if (authed && to.meta.unauthenticatedOnly)
8
- return navigateTo(routes.home);
9
- if (!authed && !isPublic)
10
- return navigateTo(`${routes.signIn}?redirect=${encodeURIComponent(to.fullPath)}`, { external: true });
12
+ return navigateTo(routes?.home ?? "/");
13
+ if (!authed && !isPublic) {
14
+ const redirect = resolveAuthRedirect({
15
+ loginRoute: routes?.login ?? "/auth/login",
16
+ signInRoute: routes?.signIn ?? "/auth/sign-in",
17
+ target: to.fullPath,
18
+ logoutIntent: logoutIntent.value === "1"
19
+ });
20
+ return navigateTo(redirect.to, { external: redirect.external });
21
+ }
11
22
  });
@@ -0,0 +1,10 @@
1
+ export interface AuthRedirectOptions {
2
+ loginRoute: string;
3
+ signInRoute: string;
4
+ target: string;
5
+ logoutIntent: boolean;
6
+ }
7
+ export declare function resolveAuthRedirect(options: AuthRedirectOptions): {
8
+ external: boolean;
9
+ to: string;
10
+ };
@@ -0,0 +1,13 @@
1
+ export function resolveAuthRedirect(options) {
2
+ const redirect = encodeURIComponent(options.target);
3
+ if (options.logoutIntent) {
4
+ return {
5
+ external: false,
6
+ to: `${options.loginRoute}?loggedout=1&redirect=${redirect}`
7
+ };
8
+ }
9
+ return {
10
+ external: true,
11
+ to: `${options.signInRoute}?redirect=${redirect}`
12
+ };
13
+ }
@@ -1,6 +1,8 @@
1
1
  import { defineEventHandler } from "h3";
2
+ import { setLogoutIntent } from "../../utils/logout-intent.js";
2
3
  import { destroySession } from "../../utils/session.js";
3
4
  export default defineEventHandler(async (event) => {
4
5
  await destroySession(event);
6
+ setLogoutIntent(event);
5
7
  return { ok: true };
6
8
  });
@@ -2,6 +2,7 @@ import { defineEventHandler, deleteCookie, getCookie, getQuery, sendRedirect } f
2
2
  import { useRuntimeConfig } from "nitropack/runtime";
3
3
  import { z } from "zod";
4
4
  import { UserinfoClaimsSchema } from "../../../contract";
5
+ import { clearLogoutIntent } from "../utils/logout-intent.js";
5
6
  import { callbackRedirectUri, exchangeCode, fetchUserinfo, safePath } from "../utils/oidc.js";
6
7
  import { newSessionId, setSessionCookie, writeSessionRecord } from "../utils/session.js";
7
8
  const RawUserinfoSchema = UserinfoClaimsSchema.extend({
@@ -59,5 +60,6 @@ export default defineEventHandler(async (event) => {
59
60
  backupId: null
60
61
  });
61
62
  await setSessionCookie(event, id);
63
+ clearLogoutIntent(event);
62
64
  return sendRedirect(event, redirectTo);
63
65
  });
@@ -1,12 +1,14 @@
1
1
  import { createError, defineEventHandler, getQuery, sendRedirect, setCookie } from "h3";
2
2
  import { useRuntimeConfig } from "nitropack/runtime";
3
3
  import { withQuery } from "ufo";
4
- import { callbackRedirectUri, pkceChallenge, randomString, safePath } from "../utils/oidc.js";
4
+ import { clearLogoutIntent } from "../utils/logout-intent.js";
5
+ import { callbackRedirectUri, idpBaseUrl, pkceChallenge, randomString, safePath } from "../utils/oidc.js";
5
6
  const ALLOWED_PROMPTS = /* @__PURE__ */ new Set(["login", "select_account", "consent", "none"]);
6
7
  export default defineEventHandler(async (event) => {
7
8
  const { auth: runtimeConfig, public: { auth: publicRuntimeConfig } } = useRuntimeConfig();
8
9
  if (!publicRuntimeConfig.domain || !publicRuntimeConfig.clientId || !runtimeConfig.clientSecret)
9
10
  throw createError({ statusCode: 503, statusMessage: "Auth not configured" });
11
+ clearLogoutIntent(event);
10
12
  const query = getQuery(event);
11
13
  const state = randomString(32);
12
14
  const verifier = randomString(64);
@@ -16,7 +18,7 @@ export default defineEventHandler(async (event) => {
16
18
  setCookie(event, "tco_state", state, opts);
17
19
  setCookie(event, "tco_verifier", verifier, opts);
18
20
  setCookie(event, "tco_redirect", redirectTo, opts);
19
- return sendRedirect(event, withQuery(`https://${publicRuntimeConfig.domain}/api/auth/oauth2/authorize`, {
21
+ return sendRedirect(event, withQuery(`${idpBaseUrl()}/api/auth/oauth2/authorize`, {
20
22
  client_id: publicRuntimeConfig.clientId,
21
23
  redirect_uri: callbackRedirectUri(event),
22
24
  response_type: "code",
@@ -1,8 +1,10 @@
1
1
  import { defineEventHandler, sendRedirect } from "h3";
2
2
  import { useRuntimeConfig } from "nitropack/runtime";
3
+ import { setLogoutIntent } from "../utils/logout-intent.js";
3
4
  import { destroySession } from "../utils/session.js";
4
5
  export default defineEventHandler(async (event) => {
5
6
  const { public: { auth: publicRuntimeConfig } } = useRuntimeConfig();
6
7
  await destroySession(event);
8
+ setLogoutIntent(event);
7
9
  return sendRedirect(event, publicRuntimeConfig.routes.home);
8
10
  });
@@ -1,6 +1,7 @@
1
1
  import { createError } from "h3";
2
2
  import { useRuntimeConfig } from "nitropack/runtime";
3
3
  import { $fetch } from "ofetch";
4
+ import { idpBaseUrl } from "./oidc.js";
4
5
  import { readSessionRecordById, writeSessionRecord } from "./session.js";
5
6
  const SKEW_MS = 6e4;
6
7
  async function refresh(rec) {
@@ -9,7 +10,7 @@ async function refresh(rec) {
9
10
  const { auth: runtimeConfig, public: { auth: publicRuntimeConfig } } = useRuntimeConfig();
10
11
  try {
11
12
  const t = await $fetch(
12
- `https://${publicRuntimeConfig.domain}/api/auth/oauth2/token`,
13
+ `${idpBaseUrl()}/api/auth/oauth2/token`,
13
14
  {
14
15
  method: "POST",
15
16
  headers: {
@@ -28,12 +29,11 @@ async function refresh(rec) {
28
29
  }
29
30
  }
30
31
  export async function idpFetch(event, id, rec, path, opts = {}) {
31
- const { public: { auth: publicRuntimeConfig } } = useRuntimeConfig();
32
32
  if (!rec.isImpersonation && Date.now() > rec.accessExpiresAt - SKEW_MS) {
33
33
  if (await refresh(rec))
34
34
  await writeSessionRecord(id, rec);
35
35
  }
36
- const call = () => $fetch(`https://${publicRuntimeConfig.domain}${path}`, {
36
+ const call = () => $fetch(`${idpBaseUrl()}${path}`, {
37
37
  method: opts.method,
38
38
  body: opts.body,
39
39
  query: opts.query,
@@ -0,0 +1,3 @@
1
+ import type { H3Event } from 'h3';
2
+ export declare function setLogoutIntent(event: H3Event): void;
3
+ export declare function clearLogoutIntent(event: H3Event): void;
@@ -0,0 +1,17 @@
1
+ import { deleteCookie, setCookie } from "h3";
2
+ import { useRuntimeConfig } from "nitropack/runtime";
3
+ const LOGOUT_INTENT_MAX_AGE = 60 * 60 * 24 * 7;
4
+ export function setLogoutIntent(event) {
5
+ const { auth: runtimeConfig } = useRuntimeConfig();
6
+ setCookie(event, runtimeConfig.logoutIntentCookieName, "1", {
7
+ httpOnly: false,
8
+ secure: !import.meta.dev,
9
+ sameSite: "lax",
10
+ path: "/",
11
+ maxAge: LOGOUT_INTENT_MAX_AGE
12
+ });
13
+ }
14
+ export function clearLogoutIntent(event) {
15
+ const { auth: runtimeConfig } = useRuntimeConfig();
16
+ deleteCookie(event, runtimeConfig.logoutIntentCookieName, { path: "/" });
17
+ }
@@ -5,6 +5,7 @@ declare module 'nitropack' {
5
5
  clientSecret: string;
6
6
  sessionStorageBase: string;
7
7
  sessionCookieName: string;
8
+ logoutIntentCookieName: string;
8
9
  };
9
10
  }
10
11
  interface NitroRuntimePublicConfig {
@@ -12,12 +13,14 @@ declare module 'nitropack' {
12
13
  domain: string;
13
14
  clientId: string;
14
15
  routes: {
16
+ login: string;
15
17
  signIn: string;
16
18
  callback: string;
17
19
  signOut: string;
18
20
  home: string;
19
21
  error: string;
20
22
  };
23
+ logoutIntentCookieName: string;
21
24
  scopes: string[];
22
25
  };
23
26
  }
@@ -25,6 +28,8 @@ declare module 'nitropack' {
25
28
  export declare function randomString(len?: number): string;
26
29
  export declare function pkceChallenge(verifier: string): Promise<string>;
27
30
  export declare function callbackRedirectUri(event: H3Event): string;
31
+ /** IdP origin. `domain` may already carry a scheme (e.g. `http://localhost:3000`); otherwise assume https. */
32
+ export declare function idpBaseUrl(): string;
28
33
  export declare function exchangeCode(code: string, verifier: string, redirectUri: string): Promise<{
29
34
  access_token: string;
30
35
  refresh_token?: string;
@@ -16,10 +16,15 @@ export function callbackRedirectUri(event) {
16
16
  const { public: { auth: publicRuntimeConfig } } = useRuntimeConfig();
17
17
  return `${getRequestProtocol(event)}://${getRequestHost(event)}${publicRuntimeConfig.routes.callback}`;
18
18
  }
19
+ export function idpBaseUrl() {
20
+ const { public: { auth: publicRuntimeConfig } } = useRuntimeConfig();
21
+ const domain = publicRuntimeConfig.domain;
22
+ return /^https?:\/\//.test(domain) ? domain : `https://${domain}`;
23
+ }
19
24
  export async function exchangeCode(code, verifier, redirectUri) {
20
25
  const { auth: runtimeConfig, public: { auth: publicRuntimeConfig } } = useRuntimeConfig();
21
26
  return $fetch(
22
- `https://${publicRuntimeConfig.domain}/api/auth/oauth2/token`,
27
+ `${idpBaseUrl()}/api/auth/oauth2/token`,
23
28
  {
24
29
  method: "POST",
25
30
  headers: {
@@ -36,8 +41,7 @@ export async function exchangeCode(code, verifier, redirectUri) {
36
41
  );
37
42
  }
38
43
  export async function fetchUserinfo(accessToken) {
39
- const { public: { auth: publicRuntimeConfig } } = useRuntimeConfig();
40
- return $fetch(`https://${publicRuntimeConfig.domain}/api/auth/oauth2/userinfo`, {
44
+ return $fetch(`${idpBaseUrl()}/api/auth/oauth2/userinfo`, {
41
45
  headers: { Authorization: `Bearer ${accessToken}` }
42
46
  });
43
47
  }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@thecodeorigin/auth",
3
3
  "type": "module",
4
- "version": "0.0.6",
4
+ "version": "0.0.8",
5
5
  "private": false,
6
6
  "description": "THECODEORIGIN Authentication Portal client module",
7
7
  "repository": "https://github.com/thecodeorigin/auth",