@vibase/sdk 0.0.0-stage → 0.3.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/LICENSE +18 -0
- package/README.md +269 -2
- package/dist/client.d.ts +10 -0
- package/dist/client.js +171 -0
- package/dist/errors.d.ts +7 -0
- package/dist/errors.js +14 -0
- package/dist/filters.d.ts +34 -0
- package/dist/filters.js +53 -0
- package/dist/generated/operations.d.ts +3 -0
- package/dist/generated/operations.js +5385 -0
- package/dist/generated/types.d.ts +10451 -0
- package/dist/generated/types.js +1 -0
- package/dist/index.d.ts +9 -0
- package/dist/index.js +4 -0
- package/dist/session.d.ts +12 -0
- package/dist/session.js +42 -0
- package/dist/sign-in.d.ts +57 -0
- package/dist/sign-in.js +386 -0
- package/dist/types.d.ts +94 -0
- package/dist/types.js +1 -0
- package/dist/typing.d.ts +119 -0
- package/dist/typing.js +1 -0
- package/package.json +19 -4
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
export { createClient } from './client.js';
|
|
2
|
+
export type { Filter } from './filters.js';
|
|
3
|
+
export { sessionToken, type SessionTokenOptions } from './session.js';
|
|
4
|
+
export { isVibaseError, VibaseError } from './errors.js';
|
|
5
|
+
export type { BuiltInOperations } from './generated/types.js';
|
|
6
|
+
/** The helper types a generated workspace map is written with (DX604 D3). */
|
|
7
|
+
export type { ArgsOf, ItemOf, ResultOf, WithFilters } from './typing.js';
|
|
8
|
+
export type { ActionRequest, Auth, CallOptions, Client, ClientOptions, Method, OperationEntry, OperationMap, OperationShape, OperationTable, Proposal, } from './types.js';
|
|
9
|
+
export { browserSignIn, type BrowserSignIn, type BrowserSignInOptions, type StorageLike, } from './sign-in.js';
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
export interface SessionTokenOptions {
|
|
2
|
+
/** The deployment's URL; only its origin is used: the token is read from `<origin>/auth/token`. */
|
|
3
|
+
url: string;
|
|
4
|
+
fetch?: typeof fetch;
|
|
5
|
+
/** A cookie header to send instead of the browser's cookies (server-side use); a function is called once per token request. */
|
|
6
|
+
cookie?: string | (() => string | null | undefined | Promise<string | null | undefined>);
|
|
7
|
+
}
|
|
8
|
+
/**
|
|
9
|
+
* The credential function for a Better Auth browser session (DX608 D7, P2): exchanges the session cookie at `GET /auth/token` on every call, never cached.
|
|
10
|
+
* Resolves `null` when signed out (a 401, or a 2xx without a non-empty string `token`), so `createClient` answers `401 no_credential` without sending.
|
|
11
|
+
*/
|
|
12
|
+
export declare function sessionToken(options: SessionTokenOptions): () => Promise<string | null>;
|
package/dist/session.js
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import { failure } from './client.js';
|
|
2
|
+
import { VibaseError } from './errors.js';
|
|
3
|
+
/**
|
|
4
|
+
* The credential function for a Better Auth browser session (DX608 D7, P2): exchanges the session cookie at `GET /auth/token` on every call, never cached.
|
|
5
|
+
* Resolves `null` when signed out (a 401, or a 2xx without a non-empty string `token`), so `createClient` answers `401 no_credential` without sending.
|
|
6
|
+
*/
|
|
7
|
+
export function sessionToken(options) {
|
|
8
|
+
const endpoint = new URL('/auth/token', new URL(options.url).origin).toString();
|
|
9
|
+
const doFetch = options.fetch ?? ((input, init) => globalThis.fetch(input, init));
|
|
10
|
+
return async () => {
|
|
11
|
+
const cookie = typeof options.cookie === 'function' ? await options.cookie() : options.cookie;
|
|
12
|
+
const headers = { accept: 'application/json' };
|
|
13
|
+
if (options.cookie !== undefined && cookie)
|
|
14
|
+
headers.cookie = cookie;
|
|
15
|
+
let response;
|
|
16
|
+
try {
|
|
17
|
+
response = await doFetch(endpoint, {
|
|
18
|
+
method: 'GET',
|
|
19
|
+
headers,
|
|
20
|
+
credentials: options.cookie === undefined ? 'include' : 'omit',
|
|
21
|
+
});
|
|
22
|
+
}
|
|
23
|
+
catch (error) {
|
|
24
|
+
if (error instanceof Error && error.name === 'AbortError')
|
|
25
|
+
throw error;
|
|
26
|
+
throw new VibaseError(0, 'network_error', error instanceof Error ? error.message : String(error));
|
|
27
|
+
}
|
|
28
|
+
if (response.status === 401)
|
|
29
|
+
return null;
|
|
30
|
+
if (!response.ok)
|
|
31
|
+
throw await failure(response);
|
|
32
|
+
let body;
|
|
33
|
+
try {
|
|
34
|
+
body = await response.json();
|
|
35
|
+
}
|
|
36
|
+
catch {
|
|
37
|
+
throw new VibaseError(response.status, 'invalid_response', `The token response is not valid JSON (HTTP ${response.status})`);
|
|
38
|
+
}
|
|
39
|
+
const token = body?.token;
|
|
40
|
+
return typeof token === 'string' && token !== '' ? token : null;
|
|
41
|
+
};
|
|
42
|
+
}
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
/** What `sessionStorage` and `localStorage` offer, and all this module needs of a store. */
|
|
2
|
+
export interface StorageLike {
|
|
3
|
+
getItem(key: string): string | null;
|
|
4
|
+
setItem(key: string, value: string): void;
|
|
5
|
+
removeItem(key: string): void;
|
|
6
|
+
}
|
|
7
|
+
export interface BrowserSignInOptions {
|
|
8
|
+
/** The deployment's URL; only its origin is used. */
|
|
9
|
+
url: string;
|
|
10
|
+
/** The first-party client's id (`oauth_clients.create`). */
|
|
11
|
+
clientId: string;
|
|
12
|
+
/** A redirect URI registered on the client, on this page's origin. */
|
|
13
|
+
redirectUri: string;
|
|
14
|
+
/** Omitted: no `scope` is sent and the instance grants its default set. Given: `openid offline_access` followed by these. */
|
|
15
|
+
scopes?: string[];
|
|
16
|
+
/** Where the token record lives (default `'session'`); the pending record is always in `sessionStorage`. */
|
|
17
|
+
storage?: 'session' | 'local' | 'memory' | StorageLike;
|
|
18
|
+
fetch?: typeof fetch;
|
|
19
|
+
/** Tests: the page's address (default `globalThis.location`). */
|
|
20
|
+
location?: {
|
|
21
|
+
href: string;
|
|
22
|
+
origin: string;
|
|
23
|
+
};
|
|
24
|
+
/** Default `location.assign`. */
|
|
25
|
+
navigate?: (url: string) => void;
|
|
26
|
+
/** Default `history.replaceState`. */
|
|
27
|
+
replaceUrl?: (url: string) => void;
|
|
28
|
+
/** Tests: the `sessionStorage` to use (default `globalThis.sessionStorage`). */
|
|
29
|
+
sessionStorage?: StorageLike;
|
|
30
|
+
}
|
|
31
|
+
export interface BrowserSignIn {
|
|
32
|
+
/** Sends the browser to the deployment's authorize endpoint with a fresh PKCE pair; the promise never resolves (the page is leaving). */
|
|
33
|
+
signIn(options?: {
|
|
34
|
+
returnTo?: string;
|
|
35
|
+
}): Promise<never>;
|
|
36
|
+
/** Call on page load: finishes a sign-in when the current URL is the callback, else resolves `null`. */
|
|
37
|
+
handleRedirect(): Promise<{
|
|
38
|
+
returnTo: string;
|
|
39
|
+
} | null>;
|
|
40
|
+
/**
|
|
41
|
+
* The access token: the stored one while more than 60 s remain, else a refreshed one (single-flight). `null` when signed out, when
|
|
42
|
+
* the grant is gone (a refused refresh clears the record) or when there is nothing to refresh with; rejects when the refresh could
|
|
43
|
+
* not be asked or answered (network, 5xx, a malformed answer), keeping the record. Exactly the `auth` function `createClient` takes.
|
|
44
|
+
*/
|
|
45
|
+
token(): Promise<string | null>;
|
|
46
|
+
/** True when a token record exists. */
|
|
47
|
+
isSignedIn(): boolean;
|
|
48
|
+
/** Forgets this client's records locally; nothing is sent. */
|
|
49
|
+
signOut(): void;
|
|
50
|
+
}
|
|
51
|
+
/** The `S256` code challenge of a verifier (RFC 7636 section 4.2). */
|
|
52
|
+
export declare function pkceChallenge(verifier: string): Promise<string>;
|
|
53
|
+
/**
|
|
54
|
+
* Browser sign-in for one app (one client id, one deployment), Better Auth deployments only (DX624). The returned `token` is the
|
|
55
|
+
* credential function `createClient` accepts: `createClient({ url, auth: signIn.token })`.
|
|
56
|
+
*/
|
|
57
|
+
export declare function browserSignIn(options: BrowserSignInOptions): BrowserSignIn;
|
package/dist/sign-in.js
ADDED
|
@@ -0,0 +1,386 @@
|
|
|
1
|
+
import { VibaseError } from './errors.js';
|
|
2
|
+
const MARGIN_MS = 60_000;
|
|
3
|
+
const CALLBACK_PARAMS = ['code', 'state', 'iss', 'error', 'error_description'];
|
|
4
|
+
const text = (v) => typeof v === 'string' && v !== '';
|
|
5
|
+
const isObject = (v) => typeof v === 'object' && v !== null;
|
|
6
|
+
const base64url = (bytes) => btoa(String.fromCharCode(...bytes))
|
|
7
|
+
.replace(/\+/g, '-')
|
|
8
|
+
.replace(/\//g, '_')
|
|
9
|
+
.replace(/=+$/, '');
|
|
10
|
+
const randomBase64url = (length) => base64url(globalThis.crypto.getRandomValues(new Uint8Array(length)));
|
|
11
|
+
/** The `S256` code challenge of a verifier (RFC 7636 section 4.2). */
|
|
12
|
+
export async function pkceChallenge(verifier) {
|
|
13
|
+
const digest = await globalThis.crypto.subtle.digest('SHA-256', new TextEncoder().encode(verifier));
|
|
14
|
+
return base64url(new Uint8Array(digest));
|
|
15
|
+
}
|
|
16
|
+
/** A store that falls back to memory, for the life of the page, once the real storage throws or is absent. */
|
|
17
|
+
function guarded(get) {
|
|
18
|
+
const memory = new Map();
|
|
19
|
+
let broken = false;
|
|
20
|
+
const backing = () => {
|
|
21
|
+
if (broken)
|
|
22
|
+
return undefined;
|
|
23
|
+
try {
|
|
24
|
+
const store = get();
|
|
25
|
+
if (store)
|
|
26
|
+
return store;
|
|
27
|
+
}
|
|
28
|
+
catch {
|
|
29
|
+
/* private mode, blocked site data */
|
|
30
|
+
}
|
|
31
|
+
broken = true;
|
|
32
|
+
return undefined;
|
|
33
|
+
};
|
|
34
|
+
return {
|
|
35
|
+
getItem(key) {
|
|
36
|
+
const store = backing();
|
|
37
|
+
if (store)
|
|
38
|
+
try {
|
|
39
|
+
return store.getItem(key);
|
|
40
|
+
}
|
|
41
|
+
catch {
|
|
42
|
+
broken = true;
|
|
43
|
+
}
|
|
44
|
+
return memory.get(key) ?? null;
|
|
45
|
+
},
|
|
46
|
+
setItem(key, value) {
|
|
47
|
+
const store = backing();
|
|
48
|
+
if (store)
|
|
49
|
+
try {
|
|
50
|
+
store.setItem(key, value);
|
|
51
|
+
return;
|
|
52
|
+
}
|
|
53
|
+
catch {
|
|
54
|
+
broken = true;
|
|
55
|
+
}
|
|
56
|
+
memory.set(key, value);
|
|
57
|
+
},
|
|
58
|
+
removeItem(key) {
|
|
59
|
+
const store = backing();
|
|
60
|
+
if (store)
|
|
61
|
+
try {
|
|
62
|
+
store.removeItem(key);
|
|
63
|
+
}
|
|
64
|
+
catch {
|
|
65
|
+
broken = true;
|
|
66
|
+
}
|
|
67
|
+
memory.delete(key);
|
|
68
|
+
},
|
|
69
|
+
};
|
|
70
|
+
}
|
|
71
|
+
/**
|
|
72
|
+
* Browser sign-in for one app (one client id, one deployment), Better Auth deployments only (DX624). The returned `token` is the
|
|
73
|
+
* credential function `createClient` accepts: `createClient({ url, auth: signIn.token })`.
|
|
74
|
+
*/
|
|
75
|
+
export function browserSignIn(options) {
|
|
76
|
+
const origin = new URL(options.url).origin;
|
|
77
|
+
const keyBase = `vibase.sign-in:${origin}:${options.clientId}`;
|
|
78
|
+
const tokenKey = `${keyBase}:token`;
|
|
79
|
+
const pendingKey = `${keyBase}:pending`;
|
|
80
|
+
const doFetch = options.fetch ?? ((input, init) => globalThis.fetch(input, init));
|
|
81
|
+
const sessionStore = () => options.sessionStorage ?? globalThis.sessionStorage;
|
|
82
|
+
const pending = guarded(sessionStore);
|
|
83
|
+
const tokens = (() => {
|
|
84
|
+
const form = options.storage ?? 'session';
|
|
85
|
+
if (form === 'session')
|
|
86
|
+
return guarded(sessionStore);
|
|
87
|
+
if (form === 'local')
|
|
88
|
+
return guarded(() => globalThis.localStorage);
|
|
89
|
+
if (form === 'memory')
|
|
90
|
+
return guarded(() => undefined);
|
|
91
|
+
return guarded(() => form);
|
|
92
|
+
})();
|
|
93
|
+
const page = () => options.location ?? globalThis.location;
|
|
94
|
+
const network = (e) => new VibaseError(0, 'network_error', e instanceof Error ? e.message : String(e));
|
|
95
|
+
async function send(url, init) {
|
|
96
|
+
try {
|
|
97
|
+
return await doFetch(url, { ...init, credentials: 'omit', redirect: 'error' });
|
|
98
|
+
}
|
|
99
|
+
catch (e) {
|
|
100
|
+
throw network(e);
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
async function getJson(url) {
|
|
104
|
+
const res = await send(url, { method: 'GET', headers: { accept: 'application/json' } });
|
|
105
|
+
return { status: res.status, body: await res.json().catch(() => undefined) };
|
|
106
|
+
}
|
|
107
|
+
async function discoverOnce() {
|
|
108
|
+
const doc = await getJson(`${origin}/.well-known/vibase`);
|
|
109
|
+
if (doc.status !== 200 || !isObject(doc.body))
|
|
110
|
+
throw new VibaseError(0, 'discovery_failed', `${origin}/.well-known/vibase answered ${doc.status}`);
|
|
111
|
+
const auth = doc.body.auth;
|
|
112
|
+
if (!isObject(auth) || auth.provider !== 'better-auth')
|
|
113
|
+
throw new VibaseError(0, 'unsupported_provider', 'browser sign-in needs a Better Auth deployment');
|
|
114
|
+
if (!text(auth.issuer) || !text(auth.resource))
|
|
115
|
+
throw new VibaseError(0, 'discovery_failed', 'the discovery document names no issuer or resource');
|
|
116
|
+
let issuerUrl;
|
|
117
|
+
try {
|
|
118
|
+
issuerUrl = new URL(auth.issuer);
|
|
119
|
+
}
|
|
120
|
+
catch {
|
|
121
|
+
throw new VibaseError(0, 'discovery_failed', 'the issuer is not a URL');
|
|
122
|
+
}
|
|
123
|
+
const loopback = issuerUrl.hostname === 'localhost' || issuerUrl.hostname === '127.0.0.1';
|
|
124
|
+
if (issuerUrl.protocol !== 'https:' && !(issuerUrl.protocol === 'http:' && loopback))
|
|
125
|
+
throw new VibaseError(0, 'insecure_issuer', `the issuer ${auth.issuer} is not https`);
|
|
126
|
+
const path = issuerUrl.pathname === '/' ? '' : issuerUrl.pathname;
|
|
127
|
+
const meta = await getJson(`${issuerUrl.origin}/.well-known/oauth-authorization-server${path}`);
|
|
128
|
+
if (meta.status !== 200 || !isObject(meta.body))
|
|
129
|
+
throw new VibaseError(0, 'discovery_failed', `the authorization server metadata answered ${meta.status}`);
|
|
130
|
+
const metadata = meta.body;
|
|
131
|
+
if (metadata.issuer !== auth.issuer)
|
|
132
|
+
throw new VibaseError(0, 'issuer_mismatch', 'the metadata names another issuer');
|
|
133
|
+
const endpoint = (name) => {
|
|
134
|
+
const value = metadata[name];
|
|
135
|
+
if (!text(value))
|
|
136
|
+
throw new VibaseError(0, 'discovery_failed', `the metadata has no ${name}`);
|
|
137
|
+
let url;
|
|
138
|
+
try {
|
|
139
|
+
url = new URL(value);
|
|
140
|
+
}
|
|
141
|
+
catch {
|
|
142
|
+
throw new VibaseError(0, 'endpoint_origin', `${name} is not a URL`);
|
|
143
|
+
}
|
|
144
|
+
if (url.origin !== issuerUrl.origin)
|
|
145
|
+
throw new VibaseError(0, 'endpoint_origin', `${name} is not on the issuer's origin`);
|
|
146
|
+
return url.toString();
|
|
147
|
+
};
|
|
148
|
+
const authorizationEndpoint = endpoint('authorization_endpoint');
|
|
149
|
+
const tokenEndpoint = endpoint('token_endpoint');
|
|
150
|
+
const methods = metadata.code_challenge_methods_supported;
|
|
151
|
+
if (!Array.isArray(methods) || !methods.includes('S256'))
|
|
152
|
+
throw new VibaseError(0, 'discovery_failed', 'the authorization server does not offer S256');
|
|
153
|
+
return { issuer: auth.issuer, resource: auth.resource, authorizationEndpoint, tokenEndpoint };
|
|
154
|
+
}
|
|
155
|
+
let discovery;
|
|
156
|
+
/** Lazy, cached per sign-in object; a failure is not cached. */
|
|
157
|
+
function discover() {
|
|
158
|
+
if (discovery)
|
|
159
|
+
return discovery;
|
|
160
|
+
const attempt = discoverOnce();
|
|
161
|
+
discovery = attempt;
|
|
162
|
+
attempt.catch(() => {
|
|
163
|
+
if (discovery === attempt)
|
|
164
|
+
discovery = undefined;
|
|
165
|
+
});
|
|
166
|
+
return attempt;
|
|
167
|
+
}
|
|
168
|
+
function readToken() {
|
|
169
|
+
const raw = tokens.getItem(tokenKey);
|
|
170
|
+
if (raw === null)
|
|
171
|
+
return null;
|
|
172
|
+
try {
|
|
173
|
+
const value = JSON.parse(raw);
|
|
174
|
+
if (isObject(value) && text(value.access_token) && typeof value.expires_at === 'number')
|
|
175
|
+
return {
|
|
176
|
+
access_token: value.access_token,
|
|
177
|
+
expires_at: value.expires_at,
|
|
178
|
+
...(text(value.refresh_token) ? { refresh_token: value.refresh_token } : {}),
|
|
179
|
+
};
|
|
180
|
+
}
|
|
181
|
+
catch {
|
|
182
|
+
/* unparseable: signed out */
|
|
183
|
+
}
|
|
184
|
+
tokens.removeItem(tokenKey);
|
|
185
|
+
return null;
|
|
186
|
+
}
|
|
187
|
+
function readPending() {
|
|
188
|
+
const raw = pending.getItem(pendingKey);
|
|
189
|
+
if (raw === null)
|
|
190
|
+
return null;
|
|
191
|
+
try {
|
|
192
|
+
const value = JSON.parse(raw);
|
|
193
|
+
if (isObject(value) &&
|
|
194
|
+
text(value.state) &&
|
|
195
|
+
text(value.verifier) &&
|
|
196
|
+
text(value.redirect_uri) &&
|
|
197
|
+
typeof value.return_to === 'string')
|
|
198
|
+
return value;
|
|
199
|
+
}
|
|
200
|
+
catch {
|
|
201
|
+
/* unparseable: no pending record */
|
|
202
|
+
}
|
|
203
|
+
return null;
|
|
204
|
+
}
|
|
205
|
+
/** `returnTo` as a same-origin path + query + hash, or `invalid_return_to`. */
|
|
206
|
+
function resolveReturnTo(requested) {
|
|
207
|
+
const here = page();
|
|
208
|
+
const base = here?.href ?? options.redirectUri;
|
|
209
|
+
const hereOrigin = here?.origin ?? new URL(options.redirectUri).origin;
|
|
210
|
+
let url;
|
|
211
|
+
try {
|
|
212
|
+
url = new URL(requested ?? (here ? here.href : '/'), base);
|
|
213
|
+
}
|
|
214
|
+
catch {
|
|
215
|
+
throw new VibaseError(0, 'invalid_return_to', 'returnTo is not a URL');
|
|
216
|
+
}
|
|
217
|
+
if (url.origin !== hereOrigin)
|
|
218
|
+
throw new VibaseError(0, 'invalid_return_to', "returnTo must be on this page's origin");
|
|
219
|
+
return url.pathname + url.search + url.hash;
|
|
220
|
+
}
|
|
221
|
+
async function signIn(o = {}) {
|
|
222
|
+
const returnTo = resolveReturnTo(o.returnTo);
|
|
223
|
+
const d = await discover();
|
|
224
|
+
const verifier = randomBase64url(32);
|
|
225
|
+
const state = randomBase64url(16);
|
|
226
|
+
const challenge = await pkceChallenge(verifier);
|
|
227
|
+
const record = {
|
|
228
|
+
state,
|
|
229
|
+
verifier,
|
|
230
|
+
redirect_uri: options.redirectUri,
|
|
231
|
+
return_to: returnTo,
|
|
232
|
+
created_at: Date.now(),
|
|
233
|
+
};
|
|
234
|
+
pending.setItem(pendingKey, JSON.stringify(record));
|
|
235
|
+
const url = new URL(d.authorizationEndpoint);
|
|
236
|
+
url.searchParams.set('response_type', 'code');
|
|
237
|
+
url.searchParams.set('client_id', options.clientId);
|
|
238
|
+
url.searchParams.set('redirect_uri', options.redirectUri);
|
|
239
|
+
url.searchParams.set('code_challenge', challenge);
|
|
240
|
+
url.searchParams.set('code_challenge_method', 'S256');
|
|
241
|
+
url.searchParams.set('state', state);
|
|
242
|
+
url.searchParams.set('resource', d.resource);
|
|
243
|
+
if (options.scopes)
|
|
244
|
+
url.searchParams.set('scope', [...new Set(['openid', 'offline_access', ...options.scopes])].join(' '));
|
|
245
|
+
const go = options.navigate ?? ((u) => globalThis.location.assign(u));
|
|
246
|
+
go(url.toString());
|
|
247
|
+
return new Promise(() => { });
|
|
248
|
+
}
|
|
249
|
+
async function exchange(d, code, record) {
|
|
250
|
+
const res = await send(d.tokenEndpoint, {
|
|
251
|
+
method: 'POST',
|
|
252
|
+
headers: { 'content-type': 'application/x-www-form-urlencoded', accept: 'application/json' },
|
|
253
|
+
body: new URLSearchParams({
|
|
254
|
+
grant_type: 'authorization_code',
|
|
255
|
+
code,
|
|
256
|
+
code_verifier: record.verifier,
|
|
257
|
+
redirect_uri: record.redirect_uri,
|
|
258
|
+
client_id: options.clientId,
|
|
259
|
+
resource: d.resource,
|
|
260
|
+
}).toString(),
|
|
261
|
+
});
|
|
262
|
+
const body = await res.json().catch(() => undefined);
|
|
263
|
+
if (res.status === 200 &&
|
|
264
|
+
isObject(body) &&
|
|
265
|
+
text(body.access_token) &&
|
|
266
|
+
typeof body.expires_in === 'number' &&
|
|
267
|
+
Number.isFinite(body.expires_in)) {
|
|
268
|
+
const stored = {
|
|
269
|
+
access_token: body.access_token,
|
|
270
|
+
expires_at: Date.now() + body.expires_in * 1000,
|
|
271
|
+
...(text(body.refresh_token) ? { refresh_token: body.refresh_token } : {}),
|
|
272
|
+
};
|
|
273
|
+
tokens.setItem(tokenKey, JSON.stringify(stored));
|
|
274
|
+
return;
|
|
275
|
+
}
|
|
276
|
+
const error = isObject(body) && text(body.error) ? body.error : 'invalid_response';
|
|
277
|
+
const description = isObject(body) && text(body.error_description) ? `: ${body.error_description}` : '';
|
|
278
|
+
throw new VibaseError(res.status, error, `the token endpoint refused (${error})${description}`);
|
|
279
|
+
}
|
|
280
|
+
/** Refreshes the sign-in whose stored record was `raw`; whatever it learns is applied only while that record is still the stored one (P3). */
|
|
281
|
+
async function refresh(record, raw) {
|
|
282
|
+
const d = await discover();
|
|
283
|
+
const res = await send(d.tokenEndpoint, {
|
|
284
|
+
method: 'POST',
|
|
285
|
+
headers: { 'content-type': 'application/x-www-form-urlencoded', accept: 'application/json' },
|
|
286
|
+
body: new URLSearchParams({
|
|
287
|
+
grant_type: 'refresh_token',
|
|
288
|
+
refresh_token: record.refresh_token,
|
|
289
|
+
client_id: options.clientId,
|
|
290
|
+
resource: d.resource,
|
|
291
|
+
}).toString(),
|
|
292
|
+
});
|
|
293
|
+
const body = await res.json().catch(() => undefined);
|
|
294
|
+
const unchanged = tokens.getItem(tokenKey) === raw;
|
|
295
|
+
if (res.status === 200 &&
|
|
296
|
+
isObject(body) &&
|
|
297
|
+
text(body.access_token) &&
|
|
298
|
+
typeof body.expires_in === 'number' &&
|
|
299
|
+
Number.isFinite(body.expires_in)) {
|
|
300
|
+
if (!unchanged)
|
|
301
|
+
return null;
|
|
302
|
+
const stored = {
|
|
303
|
+
access_token: body.access_token,
|
|
304
|
+
expires_at: Date.now() + body.expires_in * 1000,
|
|
305
|
+
refresh_token: text(body.refresh_token) ? body.refresh_token : record.refresh_token,
|
|
306
|
+
};
|
|
307
|
+
tokens.setItem(tokenKey, JSON.stringify(stored));
|
|
308
|
+
return stored.access_token;
|
|
309
|
+
}
|
|
310
|
+
if (res.status === 400 || res.status === 401) {
|
|
311
|
+
if (unchanged)
|
|
312
|
+
tokens.removeItem(tokenKey);
|
|
313
|
+
return null;
|
|
314
|
+
}
|
|
315
|
+
if (res.status === 200)
|
|
316
|
+
throw new VibaseError(200, 'invalid_response', 'the token endpoint answered without an access token');
|
|
317
|
+
const error = isObject(body) && text(body.error) ? body.error : `http_${res.status}`;
|
|
318
|
+
const description = isObject(body) && text(body.error_description) ? `: ${body.error_description}` : '';
|
|
319
|
+
throw new VibaseError(res.status, error, `the token endpoint could not refresh (${error})${description}`);
|
|
320
|
+
}
|
|
321
|
+
let refreshing;
|
|
322
|
+
async function token() {
|
|
323
|
+
const record = readToken();
|
|
324
|
+
if (!record)
|
|
325
|
+
return null;
|
|
326
|
+
if (record.expires_at - Date.now() > MARGIN_MS)
|
|
327
|
+
return record.access_token;
|
|
328
|
+
if (!record.refresh_token) {
|
|
329
|
+
tokens.removeItem(tokenKey); // P2: expired and nothing to refresh with: signed out, so isSignedIn() agrees
|
|
330
|
+
return null;
|
|
331
|
+
}
|
|
332
|
+
if (refreshing)
|
|
333
|
+
return refreshing;
|
|
334
|
+
const raw = tokens.getItem(tokenKey);
|
|
335
|
+
const attempt = refresh({ ...record, refresh_token: record.refresh_token }, raw).finally(() => {
|
|
336
|
+
if (refreshing === attempt)
|
|
337
|
+
refreshing = undefined;
|
|
338
|
+
});
|
|
339
|
+
refreshing = attempt;
|
|
340
|
+
return attempt;
|
|
341
|
+
}
|
|
342
|
+
async function handleRedirect() {
|
|
343
|
+
const here = page();
|
|
344
|
+
if (!here)
|
|
345
|
+
return null;
|
|
346
|
+
const url = new URL(here.href);
|
|
347
|
+
const redirect = new URL(options.redirectUri);
|
|
348
|
+
if (url.origin !== redirect.origin || url.pathname !== redirect.pathname)
|
|
349
|
+
return null;
|
|
350
|
+
const params = url.searchParams;
|
|
351
|
+
if (!params.has('code') && !params.has('error'))
|
|
352
|
+
return null;
|
|
353
|
+
try {
|
|
354
|
+
const record = readPending();
|
|
355
|
+
pending.removeItem(pendingKey); // one-shot: before anything is sent, so a failure leaves no reusable verifier
|
|
356
|
+
if (!record || record.state !== params.get('state'))
|
|
357
|
+
throw new VibaseError(0, 'state_mismatch', 'the sign-in callback does not match a sign-in this page started');
|
|
358
|
+
if (params.has('iss') && params.get('iss') !== (await discover()).issuer)
|
|
359
|
+
throw new VibaseError(0, 'issuer_mismatch', 'the callback names another issuer');
|
|
360
|
+
if (params.has('error')) {
|
|
361
|
+
const description = params.get('error_description');
|
|
362
|
+
throw new VibaseError(0, 'authorization_failed', `${params.get('error')}${description ? `: ${description}` : ''}`);
|
|
363
|
+
}
|
|
364
|
+
await exchange(await discover(), params.get('code') ?? '', record);
|
|
365
|
+
return { returnTo: record.return_to };
|
|
366
|
+
}
|
|
367
|
+
finally {
|
|
368
|
+
for (const name of CALLBACK_PARAMS)
|
|
369
|
+
params.delete(name);
|
|
370
|
+
const search = params.toString();
|
|
371
|
+
const clean = url.pathname + (search ? `?${search}` : '') + url.hash;
|
|
372
|
+
const replace = options.replaceUrl ?? ((u) => globalThis.history.replaceState(null, '', u));
|
|
373
|
+
replace(clean);
|
|
374
|
+
}
|
|
375
|
+
}
|
|
376
|
+
return {
|
|
377
|
+
signIn,
|
|
378
|
+
handleRedirect,
|
|
379
|
+
token,
|
|
380
|
+
isSignedIn: () => readToken() !== null,
|
|
381
|
+
signOut() {
|
|
382
|
+
tokens.removeItem(tokenKey);
|
|
383
|
+
pending.removeItem(pendingKey);
|
|
384
|
+
},
|
|
385
|
+
};
|
|
386
|
+
}
|
package/dist/types.d.ts
ADDED
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
import type { FilterEntry } from './filters.js';
|
|
2
|
+
import type { AggregateMethod, AggregateShape } from './typing.js';
|
|
3
|
+
/** What the generator and the client share: the operation map (types) and the operation table (data), DX603 D5 and D12. */
|
|
4
|
+
/** One operation of a map: its member names, its flat arguments, its result and whether it pages or may be proposed. */
|
|
5
|
+
export interface OperationShape {
|
|
6
|
+
/** The client namespace (`deals`, `actionRequests`): the operation id's first part, camelCased (D4). */
|
|
7
|
+
namespace: string;
|
|
8
|
+
/** The method name in that namespace (`moveStage`). Never `all` or `propose`. */
|
|
9
|
+
method: string;
|
|
10
|
+
/** The flat arguments: path, query and body fields in one object (D5). */
|
|
11
|
+
args: object;
|
|
12
|
+
/** The success result as the wire carries it: the parsed JSON body, `undefined` for a 204, `Response` for a binary one. */
|
|
13
|
+
result: unknown;
|
|
14
|
+
/** A paginated operation's item type (`data[number]`); absent otherwise. */
|
|
15
|
+
item?: unknown;
|
|
16
|
+
proposable: boolean;
|
|
17
|
+
paginated: boolean;
|
|
18
|
+
/** An aggregate operation's field lists, kinds and money fields (DX616 D2); absent on every other operation. */
|
|
19
|
+
aggregate?: AggregateShape;
|
|
20
|
+
}
|
|
21
|
+
/** The map: operation id to its shape. The generator writes `BuiltInOperations` as a type alias (an interface has no index signature, so it would not satisfy this); DX604 writes a per-workspace one. */
|
|
22
|
+
export type OperationMap = {
|
|
23
|
+
[operationId: string]: OperationShape;
|
|
24
|
+
};
|
|
25
|
+
export type HttpMethod = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';
|
|
26
|
+
export type FieldPlace = 'path' | 'query' | 'body';
|
|
27
|
+
/** One row of the runtime table: where the operation lives and where each argument goes. */
|
|
28
|
+
export interface OperationEntry<O extends OperationShape = OperationShape> {
|
|
29
|
+
readonly namespace: O['namespace'];
|
|
30
|
+
readonly method: O['method'];
|
|
31
|
+
readonly http: HttpMethod;
|
|
32
|
+
/** The path template, `{name}` for a path field: `/api/v1/deals/{id}`. */
|
|
33
|
+
readonly path: string;
|
|
34
|
+
/** Every declared argument and where it goes. A name not listed goes to the body when the operation has one. */
|
|
35
|
+
readonly fields: Readonly<Record<string, FieldPlace>>;
|
|
36
|
+
/** Whether the operation has a JSON request body. */
|
|
37
|
+
readonly body: boolean;
|
|
38
|
+
/** `json` the parsed body, `empty` a 204 (resolves undefined), `binary` the checked `Response`. */
|
|
39
|
+
readonly output: 'json' | 'empty' | 'binary';
|
|
40
|
+
readonly paginated: O['paginated'];
|
|
41
|
+
readonly proposable: O['proposable'];
|
|
42
|
+
/** Query parameters that are column filters (`x-vibase-filter`): their kind and operators. */
|
|
43
|
+
readonly filters: Readonly<Record<string, FilterEntry>>;
|
|
44
|
+
/** An aggregate operation's list parameters (`sum`, `group_by`, ...): an array is sent comma-joined, an empty one refused (DX616 D5). */
|
|
45
|
+
readonly aggregateParams?: readonly string[];
|
|
46
|
+
}
|
|
47
|
+
/** The runtime table, typed by the map it was generated with, so `createClient` infers the map from it. */
|
|
48
|
+
export type OperationTable<Ops extends OperationMap> = {
|
|
49
|
+
readonly [K in keyof Ops]: OperationEntry<Ops[K]>;
|
|
50
|
+
};
|
|
51
|
+
export interface CallOptions {
|
|
52
|
+
signal?: AbortSignal;
|
|
53
|
+
}
|
|
54
|
+
/** A method: the flat arguments (omitted when none is required) and an optional `{ signal }`. */
|
|
55
|
+
export type Method<O extends OperationShape> = O extends {
|
|
56
|
+
aggregate: infer S extends AggregateShape;
|
|
57
|
+
} ? AggregateMethod<O['args'], S> : Record<never, never> extends O['args'] ? (args?: O['args'], options?: CallOptions) => Promise<O['result']> : (args: O['args'], options?: CallOptions) => Promise<O['result']>;
|
|
58
|
+
/** `action_requests.create` in a map: where `.propose` sends, and the source of the proposal fields and the record type. */
|
|
59
|
+
type CreateOf<Ops extends OperationMap> = Ops extends {
|
|
60
|
+
'action_requests.create': infer C extends OperationShape;
|
|
61
|
+
} ? C : never;
|
|
62
|
+
/** The proposal fields of `.propose` (`reason` required): `action_requests.create`'s body without `operation` and `arguments`. */
|
|
63
|
+
export type Proposal<Ops extends OperationMap> = Omit<CreateOf<Ops>['args'], 'operation' | 'arguments'>;
|
|
64
|
+
/** The record `.propose` resolves to: the created action request with `operation` narrowed to the id and `arguments` typed (DX608 D11). */
|
|
65
|
+
export type ActionRequest<Ops extends OperationMap, Id extends keyof Ops> = Omit<CreateOf<Ops>['result'], 'operation' | 'arguments'> & {
|
|
66
|
+
operation: Id;
|
|
67
|
+
arguments: Ops[Id]['args'];
|
|
68
|
+
};
|
|
69
|
+
type All<O extends OperationShape> = Record<never, never> extends O['args'] ? (args?: O['args'], options?: CallOptions) => AsyncIterable<O['item']> : (args: O['args'], options?: CallOptions) => AsyncIterable<O['item']>;
|
|
70
|
+
type Propose<Ops extends OperationMap, K extends keyof Ops> = (args: Ops[K]['args'], proposal: Proposal<Ops>, options?: CallOptions) => Promise<ActionRequest<Ops, K>>;
|
|
71
|
+
/** A method; `.all` on a paginated operation, `.propose` on a proposable one (DX608 D10, D11). */
|
|
72
|
+
export type Member<Ops extends OperationMap, K extends keyof Ops> = Method<Ops[K]> & (Ops[K]['paginated'] extends true ? {
|
|
73
|
+
all: All<Ops[K]>;
|
|
74
|
+
} : unknown) & (Ops[K]['proposable'] extends true ? {
|
|
75
|
+
propose: Propose<Ops, K>;
|
|
76
|
+
} : unknown);
|
|
77
|
+
/** The client: one namespace per resource prefix, one method per operation. */
|
|
78
|
+
export type Client<Ops extends OperationMap> = {
|
|
79
|
+
[N in Ops[keyof Ops]['namespace']]: {
|
|
80
|
+
[K in keyof Ops as Ops[K]['namespace'] extends N ? Ops[K]['method'] : never]: Member<Ops, K>;
|
|
81
|
+
};
|
|
82
|
+
};
|
|
83
|
+
/** A credential: the token, or a function called before every request; `null` means signed out (D6). */
|
|
84
|
+
export type Auth = string | (() => string | null | Promise<string | null>);
|
|
85
|
+
export interface ClientOptions<Ops extends OperationMap> {
|
|
86
|
+
/** The deployment's origin, `https://api.acme.example`. Required: one deployment per organisation. */
|
|
87
|
+
url: string;
|
|
88
|
+
auth: Auth;
|
|
89
|
+
/** Defaults to the global `fetch`. */
|
|
90
|
+
fetch?: typeof fetch;
|
|
91
|
+
/** The operation table; defaults to the built-ins. Passing a generated table infers the map. */
|
|
92
|
+
operations?: OperationTable<Ops>;
|
|
93
|
+
}
|
|
94
|
+
export {};
|
package/dist/types.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|