@samebase/identity-broker 0.0.0-stage → 0.2.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.
Files changed (82) hide show
  1. package/LICENSE +201 -0
  2. package/NOTICE +4 -0
  3. package/README.md +104 -2
  4. package/dist/cli/index.d.ts +2 -0
  5. package/dist/cli/index.js +39 -0
  6. package/dist/cli/index.js.map +1 -0
  7. package/dist/client/connectors/email.d.ts +6 -0
  8. package/dist/client/connectors/email.js +5 -0
  9. package/dist/client/connectors/email.js.map +1 -0
  10. package/dist/client/connectors/github.d.ts +7 -0
  11. package/dist/client/connectors/github.js +57 -0
  12. package/dist/client/connectors/github.js.map +1 -0
  13. package/dist/client/connectors/google.d.ts +7 -0
  14. package/dist/client/connectors/google.js +13 -0
  15. package/dist/client/connectors/google.js.map +1 -0
  16. package/dist/client/connectors/types.d.ts +47 -0
  17. package/dist/client/connectors/types.js +2 -0
  18. package/dist/client/connectors/types.js.map +1 -0
  19. package/dist/client/connectors/upstream.d.ts +25 -0
  20. package/dist/client/connectors/upstream.js +86 -0
  21. package/dist/client/connectors/upstream.js.map +1 -0
  22. package/dist/client/html.d.ts +34 -0
  23. package/dist/client/html.js +91 -0
  24. package/dist/client/html.js.map +1 -0
  25. package/dist/client/index.d.ts +93 -0
  26. package/dist/client/index.js +819 -0
  27. package/dist/client/index.js.map +1 -0
  28. package/dist/client/jwt.d.ts +31 -0
  29. package/dist/client/jwt.js +55 -0
  30. package/dist/client/jwt.js.map +1 -0
  31. package/dist/client/keys.d.ts +49 -0
  32. package/dist/client/keys.js +138 -0
  33. package/dist/client/keys.js.map +1 -0
  34. package/dist/client/protocol.d.ts +79 -0
  35. package/dist/client/protocol.js +279 -0
  36. package/dist/client/protocol.js.map +1 -0
  37. package/dist/client/responses.d.ts +24 -0
  38. package/dist/client/responses.js +57 -0
  39. package/dist/client/responses.js.map +1 -0
  40. package/dist/client/subject.d.ts +15 -0
  41. package/dist/client/subject.js +32 -0
  42. package/dist/client/subject.js.map +1 -0
  43. package/dist/component/_generated/api.d.ts +45 -0
  44. package/dist/component/_generated/api.js +31 -0
  45. package/dist/component/_generated/api.js.map +1 -0
  46. package/dist/component/_generated/component.d.ts +398 -0
  47. package/dist/component/_generated/component.js +11 -0
  48. package/dist/component/_generated/component.js.map +1 -0
  49. package/dist/component/_generated/dataModel.d.ts +45 -0
  50. package/dist/component/_generated/dataModel.js +11 -0
  51. package/dist/component/_generated/dataModel.js.map +1 -0
  52. package/dist/component/_generated/server.d.ts +132 -0
  53. package/dist/component/_generated/server.js +80 -0
  54. package/dist/component/_generated/server.js.map +1 -0
  55. package/dist/component/apps.d.ts +36 -0
  56. package/dist/component/apps.js +124 -0
  57. package/dist/component/apps.js.map +1 -0
  58. package/dist/component/authRequests.d.ts +274 -0
  59. package/dist/component/authRequests.js +461 -0
  60. package/dist/component/authRequests.js.map +1 -0
  61. package/dist/component/clients.d.ts +43 -0
  62. package/dist/component/clients.js +95 -0
  63. package/dist/component/clients.js.map +1 -0
  64. package/dist/component/convex.config.d.ts +2 -0
  65. package/dist/component/convex.config.js +3 -0
  66. package/dist/component/convex.config.js.map +1 -0
  67. package/dist/component/crypto.d.ts +2 -0
  68. package/dist/component/crypto.js +9 -0
  69. package/dist/component/crypto.js.map +1 -0
  70. package/dist/component/lifecycle.d.ts +18 -0
  71. package/dist/component/lifecycle.js +79 -0
  72. package/dist/component/lifecycle.js.map +1 -0
  73. package/dist/component/registration.d.ts +29 -0
  74. package/dist/component/registration.js +90 -0
  75. package/dist/component/registration.js.map +1 -0
  76. package/dist/component/schema.d.ts +749 -0
  77. package/dist/component/schema.js +140 -0
  78. package/dist/component/schema.js.map +1 -0
  79. package/dist/component/signIns.d.ts +8 -0
  80. package/dist/component/signIns.js +26 -0
  81. package/dist/component/signIns.js.map +1 -0
  82. package/package.json +51 -3
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 [yyyy] [name of copyright owner]
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/NOTICE ADDED
@@ -0,0 +1,4 @@
1
+ identity-broker
2
+ Copyright 2026 Nicușor Chiciuc
3
+
4
+ Licensed under the Apache License, Version 2.0.
package/README.md CHANGED
@@ -1,3 +1,105 @@
1
- # Temporary Holding Version
1
+ # identity-broker
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ An OpenID Provider that runs on [Convex](https://convex.dev). One deployment holds a team's sign-in
4
+ connections once, such as GitHub, Google and email codes, and signs users in to many small apps. The
5
+ broker keeps no user accounts and no sessions: every sign-in goes upstream again, and each app
6
+ creates its own user from the `id_token` it receives.
7
+
8
+ Why: every new app otherwise needs its own OAuth app registrations and its own email sender, and a
9
+ preview deployment with a fresh callback URL cannot have them at all. With the broker, an app
10
+ registers each deployment as a client at deploy time and never touches GitHub or Google.
11
+
12
+ ## What it is
13
+
14
+ - `@samebase/identity-broker`: a Convex component plus the host-side endpoints. Authorization code
15
+ flow with PKCE, discovery, JWKS, dynamic client registration (RFC 7591) gated by per-app tokens,
16
+ userinfo. RS256 `id_token`s with pairwise subjects per app.
17
+ - Connectors are configuration: any OAuth 2.0 or OpenID Connect provider, and an email code sent by
18
+ your own action. `github()`, `google()` and `email()` are included.
19
+ - A hub is a small Convex app that mounts the component. Fork
20
+ [samebase/identity-hub](https://github.com/samebase/identity-hub) for one.
21
+ - `@samebase/alchemy-identity-hub`: an Alchemy v2 resource, `IdentityHub.Client`, that registers a
22
+ deployment as a client at deploy time. See
23
+ [packages/alchemy-identity-hub](https://github.com/samebase/identity-broker/tree/main/packages/alchemy-identity-hub).
24
+
25
+ ## Mount it
26
+
27
+ ```ts
28
+ // convex/convex.config.ts
29
+ import { defineApp } from "convex/server";
30
+ import identityBroker from "@samebase/identity-broker/convex.config";
31
+
32
+ const app = defineApp();
33
+ app.use(identityBroker);
34
+ export default app;
35
+ ```
36
+
37
+ ```ts
38
+ // convex/http.ts
39
+ import { httpRouter } from "convex/server";
40
+ import { defineIdentityBroker, email, github, google } from "@samebase/identity-broker";
41
+ import { components, internal } from "./_generated/api";
42
+
43
+ export const broker = defineIdentityBroker({
44
+ component: components.identityBroker,
45
+ issuer: process.env.ISSUER ?? process.env.CONVEX_SITE_URL!,
46
+ keys: () => process.env.IDENTITY_BROKER_KEYS,
47
+ connectors: [
48
+ github({
49
+ clientId: () => process.env.GITHUB_CLIENT_ID!,
50
+ clientSecret: () => process.env.GITHUB_CLIENT_SECRET!,
51
+ }),
52
+ google({
53
+ clientId: () => process.env.GOOGLE_CLIENT_ID!,
54
+ clientSecret: () => process.env.GOOGLE_CLIENT_SECRET!,
55
+ }),
56
+ email({ send: internal.email.sendCode }),
57
+ ],
58
+ });
59
+
60
+ const http = httpRouter();
61
+ broker.addHttpRoutes(http);
62
+ export default http;
63
+ ```
64
+
65
+ ```ts
66
+ // convex/identityBroker.ts: administration for `npx convex run`
67
+ import { broker } from "./http";
68
+ export const {
69
+ createApp,
70
+ mintRegistrationToken,
71
+ listRegistrationTokens,
72
+ revokeRegistrationToken,
73
+ setAllowedCallbackHosts,
74
+ deleteClient,
75
+ deleteApp,
76
+ listApps,
77
+ listClients,
78
+ cleanup,
79
+ } = broker.admin();
80
+ ```
81
+
82
+ Keys: `npx identity-broker keys` prints the value for `IDENTITY_BROKER_KEYS`; `keys --rotate`
83
+ advances it, and `keys --rotate --no-overlap` replaces a compromised key at once. Back up the key
84
+ set: its salt makes every `sub`. `parseKeySet` checks a value before a deploy.
85
+
86
+ ## Register an app's deployments
87
+
88
+ ```sh
89
+ npx convex run identityBroker:createApp '{"name":"Bristol","firstParty":true,"allowedCallbackHosts":["*.convex.site","127.0.0.1"]}'
90
+ npx convex run identityBroker:mintRegistrationToken '{"appId":"bristol-ab12c"}'
91
+ ```
92
+
93
+ Each deployment then posts its callback URL to `/register` with that token as a Bearer token and
94
+ gets a `client_id` and `client_secret`. A Convex Auth v2 app points its generic OAuth method at
95
+ `<issuer>/authorize` and `<issuer>/token`; see the [docs](docs/consumers.md).
96
+
97
+ ## Standards
98
+
99
+ OAuth 2.1 (code flow, PKCE S256, exact redirect URIs, `iss` on responses), OpenID Connect Core and
100
+ Discovery, RFC 7591, RFC 8414, RFC 9207, RFC 9700. Departures are named in
101
+ [docs/design.md](docs/design.md).
102
+
103
+ ## License
104
+
105
+ Apache-2.0.
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};
@@ -0,0 +1,39 @@
1
+ #!/usr/bin/env node
2
+ import { createKeySet, parseKeySet, rotateKeySet, rotateKeySetWithoutOverlap, } from "../client/keys.js";
3
+ const USAGE = `identity-broker keys print a new key set for IDENTITY_BROKER_KEYS
4
+ identity-broker keys --rotate read the current key set on stdin, print the rotated
5
+ one; the retired public key stays for 14 days
6
+ identity-broker keys --rotate --no-overlap the same after a key compromise: retired keys are
7
+ dropped at once; the salt is kept`;
8
+ async function readStdin() {
9
+ const chunks = [];
10
+ for await (const chunk of process.stdin) {
11
+ chunks.push(typeof chunk === "string" ? Buffer.from(chunk) : chunk);
12
+ }
13
+ return Buffer.concat(chunks).toString("utf8");
14
+ }
15
+ async function main(argv) {
16
+ if (argv[0] !== "keys") {
17
+ console.error(USAGE);
18
+ return 2;
19
+ }
20
+ const rotate = argv.includes("--rotate");
21
+ const noOverlap = argv.includes("--no-overlap");
22
+ // Without --rotate, --no-overlap would print a new key set with a new salt: every sub changes.
23
+ if (noOverlap && !rotate) {
24
+ console.error(USAGE);
25
+ return 2;
26
+ }
27
+ if (rotate) {
28
+ const current = parseKeySet(await readStdin());
29
+ const rotated = noOverlap
30
+ ? await rotateKeySetWithoutOverlap(current)
31
+ : await rotateKeySet(current);
32
+ process.stdout.write(`${JSON.stringify(rotated)}\n`);
33
+ return 0;
34
+ }
35
+ process.stdout.write(`${JSON.stringify(await createKeySet())}\n`);
36
+ return 0;
37
+ }
38
+ process.exitCode = await main(process.argv.slice(2));
39
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","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C,OAAO,CAAC,CAAC;QAChC,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,GAAG,IAAI,CAAC,SAAS,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC;QACrD,OAAO,CAAC,CAAC;IACX,CAAC;IACD,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,GAAG,IAAI,CAAC,SAAS,CAAC,MAAM,YAAY,EAAE,CAAC,IAAI,CAAC,CAAC;IAClE,OAAO,CAAC,CAAC;AACX,CAAC;AAED,OAAO,CAAC,QAAQ,GAAG,MAAM,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC"}
@@ -0,0 +1,6 @@
1
+ import type { EmailConnector, SendEmailCode } from "./types.js";
2
+ /** A six-digit code sent by the host's action. The canonical address is the identity. */
3
+ export declare function email(options: {
4
+ send: SendEmailCode;
5
+ name?: string;
6
+ }): EmailConnector;
@@ -0,0 +1,5 @@
1
+ /** A six-digit code sent by the host's action. The canonical address is the identity. */
2
+ export function email(options) {
3
+ return { kind: "email", name: options.name ?? "email", label: "Email", send: options.send };
4
+ }
5
+ //# sourceMappingURL=email.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"email.js","sourceRoot":"","sources":["../../../src/client/connectors/email.ts"],"names":[],"mappings":"AAEA,yFAAyF;AACzF,MAAM,UAAU,KAAK,CAAC,OAA+C;IACnE,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,IAAI,EAAE,OAAO,CAAC,IAAI,IAAI,OAAO,EAAE,KAAK,EAAE,OAAO,EAAE,IAAI,EAAE,OAAO,CAAC,IAAI,EAAE,CAAC;AAC9F,CAAC"}
@@ -0,0 +1,7 @@
1
+ import type { OauthConnector } from "./types.js";
2
+ /** GitHub as an OAuth connector. The callback must be registered on the OAuth App or GitHub App. */
3
+ export declare function github(credentials: {
4
+ clientId: () => string;
5
+ clientSecret: () => string;
6
+ name?: string;
7
+ }): OauthConnector;
@@ -0,0 +1,57 @@
1
+ import * as oauth from "oauth4webapi";
2
+ import { asRecord } from "../protocol.js";
3
+ const USER_URL = "https://api.github.com/user";
4
+ const EMAILS_URL = "https://api.github.com/user/emails";
5
+ async function githubJson(accessToken, url) {
6
+ const response = await oauth.protectedResourceRequest(accessToken, "GET", new URL(url), new Headers({ Accept: "application/vnd.github+json", "User-Agent": "identity-broker" }));
7
+ if (!response.ok) {
8
+ throw new Error(`GitHub ${url} answered ${response.status}`);
9
+ }
10
+ return await response.json();
11
+ }
12
+ /**
13
+ * The GitHub user and a verified email. GitHub's `/user` email is whatever the user made public,
14
+ * so the verified primary address from `/user/emails` is used instead; a user with no verified
15
+ * address gets no email claim.
16
+ */
17
+ async function githubIdentity(accessToken) {
18
+ const user = asRecord(await githubJson(accessToken, USER_URL));
19
+ const id = user["id"];
20
+ if (typeof id !== "number" && typeof id !== "string") {
21
+ throw new Error("GitHub /user returned no id");
22
+ }
23
+ const identity = { upstreamId: String(id) };
24
+ const name = user["name"] ?? user["login"];
25
+ if (typeof name === "string" && name.length > 0) {
26
+ identity.name = name;
27
+ }
28
+ if (typeof user["avatar_url"] === "string") {
29
+ identity.picture = user["avatar_url"];
30
+ }
31
+ const emails = await githubJson(accessToken, EMAILS_URL);
32
+ if (Array.isArray(emails)) {
33
+ const entries = emails.map((entry) => asRecord(entry));
34
+ const verified = entries.filter((entry) => entry["verified"] === true);
35
+ const primary = verified.find((entry) => entry["primary"] === true) ?? verified[0];
36
+ if (primary !== undefined && typeof primary["email"] === "string") {
37
+ identity.email = primary["email"];
38
+ identity.emailVerified = true;
39
+ }
40
+ }
41
+ return identity;
42
+ }
43
+ /** GitHub as an OAuth connector. The callback must be registered on the OAuth App or GitHub App. */
44
+ export function github(credentials) {
45
+ return {
46
+ kind: "oauth",
47
+ name: credentials.name ?? "github",
48
+ label: "GitHub",
49
+ authorizationEndpoint: "https://github.com/login/oauth/authorize",
50
+ tokenEndpoint: "https://github.com/login/oauth/access_token",
51
+ scopes: ["read:user", "user:email"],
52
+ clientId: credentials.clientId,
53
+ clientSecret: credentials.clientSecret,
54
+ identity: githubIdentity,
55
+ };
56
+ }
57
+ //# sourceMappingURL=github.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"github.js","sourceRoot":"","sources":["../../../src/client/connectors/github.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,KAAK,MAAM,cAAc,CAAC;AACtC,OAAO,EAAE,QAAQ,EAAE,MAAM,gBAAgB,CAAC;AAG1C,MAAM,QAAQ,GAAG,6BAA6B,CAAC;AAC/C,MAAM,UAAU,GAAG,oCAAoC,CAAC;AAExD,KAAK,UAAU,UAAU,CAAC,WAAmB,EAAE,GAAW;IACxD,MAAM,QAAQ,GAAG,MAAM,KAAK,CAAC,wBAAwB,CACnD,WAAW,EACX,KAAK,EACL,IAAI,GAAG,CAAC,GAAG,CAAC,EACZ,IAAI,OAAO,CAAC,EAAE,MAAM,EAAE,6BAA6B,EAAE,YAAY,EAAE,iBAAiB,EAAE,CAAC,CACxF,CAAC;IACF,IAAI,CAAC,QAAQ,CAAC,EAAE,EAAE,CAAC;QACjB,MAAM,IAAI,KAAK,CAAC,UAAU,GAAG,aAAa,QAAQ,CAAC,MAAM,EAAE,CAAC,CAAC;IAC/D,CAAC;IACD,OAAO,MAAM,QAAQ,CAAC,IAAI,EAAE,CAAC;AAC/B,CAAC;AAED;;;;GAIG;AACH,KAAK,UAAU,cAAc,CAAC,WAAmB;IAC/C,MAAM,IAAI,GAAG,QAAQ,CAAC,MAAM,UAAU,CAAC,WAAW,EAAE,QAAQ,CAAC,CAAC,CAAC;IAC/D,MAAM,EAAE,GAAG,IAAI,CAAC,IAAI,CAAC,CAAC;IACtB,IAAI,OAAO,EAAE,KAAK,QAAQ,IAAI,OAAO,EAAE,KAAK,QAAQ,EAAE,CAAC;QACrD,MAAM,IAAI,KAAK,CAAC,6BAA6B,CAAC,CAAC;IACjD,CAAC;IACD,MAAM,QAAQ,GAAqB,EAAE,UAAU,EAAE,MAAM,CAAC,EAA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OAAO;QACL,IAAI,EAAE,OAAO;QACb,IAAI,EAAE,WAAW,CAAC,IAAI,IAAI,QAAQ;QAClC,KAAK,EAAE,QAAQ;QACf,qBAAqB,EAAE,0CAA0C;QACjE,aAAa,EAAE,6CAA6C;QAC5D,MAAM,EAAE,CAAC,WAAW,EAAE,YAAY,CAAC;QACnC,QAAQ,EAAE,WAAW,CAAC,QAAQ;QAC9B,YAAY,EAAE,WAAW,CAAC,YAAY;QACtC,QAAQ,EAAE,cAAc;KACzB,CAAC;AACJ,CAAC"}
@@ -0,0 +1,7 @@
1
+ import type { OidcConnector } from "./types.js";
2
+ /** Google as an OIDC connector: discovery, id_token claims, `prompt=login` for fresh logins. */
3
+ export declare function google(credentials: {
4
+ clientId: () => string;
5
+ clientSecret: () => string;
6
+ name?: string;
7
+ }): OidcConnector;
@@ -0,0 +1,13 @@
1
+ /** Google as an OIDC connector: discovery, id_token claims, `prompt=login` for fresh logins. */
2
+ export function google(credentials) {
3
+ return {
4
+ kind: "oidc",
5
+ name: credentials.name ?? "google",
6
+ label: "Google",
7
+ issuer: "https://accounts.google.com",
8
+ scopes: ["openid", "email", "profile"],
9
+ clientId: credentials.clientId,
10
+ clientSecret: credentials.clientSecret,
11
+ };
12
+ }
13
+ //# sourceMappingURL=google.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"google.js","sourceRoot":"","sources":["../../../src/client/connectors/google.ts"],"names":[],"mappings":"AAEA,gGAAgG;AAChG,MAAM,UAAU,MAAM,CAAC,WAItB;IACC,OAAO;QACL,IAAI,EAAE,MAAM;QACZ,IAAI,EAAE,WAAW,CAAC,IAAI,IAAI,QAAQ;QAClC,KAAK,EAAE,QAAQ;QACf,MAAM,EAAE,6BAA6B;QACrC,MAAM,EAAE,CAAC,QAAQ,EAAE,OAAO,EAAE,SAAS,CAAC;QACtC,QAAQ,EAAE,WAAW,CAAC,QAAQ;QAC9B,YAAY,EAAE,WAAW,CAAC,YAAY;KACvC,CAAC;AACJ,CAAC"}
@@ -0,0 +1,47 @@
1
+ import type { FunctionReference } from "convex/server";
2
+ /** What a connector attested about the user. `upstreamId` is the connector's stable account id. */
3
+ export type UpstreamIdentity = {
4
+ upstreamId: string;
5
+ email?: string;
6
+ emailVerified?: boolean;
7
+ name?: string;
8
+ picture?: string;
9
+ };
10
+ type Credentials = {
11
+ /** Read lazily, in the request, so a missing env var fails that request and not the deploy. */
12
+ clientId: () => string;
13
+ clientSecret: () => string;
14
+ };
15
+ /** A plain OAuth 2.0 provider: identity comes from an API call with the access token. */
16
+ export type OauthConnector = Credentials & {
17
+ kind: "oauth";
18
+ name: string;
19
+ /** Shown on the chooser button, e.g. "GitHub". */
20
+ label: string;
21
+ authorizationEndpoint: string;
22
+ tokenEndpoint: string;
23
+ scopes: string[];
24
+ identity: (accessToken: string) => Promise<UpstreamIdentity>;
25
+ };
26
+ /** An OpenID Connect provider found through discovery: identity comes from the id_token. */
27
+ export type OidcConnector = Credentials & {
28
+ kind: "oidc";
29
+ name: string;
30
+ label: string;
31
+ issuer: string;
32
+ scopes: string[];
33
+ };
34
+ /** The host action that delivers a code. The broker never sees how. */
35
+ export type SendEmailCode = FunctionReference<"action", "internal", {
36
+ to: string;
37
+ code: string;
38
+ appName: string;
39
+ }, null>;
40
+ export type EmailConnector = {
41
+ kind: "email";
42
+ name: string;
43
+ label: string;
44
+ send: SendEmailCode;
45
+ };
46
+ export type Connector = OauthConnector | OidcConnector | EmailConnector;
47
+ export {};
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=types.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["../../../src/client/connectors/types.ts"],"names":[],"mappings":""}
@@ -0,0 +1,25 @@
1
+ import type { OauthConnector, OidcConnector, UpstreamIdentity } from "./types.js";
2
+ export type UpstreamStart = {
3
+ url: string;
4
+ state: string;
5
+ codeVerifier: string;
6
+ nonce: string | undefined;
7
+ };
8
+ /** The authorization URL for a connector, with fresh state, PKCE pair and, for OIDC, a nonce. */
9
+ export declare function startUpstream(args: {
10
+ connector: OauthConnector | OidcConnector;
11
+ callbackUrl: string;
12
+ freshLogin: boolean;
13
+ }): Promise<UpstreamStart>;
14
+ /**
15
+ * The connector callback: validate the response, exchange the code, and read the identity. Errors
16
+ * propagate; the caller turns them into a redirect back to the client.
17
+ */
18
+ export declare function finishUpstream(args: {
19
+ connector: OauthConnector | OidcConnector;
20
+ callbackUrl: string;
21
+ currentUrl: URL;
22
+ state: string;
23
+ codeVerifier: string;
24
+ nonce: string | undefined;
25
+ }): Promise<UpstreamIdentity>;
@@ -0,0 +1,86 @@
1
+ import * as oauth from "oauth4webapi";
2
+ const discovered = new Map();
3
+ /** OIDC discovery, once per issuer per isolate. */
4
+ function authorizationServer(connector) {
5
+ if (connector.kind === "oauth") {
6
+ return Promise.resolve({
7
+ issuer: connector.authorizationEndpoint,
8
+ authorization_endpoint: connector.authorizationEndpoint,
9
+ token_endpoint: connector.tokenEndpoint,
10
+ });
11
+ }
12
+ const cached = discovered.get(connector.issuer);
13
+ if (cached !== undefined) {
14
+ return cached;
15
+ }
16
+ const issuer = new URL(connector.issuer);
17
+ const pending = oauth
18
+ .discoveryRequest(issuer, { algorithm: "oidc" })
19
+ .then((response) => oauth.processDiscoveryResponse(issuer, response));
20
+ discovered.set(connector.issuer, pending);
21
+ pending.catch(() => discovered.delete(connector.issuer));
22
+ return pending;
23
+ }
24
+ /** The authorization URL for a connector, with fresh state, PKCE pair and, for OIDC, a nonce. */
25
+ export async function startUpstream(args) {
26
+ const as = await authorizationServer(args.connector);
27
+ if (as.authorization_endpoint === undefined) {
28
+ throw new Error(`Connector "${args.connector.name}" has no authorization endpoint`);
29
+ }
30
+ const state = oauth.generateRandomState();
31
+ const codeVerifier = oauth.generateRandomCodeVerifier();
32
+ const nonce = args.connector.kind === "oidc" ? oauth.generateRandomNonce() : undefined;
33
+ const url = new URL(as.authorization_endpoint);
34
+ url.searchParams.set("client_id", args.connector.clientId());
35
+ url.searchParams.set("redirect_uri", args.callbackUrl);
36
+ url.searchParams.set("response_type", "code");
37
+ url.searchParams.set("scope", args.connector.scopes.join(" "));
38
+ url.searchParams.set("code_challenge", await oauth.calculatePKCECodeChallenge(codeVerifier));
39
+ url.searchParams.set("code_challenge_method", "S256");
40
+ url.searchParams.set("state", state);
41
+ if (nonce !== undefined) {
42
+ url.searchParams.set("nonce", nonce);
43
+ }
44
+ if (args.freshLogin && args.connector.kind === "oidc") {
45
+ url.searchParams.set("prompt", "login");
46
+ }
47
+ return { url: url.toString(), state, codeVerifier, nonce };
48
+ }
49
+ /**
50
+ * The connector callback: validate the response, exchange the code, and read the identity. Errors
51
+ * propagate; the caller turns them into a redirect back to the client.
52
+ */
53
+ export async function finishUpstream(args) {
54
+ const as = await authorizationServer(args.connector);
55
+ const client = { client_id: args.connector.clientId() };
56
+ const clientAuth = oauth.ClientSecretPost(args.connector.clientSecret());
57
+ const params = oauth.validateAuthResponse(as, client, args.currentUrl, args.state);
58
+ const response = await oauth.authorizationCodeGrantRequest(as, client, clientAuth, params, args.callbackUrl, args.codeVerifier);
59
+ if (args.connector.kind === "oauth") {
60
+ const tokens = await oauth.processAuthorizationCodeResponse(as, client, response);
61
+ return await args.connector.identity(tokens.access_token);
62
+ }
63
+ const tokens = await oauth.processAuthorizationCodeResponse(as, client, response, {
64
+ requireIdToken: true,
65
+ ...(args.nonce === undefined ? {} : { expectedNonce: args.nonce }),
66
+ });
67
+ const claims = oauth.getValidatedIdTokenClaims(tokens);
68
+ if (claims === undefined) {
69
+ throw new Error(`Connector "${args.connector.name}" returned no id_token`);
70
+ }
71
+ const identity = { upstreamId: claims.sub };
72
+ if (typeof claims["email"] === "string") {
73
+ identity.email = claims["email"];
74
+ }
75
+ if (typeof claims["email_verified"] === "boolean") {
76
+ identity.emailVerified = claims["email_verified"];
77
+ }
78
+ if (typeof claims["name"] === "string") {
79
+ identity.name = claims["name"];
80
+ }
81
+ if (typeof claims["picture"] === "string") {
82
+ identity.picture = claims["picture"];
83
+ }
84
+ return identity;
85
+ }
86
+ //# sourceMappingURL=upstream.js.map