@spfn/auth 0.2.0-beta.2 → 0.2.0-beta.21

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 CHANGED
@@ -1,6 +1,6 @@
1
1
  # @spfn/auth - Technical Documentation
2
2
 
3
- **Version:** 0.1.0-alpha.88
3
+ **Version:** 0.2.0-beta.15
4
4
  **Status:** Alpha - Internal Development
5
5
 
6
6
  > **Note:** This is a technical documentation for developers working on the @spfn/auth package.
@@ -12,12 +12,14 @@
12
12
 
13
13
  - [Overview](#overview)
14
14
  - [Installation](#installation)
15
+ - [Admin Account Setup](#6-admin-account-setup)
15
16
  - [Architecture](#architecture)
16
17
  - [Package Structure](#package-structure)
17
18
  - [Module Exports](#module-exports)
18
19
  - [Email & SMS Services](#email--sms-services)
19
- - [Email Templates](#email-templates)
20
20
  - [Server-Side API](#server-side-api)
21
+ - [Events](#events)
22
+ - [OAuth Authentication](#oauth-authentication)
21
23
  - [Database Schema](#database-schema)
22
24
  - [RBAC System](#rbac-system)
23
25
  - [Next.js Adapter](#nextjs-adapter)
@@ -34,10 +36,11 @@
34
36
 
35
37
  - **Asymmetric JWT Authentication** - Client-signed tokens using ES256/RS256
36
38
  - **User Management** - Email/phone-based identity with bcrypt hashing
39
+ - **OAuth Authentication** - Google OAuth 2.0 (Authorization Code Flow), extensible to other providers
37
40
  - **Multi-Factor Authentication** - OTP verification via email/SMS
38
41
  - **Session Management** - Public key rotation with 90-day expiry
39
42
  - **Role-Based Access Control** - Flexible RBAC with runtime role/permission management
40
- - **Next.js Integration** - Session helpers and server-side guards
43
+ - **Next.js Integration** - Session helpers, server-side guards, and OAuth interceptors
41
44
 
42
45
  ### Design Principles
43
46
 
@@ -90,18 +93,26 @@ export const appRouter = defineRouter({
90
93
 
91
94
  ### 3. Configure Client (Next.js)
92
95
 
93
- #### Register Router Metadata and Errors in `api-client.ts`
96
+ #### Option A: Use the built-in `authApi` (Recommended)
97
+
98
+ ```typescript
99
+ import { authApi } from '@spfn/auth';
100
+
101
+ // Type-safe API calls for auth routes
102
+ const session = await authApi.getAuthSession.call({});
103
+ ```
104
+
105
+ #### Option B: Register Error Registry in Custom API Client
94
106
 
95
107
  ```typescript
96
108
  import { createApi } from '@spfn/core/nextjs';
97
109
  import type { AppRouter } from '@/server/router';
98
- import { appMetadata as authAppMetadata } from "@spfn/auth";
99
110
  import { authErrorRegistry } from "@spfn/auth/errors";
100
111
  import { appMetadata } from '@/server/router.metadata';
101
112
  import { errorRegistry } from "@spfn/core/errors";
102
113
 
103
114
  export const api = createApi<AppRouter>({
104
- metadata: { ...appMetadata, ...authAppMetadata },
115
+ metadata: appMetadata,
105
116
  errorRegistry: errorRegistry.concat(authErrorRegistry),
106
117
  });
107
118
  ```
@@ -122,16 +133,19 @@ SPFN_AUTH_JWT_EXPIRES_IN=7d
122
133
  SPFN_AUTH_BCRYPT_SALT_ROUNDS=10
123
134
  SPFN_AUTH_SESSION_TTL=7d
124
135
 
125
- # AWS SES (Email)
126
- SPFN_AUTH_AWS_REGION=ap-northeast-2
127
- SPFN_AUTH_AWS_SES_ACCESS_KEY_ID=AKIA...
128
- SPFN_AUTH_AWS_SES_SECRET_ACCESS_KEY=...
129
- SPFN_AUTH_AWS_SES_FROM_EMAIL=noreply@yourdomain.com
136
+ # Google OAuth
137
+ SPFN_AUTH_GOOGLE_CLIENT_ID=123456789-abc.apps.googleusercontent.com
138
+ SPFN_AUTH_GOOGLE_CLIENT_SECRET=GOCSPX-...
139
+ SPFN_APP_URL=http://localhost:3000
130
140
 
131
- # AWS SNS (SMS)
132
- SPFN_AUTH_AWS_SNS_ACCESS_KEY_ID=AKIA...
133
- SPFN_AUTH_AWS_SNS_SECRET_ACCESS_KEY=...
134
- SPFN_AUTH_AWS_SNS_SENDER_ID=MyApp
141
+ # Google OAuth (Optional)
142
+ SPFN_AUTH_GOOGLE_SCOPES=email,profile,https://www.googleapis.com/auth/gmail.readonly
143
+ SPFN_AUTH_GOOGLE_REDIRECT_URI=http://localhost:8790/_auth/oauth/google/callback
144
+ SPFN_AUTH_OAUTH_SUCCESS_URL=/auth/callback
145
+ SPFN_AUTH_OAUTH_ERROR_URL=http://localhost:3000/auth/error?error={error}
146
+
147
+ # Email/SMS — configure via @spfn/notification
148
+ # See @spfn/notification README for AWS SES/SNS settings
135
149
  ```
136
150
 
137
151
  ### 5. Run Migrations
@@ -144,6 +158,83 @@ pnpm spfn db generate
144
158
  pnpm spfn db migrate
145
159
  ```
146
160
 
161
+ ### 6. Admin Account Setup
162
+
163
+ Admin accounts are automatically created on server startup via `createAuthLifecycle()`.
164
+ Choose one of the following methods:
165
+
166
+ #### Method 1: JSON Format (Recommended)
167
+
168
+ Best for multiple accounts with full configuration:
169
+
170
+ ```bash
171
+ SPFN_AUTH_ADMIN_ACCOUNTS='[
172
+ {"email": "superadmin@example.com", "password": "secure-pass-1", "role": "superadmin"},
173
+ {"email": "admin@example.com", "password": "secure-pass-2", "role": "admin"},
174
+ {"email": "manager@example.com", "password": "secure-pass-3", "role": "user"}
175
+ ]'
176
+ ```
177
+
178
+ **JSON Schema:**
179
+ ```typescript
180
+ interface AdminAccountConfig {
181
+ email: string; // Required
182
+ password: string; // Required
183
+ role?: string; // Default: 'user' (options: 'user', 'admin', 'superadmin')
184
+ phone?: string; // Optional
185
+ passwordChangeRequired?: boolean; // Default: true
186
+ }
187
+ ```
188
+
189
+ #### Method 2: CSV Format
190
+
191
+ For multiple accounts with simpler configuration:
192
+
193
+ ```bash
194
+ SPFN_AUTH_ADMIN_EMAILS=admin@example.com,manager@example.com
195
+ SPFN_AUTH_ADMIN_PASSWORDS=admin-pass,manager-pass
196
+ SPFN_AUTH_ADMIN_ROLES=superadmin,admin
197
+ ```
198
+
199
+ #### Method 3: Single Account (Legacy)
200
+
201
+ Simplest format for a single superadmin:
202
+
203
+ ```bash
204
+ SPFN_AUTH_ADMIN_EMAIL=admin@example.com
205
+ SPFN_AUTH_ADMIN_PASSWORD=secure-password
206
+ ```
207
+
208
+ > **Note:** This method always creates a `superadmin` role account.
209
+
210
+ #### Default Behavior
211
+
212
+ All admin accounts created via environment variables have:
213
+ - `emailVerifiedAt`: Auto-verified (current timestamp)
214
+ - `passwordChangeRequired`: `true` (must change on first login)
215
+ - `status`: `active`
216
+
217
+ #### Programmatic Creation
218
+
219
+ You can also create admin accounts programmatically:
220
+
221
+ ```typescript
222
+ import { usersRepository, getRoleByName, hashPassword } from '@spfn/auth/server';
223
+
224
+ // After initializeAuth() has been called
225
+ const role = await getRoleByName('admin');
226
+ const passwordHash = await hashPassword('secure-password');
227
+
228
+ await usersRepository.create({
229
+ email: 'admin@example.com',
230
+ passwordHash,
231
+ roleId: role.id,
232
+ emailVerifiedAt: new Date(),
233
+ passwordChangeRequired: true,
234
+ status: 'active',
235
+ });
236
+ ```
237
+
147
238
  ---
148
239
 
149
240
  ## Architecture
@@ -335,20 +426,15 @@ packages/auth/
335
426
 
336
427
  ### Common Module (`@spfn/auth`)
337
428
 
338
- **Entities:**
429
+ **API Client:**
339
430
  ```typescript
340
- import {
341
- users,
342
- userPublicKeys,
343
- verificationCodes,
344
- roles,
345
- permissions,
346
- rolePermissions,
347
- userPermissions,
348
- userInvitations,
349
- userSocialAccounts,
350
- userProfiles
351
- } from '@spfn/auth';
431
+ import { authApi } from '@spfn/auth';
432
+
433
+ // Type-safe API calls
434
+ const session = await authApi.getAuthSession.call({});
435
+ const result = await authApi.login.call({
436
+ body: { email, password, fingerprint, publicKey, keyId }
437
+ });
352
438
  ```
353
439
 
354
440
  **Types:**
@@ -359,6 +445,9 @@ import type {
359
445
  VerificationCode,
360
446
  Role,
361
447
  Permission,
448
+ AuthSession,
449
+ UserProfile,
450
+ ProfileInfo,
362
451
  // ... etc
363
452
  } from '@spfn/auth';
364
453
  ```
@@ -380,6 +469,34 @@ import type {
380
469
  } from '@spfn/auth';
381
470
  ```
382
471
 
472
+ **Validation Patterns:**
473
+ ```typescript
474
+ import {
475
+ UUID_PATTERN,
476
+ EMAIL_PATTERN,
477
+ BASE64_PATTERN,
478
+ FINGERPRINT_PATTERN,
479
+ PHONE_PATTERN,
480
+ } from '@spfn/auth';
481
+ ```
482
+
483
+ **Route Map (for RPC Proxy):**
484
+ ```typescript
485
+ import { authRouteMap } from '@spfn/auth';
486
+
487
+ // Use in Next.js RPC proxy (app/api/rpc/[routeName]/route.ts)
488
+ import '@spfn/auth/nextjs/api'; // Auto-register auth interceptors
489
+ import { routeMap } from '@/generated/route-map';
490
+ import { authRouteMap } from '@spfn/auth';
491
+ import { createRpcProxy } from '@spfn/core/nextjs/proxy';
492
+
493
+ export const { GET, POST } = createRpcProxy({
494
+ routeMap: { ...routeMap, ...authRouteMap }
495
+ });
496
+ ```
497
+
498
+ > **Note:** Database entities (`users`, `userPublicKeys`, etc.) are exported from `@spfn/auth/server`, not the common module.
499
+
383
500
  ---
384
501
 
385
502
  ### Server Module (`@spfn/auth/server`)
@@ -456,22 +573,13 @@ import {
456
573
 
457
574
  // Session
458
575
  getAuthSessionService,
459
- getUserProfileService,
460
576
 
461
- // Email
462
- sendEmail,
463
- registerEmailProvider,
464
-
465
- // SMS
466
- sendSMS,
467
- registerSMSProvider,
577
+ // User Profile
578
+ getUserProfileService,
579
+ updateUserProfileService,
468
580
 
469
- // Email Templates
470
- registerEmailTemplates,
471
- getVerificationCodeTemplate,
472
- getWelcomeTemplate,
473
- getPasswordResetTemplate,
474
- getInvitationTemplate,
581
+ // OAuth - Google API Access
582
+ getGoogleAccessToken,
475
583
  } from '@spfn/auth/server';
476
584
  ```
477
585
 
@@ -495,10 +603,11 @@ import {
495
603
  import {
496
604
  authenticate,
497
605
  requirePermissions,
606
+ requireAnyPermission,
498
607
  requireRole,
499
608
  } from '@spfn/auth/server';
500
609
 
501
- // Usage
610
+ // Usage - all permissions required
502
611
  app.bind(
503
612
  myContract,
504
613
  [authenticate, requirePermissions('user:delete')],
@@ -506,6 +615,15 @@ app.bind(
506
615
  // Handler
507
616
  }
508
617
  );
618
+
619
+ // Usage - any of the permissions
620
+ app.bind(
621
+ myContract,
622
+ [authenticate, requireAnyPermission('content:read', 'admin:access')],
623
+ async (c) => {
624
+ // User has either content:read OR admin:access
625
+ }
626
+ );
509
627
  ```
510
628
 
511
629
  **Helpers:**
@@ -610,9 +728,11 @@ import {
610
728
  loginRegisterInterceptor,
611
729
  generalAuthInterceptor,
612
730
  keyRotationInterceptor,
731
+ oauthUrlInterceptor,
732
+ oauthFinalizeInterceptor,
613
733
  } from '@spfn/auth/nextjs/api';
614
734
 
615
- // Auto-registers interceptors on import
735
+ // Auto-registers interceptors on import (including OAuth)
616
736
  import '@spfn/auth/nextjs/api';
617
737
  ```
618
738
 
@@ -679,141 +799,24 @@ export default async function DashboardPage()
679
799
 
680
800
  ## Email & SMS Services
681
801
 
682
- ### Email Service
802
+ > **⚠️ DEPRECATED:** Email and SMS functionality has been moved to `@spfn/notification` package.
683
803
 
684
- The email service uses AWS SES by default, with fallback to console logging in development.
804
+ ### Migration Guide
685
805
 
686
- **Send Email:**
687
806
  ```typescript
688
- import { sendEmail } from '@spfn/auth/server';
807
+ // Before (deprecated)
808
+ import { sendEmail, sendSMS } from '@spfn/auth/server';
689
809
 
690
- await sendEmail({
691
- to: 'user@example.com',
692
- subject: 'Welcome!',
693
- text: 'Plain text content',
694
- html: '<h1>HTML content</h1>',
695
- purpose: 'welcome', // for logging
696
- });
810
+ // After (recommended)
811
+ import { sendEmail, sendSMS } from '@spfn/notification/server';
697
812
  ```
698
813
 
699
- **Custom Email Provider:**
700
- ```typescript
701
- import { registerEmailProvider } from '@spfn/auth/server';
814
+ The `@spfn/notification` package provides:
815
+ - Multi-channel support (Email, SMS, Slack, Push)
816
+ - Template system with variable substitution
817
+ - Multiple provider support (AWS SES, SNS, SendGrid, Twilio, etc.)
702
818
 
703
- // Register SendGrid provider
704
- registerEmailProvider({
705
- name: 'sendgrid',
706
- sendEmail: async ({ to, subject, text, html }) => {
707
- // Your SendGrid implementation
708
- return { success: true, messageId: '...' };
709
- },
710
- });
711
- ```
712
-
713
- ---
714
-
715
- ### SMS Service
716
-
717
- The SMS service uses AWS SNS by default.
718
-
719
- **Send SMS:**
720
- ```typescript
721
- import { sendSMS } from '@spfn/auth/server';
722
-
723
- await sendSMS({
724
- phone: '+821012345678', // E.164 format
725
- message: 'Your code is: 123456',
726
- purpose: 'verification',
727
- });
728
- ```
729
-
730
- **Custom SMS Provider:**
731
- ```typescript
732
- import { registerSMSProvider } from '@spfn/auth/server';
733
-
734
- // Register Twilio provider
735
- registerSMSProvider({
736
- name: 'twilio',
737
- sendSMS: async ({ phone, message }) => {
738
- // Your Twilio implementation
739
- return { success: true, messageId: '...' };
740
- },
741
- });
742
- ```
743
-
744
- ---
745
-
746
- ## Email Templates
747
-
748
- ### Built-in Templates
749
-
750
- | Template | Function | Purpose |
751
- |----------|----------|---------|
752
- | `verificationCode` | `getVerificationCodeTemplate` | Verification codes (registration, login, password reset) |
753
- | `welcome` | `getWelcomeTemplate` | Welcome email after registration |
754
- | `passwordReset` | `getPasswordResetTemplate` | Password reset link |
755
- | `invitation` | `getInvitationTemplate` | User invitation |
756
-
757
- **Usage:**
758
- ```typescript
759
- import { getVerificationCodeTemplate, sendEmail } from '@spfn/auth/server';
760
-
761
- const { subject, text, html } = getVerificationCodeTemplate({
762
- code: '123456',
763
- purpose: 'registration',
764
- expiresInMinutes: 5,
765
- appName: 'MyApp',
766
- });
767
-
768
- await sendEmail({ to: 'user@example.com', subject, text, html });
769
- ```
770
-
771
- ---
772
-
773
- ### Custom Templates
774
-
775
- Register custom templates to override defaults with your brand design:
776
-
777
- ```typescript
778
- import { registerEmailTemplates } from '@spfn/auth/server';
779
-
780
- // Register at app initialization (e.g., server.config.ts)
781
- registerEmailTemplates({
782
- // Override verification code template
783
- verificationCode: ({ code, purpose, expiresInMinutes, appName }) => ({
784
- subject: `[${appName}] Your verification code`,
785
- text: `Your code: ${code}\nExpires in ${expiresInMinutes} minutes.`,
786
- html: `
787
- <div style="font-family: Arial, sans-serif;">
788
- <img src="https://myapp.com/logo.png" alt="Logo" />
789
- <h1>Verification Code</h1>
790
- <div style="font-size: 32px; font-weight: bold;">${code}</div>
791
- <p>This code expires in ${expiresInMinutes} minutes.</p>
792
- </div>
793
- `,
794
- }),
795
-
796
- // Override invitation template
797
- invitation: ({ inviteLink, inviterName, roleName, appName }) => ({
798
- subject: `${inviterName} invited you to ${appName}`,
799
- text: `Accept invitation: ${inviteLink}`,
800
- html: `
801
- <h1>You're Invited!</h1>
802
- <p>${inviterName} invited you to join ${appName} as ${roleName}.</p>
803
- <a href="${inviteLink}">Accept Invitation</a>
804
- `,
805
- }),
806
- });
807
- ```
808
-
809
- **Template Parameters:**
810
-
811
- | Template | Parameters |
812
- |----------|------------|
813
- | `verificationCode` | `code`, `purpose`, `expiresInMinutes?`, `appName?` |
814
- | `welcome` | `email`, `appName?` |
815
- | `passwordReset` | `resetLink`, `expiresInMinutes?`, `appName?` |
816
- | `invitation` | `inviteLink`, `inviterName?`, `roleName?`, `appName?` |
819
+ For documentation, see `@spfn/notification` package README.
817
820
 
818
821
  ---
819
822
 
@@ -1027,6 +1030,437 @@ Change password.
1027
1030
 
1028
1031
  ---
1029
1032
 
1033
+ ## Events
1034
+
1035
+ `@spfn/auth`는 `@spfn/core/event`를 사용하여 인증 관련 이벤트를 발행합니다. 이를 통해 로그인/회원가입 시 추가 로직(환영 이메일, 분석, 알림 등)을 디커플링된 방식으로 처리할 수 있습니다.
1036
+
1037
+ ### Available Events
1038
+
1039
+ | Event | Description | Trigger |
1040
+ |-------|-------------|---------|
1041
+ | `auth.login` | 로그인 성공 | 이메일/전화 로그인, OAuth 기존 사용자 |
1042
+ | `auth.register` | 회원가입 성공 | 이메일/전화 회원가입, OAuth 신규 사용자 |
1043
+
1044
+ ---
1045
+
1046
+ ### Event Payloads
1047
+
1048
+ #### `auth.login`
1049
+
1050
+ ```typescript
1051
+ {
1052
+ userId: string;
1053
+ provider: 'email' | 'phone' | 'google';
1054
+ email?: string;
1055
+ phone?: string;
1056
+ }
1057
+ ```
1058
+
1059
+ #### `auth.register`
1060
+
1061
+ ```typescript
1062
+ {
1063
+ userId: string;
1064
+ provider: 'email' | 'phone' | 'google';
1065
+ email?: string;
1066
+ phone?: string;
1067
+ }
1068
+ ```
1069
+
1070
+ ---
1071
+
1072
+ ### Subscribing to Events
1073
+
1074
+ ```typescript
1075
+ import { authLoginEvent, authRegisterEvent } from '@spfn/auth/server';
1076
+
1077
+ // 로그인 이벤트 구독
1078
+ authLoginEvent.subscribe(async (payload) => {
1079
+ console.log('User logged in:', payload.userId, payload.provider);
1080
+ await analytics.trackLogin(payload.userId);
1081
+ });
1082
+
1083
+ // 회원가입 이벤트 구독
1084
+ authRegisterEvent.subscribe(async (payload) => {
1085
+ console.log('New user registered:', payload.userId);
1086
+ if (payload.email) {
1087
+ await emailService.sendWelcome(payload.email);
1088
+ }
1089
+ });
1090
+ ```
1091
+
1092
+ ---
1093
+
1094
+ ### Job Integration
1095
+
1096
+ `@spfn/core/job`과 연동하여 백그라운드 작업을 실행할 수 있습니다.
1097
+
1098
+ ```typescript
1099
+ import { job, defineJobRouter } from '@spfn/core/job';
1100
+ import { authRegisterEvent } from '@spfn/auth/server';
1101
+
1102
+ // 회원가입 시 환영 이메일 발송 Job
1103
+ const sendWelcomeEmailJob = job('send-welcome-email')
1104
+ .on(authRegisterEvent)
1105
+ .handler(async ({ userId, email }) => {
1106
+ if (email) {
1107
+ await emailService.sendWelcome(email);
1108
+ }
1109
+ });
1110
+
1111
+ // 회원가입 시 기본 설정 생성 Job
1112
+ const createDefaultSettingsJob = job('create-default-settings')
1113
+ .on(authRegisterEvent)
1114
+ .handler(async ({ userId }) => {
1115
+ await settingsService.createDefaults(userId);
1116
+ });
1117
+
1118
+ export const jobRouter = defineJobRouter({
1119
+ sendWelcomeEmailJob,
1120
+ createDefaultSettingsJob,
1121
+ });
1122
+ ```
1123
+
1124
+ ---
1125
+
1126
+ ### Event Flow
1127
+
1128
+ ```
1129
+ ┌─────────────────────────────────────────────────────────────────┐
1130
+ │ loginService() / registerService() │
1131
+ │ oauthCallbackService() │
1132
+ └─────────────────────────────────────────────────────────────────┘
1133
+
1134
+
1135
+ authLoginEvent.emit()
1136
+ authRegisterEvent.emit()
1137
+
1138
+ ┌───────────────────┼───────────────────┐
1139
+ ▼ ▼ ▼
1140
+ ┌──────────┐ ┌──────────┐ ┌──────────┐
1141
+ │ Backend │ │ Job │ │ SSE │
1142
+ │ Handler │ │ Queue │ │ Stream │
1143
+ └──────────┘ └──────────┘ └──────────┘
1144
+ .subscribe() .on(event) (optional)
1145
+ │ │
1146
+ ▼ ▼
1147
+ [Analytics, [Background
1148
+ Logging] Processing]
1149
+ ```
1150
+
1151
+ ---
1152
+
1153
+ ### Type Exports
1154
+
1155
+ ```typescript
1156
+ import type {
1157
+ AuthLoginPayload,
1158
+ AuthRegisterPayload,
1159
+ } from '@spfn/auth/server';
1160
+ ```
1161
+
1162
+ ---
1163
+
1164
+ ## OAuth Authentication
1165
+
1166
+ ### Overview
1167
+
1168
+ `@spfn/auth`는 OAuth 2.0 Authorization Code Flow를 지원합니다. 현재 Google OAuth가 구현되어 있으며, 다른 provider (GitHub, Kakao, Naver)는 동일한 패턴으로 확장 가능합니다.
1169
+
1170
+ **핵심 설계:**
1171
+ - 환경 변수만으로 설정 (`SPFN_AUTH_GOOGLE_CLIENT_ID`, `SPFN_AUTH_GOOGLE_CLIENT_SECRET`)
1172
+ - Next.js 인터셉터 기반 자동 세션 관리 (키쌍 생성 → pending session → full session)
1173
+ - 기존 이메일 계정과 자동 연결 (Google verified_email 확인 시에만)
1174
+
1175
+ ---
1176
+
1177
+ ### Authentication Flow
1178
+
1179
+ ```
1180
+ ┌──────────┐ ┌──────────────┐ ┌──────────┐ ┌──────────┐
1181
+ │ Client │ │ Next.js RPC │ │ Backend │ │ Google │
1182
+ │ (Browser)│ │ (Interceptor)│ │ (SPFN) │ │ OAuth │
1183
+ └────┬─────┘ └──────┬───────┘ └────┬─────┘ └────┬─────┘
1184
+ │ │ │ │
1185
+ │ 1. Click Login │ │ │
1186
+ ├──────────────────>│ │ │
1187
+ │ │ │ │
1188
+ │ 2. Generate keypair (ES256) │ │
1189
+ │ 3. Create encrypted state │ │
1190
+ │ (publicKey, keyId in JWE) │ │
1191
+ │ 4. Save privateKey to │ │
1192
+ │ pending session cookie │ │
1193
+ │ │ │ │
1194
+ │ │ 5. Forward with │ │
1195
+ │ │ state in body │ │
1196
+ │ ├─────────────────>│ │
1197
+ │ │ │ │
1198
+ │ │ 6. Return Google │ │
1199
+ │ │ Auth URL │ │
1200
+ │ │<─────────────────┤ │
1201
+ │ │ │ │
1202
+ │ 7. Redirect to Google │ │
1203
+ │<──────────────────┤ │ │
1204
+ │ │ │ │
1205
+ │ 8. User consents │ │ │
1206
+ ├───────────────────┼──────────────────┼────────────────>│
1207
+ │ │ │ │
1208
+ │ │ 9. Callback with code + state │
1209
+ │ │ │<────────────────┤
1210
+ │ │ │ │
1211
+ │ │ 10. Verify state, exchange code │
1212
+ │ │ Create/link user account │
1213
+ │ │ Register publicKey │
1214
+ │ │ │ │
1215
+ │ 11. Redirect to /auth/callback │ │
1216
+ │ ?userId=X&keyId=Y&returnUrl=/ │ │
1217
+ │<─────────────────────────────────────┤ │
1218
+ │ │ │ │
1219
+ │ 12. OAuthCallback │ │ │
1220
+ │ component │ │ │
1221
+ │ calls finalize│ │ │
1222
+ ├──────────────────>│ │ │
1223
+ │ │ │ │
1224
+ │ 13. Interceptor reads pending │ │
1225
+ │ session cookie, verifies │ │
1226
+ │ keyId match, creates full │ │
1227
+ │ session cookie │ │
1228
+ │ │ │ │
1229
+ │ 14. Session set, │ │ │
1230
+ │ redirect to │ │ │
1231
+ │ returnUrl │ │ │
1232
+ │<──────────────────┤ │ │
1233
+ │ │ │ │
1234
+ ```
1235
+
1236
+ ---
1237
+
1238
+ ### Setup
1239
+
1240
+ #### 1. Google Cloud Console
1241
+
1242
+ 1. [Google Cloud Console](https://console.cloud.google.com/) > APIs & Services > Credentials
1243
+ 2. Create OAuth 2.0 Client ID (Web application)
1244
+ 3. Add Authorized redirect URI: `http://localhost:8790/_auth/oauth/google/callback`
1245
+ 4. Copy Client ID and Client Secret
1246
+
1247
+ #### 2. Environment Variables
1248
+
1249
+ ```bash
1250
+ # Required
1251
+ SPFN_AUTH_GOOGLE_CLIENT_ID=your-client-id.apps.googleusercontent.com
1252
+ SPFN_AUTH_GOOGLE_CLIENT_SECRET=GOCSPX-your-secret
1253
+
1254
+ # Next.js app URL (for OAuth callback redirect)
1255
+ SPFN_APP_URL=http://localhost:3000
1256
+
1257
+ # Optional
1258
+ SPFN_AUTH_GOOGLE_SCOPES=email,profile # default (comma-separated)
1259
+ SPFN_AUTH_GOOGLE_REDIRECT_URI=http://localhost:8790/_auth/oauth/google/callback # default
1260
+ SPFN_AUTH_OAUTH_SUCCESS_URL=/auth/callback # default
1261
+ ```
1262
+
1263
+ #### 3. Next.js Callback Page
1264
+
1265
+ ```tsx
1266
+ // app/auth/callback/page.tsx
1267
+ export { OAuthCallback as default } from '@spfn/auth/nextjs/client';
1268
+ ```
1269
+
1270
+ #### 4. Login Button
1271
+
1272
+ ```typescript
1273
+ import { authApi } from '@spfn/auth';
1274
+
1275
+ const handleGoogleLogin = async () =>
1276
+ {
1277
+ const response = await authApi.getGoogleOAuthUrl.call({
1278
+ body: { returnUrl: '/dashboard' },
1279
+ });
1280
+ window.location.href = response.authUrl;
1281
+ };
1282
+ ```
1283
+
1284
+ ---
1285
+
1286
+ ### OAuth Routes
1287
+
1288
+ #### `GET /_auth/oauth/google`
1289
+
1290
+ Google OAuth 시작 (리다이렉트 방식). 브라우저를 Google 로그인 페이지로 직접 리다이렉트합니다.
1291
+
1292
+ **Query:**
1293
+ ```typescript
1294
+ {
1295
+ state: string; // Encrypted OAuth state (JWE)
1296
+ }
1297
+ ```
1298
+
1299
+ ---
1300
+
1301
+ #### `POST /_auth/oauth/google/url`
1302
+
1303
+ Google OAuth URL 획득 (인터셉터 방식). 인터셉터가 state를 자동 생성하여 주입합니다.
1304
+
1305
+ **Request:**
1306
+ ```typescript
1307
+ {
1308
+ returnUrl?: string; // Default: '/'
1309
+ }
1310
+ ```
1311
+
1312
+ **Response:**
1313
+ ```typescript
1314
+ {
1315
+ authUrl: string; // Google OAuth URL
1316
+ }
1317
+ ```
1318
+
1319
+ ---
1320
+
1321
+ #### `GET /_auth/oauth/google/callback`
1322
+
1323
+ Google에서 리다이렉트되는 콜백. code를 token으로 교환하고 사용자를 생성/연결합니다.
1324
+
1325
+ **Query (from Google):**
1326
+ ```typescript
1327
+ {
1328
+ code?: string; // Authorization code
1329
+ state?: string; // OAuth state
1330
+ error?: string; // Error code
1331
+ error_description?: string; // Error description
1332
+ }
1333
+ ```
1334
+
1335
+ **Result:** Next.js 콜백 페이지로 리다이렉트 (`/auth/callback?userId=X&keyId=Y&returnUrl=/`)
1336
+
1337
+ ---
1338
+
1339
+ #### `POST /_auth/oauth/finalize`
1340
+
1341
+ OAuth 세션 완료. 인터셉터가 pending session에서 full session을 생성합니다.
1342
+
1343
+ **Request:**
1344
+ ```typescript
1345
+ {
1346
+ userId: string;
1347
+ keyId: string;
1348
+ returnUrl?: string;
1349
+ }
1350
+ ```
1351
+
1352
+ **Response:**
1353
+ ```typescript
1354
+ {
1355
+ success: boolean;
1356
+ returnUrl: string;
1357
+ }
1358
+ ```
1359
+
1360
+ ---
1361
+
1362
+ #### `GET /_auth/oauth/providers`
1363
+
1364
+ 활성화된 OAuth provider 목록을 반환합니다.
1365
+
1366
+ **Response:**
1367
+ ```typescript
1368
+ {
1369
+ providers: ('google' | 'github' | 'kakao' | 'naver')[];
1370
+ }
1371
+ ```
1372
+
1373
+ ---
1374
+
1375
+ ### Google API Access
1376
+
1377
+ OAuth 로그인 후 저장된 access token으로 Google API를 호출할 수 있습니다.
1378
+
1379
+ #### Custom Scopes 설정
1380
+
1381
+ `SPFN_AUTH_GOOGLE_SCOPES` 환경변수로 추가 스코프를 요청합니다. 미설정 시 `email,profile`이 기본값입니다.
1382
+
1383
+ ```bash
1384
+ # Gmail + Calendar 읽기 권한 추가
1385
+ SPFN_AUTH_GOOGLE_SCOPES=email,profile,https://www.googleapis.com/auth/gmail.readonly,https://www.googleapis.com/auth/calendar.readonly
1386
+ ```
1387
+
1388
+ > **Note:** Google Cloud Console에서 해당 API를 활성화해야 합니다.
1389
+
1390
+ #### Access Token 사용
1391
+
1392
+ `getGoogleAccessToken(userId)`은 유효한 access token을 반환합니다. 토큰이 만료 임박(5분 이내) 또는 만료 상태이면 자동으로 refresh token을 사용하여 갱신합니다.
1393
+
1394
+ ```typescript
1395
+ import { getGoogleAccessToken } from '@spfn/auth/server';
1396
+
1397
+ // 항상 유효한 토큰 반환 (만료 시 자동 갱신)
1398
+ const token = await getGoogleAccessToken(userId);
1399
+
1400
+ // Gmail API 호출
1401
+ const response = await fetch(
1402
+ 'https://gmail.googleapis.com/gmail/v1/users/me/messages?maxResults=10',
1403
+ { headers: { Authorization: `Bearer ${token}` } }
1404
+ );
1405
+ const data = await response.json();
1406
+ ```
1407
+
1408
+ **에러 케이스:**
1409
+ - Google 계정 미연결 → `'No Google account linked'`
1410
+ - Refresh token 없음 → `'Google refresh token not available'` (재로그인 필요)
1411
+
1412
+ ---
1413
+
1414
+ ### Security
1415
+
1416
+ - **State 암호화**: JWE (A256GCM)로 state 파라미터 암호화. CSRF 방지용 nonce 포함.
1417
+ - **Pending Session**: OAuth 리다이렉트 중 privateKey를 JWE로 암호화한 HttpOnly 쿠키에 저장. 10분 TTL.
1418
+ - **KeyId 검증**: finalize 시 pending session의 keyId와 응답의 keyId 일치 확인.
1419
+ - **Email 검증**: `verified_email`이 true인 경우에만 기존 계정에 자동 연결. 미검증 이메일로 기존 계정 연결 시도 시 에러.
1420
+ - **Session Cookie**: `HttpOnly`, `Secure` (production), `SameSite=strict`.
1421
+
1422
+ ---
1423
+
1424
+ ### OAuthCallback Component
1425
+
1426
+ `@spfn/auth/nextjs/client`에서 제공하는 클라이언트 컴포넌트입니다.
1427
+
1428
+ ```tsx
1429
+ import { OAuthCallback } from '@spfn/auth/nextjs/client';
1430
+
1431
+ // 기본 사용
1432
+ export default function CallbackPage()
1433
+ {
1434
+ return <OAuthCallback />;
1435
+ }
1436
+
1437
+ // 커스터마이징
1438
+ export default function CallbackPage()
1439
+ {
1440
+ return (
1441
+ <OAuthCallback
1442
+ apiBasePath="/api/rpc"
1443
+ loadingComponent={<MySpinner />}
1444
+ errorComponent={(error) => <MyError message={error} />}
1445
+ onSuccess={(userId) => console.log('Logged in:', userId)}
1446
+ onError={(error) => console.error(error)}
1447
+ />
1448
+ );
1449
+ }
1450
+ ```
1451
+
1452
+ **Props:**
1453
+
1454
+ | Prop | Type | Default | Description |
1455
+ |------|------|---------|-------------|
1456
+ | `apiBasePath` | `string` | `'/api/rpc'` | RPC API base path |
1457
+ | `loadingComponent` | `ReactNode` | Built-in | 로딩 중 표시할 컴포넌트 |
1458
+ | `errorComponent` | `(error: string) => ReactNode` | Built-in | 에러 표시 컴포넌트 |
1459
+ | `onSuccess` | `(userId: string) => void` | - | 성공 콜백 |
1460
+ | `onError` | `(error: string) => void` | - | 에러 콜백 |
1461
+
1462
+ ---
1463
+
1030
1464
  ## Database Schema
1031
1465
 
1032
1466
  ### Core Tables
@@ -1167,7 +1601,7 @@ CREATE TABLE permissions (
1167
1601
 
1168
1602
  **Built-in Permissions:**
1169
1603
  - `auth:self:manage`
1170
- - `user:read`, `user:write`, `user:delete`
1604
+ - `user:read`, `user:write`, `user:delete`, `user:invite`
1171
1605
  - `rbac:role:manage`, `rbac:permission:manage`
1172
1606
 
1173
1607
  ---
@@ -1260,7 +1694,7 @@ CREATE TABLE user_profiles (
1260
1694
 
1261
1695
  #### `user_social_accounts`
1262
1696
 
1263
- OAuth provider accounts (future feature).
1697
+ OAuth provider accounts (Google, GitHub, etc.).
1264
1698
 
1265
1699
  ```sql
1266
1700
  CREATE TABLE user_social_accounts (
@@ -1327,7 +1761,7 @@ await initializeAuth({
1327
1761
 
1328
1762
  **Permissions:**
1329
1763
  - `auth:self:manage` - Change password, rotate keys
1330
- - `user:read`, `user:write`, `user:delete`
1764
+ - `user:read`, `user:write`, `user:delete`, `user:invite`
1331
1765
  - `rbac:role:manage`, `rbac:permission:manage`
1332
1766
 
1333
1767
  ---
@@ -1335,7 +1769,7 @@ await initializeAuth({
1335
1769
  ### Middleware Usage
1336
1770
 
1337
1771
  ```typescript
1338
- import { authenticate, requirePermissions, requireRole } from '@spfn/auth/server';
1772
+ import { authenticate, requirePermissions, requireAnyPermission, requireRole } from '@spfn/auth/server';
1339
1773
 
1340
1774
  // Single permission
1341
1775
  app.bind(
@@ -1355,6 +1789,15 @@ app.bind(
1355
1789
  }
1356
1790
  );
1357
1791
 
1792
+ // Any of the permissions (at least one required)
1793
+ app.bind(
1794
+ viewContentContract,
1795
+ [authenticate, requireAnyPermission('content:read', 'admin:access')],
1796
+ async (c) => {
1797
+ // User has either content:read OR admin:access
1798
+ }
1799
+ );
1800
+
1358
1801
  // Role-based
1359
1802
  app.bind(
1360
1803
  adminDashboardContract,
@@ -1468,10 +1911,22 @@ import '@spfn/auth/nextjs/api';
1468
1911
  **Target Routes:**
1469
1912
  - `/_auth/login`, `/_auth/register` - Login/register interceptor
1470
1913
  - `/_auth/keys/rotate` - Key rotation interceptor
1914
+ - `/_auth/oauth/:provider/url` - OAuth URL interceptor (keypair + state generation)
1915
+ - `/_auth/oauth/finalize` - OAuth finalize interceptor (pending session → full session)
1471
1916
  - All other authenticated routes - General auth interceptor
1472
1917
 
1473
1918
  ---
1474
1919
 
1920
+ ### OAuth Client Component (`@spfn/auth/nextjs/client`)
1921
+
1922
+ ```typescript
1923
+ import { OAuthCallback, type OAuthCallbackProps } from '@spfn/auth/nextjs/client';
1924
+ ```
1925
+
1926
+ OAuth 콜백 페이지용 `'use client'` 컴포넌트. 자세한 사용법은 [OAuth Authentication](#oauth-authentication) 섹션 참조.
1927
+
1928
+ ---
1929
+
1475
1930
  ## Testing
1476
1931
 
1477
1932
  ### Setup Test Environment
@@ -1817,7 +2272,7 @@ ls migrations/
1817
2272
 
1818
2273
  - [ ] **React hooks** - useAuth, useSession, usePermissions
1819
2274
  - [ ] **UI components** - LoginForm, RegisterForm, AuthProvider
1820
- - [ ] **OAuth integration** - Google, GitHub, etc.
2275
+ - [x] **OAuth integration** - Google (implemented), GitHub/Kakao/Naver (planned)
1821
2276
  - [ ] **2FA support** - TOTP/authenticator apps
1822
2277
  - [ ] **Password reset flow** - Complete email-based reset
1823
2278
  - [ ] **Email change flow** - Verification for email updates
@@ -1957,6 +2412,6 @@ MIT License - See LICENSE file for details.
1957
2412
 
1958
2413
  ---
1959
2414
 
1960
- **Last Updated:** 2025-12-07
1961
- **Document Version:** 2.2.0 (Technical Documentation)
1962
- **Package Version:** 0.1.0-alpha.88
2415
+ **Last Updated:** 2026-01-29
2416
+ **Document Version:** 2.5.0 (Technical Documentation)
2417
+ **Package Version:** 0.2.0-beta.15