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

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,6 +133,17 @@ SPFN_AUTH_JWT_EXPIRES_IN=7d
122
133
  SPFN_AUTH_BCRYPT_SALT_ROUNDS=10
123
134
  SPFN_AUTH_SESSION_TTL=7d
124
135
 
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
140
+
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
+
125
147
  # AWS SES (Email)
126
148
  SPFN_AUTH_AWS_REGION=ap-northeast-2
127
149
  SPFN_AUTH_AWS_SES_ACCESS_KEY_ID=AKIA...
@@ -144,6 +166,83 @@ pnpm spfn db generate
144
166
  pnpm spfn db migrate
145
167
  ```
146
168
 
169
+ ### 6. Admin Account Setup
170
+
171
+ Admin accounts are automatically created on server startup via `createAuthLifecycle()`.
172
+ Choose one of the following methods:
173
+
174
+ #### Method 1: JSON Format (Recommended)
175
+
176
+ Best for multiple accounts with full configuration:
177
+
178
+ ```bash
179
+ SPFN_AUTH_ADMIN_ACCOUNTS='[
180
+ {"email": "superadmin@example.com", "password": "secure-pass-1", "role": "superadmin"},
181
+ {"email": "admin@example.com", "password": "secure-pass-2", "role": "admin"},
182
+ {"email": "manager@example.com", "password": "secure-pass-3", "role": "user"}
183
+ ]'
184
+ ```
185
+
186
+ **JSON Schema:**
187
+ ```typescript
188
+ interface AdminAccountConfig {
189
+ email: string; // Required
190
+ password: string; // Required
191
+ role?: string; // Default: 'user' (options: 'user', 'admin', 'superadmin')
192
+ phone?: string; // Optional
193
+ passwordChangeRequired?: boolean; // Default: true
194
+ }
195
+ ```
196
+
197
+ #### Method 2: CSV Format
198
+
199
+ For multiple accounts with simpler configuration:
200
+
201
+ ```bash
202
+ SPFN_AUTH_ADMIN_EMAILS=admin@example.com,manager@example.com
203
+ SPFN_AUTH_ADMIN_PASSWORDS=admin-pass,manager-pass
204
+ SPFN_AUTH_ADMIN_ROLES=superadmin,admin
205
+ ```
206
+
207
+ #### Method 3: Single Account (Legacy)
208
+
209
+ Simplest format for a single superadmin:
210
+
211
+ ```bash
212
+ SPFN_AUTH_ADMIN_EMAIL=admin@example.com
213
+ SPFN_AUTH_ADMIN_PASSWORD=secure-password
214
+ ```
215
+
216
+ > **Note:** This method always creates a `superadmin` role account.
217
+
218
+ #### Default Behavior
219
+
220
+ All admin accounts created via environment variables have:
221
+ - `emailVerifiedAt`: Auto-verified (current timestamp)
222
+ - `passwordChangeRequired`: `true` (must change on first login)
223
+ - `status`: `active`
224
+
225
+ #### Programmatic Creation
226
+
227
+ You can also create admin accounts programmatically:
228
+
229
+ ```typescript
230
+ import { usersRepository, getRoleByName, hashPassword } from '@spfn/auth/server';
231
+
232
+ // After initializeAuth() has been called
233
+ const role = await getRoleByName('admin');
234
+ const passwordHash = await hashPassword('secure-password');
235
+
236
+ await usersRepository.create({
237
+ email: 'admin@example.com',
238
+ passwordHash,
239
+ roleId: role.id,
240
+ emailVerifiedAt: new Date(),
241
+ passwordChangeRequired: true,
242
+ status: 'active',
243
+ });
244
+ ```
245
+
147
246
  ---
148
247
 
149
248
  ## Architecture
@@ -335,20 +434,15 @@ packages/auth/
335
434
 
336
435
  ### Common Module (`@spfn/auth`)
337
436
 
338
- **Entities:**
437
+ **API Client:**
339
438
  ```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';
