@logto/sveltekit 0.1.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2022 Silverhand
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,45 @@
1
+ # Logto SvelteKit SDK
2
+
3
+ [![Version](https://img.shields.io/npm/v/@logto/sveltekit)](https://www.npmjs.com/package/@logto/sveltekit)
4
+ [![Build Status](https://github.com/logto-io/js/actions/workflows/main.yml/badge.svg)](https://github.com/logto-io/js/actions/workflows/main.yml)
5
+
6
+ The Logto SvelteKit SDK written in TypeScript. Requires SvelteKit ^2.0.0.
7
+
8
+ Check out our [docs](https://docs.logto.io/sdk/sveltekit/) for more information.
9
+
10
+ ## Installation
11
+
12
+ ### Using npm
13
+
14
+ ```bash
15
+ npm install @logto/sveltekit
16
+ ```
17
+
18
+ ### Using yarn
19
+
20
+ ```bash
21
+ yarn add @logto/sveltekit
22
+ ```
23
+
24
+ ### Using pnpm
25
+
26
+ ```bash
27
+ pnpm add @logto/sveltekit
28
+ ```
29
+
30
+ ## Get sample
31
+
32
+ A sample project can be found at [SvelteKit sample](https://github.com/logto-io/js/tree/master/packages/sveltekit-sample)
33
+
34
+ Check out the full JS repo and try it with pnpm.
35
+
36
+ ```bash
37
+ pnpm i && pnpm build
38
+ cd packages/sveltekit-sample && pnpm start
39
+ ```
40
+
41
+ ## Resources
42
+
43
+ [![Website](https://img.shields.io/badge/website-logto.io-8262F8.svg)](https://logto.io/)
44
+ [![Docs](https://img.shields.io/badge/docs-logto.io-green.svg)](https://docs.logto.io/)
45
+ [![Discord](https://img.shields.io/discord/965845662535147551?logo=discord&logoColor=ffffff&color=7389D8&cacheSeconds=600)](https://discord.gg/UEPaF3j5e6)
@@ -0,0 +1,2 @@
1
+ /// <reference types="jest" />
2
+ export declare const redirect: jest.Mock<any, any, any>;
@@ -0,0 +1 @@
1
+ export const redirect = jest.fn();
package/lib/index.d.ts ADDED
@@ -0,0 +1,70 @@
1
+ import LogtoClient, { type LogtoConfig, type CookieConfig } from '@logto/node';
2
+ import { type Handle, type RequestEvent } from '@sveltejs/kit';
3
+ export type { IdTokenClaims, LogtoErrorCode, LogtoConfig, LogtoClientErrorCode, Storage, StorageKey, InteractionMode, ClientAdapter, JwtVerifier, UserInfoResponse, } from '@logto/node';
4
+ export { LogtoError, LogtoRequestError, LogtoClientError, OidcError, Prompt, ReservedScope, ReservedResource, UserScope, organizationUrnPrefix, buildOrganizationUrn, getOrganizationIdFromUrn, PersistKey, StandardLogtoClient, default as LogtoClient, } from '@logto/node';
5
+ export type HookConfig = {
6
+ /**
7
+ * The error response factory when an error occurs during the callback. If not provided, a 400
8
+ * response will be returned.
9
+ *
10
+ * @param error The error that occurred.
11
+ */
12
+ onCallbackError?: (error: unknown) => Response;
13
+ /**
14
+ * The path to the callback handler. Default to `/callback`.
15
+ */
16
+ signInCallback?: string;
17
+ /**
18
+ * Whether to fetch user info via OIDC userinfo endpoint. Default to `false`.
19
+ */
20
+ fetchUserInfo?: boolean;
21
+ /**
22
+ * The factory to build the `LogtoClient` instance. If not provided, a default instance will be
23
+ * created.
24
+ */
25
+ buildLogtoClient?: (event: RequestEvent) => LogtoClient;
26
+ };
27
+ /**
28
+ * The factory to create a SvelteKit hook to handle Logto authentication. The hook will
29
+ * initialize the `LogtoClient` instance and add it to the `locals` of the request event. It will
30
+ * also handle the callback from the OIDC provider and fetch user info if necessary.
31
+ *
32
+ * @example
33
+ * Here is a minimal example of how to use this hook:
34
+ * ```ts
35
+ * // src/hooks.server.ts
36
+ * import { handleLogto } from '@logto/sveltekit';
37
+ * import { env } from '$env/dynamic/private';
38
+ *
39
+ * export const handle = handleLogto(
40
+ * {
41
+ * endpoint: env.LOGTO_ENDPOINT,
42
+ * appId: env.LOGTO_APP_ID,
43
+ * appSecret: env.LOGTO_APP_SECRET,
44
+ * },
45
+ * {
46
+ * encryptionKey: env.LOGTO_COOKIE_ENCRYPTION_KEY,
47
+ * }
48
+ * );
49
+ * // Then you can use the `logtoClient` and `user` in `locals` of the request event.
50
+ *
51
+ * // For TypeScript, you can extend the `Locals` interface to add the `logtoClient` and `user` properties:
52
+ * // app.d.ts
53
+ * import type { UserInfoResponse, LogtoClient } from '@logto/sveltekit';
54
+ *
55
+ * declare global {
56
+ * namespace App {
57
+ * interface Locals {
58
+ * logtoClient: LogtoClient;
59
+ * user?: UserInfoResponse;
60
+ * }
61
+ * }
62
+ * }
63
+ * ```
64
+ *
65
+ * @param config The Logto configuration.
66
+ * @param cookieConfig The configuration object for the cookie storage.
67
+ * @param hookConfig The configuration object for the hook itself.
68
+ * @returns The SvelteKit hook.
69
+ */
70
+ export declare const handleLogto: (config: LogtoConfig, cookieConfig: Pick<CookieConfig, 'cookieKey' | 'encryptionKey'>, hookConfig?: HookConfig) => Handle;
package/lib/index.js ADDED
@@ -0,0 +1,92 @@
1
+ import LogtoClient, { CookieStorage } from '@logto/node';
2
+ import { redirect } from '@sveltejs/kit';
3
+ export { LogtoError, LogtoRequestError, LogtoClientError, OidcError, Prompt, ReservedScope, ReservedResource, UserScope, organizationUrnPrefix, buildOrganizationUrn, getOrganizationIdFromUrn, PersistKey, StandardLogtoClient, default as LogtoClient, } from '@logto/node';
4
+ /**
5
+ * The factory to create a SvelteKit hook to handle Logto authentication. The hook will
6
+ * initialize the `LogtoClient` instance and add it to the `locals` of the request event. It will
7
+ * also handle the callback from the OIDC provider and fetch user info if necessary.
8
+ *
9
+ * @example
10
+ * Here is a minimal example of how to use this hook:
11
+ * ```ts
12
+ * // src/hooks.server.ts
13
+ * import { handleLogto } from '@logto/sveltekit';
14
+ * import { env } from '$env/dynamic/private';
15
+ *
16
+ * export const handle = handleLogto(
17
+ * {
18
+ * endpoint: env.LOGTO_ENDPOINT,
19
+ * appId: env.LOGTO_APP_ID,
20
+ * appSecret: env.LOGTO_APP_SECRET,
21
+ * },
22
+ * {
23
+ * encryptionKey: env.LOGTO_COOKIE_ENCRYPTION_KEY,
24
+ * }
25
+ * );
26
+ * // Then you can use the `logtoClient` and `user` in `locals` of the request event.
27
+ *
28
+ * // For TypeScript, you can extend the `Locals` interface to add the `logtoClient` and `user` properties:
29
+ * // app.d.ts
30
+ * import type { UserInfoResponse, LogtoClient } from '@logto/sveltekit';
31
+ *
32
+ * declare global {
33
+ * namespace App {
34
+ * interface Locals {
35
+ * logtoClient: LogtoClient;
36
+ * user?: UserInfoResponse;
37
+ * }
38
+ * }
39
+ * }
40
+ * ```
41
+ *
42
+ * @param config The Logto configuration.
43
+ * @param cookieConfig The configuration object for the cookie storage.
44
+ * @param hookConfig The configuration object for the hook itself.
45
+ * @returns The SvelteKit hook.
46
+ */
47
+ export const handleLogto = (config, cookieConfig, hookConfig) => {
48
+ const { signInCallback = '/callback', onCallbackError, fetchUserInfo = false, buildLogtoClient, } = hookConfig ?? {};
49
+ return async ({ resolve, event }) => {
50
+ // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition -- sanity check
51
+ if (event.locals.logtoClient) {
52
+ console.warn('`logtoClient` already exists in `locals`, you probably have added the `handleLogto` hook more than once. Skipping.');
53
+ return resolve(event);
54
+ }
55
+ const storage = new CookieStorage({
56
+ setCookie: (...args) => {
57
+ event.cookies.set(...args);
58
+ },
59
+ getCookie: (...args) => event.cookies.get(...args),
60
+ ...cookieConfig,
61
+ }, event.request);
62
+ await storage.init();
63
+ const logtoClient = buildLogtoClient?.(event) ??
64
+ new LogtoClient(config, {
65
+ navigate: (url) => {
66
+ redirect(302, url);
67
+ },
68
+ storage,
69
+ });
70
+ // eslint-disable-next-line @silverhand/fp/no-mutation -- for init
71
+ event.locals.logtoClient = logtoClient;
72
+ if (event.url.pathname === signInCallback) {
73
+ try {
74
+ await logtoClient.handleSignInCallback(event.url.href);
75
+ }
76
+ catch (error) {
77
+ return (onCallbackError?.(error) ??
78
+ new Response(`Error: ${error instanceof Error ? error.message : String(error)}`, {
79
+ status: 400,
80
+ }));
81
+ }
82
+ return redirect(302, '/');
83
+ }
84
+ if (await logtoClient.isAuthenticated()) {
85
+ // eslint-disable-next-line @silverhand/fp/no-mutation
86
+ event.locals.user = await (fetchUserInfo
87
+ ? logtoClient.fetchUserInfo()
88
+ : logtoClient.getIdTokenClaims());
89
+ }
90
+ return resolve(event);
91
+ };
92
+ };
package/package.json ADDED
@@ -0,0 +1,59 @@
1
+ {
2
+ "name": "@logto/sveltekit",
3
+ "version": "0.1.0",
4
+ "type": "module",
5
+ "main": "./lib/index.js",
6
+ "module": "./lib/index.js",
7
+ "types": "./lib/index.d.ts",
8
+ "exports": {
9
+ "types": "./lib/index.d.ts",
10
+ "import": "./lib/index.js",
11
+ "require": "./lib/index.js",
12
+ "default": "./lib/index.js"
13
+ },
14
+ "files": [
15
+ "lib"
16
+ ],
17
+ "license": "MIT",
18
+ "repository": {
19
+ "type": "git",
20
+ "url": "https://github.com/logto-io/js.git",
21
+ "directory": "packages/sveltekit"
22
+ },
23
+ "devDependencies": {
24
+ "@silverhand/eslint-config": "^5.0.0",
25
+ "@silverhand/ts-config": "^5.0.0",
26
+ "@sveltejs/kit": "^2.0.0",
27
+ "@swc/core": "^1.4.2",
28
+ "@swc/jest": "^0.2.24",
29
+ "@types/cookie": "^0.6.0",
30
+ "@types/jest": "^29.5.12",
31
+ "@types/node": "^20.11.19",
32
+ "eslint": "^8.44.0",
33
+ "jest": "^29.5.0",
34
+ "lint-staged": "^15.0.0",
35
+ "prettier": "^3.0.0",
36
+ "typescript": "^5.3.3"
37
+ },
38
+ "eslintConfig": {
39
+ "extends": "@silverhand"
40
+ },
41
+ "prettier": "@silverhand/eslint-config/.prettierrc",
42
+ "publishConfig": {
43
+ "access": "public"
44
+ },
45
+ "peerDependencies": {
46
+ "@sveltejs/kit": "^2.0.0"
47
+ },
48
+ "dependencies": {
49
+ "@logto/node": "^2.4.0"
50
+ },
51
+ "scripts": {
52
+ "dev:tsc": "tsc -p tsconfig.build.json -w --preserveWatchOutput",
53
+ "precommit": "lint-staged",
54
+ "check": "tsc --noEmit",
55
+ "build": "rm -rf lib/ && tsc -p tsconfig.build.json",
56
+ "lint": "eslint --ext .ts src",
57
+ "test": "jest"
58
+ }
59
+ }