@seletech/sele 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/CHANGELOG.md +5 -0
- package/LICENSE +202 -0
- package/README.md +89 -2
- package/dist/cjs/ai.d.ts +37 -0
- package/dist/cjs/ai.js +15 -0
- package/dist/cjs/auth.d.ts +61 -0
- package/dist/cjs/auth.js +62 -0
- package/dist/cjs/db.d.ts +29 -0
- package/dist/cjs/db.js +18 -0
- package/dist/cjs/events.d.ts +51 -0
- package/dist/cjs/events.js +41 -0
- package/dist/cjs/http.d.ts +33 -0
- package/dist/cjs/http.js +59 -0
- package/dist/cjs/index.d.ts +7 -0
- package/dist/cjs/index.js +22 -0
- package/dist/cjs/package.json +1 -0
- package/dist/cjs/storage.d.ts +41 -0
- package/dist/cjs/storage.js +23 -0
- package/dist/cjs/supabase.d.ts +18 -0
- package/dist/cjs/supabase.js +52 -0
- package/dist/esm/ai.d.ts +37 -0
- package/dist/esm/ai.js +11 -0
- package/dist/esm/auth.d.ts +61 -0
- package/dist/esm/auth.js +56 -0
- package/dist/esm/db.d.ts +29 -0
- package/dist/esm/db.js +14 -0
- package/dist/esm/events.d.ts +51 -0
- package/dist/esm/events.js +36 -0
- package/dist/esm/http.d.ts +33 -0
- package/dist/esm/http.js +53 -0
- package/dist/esm/index.d.ts +7 -0
- package/dist/esm/index.js +7 -0
- package/dist/esm/storage.d.ts +41 -0
- package/dist/esm/storage.js +19 -0
- package/dist/esm/supabase.d.ts +18 -0
- package/dist/esm/supabase.js +49 -0
- package/package.json +27 -4
package/CHANGELOG.md
ADDED
package/LICENSE
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
http://www.apache.org/licenses/
|
|
5
|
+
|
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
7
|
+
|
|
8
|
+
1. Definitions.
|
|
9
|
+
|
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
14
|
+
the copyright owner that is granting the License.
|
|
15
|
+
|
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
17
|
+
other entities that control, are controlled by, or are under common
|
|
18
|
+
control with that entity. For the purposes of this definition,
|
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
20
|
+
direction or management of such entity, whether by contract or
|
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
25
|
+
exercising permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
28
|
+
including but not limited to software source code, documentation
|
|
29
|
+
source, and configuration files.
|
|
30
|
+
|
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
|
32
|
+
transformation or translation of a Source form, including but
|
|
33
|
+
not limited to compiled object code, generated documentation,
|
|
34
|
+
and conversions to other media types.
|
|
35
|
+
|
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
37
|
+
Object form, made available under the License, as indicated by a
|
|
38
|
+
copyright notice that is included in or attached to the work
|
|
39
|
+
(an example is provided in the Appendix below).
|
|
40
|
+
|
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
47
|
+
the Work and Derivative Works thereof.
|
|
48
|
+
|
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
|
50
|
+
the original version of the Work and any modifications or additions
|
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
52
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
62
|
+
|
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
65
|
+
subsequently incorporated within the Work.
|
|
66
|
+
|
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
|
73
|
+
|
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
79
|
+
where such license applies only to those patent claims licensable
|
|
80
|
+
by such Contributor that are necessarily infringed by their
|
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
83
|
+
institute patent litigation against any entity (including a
|
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
86
|
+
or contributory patent infringement, then any patent licenses
|
|
87
|
+
granted to You under this License for that Work shall terminate
|
|
88
|
+
as of the date such litigation is filed.
|
|
89
|
+
|
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
92
|
+
modifications, and in Source or Object form, provided that You
|
|
93
|
+
meet the following conditions:
|
|
94
|
+
|
|
95
|
+
(a) You must give any other recipients of the Work or
|
|
96
|
+
Derivative Works a copy of this License; and
|
|
97
|
+
|
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
|
99
|
+
stating that You changed the files; and
|
|
100
|
+
|
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
|
103
|
+
attribution notices from the Source form of the Work,
|
|
104
|
+
excluding those notices that do not pertain to any part of
|
|
105
|
+
the Derivative Works; and
|
|
106
|
+
|
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
|
109
|
+
include a readable copy of the attribution notices contained
|
|
110
|
+
within such NOTICE file, excluding those notices that do not
|
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
|
112
|
+
of the following places: within a NOTICE text file distributed
|
|
113
|
+
as part of the Derivative Works; within the Source form or
|
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
|
115
|
+
within a display generated by the Derivative Works, if and
|
|
116
|
+
wherever such third-party notices normally appear. The contents
|
|
117
|
+
of the NOTICE file are for informational purposes only and
|
|
118
|
+
do not modify the License. You may add Your own attribution
|
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
121
|
+
that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
176
|
+
|
|
177
|
+
END OF TERMS AND CONDITIONS
|
|
178
|
+
|
|
179
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
180
|
+
|
|
181
|
+
To apply the Apache License to your work, attach the following
|
|
182
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
183
|
+
replaced with your own identifying information. (Don't include
|
|
184
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
185
|
+
comment syntax for the file format. We also recommend that a
|
|
186
|
+
file or class name and description of purpose be included on the
|
|
187
|
+
same "printed page" as the copyright notice for easier
|
|
188
|
+
identification within third-party archives.
|
|
189
|
+
|
|
190
|
+
Copyright [yyyy] [name of copyright owner]
|
|
191
|
+
|
|
192
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
193
|
+
you may not use this file except in compliance with the License.
|
|
194
|
+
You may obtain a copy of the License at
|
|
195
|
+
|
|
196
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
197
|
+
|
|
198
|
+
Unless required by applicable law or agreed to in writing, software
|
|
199
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
200
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
201
|
+
See the License for the specific language governing permissions and
|
|
202
|
+
limitations under the License.
|
package/README.md
CHANGED
|
@@ -1,3 +1,90 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @seletech/sele
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Release candidate **0.1.0**. Licensed under [Apache-2.0](LICENSE). See [release notes](CHANGELOG.md).
|
|
4
|
+
|
|
5
|
+
TypeScript client for **Continue with SeleID** (OIDC + PKCE), **SeleStorage**, **SeleBase**, events (webhooks, mail, push) and **SeleAI**.
|
|
6
|
+
ESM and CommonJS builds with types, zero runtime dependencies, works on Node 20+, edge runtimes and browsers (sign-in helpers only in browsers: never put an API key in client code).
|
|
7
|
+
|
|
8
|
+
> **Not published.** Until the founder approves publishing, install from a checkout: `npm install ./sdks/typescript` after `npm run build`.
|
|
9
|
+
|
|
10
|
+
## Install (after publishing)
|
|
11
|
+
|
|
12
|
+
```bash
|
|
13
|
+
npm install @seletech/sele
|
|
14
|
+
```
|
|
15
|
+
|
|
16
|
+
## Sign in with SeleID (PKCE)
|
|
17
|
+
|
|
18
|
+
```ts
|
|
19
|
+
import { SeleIdAuth, createPkce, buildAuthorizeUrl } from '@seletech/sele';
|
|
20
|
+
|
|
21
|
+
const auth = new SeleIdAuth({ clientId: 'YOUR_CLIENT_ID' }); // public client: no secret
|
|
22
|
+
|
|
23
|
+
// 1. Send the person to SeleID.
|
|
24
|
+
const { codeVerifier, codeChallenge } = await createPkce();
|
|
25
|
+
const { url, state, nonce } = buildAuthorizeUrl({ clientId: 'YOUR_CLIENT_ID', redirectUri: 'https://app.example.com/callback', codeChallenge });
|
|
26
|
+
// Save { codeVerifier, state, nonce } in the session, then redirect to `url`.
|
|
27
|
+
|
|
28
|
+
// 2. On the redirect back: check `state`, then exchange the code.
|
|
29
|
+
const tokens = await auth.exchangeCode({ code, redirectUri: 'https://app.example.com/callback', codeVerifier });
|
|
30
|
+
const user = await auth.userInfo(tokens.access_token);
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
## Storage
|
|
34
|
+
|
|
35
|
+
```ts
|
|
36
|
+
import { SeleStorage } from '@seletech/sele';
|
|
37
|
+
const storage = new SeleStorage({ apiKey: process.env.SELESTORAGE_KEY });
|
|
38
|
+
await storage.put('reports/q3.txt', 'hello', 'text/plain');
|
|
39
|
+
console.log(await storage.getText('reports/q3.txt'));
|
|
40
|
+
const { url } = await storage.signedUrl({ method: 'PUT', key: 'uploads/photo.jpg', expiresIn: 300 }); // relative to the storage base URL
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
## SQL
|
|
44
|
+
|
|
45
|
+
```ts
|
|
46
|
+
import { SeleDb } from '@seletech/sele';
|
|
47
|
+
const db = new SeleDb({ apiKey: process.env.SELEBASE_KEY });
|
|
48
|
+
await db.createDatabase('app');
|
|
49
|
+
await db.query('app', 'CREATE TABLE IF NOT EXISTS notes (id INTEGER PRIMARY KEY, title TEXT)');
|
|
50
|
+
await db.query('app', 'INSERT INTO notes (title) VALUES (?)', ['Hello']); // always use params
|
|
51
|
+
console.log(await db.query('app', 'SELECT * FROM notes'));
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
## Webhooks, mail, push
|
|
55
|
+
|
|
56
|
+
```ts
|
|
57
|
+
import { SeleEvents, verifyWebhook } from '@seletech/sele';
|
|
58
|
+
const events = new SeleEvents({ apiKey: process.env.SELE_KEY });
|
|
59
|
+
const { secret } = await events.createWebhookEndpoint('https://app.example.com/hooks/sele', ['order.created']); // secret shown once
|
|
60
|
+
await events.sendMail({ from: 'hello@yourdomain.com', to: 'ada@example.com', subject: 'Welcome', text: 'Hi Ada' });
|
|
61
|
+
|
|
62
|
+
// In your receiver, with the RAW body:
|
|
63
|
+
const ok = await verifyWebhook(secret, rawBody, request.headers.get('seleid-signature'));
|
|
64
|
+
```
|
|
65
|
+
|
|
66
|
+
## AI
|
|
67
|
+
|
|
68
|
+
```ts
|
|
69
|
+
import { SeleAi, SeleError } from '@seletech/sele';
|
|
70
|
+
const ai = new SeleAi({ apiKey: process.env.SELEAI_KEY });
|
|
71
|
+
try {
|
|
72
|
+
const r = await ai.chat({ model: 'MODEL_ID', messages: [{ role: 'user', content: 'Say hello' }], maxTokens: 64 }); // list ids with ai.models()
|
|
73
|
+
console.log(r.message.content);
|
|
74
|
+
} catch (e) {
|
|
75
|
+
if (e instanceof SeleError && e.code === 'spend_cap_reached') console.log('Cap reached');
|
|
76
|
+
}
|
|
77
|
+
```
|
|
78
|
+
|
|
79
|
+
## Errors
|
|
80
|
+
|
|
81
|
+
Every non-2xx response throws `SeleError` with `status`, `code` (machine readable), `message` and `requestId` when present. Calls time out after 15 seconds (`timeoutMs`). Base URLs can be overridden with `baseUrl`; pass `fetch` to supply your own transport.
|
|
82
|
+
|
|
83
|
+
## Develop
|
|
84
|
+
|
|
85
|
+
```bash
|
|
86
|
+
npm test # tests against mocked HTTP
|
|
87
|
+
npm run build # dist/esm + dist/cjs with .d.ts (uses the repo's TypeScript)
|
|
88
|
+
```
|
|
89
|
+
|
|
90
|
+
API reference: https://seleid.dev/docs/api
|
package/dist/cjs/ai.d.ts
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import { type ClientOptions } from './http.ts';
|
|
2
|
+
export interface ChatMessage {
|
|
3
|
+
role: 'system' | 'user' | 'assistant';
|
|
4
|
+
content: string;
|
|
5
|
+
}
|
|
6
|
+
export interface ChatResponse {
|
|
7
|
+
id: string;
|
|
8
|
+
model: string;
|
|
9
|
+
message: {
|
|
10
|
+
role: 'assistant';
|
|
11
|
+
content: string;
|
|
12
|
+
};
|
|
13
|
+
usage: {
|
|
14
|
+
input_tokens: number;
|
|
15
|
+
output_tokens: number;
|
|
16
|
+
attempts: number;
|
|
17
|
+
charge_micro_usd: number;
|
|
18
|
+
};
|
|
19
|
+
}
|
|
20
|
+
export declare class SeleAi {
|
|
21
|
+
private readonly http;
|
|
22
|
+
constructor(o: ClientOptions);
|
|
23
|
+
models(): Promise<{
|
|
24
|
+
models: Array<{
|
|
25
|
+
id: string;
|
|
26
|
+
context_tokens: number;
|
|
27
|
+
max_output_tokens: number;
|
|
28
|
+
}>;
|
|
29
|
+
}>;
|
|
30
|
+
usage(): Promise<Record<string, number>>;
|
|
31
|
+
/** Throws SeleError with code `spend_cap_reached` (HTTP 402) when the cap or credit is used up. */
|
|
32
|
+
chat(r: {
|
|
33
|
+
model: string;
|
|
34
|
+
messages: ChatMessage[];
|
|
35
|
+
maxTokens?: number;
|
|
36
|
+
}): Promise<ChatResponse>;
|
|
37
|
+
}
|
package/dist/cjs/ai.js
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.SeleAi = void 0;
|
|
4
|
+
const http_ts_1 = require("./http.js");
|
|
5
|
+
class SeleAi {
|
|
6
|
+
http;
|
|
7
|
+
constructor(o) { this.http = new http_ts_1.Http({ baseUrl: 'https://api.seleid.dev' }, o); }
|
|
8
|
+
models() { return this.http.json('GET', '/v1/ai/models'); }
|
|
9
|
+
usage() { return this.http.json('GET', '/v1/ai/usage'); }
|
|
10
|
+
/** Throws SeleError with code `spend_cap_reached` (HTTP 402) when the cap or credit is used up. */
|
|
11
|
+
chat(r) {
|
|
12
|
+
return this.http.json('POST', '/v1/ai/chat', { model: r.model, messages: r.messages, max_tokens: r.maxTokens });
|
|
13
|
+
}
|
|
14
|
+
}
|
|
15
|
+
exports.SeleAi = SeleAi;
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
import { type FetchLike } from './http.ts';
|
|
2
|
+
export declare const ISSUER = "https://auth.seleid.dev";
|
|
3
|
+
export interface PkcePair {
|
|
4
|
+
codeVerifier: string;
|
|
5
|
+
codeChallenge: string;
|
|
6
|
+
}
|
|
7
|
+
/** Generates a 64 character verifier and its S256 challenge. */
|
|
8
|
+
export declare function createPkce(): Promise<PkcePair>;
|
|
9
|
+
export interface AuthorizeRequest {
|
|
10
|
+
clientId: string;
|
|
11
|
+
redirectUri: string;
|
|
12
|
+
/** Default: openid profile email. Must include openid. */
|
|
13
|
+
scope?: string;
|
|
14
|
+
codeChallenge: string;
|
|
15
|
+
state?: string;
|
|
16
|
+
nonce?: string;
|
|
17
|
+
issuer?: string;
|
|
18
|
+
}
|
|
19
|
+
export interface AuthorizeResult {
|
|
20
|
+
url: string;
|
|
21
|
+
state: string;
|
|
22
|
+
nonce: string;
|
|
23
|
+
}
|
|
24
|
+
/** Builds the /authorize URL. Store `state`, `nonce` and the verifier with the session; check `state` on return. */
|
|
25
|
+
export declare function buildAuthorizeUrl(r: AuthorizeRequest): AuthorizeResult;
|
|
26
|
+
export interface Tokens {
|
|
27
|
+
access_token: string;
|
|
28
|
+
token_type: 'Bearer';
|
|
29
|
+
expires_in: number;
|
|
30
|
+
refresh_token?: string;
|
|
31
|
+
id_token?: string;
|
|
32
|
+
scope?: string;
|
|
33
|
+
}
|
|
34
|
+
export interface UserInfo {
|
|
35
|
+
sub: string;
|
|
36
|
+
name?: string;
|
|
37
|
+
email?: string;
|
|
38
|
+
email_verified?: boolean;
|
|
39
|
+
}
|
|
40
|
+
export declare class SeleIdAuth {
|
|
41
|
+
private readonly http;
|
|
42
|
+
private readonly o;
|
|
43
|
+
constructor(o: {
|
|
44
|
+
clientId: string;
|
|
45
|
+
clientSecret?: string;
|
|
46
|
+
issuer?: string;
|
|
47
|
+
fetch?: FetchLike;
|
|
48
|
+
});
|
|
49
|
+
private form;
|
|
50
|
+
/** Exchange the `code` from the redirect. Check `state` yourself before calling this. */
|
|
51
|
+
exchangeCode(p: {
|
|
52
|
+
code: string;
|
|
53
|
+
redirectUri: string;
|
|
54
|
+
codeVerifier: string;
|
|
55
|
+
}): Promise<Tokens>;
|
|
56
|
+
/** Refresh tokens rotate: store the new refresh_token from the response. */
|
|
57
|
+
refresh(refreshToken: string): Promise<Tokens>;
|
|
58
|
+
userInfo(accessToken: string): Promise<UserInfo>;
|
|
59
|
+
revoke(token: string): Promise<void>;
|
|
60
|
+
discovery(): Promise<Record<string, unknown>>;
|
|
61
|
+
}
|
package/dist/cjs/auth.js
ADDED
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.SeleIdAuth = exports.ISSUER = void 0;
|
|
4
|
+
exports.createPkce = createPkce;
|
|
5
|
+
exports.buildAuthorizeUrl = buildAuthorizeUrl;
|
|
6
|
+
// Continue with SeleID: authorization code flow with PKCE (S256). Safe for public clients (no secret needed).
|
|
7
|
+
const http_ts_1 = require("./http.js");
|
|
8
|
+
exports.ISSUER = 'https://auth.seleid.dev';
|
|
9
|
+
const b64url = (bytes) => btoa(String.fromCharCode(...bytes)).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
|
|
10
|
+
const random = (n) => b64url(crypto.getRandomValues(new Uint8Array(n)));
|
|
11
|
+
/** Generates a 64 character verifier and its S256 challenge. */
|
|
12
|
+
async function createPkce() {
|
|
13
|
+
const codeVerifier = random(48);
|
|
14
|
+
const digest = new Uint8Array(await crypto.subtle.digest('SHA-256', new TextEncoder().encode(codeVerifier)));
|
|
15
|
+
return { codeVerifier, codeChallenge: b64url(digest) };
|
|
16
|
+
}
|
|
17
|
+
/** Builds the /authorize URL. Store `state`, `nonce` and the verifier with the session; check `state` on return. */
|
|
18
|
+
function buildAuthorizeUrl(r) {
|
|
19
|
+
const scope = r.scope ?? 'openid profile email';
|
|
20
|
+
if (!scope.split(' ').includes('openid'))
|
|
21
|
+
throw new Error('scope must include openid');
|
|
22
|
+
const state = r.state ?? random(24);
|
|
23
|
+
const nonce = r.nonce ?? random(24);
|
|
24
|
+
const u = new URL(`${(r.issuer ?? exports.ISSUER).replace(/\/+$/, '')}/authorize`);
|
|
25
|
+
u.search = new URLSearchParams({ client_id: r.clientId, redirect_uri: r.redirectUri, response_type: 'code', scope, state, nonce, code_challenge: r.codeChallenge, code_challenge_method: 'S256' }).toString();
|
|
26
|
+
return { url: u.toString(), state, nonce };
|
|
27
|
+
}
|
|
28
|
+
class SeleIdAuth {
|
|
29
|
+
http;
|
|
30
|
+
o;
|
|
31
|
+
constructor(o) {
|
|
32
|
+
this.o = o;
|
|
33
|
+
this.http = new http_ts_1.Http({ baseUrl: exports.ISSUER }, { baseUrl: o.issuer, fetch: o.fetch });
|
|
34
|
+
}
|
|
35
|
+
async form(path, params) {
|
|
36
|
+
const res = await this.http.raw('POST', path, { headers: { 'content-type': 'application/x-www-form-urlencoded' }, body: new URLSearchParams(params).toString() });
|
|
37
|
+
return (await res.json());
|
|
38
|
+
}
|
|
39
|
+
/** Exchange the `code` from the redirect. Check `state` yourself before calling this. */
|
|
40
|
+
exchangeCode(p) {
|
|
41
|
+
return this.form('/oauth/token', { grant_type: 'authorization_code', code: p.code, redirect_uri: p.redirectUri, client_id: this.o.clientId, code_verifier: p.codeVerifier, ...(this.o.clientSecret ? { client_secret: this.o.clientSecret } : {}) });
|
|
42
|
+
}
|
|
43
|
+
/** Refresh tokens rotate: store the new refresh_token from the response. */
|
|
44
|
+
refresh(refreshToken) {
|
|
45
|
+
return this.form('/oauth/token', { grant_type: 'refresh_token', refresh_token: refreshToken, client_id: this.o.clientId, ...(this.o.clientSecret ? { client_secret: this.o.clientSecret } : {}) });
|
|
46
|
+
}
|
|
47
|
+
async userInfo(accessToken) {
|
|
48
|
+
const res = await this.http.raw('GET', '/oauth/userinfo', { headers: { authorization: `Bearer ${accessToken}` } });
|
|
49
|
+
return (await res.json());
|
|
50
|
+
}
|
|
51
|
+
async revoke(token) {
|
|
52
|
+
try {
|
|
53
|
+
await this.form('/oauth/revoke', { token, client_id: this.o.clientId });
|
|
54
|
+
}
|
|
55
|
+
catch (e) {
|
|
56
|
+
if (!(e instanceof http_ts_1.SeleError) || e.status >= 500)
|
|
57
|
+
throw e;
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
discovery() { return this.http.json('GET', '/.well-known/openid-configuration'); }
|
|
61
|
+
}
|
|
62
|
+
exports.SeleIdAuth = SeleIdAuth;
|
package/dist/cjs/db.d.ts
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import { type ClientOptions } from './http.ts';
|
|
2
|
+
export type Param = string | number | boolean | null;
|
|
3
|
+
export interface QueryResult {
|
|
4
|
+
[k: string]: unknown;
|
|
5
|
+
}
|
|
6
|
+
export declare class SeleDb {
|
|
7
|
+
private readonly http;
|
|
8
|
+
constructor(o: ClientOptions);
|
|
9
|
+
listDatabases(): Promise<{
|
|
10
|
+
databases: Array<{
|
|
11
|
+
name: string;
|
|
12
|
+
sizeBytes: number;
|
|
13
|
+
createdAt: string;
|
|
14
|
+
}>;
|
|
15
|
+
}>;
|
|
16
|
+
createDatabase(name: string): Promise<{
|
|
17
|
+
name: string;
|
|
18
|
+
createdAt: string;
|
|
19
|
+
}>;
|
|
20
|
+
deleteDatabase(name: string): Promise<{
|
|
21
|
+
deleted: string;
|
|
22
|
+
}>;
|
|
23
|
+
/** One statement per call. Always pass user input through `params`, never string-concatenate it into `sql`. */
|
|
24
|
+
query(database: string, sql: string, params?: Param[]): Promise<QueryResult>;
|
|
25
|
+
schema(database: string): Promise<{
|
|
26
|
+
schema: unknown;
|
|
27
|
+
}>;
|
|
28
|
+
usage(): Promise<Record<string, unknown>>;
|
|
29
|
+
}
|
package/dist/cjs/db.js
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.SeleDb = void 0;
|
|
4
|
+
const http_ts_1 = require("./http.js");
|
|
5
|
+
class SeleDb {
|
|
6
|
+
http;
|
|
7
|
+
constructor(o) { this.http = new http_ts_1.Http({ baseUrl: 'https://api.seleid.dev' }, o); }
|
|
8
|
+
listDatabases() { return this.http.json('GET', '/v1/databases'); }
|
|
9
|
+
createDatabase(name) { return this.http.json('POST', '/v1/databases', { name }); }
|
|
10
|
+
deleteDatabase(name) { return this.http.json('DELETE', `/v1/databases/${encodeURIComponent(name)}`); }
|
|
11
|
+
/** One statement per call. Always pass user input through `params`, never string-concatenate it into `sql`. */
|
|
12
|
+
query(database, sql, params = []) {
|
|
13
|
+
return this.http.json('POST', `/v1/databases/${encodeURIComponent(database)}/query`, { sql, params });
|
|
14
|
+
}
|
|
15
|
+
schema(database) { return this.http.json('GET', `/v1/databases/${encodeURIComponent(database)}/schema`); }
|
|
16
|
+
usage() { return this.http.json('GET', '/v1/usage'); }
|
|
17
|
+
}
|
|
18
|
+
exports.SeleDb = SeleDb;
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
import { type ClientOptions } from './http.ts';
|
|
2
|
+
export declare class SeleEvents {
|
|
3
|
+
private readonly http;
|
|
4
|
+
constructor(o: ClientOptions);
|
|
5
|
+
createWebhookEndpoint(url: string, events: string[]): Promise<{
|
|
6
|
+
id: string;
|
|
7
|
+
secret: string;
|
|
8
|
+
}>;
|
|
9
|
+
listWebhookEndpoints(): Promise<{
|
|
10
|
+
endpoints: unknown[];
|
|
11
|
+
}>;
|
|
12
|
+
deleteWebhookEndpoint(id: string): Promise<{
|
|
13
|
+
deleted: string;
|
|
14
|
+
}>;
|
|
15
|
+
rotateWebhookSecret(id: string): Promise<{
|
|
16
|
+
secret: string;
|
|
17
|
+
}>;
|
|
18
|
+
emit(type: string, data: unknown): Promise<{
|
|
19
|
+
deliveries: unknown[];
|
|
20
|
+
}>;
|
|
21
|
+
deliveries(endpoint?: string): Promise<{
|
|
22
|
+
deliveries: unknown[];
|
|
23
|
+
}>;
|
|
24
|
+
replay(deliveryId: string): Promise<unknown>;
|
|
25
|
+
sendMail(m: {
|
|
26
|
+
from: string;
|
|
27
|
+
to: string;
|
|
28
|
+
subject: string;
|
|
29
|
+
text?: string;
|
|
30
|
+
html?: string;
|
|
31
|
+
}): Promise<unknown>;
|
|
32
|
+
registerDevice(d: {
|
|
33
|
+
userId: string;
|
|
34
|
+
platform: 'android' | 'ios' | 'web';
|
|
35
|
+
token: string;
|
|
36
|
+
}): Promise<unknown>;
|
|
37
|
+
sendPush(p: {
|
|
38
|
+
userId: string;
|
|
39
|
+
title: string;
|
|
40
|
+
body: string;
|
|
41
|
+
data?: unknown;
|
|
42
|
+
}): Promise<unknown>;
|
|
43
|
+
}
|
|
44
|
+
/**
|
|
45
|
+
* Verify a webhook. Pass the RAW request body string, the `seleid-signature` header and your endpoint secret.
|
|
46
|
+
* Header format: t=<unix seconds>,v1=<hex HMAC-SHA256 of "<t>.<body>">. Rejects timestamps older than `toleranceSec` (default 300).
|
|
47
|
+
*/
|
|
48
|
+
export declare function verifyWebhook(secret: string, rawBody: string, header: string | null | undefined, opts?: {
|
|
49
|
+
nowSec?: number;
|
|
50
|
+
toleranceSec?: number;
|
|
51
|
+
}): Promise<boolean>;
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.SeleEvents = void 0;
|
|
4
|
+
exports.verifyWebhook = verifyWebhook;
|
|
5
|
+
const http_ts_1 = require("./http.js");
|
|
6
|
+
class SeleEvents {
|
|
7
|
+
http;
|
|
8
|
+
constructor(o) { this.http = new http_ts_1.Http({ baseUrl: 'https://api.seleid.dev' }, o); }
|
|
9
|
+
createWebhookEndpoint(url, events) { return this.http.json('POST', '/v1/webhooks/endpoints', { url, events }); }
|
|
10
|
+
listWebhookEndpoints() { return this.http.json('GET', '/v1/webhooks/endpoints'); }
|
|
11
|
+
deleteWebhookEndpoint(id) { return this.http.json('DELETE', `/v1/webhooks/endpoints/${encodeURIComponent(id)}`); }
|
|
12
|
+
rotateWebhookSecret(id) { return this.http.json('POST', `/v1/webhooks/endpoints/${encodeURIComponent(id)}/rotate`); }
|
|
13
|
+
emit(type, data) { return this.http.json('POST', '/v1/events', { type, data }); }
|
|
14
|
+
deliveries(endpoint) { return this.http.json('GET', '/v1/webhooks/deliveries', undefined, { endpoint }); }
|
|
15
|
+
replay(deliveryId) { return this.http.json('POST', `/v1/webhooks/deliveries/${encodeURIComponent(deliveryId)}/replay`); }
|
|
16
|
+
sendMail(m) { return this.http.json('POST', '/v1/mail/send', m); }
|
|
17
|
+
registerDevice(d) { return this.http.json('POST', '/v1/push/devices', d); }
|
|
18
|
+
sendPush(p) { return this.http.json('POST', '/v1/push/send', p); }
|
|
19
|
+
}
|
|
20
|
+
exports.SeleEvents = SeleEvents;
|
|
21
|
+
const hex = (b) => [...new Uint8Array(b)].map((x) => x.toString(16).padStart(2, '0')).join('');
|
|
22
|
+
/**
|
|
23
|
+
* Verify a webhook. Pass the RAW request body string, the `seleid-signature` header and your endpoint secret.
|
|
24
|
+
* Header format: t=<unix seconds>,v1=<hex HMAC-SHA256 of "<t>.<body>">. Rejects timestamps older than `toleranceSec` (default 300).
|
|
25
|
+
*/
|
|
26
|
+
async function verifyWebhook(secret, rawBody, header, opts = {}) {
|
|
27
|
+
const parts = Object.fromEntries(String(header ?? '').split(',').map((p) => { const i = p.indexOf('='); return [p.slice(0, i), p.slice(i + 1)]; }));
|
|
28
|
+
const t = Number(parts.t);
|
|
29
|
+
if (!Number.isInteger(t) || typeof parts.v1 !== 'string')
|
|
30
|
+
return false;
|
|
31
|
+
if (Math.abs((opts.nowSec ?? Date.now() / 1000) - t) > (opts.toleranceSec ?? 300))
|
|
32
|
+
return false;
|
|
33
|
+
const key = await crypto.subtle.importKey('raw', new TextEncoder().encode(secret), { name: 'HMAC', hash: 'SHA-256' }, false, ['sign']);
|
|
34
|
+
const want = hex(await crypto.subtle.sign('HMAC', key, new TextEncoder().encode(`${t}.${rawBody}`)));
|
|
35
|
+
if (want.length !== parts.v1.length)
|
|
36
|
+
return false;
|
|
37
|
+
let diff = 0;
|
|
38
|
+
for (let i = 0; i < want.length; i++)
|
|
39
|
+
diff |= want.charCodeAt(i) ^ parts.v1.charCodeAt(i);
|
|
40
|
+
return diff === 0;
|
|
41
|
+
}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
export type FetchLike = (input: string, init?: RequestInit) => Promise<Response>;
|
|
2
|
+
export interface ClientOptions {
|
|
3
|
+
/** API key from the developer console. Keep it on the server; never ship it in a browser or mobile app. */
|
|
4
|
+
apiKey?: string;
|
|
5
|
+
baseUrl?: string;
|
|
6
|
+
fetch?: FetchLike;
|
|
7
|
+
/** Request timeout in milliseconds. Default 15000. */
|
|
8
|
+
timeoutMs?: number;
|
|
9
|
+
}
|
|
10
|
+
/** Thrown for every non-2xx response. `code` is the machine-readable error code from the API. */
|
|
11
|
+
export declare class SeleError extends Error {
|
|
12
|
+
readonly status: number;
|
|
13
|
+
readonly code: string;
|
|
14
|
+
readonly requestId?: string;
|
|
15
|
+
readonly body: unknown;
|
|
16
|
+
constructor(status: number, code: string, message: string, body: unknown, requestId?: string);
|
|
17
|
+
}
|
|
18
|
+
export declare class Http {
|
|
19
|
+
readonly baseUrl: string;
|
|
20
|
+
private readonly apiKey?;
|
|
21
|
+
private readonly fetchFn;
|
|
22
|
+
private readonly timeoutMs;
|
|
23
|
+
constructor(defaults: {
|
|
24
|
+
baseUrl: string;
|
|
25
|
+
}, o?: ClientOptions);
|
|
26
|
+
raw(method: string, path: string, init?: {
|
|
27
|
+
headers?: Record<string, string>;
|
|
28
|
+
body?: BodyInit | null;
|
|
29
|
+
query?: Record<string, string | number | undefined>;
|
|
30
|
+
}): Promise<Response>;
|
|
31
|
+
json<T>(method: string, path: string, body?: unknown, query?: Record<string, string | number | undefined>): Promise<T>;
|
|
32
|
+
}
|
|
33
|
+
export declare const enc: (s: string) => string;
|