Zum Hauptinhalt springen

TypeScript-Schnellstart

Diese Anleitung führt Sie durch die Authentifizierung bei der VaultPAM-API und das Absetzen Ihrer ersten Anfrage mit TypeScript und der nativen fetch-API (Node.js 18+).

Voraussetzungen:

  • Node.js 18 oder neuer (integrierte fetch-API)
  • TypeScript 5.x (optional — die Beispiele funktionieren auch als reines JavaScript)
  • Ein VaultPAM-Konto mit aktiviertem API-Zugriff

Schritt 1 — Richten Sie Ihre Umgebung ein

# Set your base URL in the environment — never hardcode in source
export VAULTPAM_BASE_URL="https://api.vaultpam.com"
export VAULTPAM_TOKEN="<your-token>" # Never commit — see auth-flow.md#token-storage

Laden Sie diese Werte bei Produktionsintegrationen aus einem Secrets-Manager oder einer .env-Datei, die in .gitignore aufgeführt ist.


Schritt 2 — Authentifizieren

const BASE_URL = process.env.VAULTPAM_BASE_URL ?? "https://api.vaultpam.com";

interface AuthResponse {
access_token: string;
expires_in: number;
}

async function login(email: string, password: string): Promise<AuthResponse> {
const response = await fetch(`${BASE_URL}/api/v1/auth/login`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ email, password }),
});

if (!response.ok) {
throw new Error(`Login failed: ${response.status} ${await response.text()}`);
}

return response.json() as Promise<AuthResponse>;
}

// Load credentials from environment — never commit to source control (see auth-flow.md#token-storage)
const email = process.env.VAULTPAM_EMAIL ?? "";
const password = process.env.VAULTPAM_PASSWORD ?? "";

const { access_token: token, expires_in: expiresIn } = await login(email, password);
console.log(`Authenticated. Token expires in ${expiresIn} seconds.`);
Geben Sie Tokens niemals in die Versionsverwaltung

Laden Sie VAULTPAM_TOKEN aus process.env oder einem Secrets-Manager — hinterlegen Sie Anmeldeinformationen niemals fest im Code. Siehe Token-Speicherung.


Schritt 3 — Rufen Sie Ihre aktive Organisation ab

interface OrgMembershipsResponse {
active_org_id: string;
memberships: Array<{ org_id: string; role: string }>;
}

async function getActiveOrgId(token: string): Promise<string> {
const response = await fetch(`${BASE_URL}/api/v1/org/memberships`, {
headers: { Authorization: `Bearer ${token}` },
});

if (!response.ok) {
throw new Error(`Failed to get org memberships: ${response.status}`);
}

const data = (await response.json()) as OrgMembershipsResponse;
return data.active_org_id;
}

const orgId = await getActiveOrgId(token);
console.log(`Active org: ${orgId}`);

Schritt 4 — Listen Sie Ihre Safes auf

interface Safe {
id: string;
name: string;
}

async function listSafes(token: string, orgId: string): Promise<Safe[]> {
const response = await fetch(`${BASE_URL}/api/v1/safes`, {
headers: {
Authorization: `Bearer ${token}`,
"X-Active-Org-Id": orgId,
},
});

if (!response.ok) {
throw new Error(`Failed to list safes: ${response.status} ${await response.text()}`);
}

return response.json() as Promise<Safe[]>;
}

const safes = await listSafes(token, orgId);
console.log(`Found ${safes.length} safe(s):`);
safes.forEach((s) => console.log(` - ${s.name}`));

Vollständiges Beispiel

const BASE_URL = process.env.VAULTPAM_BASE_URL ?? "https://api.vaultpam.com";

// Load from environment — never commit to source control (see auth-flow.md#token-storage)
const email = process.env.VAULTPAM_EMAIL ?? "";
const password = process.env.VAULTPAM_PASSWORD ?? "";

async function main(): Promise<void> {
// Step 1: Authenticate
const loginResp = await fetch(`${BASE_URL}/api/v1/auth/login`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ email, password }),
});
if (!loginResp.ok) throw new Error(`Login failed: ${loginResp.status}`);
const { access_token: token } = (await loginResp.json()) as { access_token: string };

// Step 2: Get active org
const orgResp = await fetch(`${BASE_URL}/api/v1/org/memberships`, {
headers: { Authorization: `Bearer ${token}` },
});
if (!orgResp.ok) throw new Error(`Org lookup failed: ${orgResp.status}`);
const { active_org_id: orgId } = (await orgResp.json()) as { active_org_id: string };

// Step 3: List safes
const safesResp = await fetch(`${BASE_URL}/api/v1/safes`, {
headers: {
Authorization: `Bearer ${token}`,
"X-Active-Org-Id": orgId,
},
});
if (!safesResp.ok) throw new Error(`Safes request failed: ${safesResp.status}`);
const safes = (await safesResp.json()) as Array<{ id: string; name: string }>;
console.log(`Safes (${safes.length}):`);
safes.forEach((s) => console.log(` ${s.name}`));
}

main().catch((err) => {
console.error(err);
process.exit(1);
});

Fehlerbehandlung

Alle fetch-Aufrufe prüfen response.ok und werfen bei einem Fehler eine Ausnahme. Häufige Statuscodes:

CodeBedeutung
401 UnauthorizedToken fehlt, ist abgelaufen oder ungültig. Erneut authentifizieren.
403 ForbiddenToken verfügt nicht über den erforderlichen Geltungsbereich für diesen Endpunkt.
429 Too Many RequestsRatenlimit überschritten. Prüfen Sie den retry-after-Header.
500 Internal Server ErrorVorübergehender Serverfehler. Mit Backoff erneut versuchen.

Berücksichtigung von Ratenlimits

const response = await fetch(`${BASE_URL}/api/v1/safes`, {
headers: { Authorization: `Bearer ${token}`, "X-Active-Org-Id": orgId },
});

const remaining = response.headers.get("x-ratelimit-remaining");
console.log(`Rate limit remaining: ${remaining}`);

Siehe Ratenlimits für Backoff-Strategien.


Nächste Schritte