@damiangilgonzalez/copypasta 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +227 -2
- package/catalog.yaml +140 -0
- package/cli/copypasta.js +4 -0
- package/cli/lib/catalog.js +131 -0
- package/cli/lib/commands.js +162 -0
- package/cli/lib/index.js +4 -0
- package/cli/lib/main.js +130 -0
- package/package.json +38 -4
- package/recipes/agents/agent-memory/RECIPE.md +75 -0
- package/recipes/agents/agent-memory/files/agentic/memory/__init__.py +25 -0
- package/recipes/agents/agent-memory/files/agentic/memory/base.py +101 -0
- package/recipes/agents/agent-memory/files/agentic/memory/factory.py +33 -0
- package/recipes/agents/agent-memory/files/agentic/memory/in_memory.py +59 -0
- package/recipes/agents/agent-memory/files/agentic/memory/models.py +66 -0
- package/recipes/agents/agent-memory/files/agentic/memory/settings.py +24 -0
- package/recipes/agents/agent-memory/files/agentic/memory/sql.py +177 -0
- package/recipes/agents/agent-memory/files/pytest.ini +5 -0
- package/recipes/agents/agent-memory/files/tests/__init__.py +0 -0
- package/recipes/agents/agent-memory/files/tests/memory_conformance.py +158 -0
- package/recipes/agents/agent-memory/files/tests/test_memory.py +74 -0
- package/recipes/agents/langchain-agent/RECIPE.md +101 -0
- package/recipes/agents/langchain-agent/files/agentic/__init__.py +10 -0
- package/recipes/agents/langchain-agent/files/agentic/agents/__init__.py +13 -0
- package/recipes/agents/langchain-agent/files/agentic/agents/agents.py +43 -0
- package/recipes/agents/langchain-agent/files/agentic/agents/base_agent.py +126 -0
- package/recipes/agents/langchain-agent/files/agentic/agents/models.py +46 -0
- package/recipes/agents/langchain-agent/files/agentic/context.py +21 -0
- package/recipes/agents/langchain-agent/files/agentic/llm/__init__.py +5 -0
- package/recipes/agents/langchain-agent/files/agentic/llm/models.py +45 -0
- package/recipes/agents/langchain-agent/files/agentic/llm/provider.py +78 -0
- package/recipes/agents/langchain-agent/files/agentic/llm/settings.py +62 -0
- package/recipes/agents/langchain-agent/files/agentic/middleware/__init__.py +3 -0
- package/recipes/agents/langchain-agent/files/agentic/middleware/language.py +28 -0
- package/recipes/agents/langchain-agent/files/agentic/prompts/__init__.py +3 -0
- package/recipes/agents/langchain-agent/files/agentic/prompts/assistant.en.yaml +15 -0
- package/recipes/agents/langchain-agent/files/agentic/prompts/assistant.es.yaml +15 -0
- package/recipes/agents/langchain-agent/files/agentic/prompts/loader.py +69 -0
- package/recipes/agents/langchain-agent/files/agentic/tools/__init__.py +25 -0
- package/recipes/agents/langchain-agent/files/agentic/tools/base_tool.py +62 -0
- package/recipes/agents/langchain-agent/files/agentic/tools/search_documents.py +42 -0
- package/recipes/agents/langchain-agent/files/pytest.ini +5 -0
- package/recipes/agents/langchain-agent/files/tests/__init__.py +0 -0
- package/recipes/agents/langchain-agent/files/tests/fakes.py +30 -0
- package/recipes/agents/langchain-agent/files/tests/test_agents.py +151 -0
- package/recipes/agents/langgraph-graph/RECIPE.md +63 -0
- package/recipes/agents/langgraph-graph/files/agentic/conversation.py +73 -0
- package/recipes/agents/langgraph-graph/files/agentic/graph/__init__.py +17 -0
- package/recipes/agents/langgraph-graph/files/agentic/graph/builder.py +37 -0
- package/recipes/agents/langgraph-graph/files/agentic/graph/edges.py +8 -0
- package/recipes/agents/langgraph-graph/files/agentic/graph/event_processor.py +48 -0
- package/recipes/agents/langgraph-graph/files/agentic/graph/events.py +30 -0
- package/recipes/agents/langgraph-graph/files/agentic/graph/graph.py +60 -0
- package/recipes/agents/langgraph-graph/files/agentic/graph/nodes.py +63 -0
- package/recipes/agents/langgraph-graph/files/agentic/graph/state.py +31 -0
- package/recipes/agents/langgraph-graph/files/agentic/registry.py +85 -0
- package/recipes/agents/langgraph-graph/files/tests/test_graph.py +145 -0
- package/recipes/backend/.gitkeep +0 -0
- package/recipes/backend/agent-chat-api/RECIPE.md +69 -0
- package/recipes/backend/agent-chat-api/files/api/agent/guards.py +35 -0
- package/recipes/backend/agent-chat-api/files/api/agent/router.py +86 -0
- package/recipes/backend/agent-chat-api/files/api/agent/sanitize.py +22 -0
- package/recipes/backend/agent-chat-api/files/api/agent/schemas.py +26 -0
- package/recipes/backend/agent-chat-api/files/api/agent/settings.py +14 -0
- package/recipes/backend/agent-chat-api/files/api/agent/tracing.py +38 -0
- package/recipes/backend/agent-chat-api/files/api/app.py +67 -0
- package/recipes/backend/agent-chat-api/files/api/auth.py +73 -0
- package/recipes/backend/agent-chat-api/files/pytest.ini +5 -0
- package/recipes/backend/agent-chat-api/files/tests/test_agent_api.py +237 -0
- package/recipes/backend/agent-feedback/RECIPE.md +63 -0
- package/recipes/backend/agent-feedback/files/api/feedback/__init__.py +0 -0
- package/recipes/backend/agent-feedback/files/api/feedback/router.py +72 -0
- package/recipes/backend/agent-feedback/files/api/feedback/schemas.py +44 -0
- package/recipes/backend/agent-feedback/files/feedback/__init__.py +25 -0
- package/recipes/backend/agent-feedback/files/feedback/base.py +53 -0
- package/recipes/backend/agent-feedback/files/feedback/factory.py +30 -0
- package/recipes/backend/agent-feedback/files/feedback/in_memory.py +29 -0
- package/recipes/backend/agent-feedback/files/feedback/models.py +48 -0
- package/recipes/backend/agent-feedback/files/feedback/settings.py +17 -0
- package/recipes/backend/agent-feedback/files/feedback/sql.py +102 -0
- package/recipes/backend/agent-feedback/files/pytest.ini +5 -0
- package/recipes/backend/agent-feedback/files/tests/feedback_conformance.py +89 -0
- package/recipes/backend/agent-feedback/files/tests/test_feedback.py +63 -0
- package/recipes/backend/agent-feedback/files/tests/test_feedback_api.py +95 -0
- package/recipes/backend/auth-verifier/RECIPE.md +63 -0
- package/recipes/backend/auth-verifier/files/api/auth.py +73 -0
- package/recipes/backend/auth-verifier/files/auth/__init__.py +23 -0
- package/recipes/backend/auth-verifier/files/auth/factory.py +28 -0
- package/recipes/backend/auth-verifier/files/auth/jwt_verifier.py +101 -0
- package/recipes/backend/auth-verifier/files/auth/models.py +29 -0
- package/recipes/backend/auth-verifier/files/auth/settings.py +45 -0
- package/recipes/backend/auth-verifier/files/auth/supabase.py +80 -0
- package/recipes/backend/auth-verifier/files/pytest.ini +5 -0
- package/recipes/backend/auth-verifier/files/tests/__init__.py +0 -0
- package/recipes/backend/auth-verifier/files/tests/test_auth.py +229 -0
- package/recipes/backend/conversation-history/RECIPE.md +49 -0
- package/recipes/backend/conversation-history/files/api/conversations/__init__.py +0 -0
- package/recipes/backend/conversation-history/files/api/conversations/router.py +55 -0
- package/recipes/backend/conversation-history/files/api/conversations/schemas.py +57 -0
- package/recipes/backend/conversation-history/files/pytest.ini +5 -0
- package/recipes/backend/conversation-history/files/tests/test_conversations_api.py +127 -0
- package/recipes/backend/fastapi-base/RECIPE.md +57 -0
- package/recipes/backend/fastapi-base/files/api/app.py +37 -0
- package/recipes/backend/fastapi-base/files/api/base.py +54 -0
- package/recipes/backend/fastapi-base/files/api/errors.py +31 -0
- package/recipes/backend/fastapi-base/files/api/health.py +19 -0
- package/recipes/backend/fastapi-base/files/api/logging_setup.py +26 -0
- package/recipes/backend/fastapi-base/files/api/request_id.py +62 -0
- package/recipes/backend/fastapi-base/files/api/settings.py +32 -0
- package/recipes/backend/fastapi-base/files/pytest.ini +5 -0
- package/recipes/backend/fastapi-base/files/tests/__init__.py +0 -0
- package/recipes/backend/fastapi-base/files/tests/test_api_base.py +136 -0
- package/recipes/backend/observability/RECIPE.md +68 -0
- package/recipes/backend/observability/files/observability/__init__.py +34 -0
- package/recipes/backend/observability/files/observability/factory.py +73 -0
- package/recipes/backend/observability/files/observability/langfuse_tracer.py +29 -0
- package/recipes/backend/observability/files/observability/langsmith_tracer.py +23 -0
- package/recipes/backend/observability/files/observability/models.py +90 -0
- package/recipes/backend/observability/files/observability/opik_tracer.py +30 -0
- package/recipes/backend/observability/files/observability/settings.py +58 -0
- package/recipes/backend/observability/files/observability/tracer.py +142 -0
- package/recipes/backend/observability/files/observability/usage.py +61 -0
- package/recipes/backend/observability/files/pytest.ini +5 -0
- package/recipes/backend/observability/files/tests/__init__.py +0 -0
- package/recipes/backend/observability/files/tests/test_observability.py +219 -0
- package/recipes/backend/project-settings/RECIPE.md +40 -0
- package/recipes/backend/project-settings/files/.env.example +7 -0
- package/recipes/backend/project-settings/files/core/__init__.py +0 -0
- package/recipes/backend/project-settings/files/core/config.py +41 -0
- package/recipes/backend/project-settings/files/pytest.ini +3 -0
- package/recipes/backend/project-settings/files/tests/__init__.py +0 -0
- package/recipes/backend/project-settings/files/tests/test_settings.py +44 -0
- package/recipes/backend/rag-retriever/RECIPE.md +79 -0
- package/recipes/backend/rag-retriever/files/pytest.ini +5 -0
- package/recipes/backend/rag-retriever/files/rag/__init__.py +53 -0
- package/recipes/backend/rag-retriever/files/rag/base.py +106 -0
- package/recipes/backend/rag-retriever/files/rag/chunking.py +84 -0
- package/recipes/backend/rag-retriever/files/rag/document_search.py +60 -0
- package/recipes/backend/rag-retriever/files/rag/embeddings.py +91 -0
- package/recipes/backend/rag-retriever/files/rag/factory.py +82 -0
- package/recipes/backend/rag-retriever/files/rag/in_memory.py +52 -0
- package/recipes/backend/rag-retriever/files/rag/models.py +107 -0
- package/recipes/backend/rag-retriever/files/rag/pgvector.py +138 -0
- package/recipes/backend/rag-retriever/files/rag/qdrant.py +96 -0
- package/recipes/backend/rag-retriever/files/rag/settings.py +48 -0
- package/recipes/backend/rag-retriever/files/tests/__init__.py +0 -0
- package/recipes/backend/rag-retriever/files/tests/rag_conformance.py +95 -0
- package/recipes/backend/rag-retriever/files/tests/test_rag.py +270 -0
- package/recipes/backend/rate-limit-quota/RECIPE.md +77 -0
- package/recipes/backend/rate-limit-quota/files/api/agent/guards.py +62 -0
- package/recipes/backend/rate-limit-quota/files/api/limits/__init__.py +0 -0
- package/recipes/backend/rate-limit-quota/files/api/limits/router.py +38 -0
- package/recipes/backend/rate-limit-quota/files/limits/__init__.py +43 -0
- package/recipes/backend/rate-limit-quota/files/limits/base.py +161 -0
- package/recipes/backend/rate-limit-quota/files/limits/factory.py +69 -0
- package/recipes/backend/rate-limit-quota/files/limits/in_memory.py +36 -0
- package/recipes/backend/rate-limit-quota/files/limits/models.py +108 -0
- package/recipes/backend/rate-limit-quota/files/limits/settings.py +32 -0
- package/recipes/backend/rate-limit-quota/files/limits/sql.py +94 -0
- package/recipes/backend/rate-limit-quota/files/pytest.ini +5 -0
- package/recipes/backend/rate-limit-quota/files/tests/limits_conformance.py +146 -0
- package/recipes/backend/rate-limit-quota/files/tests/test_limits.py +167 -0
- package/recipes/backend/rate-limit-quota/files/tests/test_limits_api.py +100 -0
- package/recipes/backend/voice-providers/RECIPE.md +73 -0
- package/recipes/backend/voice-providers/files/api/__init__.py +0 -0
- package/recipes/backend/voice-providers/files/api/voice/__init__.py +0 -0
- package/recipes/backend/voice-providers/files/api/voice/router.py +113 -0
- package/recipes/backend/voice-providers/files/pytest.ini +5 -0
- package/recipes/backend/voice-providers/files/tests/__init__.py +0 -0
- package/recipes/backend/voice-providers/files/tests/fake_openai.py +44 -0
- package/recipes/backend/voice-providers/files/tests/test_voice.py +164 -0
- package/recipes/backend/voice-providers/files/tests/test_voice_api.py +106 -0
- package/recipes/backend/voice-providers/files/tests/voice_conformance.py +80 -0
- package/recipes/backend/voice-providers/files/voice/__init__.py +29 -0
- package/recipes/backend/voice-providers/files/voice/base.py +116 -0
- package/recipes/backend/voice-providers/files/voice/factory.py +48 -0
- package/recipes/backend/voice-providers/files/voice/fake.py +51 -0
- package/recipes/backend/voice-providers/files/voice/models.py +85 -0
- package/recipes/backend/voice-providers/files/voice/openai_provider.py +116 -0
- package/recipes/backend/voice-providers/files/voice/settings.py +48 -0
- package/recipes/frontend/.gitkeep +0 -0
- package/recipes/frontend/playwright-e2e/RECIPE.md +48 -0
- package/recipes/frontend/playwright-e2e/files/.github/workflows/frontend.yml +35 -0
- package/recipes/frontend/playwright-e2e/files/e2e/helpers.ts +25 -0
- package/recipes/frontend/playwright-e2e/files/e2e/home.spec.ts +10 -0
- package/recipes/frontend/playwright-e2e/files/e2e/login.spec.ts +26 -0
- package/recipes/frontend/playwright-e2e/files/e2e/navigation.spec.ts +27 -0
- package/recipes/frontend/playwright-e2e/files/playwright.config.ts +35 -0
- package/recipes/frontend/react-agent-chat/RECIPE.md +69 -0
- package/recipes/frontend/react-agent-chat/files/src/features/chat/chat-api.ts +27 -0
- package/recipes/frontend/react-agent-chat/files/src/features/chat/chat.css +18 -0
- package/recipes/frontend/react-agent-chat/files/src/features/chat/chat.test.tsx +139 -0
- package/recipes/frontend/react-agent-chat/files/src/features/chat/components/ChatView.tsx +22 -0
- package/recipes/frontend/react-agent-chat/files/src/features/chat/components/Composer.tsx +40 -0
- package/recipes/frontend/react-agent-chat/files/src/features/chat/components/Markdown.tsx +20 -0
- package/recipes/frontend/react-agent-chat/files/src/features/chat/components/MessageList.tsx +42 -0
- package/recipes/frontend/react-agent-chat/files/src/features/chat/events.ts +42 -0
- package/recipes/frontend/react-agent-chat/files/src/features/chat/fake-chat-api.ts +44 -0
- package/recipes/frontend/react-agent-chat/files/src/features/chat/index.ts +6 -0
- package/recipes/frontend/react-agent-chat/files/src/features/chat/sse-parser.test.ts +97 -0
- package/recipes/frontend/react-agent-chat/files/src/features/chat/sse-parser.ts +85 -0
- package/recipes/frontend/react-agent-chat/files/src/features/chat/use-chat.ts +136 -0
- package/recipes/frontend/react-app-router/RECIPE.md +58 -0
- package/recipes/frontend/react-app-router/files/src/App.test.tsx +54 -0
- package/recipes/frontend/react-app-router/files/src/App.tsx +14 -0
- package/recipes/frontend/react-app-router/files/src/router/ErrorScreen.tsx +21 -0
- package/recipes/frontend/react-app-router/files/src/router/Layout.tsx +28 -0
- package/recipes/frontend/react-app-router/files/src/router/NotFoundScreen.tsx +12 -0
- package/recipes/frontend/react-app-router/files/src/router/index.ts +1 -0
- package/recipes/frontend/react-app-router/files/src/router/router.css +29 -0
- package/recipes/frontend/react-app-router/files/src/router/router.test.tsx +65 -0
- package/recipes/frontend/react-app-router/files/src/router/routes.tsx +59 -0
- package/recipes/frontend/react-app-router/files/src/screens/SettingsScreen.tsx +10 -0
- package/recipes/frontend/react-supabase-auth/RECIPE.md +77 -0
- package/recipes/frontend/react-supabase-auth/files/src/auth/LoginScreen.tsx +64 -0
- package/recipes/frontend/react-supabase-auth/files/src/auth/SignOutButton.tsx +12 -0
- package/recipes/frontend/react-supabase-auth/files/src/auth/auth.css +33 -0
- package/recipes/frontend/react-supabase-auth/files/src/auth/auth.test.ts +149 -0
- package/recipes/frontend/react-supabase-auth/files/src/auth/auth.ts +59 -0
- package/recipes/frontend/react-supabase-auth/files/src/auth/fake-auth.ts +87 -0
- package/recipes/frontend/react-supabase-auth/files/src/auth/fake-gotrue.ts +85 -0
- package/recipes/frontend/react-supabase-auth/files/src/auth/index.ts +7 -0
- package/recipes/frontend/react-supabase-auth/files/src/auth/make-auth.ts +20 -0
- package/recipes/frontend/react-supabase-auth/files/src/auth/session-context.tsx +35 -0
- package/recipes/frontend/react-supabase-auth/files/src/auth/session-store.ts +63 -0
- package/recipes/frontend/react-supabase-auth/files/src/auth/session.test.tsx +56 -0
- package/recipes/frontend/react-supabase-auth/files/src/auth/settings.ts +30 -0
- package/recipes/frontend/react-supabase-auth/files/src/auth/supabase-auth.ts +85 -0
- package/recipes/frontend/vite-react-base/RECIPE.md +69 -0
- package/recipes/frontend/vite-react-base/files/.env +6 -0
- package/recipes/frontend/vite-react-base/files/.env.fake +2 -0
- package/recipes/frontend/vite-react-base/files/index.html +12 -0
- package/recipes/frontend/vite-react-base/files/package.json +30 -0
- package/recipes/frontend/vite-react-base/files/src/App.test.tsx +49 -0
- package/recipes/frontend/vite-react-base/files/src/App.tsx +13 -0
- package/recipes/frontend/vite-react-base/files/src/api/api.ts +37 -0
- package/recipes/frontend/vite-react-base/files/src/api/fake/fake-api.ts +29 -0
- package/recipes/frontend/vite-react-base/files/src/api/http-api.ts +16 -0
- package/recipes/frontend/vite-react-base/files/src/api/http-client.test.ts +84 -0
- package/recipes/frontend/vite-react-base/files/src/api/http-client.ts +94 -0
- package/recipes/frontend/vite-react-base/files/src/api/make-api.ts +30 -0
- package/recipes/frontend/vite-react-base/files/src/api/types.ts +7 -0
- package/recipes/frontend/vite-react-base/files/src/app-context.tsx +24 -0
- package/recipes/frontend/vite-react-base/files/src/auth/token-provider.ts +27 -0
- package/recipes/frontend/vite-react-base/files/src/config.ts +18 -0
- package/recipes/frontend/vite-react-base/files/src/hooks/use-load.ts +46 -0
- package/recipes/frontend/vite-react-base/files/src/main.tsx +27 -0
- package/recipes/frontend/vite-react-base/files/src/screens/HomeScreen.tsx +28 -0
- package/recipes/frontend/vite-react-base/files/src/styles/global.css +25 -0
- package/recipes/frontend/vite-react-base/files/src/styles/tokens.css +33 -0
- package/recipes/frontend/vite-react-base/files/src/styles/tokens.test.ts +45 -0
- package/recipes/frontend/vite-react-base/files/src/test-setup.ts +8 -0
- package/recipes/frontend/vite-react-base/files/src/vite-env.d.ts +11 -0
- package/recipes/frontend/vite-react-base/files/tsconfig.json +18 -0
- package/recipes/frontend/vite-react-base/files/vite.config.ts +19 -0
- package/unpacked-files.json +3 -0
|
@@ -0,0 +1,149 @@
|
|
|
1
|
+
import { describe, expect, it } from 'vitest'
|
|
2
|
+
|
|
3
|
+
import { AuthError, tokenProviderOf, type Auth } from './auth'
|
|
4
|
+
import { createFakeAuth } from './fake-auth'
|
|
5
|
+
import { FakeGoTrue } from './fake-gotrue'
|
|
6
|
+
import { makeAuth } from './make-auth'
|
|
7
|
+
import { createSessionStore } from './session-store'
|
|
8
|
+
import { authSettings } from './settings'
|
|
9
|
+
import { createSupabaseAuth } from './supabase-auth'
|
|
10
|
+
|
|
11
|
+
const ANA = { email: 'ana@example.com', password: 'secret' }
|
|
12
|
+
|
|
13
|
+
/** What every `Auth` must do. A new provider = one more `describe` with its builder. */
|
|
14
|
+
function conformance(name: string, build: () => Auth) {
|
|
15
|
+
describe(`${name} conformance`, () => {
|
|
16
|
+
it('starts signed out and signs in with email and password', async () => {
|
|
17
|
+
const auth = build()
|
|
18
|
+
expect(await auth.getSession()).toBeNull()
|
|
19
|
+
const session = await auth.signIn(ANA)
|
|
20
|
+
expect(session.accessToken).toBeTruthy()
|
|
21
|
+
expect(session.user.email).toBe(ANA.email)
|
|
22
|
+
expect(await auth.getSession()).toEqual(session)
|
|
23
|
+
})
|
|
24
|
+
|
|
25
|
+
it('rejects a wrong password with a code, never the provider message', async () => {
|
|
26
|
+
const auth = build()
|
|
27
|
+
const error = await auth.signIn({ ...ANA, password: 'wrong' }).catch((reason: unknown) => reason)
|
|
28
|
+
expect(error).toBeInstanceOf(AuthError)
|
|
29
|
+
expect((error as AuthError).code).toBe('invalid_credentials')
|
|
30
|
+
expect(String(error)).not.toContain('Invalid login')
|
|
31
|
+
})
|
|
32
|
+
|
|
33
|
+
it('keeps the session across instances (a reload) and clears it on sign out', async () => {
|
|
34
|
+
await build().signIn(ANA)
|
|
35
|
+
const again = build()
|
|
36
|
+
expect((await again.getSession())?.user.email).toBe(ANA.email)
|
|
37
|
+
await again.signOut()
|
|
38
|
+
expect(await again.getSession()).toBeNull()
|
|
39
|
+
expect(await build().getSession()).toBeNull()
|
|
40
|
+
})
|
|
41
|
+
|
|
42
|
+
it('refreshes to a new token and tells listeners', async () => {
|
|
43
|
+
const auth = build()
|
|
44
|
+
const seen: (string | null)[] = []
|
|
45
|
+
const stop = auth.onChange((session) => seen.push(session?.accessToken ?? null))
|
|
46
|
+
const first = (await auth.signIn(ANA)).accessToken
|
|
47
|
+
const refreshed = await auth.refresh()
|
|
48
|
+
expect(refreshed?.accessToken).toBeTruthy()
|
|
49
|
+
expect(refreshed?.accessToken).not.toBe(first)
|
|
50
|
+
await auth.signOut()
|
|
51
|
+
stop()
|
|
52
|
+
expect(seen).toContain(first)
|
|
53
|
+
expect(seen[seen.length - 1]).toBeNull()
|
|
54
|
+
})
|
|
55
|
+
|
|
56
|
+
it('refresh without a session is null, not an error', async () => {
|
|
57
|
+
expect(await build().refresh()).toBeNull()
|
|
58
|
+
})
|
|
59
|
+
|
|
60
|
+
it('is a TokenProvider for the HTTP client', async () => {
|
|
61
|
+
const auth = build()
|
|
62
|
+
const tokens = tokenProviderOf(auth)
|
|
63
|
+
expect(await tokens.getToken()).toBeNull()
|
|
64
|
+
const { accessToken } = await auth.signIn(ANA)
|
|
65
|
+
expect(await tokens.getToken()).toBe(accessToken)
|
|
66
|
+
expect(await tokens.refresh()).not.toBeNull()
|
|
67
|
+
})
|
|
68
|
+
})
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
conformance('fake auth', () => createFakeAuth({ users: [{ id: 'u-ana', ...ANA }], latencyMs: 0 }))
|
|
72
|
+
|
|
73
|
+
const gotrue = { current: new FakeGoTrue() }
|
|
74
|
+
conformance('supabase auth', () => createSupabaseAuth({ url: 'http://localhost:54321', anonKey: 'anon-key', fetcher: gotrue.current.fetch }))
|
|
75
|
+
|
|
76
|
+
describe('supabase auth over HTTP', () => {
|
|
77
|
+
const build = (server: FakeGoTrue) => createSupabaseAuth({ url: 'http://localhost:54321', anonKey: 'anon-key', fetcher: server.fetch })
|
|
78
|
+
|
|
79
|
+
it('sends the password grant with the anon key and the refresh grant with the refresh token', async () => {
|
|
80
|
+
const server = new FakeGoTrue()
|
|
81
|
+
const auth = build(server)
|
|
82
|
+
await auth.signIn({ email: ' Ana@example.com '.toLowerCase(), password: 'secret' })
|
|
83
|
+
await auth.refresh()
|
|
84
|
+
const [login, refresh] = server.requests.filter((r) => r.path.endsWith('/token'))
|
|
85
|
+
expect(login).toMatchObject({ grant: 'password', apikey: 'anon-key', body: { email: 'ana@example.com', password: 'secret' } })
|
|
86
|
+
expect(refresh.grant).toBe('refresh_token')
|
|
87
|
+
expect(String(refresh.body.refresh_token)).toMatch(/^refresh-/)
|
|
88
|
+
})
|
|
89
|
+
|
|
90
|
+
it('a refresh token GoTrue rejects ends the session', async () => {
|
|
91
|
+
const accepted = new Set<string>()
|
|
92
|
+
const auth = build(new FakeGoTrue({ refreshTokens: accepted }))
|
|
93
|
+
await auth.signIn(ANA)
|
|
94
|
+
accepted.clear() // revoked on the server (signed out elsewhere, password changed)
|
|
95
|
+
expect(await auth.refresh()).toBeNull()
|
|
96
|
+
expect(await auth.getSession()).toBeNull()
|
|
97
|
+
})
|
|
98
|
+
|
|
99
|
+
it('maps 429 and 5xx to codes without the message', async () => {
|
|
100
|
+
const limited = await build(new FakeGoTrue({ failWith: 429 })).signIn(ANA).catch((reason: unknown) => reason as AuthError)
|
|
101
|
+
expect(limited).toMatchObject({ code: 'rate_limited' })
|
|
102
|
+
const down = await build(new FakeGoTrue({ failWith: 503 })).signIn(ANA).catch((reason: unknown) => reason as AuthError)
|
|
103
|
+
expect(down).toMatchObject({ code: 'unavailable' })
|
|
104
|
+
expect(String(down)).not.toContain('secret details')
|
|
105
|
+
})
|
|
106
|
+
})
|
|
107
|
+
|
|
108
|
+
describe('session store', () => {
|
|
109
|
+
it('goes loading -> signed_out -> signed_in -> expired', async () => {
|
|
110
|
+
const auth = createFakeAuth({ latencyMs: 0 })
|
|
111
|
+
const store = createSessionStore(auth)
|
|
112
|
+
const statuses: string[] = []
|
|
113
|
+
store.subscribe(() => statuses.push(store.getState().status))
|
|
114
|
+
expect(store.getState().status).toBe('loading')
|
|
115
|
+
const stop = await store.start()
|
|
116
|
+
expect(store.getState().status).toBe('signed_out')
|
|
117
|
+
await store.signIn({ email: 'demo@example.com', password: 'demo' })
|
|
118
|
+
expect(store.getState()).toMatchObject({ status: 'signed_in', expired: false })
|
|
119
|
+
store.expire()
|
|
120
|
+
expect(store.getState()).toMatchObject({ status: 'signed_out', session: null, expired: true })
|
|
121
|
+
expect(await auth.getSession()).toBeNull()
|
|
122
|
+
await store.signIn({ email: 'demo@example.com', password: 'demo' })
|
|
123
|
+
expect(store.getState().expired).toBe(false)
|
|
124
|
+
stop()
|
|
125
|
+
expect(statuses).toEqual(['signed_out', 'signed_in', 'signed_in', 'signed_out', 'signed_out', 'signed_in', 'signed_in'])
|
|
126
|
+
})
|
|
127
|
+
|
|
128
|
+
it('follows a sign out made elsewhere (another tab)', async () => {
|
|
129
|
+
const auth = createFakeAuth({ latencyMs: 0 })
|
|
130
|
+
const store = createSessionStore(auth)
|
|
131
|
+
await store.start()
|
|
132
|
+
await auth.signIn({ email: 'demo@example.com', password: 'demo' })
|
|
133
|
+
expect(store.getState().status).toBe('signed_in')
|
|
134
|
+
await auth.signOut()
|
|
135
|
+
expect(store.getState().status).toBe('signed_out')
|
|
136
|
+
})
|
|
137
|
+
})
|
|
138
|
+
|
|
139
|
+
describe('settings and factory', () => {
|
|
140
|
+
it('requires the provider and the supabase keys', async () => {
|
|
141
|
+
expect(() => authSettings({})).toThrow('VITE_AUTH_PROVIDER')
|
|
142
|
+
expect(() => authSettings({ VITE_AUTH_PROVIDER: 'supabase' })).toThrow('VITE_SUPABASE_URL')
|
|
143
|
+
expect(authSettings({ VITE_AUTH_PROVIDER: 'fake' })).toEqual({ provider: 'fake' })
|
|
144
|
+
const auth = await makeAuth(authSettings({ VITE_AUTH_PROVIDER: 'fake' }))
|
|
145
|
+
expect((await auth.signIn({ email: 'demo@example.com', password: 'demo' })).user.email).toBe('demo@example.com')
|
|
146
|
+
const supabase = await makeAuth({ provider: 'supabase', supabaseUrl: 'http://localhost:54321', supabaseAnonKey: 'k' })
|
|
147
|
+
expect(await supabase.getSession()).toBeNull()
|
|
148
|
+
})
|
|
149
|
+
})
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Auth contract of the app: who is signed in and where the bearer token comes from.
|
|
3
|
+
* Two implementations, same type: `createSupabaseAuth` (supabase-js) and `createFakeAuth` (in memory, persisted
|
|
4
|
+
* in localStorage so a reload keeps you in). `makeAuth` picks one from the settings (VITE_AUTH_PROVIDER).
|
|
5
|
+
*
|
|
6
|
+
* Screens never import supabase-js: they use `useSession()` (session-context.tsx), and the HTTP client only
|
|
7
|
+
* sees a `TokenProvider` (`tokenProviderOf(auth)`).
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
import type { TokenProvider } from './token-provider'
|
|
11
|
+
|
|
12
|
+
export type AuthUser = {
|
|
13
|
+
id: string
|
|
14
|
+
email: string
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
export type Session = {
|
|
18
|
+
accessToken: string
|
|
19
|
+
user: AuthUser
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export type Credentials = {
|
|
23
|
+
email: string
|
|
24
|
+
password: string
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** Stable codes: the login screen shows a message per code, never the provider's text. */
|
|
28
|
+
export type AuthErrorCode = 'invalid_credentials' | 'email_not_confirmed' | 'rate_limited' | 'unavailable'
|
|
29
|
+
|
|
30
|
+
export class AuthError extends Error {
|
|
31
|
+
constructor(
|
|
32
|
+
readonly code: AuthErrorCode,
|
|
33
|
+
readonly cause?: unknown,
|
|
34
|
+
) {
|
|
35
|
+
super(`Auth error: ${code}`)
|
|
36
|
+
this.name = 'AuthError'
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
export type Auth = {
|
|
41
|
+
/** The stored session, or null when signed out. Never throws: a broken store is "signed out". */
|
|
42
|
+
getSession(): Promise<Session | null>
|
|
43
|
+
/** Email + password. Throws `AuthError`. */
|
|
44
|
+
signIn(credentials: Credentials): Promise<Session>
|
|
45
|
+
/** Clears the local session first; telling the provider is best effort. Never throws. */
|
|
46
|
+
signOut(): Promise<void>
|
|
47
|
+
/** New access token with the refresh token. Null = the session is over. Never throws. */
|
|
48
|
+
refresh(): Promise<Session | null>
|
|
49
|
+
/** Fires with the new session on sign in, refresh and sign out. Returns the unsubscribe. */
|
|
50
|
+
onChange(listener: (session: Session | null) => void): () => void
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** What the HTTP client needs, taken from the auth. */
|
|
54
|
+
export function tokenProviderOf(auth: Auth): TokenProvider {
|
|
55
|
+
return {
|
|
56
|
+
getToken: async () => (await auth.getSession())?.accessToken ?? null,
|
|
57
|
+
refresh: async () => (await auth.refresh())?.accessToken ?? null,
|
|
58
|
+
}
|
|
59
|
+
}
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* In-memory `Auth`: the app signs in with no Supabase (VITE_AUTH_PROVIDER=fake). Used by demos, tests and e2e.
|
|
3
|
+
* The session is kept in `storage` (localStorage by default) so a reload keeps you signed in, like the real one.
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
import { AuthError, type Auth, type Credentials, type Session } from './auth'
|
|
7
|
+
|
|
8
|
+
export type FakeUser = Credentials & { id?: string }
|
|
9
|
+
|
|
10
|
+
export type FakeAuthOptions = {
|
|
11
|
+
/** Accounts that can sign in. Default: `demo@example.com` / `demo`. */
|
|
12
|
+
users?: FakeUser[]
|
|
13
|
+
storage?: Pick<Storage, 'getItem' | 'setItem' | 'removeItem'>
|
|
14
|
+
storageKey?: string
|
|
15
|
+
/** Simulated latency in ms. 0 in tests. */
|
|
16
|
+
latencyMs?: number
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export const FAKE_USER: FakeUser = { id: 'user-1', email: 'demo@example.com', password: 'demo' }
|
|
20
|
+
|
|
21
|
+
export function createFakeAuth(options: FakeAuthOptions = {}): Auth {
|
|
22
|
+
const { users = [FAKE_USER], storageKey = 'fake-auth.session', latencyMs = 100 } = options
|
|
23
|
+
const storage = options.storage ?? memoryStorage()
|
|
24
|
+
const listeners = new Set<(session: Session | null) => void>()
|
|
25
|
+
const wait = () => new Promise((resolve) => setTimeout(resolve, latencyMs))
|
|
26
|
+
let issued = 0
|
|
27
|
+
|
|
28
|
+
function read(): Session | null {
|
|
29
|
+
try {
|
|
30
|
+
const raw = storage.getItem(storageKey)
|
|
31
|
+
return raw ? (JSON.parse(raw) as Session) : null
|
|
32
|
+
} catch {
|
|
33
|
+
return null
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
function write(session: Session | null) {
|
|
38
|
+
if (session) storage.setItem(storageKey, JSON.stringify(session))
|
|
39
|
+
else storage.removeItem(storageKey)
|
|
40
|
+
listeners.forEach((listener) => listener(session))
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
return {
|
|
44
|
+
async getSession() {
|
|
45
|
+
return read()
|
|
46
|
+
},
|
|
47
|
+
|
|
48
|
+
async signIn({ email, password }) {
|
|
49
|
+
await wait()
|
|
50
|
+
const user = users.find((candidate) => candidate.email === email.trim().toLowerCase())
|
|
51
|
+
if (!user || user.password !== password) throw new AuthError('invalid_credentials')
|
|
52
|
+
const session: Session = {
|
|
53
|
+
accessToken: `fake-token-${++issued}`,
|
|
54
|
+
user: { id: user.id ?? `user-${user.email}`, email: user.email },
|
|
55
|
+
}
|
|
56
|
+
write(session)
|
|
57
|
+
return session
|
|
58
|
+
},
|
|
59
|
+
|
|
60
|
+
async signOut() {
|
|
61
|
+
write(null)
|
|
62
|
+
},
|
|
63
|
+
|
|
64
|
+
async refresh() {
|
|
65
|
+
const current = read()
|
|
66
|
+
if (!current) return null
|
|
67
|
+
const session = { ...current, accessToken: `fake-token-${++issued}` }
|
|
68
|
+
write(session)
|
|
69
|
+
return session
|
|
70
|
+
},
|
|
71
|
+
|
|
72
|
+
onChange(listener) {
|
|
73
|
+
listeners.add(listener)
|
|
74
|
+
return () => listeners.delete(listener)
|
|
75
|
+
},
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
function memoryStorage(): Pick<Storage, 'getItem' | 'setItem' | 'removeItem'> {
|
|
80
|
+
if (typeof localStorage !== 'undefined') return localStorage
|
|
81
|
+
const map = new Map<string, string>()
|
|
82
|
+
return {
|
|
83
|
+
getItem: (key) => map.get(key) ?? null,
|
|
84
|
+
setItem: (key, value) => void map.set(key, value),
|
|
85
|
+
removeItem: (key) => void map.delete(key),
|
|
86
|
+
}
|
|
87
|
+
}
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Supabase Auth (GoTrue) at the HTTP level for tests: the real supabase-js runs, only `fetch` is replaced.
|
|
3
|
+
* That way the tests check what is actually sent (grant type, apikey, refresh token) and how real answers
|
|
4
|
+
* (session JSON, `error_code`) are handled. Not shipped: it is only imported by tests.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
export type FakeGoTrueOptions = {
|
|
8
|
+
users?: Record<string, string> // email -> password
|
|
9
|
+
/** Answers every request with this status (to simulate 429 or 503). */
|
|
10
|
+
failWith?: number
|
|
11
|
+
/** Refresh tokens that GoTrue still accepts. */
|
|
12
|
+
refreshTokens?: Set<string>
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
export class FakeGoTrue {
|
|
16
|
+
readonly requests: { path: string; grant: string | null; apikey: string | null; body: Record<string, unknown> }[] = []
|
|
17
|
+
private readonly users: Record<string, string>
|
|
18
|
+
private readonly refreshTokens: Set<string>
|
|
19
|
+
private counter = 0
|
|
20
|
+
|
|
21
|
+
constructor(private readonly options: FakeGoTrueOptions = {}) {
|
|
22
|
+
this.users = options.users ?? { 'ana@example.com': 'secret' }
|
|
23
|
+
this.refreshTokens = options.refreshTokens ?? new Set()
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/** Pass as `fetcher` to `createSupabaseAuth`. */
|
|
27
|
+
readonly fetch: typeof fetch = async (input, init) => {
|
|
28
|
+
const url = new URL(typeof input === 'string' ? input : input instanceof URL ? input.href : input.url)
|
|
29
|
+
const headers = new Headers(init?.headers)
|
|
30
|
+
const body = init?.body ? (JSON.parse(String(init.body)) as Record<string, unknown>) : {}
|
|
31
|
+
this.requests.push({ path: url.pathname, grant: url.searchParams.get('grant_type'), apikey: headers.get('apikey'), body })
|
|
32
|
+
|
|
33
|
+
if (this.options.failWith) return error(this.options.failWith, 'unexpected_failure', 'nope: secret details')
|
|
34
|
+
if (url.pathname.endsWith('/token')) {
|
|
35
|
+
if (url.searchParams.get('grant_type') === 'password') {
|
|
36
|
+
const email = String(body.email)
|
|
37
|
+
if (this.users[email] !== body.password) return error(400, 'invalid_credentials', 'Invalid login credentials')
|
|
38
|
+
return json(this.session(email))
|
|
39
|
+
}
|
|
40
|
+
if (url.searchParams.get('grant_type') === 'refresh_token') {
|
|
41
|
+
const token = String(body.refresh_token)
|
|
42
|
+
if (!this.refreshTokens.delete(token)) return error(400, 'refresh_token_not_found', 'Invalid Refresh Token')
|
|
43
|
+
return json(this.session(token.split(':')[1]))
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
if (url.pathname.endsWith('/logout')) return new Response(null, { status: 204 })
|
|
47
|
+
if (url.pathname.endsWith('/user')) return json(this.user(String(headers.get('authorization')).split(':')[1] ?? ''))
|
|
48
|
+
return error(404, 'not_found', url.pathname)
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
private session(email: string) {
|
|
52
|
+
const refresh = `refresh-${++this.counter}:${email}`
|
|
53
|
+
this.refreshTokens.add(refresh)
|
|
54
|
+
const now = Math.floor(Date.now() / 1000)
|
|
55
|
+
return {
|
|
56
|
+
access_token: jwt({ sub: this.user(email).id, email, role: 'authenticated', aud: 'authenticated', exp: now + 3600, iat: now, jti: this.counter }),
|
|
57
|
+
token_type: 'bearer',
|
|
58
|
+
expires_in: 3600,
|
|
59
|
+
expires_at: now + 3600,
|
|
60
|
+
refresh_token: refresh,
|
|
61
|
+
user: this.user(email),
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
private user(email: string) {
|
|
66
|
+
return { id: `id-${email}`, aud: 'authenticated', role: 'authenticated', email, app_metadata: {}, user_metadata: {}, created_at: '' }
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/** A token with the shape of a JWT (supabase-js reads `exp` from it). Unsigned: only for tests. */
|
|
71
|
+
function jwt(claims: Record<string, unknown>): string {
|
|
72
|
+
const part = (value: unknown) => btoa(JSON.stringify(value)).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '')
|
|
73
|
+
return `${part({ alg: 'HS256', typ: 'JWT' })}.${part(claims)}.sig`
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
function json(data: unknown, status = 200): Response {
|
|
77
|
+
return new Response(JSON.stringify(data), { status, headers: { 'content-type': 'application/json' } })
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
function error(status: number, code: string, msg: string): Response {
|
|
81
|
+
return new Response(JSON.stringify({ code: status, error_code: code, msg }), {
|
|
82
|
+
status,
|
|
83
|
+
headers: { 'content-type': 'application/json', 'x-sb-error-code': code },
|
|
84
|
+
})
|
|
85
|
+
}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
export { AuthError, tokenProviderOf, type Auth, type AuthErrorCode, type Credentials, type Session } from './auth'
|
|
2
|
+
export { LoginScreen } from './LoginScreen'
|
|
3
|
+
export { makeAuth } from './make-auth'
|
|
4
|
+
export { RequireSession, SessionProvider, useSession } from './session-context'
|
|
5
|
+
export { createSessionStore, type SessionState, type SessionStore } from './session-store'
|
|
6
|
+
export { authSettings, type AuthProvider, type AuthSettings } from './settings'
|
|
7
|
+
export { SignOutButton } from './SignOutButton'
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Factory: builds the `Auth` the settings name (VITE_AUTH_PROVIDER). Both implementations are dynamic
|
|
3
|
+
* imports: supabase-js is a separate chunk the fake build never downloads, and vice versa.
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
import type { Auth } from './auth'
|
|
7
|
+
import type { AuthSettings } from './settings'
|
|
8
|
+
|
|
9
|
+
export async function makeAuth(settings: AuthSettings): Promise<Auth> {
|
|
10
|
+
switch (settings.provider) {
|
|
11
|
+
case 'supabase': {
|
|
12
|
+
const { createSupabaseAuth } = await import('./supabase-auth')
|
|
13
|
+
return createSupabaseAuth({ url: settings.supabaseUrl!, anonKey: settings.supabaseAnonKey! })
|
|
14
|
+
}
|
|
15
|
+
case 'fake': {
|
|
16
|
+
const { createFakeAuth } = await import('./fake-auth')
|
|
17
|
+
return createFakeAuth()
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
}
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* React binding of the session store: `useSession()` for screens and `<RequireSession>` as the guard.
|
|
3
|
+
* The guard renders the login until there is a session; it does not depend on any router.
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
import { createContext, useContext, useEffect, useSyncExternalStore, type ReactNode } from 'react'
|
|
7
|
+
|
|
8
|
+
import { LoginScreen } from './LoginScreen'
|
|
9
|
+
import type { SessionState, SessionStore } from './session-store'
|
|
10
|
+
|
|
11
|
+
const SessionContext = createContext<SessionStore | null>(null)
|
|
12
|
+
|
|
13
|
+
export function SessionProvider({ store, children }: { store: SessionStore; children: ReactNode }) {
|
|
14
|
+
useEffect(() => {
|
|
15
|
+
let stop: (() => void) | undefined
|
|
16
|
+
void store.start().then((unsubscribe) => (stop = unsubscribe))
|
|
17
|
+
return () => stop?.()
|
|
18
|
+
}, [store])
|
|
19
|
+
return <SessionContext.Provider value={store}>{children}</SessionContext.Provider>
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export function useSession(): SessionState & Pick<SessionStore, 'signIn' | 'signOut'> {
|
|
23
|
+
const store = useContext(SessionContext)
|
|
24
|
+
if (!store) throw new Error('useSession() outside <SessionProvider>')
|
|
25
|
+
const state = useSyncExternalStore(store.subscribe, store.getState)
|
|
26
|
+
return { ...state, signIn: store.signIn, signOut: store.signOut }
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** Shows `children` only with a session; the login otherwise. Wrap the whole app or a single screen. */
|
|
30
|
+
export function RequireSession({ children, fallback }: { children: ReactNode; fallback?: ReactNode }) {
|
|
31
|
+
const { status } = useSession()
|
|
32
|
+
if (status === 'loading') return <>{fallback ?? <p className="muted">Comprobando sesión…</p>}</>
|
|
33
|
+
if (status === 'signed_out') return <LoginScreen />
|
|
34
|
+
return <>{children}</>
|
|
35
|
+
}
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Session state of the app, outside React: `loading` -> `signed_in` | `signed_out` (+ `expired`).
|
|
3
|
+
* `main.tsx` builds it once, gives `expire` to the HTTP client (`onSessionExpired`) and the store to
|
|
4
|
+
* `<SessionProvider>`. Tested without rendering anything.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
import type { Auth, Credentials, Session } from './auth'
|
|
8
|
+
|
|
9
|
+
export type SessionStatus = 'loading' | 'signed_in' | 'signed_out'
|
|
10
|
+
|
|
11
|
+
export type SessionState = {
|
|
12
|
+
status: SessionStatus
|
|
13
|
+
session: Session | null
|
|
14
|
+
/** True when the last session ended by itself (401 after refresh), so the login can say so. */
|
|
15
|
+
expired: boolean
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export function createSessionStore(auth: Auth) {
|
|
19
|
+
let state: SessionState = { status: 'loading', session: null, expired: false }
|
|
20
|
+
const listeners = new Set<() => void>()
|
|
21
|
+
|
|
22
|
+
function set(next: Partial<SessionState>) {
|
|
23
|
+
state = { ...state, ...next }
|
|
24
|
+
listeners.forEach((listener) => listener())
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
function apply(session: Session | null) {
|
|
28
|
+
set({ status: session ? 'signed_in' : 'signed_out', session })
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
return {
|
|
32
|
+
getState: () => state,
|
|
33
|
+
subscribe(listener: () => void) {
|
|
34
|
+
listeners.add(listener)
|
|
35
|
+
return () => listeners.delete(listener)
|
|
36
|
+
},
|
|
37
|
+
|
|
38
|
+
/** Reads the stored session and follows the provider from then on (refresh, sign out in another tab). */
|
|
39
|
+
async start(): Promise<() => void> {
|
|
40
|
+
const stop = auth.onChange(apply)
|
|
41
|
+
apply(await auth.getSession())
|
|
42
|
+
return stop
|
|
43
|
+
},
|
|
44
|
+
|
|
45
|
+
async signIn(credentials: Credentials): Promise<void> {
|
|
46
|
+
const session = await auth.signIn(credentials) // throws AuthError; the screen shows it by code
|
|
47
|
+
set({ status: 'signed_in', session, expired: false })
|
|
48
|
+
},
|
|
49
|
+
|
|
50
|
+
async signOut(): Promise<void> {
|
|
51
|
+
await auth.signOut()
|
|
52
|
+
set({ status: 'signed_out', session: null, expired: false })
|
|
53
|
+
},
|
|
54
|
+
|
|
55
|
+
/** A 401 survived the refresh: the session is over. Called by the HTTP client. */
|
|
56
|
+
expire(): void {
|
|
57
|
+
void auth.signOut()
|
|
58
|
+
set({ status: 'signed_out', session: null, expired: true })
|
|
59
|
+
},
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
export type SessionStore = ReturnType<typeof createSessionStore>
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
import { render, screen } from '@testing-library/react'
|
|
2
|
+
import userEvent from '@testing-library/user-event'
|
|
3
|
+
import { describe, expect, it } from 'vitest'
|
|
4
|
+
|
|
5
|
+
import { createFakeAuth } from './fake-auth'
|
|
6
|
+
import { RequireSession, SessionProvider } from './session-context'
|
|
7
|
+
import { createSessionStore } from './session-store'
|
|
8
|
+
|
|
9
|
+
function mount(store = createSessionStore(createFakeAuth({ latencyMs: 0 }))) {
|
|
10
|
+
render(
|
|
11
|
+
<SessionProvider store={store}>
|
|
12
|
+
<RequireSession>
|
|
13
|
+
<h1>Dentro</h1>
|
|
14
|
+
</RequireSession>
|
|
15
|
+
</SessionProvider>,
|
|
16
|
+
)
|
|
17
|
+
return store
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
async function enter(email = 'demo@example.com', password = 'demo') {
|
|
21
|
+
await userEvent.type(await screen.findByLabelText('Correo'), email)
|
|
22
|
+
await userEvent.type(screen.getByLabelText('Contraseña'), password)
|
|
23
|
+
await userEvent.click(screen.getByRole('button', { name: 'Entrar' }))
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
describe('RequireSession', () => {
|
|
27
|
+
it('shows the login, then the content after signing in', async () => {
|
|
28
|
+
mount()
|
|
29
|
+
expect(await screen.findByRole('heading', { name: 'Entrar' })).toBeTruthy()
|
|
30
|
+
await enter()
|
|
31
|
+
expect(await screen.findByRole('heading', { name: 'Dentro' })).toBeTruthy()
|
|
32
|
+
})
|
|
33
|
+
|
|
34
|
+
it('shows a message by code and keeps the form on a wrong password', async () => {
|
|
35
|
+
mount()
|
|
36
|
+
await enter('demo@example.com', 'wrong')
|
|
37
|
+
expect((await screen.findByRole('alert')).textContent).toContain('No coinciden')
|
|
38
|
+
expect(screen.getByRole('button', { name: 'Entrar' })).toBeTruthy()
|
|
39
|
+
})
|
|
40
|
+
|
|
41
|
+
it('skips the login when a session is stored', async () => {
|
|
42
|
+
const auth = createFakeAuth({ latencyMs: 0 })
|
|
43
|
+
await auth.signIn({ email: 'demo@example.com', password: 'demo' })
|
|
44
|
+
mount(createSessionStore(auth))
|
|
45
|
+
expect(await screen.findByRole('heading', { name: 'Dentro' })).toBeTruthy()
|
|
46
|
+
})
|
|
47
|
+
|
|
48
|
+
it('goes back to the login and says why when the session expires', async () => {
|
|
49
|
+
const store = mount()
|
|
50
|
+
await enter()
|
|
51
|
+
await screen.findByRole('heading', { name: 'Dentro' })
|
|
52
|
+
store.expire()
|
|
53
|
+
expect(await screen.findByRole('heading', { name: 'Entrar' })).toBeTruthy()
|
|
54
|
+
expect(screen.getByText('Tu sesión ha caducado')).toBeTruthy()
|
|
55
|
+
})
|
|
56
|
+
})
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Settings block of the auth capability. `config.ts` mixes it in (`auth: authSettings(import.meta.env)`),
|
|
3
|
+
* the same way a backend `Settings` inherits `AuthSettings`. Only `config.ts` reads `import.meta.env`.
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
export type AuthProvider = 'supabase' | 'fake'
|
|
7
|
+
|
|
8
|
+
export type AuthSettings = {
|
|
9
|
+
provider: AuthProvider
|
|
10
|
+
supabaseUrl?: string
|
|
11
|
+
supabaseAnonKey?: string
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
type AuthEnv = {
|
|
15
|
+
readonly VITE_AUTH_PROVIDER?: string
|
|
16
|
+
readonly VITE_SUPABASE_URL?: string
|
|
17
|
+
readonly VITE_SUPABASE_ANON_KEY?: string
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export function authSettings(env: AuthEnv): AuthSettings {
|
|
21
|
+
const provider = env.VITE_AUTH_PROVIDER
|
|
22
|
+
// No silent default: a typo must not ship a fake login to production.
|
|
23
|
+
if (provider !== 'supabase' && provider !== 'fake') {
|
|
24
|
+
throw new Error(`VITE_AUTH_PROVIDER must be "supabase" or "fake", got ${JSON.stringify(provider)}`)
|
|
25
|
+
}
|
|
26
|
+
if (provider === 'supabase' && !(env.VITE_SUPABASE_URL && env.VITE_SUPABASE_ANON_KEY)) {
|
|
27
|
+
throw new Error('VITE_SUPABASE_URL and VITE_SUPABASE_ANON_KEY are required when VITE_AUTH_PROVIDER=supabase')
|
|
28
|
+
}
|
|
29
|
+
return { provider, supabaseUrl: env.VITE_SUPABASE_URL, supabaseAnonKey: env.VITE_SUPABASE_ANON_KEY }
|
|
30
|
+
}
|