spfn 0.2.0-beta.60 → 0.2.0-beta.63

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.
@@ -1,7 +1,7 @@
1
1
  # {{projectName}}
2
2
 
3
- A full-stack app built with [SPFN](https://github.com/spfn/spfn) — a typed SPFN
4
- backend running alongside Next.js.
3
+ A full-stack app built with [SPFN](https://github.com/spfn/spfn) — a consistent
4
+ architecture for taking an AI-built prototype to production. Scaffold mode: `{{mode}}`.
5
5
 
6
6
  ## Getting started
7
7
 
@@ -10,7 +10,7 @@ backend running alongside Next.js.
10
10
  docker compose up -d
11
11
 
12
12
  # 2. The env files are generated for you:
13
- # .env.local — Next.js-facing values (gitignored)
13
+ # .env.local — values loaded by Next.js, including auth session crypto (gitignored)
14
14
  # .env.server — server secrets: DB, cache (gitignored, never loaded by Next.js)
15
15
  # Review them and adjust as needed.
16
16
 
@@ -30,7 +30,7 @@ src/
30
30
  app/ Next.js App Router
31
31
  server/ SPFN backend (entities, repositories, routes, router)
32
32
  generated/ codegen output (route map) — do not edit by hand
33
- .env.local Next.js-facing env (gitignored)
33
+ .env.local Next.js runtime env (gitignored)
34
34
  .env.server server secrets (gitignored)
35
35
  .env.example committed reference — keys only, placeholder values
36
36
  .spfnrc.ts codegen configuration
@@ -46,15 +46,15 @@ A feature is a vertical slice: `Entity` (Drizzle table) → `Repository` →
46
46
  {{pmRun}} spfn:dev # dev: Next.js + SPFN API (add --watch to restart on changes)
47
47
  {{pmRun}} spfn:build # production build
48
48
  {{pmRun}} spfn:start # run the production build
49
- {{pm}} spfn db generate # create a migration from schema changes
50
- {{pm}} spfn db migrate # apply pending migrations
51
- {{pm}} spfn env check # check .env files against the schema
52
- {{pm}} spfn secret set DB_URL # store a secret (keychain locally, SOPS for deploys)
49
+ {{pmExec}} spfn db generate # create a migration from schema changes
50
+ {{pmExec}} spfn db migrate # apply pending migrations
51
+ {{pmExec}} spfn env check # check .env files against the schema
52
+ {{pmExec}} spfn secret set DB_URL # store a secret (keychain locally, SOPS for deploys)
53
53
  ```
54
54
 
55
55
  ## Environment & secrets
56
56
 
57
- `.env.server` holds server-only secrets and is gitignored — Next.js never loads it.
57
+ `.env.server` holds backend-only secrets and is gitignored — Next.js never loads it.
58
58
  For a managed workflow use `spfn secret`: local values go to the OS keychain (only a
59
59
  `secret:keychain:` reference lands in `.env.server`), and deployed secrets are stored
60
60
  in encrypted SOPS files. See the [SPFN CLI docs](https://github.com/spfn/spfn).
@@ -63,8 +63,21 @@ in encrypted SOPS files. See the [SPFN CLI docs](https://github.com/spfn/spfn).
63
63
  ## Authentication
64
64
 
65
65
  This project includes `@spfn/auth`. Configure providers and session settings in your
66
- server setup, and read `@spfn/auth`'s README for the full Entity → Repository →
67
- Service → Route flow and the typed `authApi` client.
66
+ generated env files, then run `{{pmExec}} spfn db migrate`. The lifecycle, router,
67
+ Next.js interceptor, `/login` starter UI, OAuth callback, and route map are already wired.
68
+
69
+ ## Internationalization
70
+
71
+ Edit `src/i18n/catalogs.ts` to add application-owned messages. Server components
72
+ and handlers can import `getT` or `getClientMessages` from `@/i18n/server`.
73
+
74
+ ## Agent operations with MCP
75
+
76
+ The SPFN API serves MCP at `http://localhost:8790/mcp`. Connect with the Bearer
77
+ token stored as `SPFN_MCP_API_KEY` in `.env.server`, then replace the starter
78
+ `app_status` tool in `src/server/mcp.ts` with operations from your domain layer.
79
+ Before third-party access, replace the generated operator-key validator with your
80
+ OAuth access-token validator and scope each tool to the resolved operator.
68
81
  <!-- {{/auth}} -->
69
82
 
70
83
  ## Deployment
@@ -0,0 +1 @@
1
+ export { OAuthCallback as default } from '@spfn/auth/nextjs/client';
@@ -0,0 +1,68 @@
1
+ 'use client';
2
+
3
+ import { useState } from 'react';
4
+ import { authApi } from '@spfn/auth';
5
+ import { I18nProvider, useT } from '@spfn/i18n/client';
6
+ import { catalogs } from '@/i18n/catalogs';
7
+
8
+ const providers = ['google', 'github', 'kakao', 'naver'] as const;
9
+
10
+ export default function LoginPage()
11
+ {
12
+ return (
13
+ <I18nProvider locale="en" messages={catalogs.en ?? {}}>
14
+ <LoginContent />
15
+ </I18nProvider>
16
+ );
17
+ }
18
+
19
+ function LoginContent()
20
+ {
21
+ const [error, setError] = useState<string>();
22
+ const [pending, setPending] = useState<string>();
23
+ const t = useT('common');
24
+
25
+ async function signIn(provider: typeof providers[number]): Promise<void>
26
+ {
27
+ setError(undefined);
28
+ setPending(provider);
29
+
30
+ try
31
+ {
32
+ const { authUrl } = provider === 'google'
33
+ ? await authApi.getGoogleOAuthUrl.call({ body: { returnUrl: '/' } })
34
+ : await authApi.getProviderOAuthUrl.call({
35
+ params: { provider },
36
+ body: { returnUrl: '/' },
37
+ });
38
+
39
+ window.location.assign(authUrl);
40
+ }
41
+ catch (cause)
42
+ {
43
+ setPending(undefined);
44
+ setError(cause instanceof Error ? cause.message : 'Could not start sign in');
45
+ }
46
+ }
47
+
48
+ return (
49
+ <main style={{ maxWidth: 420, margin: '10vh auto', padding: 24 }}>
50
+ <h1>{t('appName')} — Sign in</h1>
51
+ <p>Connect a provider key in <code>.env.server</code>, then continue.</p>
52
+ <div style={{ display: 'grid', gap: 12, marginTop: 24 }}>
53
+ {providers.map(provider => (
54
+ <button
55
+ key={provider}
56
+ type="button"
57
+ disabled={pending !== undefined}
58
+ onClick={() => void signIn(provider)}
59
+ style={{ padding: 12, textTransform: 'capitalize' }}
60
+ >
61
+ {pending === provider ? 'Connecting…' : `Continue with ${provider}`}
62
+ </button>
63
+ ))}
64
+ </div>
65
+ {error ? <p role="alert">{error}</p> : null}
66
+ </main>
67
+ );
68
+ }
@@ -0,0 +1,16 @@
1
+ import type { LocaleCatalogs } from '@spfn/i18n';
2
+
3
+ export const catalogs: LocaleCatalogs = {
4
+ en: {
5
+ common: {
6
+ appName: 'My SPFN app',
7
+ welcome: 'Welcome, {name}',
8
+ },
9
+ },
10
+ ko: {
11
+ common: {
12
+ appName: '나의 SPFN 앱',
13
+ welcome: '환영합니다, {name}',
14
+ },
15
+ },
16
+ };
@@ -0,0 +1,9 @@
1
+ import { configureI18n } from '@spfn/i18n/server';
2
+ import { catalogs } from './catalogs';
3
+
4
+ configureI18n({
5
+ catalogs,
6
+ fallbackLocale: 'en',
7
+ });
8
+
9
+ export { getClientMessages, getT } from '@spfn/i18n/server';
@@ -0,0 +1,23 @@
1
+ import {
2
+ createEnvRegistry,
3
+ defineEnvSchema,
4
+ envSecret,
5
+ envUrl,
6
+ } from '@spfn/core/env';
7
+
8
+ export const envSchema = defineEnvSchema({
9
+ SPFN_MCP_URL: envUrl({
10
+ description: 'Public base URL of the SPFN server that exposes /mcp',
11
+ default: 'http://localhost:8790',
12
+ required: false,
13
+ }),
14
+ SPFN_MCP_API_KEY: envSecret({
15
+ description: 'First-party Bearer token for the generated MCP operator endpoint',
16
+ required: true,
17
+ generate: 'base64url32',
18
+ }),
19
+ });
20
+
21
+ export const env = createEnvRegistry(envSchema).validate();
22
+
23
+ export default env;
@@ -0,0 +1,75 @@
1
+ /**
2
+ * Remote MCP endpoint for operating this application with an agent.
3
+ *
4
+ * The generated operator key makes the endpoint usable immediately. Replace
5
+ * `validateToken` with your OAuth access-token validator before granting access
6
+ * to third-party clients, and expose only tools the resolved operator may use.
7
+ */
8
+ import { timingSafeEqual } from 'node:crypto';
9
+ import type { McpAuth, McpTool } from '@spfn/mcp';
10
+ import { createMcpRoute } from '@spfn/mcp/server';
11
+ import env from './config/env.config';
12
+
13
+ type OperatorAuth = McpAuth & {
14
+ operatorId: string;
15
+ };
16
+
17
+ type OperatorContext = {
18
+ operatorId: string;
19
+ };
20
+
21
+ const tools: McpTool<OperatorContext>[] = [
22
+ {
23
+ name: 'app_status',
24
+ title: 'Application status',
25
+ description: 'Check that the deployed application MCP endpoint is available.',
26
+ inputSchema: {
27
+ type: 'object',
28
+ properties: {},
29
+ },
30
+ annotations: {
31
+ readOnlyHint: true,
32
+ destructiveHint: false,
33
+ },
34
+ handler: async (_args, context) => ({
35
+ status: 'ok',
36
+ operatorId: context.operatorId,
37
+ }),
38
+ },
39
+ ];
40
+
41
+ export const mcpRouter = createMcpRoute<OperatorAuth, OperatorContext>({
42
+ appUrl: env.SPFN_MCP_URL,
43
+ serverInfo: {
44
+ name: 'spfn-app',
45
+ version: '1.0.0',
46
+ description: 'Operate this SPFN application with an agent.',
47
+ },
48
+ validateToken: async (token) =>
49
+ {
50
+ // The registry validates this required secret at startup. Its public
51
+ // proxy type remains optional so schemas can also describe values that
52
+ // are not required in every environment.
53
+ if (!secretsMatch(token, env.SPFN_MCP_API_KEY!))
54
+ {
55
+ throw new Error('Invalid MCP access token');
56
+ }
57
+
58
+ return {
59
+ clientId: 'operator-agent',
60
+ operatorId: 'operator',
61
+ scopes: ['operate'],
62
+ };
63
+ },
64
+ resolveContext: async auth => ({ operatorId: auth.operatorId }),
65
+ listTools: () => tools,
66
+ });
67
+
68
+ function secretsMatch(actual: string, expected: string): boolean
69
+ {
70
+ const actualBytes = Buffer.from(actual);
71
+ const expectedBytes = Buffer.from(expected);
72
+
73
+ return actualBytes.length === expectedBytes.length
74
+ && timingSafeEqual(actualBytes, expectedBytes);
75
+ }
@@ -0,0 +1,32 @@
1
+ /**
2
+ * Prototype-to-Production application router.
3
+ *
4
+ * Auth protects application routes by default. Public routes opt out with
5
+ * `.skip(['auth'])`; the MCP router owns its Bearer-token boundary.
6
+ */
7
+ import { authRouter, authenticate } from '@spfn/auth/server';
8
+ import { defineRouter } from '@spfn/core/route';
9
+ import { mcpRouter } from './mcp';
10
+ import { getRoot } from './routes/root';
11
+ import { getHealth } from './routes/health';
12
+ import {
13
+ listExamples,
14
+ getExample,
15
+ createExample,
16
+ updateExample,
17
+ deleteExample,
18
+ } from './routes/examples';
19
+
20
+ export const appRouter = defineRouter({
21
+ getRoot,
22
+ getHealth,
23
+ listExamples,
24
+ getExample,
25
+ createExample,
26
+ updateExample,
27
+ deleteExample,
28
+ })
29
+ .packages([authRouter, mcpRouter])
30
+ .use([authenticate]);
31
+
32
+ export type AppRouter = typeof appRouter;
@@ -0,0 +1,94 @@
1
+ import { route } from '@spfn/core/route';
2
+ import { Type } from '@sinclair/typebox';
3
+ import { ExampleRepository } from '../repositories/example.repository';
4
+
5
+ const exampleRepo = new ExampleRepository();
6
+
7
+ export const listExamples = route.get('/examples')
8
+ .input({
9
+ query: Type.Object({
10
+ limit: Type.Optional(Type.Number({ minimum: 1, maximum: 100 })),
11
+ offset: Type.Optional(Type.Number({ minimum: 0 })),
12
+ }),
13
+ })
14
+ .skip(['auth'])
15
+ .handler(async (c) =>
16
+ {
17
+ const { query } = await c.data();
18
+ const limit = query.limit ?? 10;
19
+ const offset = query.offset ?? 0;
20
+
21
+ return {
22
+ examples: await exampleRepo.findAll(limit, offset),
23
+ total: await exampleRepo.countAll(),
24
+ limit,
25
+ offset,
26
+ };
27
+ });
28
+
29
+ export const getExample = route.get('/examples/:id')
30
+ .input({
31
+ params: Type.Object({ id: Type.String() }),
32
+ })
33
+ .skip(['auth'])
34
+ .handler(async (c) =>
35
+ {
36
+ const { params } = await c.data();
37
+ const example = await exampleRepo.findById(params.id);
38
+ if (!example)
39
+ {
40
+ throw new Error('Example not found');
41
+ }
42
+
43
+ return example;
44
+ });
45
+
46
+ export const createExample = route.post('/examples')
47
+ .input({
48
+ body: Type.Object({
49
+ name: Type.String(),
50
+ description: Type.String(),
51
+ }),
52
+ })
53
+ .handler(async (c) =>
54
+ {
55
+ const { body } = await c.data();
56
+
57
+ return exampleRepo.createExample(body);
58
+ });
59
+
60
+ export const updateExample = route.put('/examples/:id')
61
+ .input({
62
+ params: Type.Object({ id: Type.String() }),
63
+ body: Type.Object({
64
+ name: Type.Optional(Type.String()),
65
+ description: Type.Optional(Type.String()),
66
+ }),
67
+ })
68
+ .handler(async (c) =>
69
+ {
70
+ const { params, body } = await c.data();
71
+ const example = await exampleRepo.updateExample(params.id, body);
72
+ if (!example)
73
+ {
74
+ throw new Error('Example not found');
75
+ }
76
+
77
+ return example;
78
+ });
79
+
80
+ export const deleteExample = route.delete('/examples/:id')
81
+ .input({
82
+ params: Type.Object({ id: Type.String() }),
83
+ })
84
+ .handler(async (c) =>
85
+ {
86
+ const { params } = await c.data();
87
+ const example = await exampleRepo.deleteExample(params.id);
88
+ if (!example)
89
+ {
90
+ throw new Error('Example not found');
91
+ }
92
+
93
+ return { success: true, id: params.id };
94
+ });
@@ -0,0 +1,9 @@
1
+ import { route } from '@spfn/core/route';
2
+
3
+ export const getHealth = route.get('/health')
4
+ .skip(['auth'])
5
+ .handler(async () => ({
6
+ status: 'ok',
7
+ timestamp: Date.now(),
8
+ uptime: process.uptime(),
9
+ }));
@@ -0,0 +1,15 @@
1
+ import { route } from '@spfn/core/route';
2
+
3
+ export const getRoot = route.get('/')
4
+ .skip(['auth'])
5
+ .handler(async () => ({
6
+ name: 'SPFN API',
7
+ version: '1.0.0',
8
+ status: 'running',
9
+ endpoints: {
10
+ health: '/health',
11
+ examples: '/examples',
12
+ auth: '/_auth',
13
+ mcp: '/mcp',
14
+ },
15
+ }));
@@ -0,0 +1,14 @@
1
+ /**
2
+ * Prototype-to-Production server configuration.
3
+ */
4
+ import '@/i18n/server';
5
+ import { createAuthLifecycle } from '@spfn/auth/server';
6
+ import { defineServerConfig } from '@spfn/core/server';
7
+ import { appRouter } from '@/server/router';
8
+
9
+ export default defineServerConfig()
10
+ .port(8790)
11
+ .host('0.0.0.0')
12
+ .routes(appRouter)
13
+ .lifecycle(createAuthLifecycle())
14
+ .build();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "spfn",
3
- "version": "0.2.0-beta.60",
3
+ "version": "0.2.0-beta.63",
4
4
  "description": "Superfunction CLI - Add SPFN to your Next.js project",
5
5
  "type": "module",
6
6
  "bin": {