@brego-ai/sdk 0.0.0-stage → 0.1.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/README.md +61 -2
- package/dist/index.d.ts +163 -0
- package/dist/index.js +397 -0
- package/dist/schema.d.ts +11221 -0
- package/package.json +26 -4
package/README.md
CHANGED
|
@@ -1,3 +1,62 @@
|
|
|
1
|
-
#
|
|
1
|
+
# Brego SDK for TypeScript
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
```bash
|
|
4
|
+
npm install @brego-ai/sdk
|
|
5
|
+
```
|
|
6
|
+
|
|
7
|
+
The partner connect flow for Node.js 22.18 or later, with no dependencies:
|
|
8
|
+
PKCE and the authorise URL, code exchange, refresh shared between concurrent
|
|
9
|
+
calls, revoke, typed API calls and webhook signature checks. Types come from
|
|
10
|
+
the published OpenAPI file.
|
|
11
|
+
|
|
12
|
+
```ts
|
|
13
|
+
import { BregoPartnerClient, createPkce, createState } from "@brego-ai/sdk";
|
|
14
|
+
|
|
15
|
+
const brego = new BregoPartnerClient({
|
|
16
|
+
clientId: process.env.BREGO_CLIENT_ID!,
|
|
17
|
+
clientSecret: process.env.BREGO_CLIENT_SECRET!,
|
|
18
|
+
tokenStore, // { get(connectionId), set(tokens), delete(connectionId) } backed by your database
|
|
19
|
+
});
|
|
20
|
+
|
|
21
|
+
const { verifier, challenge } = createPkce();
|
|
22
|
+
const state = createState();
|
|
23
|
+
// Store verifier and state against the user's session, then redirect:
|
|
24
|
+
const url = brego.authorizeUrl({
|
|
25
|
+
redirectUri,
|
|
26
|
+
scopes: ["api:vehicle:read"],
|
|
27
|
+
state,
|
|
28
|
+
codeChallenge: challenge,
|
|
29
|
+
});
|
|
30
|
+
|
|
31
|
+
// In your callback, after checking state:
|
|
32
|
+
const connection = await brego.exchangeCode({
|
|
33
|
+
code,
|
|
34
|
+
redirectUri,
|
|
35
|
+
codeVerifier: verifier,
|
|
36
|
+
});
|
|
37
|
+
const info = await brego.getConnection(connection.connectionId);
|
|
38
|
+
const vehicle = await brego.request(
|
|
39
|
+
connection.connectionId,
|
|
40
|
+
"GET",
|
|
41
|
+
"/v1/vehicles",
|
|
42
|
+
{ query: { vrm: "AB12CDE" } },
|
|
43
|
+
);
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
`request` refreshes the access token before it expires. A `403` comes back
|
|
47
|
+
as a `BregoApiError`: if `getConnection` also fails, refresh once, and ask the
|
|
48
|
+
organisation to connect again if that fails too. Persist the tokens the store receives: each refresh returns a new
|
|
49
|
+
refresh token. See `examples/partner-connect` for a runnable app.
|
|
50
|
+
|
|
51
|
+
Refresh tokens are single use. One client refreshes each connection once at
|
|
52
|
+
a time. If several processes share the token store, add
|
|
53
|
+
`withLock(connectionId, fn)` to it: run `fn` while holding a lock they all
|
|
54
|
+
respect (a database row lock, for example) and return its result. Without it,
|
|
55
|
+
two processes can refresh together and one can store a refresh token that no
|
|
56
|
+
longer works, which ends the connection's tokens when it is next used.
|
|
57
|
+
|
|
58
|
+
Pass API paths that start with a single `/` (for example `/v1/vehicles`); anything else is refused, so a connection's token is only ever sent to the configured API.
|
|
59
|
+
|
|
60
|
+
If two approvals of the same connection are exchanged at once, the later one replaces the earlier tokens. The SDK saves exchanged tokens one connection at a time and never over stored tokens that still work while the new ones are refused; the exchange then returns the stored tokens. If Brego can't be reached to check which tokens work, nothing is overwritten and the exchange raises `BregoTokenCheckError`, carrying the new tokens in `tokens` and the stored ones in `stored`. The code that produced the new tokens can't be used again, so keep whichever set works once you can check. If Brego refuses both sets, nothing is saved and the exchange raises `BregoTokensRefusedError`: the connection was approved again or revoked, so read its tokens from your store again.
|
|
61
|
+
|
|
62
|
+
If your token store cannot save tokens Brego has just issued, the SDK retries a few times and then raises `BregoTokenStoreError`, carrying the new tokens in `tokens`. The code or refresh token that produced them can't be used again, so save those tokens yourself.
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,163 @@
|
|
|
1
|
+
import type { components, paths } from "./schema.d.ts";
|
|
2
|
+
/**
|
|
3
|
+
* Brego partner SDK: the OAuth 2.0 connect flow, token refresh and typed API
|
|
4
|
+
* calls for partner apps, plus webhook signature checks. No dependencies.
|
|
5
|
+
* Types are generated from the published OpenAPI file.
|
|
6
|
+
*/
|
|
7
|
+
export type { components, paths };
|
|
8
|
+
export interface ConnectionTokens {
|
|
9
|
+
accessToken: string;
|
|
10
|
+
refreshToken: string;
|
|
11
|
+
/** Epoch milliseconds. */
|
|
12
|
+
expiresAt: number;
|
|
13
|
+
scope: string[];
|
|
14
|
+
connectionId: string;
|
|
15
|
+
organizationId: string;
|
|
16
|
+
}
|
|
17
|
+
/** Where the SDK keeps each connection's tokens. Persist them yourself. */
|
|
18
|
+
export interface TokenStore {
|
|
19
|
+
get(connectionId: string): Promise<ConnectionTokens | undefined>;
|
|
20
|
+
set(tokens: ConnectionTokens): Promise<void>;
|
|
21
|
+
/** Removes a connection's tokens. Called once the connection is revoked. */
|
|
22
|
+
delete(connectionId: string): Promise<void>;
|
|
23
|
+
/**
|
|
24
|
+
* When several processes share the store, runs `fn` while holding a lock
|
|
25
|
+
* they all respect (a database row lock, say) and returns its result, so
|
|
26
|
+
* only one of them refreshes a connection at a time. Refresh tokens are
|
|
27
|
+
* single use, so without it two processes can refresh together and one
|
|
28
|
+
* can store a token that no longer works.
|
|
29
|
+
*/
|
|
30
|
+
withLock?<T>(connectionId: string, fn: () => Promise<T>): Promise<T>;
|
|
31
|
+
}
|
|
32
|
+
export interface BregoPartnerOptions {
|
|
33
|
+
clientId: string;
|
|
34
|
+
clientSecret: string;
|
|
35
|
+
/** Defaults to https://api.brego.io. */
|
|
36
|
+
apiBaseUrl?: string;
|
|
37
|
+
tokenStore: TokenStore;
|
|
38
|
+
fetch?: typeof fetch;
|
|
39
|
+
/** Refresh this many milliseconds before expiry. Defaults to 60 seconds. */
|
|
40
|
+
refreshMarginMs?: number;
|
|
41
|
+
}
|
|
42
|
+
export declare class BregoOAuthError extends Error {
|
|
43
|
+
readonly code: string;
|
|
44
|
+
readonly status: number;
|
|
45
|
+
constructor(code: string, status: number, description?: string);
|
|
46
|
+
}
|
|
47
|
+
/**
|
|
48
|
+
* The token store could not save tokens Brego has already issued. The code
|
|
49
|
+
* or refresh token that produced them is spent, so save `tokens` yourself
|
|
50
|
+
* (they are the only usable credentials for the connection) before retrying.
|
|
51
|
+
*/
|
|
52
|
+
export declare class BregoTokenStoreError extends Error {
|
|
53
|
+
readonly tokens: ConnectionTokens;
|
|
54
|
+
readonly cause: unknown;
|
|
55
|
+
constructor(tokens: ConnectionTokens, cause: unknown);
|
|
56
|
+
}
|
|
57
|
+
/**
|
|
58
|
+
* An exchange returned tokens that differ from the stored ones, and Brego
|
|
59
|
+
* could not be reached to tell which still work. Neither set was overwritten:
|
|
60
|
+
* `tokens` are the new ones (their code is spent) and `stored` the old ones.
|
|
61
|
+
* Check again later, or keep whichever works.
|
|
62
|
+
*/
|
|
63
|
+
/**
|
|
64
|
+
* An exchange returned tokens that Brego already refuses, as it does the
|
|
65
|
+
* stored ones: the connection was approved again (its newest tokens are still
|
|
66
|
+
* on their way to the store) or revoked. Nothing was saved. Read the
|
|
67
|
+
* connection's tokens from the store again, or ask the organisation to
|
|
68
|
+
* connect again if there are none that work.
|
|
69
|
+
*/
|
|
70
|
+
export declare class BregoTokensRefusedError extends Error {
|
|
71
|
+
readonly tokens: ConnectionTokens;
|
|
72
|
+
constructor(tokens: ConnectionTokens);
|
|
73
|
+
}
|
|
74
|
+
export declare class BregoTokenCheckError extends Error {
|
|
75
|
+
readonly tokens: ConnectionTokens;
|
|
76
|
+
readonly stored: ConnectionTokens;
|
|
77
|
+
constructor(tokens: ConnectionTokens, stored: ConnectionTokens);
|
|
78
|
+
}
|
|
79
|
+
export declare class BregoApiError extends Error {
|
|
80
|
+
readonly status: number;
|
|
81
|
+
readonly body: unknown;
|
|
82
|
+
constructor(status: number, body: unknown);
|
|
83
|
+
}
|
|
84
|
+
export declare const createPkce: () => {
|
|
85
|
+
verifier: string;
|
|
86
|
+
challenge: string;
|
|
87
|
+
};
|
|
88
|
+
export declare const createState: () => string;
|
|
89
|
+
/**
|
|
90
|
+
* Checks `X-Signature: t={ms},v1={hex}[,v1=…]` against the raw body. Any
|
|
91
|
+
* matching `v1` is valid, so secret rotation works.
|
|
92
|
+
*/
|
|
93
|
+
export declare const verifyWebhookSignature: (header: string | undefined | null, rawBody: string, secret: string, options?: {
|
|
94
|
+
now?: number;
|
|
95
|
+
toleranceMs?: number;
|
|
96
|
+
}) => boolean;
|
|
97
|
+
export declare class BregoPartnerClient {
|
|
98
|
+
private readonly options;
|
|
99
|
+
private readonly refreshing;
|
|
100
|
+
/** Per-connection queue: refreshes and revocations run one at a time. */
|
|
101
|
+
private readonly queues;
|
|
102
|
+
private exclusive;
|
|
103
|
+
constructor(options: BregoPartnerOptions);
|
|
104
|
+
/** The URL to send an organisation's admin to. */
|
|
105
|
+
authorizeUrl(input: {
|
|
106
|
+
redirectUri: string;
|
|
107
|
+
scopes?: string[];
|
|
108
|
+
state: string;
|
|
109
|
+
codeChallenge: string;
|
|
110
|
+
}): string;
|
|
111
|
+
/** Exchanges the callback's code and stores the connection's tokens. */
|
|
112
|
+
exchangeCode(input: {
|
|
113
|
+
code: string;
|
|
114
|
+
redirectUri: string;
|
|
115
|
+
codeVerifier: string;
|
|
116
|
+
}): Promise<ConnectionTokens>;
|
|
117
|
+
/**
|
|
118
|
+
* The stored tokens, when they are newer than `issued`: `issued` is
|
|
119
|
+
* refused while the different stored ones still work. Otherwise undefined.
|
|
120
|
+
* Throws `BregoTokenCheckError` when neither can be shown to be refused,
|
|
121
|
+
* and `BregoTokensRefusedError` when both are.
|
|
122
|
+
*/
|
|
123
|
+
private newerStoredTokens;
|
|
124
|
+
/**
|
|
125
|
+
* Whether Brego accepts the token: true, false when it says the token
|
|
126
|
+
* itself is invalid, or undefined when that is not clear. A 403 for any
|
|
127
|
+
* other reason (the app suspended, say) applies to every token of the
|
|
128
|
+
* connection, so it says nothing about which one is current.
|
|
129
|
+
*/
|
|
130
|
+
private works;
|
|
131
|
+
/**
|
|
132
|
+
* Saves tokens Brego has just issued, retrying a failing store a few times.
|
|
133
|
+
* If it still fails, the tokens come back on a `BregoTokenStoreError`, as
|
|
134
|
+
* the code or refresh token that produced them can't be used again.
|
|
135
|
+
*/
|
|
136
|
+
private saveIssued;
|
|
137
|
+
/**
|
|
138
|
+
* Refreshes a connection's tokens once at a time per connection, so
|
|
139
|
+
* concurrent callers share one refresh instead of reusing a spent token.
|
|
140
|
+
* Across processes this needs the token store's `withLock`.
|
|
141
|
+
*/
|
|
142
|
+
refresh(connectionId: string): Promise<ConnectionTokens>;
|
|
143
|
+
/**
|
|
144
|
+
* Ends the connection. Runs after any refresh in progress, and under the
|
|
145
|
+
* token store's `withLock`, so a refresh cannot store new tokens after
|
|
146
|
+
* they are deleted.
|
|
147
|
+
*/
|
|
148
|
+
revoke(connectionId: string): Promise<void>;
|
|
149
|
+
/**
|
|
150
|
+
* Calls the API as a connection, refreshing first when the access token is
|
|
151
|
+
* about to expire. A `403` is returned as a `BregoApiError` without a
|
|
152
|
+
* refresh; its body's `message` says why, for example that the token is
|
|
153
|
+
* expired or revoked, lacks a scope or the app is suspended.
|
|
154
|
+
*/
|
|
155
|
+
request<T = unknown>(connectionId: string, method: string, path: string, options?: {
|
|
156
|
+
query?: Record<string, string | number | boolean | Array<string | number> | undefined>;
|
|
157
|
+
body?: unknown;
|
|
158
|
+
}): Promise<T>;
|
|
159
|
+
/** Which organisation a connection belongs to and the scopes it can use. */
|
|
160
|
+
getConnection(connectionId: string): Promise<components["schemas"]["ConnectionInfo"]>;
|
|
161
|
+
private form;
|
|
162
|
+
private tokenRequest;
|
|
163
|
+
}
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,397 @@
|
|
|
1
|
+
import { createHash, createHmac, randomBytes, timingSafeEqual, } from "node:crypto";
|
|
2
|
+
export class BregoOAuthError extends Error {
|
|
3
|
+
code;
|
|
4
|
+
status;
|
|
5
|
+
constructor(code, status, description) {
|
|
6
|
+
super(description ?? code);
|
|
7
|
+
this.code = code;
|
|
8
|
+
this.status = status;
|
|
9
|
+
}
|
|
10
|
+
}
|
|
11
|
+
/**
|
|
12
|
+
* The token store could not save tokens Brego has already issued. The code
|
|
13
|
+
* or refresh token that produced them is spent, so save `tokens` yourself
|
|
14
|
+
* (they are the only usable credentials for the connection) before retrying.
|
|
15
|
+
*/
|
|
16
|
+
export class BregoTokenStoreError extends Error {
|
|
17
|
+
tokens;
|
|
18
|
+
cause;
|
|
19
|
+
constructor(tokens, cause) {
|
|
20
|
+
super("The token store could not save the new tokens; save error.tokens yourself.");
|
|
21
|
+
this.tokens = tokens;
|
|
22
|
+
this.cause = cause;
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
/**
|
|
26
|
+
* An exchange returned tokens that differ from the stored ones, and Brego
|
|
27
|
+
* could not be reached to tell which still work. Neither set was overwritten:
|
|
28
|
+
* `tokens` are the new ones (their code is spent) and `stored` the old ones.
|
|
29
|
+
* Check again later, or keep whichever works.
|
|
30
|
+
*/
|
|
31
|
+
/**
|
|
32
|
+
* An exchange returned tokens that Brego already refuses, as it does the
|
|
33
|
+
* stored ones: the connection was approved again (its newest tokens are still
|
|
34
|
+
* on their way to the store) or revoked. Nothing was saved. Read the
|
|
35
|
+
* connection's tokens from the store again, or ask the organisation to
|
|
36
|
+
* connect again if there are none that work.
|
|
37
|
+
*/
|
|
38
|
+
export class BregoTokensRefusedError extends Error {
|
|
39
|
+
tokens;
|
|
40
|
+
constructor(tokens) {
|
|
41
|
+
super("Brego refused both the new tokens and the stored ones; nothing was saved.");
|
|
42
|
+
this.tokens = tokens;
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
export class BregoTokenCheckError extends Error {
|
|
46
|
+
tokens;
|
|
47
|
+
stored;
|
|
48
|
+
constructor(tokens, stored) {
|
|
49
|
+
super("Could not check which of the connection's tokens still work; both are on the error.");
|
|
50
|
+
this.tokens = tokens;
|
|
51
|
+
this.stored = stored;
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
/** How Brego's refusal of an invalid, expired or revoked token begins. */
|
|
55
|
+
const INVALID_TOKEN_MESSAGE = "The access token is invalid, expired or revoked.";
|
|
56
|
+
export class BregoApiError extends Error {
|
|
57
|
+
status;
|
|
58
|
+
body;
|
|
59
|
+
constructor(status, body) {
|
|
60
|
+
super(`Brego API request failed with ${status}`);
|
|
61
|
+
this.status = status;
|
|
62
|
+
this.body = body;
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
export const createPkce = () => {
|
|
66
|
+
const verifier = randomBytes(32).toString("base64url");
|
|
67
|
+
return {
|
|
68
|
+
verifier,
|
|
69
|
+
challenge: createHash("sha256").update(verifier).digest("base64url"),
|
|
70
|
+
};
|
|
71
|
+
};
|
|
72
|
+
export const createState = () => randomBytes(24).toString("base64url");
|
|
73
|
+
/**
|
|
74
|
+
* Checks `X-Signature: t={ms},v1={hex}[,v1=…]` against the raw body. Any
|
|
75
|
+
* matching `v1` is valid, so secret rotation works.
|
|
76
|
+
*/
|
|
77
|
+
export const verifyWebhookSignature = (header, rawBody, secret, options = {}) => {
|
|
78
|
+
if (!header)
|
|
79
|
+
return false;
|
|
80
|
+
const now = options.now ?? Date.now();
|
|
81
|
+
const toleranceMs = options.toleranceMs ?? 5 * 60 * 1000;
|
|
82
|
+
const parts = header.split(",");
|
|
83
|
+
const timestamp = Number(parts.find((part) => part.startsWith("t="))?.slice(2));
|
|
84
|
+
if (!Number.isFinite(timestamp) || Math.abs(now - timestamp) > toleranceMs) {
|
|
85
|
+
return false;
|
|
86
|
+
}
|
|
87
|
+
const expected = createHmac("sha256", secret)
|
|
88
|
+
.update(`${timestamp}.${rawBody}`)
|
|
89
|
+
.digest();
|
|
90
|
+
return parts
|
|
91
|
+
.filter((part) => part.startsWith("v1="))
|
|
92
|
+
.some((part) => {
|
|
93
|
+
const given = Buffer.from(part.slice(3), "hex");
|
|
94
|
+
return (given.length === expected.length && timingSafeEqual(given, expected));
|
|
95
|
+
});
|
|
96
|
+
};
|
|
97
|
+
export class BregoPartnerClient {
|
|
98
|
+
options;
|
|
99
|
+
refreshing = new Map();
|
|
100
|
+
/** Per-connection queue: refreshes and revocations run one at a time. */
|
|
101
|
+
queues = new Map();
|
|
102
|
+
exclusive(connectionId, fn) {
|
|
103
|
+
const previous = this.queues.get(connectionId) ?? Promise.resolve();
|
|
104
|
+
const result = previous.then(fn, fn);
|
|
105
|
+
const tail = result.then(() => undefined, () => undefined);
|
|
106
|
+
this.queues.set(connectionId, tail);
|
|
107
|
+
void tail.then(() => {
|
|
108
|
+
if (this.queues.get(connectionId) === tail) {
|
|
109
|
+
this.queues.delete(connectionId);
|
|
110
|
+
}
|
|
111
|
+
});
|
|
112
|
+
return result;
|
|
113
|
+
}
|
|
114
|
+
constructor(options) {
|
|
115
|
+
this.options = {
|
|
116
|
+
apiBaseUrl: "https://api.brego.io",
|
|
117
|
+
refreshMarginMs: 60_000,
|
|
118
|
+
...options,
|
|
119
|
+
fetch: options.fetch ?? fetch,
|
|
120
|
+
};
|
|
121
|
+
}
|
|
122
|
+
/** The URL to send an organisation's admin to. */
|
|
123
|
+
authorizeUrl(input) {
|
|
124
|
+
const url = new URL("/v1/oauth/authorize", this.options.apiBaseUrl);
|
|
125
|
+
url.search = new URLSearchParams({
|
|
126
|
+
response_type: "code",
|
|
127
|
+
client_id: this.options.clientId,
|
|
128
|
+
redirect_uri: input.redirectUri,
|
|
129
|
+
scope: (input.scopes ?? []).join(" "),
|
|
130
|
+
state: input.state,
|
|
131
|
+
code_challenge: input.codeChallenge,
|
|
132
|
+
code_challenge_method: "S256",
|
|
133
|
+
}).toString();
|
|
134
|
+
return url.toString();
|
|
135
|
+
}
|
|
136
|
+
/** Exchanges the callback's code and stores the connection's tokens. */
|
|
137
|
+
async exchangeCode(input) {
|
|
138
|
+
const tokens = await this.tokenRequest({
|
|
139
|
+
grant_type: "authorization_code",
|
|
140
|
+
code: input.code,
|
|
141
|
+
redirect_uri: input.redirectUri,
|
|
142
|
+
code_verifier: input.codeVerifier,
|
|
143
|
+
});
|
|
144
|
+
// Two approvals for the same connection can be exchanged at once: the
|
|
145
|
+
// later one replaces the earlier tokens. Saved one at a time per
|
|
146
|
+
// connection, and never over newer tokens that still work.
|
|
147
|
+
const store = this.options.tokenStore;
|
|
148
|
+
return await this.exclusive(tokens.connectionId, async () => {
|
|
149
|
+
const run = async () => {
|
|
150
|
+
const kept = await this.newerStoredTokens(tokens);
|
|
151
|
+
if (kept)
|
|
152
|
+
return kept;
|
|
153
|
+
await this.saveIssued(tokens);
|
|
154
|
+
return tokens;
|
|
155
|
+
};
|
|
156
|
+
return store.withLock
|
|
157
|
+
? await store.withLock(tokens.connectionId, run)
|
|
158
|
+
: await run();
|
|
159
|
+
});
|
|
160
|
+
}
|
|
161
|
+
/**
|
|
162
|
+
* The stored tokens, when they are newer than `issued`: `issued` is
|
|
163
|
+
* refused while the different stored ones still work. Otherwise undefined.
|
|
164
|
+
* Throws `BregoTokenCheckError` when neither can be shown to be refused,
|
|
165
|
+
* and `BregoTokensRefusedError` when both are.
|
|
166
|
+
*/
|
|
167
|
+
async newerStoredTokens(issued) {
|
|
168
|
+
const stored = await this.options.tokenStore.get(issued.connectionId);
|
|
169
|
+
if (!stored || stored.accessToken === issued.accessToken)
|
|
170
|
+
return undefined;
|
|
171
|
+
const issuedWorks = await this.works(issued.accessToken);
|
|
172
|
+
if (issuedWorks === true)
|
|
173
|
+
return undefined;
|
|
174
|
+
const storedWorks = await this.works(stored.accessToken);
|
|
175
|
+
if (storedWorks === true)
|
|
176
|
+
return stored;
|
|
177
|
+
// Neither works: a later approval replaced both, or the connection was
|
|
178
|
+
// revoked. Saving either would only store tokens known not to work.
|
|
179
|
+
if (storedWorks === false && issuedWorks === false) {
|
|
180
|
+
throw new BregoTokensRefusedError(issued);
|
|
181
|
+
}
|
|
182
|
+
// Replace the stored tokens only once they are known to be refused, and
|
|
183
|
+
// keep them while the new ones are.
|
|
184
|
+
if (storedWorks === false)
|
|
185
|
+
return undefined;
|
|
186
|
+
if (issuedWorks === false)
|
|
187
|
+
return stored;
|
|
188
|
+
throw new BregoTokenCheckError(issued, stored);
|
|
189
|
+
}
|
|
190
|
+
/**
|
|
191
|
+
* Whether Brego accepts the token: true, false when it says the token
|
|
192
|
+
* itself is invalid, or undefined when that is not clear. A 403 for any
|
|
193
|
+
* other reason (the app suspended, say) applies to every token of the
|
|
194
|
+
* connection, so it says nothing about which one is current.
|
|
195
|
+
*/
|
|
196
|
+
async works(accessToken) {
|
|
197
|
+
try {
|
|
198
|
+
const response = await this.options.fetch(new URL("/v1/oauth/connection", this.options.apiBaseUrl), { headers: { Authorization: `Bearer ${accessToken}` } });
|
|
199
|
+
if (response.ok)
|
|
200
|
+
return true;
|
|
201
|
+
if (response.status === 401)
|
|
202
|
+
return false;
|
|
203
|
+
if (response.status !== 403)
|
|
204
|
+
return undefined;
|
|
205
|
+
const body = (await response.json().catch(() => undefined));
|
|
206
|
+
return typeof body?.message === "string" &&
|
|
207
|
+
body.message.startsWith(INVALID_TOKEN_MESSAGE)
|
|
208
|
+
? false
|
|
209
|
+
: undefined;
|
|
210
|
+
}
|
|
211
|
+
catch {
|
|
212
|
+
return undefined;
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
/**
|
|
216
|
+
* Saves tokens Brego has just issued, retrying a failing store a few times.
|
|
217
|
+
* If it still fails, the tokens come back on a `BregoTokenStoreError`, as
|
|
218
|
+
* the code or refresh token that produced them can't be used again.
|
|
219
|
+
*/
|
|
220
|
+
async saveIssued(tokens) {
|
|
221
|
+
let lastError;
|
|
222
|
+
for (const delayMs of [0, 200, 1_000]) {
|
|
223
|
+
if (delayMs)
|
|
224
|
+
await new Promise((resolve) => setTimeout(resolve, delayMs));
|
|
225
|
+
try {
|
|
226
|
+
await this.options.tokenStore.set(tokens);
|
|
227
|
+
return;
|
|
228
|
+
}
|
|
229
|
+
catch (error) {
|
|
230
|
+
lastError = error;
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
throw new BregoTokenStoreError(tokens, lastError);
|
|
234
|
+
}
|
|
235
|
+
/**
|
|
236
|
+
* Refreshes a connection's tokens once at a time per connection, so
|
|
237
|
+
* concurrent callers share one refresh instead of reusing a spent token.
|
|
238
|
+
* Across processes this needs the token store's `withLock`.
|
|
239
|
+
*/
|
|
240
|
+
async refresh(connectionId) {
|
|
241
|
+
const pending = this.refreshing.get(connectionId);
|
|
242
|
+
if (pending)
|
|
243
|
+
return await pending;
|
|
244
|
+
const store = this.options.tokenStore;
|
|
245
|
+
const work = this.exclusive(connectionId, async () => {
|
|
246
|
+
const before = await store.get(connectionId);
|
|
247
|
+
const run = async () => {
|
|
248
|
+
const current = await store.get(connectionId);
|
|
249
|
+
if (!current)
|
|
250
|
+
throw new Error(`No tokens stored for ${connectionId}`);
|
|
251
|
+
// Another process refreshed while this one waited for the lock.
|
|
252
|
+
if (before && current.refreshToken !== before.refreshToken) {
|
|
253
|
+
return current;
|
|
254
|
+
}
|
|
255
|
+
const tokens = await this.tokenRequest({
|
|
256
|
+
grant_type: "refresh_token",
|
|
257
|
+
refresh_token: current.refreshToken,
|
|
258
|
+
});
|
|
259
|
+
await this.saveIssued(tokens);
|
|
260
|
+
return tokens;
|
|
261
|
+
};
|
|
262
|
+
return store.withLock
|
|
263
|
+
? await store.withLock(connectionId, run)
|
|
264
|
+
: await run();
|
|
265
|
+
});
|
|
266
|
+
this.refreshing.set(connectionId, work);
|
|
267
|
+
try {
|
|
268
|
+
return await work;
|
|
269
|
+
}
|
|
270
|
+
finally {
|
|
271
|
+
this.refreshing.delete(connectionId);
|
|
272
|
+
}
|
|
273
|
+
}
|
|
274
|
+
/**
|
|
275
|
+
* Ends the connection. Runs after any refresh in progress, and under the
|
|
276
|
+
* token store's `withLock`, so a refresh cannot store new tokens after
|
|
277
|
+
* they are deleted.
|
|
278
|
+
*/
|
|
279
|
+
async revoke(connectionId) {
|
|
280
|
+
const store = this.options.tokenStore;
|
|
281
|
+
await this.exclusive(connectionId, async () => {
|
|
282
|
+
const run = async () => {
|
|
283
|
+
const current = await store.get(connectionId);
|
|
284
|
+
if (!current)
|
|
285
|
+
return;
|
|
286
|
+
const response = await this.form("/v1/oauth/revoke", {
|
|
287
|
+
token: current.refreshToken,
|
|
288
|
+
});
|
|
289
|
+
if (!response.ok) {
|
|
290
|
+
throw new BregoApiError(response.status, await safeJson(response));
|
|
291
|
+
}
|
|
292
|
+
// The connection is ended for good, so its tokens are of no use.
|
|
293
|
+
await store.delete(connectionId);
|
|
294
|
+
};
|
|
295
|
+
if (store.withLock) {
|
|
296
|
+
await store.withLock(connectionId, run);
|
|
297
|
+
}
|
|
298
|
+
else {
|
|
299
|
+
await run();
|
|
300
|
+
}
|
|
301
|
+
});
|
|
302
|
+
}
|
|
303
|
+
/**
|
|
304
|
+
* Calls the API as a connection, refreshing first when the access token is
|
|
305
|
+
* about to expire. A `403` is returned as a `BregoApiError` without a
|
|
306
|
+
* refresh; its body's `message` says why, for example that the token is
|
|
307
|
+
* expired or revoked, lacks a scope or the app is suspended.
|
|
308
|
+
*/
|
|
309
|
+
async request(connectionId, method, path, options = {}) {
|
|
310
|
+
let tokens = await this.options.tokenStore.get(connectionId);
|
|
311
|
+
if (!tokens)
|
|
312
|
+
throw new Error(`No tokens stored for ${connectionId}`);
|
|
313
|
+
if (tokens.expiresAt - this.options.refreshMarginMs <= Date.now()) {
|
|
314
|
+
tokens = await this.refresh(connectionId);
|
|
315
|
+
}
|
|
316
|
+
// Only paths on the configured API: an absolute or scheme-relative value
|
|
317
|
+
// would send the access token to another host.
|
|
318
|
+
if (!path.startsWith("/") || path.startsWith("//")) {
|
|
319
|
+
throw new Error("path must be an API path starting with a single /");
|
|
320
|
+
}
|
|
321
|
+
const base = new URL(this.options.apiBaseUrl);
|
|
322
|
+
const send = (accessToken) => {
|
|
323
|
+
const url = new URL(path, base);
|
|
324
|
+
if (url.origin !== base.origin) {
|
|
325
|
+
throw new Error("path must stay on the configured API");
|
|
326
|
+
}
|
|
327
|
+
for (const [key, value] of Object.entries(options.query ?? {})) {
|
|
328
|
+
// Arrays become repeated fields, as array parameters such as
|
|
329
|
+
// `expand` need.
|
|
330
|
+
if (Array.isArray(value)) {
|
|
331
|
+
for (const item of value)
|
|
332
|
+
url.searchParams.append(key, String(item));
|
|
333
|
+
}
|
|
334
|
+
else if (value !== undefined) {
|
|
335
|
+
url.searchParams.set(key, String(value));
|
|
336
|
+
}
|
|
337
|
+
}
|
|
338
|
+
return this.options.fetch(url, {
|
|
339
|
+
method,
|
|
340
|
+
headers: {
|
|
341
|
+
Authorization: `Bearer ${accessToken}`,
|
|
342
|
+
...(options.body === undefined
|
|
343
|
+
? {}
|
|
344
|
+
: { "Content-Type": "application/json" }),
|
|
345
|
+
},
|
|
346
|
+
body: options.body === undefined ? undefined : JSON.stringify(options.body),
|
|
347
|
+
});
|
|
348
|
+
};
|
|
349
|
+
const response = await send(tokens.accessToken);
|
|
350
|
+
const body = await safeJson(response);
|
|
351
|
+
if (!response.ok)
|
|
352
|
+
throw new BregoApiError(response.status, body);
|
|
353
|
+
return body;
|
|
354
|
+
}
|
|
355
|
+
/** Which organisation a connection belongs to and the scopes it can use. */
|
|
356
|
+
getConnection(connectionId) {
|
|
357
|
+
return this.request(connectionId, "GET", "/v1/oauth/connection");
|
|
358
|
+
}
|
|
359
|
+
form(path, body) {
|
|
360
|
+
const basic = Buffer.from(`${this.options.clientId}:${this.options.clientSecret}`).toString("base64");
|
|
361
|
+
return this.options.fetch(new URL(path, this.options.apiBaseUrl), {
|
|
362
|
+
method: "POST",
|
|
363
|
+
headers: {
|
|
364
|
+
Authorization: `Basic ${basic}`,
|
|
365
|
+
"Content-Type": "application/x-www-form-urlencoded",
|
|
366
|
+
},
|
|
367
|
+
body: new URLSearchParams(body).toString(),
|
|
368
|
+
});
|
|
369
|
+
}
|
|
370
|
+
async tokenRequest(body) {
|
|
371
|
+
const response = await this.form("/v1/oauth/token", body);
|
|
372
|
+
const json = (await safeJson(response));
|
|
373
|
+
if (!response.ok) {
|
|
374
|
+
throw new BregoOAuthError(json?.error ?? "server_error", response.status, json?.error_description);
|
|
375
|
+
}
|
|
376
|
+
const tokens = json;
|
|
377
|
+
return {
|
|
378
|
+
accessToken: tokens.access_token,
|
|
379
|
+
refreshToken: tokens.refresh_token,
|
|
380
|
+
expiresAt: Date.now() + tokens.expires_in * 1000,
|
|
381
|
+
scope: tokens.scope ? tokens.scope.split(" ") : [],
|
|
382
|
+
connectionId: tokens.connection_id,
|
|
383
|
+
organizationId: tokens.organization_id,
|
|
384
|
+
};
|
|
385
|
+
}
|
|
386
|
+
}
|
|
387
|
+
const safeJson = async (response) => {
|
|
388
|
+
const text = await response.text();
|
|
389
|
+
if (!text)
|
|
390
|
+
return undefined;
|
|
391
|
+
try {
|
|
392
|
+
return JSON.parse(text);
|
|
393
|
+
}
|
|
394
|
+
catch {
|
|
395
|
+
return text;
|
|
396
|
+
}
|
|
397
|
+
};
|