@supatype/ssr 0.9.0 → 0.9.1

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@supatype/ssr",
3
- "version": "0.9.0",
3
+ "version": "0.9.1",
4
4
  "license": "MIT",
5
5
  "description": "Supatype server-side rendering utilities, create a client from cookie-based auth for Server Components, Route Handlers, and middleware",
6
6
  "type": "module",
@@ -10,10 +10,14 @@
10
10
  ".": {
11
11
  "import": "./dist/index.js",
12
12
  "types": "./dist/index.d.ts"
13
+ },
14
+ "./next": {
15
+ "import": "./dist/next.js",
16
+ "types": "./dist/next.d.ts"
13
17
  }
14
18
  },
15
19
  "dependencies": {
16
- "@supatype/client": "0.9.0"
20
+ "@supatype/client": "0.9.1"
17
21
  },
18
22
  "devDependencies": {
19
23
  "@types/node": "^22",
@@ -1,5 +1,6 @@
1
1
  import type { Session, User } from "@supatype/client"
2
2
  import type { CookieToSet } from "./types.js"
3
+ import { decodeBase64, isJsonObject, jwtClaims } from "./jwt-claims.js"
3
4
 
4
5
  /** The prefix `@supatype/client` names its session cookie with: `st-auth-token`. */
5
6
  export const DEFAULT_COOKIE_PREFIX = "st"
@@ -29,11 +30,6 @@ export function parseSessionFromCookies(
29
30
  return null
30
31
  }
31
32
 
32
- /** True for a JSON object: not null, not an array. */
33
- function isJsonObject(value: unknown): value is Record<string, unknown> {
34
- return typeof value === "object" && value !== null && !Array.isArray(value)
35
- }
36
-
37
33
  function parseSessionValue(value: string): Session | null {
38
34
  try {
39
35
  return normalizeSession(JSON.parse(decodeURIComponent(value)))
@@ -44,17 +40,6 @@ function parseSessionValue(value: string): Session | null {
44
40
  return null
45
41
  }
46
42
 
47
- /**
48
- * Base64 or base64url text decoded as UTF-8, with `atob` and `TextDecoder` rather than Node's
49
- * `Buffer`: the server client also runs on edge runtimes, which have no `Buffer`. Throws on input
50
- * that is not base64.
51
- */
52
- function decodeBase64(text: string): string {
53
- const standard = text.replace(/-/g, "+").replace(/_/g, "/")
54
- const binary = atob(standard + "=".repeat((4 - (standard.length % 4)) % 4))
55
- return new TextDecoder().decode(Uint8Array.from(binary, (c) => c.charCodeAt(0)))
56
- }
57
-
58
43
  /**
59
44
  * The session a cookie holds. One whose access token has expired is kept when it carries a refresh
60
45
  * token: the first request the client makes refreshes it, and the server client writes the new
@@ -76,18 +61,12 @@ function normalizeSession(r: unknown): Session | null {
76
61
  }
77
62
 
78
63
  function isJwtExpired(token: string): boolean {
79
- const parts = token.split(".")
80
- if (parts.length !== 3) return true
81
- try {
82
- const payload = JSON.parse(decodeBase64(parts[1]!))
83
- // A payload that is not an object reads as expired, as it did when reading it threw.
84
- if (!isJsonObject(payload)) return true
85
- const exp = typeof payload["exp"] === "number" ? payload["exp"] : null
86
- if (exp === null) return false
87
- return Date.now() / 1000 > exp
88
- } catch {
89
- return true
90
- }
64
+ // A token that is not a JWT, or whose payload is not an object, reads as expired.
65
+ const payload = jwtClaims(token)
66
+ if (payload === null) return true
67
+ const exp = typeof payload["exp"] === "number" ? payload["exp"] : null
68
+ if (exp === null) return false
69
+ return Date.now() / 1000 > exp
91
70
  }
92
71
 
93
72
  function normalizeUser(raw: Record<string, unknown>): User {
@@ -0,0 +1,30 @@
1
+ /**
2
+ * Reading a JWT's claims without verifying it, in a way every runtime the server client reaches
3
+ * supports: `atob` and `TextDecoder` rather than Node's `Buffer`, which edge runtimes do not have.
4
+ * Shared by the cookie parser (a session's expiry) and the Next.js route (a service role token
5
+ * where the anon key belongs).
6
+ */
7
+
8
+ /** True for a JSON object: not null, not an array. */
9
+ export function isJsonObject(value: unknown): value is Record<string, unknown> {
10
+ return typeof value === "object" && value !== null && !Array.isArray(value)
11
+ }
12
+
13
+ /** Base64 or base64url text decoded as UTF-8. Throws on input that is not base64. */
14
+ export function decodeBase64(text: string): string {
15
+ const standard = text.replace(/-/g, "+").replace(/_/g, "/")
16
+ const binary = atob(standard + "=".repeat((4 - (standard.length % 4)) % 4))
17
+ return new TextDecoder().decode(Uint8Array.from(binary, (c) => c.charCodeAt(0)))
18
+ }
19
+
20
+ /** The payload of a three-part JWT, or null for anything else. Not verified. */
21
+ export function jwtClaims(token: string): Record<string, unknown> | null {
22
+ const payload = token.split(".")
23
+ if (payload.length !== 3 || payload[1] === undefined) return null
24
+ try {
25
+ const claims: unknown = JSON.parse(decodeBase64(payload[1]))
26
+ return isJsonObject(claims) ? claims : null
27
+ } catch {
28
+ return null
29
+ }
30
+ }
package/src/next.ts ADDED
@@ -0,0 +1,149 @@
1
+ /**
2
+ * `/supatype-env.js` for a Next.js app: the route that gives a page the deployment's API address
3
+ * and anon key when it loads, so one `next build` runs against any deployment.
4
+ *
5
+ * `next build` prerenders the static pages without the deployment's values, and the client then
6
+ * reads them from `window.__SUPATYPE_ENV__` at its first request. This route sets that global from
7
+ * `SUPATYPE_URL` and `SUPATYPE_ANON_KEY` as the running server has them, with the same body,
8
+ * headers and misconfigured answer as the Supatype server's own `/supatype-env.js`. Put it at
9
+ * `app/supatype-env.js/route.ts`:
10
+ *
11
+ * export { GET } from "@supatype/ssr/next"
12
+ * export const dynamic = "force-dynamic"
13
+ *
14
+ * The `dynamic` line is written in the route file itself: Next's build reads a route's segment
15
+ * config from that file's own source, and warns that it cannot recognize a re-exported one and
16
+ * uses the default instead. Next 15 already renders a `GET` handler per request by default; Next 14
17
+ * prerendered one, which would bake the build machine's values into a static file. Then load it
18
+ * before the app in the root layout:
19
+ *
20
+ * <Script src="/supatype-env.js" strategy="beforeInteractive" />
21
+ *
22
+ * The anon key is not a secret: every browser that loads the app holds it, and row-level security
23
+ * protects the data. The service role key is never read here, and an anon key variable holding a
24
+ * service role token is refused rather than published.
25
+ */
26
+
27
+ import { jwtClaims } from "./jwt-claims.js"
28
+ import { SERVER_ANON_KEY_ENV, SERVER_URL_ENV, serverEnv } from "./server-env.js"
29
+
30
+ /** Never prerendered. Exported for tests and tools; the route file writes its own (see above). */
31
+ export const dynamic = "force-dynamic"
32
+
33
+ const PUBLIC_ENV_SWITCH = "SUPATYPE_PUBLIC_ENV"
34
+ const SCRIPT_GLOBAL = "window.__SUPATYPE_ENV__"
35
+
36
+ /** `<`, `>`, `&` and the two JavaScript line separators, escaped in the body as Go's JSON does. */
37
+ const SCRIPT_UNSAFE = new Set([0x3c, 0x3e, 0x26, 0x2028, 0x2029])
38
+
39
+ /**
40
+ * The deployment's values for the page; or the reason it is misconfigured, a fault to fix; or
41
+ * switched off, as if there were no route.
42
+ */
43
+ type PublicEnv = { url: string; anonKey: string } | { error: string } | "off"
44
+
45
+ /**
46
+ * `GET /supatype-env.js`: the script setting `window.__SUPATYPE_ENV__`. Misconfigured, it is still
47
+ * 200 and sets only `error`, the reason, because a browser runs no script answered with an error
48
+ * status and tells the page nothing of why: this is the one way the client can name the fault on
49
+ * its first call. Switched off it is 404, as the Supatype server answers.
50
+ */
51
+ export function GET(): Response {
52
+ const env = readPublicEnv()
53
+ if (env === "off") return notFound()
54
+ // A reason is kept by nothing, so the fixed configuration is read on the next load. Values are
55
+ // revalidated on every load: they change when the deployment's configuration does.
56
+ return script(env, "error" in env ? "no-store" : "no-cache")
57
+ }
58
+
59
+ /** The values to serve, read from the environment now, or why there are none. */
60
+ function readPublicEnv(): PublicEnv {
61
+ const enabled = publicEnvSwitch(serverEnv(PUBLIC_ENV_SWITCH))
62
+ if (enabled === false) return "off"
63
+ // A word it cannot read is a fault to fix, not a choice to turn the route off.
64
+ if (enabled !== true) return { error: enabled.invalid }
65
+ // Both, or neither: a page given only the key fails at its first request for want of an address,
66
+ // and the reason naming the variables says why, where the deployment is configured. Every fault
67
+ // is named in one reason, one per line and the key's first, so a single visit fixes them all.
68
+ const url = publicUrl(serverEnv(SERVER_URL_ENV))
69
+ const anonKey = serverEnv(SERVER_ANON_KEY_ENV)
70
+ const keyFault = anonKeyFault(anonKey)
71
+ const urlFault = url === undefined ? notSet(SERVER_URL_ENV) : undefined
72
+ if (url === undefined || anonKey === undefined || keyFault !== undefined) {
73
+ const faults = [keyFault, urlFault].filter((fault): fault is string => fault !== undefined)
74
+ return { error: faults.join("\n") }
75
+ }
76
+ return { url, anonKey }
77
+ }
78
+
79
+ /** Why the anon key variable cannot be served, or undefined when it can. */
80
+ function anonKeyFault(anonKey: string | undefined): string | undefined {
81
+ if (anonKey === undefined) return notSet(SERVER_ANON_KEY_ENV)
82
+ if (jwtClaims(anonKey)?.["role"] !== "service_role") return undefined
83
+ return (
84
+ `public env unavailable: ${SERVER_ANON_KEY_ENV} holds a service_role token, which must never ` +
85
+ "reach a browser. Set it to the project's anon key."
86
+ )
87
+ }
88
+
89
+ /** The reason line for a variable the server does not have, as the Supatype server words it. */
90
+ function notSet(name: string): string {
91
+ return `public env unavailable: ${name} is not set on this server`
92
+ }
93
+
94
+ /**
95
+ * `SUPATYPE_PUBLIC_ENV` as the server reads it: on when blank or 1, true, yes or on; off for 0, false,
96
+ * no or off. Any other word stops the server from starting; here, with no start to stop, the route
97
+ * is a reason naming the variable and the words it takes.
98
+ */
99
+ function publicEnvSwitch(raw: string | undefined): boolean | { invalid: string } {
100
+ const value = (raw ?? "").toLowerCase()
101
+ if (["", "1", "true", "yes", "on"].includes(value)) return true
102
+ if (["0", "false", "no", "off"].includes(value)) return false
103
+ return {
104
+ invalid:
105
+ `public env unavailable: ${PUBLIC_ENV_SWITCH}=${JSON.stringify(raw)} is not a switch value. Use ` +
106
+ "true, 1, yes or on (or leave it blank) to serve it, and false, 0, no or off to turn it off.",
107
+ }
108
+ }
109
+
110
+ /** The API root, as the server gives it: no trailing slash, no auth service mount. */
111
+ function publicUrl(raw: string | undefined): string | undefined {
112
+ const trimmed = raw?.replace(/\/+$/, "").replace(/\/auth\/v1$/, "")
113
+ return trimmed === undefined || trimmed === "" ? undefined : trimmed
114
+ }
115
+
116
+ /** JSON that cannot close the script element or end the statement early. */
117
+ function escapeForScript(json: string): string {
118
+ let out = ""
119
+ for (const ch of json) {
120
+ const code = ch.codePointAt(0) ?? 0
121
+ out += SCRIPT_UNSAFE.has(code) ? `\\u${code.toString(16).padStart(4, "0")}` : ch
122
+ }
123
+ return out
124
+ }
125
+
126
+ /** The statement setting `window.__SUPATYPE_ENV__` to `doc`, with the server's headers. */
127
+ function script(doc: object, cacheControl: "no-cache" | "no-store"): Response {
128
+ const body = `${SCRIPT_GLOBAL} = ${escapeForScript(JSON.stringify(doc))};\n`
129
+ return new Response(body, {
130
+ status: 200,
131
+ headers: {
132
+ "Content-Type": "application/javascript; charset=utf-8",
133
+ "Cache-Control": cacheControl,
134
+ "X-Content-Type-Options": "nosniff",
135
+ },
136
+ })
137
+ }
138
+
139
+ /** A 404 nothing keeps, so switching the route back on is seen at once, as the server answers. */
140
+ function notFound(): Response {
141
+ return new Response("404 page not found\n", {
142
+ status: 404,
143
+ headers: {
144
+ "Content-Type": "text/plain; charset=utf-8",
145
+ "Cache-Control": "no-store",
146
+ "X-Content-Type-Options": "nosniff",
147
+ },
148
+ })
149
+ }
@@ -1,6 +1,7 @@
1
1
  import { createClient } from "@supatype/client"
2
2
  import type { SupatypeClient, AnyDatabase } from "@supatype/client"
3
3
  import { DEFAULT_COOKIE_PREFIX, parseSessionFromCookies, sessionCookie } from "./cookie-parser.js"
4
+ import { SERVER_ANON_KEY_NAMES, SERVER_URL_NAMES, serverEnv } from "./server-env.js"
4
5
  import type { CookieAdapter, ServerClientOptions } from "./types.js"
5
6
 
6
7
  /**
@@ -14,17 +15,30 @@ import type { CookieAdapter, ServerClientOptions } from "./types.js"
14
15
  * Without `setAll` (a Server Component) it never refreshes: an expired access token is sent as it
15
16
  * is and refused. A refresh there would spend the browser's refresh token and return one the
16
17
  * browser never receives, so the browser's own next refresh would be refused and sign it out.
18
+ *
19
+ * The address and anon key default to `SUPATYPE_URL` and `SUPATYPE_ANON_KEY` from the server's
20
+ * environment, read now: pass only the options, or `undefined` for either. These are the same two
21
+ * variables `@supatype/ssr/next` serves to the page. Where one is unset, `NEXT_PUBLIC_SUPATYPE_URL`
22
+ * or `NEXT_PUBLIC_SUPATYPE_ANON_KEY` is used instead. With none given or set, the client's first
23
+ * request throws the error naming them.
17
24
  */
18
25
  export function createServerClient<TDatabase extends AnyDatabase = AnyDatabase>(
19
- url: string,
20
- anonKey: string,
21
26
  options: ServerClientOptions,
27
+ ): SupatypeClient<TDatabase>
28
+ export function createServerClient<TDatabase extends AnyDatabase = AnyDatabase>(
29
+ url: string | undefined,
30
+ anonKey: string | undefined,
31
+ options: ServerClientOptions,
32
+ ): SupatypeClient<TDatabase>
33
+ export function createServerClient<TDatabase extends AnyDatabase = AnyDatabase>(
34
+ ...args: [ServerClientOptions] | [string | undefined, string | undefined, ServerClientOptions]
22
35
  ): SupatypeClient<TDatabase> {
36
+ const [url, anonKey, options] = args.length === 1 ? [undefined, undefined, args[0]] : args
23
37
  const prefix = options.cookiePrefix ?? DEFAULT_COOKIE_PREFIX
24
38
  const session = parseSessionFromCookies(options.cookies.getAll(), prefix)
25
39
  const client = createClient<TDatabase>({
26
- url,
27
- anonKey,
40
+ url: givenOrServerEnv(url, SERVER_URL_NAMES),
41
+ anonKey: givenOrServerEnv(anonKey, SERVER_ANON_KEY_NAMES),
28
42
  auth: {
29
43
  persistSession: false,
30
44
  autoRefreshToken: false,
@@ -37,6 +51,16 @@ export function createServerClient<TDatabase extends AnyDatabase = AnyDatabase>(
37
51
  return client
38
52
  }
39
53
 
54
+ /** The value given, unless it is missing or blank, else the first of the server's `names` that is set. */
55
+ function givenOrServerEnv(given: string | undefined, names: readonly string[]): string | undefined {
56
+ if (given !== undefined && given.trim() !== "") return given
57
+ for (const name of names) {
58
+ const value = serverEnv(name)
59
+ if (value !== undefined) return value
60
+ }
61
+ return undefined
62
+ }
63
+
40
64
  /**
41
65
  * Send every change to the client's session (a refresh, a sign-in, a sign-out) back to the browser
42
66
  * through the adapter's `setAll`, so the next request reads the new tokens rather than the old ones.
@@ -0,0 +1,26 @@
1
+ /**
2
+ * The two variables a Next.js server (or any server-side code) reads the deployment's address and
3
+ * anon key from: `createServerClient`'s defaults, and the values `@supatype/ssr/next` serves to the
4
+ * page. They are read where the app runs, so one build serves whichever deployment it runs as. A
5
+ * `NEXT_PUBLIC_` name, fixed into the build, is only the server client's fallback.
6
+ */
7
+
8
+ export const SERVER_URL_ENV = "SUPATYPE_URL"
9
+ export const SERVER_ANON_KEY_ENV = "SUPATYPE_ANON_KEY"
10
+
11
+ /**
12
+ * Where `createServerClient` looks for each value: the server's own name first, read where the app
13
+ * runs, then the Next.js build-time name an app may already set. The route serves only the first.
14
+ */
15
+ export const SERVER_URL_NAMES = [SERVER_URL_ENV, "NEXT_PUBLIC_SUPATYPE_URL"] as const
16
+ export const SERVER_ANON_KEY_NAMES = [SERVER_ANON_KEY_ENV, "NEXT_PUBLIC_SUPATYPE_ANON_KEY"] as const
17
+
18
+ /**
19
+ * A variable from the server's environment, trimmed; undefined when unset or blank, and where there
20
+ * is no `process` at all. Read by name at call time, so no bundler can fix its build-time value in.
21
+ */
22
+ export function serverEnv(name: string): string | undefined {
23
+ if (typeof process === "undefined" || typeof process.env !== "object") return undefined
24
+ const value = process.env[name]?.trim()
25
+ return value === undefined || value === "" ? undefined : value
26
+ }
@@ -0,0 +1,184 @@
1
+ /**
2
+ * `@supatype/ssr/next`: `/supatype-env.js` served by a Next.js app, from the server's environment.
3
+ *
4
+ * `next build` prerenders the app's pages without the deployment's values. The route below answers
5
+ * every page load with the ones the running server has, in the same body, headers and refusals as
6
+ * the Supatype server's own `/supatype-env.js`, so one build runs on any deployment.
7
+ */
8
+ import { runInNewContext } from "node:vm"
9
+ import { afterEach, assert, describe, expect, it, vi } from "vitest"
10
+ import { GET, dynamic } from "../src/next.js"
11
+
12
+ afterEach(() => {
13
+ vi.unstubAllEnvs()
14
+ })
15
+
16
+ /** An unsigned JWT carrying `role`. */
17
+ function jwtFor(role: string): string {
18
+ return `e30.${Buffer.from(JSON.stringify({ role })).toString("base64url")}.sig`
19
+ }
20
+
21
+ /** Set the two variables the route reads; undefined removes one. */
22
+ function serverEnv(url: string | undefined, anonKey: string | undefined): void {
23
+ vi.stubEnv("SUPATYPE_URL", url)
24
+ vi.stubEnv("SUPATYPE_ANON_KEY", anonKey)
25
+ }
26
+
27
+ /** What the page's global holds after running `body`, as a browser would. */
28
+ function pageEnvAfter(body: string): unknown {
29
+ const window: Record<string, unknown> = {}
30
+ runInNewContext(body, { window })
31
+ return window["__SUPATYPE_ENV__"]
32
+ }
33
+
34
+ /**
35
+ * The reason a misconfigured route gives the page. A browser runs no script answered with an error
36
+ * status and tells the page nothing of why, so the route answers 200, kept by nothing, with a
37
+ * script that sets only `error`: the one way the client can name the fault on its first call.
38
+ */
39
+ async function reasonFrom(res: Response): Promise<{ error: string; body: string }> {
40
+ expect(res.status).toBe(200)
41
+ expect(res.headers.get("content-type")).toBe("application/javascript; charset=utf-8")
42
+ expect(res.headers.get("cache-control")).toBe("no-store")
43
+ expect(res.headers.get("x-content-type-options")).toBe("nosniff")
44
+ const body = await res.text()
45
+ const env = pageEnvAfter(body)
46
+ assert(typeof env === "object" && env !== null && "error" in env && typeof env.error === "string")
47
+ expect(Object.keys(env)).toEqual(["error"])
48
+ return { error: env.error, body }
49
+ }
50
+
51
+ describe("GET /supatype-env.js", () => {
52
+ it("is never prerendered", () => {
53
+ expect(dynamic).toBe("force-dynamic")
54
+ })
55
+
56
+ it("sets window.__SUPATYPE_ENV__ to the server's address and anon key", async () => {
57
+ serverEnv("https://api.example.com", "anon-key")
58
+ const res = GET()
59
+
60
+ expect(res.status).toBe(200)
61
+ expect(await res.text()).toBe('window.__SUPATYPE_ENV__ = {"url":"https://api.example.com","anonKey":"anon-key"};\n')
62
+ })
63
+
64
+ it("carries the server's headers: a script, revalidated on every load, never sniffed", () => {
65
+ serverEnv("https://api.example.com", "anon-key")
66
+ const res = GET()
67
+
68
+ expect(res.headers.get("content-type")).toBe("application/javascript; charset=utf-8")
69
+ expect(res.headers.get("cache-control")).toBe("no-cache")
70
+ expect(res.headers.get("x-content-type-options")).toBe("nosniff")
71
+ })
72
+
73
+ it("reads the environment per request, so one build serves whichever values it runs with", async () => {
74
+ serverEnv("https://one.example.com", "key-one")
75
+ const first = pageEnvAfter(await GET().text())
76
+ serverEnv("https://two.example.com", "key-two")
77
+ const second = pageEnvAfter(await GET().text())
78
+
79
+ expect(first).toEqual({ url: "https://one.example.com", anonKey: "key-one" })
80
+ expect(second).toEqual({ url: "https://two.example.com", anonKey: "key-two" })
81
+ })
82
+
83
+ it("sets only the reason, 200 no-store, naming the variable, when the address is unset", async () => {
84
+ serverEnv(undefined, "anon-key")
85
+ const { error, body } = await reasonFrom(GET())
86
+
87
+ expect(error).toBe("public env unavailable: SUPATYPE_URL is not set on this server")
88
+ expect(body).not.toContain("anon-key")
89
+ })
90
+
91
+ it("trims the address as the server does", async () => {
92
+ serverEnv(" https://api.example.com/auth/v1/ ", " anon-key ")
93
+ expect(pageEnvAfter(await GET().text())).toEqual({ url: "https://api.example.com", anonKey: "anon-key" })
94
+ })
95
+
96
+ it("escapes what could end the script element or the statement", async () => {
97
+ const hostile = "</script><script>alert(1)</script>\u2028\u2029&"
98
+ serverEnv("https://api.example.com", hostile)
99
+ const body = await GET().text()
100
+
101
+ expect(body).not.toContain("</script>")
102
+ expect(body).not.toMatch(/[<>&\u2028\u2029]/)
103
+ expect(pageEnvAfter(body)).toEqual({ url: "https://api.example.com", anonKey: hostile })
104
+ })
105
+
106
+ it("sets only the reason, 200 no-store, naming the variable, when the anon key is unset", async () => {
107
+ serverEnv("https://api.example.com", undefined)
108
+ const { error } = await reasonFrom(GET())
109
+
110
+ expect(error).toBe("public env unavailable: SUPATYPE_ANON_KEY is not set on this server")
111
+ })
112
+
113
+ it("names every unset setting in one reason, the anon key first, so one fix covers both", async () => {
114
+ serverEnv(undefined, undefined)
115
+ const { body } = await reasonFrom(GET())
116
+
117
+ expect(body).toBe(
118
+ 'window.__SUPATYPE_ENV__ = {"error":"public env unavailable: SUPATYPE_ANON_KEY is not set on this server\\n' +
119
+ 'public env unavailable: SUPATYPE_URL is not set on this server"};\n',
120
+ )
121
+ })
122
+
123
+ it("names an unset address beside a service role anon key, whose refusal reads as before", async () => {
124
+ const service = jwtFor("service_role")
125
+ serverEnv(undefined, service)
126
+ const { error, body } = await reasonFrom(GET())
127
+ const lines = error.split("\n")
128
+
129
+ expect(lines).toHaveLength(2)
130
+ expect(lines[0]).toContain("holds a service_role token")
131
+ expect(lines[1]).toBe("public env unavailable: SUPATYPE_URL is not set on this server")
132
+ expect(body).not.toContain(service)
133
+ })
134
+
135
+ it.each(["false", "0", "no", "off", " FALSE "])("is 404 no-store when SUPATYPE_PUBLIC_ENV is %j", async (off) => {
136
+ serverEnv("https://api.example.com", "anon-key")
137
+ vi.stubEnv("SUPATYPE_PUBLIC_ENV", off)
138
+ const res = GET()
139
+
140
+ expect(res.status).toBe(404)
141
+ expect(res.headers.get("cache-control")).toBe("no-store")
142
+ expect(await res.text()).not.toContain("anon-key")
143
+ })
144
+
145
+ it.each(["", "true", "1", "yes", "on"])("serves when SUPATYPE_PUBLIC_ENV is %j", (on) => {
146
+ serverEnv("https://api.example.com", "anon-key")
147
+ vi.stubEnv("SUPATYPE_PUBLIC_ENV", on)
148
+ expect(GET().status).toBe(200)
149
+ })
150
+
151
+ it("sets only the reason for a SUPATYPE_PUBLIC_ENV it cannot read, naming it and the words it takes", async () => {
152
+ serverEnv("https://api.example.com", "anon-key")
153
+ vi.stubEnv("SUPATYPE_PUBLIC_ENV", "nope")
154
+ const { error, body } = await reasonFrom(GET())
155
+
156
+ expect(error).toContain('SUPATYPE_PUBLIC_ENV="nope"')
157
+ for (const word of ["true", "1", "yes", "on", "false", "0", "no", "off"]) expect(error).toContain(word)
158
+ expect(body).not.toContain("anon-key")
159
+ })
160
+
161
+ it("never serves a service role value", async () => {
162
+ const service = jwtFor("service_role")
163
+ serverEnv("https://api.example.com", "anon-key")
164
+ vi.stubEnv("SUPATYPE_SERVICE_ROLE_KEY", service)
165
+ vi.stubEnv("SERVICE_ROLE_KEY", service)
166
+
167
+ expect(await GET().text()).not.toContain(service)
168
+ })
169
+
170
+ it("sets only the reason for an anon key that is a service role token, rather than publish it", async () => {
171
+ const service = jwtFor("service_role")
172
+ serverEnv("https://api.example.com", service)
173
+ const { error, body } = await reasonFrom(GET())
174
+
175
+ expect(body).not.toContain(service)
176
+ expect(error).toContain("service_role")
177
+ })
178
+
179
+ it("serves an anon key that is an anon token", async () => {
180
+ const anon = jwtFor("anon")
181
+ serverEnv("https://api.example.com", anon)
182
+ expect(pageEnvAfter(await GET().text())).toEqual({ url: "https://api.example.com", anonKey: anon })
183
+ })
184
+ })
@@ -0,0 +1,108 @@
1
+ /**
2
+ * `createServerClient` takes its address and anon key from `SUPATYPE_URL` and `SUPATYPE_ANON_KEY`
3
+ * when it is not given them: the same two variables `@supatype/ssr/next` serves to the page, so a
4
+ * Next.js server sets them once for both. Read when the client is created, at request time.
5
+ */
6
+ import { afterEach, describe, expect, it, vi } from "vitest"
7
+ import { MissingClientValuesError } from "@supatype/client"
8
+ import { createServerClient } from "../src/index.js"
9
+
10
+ const cookies = { getAll: (): Array<{ name: string; value: string }> => [] }
11
+
12
+ afterEach(() => {
13
+ vi.unstubAllEnvs()
14
+ vi.unstubAllGlobals()
15
+ })
16
+
17
+ /** Every request's address and apikey, answered with an empty list. */
18
+ function captureRequests(): Array<{ url: string; apikey: string | null }> {
19
+ const seen: Array<{ url: string; apikey: string | null }> = []
20
+ vi.stubGlobal("fetch", async (url: string, init?: RequestInit) => {
21
+ seen.push({ url, apikey: new Headers(init?.headers).get("apikey") })
22
+ return new Response("[]", { status: 200, headers: { "content-type": "application/json" } })
23
+ })
24
+ return seen
25
+ }
26
+
27
+ describe("createServerClient's address and anon key", () => {
28
+ it("default to SUPATYPE_URL and SUPATYPE_ANON_KEY, given only the options", async () => {
29
+ vi.stubEnv("SUPATYPE_URL", "https://api.example.com")
30
+ vi.stubEnv("SUPATYPE_ANON_KEY", "server-anon")
31
+ const seen = captureRequests()
32
+
33
+ await createServerClient({ cookies }).from("posts").select()
34
+
35
+ expect(seen[0]?.url.startsWith("https://api.example.com/rest/v1/posts")).toBe(true)
36
+ expect(seen[0]?.apikey).toBe("server-anon")
37
+ })
38
+
39
+ it("default each on its own when passed as undefined", async () => {
40
+ vi.stubEnv("SUPATYPE_URL", "https://api.example.com")
41
+ vi.stubEnv("SUPATYPE_ANON_KEY", "server-anon")
42
+ const seen = captureRequests()
43
+
44
+ await createServerClient(undefined, "given-anon", { cookies }).from("posts").select()
45
+ await createServerClient("https://given.example.com", undefined, { cookies }).from("posts").select()
46
+
47
+ expect(seen.map((r) => [new URL(r.url).origin, r.apikey])).toEqual([
48
+ ["https://api.example.com", "given-anon"],
49
+ ["https://given.example.com", "server-anon"],
50
+ ])
51
+ })
52
+
53
+ it("are the ones passed, whatever the environment holds", async () => {
54
+ vi.stubEnv("SUPATYPE_URL", "https://api.example.com")
55
+ vi.stubEnv("SUPATYPE_ANON_KEY", "server-anon")
56
+ const seen = captureRequests()
57
+
58
+ await createServerClient("https://given.example.com", "given-anon", { cookies }).from("posts").select()
59
+
60
+ expect(seen[0]?.url.startsWith("https://given.example.com/")).toBe(true)
61
+ expect(seen[0]?.apikey).toBe("given-anon")
62
+ })
63
+
64
+ it("fall back to the build-time NEXT_PUBLIC_ names when the server's own are unset", async () => {
65
+ vi.stubEnv("SUPATYPE_URL", undefined)
66
+ vi.stubEnv("SUPATYPE_ANON_KEY", undefined)
67
+ vi.stubEnv("NEXT_PUBLIC_SUPATYPE_URL", "https://public.example.com")
68
+ vi.stubEnv("NEXT_PUBLIC_SUPATYPE_ANON_KEY", "public-anon")
69
+ const seen = captureRequests()
70
+
71
+ await createServerClient({ cookies }).from("posts").select()
72
+
73
+ expect(seen[0]?.url.startsWith("https://public.example.com/rest/v1/posts")).toBe(true)
74
+ expect(seen[0]?.apikey).toBe("public-anon")
75
+ })
76
+
77
+ it("prefer the server's own names to the NEXT_PUBLIC_ ones, each on its own", async () => {
78
+ vi.stubEnv("SUPATYPE_URL", "https://api.example.com")
79
+ vi.stubEnv("SUPATYPE_ANON_KEY", undefined)
80
+ vi.stubEnv("NEXT_PUBLIC_SUPATYPE_URL", "https://public.example.com")
81
+ vi.stubEnv("NEXT_PUBLIC_SUPATYPE_ANON_KEY", "public-anon")
82
+ const seen = captureRequests()
83
+
84
+ await createServerClient({ cookies }).from("posts").select()
85
+
86
+ expect(seen.map((r) => [new URL(r.url).origin, r.apikey])).toEqual([["https://api.example.com", "public-anon"]])
87
+ })
88
+
89
+ it("leave the first request to throw the named error when neither is anywhere", async () => {
90
+ vi.stubEnv("SUPATYPE_URL", undefined)
91
+ vi.stubEnv("SUPATYPE_ANON_KEY", undefined)
92
+ vi.stubEnv("NEXT_PUBLIC_SUPATYPE_URL", undefined)
93
+ vi.stubEnv("NEXT_PUBLIC_SUPATYPE_ANON_KEY", undefined)
94
+ const seen = captureRequests()
95
+
96
+ const client = createServerClient({ cookies })
97
+ const err: unknown = await client.from("posts").select().then(() => undefined, (e: unknown) => e)
98
+ expect(err).toBeInstanceOf(MissingClientValuesError)
99
+ expect(seen).toEqual([])
100
+
101
+ // On a server there is no page: the server's own variables come first, then the build-time ones.
102
+ const message = err instanceof Error ? err.message : ""
103
+ expect(message).not.toContain("window.__SUPATYPE_ENV__")
104
+ const serverNames = message.indexOf("Set SUPATYPE_URL and SUPATYPE_ANON_KEY in the server's environment")
105
+ expect(serverNames).toBeGreaterThan(-1)
106
+ expect(serverNames).toBeLessThan(message.indexOf("NEXT_PUBLIC_SUPATYPE_URL"))
107
+ })
108
+ })