@enlt-bakusoku/nuxt4 0.0.0-stage → 2.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 +38 -2
- package/dist/module.d.mts +25 -0
- package/dist/module.json +9 -0
- package/dist/module.mjs +208 -0
- package/dist/runtime/shared/schemas/user.d.ts +40 -0
- package/dist/runtime/shared/schemas/user.js +21 -0
- package/dist/runtime/tasks-catalog.d.ts +6 -0
- package/dist/runtime/tasks-catalog.js +7 -0
- package/dist/types.d.mts +9 -0
- package/package.json +120 -3
- package/scripts/bakusoku-dev.mjs +387 -0
- package/scripts/dev-log-relay.mjs +96 -0
- package/scripts/predeploy.mjs +24 -0
- package/scripts/prepare-firebase-artifact.mjs +43 -0
- package/scripts/setup-worktree.sh +59 -0
- package/scripts/verify-firebase-artifacts.mjs +70 -0
- package/src/layer/app/components/admin/AdminExecutionHistory.vue +137 -0
- package/src/layer/app/components/admin/TaskRunDialog.vue +162 -0
- package/src/layer/app/components/admin/UserManagementPage.vue +342 -0
- package/src/layer/app/components/debug/DebugApplicationLogs.vue +87 -0
- package/src/layer/app/components/debug/DebugErrorLogs.vue +47 -0
- package/src/layer/app/components/debug/DebugFirestoreOperations.vue +48 -0
- package/src/layer/app/components/debug/DebugHttpRequests.vue +86 -0
- package/src/layer/app/components/debug/DebugNavigation.vue +60 -0
- package/src/layer/app/components/debug/DebugNowControl.vue +243 -0
- package/src/layer/app/components/debug/DebugPublicConfig.vue +24 -0
- package/src/layer/app/components/debug/DebugTestAdmin.vue +67 -0
- package/src/layer/app/components/demo/DemoDebug.vue +266 -0
- package/src/layer/app/components/demo/DemoHome.vue +347 -0
- package/src/layer/app/components/demo/DemoLogin.vue +391 -0
- package/src/layer/app/components/demo/DemoPassword.vue +224 -0
- package/src/layer/app/components/demo/DemoRegister.vue +148 -0
- package/src/layer/app/components/home/HomePage.vue +77 -0
- package/src/layer/app/layouts/dashboard.vue +126 -0
- package/src/layer/app/layouts/default.vue +3 -0
- package/src/layer/app/middleware/admin.ts +15 -0
- package/src/layer/app/middleware/authenticated.ts +19 -0
- package/src/layer/app/pages/admin/migrations.vue +463 -0
- package/src/layer/app/pages/admin/tasks/[id].vue +276 -0
- package/src/layer/app/pages/admin/tasks/index.vue +220 -0
- package/src/layer/app/pages/admin/users.vue +17 -0
- package/src/layer/app/pages/bakusoku-devtools.vue +294 -0
- package/src/layer/app/plugins/auth-init.ts +36 -0
- package/src/layer/app/plugins/debug-devtools.client.ts +20 -0
- package/src/layer/app/plugins/debug-errors.client.ts +78 -0
- package/src/layer/app/plugins/debug-http.client.ts +154 -0
- package/src/layer/app/plugins/debug-nav.client.ts +28 -0
- package/src/layer/app/plugins/vuefire-inspect.ts +18 -0
- package/src/layer/app/stores/auth.ts +462 -0
- package/src/layer/app/stores/datetime.ts +41 -0
- package/src/layer/app/stores/debug.ts +235 -0
- package/src/layer/app/stores/user.ts +170 -0
- package/src/layer/app/utils/admin-execution.ts +48 -0
- package/src/layer/app/utils/dashboard-heading.ts +36 -0
- package/src/layer/app/utils/debug-bridge.ts +270 -0
- package/src/layer/app/utils/debug-firestore.ts +38 -0
- package/src/layer/app/utils/debug-format.ts +19 -0
- package/src/layer/app/utils/execution-refresh.ts +66 -0
- package/src/layer/app/utils/framework-version.ts +4 -0
- package/src/layer/app/utils/inspect-nuxt-vuefire.ts +288 -0
- package/src/layer/app/utils/is-debug-enabled.ts +13 -0
- package/src/layer/app/utils/logger.ts +235 -0
- package/src/layer/app/utils/map-auth-error.ts +11 -0
- package/src/layer/app/utils/mask-secrets.ts +100 -0
- package/src/layer/app/utils/resolve-auth-user.ts +53 -0
- package/src/layer/app/utils/resolve-firestore.ts +20 -0
- package/src/layer/app/utils/task-run.ts +15 -0
- package/src/layer/build-credentials.mjs +33 -0
- package/src/layer/nuxt.config.ts +86 -0
- package/src/layer/package.json +5 -0
- package/src/layer/server/api/debug/test-admin.post.ts +38 -0
- package/src/layer/server/api/tasks/executions/cancel.post.ts +21 -0
- package/src/layer/server/api/tasks/executions/index.get.ts +22 -0
- package/src/layer/server/api/tasks/executions/index.post.ts +25 -0
- package/src/layer/server/api/tasks/index.get.ts +70 -0
- package/src/layer/server/api/tasks/migrations/index.post.ts +27 -0
- package/src/layer/server/api/tasks/migrations/recovery.post.ts +20 -0
- package/src/layer/server/api/users/[id].delete.ts +57 -0
- package/src/layer/server/api/users/[id].put.ts +110 -0
- package/src/layer/server/api/users/index.post.ts +232 -0
- package/src/layer/server/utils/admin-access.ts +32 -0
- package/src/layer/server/utils/debug-test-admin.ts +17 -0
- package/src/layer/server/utils/firebase-admin.ts +22 -0
- package/src/layer/server/utils/logger.ts +172 -0
- package/src/layer/server/utils/tasks-gateway.ts +57 -0
- package/src/layer/server/utils/user-mutations.ts +103 -0
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
import { tasksCatalog } from '#bakusoku/tasks-catalog'
|
|
2
|
+
import { getMigrationPlanStatus, latestExecutions, listMigrationStates, subjectName, summarizeMigrations, summarizeSchedules, summarizeTasks, type MigrationCatalogEntry, type TaskCatalogEntry } from '@enlt-bakusoku/functions/enqueue-task'
|
|
3
|
+
import { assertTasksAdmin } from '../../utils/tasks-gateway'
|
|
4
|
+
|
|
5
|
+
/** 管理画面で利用するタスクやマイグレーションの情報を返す。 */
|
|
6
|
+
export default defineEventHandler(async (event) => {
|
|
7
|
+
await assertTasksAdmin(event)
|
|
8
|
+
const catalog = tasksCatalog() as {
|
|
9
|
+
tasks?: readonly TaskCatalogEntry[]
|
|
10
|
+
migrations?: readonly MigrationCatalogEntry[]
|
|
11
|
+
schedules?: Parameters<typeof summarizeSchedules>[0]
|
|
12
|
+
}
|
|
13
|
+
const tasks = summarizeTasks(catalog.tasks ?? [])
|
|
14
|
+
const migrations = summarizeMigrations(catalog.migrations ?? [])
|
|
15
|
+
const migrationState = new Map<string, 'running' | 'succeeded' | 'absent'>()
|
|
16
|
+
let migrationStatesAvailable = true
|
|
17
|
+
let migrationPlan: Awaited<ReturnType<typeof getMigrationPlanStatus>> = null
|
|
18
|
+
try {
|
|
19
|
+
const [states, plan] = await Promise.all([
|
|
20
|
+
listMigrationStates(migrations.map(migration => migration.id)),
|
|
21
|
+
getMigrationPlanStatus(),
|
|
22
|
+
])
|
|
23
|
+
migrationPlan = plan
|
|
24
|
+
for (const state of states) {
|
|
25
|
+
migrationState.set(state.id, state.status)
|
|
26
|
+
}
|
|
27
|
+
} catch {
|
|
28
|
+
migrationStatesAvailable = false
|
|
29
|
+
}
|
|
30
|
+
const schedules = summarizeSchedules(catalog.schedules ?? [])
|
|
31
|
+
let latestAvailable = true
|
|
32
|
+
const latestByTask = new Map<string, Awaited<ReturnType<typeof latestExecutions>>[number]>()
|
|
33
|
+
try {
|
|
34
|
+
const latest = await latestExecutions('task', tasks.map(task => task.id))
|
|
35
|
+
for (const row of latest) {
|
|
36
|
+
latestByTask.set(row.subjectId, row)
|
|
37
|
+
}
|
|
38
|
+
} catch {
|
|
39
|
+
latestAvailable = false
|
|
40
|
+
}
|
|
41
|
+
return {
|
|
42
|
+
success: true,
|
|
43
|
+
data: {
|
|
44
|
+
latestAvailable,
|
|
45
|
+
migrationStatesAvailable,
|
|
46
|
+
migrationPlan,
|
|
47
|
+
tasks: tasks.map(task => {
|
|
48
|
+
const latest = latestByTask.get(task.id)
|
|
49
|
+
return {
|
|
50
|
+
...task,
|
|
51
|
+
schedules: schedules.flatMap(schedule => schedule.registrations
|
|
52
|
+
.filter(registration => registration.taskId === task.id)
|
|
53
|
+
.map(registration => ({
|
|
54
|
+
id: schedule.id,
|
|
55
|
+
schedule: schedule.schedule,
|
|
56
|
+
timeZone: schedule.timeZone,
|
|
57
|
+
registrationId: registration.id,
|
|
58
|
+
}))),
|
|
59
|
+
latest: latest
|
|
60
|
+
? { ...latest, name: subjectName(latest, tasks, migrations) }
|
|
61
|
+
: null,
|
|
62
|
+
}
|
|
63
|
+
}),
|
|
64
|
+
migrations: migrations.map(migration => ({
|
|
65
|
+
...migration,
|
|
66
|
+
state: migrationState.get(migration.id) ?? 'absent',
|
|
67
|
+
})),
|
|
68
|
+
},
|
|
69
|
+
}
|
|
70
|
+
})
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import { tasksCatalog } from '#bakusoku/tasks-catalog'
|
|
2
|
+
import { enqueueMigration } from '@enlt-bakusoku/functions/enqueue-task'
|
|
3
|
+
import { assertTasksAdmin, rethrowExecutionError } from '../../../utils/tasks-gateway'
|
|
4
|
+
|
|
5
|
+
/** 管理者からのマイグレーション移動依頼を検証し、最初の版をキューに登録する。 */
|
|
6
|
+
export default defineEventHandler(async (event) => {
|
|
7
|
+
const admin = await assertTasksAdmin(event)
|
|
8
|
+
const body = await readBody(event)
|
|
9
|
+
const executionId = typeof body?.executionId === 'string' ? body.executionId.trim() : ''
|
|
10
|
+
const targetId = typeof body?.targetId === 'string' ? body.targetId.trim() : ''
|
|
11
|
+
const direction = body?.direction === 'down' ? 'down' : 'up'
|
|
12
|
+
if (!executionId || (direction === 'up' && !targetId)) {
|
|
13
|
+
throw createError({ statusCode: 400, message: '実行IDと到達するバージョンが必要です。' })
|
|
14
|
+
}
|
|
15
|
+
try {
|
|
16
|
+
const result = await enqueueMigration({
|
|
17
|
+
catalog: tasksCatalog().migrations ?? [],
|
|
18
|
+
executionId,
|
|
19
|
+
targetId,
|
|
20
|
+
direction,
|
|
21
|
+
actorUid: admin.uid,
|
|
22
|
+
})
|
|
23
|
+
return { success: true, data: result }
|
|
24
|
+
} catch (error) {
|
|
25
|
+
rethrowExecutionError(error)
|
|
26
|
+
}
|
|
27
|
+
})
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import { resolveStalledMigrationPlan } from '@enlt-bakusoku/functions/enqueue-task'
|
|
2
|
+
import { createError, defineEventHandler, readBody } from 'h3'
|
|
3
|
+
import { assertTasksAdmin, rethrowExecutionError } from '../../../utils/tasks-gateway'
|
|
4
|
+
|
|
5
|
+
/** 管理者が確認した適用状態を記録し、停止した計画を終了する。 */
|
|
6
|
+
export default defineEventHandler(async (event) => {
|
|
7
|
+
const admin = await assertTasksAdmin(event)
|
|
8
|
+
const body = await readBody(event)
|
|
9
|
+
const executionId = typeof body?.executionId === 'string' ? body.executionId.trim() : ''
|
|
10
|
+
const applied: unknown = body?.applied
|
|
11
|
+
if (!executionId || (applied !== undefined && typeof applied !== 'boolean')) {
|
|
12
|
+
throw createError({ statusCode: 400, message: '実行IDと確認した適用状態を確認してください。' })
|
|
13
|
+
}
|
|
14
|
+
try {
|
|
15
|
+
await resolveStalledMigrationPlan({ executionId, applied, actorUid: admin.uid })
|
|
16
|
+
return { success: true }
|
|
17
|
+
} catch (error) {
|
|
18
|
+
rethrowExecutionError(error)
|
|
19
|
+
}
|
|
20
|
+
})
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
import { getAdminAuth, getAdminFirestore } from '../../utils/firebase-admin'
|
|
2
|
+
import { assertUserAdmin } from '../../utils/admin-access'
|
|
3
|
+
import { useBakusokuServerLogger } from '../../utils/logger'
|
|
4
|
+
import { assertRetainsActiveAdmin, removeAuthUser, revokeAuthUser, userMutationError } from '../../utils/user-mutations'
|
|
5
|
+
import { FieldValue } from 'firebase-admin/firestore'
|
|
6
|
+
import {
|
|
7
|
+
getRouterParam,
|
|
8
|
+
assertMethod,
|
|
9
|
+
defineEventHandler,
|
|
10
|
+
createError
|
|
11
|
+
} from 'h3'
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* DELETE /api/users/:id — ユーザー削除
|
|
15
|
+
*/
|
|
16
|
+
export default defineEventHandler(async event => {
|
|
17
|
+
assertMethod(event, 'DELETE')
|
|
18
|
+
await assertUserAdmin(event)
|
|
19
|
+
const logger = useBakusokuServerLogger('users-api')
|
|
20
|
+
|
|
21
|
+
const uid = getRouterParam(event, 'id')
|
|
22
|
+
if (!uid) {
|
|
23
|
+
throw createError({ statusCode: 400, message: 'ユーザーIDが指定されていません。' })
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
try {
|
|
27
|
+
const auth = getAdminAuth()
|
|
28
|
+
const db = getAdminFirestore()
|
|
29
|
+
|
|
30
|
+
await assertRetainsActiveAdmin(db, uid, { deleting: true })
|
|
31
|
+
const profile = db.collection('users').doc(uid)
|
|
32
|
+
// Auth の削除が失敗しても再試行できるよう、権限を外したプロフィールを残す。
|
|
33
|
+
await db.runTransaction(async (tx) => {
|
|
34
|
+
const current = await tx.get(profile)
|
|
35
|
+
if (current.exists && current.get('deletionPending') !== true) {
|
|
36
|
+
tx.update(profile, {
|
|
37
|
+
role: FieldValue.delete(),
|
|
38
|
+
disabled: true,
|
|
39
|
+
deletionPending: true,
|
|
40
|
+
updatedAt: FieldValue.serverTimestamp(),
|
|
41
|
+
})
|
|
42
|
+
}
|
|
43
|
+
})
|
|
44
|
+
await revokeAuthUser(auth, uid)
|
|
45
|
+
await removeAuthUser(auth, uid)
|
|
46
|
+
await db.runTransaction(async (tx) => {
|
|
47
|
+
const current = await tx.get(profile)
|
|
48
|
+
if (current.get('deletionPending') === true) tx.delete(profile)
|
|
49
|
+
})
|
|
50
|
+
logger.info('User deleted successfully', { uid })
|
|
51
|
+
|
|
52
|
+
return { success: true }
|
|
53
|
+
} catch (err: unknown) {
|
|
54
|
+
logger.error('Failed to delete user', err, { uid })
|
|
55
|
+
throw userMutationError(err, 'ユーザーの削除を完了できませんでした。再度お試しください。')
|
|
56
|
+
}
|
|
57
|
+
})
|
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
import { getAdminAuth, getAdminFirestore } from '../../utils/firebase-admin'
|
|
2
|
+
import { assertUserAdmin } from '../../utils/admin-access'
|
|
3
|
+
import { useBakusokuServerLogger } from '../../utils/logger'
|
|
4
|
+
import { assertRetainsActiveAdmin, revokeAuthUser, userMutationError } from '../../utils/user-mutations'
|
|
5
|
+
import type { UpdateRequest } from 'firebase-admin/auth'
|
|
6
|
+
import { FieldValue, type DocumentSnapshot } from 'firebase-admin/firestore'
|
|
7
|
+
import { updateUserSchema, type UpdateUserInput } from '#bakusoku/user-schemas'
|
|
8
|
+
import {
|
|
9
|
+
getRouterParam,
|
|
10
|
+
assertMethod,
|
|
11
|
+
defineEventHandler,
|
|
12
|
+
createError,
|
|
13
|
+
readBody
|
|
14
|
+
} from 'h3'
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* PUT /api/users/:id — ユーザー更新
|
|
18
|
+
* disabled は Firebase Auth と Firestore の両方へ書く。
|
|
19
|
+
*/
|
|
20
|
+
export default defineEventHandler(async event => {
|
|
21
|
+
assertMethod(event, 'PUT')
|
|
22
|
+
await assertUserAdmin(event)
|
|
23
|
+
const logger = useBakusokuServerLogger('users-api')
|
|
24
|
+
|
|
25
|
+
const uid = getRouterParam(event, 'id')
|
|
26
|
+
if (!uid) {
|
|
27
|
+
throw createError({ statusCode: 400, message: 'ユーザーIDが指定されていません。' })
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
const body = await readBody(event)
|
|
31
|
+
const validationResult = updateUserSchema.safeParse(body)
|
|
32
|
+
|
|
33
|
+
if (!validationResult.success) {
|
|
34
|
+
const firstIssue = validationResult.error.issues[0]
|
|
35
|
+
throw createError({
|
|
36
|
+
statusCode: 400,
|
|
37
|
+
message: firstIssue?.message ?? 'バリデーションエラーが発生しました。',
|
|
38
|
+
})
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
const validatedData: UpdateUserInput = validationResult.data
|
|
42
|
+
|
|
43
|
+
try {
|
|
44
|
+
const auth = getAdminAuth()
|
|
45
|
+
const db = getAdminFirestore()
|
|
46
|
+
const profile = db.collection('users').doc(uid)
|
|
47
|
+
const { email, displayName, disabled, password, role } = validatedData
|
|
48
|
+
await assertRetainsActiveAdmin(db, uid, { role, disabled })
|
|
49
|
+
const previous = await auth.getUser(uid)
|
|
50
|
+
const authUpdate: UpdateRequest = {
|
|
51
|
+
...(email !== undefined ? { email } : {}),
|
|
52
|
+
...(displayName !== undefined ? { displayName } : {}),
|
|
53
|
+
...(disabled !== undefined ? { disabled } : {}),
|
|
54
|
+
}
|
|
55
|
+
const restoresPreviousAuth: UpdateRequest = {
|
|
56
|
+
...(email !== undefined ? { email: previous.email } : {}),
|
|
57
|
+
...(displayName !== undefined ? { displayName: previous.displayName } : {}),
|
|
58
|
+
...(disabled !== undefined ? { disabled: previous.disabled } : {}),
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
let authChanged = false
|
|
62
|
+
if (Object.keys(authUpdate).length > 0) {
|
|
63
|
+
assertEditableProfile(await profile.get())
|
|
64
|
+
await auth.updateUser(uid, authUpdate)
|
|
65
|
+
authChanged = true
|
|
66
|
+
}
|
|
67
|
+
try {
|
|
68
|
+
// プロフィールを読み直し、同時更新の後でも Auth の現在値を反映する。
|
|
69
|
+
await db.runTransaction(async (tx) => {
|
|
70
|
+
assertEditableProfile(await tx.get(profile))
|
|
71
|
+
const current = await auth.getUser(uid)
|
|
72
|
+
tx.update(profile, {
|
|
73
|
+
updatedAt: FieldValue.serverTimestamp(),
|
|
74
|
+
...(email !== undefined ? { email: current.email ?? '' } : {}),
|
|
75
|
+
...(displayName !== undefined ? { displayName: current.displayName ?? '' } : {}),
|
|
76
|
+
...(disabled !== undefined ? { disabled: current.disabled } : {}),
|
|
77
|
+
...(role !== undefined ? { role } : {}),
|
|
78
|
+
})
|
|
79
|
+
})
|
|
80
|
+
} catch (error) {
|
|
81
|
+
if (authChanged) {
|
|
82
|
+
try {
|
|
83
|
+
await auth.updateUser(uid, restoresPreviousAuth)
|
|
84
|
+
} catch (revertError) {
|
|
85
|
+
logger.error('Failed to restore Auth user after profile update failed', revertError, { uid })
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
throw error
|
|
89
|
+
}
|
|
90
|
+
if (password !== undefined) await auth.updateUser(uid, { password })
|
|
91
|
+
const current = await auth.getUser(uid)
|
|
92
|
+
if (current.disabled === true || (role !== undefined && role !== 'admin')) {
|
|
93
|
+
await revokeAuthUser(auth, uid)
|
|
94
|
+
}
|
|
95
|
+
logger.info('User updated successfully', { uid, role: validatedData.role, disabled: validatedData.disabled })
|
|
96
|
+
|
|
97
|
+
return { success: true }
|
|
98
|
+
} catch (err: unknown) {
|
|
99
|
+
logger.error('Failed to update user', err, { uid })
|
|
100
|
+
throw userMutationError(err, 'ユーザー情報を保存できませんでした。同じ編集内容でもう一度お試しください。')
|
|
101
|
+
}
|
|
102
|
+
})
|
|
103
|
+
|
|
104
|
+
/** プロフィールの存在と、削除が開始されていないことを確認する。 */
|
|
105
|
+
function assertEditableProfile(profile: DocumentSnapshot) {
|
|
106
|
+
if (!profile.exists) throw createError({ statusCode: 404, message: 'ユーザーが見つかりません。' })
|
|
107
|
+
if (profile.get('deletionPending') === true) {
|
|
108
|
+
throw createError({ statusCode: 409, message: 'このユーザーは削除待ちです。' })
|
|
109
|
+
}
|
|
110
|
+
}
|
|
@@ -0,0 +1,232 @@
|
|
|
1
|
+
import { randomUUID } from 'node:crypto'
|
|
2
|
+
import { createUserSchema } from '#bakusoku/user-schemas'
|
|
3
|
+
import type { Auth, UserRecord } from 'firebase-admin/auth'
|
|
4
|
+
import { FieldValue, type Firestore } from 'firebase-admin/firestore'
|
|
5
|
+
import { assertUserAdmin } from '../../utils/admin-access'
|
|
6
|
+
import { getAdminAuth, getAdminFirestore } from '../../utils/firebase-admin'
|
|
7
|
+
import { useBakusokuServerLogger } from '../../utils/logger'
|
|
8
|
+
import {
|
|
9
|
+
findAuthUser,
|
|
10
|
+
findAuthUserByEmail,
|
|
11
|
+
isRecoverableAuthOrphan,
|
|
12
|
+
removeAuthUser,
|
|
13
|
+
userMutationError,
|
|
14
|
+
} from '../../utils/user-mutations'
|
|
15
|
+
import {
|
|
16
|
+
assertMethod,
|
|
17
|
+
defineEventHandler,
|
|
18
|
+
createError,
|
|
19
|
+
getHeader,
|
|
20
|
+
readBody
|
|
21
|
+
} from 'h3'
|
|
22
|
+
/**
|
|
23
|
+
* POST /api/users — ユーザー作成(スターター提供)
|
|
24
|
+
*/
|
|
25
|
+
export default defineEventHandler(async event => {
|
|
26
|
+
assertMethod(event, 'POST')
|
|
27
|
+
const logger = useBakusokuServerLogger('users-api')
|
|
28
|
+
|
|
29
|
+
const body = await readBody(event)
|
|
30
|
+
const validationResult = createUserSchema.safeParse(body)
|
|
31
|
+
|
|
32
|
+
if (!validationResult.success) {
|
|
33
|
+
const firstIssue = validationResult.error.issues[0]
|
|
34
|
+
throw createError({
|
|
35
|
+
statusCode: 400,
|
|
36
|
+
message: firstIssue?.message ?? 'バリデーションエラーが発生しました。',
|
|
37
|
+
})
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
const validatedData = validationResult.data
|
|
41
|
+
const role = validatedData.role ?? 'user'
|
|
42
|
+
// 公開登録では一般ユーザーだけを作る。管理者として作る場合と、ログイン中の作成は管理者だけ。
|
|
43
|
+
const administrator = role !== 'user' || Boolean(getHeader(event, 'authorization'))
|
|
44
|
+
if (administrator) await assertUserAdmin(event)
|
|
45
|
+
|
|
46
|
+
const issuedUid = randomUUID()
|
|
47
|
+
let uid = issuedUid
|
|
48
|
+
try {
|
|
49
|
+
const auth = getAdminAuth()
|
|
50
|
+
const db = getAdminFirestore()
|
|
51
|
+
const resolved = await resolveRegistrationUid(auth, db, issuedUid, validatedData, role, administrator)
|
|
52
|
+
uid = resolved.uid
|
|
53
|
+
const userRef = db.collection('users').doc(uid)
|
|
54
|
+
const { password: _password, ...userData } = validatedData
|
|
55
|
+
|
|
56
|
+
try {
|
|
57
|
+
await userRef.create({
|
|
58
|
+
...userData,
|
|
59
|
+
uid,
|
|
60
|
+
role,
|
|
61
|
+
createdAt: FieldValue.serverTimestamp(),
|
|
62
|
+
updatedAt: FieldValue.serverTimestamp(),
|
|
63
|
+
})
|
|
64
|
+
} catch (error) {
|
|
65
|
+
// 書き込みが反映済みなら、そのアカウントを削除せずに登録を完了する。
|
|
66
|
+
let profile
|
|
67
|
+
try {
|
|
68
|
+
profile = await userRef.get()
|
|
69
|
+
} catch (readError) {
|
|
70
|
+
// Firestore 全体に接続できない場合も、今回作成した Auth アカウントは取り消す。
|
|
71
|
+
await removeAuthUser(auth, uid)
|
|
72
|
+
await userRef.delete()
|
|
73
|
+
throw readError
|
|
74
|
+
}
|
|
75
|
+
if (!profile.exists) {
|
|
76
|
+
await removeAuthUser(auth, uid)
|
|
77
|
+
throw error
|
|
78
|
+
}
|
|
79
|
+
if (profile.get('uid') !== uid || profile.get('role') !== role || profile.get('email') !== validatedData.email) throw error
|
|
80
|
+
}
|
|
81
|
+
logger.info('User created successfully', {
|
|
82
|
+
uid,
|
|
83
|
+
email: validatedData.email,
|
|
84
|
+
role,
|
|
85
|
+
recovered: resolved.recovered,
|
|
86
|
+
})
|
|
87
|
+
return { uid }
|
|
88
|
+
} catch (err: unknown) {
|
|
89
|
+
logger.error('Failed to create user', err, { uid })
|
|
90
|
+
throw userMutationError(err, 'ユーザーを登録できませんでした。時間をおいて再度お試しください。')
|
|
91
|
+
}
|
|
92
|
+
})
|
|
93
|
+
|
|
94
|
+
type RegistrationAccount = {
|
|
95
|
+
email: string
|
|
96
|
+
password: string
|
|
97
|
+
displayName: string
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/**
|
|
101
|
+
* 未確認のパスワードアカウントは、同じメールでの再登録でパスワードを引き取る。
|
|
102
|
+
* 確認済みのアカウントはパスワードを変えず、プロフィールが無いときだけログインで作成する。
|
|
103
|
+
*/
|
|
104
|
+
async function resolveRegistrationUid(
|
|
105
|
+
auth: Auth,
|
|
106
|
+
db: Firestore,
|
|
107
|
+
issuedUid: string,
|
|
108
|
+
data: RegistrationAccount,
|
|
109
|
+
role: string,
|
|
110
|
+
emailVerified: boolean,
|
|
111
|
+
) {
|
|
112
|
+
const existing = await findAuthUserByEmail(auth, data.email)
|
|
113
|
+
if (existing) {
|
|
114
|
+
await adoptUnverifiedPasswordAccount(auth, db, existing, data, emailVerified)
|
|
115
|
+
return { uid: existing.uid, recovered: true }
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
const matches = await db.collection('users').where('email', '==', data.email).limit(2).get()
|
|
119
|
+
if (matches.size > 1) throw emailAlreadyUsed()
|
|
120
|
+
const profileUid = matches.docs[0]?.id
|
|
121
|
+
if (!profileUid) {
|
|
122
|
+
await createAuthUser(auth, issuedUid, data, emailVerified)
|
|
123
|
+
return { uid: issuedUid, recovered: false }
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
const reusedUid = await recoverProfileWithoutAuth(auth, db, profileUid, data, role)
|
|
127
|
+
const uid = reusedUid ?? issuedUid
|
|
128
|
+
await createAuthUser(auth, uid, data, emailVerified)
|
|
129
|
+
return { uid, recovered: true }
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/**
|
|
133
|
+
* メール未確認のパスワードアカウントだけ、今回のパスワードと表示名で登録を続ける。
|
|
134
|
+
* 確認済みでプロフィールが無いアカウントは、パスワードを変えずにログインへ戻す。
|
|
135
|
+
*/
|
|
136
|
+
async function adoptUnverifiedPasswordAccount(
|
|
137
|
+
auth: Auth,
|
|
138
|
+
db: Firestore,
|
|
139
|
+
existing: UserRecord,
|
|
140
|
+
data: RegistrationAccount,
|
|
141
|
+
emailVerified: boolean,
|
|
142
|
+
) {
|
|
143
|
+
const profileRef = db.collection('users').doc(existing.uid)
|
|
144
|
+
const profile = await profileRef.get()
|
|
145
|
+
if (profile.exists && profile.get('deletionPending') === true) throw deletionPendingError()
|
|
146
|
+
if (existing.emailVerified === true) {
|
|
147
|
+
if (profile.exists) throw emailAlreadyUsed()
|
|
148
|
+
throw verifiedAccountNeedsLogin()
|
|
149
|
+
}
|
|
150
|
+
if (!isRecoverableAuthOrphan(existing)) throw emailAlreadyUsed()
|
|
151
|
+
if (profile.exists && profile.get('role') !== 'user') throw emailAlreadyUsed()
|
|
152
|
+
if (profile.exists) {
|
|
153
|
+
await profileRef.update({
|
|
154
|
+
displayName: data.displayName,
|
|
155
|
+
email: data.email,
|
|
156
|
+
updatedAt: FieldValue.serverTimestamp(),
|
|
157
|
+
})
|
|
158
|
+
}
|
|
159
|
+
await auth.updateUser(existing.uid, {
|
|
160
|
+
email: data.email,
|
|
161
|
+
password: data.password,
|
|
162
|
+
displayName: data.displayName,
|
|
163
|
+
...(emailVerified ? { emailVerified: true } : {}),
|
|
164
|
+
})
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
/**
|
|
168
|
+
* Auth がないプロフィールを、同じ権限の登録として再開する。
|
|
169
|
+
* 削除待ちで Auth も消えている場合は、残りを消して新しいアカウントを作る。
|
|
170
|
+
*/
|
|
171
|
+
async function recoverProfileWithoutAuth(
|
|
172
|
+
auth: Auth,
|
|
173
|
+
db: Firestore,
|
|
174
|
+
profileUid: string,
|
|
175
|
+
data: RegistrationAccount,
|
|
176
|
+
role: string,
|
|
177
|
+
) {
|
|
178
|
+
const profile = db.collection('users').doc(profileUid)
|
|
179
|
+
const linked = await findAuthUser(auth, profileUid)
|
|
180
|
+
const snapshot = await profile.get()
|
|
181
|
+
if (!snapshot.exists) return null
|
|
182
|
+
|
|
183
|
+
if (snapshot.get('deletionPending') === true) {
|
|
184
|
+
if (linked) throw deletionPendingError()
|
|
185
|
+
await db.runTransaction(async (tx) => {
|
|
186
|
+
const current = await tx.get(profile)
|
|
187
|
+
if (current.get('deletionPending') === true) tx.delete(profile)
|
|
188
|
+
})
|
|
189
|
+
if ((await profile.get()).exists) throw emailAlreadyUsed()
|
|
190
|
+
return null
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
// 別メールの Auth が残っている、または権限が違うプロフィールは引き継がない。
|
|
194
|
+
if (linked || snapshot.get('role') !== role) throw emailAlreadyUsed()
|
|
195
|
+
await profile.update({
|
|
196
|
+
uid: profileUid,
|
|
197
|
+
displayName: data.displayName,
|
|
198
|
+
email: data.email,
|
|
199
|
+
updatedAt: FieldValue.serverTimestamp(),
|
|
200
|
+
})
|
|
201
|
+
return profileUid
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
/** 作成レスポンスが失われても、今回の UID とメールのアカウントだけを引き継ぐ。 */
|
|
205
|
+
async function createAuthUser(auth: Auth, uid: string, data: RegistrationAccount, emailVerified: boolean) {
|
|
206
|
+
try {
|
|
207
|
+
await auth.createUser({
|
|
208
|
+
uid,
|
|
209
|
+
email: data.email,
|
|
210
|
+
password: data.password,
|
|
211
|
+
displayName: data.displayName,
|
|
212
|
+
emailVerified,
|
|
213
|
+
})
|
|
214
|
+
} catch (error) {
|
|
215
|
+
const created = await findAuthUser(auth, uid)
|
|
216
|
+
if (!created || created.email !== data.email) throw error
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
function emailAlreadyUsed() {
|
|
221
|
+
return Object.assign(new Error('The email address is already in use by another account.'), {
|
|
222
|
+
code: 'auth/email-already-exists',
|
|
223
|
+
})
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
function deletionPendingError() {
|
|
227
|
+
return createError({ statusCode: 409, message: 'このユーザーは削除待ちです。' })
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
function verifiedAccountNeedsLogin() {
|
|
231
|
+
return createError({ statusCode: 409, message: 'このメールアドレスは確認済みです。ログインしてください。' })
|
|
232
|
+
}
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import { createError, getCookie, getHeader, type H3Event } from 'h3'
|
|
2
|
+
import { getAdminAuth, getAdminFirestore } from './firebase-admin'
|
|
3
|
+
|
|
4
|
+
/** ユーザー管理のリクエストで、明示的に送られた Firebase ID トークンを検証する。 */
|
|
5
|
+
export async function assertUserAdmin(event: H3Event) {
|
|
6
|
+
const token = getHeader(event, 'authorization')?.match(/^Bearer (\S+)$/i)?.[1]
|
|
7
|
+
return assertAdmin(token, token => getAdminAuth().verifyIdToken(token, true))
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
/** SSR セッションで認証された管理者を確認する。 */
|
|
11
|
+
export async function assertSessionAdmin(event: H3Event) {
|
|
12
|
+
return assertAdmin(getCookie(event, '__session'), cookie => getAdminAuth().verifySessionCookie(cookie, true))
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
/** トークンの本人確認と、現在のプロフィールによる管理者権限の確認を行う。 */
|
|
16
|
+
async function assertAdmin(credential: string | undefined, verify: (value: string) => Promise<{ uid: string }>) {
|
|
17
|
+
if (!credential) {
|
|
18
|
+
throw createError({ statusCode: 401, message: 'ログインが必要です。' })
|
|
19
|
+
}
|
|
20
|
+
let uid: string
|
|
21
|
+
try {
|
|
22
|
+
const decoded = await verify(credential)
|
|
23
|
+
uid = decoded.uid
|
|
24
|
+
} catch {
|
|
25
|
+
throw createError({ statusCode: 401, message: 'ログイン状態を確認できませんでした。' })
|
|
26
|
+
}
|
|
27
|
+
const profile = (await getAdminFirestore().collection('users').doc(uid).get()).data()
|
|
28
|
+
if (profile?.role !== 'admin' || profile.disabled === true) {
|
|
29
|
+
throw createError({ statusCode: 403, message: '管理者だけが操作できます。' })
|
|
30
|
+
}
|
|
31
|
+
return { uid }
|
|
32
|
+
}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import { FieldValue, type Firestore } from 'firebase-admin/firestore'
|
|
2
|
+
|
|
3
|
+
/** 確認済みの本人のプロフィールだけを指定したロールに変更する。 */
|
|
4
|
+
export async function setDebugUserRole(db: Firestore, uid: string, role: 'admin' | 'user'): Promise<boolean> {
|
|
5
|
+
const profile = db.collection('users').doc(uid)
|
|
6
|
+
return db.runTransaction(async (transaction) => {
|
|
7
|
+
const existing = await transaction.get(profile)
|
|
8
|
+
if (!existing.exists) return false
|
|
9
|
+
if (existing.get('role') !== role) {
|
|
10
|
+
transaction.update(profile, {
|
|
11
|
+
role,
|
|
12
|
+
updatedAt: FieldValue.serverTimestamp(),
|
|
13
|
+
})
|
|
14
|
+
}
|
|
15
|
+
return true
|
|
16
|
+
})
|
|
17
|
+
}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import { initializeApp, type App } from 'firebase-admin/app'
|
|
2
|
+
import { getAuth } from 'firebase-admin/auth'
|
|
3
|
+
import { getFirestore } from 'firebase-admin/firestore'
|
|
4
|
+
|
|
5
|
+
let app: App | null = null
|
|
6
|
+
|
|
7
|
+
/** 初期化済みの Firebase Admin アプリを取得し、必要なら初期化する。 */
|
|
8
|
+
function getFirebaseAdminApp(): App {
|
|
9
|
+
if (app) return app
|
|
10
|
+
app = initializeApp()
|
|
11
|
+
return app
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
/** Firebase Admin SDK の認証クライアントを取得する。 */
|
|
15
|
+
export function getAdminAuth() {
|
|
16
|
+
return getAuth(getFirebaseAdminApp())
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/** Firebase Admin SDK の Firestore クライアントを取得する。 */
|
|
20
|
+
export function getAdminFirestore() {
|
|
21
|
+
return getFirestore(getFirebaseAdminApp())
|
|
22
|
+
}
|