The sandbox suites (stack.ts and its importers, the shell Playwright config) stop before their first request unless the container, the four loopback URLs and the key issuer are exactly the db:sandbox ones; the LAN config accepts the 5193 trial app only. Drift and wiring tests tie the constants to scripts/db-sandbox.sh.
252 lines
7.2 KiB
TypeScript
252 lines
7.2 KiB
TypeScript
/**
|
|
* Access to the throwaway stack of `pnpm db:sandbox` (scripts/db-sandbox.sh):
|
|
* real GoTrue, PostgREST and PostgreSQL sessions, never the DEV stack. The
|
|
* script passes the endpoints and the generated keys through the environment;
|
|
* the database password reaches `docker exec` through the environment too,
|
|
* never through a command argument. Any other target (the db:trial stack, DEV,
|
|
* a look-alike) stops the suite here, before its first request (./target.ts).
|
|
*/
|
|
import { execFile } from 'node:child_process'
|
|
import { randomBytes, randomUUID } from 'node:crypto'
|
|
import { assertSandboxTarget } from './target'
|
|
|
|
assertSandboxTarget(process.env)
|
|
|
|
const need = (name: string): string => {
|
|
const value = process.env[name]
|
|
if (!value)
|
|
throw new Error(`${name} missing: run through pnpm db:sandbox test`)
|
|
return value
|
|
}
|
|
|
|
export const stack = {
|
|
container: need('SANDBOX_DB_CONTAINER'),
|
|
authUrl: need('SANDBOX_AUTH_URL'),
|
|
restUrl: need('SANDBOX_REST_URL'),
|
|
storageUrl: need('SANDBOX_STORAGE_URL'),
|
|
mailUrl: need('SANDBOX_MAIL_URL'),
|
|
anonKey: need('SANDBOX_ANON_KEY'),
|
|
serviceKey: need('SANDBOX_SERVICE_KEY'),
|
|
}
|
|
const PG_PASSWORD = need('SANDBOX_PG_PASSWORD')
|
|
/** The seeded accounts' password in this sandbox session (db-sandbox.sh replaces the seed's). */
|
|
export const SEED_PASSWORD = need('SANDBOX_SEED_PASSWORD')
|
|
/** The password of the accounts a run creates: random per run, kept in memory only. */
|
|
export const PASSWORD = randomBytes(18).toString('base64url')
|
|
|
|
/** One psql session as postgres; resolves with stdout (tuples only) or rejects with stderr. */
|
|
export function sql(script: string): Promise<string> {
|
|
return new Promise((resolve, reject) => {
|
|
const child = execFile(
|
|
'docker',
|
|
[
|
|
'exec',
|
|
'-i',
|
|
'-e',
|
|
'PGPASSWORD',
|
|
stack.container,
|
|
'psql',
|
|
'-X',
|
|
'-q',
|
|
'-t',
|
|
'-A',
|
|
'-h',
|
|
'127.0.0.1',
|
|
'-U',
|
|
'postgres',
|
|
'-d',
|
|
'postgres',
|
|
'-v',
|
|
'ON_ERROR_STOP=1',
|
|
],
|
|
{
|
|
env: { ...process.env, PGPASSWORD: PG_PASSWORD },
|
|
maxBuffer: 64 * 1024 * 1024,
|
|
},
|
|
(error, stdout, stderr) =>
|
|
error
|
|
? reject(new Error(stderr || error.message))
|
|
: resolve(stdout.trim()),
|
|
)
|
|
child.stdin?.end(script)
|
|
})
|
|
}
|
|
|
|
/** Same session, but settles with the outcome instead of throwing (for refusal checks). */
|
|
export async function sqlOutcome(
|
|
script: string,
|
|
): Promise<{ ok: boolean; out: string }> {
|
|
try {
|
|
return { ok: true, out: await sql(script) }
|
|
} catch (error) {
|
|
return { ok: false, out: (error as Error).message }
|
|
}
|
|
}
|
|
|
|
export const uniqueEmail = (tag: string) =>
|
|
`${tag}-${randomUUID().slice(0, 8)}@sandbox.local`
|
|
|
|
async function authCall(
|
|
path: string,
|
|
body: unknown,
|
|
key = stack.anonKey,
|
|
): Promise<Response> {
|
|
return fetch(stack.authUrl + path, {
|
|
method: 'POST',
|
|
headers: {
|
|
apikey: stack.anonKey,
|
|
Authorization: `Bearer ${key}`,
|
|
'Content-Type': 'application/json',
|
|
},
|
|
body: JSON.stringify(body),
|
|
})
|
|
}
|
|
|
|
export async function signIn(
|
|
email: string,
|
|
password = PASSWORD,
|
|
): Promise<{ status: number; body: Record<string, unknown> }> {
|
|
const res = await authCall('/token?grant_type=password', { email, password })
|
|
return {
|
|
status: res.status,
|
|
body: (await res.json()) as Record<string, unknown>,
|
|
}
|
|
}
|
|
|
|
export interface Account {
|
|
id: string
|
|
email: string
|
|
token: string
|
|
}
|
|
|
|
/** A confirmed account created by the admin API, signed in. */
|
|
export async function confirmedAccount(tag: string): Promise<Account> {
|
|
const email = uniqueEmail(tag)
|
|
const res = await authCall(
|
|
'/admin/users',
|
|
{ email, password: PASSWORD, email_confirm: true },
|
|
stack.serviceKey,
|
|
)
|
|
const user = (await res.json()) as { id: string }
|
|
const session = await signIn(email)
|
|
return { id: user.id, email, token: session.body.access_token as string }
|
|
}
|
|
|
|
/** Public sign-up (no session until confirmation). */
|
|
export async function signUp(
|
|
email: string,
|
|
): Promise<{ status: number; body: Record<string, unknown> }> {
|
|
const res = await authCall('/signup', { email, password: PASSWORD })
|
|
return {
|
|
status: res.status,
|
|
body: (await res.json()) as Record<string, unknown>,
|
|
}
|
|
}
|
|
|
|
/** Opens the confirmation link GoTrue mailed to this address; returns the HTTP status. */
|
|
export async function confirmByMail(email: string): Promise<number> {
|
|
const search = (await (
|
|
await fetch(
|
|
`${stack.mailUrl}/api/v1/search?query=${encodeURIComponent('to:' + email)}`,
|
|
)
|
|
).json()) as {
|
|
messages: { ID: string }[]
|
|
}
|
|
const message = (await (
|
|
await fetch(`${stack.mailUrl}/api/v1/message/${search.messages[0].ID}`)
|
|
).json()) as { Text: string }
|
|
const link = message.Text.match(
|
|
new RegExp(
|
|
`${stack.authUrl.replace(/[.:/]/g, '\\$&')}/verify\\?[^\\s)\\]]+`,
|
|
),
|
|
)?.[0]
|
|
if (!link) throw new Error('no confirmation link in the mail')
|
|
return (await fetch(link.replace(/&/g, '&'), { redirect: 'manual' }))
|
|
.status
|
|
}
|
|
|
|
/** GoTrue admin link for any account: the residual path of contract §6.3. */
|
|
export async function adminMagicLinkSession(
|
|
email: string,
|
|
): Promise<string | null> {
|
|
const res = await authCall(
|
|
'/admin/generate_link',
|
|
{ type: 'magiclink', email },
|
|
stack.serviceKey,
|
|
)
|
|
const body = (await res.json()) as {
|
|
action_link?: string
|
|
properties?: { action_link?: string }
|
|
}
|
|
const link = body.action_link ?? body.properties?.action_link
|
|
if (!link) return null
|
|
const verify = await fetch(link, { redirect: 'manual' })
|
|
return new URLSearchParams(
|
|
(verify.headers.get('location') ?? '').split('#')[1] ?? '',
|
|
).get('access_token')
|
|
}
|
|
|
|
export async function adminDeleteUser(id: string): Promise<number> {
|
|
const res = await fetch(`${stack.authUrl}/admin/users/${id}`, {
|
|
method: 'DELETE',
|
|
headers: {
|
|
apikey: stack.anonKey,
|
|
Authorization: `Bearer ${stack.serviceKey}`,
|
|
},
|
|
})
|
|
return res.status
|
|
}
|
|
|
|
export interface RestResult {
|
|
status: number
|
|
body: unknown
|
|
text: string
|
|
headers: Headers
|
|
}
|
|
|
|
/** A PostgREST request with the given bearer token (a user's, or the anon / service key). */
|
|
export async function rest(
|
|
path: string,
|
|
token: string,
|
|
init: RequestInit = {},
|
|
): Promise<RestResult> {
|
|
const res = await fetch(stack.restUrl + path, {
|
|
...init,
|
|
headers: {
|
|
Authorization: `Bearer ${token}`,
|
|
'Content-Type': 'application/json',
|
|
...(init.headers ?? {}),
|
|
},
|
|
})
|
|
const text = await res.text()
|
|
let body: unknown = text
|
|
try {
|
|
body = JSON.parse(text)
|
|
} catch {
|
|
// not JSON: keep the text
|
|
}
|
|
return { status: res.status, body, text, headers: res.headers }
|
|
}
|
|
|
|
/** POST /rpc/<fn>: the way the app calls every RPC (terms stay out of URLs). */
|
|
export function rpc(
|
|
fn: string,
|
|
args: Record<string, unknown>,
|
|
token: string,
|
|
headers: Record<string, string> = {},
|
|
) {
|
|
return rest(`/rpc/${fn}`, token, {
|
|
method: 'POST',
|
|
body: JSON.stringify(args),
|
|
headers,
|
|
})
|
|
}
|
|
|
|
/** The PostgREST error code of a refusal, or null. */
|
|
export const errorCode = (result: RestResult): string | null =>
|
|
typeof result.body === 'object' &&
|
|
result.body !== null &&
|
|
'code' in result.body
|
|
? String((result.body as { code: unknown }).code)
|
|
: null
|