439
+ import { authApi } from '@spfn/auth';
440
+
441
+ // Type-safe API calls
442
+ const session = await authApi.getAuthSession.call({});
443
+ const result = await authApi.login.call({
444
+ body: { email, password, fingerprint, publicKey, keyId }
445
+ });
352
446
  ```
353
447
 
354
448
  **Types:**
@@ -359,6 +453,9 @@ import type {
359
453
  VerificationCode,
360
454
  Role,
361
455
  Permission,
456
+ AuthSession,
457
+ UserProfile,
458
+ ProfileInfo,
362
459
  // ... etc
363
460
  } from '@spfn/auth';
364
461
  ```
@@ -380,6 +477,34 @@ import type {
380
477
  } from '@spfn/auth';
381
478
  ```
382
479
 
480
+ **Validation Patterns:**
481
+ ```typescript
482
+ import {
483
+ UUID_PATTERN,
484
+ EMAIL_PATTERN,
485
+ BASE64_PATTERN,
486
+ FINGERPRINT_PATTERN,
487
+ PHONE_PATTERN,
488
+ } from '@spfn/auth';
489
+ ```
490
+
491
+ **Route Map (for RPC Proxy):**
492
+ ```typescript
493
+ import { authRouteMap } from '@spfn/auth';
494
+
495
+ // Use in Next.js RPC proxy (app/api/rpc/[routeName]/route.ts)
496
+ import '@spfn/auth/nextjs/api'; // Auto-register auth interceptors
497
+ import { routeMap } from '@/generated/route-map';
498
+ import { authRouteMap } from '@spfn/auth';
499
+ import { createRpcProxy } from '@spfn/core/nextjs/proxy';
500
+
501
+ export const { GET, POST } = createRpcProxy({
502
+ routeMap: { ...routeMap, ...authRouteMap }
503
+ });
504
+ ```
505
+
506
+ > **Note:** Database entities (`users`, `userPublicKeys`, etc.) are exported from `@spfn/auth/server`, not the common module.
507
+
383
508
  ---
384
509
 
385
510
  ### Server Module (`@spfn/auth/server`)
@@ -456,22 +581,13 @@ import {
456
581
 
457
582
  // Session
458
583
  getAuthSessionService,
459
- getUserProfileService,
460
-
461
- // Email
462
- sendEmail,
463
- registerEmailProvider,
464
584
 
465
- // SMS
466
- sendSMS,
467
- registerSMSProvider,
585
+ // User Profile
586
+ getUserProfileService,
587
+ updateUserProfileService,
468
588
 
469
- // Email Templates
470
- registerEmailTemplates,
471
- getVerificationCodeTemplate,
472
- getWelcomeTemplate,
473
- getPasswordResetTemplate,
474
- getInvitationTemplate,
589
+ // OAuth - Google API Access
590
+ getGoogleAccessToken,
475
591
  } from '@spfn/auth/server';
476
592
  ```
477
593
 
