@orbiworkspace/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 +56 -2
- package/dist/index.d.ts +170 -0
- package/dist/index.js +233 -0
- package/package.json +31 -4
package/README.md
CHANGED
|
@@ -1,3 +1,57 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @orbiworkspace/sdk
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
TypeScript SDK for Orbi's public API. An app connected on Orbi's **Apps** page reads the collections
|
|
4
|
+
its approved `orbi.manifest` names.
|
|
5
|
+
|
|
6
|
+
```bash
|
|
7
|
+
npm install @orbiworkspace/sdk
|
|
8
|
+
```
|
|
9
|
+
|
|
10
|
+
```ts
|
|
11
|
+
import { createOrbiClient } from '@orbiworkspace/sdk';
|
|
12
|
+
|
|
13
|
+
// ORBI_URL and ORBI_APP_KEY come from the environment.
|
|
14
|
+
const orbi = createOrbiClient();
|
|
15
|
+
const { items } = await orbi.collection('Receipts').list({ limit: 20 });
|
|
16
|
+
await orbi.collection('Expense reports').create({ month: '2026-11', total: 1250 });
|
|
17
|
+
```
|
|
18
|
+
|
|
19
|
+
From plain JavaScript the package is CommonJS: `const { createOrbiClient } = require('@orbiworkspace/sdk')`,
|
|
20
|
+
or `import` from an ES module. On Orbi Apps, Orbi sets `ORBI_URL`,
|
|
21
|
+
`ORBI_PUBLIC_URL` and `ORBI_APP_KEY` itself.
|
|
22
|
+
|
|
23
|
+
A development key reads real data, but a collection its manifest may write is read and written in
|
|
24
|
+
the developer's own shadow, so trying the app never changes real records. The live key, given by an
|
|
25
|
+
admin, works on the real collections with the app's approved permissions. A call outside the manifest fails with `OrbiError` code
|
|
26
|
+
`app.permission_missing`.
|
|
27
|
+
|
|
28
|
+
## Reading documents
|
|
29
|
+
|
|
30
|
+
With \`orbi.extraction\` in the manifest, \`extract\` reads the fields you ask for from a document
|
|
31
|
+
(PDF, image, DOCX, XLSX or text, at most 10 MB) and answers each with a value and a confidence:
|
|
32
|
+
|
|
33
|
+
\`\`\`ts
|
|
34
|
+
const result = await orbi.extract({
|
|
35
|
+
file, filename: 'receipt.jpg', mimeType: 'image/jpeg',
|
|
36
|
+
fields: [{ name: 'total', type: 'number', required: true }, { name: 'date', type: 'date' }],
|
|
37
|
+
});
|
|
38
|
+
if (result.needsReview) {
|
|
39
|
+
// a field is below 0.8 confidence, or a required one is empty: let a person confirm
|
|
40
|
+
}
|
|
41
|
+
\`\`\`
|
|
42
|
+
|
|
43
|
+
It spends the workspace's credits; with none left it throws \`OrbiError\` with code
|
|
44
|
+
\`app.extract_no_credits\`.
|
|
45
|
+
|
|
46
|
+
## Sign in with Orbi
|
|
47
|
+
|
|
48
|
+
```ts
|
|
49
|
+
const start = await orbi.signIn.start({ redirectUri: 'https://report.example.com/callback' });
|
|
50
|
+
// Redirect the person to start.url; keep start.codeVerifier and start.state in their session.
|
|
51
|
+
const { user, session } = await orbi.signIn.finish({ code, redirectUri, codeVerifier: start.codeVerifier });
|
|
52
|
+
const receipts = await orbi.asUser(session).collection('Receipts').list();
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
Calls on behalf of a person carry a DPoP proof and reach only what both the app and the person may.
|
|
56
|
+
|
|
57
|
+
Licensed under Apache-2.0.
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,170 @@
|
|
|
1
|
+
export interface OrbiClientOptions {
|
|
2
|
+
/** Orbi's address, for example https://api.orbiwork.space. Defaults to `ORBI_URL`. */
|
|
3
|
+
url?: string;
|
|
4
|
+
/**
|
|
5
|
+
* Orbi's address as a person's browser reaches it, for sign-in. Defaults to `ORBI_PUBLIC_URL`,
|
|
6
|
+
* then to `url`; Orbi Apps sets it where the app reaches Orbi at another address.
|
|
7
|
+
*/
|
|
8
|
+
publicUrl?: string;
|
|
9
|
+
/** The app's key, live or development. Defaults to `ORBI_APP_KEY`. */
|
|
10
|
+
key?: string;
|
|
11
|
+
/** For tests and runtimes without a global fetch. */
|
|
12
|
+
fetch?: typeof fetch;
|
|
13
|
+
}
|
|
14
|
+
export interface OrbiRecord<T = Record<string, unknown>> {
|
|
15
|
+
number: number;
|
|
16
|
+
data: T;
|
|
17
|
+
createdAt: string;
|
|
18
|
+
updatedAt: string;
|
|
19
|
+
}
|
|
20
|
+
export interface RecordPage<T = Record<string, unknown>> {
|
|
21
|
+
items: OrbiRecord<T>[];
|
|
22
|
+
total: number;
|
|
23
|
+
/** True when a development key read its shadow of the collection (preview mode). */
|
|
24
|
+
shadow?: boolean;
|
|
25
|
+
}
|
|
26
|
+
export interface ListOptions {
|
|
27
|
+
/** Full-text search in the records. */
|
|
28
|
+
q?: string;
|
|
29
|
+
/** At most 200; 50 by default. */
|
|
30
|
+
limit?: number;
|
|
31
|
+
offset?: number;
|
|
32
|
+
}
|
|
33
|
+
/** The app as Orbi knows it (`GET /v1/app`). */
|
|
34
|
+
export interface OrbiApp {
|
|
35
|
+
clientId: string;
|
|
36
|
+
name: string;
|
|
37
|
+
title: string;
|
|
38
|
+
/** `live` for the app's own key, `dev` for a developer's key (preview mode). */
|
|
39
|
+
mode: 'live' | 'dev';
|
|
40
|
+
/** Whether the approved manifest has sign-in with Orbi. */
|
|
41
|
+
signIn: boolean;
|
|
42
|
+
}
|
|
43
|
+
/** A field to read from a document (plan 33.9). */
|
|
44
|
+
export interface ExtractField {
|
|
45
|
+
/** 1-64 letters, digits or `_`; the key of the answer. */
|
|
46
|
+
name: string;
|
|
47
|
+
type?: 'string' | 'number' | 'date' | 'boolean' | 'enum';
|
|
48
|
+
/** What the field means; the model reads it. */
|
|
49
|
+
description?: string;
|
|
50
|
+
/** The allowed values of an `enum` field. */
|
|
51
|
+
options?: string[];
|
|
52
|
+
/** A required field left empty marks the result for review. */
|
|
53
|
+
required?: boolean;
|
|
54
|
+
}
|
|
55
|
+
export interface ExtractOptions {
|
|
56
|
+
/** The document: PDF, PNG, JPEG, WebP, GIF, DOCX, XLSX or plain text, at most 10 MB. */
|
|
57
|
+
file: Blob | Uint8Array;
|
|
58
|
+
/** The file's name; its type is taken from `mimeType`, else from a Blob. */
|
|
59
|
+
filename?: string;
|
|
60
|
+
mimeType?: string;
|
|
61
|
+
fields: ExtractField[];
|
|
62
|
+
/** A field below this confidence marks the result for review; 0.8 by default. */
|
|
63
|
+
reviewBelow?: number;
|
|
64
|
+
}
|
|
65
|
+
export interface ExtractResult<T extends Record<string, unknown> = Record<string, unknown>> {
|
|
66
|
+
/** Per field: the value (null when not found) and how sure the model is, 0 to 1. */
|
|
67
|
+
fields: {
|
|
68
|
+
[K in keyof T]: {
|
|
69
|
+
value: T[K] | null;
|
|
70
|
+
confidence: number;
|
|
71
|
+
};
|
|
72
|
+
};
|
|
73
|
+
/** True when a person should look before the values are used. */
|
|
74
|
+
needsReview: boolean;
|
|
75
|
+
model: string;
|
|
76
|
+
}
|
|
77
|
+
/** An error Orbi answered with: a stable `code`, the HTTP status and a diagnostic message. */
|
|
78
|
+
export declare class OrbiError extends Error {
|
|
79
|
+
readonly code: string;
|
|
80
|
+
readonly status: number;
|
|
81
|
+
readonly params: Record<string, string>;
|
|
82
|
+
constructor(code: string, status: number, message: string, params?: Record<string, string>);
|
|
83
|
+
}
|
|
84
|
+
/**
|
|
85
|
+
* A person signed in with Orbi (plan 33.7). Keep it on the server, in the person's session: it
|
|
86
|
+
* holds the refresh token and the private DPoP key every token of it is bound to. It is plain
|
|
87
|
+
* JSON, so it can be stored as is; `asUser` renews it in place and calls `onRefresh`.
|
|
88
|
+
*/
|
|
89
|
+
export interface OrbiUserSession {
|
|
90
|
+
accessToken: string;
|
|
91
|
+
refreshToken: string;
|
|
92
|
+
/** Epoch milliseconds when the access token ends. */
|
|
93
|
+
expiresAt: number;
|
|
94
|
+
/** The private DPoP key as a JWK (ES256). */
|
|
95
|
+
dpopKey: JsonWebKey;
|
|
96
|
+
}
|
|
97
|
+
export interface OrbiUser {
|
|
98
|
+
/** The person's Orbi id; match people by issuer + sub, never by email. */
|
|
99
|
+
sub: string;
|
|
100
|
+
name?: string;
|
|
101
|
+
email?: string;
|
|
102
|
+
}
|
|
103
|
+
export interface SignInStart {
|
|
104
|
+
url: string;
|
|
105
|
+
/** Store these with the person's session until the return: the verifier proves the code is yours. */
|
|
106
|
+
codeVerifier: string;
|
|
107
|
+
state: string;
|
|
108
|
+
nonce: string;
|
|
109
|
+
}
|
|
110
|
+
export declare function createOrbiClient(options?: OrbiClientOptions): {
|
|
111
|
+
/** The app as Orbi knows it: its client id, name and whether its key is live or a developer's. */
|
|
112
|
+
app(): Promise<OrbiApp>;
|
|
113
|
+
/** A collection the app's approved manifest names, read and written as the app itself. */
|
|
114
|
+
collection<T = Record<string, unknown>>(name: string): {
|
|
115
|
+
list(opts?: ListOptions): Promise<RecordPage<T>>;
|
|
116
|
+
get(number: number): Promise<OrbiRecord<T>>;
|
|
117
|
+
/**
|
|
118
|
+
* Adds a record. With a development key it lands in the developer's shadow of the
|
|
119
|
+
* collection, never in the real one (preview mode).
|
|
120
|
+
*/
|
|
121
|
+
create(data: Partial<T> & Record<string, unknown>): Promise<OrbiRecord<T>>;
|
|
122
|
+
/** Changes the given fields of a record; the others stay. */
|
|
123
|
+
update(number: number, data: Partial<T> & Record<string, unknown>): Promise<OrbiRecord<T>>;
|
|
124
|
+
};
|
|
125
|
+
/**
|
|
126
|
+
* Document extraction (plan 33.9): a file and the fields to read, a value and a confidence per
|
|
127
|
+
* field back. With no credit left it throws `app.extract_no_credits`: keep the record for a
|
|
128
|
+
* person. The file is not kept by Orbi.
|
|
129
|
+
*/
|
|
130
|
+
extract: <T extends Record<string, unknown> = Record<string, unknown>>(opts: ExtractOptions, retried?: boolean) => Promise<ExtractResult<T>>;
|
|
131
|
+
/** Sign-in with Orbi (plan 33.7): the authorization code flow with PKCE and DPoP. */
|
|
132
|
+
signIn: {
|
|
133
|
+
/** The address to send the person to, and what to keep until they come back. */
|
|
134
|
+
start(opts: {
|
|
135
|
+
redirectUri: string;
|
|
136
|
+
state?: string;
|
|
137
|
+
}): Promise<SignInStart>;
|
|
138
|
+
/** Trades the code from the return address for the person and their session. */
|
|
139
|
+
finish(opts: {
|
|
140
|
+
code: string;
|
|
141
|
+
redirectUri: string;
|
|
142
|
+
codeVerifier: string;
|
|
143
|
+
}): Promise<{
|
|
144
|
+
user: OrbiUser;
|
|
145
|
+
session: OrbiUserSession;
|
|
146
|
+
}>;
|
|
147
|
+
};
|
|
148
|
+
/**
|
|
149
|
+
* The client on behalf of a signed-in person: every call carries a DPoP proof, reaches only
|
|
150
|
+
* what both the app and the person may, and renews the session before it runs out.
|
|
151
|
+
*/
|
|
152
|
+
asUser(session: OrbiUserSession, opts?: {
|
|
153
|
+
onRefresh?: (session: OrbiUserSession) => void | Promise<void>;
|
|
154
|
+
}): {
|
|
155
|
+
collection<T = Record<string, unknown>>(name: string): {
|
|
156
|
+
list(opts?: ListOptions): Promise<RecordPage<T>>;
|
|
157
|
+
get(number: number): Promise<OrbiRecord<T>>;
|
|
158
|
+
/**
|
|
159
|
+
* Adds a record. With a development key it lands in the developer's shadow of the
|
|
160
|
+
* collection, never in the real one (preview mode).
|
|
161
|
+
*/
|
|
162
|
+
create(data: Partial<T> & Record<string, unknown>): Promise<OrbiRecord<T>>;
|
|
163
|
+
/** Changes the given fields of a record; the others stay. */
|
|
164
|
+
update(number: number, data: Partial<T> & Record<string, unknown>): Promise<OrbiRecord<T>>;
|
|
165
|
+
};
|
|
166
|
+
/** What the app may know of the person, as its approved manifest names it. */
|
|
167
|
+
me(): Promise<OrbiUser>;
|
|
168
|
+
};
|
|
169
|
+
};
|
|
170
|
+
export type OrbiClient = ReturnType<typeof createOrbiClient>;
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,233 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
// Orbi SDK for TypeScript (plan 33.9). A thin client of the public API: it trades the app's key
|
|
3
|
+
// for a short-lived access token, renews it before it runs out and turns Orbi's error codes into
|
|
4
|
+
// `OrbiError`. The permissions are enforced by Orbi, not here (33.4): a call outside the app's
|
|
5
|
+
// approved manifest comes back as `app.permission_missing` with the collection's name.
|
|
6
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
7
|
+
exports.OrbiError = void 0;
|
|
8
|
+
exports.createOrbiClient = createOrbiClient;
|
|
9
|
+
/** An error Orbi answered with: a stable `code`, the HTTP status and a diagnostic message. */
|
|
10
|
+
class OrbiError extends Error {
|
|
11
|
+
code;
|
|
12
|
+
status;
|
|
13
|
+
params;
|
|
14
|
+
constructor(code, status, message, params = {}) {
|
|
15
|
+
super(message);
|
|
16
|
+
this.code = code;
|
|
17
|
+
this.status = status;
|
|
18
|
+
this.params = params;
|
|
19
|
+
this.name = 'OrbiError';
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
exports.OrbiError = OrbiError;
|
|
23
|
+
// Renew a little before the token ends, so a call never leaves with a token about to die.
|
|
24
|
+
const RENEW_MARGIN_MS = 30_000;
|
|
25
|
+
// Read without Node's types, so the package also builds for the browser.
|
|
26
|
+
function env(name) {
|
|
27
|
+
const proc = globalThis.process;
|
|
28
|
+
return proc?.env?.[name];
|
|
29
|
+
}
|
|
30
|
+
const b64url = (bytes) => {
|
|
31
|
+
const arr = bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes);
|
|
32
|
+
let bin = '';
|
|
33
|
+
for (const b of arr)
|
|
34
|
+
bin += String.fromCharCode(b);
|
|
35
|
+
return btoa(bin).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
|
|
36
|
+
};
|
|
37
|
+
const randomId = (n = 32) => b64url(globalThis.crypto.getRandomValues(new Uint8Array(n)));
|
|
38
|
+
const sha256 = async (text) => b64url(await globalThis.crypto.subtle.digest('SHA-256', new TextEncoder().encode(text)));
|
|
39
|
+
const jsonPart = (value) => b64url(new TextEncoder().encode(JSON.stringify(value)));
|
|
40
|
+
/** A DPoP proof (RFC 9449) signed with the session's key. */
|
|
41
|
+
async function dpopProof(privateJwk, method, url, accessToken) {
|
|
42
|
+
const subtle = globalThis.crypto.subtle;
|
|
43
|
+
const key = await subtle.importKey('jwk', privateJwk, { name: 'ECDSA', namedCurve: 'P-256' }, false, ['sign']);
|
|
44
|
+
const { kty, crv, x, y } = privateJwk;
|
|
45
|
+
const u = new URL(url);
|
|
46
|
+
const header = jsonPart({ typ: 'dpop+jwt', alg: 'ES256', jwk: { kty, crv, x, y } });
|
|
47
|
+
const payload = jsonPart({ htm: method, htu: `${u.protocol}//${u.host}${u.pathname}`, iat: Math.floor(Date.now() / 1000), jti: randomId(16), ...(accessToken ? { ath: await sha256(accessToken) } : {}) });
|
|
48
|
+
const signature = await subtle.sign({ name: 'ECDSA', hash: 'SHA-256' }, key, new TextEncoder().encode(`${header}.${payload}`));
|
|
49
|
+
return `${header}.${payload}.${b64url(signature)}`;
|
|
50
|
+
}
|
|
51
|
+
function createOrbiClient(options = {}) {
|
|
52
|
+
const url = (options.url ?? env('ORBI_URL') ?? '').replace(/\/+$/, '');
|
|
53
|
+
const publicUrl = (options.publicUrl ?? env('ORBI_PUBLIC_URL') ?? url).replace(/\/+$/, '');
|
|
54
|
+
const key = options.key ?? env('ORBI_APP_KEY') ?? '';
|
|
55
|
+
const doFetch = options.fetch ?? fetch;
|
|
56
|
+
if (!url)
|
|
57
|
+
throw new OrbiError('sdk.url_missing', 0, 'Set ORBI_URL or pass { url } to createOrbiClient');
|
|
58
|
+
if (!key)
|
|
59
|
+
throw new OrbiError('sdk.key_missing', 0, 'Set ORBI_APP_KEY or pass { key } to createOrbiClient');
|
|
60
|
+
let token = null;
|
|
61
|
+
let pending = null;
|
|
62
|
+
async function readError(res) {
|
|
63
|
+
const body = (await res.json().catch(() => ({})));
|
|
64
|
+
const message = Array.isArray(body.message) ? body.message.join('; ') : (body.message ?? res.statusText);
|
|
65
|
+
return new OrbiError(body.code ?? `http.${res.status}`, res.status, message, body.params ?? {});
|
|
66
|
+
}
|
|
67
|
+
async function postToken(body, headers = {}) {
|
|
68
|
+
const res = await doFetch(`${url}/v1/oauth/token`, { method: 'POST', headers: { 'Content-Type': 'application/json', ...headers }, body: JSON.stringify({ ...body, client_secret: key }) });
|
|
69
|
+
if (!res.ok)
|
|
70
|
+
throw await readError(res);
|
|
71
|
+
return res.json();
|
|
72
|
+
}
|
|
73
|
+
async function fetchToken() {
|
|
74
|
+
const body = (await postToken({ grant_type: 'client_credentials' }));
|
|
75
|
+
token = { value: body.access_token, renewAt: Date.now() + body.expires_in * 1000 - RENEW_MARGIN_MS };
|
|
76
|
+
return body.access_token;
|
|
77
|
+
}
|
|
78
|
+
async function accessToken() {
|
|
79
|
+
if (token && Date.now() < token.renewAt)
|
|
80
|
+
return token.value;
|
|
81
|
+
// Calls made at the same moment share one exchange.
|
|
82
|
+
pending ??= fetchToken().finally(() => {
|
|
83
|
+
pending = null;
|
|
84
|
+
});
|
|
85
|
+
return pending;
|
|
86
|
+
}
|
|
87
|
+
const appAuth = async () => ({ Authorization: `Bearer ${await accessToken()}` });
|
|
88
|
+
async function call(auth, path, method = 'GET', body, onUnauthorized, retried = false) {
|
|
89
|
+
const target = `${url}${path}`;
|
|
90
|
+
const headers = await auth(method, target);
|
|
91
|
+
if (body !== undefined)
|
|
92
|
+
headers['Content-Type'] = 'application/json';
|
|
93
|
+
const res = await doFetch(target, { method, headers, ...(body !== undefined ? { body: JSON.stringify(body) } : {}) });
|
|
94
|
+
// A token revoked or expired on Orbi's side is renewed once; a second refusal is real.
|
|
95
|
+
if (res.status === 401 && !retried) {
|
|
96
|
+
(onUnauthorized ?? (() => (token = null)))();
|
|
97
|
+
return call(auth, path, method, body, onUnauthorized, true);
|
|
98
|
+
}
|
|
99
|
+
if (!res.ok)
|
|
100
|
+
throw await readError(res);
|
|
101
|
+
return (await res.json());
|
|
102
|
+
}
|
|
103
|
+
function collectionOf(auth, name, onUnauthorized) {
|
|
104
|
+
const base = `/v1/collections/${encodeURIComponent(name)}/records`;
|
|
105
|
+
const run = (path, method, body) => call(auth, path, method, body, onUnauthorized);
|
|
106
|
+
return {
|
|
107
|
+
list(opts = {}) {
|
|
108
|
+
const query = new URLSearchParams();
|
|
109
|
+
if (opts.q)
|
|
110
|
+
query.set('q', opts.q);
|
|
111
|
+
if (opts.limit !== undefined)
|
|
112
|
+
query.set('limit', String(opts.limit));
|
|
113
|
+
if (opts.offset !== undefined)
|
|
114
|
+
query.set('offset', String(opts.offset));
|
|
115
|
+
const qs = query.toString();
|
|
116
|
+
return run(qs ? `${base}?${qs}` : base);
|
|
117
|
+
},
|
|
118
|
+
get(number) {
|
|
119
|
+
return run(`${base}/${number}`);
|
|
120
|
+
},
|
|
121
|
+
/**
|
|
122
|
+
* Adds a record. With a development key it lands in the developer's shadow of the
|
|
123
|
+
* collection, never in the real one (preview mode).
|
|
124
|
+
*/
|
|
125
|
+
create(data) {
|
|
126
|
+
return run(base, 'POST', { data });
|
|
127
|
+
},
|
|
128
|
+
/** Changes the given fields of a record; the others stay. */
|
|
129
|
+
update(number, data) {
|
|
130
|
+
return run(`${base}/${number}`, 'PATCH', { data });
|
|
131
|
+
},
|
|
132
|
+
};
|
|
133
|
+
}
|
|
134
|
+
/** Reads fields from a document with a model; needs `orbi.extraction` in the manifest. */
|
|
135
|
+
async function extract(opts, retried = false) {
|
|
136
|
+
const target = `${url}/v1/extract`;
|
|
137
|
+
const form = new FormData();
|
|
138
|
+
const type = opts.mimeType ?? (opts.file instanceof Blob ? opts.file.type : '') ?? '';
|
|
139
|
+
const blob = opts.file instanceof Blob ? (opts.mimeType ? new Blob([opts.file], { type: opts.mimeType }) : opts.file) : new Blob([new Uint8Array(opts.file)], { type: type || 'application/octet-stream' });
|
|
140
|
+
form.set('file', blob, opts.filename ?? 'document');
|
|
141
|
+
form.set('fields', JSON.stringify(opts.fields));
|
|
142
|
+
if (opts.reviewBelow !== undefined)
|
|
143
|
+
form.set('reviewBelow', String(opts.reviewBelow));
|
|
144
|
+
const res = await doFetch(target, { method: 'POST', headers: await appAuth('POST', target), body: form });
|
|
145
|
+
if (res.status === 401 && !retried) {
|
|
146
|
+
token = null;
|
|
147
|
+
return extract(opts, true);
|
|
148
|
+
}
|
|
149
|
+
if (!res.ok)
|
|
150
|
+
throw await readError(res);
|
|
151
|
+
return (await res.json());
|
|
152
|
+
}
|
|
153
|
+
let clientId = null;
|
|
154
|
+
return {
|
|
155
|
+
/** The app as Orbi knows it: its client id, name and whether its key is live or a developer's. */
|
|
156
|
+
app() {
|
|
157
|
+
return call(appAuth, '/v1/app');
|
|
158
|
+
},
|
|
159
|
+
/** A collection the app's approved manifest names, read and written as the app itself. */
|
|
160
|
+
collection(name) {
|
|
161
|
+
return collectionOf(appAuth, name);
|
|
162
|
+
},
|
|
163
|
+
/**
|
|
164
|
+
* Document extraction (plan 33.9): a file and the fields to read, a value and a confidence per
|
|
165
|
+
* field back. With no credit left it throws `app.extract_no_credits`: keep the record for a
|
|
166
|
+
* person. The file is not kept by Orbi.
|
|
167
|
+
*/
|
|
168
|
+
extract,
|
|
169
|
+
/** Sign-in with Orbi (plan 33.7): the authorization code flow with PKCE and DPoP. */
|
|
170
|
+
signIn: {
|
|
171
|
+
/** The address to send the person to, and what to keep until they come back. */
|
|
172
|
+
async start(opts) {
|
|
173
|
+
clientId ??= (await call(appAuth, '/v1/app')).clientId;
|
|
174
|
+
const codeVerifier = randomId(32);
|
|
175
|
+
const state = opts.state ?? randomId(16);
|
|
176
|
+
const nonce = randomId(16);
|
|
177
|
+
const q = new URLSearchParams({ client_id: clientId, redirect_uri: opts.redirectUri, response_type: 'code', code_challenge: await sha256(codeVerifier), code_challenge_method: 'S256', state, nonce });
|
|
178
|
+
return { url: `${publicUrl}/v1/oauth/authorize?${q.toString()}`, codeVerifier, state, nonce };
|
|
179
|
+
},
|
|
180
|
+
/** Trades the code from the return address for the person and their session. */
|
|
181
|
+
async finish(opts) {
|
|
182
|
+
const pair = await globalThis.crypto.subtle.generateKey({ name: 'ECDSA', namedCurve: 'P-256' }, true, ['sign', 'verify']);
|
|
183
|
+
const dpopKey = await globalThis.crypto.subtle.exportKey('jwk', pair.privateKey);
|
|
184
|
+
const tokenUrl = `${url}/v1/oauth/token`;
|
|
185
|
+
const body = (await postToken({ grant_type: 'authorization_code', code: opts.code, redirect_uri: opts.redirectUri, code_verifier: opts.codeVerifier }, { DPoP: await dpopProof(dpopKey, 'POST', tokenUrl) }));
|
|
186
|
+
const claims = JSON.parse(new TextDecoder().decode(Uint8Array.from(atob(body.id_token.split('.')[1].replace(/-/g, '+').replace(/_/g, '/')), (c) => c.charCodeAt(0))));
|
|
187
|
+
return {
|
|
188
|
+
user: { sub: claims.sub, ...(claims.name ? { name: claims.name } : {}), ...(claims.email ? { email: claims.email } : {}) },
|
|
189
|
+
session: { accessToken: body.access_token, refreshToken: body.refresh_token, expiresAt: Date.now() + body.expires_in * 1000, dpopKey },
|
|
190
|
+
};
|
|
191
|
+
},
|
|
192
|
+
},
|
|
193
|
+
/**
|
|
194
|
+
* The client on behalf of a signed-in person: every call carries a DPoP proof, reaches only
|
|
195
|
+
* what both the app and the person may, and renews the session before it runs out.
|
|
196
|
+
*/
|
|
197
|
+
asUser(session, opts = {}) {
|
|
198
|
+
let refreshing = null;
|
|
199
|
+
const refresh = async () => {
|
|
200
|
+
const tokenUrl = `${url}/v1/oauth/token`;
|
|
201
|
+
const body = (await postToken({ grant_type: 'refresh_token', refresh_token: session.refreshToken }, { DPoP: await dpopProof(session.dpopKey, 'POST', tokenUrl) }));
|
|
202
|
+
session.accessToken = body.access_token;
|
|
203
|
+
session.refreshToken = body.refresh_token;
|
|
204
|
+
session.expiresAt = Date.now() + body.expires_in * 1000;
|
|
205
|
+
await opts.onRefresh?.(session);
|
|
206
|
+
};
|
|
207
|
+
const fresh = async () => {
|
|
208
|
+
if (Date.now() < session.expiresAt - RENEW_MARGIN_MS)
|
|
209
|
+
return;
|
|
210
|
+
refreshing ??= refresh().finally(() => {
|
|
211
|
+
refreshing = null;
|
|
212
|
+
});
|
|
213
|
+
await refreshing;
|
|
214
|
+
};
|
|
215
|
+
const userAuth = async (method, target) => {
|
|
216
|
+
await fresh();
|
|
217
|
+
return { Authorization: `DPoP ${session.accessToken}`, DPoP: await dpopProof(session.dpopKey, method, target, session.accessToken) };
|
|
218
|
+
};
|
|
219
|
+
const expire = () => {
|
|
220
|
+
session.expiresAt = 0;
|
|
221
|
+
};
|
|
222
|
+
return {
|
|
223
|
+
collection(name) {
|
|
224
|
+
return collectionOf(userAuth, name, expire);
|
|
225
|
+
},
|
|
226
|
+
/** What the app may know of the person, as its approved manifest names it. */
|
|
227
|
+
me() {
|
|
228
|
+
return call(userAuth, '/v1/oauth/userinfo', 'GET', undefined, expire);
|
|
229
|
+
},
|
|
230
|
+
};
|
|
231
|
+
},
|
|
232
|
+
};
|
|
233
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,33 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@orbiworkspace/sdk",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "TypeScript SDK for Orbi's public API: an app reads Orbi's data with its approved permissions.",
|
|
5
|
+
"license": "Apache-2.0",
|
|
6
|
+
"homepage": "https://orbiwork.space",
|
|
7
|
+
"keywords": [
|
|
8
|
+
"orbi",
|
|
9
|
+
"sdk"
|
|
10
|
+
],
|
|
11
|
+
"engines": {
|
|
12
|
+
"node": ">=20"
|
|
13
|
+
},
|
|
14
|
+
"publishConfig": {
|
|
15
|
+
"access": "public"
|
|
16
|
+
},
|
|
17
|
+
"main": "./dist/index.js",
|
|
18
|
+
"types": "./dist/index.d.ts",
|
|
19
|
+
"files": [
|
|
20
|
+
"dist",
|
|
21
|
+
"README.md"
|
|
22
|
+
],
|
|
23
|
+
"scripts": {
|
|
24
|
+
"build": "tsc -p tsconfig.json",
|
|
25
|
+
"typecheck": "tsc --noEmit -p tsconfig.json",
|
|
26
|
+
"lint": "echo \"no-op\"",
|
|
27
|
+
"test": "vitest run"
|
|
28
|
+
},
|
|
29
|
+
"devDependencies": {
|
|
30
|
+
"typescript": "^5.7.2",
|
|
31
|
+
"vitest": "^4.1.10"
|
|
32
|
+
}
|
|
33
|
+
}
|