@appgrowstack/app-auth 0.0.0-stage → 0.6.1
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/CHANGELOG.md +134 -0
- package/LICENSE +21 -0
- package/README.md +320 -2
- package/dist/apple-revoke.d.ts +23 -0
- package/dist/apple-revoke.js +100 -0
- package/dist/apple-web.d.ts +33 -0
- package/dist/apple-web.js +92 -0
- package/dist/authenticate.d.ts +29 -0
- package/dist/authenticate.js +64 -0
- package/dist/config.d.ts +88 -0
- package/dist/config.js +5 -0
- package/dist/contract.d.ts +93 -0
- package/dist/contract.js +0 -0
- package/dist/d1.d.ts +17 -0
- package/dist/d1.js +0 -0
- package/dist/delete-user.d.ts +14 -0
- package/dist/delete-user.js +17 -0
- package/dist/device-routes.d.ts +9 -0
- package/dist/device-routes.js +144 -0
- package/dist/device.d.ts +31 -0
- package/dist/device.js +88 -0
- package/dist/firebase-refresh.d.ts +14 -0
- package/dist/firebase-refresh.js +33 -0
- package/dist/http.d.ts +25 -0
- package/dist/http.js +32 -0
- package/dist/index.d.ts +11 -0
- package/dist/index.js +10 -0
- package/dist/providers.d.ts +24 -0
- package/dist/providers.js +74 -0
- package/dist/routes.d.ts +6 -0
- package/dist/routes.js +349 -0
- package/dist/store.d.ts +35 -0
- package/dist/store.js +135 -0
- package/dist/tokens.d.ts +34 -0
- package/dist/tokens.js +105 -0
- package/migrations/0001_app_auth.sql +25 -0
- package/migrations/0002_app_auth_apple_web.sql +7 -0
- package/migrations/0003_app_auth_device.sql +12 -0
- package/package.json +47 -4
- package/scripts/import-firebase-users.ts +117 -0
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
CREATE TABLE IF NOT EXISTS auth_users (
|
|
2
|
+
id TEXT PRIMARY KEY,
|
|
3
|
+
created_at INTEGER NOT NULL,
|
|
4
|
+
deleted_at INTEGER
|
|
5
|
+
);
|
|
6
|
+
|
|
7
|
+
CREATE TABLE IF NOT EXISTS auth_identities (
|
|
8
|
+
provider TEXT NOT NULL CHECK (provider IN ('apple','google','firebase')),
|
|
9
|
+
subject TEXT NOT NULL,
|
|
10
|
+
user_id TEXT NOT NULL REFERENCES auth_users(id),
|
|
11
|
+
created_at INTEGER NOT NULL,
|
|
12
|
+
PRIMARY KEY (provider, subject)
|
|
13
|
+
);
|
|
14
|
+
CREATE INDEX IF NOT EXISTS auth_identities_user ON auth_identities(user_id);
|
|
15
|
+
|
|
16
|
+
CREATE TABLE IF NOT EXISTS auth_devices (
|
|
17
|
+
id TEXT PRIMARY KEY,
|
|
18
|
+
user_id TEXT NOT NULL REFERENCES auth_users(id),
|
|
19
|
+
install_id TEXT NOT NULL,
|
|
20
|
+
secret_hash TEXT NOT NULL,
|
|
21
|
+
created_at INTEGER NOT NULL,
|
|
22
|
+
last_seen_at INTEGER NOT NULL,
|
|
23
|
+
revoked_at INTEGER
|
|
24
|
+
);
|
|
25
|
+
CREATE INDEX IF NOT EXISTS auth_devices_user ON auth_devices(user_id);
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
CREATE TABLE IF NOT EXISTS auth_device_codes (
|
|
2
|
+
device_code_hash TEXT PRIMARY KEY,
|
|
3
|
+
user_code TEXT NOT NULL UNIQUE,
|
|
4
|
+
install_id TEXT NOT NULL,
|
|
5
|
+
device_name TEXT NOT NULL,
|
|
6
|
+
status TEXT NOT NULL CHECK (status IN ('pending','approved','denied')),
|
|
7
|
+
user_id TEXT REFERENCES auth_users(id),
|
|
8
|
+
created_at INTEGER NOT NULL,
|
|
9
|
+
expires_at INTEGER NOT NULL,
|
|
10
|
+
last_polled_at INTEGER
|
|
11
|
+
);
|
|
12
|
+
CREATE INDEX IF NOT EXISTS auth_device_codes_user ON auth_device_codes(user_id);
|
package/package.json
CHANGED
|
@@ -1,6 +1,49 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@appgrowstack/app-auth",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"description": "
|
|
6
|
-
|
|
3
|
+
"version": "0.6.1",
|
|
4
|
+
"type": "module",
|
|
5
|
+
"description": "アプリの Worker が自分で user_id を発行し、Apple・Google・古い Firebase のトークンを確かめてセッションを返す",
|
|
6
|
+
"license": "MIT",
|
|
7
|
+
"repository": {
|
|
8
|
+
"type": "git",
|
|
9
|
+
"url": "git+https://github.com/appgrowstack/app-growth.git",
|
|
10
|
+
"directory": "packages/app-auth"
|
|
11
|
+
},
|
|
12
|
+
"homepage": "https://github.com/appgrowstack/app-growth/tree/main/packages/app-auth#readme",
|
|
13
|
+
"keywords": [
|
|
14
|
+
"cloudflare-workers",
|
|
15
|
+
"hono",
|
|
16
|
+
"d1",
|
|
17
|
+
"authentication",
|
|
18
|
+
"appgrowstack"
|
|
19
|
+
],
|
|
20
|
+
"sideEffects": false,
|
|
21
|
+
"exports": {
|
|
22
|
+
".": {
|
|
23
|
+
"types": "./dist/index.d.ts",
|
|
24
|
+
"default": "./dist/index.js"
|
|
25
|
+
},
|
|
26
|
+
"./migrations/0001_app_auth.sql": "./migrations/0001_app_auth.sql",
|
|
27
|
+
"./migrations/0002_app_auth_apple_web.sql": "./migrations/0002_app_auth_apple_web.sql",
|
|
28
|
+
"./migrations/0003_app_auth_device.sql": "./migrations/0003_app_auth_device.sql"
|
|
29
|
+
},
|
|
30
|
+
"files": [
|
|
31
|
+
"dist",
|
|
32
|
+
"migrations",
|
|
33
|
+
"scripts",
|
|
34
|
+
"README.md",
|
|
35
|
+
"CHANGELOG.md",
|
|
36
|
+
"LICENSE"
|
|
37
|
+
],
|
|
38
|
+
"publishConfig": {
|
|
39
|
+
"access": "public"
|
|
40
|
+
},
|
|
41
|
+
"dependencies": {
|
|
42
|
+
"jose": "^5.10.0"
|
|
43
|
+
},
|
|
44
|
+
"peerDependencies": {
|
|
45
|
+
"hono": "^4.7.0"
|
|
46
|
+
},
|
|
47
|
+
"types": "./dist/index.d.ts",
|
|
48
|
+
"module": "./dist/index.js"
|
|
49
|
+
}
|
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
#!/usr/bin/env bun
|
|
2
|
+
import { SignJWT, importPKCS8 } from "jose"
|
|
3
|
+
import { writeFileSync } from "node:fs"
|
|
4
|
+
|
|
5
|
+
const TOKEN_URL = "https://oauth2.googleapis.com/token"
|
|
6
|
+
const SCOPE = "https://www.googleapis.com/auth/identitytoolkit"
|
|
7
|
+
const PAGE_SIZE = 1000
|
|
8
|
+
|
|
9
|
+
export interface FirebaseAccount {
|
|
10
|
+
localId: string
|
|
11
|
+
createdAt?: string
|
|
12
|
+
providerUserInfo?: { providerId?: string; rawId?: string }[]
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
export interface ServiceAccount {
|
|
16
|
+
clientEmail: string
|
|
17
|
+
privateKey: string
|
|
18
|
+
projectId: string
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
const PROVIDERS: Record<string, "apple" | "google"> = { "apple.com": "apple", "google.com": "google" }
|
|
22
|
+
|
|
23
|
+
const quote = (value: string) => `'${value.replace(/'/g, "''")}'`
|
|
24
|
+
|
|
25
|
+
export function firebaseUsersToSql(accounts: FirebaseAccount[], now: number): string {
|
|
26
|
+
const lines: string[] = []
|
|
27
|
+
for (const account of accounts) {
|
|
28
|
+
if (!account.localId) continue
|
|
29
|
+
const uid = quote(account.localId)
|
|
30
|
+
const created = Number(account.createdAt)
|
|
31
|
+
const createdAt = Number.isFinite(created) && created > 0 ? Math.trunc(created) : now
|
|
32
|
+
lines.push(`INSERT INTO auth_users (id, created_at) VALUES (${uid}, ${createdAt}) ON CONFLICT (id) DO NOTHING;`)
|
|
33
|
+
const identities: [string, string][] = [["firebase", account.localId]]
|
|
34
|
+
for (const info of account.providerUserInfo ?? []) {
|
|
35
|
+
const provider = info.providerId ? PROVIDERS[info.providerId] : undefined
|
|
36
|
+
if (provider && info.rawId) identities.push([provider, info.rawId])
|
|
37
|
+
}
|
|
38
|
+
for (const [provider, subject] of identities) {
|
|
39
|
+
lines.push(
|
|
40
|
+
`INSERT INTO auth_identities (provider, subject, user_id, created_at) SELECT ${quote(provider)}, ${quote(subject)}, ${uid}, ${createdAt} ` +
|
|
41
|
+
`WHERE EXISTS (SELECT 1 FROM auth_users WHERE id = ${uid} AND deleted_at IS NULL) ON CONFLICT (provider, subject) DO NOTHING;`,
|
|
42
|
+
)
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
return lines.join("\n") + "\n"
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
export function readServiceAccount(env: Record<string, string | undefined>): ServiceAccount {
|
|
49
|
+
const json = env.FIREBASE_SERVICE_ACCOUNT_JSON
|
|
50
|
+
if (json) {
|
|
51
|
+
const parsed = JSON.parse(json) as { client_email?: string; private_key?: string; project_id?: string }
|
|
52
|
+
if (!parsed.client_email || !parsed.private_key || !parsed.project_id) {
|
|
53
|
+
throw new Error("FIREBASE_SERVICE_ACCOUNT_JSON lacks client_email, private_key or project_id")
|
|
54
|
+
}
|
|
55
|
+
return { clientEmail: parsed.client_email, privateKey: parsed.private_key, projectId: parsed.project_id }
|
|
56
|
+
}
|
|
57
|
+
const { FIREBASE_SA_CLIENT_EMAIL: clientEmail, FIREBASE_SA_PRIVATE_KEY: privateKey, FIREBASE_PROJECT_ID: projectId } = env
|
|
58
|
+
if (!clientEmail || !privateKey || !projectId) {
|
|
59
|
+
throw new Error("set FIREBASE_SERVICE_ACCOUNT_JSON, or FIREBASE_SA_CLIENT_EMAIL + FIREBASE_SA_PRIVATE_KEY + FIREBASE_PROJECT_ID")
|
|
60
|
+
}
|
|
61
|
+
return { clientEmail, privateKey, projectId }
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
export async function googleAccessToken(account: ServiceAccount, send: typeof fetch = fetch, now = Date.now()): Promise<string> {
|
|
65
|
+
const key = await importPKCS8(account.privateKey.replace(/\\n/g, "\n"), "RS256")
|
|
66
|
+
const iat = Math.floor(now / 1000)
|
|
67
|
+
const assertion = await new SignJWT({ scope: SCOPE })
|
|
68
|
+
.setProtectedHeader({ alg: "RS256", typ: "JWT" })
|
|
69
|
+
.setIssuer(account.clientEmail)
|
|
70
|
+
.setAudience(TOKEN_URL)
|
|
71
|
+
.setIssuedAt(iat)
|
|
72
|
+
.setExpirationTime(iat + 3600)
|
|
73
|
+
.sign(key)
|
|
74
|
+
const response = await send(TOKEN_URL, {
|
|
75
|
+
method: "POST",
|
|
76
|
+
headers: { "content-type": "application/x-www-form-urlencoded" },
|
|
77
|
+
body: new URLSearchParams({ grant_type: "urn:ietf:params:oauth:grant-type:jwt-bearer", assertion }),
|
|
78
|
+
})
|
|
79
|
+
const body = (await response.json().catch(() => ({}))) as { access_token?: unknown; error?: unknown }
|
|
80
|
+
if (!response.ok || typeof body.access_token !== "string") {
|
|
81
|
+
throw new Error(`Google OAuth token exchange failed: ${response.status} ${typeof body.error === "string" ? body.error : ""}`)
|
|
82
|
+
}
|
|
83
|
+
return body.access_token
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
export async function fetchFirebaseAccounts(accessToken: string, projectId: string, send: typeof fetch = fetch): Promise<FirebaseAccount[]> {
|
|
87
|
+
const accounts: FirebaseAccount[] = []
|
|
88
|
+
let pageToken: string | undefined
|
|
89
|
+
do {
|
|
90
|
+
const url = new URL(`https://identitytoolkit.googleapis.com/v1/projects/${encodeURIComponent(projectId)}/accounts:batchGet`)
|
|
91
|
+
url.searchParams.set("maxResults", String(PAGE_SIZE))
|
|
92
|
+
if (pageToken) url.searchParams.set("nextPageToken", pageToken)
|
|
93
|
+
const response = await send(url, { headers: { authorization: `Bearer ${accessToken}` } })
|
|
94
|
+
const body = (await response.json().catch(() => ({}))) as { users?: FirebaseAccount[]; nextPageToken?: string; error?: { message?: string } }
|
|
95
|
+
if (!response.ok) throw new Error(`accounts:batchGet failed: ${response.status} ${body.error?.message ?? ""}`)
|
|
96
|
+
accounts.push(...(body.users ?? []))
|
|
97
|
+
pageToken = body.users?.length ? body.nextPageToken : undefined
|
|
98
|
+
} while (pageToken)
|
|
99
|
+
return accounts
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
async function main() {
|
|
103
|
+
const outIndex = process.argv.indexOf("--out")
|
|
104
|
+
const out = outIndex > 0 ? process.argv[outIndex + 1] : undefined
|
|
105
|
+
if (!out) {
|
|
106
|
+
console.error("使い方: bun scripts/import-firebase-users.ts --out <書く SQL のファイル>")
|
|
107
|
+
process.exit(2)
|
|
108
|
+
}
|
|
109
|
+
const account = readServiceAccount(process.env)
|
|
110
|
+
const accounts = await fetchFirebaseAccounts(await googleAccessToken(account), account.projectId)
|
|
111
|
+
writeFileSync(out, firebaseUsersToSql(accounts, Date.now()))
|
|
112
|
+
const linked = accounts.filter((a) => (a.providerUserInfo ?? []).some((p) => p.providerId && p.providerId in PROVIDERS)).length
|
|
113
|
+
console.log(`書いた: ${out}(${account.projectId}・${accounts.length} 人・Apple か Google をつないだ人 ${linked})`)
|
|
114
|
+
console.log(`流す: npx wrangler d1 execute <database_name> --remote --file ${out}`)
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
if (import.meta.main) await main()
|