Guida rapida TypeScript
Questa guida illustra come autenticarsi all'API VaultPAM e effettuare la tua prima richiesta utilizzando TypeScript e l'API fetch nativa (Node.js 18+).
Prerequisiti:
- Node.js 18 o versione successiva (API
fetchintegrata) - TypeScript 5.x (facoltativo — gli esempi funzionano anche come JavaScript semplice)
- Un account VaultPAM con accesso API abilitato
Passaggio 1 — Configura il tuo ambiente
# Imposta il tuo URL base nell'ambiente — non inserire mai hardcoded nella sorgente
export VAULTPAM_BASE_URL="https://api.vaultpam.com"
export VAULTPAM_TOKEN="<your-token>" # Non eseguire il commit — vedi auth-flow.md#token-storage
Per le integrazioni di produzione, carica questi valori da un gestore di segreti o da un file .env elencato in .gitignore.
Passaggio 2 — Autentica
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>;
}
// Carica le credenziali dall'ambiente — non eseguire mai il commit nel controllo di sorgente (vedi 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.`);
Non eseguire mai il commit di token
Carica VAULTPAM_TOKEN da process.env o da un gestore di segreti — non inserire mai hardcoded le credenziali. Vedi Archiviazione dei token.
Passaggio 3 — Ottieni la tua organizzazione attiva
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}`);
Passaggio 4 — Elenca i tuoi Safes
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}`));
Esempio completo
const BASE_URL = process.env.VAULTPAM_BASE_URL ?? "https://api.vaultpam.com";
// Carica dall'ambiente — non eseguire mai il commit nel controllo di sorgente (vedi auth-flow.md#token-storage)
const email = process.env.VAULTPAM_EMAIL ?? "";
const password = process.env.VAULTPAM_PASSWORD ?? "";
async function main(): Promise<void> {
// Passaggio 1: Autentica
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 };
// Passaggio 2: Ottieni l'organizzazione attiva
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 };
// Passaggio 3: Elenca i 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);
});
Gestione degli errori
Tutte le chiamate fetch controllano response.ok e generano un'eccezione in caso di errore. Codici di stato comuni:
| Codice | Significato |
|---|---|
401 Unauthorized | Il token è mancante, scaduto o non valido. Effettua di nuovo l'autenticazione. |
403 Forbidden | Il token non dispone dell'ambito richiesto per questo endpoint. |
429 Too Many Requests | Limite di frequenza superato. Controlla l'header retry-after. |
500 Internal Server Error | Errore transitorio del server. Ripeti con backoff. |
Consapevolezza del limite di frequenza
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}`);
Vedi Limiti di frequenza per le strategie di backoff.
Passaggi successivi
- Flusso di autenticazione — ciclo di vita completo del token, PAT e archiviazione sicura
- Guida rapida curl — stesso flusso utilizzando la riga di comando
- Guida rapida Python — stesso flusso utilizzando Python
- Limiti di frequenza — comprendi gli header
x-ratelimit-*