@_mustachio/openauth 0.12.0 → 0.13.1

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 (98) hide show
  1. package/dist/esm/domain/scim/discovery.js +206 -0
  2. package/dist/esm/domain/scim/filter.js +177 -0
  3. package/dist/esm/domain/scim/handle.js +338 -0
  4. package/dist/esm/domain/scim/patch.js +568 -0
  5. package/dist/esm/domain/scim/resource.js +256 -0
  6. package/dist/esm/http/handlers/scim.js +59 -0
  7. package/dist/esm/http/middleware/tenant.js +25 -0
  8. package/dist/esm/http/router.js +3 -0
  9. package/dist/esm/index.js +1 -0
  10. package/dist/esm/methods/saml-sp/acs.js +44 -20
  11. package/dist/esm/methods/saml-sp/attributes.js +2 -0
  12. package/dist/esm/methods/saml-sp/authnrequest.js +2 -2
  13. package/dist/esm/methods/saml-sp/factory.js +12 -1
  14. package/dist/esm/methods/saml-sp/metadata.js +5 -3
  15. package/dist/esm/methods/saml-sp/saml-instance.js +13 -3
  16. package/dist/esm/methods/saml-sp/slo-initiate.js +2 -2
  17. package/dist/esm/methods/saml-sp/sls.js +12 -4
  18. package/dist/esm/ports/scim-directory.js +0 -0
  19. package/dist/esm/types/error.js +5 -0
  20. package/dist/esm/types/scim.js +0 -0
  21. package/dist/types/domain/scim/discovery.d.ts +11 -0
  22. package/dist/types/domain/scim/discovery.d.ts.map +1 -0
  23. package/dist/types/domain/scim/filter.d.ts +51 -0
  24. package/dist/types/domain/scim/filter.d.ts.map +1 -0
  25. package/dist/types/domain/scim/handle.d.ts +35 -0
  26. package/dist/types/domain/scim/handle.d.ts.map +1 -0
  27. package/dist/types/domain/scim/patch.d.ts +73 -0
  28. package/dist/types/domain/scim/patch.d.ts.map +1 -0
  29. package/dist/types/domain/scim/resource.d.ts +56 -0
  30. package/dist/types/domain/scim/resource.d.ts.map +1 -0
  31. package/dist/types/http/context.d.ts +3 -0
  32. package/dist/types/http/context.d.ts.map +1 -1
  33. package/dist/types/http/handlers/method-route.d.ts.map +1 -1
  34. package/dist/types/http/handlers/scim.d.ts +3 -0
  35. package/dist/types/http/handlers/scim.d.ts.map +1 -0
  36. package/dist/types/http/middleware/tenant.d.ts.map +1 -1
  37. package/dist/types/http/router.d.ts.map +1 -1
  38. package/dist/types/index.d.ts +2 -0
  39. package/dist/types/index.d.ts.map +1 -1
  40. package/dist/types/methods/saml-sp/acs.d.ts.map +1 -1
  41. package/dist/types/methods/saml-sp/attributes.d.ts +5 -0
  42. package/dist/types/methods/saml-sp/attributes.d.ts.map +1 -1
  43. package/dist/types/methods/saml-sp/authnrequest.d.ts.map +1 -1
  44. package/dist/types/methods/saml-sp/factory.d.ts +217 -1
  45. package/dist/types/methods/saml-sp/factory.d.ts.map +1 -1
  46. package/dist/types/methods/saml-sp/metadata.d.ts +8 -0
  47. package/dist/types/methods/saml-sp/metadata.d.ts.map +1 -1
  48. package/dist/types/methods/saml-sp/parse-idp-metadata.d.ts.map +1 -1
  49. package/dist/types/methods/saml-sp/saml-instance.d.ts +12 -0
  50. package/dist/types/methods/saml-sp/saml-instance.d.ts.map +1 -1
  51. package/dist/types/methods/saml-sp/slo-initiate.d.ts.map +1 -1
  52. package/dist/types/methods/saml-sp/sls.d.ts +20 -0
  53. package/dist/types/methods/saml-sp/sls.d.ts.map +1 -1
  54. package/dist/types/methods/saml-sp/types.d.ts +95 -0
  55. package/dist/types/methods/saml-sp/types.d.ts.map +1 -1
  56. package/dist/types/ports/scim-directory.d.ts +104 -0
  57. package/dist/types/ports/scim-directory.d.ts.map +1 -0
  58. package/dist/types/ports/session-store.d.ts.map +1 -1
  59. package/dist/types/types/error.d.ts +5 -0
  60. package/dist/types/types/error.d.ts.map +1 -1
  61. package/dist/types/types/idp.d.ts +12 -0
  62. package/dist/types/types/idp.d.ts.map +1 -1
  63. package/dist/types/types/result.d.ts.map +1 -1
  64. package/dist/types/types/scim.d.ts +269 -0
  65. package/dist/types/types/scim.d.ts.map +1 -0
  66. package/dist/types/types/tenant.d.ts +10 -0
  67. package/dist/types/types/tenant.d.ts.map +1 -1
  68. package/package.json +1 -1
  69. package/src/domain/scim/discovery.ts +262 -0
  70. package/src/domain/scim/filter.ts +295 -0
  71. package/src/domain/scim/handle.ts +597 -0
  72. package/src/domain/scim/patch.ts +807 -0
  73. package/src/domain/scim/resource.ts +358 -0
  74. package/src/http/context.ts +3 -0
  75. package/src/http/handlers/authorize.ts +0 -1
  76. package/src/http/handlers/method-route.ts +1 -4
  77. package/src/http/handlers/scim.ts +107 -0
  78. package/src/http/middleware/tenant.ts +47 -1
  79. package/src/http/router.ts +9 -0
  80. package/src/index.ts +20 -0
  81. package/src/methods/saml-sp/acs.ts +98 -49
  82. package/src/methods/saml-sp/attributes.ts +12 -3
  83. package/src/methods/saml-sp/authnrequest.ts +3 -2
  84. package/src/methods/saml-sp/factory.ts +24 -3
  85. package/src/methods/saml-sp/metadata.ts +19 -8
  86. package/src/methods/saml-sp/parse-idp-metadata.ts +3 -9
  87. package/src/methods/saml-sp/saml-instance.ts +42 -5
  88. package/src/methods/saml-sp/slo-initiate.ts +6 -3
  89. package/src/methods/saml-sp/sls.ts +35 -5
  90. package/src/methods/saml-sp/types.ts +97 -6
  91. package/src/ports/CONSISTENCY.md +28 -25
  92. package/src/ports/scim-directory.ts +166 -0
  93. package/src/ports/session-store.ts +1 -5
  94. package/src/types/error.ts +11 -0
  95. package/src/types/idp.ts +13 -3
  96. package/src/types/result.ts +1 -2
  97. package/src/types/scim.ts +280 -0
  98. package/src/types/tenant.ts +12 -10
