Files
life-echo/google-token-verifier/api/verify-google-token.ts
Sully 105b50a277 merge dark mode and google OAuth (#35)
* feat(api): implement Google OAuth login and user management

- Added Google OpenID Connect login functionality, allowing users to authenticate using their Google accounts.
- Created new endpoints for Google login, including user registration and linking existing accounts.
- Introduced Google token verification logic and error handling for authentication failures.
- Updated environment configuration to include Google OAuth client IDs and verification settings.
- Enhanced user model to support OpenID and linked Google accounts.

This feature improves user experience by enabling seamless sign-in with Google, while maintaining security and integrity of user data.

* fix(auth): wire staging Google token verifier

* chore(deps): update expo to version 55.0.6 and adjust @expo/env dependency in pnpm-lock.yaml

* chore(deps): update Babel dependencies to version 7.29.7 in package-lock.json

* feat(auth): enhance phone login for China users

- Updated phone login functionality to support only mainland China (+86) mobile numbers.
- Added user prompts and descriptions for phone login, including confirmation and cancellation options.
- Adjusted translations for both English and Chinese to reflect the new phone login requirements.
- Updated Google OAuth client IDs in configuration files for production and staging environments.

* chore(deps): add peer flag to use-sync-external-store in package-lock.json

* chore(deps): add @emnapi/core and @emnapi/runtime to package-lock.json

* fix(app-expo): align Android native dependencies

* fix(app-expo): normalize lockfile for npm 10

* fix(config): update environment variable handling to use static access

- Introduced a static mapping for public environment variables to ensure proper access during the release bundle.
- Updated the `requirePublicEnv` and `optionalPublicEnv` functions to reference the new `PUBLIC_ENV` object instead of directly accessing `process.env`.
- Added comments to clarify the necessity of static access for certain environment variables.

* feat(app-expo): dark mode, FAQ i18n, eval ASR, and theme cleanup (#34)

* feat(app-expo): dark mode, FAQ i18n, version CI, and theme cleanup

Implement light/dark scene colors across chat, reading, and headers; remove
default/brand theme picker and ThemeVariablesProvider. Localize FAQ in-app,
fix dark-mode text visibility, and remove the unused /api/faqs endpoint.
Align About/version with Expo config and inject APP_VERSION in CI builds.

Also includes phone E164 auth/SMS updates, eval ASR page, and related API work.

* revert: remove phone E.164 changes from dark-mode branch

These auth/SMS internationalization updates were accidentally bundled into
the dark-mode commit; restore 11-digit CN phone flow and drop related API,
migration, and Expo UI work from this branch.

* fix: address PR review issues for dark mode and eval ASR

Use light foreground colors for sepia reading in dark mode, fix chat send
button contrast, stream-limit eval ASR uploads, restore LiveTester phone
validation, and remove unused AudioSegmenter code.

* fix(app-expo): improve chat send button contrast in light and dark mode

Add dedicated send button colors (accent fill in dark, primary fill in
light), use RNText to avoid NativeWind overrides, and restore dark labels
in light mode for readable composer actions.

---------

Co-authored-by: Kevin <kevin@brighteng.org>

---------

Co-authored-by: penghanyuan <penghanyuan@gmail.com>
Co-authored-by: Kevin <kevin@brighteng.org>
2026-06-09 11:14:36 +08:00

139 lines
3.7 KiB
TypeScript

import { Hono, type Context } from "hono";
import { handle } from "hono/vercel";
import { createRemoteJWKSet, jwtVerify } from "jose";
type ErrorCode =
| "CONFIGURATION_ERROR"
| "INVALID_REQUEST"
| "INVALID_TOKEN"
| "UNAUTHORIZED";
const GOOGLE_JWKS_URL = new URL("https://www.googleapis.com/oauth2/v3/certs");
const GOOGLE_ISSUERS = new Set([
"accounts.google.com",
"https://accounts.google.com",
]);
const googleJwks = createRemoteJWKSet(GOOGLE_JWKS_URL);
const app = new Hono();
export const config = {
runtime: "edge",
};
function parseClientIds(raw: string | undefined): string[] {
return (raw ?? "")
.split(",")
.map((part) => part.trim())
.filter(Boolean);
}
function jsonError(
c: Context,
status: 400 | 401 | 503,
code: ErrorCode,
message: string,
) {
c.header("Cache-Control", "no-store");
return c.json({ error: code, message }, status);
}
async function verifyGoogleToken(c: Context) {
const expectedSecret = process.env.GOOGLE_TOKEN_VERIFIER_SECRET?.trim();
if (!expectedSecret) {
return jsonError(
c,
503,
"CONFIGURATION_ERROR",
"GOOGLE_TOKEN_VERIFIER_SECRET is not configured",
);
}
if (c.req.header("authorization") !== `Bearer ${expectedSecret}`) {
return jsonError(c, 401, "UNAUTHORIZED", "Unauthorized");
}
const clientIds = parseClientIds(process.env.GOOGLE_OAUTH_CLIENT_IDS);
if (clientIds.length === 0) {
return jsonError(
c,
503,
"CONFIGURATION_ERROR",
"GOOGLE_OAUTH_CLIENT_IDS is not configured",
);
}
let body: unknown;
try {
body = await c.req.json();
} catch {
return jsonError(c, 400, "INVALID_REQUEST", "JSON body is required");
}
const idToken =
typeof body === "object" &&
body !== null &&
"id_token" in body &&
typeof body.id_token === "string"
? body.id_token.trim()
: "";
if (!idToken) {
return jsonError(c, 400, "INVALID_REQUEST", "id_token is required");
}
try {
const { payload } = await jwtVerify(idToken, googleJwks, {
algorithms: ["RS256"],
audience: clientIds,
});
const issuer = typeof payload.iss === "string" ? payload.iss : "";
if (!GOOGLE_ISSUERS.has(issuer)) {
return jsonError(c, 401, "INVALID_TOKEN", "Invalid token issuer");
}
const audiences = Array.isArray(payload.aud)
? payload.aud
: typeof payload.aud === "string"
? [payload.aud]
: [];
const audience = audiences.find((item) => clientIds.includes(item)) ?? "";
if (!audience) {
return jsonError(c, 401, "INVALID_TOKEN", "Invalid token audience");
}
const subject = typeof payload.sub === "string" ? payload.sub.trim() : "";
const email =
typeof payload.email === "string" ? payload.email.trim().toLowerCase() : "";
const emailVerified =
payload.email_verified === true ||
String(payload.email_verified).toLowerCase() === "true";
if (!subject || !email || !emailVerified) {
return jsonError(c, 401, "INVALID_TOKEN", "Verified email is required");
}
c.header("Cache-Control", "no-store");
return c.json({
subject,
email,
email_verified: true,
name: typeof payload.name === "string" ? payload.name.trim() : "",
picture:
typeof payload.picture === "string" && payload.picture.trim()
? payload.picture.trim()
: null,
audience,
issuer,
});
} catch {
return jsonError(c, 401, "INVALID_TOKEN", "Google token is invalid");
}
}
app.post("/", verifyGoogleToken);
app.post("/api/verify-google-token", verifyGoogleToken);
app.get("/", (c) => c.json({ status: "ok" }));
app.get("/api/verify-google-token", (c) => c.json({ status: "ok" }));
export default handle(app);