@~lyre/auth 0.0.4

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) 2026 Britam Trust Services / Lyre
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,59 @@
1
+ # @~lyre/auth
2
+
3
+ Shared **Axis Accounts** auth SDK. A small, framework-agnostic core for session
4
+ and identity handling (HMAC-signed cookies, the accounts login → callback →
5
+ logout exchange, tenant resolution), plus an optional turnkey **SvelteKit**
6
+ adapter that wires it all up in a few lines.
7
+
8
+ Ships as raw TypeScript source.
9
+
10
+ ## Install
11
+
12
+ ```bash
13
+ pnpm add @~lyre/auth # or: npm i / yarn add
14
+ ```
15
+
16
+ ## Entry points
17
+
18
+ ### `@~lyre/auth` — framework-agnostic core
19
+
20
+ Session, identity and accounts primitives — usable from any Node runtime:
21
+
22
+ ```ts
23
+ import {
24
+ createPlatformAuth,
25
+ beginAccountsLoginRedirect,
26
+ handleAccountsCallback,
27
+ readPlatformSessionCookie,
28
+ clearPlatformSessionCookie,
29
+ resolveActiveTenant,
30
+ syncAccountsUser,
31
+ type PlatformSession,
32
+ type AccountsIdentity,
33
+ } from '@~lyre/auth';
34
+ ```
35
+
36
+ The core depends only on `node:crypto` — no framework required.
37
+
38
+ ### `@~lyre/auth/sveltekit` — turnkey SvelteKit adapter
39
+
40
+ A single `handle` that reads the session into `event.locals`, serves
41
+ `/auth/login`, `/auth/callback` and `/auth/logout` inline (no route files), and
42
+ optionally gates protected paths:
43
+
44
+ ```ts
45
+ // src/hooks.server.ts
46
+ import { createAuthHandle } from '@~lyre/auth/sveltekit';
47
+
48
+ export const handle = createAuthHandle({
49
+ // ...SvelteKitAuthOptions
50
+ });
51
+ ```
52
+
53
+ `@sveltejs/kit` is an **optional peer dependency** — only required if you import
54
+ the `/sveltekit` entry.
55
+
56
+ ## Publishing
57
+
58
+ See [PUBLISHING.md](PUBLISHING.md). Published to npm via GitHub Actions Trusted
59
+ Publishing on version bump.
@@ -0,0 +1,246 @@
1
+ // src/index.ts
2
+ import { createHmac, timingSafeEqual } from "crypto";
3
+ var SESSION_COOKIE_NAME = "platform_session";
4
+ var STATE_COOKIE_NAME = "accounts_auth_state";
5
+ function createAccountsClientConfig(input = {}) {
6
+ return {
7
+ baseUrl: input.baseUrl ?? process.env.ACCOUNTS_BASE_URL,
8
+ clientId: input.clientId ?? process.env.ACCOUNTS_CLIENT_ID ?? "accounts-app",
9
+ clientSecret: input.clientSecret ?? process.env.ACCOUNTS_CLIENT_SECRET,
10
+ redirectUri: input.redirectUri ?? process.env.ACCOUNTS_REDIRECT_URI ?? "http://localhost:5173/auth/callback",
11
+ logoutRedirectUri: input.logoutRedirectUri ?? process.env.ACCOUNTS_LOGOUT_REDIRECT_URI ?? "http://localhost:5173/",
12
+ useMock: input.useMock ?? (process.env.ACCOUNTS_USE_MOCK === "true" || !process.env.ACCOUNTS_BASE_URL || !process.env.ACCOUNTS_CLIENT_ID)
13
+ };
14
+ }
15
+ function createPlatformAuth() {
16
+ return {
17
+ readSession(cookieHeader) {
18
+ return readPlatformSessionCookie(cookieHeader);
19
+ },
20
+ requirePrincipal(session) {
21
+ if (!session.principal) {
22
+ throw new Error("Authentication required.");
23
+ }
24
+ return session.principal;
25
+ }
26
+ };
27
+ }
28
+ function beginAccountsLoginRedirect(config, options) {
29
+ const nonce = globalThis.crypto?.randomUUID?.() ?? Math.random().toString(36).slice(2);
30
+ const state = {
31
+ nonce,
32
+ nextPath: options.nextPath && options.nextPath.startsWith("/") ? options.nextPath : "/",
33
+ tenantSlug: options.tenantSlug
34
+ };
35
+ if (config.useMock) {
36
+ const redirectUrl = new URL(config.redirectUri);
37
+ redirectUrl.searchParams.set("code", `demo_${nonce}`);
38
+ redirectUrl.searchParams.set("state", serializeAuthorizationState(state));
39
+ return {
40
+ redirectUrl: redirectUrl.toString(),
41
+ stateValue: serializeAuthorizationState(state),
42
+ stateCookie: createStateCookie(serializeAuthorizationState(state), options.cookieOptions)
43
+ };
44
+ }
45
+ const authorizeUrl = new URL("/auth/authorize", config.baseUrl);
46
+ authorizeUrl.searchParams.set("app_id", config.clientId);
47
+ authorizeUrl.searchParams.set("redirect_uri", config.redirectUri);
48
+ authorizeUrl.searchParams.set("state", serializeAuthorizationState(state));
49
+ return {
50
+ redirectUrl: authorizeUrl.toString(),
51
+ stateValue: serializeAuthorizationState(state),
52
+ stateCookie: createStateCookie(serializeAuthorizationState(state))
53
+ };
54
+ }
55
+ async function handleAccountsCallback(input) {
56
+ if (!input.code) {
57
+ throw new Error("Missing authorization code.");
58
+ }
59
+ if (input.storedState && input.state !== input.storedState) {
60
+ throw new Error("Invalid authorization state.");
61
+ }
62
+ const parsedState = parseAuthorizationState(input.state);
63
+ const tokenResponse = await exchangeAuthorizationCode({
64
+ config: input.config,
65
+ code: input.code,
66
+ fetchImpl: input.fetchImpl
67
+ });
68
+ const identity = normalizeIdentity(tokenResponse.user);
69
+ const local = await input.syncAccountsUser(identity);
70
+ const session = {
71
+ principal: {
72
+ identity,
73
+ user: local.user,
74
+ tenantAccess: {
75
+ activeTenantId: local.activeTenantId,
76
+ memberships: local.memberships
77
+ }
78
+ },
79
+ tenant: null,
80
+ accessToken: tokenResponse.access_token,
81
+ refreshToken: tokenResponse.refresh_token,
82
+ expiresAt: new Date(Date.now() + tokenResponse.expires_in * 1e3).toISOString()
83
+ };
84
+ return {
85
+ session,
86
+ nextPath: parsedState.nextPath,
87
+ tenantSlug: parsedState.tenantSlug,
88
+ sessionCookie: createSessionCookie(session, input.cookieOptions, input.secret),
89
+ clearStateCookie: clearStateCookie(input.cookieOptions)
90
+ };
91
+ }
92
+ async function exchangeAuthorizationCode(input) {
93
+ if (input.config.useMock || input.code.startsWith("demo_")) {
94
+ return createMockTokenResponse(input.code);
95
+ }
96
+ const fetchImpl = input.fetchImpl ?? fetch;
97
+ const response = await fetchImpl(new URL("/api/auth/token", input.config.baseUrl), {
98
+ method: "POST",
99
+ headers: {
100
+ "content-type": "application/json"
101
+ },
102
+ body: JSON.stringify({
103
+ grant_type: "authorization_code",
104
+ code: input.code,
105
+ redirect_uri: input.config.redirectUri,
106
+ client_id: input.config.clientId,
107
+ client_secret: input.config.clientSecret
108
+ })
109
+ });
110
+ if (!response.ok) {
111
+ throw new Error(`Accounts token exchange failed with status ${response.status}.`);
112
+ }
113
+ return await response.json();
114
+ }
115
+ function syncAccountsUser(identity, syncer) {
116
+ return syncer(identity);
117
+ }
118
+ var identityPassthroughSync = (identity) => ({
119
+ user: {
120
+ id: identity.id,
121
+ externalIdentityId: identity.id,
122
+ email: identity.email,
123
+ name: identity.name,
124
+ firstName: identity.firstName,
125
+ lastName: identity.lastName
126
+ },
127
+ memberships: []
128
+ });
129
+ function resolveActiveTenant(memberships, preferredTenantId) {
130
+ if (preferredTenantId && memberships.some((membership) => membership.tenantId === preferredTenantId)) {
131
+ return preferredTenantId;
132
+ }
133
+ return memberships.find((membership) => membership.isDefault)?.tenantId ?? memberships[0]?.tenantId;
134
+ }
135
+ function readPlatformSessionCookie(cookieHeader, opts) {
136
+ const cookieValue = readCookie(cookieHeader, SESSION_COOKIE_NAME);
137
+ if (!cookieValue) {
138
+ return { principal: null, tenant: null };
139
+ }
140
+ let raw = cookieValue;
141
+ if (opts?.secret) {
142
+ const verified = unsignValue(cookieValue, opts.secret);
143
+ if (verified == null) return { principal: null, tenant: null };
144
+ raw = verified;
145
+ }
146
+ try {
147
+ return JSON.parse(decodeURIComponent(raw));
148
+ } catch {
149
+ return { principal: null, tenant: null };
150
+ }
151
+ }
152
+ function cookieAttrs(opts) {
153
+ const sameSite = opts?.sameSite ?? "lax";
154
+ const secure = opts?.secure || sameSite === "none";
155
+ const cap = sameSite.charAt(0).toUpperCase() + sameSite.slice(1);
156
+ return `Path=/; HttpOnly; SameSite=${cap}${secure ? "; Secure" : ""}`;
157
+ }
158
+ function signValue(value, secret) {
159
+ const sig = createHmac("sha256", secret).update(value).digest("hex");
160
+ return `${value}.${sig}`;
161
+ }
162
+ function unsignValue(signed, secret) {
163
+ const dot = signed.lastIndexOf(".");
164
+ if (dot < 0) return null;
165
+ const value = signed.slice(0, dot);
166
+ const sig = signed.slice(dot + 1);
167
+ if (!/^[0-9a-f]{64}$/.test(sig)) return null;
168
+ const expected = createHmac("sha256", secret).update(value).digest("hex");
169
+ const a = Buffer.from(sig, "hex");
170
+ const b = Buffer.from(expected, "hex");
171
+ if (a.length !== b.length) return null;
172
+ return timingSafeEqual(a, b) ? value : null;
173
+ }
174
+ function clearPlatformSessionCookie(opts) {
175
+ return `${SESSION_COOKIE_NAME}=; ${cookieAttrs(opts)}; Max-Age=0`;
176
+ }
177
+ function createSessionCookie(session, opts, secret) {
178
+ const raw = encodeURIComponent(JSON.stringify(session));
179
+ const value = secret ? signValue(raw, secret) : raw;
180
+ return `${SESSION_COOKIE_NAME}=${value}; ${cookieAttrs(opts)}; Max-Age=${60 * 60 * 24 * 7}`;
181
+ }
182
+ function createStateCookie(value, opts) {
183
+ return `${STATE_COOKIE_NAME}=${encodeURIComponent(value)}; ${cookieAttrs(opts)}; Max-Age=${60 * 10}`;
184
+ }
185
+ function clearStateCookie(opts) {
186
+ return `${STATE_COOKIE_NAME}=; ${cookieAttrs(opts)}; Max-Age=0`;
187
+ }
188
+ function serializeAuthorizationState(state) {
189
+ return encodeURIComponent(JSON.stringify(state));
190
+ }
191
+ function parseAuthorizationState(value) {
192
+ try {
193
+ return JSON.parse(decodeURIComponent(value));
194
+ } catch {
195
+ throw new Error("Invalid authorization state payload.");
196
+ }
197
+ }
198
+ function normalizeIdentity(user) {
199
+ return {
200
+ id: user.id,
201
+ email: user.email ?? `${user.id}@accounts.local`,
202
+ name: user.name ?? ([user.first_name, user.last_name].filter(Boolean).join(" ") || "Accounts User"),
203
+ firstName: user.first_name,
204
+ lastName: user.last_name,
205
+ avatarUrl: user.avatar_url
206
+ };
207
+ }
208
+ function createMockTokenResponse(code) {
209
+ const suffix = code.replace("demo_", "").slice(0, 8) || "demo";
210
+ return {
211
+ access_token: `access_${suffix}`,
212
+ refresh_token: `refresh_${suffix}`,
213
+ token_type: "Bearer",
214
+ expires_in: 60 * 60 * 24 * 7,
215
+ user: {
216
+ id: "accounts-user-demo-admin",
217
+ email: "hello@babyplanet.example",
218
+ name: "Baby Planet Admin",
219
+ first_name: "Baby",
220
+ last_name: "Planet"
221
+ }
222
+ };
223
+ }
224
+ function readCookie(cookieHeader, name) {
225
+ if (!cookieHeader) return null;
226
+ for (const part of cookieHeader.split(";")) {
227
+ const [key, ...rest] = part.trim().split("=");
228
+ if (key === name) {
229
+ return rest.join("=");
230
+ }
231
+ }
232
+ return null;
233
+ }
234
+
235
+ export {
236
+ createAccountsClientConfig,
237
+ createPlatformAuth,
238
+ beginAccountsLoginRedirect,
239
+ handleAccountsCallback,
240
+ exchangeAuthorizationCode,
241
+ syncAccountsUser,
242
+ identityPassthroughSync,
243
+ resolveActiveTenant,
244
+ readPlatformSessionCookie,
245
+ clearPlatformSessionCookie
246
+ };
@@ -0,0 +1,142 @@
1
+ type PermissionSet = string[];
2
+ type AccountsIdentity = {
3
+ id: string;
4
+ email: string;
5
+ name: string;
6
+ firstName?: string;
7
+ lastName?: string;
8
+ avatarUrl?: string;
9
+ };
10
+ type LocalUser = {
11
+ id: string;
12
+ externalIdentityId: string;
13
+ email: string;
14
+ name: string;
15
+ firstName?: string;
16
+ lastName?: string;
17
+ defaultTenantId?: string;
18
+ };
19
+ type TenantMembership = {
20
+ tenantId: string;
21
+ role: 'customer' | 'admin' | 'owner';
22
+ permissions: PermissionSet;
23
+ isDefault?: boolean;
24
+ };
25
+ type TenantContext = {
26
+ id: string;
27
+ slug: string;
28
+ name: string;
29
+ primaryDomain: string;
30
+ locale: string;
31
+ currency: string;
32
+ themeKey: string;
33
+ status: 'draft' | 'active' | 'archived';
34
+ };
35
+ type TenantAccessContext = {
36
+ activeTenantId?: string;
37
+ memberships: TenantMembership[];
38
+ };
39
+ type AuthenticatedPrincipal = {
40
+ identity: AccountsIdentity;
41
+ user: LocalUser;
42
+ tenantAccess: TenantAccessContext;
43
+ };
44
+ type PlatformSession = {
45
+ principal: AuthenticatedPrincipal | null;
46
+ tenant: TenantContext | null;
47
+ accessToken?: string;
48
+ refreshToken?: string;
49
+ expiresAt?: string;
50
+ };
51
+ type AccountsClientConfig = {
52
+ baseUrl?: string;
53
+ clientId: string;
54
+ clientSecret?: string;
55
+ redirectUri: string;
56
+ logoutRedirectUri?: string;
57
+ useMock?: boolean;
58
+ };
59
+ type AuthorizationState = {
60
+ nonce: string;
61
+ nextPath: string;
62
+ tenantSlug?: string;
63
+ };
64
+ type AccountsTokenResponse = {
65
+ access_token: string;
66
+ refresh_token?: string;
67
+ token_type: 'Bearer';
68
+ expires_in: number;
69
+ user: {
70
+ id: string;
71
+ email?: string;
72
+ name?: string;
73
+ first_name?: string;
74
+ last_name?: string;
75
+ avatar_url?: string;
76
+ };
77
+ };
78
+ type SyncAccountsUserResult = {
79
+ user: LocalUser;
80
+ memberships: TenantMembership[];
81
+ activeTenantId?: string;
82
+ };
83
+ type SyncAccountsUser = (identity: AccountsIdentity) => SyncAccountsUserResult | Promise<SyncAccountsUserResult>;
84
+ declare function createAccountsClientConfig(input?: Partial<AccountsClientConfig>): AccountsClientConfig;
85
+ declare function createPlatformAuth(): {
86
+ readSession(cookieHeader: string | null | undefined): PlatformSession;
87
+ requirePrincipal(session: PlatformSession): AuthenticatedPrincipal;
88
+ };
89
+ declare function beginAccountsLoginRedirect(config: AccountsClientConfig, options: {
90
+ nextPath?: string;
91
+ tenantSlug?: string;
92
+ cookieOptions?: CookieOptions;
93
+ }): {
94
+ redirectUrl: string;
95
+ stateValue: string;
96
+ stateCookie: string;
97
+ };
98
+ declare function handleAccountsCallback(input: {
99
+ config: AccountsClientConfig;
100
+ code: string;
101
+ state: string;
102
+ storedState?: string | null;
103
+ syncAccountsUser: SyncAccountsUser;
104
+ fetchImpl?: typeof fetch;
105
+ cookieOptions?: CookieOptions;
106
+ /** When set, the session cookie is HMAC-signed so it cannot be forged/tampered. */
107
+ secret?: string;
108
+ }): Promise<{
109
+ session: PlatformSession;
110
+ nextPath: string;
111
+ tenantSlug: string | undefined;
112
+ sessionCookie: string;
113
+ clearStateCookie: string;
114
+ }>;
115
+ declare function exchangeAuthorizationCode(input: {
116
+ config: AccountsClientConfig;
117
+ code: string;
118
+ fetchImpl?: typeof fetch;
119
+ }): Promise<AccountsTokenResponse>;
120
+ declare function syncAccountsUser(identity: AccountsIdentity, syncer: SyncAccountsUser): SyncAccountsUserResult | Promise<SyncAccountsUserResult>;
121
+ /**
122
+ * Default identity → local-user mapping for apps that do NOT keep their own users table
123
+ * (e.g. a read-only companion app). Maps the Accounts identity straight through with no
124
+ * memberships. Added 0.0.2; non-breaking.
125
+ */
126
+ declare const identityPassthroughSync: SyncAccountsUser;
127
+ declare function resolveActiveTenant(memberships: TenantMembership[], preferredTenantId?: string): string;
128
+ declare function readPlatformSessionCookie(cookieHeader: string | null | undefined, opts?: {
129
+ secret?: string;
130
+ }): PlatformSession;
131
+ /**
132
+ * Cookie attribute options. Set `sameSite: 'none'` (which implies `secure: true`) to make
133
+ * the session usable on CROSS-SITE requests — required when an SDK on another origin calls
134
+ * an API that relies on this cookie. Added 0.0.3; defaults preserve the prior Lax behavior.
135
+ */
136
+ type CookieOptions = {
137
+ sameSite?: 'lax' | 'none' | 'strict';
138
+ secure?: boolean;
139
+ };
140
+ declare function clearPlatformSessionCookie(opts?: CookieOptions): string;
141
+
142
+ export { type AccountsClientConfig, type AccountsIdentity, type AccountsTokenResponse, type AuthenticatedPrincipal, type AuthorizationState, type CookieOptions, type LocalUser, type PermissionSet, type PlatformSession, type SyncAccountsUser, type SyncAccountsUserResult, type TenantAccessContext, type TenantContext, type TenantMembership, beginAccountsLoginRedirect, clearPlatformSessionCookie, createAccountsClientConfig, createPlatformAuth, exchangeAuthorizationCode, handleAccountsCallback, identityPassthroughSync, readPlatformSessionCookie, resolveActiveTenant, syncAccountsUser };
package/dist/index.js ADDED
@@ -0,0 +1,24 @@
1
+ import {
2
+ beginAccountsLoginRedirect,
3
+ clearPlatformSessionCookie,
4
+ createAccountsClientConfig,
5
+ createPlatformAuth,
6
+ exchangeAuthorizationCode,
7
+ handleAccountsCallback,
8
+ identityPassthroughSync,
9
+ readPlatformSessionCookie,
10
+ resolveActiveTenant,
11
+ syncAccountsUser
12
+ } from "./chunk-R3JOX2XR.js";
13
+ export {
14
+ beginAccountsLoginRedirect,
15
+ clearPlatformSessionCookie,
16
+ createAccountsClientConfig,
17
+ createPlatformAuth,
18
+ exchangeAuthorizationCode,
19
+ handleAccountsCallback,
20
+ identityPassthroughSync,
21
+ readPlatformSessionCookie,
22
+ resolveActiveTenant,
23
+ syncAccountsUser
24
+ };
@@ -0,0 +1,39 @@
1
+ import { RequestEvent, Handle } from '@sveltejs/kit';
2
+ import { PlatformSession, AccountsClientConfig, SyncAccountsUser, CookieOptions } from './index.js';
3
+ export { clearPlatformSessionCookie } from './index.js';
4
+
5
+ type SvelteKitAuthOptions = {
6
+ /** Accounts client config (use createAccountsClientConfig()). */
7
+ config: AccountsClientConfig;
8
+ /** Map an Accounts identity to a local user. Defaults to identity passthrough (no DB). */
9
+ syncAccountsUser?: SyncAccountsUser;
10
+ loginPath?: string;
11
+ callbackPath?: string;
12
+ logoutPath?: string;
13
+ /** Where to send the user after logout. Default '/'. */
14
+ postLogoutPath?: string;
15
+ /**
16
+ * Return true if THIS request must be authenticated. Unauthenticated page requests are
17
+ * redirected to the login flow; unauthenticated /api requests get a 401 JSON response.
18
+ * Omit to leave everything public (session is still read into locals).
19
+ */
20
+ protect?: (event: RequestEvent) => boolean;
21
+ /**
22
+ * Cookie attributes for the session + state cookies. Set `{ sameSite: 'none' }` to make
23
+ * the session usable cross-site (an SDK on another origin calling a protected API).
24
+ */
25
+ cookieOptions?: CookieOptions;
26
+ /**
27
+ * HMAC secret. When set, the session cookie is signed on write and verified on read —
28
+ * unsigned/forged/tampered cookies are rejected (treated as logged out). Strongly
29
+ * recommended in production, since the session payload includes tenant memberships.
30
+ */
31
+ sessionSecret?: string;
32
+ };
33
+ type PlatformLocals = {
34
+ session: PlatformSession;
35
+ principal: PlatformSession['principal'];
36
+ };
37
+ declare function createAuthHandle(opts: SvelteKitAuthOptions): Handle;
38
+
39
+ export { type PlatformLocals, type SvelteKitAuthOptions, createAuthHandle };
@@ -0,0 +1,76 @@
1
+ import {
2
+ beginAccountsLoginRedirect,
3
+ clearPlatformSessionCookie,
4
+ handleAccountsCallback,
5
+ identityPassthroughSync,
6
+ readPlatformSessionCookie
7
+ } from "./chunk-R3JOX2XR.js";
8
+
9
+ // src/sveltekit.ts
10
+ import { redirect } from "@sveltejs/kit";
11
+ var STATE_COOKIE = "accounts_auth_state";
12
+ function redirectWithCookies(location, cookies) {
13
+ const headers = new Headers({ location });
14
+ for (const c of cookies) if (c) headers.append("set-cookie", c);
15
+ return new Response(null, { status: 302, headers });
16
+ }
17
+ function createAuthHandle(opts) {
18
+ const sync = opts.syncAccountsUser ?? identityPassthroughSync;
19
+ const loginPath = opts.loginPath ?? "/auth/login";
20
+ const callbackPath = opts.callbackPath ?? "/auth/callback";
21
+ const logoutPath = opts.logoutPath ?? "/auth/logout";
22
+ const postLogoutPath = opts.postLogoutPath ?? "/";
23
+ const cookieOptions = opts.cookieOptions;
24
+ const sessionSecret = opts.sessionSecret;
25
+ return async ({ event, resolve }) => {
26
+ const session = readPlatformSessionCookie(event.request.headers.get("cookie"), {
27
+ secret: sessionSecret
28
+ });
29
+ event.locals.session = session;
30
+ event.locals.principal = session.principal;
31
+ const path = event.url.pathname;
32
+ if (path === loginPath) {
33
+ const next = event.url.searchParams.get("next") ?? "/";
34
+ const flow = beginAccountsLoginRedirect(opts.config, { nextPath: next, cookieOptions });
35
+ return redirectWithCookies(flow.redirectUrl, [flow.stateCookie]);
36
+ }
37
+ if (path === callbackPath) {
38
+ const code = event.url.searchParams.get("code") ?? "";
39
+ const state = event.url.searchParams.get("state") ?? "";
40
+ const storedState = event.cookies.get(STATE_COOKIE);
41
+ const result = await handleAccountsCallback({
42
+ config: opts.config,
43
+ code,
44
+ state,
45
+ storedState,
46
+ syncAccountsUser: sync,
47
+ cookieOptions,
48
+ secret: sessionSecret
49
+ });
50
+ return redirectWithCookies(result.nextPath || "/", [
51
+ result.sessionCookie,
52
+ result.clearStateCookie
53
+ ]);
54
+ }
55
+ if (path === logoutPath) {
56
+ return redirectWithCookies(postLogoutPath, [
57
+ clearPlatformSessionCookie(cookieOptions),
58
+ `${STATE_COOKIE}=; ${cookieOptions?.sameSite === "none" ? "Path=/; HttpOnly; SameSite=None; Secure" : "Path=/; HttpOnly; SameSite=Lax"}; Max-Age=0`
59
+ ]);
60
+ }
61
+ if (opts.protect && opts.protect(event) && !session.principal) {
62
+ if (path.startsWith("/api")) {
63
+ return new Response(JSON.stringify({ message: "Authentication required." }), {
64
+ status: 401,
65
+ headers: { "content-type": "application/json" }
66
+ });
67
+ }
68
+ throw redirect(302, `${loginPath}?next=${encodeURIComponent(path + event.url.search)}`);
69
+ }
70
+ return resolve(event);
71
+ };
72
+ }
73
+ export {
74
+ clearPlatformSessionCookie,
75
+ createAuthHandle
76
+ };
package/package.json ADDED
@@ -0,0 +1,64 @@
1
+ {
2
+ "name": "@~lyre/auth",
3
+ "version": "0.0.4",
4
+ "description": "Shared Axis Accounts auth SDK — framework-agnostic session/identity core (HMAC-signed cookies, accounts login/callback/logout) plus an optional turnkey SvelteKit adapter.",
5
+ "type": "module",
6
+ "sideEffects": false,
7
+ "license": "MIT",
8
+ "author": "Britam Trust Services / Lyre",
9
+ "repository": {
10
+ "type": "git",
11
+ "url": "git+https://github.com/kigathi-chege/lyre-auth-sdk.git"
12
+ },
13
+ "homepage": "https://github.com/kigathi-chege/lyre-auth-sdk#readme",
14
+ "bugs": {
15
+ "url": "https://github.com/kigathi-chege/lyre-auth-sdk/issues"
16
+ },
17
+ "keywords": [
18
+ "auth",
19
+ "sso",
20
+ "accounts",
21
+ "session",
22
+ "sveltekit",
23
+ "hmac",
24
+ "lyre"
25
+ ],
26
+ "main": "./dist/index.js",
27
+ "types": "./dist/index.d.ts",
28
+ "exports": {
29
+ ".": {
30
+ "types": "./dist/index.d.ts",
31
+ "import": "./dist/index.js"
32
+ },
33
+ "./sveltekit": {
34
+ "types": "./dist/sveltekit.d.ts",
35
+ "import": "./dist/sveltekit.js"
36
+ }
37
+ },
38
+ "files": [
39
+ "dist",
40
+ "README.md",
41
+ "LICENSE"
42
+ ],
43
+ "scripts": {
44
+ "build": "tsup src/index.ts src/sveltekit.ts --format esm --dts --clean",
45
+ "check": "tsc --noEmit"
46
+ },
47
+ "peerDependencies": {
48
+ "@sveltejs/kit": "^2.0.0"
49
+ },
50
+ "peerDependenciesMeta": {
51
+ "@sveltejs/kit": {
52
+ "optional": true
53
+ }
54
+ },
55
+ "devDependencies": {
56
+ "@sveltejs/kit": "^2.0.0",
57
+ "@types/node": "^22",
58
+ "tsup": "^8.3.5",
59
+ "typescript": "^6.0.2"
60
+ },
61
+ "publishConfig": {
62
+ "access": "public"
63
+ }
64
+ }