@vxil/sdk 0.24.1 → 0.26.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.
- package/dist/index.d.ts +393 -42
- package/dist/index.js +299 -32
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -92,6 +92,14 @@ const B64URL = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_
|
|
|
92
92
|
* schedules the refresh); undefined for an opaque or malformed token. No
|
|
93
93
|
* atob: the SDK also runs on React Native builds that lack it. */
|
|
94
94
|
function sessionLifetimeSeconds(token) {
|
|
95
|
+
const p = jwtPayloadUnverified(token);
|
|
96
|
+
if (p && typeof p.iat === 'number' && typeof p.exp === 'number' && p.exp > p.iat)
|
|
97
|
+
return p.exp - p.iat;
|
|
98
|
+
return undefined;
|
|
99
|
+
}
|
|
100
|
+
/** A session JWT's payload, read WITHOUT verification (display/scheduling
|
|
101
|
+
* only — the edge verifies); undefined for an opaque or malformed token. */
|
|
102
|
+
function jwtPayloadUnverified(token) {
|
|
95
103
|
const parts = token.split('.');
|
|
96
104
|
if (parts.length !== 3 || !parts[1] || parts[1].length > 8192)
|
|
97
105
|
return undefined;
|
|
@@ -110,13 +118,41 @@ function sessionLifetimeSeconds(token) {
|
|
|
110
118
|
}
|
|
111
119
|
}
|
|
112
120
|
try {
|
|
121
|
+
// byte-per-char decode: the claims read here (iat/exp/org) are ASCII
|
|
113
122
|
const p = JSON.parse(json);
|
|
114
|
-
if (
|
|
115
|
-
return p
|
|
123
|
+
if (p && typeof p === 'object' && !Array.isArray(p))
|
|
124
|
+
return p;
|
|
116
125
|
}
|
|
117
126
|
catch { /* not a JWT payload */ }
|
|
118
127
|
return undefined;
|
|
119
128
|
}
|
|
129
|
+
function sessionOrgOf(token) {
|
|
130
|
+
const org = token ? jwtPayloadUnverified(token)?.org : undefined;
|
|
131
|
+
if (!org || typeof org !== 'object')
|
|
132
|
+
return null;
|
|
133
|
+
const o = org;
|
|
134
|
+
if (typeof o.id !== 'string' || typeof o.role !== 'string')
|
|
135
|
+
return null;
|
|
136
|
+
return {
|
|
137
|
+
id: o.id, role: o.role,
|
|
138
|
+
perms: Array.isArray(o.perms) ? o.perms.filter((x) => typeof x === 'string') : [],
|
|
139
|
+
};
|
|
140
|
+
}
|
|
141
|
+
/** The query members for a PaymentsSubject (insertion order = wire order). */
|
|
142
|
+
function paymentsSubjectQuery(s) {
|
|
143
|
+
if (typeof s === 'string')
|
|
144
|
+
return { user_id: s };
|
|
145
|
+
if ('org_id' in s)
|
|
146
|
+
return { org_id: s.org_id };
|
|
147
|
+
if ('subject' in s)
|
|
148
|
+
return { subject: s.subject };
|
|
149
|
+
return { user_id: s.user_id };
|
|
150
|
+
}
|
|
151
|
+
/** `k=v&…` (no leading `?`) for a PaymentsSubject — a string subject is
|
|
152
|
+
* byte-identical to the old `user_id=${encodeURIComponent(id)}`. */
|
|
153
|
+
function paymentsSubjectPairs(s) {
|
|
154
|
+
return Object.entries(paymentsSubjectQuery(s)).map(([k, v]) => `${k}=${encodeURIComponent(v)}`).join('&');
|
|
155
|
+
}
|
|
120
156
|
const DEFAULT_BASE = 'https://api.vxil.com';
|
|
121
157
|
/** Normalize the `expand` option to the `$expand` query value: a comma-joined
|
|
122
158
|
* list (the server's spelling), or `undefined` when nothing is expanded so the
|
|
@@ -225,6 +261,10 @@ export class Vxil {
|
|
|
225
261
|
/** The end-user session token threaded as `X-Vxil-End-User` when set (end-user
|
|
226
262
|
* mode). Undefined ⇒ no header ⇒ server-caller mode (unchanged). */
|
|
227
263
|
endUserToken;
|
|
264
|
+
/** The end-user session pair (`endUserSession`), when the client holds one:
|
|
265
|
+
* replaced in place by a `session_stale` recovery or `switchOrg`. */
|
|
266
|
+
endUserPair;
|
|
267
|
+
onSessionChange;
|
|
228
268
|
/** The ONE path every request takes: retry + timeout + hooks around
|
|
229
269
|
* `fetchImpl`. With none of the three configured it is a single fetch. */
|
|
230
270
|
transport;
|
|
@@ -237,7 +277,9 @@ export class Vxil {
|
|
|
237
277
|
this.fetchImpl = opts.fetch ?? fetch;
|
|
238
278
|
this.apiVersion = opts.apiVersion ?? 'v1';
|
|
239
279
|
this.apiVersions = opts.apiVersions ?? {};
|
|
240
|
-
this.
|
|
280
|
+
this.endUserPair = opts.endUserSession?.token ? { ...opts.endUserSession } : undefined;
|
|
281
|
+
this.endUserToken = this.endUserPair?.token ?? opts.endUserToken;
|
|
282
|
+
this.onSessionChange = opts.onSessionChange;
|
|
241
283
|
this.retryOpts = opts.retry;
|
|
242
284
|
this.timeoutMs = opts.timeoutMs;
|
|
243
285
|
this.hooks = opts.hooks;
|
|
@@ -260,8 +302,15 @@ export class Vxil {
|
|
|
260
302
|
* client, mirroring how the edge threads the verified principal. The base
|
|
261
303
|
* URL, api key, fetch impl, version pins and the retry/timeout/hooks options
|
|
262
304
|
* are inherited unchanged; only the end-user token is (re)set. Pass a falsy token to get back a server-mode
|
|
263
|
-
* client (drops the header).
|
|
264
|
-
|
|
305
|
+
* client (drops the header). Pass the whole session PAIR (`AuthSession`)
|
|
306
|
+
* instead of the bare token to let the client recover from
|
|
307
|
+
* `401 session_stale` and `switchOrg` on its own (see `endUserSession`);
|
|
308
|
+
* `opts.onSessionChange` then receives each pair it rotates (default: this
|
|
309
|
+
* client's own). See https://vxil.com/docs/guide/09-security-and-multitenancy. */
|
|
310
|
+
asEndUser(endUser, opts = {}) {
|
|
311
|
+
const pair = endUser && typeof endUser === 'object' ? endUser : undefined;
|
|
312
|
+
const endUserToken = pair ? pair.token : endUser;
|
|
313
|
+
const onSessionChange = opts.onSessionChange ?? this.onSessionChange;
|
|
265
314
|
return new Vxil({
|
|
266
315
|
apiKey: this.key,
|
|
267
316
|
baseUrl: this.base,
|
|
@@ -272,8 +321,76 @@ export class Vxil {
|
|
|
272
321
|
...(this.timeoutMs !== undefined ? { timeoutMs: this.timeoutMs } : {}),
|
|
273
322
|
...(this.hooks ? { hooks: this.hooks } : {}),
|
|
274
323
|
...(endUserToken ? { endUserToken } : {}),
|
|
324
|
+
...(pair?.token ? { endUserSession: pair } : {}),
|
|
325
|
+
...(onSessionChange ? { onSessionChange } : {}),
|
|
275
326
|
});
|
|
276
327
|
}
|
|
328
|
+
/** Adopt a rotated end-user pair when it replaces the one this client sends
|
|
329
|
+
* (a no-op for a pair this client does not hold), then tell the app. */
|
|
330
|
+
async adoptSession(old, fresh, info) {
|
|
331
|
+
if (this.endUserToken !== old.token || fresh.token === old.token)
|
|
332
|
+
return;
|
|
333
|
+
this.endUserToken = fresh.token;
|
|
334
|
+
this.endUserPair = { ...fresh };
|
|
335
|
+
await this.onSessionChange?.(fresh, info);
|
|
336
|
+
}
|
|
337
|
+
/** The edge answered `401 session_stale` — force ONE
|
|
338
|
+
* rotation of the held pair (no near-expiry check; the stale token stays on
|
|
339
|
+
* the request, which the edge admits on the refresh route only). Concurrent
|
|
340
|
+
* stale requests share the rotation through the process-wide cache.
|
|
341
|
+
* false = nothing to rotate with (no pair held) or the rotation failed. */
|
|
342
|
+
async recoverStale() {
|
|
343
|
+
const pair = this.endUserPair;
|
|
344
|
+
if (!pair?.refresh_token || this.endUserToken !== pair.token)
|
|
345
|
+
return false;
|
|
346
|
+
const now = Date.now();
|
|
347
|
+
const key = `${this.base}\n${pair.refresh_token}`;
|
|
348
|
+
let info = { reason: 'session_stale' };
|
|
349
|
+
let entry = refreshRotations.get(key);
|
|
350
|
+
if (!entry || entry.until <= now) {
|
|
351
|
+
sweepRefreshCaches(now);
|
|
352
|
+
const fresh = {
|
|
353
|
+
session: this.call('POST', '/v1/auth/sessions/refresh', { refresh_token: pair.refresh_token }, {}, false).then((r) => {
|
|
354
|
+
info = {
|
|
355
|
+
reason: 'session_stale',
|
|
356
|
+
...(r.data.org !== undefined ? { org: r.data.org } : {}),
|
|
357
|
+
...(r.data.org_unavailable === true ? { org_unavailable: true } : {}),
|
|
358
|
+
};
|
|
359
|
+
return r.data.session;
|
|
360
|
+
}),
|
|
361
|
+
until: Number.POSITIVE_INFINITY,
|
|
362
|
+
};
|
|
363
|
+
fresh.session.then((s) => {
|
|
364
|
+
fresh.until = Date.now() + ENSURE_FRESH_GRACE_MS;
|
|
365
|
+
if (s.refresh_token)
|
|
366
|
+
refreshJustMinted.set(`${this.base}\n${s.refresh_token}`, fresh.until);
|
|
367
|
+
}, () => { if (refreshRotations.get(key) === fresh)
|
|
368
|
+
refreshRotations.delete(key); });
|
|
369
|
+
refreshRotations.set(key, fresh);
|
|
370
|
+
entry = fresh;
|
|
371
|
+
}
|
|
372
|
+
let session;
|
|
373
|
+
try {
|
|
374
|
+
session = await entry.session;
|
|
375
|
+
}
|
|
376
|
+
catch {
|
|
377
|
+
return false;
|
|
378
|
+
}
|
|
379
|
+
await this.adoptSession(pair, session, info);
|
|
380
|
+
return this.endUserToken === session.token;
|
|
381
|
+
}
|
|
382
|
+
/** The session_stale test: ONLY the edge's own 401 envelope (a feature never
|
|
383
|
+
* answers this code at top level). */
|
|
384
|
+
static isSessionStale(status, text) {
|
|
385
|
+
if (status !== 401 || !text.includes('session_stale'))
|
|
386
|
+
return false;
|
|
387
|
+
try {
|
|
388
|
+
return JSON.parse(text).error?.code === 'session_stale';
|
|
389
|
+
}
|
|
390
|
+
catch {
|
|
391
|
+
return false;
|
|
392
|
+
}
|
|
393
|
+
}
|
|
277
394
|
/** Build the versioned request path — the ONE place a wire path is finalized.
|
|
278
395
|
* Every request (call(), audit.export, the fn proxy) routes through here, so
|
|
279
396
|
* the per-feature/global major pin applies uniformly. Default → unchanged
|
|
@@ -348,7 +465,7 @@ export class Vxil {
|
|
|
348
465
|
// envelope), so bypass call()'s unwrap — read the body directly, like
|
|
349
466
|
// audit.export. Errors still surface as VxilError.
|
|
350
467
|
return async (payload, opts) => {
|
|
351
|
-
const
|
|
468
|
+
const send = () => this.transport.send(`${this.base}${this.path(`/v1/fn/${encodeURIComponent(prop)}`)}`, {
|
|
352
469
|
method: 'POST',
|
|
353
470
|
headers: {
|
|
354
471
|
authorization: `Bearer ${this.key}`, ...this.authHeaders(), 'content-type': 'application/json',
|
|
@@ -358,6 +475,13 @@ export class Vxil {
|
|
|
358
475
|
},
|
|
359
476
|
body: JSON.stringify(payload ?? {}),
|
|
360
477
|
});
|
|
478
|
+
let { response: res, text } = await send();
|
|
479
|
+
// session_stale: rotate the held pair once (the next call works);
|
|
480
|
+
// re-invoke only with an idempotencyKey — a function's own error
|
|
481
|
+
// body could relay the code after it already ran side effects.
|
|
482
|
+
if (Vxil.isSessionStale(res.status, text) && await this.recoverStale() && opts?.idempotencyKey) {
|
|
483
|
+
({ response: res, text } = await send());
|
|
484
|
+
}
|
|
361
485
|
if (!res.ok) {
|
|
362
486
|
// A function answers its OWN error body: the platform envelope
|
|
363
487
|
// `{ error: { code, message } }`, or a bare string code
|
|
@@ -397,8 +521,10 @@ export class Vxil {
|
|
|
397
521
|
};
|
|
398
522
|
},
|
|
399
523
|
});
|
|
400
|
-
async call(method, path, body, headers = {}
|
|
401
|
-
|
|
524
|
+
async call(method, path, body, headers = {},
|
|
525
|
+
/** false on the recovery refresh itself (no recursion). */
|
|
526
|
+
staleRetry = true) {
|
|
527
|
+
const send = () => this.transport.send(`${this.base}${this.path(path)}`, {
|
|
402
528
|
method,
|
|
403
529
|
headers: {
|
|
404
530
|
authorization: `Bearer ${this.key}`,
|
|
@@ -408,6 +534,13 @@ export class Vxil {
|
|
|
408
534
|
},
|
|
409
535
|
...(body !== undefined ? { body: JSON.stringify(body) } : {}),
|
|
410
536
|
});
|
|
537
|
+
let { response: res, text } = await send();
|
|
538
|
+
// session_stale: the edge refused BEFORE dispatch, so re-sending is
|
|
539
|
+
// safe for any method. ONE forced refresh, ONE retry; a second
|
|
540
|
+
// session_stale (or no pair to rotate) surfaces to the app.
|
|
541
|
+
if (staleRetry && Vxil.isSessionStale(res.status, text) && await this.recoverStale()) {
|
|
542
|
+
({ response: res, text } = await send());
|
|
543
|
+
}
|
|
411
544
|
// An empty body on a 2xx is a valid "no content" success (e.g. 204 from
|
|
412
545
|
// DELETE/markRead) — never an error. Only parse when there are bytes; a
|
|
413
546
|
// void-returning caller ignores `data` anyway.
|
|
@@ -985,6 +1118,18 @@ export class Vxil {
|
|
|
985
1118
|
* sessions only, own devices only, erase self only. `auth:write` still
|
|
986
1119
|
* satisfies every call. */
|
|
987
1120
|
auth = {
|
|
1121
|
+
/** The end-user session this client sends (end-user mode), read from its
|
|
1122
|
+
* token WITHOUT verification — for display (the workspace switcher), not
|
|
1123
|
+
* for authorization (the edge verifies). */
|
|
1124
|
+
session: ((vx) => ({
|
|
1125
|
+
/** The org the session acts in (its `org` claim, auth `orgClaims`), or
|
|
1126
|
+
* null: server mode, no membership, the user left the stored org, or
|
|
1127
|
+
* orgs was unreachable at the last refresh. Updates after `switchOrg`
|
|
1128
|
+
* and a `session_stale` recovery. */
|
|
1129
|
+
get org() { return sessionOrgOf(vx.endUserToken); },
|
|
1130
|
+
/** The pair the client holds (`endUserSession`), after any rotation. */
|
|
1131
|
+
get current() { return vx.endUserPair ? { ...vx.endUserPair } : null; },
|
|
1132
|
+
}))(this),
|
|
988
1133
|
signUp: async (input) => (await this.call('POST', '/v1/auth/sign-up', input)).data,
|
|
989
1134
|
signIn: async (input) => (await this.call('POST', '/v1/auth/sign-in', input)).data,
|
|
990
1135
|
/** Magic-link sign-in: vxil mails a single-use link to the address and the
|
|
@@ -1108,8 +1253,15 @@ export class Vxil {
|
|
|
1108
1253
|
* (e.g. a rehearsal dev backend) is `skipped` / `id_taken`. `oidc_issuer` links each id as that
|
|
1109
1254
|
* issuer's subject, so an installed app can trade its old session token
|
|
1110
1255
|
* for a vxil one (`auth.oauth.native('oidc', …)`). One result per id:
|
|
1111
|
-
* `created` / `updated` / `kept` / `skipped` + `reason`. `
|
|
1112
|
-
*
|
|
1256
|
+
* `created` / `updated` / `kept` / `skipped` + `reason`. `identities`
|
|
1257
|
+
* (≤ 8 per user: google / apple / github / facebook + the provider's
|
|
1258
|
+
* subject — Supabase `auth.identities.provider_id`) seeds the social
|
|
1259
|
+
* sign-in links, so the first Google / Apple sign-in after the move lands
|
|
1260
|
+
* on the same user (Apple Hide-My-Email included); like `oidc_issuer`,
|
|
1261
|
+
* only for identities the import creates or still holds, and a subject
|
|
1262
|
+
* already linked stays where it is (`identities_linked` counts the new
|
|
1263
|
+
* ones). `vxil migrate data --with-password-hashes` /
|
|
1264
|
+
* `--with-oauth-identities` drives this for you. */
|
|
1113
1265
|
import: async (input) => (await this.call('POST', '/v1/auth/users/import', input)).data,
|
|
1114
1266
|
/** END-USER MODE ONLY (`endUserToken` / `asEndUser`): the signed-in user
|
|
1115
1267
|
* deep-merges a bounded `attributes` object into its OWN shared identity
|
|
@@ -1188,6 +1340,36 @@ export class Vxil {
|
|
|
1188
1340
|
refreshRotations.set(key, entry);
|
|
1189
1341
|
return { session: await entry.session, refreshed: true };
|
|
1190
1342
|
},
|
|
1343
|
+
/** Workspaces (auth `orgClaims.activeOrg`): make `orgId` the org the
|
|
1344
|
+
* session acts in — a refresh with `org_id`, so the NEW pair carries that
|
|
1345
|
+
* org's claim and later refreshes keep it. `pair` defaults to the pair
|
|
1346
|
+
* this client holds (`endUserSession` / `asEndUser(pair)`); a client
|
|
1347
|
+
* sending that pair's token switches to the new one in place and calls
|
|
1348
|
+
* `onSessionChange`. Store the returned `session` (the old refresh token
|
|
1349
|
+
* is revoked). The user must be a member: 403 `not_a_member`, and
|
|
1350
|
+
* 503 `orgs_unavailable`, leave the session untouched. List the
|
|
1351
|
+
* choices with `vx.orgs.list()`. Needs `@vxil/sdk` 0.25.0 or later on
|
|
1352
|
+
* the client for the `session_stale` recovery that goes with it. */
|
|
1353
|
+
switchOrg: async (orgId, pair) => {
|
|
1354
|
+
const p = pair ?? this.endUserPair;
|
|
1355
|
+
if (!p?.refresh_token) {
|
|
1356
|
+
throw new VxilError(0, 'refresh_token_missing', 'switchOrg: no session pair to rotate.', 'Pass the pair (token + refresh_token) as the second argument, or build the client with endUserSession.');
|
|
1357
|
+
}
|
|
1358
|
+
const expMs = Date.parse(p.expires_at);
|
|
1359
|
+
const keepEndUser = this.endUserToken !== undefined && this.endUserToken === p.token
|
|
1360
|
+
&& Number.isFinite(expMs) && expMs - Date.now() >= ENSURE_FRESH_HEADER_MARGIN_MS;
|
|
1361
|
+
const client = this.endUserToken && !keepEndUser ? this.asEndUser(undefined) : this;
|
|
1362
|
+
const r = (await client.call('POST', '/v1/auth/sessions/refresh', { refresh_token: p.refresh_token, org_id: orgId })).data;
|
|
1363
|
+
// the old pair is revoked: a concurrent ensureFresh / stale recovery
|
|
1364
|
+
// still carrying it adopts this pair instead of re-sending it
|
|
1365
|
+
const until = Date.now() + ENSURE_FRESH_GRACE_MS;
|
|
1366
|
+
refreshRotations.set(`${this.base}\n${p.refresh_token}`, { session: Promise.resolve(r.session), until });
|
|
1367
|
+
if (r.session.refresh_token)
|
|
1368
|
+
refreshJustMinted.set(`${this.base}\n${r.session.refresh_token}`, until);
|
|
1369
|
+
const org = r.org ?? null;
|
|
1370
|
+
await this.adoptSession(p, r.session, { reason: 'switch_org', org });
|
|
1371
|
+
return { user_id: r.user_id, session: r.session, org };
|
|
1372
|
+
},
|
|
1191
1373
|
revoke: async (token) => {
|
|
1192
1374
|
await this.call('POST', '/v1/auth/sessions/revoke', { token });
|
|
1193
1375
|
},
|
|
@@ -1212,6 +1394,9 @@ export class Vxil {
|
|
|
1212
1394
|
list: async (userId) => (await this.call('GET', `/v1/auth/sessions?user_id=${encodeURIComponent(userId)}`)).data.sessions,
|
|
1213
1395
|
},
|
|
1214
1396
|
password: {
|
|
1397
|
+
/** Always resolves (anti-enumeration). `captcha_token` is required only
|
|
1398
|
+
* when the tenant set BOTH `security.captchaOnReset: true` and
|
|
1399
|
+
* `security.captchaSecretRef` (403 `captcha_failed`). */
|
|
1215
1400
|
requestReset: async (input) => {
|
|
1216
1401
|
await this.call('POST', '/v1/auth/password/reset/request', input);
|
|
1217
1402
|
},
|
|
@@ -1219,18 +1404,34 @@ export class Vxil {
|
|
|
1219
1404
|
confirmReset: async (input) => {
|
|
1220
1405
|
await this.call('POST', '/v1/auth/password/reset/confirm', input);
|
|
1221
1406
|
},
|
|
1407
|
+
/** Change (or set a first) password for a signed-in user. `token` is the
|
|
1408
|
+
* user's CURRENT session. An account with a password sends
|
|
1409
|
+
* `current_password` (wrong → 403 `invalid_credentials`, counts toward
|
|
1410
|
+
* `security.lockout`). An account with none yet (OTP, magic-link or social
|
|
1411
|
+
* sign-up) needs a step-up on this session in the last 300 s instead
|
|
1412
|
+
* (`stepUp.request` / `stepUp.verify`, then pass the rotated token) —
|
|
1413
|
+
* otherwise 403 `step_up_required`. Step-up needs `otp.enabled`; with
|
|
1414
|
+
* OTP off, such a user sets a first password through
|
|
1415
|
+
* `password.requestReset` (the reset email) instead. Every OTHER session is revoked
|
|
1416
|
+
* (reason `password_changed`); the presenting one keeps working. A guest
|
|
1417
|
+
* session is 409 `anonymous_user`. */
|
|
1418
|
+
change: async (input) => (await this.call('POST', '/v1/auth/password/change', input)).data,
|
|
1222
1419
|
},
|
|
1223
1420
|
/** Email verification (the flow behind auth config `emailVerification.required`,
|
|
1224
1421
|
* which makes password sign-in answer 403 `email_not_verified` until the
|
|
1225
1422
|
* address is confirmed). `request` always resolves (anti-enumeration —
|
|
1226
1423
|
* a link is mailed only to an existing, unverified user; `redirect_url`
|
|
1227
1424
|
* is your page that reads `?token=` and calls `confirm`). `confirm` is
|
|
1228
|
-
* single-use and expires after 24h.
|
|
1425
|
+
* single-use and expires after 24h. Pass the session sign-up returned as
|
|
1426
|
+
* `session_token` to keep the password: without the same user's live
|
|
1427
|
+
* session the click proves only the mailbox, so a never-verified
|
|
1428
|
+
* account's password is cleared and its sessions revoked
|
|
1429
|
+
* (`password_cleared: true` — send the user to a password reset). */
|
|
1229
1430
|
emailVerification: {
|
|
1230
1431
|
request: async (input) => {
|
|
1231
1432
|
await this.call('POST', '/v1/auth/email/verify/request', input);
|
|
1232
1433
|
},
|
|
1233
|
-
confirm: async (token) => (await this.call('POST', '/v1/auth/email/verify/confirm', { token })).data,
|
|
1434
|
+
confirm: async (token, opts) => (await this.call('POST', '/v1/auth/email/verify/confirm', opts?.session_token ? { token, session_token: opts.session_token } : { token })).data,
|
|
1234
1435
|
},
|
|
1235
1436
|
/** Social sign-in. The web flow: `startUrl` fetches the provider authorize
|
|
1236
1437
|
* URL with your key (a browser cannot follow the header-carrying 302 of
|
|
@@ -1280,7 +1481,10 @@ export class Vxil {
|
|
|
1280
1481
|
* an Apple "Hide My Email" relay address on an OTP account. Idempotent
|
|
1281
1482
|
* for an identity this user already holds; 409 `oauth_identity_linked`
|
|
1282
1483
|
* when another user holds it; 401 `invalid_session` / 409
|
|
1283
|
-
* `anonymous_user` for an unknown or guest session
|
|
1484
|
+
* `anonymous_user` for an unknown or guest session; 409
|
|
1485
|
+
* `email_unverified` (verify the address first) or `password_unproven`
|
|
1486
|
+
* (complete a password reset, or step up then `password/change`) on a
|
|
1487
|
+
* password account, unless the provider-verified address is its own. */
|
|
1284
1488
|
link: async (provider, input) => (await this.call('POST', `/v1/auth/oauth/${encodeURIComponent(provider)}/native`, { ...input, link: true })).data,
|
|
1285
1489
|
},
|
|
1286
1490
|
};
|
|
@@ -1400,6 +1604,18 @@ export class Vxil {
|
|
|
1400
1604
|
* unaffected; server keys are never affected. Audited; takes effect on
|
|
1401
1605
|
* the next write. */
|
|
1402
1606
|
setWriteRoles: async (collection, roles) => (await this.call('POST', `/v1/cms/collections/${encodeURIComponent(collection)}/fields`, { write_roles: roles ?? [] })).data,
|
|
1607
|
+
/** Set (or clear, with `null`) the collection's WORKSPACE field (guide
|
|
1608
|
+
* ch. 4, "Workspace-scoped collections"): a `string` field on an index
|
|
1609
|
+
* slot (s1–s4) holding the orgs org id. A verified end user then reads and
|
|
1610
|
+
* writes only rows of the session's ACTIVE org, and `writeRoles` match the
|
|
1611
|
+
* active-org role. Server keys are never affected. Changing or clearing a
|
|
1612
|
+
* set one needs `{ allowDestructive: true }` (422 destructive_change_requires_ack). */
|
|
1613
|
+
setOrgField: async (collection, orgField, opts) => (await this.call('POST', `/v1/cms/collections/${encodeURIComponent(collection)}/fields`, { org_field: orgField, ...(opts?.allowDestructive ? { allow_destructive: true } : {}) })).data,
|
|
1614
|
+
/** Set (or clear, with `[]` / `null`) the active-org roles one of which a
|
|
1615
|
+
* verified end user must hold to READ a workspace collection (the built-in
|
|
1616
|
+
* `owner` always passes; empty = any member). Needs an org field. Widening
|
|
1617
|
+
* (clearing or adding a role) needs `{ allowDestructive: true }`. */
|
|
1618
|
+
setOrgReadRoles: async (collection, roles, opts) => (await this.call('POST', `/v1/cms/collections/${encodeURIComponent(collection)}/fields`, { org_read_roles: roles && roles.length ? roles : null, ...(opts?.allowDestructive ? { allow_destructive: true } : {}) })).data,
|
|
1403
1619
|
/** Set (1..3650 days) or clear (`null`) the collection's RETENTION (guide
|
|
1404
1620
|
* ch. 4): the nightly platform sweep soft-deletes live items created more
|
|
1405
1621
|
* than `days` ago — bounded per project per night, no restore, purged at
|
|
@@ -1950,12 +2166,19 @@ export class Vxil {
|
|
|
1950
2166
|
const d = (await this.call('GET', `/v1/orgs${s}`)).data;
|
|
1951
2167
|
return { orgs: d.orgs, next_cursor: d.next_cursor ?? null };
|
|
1952
2168
|
},
|
|
1953
|
-
/** Every org (walks `listPage` at 500 a page), each with `member_count`.
|
|
2169
|
+
/** Every org (walks `listPage` at 500 a page), each with `member_count`.
|
|
2170
|
+
* In END-USER mode with no `user_id` it lists the SIGNED-IN user's orgs,
|
|
2171
|
+
* each with their `role` — the workspace switcher's read (the id comes
|
|
2172
|
+
* from the session token; with auth `orgClaims.activeOrg` the server
|
|
2173
|
+
* binds the list to the verified caller whatever is sent). */
|
|
1954
2174
|
list: async (q) => {
|
|
2175
|
+
const self = q?.user_id === undefined && this.endUserToken
|
|
2176
|
+
? jwtPayloadUnverified(this.endUserToken)?.sub : undefined;
|
|
2177
|
+
const userId = q?.user_id ?? (typeof self === 'string' && self ? self : undefined);
|
|
1955
2178
|
const out = [];
|
|
1956
2179
|
let cursor = null;
|
|
1957
2180
|
do {
|
|
1958
|
-
const page = await this.orgs.listPage({ user_id:
|
|
2181
|
+
const page = await this.orgs.listPage({ user_id: userId, limit: 500, cursor });
|
|
1959
2182
|
out.push(...page.orgs);
|
|
1960
2183
|
cursor = page.next_cursor;
|
|
1961
2184
|
} while (cursor);
|
|
@@ -1972,11 +2195,14 @@ export class Vxil {
|
|
|
1972
2195
|
const s = qs({ user_id: userId, permission, resource: opts?.resource || undefined });
|
|
1973
2196
|
return (await this.call('GET', `/v1/orgs/${encodeURIComponent(orgId)}/check${s}`)).data;
|
|
1974
2197
|
},
|
|
1975
|
-
/** The
|
|
1976
|
-
*
|
|
2198
|
+
/** The org snapshot auth embeds in session JWTs when the tenant enables
|
|
2199
|
+
* auth config `orgClaims`: the most recent membership by joined_at — or,
|
|
2200
|
+
* with `orgClaims.activeOrg`, the org the session picked (first sign-in
|
|
2201
|
+
* stores the most recent; `vx.auth.sessions.switchOrg` changes it).
|
|
1977
2202
|
* EVENTUAL-CONSISTENT for JWTs (recomputed at refresh); use `check` for
|
|
1978
|
-
* revocation-grade authz. No membership → org_id null.
|
|
1979
|
-
|
|
2203
|
+
* revocation-grade authz. No membership → org_id null. `opts.orgId`
|
|
2204
|
+
* resolves that org's claim instead (null when not a member). */
|
|
2205
|
+
sessionClaims: async (userId, opts) => (await this.call('GET', `/v1/orgs/session-claims?user_id=${encodeURIComponent(userId)}${opts?.orgId ? `&org_id=${encodeURIComponent(opts.orgId)}` : ''}`)).data,
|
|
1980
2206
|
/** Read one workspace (incl. `settings`). */
|
|
1981
2207
|
get: async (orgId) => (await this.call('GET', `/v1/orgs/${encodeURIComponent(orgId)}`)).data,
|
|
1982
2208
|
/** Update a workspace's name / `settings` JSON. */
|
|
@@ -1992,9 +2218,18 @@ export class Vxil {
|
|
|
1992
2218
|
},
|
|
1993
2219
|
},
|
|
1994
2220
|
invitations: {
|
|
1995
|
-
/** invite_token is returned ONCE — your app builds the accept URL.
|
|
1996
|
-
|
|
1997
|
-
|
|
2221
|
+
/** invite_token is returned ONCE — your app builds the accept URL.
|
|
2222
|
+
* `role`: admin | member | viewer, or a custom role_key defined with
|
|
2223
|
+
* `roles.define` (never owner). Pass `email: null` for a LINK invite —
|
|
2224
|
+
* no email is sent and any signed-in user holding the token may accept. */
|
|
2225
|
+
create: async (orgId, email, role) => (await this.call('POST', `/v1/orgs/${encodeURIComponent(orgId)}/invitations`, email === null ? { role } : { email, role })).data,
|
|
2226
|
+
/** Redeem a token. With an end-user session the signed-in user is seated
|
|
2227
|
+
* (omit `userId`) and an email invite needs that user's VERIFIED email to
|
|
2228
|
+
* match (403 `invitation_email_mismatch`); a server key passes `userId`. */
|
|
2229
|
+
accept: async (token, userId) => (await this.call('POST', '/v1/orgs/invitations/accept', userId === undefined ? { token } : { token, user_id: userId })).data,
|
|
2230
|
+
/** Server key only: one address's PENDING invitations across your orgs
|
|
2231
|
+
* (newest first, at most 100; never the token). */
|
|
2232
|
+
pendingForEmail: async (email) => (await this.call('GET', `/v1/orgs/invitations?email=${encodeURIComponent(email)}`)).data.invitations,
|
|
1998
2233
|
revoke: async (inviteId) => {
|
|
1999
2234
|
await this.call('DELETE', `/v1/orgs/invitations/${encodeURIComponent(inviteId)}`);
|
|
2000
2235
|
},
|
|
@@ -2078,7 +2313,11 @@ export class Vxil {
|
|
|
2078
2313
|
* on the PUT) and kept with the upload: `complete` compares it with the
|
|
2079
2314
|
* SHA-256 the store reports for the bytes — 409 `checksum_mismatch` when
|
|
2080
2315
|
* they differ, 409 `checksum_unverified` when the store reports none —
|
|
2081
|
-
* and on success answers the verified `checksum_sha256`.
|
|
2316
|
+
* and on success answers the verified `checksum_sha256`.
|
|
2317
|
+
* Workspace files: `org: true` (end-user mode) makes the
|
|
2318
|
+
* session's ACTIVE org own the object — every member of that org can
|
|
2319
|
+
* list (`list({ scope: 'org' })`) and read it, it survives the uploader's
|
|
2320
|
+
* erasure, and deleting the org removes it. A server key names `org_id`. */
|
|
2082
2321
|
createUploadUrl: async (input) => (await this.call('POST', '/v1/files/upload-url', input)).data,
|
|
2083
2322
|
/** Confirm the PUT (bytes verified, object → available). Answers the
|
|
2084
2323
|
* object's `expires_at` (null = never) and `checksum_sha256` (hex; null
|
|
@@ -2087,7 +2326,23 @@ export class Vxil {
|
|
|
2087
2326
|
* the bytes hash differently, 409 `checksum_unverified` if the store
|
|
2088
2327
|
* reports no checksum (the object stays pending either way). */
|
|
2089
2328
|
complete: async (objectId) => (await this.call('POST', `/v1/files/${encodeURIComponent(objectId)}/complete`)).data,
|
|
2090
|
-
|
|
2329
|
+
/** Mint a short-lived presigned GET. Options:
|
|
2330
|
+
* `disposition: 'inline'` opens a PDF (or an image, ICO, audio/video) in
|
|
2331
|
+
* the browser instead of downloading it — html/svg/js and every other
|
|
2332
|
+
* type stay attachments whatever you ask; `'attachment'` forces a
|
|
2333
|
+
* download; omitted = raster images inline, everything else attachment.
|
|
2334
|
+
* `filename` sets the name the browser saves (sanitised server-side:
|
|
2335
|
+
* control/bidi characters dropped, `/` → `_`, ≤ 200 characters; sent as
|
|
2336
|
+
* RFC 6266 `filename*`), default the upload's filename. */
|
|
2337
|
+
downloadUrl: async (objectId, opts = {}) => {
|
|
2338
|
+
const q = [];
|
|
2339
|
+
if (opts.disposition !== undefined)
|
|
2340
|
+
q.push(`disposition=${encodeURIComponent(opts.disposition)}`);
|
|
2341
|
+
if (opts.filename !== undefined)
|
|
2342
|
+
q.push(`filename=${encodeURIComponent(opts.filename)}`);
|
|
2343
|
+
const qs = q.join('&');
|
|
2344
|
+
return (await this.call('GET', `/v1/files/${encodeURIComponent(objectId)}/download-url${qs ? `?${qs}` : ''}`)).data.download_url;
|
|
2345
|
+
},
|
|
2091
2346
|
/** Mint up to 100 presigned GETs in ONE call (`GET /v1/files/download-urls`)
|
|
2092
2347
|
* — a gallery page costs one request, not one per image. `urls[]` keeps
|
|
2093
2348
|
* your order (duplicates collapse); an id that is unknown, someone else's
|
|
@@ -2096,9 +2351,14 @@ export class Vxil {
|
|
|
2096
2351
|
* `inline`. For expo-image, cache on the object id, not the URL:
|
|
2097
2352
|
* `<Image source={{ uri: u.download_url, cacheKey: u.object_id }} />`. */
|
|
2098
2353
|
downloadUrls: async (objectIds) => (await this.call('GET', `/v1/files/download-urls?object_ids=${encodeURIComponent(objectIds.join(','))}`)).data,
|
|
2354
|
+
/** List objects. End-user mode: your PERSONAL files, or `scope: 'org'`
|
|
2355
|
+
* for the active org's WORKSPACE files (403 `org_required` without an
|
|
2356
|
+
* active org). Server key: `user_id` / `org_id` filters. */
|
|
2099
2357
|
list: async (q) => {
|
|
2100
2358
|
const s = qs({
|
|
2101
2359
|
user_id: q?.user_id || undefined,
|
|
2360
|
+
scope: q?.scope || undefined,
|
|
2361
|
+
org_id: q?.org_id || undefined,
|
|
2102
2362
|
cursor: q?.cursor || undefined,
|
|
2103
2363
|
limit: q?.limit || undefined,
|
|
2104
2364
|
});
|
|
@@ -2454,10 +2714,13 @@ export class Vxil {
|
|
|
2454
2714
|
* higher tier's earlier end; access does not dip (a lapsed winner re-folds
|
|
2455
2715
|
* on read and the lower tier takes over), but a client that CACHES `until`
|
|
2456
2716
|
* will show an early expiry — re-read instead of trusting a cached value
|
|
2457
|
-
* past it.
|
|
2717
|
+
* past it.
|
|
2718
|
+
*
|
|
2719
|
+
* WORKSPACE BILLING: pass `{ org_id }` (server) or `{ subject: 'org' }`
|
|
2720
|
+
* (thin client, the active workspace) for a workspace's entitlements. */
|
|
2458
2721
|
getEntitlements: async (userId, opts) => {
|
|
2459
2722
|
const s = qs({
|
|
2460
|
-
|
|
2723
|
+
...paymentsSubjectQuery(userId),
|
|
2461
2724
|
quota: opts?.quota || undefined,
|
|
2462
2725
|
credit_type: opts?.creditType || undefined,
|
|
2463
2726
|
});
|
|
@@ -2465,8 +2728,9 @@ export class Vxil {
|
|
|
2465
2728
|
},
|
|
2466
2729
|
/** Boolean gate: does the user hold `entitlement`? Returns granted + its
|
|
2467
2730
|
* source (subscription/tier) + the resolved tier, plus `until` (how long
|
|
2468
|
-
* the answer is good for) and `as_of`. Non-2xx = unknown, never free.
|
|
2469
|
-
|
|
2731
|
+
* the answer is good for) and `as_of`. Non-2xx = unknown, never free.
|
|
2732
|
+
* `{ org_id }` / `{ subject: 'org' }` check a workspace (PaymentsSubject). */
|
|
2733
|
+
hasEntitlement: async (userId, entitlement) => (await this.call('GET', `/v1/payments/entitlements/check?${paymentsSubjectPairs(userId)}&entitlement=${encodeURIComponent(entitlement)}`)).data,
|
|
2470
2734
|
/** A single numeric quota for the user (e.g. `seats`, `api_calls`); null when
|
|
2471
2735
|
* the resolved tier declares no such quota. Convenience over getEntitlements. */
|
|
2472
2736
|
getQuota: async (userId, quota) => {
|
|
@@ -2475,8 +2739,9 @@ export class Vxil {
|
|
|
2475
2739
|
return typeof v === 'number' ? v : null;
|
|
2476
2740
|
},
|
|
2477
2741
|
/** The credit balance for a credit type: balance/held/available (= balance −
|
|
2478
|
-
* held) + the current period_end.
|
|
2479
|
-
|
|
2742
|
+
* held) + the current period_end. `{ org_id }` / `{ subject: 'org' }`
|
|
2743
|
+
* read a workspace's balance (PaymentsSubject). */
|
|
2744
|
+
getBalance: async (userId, creditType) => (await this.call('GET', `/v1/payments/credits/balance?${paymentsSubjectPairs(userId)}&credit_type=${encodeURIComponent(creditType)}`)).data,
|
|
2480
2745
|
/**
|
|
2481
2746
|
* Debit credits — idempotent (Idempotency-Key REQUIRED) + balance-guarded
|
|
2482
2747
|
* (no oversell). Pass `job_id` to make the debit PROVISIONAL (held, not yet
|
|
@@ -2520,10 +2785,12 @@ export class Vxil {
|
|
|
2520
2785
|
* not just retries). A repeat with the same key → granted:false. */
|
|
2521
2786
|
grantOnce: async (input) => (await this.call('POST', '/v1/payments/credits/grant-once', input)).data,
|
|
2522
2787
|
/** Recent ledger rows for the user (the audit/trail surface), newest first;
|
|
2523
|
-
* optionally scoped to one credit type.
|
|
2788
|
+
* optionally scoped to one credit type. `org_id` (SERVER key only) reads a
|
|
2789
|
+
* workspace's rows instead — the workspace trail lists every member's
|
|
2790
|
+
* consumes, so a thin client gets 403 org_usage_server_only. */
|
|
2524
2791
|
usage: async (q) => {
|
|
2525
2792
|
const s = qs({
|
|
2526
|
-
|
|
2793
|
+
...paymentsSubjectQuery(q),
|
|
2527
2794
|
credit_type: q.credit_type || undefined,
|
|
2528
2795
|
limit: q.limit || undefined,
|
|
2529
2796
|
});
|
package/package.json
CHANGED