@seletech/seleid-react-native 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 +61 -2
- package/dist/ai.d.ts +36 -0
- package/dist/ai.js +10 -0
- package/dist/auth.d.ts +52 -0
- package/dist/auth.js +60 -0
- package/dist/db.d.ts +26 -0
- package/dist/db.js +16 -0
- package/dist/events.d.ts +11 -0
- package/dist/events.js +6 -0
- package/dist/hooks.d.ts +24 -0
- package/dist/hooks.js +30 -0
- package/dist/http.d.ts +34 -0
- package/dist/http.js +64 -0
- package/dist/index.d.ts +9 -0
- package/dist/index.js +8 -0
- package/dist/platform.d.ts +20 -0
- package/dist/platform.js +37 -0
- package/dist/session.d.ts +50 -0
- package/dist/session.js +133 -0
- package/dist/storage.d.ts +41 -0
- package/dist/storage.js +31 -0
- package/package.json +26 -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,62 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @seletech/seleid-react-native
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Release candidate **0.1.0**. Licensed under [Apache-2.0](LICENSE). See [release notes](CHANGELOG.md).
|
|
4
|
+
|
|
5
|
+
Continue with SeleID for React Native and Expo, plus clients for SeleStorage, SeleBase, events and SeleAI.
|
|
6
|
+
|
|
7
|
+
> Not published yet. Publication requires registry account setup.
|
|
8
|
+
|
|
9
|
+
## Install
|
|
10
|
+
|
|
11
|
+
```bash
|
|
12
|
+
npm install @seletech/seleid-react-native expo-secure-store expo-web-browser expo-crypto
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
Register a redirect URI for your client in the developer console, for example `myapp://auth/callback`, and set `"scheme": "myapp"` in `app.json`.
|
|
16
|
+
|
|
17
|
+
## Quickstart
|
|
18
|
+
|
|
19
|
+
```tsx
|
|
20
|
+
import { SeleIDProvider, useSeleID, useStorage, useDb } from '@seletech/seleid-react-native';
|
|
21
|
+
|
|
22
|
+
const config = { clientId: 'YOUR_CLIENT_ID', redirectUri: 'myapp://auth/callback' };
|
|
23
|
+
|
|
24
|
+
export default function App() {
|
|
25
|
+
return <SeleIDProvider config={config}><Home /></SeleIDProvider>;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
function Home() {
|
|
29
|
+
const { status, user, signIn, signOut } = useSeleID();
|
|
30
|
+
const storage = useStorage();
|
|
31
|
+
const db = useDb();
|
|
32
|
+
if (status === 'loading') return null;
|
|
33
|
+
if (status === 'signedOut') return <Button title="Continue with SeleID" onPress={signIn} />;
|
|
34
|
+
// user.sub, user.email ...
|
|
35
|
+
// await storage.upload('photos/a.jpg', blob, 'image/jpeg');
|
|
36
|
+
// const rows = await db.rows<{ id: number }>('main', 'select id from t where owner = ?', [user.sub]);
|
|
37
|
+
return <Button title="Sign out" onPress={signOut} />;
|
|
38
|
+
}
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
## How it works
|
|
42
|
+
|
|
43
|
+
- Authorization code flow with PKCE (S256), public client, no secret in the app.
|
|
44
|
+
- Opens the system browser (ASWebAuthenticationSession / Custom Tab) through `expo-web-browser`; `state` is checked on return.
|
|
45
|
+
- Tokens live in the device keystore through `expo-secure-store`. The access token is refreshed shortly before it expires (one shared refresh for concurrent calls); refresh tokens rotate and the new one is stored. A refresh the server rejects signs the person out.
|
|
46
|
+
- `useStorage`, `useDb`, `useEvents` and `useAi` call the APIs with the signed-in person's access token. Do not put a server API key in a mobile app.
|
|
47
|
+
- Uploads and downloads go through signed URLs (`storage.upload`, `storage.download`).
|
|
48
|
+
- Always pass user input to SQL through `params`.
|
|
49
|
+
|
|
50
|
+
## API
|
|
51
|
+
|
|
52
|
+
`SeleIDProvider`, `useSeleID()` (`status`, `user`, `error`, `signIn`, `signOut`, `getAccessToken`), `useStorage()` (`list`, `upload`, `download`, `delete`, `signedUrl`, `usage`), `useDb()` (`query`, `rows`, `listDatabases`, `schema`), `useEvents()` (`registerDevice`), `useAi()` (`chat`, `models`). Errors are `SeleError` with `status`, `code`, `requestId`.
|
|
53
|
+
|
|
54
|
+
Outside React, use `SeleIDSession` and the client classes directly. Platform adapters (`secureStore`, `browser`, `crypto`) can be replaced in the config, which is also how the tests run.
|
|
55
|
+
|
|
56
|
+
## Develop
|
|
57
|
+
|
|
58
|
+
```bash
|
|
59
|
+
npm install
|
|
60
|
+
npm test
|
|
61
|
+
npm run typecheck
|
|
62
|
+
```
|
package/dist/ai.d.ts
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
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
|
+
/** Throws SeleError with code `spend_cap_reached` (HTTP 402) when the cap or credit is used up. */
|
|
31
|
+
chat(r: {
|
|
32
|
+
model: string;
|
|
33
|
+
messages: ChatMessage[];
|
|
34
|
+
maxTokens?: number;
|
|
35
|
+
}): Promise<ChatResponse>;
|
|
36
|
+
}
|
package/dist/ai.js
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import { Http } from "./http.js";
|
|
2
|
+
export class SeleAi {
|
|
3
|
+
http;
|
|
4
|
+
constructor(o = {}) { this.http = new Http({ baseUrl: 'https://api.seleid.dev' }, o); }
|
|
5
|
+
models() { return this.http.json('GET', '/v1/ai/models'); }
|
|
6
|
+
/** Throws SeleError with code `spend_cap_reached` (HTTP 402) when the cap or credit is used up. */
|
|
7
|
+
chat(r) {
|
|
8
|
+
return this.http.json('POST', '/v1/ai/chat', { model: r.model, messages: r.messages, max_tokens: r.maxTokens });
|
|
9
|
+
}
|
|
10
|
+
}
|
package/dist/auth.d.ts
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
import { type FetchLike } from './http.ts';
|
|
2
|
+
import type { CryptoLike } from './platform.ts';
|
|
3
|
+
export declare const ISSUER = "https://auth.seleid.dev";
|
|
4
|
+
export declare function b64url(bytes: Uint8Array): string;
|
|
5
|
+
export interface PkcePair {
|
|
6
|
+
codeVerifier: string;
|
|
7
|
+
codeChallenge: string;
|
|
8
|
+
}
|
|
9
|
+
export declare function createPkce(c: CryptoLike): Promise<PkcePair>;
|
|
10
|
+
export interface AuthorizeRequest {
|
|
11
|
+
clientId: string;
|
|
12
|
+
redirectUri: string;
|
|
13
|
+
scope?: string;
|
|
14
|
+
codeChallenge: string;
|
|
15
|
+
state: string;
|
|
16
|
+
nonce: string;
|
|
17
|
+
issuer?: string;
|
|
18
|
+
}
|
|
19
|
+
export declare function buildAuthorizeUrl(r: AuthorizeRequest): string;
|
|
20
|
+
export interface Tokens {
|
|
21
|
+
access_token: string;
|
|
22
|
+
token_type: 'Bearer';
|
|
23
|
+
expires_in: number;
|
|
24
|
+
refresh_token?: string;
|
|
25
|
+
id_token?: string;
|
|
26
|
+
scope?: string;
|
|
27
|
+
}
|
|
28
|
+
export interface UserInfo {
|
|
29
|
+
sub: string;
|
|
30
|
+
name?: string;
|
|
31
|
+
email?: string;
|
|
32
|
+
email_verified?: boolean;
|
|
33
|
+
}
|
|
34
|
+
export declare class SeleIdAuth {
|
|
35
|
+
private readonly http;
|
|
36
|
+
private readonly o;
|
|
37
|
+
constructor(o: {
|
|
38
|
+
clientId: string;
|
|
39
|
+
issuer?: string;
|
|
40
|
+
fetch?: FetchLike;
|
|
41
|
+
});
|
|
42
|
+
private form;
|
|
43
|
+
exchangeCode(p: {
|
|
44
|
+
code: string;
|
|
45
|
+
redirectUri: string;
|
|
46
|
+
codeVerifier: string;
|
|
47
|
+
}): Promise<Tokens>;
|
|
48
|
+
/** Refresh tokens rotate: always store the refresh_token from the response. */
|
|
49
|
+
refresh(refreshToken: string): Promise<Tokens>;
|
|
50
|
+
userInfo(accessToken: string): Promise<UserInfo>;
|
|
51
|
+
revoke(token: string): Promise<void>;
|
|
52
|
+
}
|
package/dist/auth.js
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
// Continue with SeleID: authorization code flow with PKCE (S256), public client (no secret).
|
|
2
|
+
import { Http, SeleError } from "./http.js";
|
|
3
|
+
export const ISSUER = 'https://auth.seleid.dev';
|
|
4
|
+
export function b64url(bytes) {
|
|
5
|
+
const A = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_';
|
|
6
|
+
let out = '';
|
|
7
|
+
for (let i = 0; i < bytes.length; i += 3) {
|
|
8
|
+
const n = (bytes[i] << 16) | ((bytes[i + 1] ?? 0) << 8) | (bytes[i + 2] ?? 0);
|
|
9
|
+
out += A[(n >> 18) & 63] + A[(n >> 12) & 63];
|
|
10
|
+
if (i + 1 < bytes.length)
|
|
11
|
+
out += A[(n >> 6) & 63];
|
|
12
|
+
if (i + 2 < bytes.length)
|
|
13
|
+
out += A[n & 63];
|
|
14
|
+
}
|
|
15
|
+
return out;
|
|
16
|
+
}
|
|
17
|
+
export async function createPkce(c) {
|
|
18
|
+
const codeVerifier = b64url(await c.randomBytes(48));
|
|
19
|
+
return { codeVerifier, codeChallenge: b64url(await c.sha256(codeVerifier)) };
|
|
20
|
+
}
|
|
21
|
+
export function buildAuthorizeUrl(r) {
|
|
22
|
+
const scope = r.scope ?? 'openid profile email';
|
|
23
|
+
if (!scope.split(' ').includes('openid'))
|
|
24
|
+
throw new Error('scope must include openid');
|
|
25
|
+
const u = new URL(`${(r.issuer ?? ISSUER).replace(/\/+$/, '')}/authorize`);
|
|
26
|
+
u.search = new URLSearchParams({ client_id: r.clientId, redirect_uri: r.redirectUri, response_type: 'code', scope, state: r.state, nonce: r.nonce, code_challenge: r.codeChallenge, code_challenge_method: 'S256' }).toString();
|
|
27
|
+
return u.toString();
|
|
28
|
+
}
|
|
29
|
+
export class SeleIdAuth {
|
|
30
|
+
http;
|
|
31
|
+
o;
|
|
32
|
+
constructor(o) {
|
|
33
|
+
this.o = o;
|
|
34
|
+
this.http = new Http({ baseUrl: ISSUER }, { baseUrl: o.issuer, fetch: o.fetch });
|
|
35
|
+
}
|
|
36
|
+
async form(path, params) {
|
|
37
|
+
const res = await this.http.raw('POST', path, { headers: { 'content-type': 'application/x-www-form-urlencoded' }, body: new URLSearchParams(params).toString() });
|
|
38
|
+
return (await res.json());
|
|
39
|
+
}
|
|
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 });
|
|
42
|
+
}
|
|
43
|
+
/** Refresh tokens rotate: always store the 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 });
|
|
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 SeleError) || e.status >= 500)
|
|
57
|
+
throw e;
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
}
|
package/dist/db.d.ts
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import { type ClientOptions } from './http.ts';
|
|
2
|
+
export type Param = string | number | boolean | null;
|
|
3
|
+
export interface QueryResult<T = Record<string, unknown>> {
|
|
4
|
+
results?: T[];
|
|
5
|
+
rows?: T[];
|
|
6
|
+
meta?: Record<string, unknown>;
|
|
7
|
+
[k: string]: unknown;
|
|
8
|
+
}
|
|
9
|
+
export declare class SeleDb {
|
|
10
|
+
private readonly http;
|
|
11
|
+
constructor(o?: ClientOptions);
|
|
12
|
+
listDatabases(): Promise<{
|
|
13
|
+
databases: Array<{
|
|
14
|
+
name: string;
|
|
15
|
+
sizeBytes: number;
|
|
16
|
+
createdAt: string;
|
|
17
|
+
}>;
|
|
18
|
+
}>;
|
|
19
|
+
/** One statement per call. Pass user input through `params`, never concatenate it into `sql`. */
|
|
20
|
+
query<T = Record<string, unknown>>(database: string, sql: string, params?: Param[]): Promise<QueryResult<T>>;
|
|
21
|
+
/** The result rows as a typed array. */
|
|
22
|
+
rows<T = Record<string, unknown>>(database: string, sql: string, params?: Param[]): Promise<T[]>;
|
|
23
|
+
schema(database: string): Promise<{
|
|
24
|
+
schema: unknown;
|
|
25
|
+
}>;
|
|
26
|
+
}
|
package/dist/db.js
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import { Http } from "./http.js";
|
|
2
|
+
export class SeleDb {
|
|
3
|
+
http;
|
|
4
|
+
constructor(o = {}) { this.http = new Http({ baseUrl: 'https://api.seleid.dev' }, o); }
|
|
5
|
+
listDatabases() { return this.http.json('GET', '/v1/databases'); }
|
|
6
|
+
/** One statement per call. Pass user input through `params`, never concatenate it into `sql`. */
|
|
7
|
+
query(database, sql, params = []) {
|
|
8
|
+
return this.http.json('POST', `/v1/databases/${encodeURIComponent(database)}/query`, { sql, params });
|
|
9
|
+
}
|
|
10
|
+
/** The result rows as a typed array. */
|
|
11
|
+
async rows(database, sql, params = []) {
|
|
12
|
+
const r = await this.query(database, sql, params);
|
|
13
|
+
return (r.results ?? r.rows ?? []);
|
|
14
|
+
}
|
|
15
|
+
schema(database) { return this.http.json('GET', `/v1/databases/${encodeURIComponent(database)}/schema`); }
|
|
16
|
+
}
|
package/dist/events.d.ts
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import { type ClientOptions } from './http.ts';
|
|
2
|
+
export interface PushDevice {
|
|
3
|
+
userId: string;
|
|
4
|
+
platform: 'android' | 'ios' | 'web';
|
|
5
|
+
token: string;
|
|
6
|
+
}
|
|
7
|
+
export declare class SeleEvents {
|
|
8
|
+
private readonly http;
|
|
9
|
+
constructor(o?: ClientOptions);
|
|
10
|
+
registerDevice(d: PushDevice): Promise<unknown>;
|
|
11
|
+
}
|
package/dist/events.js
ADDED
package/dist/hooks.d.ts
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import { type ReactNode } from 'react';
|
|
2
|
+
import { SeleIDSession, type SeleIDConfig, type SessionState } from './session.ts';
|
|
3
|
+
import { SeleStorage } from './storage.ts';
|
|
4
|
+
import { SeleDb } from './db.ts';
|
|
5
|
+
import { SeleEvents } from './events.ts';
|
|
6
|
+
import { SeleAi } from './ai.ts';
|
|
7
|
+
import type { UserInfo } from './auth.ts';
|
|
8
|
+
import type { ClientOptions } from './http.ts';
|
|
9
|
+
export declare function SeleIDProvider(props: {
|
|
10
|
+
config: SeleIDConfig;
|
|
11
|
+
session?: SeleIDSession;
|
|
12
|
+
children?: ReactNode;
|
|
13
|
+
}): import("react").FunctionComponentElement<import("react").ProviderProps<SeleIDSession | null>>;
|
|
14
|
+
export interface UseSeleID extends SessionState {
|
|
15
|
+
signIn(): Promise<UserInfo | null>;
|
|
16
|
+
signOut(): Promise<void>;
|
|
17
|
+
getAccessToken(): Promise<string | undefined>;
|
|
18
|
+
session: SeleIDSession;
|
|
19
|
+
}
|
|
20
|
+
export declare function useSeleID(): UseSeleID;
|
|
21
|
+
export declare const useStorage: (o?: ClientOptions) => SeleStorage;
|
|
22
|
+
export declare const useDb: (o?: ClientOptions) => SeleDb;
|
|
23
|
+
export declare const useEvents: (o?: ClientOptions) => SeleEvents;
|
|
24
|
+
export declare const useAi: (o?: ClientOptions) => SeleAi;
|
package/dist/hooks.js
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import { createContext, createElement, useContext, useEffect, useMemo, useSyncExternalStore } from 'react';
|
|
2
|
+
import { SeleIDSession } from "./session.js";
|
|
3
|
+
import { SeleStorage } from "./storage.js";
|
|
4
|
+
import { SeleDb } from "./db.js";
|
|
5
|
+
import { SeleEvents } from "./events.js";
|
|
6
|
+
import { SeleAi } from "./ai.js";
|
|
7
|
+
const Ctx = createContext(null);
|
|
8
|
+
export function SeleIDProvider(props) {
|
|
9
|
+
const session = useMemo(() => props.session ?? new SeleIDSession(props.config), [props.session, props.config.clientId, props.config.redirectUri]);
|
|
10
|
+
useEffect(() => { void session.restore(); }, [session]);
|
|
11
|
+
return createElement(Ctx.Provider, { value: session }, props.children);
|
|
12
|
+
}
|
|
13
|
+
function useSession() {
|
|
14
|
+
const s = useContext(Ctx);
|
|
15
|
+
if (!s)
|
|
16
|
+
throw new Error('Wrap your app in <SeleIDProvider>');
|
|
17
|
+
return s;
|
|
18
|
+
}
|
|
19
|
+
export function useSeleID() {
|
|
20
|
+
const session = useSession();
|
|
21
|
+
const state = useSyncExternalStore(session.subscribe, session.getState, session.getState);
|
|
22
|
+
return { ...state, session, signIn: () => session.signIn(), signOut: () => session.signOut(), getAccessToken: () => session.getAccessToken() };
|
|
23
|
+
}
|
|
24
|
+
function opts(session, o) {
|
|
25
|
+
return { getToken: () => session.getAccessToken(), fetch: session.config.fetch, ...o };
|
|
26
|
+
}
|
|
27
|
+
export const useStorage = (o) => { const s = useSession(); return useMemo(() => new SeleStorage(opts(s, o)), [s]); };
|
|
28
|
+
export const useDb = (o) => { const s = useSession(); return useMemo(() => new SeleDb(opts(s, o)), [s]); };
|
|
29
|
+
export const useEvents = (o) => { const s = useSession(); return useMemo(() => new SeleEvents(opts(s, o)), [s]); };
|
|
30
|
+
export const useAi = (o) => { const s = useSession(); return useMemo(() => new SeleAi(opts(s, o)), [s]); };
|
package/dist/http.d.ts
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
export type FetchLike = (input: string, init?: RequestInit) => Promise<Response>;
|
|
2
|
+
export type TokenProvider = () => Promise<string | undefined>;
|
|
3
|
+
export interface ClientOptions {
|
|
4
|
+
/** Supplies the bearer token per request, typically `() => session.getAccessToken()`. Never ship a server API key in an app. */
|
|
5
|
+
getToken?: TokenProvider;
|
|
6
|
+
baseUrl?: string;
|
|
7
|
+
fetch?: FetchLike;
|
|
8
|
+
/** Request timeout in milliseconds. Default 15000. */
|
|
9
|
+
timeoutMs?: number;
|
|
10
|
+
}
|
|
11
|
+
/** Thrown for every non-2xx response. */
|
|
12
|
+
export declare class SeleError extends Error {
|
|
13
|
+
readonly status: number;
|
|
14
|
+
readonly code: string;
|
|
15
|
+
readonly requestId?: string;
|
|
16
|
+
readonly body: unknown;
|
|
17
|
+
constructor(status: number, code: string, message: string, body: unknown, requestId?: string);
|
|
18
|
+
}
|
|
19
|
+
export declare class Http {
|
|
20
|
+
readonly baseUrl: string;
|
|
21
|
+
private readonly getToken?;
|
|
22
|
+
private readonly fetchFn;
|
|
23
|
+
private readonly timeoutMs;
|
|
24
|
+
constructor(defaults: {
|
|
25
|
+
baseUrl: string;
|
|
26
|
+
}, o?: ClientOptions);
|
|
27
|
+
raw(method: string, path: string, init?: {
|
|
28
|
+
headers?: Record<string, string>;
|
|
29
|
+
body?: any;
|
|
30
|
+
query?: Record<string, string | number | undefined>;
|
|
31
|
+
}): Promise<Response>;
|
|
32
|
+
json<T>(method: string, path: string, body?: unknown, query?: Record<string, string | number | undefined>): Promise<T>;
|
|
33
|
+
}
|
|
34
|
+
export declare const enc: (s: string) => string;
|
package/dist/http.js
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
/** Thrown for every non-2xx response. */
|
|
2
|
+
export class SeleError extends Error {
|
|
3
|
+
status;
|
|
4
|
+
code;
|
|
5
|
+
requestId;
|
|
6
|
+
body;
|
|
7
|
+
constructor(status, code, message, body, requestId) {
|
|
8
|
+
super(message);
|
|
9
|
+
this.name = 'SeleError';
|
|
10
|
+
this.status = status;
|
|
11
|
+
this.code = code;
|
|
12
|
+
this.body = body;
|
|
13
|
+
this.requestId = requestId;
|
|
14
|
+
}
|
|
15
|
+
}
|
|
16
|
+
export class Http {
|
|
17
|
+
baseUrl;
|
|
18
|
+
getToken;
|
|
19
|
+
fetchFn;
|
|
20
|
+
timeoutMs;
|
|
21
|
+
constructor(defaults, o = {}) {
|
|
22
|
+
this.baseUrl = (o.baseUrl ?? defaults.baseUrl).replace(/\/+$/, '');
|
|
23
|
+
this.getToken = o.getToken;
|
|
24
|
+
this.fetchFn = o.fetch ?? ((i, init) => fetch(i, init));
|
|
25
|
+
this.timeoutMs = o.timeoutMs ?? 15000;
|
|
26
|
+
}
|
|
27
|
+
async raw(method, path, init = {}) {
|
|
28
|
+
const q = init.query ? Object.entries(init.query).filter(([, v]) => v !== undefined).map(([k, v]) => `${encodeURIComponent(k)}=${encodeURIComponent(String(v))}`).join('&') : '';
|
|
29
|
+
const headers = { ...init.headers };
|
|
30
|
+
if (this.getToken && !headers.authorization) {
|
|
31
|
+
const t = await this.getToken();
|
|
32
|
+
if (t)
|
|
33
|
+
headers.authorization = `Bearer ${t}`;
|
|
34
|
+
}
|
|
35
|
+
const ctl = new AbortController();
|
|
36
|
+
const timer = setTimeout(() => ctl.abort(), this.timeoutMs);
|
|
37
|
+
let res;
|
|
38
|
+
try {
|
|
39
|
+
res = await this.fetchFn(`${this.baseUrl}${path}${q ? `?${q}` : ''}`, { method, headers, body: init.body ?? undefined, signal: ctl.signal });
|
|
40
|
+
}
|
|
41
|
+
finally {
|
|
42
|
+
clearTimeout(timer);
|
|
43
|
+
}
|
|
44
|
+
if (!res.ok)
|
|
45
|
+
throw await toError(res);
|
|
46
|
+
return res;
|
|
47
|
+
}
|
|
48
|
+
async json(method, path, body, query) {
|
|
49
|
+
const res = await this.raw(method, path, { headers: body === undefined ? {} : { 'content-type': 'application/json' }, body: body === undefined ? undefined : JSON.stringify(body), query });
|
|
50
|
+
return (await res.json());
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
async function toError(res) {
|
|
54
|
+
let body = null;
|
|
55
|
+
try {
|
|
56
|
+
body = await res.json();
|
|
57
|
+
}
|
|
58
|
+
catch { /* not JSON */ }
|
|
59
|
+
const e = body?.error;
|
|
60
|
+
const code = typeof e === 'string' ? e : typeof e?.code === 'string' ? e.code : `http_${res.status}`;
|
|
61
|
+
const message = typeof e?.message === 'string' ? e.message : typeof body?.error_description === 'string' ? body.error_description : `Request failed with status ${res.status}`;
|
|
62
|
+
return new SeleError(res.status, code, message, body, typeof e?.request_id === 'string' ? e.request_id : undefined);
|
|
63
|
+
}
|
|
64
|
+
export const enc = (s) => s.split('/').map(encodeURIComponent).join('/');
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
export { SeleError, type ClientOptions, type FetchLike, type TokenProvider } from './http.ts';
|
|
2
|
+
export { SeleIdAuth, createPkce, buildAuthorizeUrl, ISSUER, type Tokens, type UserInfo, type PkcePair, type AuthorizeRequest } from './auth.ts';
|
|
3
|
+
export { SeleIDSession, type SeleIDConfig, type SessionState, type SessionStatus } from './session.ts';
|
|
4
|
+
export type { SecureStore, AuthBrowser, CryptoLike, BrowserResult } from './platform.ts';
|
|
5
|
+
export { SeleStorage, type StoredObject, type ObjectList, type SignedUrl } from './storage.ts';
|
|
6
|
+
export { SeleDb, type Param, type QueryResult } from './db.ts';
|
|
7
|
+
export { SeleEvents, type PushDevice } from './events.ts';
|
|
8
|
+
export { SeleAi, type ChatMessage, type ChatResponse } from './ai.ts';
|
|
9
|
+
export { SeleIDProvider, useSeleID, useStorage, useDb, useEvents, useAi, type UseSeleID } from './hooks.ts';
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
export { SeleError } from "./http.js";
|
|
2
|
+
export { SeleIdAuth, createPkce, buildAuthorizeUrl, ISSUER } from "./auth.js";
|
|
3
|
+
export { SeleIDSession } from "./session.js";
|
|
4
|
+
export { SeleStorage } from "./storage.js";
|
|
5
|
+
export { SeleDb } from "./db.js";
|
|
6
|
+
export { SeleEvents } from "./events.js";
|
|
7
|
+
export { SeleAi } from "./ai.js";
|
|
8
|
+
export { SeleIDProvider, useSeleID, useStorage, useDb, useEvents, useAi } from "./hooks.js";
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
export interface SecureStore {
|
|
2
|
+
getItem(key: string): Promise<string | null>;
|
|
3
|
+
setItem(key: string, value: string): Promise<void>;
|
|
4
|
+
deleteItem(key: string): Promise<void>;
|
|
5
|
+
}
|
|
6
|
+
export interface BrowserResult {
|
|
7
|
+
type: 'success' | 'cancel';
|
|
8
|
+
url?: string;
|
|
9
|
+
}
|
|
10
|
+
export interface AuthBrowser {
|
|
11
|
+
/** Opens `url` in the system browser (ASWebAuthenticationSession / Custom Tab) and resolves with the redirect URL. */
|
|
12
|
+
openAuthSession(url: string, redirectUri: string): Promise<BrowserResult>;
|
|
13
|
+
}
|
|
14
|
+
export interface CryptoLike {
|
|
15
|
+
randomBytes(n: number): Promise<Uint8Array>;
|
|
16
|
+
sha256(input: string): Promise<Uint8Array>;
|
|
17
|
+
}
|
|
18
|
+
export declare function expoSecureStore(): SecureStore;
|
|
19
|
+
export declare function expoAuthBrowser(): AuthBrowser;
|
|
20
|
+
export declare function expoCrypto(): CryptoLike;
|
package/dist/platform.js
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
var __rewriteRelativeImportExtension = (this && this.__rewriteRelativeImportExtension) || function (path, preserveJsx) {
|
|
2
|
+
if (typeof path === "string" && /^\.\.?\//.test(path)) {
|
|
3
|
+
return path.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i, function (m, tsx, d, ext, cm) {
|
|
4
|
+
return tsx ? preserveJsx ? ".jsx" : ".js" : d && (!ext || !cm) ? m : (d + ext + "." + cm.toLowerCase() + "js");
|
|
5
|
+
});
|
|
6
|
+
}
|
|
7
|
+
return path;
|
|
8
|
+
};
|
|
9
|
+
export function expoSecureStore() {
|
|
10
|
+
let mod;
|
|
11
|
+
const m = () => (mod ??= import(__rewriteRelativeImportExtension('expo-secure-store')));
|
|
12
|
+
return {
|
|
13
|
+
getItem: async (k) => (await m()).getItemAsync(k),
|
|
14
|
+
setItem: async (k, v) => (await m()).setItemAsync(k, v),
|
|
15
|
+
deleteItem: async (k) => (await m()).deleteItemAsync(k),
|
|
16
|
+
};
|
|
17
|
+
}
|
|
18
|
+
export function expoAuthBrowser() {
|
|
19
|
+
return {
|
|
20
|
+
async openAuthSession(url, redirectUri) {
|
|
21
|
+
const wb = await import(__rewriteRelativeImportExtension('expo-web-browser'));
|
|
22
|
+
const r = await wb.openAuthSessionAsync(url, redirectUri);
|
|
23
|
+
return r.type === 'success' ? { type: 'success', url: r.url } : { type: 'cancel' };
|
|
24
|
+
},
|
|
25
|
+
};
|
|
26
|
+
}
|
|
27
|
+
export function expoCrypto() {
|
|
28
|
+
return {
|
|
29
|
+
async randomBytes(n) { return (await import(__rewriteRelativeImportExtension('expo-crypto'))).getRandomBytes(n); },
|
|
30
|
+
async sha256(input) {
|
|
31
|
+
const c = await import(__rewriteRelativeImportExtension('expo-crypto'));
|
|
32
|
+
const b64 = await c.digestStringAsync(c.CryptoDigestAlgorithm.SHA256, input, { encoding: c.CryptoEncoding.BASE64 });
|
|
33
|
+
const bin = atob(b64);
|
|
34
|
+
return Uint8Array.from(bin, (ch) => ch.charCodeAt(0));
|
|
35
|
+
},
|
|
36
|
+
};
|
|
37
|
+
}
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
import { SeleIdAuth, type UserInfo } from './auth.ts';
|
|
2
|
+
import { type FetchLike } from './http.ts';
|
|
3
|
+
import { type AuthBrowser, type CryptoLike, type SecureStore } from './platform.ts';
|
|
4
|
+
export interface SeleIDConfig {
|
|
5
|
+
clientId: string;
|
|
6
|
+
/** Must be registered for the client, e.g. `myapp://auth/callback`. */
|
|
7
|
+
redirectUri: string;
|
|
8
|
+
scope?: string;
|
|
9
|
+
issuer?: string;
|
|
10
|
+
fetch?: FetchLike;
|
|
11
|
+
secureStore?: SecureStore;
|
|
12
|
+
browser?: AuthBrowser;
|
|
13
|
+
crypto?: CryptoLike;
|
|
14
|
+
/** Refresh this many seconds before expiry. Default 60. */
|
|
15
|
+
refreshSkewSec?: number;
|
|
16
|
+
now?: () => number;
|
|
17
|
+
}
|
|
18
|
+
export type SessionStatus = 'loading' | 'signedOut' | 'signedIn';
|
|
19
|
+
export interface SessionState {
|
|
20
|
+
status: SessionStatus;
|
|
21
|
+
user: UserInfo | null;
|
|
22
|
+
error: Error | null;
|
|
23
|
+
}
|
|
24
|
+
export declare class SeleIDSession {
|
|
25
|
+
private state;
|
|
26
|
+
private readonly listeners;
|
|
27
|
+
private tokens;
|
|
28
|
+
private refreshing;
|
|
29
|
+
readonly auth: SeleIdAuth;
|
|
30
|
+
private readonly store;
|
|
31
|
+
private readonly browser;
|
|
32
|
+
private readonly crypto;
|
|
33
|
+
private readonly now;
|
|
34
|
+
readonly config: SeleIDConfig;
|
|
35
|
+
constructor(config: SeleIDConfig);
|
|
36
|
+
getState: () => SessionState;
|
|
37
|
+
subscribe: (fn: () => void) => (() => void);
|
|
38
|
+
private set;
|
|
39
|
+
/** Load a saved session from secure storage. Call once at startup (the provider does this). */
|
|
40
|
+
restore(): Promise<void>;
|
|
41
|
+
/** Continue with SeleID. Resolves with the user, or null if the person closed the browser. */
|
|
42
|
+
signIn(): Promise<UserInfo | null>;
|
|
43
|
+
signOut(): Promise<void>;
|
|
44
|
+
/** A valid access token, refreshing first when it is about to expire. Concurrent callers share one refresh. */
|
|
45
|
+
getAccessToken(): Promise<string | undefined>;
|
|
46
|
+
private doRefresh;
|
|
47
|
+
userInfo(): Promise<UserInfo>;
|
|
48
|
+
private save;
|
|
49
|
+
private clear;
|
|
50
|
+
}
|
package/dist/session.js
ADDED
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
import { SeleIdAuth, buildAuthorizeUrl, createPkce, b64url } from "./auth.js";
|
|
2
|
+
import { SeleError } from "./http.js";
|
|
3
|
+
import { expoAuthBrowser, expoCrypto, expoSecureStore } from "./platform.js";
|
|
4
|
+
const KEY = 'seleid.session.v1';
|
|
5
|
+
export class SeleIDSession {
|
|
6
|
+
state = { status: 'loading', user: null, error: null };
|
|
7
|
+
listeners = new Set();
|
|
8
|
+
tokens = null;
|
|
9
|
+
refreshing = null;
|
|
10
|
+
auth;
|
|
11
|
+
store;
|
|
12
|
+
browser;
|
|
13
|
+
crypto;
|
|
14
|
+
now;
|
|
15
|
+
config;
|
|
16
|
+
constructor(config) {
|
|
17
|
+
this.config = config;
|
|
18
|
+
this.auth = new SeleIdAuth({ clientId: config.clientId, issuer: config.issuer, fetch: config.fetch });
|
|
19
|
+
this.store = config.secureStore ?? expoSecureStore();
|
|
20
|
+
this.browser = config.browser ?? expoAuthBrowser();
|
|
21
|
+
this.crypto = config.crypto ?? expoCrypto();
|
|
22
|
+
this.now = config.now ?? (() => Date.now());
|
|
23
|
+
}
|
|
24
|
+
getState = () => this.state;
|
|
25
|
+
subscribe = (fn) => { this.listeners.add(fn); return () => { this.listeners.delete(fn); }; };
|
|
26
|
+
set(patch) { this.state = { ...this.state, ...patch }; this.listeners.forEach((l) => l()); }
|
|
27
|
+
/** Load a saved session from secure storage. Call once at startup (the provider does this). */
|
|
28
|
+
async restore() {
|
|
29
|
+
try {
|
|
30
|
+
const raw = await this.store.getItem(KEY);
|
|
31
|
+
this.tokens = raw ? JSON.parse(raw) : null;
|
|
32
|
+
}
|
|
33
|
+
catch {
|
|
34
|
+
this.tokens = null;
|
|
35
|
+
}
|
|
36
|
+
if (!this.tokens)
|
|
37
|
+
return this.set({ status: 'signedOut', user: null });
|
|
38
|
+
try {
|
|
39
|
+
const user = await this.userInfo();
|
|
40
|
+
this.set({ status: 'signedIn', user, error: null });
|
|
41
|
+
}
|
|
42
|
+
catch (e) {
|
|
43
|
+
if (!this.tokens || (e instanceof SeleError && e.status < 500)) {
|
|
44
|
+
await this.clear();
|
|
45
|
+
this.set({ status: 'signedOut', user: null });
|
|
46
|
+
}
|
|
47
|
+
else
|
|
48
|
+
this.set({ status: 'signedIn', error: e }); // offline: keep the session, retry later
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
/** Continue with SeleID. Resolves with the user, or null if the person closed the browser. */
|
|
52
|
+
async signIn() {
|
|
53
|
+
const { clientId, redirectUri, scope, issuer } = this.config;
|
|
54
|
+
try {
|
|
55
|
+
const pkce = await createPkce(this.crypto);
|
|
56
|
+
const state = b64url(await this.crypto.randomBytes(24));
|
|
57
|
+
const nonce = b64url(await this.crypto.randomBytes(24));
|
|
58
|
+
const url = buildAuthorizeUrl({ clientId, redirectUri, scope, issuer, codeChallenge: pkce.codeChallenge, state, nonce });
|
|
59
|
+
const r = await this.browser.openAuthSession(url, redirectUri);
|
|
60
|
+
if (r.type !== 'success' || !r.url)
|
|
61
|
+
return null;
|
|
62
|
+
const q = new URL(r.url).searchParams;
|
|
63
|
+
if (q.get('error'))
|
|
64
|
+
throw new Error(q.get('error_description') ?? q.get('error'));
|
|
65
|
+
if (q.get('state') !== state)
|
|
66
|
+
throw new Error('state_mismatch');
|
|
67
|
+
const code = q.get('code');
|
|
68
|
+
if (!code)
|
|
69
|
+
throw new Error('missing_code');
|
|
70
|
+
const tk = await this.auth.exchangeCode({ code, redirectUri, codeVerifier: pkce.codeVerifier });
|
|
71
|
+
await this.save(tk);
|
|
72
|
+
const user = await this.auth.userInfo(tk.access_token);
|
|
73
|
+
this.set({ status: 'signedIn', user, error: null });
|
|
74
|
+
return user;
|
|
75
|
+
}
|
|
76
|
+
catch (e) {
|
|
77
|
+
this.set({ error: e });
|
|
78
|
+
throw e;
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
async signOut() {
|
|
82
|
+
const t = this.tokens;
|
|
83
|
+
await this.clear();
|
|
84
|
+
this.set({ status: 'signedOut', user: null, error: null });
|
|
85
|
+
if (t) {
|
|
86
|
+
try {
|
|
87
|
+
await this.auth.revoke(t.refreshToken ?? t.accessToken);
|
|
88
|
+
}
|
|
89
|
+
catch { /* local sign-out already done */ }
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
/** A valid access token, refreshing first when it is about to expire. Concurrent callers share one refresh. */
|
|
93
|
+
async getAccessToken() {
|
|
94
|
+
const t = this.tokens;
|
|
95
|
+
if (!t)
|
|
96
|
+
return undefined;
|
|
97
|
+
if (t.expiresAt - this.now() > (this.config.refreshSkewSec ?? 60) * 1000)
|
|
98
|
+
return t.accessToken;
|
|
99
|
+
if (!t.refreshToken)
|
|
100
|
+
return t.accessToken;
|
|
101
|
+
this.refreshing ??= this.doRefresh(t.refreshToken).finally(() => { this.refreshing = null; });
|
|
102
|
+
return (await this.refreshing)?.accessToken;
|
|
103
|
+
}
|
|
104
|
+
async doRefresh(rt) {
|
|
105
|
+
try {
|
|
106
|
+
return await this.save(await this.auth.refresh(rt));
|
|
107
|
+
}
|
|
108
|
+
catch (e) {
|
|
109
|
+
if (e instanceof SeleError && e.status >= 400 && e.status < 500) {
|
|
110
|
+
await this.clear();
|
|
111
|
+
this.set({ status: 'signedOut', user: null, error: e });
|
|
112
|
+
return null;
|
|
113
|
+
}
|
|
114
|
+
throw e;
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
async userInfo() {
|
|
118
|
+
const t = await this.getAccessToken();
|
|
119
|
+
if (!t)
|
|
120
|
+
throw new Error('not_signed_in');
|
|
121
|
+
return this.auth.userInfo(t);
|
|
122
|
+
}
|
|
123
|
+
async save(tk) {
|
|
124
|
+
const s = { accessToken: tk.access_token, refreshToken: tk.refresh_token ?? this.tokens?.refreshToken, idToken: tk.id_token, scope: tk.scope, expiresAt: this.now() + tk.expires_in * 1000 };
|
|
125
|
+
this.tokens = s;
|
|
126
|
+
await this.store.setItem(KEY, JSON.stringify(s));
|
|
127
|
+
return s;
|
|
128
|
+
}
|
|
129
|
+
async clear() { this.tokens = null; try {
|
|
130
|
+
await this.store.deleteItem(KEY);
|
|
131
|
+
}
|
|
132
|
+
catch { /* ignore */ } }
|
|
133
|
+
}
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import { type ClientOptions } from './http.ts';
|
|
2
|
+
export interface StoredObject {
|
|
3
|
+
key: string;
|
|
4
|
+
size: number;
|
|
5
|
+
uploaded: string | null;
|
|
6
|
+
}
|
|
7
|
+
export interface ObjectList {
|
|
8
|
+
objects: StoredObject[];
|
|
9
|
+
truncated: boolean;
|
|
10
|
+
cursor: string | null;
|
|
11
|
+
}
|
|
12
|
+
export interface SignedUrl {
|
|
13
|
+
url: string;
|
|
14
|
+
method: 'GET' | 'PUT';
|
|
15
|
+
expires_at: string;
|
|
16
|
+
}
|
|
17
|
+
export declare class SeleStorage {
|
|
18
|
+
private readonly http;
|
|
19
|
+
private readonly fetchFn;
|
|
20
|
+
constructor(o?: ClientOptions);
|
|
21
|
+
list(q?: {
|
|
22
|
+
prefix?: string;
|
|
23
|
+
limit?: number;
|
|
24
|
+
cursor?: string;
|
|
25
|
+
}): Promise<ObjectList>;
|
|
26
|
+
delete(key: string): Promise<{
|
|
27
|
+
deleted: string;
|
|
28
|
+
}>;
|
|
29
|
+
usage(): Promise<Record<string, unknown>>;
|
|
30
|
+
signedUrl(p: {
|
|
31
|
+
method: 'GET' | 'PUT';
|
|
32
|
+
key: string;
|
|
33
|
+
expiresIn?: number;
|
|
34
|
+
}): Promise<SignedUrl>;
|
|
35
|
+
private resolve;
|
|
36
|
+
/** Upload through a signed URL. `body` is a Blob, ArrayBuffer or Uint8Array. */
|
|
37
|
+
upload(key: string, body: Blob | ArrayBuffer | Uint8Array, contentType?: string): Promise<{
|
|
38
|
+
key: string;
|
|
39
|
+
}>;
|
|
40
|
+
download(key: string): Promise<ArrayBuffer>;
|
|
41
|
+
}
|
package/dist/storage.js
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import { Http, enc } from "./http.js";
|
|
2
|
+
export class SeleStorage {
|
|
3
|
+
http;
|
|
4
|
+
fetchFn;
|
|
5
|
+
constructor(o = {}) {
|
|
6
|
+
this.http = new Http({ baseUrl: 'https://storage.seleid.dev' }, o);
|
|
7
|
+
this.fetchFn = o.fetch ?? ((i, init) => fetch(i, init));
|
|
8
|
+
}
|
|
9
|
+
list(q = {}) { return this.http.json('GET', '/v1/objects', undefined, q); }
|
|
10
|
+
delete(key) { return this.http.json('DELETE', `/v1/objects/${enc(key)}`); }
|
|
11
|
+
usage() { return this.http.json('GET', '/v1/usage'); }
|
|
12
|
+
signedUrl(p) {
|
|
13
|
+
return this.http.json('POST', '/v1/signed-urls', { method: p.method, key: p.key, expires_in: p.expiresIn });
|
|
14
|
+
}
|
|
15
|
+
resolve(u) { return /^https?:/.test(u.url) ? u.url : `${this.http.baseUrl}${u.url}`; }
|
|
16
|
+
/** Upload through a signed URL. `body` is a Blob, ArrayBuffer or Uint8Array. */
|
|
17
|
+
async upload(key, body, contentType = 'application/octet-stream') {
|
|
18
|
+
const s = await this.signedUrl({ method: 'PUT', key });
|
|
19
|
+
const res = await this.fetchFn(this.resolve(s), { method: 'PUT', headers: { 'content-type': contentType }, body: body });
|
|
20
|
+
if (!res.ok)
|
|
21
|
+
throw new Error(`upload_failed_${res.status}`);
|
|
22
|
+
return { key };
|
|
23
|
+
}
|
|
24
|
+
async download(key) {
|
|
25
|
+
const s = await this.signedUrl({ method: 'GET', key });
|
|
26
|
+
const res = await this.fetchFn(this.resolve(s), { method: 'GET' });
|
|
27
|
+
if (!res.ok)
|
|
28
|
+
throw new Error(`download_failed_${res.status}`);
|
|
29
|
+
return res.arrayBuffer();
|
|
30
|
+
}
|
|
31
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,28 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@seletech/seleid-react-native",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "React Native and Expo client for Continue with SeleID (PKCE), SeleStorage, SeleBase, events and SeleAI.",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"license": "Apache-2.0",
|
|
7
|
+
"main": "./dist/index.js",
|
|
8
|
+
"types": "./dist/index.d.ts",
|
|
9
|
+
"exports": { ".": { "types": "./dist/index.d.ts", "default": "./dist/index.js" }, "./package.json": "./package.json" },
|
|
10
|
+
"files": ["dist", "README.md", "CHANGELOG.md", "LICENSE"],
|
|
11
|
+
"sideEffects": false,
|
|
12
|
+
"scripts": {
|
|
13
|
+
"build": "tsc -p tsconfig.json --noEmit false",
|
|
14
|
+
"typecheck": "tsc -p tsconfig.json",
|
|
15
|
+
"test": "node --test --experimental-strip-types test/*.test.mjs",
|
|
16
|
+
"prepublishOnly": "npm test && npm run build"
|
|
17
|
+
},
|
|
18
|
+
"peerDependencies": {
|
|
19
|
+
"expo-crypto": ">=13",
|
|
20
|
+
"expo-secure-store": ">=13",
|
|
21
|
+
"expo-web-browser": ">=13",
|
|
22
|
+
"react": ">=18"
|
|
23
|
+
},
|
|
24
|
+
"devDependencies": { "@types/node": "^22.0.0", "@types/react": "^18.3.0", "react": "^18.3.1", "typescript": "^5.7.0" },
|
|
25
|
+
"publishConfig": { "access": "public" },
|
|
26
|
+
"repository": { "type": "git", "url": "git+https://github.com/seletech-ai/SeleID.git", "directory": "sdks/react-native" },
|
|
27
|
+
"keywords": ["seleid", "oidc", "pkce", "expo", "react-native", "sdk"]
|
|
28
|
+
}
|