@appgrowstack/app-auth 0.0.0-stage → 0.7.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/dist/tokens.js ADDED
@@ -0,0 +1,105 @@
1
+ import { SignJWT, jwtVerify } from "jose";
2
+ const MIN_SECRET_LENGTH = 32;
3
+ export function parseTokenSecrets(raw) {
4
+ const entries = (raw ?? "")
5
+ .split(",")
6
+ .map((part) => part.trim())
7
+ .filter((part) => part.length > 0);
8
+ if (entries.length === 0)
9
+ throw new Error("AUTH_TOKEN_SECRETS is not set");
10
+ const byKid = new Map();
11
+ const secrets = [];
12
+ for (const [index, entry] of entries.entries()) {
13
+ const colon = entry.indexOf(":");
14
+ const kid = colon > 0 ? entry.slice(0, colon) : "";
15
+ const secret = colon > 0 ? entry.slice(colon + 1) : "";
16
+ if (!kid || secret.length < MIN_SECRET_LENGTH) {
17
+ throw new Error(`AUTH_TOKEN_SECRETS entry #${index + 1} must be "kid:secret" with a secret of ${MIN_SECRET_LENGTH}+ characters`);
18
+ }
19
+ if (byKid.has(kid))
20
+ throw new Error(`AUTH_TOKEN_SECRETS has kid "${kid}" twice`);
21
+ const key = new TextEncoder().encode(secret);
22
+ byKid.set(kid, key);
23
+ secrets.push({ kid, key });
24
+ }
25
+ return { signing: secrets[0], byKid };
26
+ }
27
+ export async function signAccessToken(keyring, app, claims, now, ttlMs) {
28
+ const accessTokenExpiresAt = now + ttlMs;
29
+ const accessToken = await new SignJWT({ did: claims.deviceId })
30
+ .setProtectedHeader({ alg: "HS256", typ: "JWT", kid: keyring.signing.kid })
31
+ .setIssuer(app)
32
+ .setAudience(app)
33
+ .setSubject(claims.userId)
34
+ .setIssuedAt(Math.floor(now / 1000))
35
+ .setExpirationTime(Math.floor(accessTokenExpiresAt / 1000))
36
+ .sign(keyring.signing.key);
37
+ return { accessToken, accessTokenExpiresAt };
38
+ }
39
+ export async function verifyAccessToken(keyring, app, token, now) {
40
+ try {
41
+ const { payload } = await jwtVerify(token, (header) => {
42
+ const key = header.kid ? keyring.byKid.get(header.kid) : undefined;
43
+ if (!key)
44
+ throw new Error("unknown kid");
45
+ return key;
46
+ }, { issuer: app, audience: app, algorithms: ["HS256"], requiredClaims: ["exp"], currentDate: new Date(now) });
47
+ if (typeof payload.sub !== "string" || payload.sub.length === 0)
48
+ return null;
49
+ if (typeof payload.did !== "string" || payload.did.length === 0)
50
+ return null;
51
+ return { userId: payload.sub, deviceId: payload.did };
52
+ }
53
+ catch {
54
+ return null;
55
+ }
56
+ }
57
+ export async function verifyLegacyAccessToken(config, token, now) {
58
+ if (!config.secret || config.secret.length < MIN_SECRET_LENGTH)
59
+ return null;
60
+ try {
61
+ const { payload } = await jwtVerify(token, new TextEncoder().encode(config.secret), {
62
+ issuer: config.issuer,
63
+ audience: config.audience,
64
+ algorithms: ["HS256"],
65
+ requiredClaims: ["exp"],
66
+ currentDate: new Date(now),
67
+ });
68
+ return typeof payload.sub === "string" && payload.sub.length > 0 ? payload.sub : null;
69
+ }
70
+ catch {
71
+ return null;
72
+ }
73
+ }
74
+ export function newRefreshSecret() {
75
+ const bytes = new Uint8Array(32);
76
+ crypto.getRandomValues(bytes);
77
+ return base64url(bytes);
78
+ }
79
+ export function joinRefreshToken(parts) {
80
+ return `${parts.deviceId}.${parts.secret}`;
81
+ }
82
+ export function splitRefreshToken(token) {
83
+ const dot = token.indexOf(".");
84
+ if (dot <= 0 || dot === token.length - 1)
85
+ return null;
86
+ return { deviceId: token.slice(0, dot), secret: token.slice(dot + 1) };
87
+ }
88
+ export async function hashSecret(secret) {
89
+ const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(secret));
90
+ return base64url(new Uint8Array(digest));
91
+ }
92
+ export function constantTimeEqual(a, b) {
93
+ if (a.length !== b.length)
94
+ return false;
95
+ let diff = 0;
96
+ for (let i = 0; i < a.length; i++)
97
+ diff |= a.charCodeAt(i) ^ b.charCodeAt(i);
98
+ return diff === 0;
99
+ }
100
+ export function base64url(bytes) {
101
+ let text = "";
102
+ for (const b of bytes)
103
+ text += String.fromCharCode(b);
104
+ return btoa(text).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
105
+ }
@@ -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,7 @@
1
+ CREATE TABLE IF NOT EXISTS auth_apple_web_codes (
2
+ code_hash TEXT PRIMARY KEY,
3
+ subject TEXT NOT NULL,
4
+ install_id TEXT NOT NULL,
5
+ created_at INTEGER NOT NULL,
6
+ expires_at INTEGER NOT NULL
7
+ );
@@ -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.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.7.0",
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()