@@ -25,10 +25,7 @@
25
25
  * - `unspecified` — IdP picks; pass through verbatim.
26
26
  */
27
27
  export type SamlNameIdFormat =
28
- | "persistent"
29
- | "transient"
30
- | "emailAddress"
31
- | "unspecified"
28
+ "persistent" | "transient" | "emailAddress" | "unspecified"
32
29
 
33
30
  /**
34
31
  * One field's source. Either the assertion's NameID or a named
@@ -36,8 +33,7 @@ export type SamlNameIdFormat =
36
33
  * multiple attributes with the same `Name` but different `NameFormat`.
37
34
  */
38
35
  export type SamlAttributeRef =
39
- | { source: "nameId" }
40
- | { source: "attribute"; name: string; format?: string }
36
+ { source: "nameId" } | { source: "attribute"; name: string; format?: string }
41
37
 
42
38
  /**
43
39
  * How the SAML method translates a verified assertion into the
@@ -152,6 +148,80 @@ export type SamlSpConfig = {
152
148
  idpInitiated?: SamlIdpInitiatedConfig
153
149
  /** Clock skew allowance for `NotBefore` / `NotOnOrAfter`. Seconds. */
154
150
  clockSkewSeconds?: number
151
+ /**
152
+ * Override the derived SP entityID.
153
+ *
154
+ * By default the entityID is derived as
155
+ * `<issuerUrl>/<tenantId>/<methodId>` (SAML-AD5) — stable, no config
156
+ * required, and guaranteed to match what SP metadata publishes. Set
157
+ * this **only** to adopt an entityID that already exists at the IdP,
158
+ * so an existing SAML app can be migrated without the customer
159
+ * editing their production SSO config.
160
+ *
161
+ * The override flows through every consumer at once — `AuthnRequest`
162
+ * issuer, `AudienceRestriction` validation, SP metadata, and logout
163
+ * messages — so the anti-drift invariant holds either way. Changing
164
+ * it on a live connection invalidates the IdP-side trust config;
165
+ * treat it as an IdP-coordination event.
166
+ */
167
+ spEntityId?: string
168
+ /**
169
+ * Set `ForceAuthn="true"` on the outbound `AuthnRequest`, asking the
170
+ * IdP to re-authenticate the user even if it has a live session.
171
+ * Default `false`.
172
+ *
173
+ * Note that this is a *request*: SAML gives the IdP no obligation to
174
+ * honour it, and there is no way to verify from the Response that it
175
+ * did. Do not treat a successful assertion as proof of fresh
176
+ * authentication.
177
+ */
178
+ forceAuthn?: boolean
179
+ /**
180
+ * Request specific authentication context classes (e.g. MFA) from
181
+ * the IdP via `<RequestedAuthnContext>`.
182
+ *
183
+ * **Omitted ⇒ no `RequestedAuthnContext` element is sent at all**,
184
+ * which lets the IdP apply its own sign-on policy. That is the right
185
+ * default for nearly every deployment: a `RequestedAuthnContext` the
186
+ * IdP cannot satisfy exactly is answered with `NoAuthnContext`
187
+ * instead of a login, and an MFA policy at the IdP is a common way
188
+ * to *not* satisfy `PasswordProtectedTransport` under
189
+ * `Comparison="exact"`.
190
+ *
191
+ * Set it only when the IdP has told you which class refs it honours.
192
+ * `comparison` maps to the `Comparison` attribute and defaults to
193
+ * `"exact"`; `"minimum"` is usually the safer choice when requesting
194
+ * MFA.
195
+ *
196
+ * Requesting a context does **not** verify one was used — read
197
+ * `SamlSpProperties.authnContextClassRef` for what the IdP actually
198
+ * asserted.
199
+ */
200
+ requestedAuthnContext?: {
201
+ /** Full URNs, e.g. `urn:oasis:names:tc:SAML:2.0:ac:classes:MultiFactorAuthn`. */
202
+ classRefs: ReadonlyArray<string>
203
+ comparison?: "exact" | "minimum" | "maximum" | "better"
204
+ }
205
+ /**
206
+ * Require the `<saml:Assertion>` itself to carry a valid XML-DSig.
207
+ * **Defaults to `true` and should stay that way** — the identity,
208
+ * conditions, and audience all live inside the assertion, so signing
209
+ * it is what actually binds them.
210
+ *
211
+ * Set `false` only for an IdP that signs the outer `<Response>` and
212
+ * nothing else, and only together with `requireSignedResponse: true`.
213
+ * The schema refuses to let both be off.
214
+ */
215
+ requireSignedAssertion?: boolean
216
+ /**
217
+ * Require the outer `<samlp:Response>` to carry a valid XML-DSig.
218
+ * Default `false` — requiring it is stricter than the Okta / Entra
219
+ * default and would reject the majority of real IdPs. Enable it for
220
+ * an IdP that signs the Response, either as defence in depth
221
+ * alongside a signed assertion or (with
222
+ * `requireSignedAssertion: false`) as the only signature on offer.
223
+ */
224
+ requireSignedResponse?: boolean
155
225
  }
