diff --git a/docs/api/openapi.yaml b/docs/api/openapi.yaml index 5559a9937..0e21cb822 100644 --- a/docs/api/openapi.yaml +++ b/docs/api/openapi.yaml @@ -1873,9 +1873,15 @@ paths: description: "Web only. Checks the link and the username, sets a sealed `hl_claim` cookie (10 minutes, `httpOnly`) and answers where to continue: `/api/auth/oidc/login?intent=claim`. The OIDC callback binds the identity provider's subject to the profile and signs the new owner in; a subject already bound to an account, or a verified email - another account holds, is refused there. Works on a single-sign-on-only instance. 404 `profile_claim.invalid` - (no usable link) or `profile_claim.sso_unavailable` (no identity provider configured); 409 `profile_claim.taken` - (username) or `auth.already_authenticated`; rate-limited per source address like the password claim." + another account holds, is refused there. Works on a single-sign-on-only instance. When the callback refuses, the + browser lands on `/auth/claim?error=` with reason `claim_expired` (the link was used, withdrawn, + replaced or expired in the meantime, or the cookie is missing, expired or belongs to another start), + `claim_sso_subject_bound`, `claim_email_taken`, `claim_username_taken` (taken during the round trip), + `claim_signed_in`, or one of the sign-in reasons (`oidc_denied`, `oidc_state`, `oidc_failed`, + `oidc_rate_limited`, `oidc_disabled`); on success it lands on `/onboarding/handover`, where the new owner + decides each guardian's access. The cookie is cleared either way. 404 `profile_claim.invalid` (no usable link) + or `profile_claim.sso_unavailable` (no identity provider configured); 409 `profile_claim.taken` (username) or + `auth.already_authenticated`; rate-limited per source address like the password claim." requestBody: required: true content: @@ -1904,15 +1910,6 @@ paths: $ref: "#/components/schemas/ErrorEnvelope" "422": *a4 "429": *a5 - "501": &a44 - description: "Not implemented on this server yet: the contract is published, the effect is not. `meta.errorCode` = - `not_implemented`, `meta.operation` names the operation. Authentication, module gates and request validation - already answer as documented. A client reaches this only by ignoring the server feature flag that guards the - operation." - content: - application/json: - schema: - $ref: "#/components/schemas/ErrorEnvelope" /api/auth/claim/preview: post: security: [] @@ -1921,7 +1918,8 @@ paths: summary: Preview a managed-profile handover link description: "What a handover link would hand over: the profile's display name, the link's expiry, and each guardian's proposal. Anonymous; the token travels in the body. An unknown, expired, used or withdrawn token, and a link - whose creator lost access, all answer the same 404. Rate-limited per source address." + whose creator lost access, all answer the same 404. Rate-limited per source address. Since v1.43 answered on a + single-sign-on-only instance too, with `methods` naming the ways in." requestBody: required: true content: @@ -1936,12 +1934,6 @@ paths: schema: $ref: "#/components/schemas/ProfileClaimPreviewEnvelope" "401": *a1 - "403": - description: "The instance allows single sign-on only (`meta.errorCode: profile_claim.oidc_only_unsupported`)." - content: - application/json: - schema: - $ref: "#/components/schemas/ErrorEnvelope" "404": description: "No usable link behind this token (`meta.errorCode: profile_claim.invalid`). Every failure class answers identically." @@ -3738,6 +3730,19 @@ paths: type: string description: "Browser leg only: where to land after login. Sanitised to an in-app path; ignored entirely on the native leg." + - in: query + name: intent + schema: + description: "v1.43 — `claim` continues a managed-profile claim started at POST /api/auth/claim/sso; the link and + username ride the sealed `hl_claim` cookie that call set, never this URL. Without a valid cookie for a + still-usable link the start redirects to `/auth/claim?error=claim_expired`. Browser leg only: with + `client=native` it fails with `oidc_invalid_request`. `next` is ignored." + type: string + const: claim + description: "v1.43 — `claim` continues a managed-profile claim started at POST /api/auth/claim/sso; the link and + username ride the sealed `hl_claim` cookie that call set, never this URL. Without a valid cookie for a + still-usable link the start redirects to `/auth/claim?error=claim_expired`. Browser leg only: with + `client=native` it fails with `oidc_invalid_request`. `next` is ignored." - in: query name: client_proto schema: @@ -3762,7 +3767,8 @@ paths: description: "Browser leg only: `location.host` of that page, read together with `client_proto`." responses: "302": - description: Always a redirect. To the provider on success. On failure to `/auth/login?error=` (browser) or + description: Always a redirect. To the provider on success. On failure to `/auth/login?error=` (browser; + `/auth/claim?error=` with `intent=claim`, where `claim_expired` is one more reason) or `healthlog://oidc-callback?error=` (native), where reason is one of `oidc_disabled`, `oidc_rate_limited`, `oidc_invalid_request`, `oidc_failed`, and on the browser leg `insecure_transport` (see `client_proto`). The provider then returns to the callback (not listed here, because the identity provider @@ -18893,7 +18899,7 @@ paths: schema: $ref: "#/components/schemas/NutrientCatalogEnvelope" "401": *a1 - "403": &a45 + "403": &a44 description: >- The opt-in `nutrients` module is off for this account (errorCode `module.disabled`). Stop syncing and do not retry; offer the enable-in-settings hint. Only run the HealthKit read-authorization flow while the module is @@ -18915,7 +18921,15 @@ paths: $ref: "#/components/schemas/ErrorEnvelope" "422": *a4 "429": *a5 - "501": *a44 + "501": &a69 + description: "Not implemented on this server yet: the contract is published, the effect is not. `meta.errorCode` = + `not_implemented`, `meta.operation` names the operation. Authentication, module gates and request validation + already answer as documented. A client reaches this only by ignoring the server feature flag that guards the + operation." + content: + application/json: + schema: + $ref: "#/components/schemas/ErrorEnvelope" /api/nutrients/batch: post: tags: @@ -19041,7 +19055,7 @@ paths: schema: $ref: "#/components/schemas/NutrientOverviewEnvelope" "401": *a1 - "403": *a45 + "403": *a44 "422": *a4 "429": *a5 /api/nutrients/daily: @@ -19077,7 +19091,7 @@ paths: schema: $ref: "#/components/schemas/NutrientDailySeriesEnvelope" "401": *a1 - "403": *a45 + "403": *a44 "422": *a4 "429": *a5 /api/nutrients/water: @@ -19106,7 +19120,7 @@ paths: schema: $ref: "#/components/schemas/NutrientWaterWriteEnvelope" "401": *a1 - "403": *a45 + "403": *a44 "409": *a7 "422": *a4 "429": *a5 @@ -19608,26 +19622,26 @@ paths: application/json: schema: $ref: "#/components/schemas/WithingsCredentialsUpdateEnvelope" - "400": &a46 + "400": &a45 description: Body is not parseable JSON. content: application/json: schema: $ref: "#/components/schemas/ErrorEnvelope" "401": *a1 - "413": &a47 + "413": &a46 description: Body exceeds 64 KiB. content: application/json: schema: $ref: "#/components/schemas/ErrorEnvelope" - "415": &a48 + "415": &a47 description: Content-Type is not `application/json`. content: application/json: schema: $ref: "#/components/schemas/ErrorEnvelope" - "422": &a49 + "422": &a48 description: "`clientId` and `clientSecret` are both required and each must be 1–200 characters. The envelope carries a single fixed message, not per-field issues." content: @@ -19813,11 +19827,11 @@ paths: application/json: schema: $ref: "#/components/schemas/FitbitCredentialsUpdateEnvelope" - "400": *a46 + "400": *a45 "401": *a1 - "413": *a47 - "415": *a48 - "422": *a49 + "413": *a46 + "415": *a47 + "422": *a48 "429": *a5 delete: tags: @@ -19960,11 +19974,11 @@ paths: application/json: schema: $ref: "#/components/schemas/GoogleHealthCredentialsUpdateEnvelope" - "400": *a46 + "400": *a45 "401": *a1 - "413": *a47 - "415": *a48 - "422": *a49 + "413": *a46 + "415": *a47 + "422": *a48 "429": *a5 delete: tags: @@ -20125,11 +20139,11 @@ paths: application/json: schema: $ref: "#/components/schemas/OuraCredentialsUpdateEnvelope" - "400": *a46 + "400": *a45 "401": *a1 - "413": *a47 - "415": *a48 - "422": *a49 + "413": *a46 + "415": *a47 + "422": *a48 "429": *a5 delete: tags: @@ -20205,21 +20219,21 @@ paths: schema: $ref: "#/components/schemas/OuraTestEnvelope" "401": *a1 - "422": &a50 + "422": &a49 description: No usable connection for this provider — nothing stored, or the stored grant could no longer be resolved into an access token. `meta.errorCode` = `not_configured`. content: application/json: schema: $ref: "#/components/schemas/ErrorEnvelope" - "429": &a51 + "429": &a50 description: More than 5 requests in 60 s from this user. `meta.errorCode` = `rate_limited_self` — this is the local limiter, distinct from a `rate_limited` 502 which is the provider's. content: application/json: schema: $ref: "#/components/schemas/ErrorEnvelope" - "502": &a52 + "502": &a51 description: "The probe did not complete. `meta.errorCode` names the class: `credentials_rejected` (the provider answered 401/403 — the stored grant is gone), `rate_limited` (the PROVIDER answered 429, which is not this endpoint's own limiter), `upstream_error` (5xx), `timeout` (no answer within 5 s), `connection_failed` @@ -20264,11 +20278,11 @@ paths: application/json: schema: $ref: "#/components/schemas/PolarCredentialsUpdateEnvelope" - "400": *a46 + "400": *a45 "401": *a1 - "413": *a47 - "415": *a48 - "422": *a49 + "413": *a46 + "415": *a47 + "422": *a48 "429": *a5 delete: tags: @@ -20344,9 +20358,9 @@ paths: schema: $ref: "#/components/schemas/PolarTestEnvelope" "401": *a1 - "422": *a50 - "429": *a51 - "502": *a52 + "422": *a49 + "429": *a50 + "502": *a51 /api/strava/credentials: get: tags: @@ -20382,11 +20396,11 @@ paths: application/json: schema: $ref: "#/components/schemas/StravaCredentialsUpdateEnvelope" - "400": *a46 + "400": *a45 "401": *a1 - "413": *a47 - "415": *a48 - "422": *a49 + "413": *a46 + "415": *a47 + "422": *a48 "429": *a5 delete: tags: @@ -20464,9 +20478,9 @@ paths: schema: $ref: "#/components/schemas/StravaTestEnvelope" "401": *a1 - "422": *a50 - "429": *a51 - "502": *a52 + "422": *a49 + "429": *a50 + "502": *a51 /api/integrations/status: get: tags: @@ -20502,7 +20516,7 @@ paths: $ref: "#/components/schemas/FitbitResumeEnvelope" "401": *a1 "422": *a4 - "429": *a51 + "429": *a50 /api/integrations/fitbit/test: post: tags: @@ -20520,9 +20534,9 @@ paths: schema: $ref: "#/components/schemas/FitbitIntegrationTestEnvelope" "401": *a1 - "422": *a50 - "429": *a51 - "502": *a52 + "422": *a49 + "429": *a50 + "502": *a51 /api/integrations/google-health/resume: post: tags: @@ -20539,7 +20553,7 @@ paths: $ref: "#/components/schemas/GoogleHealthResumeEnvelope" "401": *a1 "422": *a4 - "429": *a51 + "429": *a50 /api/integrations/google-health/test: post: tags: @@ -20572,9 +20586,9 @@ paths: application/json: schema: $ref: "#/components/schemas/ErrorEnvelope" - "422": *a50 - "429": *a51 - "502": *a52 + "422": *a49 + "429": *a50 + "502": *a51 /api/integrations/whoop/resume: post: tags: @@ -20591,7 +20605,7 @@ paths: $ref: "#/components/schemas/WhoopResumeEnvelope" "401": *a1 "422": *a4 - "429": *a51 + "429": *a50 /api/integrations/whoop/test: post: tags: @@ -20608,9 +20622,9 @@ paths: schema: $ref: "#/components/schemas/WhoopIntegrationTestEnvelope" "401": *a1 - "422": *a50 - "429": *a51 - "502": *a52 + "422": *a49 + "429": *a50 + "502": *a51 /api/integrations/withings/resume: post: tags: @@ -20628,7 +20642,7 @@ paths: $ref: "#/components/schemas/WithingsResumeEnvelope" "401": *a1 "422": *a4 - "429": *a51 + "429": *a50 /api/integrations/withings/test: post: tags: @@ -20646,8 +20660,8 @@ paths: schema: $ref: "#/components/schemas/WithingsIntegrationTestEnvelope" "401": *a1 - "422": *a50 - "429": *a51 + "422": *a49 + "429": *a50 "502": description: "The probe did not complete. The shared codes apply (`credentials_rejected`, `rate_limited`, `upstream_error`, `timeout`, `connection_failed`) and this path adds one of its own: @@ -20903,7 +20917,9 @@ paths: $ref: "#/components/schemas/ManagedProfileHandoverEnvelope" "401": *a1 "403": - description: "The instance allows single sign-on only (`meta.errorCode: profile_claim.oidc_only_unsupported`)." + description: "Neither a password nor single sign-on could redeem a link on this instance (`meta.errorCode: + profile_claim.oidc_only_unsupported`). Since v1.43 a single-sign-on-only instance hands over through the + identity provider, so a working configuration never answers this." content: application/json: schema: @@ -21049,7 +21065,7 @@ paths: schema: $ref: "#/components/schemas/RecordActivityEnvelope" "401": *a1 - "403": &a53 + "403": &a52 description: Refused. `meta.errorCode` is `sharing.not_permitted` when the request was made while acting on another account (grant management is never delegable), or `sharing.access.denied` when the caller may not act as the account they named. The latter is byte-identical for an account that does not exist and one that granted @@ -21074,7 +21090,7 @@ paths: schema: $ref: "#/components/schemas/AccountGrantListEnvelope" "401": *a1 - "403": *a53 + "403": *a52 "422": *a4 "429": *a5 post: @@ -21176,7 +21192,7 @@ paths: schema: $ref: "#/components/schemas/AcceptedAccountGrantEnvelope" "401": *a1 - "403": *a53 + "403": *a52 "404": description: No such invitation for this account. content: @@ -21220,7 +21236,7 @@ paths: schema: $ref: "#/components/schemas/RevokedAccountGrantEnvelope" "401": *a1 - "403": *a53 + "403": *a52 "404": description: No such grant on this account's record. content: @@ -21261,7 +21277,7 @@ paths: schema: $ref: "#/components/schemas/RenouncedAccountGrantEnvelope" "401": *a1 - "403": *a53 + "403": *a52 "404": description: No such grant held by this account. content: @@ -21643,7 +21659,7 @@ paths: schema: $ref: "#/components/schemas/ErrorEnvelope" "401": *a1 - "403": *a53 + "403": *a52 "409": description: "The record this browser session is on is not the record the request asserted. `meta.errorCode` is `sharing.session.changed`. It is not a refusal of access — the caller may well be entitled to both records — @@ -22023,7 +22039,7 @@ paths: schema: $ref: "#/components/schemas/McpConnectionListEnvelope" "401": *a1 - "403": &a54 + "403": &a53 description: The operator has disabled the API instance-wide. Every route in this module refuses while that setting is off, for a cookie session as well as for a Bearer token; it is not a per-user permission and retrying will not help. @@ -22056,7 +22072,7 @@ paths: schema: $ref: "#/components/schemas/McpConnectionRevokeEnvelope" "401": *a1 - "403": *a54 + "403": *a53 "404": description: No live connection with this id for this caller — also the answer for an already-revoked one, so a repeat revoke is 404 rather than an idempotent 200. @@ -22083,7 +22099,7 @@ paths: schema: $ref: "#/components/schemas/McpConnectorTokenListEnvelope" "401": *a1 - "403": *a54 + "403": *a53 "422": *a4 "429": *a5 post: @@ -22116,7 +22132,7 @@ paths: schema: $ref: "#/components/schemas/ErrorEnvelope" "401": *a1 - "403": *a54 + "403": *a53 "413": description: Body exceeds 16 KiB. content: @@ -22159,7 +22175,7 @@ paths: schema: $ref: "#/components/schemas/McpConnectorTokenRevokeEnvelope" "401": *a1 - "403": *a54 + "403": *a53 "404": description: No `health:read` token with this id for this caller. An already-revoked token is still found, so a repeat revoke answers 200. @@ -22218,7 +22234,7 @@ paths: description: Returns the named family's resolved settings for the record the session is acting on. Cookie session or Bearer, while acting on a managed record the caller guards. parameters: - - &a55 + - &a54 name: family in: path required: true @@ -22262,7 +22278,7 @@ paths: ride the audit row. Body capped at 64 KiB. Cookie session or Bearer, while acting on a managed record the caller guards. parameters: - - *a55 + - *a54 requestBody: required: true content: @@ -22835,13 +22851,13 @@ paths: application/json: schema: $ref: "#/components/schemas/AdminBackupDocument" - "403": &a56 + "403": &a55 description: Caller is not an admin. `requireAdmin()` is cookie-only, so a Bearer token lands here whatever its scope. content: application/json: schema: $ref: "#/components/schemas/ErrorEnvelope" - "404": &a57 + "404": &a56 description: No stored copy with this id. content: application/json: @@ -22915,8 +22931,8 @@ paths: application/json: schema: $ref: "#/components/schemas/ErrorEnvelope" - "403": *a56 - "404": *a57 + "403": *a55 + "404": *a56 "409": description: A restore of the same account is already queued or running (`meta.errorCode` = `backup.restore.active`, `meta.jobId` names it), the stored copy was replaced by a newer one while it was being checked @@ -22960,7 +22976,7 @@ paths: application/json: schema: $ref: "#/components/schemas/AdminBackupRestoreJobListResponse" - "403": *a56 + "403": *a55 /api/admin/backups/restores/{jobId}: get: tags: @@ -22983,7 +22999,7 @@ paths: application/json: schema: $ref: "#/components/schemas/AdminBackupRestoreJobResponse" - "403": *a56 + "403": *a55 "404": description: No restore job with this id. content: @@ -23002,7 +23018,7 @@ paths: request leaves the server. Needs neither the Documents module nor the list: with the list unset, `available` is false and any connection still stored is listed (with `originAllowed: false`) so it can be removed. Cookie session only; not delegable." - security: &a58 + security: &a57 - cookieAuth: [] responses: "200": @@ -23012,7 +23028,7 @@ paths: schema: $ref: "#/components/schemas/DocumentSourcesStatusEnvelope" "401": *a1 - "403": &a59 + "403": &a58 description: "Refused before any request to the source: `documents.sources.browserOnly` for a Bearer caller, `sharing.not_permitted` while acting on another person's record (a delegate or guardian never uses the owner's archive), or `module.disabled` when the Documents module is off." @@ -23035,9 +23051,9 @@ paths: `documents.sources.tokenRequired`), so a stored token is never sent to an address it was not saved for. A Papra organization id is letters, digits, `_` and `-`. The token is stored encrypted (AES-256-GCM) and never returned. Ten saves and tests a minute per person. Cookie session only; not delegable." - security: *a58 + security: *a57 parameters: - - &a60 + - &a59 name: system in: path required: true @@ -23076,8 +23092,8 @@ paths: schema: $ref: "#/components/schemas/DocumentSourceConnectionEnvelope" "401": *a1 - "403": *a59 - "404": &a61 + "403": *a58 + "404": &a60 description: "`documents.sources.unavailable`: the operator has not listed any origin in `DOCUMENT_SOURCE_ORIGINS`, so the picker is off. `documents.sources.notConnected`: no connection is saved for this system. `documents.sources.notFound`: the source has no such document, or (Papra) no such organization, including @@ -23096,7 +23112,7 @@ paths: schema: $ref: "#/components/schemas/ErrorEnvelope" "429": *a5 - "502": &a62 + "502": &a61 description: "The source could not answer usefully, with the reason in `meta.errorCode` and, when the source answered at all, its HTTP status in `meta.upstreamStatus` (its body is never passed on): `documents.sources.unreachable` (no connection, timeout, or a destination refused at dial time), `documents.sources.redirected` (the source @@ -23115,9 +23131,9 @@ paths: description: Deletes the caller's connection for this system, and its token with it. Works even after the operator removed the origin from the list, and with the Documents module switched off. `disconnected` is false when there was nothing to delete. Cookie session only; not delegable. - security: *a58 + security: *a57 parameters: - - *a60 + - *a59 responses: "200": description: Removed, or there was nothing to remove. @@ -23126,7 +23142,7 @@ paths: schema: $ref: "#/components/schemas/DocumentSourceDisconnectEnvelope" "401": *a1 - "403": *a59 + "403": *a58 "422": *a4 "429": *a5 /api/documents/sources/{system}/test: @@ -23137,9 +23153,9 @@ paths: description: One request to the source with the stored token. Answers `ok` with the round-trip time and stamps `lastVerifiedAt`, or the reason in `meta.errorCode`. Shares the save's allowance of ten a minute. Cookie session only; not delegable. - security: *a58 + security: *a57 parameters: - - *a60 + - *a59 responses: "200": description: The source answered. @@ -23148,9 +23164,9 @@ paths: schema: $ref: "#/components/schemas/DocumentSourceTestEnvelope" "401": *a1 - "403": *a59 - "404": *a61 - "422": &a63 + "403": *a58 + "404": *a60 + "422": &a62 description: "`documents.sources.originNotAllowed`: the base address's origin is not on the operator's list (checked on every request, so a connection saved earlier is cut off once its origin is removed), or another validation failure." @@ -23159,7 +23175,7 @@ paths: schema: $ref: "#/components/schemas/ErrorEnvelope" "429": *a5 - "502": *a62 + "502": *a61 /api/documents/sources/{system}/tags: get: tags: @@ -23167,9 +23183,9 @@ paths: summary: Tags of a connected archive description: The source's tags for the picker's filter, the first 250 by name, in the source's own ids. Shares the search allowance of sixty a minute. Cookie session only; not delegable. - security: *a58 + security: *a57 parameters: - - *a60 + - *a59 responses: "200": description: The tags. @@ -23178,11 +23194,11 @@ paths: schema: $ref: "#/components/schemas/DocumentSourceTagsEnvelope" "401": *a1 - "403": *a59 - "404": *a61 - "422": *a63 + "403": *a58 + "404": *a60 + "422": *a62 "429": *a5 - "502": *a62 + "502": *a61 /api/documents/sources/{system}/search: get: tags: @@ -23196,9 +23212,9 @@ paths: under that source key: `new`, `imported` with the vault document's `documentId`, or `deleted` (deleted in HealthLog; importing it again stores nothing). Nothing is stored. Sixty searches a minute, shared with the tag read. Cookie session only; not delegable." - security: *a58 + security: *a57 parameters: - - *a60 + - *a59 - name: q in: query required: false @@ -23239,11 +23255,11 @@ paths: schema: $ref: "#/components/schemas/DocumentSourceSearchEnvelope" "401": *a1 - "403": *a59 - "404": *a61 - "422": *a63 + "403": *a58 + "404": *a60 + "422": *a62 "429": *a5 - "502": *a62 + "502": *a61 /api/documents/sources/{system}/import: post: tags: @@ -23262,9 +23278,9 @@ paths: fetched), including a duplicate. `kind` sets the document type (default OTHER). Automatic AI reading follows the person's own setting. Counts against the person's upload allowance (60 an hour) and storage quota. 201 for a new document, 200 otherwise. Cookie session only; not delegable." - security: *a58 + security: *a57 parameters: - - *a60 + - *a59 requestBody: required: true content: @@ -23322,7 +23338,7 @@ paths: schema: $ref: "#/components/schemas/DocumentSourceImportEnvelope" "401": *a1 - "403": *a59 + "403": *a58 "404": description: "`documents.sources.unavailable`: the operator has not listed any origin in `DOCUMENT_SOURCE_ORIGINS`, so the picker is off. `documents.sources.notConnected`: no connection is saved for this system. @@ -23353,7 +23369,7 @@ paths: application/json: schema: $ref: "#/components/schemas/ErrorEnvelope" - "422": *a63 + "422": *a62 "429": description: "`documents.inbound.rateLimited` (the person's hourly upload allowance, with the rate-limit headers) or `documents.inbound.uploadBusy` (too many uploads in progress; `Retry-After: 1`)." @@ -23361,7 +23377,7 @@ paths: application/json: schema: $ref: "#/components/schemas/ErrorEnvelope" - "502": *a62 + "502": *a61 /api/symptoms/definitions: get: tags: @@ -23385,7 +23401,7 @@ paths: schema: $ref: "#/components/schemas/ListSymptomDefinitionsEnvelope" "401": *a1 - "403": &a64 + "403": &a63 description: >- `illness.disabled`: the record has the illness module switched off (or the operator turned it off server-wide); symptoms ride that module. @@ -23428,7 +23444,7 @@ paths: schema: $ref: "#/components/schemas/CreateSymptomDefinitionEnvelope" "401": *a1 - "403": *a64 + "403": *a63 "409": *a7 "422": *a4 "429": *a5 @@ -23458,8 +23474,8 @@ paths: schema: $ref: "#/components/schemas/UpdateSymptomDefinitionEnvelope" "401": *a1 - "403": *a64 - "404": &a65 + "403": *a63 + "404": &a64 description: "`symptoms.definition.notFound`: no definition with this id on the record." content: application/json: @@ -23493,8 +23509,8 @@ paths: schema: $ref: "#/components/schemas/DeleteSymptomDefinitionEnvelope" "401": *a1 - "403": *a64 - "404": *a65 + "403": *a63 + "404": *a64 "422": *a4 "429": *a5 /api/symptoms/events: @@ -23543,7 +23559,7 @@ paths: schema: $ref: "#/components/schemas/ListSymptomEventsEnvelope" "401": *a1 - "403": *a64 + "403": *a63 "422": *a4 "429": *a5 post: @@ -23569,8 +23585,8 @@ paths: schema: $ref: "#/components/schemas/CreateSymptomEventEnvelope" "401": *a1 - "403": *a64 - "404": *a65 + "403": *a63 + "404": *a64 "409": *a7 "422": *a4 "429": *a5 @@ -23600,8 +23616,8 @@ paths: schema: $ref: "#/components/schemas/UpdateSymptomEventEnvelope" "401": *a1 - "403": *a64 - "404": &a66 + "403": *a63 + "404": &a65 description: "`symptoms.event.notFound`: no occurrence with this id on the record." content: application/json: @@ -23628,8 +23644,8 @@ paths: schema: $ref: "#/components/schemas/DeleteSymptomEventEnvelope" "401": *a1 - "403": *a64 - "404": *a66 + "403": *a63 + "404": *a65 "422": *a4 "429": *a5 /api/day/index: @@ -23779,7 +23795,7 @@ paths: schema: $ref: "#/components/schemas/TimelineEnvelope" "401": *a1 - "403": &a67 + "403": &a66 description: >- `module.disabled` with `meta.module = timeline`: the record has the timeline switched off (it is opt-in), or the operator turned it off server-wide. @@ -23816,7 +23832,7 @@ paths: schema: $ref: "#/components/schemas/TimelineReadinessEnvelope" "401": *a1 - "403": *a67 + "403": *a66 "422": *a4 "429": *a5 /api/life-events: @@ -23834,7 +23850,7 @@ paths: schema: $ref: "#/components/schemas/LifeEventListEnvelope" "401": *a1 - "403": &a68 + "403": &a67 description: >- Owner-only in v1.42: no share reaches life events, not a `profile` share, a whole-record share or MANAGE, and not a guardian acting for a managed profile. @@ -23874,7 +23890,7 @@ paths: schema: $ref: "#/components/schemas/CreateLifeEventEnvelope" "401": *a1 - "403": *a68 + "403": *a67 "409": *a7 "422": *a4 "429": *a12 @@ -23905,8 +23921,8 @@ paths: schema: $ref: "#/components/schemas/UpdateLifeEventEnvelope" "401": *a1 - "403": *a68 - "404": &a69 + "403": *a67 + "404": &a68 description: No such life event on this account. content: application/json: @@ -23933,8 +23949,8 @@ paths: schema: $ref: "#/components/schemas/DeleteLifeEventEnvelope" "401": *a1 - "403": *a68 - "404": *a69 + "403": *a67 + "404": *a68 "422": *a4 "429": *a5 /api/search: @@ -24053,7 +24069,7 @@ paths: "409": *a7 "422": *a4 "429": *a5 - "501": *a44 + "501": *a69 /api/medications/{id}/ingredients/extract: post: tags: @@ -24094,7 +24110,7 @@ paths: $ref: "#/components/schemas/ErrorEnvelope" "422": *a4 "429": *a5 - "501": *a44 + "501": *a69 "503": description: "`aiRuns.workerUnavailable`: the run could not be handed to the background worker. Nothing was read and nothing was charged; try again." @@ -24119,7 +24135,7 @@ paths: "403": *a11 "422": *a4 "429": *a5 - "501": *a44 + "501": *a69 /api/anamnesis/life-circumstances/ai-sections: patch: tags: @@ -24149,7 +24165,7 @@ paths: $ref: "#/components/schemas/ErrorEnvelope" "422": *a4 "429": *a5 - "501": *a44 + "501": *a69 /api/anamnesis/life-circumstances/confirm: post: tags: @@ -24173,7 +24189,7 @@ paths: "401": *a1 "422": *a4 "429": *a5 - "501": *a44 + "501": *a69 /api/anamnesis/audit-c: post: tags: @@ -24206,7 +24222,7 @@ paths: "409": *a7 "422": *a4 "429": *a5 - "501": *a44 + "501": *a69 /api/anamnesis/audit-c/{id}: delete: tags: @@ -24235,7 +24251,7 @@ paths: $ref: "#/components/schemas/ErrorEnvelope" "422": *a4 "429": *a5 - "501": *a44 + "501": *a69 /api/dawarich/connect: post: tags: @@ -24261,7 +24277,7 @@ paths: "403": *a19 "422": *a4 "429": *a5 - "501": *a44 + "501": *a69 /api/dawarich/status: get: tags: @@ -24278,7 +24294,7 @@ paths: "403": *a19 "422": *a4 "429": *a5 - "501": *a44 + "501": *a69 /api/dawarich/places: get: tags: @@ -24309,7 +24325,7 @@ paths: $ref: "#/components/schemas/ErrorEnvelope" "422": *a4 "429": *a5 - "501": *a44 + "501": *a69 "502": description: "`dawarich.unreachable`." content: @@ -24339,7 +24355,7 @@ paths: "403": *a19 "422": *a4 "429": *a5 - "501": *a44 + "501": *a69 /api/dawarich/test: post: tags: @@ -24358,7 +24374,7 @@ paths: "403": *a19 "422": *a4 "429": *a5 - "501": *a44 + "501": *a69 /api/dawarich/sync: post: tags: @@ -24393,7 +24409,7 @@ paths: $ref: "#/components/schemas/ErrorEnvelope" "422": *a4 "429": *a5 - "501": *a44 + "501": *a69 /api/dawarich/disconnect: post: tags: @@ -24422,7 +24438,7 @@ paths: "403": *a19 "422": *a4 "429": *a5 - "501": *a44 + "501": *a69 /api/environment/travel/suggestions: get: tags: @@ -24439,7 +24455,7 @@ paths: "403": *a19 "422": *a4 "429": *a5 - "501": *a44 + "501": *a69 /api/environment/travel/suggestions/{id}/dismiss: post: tags: @@ -24469,7 +24485,7 @@ paths: $ref: "#/components/schemas/ErrorEnvelope" "422": *a4 "429": *a5 - "501": *a44 + "501": *a69 /api/medications/{id}/links: post: tags: @@ -24506,7 +24522,7 @@ paths: $ref: "#/components/schemas/ErrorEnvelope" "422": *a4 "429": *a5 - "501": *a44 + "501": *a69 delete: tags: - Links @@ -24542,7 +24558,7 @@ paths: $ref: "#/components/schemas/ErrorEnvelope" "422": *a4 "429": *a5 - "501": *a44 + "501": *a69 /api/labs/{id}/links: post: tags: @@ -24579,7 +24595,7 @@ paths: $ref: "#/components/schemas/ErrorEnvelope" "422": *a4 "429": *a5 - "501": *a44 + "501": *a69 delete: tags: - Links @@ -24615,7 +24631,7 @@ paths: $ref: "#/components/schemas/ErrorEnvelope" "422": *a4 "429": *a5 - "501": *a44 + "501": *a69 /api/bugreport: post: security: [] @@ -35632,17 +35648,17 @@ components: personal_records.invalid_query; practitioner — practitioner.invalid; profile — profile.update.emailInUse, profile.update.emailRateLimited, profile.update.emailSecondFactorRequired, profile.update.invalidBody, profile.update.nothingSaved; profile_claim — profile_claim.invalid, - profile_claim.oidc_only_unsupported, profile_claim.taken; record_write — record_write.rate_limited; - report-selection — report-selection.body.invalid_json, report-selection.body.invalid_shape, - report-selection.leaves.unknown; route — route.retired; search — search.invalid; share-link — - share-link.document.decryptFailed, share-link.document.notFound, share-link.document.rateLimited, - share-link.documents.invalid, share-link.report.notFound, share-link.report.rateLimited, - share-link.selection.forbidden_leaf, share-link.selection.unknown_leaf; sharing — - sharing.accept.expired, sharing.accept.not_found, sharing.accept.not_pending, sharing.accept.revoked, - sharing.access.denied, sharing.invite.duplicate, sharing.invite.invalid, sharing.invite.invalid_scope, - sharing.invite.manage_browser_only, sharing.invite.refused, sharing.invite.self, sharing.not_permitted, - sharing.renounce.already_ended, sharing.renounce.not_found, sharing.revoke.already_ended, - sharing.revoke.not_found, sharing.session.changed, sharing.switch.invalid, + profile_claim.oidc_only_unsupported, profile_claim.sso_unavailable, profile_claim.taken; record_write — + record_write.rate_limited; report-selection — report-selection.body.invalid_json, + report-selection.body.invalid_shape, report-selection.leaves.unknown; route — route.retired; search — + search.invalid; share-link — share-link.document.decryptFailed, share-link.document.notFound, + share-link.document.rateLimited, share-link.documents.invalid, share-link.report.notFound, + share-link.report.rateLimited, share-link.selection.forbidden_leaf, share-link.selection.unknown_leaf; + sharing — sharing.accept.expired, sharing.accept.not_found, sharing.accept.not_pending, + sharing.accept.revoked, sharing.access.denied, sharing.invite.duplicate, sharing.invite.invalid, + sharing.invite.invalid_scope, sharing.invite.manage_browser_only, sharing.invite.refused, + sharing.invite.self, sharing.not_permitted, sharing.renounce.already_ended, sharing.renounce.not_found, + sharing.revoke.already_ended, sharing.revoke.not_found, sharing.session.changed, sharing.switch.invalid, sharing.switch.wrong_transport; source-priority — source-priority.body.invalid_json, source-priority.body.invalid_shape; symptoms — symptoms.definition.limitReached, symptoms.definition.notFound, symptoms.episode.notOpen, symptoms.event.notFound, symptoms.invalid; diff --git a/docs/self-hosting/account-sharing.md b/docs/self-hosting/account-sharing.md index 05e2a9b14..62df60982 100644 --- a/docs/self-hosting/account-sharing.md +++ b/docs/self-hosting/account-sharing.md @@ -231,11 +231,58 @@ as something to log in as. person it was sent to, so the admin notification diagnostic can answer "who was this for" and "whose record was it about" separately. -There is no emancipation flow: no route, no control and no copy suggests -a managed profile can be turned into an ordinary account. The data model -leaves room for it (the credentials are nullable and the managed marker -can be cleared) and clearing that marker stops the notification fan-out, -but nothing in v1.37.0 exercises any of that. +### Handing a record over to its person + +Since v1.42 a guardian can hand a managed profile over to the person it +describes, so the record becomes their own account with its whole history. +Nothing is copied or moved; the profile's row gets credentials, loses the +managed marker, and stops fanning reminders out to its guardians. + +- A guardian with a fresh second factor creates a one-time link (valid for + one, seven or fourteen days, shown once) and proposes, for each guardian, + no access, view only or manage. Only a keyed hash of the link is stored, + at most one link per profile is open, and any guardian can withdraw it + without a second factor. +- The person opens the link, sees the record's name, the expiry and who + keeps which access, and chooses how they sign in. The claim runs as one + transaction: the link is consumed, the proposals are applied, open + invitations the record offered are withdrawn, and the disclaimer, + onboarding and AI consent are reset so the person gives them themselves. + After the first sign-in they confirm or change each guardian's access. +- How the person signs in depends on the instance: + + | Instance | Ways in | + | --------------------------------- | -------------------------- | + | No SSO configured | Password | + | SSO configured, `OIDC_ONLY` unset | Password or single sign-on | + | `OIDC_ONLY="true"` | Single sign-on only | + + The guardian's panel and the claim page both show which ways are open. + +- **Through single sign-on** (v1.43) the person picks a username and + continues to the identity provider. When they come back, the provider's + `(issuer, sub)` pair is bound to the record in the same transaction, the + address is taken from the provider only when it asserts + `email_verified: true` (otherwise the account has no address), and no + password is set. Refused, with the record left exactly as it was: + a provider identity that already signs in to an account on this instance + (one identity, one account; the refusal is audited on that account as + `auth.oidc.claim_conflict`), a verified address another account holds, + a username taken in the meantime, a link that was used, withdrawn, + replaced or expired while the person was at the provider, and a browser + that is signed in to another account. +- The link never appears in a URL the server builds: the claim page sends it + in request bodies only, and the single-sign-on leg carries a sealed, + ten-minute, HttpOnly cookie that names the link by its id. The `/claim/` + path and `hlp_` tokens are scrubbed from logs. +- The iOS app does not claim. The person claims in a browser and then signs + in to the app as usual (with SSO, through the app's own SSO sign-in). + +Audit rows: `managed_profile.handover.created` and `.revoked` on the record, +`managed_profile.claim_sso.started` when a single-sign-on claim starts, +`managed_profile.claimed` and `auth.claim` (with `method: "password"` or +`"sso"`) when it lands, and `managed_profile.handed_over` on each guardian's +own account. ## Seeing what happened diff --git a/docs/self-hosting/sso.md b/docs/self-hosting/sso.md index aedefa419..c537083e1 100644 --- a/docs/self-hosting/sso.md +++ b/docs/self-hosting/sso.md @@ -112,6 +112,12 @@ Client registration essentials only — the IdP's own docs cover the rest. MFA in the IdP's policy engine — that is the point of delegating authentication. HealthLog-side 2FA remains available on top for the step-up gates above. +- **Claiming a managed profile binds a fresh identity only.** When a + person claims a managed profile through SSO, their `(issuer, sub)` is + bound to that record, and only if no account on the instance already + holds it, and the provider's address is used only when it is verified + and not already taken. A claim can therefore never attach somebody's + existing sign-in to a second record or take over an existing account. - **Linking is once.** There is no unlink/relink flow in this cut; the pin is deliberately sticky. Moving an account to a new IdP identity is an operator decision (a manual `users.oidc_issuer` / `users.oidc_sub` @@ -134,6 +140,10 @@ Consequences to accept before turning it on: - **Self-disabling on half-config.** The flag only takes effect while the three provider vars are fully set, so a typo in the provider group can never lock every user out. +- **Managed profiles are still handed over** (v1.43). The person claims the + record through the identity provider instead of setting a password; the + password claim is refused. See + [Handing a record over to its person](account-sharing.md#handing-a-record-over-to-its-person). ### Break-glass (IdP down or misconfigured) diff --git a/messages/de.json b/messages/de.json index 22defd4fa..f7c26583e 100644 --- a/messages/de.json +++ b/messages/de.json @@ -528,7 +528,7 @@ "loading": "Dein Link wird geprüft…", "invalid": "Dieser Link funktioniert nicht mehr", "invalidHint": "Er ist unbekannt, abgelaufen, zurückgezogen oder schon benutzt. Bitte die Person, die ihn dir gegeben hat, um einen neuen.", - "oidcOnly": "Dieser Server erlaubt nur Single Sign-on, deshalb lässt sich ein Profil hier noch nicht übernehmen.", + "oidcOnly": "Dieser Server erlaubt nur Single Sign-on. Fahre stattdessen mit deinem Identitätsanbieter fort.", "signedInTitle": "Melde dich zuerst ab", "signedInBody": "Du bist als {username} angemeldet. Dieser Link richtet eine Anmeldung für jemand anderen ein, melde dich also ab, bevor du ihn benutzt.", "signOut": "Abmelden und weiter", @@ -545,7 +545,19 @@ "errorTaken": "Dieser Benutzername oder diese E-Mail-Adresse ist schon vergeben.", "errorRateLimit": "Zu viele Versuche. Warte ein paar Minuten und versuche es erneut.", "errorFailed": "Das hat nicht geklappt. Versuche es gleich noch einmal.", - "errorOffline": "Das hat den Server nicht erreicht. Prüfe deine Verbindung und versuche es erneut." + "errorOffline": "Das hat den Server nicht erreicht. Prüfe deine Verbindung und versuche es erneut.", + "ssoContinue": "Weiter mit {provider}", + "ssoStarting": "Weiterleitung…", + "ssoHint": "Ab dann meldest du dich hier mit deinem Konto bei {provider} an.", + "ssoDivider": "oder", + "ssoFallbackName": "Single Sign-on", + "errorTitle": "Die Übernahme hat nicht geklappt", + "errorSubjectBound": "Diese Anmeldung gehört schon zu einem anderen Konto auf diesem Server. Öffne den Link noch einmal und nimm ein anderes Konto bei deinem Identitätsanbieter.", + "errorEmailTaken": "Dein Identitätsanbieter hat eine E-Mail-Adresse geliefert, die hier schon ein anderes Konto nutzt. Öffne den Link noch einmal und nimm ein anderes Konto, oder frag die Person, die den Server betreibt.", + "errorUsernameTaken": "Jemand hat diesen Benutzernamen inzwischen vergeben. Öffne den Link noch einmal und wähle einen anderen.", + "errorSignedIn": "Bei der Rückkehr warst du angemeldet. Melde dich ab und öffne den Link noch einmal.", + "errorSso": "Die Anmeldung bei deinem Identitätsanbieter hat nicht funktioniert. Öffne den Link noch einmal, um es erneut zu versuchen.", + "signInInstead": "Bei diesem Konto anmelden" }, "inviteInvalid": { "title": "Einladung ungültig", @@ -11989,9 +12001,11 @@ "revokeFailed": "Der Link ließ sich nicht zurückziehen. Versuche es erneut.", "errorFailed": "Der Übergabelink ließ sich nicht erstellen.", "errorRosterChanged": "Inzwischen hat sich geändert, wer die Akte betreut. Schließe das hier und öffne es erneut.", - "oidcOnly": "Ein Profil zu übergeben ist nicht möglich, solange dieser Server nur Single Sign-on erlaubt.", + "oidcOnly": "Ein Profil zu übergeben ist auf diesem Server nicht möglich.", "loadError": "Der Stand der Übergabe ließ sich nicht laden.", - "entryHint": "Wenn {name} die Akte selbst führen möchte." + "entryHint": "Wenn {name} die Akte selbst führen möchte.", + "methodSso": "{name} meldet sich beim Einlösen des Links über Single Sign-on an.", + "methodBoth": "{name} kann ein Passwort festlegen oder sich über Single Sign-on anmelden." } }, "toast": { diff --git a/messages/en.json b/messages/en.json index 874ee9856..4d2ef1aa2 100644 --- a/messages/en.json +++ b/messages/en.json @@ -528,7 +528,7 @@ "loading": "Checking your link…", "invalid": "This link no longer works", "invalidHint": "It is unknown, expired, withdrawn or already used. Ask the person who sent it for a new one.", - "oidcOnly": "This server only allows single sign-on, so a profile cannot be taken over here yet.", + "oidcOnly": "This server only allows single sign-on. Continue with your identity provider instead.", "signedInTitle": "Sign out first", "signedInBody": "You are signed in as {username}. This link sets up a sign-in for someone else, so sign out before you use it.", "signOut": "Sign out and continue", @@ -545,7 +545,19 @@ "errorTaken": "That username or email address is already in use.", "errorRateLimit": "Too many attempts. Wait a few minutes and try again.", "errorFailed": "That did not work. Try again in a moment.", - "errorOffline": "That did not reach the server. Check your connection and try again." + "errorOffline": "That did not reach the server. Check your connection and try again.", + "ssoContinue": "Continue with {provider}", + "ssoStarting": "Redirecting…", + "ssoHint": "From then on you sign in here with your {provider} account.", + "ssoDivider": "or", + "ssoFallbackName": "single sign-on", + "errorTitle": "The handover did not go through", + "errorSubjectBound": "This sign-in already belongs to another account on this server. Open the link again and use a different account at your identity provider.", + "errorEmailTaken": "Your identity provider gave an email address that another account here already uses. Open the link again and use a different account, or ask the server's administrator.", + "errorUsernameTaken": "Someone took that username in the meantime. Open the link again and choose another one.", + "errorSignedIn": "You were signed in when you came back. Sign out, then open the link again.", + "errorSso": "Signing in with your identity provider did not work. Open the link again to try once more.", + "signInInstead": "Sign in to that account" }, "inviteInvalid": { "title": "Invitation invalid", @@ -11989,9 +12001,11 @@ "revokeFailed": "The link could not be withdrawn. Try again.", "errorFailed": "The handover link could not be created.", "errorRosterChanged": "The list of guardians changed in the meantime. Close this and open it again.", - "oidcOnly": "Handing over a profile is not available while this server allows single sign-on only.", + "oidcOnly": "Handing over a profile is not available on this server.", "loadError": "The handover status could not be loaded.", - "entryHint": "When {name} is ready to look after this record themselves." + "entryHint": "When {name} is ready to look after this record themselves.", + "methodSso": "{name} signs in through single sign-on when they use the link.", + "methodBoth": "{name} can set a password or sign in through single sign-on." } }, "toast": { diff --git a/messages/es.json b/messages/es.json index e27e98043..932799bd1 100644 --- a/messages/es.json +++ b/messages/es.json @@ -528,7 +528,7 @@ "loading": "Comprobando tu enlace…", "invalid": "Este enlace ya no funciona", "invalidHint": "Es desconocido, ha caducado, se ha retirado o ya se ha usado. Pide uno nuevo a quien te lo envió.", - "oidcOnly": "Este servidor solo permite el inicio de sesión único, así que aquí todavía no se puede asumir un perfil.", + "oidcOnly": "Este servidor solo permite el inicio de sesión único. Continúa con tu proveedor de identidad.", "signedInTitle": "Cierra la sesión primero", "signedInBody": "Has iniciado sesión como {username}. Este enlace crea un acceso para otra persona, así que cierra la sesión antes de usarlo.", "signOut": "Cerrar sesión y continuar", @@ -545,7 +545,19 @@ "errorTaken": "Ese nombre de usuario o correo electrónico ya está en uso.", "errorRateLimit": "Demasiados intentos. Espera unos minutos y vuelve a intentarlo.", "errorFailed": "No ha funcionado. Vuelve a intentarlo en un momento.", - "errorOffline": "No se llegó al servidor. Comprueba tu conexión y vuelve a intentarlo." + "errorOffline": "No se llegó al servidor. Comprueba tu conexión y vuelve a intentarlo.", + "ssoContinue": "Continuar con {provider}", + "ssoStarting": "Redirigiendo…", + "ssoHint": "A partir de entonces inicias sesión aquí con tu cuenta de {provider}.", + "ssoDivider": "o", + "ssoFallbackName": "inicio de sesión único", + "errorTitle": "La entrega no se ha completado", + "errorSubjectBound": "Este inicio de sesión ya pertenece a otra cuenta de este servidor. Vuelve a abrir el enlace y usa otra cuenta en tu proveedor de identidad.", + "errorEmailTaken": "Tu proveedor de identidad ha enviado una dirección de correo que ya usa otra cuenta aquí. Vuelve a abrir el enlace y usa otra cuenta, o pregunta a quien administra el servidor.", + "errorUsernameTaken": "Alguien ha cogido ese nombre de usuario mientras tanto. Vuelve a abrir el enlace y elige otro.", + "errorSignedIn": "Tenías una sesión iniciada al volver. Cierra la sesión y vuelve a abrir el enlace.", + "errorSso": "No se ha podido iniciar sesión con tu proveedor de identidad. Vuelve a abrir el enlace para intentarlo otra vez.", + "signInInstead": "Iniciar sesión en esa cuenta" }, "inviteInvalid": { "title": "Invitación no válida", @@ -11989,9 +12001,11 @@ "revokeFailed": "No se pudo retirar el enlace. Vuelve a intentarlo.", "errorFailed": "No se pudo crear el enlace de entrega.", "errorRosterChanged": "Mientras tanto ha cambiado quién se ocupa del historial. Cierra esto y vuelve a abrirlo.", - "oidcOnly": "No se puede entregar un perfil mientras este servidor solo permita el inicio de sesión único.", + "oidcOnly": "En este servidor no se puede entregar un perfil.", "loadError": "No se pudo cargar el estado de la entrega.", - "entryHint": "Cuando {name} quiera llevar este historial por su cuenta." + "entryHint": "Cuando {name} quiera llevar este historial por su cuenta.", + "methodSso": "{name} inicia sesión con el inicio de sesión único cuando usa el enlace.", + "methodBoth": "{name} puede elegir una contraseña o iniciar sesión con el inicio de sesión único." } }, "toast": { diff --git a/messages/fr.json b/messages/fr.json index 2743484ab..9638f8572 100644 --- a/messages/fr.json +++ b/messages/fr.json @@ -528,7 +528,7 @@ "loading": "Vérification de votre lien…", "invalid": "Ce lien ne fonctionne plus", "invalidHint": "Il est inconnu, expiré, retiré ou déjà utilisé. Demandez-en un nouveau à la personne qui vous l'a envoyé.", - "oidcOnly": "Ce serveur n'autorise que l'authentification unique, un profil ne peut donc pas encore être repris ici.", + "oidcOnly": "Ce serveur n'autorise que l'authentification unique. Continuez plutôt avec votre fournisseur d'identité.", "signedInTitle": "Déconnectez-vous d'abord", "signedInBody": "Vous êtes connecté en tant que {username}. Ce lien crée une connexion pour quelqu'un d'autre, déconnectez-vous donc avant de l'utiliser.", "signOut": "Se déconnecter et continuer", @@ -545,7 +545,19 @@ "errorTaken": "Ce nom d'utilisateur ou cette adresse e-mail est déjà utilisé.", "errorRateLimit": "Trop de tentatives. Attendez quelques minutes puis réessayez.", "errorFailed": "Cela n'a pas fonctionné. Réessayez dans un instant.", - "errorOffline": "Le serveur n'a pas été atteint. Vérifiez votre connexion et réessayez." + "errorOffline": "Le serveur n'a pas été atteint. Vérifiez votre connexion et réessayez.", + "ssoContinue": "Continuer avec {provider}", + "ssoStarting": "Redirection…", + "ssoHint": "Ensuite, vous vous connectez ici avec votre compte {provider}.", + "ssoDivider": "ou", + "ssoFallbackName": "l'authentification unique", + "errorTitle": "La transmission n'a pas abouti", + "errorSubjectBound": "Cette connexion appartient déjà à un autre compte sur ce serveur. Rouvrez le lien et utilisez un autre compte chez votre fournisseur d'identité.", + "errorEmailTaken": "Votre fournisseur d'identité a transmis une adresse e-mail déjà utilisée par un autre compte ici. Rouvrez le lien et utilisez un autre compte, ou contactez la personne qui administre le serveur.", + "errorUsernameTaken": "Quelqu'un a pris ce nom d'utilisateur entre-temps. Rouvrez le lien et choisissez-en un autre.", + "errorSignedIn": "Vous étiez connecté à votre retour. Déconnectez-vous, puis rouvrez le lien.", + "errorSso": "La connexion avec votre fournisseur d'identité n'a pas fonctionné. Rouvrez le lien pour réessayer.", + "signInInstead": "Se connecter à ce compte" }, "inviteInvalid": { "title": "Invitation invalide", @@ -11989,9 +12001,11 @@ "revokeFailed": "Le lien n'a pas pu être retiré. Réessayez.", "errorFailed": "Le lien de transmission n'a pas pu être créé.", "errorRosterChanged": "Entre-temps, les personnes qui s'occupent du dossier ont changé. Fermez ceci et rouvrez-le.", - "oidcOnly": "Transmettre un profil n'est pas possible tant que ce serveur n'autorise que l'authentification unique.", + "oidcOnly": "Transmettre un profil n'est pas possible sur ce serveur.", "loadError": "L'état de la transmission n'a pas pu être chargé.", - "entryHint": "Quand {name} souhaite tenir ce dossier de façon autonome." + "entryHint": "Quand {name} souhaite tenir ce dossier de façon autonome.", + "methodSso": "{name} se connecte par authentification unique en utilisant le lien.", + "methodBoth": "{name} peut définir un mot de passe ou se connecter par authentification unique." } }, "toast": { diff --git a/messages/it.json b/messages/it.json index 80f4e0504..2d68f0d6a 100644 --- a/messages/it.json +++ b/messages/it.json @@ -528,7 +528,7 @@ "loading": "Controllo del link…", "invalid": "Questo link non funziona più", "invalidHint": "È sconosciuto, scaduto, ritirato o già usato. Chiedine uno nuovo a chi te l'ha inviato.", - "oidcOnly": "Questo server consente solo il single sign-on, quindi qui non è ancora possibile prendere in carico un profilo.", + "oidcOnly": "Questo server consente solo il single sign-on. Continua invece con il tuo provider di identità.", "signedInTitle": "Prima esci", "signedInBody": "Hai effettuato l'accesso come {username}. Questo link crea un accesso per un'altra persona, quindi esci prima di usarlo.", "signOut": "Esci e continua", @@ -545,7 +545,19 @@ "errorTaken": "Questo nome utente o indirizzo email è già in uso.", "errorRateLimit": "Troppi tentativi. Attendi qualche minuto e riprova.", "errorFailed": "Non ha funzionato. Riprova tra un momento.", - "errorOffline": "Il server non è stato raggiunto. Controlla la connessione e riprova." + "errorOffline": "Il server non è stato raggiunto. Controlla la connessione e riprova.", + "ssoContinue": "Continua con {provider}", + "ssoStarting": "Reindirizzamento…", + "ssoHint": "Da quel momento accedi qui con il tuo account {provider}.", + "ssoDivider": "oppure", + "ssoFallbackName": "single sign-on (SSO)", + "errorTitle": "La consegna non è andata a buon fine", + "errorSubjectBound": "Questo accesso appartiene già a un altro account su questo server. Riapri il link e usa un altro account presso il tuo provider di identità.", + "errorEmailTaken": "Il tuo provider di identità ha fornito un indirizzo email che qui usa già un altro account. Riapri il link e usa un altro account, oppure chiedi a chi amministra il server.", + "errorUsernameTaken": "Nel frattempo qualcuno ha preso quel nome utente. Riapri il link e scegline un altro.", + "errorSignedIn": "Al ritorno avevi già effettuato l'accesso. Esci, poi riapri il link.", + "errorSso": "L'accesso con il tuo provider di identità non è riuscito. Riapri il link per riprovare.", + "signInInstead": "Accedi a quell'account" }, "inviteInvalid": { "title": "Invito non valido", @@ -11989,9 +12001,11 @@ "revokeFailed": "Impossibile ritirare il link. Riprova.", "errorFailed": "Impossibile creare il link di consegna.", "errorRosterChanged": "Nel frattempo è cambiato chi si occupa della cartella. Chiudi e riapri.", - "oidcOnly": "Non è possibile consegnare un profilo finché questo server consente solo il single sign-on.", + "oidcOnly": "Su questo server non è possibile consegnare un profilo.", "loadError": "Impossibile caricare lo stato della consegna.", - "entryHint": "Quando {name} vuole tenere questa cartella in autonomia." + "entryHint": "Quando {name} vuole tenere questa cartella in autonomia.", + "methodSso": "{name} accede con il single sign-on quando usa il link.", + "methodBoth": "{name} può impostare una password oppure accedere con il single sign-on." } }, "toast": { diff --git a/messages/ko.json b/messages/ko.json index 29f8be638..c60235d85 100644 --- a/messages/ko.json +++ b/messages/ko.json @@ -528,7 +528,7 @@ "loading": "링크를 확인하는 중…", "invalid": "이 링크는 더 이상 작동하지 않습니다", "invalidHint": "알 수 없거나, 만료되었거나, 철회되었거나, 이미 사용된 링크입니다. 보낸 사람에게 새 링크를 요청하세요.", - "oidcOnly": "이 서버는 통합 로그인(SSO)만 허용하므로 아직 여기서 프로필을 넘겨받을 수 없습니다.", + "oidcOnly": "이 서버는 통합 로그인(SSO)만 허용합니다. 대신 ID 공급자로 계속하세요.", "signedInTitle": "먼저 로그아웃하세요", "signedInBody": "{username} 계정으로 로그인되어 있습니다. 이 링크는 다른 사람의 로그인을 만드는 링크이므로 사용하기 전에 로그아웃하세요.", "signOut": "로그아웃하고 계속", @@ -545,7 +545,19 @@ "errorTaken": "이미 사용 중인 사용자 이름 또는 이메일 주소입니다.", "errorRateLimit": "시도 횟수가 너무 많습니다. 몇 분 후 다시 시도하세요.", "errorFailed": "처리하지 못했습니다. 잠시 후 다시 시도하세요.", - "errorOffline": "서버에 연결하지 못했습니다. 연결을 확인하고 다시 시도하세요." + "errorOffline": "서버에 연결하지 못했습니다. 연결을 확인하고 다시 시도하세요.", + "ssoContinue": "{provider}(으)로 계속", + "ssoStarting": "이동하는 중…", + "ssoHint": "이후에는 {provider} 계정으로 여기에 로그인합니다.", + "ssoDivider": "또는", + "ssoFallbackName": "통합 로그인(SSO)", + "errorTitle": "넘겨받기를 완료하지 못했습니다", + "errorSubjectBound": "이 로그인은 이미 이 서버의 다른 계정에 연결되어 있습니다. 링크를 다시 열고 ID 공급자에서 다른 계정을 사용하세요.", + "errorEmailTaken": "ID 공급자가 보낸 이메일 주소를 이 서버의 다른 계정이 이미 사용하고 있습니다. 링크를 다시 열고 다른 계정을 사용하거나 서버 관리자에게 문의하세요.", + "errorUsernameTaken": "그 사이에 다른 사람이 이 사용자 이름을 사용했습니다. 링크를 다시 열고 다른 이름을 선택하세요.", + "errorSignedIn": "돌아왔을 때 이미 로그인되어 있었습니다. 로그아웃한 다음 링크를 다시 여세요.", + "errorSso": "ID 공급자로 로그인하지 못했습니다. 링크를 다시 열어 한 번 더 시도하세요.", + "signInInstead": "그 계정으로 로그인" }, "inviteInvalid": { "title": "유효하지 않은 초대예요", @@ -11989,9 +12001,11 @@ "revokeFailed": "링크를 철회하지 못했습니다. 다시 시도하세요.", "errorFailed": "넘겨주기 링크를 만들지 못했습니다.", "errorRosterChanged": "그 사이 기록을 돌보는 사람이 바뀌었습니다. 닫았다가 다시 여세요.", - "oidcOnly": "이 서버가 통합 로그인(SSO)만 허용하는 동안에는 프로필을 넘겨줄 수 없습니다.", + "oidcOnly": "이 서버에서는 프로필을 넘겨줄 수 없습니다.", "loadError": "넘겨주기 상태를 불러오지 못했습니다.", - "entryHint": "{name} 님이 이 기록을 직접 관리할 준비가 되었을 때." + "entryHint": "{name} 님이 이 기록을 직접 관리할 준비가 되었을 때.", + "methodSso": "{name}님은 링크를 사용할 때 통합 로그인(SSO)으로 로그인합니다.", + "methodBoth": "{name}님은 비밀번호를 정하거나 통합 로그인(SSO)으로 로그인할 수 있습니다." } }, "toast": { diff --git a/messages/pl.json b/messages/pl.json index 8b9d69342..0df1eadae 100644 --- a/messages/pl.json +++ b/messages/pl.json @@ -528,7 +528,7 @@ "loading": "Sprawdzanie linku…", "invalid": "Ten link już nie działa", "invalidHint": "Jest nieznany, wygasł, został wycofany albo już użyty. Poproś osobę, która go wysłała, o nowy.", - "oidcOnly": "Ten serwer pozwala tylko na logowanie jednokrotne (SSO), więc profilu nie można tu jeszcze przejąć.", + "oidcOnly": "Ten serwer pozwala tylko na logowanie jednokrotne (SSO). Kontynuuj u swojego dostawcy tożsamości.", "signedInTitle": "Najpierw się wyloguj", "signedInBody": "Masz zalogowaną sesję jako {username}. Ten link tworzy logowanie dla kogoś innego, więc wyloguj się, zanim go użyjesz.", "signOut": "Wyloguj i kontynuuj", @@ -545,7 +545,19 @@ "errorTaken": "Ta nazwa użytkownika lub adres e-mail jest już zajęty.", "errorRateLimit": "Zbyt wiele prób. Odczekaj kilka minut i spróbuj ponownie.", "errorFailed": "Nie udało się. Spróbuj ponownie za chwilę.", - "errorOffline": "Nie udało się połączyć z serwerem. Sprawdź połączenie i spróbuj ponownie." + "errorOffline": "Nie udało się połączyć z serwerem. Sprawdź połączenie i spróbuj ponownie.", + "ssoContinue": "Kontynuuj przez {provider}", + "ssoStarting": "Przekierowywanie…", + "ssoHint": "Od tej pory logujesz się tutaj swoim kontem {provider}.", + "ssoDivider": "lub", + "ssoFallbackName": "logowanie jednokrotne (SSO)", + "errorTitle": "Przejęcie się nie udało", + "errorSubjectBound": "To logowanie należy już do innego konta na tym serwerze. Otwórz link ponownie i użyj innego konta u swojego dostawcy tożsamości.", + "errorEmailTaken": "Twój dostawca tożsamości przekazał adres e-mail, którego używa już inne konto na tym serwerze. Otwórz link ponownie i użyj innego konta albo zapytaj osobę, która administruje serwerem.", + "errorUsernameTaken": "W międzyczasie ktoś zajął tę nazwę użytkownika. Otwórz link ponownie i wybierz inną.", + "errorSignedIn": "Po powrocie byłeś zalogowany. Wyloguj się i otwórz link ponownie.", + "errorSso": "Logowanie u dostawcy tożsamości się nie powiodło. Otwórz link ponownie, aby spróbować jeszcze raz.", + "signInInstead": "Zaloguj się na to konto" }, "inviteInvalid": { "title": "Nieprawidłowe zaproszenie", @@ -11989,9 +12001,11 @@ "revokeFailed": "Nie udało się wycofać linku. Spróbuj ponownie.", "errorFailed": "Nie udało się utworzyć linku przekazania.", "errorRosterChanged": "W międzyczasie zmieniło się, kto opiekuje się kartą. Zamknij to i otwórz ponownie.", - "oidcOnly": "Przekazanie profilu nie jest możliwe, dopóki ten serwer pozwala tylko na logowanie jednokrotne (SSO).", + "oidcOnly": "Przekazanie profilu nie jest możliwe na tym serwerze.", "loadError": "Nie udało się wczytać stanu przekazania.", - "entryHint": "Gdy {name} chce samodzielnie prowadzić tę kartę." + "entryHint": "Gdy {name} chce samodzielnie prowadzić tę kartę.", + "methodSso": "{name} loguje się przez logowanie jednokrotne (SSO), gdy użyje linku.", + "methodBoth": "{name} może ustawić hasło albo zalogować się przez logowanie jednokrotne (SSO)." } }, "toast": { diff --git a/src/__tests__/contract-stub-inventory.test.ts b/src/__tests__/contract-stub-inventory.test.ts index 5d73a18ab..56aea5d1d 100644 --- a/src/__tests__/contract-stub-inventory.test.ts +++ b/src/__tests__/contract-stub-inventory.test.ts @@ -37,7 +37,6 @@ const CONTRACT_STUBS: Readonly> = { "anamnesis.life_circumstances.confirm", ], "anamnesis/life-circumstances/route.ts": ["anamnesis.life_circumstances.get"], - "auth/claim/sso/route.ts": ["profile_claim.sso.start"], "dawarich/connect/route.ts": ["dawarich.connect"], "dawarich/disconnect/route.ts": ["dawarich.disconnect"], "dawarich/places/route.ts": ["dawarich.places.get"], @@ -61,7 +60,7 @@ const CONTRACT_STUBS: Readonly> = { }; /** The size of the register when it was written; see the header. */ -const REGISTER_SIZE = 21; +const REGISTER_SIZE = 20; function routeFiles(): string[] { return walkSourceFiles(API_ROOT, { floor: 400, extensions: [".ts"] }) diff --git a/src/__tests__/session-surface-guard.test.ts b/src/__tests__/session-surface-guard.test.ts index d27126a2b..6fdcd8534 100644 --- a/src/__tests__/session-surface-guard.test.ts +++ b/src/__tests__/session-surface-guard.test.ts @@ -100,9 +100,11 @@ describe("S1 — the direct session-resolution set is frozen", () => { "app/api/auth/claim/sso/route.ts": "refuses to start a single-sign-on claim over a live session", // Anonymous IdP callback. Probes for an already-valid session so a - // replayed callback redirects instead of minting a second identity. + // replayed callback redirects instead of minting a second identity, and + // (v1.43, #959) so a single-sign-on claim is refused over a live session, + // as the claim routes refuse it. "app/api/auth/oidc/callback/route.ts": - "duplicate-callback probe on an otherwise anonymous route", + "duplicate-callback probe and the claim's live-session refusal on an otherwise anonymous route", // Public liveness probe. The session read only decides whether the body // carries operational detail; the status code is computed without it. "app/api/health/route.ts": "admin-only detail on a public probe", @@ -370,6 +372,48 @@ describe("S2 — the URL-token authentication set is frozen", () => { }); }); +describe("S4 — the single-sign-on claim cookie set is frozen", () => { + /** + * v1.43 (#959). A third way to act without a session: the sealed `hl_claim` + * cookie carries a managed-profile claim from `POST /api/auth/claim/sso` + * through the OIDC round trip, and the callback turns it — together with + * the provider's subject — into somebody's account. It is neither a session + * nor a URL credential, so neither leg above sees it. + * + * The handover token itself still only travels in the claim routes' bodies + * and the claim page's query string (S2); the cookie names the link by id. + * What this freezes is who may mint the cookie and who may act on it. + */ + const CLAIM_COOKIE_ALLOWLIST: Record = { + "app/api/auth/claim/sso/route.ts": + "mints the cookie, only after checking the token and the username", + "app/api/auth/oidc/login/route.ts": + "requires the cookie for intent=claim and binds it into the OIDC state", + "app/api/auth/oidc/callback/route.ts": + "binds the provider's subject to the profile the cookie names", + }; + + const CLAIM_COOKIE_USE = + /\b(readClaimCookie|setClaimCookie|claimMatchesBinding|clearClaimCookie)\s*\(|\bCLAIM_COOKIE\b|["']hl_claim["']/; + + it("no file under src/app touches the claim cookie unlisted", () => { + const users = appFilesMatching(CLAIM_COOKIE_USE); + expect(users.length).toBeGreaterThan(0); + expect(users).toEqual(Object.keys(CLAIM_COOKIE_ALLOWLIST).sort()); + }); + + it("only the single-sign-on start mints it", () => { + const minters = appFilesMatching(/\bsetClaimCookie\s*\(/); + expect(minters).toEqual(["app/api/auth/claim/sso/route.ts"]); + }); + + it("every allowlist entry carries a reason", () => { + for (const [rel, reason] of Object.entries(CLAIM_COOKIE_ALLOWLIST)) { + expect(reason.trim().length, `${rel} has no reason`).toBeGreaterThan(0); + } + }); +}); + describe("S3 — the two families stay distinct", () => { /** * A file that both resolves a session AND authenticates by a URL token is diff --git a/src/app/api/auth/claim/__tests__/route.test.ts b/src/app/api/auth/claim/__tests__/route.test.ts index b5b9722b1..49d2fc9c4 100644 --- a/src/app/api/auth/claim/__tests__/route.test.ts +++ b/src/app/api/auth/claim/__tests__/route.test.ts @@ -5,7 +5,11 @@ * (`tests/integration/managed-profile-handover.test.ts`); here the order of * the refusals is pinned, because each one is a security property: * - * - single sign-on only refuses before anything else; + * - single sign-on only refuses the PASSWORD claim before anything else, + * while the preview answers there and names `sso` as the way in (v1.43); + * - the single-sign-on start needs a configured provider, refuses a live + * session before the rate limit, checks the link before the username, + * and seals the link's id (never the token) into `hl_claim`; * - a live session is refused BEFORE the rate limit (a state, not an * attempt), and before any token is read; * - the rate limit runs before the body is parsed; @@ -24,7 +28,18 @@ vi.mock("@/lib/auth/session", () => ({ createSession: vi.fn(), getSession: vi.fn(), })); -vi.mock("@/lib/auth/oidc", () => ({ isOidcOnly: vi.fn() })); +vi.mock("@/lib/auth/oidc", () => ({ + isOidcOnly: vi.fn(), + isOidcConfigured: vi.fn(), + getOidcConfig: vi.fn(), +})); +vi.mock("@/lib/crypto", () => ({ + encrypt: vi.fn((s: string) => `sealed(${s})`), + decrypt: vi.fn(), +})); +vi.mock("@/lib/auth/secure-cookie", () => ({ + shouldEmitSecureCookie: () => true, +})); vi.mock("@/lib/rate-limit", () => ({ checkRateLimit: vi.fn(), checkAuthSurfaceRateLimit: vi.fn(), @@ -49,6 +64,7 @@ vi.mock("@/lib/managed-profiles/handover", async () => { return { HandoverError: actual.HandoverError, previewHandover: vi.fn(), + usableHandoverForToken: vi.fn(), claimManagedProfile: vi.fn(), }; }); @@ -67,9 +83,11 @@ vi.mock("next/headers", () => ({ import { POST as claim } from "../route"; import { POST as preview } from "../preview/route"; +import { POST as claimSso } from "../sso/route"; import { prisma } from "@/lib/db"; import { createSession, getSession } from "@/lib/auth/session"; -import { isOidcOnly } from "@/lib/auth/oidc"; +import { getOidcConfig, isOidcConfigured, isOidcOnly } from "@/lib/auth/oidc"; +import { auditLog } from "@/lib/auth/audit"; import { checkAuthSurfaceRateLimit } from "@/lib/rate-limit"; import { checkPasswordStrength, hashPassword } from "@/lib/auth/password"; import { checkPasswordBreachIfEnabled } from "@/lib/password-breach-check"; @@ -77,6 +95,7 @@ import { claimManagedProfile, HandoverError, previewHandover, + usableHandoverForToken, } from "@/lib/managed-profiles/handover"; import { notifyGuardiansOfHandover } from "@/lib/managed-profiles/handover-notify"; @@ -105,6 +124,12 @@ const PREVIEW = { beforeEach(() => { vi.resetAllMocks(); vi.mocked(isOidcOnly).mockReturnValue(false); + vi.mocked(isOidcConfigured).mockReturnValue(false); + vi.mocked(getOidcConfig).mockReturnValue(null); + vi.mocked(usableHandoverForToken).mockResolvedValue({ + handoverId: "h1", + profileId: "p1", + }); vi.mocked(getSession).mockResolvedValue(null as never); vi.mocked(checkAuthSurfaceRateLimit).mockResolvedValue({ allowed: true, @@ -131,19 +156,62 @@ async function errorCode(res: Response): Promise { return body.meta?.errorCode; } +const OIDC_CONFIG = { + issuerUrl: "https://idp.example.test", + clientId: "c", + clientSecret: "s", + scopes: "openid email", + buttonLabel: "Example ID", +}; + +function singleSignOnOnly(): void { + vi.mocked(isOidcOnly).mockReturnValue(true); + vi.mocked(isOidcConfigured).mockReturnValue(true); + vi.mocked(getOidcConfig).mockReturnValue(OIDC_CONFIG); +} + +describe("on a single-sign-on-only instance", () => { + it("refuses the password claim before anything else", async () => { + singleSignOnOnly(); + vi.mocked(getSession).mockResolvedValue({ user: { id: "u1" } } as never); + const res = await claim(post("/api/auth/claim", BODY)); + expect(res.status).toBe(403); + expect(await errorCode(res)).toBe("profile_claim.oidc_only_unsupported"); + expect(previewHandover).not.toHaveBeenCalled(); + }); + + it("answers the preview and names single sign-on as the only way in", async () => { + singleSignOnOnly(); + const res = await preview( + post("/api/auth/claim/preview", { token: TOKEN }), + ); + expect(res.status).toBe(200); + const body = (await res.json()) as { data: Record }; + expect(body.data.methods).toEqual(["sso"]); + expect(body.data.ssoProviderName).toBe("Example ID"); + }); +}); + describe.each([ ["claim", claim, "/api/auth/claim", BODY], ["preview", preview, "/api/auth/claim/preview", { token: TOKEN }], + ["sso", claimSso, "/api/auth/claim/sso", { token: TOKEN, username: "alex" }], ] as const)( "POST %s — refusals that read no token", - (_n, route, path, body) => { - it("refuses on a single-sign-on-only instance before anything else", async () => { - vi.mocked(isOidcOnly).mockReturnValue(true); - vi.mocked(getSession).mockResolvedValue({ user: { id: "u1" } } as never); - const res = await route(post(path, body)); - expect(res.status).toBe(403); - expect(await errorCode(res)).toBe("profile_claim.oidc_only_unsupported"); - expect(previewHandover).not.toHaveBeenCalled(); + (name, route, path, body) => { + beforeEach(() => { + if (name === "sso") { + vi.mocked(isOidcConfigured).mockReturnValue(true); + vi.mocked(getOidcConfig).mockReturnValue(OIDC_CONFIG); + } + if (name === "sso") { + vi.mocked(usableHandoverForToken).mockImplementation(async () => { + // Routes the sso start through the same "link" spy the other two + // use, so one set of assertions covers all three. + const found = await previewHandover(TOKEN); + return found ? { handoverId: "h1", profileId: "p1" } : null; + }); + } }); it("refuses over a live session before spending the rate limit", async () => { @@ -234,7 +302,7 @@ describe("POST /api/auth/claim", () => { expect(res.status).toBe(201); expect(claimManagedProfile).toHaveBeenCalledWith( expect.objectContaining({ - rawToken: TOKEN, + link: { rawToken: TOKEN }, username: "alex", email: "alex@example.test", passwordHash: "argon2-hash", @@ -260,7 +328,101 @@ describe("POST /api/auth/claim/preview", () => { "displayName", "expiresAt", "guardians", + "methods", + "ssoProviderName", ]); + expect(body.data.methods).toEqual(["password"]); + expect(body.data.ssoProviderName).toBeNull(); expect(body.data.expiresAt).toBe("2030-01-01T00:00:00.000Z"); }); }); + +describe("POST /api/auth/claim/sso", () => { + const SSO_BODY = { token: TOKEN, username: "alex" }; + + beforeEach(() => { + vi.mocked(isOidcConfigured).mockReturnValue(true); + vi.mocked(getOidcConfig).mockReturnValue(OIDC_CONFIG); + }); + + it("answers 404 sso_unavailable without an identity provider, before anything else", async () => { + vi.mocked(isOidcConfigured).mockReturnValue(false); + vi.mocked(getSession).mockResolvedValue({ user: { id: "u1" } } as never); + const res = await claimSso(post("/api/auth/claim/sso", SSO_BODY)); + expect(res.status).toBe(404); + expect(await errorCode(res)).toBe("profile_claim.sso_unavailable"); + expect(checkAuthSurfaceRateLimit).not.toHaveBeenCalled(); + expect(usableHandoverForToken).not.toHaveBeenCalled(); + }); + + it("works on a single-sign-on-only instance", async () => { + singleSignOnOnly(); + const res = await claimSso(post("/api/auth/claim/sso", SSO_BODY)); + expect(res.status).toBe(200); + }); + + it("draws on the password claim's bucket", async () => { + await claimSso(post("/api/auth/claim/sso", SSO_BODY)); + expect(checkAuthSurfaceRateLimit).toHaveBeenCalledWith( + expect.anything(), + "auth:claim", + 5, + 15 * 60 * 1000, + ); + }); + + it("checks the link before the username probe", async () => { + vi.mocked(usableHandoverForToken).mockResolvedValue(null); + vi.mocked(prisma.user.findUnique).mockResolvedValue({ id: "x" } as never); + const res = await claimSso(post("/api/auth/claim/sso", SSO_BODY)); + expect(res.status).toBe(404); + expect(await errorCode(res)).toBe("profile_claim.invalid"); + expect(prisma.user.findUnique).not.toHaveBeenCalled(); + expect(res.headers.get("set-cookie")).toBeNull(); + }); + + it("answers 409 taken for a username in use, and sets no cookie", async () => { + vi.mocked(prisma.user.findUnique).mockResolvedValue({ id: "x" } as never); + const res = await claimSso(post("/api/auth/claim/sso", SSO_BODY)); + expect(res.status).toBe(409); + expect(await errorCode(res)).toBe("profile_claim.taken"); + expect(res.headers.get("set-cookie")).toBeNull(); + }); + + it("refuses an unknown field and a managed- username (strict body)", async () => { + for (const body of [ + { ...SSO_BODY, email: "x@example.test" }, + { ...SSO_BODY, username: "managed-alex" }, + ]) { + const res = await claimSso(post("/api/auth/claim/sso", body)); + expect(res.status).toBe(422); + } + expect(usableHandoverForToken).not.toHaveBeenCalled(); + }); + + it("seals the link's id and the username, never the token, into hl_claim", async () => { + const res = await claimSso(post("/api/auth/claim/sso", SSO_BODY)); + expect(res.status).toBe(200); + expect((await res.json()).data).toEqual({ + redirectTo: "/api/auth/oidc/login?intent=claim", + }); + const cookie = res.headers.get("set-cookie") ?? ""; + expect(cookie).toMatch(/^hl_claim=/); + expect(cookie).toMatch(/Path=\/api\/auth\/oidc/); + expect(cookie).toMatch(/HttpOnly/i); + expect(cookie).toMatch(/Secure/i); + expect(cookie).toMatch(/SameSite=lax/i); + expect(cookie).toMatch(/Max-Age=600/); + const sealed = decodeURIComponent(cookie.split(";")[0]!.slice(9)); + const payload = JSON.parse(sealed.replace(/^sealed\(/, "").slice(0, -1)); + expect(payload.h).toBe("h1"); + expect(payload.u).toBe("alex"); + expect(typeof payload.b).toBe("string"); + expect(cookie).not.toContain(TOKEN); + expect(JSON.stringify(vi.mocked(auditLog).mock.calls)).not.toContain(TOKEN); + expect(auditLog).toHaveBeenCalledWith( + "managed_profile.claim_sso.started", + expect.objectContaining({ userId: "p1", details: { handoverId: "h1" } }), + ); + }); +}); diff --git a/src/app/api/auth/claim/preview/route.ts b/src/app/api/auth/claim/preview/route.ts index 865f7fdfb..b5cb0b924 100644 --- a/src/app/api/auth/claim/preview/route.ts +++ b/src/app/api/auth/claim/preview/route.ts @@ -4,6 +4,8 @@ * access (v1.42, #959). No health data. * * Anonymous by design: the person opening the link has no credentials yet. + * Answered on a single-sign-on-only server too (v1.43): `methods` then names + * only `sso`, and the page offers the identity provider. * The one-time `hlp_` token travels in the BODY, never in this request's URL, * so it never reaches an access log or a wide event's `http.path`. Every * unusable link — malformed, unknown, expired, used, withdrawn, a profile no @@ -15,7 +17,12 @@ import { apiHandler } from "@/lib/api-handler"; import { apiSuccess, returnAllZodIssues, safeJson } from "@/lib/api-response"; import { getSession } from "@/lib/auth/session"; import { annotate } from "@/lib/logging/context"; -import { claimGate, claimInvalid } from "@/lib/managed-profiles/claim-gate"; +import { + claimGate, + claimInvalid, + handoverMethods, + ssoProviderName, +} from "@/lib/managed-profiles/claim-gate"; import { previewHandover } from "@/lib/managed-profiles/handover"; import { claimPreviewSchema } from "@/lib/validations/managed-profile-handover"; @@ -46,5 +53,9 @@ export const POST = apiHandler(async (request: NextRequest) => { displayName: preview.displayName, expiresAt: preview.expiresAt.toISOString(), guardians: preview.guardians, + // v1.43 (#959) — which ways in this server offers, so the page shows the + // password form, the provider button, or both. + methods: handoverMethods(), + ssoProviderName: ssoProviderName(), }); }); diff --git a/src/app/api/auth/claim/route.ts b/src/app/api/auth/claim/route.ts index 82bba356d..9ca4e09c2 100644 --- a/src/app/api/auth/claim/route.ts +++ b/src/app/api/auth/claim/route.ts @@ -104,7 +104,7 @@ export const POST = apiHandler(async (request: NextRequest) => { let claimed; try { claimed = await claimManagedProfile({ - rawToken: token, + link: { rawToken: token }, username, email, passwordHash, diff --git a/src/app/api/auth/claim/sso/route.ts b/src/app/api/auth/claim/sso/route.ts index 01b591758..21fd4938b 100644 --- a/src/app/api/auth/claim/sso/route.ts +++ b/src/app/api/auth/claim/sso/route.ts @@ -1,29 +1,47 @@ /** * `POST /api/auth/claim/sso` — start claiming a managed profile through - * single sign-on (#959). + * single sign-on (v1.43, #959). * - * Anonymous, like the password claim beside it. `{ token, username }`: the - * link is checked and the username reserved for the round trip, a sealed - * `hl_claim` cookie (10 minutes, `httpOnly`, `Secure` through - * `shouldEmitSecureCookie()`) carries `{ handoverId, username, exp }`, and the - * answer names where to go: `{ redirectTo: "/api/auth/oidc/login?intent=claim" }`. - * The OIDC callback binds the identity provider's subject to the profile. The - * token never rides a URL. Works on a single-sign-on-only server; 404 - * `profile_claim.sso_unavailable` when no identity provider is configured. + * Anonymous, like the password claim beside it, and ordered like it: + * + * 1. refusals that read no token (`claimGate`: no identity provider, a live + * session, the per-address bucket the password claim also draws on); + * 2. the body, strictly parsed, and the link checked; + * 3. the username probe, so the person learns a name is taken here rather + * than after the round trip to the provider. + * + * Nothing about the account changes here. The answer is a sealed `hl_claim` + * cookie (`claim-cookie.ts`) naming the link by its id and carrying the + * chosen username, and `{ redirectTo }` for the browser to navigate to. The + * OIDC callback binds the provider's subject to the profile, under the lock, + * with every check repeated. The token never rides a URL and never reaches the + * cookie. */ import { NextRequest } from "next/server"; import { apiHandler } from "@/lib/api-handler"; -import { returnAllZodIssues, safeJson } from "@/lib/api-response"; +import { + apiError, + apiSuccess, + returnAllZodIssues, + safeJson, +} from "@/lib/api-response"; +import { auditLog } from "@/lib/auth/audit"; import { getSession } from "@/lib/auth/session"; -import { notImplemented } from "@/lib/http/not-implemented"; -import { claimGate } from "@/lib/managed-profiles/claim-gate"; +import { prisma } from "@/lib/db"; +import { annotate } from "@/lib/logging/context"; +import { + CLAIM_SSO_REDIRECT, + setClaimCookie, +} from "@/lib/managed-profiles/claim-cookie"; +import { claimGate, claimInvalid } from "@/lib/managed-profiles/claim-gate"; +import { usableHandoverForToken } from "@/lib/managed-profiles/handover"; import { claimSsoSchema } from "@/lib/validations/claim-sso"; export const POST = apiHandler(async (request: NextRequest) => { // Refuses a signed-in caller and rate-limits the address, as the password // claim does. - const gate = await claimGate(request, "claim", (await getSession()) !== null); + const gate = await claimGate(request, "sso", (await getSession()) !== null); if (gate.refusal) return gate.refusal; const { data: body, error: jsonError } = await safeJson(request, { @@ -32,6 +50,43 @@ export const POST = apiHandler(async (request: NextRequest) => { if (jsonError) return jsonError; const parsed = claimSsoSchema.safeParse(body); if (!parsed.success) return returnAllZodIssues(parsed.error, 422); + const { token, username } = parsed.data; - return notImplemented("profile_claim.sso.start"); + // The link first, so the username probe below is no oracle for anybody + // without a live link (the password claim's argument). + const link = await usableHandoverForToken(token); + if (!link) { + annotate({ + action: { name: "profile_claim.sso.start" }, + meta: { found: false }, + }); + return claimInvalid(); + } + + const existing = await prisma.user.findUnique({ + where: { username }, + select: { id: true }, + }); + if (existing) { + return apiError("Username already taken", 409, { + errorCode: "profile_claim.taken", + }); + } + + const response = apiSuccess({ redirectTo: CLAIM_SSO_REDIRECT }); + setClaimCookie(response, { handoverId: link.handoverId, username }); + + // Filed under the record, with no actor: nobody is signed in yet. No token, + // no username — the username is not the person's until the claim lands. + await auditLog("managed_profile.claim_sso.started", { + userId: link.profileId, + actorUserId: null, + ipAddress: gate.ip, + details: { handoverId: link.handoverId }, + }); + annotate({ + action: { name: "profile_claim.sso.start" }, + meta: { found: true }, + }); + return response; }); diff --git a/src/app/api/auth/oidc/callback/route.ts b/src/app/api/auth/oidc/callback/route.ts index 0c090f4a0..af57ea28a 100644 --- a/src/app/api/auth/oidc/callback/route.ts +++ b/src/app/api/auth/oidc/callback/route.ts @@ -38,6 +38,18 @@ import { mintNativeHandoff, } from "@/lib/auth/oidc-native-handoff"; import { setPendingLinkCookie } from "@/lib/auth/oidc-pending-link"; +import { + CLAIM_COOKIE, + CLAIM_ERROR_PATH, + claimMatchesBinding, + clearClaimCookie, + readClaimCookie, +} from "@/lib/managed-profiles/claim-cookie"; +import { + completeSsoClaim, + SSO_CLAIM_LANDING, +} from "@/lib/managed-profiles/claim-sso"; +import { isHandoverUsable } from "@/lib/managed-profiles/handover"; const LOGIN_ERROR_URL = "/auth/login"; @@ -102,6 +114,14 @@ interface StoredOidcState { native?: boolean; /** The app's S256 PKCE challenge, bound at login; verified at the exchange. */ appCodeChallenge?: string; + /** + * v1.43 (#959) — set only when the login carried `intent=claim` and a valid + * `hl_claim` cookie. The callback then claims the managed profile the + * cookie names instead of signing in, and only when the cookie still + * carries this exact binding. Web only: never together with `native`. + */ + intent?: "claim"; + claimBinding?: string; } function isStoredOidcState(value: unknown): value is StoredOidcState { @@ -122,6 +142,13 @@ function isStoredOidcState(value: unknown): value is StoredOidcState { if (v.native !== true) return false; if (typeof v.appCodeChallenge !== "string") return false; } + if (v.intent !== undefined) { + if (v.intent !== "claim") return false; + if (typeof v.claimBinding !== "string" || v.claimBinding.length === 0) { + return false; + } + if (v.native !== undefined) return false; + } return true; } @@ -153,12 +180,27 @@ export const GET = apiHandler(async (req: NextRequest) => { } } const isNative = stored?.native === true; + const isClaim = stored?.intent === "claim"; // Native-aware error redirect: the custom scheme for a decrypted native flow, // the web login page otherwise. Deletes the single-use state cookie either // way. An error redirect carries no code, ticket, or session, so routing it // to the scheme leaks nothing (spec §1). + // v1.43 (#959) — a refused claim returns to the claim page, never the + // sign-in page, and takes the claim cookie with it: the person starts again + // from the link, which is still theirs to use if the refusal left it open. + // Browser-only, like `errorRedirect`: a claim is never native. + const claimRedirect = (reason: string): NextResponse => { + const response = NextResponse.redirect( + oidcAppUrl(`${CLAIM_ERROR_PATH}?error=${reason}`), + ); + deleteStateCookie(response); + clearClaimCookie(response); + return response; + }; + const failRedirect = (reason: string): NextResponse => { + if (isClaim) return claimRedirect(reason); if (isNative) { const response = NextResponse.redirect( buildNativeCallbackUrl({ error: reason }), @@ -198,7 +240,9 @@ export const GET = apiHandler(async (req: NextRequest) => { // Broken round-trip / missing-or-unreadable state blob / CSRF mismatch all // resolve to the web `oidc_state` fallback: the flow is fundamentally broken // and there is nothing safe to hand the app (spec §1 web-fallback). - if (!code || !state) return errorRedirect("oidc_state"); + if (!code || !state) { + return isClaim ? claimRedirect("oidc_state") : errorRedirect("oidc_state"); + } if (!stored) { // Defence-in-depth idempotency for a duplicated callback. The single-use @@ -240,7 +284,34 @@ export const GET = apiHandler(async (req: NextRequest) => { !timingSafeEqual(Buffer.from(state), Buffer.from(stored.state)) ) { annotate({ meta: { reason: "csrf" } }); - return errorRedirect("oidc_state"); + return isClaim ? claimRedirect("oidc_state") : errorRedirect("oidc_state"); + } + + // v1.43 (#959) — a claim is never finished over a live session (the claim + // routes' rule: a Guardian finishing their own link would otherwise be + // signed out of their account and into the person's), and is admitted only + // with its own sealed cookie, still bound to this sign-in, for a link that + // is still usable. All of it before the code is redeemed, so a refused claim + // spends nothing at the provider. + const pendingClaim = isClaim + ? readClaimCookie(req.cookies.get(CLAIM_COOKIE)?.value) + : null; + if (isClaim) { + const liveSession = await validateSessionFromCookieValue( + req.cookies.get(SESSION_COOKIE_NAME)?.value, + ); + if (liveSession) { + annotate({ meta: { reason: "claim_signed_in" } }); + return failRedirect("claim_signed_in"); + } + if ( + !pendingClaim || + !claimMatchesBinding(pendingClaim, stored.claimBinding as string) || + !(await isHandoverUsable(pendingClaim.handoverId)) + ) { + annotate({ meta: { reason: "claim_expired" } }); + return failRedirect("claim_expired"); + } } try { @@ -274,6 +345,28 @@ export const GET = apiHandler(async (req: NextRequest) => { emailVerified = userinfo.emailVerified; } + // v1.43 (#959) — the claim. The provider has authenticated somebody; bind + // that subject to the profile the cookie names, or refuse. Never falls + // through to the sign-in below: a refused claim signs nobody in, and + // provisions and links nothing. + if (pendingClaim) { + const outcome = await completeSsoClaim({ + handoverId: pendingClaim.handoverId, + username: pendingClaim.username, + issuer: metadata.issuer, + sub: identity.sub, + email, + emailVerified, + ipAddress: ip, + userAgent: req.headers.get("user-agent"), + }); + if (!outcome.ok) return failRedirect(outcome.reason); + const response = NextResponse.redirect(oidcAppUrl(SSO_CLAIM_LANDING)); + deleteStateCookie(response); + clearClaimCookie(response); + return response; + } + // (1) Durable identity match — the (issuer, sub) pair stamped on a // previous login, link, or provision. Email is deliberately NOT // consulted here: after the stamp it is a display field, so an diff --git a/src/app/api/auth/oidc/login/__tests__/route.test.ts b/src/app/api/auth/oidc/login/__tests__/route.test.ts index 38c13a58f..1d9fc1584 100644 --- a/src/app/api/auth/oidc/login/__tests__/route.test.ts +++ b/src/app/api/auth/oidc/login/__tests__/route.test.ts @@ -214,3 +214,50 @@ describe("GET /api/auth/oidc/login", () => { }); }); }); + +describe("GET /api/auth/oidc/login?intent=claim (v1.43, #959)", () => { + beforeEach(() => { + vi.mocked(getOidcConfig).mockReturnValue({ + issuerUrl: "https://idp.example.com", + clientId: "client-1", + clientSecret: "secret-1", + scopes: "openid email profile", + buttonLabel: "SSO", + }); + }); + + it("refuses a claim on the native leg with oidc_invalid_request", async () => { + const res = await GET( + makeRequest( + `/api/auth/oidc/login?intent=claim&client=native&code_challenge=${"a".repeat(43)}`, + ), + ); + expect(res.headers.get("location")).toMatch( + /^healthlog:\/\/oidc-callback\?error=oidc_invalid_request$/, + ); + expect(discoverOidcMetadata).not.toHaveBeenCalled(); + expect(res.cookies.get("oidc_auth_state")).toBeUndefined(); + }); + + it("sends a claim without its cookie back to the claim page, before the provider", async () => { + const res = await GET(makeRequest("/api/auth/oidc/login?intent=claim")); + expect(res.headers.get("location")).toBe( + "https://healthlog.example.com/auth/claim?error=claim_expired", + ); + expect(discoverOidcMetadata).not.toHaveBeenCalled(); + expect(res.cookies.get("oidc_auth_state")).toBeUndefined(); + }); + + it("routes the claim's other failures to the claim page too", async () => { + vi.mocked(checkAuthSurfaceRateLimit).mockResolvedValue({ + allowed: false, + remaining: 0, + reset: 0, + ip: "1.2.3.4", + } as never); + const res = await GET(makeRequest("/api/auth/oidc/login?intent=claim")); + expect(res.headers.get("location")).toBe( + "https://healthlog.example.com/auth/claim?error=oidc_rate_limited", + ); + }); +}); diff --git a/src/app/api/auth/oidc/login/route.ts b/src/app/api/auth/oidc/login/route.ts index 9e55d9c0a..dd0dc1cc8 100644 --- a/src/app/api/auth/oidc/login/route.ts +++ b/src/app/api/auth/oidc/login/route.ts @@ -21,6 +21,12 @@ import { OIDC_STATE_COOKIE_PATH, OIDC_STATE_TTL_MS, } from "@/lib/auth/oidc-cookie"; +import { + CLAIM_COOKIE, + CLAIM_ERROR_PATH, + readClaimCookie, +} from "@/lib/managed-profiles/claim-cookie"; +import { isHandoverUsable } from "@/lib/managed-profiles/handover"; /** * Redirects the browser to the configured OIDC provider's authorization @@ -40,16 +46,34 @@ export const GET = apiHandler(async (req: NextRequest) => { // nothing — an error redirect carries no code, ticket, or session (spec §1). const isNative = req.nextUrl.searchParams.get("client") === "native"; const appCodeChallenge = req.nextUrl.searchParams.get("code_challenge"); + // v1.43 (#959) — `intent=claim`: the sign-in claims a managed profile. The + // link and the username ride the sealed `hl_claim` cookie set by + // `POST /api/auth/claim/sso`, never this URL; the intent only says to look + // for it. Web only. + const isClaim = req.nextUrl.searchParams.get("intent") === "claim"; // Native-aware error redirect: the scheme for a native start, the web login - // page otherwise. Machine-readable `error=` in both. + // page otherwise, and the claim page for a claim. Machine-readable + // `error=` in all three. const loginError = (reason: string): NextResponse => { if (isNative) { return NextResponse.redirect(buildNativeCallbackUrl({ error: reason })); } + if (isClaim) { + return NextResponse.redirect( + oidcAppUrl(`${CLAIM_ERROR_PATH}?error=${reason}`), + ); + } return NextResponse.redirect(oidcAppUrl(`/auth/login?error=${reason}`)); }; + // The app never claims a profile: the claim runs in a browser, and the new + // owner signs in to the app afterwards through the ordinary native leg. + if (isClaim && isNative) { + annotate({ meta: { reason: "claim_on_native" } }); + return loginError("oidc_invalid_request"); + } + const config = getOidcConfig(); if (!config) { return loginError("oidc_disabled"); @@ -90,6 +114,19 @@ export const GET = apiHandler(async (req: NextRequest) => { return loginError("oidc_invalid_request"); } + // A claim needs its sealed cookie and a link that is still usable. Checked + // here, after the rate limit, so a dead link is told before the round trip + // to the provider; the callback checks both again. + let claimBinding: string | null = null; + if (isClaim) { + const claim = readClaimCookie(req.cookies.get(CLAIM_COOKIE)?.value); + if (!claim || !(await isHandoverUsable(claim.handoverId))) { + annotate({ meta: { reason: "claim_expired" } }); + return loginError("claim_expired"); + } + claimBinding = claim.binding; + } + let metadata; try { metadata = await discoverOidcMetadata(config); @@ -104,10 +141,12 @@ export const GET = apiHandler(async (req: NextRequest) => { const codeChallenge = s256Challenge(codeVerifier); // `next` is a post-login WEB path, meaningless to the app — pin it to "/" on - // the native branch (one less input to sanitize). - const safeNext = isNative - ? "/" - : sanitizeOidcNextPath(req.nextUrl.searchParams.get("next"), req.url); + // the native branch (one less input to sanitize). A claim lands on a fixed + // page the callback names, so its `next` is pinned too. + const safeNext = + isNative || isClaim + ? "/" + : sanitizeOidcNextPath(req.nextUrl.searchParams.get("next"), req.url); const redirectUri = getOidcRedirectUri(); const authorizationUrl = buildAuthorizationUrl({ @@ -133,6 +172,12 @@ export const GET = apiHandler(async (req: NextRequest) => { ...(isNative ? { native: true as const, appCodeChallenge: appCodeChallenge! } : {}), + // The claim's binding, inside the same tamper-authenticated blob: the + // callback admits the claim only when the cookie it carries back holds + // this exact value. + ...(claimBinding !== null + ? { intent: "claim" as const, claimBinding } + : {}), }), ); response.cookies.set(OIDC_STATE_COOKIE, cookiePayload, { diff --git a/src/app/api/managed-profiles/[id]/handover/route.ts b/src/app/api/managed-profiles/[id]/handover/route.ts index 3c702f200..1177988b2 100644 --- a/src/app/api/managed-profiles/[id]/handover/route.ts +++ b/src/app/api/managed-profiles/[id]/handover/route.ts @@ -30,8 +30,8 @@ import { safeJson, } from "@/lib/api-response"; import { buildHandoverUrl } from "@/lib/auth/handover-token"; -import { isOidcOnly } from "@/lib/auth/oidc"; import { annotate } from "@/lib/logging/context"; +import { handoverMethods } from "@/lib/managed-profiles/claim-gate"; import { createHandover, HandoverError, @@ -49,16 +49,15 @@ const notFound = () => }); /** - * v1.42 refuses the handover on a single-sign-on-only instance: the claim - * sets a password, and such an instance admits none. The SSO arm of the claim - * is a separate piece of work. + * A link nobody could redeem is not minted. Since v1.43 the person can claim + * through the identity provider, so a single-sign-on-only server hands over + * too; this answers only when neither a password nor single sign-on is + * possible, which a working configuration never produces. */ -const oidcOnlyRefusal = () => - apiError( - "Handing over a profile is not available while this server allows single sign-on only", - 403, - { errorCode: "profile_claim.oidc_only_unsupported" }, - ); +const noMethodRefusal = () => + apiError("Handing over a profile is not available on this server", 403, { + errorCode: "profile_claim.oidc_only_unsupported", + }); /** Same ceiling as creating, editing and inviting: ten an hour per caller. */ const CREATE_LIMIT = 10; @@ -79,8 +78,10 @@ export const GET = apiHandler( action: { name: "managed_profile.handover.read" }, meta: { profile_id: id, open: status.open !== null }, }); + const methods = handoverMethods(); return apiSuccess({ - available: !isOidcOnly(), + available: methods.length > 0, + methods, open: status.open ? { id: status.open.id, @@ -107,7 +108,7 @@ export const POST = apiHandler( if (!rateLimit.allowed) { return apiError("Too many handover links, try again later", 429); } - if (isOidcOnly()) return oidcOnlyRefusal(); + if (handoverMethods().length === 0) return noMethodRefusal(); const { id } = await params; const { data: body, error: jsonError } = await safeJson(request, { diff --git a/src/app/auth/claim/page.tsx b/src/app/auth/claim/page.tsx index 217302b9c..2a37b693f 100644 --- a/src/app/auth/claim/page.tsx +++ b/src/app/auth/claim/page.tsx @@ -6,7 +6,9 @@ import { ClaimProfile } from "@/components/auth/claim-profile"; /** * v1.42 (#959) — `/auth/claim?token=hlp_…`, where the link a Guardian handed - * over (`/claim/`) lands after the edge redirect. + * over (`/claim/`) lands after the edge redirect. Since v1.43 also + * `/auth/claim?error=`, where a refused single-sign-on claim returns; + * the reason is a fixed word, never a credential. * * A URL-credential surface by shape (`session-surface-guard.test.ts`, S2): the * page reads the one-time token off the query string and passes it to the @@ -16,5 +18,10 @@ import { ClaimProfile } from "@/components/auth/claim-profile"; */ export default function ClaimProfilePage() { const searchParams = useSearchParams(); - return ; + return ( + + ); } diff --git a/src/components/auth/__tests__/claim-profile-invalid.test.tsx b/src/components/auth/__tests__/claim-profile-invalid.test.tsx index b240065c0..5e0881043 100644 --- a/src/components/auth/__tests__/claim-profile-invalid.test.tsx +++ b/src/components/auth/__tests__/claim-profile-invalid.test.tsx @@ -19,6 +19,7 @@ vi.mock("@/hooks/use-auth", () => ({ vi.mock("@/lib/queries/use-profile-claim", () => ({ useProfileClaimPreview: () => ({ data: undefined, error: null }), useClaimProfile: () => ({ mutate: () => {}, isPending: false }), + useClaimProfileSso: () => ({ mutate: () => {}, isPending: false }), })); import { ClaimProfile } from "../claim-profile"; diff --git a/src/components/auth/__tests__/claim-profile-sso.test.tsx b/src/components/auth/__tests__/claim-profile-sso.test.tsx new file mode 100644 index 000000000..75d1c8d99 --- /dev/null +++ b/src/components/auth/__tests__/claim-profile-sso.test.tsx @@ -0,0 +1,105 @@ +import { describe, it, expect, vi } from "vitest"; +import { renderToStaticMarkup } from "react-dom/server"; +import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; + +import { I18nProvider } from "@/lib/i18n/context"; +import type { ProfileClaimPreview } from "@/lib/queries/use-profile-claim"; + +/** + * v1.43 (#959) — the claim page offers the ways in the server names: the + * password form, the identity provider, or both. A refused single-sign-on + * claim comes back with `?error=` and no link, and says what happened. + */ + +let previewData: ProfileClaimPreview | undefined; + +vi.mock("next/navigation", () => ({ + useRouter: () => ({ replace: () => {}, refresh: () => {}, push: () => {} }), +})); +vi.mock("@/hooks/use-auth", () => ({ + useAuth: () => ({ user: null }), + clearCachesForSessionEnd: () => {}, +})); +vi.mock("@/lib/queries/use-profile-claim", () => ({ + useProfileClaimPreview: () => ({ data: previewData, error: null }), + useClaimProfile: () => ({ mutate: () => {}, isPending: false }), + useClaimProfileSso: () => ({ mutate: () => {}, isPending: false }), +})); + +import { ClaimProfile, claimSsoErrorKey } from "../claim-profile"; + +const BASE: ProfileClaimPreview = { + displayName: "Robin", + expiresAt: "2030-01-01T00:00:00.000Z", + guardians: [], +}; + +function render(props: { token: string | null; error?: string | null }) { + return renderToStaticMarkup( + + + + + , + ); +} + +describe("ClaimProfile — ways in", () => { + it("offers only the provider on a single-sign-on-only server", () => { + previewData = { ...BASE, methods: ["sso"], ssoProviderName: "Example ID" }; + const html = render({ token: "hlp_x" }); + expect(html).toContain('data-slot="claim-sso-continue"'); + expect(html).toContain("Continue with Example ID"); + expect(html).not.toContain('id="claim-password"'); + expect(html).not.toContain('id="claim-email"'); + expect(html).not.toContain('data-slot="claim-submit"'); + expect(html).toContain('id="claim-username"'); + }); + + it("offers both when both are allowed", () => { + previewData = { + ...BASE, + methods: ["password", "sso"], + ssoProviderName: "Example ID", + }; + const html = render({ token: "hlp_x" }); + expect(html).toContain('data-slot="claim-sso-continue"'); + expect(html).toContain('id="claim-password"'); + expect(html).toContain('data-slot="claim-submit"'); + }); + + it("offers only the password when an older server names no methods", () => { + previewData = { ...BASE }; + const html = render({ token: "hlp_x" }); + expect(html).not.toContain('data-slot="claim-sso-continue"'); + expect(html).toContain('id="claim-password"'); + }); +}); + +describe("ClaimProfile — a refused single-sign-on claim", () => { + it("says what happened and offers a way on", () => { + previewData = undefined; + const html = render({ token: null, error: "claim_sso_subject_bound" }); + expect(html).toContain('data-testid="claim-sso-error"'); + expect(html).toContain("already belongs to another account"); + expect(html).toContain('href="/auth/login"'); + }); + + it("maps every reason the callback sends, and reads an unknown one as a failure", () => { + expect(claimSsoErrorKey("claim_expired")).toBe("auth.claim.invalidHint"); + expect(claimSsoErrorKey("claim_sso_subject_bound")).toBe( + "auth.claim.errorSubjectBound", + ); + expect(claimSsoErrorKey("claim_email_taken")).toBe( + "auth.claim.errorEmailTaken", + ); + expect(claimSsoErrorKey("claim_username_taken")).toBe( + "auth.claim.errorUsernameTaken", + ); + expect(claimSsoErrorKey("claim_signed_in")).toBe( + "auth.claim.errorSignedIn", + ); + expect(claimSsoErrorKey("oidc_failed")).toBe("auth.claim.errorSso"); + expect(claimSsoErrorKey("