@o3co/auth-provider-foundation 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/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2026 1o1 Co. Ltd.
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.ja.md ADDED
@@ -0,0 +1,114 @@
1
+ # @o3co/auth-provider-foundation
2
+
3
+ auth.provider 向けの組み込みリポジトリ実装パッケージ。HTTP ベースのユーザー認証と、Redis を使った認可コードのストレージを提供する。
4
+
5
+ ## インストール
6
+
7
+ ```sh
8
+ npm install @o3co/auth-provider-foundation
9
+ # peer dependency(必須):
10
+ npm install @o3co/auth-provider-core
11
+ # peer dependency(任意 — RedisCodeRepository を使う場合のみ必要):
12
+ npm install redis
13
+ ```
14
+
15
+ ## パブリック API
16
+
17
+ ### `registerBuiltinAdapters`
18
+
19
+ 組み込みアダプターのファクトリーを、指定されたファクトリーインスタンスに登録する。
20
+
21
+ - `"http"` を `userFactory` に登録 → `HttpUserRepository` を生成
22
+ - `"redis"` を `codeFactory` に登録 → `RedisCodeRepository` を生成
23
+
24
+ ```typescript
25
+ function registerBuiltinAdapters(factories: {
26
+ userFactory: RepositoryFactory<UserRepository>;
27
+ codeFactory: RepositoryFactory<CodeRepository>;
28
+ pathResolver?: PathResolver; // 任意 — "redis" モジュールのパス解決に使用
29
+ }): void;
30
+ ```
31
+
32
+ ### `HttpUserRepository`
33
+
34
+ 上流の HTTP サービスに認証処理を委譲する `UserRepository` 実装。
35
+
36
+ ```typescript
37
+ class HttpUserRepository implements UserRepository {
38
+ constructor(options: {
39
+ authenticateUrl: string; // ユーザー名・パスワード認証用の POST エンドポイント
40
+ authenticateByTokenUrl: string; // トークン認証用の POST エンドポイント
41
+ timeout: number; // リクエストタイムアウト(ミリ秒)
42
+ });
43
+
44
+ // authenticateUrl に対して { email, password } を POST
45
+ authenticate(username: string, password: string): Promise<User | null>;
46
+
47
+ // authenticateByTokenUrl に対して { token } を POST
48
+ authenticateByToken(token: string): Promise<User | null>;
49
+ }
50
+ ```
51
+
52
+ - HTTP 401 または 403 の場合は `null` を返す。
53
+ - その他の非 OK ステータスの場合はエラーをスローする。
54
+
55
+ ### `RedisCodeRepository`
56
+
57
+ Redis に認可コードを保存する `CodeRepository` 実装。キーは `oauth:code:<base64url-code>` 形式で保存され、TTL を設定できる。
58
+
59
+ ```typescript
60
+ class RedisCodeRepository implements CodeRepository {
61
+ constructor(redis: RedisClient, defaultExpiresIn?: number); // defaultExpiresIn のデフォルトは 600 秒
62
+
63
+ // ファクトリーメソッド — config から Redis クライアントを生成して接続する
64
+ static create(
65
+ config: Record<string, unknown>,
66
+ pathResolver?: PathResolver,
67
+ ): Promise<RedisCodeRepository>;
68
+ // config のキー:
69
+ // endpointUri (string, 必須) — Redis 接続 URI
70
+ // password (string, 任意) — Redis パスワード
71
+ // defaultExpiresIn (number, 任意) — TTL(秒)、デフォルト 600
72
+
73
+ initialize(): Promise<void>; // Redis クライアントを接続する
74
+ createCode(params: {
75
+ code_challenge?: string;
76
+ code_challenge_method?: string;
77
+ expiresIn?: number; // このコードだけ defaultExpiresIn を上書きする
78
+ }): Promise<Code>;
79
+ getByCode(code: string): Promise<Code | null>;
80
+ consumeByCode(code: string): Promise<Code | null>; // アトミックな GET + DEL
81
+ removeByCode(code: string): Promise<void>;
82
+ }
83
+ ```
84
+
85
+ ## 使い方
86
+
87
+ ```typescript
88
+ import { createDefaultFactories } from "@o3co/auth-provider-core";
89
+ import { registerBuiltinAdapters } from "@o3co/auth-provider-foundation";
90
+
91
+ const { userFactory, codeFactory } = createDefaultFactories();
92
+
93
+ registerBuiltinAdapters({ userFactory, codeFactory });
94
+
95
+ // ファクトリー経由で HTTP ユーザーリポジトリを生成
96
+ const userRepo = await userFactory.create({
97
+ type: "http",
98
+ authenticateUrl: "https://users.example.com/authenticate",
99
+ authenticateByTokenUrl: "https://users.example.com/authenticate-by-token",
100
+ timeout: 5000,
101
+ });
102
+
103
+ // ファクトリー経由で Redis コードリポジトリを生成
104
+ const codeRepo = await codeFactory.create({
105
+ type: "redis",
106
+ endpointUri: "redis://localhost:6379",
107
+ defaultExpiresIn: 300,
108
+ });
109
+ ```
110
+
111
+ ## 関連
112
+
113
+ - [`@o3co/auth-provider-core`](../core/README.md) — コアインターフェース(`UserRepository`、`CodeRepository`、`RepositoryFactory`、`PathResolver`)
114
+ - [auth.provider](../../README.md) — リポジトリ全体のドキュメント
package/README.md ADDED
@@ -0,0 +1,114 @@
1
+ # @o3co/auth-provider-foundation
2
+
3
+ Built-in repository implementations for auth.provider. Provides HTTP-based user authentication and Redis-backed authorization code storage.
4
+
5
+ ## Install
6
+
7
+ ```sh
8
+ npm install @o3co/auth-provider-foundation
9
+ # Peer dependency (required):
10
+ npm install @o3co/auth-provider-core
11
+ # Peer dependency (optional — required only when using RedisCodeRepository):
12
+ npm install redis
13
+ ```
14
+
15
+ ## Public API
16
+
17
+ ### `registerBuiltinAdapters`
18
+
19
+ Registers the built-in adapter factories into the provided factory instances.
20
+
21
+ - Registers `"http"` into `userFactory` → creates `HttpUserRepository`
22
+ - Registers `"redis"` into `codeFactory` → creates `RedisCodeRepository`
23
+
24
+ ```typescript
25
+ function registerBuiltinAdapters(factories: {
26
+ userFactory: RepositoryFactory<UserRepository>;
27
+ codeFactory: RepositoryFactory<CodeRepository>;
28
+ pathResolver?: PathResolver; // optional — used to resolve the "redis" module path
29
+ }): void;
30
+ ```
31
+
32
+ ### `HttpUserRepository`
33
+
34
+ A `UserRepository` implementation that delegates authentication to an upstream HTTP service.
35
+
36
+ ```typescript
37
+ class HttpUserRepository implements UserRepository {
38
+ constructor(options: {
39
+ authenticateUrl: string; // POST endpoint for username/password auth
40
+ authenticateByTokenUrl: string; // POST endpoint for token-based auth
41
+ timeout: number; // request timeout in milliseconds
42
+ });
43
+
44
+ // POST authenticateUrl with body: { email, password }
45
+ authenticate(username: string, password: string): Promise<User | null>;
46
+
47
+ // POST authenticateByTokenUrl with body: { token }
48
+ authenticateByToken(token: string): Promise<User | null>;
49
+ }
50
+ ```
51
+
52
+ - Returns `null` on HTTP 401 or 403.
53
+ - Throws an error on any other non-OK HTTP status.
54
+
55
+ ### `RedisCodeRepository`
56
+
57
+ A `CodeRepository` implementation that stores authorization codes in Redis. Keys are stored as `oauth:code:<base64url-code>` with a configurable TTL.
58
+
59
+ ```typescript
60
+ class RedisCodeRepository implements CodeRepository {
61
+ constructor(redis: RedisClient, defaultExpiresIn?: number); // defaultExpiresIn defaults to 600 seconds
62
+
63
+ // Factory method — creates and connects a Redis client from config
64
+ static create(
65
+ config: Record<string, unknown>,
66
+ pathResolver?: PathResolver,
67
+ ): Promise<RedisCodeRepository>;
68
+ // config keys:
69
+ // endpointUri (string, required) — Redis connection URI
70
+ // password (string, optional) — Redis password
71
+ // defaultExpiresIn (number, optional) — TTL in seconds, default 600
72
+
73
+ initialize(): Promise<void>; // connects the Redis client
74
+ createCode(params: {
75
+ code_challenge?: string;
76
+ code_challenge_method?: string;
77
+ expiresIn?: number; // overrides defaultExpiresIn for this code
78
+ }): Promise<Code>;
79
+ getByCode(code: string): Promise<Code | null>;
80
+ consumeByCode(code: string): Promise<Code | null>; // atomic GET + DEL
81
+ removeByCode(code: string): Promise<void>;
82
+ }
83
+ ```
84
+
85
+ ## Usage Example
86
+
87
+ ```typescript
88
+ import { createDefaultFactories } from "@o3co/auth-provider-core";
89
+ import { registerBuiltinAdapters } from "@o3co/auth-provider-foundation";
90
+
91
+ const { userFactory, codeFactory } = createDefaultFactories();
92
+
93
+ registerBuiltinAdapters({ userFactory, codeFactory });
94
+
95
+ // Create an HTTP user repository via the factory
96
+ const userRepo = await userFactory.create({
97
+ type: "http",
98
+ authenticateUrl: "https://users.example.com/authenticate",
99
+ authenticateByTokenUrl: "https://users.example.com/authenticate-by-token",
100
+ timeout: 5000,
101
+ });
102
+
103
+ // Create a Redis code repository via the factory
104
+ const codeRepo = await codeFactory.create({
105
+ type: "redis",
106
+ endpointUri: "redis://localhost:6379",
107
+ defaultExpiresIn: 300,
108
+ });
109
+ ```
110
+
111
+ ## See Also
112
+
113
+ - [`@o3co/auth-provider-core`](../core/README.md) — Core interfaces (`UserRepository`, `CodeRepository`, `RepositoryFactory`, `PathResolver`)
114
+ - [auth.provider](../../README.md) — Top-level repository documentation
@@ -0,0 +1,9 @@
1
+ import type { CodeRepository, PathResolver, RepositoryFactory, UserRepository } from "@o3co/auth-provider-core";
2
+ export declare const registerBuiltinAdapters: (factories: {
3
+ userFactory: RepositoryFactory<UserRepository>;
4
+ codeFactory: RepositoryFactory<CodeRepository>;
5
+ pathResolver?: PathResolver;
6
+ }) => void;
7
+ export { HttpUserRepository } from "./repositories/HttpUserRepository.mjs";
8
+ export { RedisCodeRepository } from "./repositories/RedisCodeRepository.mjs";
9
+ //# sourceMappingURL=index.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.mts","sourceRoot":"","sources":["../src/index.mts"],"names":[],"mappings":"AAgBA,OAAO,KAAK,EAAE,cAAc,EAAE,YAAY,EAAE,iBAAiB,EAAE,cAAc,EAAE,MAAM,0BAA0B,CAAC;AAIhH,eAAO,MAAM,uBAAuB,GAAI,WAAW;IAClD,WAAW,EAAE,iBAAiB,CAAC,cAAc,CAAC,CAAC;IAC/C,WAAW,EAAE,iBAAiB,CAAC,cAAc,CAAC,CAAC;IAC/C,YAAY,CAAC,EAAE,YAAY,CAAC;CAC5B,KAAG,IAsBH,CAAC;AAEF,OAAO,EAAE,kBAAkB,EAAE,MAAM,uCAAuC,CAAC;AAC3E,OAAO,EAAE,mBAAmB,EAAE,MAAM,wCAAwC,CAAC"}
package/dist/index.mjs ADDED
@@ -0,0 +1,41 @@
1
+ /*
2
+ * Copyright 2026 1o1 Co. Ltd.
3
+ *
4
+ * Licensed under the Apache License, Version 2.0 (the "License");
5
+ * you may not use this file except in compliance with the License.
6
+ * You may obtain a copy of the License at
7
+ *
8
+ * http://www.apache.org/licenses/LICENSE-2.0
9
+ *
10
+ * Unless required by applicable law or agreed to in writing, software
11
+ * distributed under the License is distributed on an "AS IS" BASIS,
12
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ * See the License for the specific language governing permissions and
14
+ * limitations under the License.
15
+ */
16
+ import { HttpUserRepository } from "./repositories/HttpUserRepository.mjs";
17
+ import { RedisCodeRepository } from "./repositories/RedisCodeRepository.mjs";
18
+ export const registerBuiltinAdapters = (factories) => {
19
+ const { pathResolver } = factories;
20
+ factories.userFactory.register("http", (config) => {
21
+ if (typeof config.authenticateUrl !== "string") {
22
+ throw new Error('HttpUserRepository requires "authenticateUrl" in config');
23
+ }
24
+ if (typeof config.authenticateByTokenUrl !== "string") {
25
+ throw new Error('HttpUserRepository requires "authenticateByTokenUrl" in config');
26
+ }
27
+ return new HttpUserRepository({
28
+ authenticateUrl: config.authenticateUrl,
29
+ authenticateByTokenUrl: config.authenticateByTokenUrl,
30
+ timeout: typeof config.timeout === "number" ? config.timeout : 5000,
31
+ });
32
+ });
33
+ factories.codeFactory.register("redis", (config) => {
34
+ if (typeof config.endpointUri !== "string") {
35
+ throw new Error('RedisCodeRepository requires "endpointUri" in config');
36
+ }
37
+ return RedisCodeRepository.create(config, pathResolver);
38
+ });
39
+ };
40
+ export { HttpUserRepository } from "./repositories/HttpUserRepository.mjs";
41
+ export { RedisCodeRepository } from "./repositories/RedisCodeRepository.mjs";
@@ -0,0 +1,15 @@
1
+ import type { User, UserRepository } from "@o3co/auth-provider-core";
2
+ export declare class HttpUserRepository implements UserRepository {
3
+ private authenticateUrl;
4
+ private authenticateByTokenUrl;
5
+ private timeout;
6
+ constructor({ authenticateUrl, authenticateByTokenUrl, timeout, }: {
7
+ authenticateUrl: string;
8
+ authenticateByTokenUrl: string;
9
+ timeout: number;
10
+ });
11
+ authenticate(username: string, password: string): Promise<User | null>;
12
+ authenticateByToken(token: string): Promise<User | null>;
13
+ private post;
14
+ }
15
+ //# sourceMappingURL=HttpUserRepository.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"HttpUserRepository.d.mts","sourceRoot":"","sources":["../../src/repositories/HttpUserRepository.mts"],"names":[],"mappings":"AAgBA,OAAO,KAAK,EAAE,IAAI,EAAE,cAAc,EAAE,MAAM,0BAA0B,CAAC;AAErE,qBAAa,kBAAmB,YAAW,cAAc;IACxD,OAAO,CAAC,eAAe,CAAS;IAChC,OAAO,CAAC,sBAAsB,CAAS;IACvC,OAAO,CAAC,OAAO,CAAS;gBAEZ,EACX,eAAe,EACf,sBAAsB,EACtB,OAAO,GACP,EAAE;QACF,eAAe,EAAE,MAAM,CAAC;QACxB,sBAAsB,EAAE,MAAM,CAAC;QAC/B,OAAO,EAAE,MAAM,CAAC;KAChB;IAMK,YAAY,CAAC,QAAQ,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,GAAG,IAAI,CAAC;IAItE,mBAAmB,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,GAAG,IAAI,CAAC;YAIhD,IAAI;CAyBlB"}
@@ -0,0 +1,53 @@
1
+ /*
2
+ * Copyright 2026 1o1 Co. Ltd.
3
+ *
4
+ * Licensed under the Apache License, Version 2.0 (the "License");
5
+ * you may not use this file except in compliance with the License.
6
+ * You may obtain a copy of the License at
7
+ *
8
+ * http://www.apache.org/licenses/LICENSE-2.0
9
+ *
10
+ * Unless required by applicable law or agreed to in writing, software
11
+ * distributed under the License is distributed on an "AS IS" BASIS,
12
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ * See the License for the specific language governing permissions and
14
+ * limitations under the License.
15
+ */
16
+ export class HttpUserRepository {
17
+ authenticateUrl;
18
+ authenticateByTokenUrl;
19
+ timeout;
20
+ constructor({ authenticateUrl, authenticateByTokenUrl, timeout, }) {
21
+ this.authenticateUrl = authenticateUrl;
22
+ this.authenticateByTokenUrl = authenticateByTokenUrl;
23
+ this.timeout = timeout;
24
+ }
25
+ async authenticate(username, password) {
26
+ return this.post(this.authenticateUrl, { email: username, password });
27
+ }
28
+ async authenticateByToken(token) {
29
+ return this.post(this.authenticateByTokenUrl, { token });
30
+ }
31
+ async post(url, body) {
32
+ const controller = new AbortController();
33
+ const timer = setTimeout(() => controller.abort(), this.timeout);
34
+ try {
35
+ const res = await fetch(url, {
36
+ method: "POST",
37
+ headers: { "Content-Type": "application/json" },
38
+ body: JSON.stringify(body),
39
+ signal: controller.signal,
40
+ });
41
+ if (res.ok) {
42
+ return (await res.json());
43
+ }
44
+ if (res.status === 401 || res.status === 403) {
45
+ return null;
46
+ }
47
+ throw new Error(`Unexpected HTTP status ${res.status} from ${url}`);
48
+ }
49
+ finally {
50
+ clearTimeout(timer);
51
+ }
52
+ }
53
+ }
@@ -0,0 +1,28 @@
1
+ import type { Code, CodeRepository, PathResolver } from "@o3co/auth-provider-core";
2
+ interface RedisClient {
3
+ connect(): Promise<void>;
4
+ get(key: string): Promise<string | null>;
5
+ set(key: string, value: string, options?: {
6
+ EX?: number;
7
+ }): Promise<unknown>;
8
+ getDel(key: string): Promise<string | null>;
9
+ del(key: string): Promise<number>;
10
+ }
11
+ export declare class RedisCodeRepository implements CodeRepository {
12
+ private redis;
13
+ private defaultExpiresIn;
14
+ constructor(redis: RedisClient, defaultExpiresIn?: number);
15
+ static create(config: Record<string, unknown>, pathResolver?: PathResolver): Promise<RedisCodeRepository>;
16
+ initialize(): Promise<void>;
17
+ createCode({ code_challenge, code_challenge_method, expiresIn, }: {
18
+ code_challenge?: string;
19
+ code_challenge_method?: string;
20
+ expiresIn?: number;
21
+ }): Promise<Code>;
22
+ getByCode(code: string): Promise<Code | null>;
23
+ consumeByCode(code: string): Promise<Code | null>;
24
+ removeByCode(code: string): Promise<void>;
25
+ private parseCodeValue;
26
+ }
27
+ export {};
28
+ //# sourceMappingURL=RedisCodeRepository.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"RedisCodeRepository.d.mts","sourceRoot":"","sources":["../../src/repositories/RedisCodeRepository.mts"],"names":[],"mappings":"AAiBA,OAAO,KAAK,EAAE,IAAI,EAAE,cAAc,EAAE,YAAY,EAAE,MAAM,0BAA0B,CAAC;AAMnF,UAAU,WAAW;IACpB,OAAO,IAAI,OAAO,CAAC,IAAI,CAAC,CAAC;IACzB,GAAG,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,GAAG,IAAI,CAAC,CAAC;IACzC,GAAG,CAAC,GAAG,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE;QAAE,EAAE,CAAC,EAAE,MAAM,CAAA;KAAE,GAAG,OAAO,CAAC,OAAO,CAAC,CAAC;IAC7E,MAAM,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,GAAG,IAAI,CAAC,CAAC;IAC5C,GAAG,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC,CAAC;CAClC;AAED,qBAAa,mBAAoB,YAAW,cAAc;IACzD,OAAO,CAAC,KAAK,CAAc;IAC3B,OAAO,CAAC,gBAAgB,CAAS;gBAErB,KAAK,EAAE,WAAW,EAAE,gBAAgB,SAAM;WAKzC,MAAM,CAClB,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAC/B,YAAY,CAAC,EAAE,YAAY,GACzB,OAAO,CAAC,mBAAmB,CAAC;IA2BzB,UAAU,IAAI,OAAO,CAAC,IAAI,CAAC;IAI3B,UAAU,CAAC,EAChB,cAAc,EACd,qBAAqB,EACrB,SAAiC,GACjC,EAAE;QACF,cAAc,CAAC,EAAE,MAAM,CAAC;QACxB,qBAAqB,CAAC,EAAE,MAAM,CAAC;QAC/B,SAAS,CAAC,EAAE,MAAM,CAAC;KACnB,GAAG,OAAO,CAAC,IAAI,CAAC;IAYX,SAAS,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,GAAG,IAAI,CAAC;IAK7C,aAAa,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,GAAG,IAAI,CAAC;IAKjD,YAAY,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IAI/C,OAAO,CAAC,cAAc;CAUtB"}
@@ -0,0 +1,79 @@
1
+ /*
2
+ * Copyright 2026 1o1 Co. Ltd.
3
+ *
4
+ * Licensed under the Apache License, Version 2.0 (the "License");
5
+ * you may not use this file except in compliance with the License.
6
+ * You may obtain a copy of the License at
7
+ *
8
+ * http://www.apache.org/licenses/LICENSE-2.0
9
+ *
10
+ * Unless required by applicable law or agreed to in writing, software
11
+ * distributed under the License is distributed on an "AS IS" BASIS,
12
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ * See the License for the specific language governing permissions and
14
+ * limitations under the License.
15
+ */
16
+ import crypto from "node:crypto";
17
+ const KEY_PREFIX = "oauth:code:";
18
+ export class RedisCodeRepository {
19
+ redis;
20
+ defaultExpiresIn;
21
+ constructor(redis, defaultExpiresIn = 600) {
22
+ this.redis = redis;
23
+ this.defaultExpiresIn = defaultExpiresIn;
24
+ }
25
+ static async create(config, pathResolver) {
26
+ if (typeof config.endpointUri !== "string") {
27
+ throw new Error('RedisCodeRepository requires "endpointUri" in config');
28
+ }
29
+ const { createClient } = pathResolver
30
+ ? (await import(pathResolver("redis")))
31
+ : await import("redis");
32
+ const redis = createClient({
33
+ url: config.endpointUri,
34
+ password: typeof config.password === "string" ? config.password : undefined,
35
+ socket: {
36
+ reconnectStrategy: (retries) => {
37
+ const jitter = Math.floor(Math.random() * 200);
38
+ const delay = Math.min(2 ** retries * 50, 2000);
39
+ return delay + jitter;
40
+ },
41
+ },
42
+ });
43
+ const defaultExpiresIn = typeof config.defaultExpiresIn === "number" ? config.defaultExpiresIn : undefined;
44
+ const repo = new RedisCodeRepository(redis, defaultExpiresIn);
45
+ await repo.initialize();
46
+ return repo;
47
+ }
48
+ async initialize() {
49
+ await this.redis.connect();
50
+ }
51
+ async createCode({ code_challenge, code_challenge_method, expiresIn = this.defaultExpiresIn, }) {
52
+ const code = crypto.randomBytes(32).toString("base64url");
53
+ await this.redis.set(KEY_PREFIX + code, JSON.stringify({ code_challenge, code_challenge_method }), { EX: expiresIn });
54
+ return { code, code_challenge, code_challenge_method, expiresIn };
55
+ }
56
+ async getByCode(code) {
57
+ const value = await this.redis.get(KEY_PREFIX + code);
58
+ return this.parseCodeValue(code, value);
59
+ }
60
+ async consumeByCode(code) {
61
+ const value = await this.redis.getDel(KEY_PREFIX + code);
62
+ return this.parseCodeValue(code, value);
63
+ }
64
+ async removeByCode(code) {
65
+ await this.redis.del(KEY_PREFIX + code);
66
+ }
67
+ parseCodeValue(code, value) {
68
+ if (!value)
69
+ return null;
70
+ try {
71
+ return { ...JSON.parse(value), code };
72
+ }
73
+ catch (err) {
74
+ const codeHash = crypto.createHash("sha256").update(code).digest("hex").slice(0, 16);
75
+ console.error(`RedisCodeRepository: corrupted data for code (hash=${codeHash})`, err);
76
+ return null;
77
+ }
78
+ }
79
+ }
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=HttpUserRepository.test.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"HttpUserRepository.test.d.mts","sourceRoot":"","sources":["../../../src/repositories/__tests__/HttpUserRepository.test.mts"],"names":[],"mappings":""}
@@ -0,0 +1,89 @@
1
+ /*
2
+ * Copyright 2026 1o1 Co. Ltd.
3
+ *
4
+ * Licensed under the Apache License, Version 2.0 (the "License");
5
+ * you may not use this file except in compliance with the License.
6
+ * You may obtain a copy of the License at
7
+ *
8
+ * http://www.apache.org/licenses/LICENSE-2.0
9
+ *
10
+ * Unless required by applicable law or agreed to in writing, software
11
+ * distributed under the License is distributed on an "AS IS" BASIS,
12
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ * See the License for the specific language governing permissions and
14
+ * limitations under the License.
15
+ */
16
+ import { HttpResponse, http } from "msw";
17
+ import { setupServer } from "msw/node";
18
+ import { afterAll, afterEach, beforeAll, describe, expect, it } from "vitest";
19
+ import { HttpUserRepository } from "../HttpUserRepository.mjs";
20
+ const BASE_URL = "http://localhost:18080";
21
+ const mockUser = { id: "user-1", username: "alice" };
22
+ const handlers = [
23
+ http.post(`${BASE_URL}/user/authenticate`, async ({ request }) => {
24
+ const body = (await request.json());
25
+ if (body.email === "alice@example.com" && body.password === "correct-pass") {
26
+ return HttpResponse.json(mockUser, { status: 200 });
27
+ }
28
+ return new HttpResponse(null, { status: 401 });
29
+ }),
30
+ http.post(`${BASE_URL}/user/authenticate/token`, async ({ request }) => {
31
+ const body = (await request.json());
32
+ if (body.token === "valid-token") {
33
+ return HttpResponse.json(mockUser, { status: 200 });
34
+ }
35
+ return new HttpResponse(null, { status: 401 });
36
+ }),
37
+ ];
38
+ const server = setupServer(...handlers);
39
+ beforeAll(() => server.listen({ onUnhandledRequest: "error" }));
40
+ afterEach(() => server.resetHandlers());
41
+ afterAll(() => server.close());
42
+ describe("HttpUserRepository", () => {
43
+ const repo = new HttpUserRepository({
44
+ authenticateUrl: `${BASE_URL}/user/authenticate`,
45
+ authenticateByTokenUrl: `${BASE_URL}/user/authenticate/token`,
46
+ timeout: 5000,
47
+ });
48
+ describe("authenticate", () => {
49
+ it("returns user on success", async () => {
50
+ const user = await repo.authenticate("alice@example.com", "correct-pass");
51
+ expect(user).not.toBeNull();
52
+ expect(user?.id).toBe("user-1");
53
+ expect(user?.username).toBe("alice");
54
+ });
55
+ it("sends email field (not username) in request body", async () => {
56
+ let capturedBody = null;
57
+ server.use(http.post(`${BASE_URL}/user/authenticate`, async ({ request }) => {
58
+ capturedBody = (await request.json());
59
+ return HttpResponse.json(mockUser, { status: 200 });
60
+ }));
61
+ await repo.authenticate("alice@example.com", "correct-pass");
62
+ expect(capturedBody).not.toBeNull();
63
+ expect(capturedBody).toHaveProperty("email", "alice@example.com");
64
+ expect(capturedBody).not.toHaveProperty("username");
65
+ });
66
+ it("returns null on 401", async () => {
67
+ const user = await repo.authenticate("alice@example.com", "wrong-pass");
68
+ expect(user).toBeNull();
69
+ });
70
+ it("throws on unexpected HTTP status", async () => {
71
+ server.use(http.post(`${BASE_URL}/user/authenticate`, () => {
72
+ return new HttpResponse(null, { status: 500 });
73
+ }));
74
+ await expect(repo.authenticate("alice@example.com", "pass")).rejects.toThrow("Unexpected HTTP status 500");
75
+ });
76
+ });
77
+ describe("authenticateByToken", () => {
78
+ it("returns user on success", async () => {
79
+ const user = await repo.authenticateByToken("valid-token");
80
+ expect(user).not.toBeNull();
81
+ expect(user?.id).toBe("user-1");
82
+ expect(user?.username).toBe("alice");
83
+ });
84
+ it("returns null on 401", async () => {
85
+ const user = await repo.authenticateByToken("invalid-token");
86
+ expect(user).toBeNull();
87
+ });
88
+ });
89
+ });
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=RedisCodeRepository.test.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"RedisCodeRepository.test.d.mts","sourceRoot":"","sources":["../../../src/repositories/__tests__/RedisCodeRepository.test.mts"],"names":[],"mappings":""}
@@ -0,0 +1,141 @@
1
+ /*
2
+ * Copyright 2026 1o1 Co. Ltd.
3
+ *
4
+ * Licensed under the Apache License, Version 2.0 (the "License");
5
+ * you may not use this file except in compliance with the License.
6
+ * You may obtain a copy of the License at
7
+ *
8
+ * http://www.apache.org/licenses/LICENSE-2.0
9
+ *
10
+ * Unless required by applicable law or agreed to in writing, software
11
+ * distributed under the License is distributed on an "AS IS" BASIS,
12
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ * See the License for the specific language governing permissions and
14
+ * limitations under the License.
15
+ */
16
+ import { beforeEach, describe, expect, it, vi } from "vitest";
17
+ const KEY_PREFIX = "oauth:code:";
18
+ // In-memory store simulating Redis
19
+ const store = new Map();
20
+ import { RedisCodeRepository } from "../RedisCodeRepository.mjs";
21
+ const createMockRedis = () => ({
22
+ connect: vi.fn().mockResolvedValue(undefined),
23
+ set: vi.fn().mockImplementation((key, value) => {
24
+ store.set(key, value);
25
+ return Promise.resolve("OK");
26
+ }),
27
+ get: vi.fn().mockImplementation((key) => {
28
+ return Promise.resolve(store.get(key) ?? null);
29
+ }),
30
+ getDel: vi.fn().mockImplementation((key) => {
31
+ const value = store.get(key) ?? null;
32
+ store.delete(key);
33
+ return Promise.resolve(value);
34
+ }),
35
+ del: vi.fn().mockImplementation((key) => {
36
+ store.delete(key);
37
+ return Promise.resolve(1);
38
+ }),
39
+ });
40
+ describe("RedisCodeRepository", () => {
41
+ let repo;
42
+ beforeEach(async () => {
43
+ store.clear();
44
+ const redis = createMockRedis();
45
+ repo = new RedisCodeRepository(redis);
46
+ await repo.initialize();
47
+ });
48
+ describe("createCode", () => {
49
+ it("generates a code string and stores it", async () => {
50
+ const result = await repo.createCode({});
51
+ expect(typeof result.code).toBe("string");
52
+ expect(result.code.length).toBeGreaterThan(0);
53
+ // Verify it was stored with namespace prefix
54
+ expect(store.has(`${KEY_PREFIX}${result.code}`)).toBe(true);
55
+ });
56
+ it("returns code with code_challenge and code_challenge_method", async () => {
57
+ const result = await repo.createCode({
58
+ code_challenge: "abc123",
59
+ code_challenge_method: "S256",
60
+ });
61
+ expect(result.code_challenge).toBe("abc123");
62
+ expect(result.code_challenge_method).toBe("S256");
63
+ });
64
+ it("stores code_challenge and code_challenge_method in Redis", async () => {
65
+ const result = await repo.createCode({
66
+ code_challenge: "challenge-value",
67
+ code_challenge_method: "S256",
68
+ });
69
+ const stored = store.get(`${KEY_PREFIX}${result.code}`);
70
+ expect(stored).toBeDefined();
71
+ const parsed = JSON.parse(stored);
72
+ expect(parsed.code_challenge).toBe("challenge-value");
73
+ expect(parsed.code_challenge_method).toBe("S256");
74
+ });
75
+ it("uses default expiresIn when not provided", async () => {
76
+ const result = await repo.createCode({});
77
+ expect(result.expiresIn).toBe(600);
78
+ });
79
+ it("uses provided expiresIn", async () => {
80
+ const result = await repo.createCode({ expiresIn: 300 });
81
+ expect(result.expiresIn).toBe(300);
82
+ });
83
+ });
84
+ describe("getByCode", () => {
85
+ it("returns stored code data", async () => {
86
+ const created = await repo.createCode({
87
+ code_challenge: "test-challenge",
88
+ code_challenge_method: "S256",
89
+ });
90
+ const found = await repo.getByCode(created.code);
91
+ expect(found).not.toBeNull();
92
+ expect(found?.code).toBe(created.code);
93
+ expect(found?.code_challenge).toBe("test-challenge");
94
+ expect(found?.code_challenge_method).toBe("S256");
95
+ });
96
+ it("returns null for unknown code", async () => {
97
+ const result = await repo.getByCode("nonexistent-code");
98
+ expect(result).toBeNull();
99
+ });
100
+ it("returns null for corrupted data", async () => {
101
+ store.set(`${KEY_PREFIX}corrupted`, "not-valid-json{{{");
102
+ const result = await repo.getByCode("corrupted");
103
+ expect(result).toBeNull();
104
+ });
105
+ });
106
+ describe("consumeByCode", () => {
107
+ it("returns code data and removes it atomically", async () => {
108
+ const created = await repo.createCode({
109
+ code_challenge: "consume-test",
110
+ code_challenge_method: "S256",
111
+ });
112
+ const consumed = await repo.consumeByCode(created.code);
113
+ expect(consumed).not.toBeNull();
114
+ expect(consumed?.code).toBe(created.code);
115
+ expect(consumed?.code_challenge).toBe("consume-test");
116
+ // Should be gone from store
117
+ expect(store.has(`${KEY_PREFIX}${created.code}`)).toBe(false);
118
+ });
119
+ it("returns null for unknown code", async () => {
120
+ expect(await repo.consumeByCode("nonexistent")).toBeNull();
121
+ });
122
+ it("second consume returns null (replay prevention)", async () => {
123
+ const created = await repo.createCode({});
124
+ const first = await repo.consumeByCode(created.code);
125
+ expect(first).not.toBeNull();
126
+ const second = await repo.consumeByCode(created.code);
127
+ expect(second).toBeNull();
128
+ });
129
+ });
130
+ describe("removeByCode", () => {
131
+ it("removes a stored code", async () => {
132
+ const created = await repo.createCode({ code_challenge: "c" });
133
+ expect(store.has(`${KEY_PREFIX}${created.code}`)).toBe(true);
134
+ await repo.removeByCode(created.code);
135
+ expect(store.has(`${KEY_PREFIX}${created.code}`)).toBe(false);
136
+ });
137
+ it("does not throw for unknown code", async () => {
138
+ await expect(repo.removeByCode("nonexistent")).resolves.toBeUndefined();
139
+ });
140
+ });
141
+ });
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=registerBuiltinAdapters.test.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"registerBuiltinAdapters.test.d.mts","sourceRoot":"","sources":["../../../src/repositories/__tests__/registerBuiltinAdapters.test.mts"],"names":[],"mappings":""}
@@ -0,0 +1,82 @@
1
+ /*
2
+ * Copyright 2026 1o1 Co. Ltd.
3
+ *
4
+ * Licensed under the Apache License, Version 2.0 (the "License");
5
+ * you may not use this file except in compliance with the License.
6
+ * You may obtain a copy of the License at
7
+ *
8
+ * http://www.apache.org/licenses/LICENSE-2.0
9
+ *
10
+ * Unless required by applicable law or agreed to in writing, software
11
+ * distributed under the License is distributed on an "AS IS" BASIS,
12
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ * See the License for the specific language governing permissions and
14
+ * limitations under the License.
15
+ */
16
+ import { RepositoryFactory } from "@o3co/auth-provider-core";
17
+ import { HttpResponse, http } from "msw";
18
+ import { setupServer } from "msw/node";
19
+ import { afterAll, afterEach, beforeAll, describe, expect, it } from "vitest";
20
+ import { registerBuiltinAdapters } from "#/index.mjs";
21
+ const BASE_URL = "http://localhost:19090";
22
+ const mockUser = { id: "u1", username: "alice" };
23
+ const server = setupServer(http.post(`${BASE_URL}/auth`, async ({ request }) => {
24
+ const body = (await request.json());
25
+ if (body.email === "alice" && body.password === "pass") {
26
+ return HttpResponse.json(mockUser, { status: 200 });
27
+ }
28
+ return new HttpResponse(null, { status: 401 });
29
+ }), http.post(`${BASE_URL}/auth/token`, async ({ request }) => {
30
+ const body = (await request.json());
31
+ if (body.token === "valid") {
32
+ return HttpResponse.json(mockUser, { status: 200 });
33
+ }
34
+ return new HttpResponse(null, { status: 401 });
35
+ }));
36
+ beforeAll(() => server.listen({ onUnhandledRequest: "error" }));
37
+ afterEach(() => server.resetHandlers());
38
+ afterAll(() => server.close());
39
+ describe("registerBuiltinAdapters", () => {
40
+ it("registers 'http' type in userFactory", async () => {
41
+ const userFactory = new RepositoryFactory("user");
42
+ const codeFactory = new RepositoryFactory("code");
43
+ registerBuiltinAdapters({ userFactory, codeFactory });
44
+ await expect(userFactory.create({ type: "unknown" })).rejects.toThrow(/http/);
45
+ });
46
+ it("registers 'redis' type in codeFactory", async () => {
47
+ const userFactory = new RepositoryFactory("user");
48
+ const codeFactory = new RepositoryFactory("code");
49
+ registerBuiltinAdapters({ userFactory, codeFactory });
50
+ await expect(codeFactory.create({ type: "unknown" })).rejects.toThrow(/redis/);
51
+ });
52
+ it("http builder creates a working HttpUserRepository", async () => {
53
+ const userFactory = new RepositoryFactory("user");
54
+ const codeFactory = new RepositoryFactory("code");
55
+ registerBuiltinAdapters({ userFactory, codeFactory });
56
+ const repo = await userFactory.create({
57
+ type: "http",
58
+ authenticateUrl: `${BASE_URL}/auth`,
59
+ authenticateByTokenUrl: `${BASE_URL}/auth/token`,
60
+ timeout: 5000,
61
+ });
62
+ const user = await repo.authenticate("alice", "pass");
63
+ expect(user).not.toBeNull();
64
+ expect(user?.username).toBe("alice");
65
+ const byToken = await repo.authenticateByToken("valid");
66
+ expect(byToken).not.toBeNull();
67
+ const invalid = await repo.authenticate("alice", "wrong");
68
+ expect(invalid).toBeNull();
69
+ });
70
+ it("http builder throws when authenticateUrl is missing", async () => {
71
+ const userFactory = new RepositoryFactory("user");
72
+ const codeFactory = new RepositoryFactory("code");
73
+ registerBuiltinAdapters({ userFactory, codeFactory });
74
+ await expect(userFactory.create({ type: "http", timeout: 5000 })).rejects.toThrow(/authenticateUrl/);
75
+ });
76
+ it("redis builder throws when endpointUri is missing", async () => {
77
+ const userFactory = new RepositoryFactory("user");
78
+ const codeFactory = new RepositoryFactory("code");
79
+ registerBuiltinAdapters({ userFactory, codeFactory });
80
+ await expect(codeFactory.create({ type: "redis" })).rejects.toThrow(/endpointUri/);
81
+ });
82
+ });
package/package.json ADDED
@@ -0,0 +1,52 @@
1
+ {
2
+ "name": "@o3co/auth-provider-foundation",
3
+ "description": "Production adapters for auth.provider",
4
+ "version": "0.1.0",
5
+ "license": "Apache-2.0",
6
+ "type": "module",
7
+ "main": "./dist/index.mjs",
8
+ "types": "./dist/index.d.mts",
9
+ "exports": {
10
+ ".": {
11
+ "import": "./dist/index.mjs",
12
+ "types": "./dist/index.d.mts"
13
+ }
14
+ },
15
+ "files": [
16
+ "dist",
17
+ "README.md",
18
+ "LICENSE"
19
+ ],
20
+ "repository": {
21
+ "type": "git",
22
+ "url": "https://github.com/o3co/auth.provider.git",
23
+ "directory": "packages/foundation"
24
+ },
25
+ "imports": {
26
+ "#/*": {
27
+ "development": "./src/*",
28
+ "default": "./dist/*"
29
+ }
30
+ },
31
+ "peerDependencies": {
32
+ "@o3co/auth-provider-core": "^0.0.0",
33
+ "redis": "^5.10.0"
34
+ },
35
+ "peerDependenciesMeta": {
36
+ "redis": {
37
+ "optional": true
38
+ }
39
+ },
40
+ "devDependencies": {
41
+ "@types/node": "^25.1.0",
42
+ "msw": "^2.12.14",
43
+ "redis": "^5.10.0",
44
+ "pino": "^10.3.1",
45
+ "vitest": "^4.1.2",
46
+ "@o3co/auth-provider-core": "0.1.0"
47
+ },
48
+ "scripts": {
49
+ "build": "tsc",
50
+ "test": "vitest run"
51
+ }
52
+ }