File size: 6,953 Bytes
17c0464
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
/**

 * @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