156
226
 
157
227
  /**
@@ -197,6 +267,27 @@ export type SamlSpProperties = {
197
267
  sessionIndex?: string
198
268
  /** Unix ms — the assertion's `AuthnInstant`. */
199
269
  authnInstant: number
270
+ /**
271
+ * Unix ms — the `AuthnStatement/@SessionNotOnOrAfter` the IdP
272
+ * asserted, when it supplied one. This is the IdP's own view of when
273
+ * its session for this user expires.
274
+ *
275
+ * The library does **not** act on it: token and session lifetimes are
276
+ * host policy, and this library owns no session. Hosts that want
277
+ * "when their IdP session ends, ours ends" should clamp their own
278
+ * session/token TTL to this value in the `success` callback.
279
+ */
280
+ sessionNotOnOrAfter?: number
281
+ /**
282
+ * The `AuthnContext/AuthnContextClassRef` the IdP actually asserted —
283
+ * i.e. how it says it authenticated the user. Absent when the
284
+ * assertion carries none.
285
+ *
286
+ * This is the value to check for step-up decisions ("was this really
287
+ * MFA?"). `SamlSpConfig.requestedAuthnContext` only *asks*; this is
288
+ * the answer, and the two can differ.
289
+ */
290
+ authnContextClassRef?: string
200
291
  raw: {
201
292
  responseXml: string
202
293
  }
@@ -15,31 +15,34 @@ overspecifies adapters that don't need that on the read-eventual paths
15
15
 
16
16
  ## Per-method consistency contracts
17
17
 