@@ -495,10 +611,11 @@ import {
495
611
  import {
496
612
  authenticate,
497
613
  requirePermissions,
614
+ requireAnyPermission,
498
615
  requireRole,
499
616
  } from '@spfn/auth/server';
500
617
 
501
- // Usage
618
+ // Usage - all permissions required
502
619
  app.bind(
503
620
  myContract,
504
621
  [authenticate, requirePermissions('user:delete')],
@@ -506,6 +623,15 @@ app.bind(
506
623
  // Handler
507
624
  }
508
625
  );
626
+
627
+ // Usage - any of the permissions
628
+ app.bind(
629
+ myContract,
630
+ [authenticate, requireAnyPermission('content:read', 'admin:access')],
631
+ async (c) => {
632
+ // User has either content:read OR admin:access
633
+ }
634
+ );
509
635
  ```
510
636
 
511
637
  **Helpers:**
@@ -610,9 +736,11 @@ import {
610
736
  loginRegisterInterceptor,
611
737
  generalAuthInterceptor,
612
738
  keyRotationInterceptor,
739
+ oauthUrlInterceptor,
740
+ oauthFinalizeInterceptor,
613
741
  } from '@spfn/auth/nextjs/api';
614
742
 
615
- // Auto-registers interceptors on import
743
+ // Auto-registers interceptors on import (including OAuth)
616
744
  import '@spfn/auth/nextjs/api';
617
745
  ```
618
746
 
@@ -679,141 +807,24 @@ export default async function DashboardPage()
679
807
 
680
808
  ## Email & SMS Services
681
809
 
682
- ### Email Service
683
-
684
- The email service uses AWS SES by default, with fallback to console logging in development.
685
-
686
- **Send Email:**
687
- ```typescript
688
- import { sendEmail } from '@spfn/auth/server';
689
-
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
- });
697
- ```
698
-
699
- **Custom Email Provider:**
700
- ```typescript
701
- import { registerEmailProvider } from '@spfn/auth/server';
702
-
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
- ```
810
+ > **⚠️ DEPRECATED:** Email and SMS functionality has been moved to `@spfn/notification` package.
770
811
 
771
- ---
772
-
773
- ### Custom Templates
774
-
775
- Register custom templates to override defaults with your brand design:
812
+ ### Migration Guide
776
813
 
777
814
  ```typescript
778
- import { registerEmailTemplates } from '@spfn/auth/server';
815
+ // Before (deprecated)
816
+ import { sendEmail, sendSMS } from '@spfn/auth/server';
779
817
 
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
- });
818
+ // After (recommended)
819
+ import { sendEmail, sendSMS } from '@spfn/notification/server';
807
820
  ```
808
821
 
809
- **Template Parameters:**
822
+ The `@spfn/notification` package provides:
823
+ - Multi-channel support (Email, SMS, Slack, Push)
824
+ - Template system with variable substitution
825
+ - Multiple provider support (AWS SES, SNS, SendGrid, Twilio, etc.)
810
826
 
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?` |
827
+ For documentation, see `@spfn/notification` package README.
817
828
 
818
829
  ---
819
830
 
@@ -1027,6 +1038,437 @@ Change password.
1027
1038
 
1028
1039
  ---
1029
1040
 
1041
+ ## Events
1042
+
1043
+ `@spfn/auth`는 `@spfn/core/event`를 사용하여 인증 관련 이벤트를 발행합니다. 이를 통해 로그인/회원가입 시 추가 로직(환영 이메일, 분석, 알림 등)을 디커플링된 방식으로 처리할 수 있습니다.
1044
+
1045
+ ### Available Events
1046
+
1047
+ | Event | Description | Trigger |
1048
+ |-------|-------------|---------|
1049
+ | `auth.login` | 로그인 성공 | 이메일/전화 로그인, OAuth 기존 사용자 |
1050
+ | `auth.register` | 회원가입 성공 | 이메일/전화 회원가입, OAuth 신규 사용자 |
1051
+
1052
+ ---
1053
+
1054
+ ### Event Payloads
1055
+
1056
+ #### `auth.login`
1057
+
1058
+ ```typescript
1059
+ {
1060
+ userId: string;
1061
+ provider: 'email' | 'phone' | 'google';
1062
+ email?: string;
1063
+ phone?: string;
1064
+ }
1065
+ ```
1066
+
1067
+ #### `auth.register`
1068
+
1069
+ ```typescript
1070
+ {
1071
+ userId: string;
1072
+ provider: 'email' | 'phone' | 'google';
1073
+ email?: string;
1074
+ phone?: string;
1075
+ }
1076
+ ```
1077
+
1078
+ ---
1079
+
1080
+ ### Subscribing to Events
1081
+
1082
+ ```typescript
1083
+ import { authLoginEvent, authRegisterEvent } from '@spfn/auth/server';
1084
+
1085
+ // 로그인 이벤트 구독
1086
+ authLoginEvent.subscribe(async (payload) => {
1087
+ console.log('User logged in:', payload.userId, payload.provider);
1088
+ await analytics.trackLogin(payload.userId);
1089
+ });
1090
+
1091
+ // 회원가입 이벤트 구독
1092
+ authRegisterEvent.subscribe(async (payload) => {
1093
+ console.log('New user registered:', payload.userId);
1094
+ if (payload.email) {
1095
+ await emailService.sendWelcome(payload.email);
1096
+ }
1097
+ });
1098
+ ```
1099
+
1100
+ ---
1101
+
1102
+ ### Job Integration
1103
+
1104
+ `@spfn/core/job`과 연동하여 백그라운드 작업을 실행할 수 있습니다.
1105
+
1106
+ ```typescript
1107
+ import { job, defineJobRouter } from '@spfn/core/job';
1108
+ import { authRegisterEvent } from '@spfn/auth/server';
1109
+
1110
+ // 회원가입 시 환영 이메일 발송 Job
1111
+ const sendWelcomeEmailJob = job('send-welcome-email')
1112
+ .on(authRegisterEvent)
1113
+ .handler(async ({ userId, email }) => {
1114
+ if (email) {
1115
+ await emailService.sendWelcome(email);
1116
+ }
1117
+ });
1118
+
1119
+ // 회원가입 시 기본 설정 생성 Job
1120
+ const createDefaultSettingsJob = job('create-default-settings')
1121
+ .on(authRegisterEvent)
1122
+ .handler(async ({ userId }) => {
1123
+ await settingsService.createDefaults(userId);
1124
+ });
1125
+
1126
+ export const jobRouter = defineJobRouter({
1127
+ sendWelcomeEmailJob,
1128
+ createDefaultSettingsJob,
1129
+ });
1130
+ ```
1131
+
1132
+ ---
1133
+
1134
+ ### Event Flow
1135
+
1136
+ ```
1137
+ ┌─────────────────────────────────────────────────────────────────┐
1138
+ │ loginService() / registerService() │
1139
+ │ oauthCallbackService() │
1140
+ └─────────────────────────────────────────────────────────────────┘
1141
+
1142
+
1143
+ authLoginEvent.emit()
1144
+ authRegisterEvent.emit()
1145
+
1146
+ ┌───────────────────┼───────────────────┐
1147
+ ▼ ▼ ▼
1148
+ ┌──────────┐ ┌──────────┐ ┌──────────┐
1149
+ │ Backend │ │ Job │ │ SSE │
1150
+ │ Handler │ │ Queue │ │ Stream │
1151
+ └──────────┘ └──────────┘ └──────────┘
1152
+ .subscribe() .on(event) (optional)
1153
+ │ │
1154
+ ▼ ▼
1155
+ [Analytics, [Background
1156
+ Logging] Processing]
1157
+ ```
1158
+
1159
+ ---
1160
+
1161
+ ### Type Exports
1162
+
1163
+ ```typescript
1164
+ import type {
1165
+ AuthLoginPayload,
1166
+ AuthRegisterPayload,
1167
+ } from '@spfn/auth/server';
1168
+ ```
1169
+
1170
+ ---
1171
+
1172
+ ## OAuth Authentication
1173
+
1174
+ ### Overview
1175
+
1176
+ `@spfn/auth`는 OAuth 2.0 Authorization Code Flow를 지원합니다. 현재 Google OAuth가 구현되어 있으며, 다른 provider (GitHub, Kakao, Naver)는 동일한 패턴으로 확장 가능합니다.
1177
+
1178
+ **핵심 설계:**
1179
+ - 환경 변수만으로 설정 (`SPFN_AUTH_GOOGLE_CLIENT_ID`, `SPFN_AUTH_GOOGLE_CLIENT_SECRET`)
1180
+ - Next.js 인터셉터 기반 자동 세션 관리 (키쌍 생성 → pending session → full session)
1181
+ - 기존 이메일 계정과 자동 연결 (Google verified_email 확인 시에만)
1182
+
1183
+ ---
1184
+
1185
+ ### Authentication Flow
1186
+
1187
+ ```
1188
+ ┌──────────┐ ┌──────────────┐ ┌──────────┐ ┌──────────┐
1189
+ │ Client │ │ Next.js RPC │ │ Backend │ │ Google │
1190
+ │ (Browser)│ │ (Interceptor)│ │ (SPFN) │ │ OAuth │
1191
+ └────┬─────┘ └──────┬───────┘ └────┬─────┘ └────┬─────┘
1192
+ │ │ │ │
1193
+ │ 1. Click Login │ │ │
1194
+ ├──────────────────>│ │ │
1195
+ │ │ │ │
1196
+ │ 2. Generate keypair (ES256) │ │
1197
+ │ 3. Create encrypted state │ │
1198
+ │ (publicKey, keyId in JWE) │ │
1199
+ │ 4. Save privateKey to │ │
1200
+ │ pending session cookie │ │
1201
+ │ │ │ │
1202
+ │ │ 5. Forward with │ │
1203
+ │ │ state in body │ │
1204
+ │ ├─────────────────>│ │
1205
+ │ │ │ │
1206
+ │ │ 6. Return Google │ │
1207
+ │ │ Auth URL │ │
1208
+ │ │<─────────────────┤ │
1209
+ │ │ │ │
1210
+ │ 7. Redirect to Google │ │
1211
+ │<──────────────────┤ │ │
1212
+ │ │ │ │
1213
+ │ 8. User consents │ │ │
1214
+ ├───────────────────┼──────────────────┼────────────────>│
1215
+ │ │ │ │
1216
+ │ │ 9. Callback with code + state │
1217
+ │ │ │<────────────────┤
1218
+ │ │ │ │
1219
+ │ │ 10. Verify state, exchange code │
1220
+ │ │ Create/link user account │
1221
+ │ │ Register publicKey │
1222
+ │ │ │ │
1223
+ │ 11. Redirect to /auth/callback │ │
1224
+ │ ?userId=X&keyId=Y&returnUrl=/ │ │
1225
+ │<─────────────────────────────────────┤ │
1226
+ │ │ │ │
1227
+ │ 12. OAuthCallback │ │ │
1228
+ │ component │ │ │
1229
+ │ calls finalize│ │ │
1230
+ ├──────────────────>│ │ │
1231
+ │ │ │ │
1232
+ │ 13. Interceptor reads pending │ │
1233
+ │ session cookie, verifies │ │
1234
+ │ keyId match, creates full │ │
1235
+ │ session cookie │ │
1236
+ │ │ │ │
1237
+ │ 14. Session set, │ │ │
1238
+ │ redirect to │ │ │
1239
+ │ returnUrl │ │ │
1240
+ │<──────────────────┤ │ │
1241
+ │ │ │ │
1242
+ ```
1243
+
1244
+ ---
1245
+
1246
+ ### Setup
1247
+
1248
+ #### 1. Google Cloud Console
1249
+
1250
+ 1. [Google Cloud Console](https://console.cloud.google.com/) > APIs & Services > Credentials
1251
+ 2. Create OAuth 2.0 Client ID (Web application)
1252
+ 3. Add Authorized redirect URI: `http://localhost:8790/_auth/oauth/google/callback`
1253
+ 4. Copy Client ID and Client Secret
1254
+
1255
+ #### 2. Environment Variables
1256
+
1257
+ ```bash
1258
+ # Required
1259
+ SPFN_AUTH_GOOGLE_CLIENT_ID=your-client-id.apps.googleusercontent.com
1260
+ SPFN_AUTH_GOOGLE_CLIENT_SECRET=GOCSPX-your-secret
1261
+
1262
+ # Next.js app URL (for OAuth callback redirect)
1263
+ SPFN_APP_URL=http://localhost:3000
1264
+
1265
+ # Optional
1266
+ SPFN_AUTH_GOOGLE_SCOPES=email,profile # default (comma-separated)
1267
+ SPFN_AUTH_GOOGLE_REDIRECT_URI=http://localhost:8790/_auth/oauth/google/callback # default
1268
+ SPFN_AUTH_OAUTH_SUCCESS_URL=/auth/callback # default
1269
+ ```
1270
+
1271
+ #### 3. Next.js Callback Page
1272
+
1273
+ ```tsx
1274
+ // app/auth/callback/page.tsx
1275
+ export { OAuthCallback as default } from '@spfn/auth/nextjs/client';
1276
+ ```
1277
+
1278
+ #### 4. Login Button
1279
+
1280
+ ```typescript
1281
+ import { authApi } from '@spfn/auth';
1282
+
1283
+ const handleGoogleLogin = async () =>
1284
+ {
1285
+ const response = await authApi.getGoogleOAuthUrl.call({
1286
+ body: { returnUrl: '/dashboard' },
1287
+ });
1288
+ window.location.href = response.authUrl;
1289
+ };
1290
+ ```
1291
+
1292
+ ---
1293
+
1294
+ ### OAuth Routes
1295
+
1296
+ #### `GET /_auth/oauth/google`
1297
+
1298
+ Google OAuth 시작 (리다이렉트 방식). 브라우저를 Google 로그인 페이지로 직접 리다이렉트합니다.
1299
+
1300
+ **Query:**
1301
+ ```typescript
1302
+ {
1303
+ state: string; // Encrypted OAuth state (JWE)
1304
+ }
1305
+ ```
1306
+
1307
+ ---
1308
+
1309
+ #### `POST /_auth/oauth/google/url`
1310
+
1311
+ Google OAuth URL 획득 (인터셉터 방식). 인터셉터가 state를 자동 생성하여 주입합니다.
1312
+
1313
+ **Request:**
1314
+ ```typescript
1315
+ {
1316
+ returnUrl?: string; // Default: '/'
1317
+ }
1318
+ ```
1319
+
1320
+ **Response:**
1321
+ ```typescript
1322
+ {
1323
+ authUrl: string; // Google OAuth URL
1324
+ }
1325
+ ```
1326
+
1327
+ ---
1328
+
1329
+ #### `GET /_auth/oauth/google/callback`
1330
+
1331
+ Google에서 리다이렉트되는 콜백. code를 token으로 교환하고 사용자를 생성/연결합니다.
1332
+
1333
+ **Query (from Google):**
1334
+ ```typescript
1335
+ {
1336
+ code?: string; // Authorization code
1337
+ state?: string; // OAuth state
1338
+ error?: string; // Error code
1339
+ error_description?: string; // Error description
1340
+ }
1341
+ ```
1342
+
1343
+ **Result:** Next.js 콜백 페이지로 리다이렉트 (`/auth/callback?userId=X&keyId=Y&returnUrl=/`)
1344
+
1345
+ ---
1346
+
1347
+ #### `POST /_auth/oauth/finalize`
1348
+
1349
+ OAuth 세션 완료. 인터셉터가 pending session에서 full session을 생성합니다.
1350
+
1351
+ **Request:**
1352
+ ```typescript
1353
+ {
1354
+ userId: string;
1355
+ keyId: string;
1356
+ returnUrl?: string;
1357
+ }
1358
+ ```
1359
+
1360
+ **Response:**
1361
+ ```typescript
1362
+ {
1363
+ success: boolean;
1364
+ returnUrl: string;
1365
+ }
1366
+ ```
1367
+
1368
+ ---
1369
+
1370
+ #### `GET /_auth/oauth/providers`
1371
+
1372
+ 활성화된 OAuth provider 목록을 반환합니다.
1373
+
1374
+ **Response:**
1375
+ ```typescript
1376
+ {
1377
+ providers: ('google' | 'github' | 'kakao' | 'naver')[];
1378
+ }
1379
+ ```
1380
+
1381
+ ---
1382
+
1383
+ ### Google API Access
1384
+
1385
+ OAuth 로그인 후 저장된 access token으로 Google API를 호출할 수 있습니다.
1386
+
1387
+ #### Custom Scopes 설정
1388
+
1389
+ `SPFN_AUTH_GOOGLE_SCOPES` 환경변수로 추가 스코프를 요청합니다. 미설정 시 `email,profile`이 기본값입니다.
1390
+
1391
+ ```bash
1392
+ # Gmail + Calendar 읽기 권한 추가
1393
+ SPFN_AUTH_GOOGLE_SCOPES=email,profile,https://www.googleapis.com/auth/gmail.readonly,https://www.googleapis.com/auth/calendar.readonly
1394
+ ```
1395
+
1396
+ > **Note:** Google Cloud Console에서 해당 API를 활성화해야 합니다.
1397
+
1398
+ #### Access Token 사용
1399
+
1400
+ `getGoogleAccessToken(userId)`은 유효한 access token을 반환합니다. 토큰이 만료 임박(5분 이내) 또는 만료 상태이면 자동으로 refresh token을 사용하여 갱신합니다.
1401
+
1402
+ ```typescript
1403
+ import { getGoogleAccessToken } from '@spfn/auth/server';
1404
+
1405
+ // 항상 유효한 토큰 반환 (만료 시 자동 갱신)
1406
+ const token = await getGoogleAccessToken(userId);
1407
+
1408
+ // Gmail API 호출
1409
+ const response = await fetch(
1410
+ 'https://gmail.googleapis.com/gmail/v1/users/me/messages?maxResults=10',
1411
+ { headers: { Authorization: `Bearer ${token}` } }
1412
+ );
1413
+ const data = await response.json();
1414
+ ```
1415
+
1416
+ **에러 케이스:**
1417
+ - Google 계정 미연결 → `'No Google account linked'`
1418
+ - Refresh token 없음 → `'Google refresh token not available'` (재로그인 필요)
1419
+
1420
+ ---
1421
+
1422
+ ### Security
1423
+
1424
+ - **State 암호화**: JWE (A256GCM)로 state 파라미터 암호화. CSRF 방지용 nonce 포함.
1425
+ - **Pending Session**: OAuth 리다이렉트 중 privateKey를 JWE로 암호화한 HttpOnly 쿠키에 저장. 10분 TTL.
1426
+ - **KeyId 검증**: finalize 시 pending session의 keyId와 응답의 keyId 일치 확인.
1427
+ - **Email 검증**: `verified_email`이 true인 경우에만 기존 계정에 자동 연결. 미검증 이메일로 기존 계정 연결 시도 시 에러.
1428
+ - **Session Cookie**: `HttpOnly`, `Secure` (production), `SameSite=strict`.
1429
+
1430
+ ---
1431
+
1432
+ ### OAuthCallback Component
1433
+
1434
+ `@spfn/auth/nextjs/client`에서 제공하는 클라이언트 컴포넌트입니다.
1435
+
1436
+ ```tsx
1437
+ import { OAuthCallback } from '@spfn/auth/nextjs/client';
1438
+
1439
+ // 기본 사용
1440
+ export default function CallbackPage()
1441
+ {
1442
+ return <OAuthCallback />;
1443
+ }
1444
+
1445
+ // 커스터마이징
1446
+ export default function CallbackPage()
1447
+ {
1448
+ return (
1449
+ <OAuthCallback
1450
+ apiBasePath="/api/rpc"
1451
+ loadingComponent={<MySpinner />}
1452
+ errorComponent={(error) => <MyError message={error} />}
1453
+ onSuccess={(userId) => console.log('Logged in:', userId)}
1454
+ onError={(error) => console.error(error)}
1455
+ />
1456
+ );
1457
+ }
1458
+ ```
1459
+
1460
+ **Props:**
1461
+
1462
+ | Prop | Type | Default | Description |
1463
+ |------|------|---------|-------------|
1464
+ | `apiBasePath` | `string` | `'/api/rpc'` | RPC API base path |
1465
+ | `loadingComponent` | `ReactNode` | Built-in | 로딩 중 표시할 컴포넌트 |
1466
+ | `errorComponent` | `(error: string) => ReactNode` | Built-in | 에러 표시 컴포넌트 |
1467
+ | `onSuccess` | `(userId: string) => void` | - | 성공 콜백 |
1468
+ | `onError` | `(error: string) => void` | - | 에러 콜백 |
1469
+
1470
+ ---
1471
+
1030
1472
  ## Database Schema
1031
1473
 
1032
1474
  ### Core Tables
@@ -1167,7 +1609,7 @@ CREATE TABLE permissions (
1167
1609
 
1168
1610
  **Built-in Permissions:**
1169
1611
  - `auth:self:manage`
1170
- - `user:read`, `user:write`, `user:delete`
1612
+ - `user:read`, `user:write`, `user:delete`, `user:invite`
1171
1613
  - `rbac:role:manage`, `rbac:permission:manage`
1172
1614
 
1173
1615
  ---
@@ -1260,7 +1702,7 @@ CREATE TABLE user_profiles (
1260
1702
 
1261
1703
  #### `user_social_accounts`
1262
1704
 
1263
- OAuth provider accounts (future feature).
1705
+ OAuth provider accounts (Google, GitHub, etc.).
1264
1706
 
1265
1707
  ```sql
1266
1708
  CREATE TABLE user_social_accounts (
@@ -1327,7 +1769,7 @@ await initializeAuth({
1327
1769
 
1328
1770
  **Permissions:**
1329
1771
  - `auth:self:manage` - Change password, rotate keys
1330
- - `user:read`, `user:write`, `user:delete`
1772
+ - `user:read`, `user:write`, `user:delete`, `user:invite`
1331
1773
  - `rbac:role:manage`, `rbac:permission:manage`
1332
1774
 
1333
1775
  ---
@@ -1335,7 +1777,7 @@ await initializeAuth({
1335
1777
  ### Middleware Usage
1336
1778
 
1337
1779
  ```typescript
1338
- import { authenticate, requirePermissions, requireRole } from '@spfn/auth/server';
1780
+ import { authenticate, requirePermissions, requireAnyPermission, requireRole } from '@spfn/auth/server';
1339
1781
 
1340
1782
  // Single permission
1341
1783
  app.bind(
@@ -1355,6 +1797,15 @@ app.bind(
1355
1797
  }
1356
1798
  );
1357
1799
 
1800
+ // Any of the permissions (at least one required)
1801
+ app.bind(
1802
+ viewContentContract,
1803
+ [authenticate, requireAnyPermission('content:read', 'admin:access')],
1804
+ async (c) => {
1805
+ // User has either content:read OR admin:access
1806
+ }
1807
+ );
1808
+
1358
1809
  // Role-based
1359
1810
  app.bind(
1360
1811
  adminDashboardContract,
@@ -1468,10 +1919,22 @@ import '@spfn/auth/nextjs/api';
1468
1919
  **Target Routes:**
1469
1920
  - `/_auth/login`, `/_auth/register` - Login/register interceptor
1470
1921
  - `/_auth/keys/rotate` - Key rotation interceptor
1922
+ - `/_auth/oauth/:provider/url` - OAuth URL interceptor (keypair + state generation)
1923
+ - `/_auth/oauth/finalize` - OAuth finalize interceptor (pending session → full session)
1471
1924
  - All other authenticated routes - General auth interceptor
1472
1925
 
1473
1926
  ---
1474
1927
 
1928
+ ### OAuth Client Component (`@spfn/auth/nextjs/client`)
1929
+
1930
+ ```typescript
1931
+ import { OAuthCallback, type OAuthCallbackProps } from '@spfn/auth/nextjs/client';
1932
+ ```
1933
+
1934
+ OAuth 콜백 페이지용 `'use client'` 컴포넌트. 자세한 사용법은 [OAuth Authentication](#oauth-authentication) 섹션 참조.
1935
+
1936
+ ---
1937
+
1475
1938
  ## Testing
1476
1939
 
1477
1940
  ### Setup Test Environment
@@ -1817,7 +2280,7 @@ ls migrations/
1817
2280
 
1818
2281
  - [ ] **React hooks** - useAuth, useSession, usePermissions
1819
2282
  - [ ] **UI components** - LoginForm, RegisterForm, AuthProvider
1820
- - [ ] **OAuth integration** - Google, GitHub, etc.
2283
+ - [x] **OAuth integration** - Google (implemented), GitHub/Kakao/Naver (planned)
1821
2284
  - [ ] **2FA support** - TOTP/authenticator apps
1822
2285
  - [ ] **Password reset flow** - Complete email-based reset
1823
2286
  - [ ] **Email change flow** - Verification for email updates
@@ -1957,6 +2420,6 @@ MIT License - See LICENSE file for details.
1957
2420
 
1958
2421
  ---
1959
2422
 
1960
- **Last Updated:** 2025-12-07
1961
- **Document Version:** 2.2.0 (Technical Documentation)
1962
- **Package Version:** 0.1.0-alpha.88
2423
+ **Last Updated:** 2026-01-29
2424
+ **Document Version:** 2.5.0 (Technical Documentation)
2425
+ **Package Version:** 0.2.0-beta.15