Download cloud-v2/packages/core/src/api/client/auth.api.ts from Anirudh1950/MentraOS: direct link, hf CLI and curl.
- Browser
- Download file 6.95 kB
-
https://huggingface.co/Anirudh1950/MentraOS/resolve/main/cloud-v2/packages/core/src/api/client/auth.api.ts
- Command line
-
hf download hf://Anirudh1950/MentraOS/cloud-v2/packages/core/src/api/client/auth.api.ts
-
curl -L -o auth.api.ts https://huggingface.co/Anirudh1950/MentraOS/resolve/main/cloud-v2/packages/core/src/api/client/auth.api.ts
6.95 kB
| /** | |
| * @fileoverview Client (device-called) auth endpoints. | |
| * | |
| * Mounted at: /api/client/auth | |
| * | |
| * POST /exchange — RFC 8693 token exchange. OEM-signed JWT (or other | |
| * supported subject token) in, Mentra access + refresh | |
| * tokens out. | |
| * POST /refresh — RFC 6749 refresh flow. Old refresh token in, fresh | |
| * access + refresh out (rotated). | |
| * POST /runtime-token — Core access token (Bearer) in, short-lived Runtime | |
| * token out (`aud=cloud-runtime`). | |
| * POST /miniapp-token — Access token (Bearer) + `{packageName, localBuild?}` | |
| * in, a short-lived miniapp-scoped Ed25519 JWT out. The | |
| * phone decides which package is running and says when | |
| * it is a local or development build (`localBuild: | |
| * true`), which marks the token. What the token carries | |
| * is `services/miniapp-token.service.ts`'s to decide. | |
| * | |
| * These are the paths the mobile client / device hits. Per auth/spec.md's | |
| * caller convention, device-called routes live under /api/client/*, while | |
| * /api/oem/* is reserved for the OEM's backend (jwks/me/sessions). The exchange | |
| * + refresh handlers moved here from /api/oem/oauth for that reason; the | |
| * mechanics are unchanged. | |
| * | |
| * exchange + refresh accept `application/x-www-form-urlencoded`, per the RFCs. | |
| * miniapp-token takes a JSON body. Errors are translated to the RFC body shape | |
| * by the global error handler in `api/app.ts`. | |
| * | |
| * Spec: docs/issues/001-cloud-core/auth/spec.md ("Endpoints") | |
| */ | |
| import {Hono} from "hono" | |
| import {InvalidRequest, UnsupportedGrantType, type TokenResponse} from "../../types/oauth.types" | |
| import {MiniappTokenUnavailableError, mintMiniappTokenFor} from "../../services/miniapp-token.service" | |
| import {createSession, refreshSession, issueRuntimeToken, revokeSession} from "../../services/session.service" | |
| import {userAuth} from "../middleware/user-auth.middleware" | |
| import type {AppContext, AppEnv} from "../../types/hono.types" | |
| const TOKEN_EXCHANGE_GRANT = "urn:ietf:params:oauth:grant-type:token-exchange" | |
| const JWT_TOKEN_TYPE = "urn:ietf:params:oauth:token-type:jwt" | |
| const app = new Hono<AppEnv>() | |
| // === Routes === | |
| app.post("/exchange", postExchange) | |
| app.post("/refresh", postRefresh) | |
| // miniapp-token requires a verified access token, so it sits behind userAuth, | |
| // which populates `c.var.user` (mentraUserId + tenantId) from the Bearer token. | |
| app.post("/runtime-token", userAuth, postRuntimeToken) | |
| app.post("/miniapp-token", userAuth, postMiniappToken) | |
| app.post("/revoke", userAuth, postRevoke) | |
| // === Handlers === | |
| async function postExchange(c: AppContext) { | |
| const form = await c.req.parseBody() | |
| const grantType = stringField(form, "grant_type") | |
| if (grantType !== TOKEN_EXCHANGE_GRANT) { | |
| throw new UnsupportedGrantType(`grant_type must be '${TOKEN_EXCHANGE_GRANT}'`) | |
| } | |
| const subjectTokenType = stringField(form, "subject_token_type") | |
| if (subjectTokenType !== JWT_TOKEN_TYPE) { | |
| throw new InvalidRequest(`subject_token_type must be '${JWT_TOKEN_TYPE}'`) | |
| } | |
| const subjectToken = stringField(form, "subject_token") | |
| if (!subjectToken) { | |
| throw new InvalidRequest("subject_token is required") | |
| } | |
| const tokens = await createSession({subjectToken}) | |
| return c.json<TokenResponse>(tokens) | |
| } | |
| async function postRefresh(c: AppContext) { | |
| const form = await c.req.parseBody() | |
| const grantType = stringField(form, "grant_type") | |
| if (grantType !== "refresh_token") { | |
| throw new UnsupportedGrantType("grant_type must be 'refresh_token'") | |
| } | |
| const refreshToken = stringField(form, "refresh_token") | |
| if (!refreshToken) { | |
| throw new InvalidRequest("refresh_token is required") | |
| } | |
| const tokens = await refreshSession({refreshToken}) | |
| return c.json<TokenResponse>(tokens) | |
| } | |
| async function postMiniappToken(c: AppContext) { | |
| // userAuth guarantees `user` is set; this guard is for the type system and | |
| // for defense in depth if the middleware chain ever changes. | |
| const user = c.var.user | |
| if (!user) { | |
| throw new InvalidRequest("missing authenticated user") | |
| } | |
| const body = await readJsonBody(c) | |
| const packageName = typeof body.packageName === "string" ? body.packageName.trim() : "" | |
| if (!packageName) { | |
| throw new InvalidRequest("packageName is required") | |
| } | |
| // Absent, as Mentra Apps from before local-build marking send it, is an unmarked token. Anything but | |
| // a boolean, `null` included, is a malformed request. | |
| const localBuild = body.localBuild === undefined ? false : body.localBuild | |
| if (typeof localBuild !== "boolean") { | |
| throw new InvalidRequest("localBuild must be a boolean") | |
| } | |
| try { | |
| const {token, expiresAt} = await mintMiniappTokenFor({ | |
| mentraUserId: user.mentraUserId, | |
| tenantId: user.tenantId, | |
| packageName, | |
| localBuild, | |
| }) | |
| return c.json({token, expiresAt}) | |
| } catch (error) { | |
| // A lookup the token cannot do without did not answer: nothing is minted and the phone asks again. | |
| if (error instanceof MiniappTokenUnavailableError) return c.json({error: error.code}, 503) | |
| throw error | |
| } | |
| } | |
| async function postRuntimeToken(c: AppContext) { | |
| const user = c.var.user | |
| if (!user) { | |
| throw new InvalidRequest("missing authenticated user") | |
| } | |
| const {token, expiresAt} = await issueRuntimeToken({ | |
| mentraUserId: user.mentraUserId, | |
| tenantId: user.tenantId, | |
| sessionId: user.sessionId, | |
| federatedIdentity: user.federatedIdentity, | |
| }) | |
| return c.json({ | |
| access_token: token, | |
| token_type: "Bearer", | |
| expires_in: Math.max(0, expiresAt - Math.floor(Date.now() / 1000)), | |
| }) | |
| } | |
| async function postRevoke(c: AppContext) { | |
| const user = c.var.user | |
| if (!user) throw new InvalidRequest("missing authenticated user") | |
| await revokeSession({ | |
| sessionId: user.sessionId, | |
| accessToken: {jti: user.accessTokenJti, expiresAt: user.accessTokenExpiresAt}, | |
| }) | |
| return c.json({success: true}) | |
| } | |
| // === Helpers === | |
| function stringField(form: Record<string, string | File | (string | File)[]>, name: string): string | null { | |
| const v = form[name] | |
| return typeof v === "string" ? v : null | |
| } | |
| /** | |
| * Parse a JSON request body, surfacing a malformed body as the RFC-shaped | |
| * `invalid_request` rather than a generic 500. | |
| */ | |
| async function readJsonBody(c: AppContext): Promise<Record<string, unknown>> { | |
| try { | |
| const parsed = await c.req.json() | |
| if (parsed && typeof parsed === "object") { | |
| return parsed as Record<string, unknown> | |
| } | |
| } catch { | |
| // fall through to the InvalidRequest below | |
| } | |
| throw new InvalidRequest("request body must be a JSON object") | |
| } | |
| export default app | |