18
- | Port | Method | Required | Why |
19
- | -------------- | ------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
20
- | `TokenStore` | `saveCode(code, payload, ttl)` | **Strong, atomic.** Payload **encrypted at rest** with a key from `KeyStore`; `ttl ≤ 60 s` (framework refuses larger). | Code must be created exactly once and visible to the next `consumeCode` on any node. Payload may carry upstream tokens — see _Code payload confidentiality_ in plan. |
21
- | `TokenStore` | `consumeCode(code)` | **Strong, CAS.** Returns the **decrypted** payload on success. | Single-use; second consumption must fail deterministically. Race with itself must resolve to one winner. |
22
- | `TokenStore` | `saveRefresh(refresh, payload)` | **Strong, atomic.** | New refresh tokens issued during rotation must be immediately retrievable on the next request. |
23
- | `TokenStore` | `consumeRefresh(refresh, options)` | **Strong, CAS with reuse-detection window** (default 60 s). | Core of refresh-token rotation security. Concurrent presentations resolve to one winner; reuse within the window triggers the revoke chain. |
24
- | `TokenStore` | `peekRefresh(refresh)` | **Eventual acceptable.** Non-destructive read; must never mark the token consumed. | Used by `/revoke` for token-to-client binding (RFC 7009 §2.2) and by the refresh-grant for client auth + audit fields. Race losers fall through to `consumeRefresh`, which is the strong gate, so a stale peek can only delay — not bypass — single-use enforcement. |
25
- | `TokenStore` | `revokeFamily(family)` | Strong preferred; eventual acceptable with documented SLA. | Reuse-detection must invalidate the whole chain. Brief lag is tolerable. |
26
- | `TokenStore` | `revokeBySubject(tenant, subject)` | Strong preferred; eventual acceptable with documented SLA. | Revocation must propagate quickly. A few seconds of lag is tolerable. |
27
- | `SessionStore` | `saveFlow(flowId, payload, ttl)` | **Strong, atomic.** `ttl == expiresAt - createdAt`. | Flow record must be visible on the callback request to `consumeFlow`. |
28
- | `SessionStore` | `updateFlowMethodState(flowId, state)` | **Strong, atomic.** Resolves **before** the user-agent redirect is sent. | Upstream PKCE verifier / nonce must be durably persisted before the redirect, otherwise the callback cannot validate. |
29
- | `SessionStore` | `consumeFlow(flowId)` | **Strong, atomic delete-on-read** that **returns the full `FlowRecord`** (`CAS` or `DELETE … RETURNING`). | Single-use; concurrent consumption resolves to one winner. The record is returned so the framework can snapshot fields into the auth-code payload before disposal. |
30
- | `SessionStore` | `savePar(uri, payload, ttl)` (optional) | **Strong, atomic.** `ttl` default 60 s. | RFC 9126 §3 — the PAR record must be visible to the next `consumePar` on any node. One-shot read. |
31
- | `SessionStore` | `consumePar(uri)` (optional) | **Strong, atomic delete-on-read.** | RFC 9126 §4 — `request_uri` is single-use; concurrent presentations of the same uri resolve to one winner. Same semantics as `consumeFlow`. |
32
- | `SessionStore` | `createSession / readSession / revokeSession` (optional long-lived) | **Strong.** | Session creation must be immediately readable on the next request. |
33
- | `SessionStore` | `saveScratch / readScratch / deleteScratch` (optional) | **Strong, TTL-respecting.** Implement the trio together; partial implementations are not supported. | Backs `MethodContext.methodScratch` for methods that need cross-flow per-instance state (e.g. SAML SP assertion-ID replay protection). Keys arrive already namespaced by `(tenantId, methodId)` — the adapter stores opaque key/value pairs. |
34
- | `TokenStore` | `recordDpopJti(jti, ttlMs)` (optional) | **Strong, atomic record-or-fail.** | RFC 9449 §11.1 — replay protection requires single-use enforcement on the jti within the TTL window. A re-presentation must return `invalid_grant` deterministically. Adapters without this method cannot satisfy DPoP and the verifier surfaces `invalid_dpop_proof`. |
35
- | `KeyStore` | `currentSigningKey()` / `currentEncryptionKey()` | Strong. | Active key must be unambiguous. |
36
- | `KeyStore` | `signingKeys()` (JWKS) | Eventual OK (with TTL). | Verifiers tolerate brief JWKS lag during rotation. |
37
- | `KeyStore` | `getEncryptionKey(kid)` | Strong. | Required to decrypt code payloads encrypted under non-current keys during the overlap window. |
38
- | `ConfigStore` | `getTenantConfig(id)` | **Eventual + bounded staleness (TTL ≤ 60 s).** Invalidation hook fires on update. | Read-heavy, write-rare. Aggressive caching is desirable. |
39
- | `ConfigStore` | `putTenantConfig(config)` | **Strong write + immediate invalidation** of cached entries for the affected `TenantId`. | Subsequent `getTenantConfig` must reflect the new value once the write resolves. |
40
- | `MethodStore` | `getMethodConfig` / `listMethods` | Same as `ConfigStore.getTenantConfig`. | Subset of tenant config. |
41
- | `MethodStore` | `putMethodConfig` / `deleteMethodConfig` | Strong write + immediate invalidation. | Console-driven mutations must take effect on the next request. |
42
- | `AuditLog` | `log(event)` | Append-only, durable. Cross-instance ordering **not** required (consumers sort by `timestamp` + `actor`). | Loss = audit gap; ordering is a UI / SIEM concern. |
18
+ | Port | Method | Required | Why |
19
+ | --------------- | ------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
20
+ | `TokenStore` | `saveCode(code, payload, ttl)` | **Strong, atomic.** Payload **encrypted at rest** with a key from `KeyStore`; `ttl ≤ 60 s` (framework refuses larger). | Code must be created exactly once and visible to the next `consumeCode` on any node. Payload may carry upstream tokens — see _Code payload confidentiality_ in plan. |
21
+ | `TokenStore` | `consumeCode(code)` | **Strong, CAS.** Returns the **decrypted** payload on success. | Single-use; second consumption must fail deterministically. Race with itself must resolve to one winner. |
22
+ | `TokenStore` | `saveRefresh(refresh, payload)` | **Strong, atomic.** | New refresh tokens issued during rotation must be immediately retrievable on the next request. |
23
+ | `TokenStore` | `consumeRefresh(refresh, options)` | **Strong, CAS with reuse-detection window** (default 60 s). | Core of refresh-token rotation security. Concurrent presentations resolve to one winner; reuse within the window triggers the revoke chain. |
24
+ | `TokenStore` | `peekRefresh(refresh)` | **Eventual acceptable.** Non-destructive read; must never mark the token consumed. | Used by `/revoke` for token-to-client binding (RFC 7009 §2.2) and by the refresh-grant for client auth + audit fields. Race losers fall through to `consumeRefresh`, which is the strong gate, so a stale peek can only delay — not bypass — single-use enforcement. |
25
+ | `TokenStore` | `revokeFamily(family)` | Strong preferred; eventual acceptable with documented SLA. | Reuse-detection must invalidate the whole chain. Brief lag is tolerable. |
26
+ | `TokenStore` | `revokeBySubject(tenant, subject)` | Strong preferred; eventual acceptable with documented SLA. | Revocation must propagate quickly. A few seconds of lag is tolerable. |
27
+ | `SessionStore` | `saveFlow(flowId, payload, ttl)` | **Strong, atomic.** `ttl == expiresAt - createdAt`. | Flow record must be visible on the callback request to `consumeFlow`. |
28
+ | `SessionStore` | `updateFlowMethodState(flowId, state)` | **Strong, atomic.** Resolves **before** the user-agent redirect is sent. | Upstream PKCE verifier / nonce must be durably persisted before the redirect, otherwise the callback cannot validate. |
29
+ | `SessionStore` | `consumeFlow(flowId)` | **Strong, atomic delete-on-read** that **returns the full `FlowRecord`** (`CAS` or `DELETE … RETURNING`). | Single-use; concurrent consumption resolves to one winner. The record is returned so the framework can snapshot fields into the auth-code payload before disposal. |
30
+ | `SessionStore` | `savePar(uri, payload, ttl)` (optional) | **Strong, atomic.** `ttl` default 60 s. | RFC 9126 §3 — the PAR record must be visible to the next `consumePar` on any node. One-shot read. |
31
+ | `SessionStore` | `consumePar(uri)` (optional) | **Strong, atomic delete-on-read.** | RFC 9126 §4 — `request_uri` is single-use; concurrent presentations of the same uri resolve to one winner. Same semantics as `consumeFlow`. |
32
+ | `SessionStore` | `createSession / readSession / revokeSession` (optional long-lived) | **Strong.** | Session creation must be immediately readable on the next request. |
33
+ | `SessionStore` | `saveScratch / readScratch / deleteScratch` (optional) | **Strong, TTL-respecting.** Implement the trio together; partial implementations are not supported. | Backs `MethodContext.methodScratch` for methods that need cross-flow per-instance state (e.g. SAML SP assertion-ID replay protection). Keys arrive already namespaced by `(tenantId, methodId)` — the adapter stores opaque key/value pairs. |
34
+ | `TokenStore` | `recordDpopJti(jti, ttlMs)` (optional) | **Strong, atomic record-or-fail.** | RFC 9449 §11.1 — replay protection requires single-use enforcement on the jti within the TTL window. A re-presentation must return `invalid_grant` deterministically. Adapters without this method cannot satisfy DPoP and the verifier surfaces `invalid_dpop_proof`. |
35
+ | `KeyStore` | `currentSigningKey()` / `currentEncryptionKey()` | Strong. | Active key must be unambiguous. |
36
+ | `KeyStore` | `signingKeys()` (JWKS) | Eventual OK (with TTL). | Verifiers tolerate brief JWKS lag during rotation. |
37
+ | `KeyStore` | `getEncryptionKey(kid)` | Strong. | Required to decrypt code payloads encrypted under non-current keys during the overlap window. |
38
+ | `ConfigStore` | `getTenantConfig(id)` | **Eventual + bounded staleness (TTL ≤ 60 s).** Invalidation hook fires on update. | Read-heavy, write-rare. Aggressive caching is desirable. |
39
+ | `ConfigStore` | `putTenantConfig(config)` | **Strong write + immediate invalidation** of cached entries for the affected `TenantId`. | Subsequent `getTenantConfig` must reflect the new value once the write resolves. |
40
+ | `MethodStore` | `getMethodConfig` / `listMethods` | Same as `ConfigStore.getTenantConfig`. | Subset of tenant config. |
41
+ | `MethodStore` | `putMethodConfig` / `deleteMethodConfig` | Strong write + immediate invalidation. | Console-driven mutations must take effect on the next request. |
42
+ | `AuditLog` | `log(event)` | Append-only, durable. Cross-instance ordering **not** required (consumers sort by `timestamp` + `actor`). | Loss = audit gap; ordering is a UI / SIEM concern. |
43
+ | `ScimDirectory` | `createUser` / `replaceUser` / `patchUser` / `deleteUser` | **Strong, read-your-writes.** | A SCIM client issues `GET /Users?filter=userName eq "…"` immediately after a create to confirm it; an eventually-consistent read there makes the client create the user a second time. Duplicate users are the classic SCIM failure and are painful to unpick. |
44
+ | `ScimDirectory` | `getUser` / `findUsers` | **Read-your-writes for the tenant's own recent writes**; otherwise eventual is acceptable. | Same reason. Cross-tenant staleness is harmless — SCIM reads are always tenant-scoped. |
45
+ | `ScimDirectory` | uniqueness of `userName` | **Host-enforced.** Return `authError.conflict(...)` on collision. | The library stores no user rows, so it cannot enforce uniqueness. A host that checks-then-writes without a constraint will race under Okta's initial import, which is heavily concurrent. |
43
46
 
