@fayz-ai/auth 0.9.0 → 0.10.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/README.md +2 -2
- package/dist/index.d.ts +2 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/lib/url-intent.d.ts.map +1 -0
- package/package.json +9 -11
- package/dist/url-intent.d.ts.map +0 -1
- package/dist/url-intent.test.d.ts +0 -2
- package/dist/url-intent.test.d.ts.map +0 -1
- package/src/adapters/mock.ts +0 -142
- package/src/adapters/supabase.ts +0 -219
- package/src/context.tsx +0 -205
- package/src/index.ts +0 -29
- package/src/store.ts +0 -46
- package/src/url-intent.test.ts +0 -91
- package/src/url-intent.ts +0 -151
- /package/dist/{url-intent.d.ts → lib/url-intent.d.ts} +0 -0
package/README.md
CHANGED
|
@@ -44,7 +44,7 @@ function Dashboard() {
|
|
|
44
44
|
```
|
|
45
45
|
|
|
46
46
|
## Part of the Fayz SDK
|
|
47
|
-
The auth seam between `@fayz-ai/core` and the multi-tenant `@fayz-ai/
|
|
47
|
+
The auth seam between `@fayz-ai/core` and the multi-tenant `@fayz-ai/admin` layer.
|
|
48
48
|
|
|
49
49
|
## Roadmap & contributing
|
|
50
|
-
Built and evolving in the open. See the [Fayz SDK roadmap](../../docs/ROADMAP.md#auth) for current gaps, missing features, and good first issues.
|
|
50
|
+
Built and evolving in the open. See the [Fayz SDK roadmap](../../docs/platform/ROADMAP.md#auth) for current gaps, missing features, and good first issues.
|
package/dist/index.d.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
export { createSupabaseAuthAdapter, MUST_SET_PASSWORD_FLAG } from './adapters/supabase';
|
|
2
2
|
export type { SupabaseAuthConfig } from './adapters/supabase';
|
|
3
|
-
export { readAuthUrlIntent, clearAuthUrlTokens, withAuthIntent, decidePasswordSetup, AUTH_INTENT_PARAM, } from './url-intent';
|
|
4
|
-
export type { AuthUrlIntent, PasswordSetupDecision, PasswordSetupInput, PasswordSetupReason, } from './url-intent';
|
|
3
|
+
export { readAuthUrlIntent, clearAuthUrlTokens, withAuthIntent, decidePasswordSetup, AUTH_INTENT_PARAM, } from './lib/url-intent';
|
|
4
|
+
export type { AuthUrlIntent, PasswordSetupDecision, PasswordSetupInput, PasswordSetupReason, } from './lib/url-intent';
|
|
5
5
|
export { createMockAuthAdapter } from './adapters/mock';
|
|
6
6
|
export type { MockUser } from './adapters/mock';
|
|
7
7
|
export { useAuthStore } from './store';
|
package/dist/index.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,yBAAyB,EAAE,sBAAsB,EAAE,MAAM,qBAAqB,CAAA;AACvF,YAAY,EAAE,kBAAkB,EAAE,MAAM,qBAAqB,CAAA;AAG7D,OAAO,EACL,iBAAiB,EACjB,kBAAkB,EAClB,cAAc,EACd,mBAAmB,EACnB,iBAAiB,GAClB,MAAM,
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,yBAAyB,EAAE,sBAAsB,EAAE,MAAM,qBAAqB,CAAA;AACvF,YAAY,EAAE,kBAAkB,EAAE,MAAM,qBAAqB,CAAA;AAG7D,OAAO,EACL,iBAAiB,EACjB,kBAAkB,EAClB,cAAc,EACd,mBAAmB,EACnB,iBAAiB,GAClB,MAAM,kBAAkB,CAAA;AACzB,YAAY,EACV,aAAa,EACb,qBAAqB,EACrB,kBAAkB,EAClB,mBAAmB,GACpB,MAAM,kBAAkB,CAAA;AAEzB,OAAO,EAAE,qBAAqB,EAAE,MAAM,iBAAiB,CAAA;AACvD,YAAY,EAAE,QAAQ,EAAE,MAAM,iBAAiB,CAAA;AAG/C,OAAO,EAAE,YAAY,EAAE,MAAM,SAAS,CAAA;AACtC,YAAY,EAAE,SAAS,EAAE,SAAS,EAAE,MAAM,SAAS,CAAA;AAGnD,OAAO,EAAE,YAAY,EAAE,OAAO,EAAE,MAAM,WAAW,CAAA;AACjD,YAAY,EAAE,iBAAiB,EAAE,MAAM,WAAW,CAAA"}
|
package/dist/index.js
CHANGED
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/url-intent.ts","../src/adapters/supabase.ts","../src/adapters/mock.ts","../src/store.ts","../src/context.tsx"],"names":[],"mappings":";;;;;;;;AA2BO,IAAM,iBAAA,GAAoB;AAIjC,IAAM,UAAA,GAAa,sBAAA;AAQnB,SAAS,QAAA,GAA+B;AACtC,EAAA,IAAI,OAAO,MAAA,KAAW,WAAA,EAAa,OAAO,IAAA;AAC1C,EAAA,OAAO;AAAA,IACL,QAAA,EAAU,OAAO,QAAA,CAAS,QAAA;AAAA,IAC1B,MAAA,EAAQ,OAAO,QAAA,CAAS,MAAA;AAAA,IACxB,IAAA,EAAM,OAAO,QAAA,CAAS;AAAA,GACxB;AACF;AAGA,IAAM,aAAiC,QAAA,EAAS;AAIhD,SAAS,WAAW,IAAA,EAA+B;AACjD,EAAA,MAAM,GAAA,GAAM,IAAA,CAAK,OAAA,CAAQ,IAAA,EAAM,EAAE,CAAA;AACjC,EAAA,IAAI,CAAC,OAAO,CAAC,GAAA,CAAI,SAAS,GAAG,CAAA,EAAG,OAAO,IAAI,eAAA,EAAgB;AAC3D,EAAA,OAAO,IAAI,gBAAgB,GAAG,CAAA;AAChC;AAEO,SAAS,kBAAkB,GAAA,EAAgD;AAChF,EAAA,MAAM,MAAM,GAAA,IAAO,UAAA;AACnB,EAAA,IAAI,CAAC,KAAK,OAAO,IAAA;AAEjB,EAAA,MAAM,KAAA,GAAQ,IAAI,eAAA,CAAgB,GAAA,CAAI,MAAM,CAAA;AAC5C,EAAA,MAAM,IAAA,GAAO,UAAA,CAAW,GAAA,CAAI,IAAI,CAAA;AAChC,EAAA,MAAM,KAAA,GA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A,SAAA;AAAA,IACA,eAAA;AAAA,IACA,KAAA;AAAA,IACA,QAAQ,GAAA,CAAI,MAAA;AAAA,IACZ,QAAQ,GAAA,CAAI,MAAA;AAAA,IACZ,SAAS,GAAA,CAAI,OAAA;AAAA,IACb,iBAAiB,GAAA,CAAI,eAAA;AAAA,IACrB,eAAe,GAAA,CAAI,aAAA;AAAA,IACnB,gBAAgB,GAAA,CAAI,cAAA;AAAA,IACpB,gBAAgB,GAAA,CAAI,cAAA;AAAA,IACpB,YAAY,GAAA,CAAI;AAAA,GAClB;AACF","file":"index.js","sourcesContent":["// ---------------------------------------------------------------------------\n// Auth link intent — what the URL the user just arrived on is asking for.\n//\n// A Supabase recovery / magic link lands on the app with the tokens in the URL\n// FRAGMENT (implicit flow is the supabase-js default), e.g.\n//\n// https://app.example.com/#access_token=…&refresh_token=…&type=recovery\n//\n// GoTrue then consumes that fragment and wipes it (`window.location.hash = ''`)\n// as soon as the client initialises — so by the time React renders, the reason\n// the user is here is gone. Hence the module-load snapshot: this file is\n// imported long before any createClient() call, so it always sees the original\n// URL.\n//\n// Errors arrive the same way, without a `type`:\n//\n// https://app.example.com/#error=access_denied&error_code=otp_expired&…\n// ---------------------------------------------------------------------------\n\nexport type AuthUrlIntent =\n /** A password-recovery link — the user must choose a new password now. */\n | { kind: 'recovery' }\n /** A one-time link that was already used or has expired. */\n | { kind: 'expired'; message?: string }\n\n/** Query param apps can put on their own redirect URLs to force the\n * set-password screen (e.g. when they override `resetPasswordUrl`). */\nexport const AUTH_INTENT_PARAM = 'fayz_auth'\n\n/** Path segment the SDK historically used as the reset-password redirect.\n * Still honoured so apps that configured it keep working. */\nconst RESET_PATH = '/auth/reset-password'\n\ninterface UrlSnapshot {\n pathname: string\n search: string\n hash: string\n}\n\nfunction snapshot(): UrlSnapshot | null {\n if (typeof window === 'undefined') return null\n return {\n pathname: window.location.pathname,\n search: window.location.search,\n hash: window.location.hash,\n }\n}\n\n/** Taken at import time — before any Supabase client can strip the fragment. */\nconst initialUrl: UrlSnapshot | null = snapshot()\n\n/** The fragment can be either auth params (`access_token=…&type=recovery`) or a\n * hash-router path (`#/dashboard`). Only the former parses into pairs. */\nfunction hashParams(hash: string): URLSearchParams {\n const raw = hash.replace(/^#/, '')\n if (!raw || !raw.includes('=')) return new URLSearchParams()\n return new URLSearchParams(raw)\n}\n\nexport function readAuthUrlIntent(url?: UrlSnapshot | null): AuthUrlIntent | null {\n const loc = url ?? initialUrl\n if (!loc) return null\n\n const query = new URLSearchParams(loc.search)\n const hash = hashParams(loc.hash)\n const param = (key: string) => hash.get(key) ?? query.get(key)\n\n const errorCode = param('error_code') ?? param('error')\n const errorDescription = param('error_description')?.replace(/\\+/g, ' ')\n // A dead one-time link (`error_code=otp_expired`). Deliberately narrow: an\n // OAuth `access_denied` is a different failure and must not land here. GoTrue\n // does not echo `type` on error redirects, so recovery and invite links are\n // indistinguishable at this point — the screen offers a fresh link either way.\n if (errorCode && /otp|expired|link/i.test(`${errorCode} ${errorDescription ?? ''}`)) {\n return { kind: 'expired', message: errorDescription ?? undefined }\n }\n\n const marker = query.get(AUTH_INTENT_PARAM)\n const type = param('type')\n if (type === 'recovery' || marker === 'recovery') return { kind: 'recovery' }\n\n // `/auth/reset-password` with no tokens at all: the user opened the reset URL\n // directly, or the tokens were already consumed by a previous page load.\n const path = loc.pathname.replace(/\\/+$/, '')\n if (path.endsWith(RESET_PATH)) return { kind: 'recovery' }\n\n return null\n}\n\n/** Strip auth leftovers from the address bar once the flow is finished, so a\n * reload does not put the user back on the set-password screen (and so the\n * hash router gets a clean slate). */\nexport function clearAuthUrlTokens(): void {\n if (typeof window === 'undefined') return\n const url = new URL(window.location.href)\n url.searchParams.delete(AUTH_INTENT_PARAM)\n if (url.hash.includes('=')) url.hash = ''\n window.history.replaceState(window.history.state, '', url.toString())\n}\n\n/** Add the intent marker to a redirect URL. Absolute or relative; existing\n * params are preserved. */\nexport function withAuthIntent(url: string, intent: 'recovery'): string {\n const base = typeof window === 'undefined' ? 'http://localhost' : window.location.origin\n const parsed = new URL(url, base)\n parsed.searchParams.set(AUTH_INTENT_PARAM, intent)\n return /^https?:\\/\\//i.test(url) ? parsed.toString() : `${parsed.pathname}${parsed.search}${parsed.hash}`\n}\n\n// ---------------------------------------------------------------------------\n// Whether the user owes us a password before they reach the app. Pure, so the\n// decision is testable without a browser; the React wrapper lives in\n// @fayz-ai/plugin-auth (usePasswordSetupGate).\n// ---------------------------------------------------------------------------\n\nexport type PasswordSetupReason = 'recovery' | 'invite'\n\nexport interface PasswordSetupInput {\n intent: AuthUrlIntent | null\n /** Session still resolving — the link's tokens are exchanged asynchronously. */\n isLoading: boolean\n isAuthenticated: boolean\n /** AuthUser.mustSetPassword — an invitee who never chose one. */\n mustSetPassword?: boolean\n}\n\nexport interface PasswordSetupDecision {\n reason: PasswordSetupReason | null\n expired: boolean\n checking: boolean\n}\n\nconst NOTHING: PasswordSetupDecision = { reason: null, expired: false, checking: false }\n\nexport function decidePasswordSetup(input: PasswordSetupInput): PasswordSetupDecision {\n const { intent, isLoading, isAuthenticated, mustSetPassword } = input\n\n if (intent?.kind === 'expired') return { reason: 'recovery', expired: true, checking: false }\n\n if (intent?.kind === 'recovery') {\n if (isLoading) return { reason: 'recovery', expired: false, checking: true }\n // A recovery link with no session behind it was already used or has expired.\n return { reason: 'recovery', expired: !isAuthenticated, checking: false }\n }\n\n if (!isLoading && isAuthenticated && mustSetPassword) {\n return { reason: 'invite', expired: false, checking: false }\n }\n\n return NOTHING\n}\n","import { createClient, type SupabaseClient } from '@supabase/supabase-js'\nimport type { AuthAdapter, AuthUser, AuthSession, AuthProvider } from '@fayz-ai/core'\nimport { withAuthIntent } from '../url-intent'\n\n/** Metadata flag stamped on invited users (created by a magic link, so they have\n * no password yet) and cleared the moment they choose one. Metadata, not a URL\n * param: it survives the link being opened later, in another browser, or twice —\n * and it needs no new entry in Supabase's redirect allow-list. */\nexport const MUST_SET_PASSWORD_FLAG = 'fayz_must_set_password'\n\nexport interface SupabaseAuthConfig {\n supabaseUrl: string\n supabaseAnonKey: string\n supabaseClient?: SupabaseClient\n callbackUrl?: string\n resetPasswordUrl?: string\n}\n\nfunction mapSupabaseUser(supabaseUser: {\n id: string\n email?: string | null\n created_at?: string\n updated_at?: string | null\n email_confirmed_at?: string | null\n user_metadata?: Record<string, unknown>\n app_metadata?: { providers?: string[]; provider?: string }\n}): AuthUser {\n return {\n id: supabaseUser.id,\n email: supabaseUser.email ?? '',\n fullName:\n (supabaseUser.user_metadata?.['full_name'] as string | undefined) ??\n (supabaseUser.user_metadata?.['name'] as string | undefined) ??\n '',\n avatarUrl: supabaseUser.user_metadata?.['avatar_url'] as string | undefined,\n mustSetPassword: supabaseUser.user_metadata?.[MUST_SET_PASSWORD_FLAG] === true,\n }\n}\n\nfunction mapSupabaseSession(session: {\n access_token: string\n refresh_token?: string\n expires_at?: number\n expires_in?: number\n user: Parameters<typeof mapSupabaseUser>[0]\n}): AuthSession {\n return {\n accessToken: session.access_token,\n refreshToken: session.refresh_token,\n expiresAt:\n session.expires_at ??\n Math.floor(Date.now() / 1000) + (session.expires_in ?? 3600),\n user: mapSupabaseUser(session.user),\n }\n}\n\nexport function createSupabaseAuthAdapter(config: SupabaseAuthConfig): AuthAdapter {\n const supabase = config.supabaseClient ?? createClient(config.supabaseUrl, config.supabaseAnonKey)\n\n return {\n async getSession() {\n const {\n data: { session },\n } = await supabase.auth.getSession()\n if (!session) return null\n const mapped = mapSupabaseSession(session)\n return { user: mapped.user, session: mapped }\n },\n\n onAuthStateChange(cb) {\n const {\n data: { subscription },\n } = supabase.auth.onAuthStateChange((_event, session) => {\n cb(session ? mapSupabaseUser(session.user) : null)\n })\n return () => subscription.unsubscribe()\n },\n\n async signIn(email, password) {\n const { data, error } = await supabase.auth.signInWithPassword({ email, password })\n if (error) throw error\n return mapSupabaseSession(data.session)\n },\n\n async signUp(email, password, fullName) {\n const { data, error } = await supabase.auth.signUp({\n email,\n password,\n options: { data: { full_name: fullName } },\n })\n if (error) throw error\n\n // When email confirmation is required, session is null\n if (!data.session) {\n if (!data.user) throw new Error('Signup failed: no user returned')\n return {\n accessToken: '',\n refreshToken: '',\n expiresAt: 0,\n user: mapSupabaseUser(data.user),\n }\n }\n\n return mapSupabaseSession(data.session)\n },\n\n async signOut() {\n const { error } = await supabase.auth.signOut()\n if (error) throw error\n },\n\n async signInWithOAuth(provider: AuthProvider) {\n const { error } = await supabase.auth.signInWithOAuth({\n provider: provider as 'google' | 'github' | 'apple',\n options: {\n redirectTo:\n config.callbackUrl ??\n (typeof window !== 'undefined' ? `${window.location.origin}/auth/callback` : undefined),\n },\n })\n if (error) throw error\n },\n\n async resetPassword(email, options) {\n // Root, not `/auth/reset-password`: the shell recognises a recovery link by\n // the link's own `type=recovery` param, so the flow needs no route of its\n // own — and the app root is the one URL every deployment already serves and\n // every Supabase project already allow-lists (a URL outside the allow-list\n // is silently swapped for the project's Site URL, i.e. another app).\n // A host that DOES point recovery somewhere else gets the explicit intent\n // marker, since we cannot assume its landing page carries the params.\n const explicit = options?.redirectTo ?? config.resetPasswordUrl\n const { error } = await supabase.auth.resetPasswordForEmail(email, {\n redirectTo: explicit\n ? withAuthIntent(explicit, 'recovery')\n : typeof window !== 'undefined'\n ? `${window.location.origin}/`\n : undefined,\n })\n if (error) throw error\n },\n\n async updatePassword(password) {\n // Clearing the flag in the same call as the password: one round-trip, and\n // no window where the password is set but the screen still demands one.\n const { data, error } = await supabase.auth.updateUser({\n password,\n data: { [MUST_SET_PASSWORD_FLAG]: false },\n })\n if (error) throw error\n const {\n data: { session },\n } = await supabase.auth.getSession()\n if (session) return mapSupabaseSession(session)\n if (!data.user) return undefined\n return {\n accessToken: '',\n refreshToken: '',\n expiresAt: 0,\n user: mapSupabaseUser(data.user),\n }\n },\n\n async handleCallback(url) {\n const target = url ?? (typeof window !== 'undefined' ? window.location.href : '')\n const parsed = new URL(target)\n // The fragment carries the params on the implicit flow; the query on PKCE\n // and on `{{ .TokenHash }}`-style e-mail templates.\n const fragment = new URLSearchParams(parsed.hash.replace(/^#/, ''))\n const param = (key: string) => parsed.searchParams.get(key) ?? fragment.get(key)\n\n const code = param('code')\n if (code) {\n const { data, error } = await supabase.auth.exchangeCodeForSession(code)\n if (error) throw error\n return data.session ? mapSupabaseSession(data.session) : null\n }\n\n // Templates that link straight at the app with a token instead of routing\n // through GoTrue's /verify never produce a session on their own.\n const tokenHash = param('token_hash') ?? param('token')\n const type = param('type')\n if (tokenHash && type) {\n const { data, error } = await supabase.auth.verifyOtp({\n token_hash: tokenHash,\n type: type as 'recovery' | 'invite' | 'magiclink' | 'signup' | 'email',\n })\n if (error) throw error\n return data.session ? mapSupabaseSession(data.session) : null\n }\n\n const {\n data: { session },\n } = await supabase.auth.getSession()\n return session ? mapSupabaseSession(session) : null\n },\n\n async inviteUser(email, options) {\n // Native, edge-function-free invite: a passwordless magic link. Sends the\n // e-mail + creates the auth user (anon-callable, no service-role/admin).\n // Membership is NOT granted from `data` (a client could forge it) — the\n // accept-time trigger trusts the RLS-protected public.invitations row.\n const { error } = await supabase.auth.signInWithOtp({\n email,\n options: {\n shouldCreateUser: true,\n emailRedirectTo:\n options?.redirectTo ??\n (typeof window !== 'undefined' ? `${window.location.origin}/` : undefined),\n // `data` only lands on users the OTP actually creates, which is exactly\n // who needs a password: the shell holds them on the set-password screen\n // until they choose one, so they can sign in normally from then on.\n data: { ...options?.data, [MUST_SET_PASSWORD_FLAG]: true },\n },\n })\n if (error) throw error\n },\n }\n}\n","import type { AuthAdapter, AuthUser, AuthSession } from '@fayz-ai/core'\n\nexport interface MockUser {\n id: string\n email: string\n fullName: string\n role?: string\n}\n\nconst DEFAULT_MOCK_USER: MockUser = {\n id: 'mock-user-id',\n email: 'demo@fayz.dev',\n fullName: 'Demo User',\n role: 'admin',\n}\n\nconst STORAGE_KEY = 'fayz:mock-auth'\n\nfunction toAuthUser(mockUser: MockUser): AuthUser {\n return {\n id: mockUser.id,\n email: mockUser.email,\n fullName: mockUser.fullName,\n }\n}\n\nfunction createMockSession(user: AuthUser): AuthSession {\n return {\n accessToken: `mock-token-${user.id}`,\n refreshToken: `mock-refresh-${user.id}`,\n expiresAt: Math.floor(Date.now() / 1000) + 3600,\n user,\n }\n}\n\nfunction getStored(): { user: AuthUser; session: AuthSession } | null {\n try {\n if (typeof localStorage === 'undefined') return null\n const raw = localStorage.getItem(STORAGE_KEY)\n if (!raw) return null\n return JSON.parse(raw) as { user: AuthUser; session: AuthSession }\n } catch {\n return null\n }\n}\n\nfunction setStored(data: { user: AuthUser; session: AuthSession } | null): void {\n try {\n if (typeof localStorage === 'undefined') return\n if (data) {\n localStorage.setItem(STORAGE_KEY, JSON.stringify(data))\n } else {\n localStorage.removeItem(STORAGE_KEY)\n }\n } catch {\n // SSR or storage unavailable — silently skip\n }\n}\n\nexport function createMockAuthAdapter(mockUser: MockUser = DEFAULT_MOCK_USER): AuthAdapter {\n const listeners = new Set<(user: AuthUser | null) => void>()\n\n function notifyListeners(user: AuthUser | null): void {\n for (const cb of listeners) cb(user)\n }\n\n return {\n async getSession() {\n return getStored()\n },\n\n onAuthStateChange(cb) {\n listeners.add(cb)\n return () => {\n listeners.delete(cb)\n }\n },\n\n async signIn(email, _password) {\n // Mock accepts any credentials, but the identity FOLLOWS the email —\n // storefront customers and saas users keep their own purchase/session\n // history instead of all becoming the configured demo user.\n const stored = getStored()\n const user: AuthUser =\n stored && stored.user.email === email\n ? stored.user\n : {\n id: email === mockUser.email ? mockUser.id : `mock-${email}`,\n email,\n fullName: email === mockUser.email ? mockUser.fullName : (email.split('@')[0] ?? 'Cliente'),\n }\n const session = createMockSession(user)\n setStored({ user, session })\n notifyListeners(user)\n return session\n },\n\n async signUp(email, _password, fullName) {\n // Mock signup creates a user from the provided details\n const user: AuthUser = {\n id: `mock-${email}`,\n email,\n fullName: fullName || (email.split('@')[0] ?? 'Cliente'),\n }\n const session = createMockSession(user)\n setStored({ user, session })\n notifyListeners(user)\n return session\n },\n\n async signOut() {\n setStored(null)\n notifyListeners(null)\n },\n\n async signInWithOAuth(_provider) {\n // Mock OAuth signs in as the configured user\n const user = toAuthUser(mockUser)\n const session = createMockSession(user)\n setStored({ user, session })\n notifyListeners(user)\n },\n\n async resetPassword(_email) {\n // No-op in mock\n },\n\n async updatePassword(_password) {\n const stored = getStored()\n return stored?.session\n },\n\n async handleCallback() {\n return getStored()?.session ?? null\n },\n\n async inviteUser(_email, _options) {\n // No admin path in mock — the org mock adapter still records the pending\n // invite so the Team UI shows it. Delivery is a no-op locally.\n },\n }\n}\n","import { create } from 'zustand'\nimport type { AuthUser, AuthSession } from '@fayz-ai/core'\n\nexport interface AuthState {\n user: AuthUser | null\n session: AuthSession | null\n isLoading: boolean\n isAuthenticated: boolean\n error: Error | null\n}\n\nexport interface AuthStore extends AuthState {\n setUser: (user: AuthUser | null) => void\n setSession: (session: AuthSession | null) => void\n setLoading: (isLoading: boolean) => void\n setError: (error: Error | null) => void\n reset: () => void\n}\n\nconst initialState: AuthState = {\n user: null,\n session: null,\n isLoading: true,\n isAuthenticated: false,\n error: null,\n}\n\nexport const useAuthStore = create<AuthStore>((set) => ({\n ...initialState,\n\n setUser: (user) =>\n set({ user, isAuthenticated: user !== null }),\n\n setSession: (session) =>\n set({\n session,\n user: session?.user ?? null,\n isAuthenticated: session !== null,\n }),\n\n setLoading: (isLoading) => set({ isLoading }),\n\n setError: (error) => set({ error }),\n\n reset: () => set(initialState),\n}))\n","import React, { createContext, useContext, useEffect, useRef } from 'react'\nimport type { AuthAdapter, AuthProvider as OAuthProvider, AuthSession } from '@fayz-ai/core'\nimport { useAuthStore } from './store'\n\n// ---------------------------------------------------------------------------\n// Context\n// ---------------------------------------------------------------------------\n\ninterface AuthContextValue {\n signIn: (email: string, password: string) => Promise<AuthSession>\n signUp: (email: string, password: string, fullName: string) => Promise<AuthSession>\n signOut: () => Promise<void>\n signInWithOAuth: (provider: OAuthProvider) => Promise<void>\n resetPassword: (email: string, options?: { redirectTo?: string }) => Promise<void>\n updatePassword: (password: string) => Promise<AuthSession | void>\n handleCallback: (url?: string) => Promise<AuthSession | null>\n inviteUser: (email: string, options?: { redirectTo?: string; data?: Record<string, unknown> }) => Promise<void>\n}\n\nconst AuthContext = createContext<AuthContextValue | null>(null)\n\n// ---------------------------------------------------------------------------\n// Provider\n// ---------------------------------------------------------------------------\n\nexport interface AuthProviderProps {\n adapter: AuthAdapter\n children: React.ReactNode\n}\n\nexport function AuthProvider({ adapter, children }: AuthProviderProps) {\n const { setSession, setLoading, setError, reset } = useAuthStore()\n\n // Keep a stable ref to the adapter so the effect only runs once on mount\n const adapterRef = useRef(adapter)\n adapterRef.current = adapter\n\n useEffect(() => {\n let unsubscribe: (() => void) | undefined\n\n async function init() {\n try {\n setLoading(true)\n const result = await adapterRef.current.getSession()\n setSession(result?.session ?? null)\n } catch (err) {\n setError(err instanceof Error ? err : new Error(String(err)))\n } finally {\n setLoading(false)\n }\n\n // Subscribe to future auth state changes\n unsubscribe = adapterRef.current.onAuthStateChange((user) => {\n if (!user) {\n reset()\n // Keep isLoading false after an explicit sign-out\n setLoading(false)\n return\n }\n // Positive change (adapter-driven sign-in — e.g. an external callback,\n // another tab, or a direct adapter.signUp bridge) — sync the session so\n // consumers reflect it even when the call didn't go through ctx.signIn.\n void adapterRef.current.getSession().then((result) => setSession(result?.session ?? null)).catch(() => {})\n })\n }\n\n void init()\n\n return () => {\n unsubscribe?.()\n }\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [])\n\n const value: AuthContextValue = {\n async signIn(email, password) {\n setError(null)\n try {\n const session = await adapterRef.current.signIn(email, password)\n setSession(session)\n return session\n } catch (err) {\n const error = err instanceof Error ? err : new Error(String(err))\n setError(error)\n throw error\n }\n },\n\n async signUp(email, password, fullName) {\n setError(null)\n try {\n const session = await adapterRef.current.signUp(email, password, fullName)\n setSession(session)\n return session\n } catch (err) {\n const error = err instanceof Error ? err : new Error(String(err))\n setError(error)\n throw error\n }\n },\n\n async signOut() {\n setError(null)\n try {\n await adapterRef.current.signOut()\n reset()\n setLoading(false)\n } catch (err) {\n const error = err instanceof Error ? err : new Error(String(err))\n setError(error)\n throw error\n }\n },\n\n async signInWithOAuth(provider) {\n setError(null)\n try {\n await adapterRef.current.signInWithOAuth(provider)\n } catch (err) {\n const error = err instanceof Error ? err : new Error(String(err))\n setError(error)\n throw error\n }\n },\n\n async resetPassword(email, options) {\n setError(null)\n try {\n await adapterRef.current.resetPassword(email, options)\n } catch (err) {\n const error = err instanceof Error ? err : new Error(String(err))\n setError(error)\n throw error\n }\n },\n\n async updatePassword(password) {\n setError(null)\n try {\n const session = await adapterRef.current.updatePassword?.(password)\n if (session) setSession(session)\n return session\n } catch (err) {\n const error = err instanceof Error ? err : new Error(String(err))\n setError(error)\n throw error\n }\n },\n\n async handleCallback(url) {\n setError(null)\n try {\n const session = await adapterRef.current.handleCallback?.(url) ?? null\n if (session) setSession(session)\n return session\n } catch (err) {\n const error = err instanceof Error ? err : new Error(String(err))\n setError(error)\n throw error\n }\n },\n\n async inviteUser(email, options) {\n setError(null)\n try {\n await adapterRef.current.inviteUser?.(email, options)\n } catch (err) {\n const error = err instanceof Error ? err : new Error(String(err))\n setError(error)\n throw error\n }\n },\n }\n\n return <AuthContext.Provider value={value}>{children}</AuthContext.Provider>\n}\n\n// ---------------------------------------------------------------------------\n// Hook\n// ---------------------------------------------------------------------------\n\nexport function useAuth() {\n const ctx = useContext(AuthContext)\n if (!ctx) {\n throw new Error('useAuth must be used inside <AuthProvider>')\n }\n\n const { user, session, isLoading, isAuthenticated, error } = useAuthStore()\n\n return {\n user,\n session,\n isLoading,\n isAuthenticated,\n error,\n signIn: ctx.signIn,\n signUp: ctx.signUp,\n signOut: ctx.signOut,\n signInWithOAuth: ctx.signInWithOAuth,\n resetPassword: ctx.resetPassword,\n updatePassword: ctx.updatePassword,\n handleCallback: ctx.handleCallback,\n inviteUser: ctx.inviteUser,\n }\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/lib/url-intent.ts","../src/adapters/supabase.ts","../src/adapters/m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gB,GAAA,CAAI,cAAA;AAAA,IACpB,YAAY,GAAA,CAAI;AAAA,GAClB;AACF","file":"index.js","sourcesContent":["// ---------------------------------------------------------------------------\n// Auth link intent — what the URL the user just arrived on is asking for.\n//\n// A Supabase recovery / magic link lands on the app with the tokens in the URL\n// FRAGMENT (implicit flow is the supabase-js default), e.g.\n//\n// https://app.example.com/#access_token=…&refresh_token=…&type=recovery\n//\n// GoTrue then consumes that fragment and wipes it (`window.location.hash = ''`)\n// as soon as the client initialises — so by the time React renders, the reason\n// the user is here is gone. Hence the module-load snapshot: this file is\n// imported long before any createClient() call, so it always sees the original\n// URL.\n//\n// Errors arrive the same way, without a `type`:\n//\n// https://app.example.com/#error=access_denied&error_code=otp_expired&…\n// ---------------------------------------------------------------------------\n\nexport type AuthUrlIntent =\n /** A password-recovery link — the user must choose a new password now. */\n | { kind: 'recovery' }\n /** A one-time link that was already used or has expired. */\n | { kind: 'expired'; message?: string }\n\n/** Query param apps can put on their own redirect URLs to force the\n * set-password screen (e.g. when they override `resetPasswordUrl`). */\nexport const AUTH_INTENT_PARAM = 'fayz_auth'\n\n/** Path segment the SDK historically used as the reset-password redirect.\n * Still honoured so apps that configured it keep working. */\nconst RESET_PATH = '/auth/reset-password'\n\ninterface UrlSnapshot {\n pathname: string\n search: string\n hash: string\n}\n\nfunction snapshot(): UrlSnapshot | null {\n if (typeof window === 'undefined') return null\n return {\n pathname: window.location.pathname,\n search: window.location.search,\n hash: window.location.hash,\n }\n}\n\n/** Taken at import time — before any Supabase client can strip the fragment. */\nconst initialUrl: UrlSnapshot | null = snapshot()\n\n/** The fragment can be either auth params (`access_token=…&type=recovery`) or a\n * hash-router path (`#/dashboard`). Only the former parses into pairs. */\nfunction hashParams(hash: string): URLSearchParams {\n const raw = hash.replace(/^#/, '')\n if (!raw || !raw.includes('=')) return new URLSearchParams()\n return new URLSearchParams(raw)\n}\n\nexport function readAuthUrlIntent(url?: UrlSnapshot | null): AuthUrlIntent | null {\n const loc = url ?? initialUrl\n if (!loc) return null\n\n const query = new URLSearchParams(loc.search)\n const hash = hashParams(loc.hash)\n const param = (key: string) => hash.get(key) ?? query.get(key)\n\n const errorCode = param('error_code') ?? param('error')\n const errorDescription = param('error_description')?.replace(/\\+/g, ' ')\n // A dead one-time link (`error_code=otp_expired`). Deliberately narrow: an\n // OAuth `access_denied` is a different failure and must not land here. GoTrue\n // does not echo `type` on error redirects, so recovery and invite links are\n // indistinguishable at this point — the screen offers a fresh link either way.\n if (errorCode && /otp|expired|link/i.test(`${errorCode} ${errorDescription ?? ''}`)) {\n return { kind: 'expired', message: errorDescription ?? undefined }\n }\n\n const marker = query.get(AUTH_INTENT_PARAM)\n const type = param('type')\n if (type === 'recovery' || marker === 'recovery') return { kind: 'recovery' }\n\n // `/auth/reset-password` with no tokens at all: the user opened the reset URL\n // directly, or the tokens were already consumed by a previous page load.\n const path = loc.pathname.replace(/\\/+$/, '')\n if (path.endsWith(RESET_PATH)) return { kind: 'recovery' }\n\n return null\n}\n\n/** Strip auth leftovers from the address bar once the flow is finished, so a\n * reload does not put the user back on the set-password screen (and so the\n * hash router gets a clean slate). */\nexport function clearAuthUrlTokens(): void {\n if (typeof window === 'undefined') return\n const url = new URL(window.location.href)\n url.searchParams.delete(AUTH_INTENT_PARAM)\n if (url.hash.includes('=')) url.hash = ''\n window.history.replaceState(window.history.state, '', url.toString())\n}\n\n/** Add the intent marker to a redirect URL. Absolute or relative; existing\n * params are preserved. */\nexport function withAuthIntent(url: string, intent: 'recovery'): string {\n const base = typeof window === 'undefined' ? 'http://localhost' : window.location.origin\n const parsed = new URL(url, base)\n parsed.searchParams.set(AUTH_INTENT_PARAM, intent)\n return /^https?:\\/\\//i.test(url) ? parsed.toString() : `${parsed.pathname}${parsed.search}${parsed.hash}`\n}\n\n// ---------------------------------------------------------------------------\n// Whether the user owes us a password before they reach the app. Pure, so the\n// decision is testable without a browser; the React wrapper lives in\n// @fayz-ai/plugin-auth (usePasswordSetupGate).\n// ---------------------------------------------------------------------------\n\nexport type PasswordSetupReason = 'recovery' | 'invite'\n\nexport interface PasswordSetupInput {\n intent: AuthUrlIntent | null\n /** Session still resolving — the link's tokens are exchanged asynchronously. */\n isLoading: boolean\n isAuthenticated: boolean\n /** AuthUser.mustSetPassword — an invitee who never chose one. */\n mustSetPassword?: boolean\n}\n\nexport interface PasswordSetupDecision {\n reason: PasswordSetupReason | null\n expired: boolean\n checking: boolean\n}\n\nconst NOTHING: PasswordSetupDecision = { reason: null, expired: false, checking: false }\n\nexport function decidePasswordSetup(input: PasswordSetupInput): PasswordSetupDecision {\n const { intent, isLoading, isAuthenticated, mustSetPassword } = input\n\n if (intent?.kind === 'expired') return { reason: 'recovery', expired: true, checking: false }\n\n if (intent?.kind === 'recovery') {\n if (isLoading) return { reason: 'recovery', expired: false, checking: true }\n // A recovery link with no session behind it was already used or has expired.\n return { reason: 'recovery', expired: !isAuthenticated, checking: false }\n }\n\n if (!isLoading && isAuthenticated && mustSetPassword) {\n return { reason: 'invite', expired: false, checking: false }\n }\n\n return NOTHING\n}\n","import { createClient, type SupabaseClient } from '@supabase/supabase-js'\nimport type { AuthAdapter, AuthUser, AuthSession, AuthProvider } from '@fayz-ai/core'\nimport { withAuthIntent } from '../lib/url-intent'\n\n/** Metadata flag stamped on invited users (created by a magic link, so they have\n * no password yet) and cleared the moment they choose one. Metadata, not a URL\n * param: it survives the link being opened later, in another browser, or twice —\n * and it needs no new entry in Supabase's redirect allow-list. */\nexport const MUST_SET_PASSWORD_FLAG = 'fayz_must_set_password'\n\nexport interface SupabaseAuthConfig {\n supabaseUrl: string\n supabaseAnonKey: string\n supabaseClient?: SupabaseClient\n callbackUrl?: string\n resetPasswordUrl?: string\n}\n\nfunction mapSupabaseUser(supabaseUser: {\n id: string\n email?: string | null\n created_at?: string\n updated_at?: string | null\n email_confirmed_at?: string | null\n user_metadata?: Record<string, unknown>\n app_metadata?: { providers?: string[]; provider?: string }\n}): AuthUser {\n return {\n id: supabaseUser.id,\n email: supabaseUser.email ?? '',\n fullName:\n (supabaseUser.user_metadata?.['full_name'] as string | undefined) ??\n (supabaseUser.user_metadata?.['name'] as string | undefined) ??\n '',\n avatarUrl: supabaseUser.user_metadata?.['avatar_url'] as string | undefined,\n mustSetPassword: supabaseUser.user_metadata?.[MUST_SET_PASSWORD_FLAG] === true,\n }\n}\n\nfunction mapSupabaseSession(session: {\n access_token: string\n refresh_token?: string\n expires_at?: number\n expires_in?: number\n user: Parameters<typeof mapSupabaseUser>[0]\n}): AuthSession {\n return {\n accessToken: session.access_token,\n refreshToken: session.refresh_token,\n expiresAt:\n session.expires_at ??\n Math.floor(Date.now() / 1000) + (session.expires_in ?? 3600),\n user: mapSupabaseUser(session.user),\n }\n}\n\nexport function createSupabaseAuthAdapter(config: SupabaseAuthConfig): AuthAdapter {\n const supabase = config.supabaseClient ?? createClient(config.supabaseUrl, config.supabaseAnonKey)\n\n return {\n async getSession() {\n const {\n data: { session },\n } = await supabase.auth.getSession()\n if (!session) return null\n const mapped = mapSupabaseSession(session)\n return { user: mapped.user, session: mapped }\n },\n\n onAuthStateChange(cb) {\n const {\n data: { subscription },\n } = supabase.auth.onAuthStateChange((_event, session) => {\n cb(session ? mapSupabaseUser(session.user) : null)\n })\n return () => subscription.unsubscribe()\n },\n\n async signIn(email, password) {\n const { data, error } = await supabase.auth.signInWithPassword({ email, password })\n if (error) throw error\n return mapSupabaseSession(data.session)\n },\n\n async signUp(email, password, fullName) {\n const { data, error } = await supabase.auth.signUp({\n email,\n password,\n options: { data: { full_name: fullName } },\n })\n if (error) throw error\n\n // When email confirmation is required, session is null\n if (!data.session) {\n if (!data.user) throw new Error('Signup failed: no user returned')\n return {\n accessToken: '',\n refreshToken: '',\n expiresAt: 0,\n user: mapSupabaseUser(data.user),\n }\n }\n\n return mapSupabaseSession(data.session)\n },\n\n async signOut() {\n const { error } = await supabase.auth.signOut()\n if (error) throw error\n },\n\n async signInWithOAuth(provider: AuthProvider) {\n const { error } = await supabase.auth.signInWithOAuth({\n provider: provider as 'google' | 'github' | 'apple',\n options: {\n redirectTo:\n config.callbackUrl ??\n (typeof window !== 'undefined' ? `${window.location.origin}/auth/callback` : undefined),\n },\n })\n if (error) throw error\n },\n\n async resetPassword(email, options) {\n // Root, not `/auth/reset-password`: the shell recognises a recovery link by\n // the link's own `type=recovery` param, so the flow needs no route of its\n // own — and the app root is the one URL every deployment already serves and\n // every Supabase project already allow-lists (a URL outside the allow-list\n // is silently swapped for the project's Site URL, i.e. another app).\n // A host that DOES point recovery somewhere else gets the explicit intent\n // marker, since we cannot assume its landing page carries the params.\n const explicit = options?.redirectTo ?? config.resetPasswordUrl\n const { error } = await supabase.auth.resetPasswordForEmail(email, {\n redirectTo: explicit\n ? withAuthIntent(explicit, 'recovery')\n : typeof window !== 'undefined'\n ? `${window.location.origin}/`\n : undefined,\n })\n if (error) throw error\n },\n\n async updatePassword(password) {\n // Clearing the flag in the same call as the password: one round-trip, and\n // no window where the password is set but the screen still demands one.\n const { data, error } = await supabase.auth.updateUser({\n password,\n data: { [MUST_SET_PASSWORD_FLAG]: false },\n })\n if (error) throw error\n const {\n data: { session },\n } = await supabase.auth.getSession()\n if (session) return mapSupabaseSession(session)\n if (!data.user) return undefined\n return {\n accessToken: '',\n refreshToken: '',\n expiresAt: 0,\n user: mapSupabaseUser(data.user),\n }\n },\n\n async handleCallback(url) {\n const target = url ?? (typeof window !== 'undefined' ? window.location.href : '')\n const parsed = new URL(target)\n // The fragment carries the params on the implicit flow; the query on PKCE\n // and on `{{ .TokenHash }}`-style e-mail templates.\n const fragment = new URLSearchParams(parsed.hash.replace(/^#/, ''))\n const param = (key: string) => parsed.searchParams.get(key) ?? fragment.get(key)\n\n const code = param('code')\n if (code) {\n const { data, error } = await supabase.auth.exchangeCodeForSession(code)\n if (error) throw error\n return data.session ? mapSupabaseSession(data.session) : null\n }\n\n // Templates that link straight at the app with a token instead of routing\n // through GoTrue's /verify never produce a session on their own.\n const tokenHash = param('token_hash') ?? param('token')\n const type = param('type')\n if (tokenHash && type) {\n const { data, error } = await supabase.auth.verifyOtp({\n token_hash: tokenHash,\n type: type as 'recovery' | 'invite' | 'magiclink' | 'signup' | 'email',\n })\n if (error) throw error\n return data.session ? mapSupabaseSession(data.session) : null\n }\n\n const {\n data: { session },\n } = await supabase.auth.getSession()\n return session ? mapSupabaseSession(session) : null\n },\n\n async inviteUser(email, options) {\n // Native, edge-function-free invite: a passwordless magic link. Sends the\n // e-mail + creates the auth user (anon-callable, no service-role/admin).\n // Membership is NOT granted from `data` (a client could forge it) — the\n // accept-time trigger trusts the RLS-protected public.invitations row.\n const { error } = await supabase.auth.signInWithOtp({\n email,\n options: {\n shouldCreateUser: true,\n emailRedirectTo:\n options?.redirectTo ??\n (typeof window !== 'undefined' ? `${window.location.origin}/` : undefined),\n // `data` only lands on users the OTP actually creates, which is exactly\n // who needs a password: the shell holds them on the set-password screen\n // until they choose one, so they can sign in normally from then on.\n data: { ...options?.data, [MUST_SET_PASSWORD_FLAG]: true },\n },\n })\n if (error) throw error\n },\n }\n}\n","import type { AuthAdapter, AuthUser, AuthSession } from '@fayz-ai/core'\n\nexport interface MockUser {\n id: string\n email: string\n fullName: string\n role?: string\n}\n\nconst DEFAULT_MOCK_USER: MockUser = {\n id: 'mock-user-id',\n email: 'demo@fayz.dev',\n fullName: 'Demo User',\n role: 'admin',\n}\n\nconst STORAGE_KEY = 'fayz:mock-auth'\n\nfunction toAuthUser(mockUser: MockUser): AuthUser {\n return {\n id: mockUser.id,\n email: mockUser.email,\n fullName: mockUser.fullName,\n }\n}\n\nfunction createMockSession(user: AuthUser): AuthSession {\n return {\n accessToken: `mock-token-${user.id}`,\n refreshToken: `mock-refresh-${user.id}`,\n expiresAt: Math.floor(Date.now() / 1000) + 3600,\n user,\n }\n}\n\nfunction getStored(): { user: AuthUser; session: AuthSession } | null {\n try {\n if (typeof localStorage === 'undefined') return null\n const raw = localStorage.getItem(STORAGE_KEY)\n if (!raw) return null\n return JSON.parse(raw) as { user: AuthUser; session: AuthSession }\n } catch {\n return null\n }\n}\n\nfunction setStored(data: { user: AuthUser; session: AuthSession } | null): void {\n try {\n if (typeof localStorage === 'undefined') return\n if (data) {\n localStorage.setItem(STORAGE_KEY, JSON.stringify(data))\n } else {\n localStorage.removeItem(STORAGE_KEY)\n }\n } catch {\n // SSR or storage unavailable — silently skip\n }\n}\n\nexport function createMockAuthAdapter(mockUser: MockUser = DEFAULT_MOCK_USER): AuthAdapter {\n const listeners = new Set<(user: AuthUser | null) => void>()\n\n function notifyListeners(user: AuthUser | null): void {\n for (const cb of listeners) cb(user)\n }\n\n return {\n async getSession() {\n return getStored()\n },\n\n onAuthStateChange(cb) {\n listeners.add(cb)\n return () => {\n listeners.delete(cb)\n }\n },\n\n async signIn(email, _password) {\n // Mock accepts any credentials, but the identity FOLLOWS the email —\n // storefront customers and saas users keep their own purchase/session\n // history instead of all becoming the configured demo user.\n const stored = getStored()\n const user: AuthUser =\n stored && stored.user.email === email\n ? stored.user\n : {\n id: email === mockUser.email ? mockUser.id : `mock-${email}`,\n email,\n fullName: email === mockUser.email ? mockUser.fullName : (email.split('@')[0] ?? 'Cliente'),\n }\n const session = createMockSession(user)\n setStored({ user, session })\n notifyListeners(user)\n return session\n },\n\n async signUp(email, _password, fullName) {\n // Mock signup creates a user from the provided details\n const user: AuthUser = {\n id: `mock-${email}`,\n email,\n fullName: fullName || (email.split('@')[0] ?? 'Cliente'),\n }\n const session = createMockSession(user)\n setStored({ user, session })\n notifyListeners(user)\n return session\n },\n\n async signOut() {\n setStored(null)\n notifyListeners(null)\n },\n\n async signInWithOAuth(_provider) {\n // Mock OAuth signs in as the configured user\n const user = toAuthUser(mockUser)\n const session = createMockSession(user)\n setStored({ user, session })\n notifyListeners(user)\n },\n\n async resetPassword(_email) {\n // No-op in mock\n },\n\n async updatePassword(_password) {\n const stored = getStored()\n return stored?.session\n },\n\n async handleCallback() {\n return getStored()?.session ?? null\n },\n\n async inviteUser(_email, _options) {\n // No admin path in mock — the org mock adapter still records the pending\n // invite so the Team UI shows it. Delivery is a no-op locally.\n },\n }\n}\n","import { create } from 'zustand'\nimport type { AuthUser, AuthSession } from '@fayz-ai/core'\n\nexport interface AuthState {\n user: AuthUser | null\n session: AuthSession | null\n isLoading: boolean\n isAuthenticated: boolean\n error: Error | null\n}\n\nexport interface AuthStore extends AuthState {\n setUser: (user: AuthUser | null) => void\n setSession: (session: AuthSession | null) => void\n setLoading: (isLoading: boolean) => void\n setError: (error: Error | null) => void\n reset: () => void\n}\n\nconst initialState: AuthState = {\n user: null,\n session: null,\n isLoading: true,\n isAuthenticated: false,\n error: null,\n}\n\nexport const useAuthStore = create<AuthStore>((set) => ({\n ...initialState,\n\n setUser: (user) =>\n set({ user, isAuthenticated: user !== null }),\n\n setSession: (session) =>\n set({\n session,\n user: session?.user ?? null,\n isAuthenticated: session !== null,\n }),\n\n setLoading: (isLoading) => set({ isLoading }),\n\n setError: (error) => set({ error }),\n\n reset: () => set(initialState),\n}))\n","import React, { createContext, useContext, useEffect, useRef } from 'react'\nimport type { AuthAdapter, AuthProvider as OAuthProvider, AuthSession } from '@fayz-ai/core'\nimport { useAuthStore } from './store'\n\n// ---------------------------------------------------------------------------\n// Context\n// ---------------------------------------------------------------------------\n\ninterface AuthContextValue {\n signIn: (email: string, password: string) => Promise<AuthSession>\n signUp: (email: string, password: string, fullName: string) => Promise<AuthSession>\n signOut: () => Promise<void>\n signInWithOAuth: (provider: OAuthProvider) => Promise<void>\n resetPassword: (email: string, options?: { redirectTo?: string }) => Promise<void>\n updatePassword: (password: string) => Promise<AuthSession | void>\n handleCallback: (url?: string) => Promise<AuthSession | null>\n inviteUser: (email: string, options?: { redirectTo?: string; data?: Record<string, unknown> }) => Promise<void>\n}\n\nconst AuthContext = createContext<AuthContextValue | null>(null)\n\n// ---------------------------------------------------------------------------\n// Provider\n// ---------------------------------------------------------------------------\n\nexport interface AuthProviderProps {\n adapter: AuthAdapter\n children: React.ReactNode\n}\n\nexport function AuthProvider({ adapter, children }: AuthProviderProps) {\n const { setSession, setLoading, setError, reset } = useAuthStore()\n\n // Keep a stable ref to the adapter so the effect only runs once on mount\n const adapterRef = useRef(adapter)\n adapterRef.current = adapter\n\n useEffect(() => {\n let unsubscribe: (() => void) | undefined\n\n async function init() {\n try {\n setLoading(true)\n const result = await adapterRef.current.getSession()\n setSession(result?.session ?? null)\n } catch (err) {\n setError(err instanceof Error ? err : new Error(String(err)))\n } finally {\n setLoading(false)\n }\n\n // Subscribe to future auth state changes\n unsubscribe = adapterRef.current.onAuthStateChange((user) => {\n if (!user) {\n reset()\n // Keep isLoading false after an explicit sign-out\n setLoading(false)\n return\n }\n // Positive change (adapter-driven sign-in — e.g. an external callback,\n // another tab, or a direct adapter.signUp bridge) — sync the session so\n // consumers reflect it even when the call didn't go through ctx.signIn.\n void adapterRef.current.getSession().then((result) => setSession(result?.session ?? null)).catch(() => {})\n })\n }\n\n void init()\n\n return () => {\n unsubscribe?.()\n }\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [])\n\n const value: AuthContextValue = {\n async signIn(email, password) {\n setError(null)\n try {\n const session = await adapterRef.current.signIn(email, password)\n setSession(session)\n return session\n } catch (err) {\n const error = err instanceof Error ? err : new Error(String(err))\n setError(error)\n throw error\n }\n },\n\n async signUp(email, password, fullName) {\n setError(null)\n try {\n const session = await adapterRef.current.signUp(email, password, fullName)\n setSession(session)\n return session\n } catch (err) {\n const error = err instanceof Error ? err : new Error(String(err))\n setError(error)\n throw error\n }\n },\n\n async signOut() {\n setError(null)\n try {\n await adapterRef.current.signOut()\n reset()\n setLoading(false)\n } catch (err) {\n const error = err instanceof Error ? err : new Error(String(err))\n setError(error)\n throw error\n }\n },\n\n async signInWithOAuth(provider) {\n setError(null)\n try {\n await adapterRef.current.signInWithOAuth(provider)\n } catch (err) {\n const error = err instanceof Error ? err : new Error(String(err))\n setError(error)\n throw error\n }\n },\n\n async resetPassword(email, options) {\n setError(null)\n try {\n await adapterRef.current.resetPassword(email, options)\n } catch (err) {\n const error = err instanceof Error ? err : new Error(String(err))\n setError(error)\n throw error\n }\n },\n\n async updatePassword(password) {\n setError(null)\n try {\n const session = await adapterRef.current.updatePassword?.(password)\n if (session) setSession(session)\n return session\n } catch (err) {\n const error = err instanceof Error ? err : new Error(String(err))\n setError(error)\n throw error\n }\n },\n\n async handleCallback(url) {\n setError(null)\n try {\n const session = await adapterRef.current.handleCallback?.(url) ?? null\n if (session) setSession(session)\n return session\n } catch (err) {\n const error = err instanceof Error ? err : new Error(String(err))\n setError(error)\n throw error\n }\n },\n\n async inviteUser(email, options) {\n setError(null)\n try {\n await adapterRef.current.inviteUser?.(email, options)\n } catch (err) {\n const error = err instanceof Error ? err : new Error(String(err))\n setError(error)\n throw error\n }\n },\n }\n\n return <AuthContext.Provider value={value}>{children}</AuthContext.Provider>\n}\n\n// ---------------------------------------------------------------------------\n// Hook\n// ---------------------------------------------------------------------------\n\nexport function useAuth() {\n const ctx = useContext(AuthContext)\n if (!ctx) {\n throw new Error('useAuth must be used inside <AuthProvider>')\n }\n\n const { user, session, isLoading, isAuthenticated, error } = useAuthStore()\n\n return {\n user,\n session,\n isLoading,\n isAuthenticated,\n error,\n signIn: ctx.signIn,\n signUp: ctx.signUp,\n signOut: ctx.signOut,\n signInWithOAuth: ctx.signInWithOAuth,\n resetPassword: ctx.resetPassword,\n updatePassword: ctx.updatePassword,\n handleCallback: ctx.handleCallback,\n inviteUser: ctx.inviteUser,\n }\n}\n"]}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"url-intent.d.ts","sourceRoot":"","sources":["../../src/lib/url-intent.ts"],"names":[],"mappings":"AAmBA,MAAM,MAAM,aAAa;AACvB,0EAA0E;AACxE;IAAE,IAAI,EAAE,UAAU,CAAA;CAAE;AACtB,4DAA4D;GAC1D;IAAE,IAAI,EAAE,SAAS,CAAC;IAAC,OAAO,CAAC,EAAE,MAAM,CAAA;CAAE,CAAA;AAEzC;wEACwE;AACxE,eAAO,MAAM,iBAAiB,cAAc,CAAA;AAM5C,UAAU,WAAW;IACnB,QAAQ,EAAE,MAAM,CAAA;IAChB,MAAM,EAAE,MAAM,CAAA;IACd,IAAI,EAAE,MAAM,CAAA;CACb;AAsBD,wBAAgB,iBAAiB,CAAC,GAAG,CAAC,EAAE,WAAW,GAAG,IAAI,GAAG,aAAa,GAAG,IAAI,CA4BhF;AAED;;uCAEuC;AACvC,wBAAgB,kBAAkB,IAAI,IAAI,CAMzC;AAED;4BAC4B;AAC5B,wBAAgB,cAAc,CAAC,GAAG,EAAE,MAAM,EAAE,MAAM,EAAE,UAAU,GAAG,MAAM,CAKtE;AAQD,MAAM,MAAM,mBAAmB,GAAG,UAAU,GAAG,QAAQ,CAAA;AAEvD,MAAM,WAAW,kBAAkB;IACjC,MAAM,EAAE,aAAa,GAAG,IAAI,CAAA;IAC5B,gFAAgF;IAChF,SAAS,EAAE,OAAO,CAAA;IAClB,eAAe,EAAE,OAAO,CAAA;IACxB,iEAAiE;IACjE,eAAe,CAAC,EAAE,OAAO,CAAA;CAC1B;AAED,MAAM,WAAW,qBAAqB;IACpC,MAAM,EAAE,mBAAmB,GAAG,IAAI,CAAA;IAClC,OAAO,EAAE,OAAO,CAAA;IAChB,QAAQ,EAAE,OAAO,CAAA;CAClB;AAID,wBAAgB,mBAAmB,CAAC,KAAK,EAAE,kBAAkB,GAAG,qBAAqB,CAgBpF"}
|
package/package.json
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
"fayz": {
|
|
4
4
|
"status": "beta"
|
|
5
5
|
},
|
|
6
|
-
"version": "0.
|
|
6
|
+
"version": "0.10.0",
|
|
7
7
|
"description": "Fayz SDK auth — pluggable authentication adapters with React hooks",
|
|
8
8
|
"type": "module",
|
|
9
9
|
"sideEffects": false,
|
|
@@ -12,31 +12,29 @@
|
|
|
12
12
|
"types": "./dist/index.d.ts",
|
|
13
13
|
"exports": {
|
|
14
14
|
".": {
|
|
15
|
-
"source": "./src/index.ts",
|
|
16
15
|
"types": "./dist/index.d.ts",
|
|
17
16
|
"import": "./dist/index.js"
|
|
18
17
|
}
|
|
19
18
|
},
|
|
20
19
|
"files": [
|
|
21
|
-
"dist"
|
|
22
|
-
"src"
|
|
20
|
+
"dist"
|
|
23
21
|
],
|
|
24
22
|
"peerDependencies": {
|
|
23
|
+
"@supabase/supabase-js": "^2.45.0",
|
|
25
24
|
"react": "^18.0.0 || ^19.0.0",
|
|
26
|
-
"zustand": "^4.5.0 || ^5.0.0"
|
|
27
|
-
"@supabase/supabase-js": "^2.45.0"
|
|
25
|
+
"zustand": "^4.5.0 || ^5.0.0"
|
|
28
26
|
},
|
|
29
27
|
"dependencies": {
|
|
30
|
-
"@fayz-ai/core": "^0.
|
|
28
|
+
"@fayz-ai/core": "^0.10.0"
|
|
31
29
|
},
|
|
32
30
|
"devDependencies": {
|
|
31
|
+
"@supabase/supabase-js": "^2.45.0",
|
|
33
32
|
"@types/react": "^18.3.0",
|
|
34
33
|
"react": "^18.3.0",
|
|
35
34
|
"tsup": "^8.2.0",
|
|
36
35
|
"typescript": "^5.5.0",
|
|
37
|
-
"
|
|
38
|
-
"
|
|
39
|
-
"vitest": "^4.1.5"
|
|
36
|
+
"vitest": "^4.1.5",
|
|
37
|
+
"zustand": "^4.5.0"
|
|
40
38
|
},
|
|
41
39
|
"license": "MIT",
|
|
42
40
|
"publishConfig": {
|
|
@@ -45,7 +43,7 @@
|
|
|
45
43
|
"scripts": {
|
|
46
44
|
"build": "tsup && tsc --emitDeclarationOnly --declaration --declarationMap --noEmit false",
|
|
47
45
|
"dev": "tsup --watch",
|
|
48
|
-
"typecheck": "tsc --noEmit",
|
|
46
|
+
"typecheck": "tsc --noEmit -p tsconfig.test.json",
|
|
49
47
|
"test": "vitest run",
|
|
50
48
|
"clean": "rm -rf dist"
|
|
51
49
|
}
|
package/dist/url-intent.d.ts.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"url-intent.d.ts","sourceRoot":"","sources":["../src/url-intent.ts"],"names":[],"mappings":"AAmBA,MAAM,MAAM,aAAa;AACvB,0EAA0E;AACxE;IAAE,IAAI,EAAE,UAAU,CAAA;CAAE;AACtB,4DAA4D;GAC1D;IAAE,IAAI,EAAE,SAAS,CAAC;IAAC,OAAO,CAAC,EAAE,MAAM,CAAA;CAAE,CAAA;AAEzC;wEACwE;AACxE,eAAO,MAAM,iBAAiB,cAAc,CAAA;AAM5C,UAAU,WAAW;IACnB,QAAQ,EAAE,MAAM,CAAA;IAChB,MAAM,EAAE,MAAM,CAAA;IACd,IAAI,EAAE,MAAM,CAAA;CACb;AAsBD,wBAAgB,iBAAiB,CAAC,GAAG,CAAC,EAAE,WAAW,GAAG,IAAI,GAAG,aAAa,GAAG,IAAI,CA4BhF;AAED;;uCAEuC;AACvC,wBAAgB,kBAAkB,IAAI,IAAI,CAMzC;AAED;4BAC4B;AAC5B,wBAAgB,cAAc,CAAC,GAAG,EAAE,MAAM,EAAE,MAAM,EAAE,UAAU,GAAG,MAAM,CAKtE;AAQD,MAAM,MAAM,mBAAmB,GAAG,UAAU,GAAG,QAAQ,CAAA;AAEvD,MAAM,WAAW,kBAAkB;IACjC,MAAM,EAAE,aAAa,GAAG,IAAI,CAAA;IAC5B,gFAAgF;IAChF,SAAS,EAAE,OAAO,CAAA;IAClB,eAAe,EAAE,OAAO,CAAA;IACxB,iEAAiE;IACjE,eAAe,CAAC,EAAE,OAAO,CAAA;CAC1B;AAED,MAAM,WAAW,qBAAqB;IACpC,MAAM,EAAE,mBAAmB,GAAG,IAAI,CAAA;IAClC,OAAO,EAAE,OAAO,CAAA;IAChB,QAAQ,EAAE,OAAO,CAAA;CAClB;AAID,wBAAgB,mBAAmB,CAAC,KAAK,EAAE,kBAAkB,GAAG,qBAAqB,CAgBpF"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"url-intent.test.d.ts","sourceRoot":"","sources":["../src/url-intent.test.ts"],"names":[],"mappings":""}
|
package/src/adapters/mock.ts
DELETED
|
@@ -1,142 +0,0 @@
|
|
|
1
|
-
import type { AuthAdapter, AuthUser, AuthSession } from '@fayz-ai/core'
|
|
2
|
-
|
|
3
|
-
export interface MockUser {
|
|
4
|
-
id: string
|
|
5
|
-
email: string
|
|
6
|
-
fullName: string
|
|
7
|
-
role?: string
|
|
8
|
-
}
|
|
9
|
-
|
|
10
|
-
const DEFAULT_MOCK_USER: MockUser = {
|
|
11
|
-
id: 'mock-user-id',
|
|
12
|
-
email: 'demo@fayz.dev',
|
|
13
|
-
fullName: 'Demo User',
|
|
14
|
-
role: 'admin',
|
|
15
|
-
}
|
|
16
|
-
|
|
17
|
-
const STORAGE_KEY = 'fayz:mock-auth'
|
|
18
|
-
|
|
19
|
-
function toAuthUser(mockUser: MockUser): AuthUser {
|
|
20
|
-
return {
|
|
21
|
-
id: mockUser.id,
|
|
22
|
-
email: mockUser.email,
|
|
23
|
-
fullName: mockUser.fullName,
|
|
24
|
-
}
|
|
25
|
-
}
|
|
26
|
-
|
|
27
|
-
function createMockSession(user: AuthUser): AuthSession {
|
|
28
|
-
return {
|
|
29
|
-
accessToken: `mock-token-${user.id}`,
|
|
30
|
-
refreshToken: `mock-refresh-${user.id}`,
|
|
31
|
-
expiresAt: Math.floor(Date.now() / 1000) + 3600,
|
|
32
|
-
user,
|
|
33
|
-
}
|
|
34
|
-
}
|
|
35
|
-
|
|
36
|
-
function getStored(): { user: AuthUser; session: AuthSession } | null {
|
|
37
|
-
try {
|
|
38
|
-
if (typeof localStorage === 'undefined') return null
|
|
39
|
-
const raw = localStorage.getItem(STORAGE_KEY)
|
|
40
|
-
if (!raw) return null
|
|
41
|
-
return JSON.parse(raw) as { user: AuthUser; session: AuthSession }
|
|
42
|
-
} catch {
|
|
43
|
-
return null
|
|
44
|
-
}
|
|
45
|
-
}
|
|
46
|
-
|
|
47
|
-
function setStored(data: { user: AuthUser; session: AuthSession } | null): void {
|
|
48
|
-
try {
|
|
49
|
-
if (typeof localStorage === 'undefined') return
|
|
50
|
-
if (data) {
|
|
51
|
-
localStorage.setItem(STORAGE_KEY, JSON.stringify(data))
|
|
52
|
-
} else {
|
|
53
|
-
localStorage.removeItem(STORAGE_KEY)
|
|
54
|
-
}
|
|
55
|
-
} catch {
|
|
56
|
-
// SSR or storage unavailable — silently skip
|
|
57
|
-
}
|
|
58
|
-
}
|
|
59
|
-
|
|
60
|
-
export function createMockAuthAdapter(mockUser: MockUser = DEFAULT_MOCK_USER): AuthAdapter {
|
|
61
|
-
const listeners = new Set<(user: AuthUser | null) => void>()
|
|
62
|
-
|
|
63
|
-
function notifyListeners(user: AuthUser | null): void {
|
|
64
|
-
for (const cb of listeners) cb(user)
|
|
65
|
-
}
|
|
66
|
-
|
|
67
|
-
return {
|
|
68
|
-
async getSession() {
|
|
69
|
-
return getStored()
|
|
70
|
-
},
|
|
71
|
-
|
|
72
|
-
onAuthStateChange(cb) {
|
|
73
|
-
listeners.add(cb)
|
|
74
|
-
return () => {
|
|
75
|
-
listeners.delete(cb)
|
|
76
|
-
}
|
|
77
|
-
},
|
|
78
|
-
|
|
79
|
-
async signIn(email, _password) {
|
|
80
|
-
// Mock accepts any credentials, but the identity FOLLOWS the email —
|
|
81
|
-
// storefront customers and saas users keep their own purchase/session
|
|
82
|
-
// history instead of all becoming the configured demo user.
|
|
83
|
-
const stored = getStored()
|
|
84
|
-
const user: AuthUser =
|
|
85
|
-
stored && stored.user.email === email
|
|
86
|
-
? stored.user
|
|
87
|
-
: {
|
|
88
|
-
id: email === mockUser.email ? mockUser.id : `mock-${email}`,
|
|
89
|
-
email,
|
|
90
|
-
fullName: email === mockUser.email ? mockUser.fullName : (email.split('@')[0] ?? 'Cliente'),
|
|
91
|
-
}
|
|
92
|
-
const session = createMockSession(user)
|
|
93
|
-
setStored({ user, session })
|
|
94
|
-
notifyListeners(user)
|
|
95
|
-
return session
|
|
96
|
-
},
|
|
97
|
-
|
|
98
|
-
async signUp(email, _password, fullName) {
|
|
99
|
-
// Mock signup creates a user from the provided details
|
|
100
|
-
const user: AuthUser = {
|
|
101
|
-
id: `mock-${email}`,
|
|
102
|
-
email,
|
|
103
|
-
fullName: fullName || (email.split('@')[0] ?? 'Cliente'),
|
|
104
|
-
}
|
|
105
|
-
const session = createMockSession(user)
|
|
106
|
-
setStored({ user, session })
|
|
107
|
-
notifyListeners(user)
|
|
108
|
-
return session
|
|
109
|
-
},
|
|
110
|
-
|
|
111
|
-
async signOut() {
|
|
112
|
-
setStored(null)
|
|
113
|
-
notifyListeners(null)
|
|
114
|
-
},
|
|
115
|
-
|
|
116
|
-
async signInWithOAuth(_provider) {
|
|
117
|
-
// Mock OAuth signs in as the configured user
|
|
118
|
-
const user = toAuthUser(mockUser)
|
|
119
|
-
const session = createMockSession(user)
|
|
120
|
-
setStored({ user, session })
|
|
121
|
-
notifyListeners(user)
|
|
122
|
-
},
|
|
123
|
-
|
|
124
|
-
async resetPassword(_email) {
|
|
125
|
-
// No-op in mock
|
|
126
|
-
},
|
|
127
|
-
|
|
128
|
-
async updatePassword(_password) {
|
|
129
|
-
const stored = getStored()
|
|
130
|
-
return stored?.session
|
|
131
|
-
},
|
|
132
|
-
|
|
133
|
-
async handleCallback() {
|
|
134
|
-
return getStored()?.session ?? null
|
|
135
|
-
},
|
|
136
|
-
|
|
137
|
-
async inviteUser(_email, _options) {
|
|
138
|
-
// No admin path in mock — the org mock adapter still records the pending
|
|
139
|
-
// invite so the Team UI shows it. Delivery is a no-op locally.
|
|
140
|
-
},
|
|
141
|
-
}
|
|
142
|
-
}
|
package/src/adapters/supabase.ts
DELETED
|
@@ -1,219 +0,0 @@
|
|
|
1
|
-
import { createClient, type SupabaseClient } from '@supabase/supabase-js'
|
|
2
|
-
import type { AuthAdapter, AuthUser, AuthSession, AuthProvider } from '@fayz-ai/core'
|
|
3
|
-
import { withAuthIntent } from '../url-intent'
|
|
4
|
-
|
|
5
|
-
/** Metadata flag stamped on invited users (created by a magic link, so they have
|
|
6
|
-
* no password yet) and cleared the moment they choose one. Metadata, not a URL
|
|
7
|
-
* param: it survives the link being opened later, in another browser, or twice —
|
|
8
|
-
* and it needs no new entry in Supabase's redirect allow-list. */
|
|
9
|
-
export const MUST_SET_PASSWORD_FLAG = 'fayz_must_set_password'
|
|
10
|
-
|
|
11
|
-
export interface SupabaseAuthConfig {
|
|
12
|
-
supabaseUrl: string
|
|
13
|
-
supabaseAnonKey: string
|
|
14
|
-
supabaseClient?: SupabaseClient
|
|
15
|
-
callbackUrl?: string
|
|
16
|
-
resetPasswordUrl?: string
|
|
17
|
-
}
|
|
18
|
-
|
|
19
|
-
function mapSupabaseUser(supabaseUser: {
|
|
20
|
-
id: string
|
|
21
|
-
email?: string | null
|
|
22
|
-
created_at?: string
|
|
23
|
-
updated_at?: string | null
|
|
24
|
-
email_confirmed_at?: string | null
|
|
25
|
-
user_metadata?: Record<string, unknown>
|
|
26
|
-
app_metadata?: { providers?: string[]; provider?: string }
|
|
27
|
-
}): AuthUser {
|
|
28
|
-
return {
|
|
29
|
-
id: supabaseUser.id,
|
|
30
|
-
email: supabaseUser.email ?? '',
|
|
31
|
-
fullName:
|
|
32
|
-
(supabaseUser.user_metadata?.['full_name'] as string | undefined) ??
|
|
33
|
-
(supabaseUser.user_metadata?.['name'] as string | undefined) ??
|
|
34
|
-
'',
|
|
35
|
-
avatarUrl: supabaseUser.user_metadata?.['avatar_url'] as string | undefined,
|
|
36
|
-
mustSetPassword: supabaseUser.user_metadata?.[MUST_SET_PASSWORD_FLAG] === true,
|
|
37
|
-
}
|
|
38
|
-
}
|
|
39
|
-
|
|
40
|
-
function mapSupabaseSession(session: {
|
|
41
|
-
access_token: string
|
|
42
|
-
refresh_token?: string
|
|
43
|
-
expires_at?: number
|
|
44
|
-
expires_in?: number
|
|
45
|
-
user: Parameters<typeof mapSupabaseUser>[0]
|
|
46
|
-
}): AuthSession {
|
|
47
|
-
return {
|
|
48
|
-
accessToken: session.access_token,
|
|
49
|
-
refreshToken: session.refresh_token,
|
|
50
|
-
expiresAt:
|
|
51
|
-
session.expires_at ??
|
|
52
|
-
Math.floor(Date.now() / 1000) + (session.expires_in ?? 3600),
|
|
53
|
-
user: mapSupabaseUser(session.user),
|
|
54
|
-
}
|
|
55
|
-
}
|
|
56
|
-
|
|
57
|
-
export function createSupabaseAuthAdapter(config: SupabaseAuthConfig): AuthAdapter {
|
|
58
|
-
const supabase = config.supabaseClient ?? createClient(config.supabaseUrl, config.supabaseAnonKey)
|
|
59
|
-
|
|
60
|
-
return {
|
|
61
|
-
async getSession() {
|
|
62
|
-
const {
|
|
63
|
-
data: { session },
|
|
64
|
-
} = await supabase.auth.getSession()
|
|
65
|
-
if (!session) return null
|
|
66
|
-
const mapped = mapSupabaseSession(session)
|
|
67
|
-
return { user: mapped.user, session: mapped }
|
|
68
|
-
},
|
|
69
|
-
|
|
70
|
-
onAuthStateChange(cb) {
|
|
71
|
-
const {
|
|
72
|
-
data: { subscription },
|
|
73
|
-
} = supabase.auth.onAuthStateChange((_event, session) => {
|
|
74
|
-
cb(session ? mapSupabaseUser(session.user) : null)
|
|
75
|
-
})
|
|
76
|
-
return () => subscription.unsubscribe()
|
|
77
|
-
},
|
|
78
|
-
|
|
79
|
-
async signIn(email, password) {
|
|
80
|
-
const { data, error } = await supabase.auth.signInWithPassword({ email, password })
|
|
81
|
-
if (error) throw error
|
|
82
|
-
return mapSupabaseSession(data.session)
|
|
83
|
-
},
|
|
84
|
-
|
|
85
|
-
async signUp(email, password, fullName) {
|
|
86
|
-
const { data, error } = await supabase.auth.signUp({
|
|
87
|
-
email,
|
|
88
|
-
password,
|
|
89
|
-
options: { data: { full_name: fullName } },
|
|
90
|
-
})
|
|
91
|
-
if (error) throw error
|
|
92
|
-
|
|
93
|
-
// When email confirmation is required, session is null
|
|
94
|
-
if (!data.session) {
|
|
95
|
-
if (!data.user) throw new Error('Signup failed: no user returned')
|
|
96
|
-
return {
|
|
97
|
-
accessToken: '',
|
|
98
|
-
refreshToken: '',
|
|
99
|
-
expiresAt: 0,
|
|
100
|
-
user: mapSupabaseUser(data.user),
|
|
101
|
-
}
|
|
102
|
-
}
|
|
103
|
-
|
|
104
|
-
return mapSupabaseSession(data.session)
|
|
105
|
-
},
|
|
106
|
-
|
|
107
|
-
async signOut() {
|
|
108
|
-
const { error } = await supabase.auth.signOut()
|
|
109
|
-
if (error) throw error
|
|
110
|
-
},
|
|
111
|
-
|
|
112
|
-
async signInWithOAuth(provider: AuthProvider) {
|
|
113
|
-
const { error } = await supabase.auth.signInWithOAuth({
|
|
114
|
-
provider: provider as 'google' | 'github' | 'apple',
|
|
115
|
-
options: {
|
|
116
|
-
redirectTo:
|
|
117
|
-
config.callbackUrl ??
|
|
118
|
-
(typeof window !== 'undefined' ? `${window.location.origin}/auth/callback` : undefined),
|
|
119
|
-
},
|
|
120
|
-
})
|
|
121
|
-
if (error) throw error
|
|
122
|
-
},
|
|
123
|
-
|
|
124
|
-
async resetPassword(email, options) {
|
|
125
|
-
// Root, not `/auth/reset-password`: the shell recognises a recovery link by
|
|
126
|
-
// the link's own `type=recovery` param, so the flow needs no route of its
|
|
127
|
-
// own — and the app root is the one URL every deployment already serves and
|
|
128
|
-
// every Supabase project already allow-lists (a URL outside the allow-list
|
|
129
|
-
// is silently swapped for the project's Site URL, i.e. another app).
|
|
130
|
-
// A host that DOES point recovery somewhere else gets the explicit intent
|
|
131
|
-
// marker, since we cannot assume its landing page carries the params.
|
|
132
|
-
const explicit = options?.redirectTo ?? config.resetPasswordUrl
|
|
133
|
-
const { error } = await supabase.auth.resetPasswordForEmail(email, {
|
|
134
|
-
redirectTo: explicit
|
|
135
|
-
? withAuthIntent(explicit, 'recovery')
|
|
136
|
-
: typeof window !== 'undefined'
|
|
137
|
-
? `${window.location.origin}/`
|
|
138
|
-
: undefined,
|
|
139
|
-
})
|
|
140
|
-
if (error) throw error
|
|
141
|
-
},
|
|
142
|
-
|
|
143
|
-
async updatePassword(password) {
|
|
144
|
-
// Clearing the flag in the same call as the password: one round-trip, and
|
|
145
|
-
// no window where the password is set but the screen still demands one.
|
|
146
|
-
const { data, error } = await supabase.auth.updateUser({
|
|
147
|
-
password,
|
|
148
|
-
data: { [MUST_SET_PASSWORD_FLAG]: false },
|
|
149
|
-
})
|
|
150
|
-
if (error) throw error
|
|
151
|
-
const {
|
|
152
|
-
data: { session },
|
|
153
|
-
} = await supabase.auth.getSession()
|
|
154
|
-
if (session) return mapSupabaseSession(session)
|
|
155
|
-
if (!data.user) return undefined
|
|
156
|
-
return {
|
|
157
|
-
accessToken: '',
|
|
158
|
-
refreshToken: '',
|
|
159
|
-
expiresAt: 0,
|
|
160
|
-
user: mapSupabaseUser(data.user),
|
|
161
|
-
}
|
|
162
|
-
},
|
|
163
|
-
|
|
164
|
-
async handleCallback(url) {
|
|
165
|
-
const target = url ?? (typeof window !== 'undefined' ? window.location.href : '')
|
|
166
|
-
const parsed = new URL(target)
|
|
167
|
-
// The fragment carries the params on the implicit flow; the query on PKCE
|
|
168
|
-
// and on `{{ .TokenHash }}`-style e-mail templates.
|
|
169
|
-
const fragment = new URLSearchParams(parsed.hash.replace(/^#/, ''))
|
|
170
|
-
const param = (key: string) => parsed.searchParams.get(key) ?? fragment.get(key)
|
|
171
|
-
|
|
172
|
-
const code = param('code')
|
|
173
|
-
if (code) {
|
|
174
|
-
const { data, error } = await supabase.auth.exchangeCodeForSession(code)
|
|
175
|
-
if (error) throw error
|
|
176
|
-
return data.session ? mapSupabaseSession(data.session) : null
|
|
177
|
-
}
|
|
178
|
-
|
|
179
|
-
// Templates that link straight at the app with a token instead of routing
|
|
180
|
-
// through GoTrue's /verify never produce a session on their own.
|
|
181
|
-
const tokenHash = param('token_hash') ?? param('token')
|
|
182
|
-
const type = param('type')
|
|
183
|
-
if (tokenHash && type) {
|
|
184
|
-
const { data, error } = await supabase.auth.verifyOtp({
|
|
185
|
-
token_hash: tokenHash,
|
|
186
|
-
type: type as 'recovery' | 'invite' | 'magiclink' | 'signup' | 'email',
|
|
187
|
-
})
|
|
188
|
-
if (error) throw error
|
|
189
|
-
return data.session ? mapSupabaseSession(data.session) : null
|
|
190
|
-
}
|
|
191
|
-
|
|
192
|
-
const {
|
|
193
|
-
data: { session },
|
|
194
|
-
} = await supabase.auth.getSession()
|
|
195
|
-
return session ? mapSupabaseSession(session) : null
|
|
196
|
-
},
|
|
197
|
-
|
|
198
|
-
async inviteUser(email, options) {
|
|
199
|
-
// Native, edge-function-free invite: a passwordless magic link. Sends the
|
|
200
|
-
// e-mail + creates the auth user (anon-callable, no service-role/admin).
|
|
201
|
-
// Membership is NOT granted from `data` (a client could forge it) — the
|
|
202
|
-
// accept-time trigger trusts the RLS-protected public.invitations row.
|
|
203
|
-
const { error } = await supabase.auth.signInWithOtp({
|
|
204
|
-
email,
|
|
205
|
-
options: {
|
|
206
|
-
shouldCreateUser: true,
|
|
207
|
-
emailRedirectTo:
|
|
208
|
-
options?.redirectTo ??
|
|
209
|
-
(typeof window !== 'undefined' ? `${window.location.origin}/` : undefined),
|
|
210
|
-
// `data` only lands on users the OTP actually creates, which is exactly
|
|
211
|
-
// who needs a password: the shell holds them on the set-password screen
|
|
212
|
-
// until they choose one, so they can sign in normally from then on.
|
|
213
|
-
data: { ...options?.data, [MUST_SET_PASSWORD_FLAG]: true },
|
|
214
|
-
},
|
|
215
|
-
})
|
|
216
|
-
if (error) throw error
|
|
217
|
-
},
|
|
218
|
-
}
|
|
219
|
-
}
|
package/src/context.tsx
DELETED
|
@@ -1,205 +0,0 @@
|
|
|
1
|
-
import React, { createContext, useContext, useEffect, useRef } from 'react'
|
|
2
|
-
import type { AuthAdapter, AuthProvider as OAuthProvider, AuthSession } from '@fayz-ai/core'
|
|
3
|
-
import { useAuthStore } from './store'
|
|
4
|
-
|
|
5
|
-
// ---------------------------------------------------------------------------
|
|
6
|
-
// Context
|
|
7
|
-
// ---------------------------------------------------------------------------
|
|
8
|
-
|
|
9
|
-
interface AuthContextValue {
|
|
10
|
-
signIn: (email: string, password: string) => Promise<AuthSession>
|
|
11
|
-
signUp: (email: string, password: string, fullName: string) => Promise<AuthSession>
|
|
12
|
-
signOut: () => Promise<void>
|
|
13
|
-
signInWithOAuth: (provider: OAuthProvider) => Promise<void>
|
|
14
|
-
resetPassword: (email: string, options?: { redirectTo?: string }) => Promise<void>
|
|
15
|
-
updatePassword: (password: string) => Promise<AuthSession | void>
|
|
16
|
-
handleCallback: (url?: string) => Promise<AuthSession | null>
|
|
17
|
-
inviteUser: (email: string, options?: { redirectTo?: string; data?: Record<string, unknown> }) => Promise<void>
|
|
18
|
-
}
|
|
19
|
-
|
|
20
|
-
const AuthContext = createContext<AuthContextValue | null>(null)
|
|
21
|
-
|
|
22
|
-
// ---------------------------------------------------------------------------
|
|
23
|
-
// Provider
|
|
24
|
-
// ---------------------------------------------------------------------------
|
|
25
|
-
|
|
26
|
-
export interface AuthProviderProps {
|
|
27
|
-
adapter: AuthAdapter
|
|
28
|
-
children: React.ReactNode
|
|
29
|
-
}
|
|
30
|
-
|
|
31
|
-
export function AuthProvider({ adapter, children }: AuthProviderProps) {
|
|
32
|
-
const { setSession, setLoading, setError, reset } = useAuthStore()
|
|
33
|
-
|
|
34
|
-
// Keep a stable ref to the adapter so the effect only runs once on mount
|
|
35
|
-
const adapterRef = useRef(adapter)
|
|
36
|
-
adapterRef.current = adapter
|
|
37
|
-
|
|
38
|
-
useEffect(() => {
|
|
39
|
-
let unsubscribe: (() => void) | undefined
|
|
40
|
-
|
|
41
|
-
async function init() {
|
|
42
|
-
try {
|
|
43
|
-
setLoading(true)
|
|
44
|
-
const result = await adapterRef.current.getSession()
|
|
45
|
-
setSession(result?.session ?? null)
|
|
46
|
-
} catch (err) {
|
|
47
|
-
setError(err instanceof Error ? err : new Error(String(err)))
|
|
48
|
-
} finally {
|
|
49
|
-
setLoading(false)
|
|
50
|
-
}
|
|
51
|
-
|
|
52
|
-
// Subscribe to future auth state changes
|
|
53
|
-
unsubscribe = adapterRef.current.onAuthStateChange((user) => {
|
|
54
|
-
if (!user) {
|
|
55
|
-
reset()
|
|
56
|
-
// Keep isLoading false after an explicit sign-out
|
|
57
|
-
setLoading(false)
|
|
58
|
-
return
|
|
59
|
-
}
|
|
60
|
-
// Positive change (adapter-driven sign-in — e.g. an external callback,
|
|
61
|
-
// another tab, or a direct adapter.signUp bridge) — sync the session so
|
|
62
|
-
// consumers reflect it even when the call didn't go through ctx.signIn.
|
|
63
|
-
void adapterRef.current.getSession().then((result) => setSession(result?.session ?? null)).catch(() => {})
|
|
64
|
-
})
|
|
65
|
-
}
|
|
66
|
-
|
|
67
|
-
void init()
|
|
68
|
-
|
|
69
|
-
return () => {
|
|
70
|
-
unsubscribe?.()
|
|
71
|
-
}
|
|
72
|
-
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
73
|
-
}, [])
|
|
74
|
-
|
|
75
|
-
const value: AuthContextValue = {
|
|
76
|
-
async signIn(email, password) {
|
|
77
|
-
setError(null)
|
|
78
|
-
try {
|
|
79
|
-
const session = await adapterRef.current.signIn(email, password)
|
|
80
|
-
setSession(session)
|
|
81
|
-
return session
|
|
82
|
-
} catch (err) {
|
|
83
|
-
const error = err instanceof Error ? err : new Error(String(err))
|
|
84
|
-
setError(error)
|
|
85
|
-
throw error
|
|
86
|
-
}
|
|
87
|
-
},
|
|
88
|
-
|
|
89
|
-
async signUp(email, password, fullName) {
|
|
90
|
-
setError(null)
|
|
91
|
-
try {
|
|
92
|
-
const session = await adapterRef.current.signUp(email, password, fullName)
|
|
93
|
-
setSession(session)
|
|
94
|
-
return session
|
|
95
|
-
} catch (err) {
|
|
96
|
-
const error = err instanceof Error ? err : new Error(String(err))
|
|
97
|
-
setError(error)
|
|
98
|
-
throw error
|
|
99
|
-
}
|
|
100
|
-
},
|
|
101
|
-
|
|
102
|
-
async signOut() {
|
|
103
|
-
setError(null)
|
|
104
|
-
try {
|
|
105
|
-
await adapterRef.current.signOut()
|
|
106
|
-
reset()
|
|
107
|
-
setLoading(false)
|
|
108
|
-
} catch (err) {
|
|
109
|
-
const error = err instanceof Error ? err : new Error(String(err))
|
|
110
|
-
setError(error)
|
|
111
|
-
throw error
|
|
112
|
-
}
|
|
113
|
-
},
|
|
114
|
-
|
|
115
|
-
async signInWithOAuth(provider) {
|
|
116
|
-
setError(null)
|
|
117
|
-
try {
|
|
118
|
-
await adapterRef.current.signInWithOAuth(provider)
|
|
119
|
-
} catch (err) {
|
|
120
|
-
const error = err instanceof Error ? err : new Error(String(err))
|
|
121
|
-
setError(error)
|
|
122
|
-
throw error
|
|
123
|
-
}
|
|
124
|
-
},
|
|
125
|
-
|
|
126
|
-
async resetPassword(email, options) {
|
|
127
|
-
setError(null)
|
|
128
|
-
try {
|
|
129
|
-
await adapterRef.current.resetPassword(email, options)
|
|
130
|
-
} catch (err) {
|
|
131
|
-
const error = err instanceof Error ? err : new Error(String(err))
|
|
132
|
-
setError(error)
|
|
133
|
-
throw error
|
|
134
|
-
}
|
|
135
|
-
},
|
|
136
|
-
|
|
137
|
-
async updatePassword(password) {
|
|
138
|
-
setError(null)
|
|
139
|
-
try {
|
|
140
|
-
const session = await adapterRef.current.updatePassword?.(password)
|
|
141
|
-
if (session) setSession(session)
|
|
142
|
-
return session
|
|
143
|
-
} catch (err) {
|
|
144
|
-
const error = err instanceof Error ? err : new Error(String(err))
|
|
145
|
-
setError(error)
|
|
146
|
-
throw error
|
|
147
|
-
}
|
|
148
|
-
},
|
|
149
|
-
|
|
150
|
-
async handleCallback(url) {
|
|
151
|
-
setError(null)
|
|
152
|
-
try {
|
|
153
|
-
const session = await adapterRef.current.handleCallback?.(url) ?? null
|
|
154
|
-
if (session) setSession(session)
|
|
155
|
-
return session
|
|
156
|
-
} catch (err) {
|
|
157
|
-
const error = err instanceof Error ? err : new Error(String(err))
|
|
158
|
-
setError(error)
|
|
159
|
-
throw error
|
|
160
|
-
}
|
|
161
|
-
},
|
|
162
|
-
|
|
163
|
-
async inviteUser(email, options) {
|
|
164
|
-
setError(null)
|
|
165
|
-
try {
|
|
166
|
-
await adapterRef.current.inviteUser?.(email, options)
|
|
167
|
-
} catch (err) {
|
|
168
|
-
const error = err instanceof Error ? err : new Error(String(err))
|
|
169
|
-
setError(error)
|
|
170
|
-
throw error
|
|
171
|
-
}
|
|
172
|
-
},
|
|
173
|
-
}
|
|
174
|
-
|
|
175
|
-
return <AuthContext.Provider value={value}>{children}</AuthContext.Provider>
|
|
176
|
-
}
|
|
177
|
-
|
|
178
|
-
// ---------------------------------------------------------------------------
|
|
179
|
-
// Hook
|
|
180
|
-
// ---------------------------------------------------------------------------
|
|
181
|
-
|
|
182
|
-
export function useAuth() {
|
|
183
|
-
const ctx = useContext(AuthContext)
|
|
184
|
-
if (!ctx) {
|
|
185
|
-
throw new Error('useAuth must be used inside <AuthProvider>')
|
|
186
|
-
}
|
|
187
|
-
|
|
188
|
-
const { user, session, isLoading, isAuthenticated, error } = useAuthStore()
|
|
189
|
-
|
|
190
|
-
return {
|
|
191
|
-
user,
|
|
192
|
-
session,
|
|
193
|
-
isLoading,
|
|
194
|
-
isAuthenticated,
|
|
195
|
-
error,
|
|
196
|
-
signIn: ctx.signIn,
|
|
197
|
-
signUp: ctx.signUp,
|
|
198
|
-
signOut: ctx.signOut,
|
|
199
|
-
signInWithOAuth: ctx.signInWithOAuth,
|
|
200
|
-
resetPassword: ctx.resetPassword,
|
|
201
|
-
updatePassword: ctx.updatePassword,
|
|
202
|
-
handleCallback: ctx.handleCallback,
|
|
203
|
-
inviteUser: ctx.inviteUser,
|
|
204
|
-
}
|
|
205
|
-
}
|
package/src/index.ts
DELETED
|
@@ -1,29 +0,0 @@
|
|
|
1
|
-
// Adapters
|
|
2
|
-
export { createSupabaseAuthAdapter, MUST_SET_PASSWORD_FLAG } from './adapters/supabase'
|
|
3
|
-
export type { SupabaseAuthConfig } from './adapters/supabase'
|
|
4
|
-
|
|
5
|
-
// Auth link intent (recovery / expired one-time link) + set-password decision
|
|
6
|
-
export {
|
|
7
|
-
readAuthUrlIntent,
|
|
8
|
-
clearAuthUrlTokens,
|
|
9
|
-
withAuthIntent,
|
|
10
|
-
decidePasswordSetup,
|
|
11
|
-
AUTH_INTENT_PARAM,
|
|
12
|
-
} from './url-intent'
|
|
13
|
-
export type {
|
|
14
|
-
AuthUrlIntent,
|
|
15
|
-
PasswordSetupDecision,
|
|
16
|
-
PasswordSetupInput,
|
|
17
|
-
PasswordSetupReason,
|
|
18
|
-
} from './url-intent'
|
|
19
|
-
|
|
20
|
-
export { createMockAuthAdapter } from './adapters/mock'
|
|
21
|
-
export type { MockUser } from './adapters/mock'
|
|
22
|
-
|
|
23
|
-
// Store
|
|
24
|
-
export { useAuthStore } from './store'
|
|
25
|
-
export type { AuthState, AuthStore } from './store'
|
|
26
|
-
|
|
27
|
-
// Context & hook
|
|
28
|
-
export { AuthProvider, useAuth } from './context'
|
|
29
|
-
export type { AuthProviderProps } from './context'
|
package/src/store.ts
DELETED
|
@@ -1,46 +0,0 @@
|
|
|
1
|
-
import { create } from 'zustand'
|
|
2
|
-
import type { AuthUser, AuthSession } from '@fayz-ai/core'
|
|
3
|
-
|
|
4
|
-
export interface AuthState {
|
|
5
|
-
user: AuthUser | null
|
|
6
|
-
session: AuthSession | null
|
|
7
|
-
isLoading: boolean
|
|
8
|
-
isAuthenticated: boolean
|
|
9
|
-
error: Error | null
|
|
10
|
-
}
|
|
11
|
-
|
|
12
|
-
export interface AuthStore extends AuthState {
|
|
13
|
-
setUser: (user: AuthUser | null) => void
|
|
14
|
-
setSession: (session: AuthSession | null) => void
|
|
15
|
-
setLoading: (isLoading: boolean) => void
|
|
16
|
-
setError: (error: Error | null) => void
|
|
17
|
-
reset: () => void
|
|
18
|
-
}
|
|
19
|
-
|
|
20
|
-
const initialState: AuthState = {
|
|
21
|
-
user: null,
|
|
22
|
-
session: null,
|
|
23
|
-
isLoading: true,
|
|
24
|
-
isAuthenticated: false,
|
|
25
|
-
error: null,
|
|
26
|
-
}
|
|
27
|
-
|
|
28
|
-
export const useAuthStore = create<AuthStore>((set) => ({
|
|
29
|
-
...initialState,
|
|
30
|
-
|
|
31
|
-
setUser: (user) =>
|
|
32
|
-
set({ user, isAuthenticated: user !== null }),
|
|
33
|
-
|
|
34
|
-
setSession: (session) =>
|
|
35
|
-
set({
|
|
36
|
-
session,
|
|
37
|
-
user: session?.user ?? null,
|
|
38
|
-
isAuthenticated: session !== null,
|
|
39
|
-
}),
|
|
40
|
-
|
|
41
|
-
setLoading: (isLoading) => set({ isLoading }),
|
|
42
|
-
|
|
43
|
-
setError: (error) => set({ error }),
|
|
44
|
-
|
|
45
|
-
reset: () => set(initialState),
|
|
46
|
-
}))
|
package/src/url-intent.test.ts
DELETED
|
@@ -1,91 +0,0 @@
|
|
|
1
|
-
import { describe, it, expect } from 'vitest'
|
|
2
|
-
import { readAuthUrlIntent, withAuthIntent, decidePasswordSetup } from './url-intent'
|
|
3
|
-
|
|
4
|
-
function url(pathname: string, search = '', hash = '') {
|
|
5
|
-
return { pathname, search, hash }
|
|
6
|
-
}
|
|
7
|
-
|
|
8
|
-
describe('readAuthUrlIntent', () => {
|
|
9
|
-
it('recognises a recovery link by its implicit-flow fragment', () => {
|
|
10
|
-
expect(
|
|
11
|
-
readAuthUrlIntent(url('/', '', '#access_token=abc&refresh_token=def&type=recovery')),
|
|
12
|
-
).toEqual({ kind: 'recovery' })
|
|
13
|
-
})
|
|
14
|
-
|
|
15
|
-
it('recognises the explicit marker for hosts that override the redirect', () => {
|
|
16
|
-
expect(readAuthUrlIntent(url('/', '?fayz_auth=recovery'))).toEqual({ kind: 'recovery' })
|
|
17
|
-
})
|
|
18
|
-
|
|
19
|
-
it('still honours the legacy /auth/reset-password path', () => {
|
|
20
|
-
expect(readAuthUrlIntent(url('/auth/reset-password'))).toEqual({ kind: 'recovery' })
|
|
21
|
-
})
|
|
22
|
-
|
|
23
|
-
it('flags a used or expired one-time link', () => {
|
|
24
|
-
const intent = readAuthUrlIntent(
|
|
25
|
-
url('/', '', '#error=access_denied&error_code=otp_expired&error_description=Email+link+is+invalid+or+has+expired'),
|
|
26
|
-
)
|
|
27
|
-
expect(intent?.kind).toBe('expired')
|
|
28
|
-
expect(intent && 'message' in intent && intent.message).toBe('Email link is invalid or has expired')
|
|
29
|
-
})
|
|
30
|
-
|
|
31
|
-
it('leaves a plain sign-in, a magic link and an OAuth denial alone', () => {
|
|
32
|
-
expect(readAuthUrlIntent(url('/', '', '#/dashboard'))).toBeNull()
|
|
33
|
-
expect(readAuthUrlIntent(url('/', '', '#access_token=abc&type=magiclink'))).toBeNull()
|
|
34
|
-
expect(readAuthUrlIntent(url('/', '', '#error=access_denied&error_code=user_banned'))).toBeNull()
|
|
35
|
-
})
|
|
36
|
-
})
|
|
37
|
-
|
|
38
|
-
describe('decidePasswordSetup', () => {
|
|
39
|
-
const signedIn = { isLoading: false, isAuthenticated: true }
|
|
40
|
-
const signedOut = { isLoading: false, isAuthenticated: false }
|
|
41
|
-
|
|
42
|
-
it('asks for a new password on a recovery link', () => {
|
|
43
|
-
expect(decidePasswordSetup({ intent: { kind: 'recovery' }, ...signedIn })).toEqual({
|
|
44
|
-
reason: 'recovery',
|
|
45
|
-
expired: false,
|
|
46
|
-
checking: false,
|
|
47
|
-
})
|
|
48
|
-
})
|
|
49
|
-
|
|
50
|
-
it('waits for the link session instead of flashing the login form', () => {
|
|
51
|
-
expect(
|
|
52
|
-
decidePasswordSetup({ intent: { kind: 'recovery' }, isLoading: true, isAuthenticated: false }),
|
|
53
|
-
).toEqual({ reason: 'recovery', expired: false, checking: true })
|
|
54
|
-
})
|
|
55
|
-
|
|
56
|
-
it('treats a recovery link that produced no session as expired', () => {
|
|
57
|
-
expect(decidePasswordSetup({ intent: { kind: 'recovery' }, ...signedOut })).toEqual({
|
|
58
|
-
reason: 'recovery',
|
|
59
|
-
expired: true,
|
|
60
|
-
checking: false,
|
|
61
|
-
})
|
|
62
|
-
})
|
|
63
|
-
|
|
64
|
-
it('holds an invitee on the screen until they choose a password', () => {
|
|
65
|
-
expect(decidePasswordSetup({ intent: null, ...signedIn, mustSetPassword: true })).toEqual({
|
|
66
|
-
reason: 'invite',
|
|
67
|
-
expired: false,
|
|
68
|
-
checking: false,
|
|
69
|
-
})
|
|
70
|
-
})
|
|
71
|
-
|
|
72
|
-
it('stays out of the way for everyone else', () => {
|
|
73
|
-
expect(decidePasswordSetup({ intent: null, ...signedIn }).reason).toBeNull()
|
|
74
|
-
expect(decidePasswordSetup({ intent: null, ...signedOut }).reason).toBeNull()
|
|
75
|
-
// Never gate the login form itself: no session, nothing to update.
|
|
76
|
-
expect(decidePasswordSetup({ intent: null, ...signedOut, mustSetPassword: true }).reason).toBeNull()
|
|
77
|
-
})
|
|
78
|
-
})
|
|
79
|
-
|
|
80
|
-
describe('withAuthIntent', () => {
|
|
81
|
-
it('keeps existing params and stays absolute', () => {
|
|
82
|
-
expect(withAuthIntent('https://app.example.com/?ref=x', 'recovery')).toBe(
|
|
83
|
-
'https://app.example.com/?ref=x&fayz_auth=recovery',
|
|
84
|
-
)
|
|
85
|
-
})
|
|
86
|
-
|
|
87
|
-
it('is idempotent', () => {
|
|
88
|
-
const once = withAuthIntent('https://app.example.com/', 'recovery')
|
|
89
|
-
expect(withAuthIntent(once, 'recovery')).toBe(once)
|
|
90
|
-
})
|
|
91
|
-
})
|
package/src/url-intent.ts
DELETED
|
@@ -1,151 +0,0 @@
|
|
|
1
|
-
// ---------------------------------------------------------------------------
|
|
2
|
-
// Auth link intent — what the URL the user just arrived on is asking for.
|
|
3
|
-
//
|
|
4
|
-
// A Supabase recovery / magic link lands on the app with the tokens in the URL
|
|
5
|
-
// FRAGMENT (implicit flow is the supabase-js default), e.g.
|
|
6
|
-
//
|
|
7
|
-
// https://app.example.com/#access_token=…&refresh_token=…&type=recovery
|
|
8
|
-
//
|
|
9
|
-
// GoTrue then consumes that fragment and wipes it (`window.location.hash = ''`)
|
|
10
|
-
// as soon as the client initialises — so by the time React renders, the reason
|
|
11
|
-
// the user is here is gone. Hence the module-load snapshot: this file is
|
|
12
|
-
// imported long before any createClient() call, so it always sees the original
|
|
13
|
-
// URL.
|
|
14
|
-
//
|
|
15
|
-
// Errors arrive the same way, without a `type`:
|
|
16
|
-
//
|
|
17
|
-
// https://app.example.com/#error=access_denied&error_code=otp_expired&…
|
|
18
|
-
// ---------------------------------------------------------------------------
|
|
19
|
-
|
|
20
|
-
export type AuthUrlIntent =
|
|
21
|
-
/** A password-recovery link — the user must choose a new password now. */
|
|
22
|
-
| { kind: 'recovery' }
|
|
23
|
-
/** A one-time link that was already used or has expired. */
|
|
24
|
-
| { kind: 'expired'; message?: string }
|
|
25
|
-
|
|
26
|
-
/** Query param apps can put on their own redirect URLs to force the
|
|
27
|
-
* set-password screen (e.g. when they override `resetPasswordUrl`). */
|
|
28
|
-
export const AUTH_INTENT_PARAM = 'fayz_auth'
|
|
29
|
-
|
|
30
|
-
/** Path segment the SDK historically used as the reset-password redirect.
|
|
31
|
-
* Still honoured so apps that configured it keep working. */
|
|
32
|
-
const RESET_PATH = '/auth/reset-password'
|
|
33
|
-
|
|
34
|
-
interface UrlSnapshot {
|
|
35
|
-
pathname: string
|
|
36
|
-
search: string
|
|
37
|
-
hash: string
|
|
38
|
-
}
|
|
39
|
-
|
|
40
|
-
function snapshot(): UrlSnapshot | null {
|
|
41
|
-
if (typeof window === 'undefined') return null
|
|
42
|
-
return {
|
|
43
|
-
pathname: window.location.pathname,
|
|
44
|
-
search: window.location.search,
|
|
45
|
-
hash: window.location.hash,
|
|
46
|
-
}
|
|
47
|
-
}
|
|
48
|
-
|
|
49
|
-
/** Taken at import time — before any Supabase client can strip the fragment. */
|
|
50
|
-
const initialUrl: UrlSnapshot | null = snapshot()
|
|
51
|
-
|
|
52
|
-
/** The fragment can be either auth params (`access_token=…&type=recovery`) or a
|
|
53
|
-
* hash-router path (`#/dashboard`). Only the former parses into pairs. */
|
|
54
|
-
function hashParams(hash: string): URLSearchParams {
|
|
55
|
-
const raw = hash.replace(/^#/, '')
|
|
56
|
-
if (!raw || !raw.includes('=')) return new URLSearchParams()
|
|
57
|
-
return new URLSearchParams(raw)
|
|
58
|
-
}
|
|
59
|
-
|
|
60
|
-
export function readAuthUrlIntent(url?: UrlSnapshot | null): AuthUrlIntent | null {
|
|
61
|
-
const loc = url ?? initialUrl
|
|
62
|
-
if (!loc) return null
|
|
63
|
-
|
|
64
|
-
const query = new URLSearchParams(loc.search)
|
|
65
|
-
const hash = hashParams(loc.hash)
|
|
66
|
-
const param = (key: string) => hash.get(key) ?? query.get(key)
|
|
67
|
-
|
|
68
|
-
const errorCode = param('error_code') ?? param('error')
|
|
69
|
-
const errorDescription = param('error_description')?.replace(/\+/g, ' ')
|
|
70
|
-
// A dead one-time link (`error_code=otp_expired`). Deliberately narrow: an
|
|
71
|
-
// OAuth `access_denied` is a different failure and must not land here. GoTrue
|
|
72
|
-
// does not echo `type` on error redirects, so recovery and invite links are
|
|
73
|
-
// indistinguishable at this point — the screen offers a fresh link either way.
|
|
74
|
-
if (errorCode && /otp|expired|link/i.test(`${errorCode} ${errorDescription ?? ''}`)) {
|
|
75
|
-
return { kind: 'expired', message: errorDescription ?? undefined }
|
|
76
|
-
}
|
|
77
|
-
|
|
78
|
-
const marker = query.get(AUTH_INTENT_PARAM)
|
|
79
|
-
const type = param('type')
|
|
80
|
-
if (type === 'recovery' || marker === 'recovery') return { kind: 'recovery' }
|
|
81
|
-
|
|
82
|
-
// `/auth/reset-password` with no tokens at all: the user opened the reset URL
|
|
83
|
-
// directly, or the tokens were already consumed by a previous page load.
|
|
84
|
-
const path = loc.pathname.replace(/\/+$/, '')
|
|
85
|
-
if (path.endsWith(RESET_PATH)) return { kind: 'recovery' }
|
|
86
|
-
|
|
87
|
-
return null
|
|
88
|
-
}
|
|
89
|
-
|
|
90
|
-
/** Strip auth leftovers from the address bar once the flow is finished, so a
|
|
91
|
-
* reload does not put the user back on the set-password screen (and so the
|
|
92
|
-
* hash router gets a clean slate). */
|
|
93
|
-
export function clearAuthUrlTokens(): void {
|
|
94
|
-
if (typeof window === 'undefined') return
|
|
95
|
-
const url = new URL(window.location.href)
|
|
96
|
-
url.searchParams.delete(AUTH_INTENT_PARAM)
|
|
97
|
-
if (url.hash.includes('=')) url.hash = ''
|
|
98
|
-
window.history.replaceState(window.history.state, '', url.toString())
|
|
99
|
-
}
|
|
100
|
-
|
|
101
|
-
/** Add the intent marker to a redirect URL. Absolute or relative; existing
|
|
102
|
-
* params are preserved. */
|
|
103
|
-
export function withAuthIntent(url: string, intent: 'recovery'): string {
|
|
104
|
-
const base = typeof window === 'undefined' ? 'http://localhost' : window.location.origin
|
|
105
|
-
const parsed = new URL(url, base)
|
|
106
|
-
parsed.searchParams.set(AUTH_INTENT_PARAM, intent)
|
|
107
|
-
return /^https?:\/\//i.test(url) ? parsed.toString() : `${parsed.pathname}${parsed.search}${parsed.hash}`
|
|
108
|
-
}
|
|
109
|
-
|
|
110
|
-
// ---------------------------------------------------------------------------
|
|
111
|
-
// Whether the user owes us a password before they reach the app. Pure, so the
|
|
112
|
-
// decision is testable without a browser; the React wrapper lives in
|
|
113
|
-
// @fayz-ai/plugin-auth (usePasswordSetupGate).
|
|
114
|
-
// ---------------------------------------------------------------------------
|
|
115
|
-
|
|
116
|
-
export type PasswordSetupReason = 'recovery' | 'invite'
|
|
117
|
-
|
|
118
|
-
export interface PasswordSetupInput {
|
|
119
|
-
intent: AuthUrlIntent | null
|
|
120
|
-
/** Session still resolving — the link's tokens are exchanged asynchronously. */
|
|
121
|
-
isLoading: boolean
|
|
122
|
-
isAuthenticated: boolean
|
|
123
|
-
/** AuthUser.mustSetPassword — an invitee who never chose one. */
|
|
124
|
-
mustSetPassword?: boolean
|
|
125
|
-
}
|
|
126
|
-
|
|
127
|
-
export interface PasswordSetupDecision {
|
|
128
|
-
reason: PasswordSetupReason | null
|
|
129
|
-
expired: boolean
|
|
130
|
-
checking: boolean
|
|
131
|
-
}
|
|
132
|
-
|
|
133
|
-
const NOTHING: PasswordSetupDecision = { reason: null, expired: false, checking: false }
|
|
134
|
-
|
|
135
|
-
export function decidePasswordSetup(input: PasswordSetupInput): PasswordSetupDecision {
|
|
136
|
-
const { intent, isLoading, isAuthenticated, mustSetPassword } = input
|
|
137
|
-
|
|
138
|
-
if (intent?.kind === 'expired') return { reason: 'recovery', expired: true, checking: false }
|
|
139
|
-
|
|
140
|
-
if (intent?.kind === 'recovery') {
|
|
141
|
-
if (isLoading) return { reason: 'recovery', expired: false, checking: true }
|
|
142
|
-
// A recovery link with no session behind it was already used or has expired.
|
|
143
|
-
return { reason: 'recovery', expired: !isAuthenticated, checking: false }
|
|
144
|
-
}
|
|
145
|
-
|
|
146
|
-
if (!isLoading && isAuthenticated && mustSetPassword) {
|
|
147
|
-
return { reason: 'invite', expired: false, checking: false }
|
|
148
|
-
}
|
|
149
|
-
|
|
150
|
-
return NOTHING
|
|
151
|
-
}
|
|
File without changes
|