@softistx/janus-social 0.0.0-stage → 0.8.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 (105) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +356 -2
  3. package/dist/authorization-url.d.ts +21 -0
  4. package/dist/authorization-url.d.ts.map +1 -0
  5. package/dist/check-options.d.ts +22 -0
  6. package/dist/check-options.d.ts.map +1 -0
  7. package/dist/claims.d.ts +15 -0
  8. package/dist/claims.d.ts.map +1 -0
  9. package/dist/code-exchange.d.ts +79 -0
  10. package/dist/code-exchange.d.ts.map +1 -0
  11. package/dist/connections/abort.d.ts +8 -0
  12. package/dist/connections/abort.d.ts.map +1 -0
  13. package/dist/connections/at-hash.d.ts +24 -0
  14. package/dist/connections/at-hash.d.ts.map +1 -0
  15. package/dist/connections/body-limit.d.ts +15 -0
  16. package/dist/connections/body-limit.d.ts.map +1 -0
  17. package/dist/connections/build.d.ts +7 -0
  18. package/dist/connections/build.d.ts.map +1 -0
  19. package/dist/connections/check.d.ts +25 -0
  20. package/dist/connections/check.d.ts.map +1 -0
  21. package/dist/connections/claims.d.ts +16 -0
  22. package/dist/connections/claims.d.ts.map +1 -0
  23. package/dist/connections/discovery.d.ts +20 -0
  24. package/dist/connections/discovery.d.ts.map +1 -0
  25. package/dist/connections/domain.d.ts +15 -0
  26. package/dist/connections/domain.d.ts.map +1 -0
  27. package/dist/connections/guarded-fetch.d.ts +49 -0
  28. package/dist/connections/guarded-fetch.d.ts.map +1 -0
  29. package/dist/connections/id-token-steps.d.ts +15 -0
  30. package/dist/connections/id-token-steps.d.ts.map +1 -0
  31. package/dist/connections/id-token.d.ts +63 -0
  32. package/dist/connections/id-token.d.ts.map +1 -0
  33. package/dist/connections/index.d.ts +11 -0
  34. package/dist/connections/index.d.ts.map +1 -0
  35. package/dist/connections/ip.d.ts +14 -0
  36. package/dist/connections/ip.d.ts.map +1 -0
  37. package/dist/connections/issuer-cache.d.ts +40 -0
  38. package/dist/connections/issuer-cache.d.ts.map +1 -0
  39. package/dist/connections/issuer.d.ts +4 -0
  40. package/dist/connections/issuer.d.ts.map +1 -0
  41. package/dist/connections/key-flights.d.ts +16 -0
  42. package/dist/connections/key-flights.d.ts.map +1 -0
  43. package/dist/connections/memory.d.ts +10 -0
  44. package/dist/connections/memory.d.ts.map +1 -0
  45. package/dist/connections/oidc-connections.d.ts +71 -0
  46. package/dist/connections/oidc-connections.d.ts.map +1 -0
  47. package/dist/connections/provider.d.ts +25 -0
  48. package/dist/connections/provider.d.ts.map +1 -0
  49. package/dist/connections/server.d.ts +55 -0
  50. package/dist/connections/server.d.ts.map +1 -0
  51. package/dist/connections/types.d.ts +87 -0
  52. package/dist/connections/types.d.ts.map +1 -0
  53. package/dist/connections/url-policy.d.ts +30 -0
  54. package/dist/connections/url-policy.d.ts.map +1 -0
  55. package/dist/connections/wiring.d.ts +5 -0
  56. package/dist/connections/wiring.d.ts.map +1 -0
  57. package/dist/discovery.d.ts +11 -0
  58. package/dist/discovery.d.ts.map +1 -0
  59. package/dist/dpop.d.ts +18 -0
  60. package/dist/dpop.d.ts.map +1 -0
  61. package/dist/failure.d.ts +14 -0
  62. package/dist/failure.d.ts.map +1 -0
  63. package/dist/github-identity.d.ts +11 -0
  64. package/dist/github-identity.d.ts.map +1 -0
  65. package/dist/github.d.ts +11 -0
  66. package/dist/github.d.ts.map +1 -0
  67. package/dist/google.d.ts +11 -0
  68. package/dist/google.d.ts.map +1 -0
  69. package/dist/guard-error.d.ts +14 -0
  70. package/dist/guard-error.d.ts.map +1 -0
  71. package/dist/index.d.ts +23 -0
  72. package/dist/index.d.ts.map +1 -0
  73. package/dist/index.js +1825 -0
  74. package/dist/index.js.map +51 -0
  75. package/dist/microsoft-tenant.d.ts +32 -0
  76. package/dist/microsoft-tenant.d.ts.map +1 -0
  77. package/dist/microsoft.d.ts +16 -0
  78. package/dist/microsoft.d.ts.map +1 -0
  79. package/dist/oauth2.d.ts +13 -0
  80. package/dist/oauth2.d.ts.map +1 -0
  81. package/dist/oidc-engine.d.ts +62 -0
  82. package/dist/oidc-engine.d.ts.map +1 -0
  83. package/dist/oidc-step-up.d.ts +15 -0
  84. package/dist/oidc-step-up.d.ts.map +1 -0
  85. package/dist/oidc.d.ts +11 -0
  86. package/dist/oidc.d.ts.map +1 -0
  87. package/dist/options.d.ts +108 -0
  88. package/dist/options.d.ts.map +1 -0
  89. package/dist/pushed-authorization.d.ts +23 -0
  90. package/dist/pushed-authorization.d.ts.map +1 -0
  91. package/dist/step-up.d.ts +50 -0
  92. package/dist/step-up.d.ts.map +1 -0
  93. package/dist/transport.d.ts +18 -0
  94. package/dist/transport.d.ts.map +1 -0
  95. package/docs/README.md +35 -0
  96. package/docs/guide/custom-providers.md +182 -0
  97. package/docs/guide/github.md +109 -0
  98. package/docs/guide/google.md +103 -0
  99. package/docs/guide/microsoft.md +158 -0
  100. package/docs/guide/oidc-connections.md +265 -0
  101. package/docs/guide/oidc-step-up.md +122 -0
  102. package/docs/guide/par-dpop.md +63 -0
  103. package/docs/roadmap.md +33 -0
  104. package/docs/troubleshooting.md +632 -0
  105. package/package.json +67 -5