44
47
  ## Implications for adapter choice
45
48
 
@@ -0,0 +1,166 @@
1
+ /**
2
+ * `ScimDirectory` — the host's user directory, as SCIM needs to see it.
3
+ *
4
+ * This is the boundary from `SCIM-AD2`: the library owns the SCIM
5
+ * protocol (routing, bearer auth, schema validation, PATCH
6
+ * normalization, error envelope, pagination, discovery docs) and the
7
+ * host owns every byte of persistence. The library stores no user data.
8
+ *
9
+ * That split is not a compromise — it is the same protocol-over-
10
+ * host-owned-state shape as `ConfigStore`, `MethodStore` and the
11
+ * `success` callback. The host's Users table is the host's.
12
+ *
13
+ * **Consistency:** read-your-writes is required. A SCIM client
14
+ * (notably Okta) will `GET /Users?filter=userName eq "…"` immediately
15
+ * after a `POST /Users` to confirm the create; an eventually-consistent
16
+ * read there produces duplicate users. See `ports/CONSISTENCY.md`.
17
+ *
18
+ * **Errors.** SCIM clients retry `5xx` and give up on `4xx`, so which
19
+ * error you return decides whether a failure is surfaced to an admin or
20
+ * retried forever:
21
+ *
22
+ * - `authError.conflict(...)` → `409 uniqueness`. A collision only you
23
+ * can detect, because only you store the rows.
24
+ * - `authError.invalidRequest(...)` → `400 invalidValue`. A
25
+ * **permanent** rejection — you understood the request and will
26
+ * never accept it. Use it when `addMembers` names a user you do not
27
+ * have (an IdP's group push can reference a member its user push
28
+ * filtered out, or one deleted between operations), or when the data
29
+ * violates a constraint you cannot satisfy.
30
+ * - anything else → `500`, which the client retries. Correct for a
31
+ * transient fault, and far better than reporting a success you did
32
+ * not perform — but returning it for a permanent problem means the
33
+ * IdP retries the same doomed request indefinitely.
34
+ *
35
+ * Your message is passed through on both `4xx` paths; it is what an IdP
36
+ * admin reads in the provisioning log, so make it specific.
37
+ */
38
+ import type { Result } from "../types/result"
39
+ import type {
40
+ ScimGroupPatch,
41
+ ScimGroupQuery,
42
+ ScimGroupRecord,
43
+ ScimGroupWrite,
44
+ ScimPage,
45
+ ScimUserPatch,
46
+ ScimUserQuery,
47
+ ScimUserRecord,
48
+ ScimUserWrite,
49
+ } from "../types/scim"
50
+ import type { TenantId } from "../types/tenant"
51
+
52
+ export type ScimDirectory = {
53
+ /** `null` (not an error) when no user has that id in this tenant. */
54
+ getUser(
55
+ tenantId: TenantId,
56
+ id: string,
57
+ ): Promise<Result<ScimUserRecord | null>>
58
+
59
+ /**
60
+ * Query users. `query.startIndex` is 1-based and `query.count` is
61
+ * already clamped; `query.totalResults` in the response must be the
62
+ * full match count, not the page length.
63
+ */
64
+ findUsers(
65
+ tenantId: TenantId,
66
+ query: ScimUserQuery,
67
+ ): Promise<Result<ScimPage<ScimUserRecord>>>
68
+
69
+ /**
70
+ * Create a user. Return `conflict` if `userName` (or another
71
+ * uniqueness constraint of yours) is already taken — the library
72
+ * cannot check that for you.
73
+ */
74
+ createUser(
75
+ tenantId: TenantId,
76
+ user: ScimUserWrite,
77
+ ): Promise<Result<ScimUserRecord>>
78
+
79
+ /**
80
+ * Full replace (`PUT`). Attributes absent from `user` are cleared, per
81
+ * RFC 7644 §3.5.1 — this is a replace, not a merge. Use `patchUser`
82
+ * for partial updates.
83
+ */
84
+ replaceUser(
85
+ tenantId: TenantId,
86
+ id: string,
87
+ user: ScimUserWrite,
88
+ ): Promise<Result<ScimUserRecord>>
89
+
90
+ /**
91
+ * Apply a normalized delta. Present key ⇒ set; absent ⇒ leave alone;
92
+ * `null` ⇒ clear. The library has already resolved SCIM path
93
+ * expressions, so no parsing is needed here.
94
+ *
95
+ * `{ active: false }` is the ordinary deprovisioning signal and is
96
+ * usually the single most important operation to implement correctly.
97
+ */
98
+ patchUser(
99
+ tenantId: TenantId,
100
+ id: string,
101
+ patch: ScimUserPatch,
102
+ ): Promise<Result<ScimUserRecord>>
103
+
104
+ /**
105
+ * Hard delete (`DELETE`). Distinct from deactivation on purpose
106
+ * (`SCIM-AD8`): the library will not quietly turn a destructive
107
+ * request into a soft one. Hosts that do not want cascading deletes
108
+ * should implement this as a tombstone and say so in their runbook —
109
+ * but that decision is theirs to make explicitly, not the library's to
110
+ * make silently.
111
+ */
112
+ deleteUser(tenantId: TenantId, id: string): Promise<Result<void>>
113
+
114
+ // ─── Groups ───
115
+ //
116
+ // Optional as a set: a host that only needs user provisioning can omit
117
+ // all six, and `/scim/v2/Groups` then answers 501 instead of failing
118
+ // at runtime. Implement all of them or none — a half-implemented
119
+ // Groups surface fails an IdP's group push in confusing ways.
120
+
121
+ getGroup?(
122
+ tenantId: TenantId,
123
+ id: string,
124
+ ): Promise<Result<ScimGroupRecord | null>>
125
+
126
+ /**
127
+ * `query.excludeMembers` is set when the client asked for
128
+ * `excludedAttributes=members`. Honour it by not loading membership —
129
+ * Okta sets it while enumerating groups, and ignoring it turns a cheap
130
+ * listing into a fan-out read per group.
131
+ */
132
+ findGroups?(
133
+ tenantId: TenantId,
134
+ query: ScimGroupQuery,
135
+ ): Promise<Result<ScimPage<ScimGroupRecord>>>
136
+
137
+ createGroup?(
138
+ tenantId: TenantId,
139
+ group: ScimGroupWrite,
140
+ ): Promise<Result<ScimGroupRecord>>
141
+
142
+ /** Full replace, including membership. */
143
+ replaceGroup?(
144
+ tenantId: TenantId,
145
+ id: string,
146
+ group: ScimGroupWrite,
147
+ ): Promise<Result<ScimGroupRecord>>
148
+
149
+ /**
150
+ * Apply a normalized group delta.
151
+ *
152
+ * Exactly one membership shape arrives at a time: `members` (replace
153
+ * everything) or `addMembers` / `removeMembers` (incremental). The
154
+ * incremental form exists so a 20,000-member group does not have to be
155
+ * read and rewritten to add one person — see `SCIM-AD9`. Adding an
156
+ * existing member or removing an absent one must succeed quietly;
157
+ * IdPs retry and expect idempotence.
158
+ */
159
+ patchGroup?(
160
+ tenantId: TenantId,
161
+ id: string,
162
+ patch: ScimGroupPatch,
163
+ ): Promise<Result<ScimGroupRecord>>
164
+
165
+ deleteGroup?(tenantId: TenantId, id: string): Promise<Result<void>>
166
+ }
@@ -122,11 +122,7 @@ export type SessionStore = {
122
122
  * `MethodContext.methodScratch` at call time. Implement all three
123
123
  * methods together — partial implementations are not supported.
124
124
  */
125
- saveScratch?(
126
- key: string,
127
- value: string,
128
- ttlMs: number,
129
- ): Promise<Result<void>>
125
+ saveScratch?(key: string, value: string, ttlMs: number): Promise<Result<void>>
130
126
  readScratch?(key: string): Promise<Result<string>>
131
127
  deleteScratch?(key: string): Promise<Result<void>>
132
128
  }
