@orbclub/create-app 0.0.0-stage → 0.1.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.
Files changed (36) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +29 -2
  3. package/bin/create-orb-app.js +410 -0
  4. package/bin/node-version.js +6 -0
  5. package/bin/package-manager.js +87 -0
  6. package/bin/sdk-version.js +3 -0
  7. package/package.json +33 -4
  8. package/template/.env.local.example +10 -0
  9. package/template/AGENTS.md +105 -0
  10. package/template/README.md +56 -0
  11. package/template/eslint.config.mjs +11 -0
  12. package/template/gitignore +26 -0
  13. package/template/next.config.ts +25 -0
  14. package/template/package.json +29 -0
  15. package/template/pnpm-workspace.yaml +15 -0
  16. package/template/src/app/.well-known/orb-siwo.json/route.ts +23 -0
  17. package/template/src/app/api/local-sign-in/init/route.ts +12 -0
  18. package/template/src/app/api/local-sign-in/local-sign-in.ts +50 -0
  19. package/template/src/app/api/local-sign-in/status/route.ts +12 -0
  20. package/template/src/app/api/orb/route-validation.ts +123 -0
  21. package/template/src/app/api/orb/user/route.ts +44 -0
  22. package/template/src/app/api/route-security.ts +105 -0
  23. package/template/src/app/api/site-session/bind/route.ts +82 -0
  24. package/template/src/app/api/site-session/binding/route.ts +35 -0
  25. package/template/src/app/api/site-session/end/route.ts +30 -0
  26. package/template/src/app/api/site-session/renew/route.ts +71 -0
  27. package/template/src/app/api/site-session/site-session.ts +152 -0
  28. package/template/src/app/globals.css +196 -0
  29. package/template/src/app/home.tsx +115 -0
  30. package/template/src/app/layout.tsx +24 -0
  31. package/template/src/app/page.tsx +12 -0
  32. package/template/src/lib/orb-session.ts +703 -0
  33. package/template/src/lib/sign-in.ts +61 -0
  34. package/template/src/lib/site-origin.ts +35 -0
  35. package/template/src/lib/use-orb-session.ts +26 -0
  36. package/template/tsconfig.json +30 -0