@@ -0,0 +1,109 @@
1
+ # GitHub
2
+
3
+ This page is for signing in with GitHub: the app to register, the wiring, which
4
+ e-mail you get, and the case where you get none.
5
+
6
+ ```ts
7
+ import { github } from '@softistx/janus-social';
8
+
9
+ export const provider = github({
10
+ clientId: process.env.GITHUB_CLIENT_ID!, // yours: from the app
11
+ clientSecret: process.env.GITHUB_CLIENT_SECRET!, // yours
12
+ redirectUri: 'https://app.example.com/auth/github/callback', // yours: the route that calls social.complete
13
+ });
14
+ ```
15
+
16
+ ## Register the app
17
+
18
+ GitHub has two kinds; either works.
19
+
20
+ **An OAuth app.** Profile picture > **Settings > Developer settings > OAuth
21
+ apps > New OAuth App** (for an organization, the same path under the
22
+ organization's settings). Fill **Application name**, **Homepage URL** and
23
+ **Authorization callback URL**: the callback URL is your `redirectUri`. Leave
24
+ **Enable Device Flow** off, then **Register application**, **Generate a new
25
+ client secret**, and copy it with the **Client ID**. The scopes asked for are
26
+ `read:user user:email`; `user:email` is what `/user/emails` requires for an
27
+ OAuth app token.
28
+
29
+ **A GitHub App.** **Settings > Developer settings > GitHub Apps > New GitHub
30
+ App**. Set the **Callback URL** to your `redirectUri`, tick **Request user
31
+ authorization (OAuth) during installation** if you want the install flow to
32
+ prompt too, and generate a client secret on the app's settings page; only the
33
+ sign-in code exchange is used. A GitHub App has permissions rather than scopes
34
+ (the `scope` parameter does not control them): under **Permissions > Account
35
+ permissions**, set **Email addresses** to **Read-only**, or `/user/emails` is
36
+ refused and every sign-in fails at `GitHub /user/emails`. Untick webhook
37
+ **Active**: an app used only to sign in needs none.
38
+
39
+ Reference: [Creating an OAuth app](https://docs.github.com/en/apps/oauth-apps/building-oauth-apps/creating-an-oauth-app),
40
+ [Scopes for OAuth apps](https://docs.github.com/en/apps/oauth-apps/building-oauth-apps/scopes-for-oauth-apps),
41
+ [Registering a GitHub App](https://docs.github.com/en/apps/creating-github-apps/registering-a-github-app/registering-a-github-app),
42
+ [Emails REST API](https://docs.github.com/en/rest/users/emails).
43
+
44
+ ## Options
45
+
46
+ | Option | Type | Default | Effect |
47
+ | --- | --- | --- | --- |
48
+ | `clientId` | `string` | required | The app's client id |
49
+ | `clientSecret` | `string` | required | Its secret |
50
+ | `redirectUri` | `string` | required | `https`, or `http` on a loopback host; registered exactly |
51
+ | `fetch` | `SocialFetch` | global `fetch` | Used for every request to GitHub, API calls included |
52
+ | `timeout` | `number` | `10000` | Milliseconds each request may take; past it the step fails as `unreachable` |
53
+
54
+ ```ts
55
+ type GithubOptions = ProviderCredentials;
56
+ ```
57
+
58
+ ## The identity
59
+
60
+ GitHub speaks OAuth 2.0 and no OpenID Connect, so after the code exchange the
61
+ package calls `GET https://api.github.com/user` and `GET /user/emails` with the
62
+ access token (PKCE and `state` are used; there is no ID token and no `nonce`).
63
+
64
+ | Field | From |
65
+ | --- | --- |
66
+ | `accountId` | the numeric user id, as a string. A login can be renamed; the id cannot |
67
+ | `email` | the address that is both **primary** and **verified**, else `null` |
68
+ | `emailVerified` | `true` exactly when `email` is not `null` |
69
+ | `name`, `picture` | `name` and `avatar_url`, when present |
70
+
71
+ A verified secondary address is not taken: it is not the one the account answers
72
+ to. A user with no verified primary address has `email: null`: they cannot sign
73
+ up, and cannot be linked by e-mail; a signed-in user can still link their GitHub
74
+ account (see the core guide).
75
+
76
+ ## Wiring beside Google
77
+
78
+ ```ts
79
+ import { createMemoryStores, janus, scryptHasher } from '@softistx/janus';
80
+ import { github, google } from '@softistx/janus-social';
81
+ import { z } from 'zod';
82
+
83
+ const base = 'https://app.example.com/auth'; // yours
84
+
85
+ export const auth = janus({
86
+ user: z.object({ email: z.email(), name: z.string() }),
87
+ password: { login: 'email' },
88
+ store: createMemoryStores(), // tests only
89
+ hasher: scryptHasher(),
90
+ social: {
91
+ providers: {
92
+ google: google({ clientId: 'g-id', clientSecret: 'g-secret', redirectUri: `${base}/google/callback` }),
93
+ github: github({ clientId: 'h-id', clientSecret: 'h-secret', redirectUri: `${base}/github/callback` }),
94
+ },
95
+ signUp: (profile) => ({ email: profile.email ?? '', name: profile.name ?? 'Unnamed' }),
96
+ },
97
+ });
98
+ ```
99
+
100
+ ## Traps
101
+
102
+ - `fetch` replaces the global one for the API calls too, so a stub for the
103
+ token endpoint must answer `/user` and `/user/emails` as well.
104
+ - A token response that holds no access token is a refusal at "the token
105
+ response", whatever its HTTP status.
106
+ - GitHub Enterprise Server is not supported yet: the endpoints are
107
+ `github.com`'s. See the [roadmap](../roadmap.md).
108
+
109
+ More in [troubleshooting](../troubleshooting.md).
@@ -0,0 +1,103 @@
1
+ # Google
2
+
3
+ This page is for signing in with Google: the OAuth client to create, the
4
+ wiring, what identity you get, and how to keep sign-in to one Workspace domain.
5
+
6
+ ```ts
7
+ import { google } from '@softistx/janus-social';
8
+
9
+ export const provider = google({
10
+ clientId: process.env.GOOGLE_CLIENT_ID!, // yours: from the OAuth client
11
+ clientSecret: process.env.GOOGLE_CLIENT_SECRET!, // yours
12
+ redirectUri: 'https://app.example.com/auth/google/callback', // yours: the route that calls social.complete
13
+ });
14
+ ```
15
+
16
+ Put it under `social.providers` of your user type (`providers: { google: provider }`)
17
+ as in the [README](../../README.md).
18
+
19
+ ## Register the app
20
+
21
+ 1. In the [Google Cloud console](https://console.cloud.google.com/), pick or
22
+ create a project.
23
+ 2. Open **Google Auth Platform** (the successor of **APIs & Services > OAuth
24
+ consent screen**) and set it up: **Branding** (app name, support e-mail) and
25
+ **Audience**. **Internal** limits sign-in to your Workspace; **External**
26
+ allows any Google account, and an app left in "Testing" only admits the test
27
+ users you list.
28
+ 3. Go to **Google Auth Platform > Clients > Create client** and pick the
29
+ application type **Web application**.
30
+ 4. Under **Authorized redirect URIs**, add your redirect URI. It must equal
31
+ `redirectUri` byte for byte (scheme, case, trailing slash). For development add
32
+ `http://localhost:3000/auth/google/callback` (Google exempts localhost URIs from
33
+ HTTPS, and this package allows `http` on a loopback host). Other URIs must be
34
+ `https`, with no wildcard and no raw IP address.
35
+ 5. **Create**, then copy the **Client ID** and the **Client secret**. Google shows
36
+ the secret at creation (it also offers a `client_secret.json` download), so
37
+ store it then. The scopes asked for are `openid email profile`.
38
+
39
+ Reference: [Using OAuth 2.0 for web server applications](https://developers.google.com/identity/protocols/oauth2/web-server),
40
+ [OpenID Connect](https://developers.google.com/identity/openid-connect/openid-connect),
41
+ [Manage OAuth clients](https://support.google.com/cloud/answer/15549257).
42
+
43
+ ## Options
44
+
45
+ | Option | Type | Default | Effect |
46
+ | --- | --- | --- | --- |
47
+ | `clientId` | `string` | required | The OAuth client's id |
48
+ | `clientSecret` | `string` | required | Its secret |
49
+ | `redirectUri` | `string` | required | `https`, or `http` on a loopback host; registered exactly |
50
+ | `hostedDomain` | `string` | absent | Only accounts of this Workspace domain |
51
+ | `fetch` | `SocialFetch` | global `fetch` | Used for every request to Google |
52
+
53
+ ```ts
54
+ interface GoogleOptions extends ProviderCredentials {
55
+ readonly hostedDomain?: string;
56
+ }
57
+ ```
58
+
59
+ ## The identity
60
+
61
+ | Field | From |
62
+ | --- | --- |
63
+ | `accountId` | the ID token's `sub` |
64
+ | `email` | the `email` claim, or `null` when absent |
65
+ | `emailVerified` | `email_verified` is `true` (a boolean or the string `"true"`) |
66
+ | `name`, `picture` | the `name` and `picture` claims, when present |
67
+
68
+ Google is read through OpenID Connect: its discovery document at
69
+ `https://accounts.google.com` is fetched on first use and kept (a failure is not
70
+ kept). The ID token's `iss`, `aud`, `exp` and `nonce` are checked; its signature
71
+ is not, for the direct TLS exchange (OpenID Connect Core 3.1.3.7).
72
+
73
+ ## One Workspace domain
74
+
75
+ ```ts
76
+ import { google } from '@softistx/janus-social';
77
+
78
+ export const clinicStaff = google({
79
+ clientId: process.env.GOOGLE_CLIENT_ID!,
80
+ clientSecret: process.env.GOOGLE_CLIENT_SECRET!,
81
+ redirectUri: 'https://app.example.com/auth/google/callback',
82
+ hostedDomain: 'example.com', // yours: the Workspace domain
83
+ });
84
+ ```
85
+
86
+ `hostedDomain` adds `hd=example.com` to the authorization URL, which only
87
+ narrows Google's account chooser: the visitor can edit it. What is trusted is
88
+ the ID token's `hd` claim, and a sign-in whose `hd` is another domain (or
89
+ absent, as for a personal `@gmail.com` account) is refused with `PROVIDER_ERROR`
90
+ at "the ID token". An empty `hostedDomain` is a `TypeError` at wiring.
91
+
92
+ ## Traps
93
+
94
+ - A Google account is one link per instance. The same Google account cannot be a
95
+ customer's and an admin's sign-in at once: see the
96
+ [core guide](https://github.com/softistx/nxgt-janus/blob/develop/packages/janus/docs/guide/social.md).
97
+ - `redirect_uri_mismatch` on Google's own page is the registration and
98
+ `redirectUri` differing: scheme, host, port, path, trailing slash.
99
+ - An address without `email_verified` is not linked to a user that holds it, and
100
+ does not create one: see `EMAIL_NOT_VERIFIED_FOR_LINK` and `EMAIL_UNVERIFIED` in the
101
+ core's troubleshooting.
102
+
103
+ More in [troubleshooting](../troubleshooting.md).
@@ -0,0 +1,158 @@
1
+ # Microsoft
2
+
3
+ This page is for signing in with the Microsoft identity platform (Microsoft
4
+ Entra ID): work and school accounts, personal accounts, or one organization
5
+ only. It covers the app registration, the tenant to choose, and the optional
6
+ claim that makes the e-mail count.
7
+
8
+ ```ts
9
+ import { microsoft } from '@softistx/janus-social';
10
+
11
+ export const provider = microsoft({
12
+ clientId: process.env.MICROSOFT_CLIENT_ID!, // yours: "Application (client) ID"
13
+ clientSecret: process.env.MICROSOFT_CLIENT_SECRET!, // yours: the secret's Value
14
+ redirectUri: 'https://app.example.com/auth/microsoft/callback', // yours: the route that calls social.complete
15
+ tenant: 'organizations', // yours: see "Tenants"
16
+ });
17
+ ```
18
+
19
+ ## Register the app
20
+
21
+ 1. Open the [Microsoft Entra admin center](https://entra.microsoft.com/) and go
22
+ to **Entra ID > App registrations > New registration**.
23
+ 2. Give it a **Name**. Under **Supported account types** pick the audience that
24
+ matches the `tenant` you will use (see below).
25
+ 3. Under **Redirect URI**, choose the platform **Web** and enter your redirect
26
+ URI. It must equal `redirectUri` byte for byte. To add one later (for example
27
+ `http://localhost:3000/...` for development): **Manage > Authentication >
28
+ Redirect URI configuration > Add Redirect URI > Web**.
29
+ 4. **Register.** On the **Overview** page copy **Application (client) ID**
30
+ (`clientId`) and **Directory (tenant) ID** (a tenant id for `tenant`, if you
31
+ want one organization).
32
+ 5. **Certificates & secrets > Client secrets > New client secret.** Add a
33
+ description and an expiry (24 months at most; Microsoft recommends under 12).
34
+ Copy the **Value** now (not the *Secret ID*): it is never shown again. Secrets
35
+ expire; put the date in your calendar. Microsoft recommends certificates over
36
+ secrets in production; this package takes a client secret.
37
+ 6. **Token configuration > Add optional claim**, token type **ID**, tick
38
+ **`email`** and **`xms_edov`**, then **Add**. `xms_edov` is only returned when
39
+ the `email` claim is present, so both are needed. If a prompt offers to turn on
40
+ the Microsoft Graph `email` permission, accept it.
41
+
42
+ Step 6 is not optional: see "The e-mail" below.
43
+
44
+ Reference: [Register an app](https://learn.microsoft.com/en-us/entra/identity-platform/quickstart-register-app),
45
+ [Add a redirect URI](https://learn.microsoft.com/en-us/entra/identity-platform/how-to-add-redirect-uri),
46
+ [Add credentials](https://learn.microsoft.com/en-us/entra/identity-platform/how-to-add-credentials),
47
+ [Configure optional claims](https://learn.microsoft.com/en-us/entra/identity-platform/optional-claims),
48
+ [Optional claims reference](https://learn.microsoft.com/en-us/entra/identity-platform/optional-claims-reference),
49
+ [OpenID Connect](https://learn.microsoft.com/en-us/entra/identity-platform/v2-protocols-oidc).
50
+
51
+ ## Options
52
+
53
+ | Option | Type | Default | Effect |
54
+ | --- | --- | --- | --- |
55
+ | `clientId` | `string` | required | Application (client) ID |
56
+ | `clientSecret` | `string` | required | The client secret's value |
57
+ | `redirectUri` | `string` | required | `https`, or `http` on a loopback host; registered exactly |
58
+ | `tenant` | `string` | `'common'` | Whose accounts may sign in |
59
+ | `fetch` | `SocialFetch` | global `fetch` | Used for every request to Microsoft |
60
+ | `timeout` | `number` | `10000` | Milliseconds each request may take, the tenant lookup included; past it the step fails as `unreachable` |
61
+
62
+ ```ts
63
+ interface MicrosoftOptions extends ProviderCredentials {
64
+ readonly tenant?: string;
65
+ }
66
+ ```
67
+
68
+ ## Tenants
69
+
70
+ | `tenant` | Admits | Supported account types to pick at registration |
71
+ | --- | --- | --- |
72
+ | `'common'` (default) | Work, school and personal accounts | **Any Entra ID Tenant + Personal Microsoft accounts** |
73
+ | `'organizations'` | Work and school accounts of any organization; a personal account is refused | **Multiple Entra ID tenants** |
74
+ | `'consumers'` | Personal accounts only | **Personal accounts only** |
75
+ | a tenant id, e.g. `'00000000-0000-0000-0000-000000000000'` | The accounts of that one organization | **Single tenant only** |
76
+ | a domain, e.g. `'contoso.onmicrosoft.com'` | Microsoft's endpoint for that tenant | as for a tenant id |
77
+
78
+ Anything else (an empty string, `'a/b'`) is a `TypeError` at wiring.
79
+
80
+ The package does not read Microsoft's discovery document: for `common`,
81
+ `organizations` and `consumers` it advertises the template issuer
82
+ `https://login.microsoftonline.com/{tenantid}/v2.0`, which no token's `iss` ever
83
+ equals. The endpoints are fixed instead, and the issuer is built from the
84
+ ID token's `tid` claim, then oauth4webapi checks `iss` against it. `consumers`,
85
+ `organizations` and a GUID are also checked against the `tid` (personal accounts
86
+ are tenant `9188040d-6c67-4c5b-b112-36a304b66dad`); a mismatch is a
87
+ `PROVIDER_ERROR` at "the ID token". A domain is not compared with `tid` by the
88
+ package: Microsoft's endpoint for that tenant is what limits it.
89
+
90
+ ## The e-mail
91
+
92
+ The e-mail counts (`emailVerified: true`) only when the ID token's optional
93
+ `xms_edov` claim is `true`. That claim says the address's domain owner is verified (the domain belongs to the user's tenant and its admin verified it), and Microsoft only emits it when the `email` claim is present. Microsoft does not vouch for an address otherwise:
94
+ the `email` claim of a work account can be set by a tenant administrator to
95
+ anything. Without `xms_edov` (and `email`) in **Token configuration**, every Microsoft
96
+ sign-in has `emailVerified: false`, so:
97
+
98
+ - a stranger cannot sign up: `EMAIL_UNVERIFIED`;
99
+ - a user who holds the address is not linked by e-mail:
100
+ `EMAIL_NOT_VERIFIED_FOR_LINK` (they sign in another way and link the account).
101
+
102
+ | Field | From |
103
+ | --- | --- |
104
+ | `accountId` | the ID token's `sub` |
105
+ | `email` | the `email` claim, or `null` (the package never falls back to `preferred_username`, which the user can edit) |
106
+ | `emailVerified` | `xms_edov` is `true` |
107
+ | `name`, `picture` | the `name` and `picture` claims, when present |
108
+
109
+ **`sub` is pairwise per app registration.** The same person has a different
110
+ `sub` in another registration: if you register the app again (a new client id),
111
+ every link made with the old one no longer matches.
112
+
113
+ ## A realistic wiring: staff of one organization
114
+
115
+ ```ts
116
+ import { createMemoryStores, janus, scryptHasher } from '@softistx/janus';
117
+ import { microsoft } from '@softistx/janus-social';
118
+ import { z } from 'zod';
119
+
120
+ export const auth = janus({
121
+ user: z.object({ email: z.email(), name: z.string() }),
122
+ password: { login: 'email' },
123
+ store: createMemoryStores(), // tests only
124
+ hasher: scryptHasher(),
125
+ social: {
126
+ providers: {
127
+ microsoft: microsoft({
128
+ clientId: process.env.MICROSOFT_CLIENT_ID!,
129
+ clientSecret: process.env.MICROSOFT_CLIENT_SECRET!,
130
+ redirectUri: 'https://app.example.com/auth/microsoft/callback',
131
+ tenant: process.env.MICROSOFT_TENANT_ID!, // yours: Directory (tenant) ID
132
+ }),
133
+ },
134
+ signUp: false, // nobody new: staff are created first, then link their account
135
+ },
136
+ });
137
+ ```
138
+
139
+ ## Traps
140
+
141
+ - The secret's **Value**, not its *Secret ID*, is `clientSecret`; an expired
142
+ secret fails at "the token request".
143
+ - `common` with an app registered for one organization only fails at
144
+ Microsoft's own page (`AADSTS50194` and relatives): pick the registration's
145
+ audience and `tenant` together.
146
+ - Work accounts whose tenant forbids the app need the administrator's consent;
147
+ that is Microsoft's page, not an error of this package.
148
+
149
+ More in [troubleshooting](../troubleshooting.md).
150
+
151
+ ## A domain as the tenant
152
+
153
+ `tenant: 'contoso.onmicrosoft.com'` is sent to Microsoft's endpoints. On the
154
+ first sign-in the package also reads
155
+ `https://login.microsoftonline.com/<domain>/v2.0/.well-known/openid-configuration`,
156
+ takes the tenant id from its issuer, and holds the ID token's `tid` to it like
157
+ a tenant id. Only a successful lookup is kept; a failed one refuses that
158
+ sign-in and is asked again at the next.
@@ -0,0 +1,265 @@
1
+ # OIDC connections
2
+
3
+ This page is for an application whose customers bring **their own** OpenID Connect identity provider (a company's Entra ID, Okta or Google Workspace): the connections live in your database, are read when someone signs in, and need no restart to add, edit or drop. Presets and `oidcProvider` are fixed at wiring; `oidcConnections` is the same engine, driven by stored records.
4
+
5
+ Each stored record is an **OIDC connection**: one tenant's identity provider. It is not a database connection.
6
+
7
+ ## Wiring
8
+
9
+ You write one thing, a read-only `ConnectionSource` over your own table. Everything else is wiring `resolve` into the core.
10
+
11
+ ```ts
12
+ import { createMemoryStores, janus, scryptHasher } from '@softistx/janus';
13
+ import {
14
+ type ConnectionSource,
15
+ type OidcConnection,
16
+ oidcConnections,
17
+ } from '@softistx/janus-social';
18
+ import { z } from 'zod';
19
+
20
+ declare const table: {
21
+ byId(id: string): Promise<OidcConnection | null>; // yours: your table
22
+ byDomain(domain: string): Promise<OidcConnection | null>;
23
+ };
24
+
25
+ const source: ConnectionSource = {
26
+ findConnection: (id) => table.byId(id), // null: absent. A throw: the table is down
27
+ findConnectionByDomain: (domain) => table.byDomain(domain), // exactly one, or null
28
+ };
29
+
30
+ export const connections = oidcConnections({
31
+ source,
32
+ redirectUri: 'https://app.example.com/auth/sso/callback', // yours: one URL for every connection
33
+ });
34
+
35
+ export const auth = janus({
36
+ user: z.object({ email: z.email(), name: z.string() }),
37
+ password: { login: 'email' },
38
+ store: createMemoryStores(), // tests only: use a database store in production
39
+ hasher: scryptHasher(),
40
+ social: {
41
+ resolveProvider: connections.resolve, // looked up at start and again at complete
42
+ signUp: (profile) => ({ email: profile.email ?? '', name: profile.name ?? 'Unnamed' }),
43
+ },
44
+ });
45
+ ```
46
+
47
+ The visitor's provider name is the record's `id`: `auth.social.start({ provider: 'acme-corp', returnTo: '/' })` signs in through the connection `acme-corp`. Register the same `redirectUri` with every identity provider; the flow cookie says which connection the callback belongs to. The core side of this is in [providers resolved at request time](https://github.com/softistx/nxgt-janus/blob/develop/packages/janus/docs/guide/social.md#providers-resolved-at-request-time).
48
+
49
+ | Option | Type | Default | Effect |
50
+ | --- | --- | --- | --- |
51
+ | `source` | `ConnectionSource` | required | Where the records live |
52
+ | `redirectUri` | `string` | required | `https`, or `http` on a loopback host |
53
+ | `fetch` | `SocialFetch` | global `fetch` | Called once a request passed the URL guard. It must honour `init.redirect` (the guard sends `'manual'` and refuses any 3xx) and `init.signal` (the guard's timeout) |
54
+ | `timeout` | `number` | `10000` | Milliseconds each request may take, body included |
55
+ | `allowUrl` | `(url: URL) => boolean` | absent | Narrows the URL policy; never widens it |
56
+ | `cache` | `{ max?, idleMs? }` | `{ max: 500, idleMs: 3_600_000 }` | The discovery cache, see [cache](#the-cache) |
57
+ | `clock` | `Clock` | system clock | The metadata cache's time and the key-request cooldown; the key set's age follows the system clock |
58
+ | `resolveHost` | `(host: string) => Promise<readonly string[]>` | `node:dns/promises` `lookup` | Resolves a host to all its addresses for the URL guard. For specs: a fake resolver replaces the real DNS lookup, and the addresses it answers are still checked by the policy |
59
+
60
+ A bad option is a `TypeError` naming it, at construction.
61
+
62
+ `resolve(name)` answers `null` for a name that is not a provider name (it never reaches your source) and for a connection your source does not have; the core then answers `SOCIAL_PROVIDER_UNKNOWN`. A failure of your source (a thrown `StoreFailure`, say) propagates untouched. Nothing is kept per connection: the provider is built again on every `resolve`.
63
+
64
+ ## The record
65
+
66
+ ```ts
67
+ import type { OidcConnection } from '@softistx/janus-social';
68
+
69
+ export const acme: OidcConnection = {
70
+ id: 'acme-corp',
71
+ issuer: 'https://login.acme.example/oauth2/default',
72
+ client: { id: 'abc123', secret: process.env['ACME_SECRET']! }, // yours: the client registered for you
73
+ domains: ['acme.example'],
74
+ revision: 1,
75
+ };
76
+ ```
77
+
78
+ | Field | Type | Default | Meaning |
79
+ | --- | --- | --- | --- |
80
+ | `id` | `string` | required | The provider name: `/^[a-z][a-z0-9-]{0,31}$/`. Links and events carry it. **Never changed while accounts are linked** |
81
+ | `issuer` | `string` | required | The issuer URL, `https`, whose discovery document is read. Written exactly as the provider states it (lowercase scheme and host; no query, fragment, credentials, or empty, `.` or `..` path segment). **Never changed while accounts are linked** |
82
+ | `client.id`, `client.secret` | `string` | required | The client you registered. The secret never reaches a message |
83
+ | `client.authentication` | `'post' \| 'basic'` | what the server lists | How the secret reaches the token endpoint |
84
+ | `client.idTokenSignedResponseAlg` | `ConnectionAlgorithm` | the intersection of `RS256`, `PS256`, `ES256`, `EdDSA` with what the metadata lists (`RS256` when it lists none) | Pins the one algorithm the ID token must use |
85
+ | `scopes` | `string[]` | `['openid', 'email', 'profile']` | `openid` is always added |
86
+ | `domains` | `string[]` | required | The e-mail domains this connection is the sign-in of, **verified by your application**. Lowercased and converted to punycode; every label is `a-z`, `0-9` or `-` (no `%`, `_` or other character). Ownership is checked on `checkConnection`'s output. May be empty only with `emailTrust: 'claim'` |
87
+ | `emailTrust` | `'claimAndDomain' \| 'domain' \| 'claim'` | `'claimAndDomain'` | See [e-mail trust](#e-mail-trust) |
88
+ | `claims` | `{ email?, emailVerified?, name?, picture? }` | the standard names | The ID token claims that fill the identity. `accountId` is always `sub`. A protocol claim name (`sub`, `iss`, `aud`, `azp`, `nonce`, `at_hash`, `acr`, `amr`, `auth_time`) is refused |
89
+ | `stepUp` | `{ acrValues?, maxAge? }` | absent | Held on every sign-in through this connection, as [`oidcStepUp`](oidc-step-up.md) |
90
+ | `pushedAuthorization`, `dpop` | as [PAR and DPoP](par-dpop.md) | as there | Per connection |
91
+ | `revision` | `string \| number` | absent | Optional, for your own bookkeeping; `janus-social` does not read it |
92
+
93
+ An unknown key is refused, so a typo never silently disables a setting. The ID token's clock tolerance is pinned at 30 seconds (`exp`, `nbf`, `iat`); there is no option. The ID token's signature is always verified, with the key set the issuer publishes; `none` and the `HS*` algorithms cannot be written and are refused if a stored record holds them.
94
+
95
+ ## Checking a record before it is stored
96
+
97
+ `checkConnection` is the gate for your admin write path. It throws one `TypeError` listing every problem by field name, never a value, and answers a normalised copy (defaults written in, domains in punycode) without touching the record you passed.
98
+
99
+ ```ts
100
+ import { checkConnection } from '@softistx/janus-social';
101
+
102
+ declare function save(record: unknown): Promise<void>; // yours
103
+
104
+ export async function saveConnection(input: unknown): Promise<void> {
105
+ try {
106
+ await save(checkConnection(input)); // store what came back, not what came in
107
+ } catch (error) {
108
+ if (error instanceof TypeError) {
109
+ // error.message: one line per problem, e.g. checkConnection: "domains" holds a value that is not a domain name
110
+ }
111
+ throw error;
112
+ }
113
+ }
114
+ ```
115
+
116
+ Two checks stay yours, because only your table can make them:
117
+
118
+ - **A domain belongs to one connection.** `findConnectionByDomain` answers exactly one record; two connections claiming `acme.example` would let one tenant intercept the other's sign-ins. Refuse the write that would duplicate a domain.
119
+ - **Prove the domain.** `domains` is what makes the e-mail trusted: only add a domain the customer proved they own (a DNS TXT challenge, say).
120
+
121
+ `checkConnection` does not read the network: whether the issuer's host is allowed is decided when its discovery document is fetched.
122
+
123
+ ## Home-realm discovery
124
+
125
+ `forEmail(email)` answers the id of the connection that owns the address's domain, or `null`. Use it to send a visitor to their company's sign-in after they type their e-mail.
126
+
127
+ ```ts
128
+ import { connections, auth } from './wiring';
129
+
130
+ export async function startFor(email: string) {
131
+ const id = await connections.forEmail(email); // 'acme-corp', or null for an unknown domain
132
+ if (id === null) return null; // show the password form instead
133
+ return auth.social.start({ provider: id, returnTo: '/' });
134
+ }
135
+ ```
136
+
137
+ It answers `null` for an address that is not one, and for a domain with no connection. It reveals whether a domain has single sign-on, so rate-limit the route that calls it.
138
+
139
+ ## E-mail trust
140
+
141
+ The core links a social sign-in to an existing local account **by e-mail, only when the provider vouches for it**. A tenant controls what its identity provider claims, so a verified claim alone proves little: an administrator of any tenant can assert any address. `emailTrust` says what counts.
142
+
143
+ | Policy | The e-mail is verified when | Use it for |
144
+ | --- | --- | --- |
145
+ | `'claimAndDomain'` (default) | `email_verified` is true **and** the address is in `domains` | Okta, Google Workspace, most providers |
146
+ | `'domain'` | the address is in `domains` | Providers that send no `email_verified`, such as Entra ID |
147
+ | `'claim'` | `email_verified` is true | Nothing, unless every tenant is trusted completely. Opt-in and dangerous: a tenant can then take over any account by claiming its address |
148
+
149
+ An address outside `domains` is still returned as `email`, but never as verified: a hostile tenant's `ceo@victim.example` is not linked to the real account (the core answers `EMAIL_NOT_VERIFIED_FOR_LINK`, or refuses the sign-up as `EMAIL_UNVERIFIED`).
150
+
151
+ ## Per identity provider
152
+
153
+ ### Microsoft Entra ID
154
+
155
+ Use a **tenant-specific issuer**, one connection per customer tenant: `https://login.microsoftonline.com/<tenant id>/v2.0`. The multi-tenant `common` and `organizations` endpoints publish an issuer with a `{tenantid}` placeholder, which never equals the one you configure, so discovery is refused; and a tenant's ID tokens carry that tenant's id in `iss`. Entra sends no `email_verified`, so use the domain policy:
156
+
157
+ ```ts
158
+ const entra: OidcConnection = {
159
+ id: 'globex',
160
+ issuer: 'https://login.microsoftonline.com/00000000-0000-0000-0000-000000000000/v2.0', // yours: the customer's tenant id
161
+ client: { id: process.env['GLOBEX_CLIENT_ID']!, secret: process.env['GLOBEX_SECRET']! },
162
+ domains: ['globex.example'],
163
+ emailTrust: 'domain',
164
+ revision: 1,
165
+ };
166
+ ```
167
+
168
+ Ask the customer to add the `email` optional claim to the ID token, since the address is read from it. For the single-tenant preset see [Microsoft](microsoft.md).
169
+
170
+ ### Google Workspace
171
+
172
+ The issuer is the same for every Google account: `https://accounts.google.com`. A connection **does not read the `hd` claim** (the `hostedDomain` option belongs to [`google()`](google.md)): what ties a connection to a Workspace is `domains`, through the e-mail trust policy. Anyone with a Google account can finish the sign-in, but only an address in `domains`, with `email_verified` true, is trusted, so a personal `@gmail.com` account cannot sign up or link by e-mail.
173
+
174
+ **Limit:** the `hd` claim is not read. An address on your domain that belongs to a personal (unmanaged) Google account also passes as verified under `claimAndDomain`. Neither the connection nor `signUp` can tell it apart today (the profile carries no `hd`), so a Google connection is not a hard Workspace boundary. If that boundary matters, wait for the per-connection Workspace check on the [roadmap](../roadmap.md).
175
+
176
+ ```ts
177
+ const workspace: OidcConnection = {
178
+ id: 'initech',
179
+ issuer: 'https://accounts.google.com',
180
+ client: { id: process.env['GOOGLE_CLIENT_ID']!, secret: process.env['GOOGLE_CLIENT_SECRET']! },
181
+ domains: ['initech.example'], // the Workspace's primary domain
182
+ revision: 1,
183
+ };
184
+ ```
185
+
186
+ ### Okta
187
+
188
+ The issuer is the authorization server's: `https://<org>.okta.com` for the org server, or `https://<org>.okta.com/oauth2/default` (or a custom server id) for an API access management one. Use the one whose discovery document you read. Okta sends `email_verified`, so the default policy applies.
189
+
190
+ ```ts
191
+ const okta: OidcConnection = {
192
+ id: 'umbrella',
193
+ issuer: 'https://umbrella.okta.com/oauth2/default',
194
+ client: { id: process.env['UMBRELLA_CLIENT_ID']!, secret: process.env['UMBRELLA_SECRET']! },
195
+ domains: ['umbrella.example'],
196
+ revision: 1,
197
+ };
198
+ ```
199
+
200
+ ## The cache
201
+
202
+ The record is read, checked and the provider built **on every `resolve`**, so an edit to a record, or its deletion, takes effect at once. What is cached is the issuer's metadata, per issuer and not per connection:
203
+
204
+ - **Discovery** is kept for 1 hour. A failed read is not kept, but the issuer is not asked again for 30 seconds.
205
+ - **At most 500 issuers** are kept (`cache.max`), the least recently used leaving first, and an issuer idle for an hour (`cache.idleMs`) is dropped.
206
+ - **The signing keys** are kept with the metadata. An ID token signed with an unknown `kid` refetches the key set only when the kept one is 60 seconds old or more; a set 300 seconds old or more is never used and is fetched again. A revoked key can therefore still be trusted for up to 5 minutes.
207
+
208
+ ```ts
209
+ oidcConnections({ source, redirectUri, cache: { max: 100, idleMs: 600_000 } });
210
+ ```
211
+
212
+ ## Network policy
213
+
214
+ Every URL read for a connection (discovery, token, key set, pushed authorization) must be `https` with no credentials, a public host and a public address: loopback, private, link-local, metadata, CGNAT, unique-local, reserved and multicast ranges, `localhost` and single-label hosts are refused, including as IPv4-mapped or decimal forms. The host is resolved before each request and **every** address must be public. Redirects are refused, the answer must be JSON, and the body is capped (64 KiB; 256 KiB for the key set). `allowUrl` can only narrow this:
215
+
216
+ ```ts
217
+ oidcConnections({
218
+ source,
219
+ redirectUri,
220
+ allowUrl: (url) => url.hostname.endsWith('.okta.com') || url.hostname === 'login.microsoftonline.com',
221
+ });
222
+ ```
223
+
224
+ The check and the connection resolve the name separately, so a DNS server that answers a public address to one and a private one to the other (DNS rebinding) is not stopped by this layer. The complete answer is an egress firewall or proxy that denies private ranges.
225
+
226
+ ## Testing
227
+
228
+ `createMemoryConnections(records)` is a `ConnectionSource` over a list. Each record goes through `checkConnection`, and a duplicate id or a domain two records claim is a `TypeError` at creation.
229
+
230
+ ```ts
231
+ import { createMemoryConnections, oidcConnections } from '@softistx/janus-social';
232
+
233
+ const source = createMemoryConnections([
234
+ {
235
+ id: 'acme-corp',
236
+ issuer: 'https://login.acme.example',
237
+ client: { id: 'abc', secret: 'shh' },
238
+ domains: ['acme.example'],
239
+ revision: 1,
240
+ },
241
+ ]);
242
+
243
+ const connections = oidcConnections({
244
+ source,
245
+ redirectUri: 'https://app.example.com/auth/sso/callback',
246
+ });
247
+
248
+ await connections.forEmail('Ada@ACME.example'); // 'acme-corp'
249
+ await connections.resolve('nobody'); // null
250
+ ```
251
+
252
+ `forEmail` and an unknown `resolve` touch no network. A full sign-in reads the issuer's discovery document, so a spec that goes that far starts a fake issuer on a public-looking host: give `fetch` a function that answers it, and `allowUrl` stays at its default. The URL guard still resolves the host before calling your `fetch`, so either use a name that resolves to a public address or pass `resolveHost`, which replaces the DNS lookup without mocking `node:dns/promises`:
253
+
254
+ ```ts
255
+ const connections = oidcConnections({
256
+ source,
257
+ redirectUri,
258
+ fetch: fakeIdp,
259
+ resolveHost: async () => ['8.8.8.8'], // a public address; a private one is still refused
260
+ });
261
+ ```
262
+
263
+ Your own adapter over your table is checked the same way: `findConnection` answers `null` for an absent id and throws for a failure.
264
+
265
+ Something fails? See [troubleshooting](../troubleshooting.md#oidc-connections).