@@ -50,6 +50,12 @@ export type AuthError =
50
50
  // endpoints. Use for control-flow signalling that should never escape to a
51
51
  // standards-compliant client.
52
52
  | { code: "internal_error"; description: string; cause?: unknown }
53
+ // Uniqueness / state conflict. Raised by hosts from `ScimDirectory`
54
+ // when a create or update collides with an existing record — only the
55
+ // host can know, since only the host stores the rows. The SCIM layer
56
+ // renders it as `409` with `scimType: "uniqueness"`. It has no OAuth
57
+ // endpoint mapping and should never reach one.
58
+ | { code: "conflict"; description: string; attribute?: string }
53
59
  // RFC 9449 §5.2 — DPoP proof verification failed (bad signature, htm/htu
54
60
  // mismatch, iat outside window, replayed jti, missing/mismatched cnf.jkt).
55
61
  // Returned as a 400 with `error="invalid_dpop_proof"` on form-body
@@ -130,6 +136,11 @@ export const authError = {
130
136
  code: "invalid_target",
131
137
  description,
132
138
  }),
139
+ conflict: (description: string, attribute?: string): AuthError => ({
140
+ code: "conflict",
141
+ description,
142
+ ...(attribute !== undefined ? { attribute } : {}),
143
+ }),
133
144
  internalError: (description: string, cause?: unknown): AuthError => ({
134
145
  code: "internal_error",
135
146
  description,
package/src/types/idp.ts CHANGED
@@ -7,6 +7,7 @@ import type { AuditLog } from "../ports/audit-log"
7
7
  import type { ConfigStore } from "../ports/config-store"
8
8
  import type { KeyStore } from "../ports/key-store"
9
9
  import type { MethodStore } from "../ports/method-store"
10
+ import type { ScimDirectory } from "../ports/scim-directory"
10
11
  import type { SessionStore } from "../ports/session-store"
11
12
  import type { TokenStore } from "../ports/token-store"
12
13
 
@@ -186,9 +187,7 @@ export type RegisterClientRequest = {
186
187
  response_types?: string[]
187
188
  /** RFC 7591 §2 — `"none"` = public client, otherwise confidential. */
188
189
  token_endpoint_auth_method?:
189
- | "none"
190
- | "client_secret_basic"
191
- | "client_secret_post"
190
+ "none" | "client_secret_basic" | "client_secret_post"
192
191
  scope?: string
193
192
  /** OIDC RP-Initiated Logout 1.0 §2. */
194
193
  post_logout_redirect_uris?: string[]
@@ -280,6 +279,17 @@ export type IdPOptions = {
280
279
  auditLog?: AuditLog
281
280
  /** Optional — falls back to `ConfigStore` for `MethodConfig` lookups. */
282
281
  methodStore?: MethodStore
282
+ /**
283
+ * The host's user directory, as SCIM needs to see it. Supply it to
284
+ * serve `/scim/v2/*`; omit it and those routes answer 501 regardless
285
+ * of per-tenant config.
286
+ *
287
+ * The library owns the SCIM protocol and stores no user data — every
288
+ * read and write goes through this port to the host's own tables. See
289
+ * `SCIM-AD2` in `docs/plans/claude/scim-plan.md` and
290
+ * `INTEGRATION.md` § SCIM.
291
+ */
292
+ scimDirectory?: ScimDirectory
283
293
 
284
294
  /** Issuer URL. Function form lets multi-tenant deployments derive it per request. */
285
295
  issuerUrl: string | ((req: Request) => string)
@@ -11,8 +11,7 @@
11
11
  import type { AuthError } from "./error"
12
12
 
13
13
  export type Result<T, E = AuthError> =
14
- | { ok: true; value: T }
15
- | { ok: false; error: E }
14
+ { ok: true; value: T } | { ok: false; error: E }
16
15
 
17
16
  export const ok = <T>(value: T): Result<T, never> => ({ ok: true, value })
18
17
  export const err = <E>(error: E): Result<never, E> => ({ ok: false, error })