@@ -0,0 +1,105 @@
1
+ # Agent guide
2
+
3
+ {{DISPLAY_NAME}} is a Next.js (App Router) app for the Orb mobile app, built on
4
+ `@orbclub/apps-sdk`. It signs the viewer in and shows their Orb profile. Its
5
+ environment variables are in `README.md`.
6
+
7
+ ## Layout
8
+
9
+ - `src/app/home.tsx`: the client view. Most product changes go here and in
10
+ `src/app/globals.css`.
11
+ - `src/app/page.tsx`: server page; reads the sign-in setup from the environment.
12
+ - `src/lib/orb-session.ts`: sign-in state for all three flows, silent renewal
13
+ and expiry. Only it holds the `OrbAppsClient` and the tokens: add anything
14
+ that needs them (calling your API routes with the access token,
15
+ `performTransaction`) as an `OrbSession` method, and give the view only
16
+ results. `src/lib/use-orb-session.ts` subscribes React to it.
17
+ - `src/lib/sign-in.ts`, `src/lib/site-origin.ts`: which flow the environment
18
+ enables.
19
+ - `src/app/.well-known/orb-siwo.json/route.ts`: the Sign in with Orb manifest.
20
+ - `src/app/api/local-sign-in/`: local sign-in routes.
21
+ - `src/app/api/site-session/`: site sessions (binding, bind, renew, end) in
22
+ HttpOnly cookies.
23
+ - `src/app/api/orb/user/route.ts`: profile lookup; input checks in
24
+ `src/app/api/orb/route-validation.ts` and `src/app/api/route-security.ts`.
25
+
26
+ ## Sign-in flows
27
+
28
+ - **Inside Orb:** bridge `connect` from `OrbAppsClient`. Silent renewal sends
29
+ `prompt: "none"` only when `context.features.grantRenewal` is `true`.
30
+ Profiles share cookies and storage: keep tokens only while their account
31
+ equals `context.user.profileId` whenever Orb sends one, ignoring case (on
32
+ load, after every `connect`, on each `onContextChange`).
33
+ - **Deployed HTTPS origin:** `signInWithOrb` in the page. `ORB_APP_ORIGIN` must
34
+ equal the page's origin; the manifest returns it. `/api/site-session/*`
35
+ keeps the session alive.
36
+ - **`http://localhost`, any port:** `createLocalQrAuthRoutes` behind
37
+ `/api/local-sign-in/*`. On only when `ORB_LOCAL_SIWO_SESSION_SECRET` is set
38
+ and `ORB_APP_ORIGIN` is unset or loopback.
39
+
40
+ ## Layout and navigation
41
+
42
+ - Orb's top bar overlays the page, and `env(safe-area-inset-*)` is zero inside
43
+ Orb. Pad content and offset every fixed or sticky element with
44
+ `var(--orb-safe-top, env(safe-area-inset-top))` and its `-bottom`, `-left`
45
+ and `-right` siblings, as `main` in `src/app/globals.css` does. The top
46
+ inset changes as Orb's bar collapses: never measure it once in JavaScript,
47
+ hard-code a bar height or add a transition to it.
48
+ - Orb's Back, Forward and back swipe step through browser history. Give every
49
+ page the viewer returns from its own route, opened with `<Link>` or
50
+ `router.push`. Slide a page in from the right with a View Transition when
51
+ the viewer opens it, and never animate history navigations. How:
52
+ `node_modules/@orbclub/apps-sdk/docs/navigation.md`.
53
+
54
+ ## Rules
55
+
56
+ - Never render or log tokens or `ORB_LOCAL_SIWO_SESSION_SECRET`. Persist
57
+ tokens only in the HttpOnly site-session cookies. Never put secrets in
58
+ `NEXT_PUBLIC_*`.
59
+ - Client components import only `@orbclub/apps-sdk/client`, `/detect` and `/site`.
60
+ The root `@orbclub/apps-sdk` is for server code.
61
+ - Run `signInWithOrb` in the page; never proxy it (Orb rate-limits per client
62
+ IP). `bindSiteSession`, `renewSiteSession` and `endSiteSession` are the
63
+ opposite: server only.
64
+ - Never send the bind secret or renew handle to the page, and never log them.
65
+ In the page, wrap calls to `/api/site-session/{bind,renew,end}` in
66
+ `withSiteSessionLock` (a stale handle ends the session).
67
+ `requestRenewBinding` takes the lock itself; never nest them.
68
+ - `context.user` and decoded token claims are unverified. Before serving
69
+ private data or changing state, call
70
+ `verifyOrbAccessToken(sdk, token, { requestorDomains: [host], signal: AbortSignal.timeout(5000) })`
71
+ and authorize with `result.session.address`.
72
+ - `host` is the hostname of `getSignInSetup().origin` (`src/lib/sign-in.ts`)
73
+ for the `site` flow, or `ORB_LOCAL_DEVELOPMENT_REQUESTOR_DOMAIN` from
74
+ `@orbclub/apps-sdk` for the `local` flow; never from request headers.
75
+ - Never pass `requireGrant: false`. `status: "refused"` means signed out.
76
+ `OrbAuthUnavailableError` means Orb gave no usable answer: answer 503, serve
77
+ nothing private, don't sign the viewer out.
78
+ - For viewer-specific API calls, use `callOrbApiAsViewer` and spread all its
79
+ options.
80
+ - `performTransaction`'s result is the page's claim. Before a route grants
81
+ anything for a payment, check on the expected chain that the transaction
82
+ succeeded and moved the expected amount of the expected token (by contract
83
+ address) from `result.session.address` to the expected recipient. Check the
84
+ transfer itself: the transaction's `from` and `to` can be the device wallet
85
+ or a contract. Credit each hash once, to one order created before it was
86
+ mined. A timeout doesn't cancel it: check before retrying.
87
+ - `getTipUserTx`, `tipUser`, `enableAction` and generated `*Tx` operations can
88
+ send the transaction at once, with no approval sheet. Call them only after
89
+ the viewer confirms in the page. Never time one out, retry it automatically
90
+ or report any of its errors as a failure: it may already be sent.
91
+ - Validate API route bodies with `src/app/api/route-security.ts` and pass other
92
+ generated API calls `signal: AbortSignal.timeout(…)`.
93
+
94
+ ## Verify
95
+
96
+ ```bash
97
+ {{PM}} run lint
98
+ {{PM}} run build
99
+ ```
100
+
101
+ ## Docs
102
+
103
+ The installed SDK ships its docs: `node_modules/@orbclub/apps-sdk/llms.txt` indexes
104
+ them, and `node_modules/@orbclub/apps-sdk/docs/authentication.md` is the place to
105
+ start.
@@ -0,0 +1,56 @@
1
+ # {{DISPLAY_NAME}}
2
+
3
+ An Orb app built with Next.js and
4
+ [`@orbclub/apps-sdk`](https://github.com/orb-club/orb-apps-sdk). Read `AGENTS.md`
5
+ (code map and security rules) before changing it.
6
+
7
+ ## Run locally
8
+
9
+ Requires Node.js 20.9.0 or newer.
10
+
11
+ ```bash
12
+ {{PM}} install
13
+ {{PM}} run dev
14
+ ```
15
+
16
+ Open the address it prints (usually http://localhost:3000; any port works).
17
+ `create-orb-app` wrote `.env.local` with a local sign-in secret. If it's
18
+ missing, copy `.env.local.example` to `.env.local` and generate
19
+ `ORB_LOCAL_SIWO_SESSION_SECRET` with the command in that file.
20
+
21
+ ## Sign-in
22
+
23
+ The page picks the flow from where it runs:
24
+
25
+ - **Inside Orb:** one-tap bridge `connect`, restored silently on load and
26
+ renewed before expiry when Orb supports it.
27
+ - **`http://localhost`:** a QR code, through the `/api/local-sign-in/*` routes.
28
+ - **Your HTTPS origin:** Sign in with Orb in the page. A sign-in ends on
29
+ reload or after ten minutes. Once Orb turns renewal on for your site and the
30
+ viewer chooses to stay logged in, the `/api/site-session/*` routes keep them
31
+ signed in.
32
+
33
+ If the page's origin doesn't match `ORB_APP_ORIGIN`, it says so instead of
34
+ starting a sign-in.
35
+
36
+ ## Environment
37
+
38
+ | Variable | Purpose |
39
+ | ------------------------------- | ----------------------------------------------------- |
40
+ | `ORB_APP_ORIGIN` | Exact HTTPS origin of the deployed app. Unset locally |
41
+ | `ORB_LOCAL_SIWO_SESSION_SECRET` | Local sign-in only. Server-only; never commit it |
42
+
43
+ ## Deploy
44
+
45
+ 1. Set `ORB_APP_ORIGIN` (such as `https://app.example.com`). Leave
46
+ `ORB_LOCAL_SIWO_SESSION_SECRET` unset.
47
+ 2. Check that `<your origin>/.well-known/orb-siwo.json` returns
48
+ `{"version":1,"origin":"<your origin>"}`.
49
+ 3. Sign in on that origin. The first sign-in can take a few minutes while Orb
50
+ sets the site up. Preview deployments on other origins can't sign in.
51
+ 4. To open the app inside Orb, contact the Orb team.
52
+
53
+ ## Learn more
54
+
55
+ SDK docs: `node_modules/@orbclub/apps-sdk/docs/`, or
56
+ [on GitHub](https://github.com/orb-club/orb-apps-sdk/tree/main/docs).
@@ -0,0 +1,11 @@
1
+ import { defineConfig, globalIgnores } from "eslint/config";
2
+ import nextVitals from "eslint-config-next/core-web-vitals";
3
+ import nextTs from "eslint-config-next/typescript";
4
+
5
+ const eslintConfig = defineConfig([
6
+ ...nextVitals,
7
+ ...nextTs,
8
+ globalIgnores([".next/**", "out/**", "build/**", "next-env.d.ts"]),
9
+ ]);
10
+
11
+ export default eslintConfig;
@@ -0,0 +1,26 @@
1
+ # dependencies
2
+ /node_modules
3
+
4
+ # next
5
+ /.next
6
+ /out
7
+
8
+ # production
9
+ /build
10
+
11
+ # misc
12
+ .DS_Store
13
+ *.pem
14
+
15
+ # debug
16
+ npm-debug.log*
17
+ yarn-debug.log*
18
+ yarn-error.log*
19
+ pnpm-debug.log*
20
+
21
+ # local env files
22
+ .env*.local
23
+
24
+ # typescript
25
+ *.tsbuildinfo
26
+ next-env.d.ts
@@ -0,0 +1,25 @@
1
+ import type { NextConfig } from "next";
2
+
3
+ // Baseline headers. Framing stays allowed so the Orb sandbox can preview the
4
+ // app; add `frame-ancestors` to the CSP once you know who may embed it.
5
+ const securityHeaders = [
6
+ {
7
+ key: "Content-Security-Policy",
8
+ value: "base-uri 'self'; object-src 'none'",
9
+ },
10
+ { key: "Referrer-Policy", value: "strict-origin-when-cross-origin" },
11
+ { key: "X-Content-Type-Options", value: "nosniff" },
12
+ // Production only, so local https development never pins localhost.
13
+ ...(process.env.NODE_ENV === "production"
14
+ ? [{ key: "Strict-Transport-Security", value: "max-age=63072000" }]
15
+ : []),
16
+ ];
17
+
18
+ const nextConfig: NextConfig = {
19
+ poweredByHeader: false,
20
+ async headers() {
21
+ return [{ source: "/:path*", headers: securityHeaders }];
22
+ },
23
+ };
24
+
25
+ export default nextConfig;
@@ -0,0 +1,29 @@
1
+ {
2
+ "name": "__APP_NAME__",
3
+ "version": "0.1.0",
4
+ "private": true,
5
+ "packageManager": "pnpm@10.14.0",
6
+ "engines": {
7
+ "node": ">=20.9.0"
8
+ },
9
+ "scripts": {
10
+ "dev": "next dev",
11
+ "build": "next build",
12
+ "start": "next start",
13
+ "lint": "eslint ."
14
+ },
15
+ "dependencies": {
16
+ "next": "16.4.0",
17
+ "@orbclub/apps-sdk": __SDK_DEPENDENCY_JSON__,
18
+ "react": "19.2.8",
19
+ "react-dom": "19.2.8"
20
+ },
21
+ "devDependencies": {
22
+ "@types/node": "^20",
23
+ "@types/react": "^19",
24
+ "@types/react-dom": "^19",
25
+ "eslint": "^9",
26
+ "eslint-config-next": "16.4.0",
27
+ "typescript": "^5"
28
+ }
29
+ }
@@ -0,0 +1,15 @@
1
+ packages:
2
+ - "."
3
+
4
+ overrides:
5
+ "js-yaml@^4": 4.3.2
6
+ "postcss@^8": 8.5.25
7
+ "brace-expansion@^1": 1.1.21
8
+ "brace-expansion@^2": 2.1.4
9
+ "brace-expansion@4.0.1": 5.0.12
10
+ "brace-expansion@^5": 5.0.12
11
+ "sharp@<0.35.5": 0.35.5
12
+
13
+ ignoredBuiltDependencies:
14
+ - sharp
15
+ - unrs-resolver
@@ -0,0 +1,23 @@
1
+ import { createSiteManifestHandler } from "@orbclub/apps-sdk/site";
2
+
3
+ import { getSiteSignInOrigin } from "@/lib/site-origin";
4
+
5
+ // Read ORB_APP_ORIGIN per request, not at build time.
6
+ export const dynamic = "force-dynamic";
7
+
8
+ /**
9
+ * Opts this origin into browser-site Sign in with Orb. The Orb backend fetches
10
+ * this before issuing a sign-in and requires HTTP 200, `application/json`, and
11
+ * exactly `{"version":1,"origin":"<this exact origin>"}`. No signing key is
12
+ * involved.
13
+ */
14
+ export function GET(request: Request): Response {
15
+ const origin = getSiteSignInOrigin();
16
+ if (!origin) {
17
+ return Response.json(
18
+ { message: "Sign in with Orb is not configured for this origin" },
19
+ { status: 503, headers: { "cache-control": "no-store" } },
20
+ );
21
+ }
22
+ return createSiteManifestHandler({ origins: origin })(request);
23
+ }
@@ -0,0 +1,12 @@
1
+ import { handleLocalSignIn } from "../local-sign-in";
2
+
3
+ export const runtime = "nodejs";
4
+
5
+ /**
6
+ * Starts a local sign-in and returns only the QR code and deep link. The
7
+ * first sign-in on a machine can take up to two minutes while Orb sets up
8
+ * local development sign-in.
9
+ */
10
+ export async function POST(request: Request): Promise<Response> {
11
+ return handleLocalSignIn("init", request);
12
+ }
@@ -0,0 +1,50 @@
1
+ import {
2
+ createLocalQrAuthRoutes,
3
+ createLocalQrAuthServer,
4
+ } from "@orbclub/apps-sdk";
5
+
6
+ import { getLocalSessionSecret, getSignInSetup } from "../../../lib/sign-in";
7
+
8
+ /**
9
+ * Local development sign-in for `http://localhost`, where browser-site Sign
10
+ * in with Orb cannot run (its manifest origin must be HTTPS). The browser
11
+ * calls `connectWithQr` against these routes; the server talks to Orb and
12
+ * keeps the encrypted session in an HttpOnly cookie. Enabled only when
13
+ * ORB_LOCAL_SIWO_SESSION_SECRET is set and ORB_APP_ORIGIN is unset or a
14
+ * loopback origin. Any loopback port works, so `next dev` moving to another
15
+ * port when 3000 is busy does not break sign-in: each request signs in as its
16
+ * own loopback `Origin`, which must equal the `Host` and come with
17
+ * `Sec-Fetch-Site: same-origin`.
18
+ */
19
+
20
+ type LocalSignInRoute = "init" | "status";
21
+
22
+ function jsonNoStore(body: unknown, status: number): Response {
23
+ return Response.json(body, {
24
+ status,
25
+ headers: { "cache-control": "no-store" },
26
+ });
27
+ }
28
+
29
+ /** Runs a local sign-in route only when loopback development is configured. */
30
+ export async function handleLocalSignIn(
31
+ route: LocalSignInRoute,
32
+ request: Request,
33
+ ): Promise<Response> {
34
+ const setup = getSignInSetup();
35
+ const sessionSecret = getLocalSessionSecret();
36
+ if (setup.flow !== "local" || !sessionSecret) {
37
+ return jsonNoStore({ message: "Local sign-in is not enabled." }, 404);
38
+ }
39
+
40
+ const routes = createLocalQrAuthRoutes({
41
+ server: (origin) =>
42
+ createLocalQrAuthServer({
43
+ requestorOrigin: origin,
44
+ credentials: "id_access",
45
+ sessionSecret,
46
+ acknowledgePollingRelayRisk: true,
47
+ }),
48
+ });
49
+ return routes[route](request);
50
+ }
@@ -0,0 +1,12 @@
1
+ import { handleLocalSignIn } from "../local-sign-in";
2
+
3
+ export const runtime = "nodejs";
4
+
5
+ /**
6
+ * Reports whether the viewer approved the sign-in and returns the tokens once
7
+ * they did. An expired or invalid session answers FAILED, so the page stops
8
+ * polling instead of waiting for its timeout.
9
+ */
10
+ export async function POST(request: Request): Promise<Response> {
11
+ return handleLocalSignIn("status", request);
12
+ }
@@ -0,0 +1,123 @@
1
+ import { isCompactJwt } from "@orbclub/apps-sdk";
2
+
3
+ import {
4
+ jsonNoStore,
5
+ readBoundedJsonObject,
6
+ RouteError,
7
+ } from "../route-security";
8
+
9
+ export { jsonNoStore };
10
+
11
+ const ETH_ADDRESS_PATTERN = /^0x[0-9a-f]{40}$/i;
12
+
13
+ export const ORB_ROUTE_LIMITS = {
14
+ bodyBytes: 40 * 1024,
15
+ accessTokenCharacters: 32 * 1024,
16
+ thumbnailDimension: 4_096,
17
+ } as const;
18
+
19
+ export type UserRouteRequest = {
20
+ address: string;
21
+ xAccessToken: string;
22
+ userAvatarThumbnailDimension: number;
23
+ mediaThumbnailDimension: number;
24
+ };
25
+
26
+ export class OrbRouteValidationError extends RouteError {
27
+ constructor(status: number, message: string) {
28
+ super(status, message);
29
+ this.name = "OrbRouteValidationError";
30
+ }
31
+ }
32
+
33
+ function validationError(message: string): never {
34
+ throw new OrbRouteValidationError(400, message);
35
+ }
36
+
37
+ function assertOnlyFields(
38
+ payload: Record<string, unknown>,
39
+ fields: readonly string[],
40
+ ): void {
41
+ if (Object.keys(payload).some((field) => !fields.includes(field))) {
42
+ validationError("Request body contains unsupported fields.");
43
+ }
44
+ }
45
+
46
+ function parseEthAddress(value: unknown): string {
47
+ if (typeof value !== "string" || !ETH_ADDRESS_PATTERN.test(value)) {
48
+ validationError("address must be a 20-byte hexadecimal address.");
49
+ }
50
+ return value;
51
+ }
52
+
53
+ function parseAccessToken(value: unknown): string {
54
+ if (
55
+ typeof value !== "string" ||
56
+ value.length > ORB_ROUTE_LIMITS.accessTokenCharacters ||
57
+ !isCompactJwt(value)
58
+ ) {
59
+ validationError("xAccessToken must be a bounded compact JWT.");
60
+ }
61
+
62
+ return value;
63
+ }
64
+
65
+ function parseThumbnailDimension(
66
+ value: unknown,
67
+ field: string,
68
+ fallback: number,
69
+ ): number {
70
+ if (value === undefined) return fallback;
71
+ if (
72
+ typeof value !== "number" ||
73
+ !Number.isInteger(value) ||
74
+ value < 1 ||
75
+ value > ORB_ROUTE_LIMITS.thumbnailDimension
76
+ ) {
77
+ validationError(
78
+ `${field} must be an integer from 1 to ${ORB_ROUTE_LIMITS.thumbnailDimension}.`,
79
+ );
80
+ }
81
+ return value;
82
+ }
83
+
84
+ export async function readUserRouteRequest(
85
+ request: Request,
86
+ ): Promise<UserRouteRequest> {
87
+ const payload = await readBoundedJsonObject(
88
+ request,
89
+ ORB_ROUTE_LIMITS.bodyBytes,
90
+ );
91
+ assertOnlyFields(payload, [
92
+ "address",
93
+ "xAccessToken",
94
+ "userAvatarThumbnailDimension",
95
+ "mediaThumbnailDimension",
96
+ ]);
97
+
98
+ return {
99
+ address: parseEthAddress(payload.address),
100
+ xAccessToken: parseAccessToken(payload.xAccessToken),
101
+ userAvatarThumbnailDimension: parseThumbnailDimension(
102
+ payload.userAvatarThumbnailDimension,
103
+ "userAvatarThumbnailDimension",
104
+ 768,
105
+ ),
106
+ mediaThumbnailDimension: parseThumbnailDimension(
107
+ payload.mediaThumbnailDimension,
108
+ "mediaThumbnailDimension",
109
+ 1180,
110
+ ),
111
+ };
112
+ }
113
+
114
+ export function orbRouteErrorResponse(
115
+ reason: unknown,
116
+ fallbackMessage: string,
117
+ ): Response {
118
+ const status = reason instanceof RouteError ? reason.status : 502;
119
+ const message =
120
+ reason instanceof RouteError ? reason.message : fallbackMessage;
121
+
122
+ return jsonNoStore({ message }, status);
123
+ }
@@ -0,0 +1,44 @@
1
+ import type { NextRequest } from "next/server";
2
+ import { OrbAppsSDK } from "@orbclub/apps-sdk";
3
+
4
+ import {
5
+ jsonNoStore,
6
+ orbRouteErrorResponse,
7
+ readUserRouteRequest,
8
+ } from "../route-validation";
9
+
10
+ export const runtime = "nodejs";
11
+
12
+ // Fail fast instead of holding the request open on a slow upstream.
13
+ const UPSTREAM_TIMEOUT_MS = 10_000;
14
+
15
+ export async function POST(request: NextRequest) {
16
+ try {
17
+ const {
18
+ address,
19
+ xAccessToken,
20
+ userAvatarThumbnailDimension,
21
+ mediaThumbnailDimension,
22
+ } = await readUserRouteRequest(request);
23
+
24
+ const sdk = new OrbAppsSDK();
25
+
26
+ const requestBody = {
27
+ address,
28
+ userAvatarThumbnailDimension,
29
+ mediaThumbnailDimension,
30
+ };
31
+
32
+ const data = await sdk.callApi(xAccessToken, (api, requestOptions) =>
33
+ api.userApi.getUser({
34
+ body: requestBody,
35
+ ...requestOptions,
36
+ signal: AbortSignal.timeout(UPSTREAM_TIMEOUT_MS),
37
+ }),
38
+ );
39
+
40
+ return jsonNoStore(data);
41
+ } catch (reason) {
42
+ return orbRouteErrorResponse(reason, "Failed to load current user");
43
+ }
44
+ }
@@ -0,0 +1,105 @@
1
+ export class RouteError extends Error {
2
+ readonly status: number;
3
+
4
+ constructor(status: number, message: string) {
5
+ super(message);
6
+ this.name = "RouteError";
7
+ this.status = status;
8
+ }
9
+ }
10
+
11
+ function assertJsonContentType(request: Request): void {
12
+ const mediaType = request.headers
13
+ .get("content-type")
14
+ ?.split(";", 1)[0]
15
+ ?.trim()
16
+ .toLowerCase();
17
+
18
+ if (mediaType !== "application/json") {
19
+ throw new RouteError(415, "Content-Type must be application/json.");
20
+ }
21
+ }
22
+
23
+ function assertDeclaredBodySize(
24
+ request: Request,
25
+ maxBytes: number,
26
+ tooLargeMessage: string,
27
+ ): void {
28
+ const contentLength = request.headers.get("content-length");
29
+ if (contentLength === null) return;
30
+
31
+ if (!/^\d+$/.test(contentLength)) {
32
+ throw new RouteError(400, "Content-Length must be a non-negative integer.");
33
+ }
34
+
35
+ if (Number(contentLength) > maxBytes) {
36
+ throw new RouteError(413, tooLargeMessage);
37
+ }
38
+ }
39
+
40
+ async function readBoundedBody(
41
+ request: Request,
42
+ maxBytes: number,
43
+ tooLargeMessage: string,
44
+ ): Promise<string> {
45
+ if (!request.body) return "";
46
+
47
+ const reader = request.body.getReader();
48
+ const decoder = new TextDecoder("utf-8", { fatal: true });
49
+ let byteLength = 0;
50
+ let body = "";
51
+
52
+ try {
53
+ while (true) {
54
+ const { done, value } = await reader.read();
55
+ if (done) break;
56
+
57
+ byteLength += value.byteLength;
58
+ if (byteLength > maxBytes) {
59
+ await reader.cancel().catch(() => undefined);
60
+ throw new RouteError(413, tooLargeMessage);
61
+ }
62
+
63
+ body += decoder.decode(value, { stream: true });
64
+ }
65
+
66
+ return body + decoder.decode();
67
+ } catch (reason) {
68
+ if (reason instanceof RouteError) throw reason;
69
+ throw new RouteError(400, "Request body must be valid UTF-8 JSON.");
70
+ } finally {
71
+ reader.releaseLock();
72
+ }
73
+ }
74
+
75
+ export async function readBoundedJsonObject(
76
+ request: Request,
77
+ maxBytes: number,
78
+ tooLargeMessage = "Request body is too large.",
79
+ ): Promise<Record<string, unknown>> {
80
+ assertJsonContentType(request);
81
+ assertDeclaredBodySize(request, maxBytes, tooLargeMessage);
82
+
83
+ let payload: unknown;
84
+ try {
85
+ payload = JSON.parse(
86
+ await readBoundedBody(request, maxBytes, tooLargeMessage),
87
+ );
88
+ } catch (reason) {
89
+ if (reason instanceof RouteError) throw reason;
90
+ throw new RouteError(400, "Request body must be valid JSON.");
91
+ }
92
+
93
+ if (!payload || typeof payload !== "object" || Array.isArray(payload)) {
94
+ throw new RouteError(400, "Request body must be a JSON object.");
95
+ }
96
+
97
+ return payload as Record<string, unknown>;
98
+ }
99
+
100
+ export function jsonNoStore(body: unknown, status = 200): Response {
101
+ return Response.json(body, {
102
+ status,
103
+ headers: { "cache-control": "no-store" },
104
+ });
105
+ }