@runeditrun/rer 0.2.78 → 0.2.80
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +17 -3
- package/cli/README.md +25 -13
- package/cli/authoring.mjs +14 -0
- package/cli/contract.mjs +25 -5
- package/cli/demo-host.mjs +4 -2
- package/cli/dev-identity.mjs +2 -2
- package/cli/export.mjs +1 -1
- package/cli/inspect.mjs +38 -2
- package/cli/main.mjs +8 -2
- package/cli/managed-server.mjs +1 -1
- package/cli/parse.mjs +7 -6
- package/cli/portability-worker.mjs +2 -1
- package/cli/portability.mjs +6 -2
- package/cli/production-auth.mjs +2 -1
- package/cli/production-mail.mjs +36 -9
- package/cli/project.mjs +5 -14
- package/cli/release.mjs +2 -1
- package/cli/server-proxy.mjs +30 -8
- package/cli/site-preview.mjs +4 -1
- package/cli/site.mjs +3 -2
- package/cli/upstream-agent.mjs +14 -0
- package/edition-authoring/adopt.mjs +39 -0
- package/edition-authoring/base-acknowledgements.mjs +24 -0
- package/edition-authoring/base-copies.mjs +418 -0
- package/edition-authoring/cli.mjs +85 -0
- package/edition-authoring/copy-checkout.mjs +69 -0
- package/edition-authoring/files.mjs +15 -2
- package/edition-authoring/lock.mjs +48 -0
- package/edition-authoring/offline-git.mjs +28 -0
- package/edition-authoring/parent-comparison.mjs +77 -0
- package/edition-authoring/projection-lock.mjs +38 -0
- package/edition-authoring/release.mjs +48 -0
- package/edition-authoring/sources.mjs +114 -0
- package/edition-authoring/updates.mjs +105 -0
- package/global/CHANGELOG.md +17 -0
- package/global/README.md +17 -3
- package/global/cli/install.mjs +3 -1
- package/global/main.mjs +9 -12
- package/modules/container/build.mjs +1 -1
- package/modules/d1-transport/index.mjs +68 -21
- package/modules/demo/README.md +8 -2
- package/modules/demo/declaration.mjs +21 -0
- package/modules/demo/input-path.mjs +18 -0
- package/modules/demo/label.d.mts +1 -1
- package/modules/demo/label.mjs +10 -5
- package/modules/demo/navigation.mjs +32 -0
- package/modules/demo/run-url.mjs +9 -0
- package/modules/demo/vite.d.mts +7 -2
- package/modules/demo/vite.mjs +17 -2
- package/modules/demo-host/README.md +5 -3
- package/modules/demo-host/native/visitor.mjs +1 -1
- package/modules/demo-host/page-style.mjs +2 -2
- package/modules/demo-host/pages.mjs +3 -3
- package/modules/demo-host/plan.mjs +6 -4
- package/modules/demo-host/theme.mjs +5 -2
- package/modules/deploy-kit/README.md +19 -15
- package/modules/deploy-kit/owner-cli.mjs +1 -1
- package/modules/deploy-kit/readiness-window.mjs +3 -3
- package/modules/erasure/README.md +10 -5
- package/modules/import-kit/src/d1/README.md +15 -9
- package/modules/import-kit/src/d1/apply.ts +10 -6
- package/modules/import-kit/src/d1/atomic-prefix.ts +64 -0
- package/modules/import-kit/src/d1/budget.ts +48 -26
- package/modules/import-kit/src/d1/compressed-plan.ts +9 -2
- package/modules/import-kit/src/d1/database.ts +2 -1
- package/modules/import-kit/src/d1/jobs.ts +2 -1
- package/modules/import-kit/src/d1/plans.ts +4 -2
- package/modules/import-kit/src/d1/verified-plan.ts +63 -0
- package/modules/integrations/core/README.md +2 -2
- package/modules/mail/README.md +4 -3
- package/modules/mail/pnpm-lock.yaml +16 -0
- package/modules/operator-auth/accounts/native.mjs +3 -1
- package/modules/operator-auth/accounts/provider-control.mjs +7 -4
- package/modules/operator-auth/accounts/provider-setup.mjs +34 -0
- package/modules/operator-auth/accounts/settings-page.mjs +13 -4
- package/modules/operator-auth/conformance/README.md +1 -1
- package/modules/operator-auth/dev/index.mjs +22 -4
- package/modules/operator-auth/dev/refusal.mjs +19 -0
- package/modules/operator-auth/docs/README.md +6 -5
- package/modules/operator-auth/docs/tanstack-start.md +1 -1
- package/modules/operator-auth/docs/vite-spa.md +5 -6
- package/modules/operator-auth/index.d.mts +1 -1
- package/modules/operator-auth/page.mjs +14 -0
- package/modules/operator-auth/representation.mjs +83 -0
- package/modules/operator-auth/routes.mjs +25 -2
- package/modules/portability/README.md +91 -14
- package/modules/portability/bookkeeping.mjs +3 -3
- package/modules/portability/bridge.mjs +5 -4
- package/modules/portability/catalogue.mjs +12 -8
- package/modules/portability/cli.mjs +5 -1
- package/modules/portability/export.mjs +5 -11
- package/modules/portability/format.mjs +7 -1
- package/modules/portability/http-errors.mjs +51 -0
- package/modules/portability/http.mjs +4 -1
- package/modules/portability/import-lease.mjs +13 -2
- package/modules/portability/import.mjs +10 -0
- package/modules/portability/index.d.mts +3 -0
- package/modules/portability/references.mjs +20 -0
- package/modules/portability/schema-identity.mjs +13 -0
- package/modules/portability/schema-legacy.mjs +21 -0
- package/modules/portability/sqlite-tokens.mjs +121 -0
- package/modules/release/README.md +20 -9
- package/modules/release/github-verify.mjs +30 -9
- package/modules/site/docs-search/search.css +1 -1
- package/onboarding/README.md +16 -4
- package/onboarding/adapter.mjs +5 -1
- package/onboarding/schema/SETUP.schema.json +26 -1
- package/onboarding/schema/business-field-inputs.mjs +37 -0
- package/onboarding/schema/json-schema.mjs +6 -2
- package/onboarding/schema/setup-validation.mjs +20 -3
- package/onboarding/server.mjs +1 -1
- package/onboarding/setup-manifest.mjs +2 -0
- package/onboarding/start-origin-diagnostic.mjs +24 -0
- package/onboarding/ui/style.css +9 -9
- package/package.json +1 -1
- package/scripts/publish-check/README.md +1 -1
|
@@ -4,10 +4,10 @@ Import portable delivery, signed webhook, token and D1 APIs from `./index.ts`.
|
|
|
4
4
|
Import Node adapters explicitly from `./sqlite.ts` and `./node-transport.ts`.
|
|
5
5
|
Node 26 is the tested runtime; no runtime npm dependency is needed.
|
|
6
6
|
|
|
7
|
-
The [consumer guide](
|
|
7
|
+
The [consumer guide](https://github.com/runeditrun/base/blob/main/modules/integrations/README.md) contains fresh SQLite migration, enqueue and
|
|
8
8
|
Worker scheduling examples. The [public contract](CONTRACT.md) defines exact
|
|
9
9
|
HMAC framing, retry outcomes, durable replay and same-database token authority.
|
|
10
|
-
The [receiver guide](
|
|
10
|
+
The [receiver guide](https://github.com/runeditrun/base/blob/main/modules/integrations/receiver.md) supplies executable Node and Fetch receiver
|
|
11
11
|
boundaries that verify original bytes before claiming replay identities.
|
|
12
12
|
|
|
13
13
|
Apply `schema.sql` once through the application's numbered migration ledger.
|
package/modules/mail/README.md
CHANGED
|
@@ -43,6 +43,7 @@ modules/mail/src/adapters/sendgrid/index.mjs
|
|
|
43
43
|
modules/mail/src/adapters/sendgrid/serialize.mjs
|
|
44
44
|
modules/mail/src/adapters/rer/contract.mjs
|
|
45
45
|
modules/mail/src/adapters/rer/index.mjs
|
|
46
|
+
modules/mail/src/adapters/rer/list-headers.mjs
|
|
46
47
|
modules/mail/src/adapters/messaging/contract.mjs
|
|
47
48
|
modules/mail/src/adapters/messaging/event-schema.mjs
|
|
48
49
|
modules/mail/src/adapters/messaging/index.mjs
|
|
@@ -118,14 +119,14 @@ These are for developing the module itself or documentation. A seed may keep any
|
|
|
118
119
|
- `modules/mail/README.md` and every `README.md` under `modules/mail/src/`
|
|
119
120
|
|
|
120
121
|
The provider is explicit: `sendgrid`, `resend`, `cloudflare`, `rer`, `messaging`, or `development`.
|
|
121
|
-
`mode` is required (`production`, `development`, or `test`).
|
|
122
|
+
`mode` is required (`production`, `development`, or `test`). SendGrid, Resend, Cloudflare and RER require `apiKey`; Cloudflare additionally requires a 32-hex `accountId`. Messaging instead requires its signed-link configuration (`serviceOrigin`, `installId`, `kid` and `signingKey`) and rejects `apiKey` and `accountId`. A remote provider in test/development mode still makes a real provider request unless the caller explicitly supplies a test fetch. Missing credentials, validation errors, or provider failure never select another provider. Config and messages reject unknown fields so requested features cannot silently disappear.
|
|
122
123
|
|
|
123
124
|
`createMailSender(config, dependencies?)` returns `{send(message)}`. Dependencies are optional standard `fetch`, `clock: () => epochMilliseconds`, and `timeoutMilliseconds` (a positive safe integer bounding each remote attempt; the default is 15,000). Production normally uses global fetch. Direct provider endpoints are fixed; `rer` uses its assigned relay URL. No retry or automatic replay exists. The sender snapshots configuration at construction and the message at submission.
|
|
124
125
|
|
|
125
126
|
### Managed mail through RER
|
|
126
127
|
|
|
127
128
|
Seeds opt into Managed mail with `mail: {providers: ["rer"]}` in their candidate
|
|
128
|
-
deployment spec. The [delivery producer](
|
|
129
|
+
deployment spec. The [delivery producer](https://github.com/runeditrun/base/blob/main/modules/delivery-producer/README.md#managed-mail)
|
|
129
130
|
can generate the matching setup fields. RER assigns public `MAIL_PROVIDER`,
|
|
130
131
|
`MAIL_FROM`, `MAIL_RELAY_URL` and private `MAIL_API_KEY`; Managed owners do not
|
|
131
132
|
enter them. Wire those settings into the shared sender:
|
|
@@ -202,7 +203,7 @@ adapter makes no retries and never reads or logs provider error bodies.
|
|
|
202
203
|
|
|
203
204
|
## Message and results
|
|
204
205
|
|
|
205
|
-
Required fields: `deliveryId` (nonempty, at most 512 characters), `from`, nonempty `to: string[]`, `subject: string` (SendGrid requires nonempty; other providers allow empty), and at least one nonempty `text` or `html`. Addresses accept a mailbox or `Display Name <mailbox>`; the conservative mailbox grammar rejects controls, multiple addresses inside one string and malformed domains. Use arrays for recipients.
|
|
206
|
+
Required fields: `deliveryId` (nonempty, at most 512 characters), `from`, nonempty `to: string[]`, `subject: string` (SendGrid requires nonempty; RER requires nonblank and at most 200 characters; other providers allow empty), and at least one nonempty `text` or `html`. Addresses accept a mailbox or `Display Name <mailbox>`; the conservative mailbox grammar rejects controls, multiple addresses inside one string and malformed domains. Use arrays for recipients.
|
|
206
207
|
|
|
207
208
|
Optional `cc`, `bcc`, `replyTo`, and string-valued `headers` preserve envelope and threading. `In-Reply-To` and ordered `References` can be supplied as headers. SendGrid and Resend also accept `Message-ID`; Cloudflare generates it and rejects a caller-supplied value; `rer` rejects it and assigns one from an optional `messageKey`. CR/LF/control characters, duplicate header names ignoring case, reserved envelope/MIME/security headers and invalid header names fail before a request. Provider-specific header restrictions are also enforced.
|
|
208
209
|
|
|
@@ -91,89 +91,105 @@ packages:
|
|
|
91
91
|
resolution: {integrity: sha512-Y3dgX/6lE2QhQb+Gxy0WZxfg9MEm/JBjamZpS2IklP7xIQoKN4hzAm7KcMVGtaVDt3neE9OKBC7vAfonA/Lr1A==}
|
|
92
92
|
cpu: [arm64]
|
|
93
93
|
os: [linux]
|
|
94
|
+
libc: [glibc]
|
|
94
95
|
|
|
95
96
|
'@img/sharp-libvips-linux-arm@1.3.4':
|
|
96
97
|
resolution: {integrity: sha512-LmRtTsOHuvM2+wlO2Db37dx5MiZhB0FvSunciw48YjdOkZz9KAiRbm8ujeMOA1INqmei5NapFxYEK1D1ZSidmw==}
|
|
97
98
|
cpu: [arm]
|
|
98
99
|
os: [linux]
|
|
100
|
+
libc: [glibc]
|
|
99
101
|
|
|
100
102
|
'@img/sharp-libvips-linux-ppc64@1.3.4':
|
|
101
103
|
resolution: {integrity: sha512-Le6boB8Tai0Nis+gIxIpKx68UDVVIqdR8Tin5Yf1z2LJJQLDJvCDRqRu+jC2qCoD+eIomonmOwB4smBRxfVpYQ==}
|
|
102
104
|
cpu: [ppc64]
|
|
103
105
|
os: [linux]
|
|
106
|
+
libc: [glibc]
|
|
104
107
|
|
|
105
108
|
'@img/sharp-libvips-linux-riscv64@1.3.4':
|
|
106
109
|
resolution: {integrity: sha512-aHkkIEHPRdQEegJN20MLmGtxYD9R2wQr3Cwpddnu5+YKMt6Uzax7S9h5gpZTo8wyrGuZSlfQ63OevL5mTyOC7Q==}
|
|
107
110
|
cpu: [riscv64]
|
|
108
111
|
os: [linux]
|
|
112
|
+
libc: [glibc]
|
|
109
113
|
|
|
110
114
|
'@img/sharp-libvips-linux-s390x@1.3.4':
|
|
111
115
|
resolution: {integrity: sha512-ra/mB6MikESDUO7Yg+Mi95bFBb9GsObURuhnOv3OqknjGe9sZrG8tCe9q0xSIGrtLgvgw0gKnFWcK4blSgQOuQ==}
|
|
112
116
|
cpu: [s390x]
|
|
113
117
|
os: [linux]
|
|
118
|
+
libc: [glibc]
|
|
114
119
|
|
|
115
120
|
'@img/sharp-libvips-linux-x64@1.3.4':
|
|
116
121
|
resolution: {integrity: sha512-GJ//SSXbnwSDes02umB3nDJLFcQzw8a18V8fyhqr6tV515tOEMdImjjxj1AoafMRz56F3PHgftnj1QEKSU1zkw==}
|
|
117
122
|
cpu: [x64]
|
|
118
123
|
os: [linux]
|
|
124
|
+
libc: [glibc]
|
|
119
125
|
|
|
120
126
|
'@img/sharp-libvips-linuxmusl-arm64@1.3.4':
|
|
121
127
|
resolution: {integrity: sha512-hvulFwtjUcagsis6BBxHwGFwWoNZjgYmULGVrZcyfNbjA8hKILbRxGg15/7w5HDyXHXUos/j6baAWqnCyQ2DWA==}
|
|
122
128
|
cpu: [arm64]
|
|
123
129
|
os: [linux]
|
|
130
|
+
libc: [musl]
|
|
124
131
|
|
|
125
132
|
'@img/sharp-libvips-linuxmusl-x64@1.3.4':
|
|
126
133
|
resolution: {integrity: sha512-6zXKeE/p39I1AmA3cJG35eyBGNqNddLnUXjhwBnsGjFPWqf5VKkDBEqaEkPDoTEtkxwi2vv8Tcr2mDyP4So7Fg==}
|
|
127
134
|
cpu: [x64]
|
|
128
135
|
os: [linux]
|
|
136
|
+
libc: [musl]
|
|
129
137
|
|
|
130
138
|
'@img/sharp-linux-arm64@0.35.5':
|
|
131
139
|
resolution: {integrity: sha512-LYVx5JTsOM2CBzmxreh+nl64/3H6Xb09iSLknqH47z2T2DFFxDeFLP5y4dJwe6H7uGQlHPyEEtIqyo3DYsRwdQ==}
|
|
132
140
|
engines: {node: '>=20.9.0'}
|
|
133
141
|
cpu: [arm64]
|
|
134
142
|
os: [linux]
|
|
143
|
+
libc: [glibc]
|
|
135
144
|
|
|
136
145
|
'@img/sharp-linux-arm@0.35.5':
|
|
137
146
|
resolution: {integrity: sha512-LEaXK2WdXVK5ykcw0buWyPMsmLLL2vpHLD6yrNSW+JGEL3BZPA4tpKN6iaMc4AxTTAoaX/sU1rOL51lcIz48ZQ==}
|
|
138
147
|
engines: {node: '>=20.9.0'}
|
|
139
148
|
cpu: [arm]
|
|
140
149
|
os: [linux]
|
|
150
|
+
libc: [glibc]
|
|
141
151
|
|
|
142
152
|
'@img/sharp-linux-ppc64@0.35.5':
|
|
143
153
|
resolution: {integrity: sha512-QVxAAq8evVRI9ia2vqgwrmWucn5Dfv+JdWzj75pD8omHLPSP7f8p20O8jxzjCcuCEQEOtYOZUmX1hkiZ0kdevA==}
|
|
144
154
|
engines: {node: '>=20.9.0'}
|
|
145
155
|
cpu: [ppc64]
|
|
146
156
|
os: [linux]
|
|
157
|
+
libc: [glibc]
|
|
147
158
|
|
|
148
159
|
'@img/sharp-linux-riscv64@0.35.5':
|
|
149
160
|
resolution: {integrity: sha512-LtdreXguaavKODPIfzJ4kffx7UNt1omwtK0rch4EBbbSTXPnxWmYSayXdLJw0fJzQ97kHt1gL/yh4tvU+nCyRQ==}
|
|
150
161
|
engines: {node: '>=20.9.0'}
|
|
151
162
|
cpu: [riscv64]
|
|
152
163
|
os: [linux]
|
|
164
|
+
libc: [glibc]
|
|
153
165
|
|
|
154
166
|
'@img/sharp-linux-s390x@0.35.5':
|
|
155
167
|
resolution: {integrity: sha512-UZasTOFiYzotTsGOCu42BfUzP6Tu6Do/947iRm1RsLKvlllxwGcn4RN27LibGWceix4Y+Pmw3jsnTcCQIgWjqA==}
|
|
156
168
|
engines: {node: '>=20.9.0'}
|
|
157
169
|
cpu: [s390x]
|
|
158
170
|
os: [linux]
|
|
171
|
+
libc: [glibc]
|
|
159
172
|
|
|
160
173
|
'@img/sharp-linux-x64@0.35.5':
|
|
161
174
|
resolution: {integrity: sha512-SxFtLTeJInhAA9Q836kux2vZNeOBQEx658qvbboZScr0wIARym3IcGmW7KpVD5sbVg0Ojy+udFQdayYIZyoNog==}
|
|
162
175
|
engines: {node: '>=20.9.0'}
|
|
163
176
|
cpu: [x64]
|
|
164
177
|
os: [linux]
|
|
178
|
+
libc: [glibc]
|
|
165
179
|
|
|
166
180
|
'@img/sharp-linuxmusl-arm64@0.35.5':
|
|
167
181
|
resolution: {integrity: sha512-9HbMclmI1zlNkFRs3z9/eBtDjfD0sGlrX1z6b1qwmiFY5ElDLh4BC0LPBdVp7z1DXFiKlIcznf+ZlsuZzLxQqg==}
|
|
168
182
|
engines: {node: '>=20.9.0'}
|
|
169
183
|
cpu: [arm64]
|
|
170
184
|
os: [linux]
|
|
185
|
+
libc: [musl]
|
|
171
186
|
|
|
172
187
|
'@img/sharp-linuxmusl-x64@0.35.5':
|
|
173
188
|
resolution: {integrity: sha512-4KOphqB035HrVdqLZfCgMzzERrQkkzOwRhl4OAkRO1YCldbaFjySXMaK534Mo0V+LndnlJk+sbUyLeU0ULyD1A==}
|
|
174
189
|
engines: {node: '>=20.9.0'}
|
|
175
190
|
cpu: [x64]
|
|
176
191
|
os: [linux]
|
|
192
|
+
libc: [musl]
|
|
177
193
|
|
|
178
194
|
'@img/sharp-wasm32@0.35.5':
|
|
179
195
|
resolution: {integrity: sha512-Ptsga1su4tQx+LLF1ECS9U6nz5kmrXKo6XVbtR48Ke3ZRxxgaWBu7IDtEe1quo8hiupwm6WFqxVlXaSf7IINGQ==}
|
|
@@ -14,6 +14,7 @@ import { createOidcProviders } from '../identity/oidc/index.mjs';
|
|
|
14
14
|
import { isLocalCli } from '../local-cli.mjs';
|
|
15
15
|
import { nativeDependencyAuthority } from '../../dependencies/native.mjs';
|
|
16
16
|
import { linkedProviders } from '../../dependencies/auth.mjs';
|
|
17
|
+
import { providerSetup } from './provider-setup.mjs';
|
|
17
18
|
|
|
18
19
|
const ACCOUNT_METHODS = ['findById', 'getSession', 'signOut', 'policyVersion', 'identityEnabled', 'requiredProvider', 'bindAndIssueSession'];
|
|
19
20
|
const PROOF_METHODS = ['limits', 'token', 'preview', 'consumeLink', 'revokeLink', 'stepUpPreview', 'stepUpChallenge', 'consumeStepUp', 'revokeStepUp', 'steppedUp'];
|
|
@@ -146,11 +147,12 @@ export function createNativeAuth({ accounts, proofs, db, config, clock, hooks, m
|
|
|
146
147
|
async admitVerifiedPassword(request, id, { returnTo } = {}) {
|
|
147
148
|
requirePost(request, config); return localSession(request, id, 'password', returnTo);
|
|
148
149
|
},
|
|
149
|
-
async identitySettings(request) { await owner(request); return { idpSignIn: await enabled() }; },
|
|
150
|
+
async identitySettings(request) { await owner(request); return { idpSignIn: await enabled(), providerSetup: await providerSetup(db, config) }; },
|
|
150
151
|
async setIdentitySettings(request, { idpSignIn }) {
|
|
151
152
|
const actor = await owner(request, true);
|
|
152
153
|
if (typeof idpSignIn !== 'boolean') deny('invalid_input', 400);
|
|
153
154
|
if (!accounts.setIdentitySettings) unavailable();
|
|
155
|
+
if (idpSignIn && !(await providerSetup(db, config)).canEnable) deny('provider_unlinked', 409);
|
|
154
156
|
if (!await accounts.setIdentitySettings({ actor, idpSignIn, now: clock() })) deny('authority_changed', 409);
|
|
155
157
|
return { idpSignIn };
|
|
156
158
|
},
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { devAdmitted } from '../dev-admission.mjs';
|
|
2
2
|
import { deny } from '../errors.mjs';
|
|
3
3
|
import { requirePost } from '../http.mjs';
|
|
4
|
+
import { providerEnableFence, providerSetup } from './provider-setup.mjs';
|
|
4
5
|
|
|
5
6
|
export function providerControl({ store, accounts, authenticate, config, clock }) {
|
|
6
7
|
async function owner(request, post = false) {
|
|
@@ -11,17 +12,19 @@ export function providerControl({ store, accounts, authenticate, config, clock }
|
|
|
11
12
|
return actor;
|
|
12
13
|
}
|
|
13
14
|
return {
|
|
14
|
-
async identitySettings(request) { await owner(request); return { idpSignIn: await accounts.identityEnabled() }; },
|
|
15
|
+
async identitySettings(request) { await owner(request); return { idpSignIn: await accounts.identityEnabled(), providerSetup: await providerSetup(store.db, config) }; },
|
|
15
16
|
async setIdentitySettings(request, { idpSignIn }) {
|
|
16
17
|
const actor = await owner(request, true);
|
|
17
18
|
if (typeof idpSignIn !== 'boolean') deny('invalid_input', 400);
|
|
19
|
+
const readiness = idpSignIn ? providerEnableFence(config) : { sql: '1', args: [] };
|
|
20
|
+
if (idpSignIn && !(await providerSetup(store.db, config)).canEnable) deny('provider_unlinked', 409);
|
|
18
21
|
const fence = store.actorFence(actor, clock());
|
|
19
22
|
const currentOwner = `?=(SELECT o.id FROM oa_operators o LEFT JOIN oa_bootstrap b ON b.claim_id=o.id WHERE o.role='owner' AND o.status='active' ORDER BY b.claim_id IS NULL,o.created_at,o.id LIMIT 1)`;
|
|
20
23
|
const auditId=crypto.randomUUID();
|
|
21
24
|
const results = await store.batch([
|
|
22
|
-
[`INSERT INTO oa_auth_settings(singleton,idp_sign_in,generation,first_setup) SELECT 1,0,0,0 WHERE ${fence.sql} AND ${currentOwner} ON CONFLICT(singleton) DO UPDATE SET first_setup=0 RETURNING singleton`, [...fence.args, actor.operator.id]],
|
|
23
|
-
[`INSERT INTO oa_auth_settings(singleton,idp_sign_in,generation) SELECT 1,?,1 WHERE ${fence.sql} AND ${currentOwner} AND NOT EXISTS(SELECT 1 FROM oa_auth_settings WHERE singleton=1 AND idp_sign_in=?)
|
|
24
|
-
ON CONFLICT(singleton) DO UPDATE SET idp_sign_in=excluded.idp_sign_in,generation=oa_auth_settings.generation+1,first_setup=0 RETURNING singleton`, [idpSignIn ? 1 : 0, ...fence.args, actor.operator.id, idpSignIn ? 1 : 0]],
|
|
25
|
+
[`INSERT INTO oa_auth_settings(singleton,idp_sign_in,generation,first_setup) SELECT 1,0,0,0 WHERE ${fence.sql} AND ${currentOwner} AND (${readiness.sql}) ON CONFLICT(singleton) DO UPDATE SET first_setup=0 RETURNING singleton`, [...fence.args, actor.operator.id, ...readiness.args]],
|
|
26
|
+
[`INSERT INTO oa_auth_settings(singleton,idp_sign_in,generation) SELECT 1,?,1 WHERE ${fence.sql} AND ${currentOwner} AND (${readiness.sql}) AND NOT EXISTS(SELECT 1 FROM oa_auth_settings WHERE singleton=1 AND idp_sign_in=?)
|
|
27
|
+
ON CONFLICT(singleton) DO UPDATE SET idp_sign_in=excluded.idp_sign_in,generation=oa_auth_settings.generation+1,first_setup=0 RETURNING singleton`, [idpSignIn ? 1 : 0, ...fence.args, actor.operator.id, ...readiness.args, idpSignIn ? 1 : 0]],
|
|
25
28
|
[`INSERT INTO oa_auth_audit(id,actor_id,action,value,created_at) SELECT ?,?,'idpSignIn',?,? WHERE changes()=1`, [auditId, actor.operator.id, String(idpSignIn), clock()]],
|
|
26
29
|
[`UPDATE oa_sessions SET revoked_at=COALESCE(revoked_at,?) WHERE kind='oidc' AND EXISTS(SELECT 1 FROM oa_auth_audit WHERE id=? AND value='false')`, [clock(), auditId]],
|
|
27
30
|
]);
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
// Registration state, independent of the sign-in switch and network health.
|
|
2
|
+
// Static providers pin on first use; an explicit unlink still requires relinking.
|
|
3
|
+
export function providerEnableFence(config) {
|
|
4
|
+
if (config.externalIssuers.length) return { sql: '1', args: [] };
|
|
5
|
+
const clauses = [], args = [];
|
|
6
|
+
for (const provider of config.providers) {
|
|
7
|
+
clauses.push("NOT EXISTS(SELECT 1 FROM oa_identity_providers WHERE provider_id=? AND status='unlinked')");
|
|
8
|
+
args.push(provider.id);
|
|
9
|
+
}
|
|
10
|
+
if (config.dependencies) clauses.push(`EXISTS(SELECT 1 FROM rer_dependency_link l JOIN rer_dependency_keys k ON k.interface=l.interface
|
|
11
|
+
WHERE l.interface='oidc-provider@1' AND l.needs_relink=0)
|
|
12
|
+
AND NOT EXISTS(SELECT 1 FROM oa_identity_providers WHERE provider_id='auth' AND status='unlinked')`);
|
|
13
|
+
return { sql: clauses.length ? clauses.map(sql => `(${sql})`).join(' OR ') : '0', args };
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
export async function providerSetup(db, config) {
|
|
17
|
+
const providers = [];
|
|
18
|
+
if (config.externalIssuers.length) providers.push({ id: 'external', label: 'Verified identity provider', state: 'configured' });
|
|
19
|
+
if (config.providers.length || config.dependencies) {
|
|
20
|
+
let pins = config.providers.length ? (await db.prepare('SELECT provider_id,status FROM oa_identity_providers').all()).results : [];
|
|
21
|
+
for (const provider of config.providers) {
|
|
22
|
+
const pin = pins.find(pin => pin.provider_id === provider.id);
|
|
23
|
+
providers.push({ id: provider.id, label: provider.label ?? provider.id, state: pin?.status ?? 'configured' });
|
|
24
|
+
}
|
|
25
|
+
if (config.dependencies) {
|
|
26
|
+
const link = await db.prepare(`SELECT l.needs_relink,EXISTS(SELECT 1 FROM rer_dependency_keys k WHERE k.interface=l.interface) AS has_key
|
|
27
|
+
FROM rer_dependency_link l WHERE l.interface='oidc-provider@1'`).first();
|
|
28
|
+
if (link && !config.providers.length) pins = (await db.prepare('SELECT provider_id,status FROM oa_identity_providers').all()).results;
|
|
29
|
+
const unlinked = pins.some(pin => pin.provider_id === 'auth' && pin.status === 'unlinked');
|
|
30
|
+
providers.push({ id: 'auth', label: 'Auth', state: !link || unlinked ? 'unlinked' : link.needs_relink || !link.has_key ? 'needs-relink' : 'linked' });
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
return { canEnable: providers.some(provider => ['linked', 'configured'].includes(provider.state)), providers };
|
|
34
|
+
}
|
|
@@ -1,9 +1,18 @@
|
|
|
1
1
|
import { pageResponse } from '../page.mjs';
|
|
2
|
+
import { escapeHtml } from '../http.mjs';
|
|
2
3
|
|
|
3
4
|
// The owner's sign-in settings, in the same frame (and seed theme) as sign-in.
|
|
4
|
-
export function identitySettingsPage({ idpSignIn }, branding) {
|
|
5
|
-
const
|
|
6
|
-
|
|
5
|
+
export function identitySettingsPage({ idpSignIn, providerSetup }, branding, { saved = false, error, status = 200, method = 'GET' } = {}) {
|
|
6
|
+
const states = { linked: 'Linked', configured: 'Configured · connects on first sign-in', unlinked: 'Not linked', 'needs-relink': 'Link needs setup again' };
|
|
7
|
+
const notice = error ? '<p class="notice" role="alert">Provider sign-in could not be enabled. Link or relink your identity provider, then try again.</p>'
|
|
8
|
+
: saved ? `<p class="notice" role="status">Settings saved. Provider sign-in is ${idpSignIn ? 'on' : 'off'}.</p>` : '';
|
|
9
|
+
const setup = providerSetup.providers.length
|
|
10
|
+
? providerSetup.providers.map(provider => `<p>${escapeHtml(provider.label)}: ${states[provider.state]}</p>`).join('')
|
|
11
|
+
: '<p>No identity provider is configured.</p>';
|
|
12
|
+
const content = notice + '<p>Allow invited people to sign in through your linked identity provider. Email links remain available to the owner.</p>'
|
|
13
|
+
+ '<h2>Provider setup</h2>' + setup
|
|
14
|
+
+ (!providerSetup.canEnable ? '<p>Have the installation administrator link or relink a provider through the project’s identity setup, then return here to enable sign-in.</p>' : '')
|
|
15
|
+
+ `<form action="/auth/settings/identity" method="post"><input type="hidden" name="setting" value="identity"><label class="check"><input type="checkbox" name="idpSignIn" value="true"${idpSignIn ? ' checked' : ''}${!providerSetup.canEnable && !idpSignIn ? ' disabled' : ''}>Allow provider sign-in</label><button>Save settings</button></form>`
|
|
7
16
|
+ '<p class="secondary-link"><a href="/app">Back to app</a></p>';
|
|
8
|
-
return pageResponse({ branding, title: 'Sign-in settings', heading: 'Sign-in settings', content, referrer: 'strict-origin' });
|
|
17
|
+
return pageResponse({ branding, title: 'Sign-in settings', heading: 'Sign-in settings', content, status, method, referrer: 'strict-origin' });
|
|
9
18
|
}
|
|
@@ -35,7 +35,7 @@ without a theme its CSP adds only `img-src 'self'`. Every other resource rule
|
|
|
35
35
|
above still applies, and mail stays image-free.
|
|
36
36
|
|
|
37
37
|
The Base conformance registration is executable at
|
|
38
|
-
[`../tests/conformance.test.ts`](
|
|
38
|
+
[`../tests/conformance.test.ts`](https://github.com/runeditrun/base/blob/main/modules/operator-auth/tests/conformance.test.ts), and its D1/Worker
|
|
39
39
|
adapter lives in this directory's `tests/worker.mjs` and `tests/runtime.mjs`.
|
|
40
40
|
An adopting seed should map these methods to its actual Hono/Worker dispatcher
|
|
41
41
|
and native private API, then import and call the exported registration from its
|
|
@@ -9,11 +9,13 @@ import { AuthError } from '../errors.mjs';
|
|
|
9
9
|
import { hashToken, opaqueToken } from '../crypto.mjs';
|
|
10
10
|
import { readCookie, sessionCookie, isLoopbackHost } from '../http.mjs';
|
|
11
11
|
import { safeReturnTo } from '../policy.mjs';
|
|
12
|
-
import { isActiveOperator, defaultRolePolicy } from '../accounts/roles.mjs';
|
|
12
|
+
import { isActiveOperator, emailAllowed, defaultRolePolicy } from '../accounts/roles.mjs';
|
|
13
13
|
import { devGate, devNotFound } from '../dev-gate.mjs';
|
|
14
14
|
import { registerDevAdmission } from '../dev-admission.mjs';
|
|
15
15
|
import { definePersonas } from './personas.mjs';
|
|
16
16
|
import { cliSession } from './cli-session.mjs';
|
|
17
|
+
import { signInRefusal } from './refusal.mjs';
|
|
18
|
+
import { representation } from '../representation.mjs';
|
|
17
19
|
import { decorateLabel } from '../../demo/label.mjs';
|
|
18
20
|
import { oneClickPage } from '../signin/one-click.mjs';
|
|
19
21
|
|
|
@@ -68,7 +70,13 @@ export function withDevIdentity(worker, { bindings = env => env, config: authCon
|
|
|
68
70
|
const response = path === '/auth/local/cli-session' ? await cliSession(request, context, headers) : path === '/__dev/personas' ? Response.json(await context.list(request), { headers }) : await enter(request, gate, context);
|
|
69
71
|
return rejectedResponse(request, response);
|
|
70
72
|
} catch (error) {
|
|
71
|
-
if (error instanceof AuthError)
|
|
73
|
+
if (error instanceof AuthError) {
|
|
74
|
+
if (path === '/auth/dev/enter' && representation(request) === 'html') return rejectedResponse(request, await signInRefusal(request, context.config.branding, {
|
|
75
|
+
status: error.status,
|
|
76
|
+
message: 'This account can no longer use this sign-in link. Choose an available account, or ask an owner or administrator to restore its access.',
|
|
77
|
+
}));
|
|
78
|
+
return rejectedResponse(request, Response.json({ error: error.code }, { status: error.status, headers }));
|
|
79
|
+
}
|
|
72
80
|
throw error;
|
|
73
81
|
}
|
|
74
82
|
}
|
|
@@ -109,8 +117,15 @@ function identity(env, authConfig, declared) {
|
|
|
109
117
|
return { ...actor, hash: await hash(readCookie(request, config)) };
|
|
110
118
|
},
|
|
111
119
|
async list(request) {
|
|
112
|
-
const personas = (await everyone()).map(({ as, email, role }) => ({ as, email, ...(role ? { role } : {}) }));
|
|
113
120
|
const people = await auth.oneClick.people(request);
|
|
121
|
+
const personas = (await Promise.all((await everyone()).map(async ({ as, email, role }) => {
|
|
122
|
+
// Existing identities keep their real admission state. A declaration
|
|
123
|
+
// must never bring back an inactive account or an expired invitation.
|
|
124
|
+
const operator = email && await store.byEmail(email);
|
|
125
|
+
const person = people?.find(person => person.email === email);
|
|
126
|
+
if (email && (!emailAllowed(email, config.allowList) || (operator && !person))) return null;
|
|
127
|
+
return { as, email, ...(role ? { role: person?.role ?? role } : {}) };
|
|
128
|
+
}))).filter(Boolean);
|
|
114
129
|
return [...personas, ...(people ?? []).filter(person => !personas.some(p => p.email === person.email))
|
|
115
130
|
.map(person => ({ as: person.email, email: person.email, role: person.role })), { as: 'signed-out' }];
|
|
116
131
|
},
|
|
@@ -159,7 +174,10 @@ async function enter(request, gate, { config, store, hash, current, everyone, ow
|
|
|
159
174
|
operator = await store.byEmail(persona.email);
|
|
160
175
|
}
|
|
161
176
|
if (!operator) return text(409, 'The owner that rer setup claimed is not in this database. Run rer setup.');
|
|
162
|
-
if (!isActiveOperator(operator, config.allowList)) return
|
|
177
|
+
if (!isActiveOperator(operator, config.allowList)) return signInRefusal(request, config.branding, {
|
|
178
|
+
status: 403,
|
|
179
|
+
message: 'This account is inactive or no longer allowed to sign in to this app. Choose another account, or ask an owner or administrator to restore its access.',
|
|
180
|
+
});
|
|
163
181
|
const domain = operator.email.slice(operator.email.lastIndexOf('@') + 1);
|
|
164
182
|
if (operator.role !== 'owner' && await store.domainRule(domain)) return text(403, 'Sign-in refused');
|
|
165
183
|
if (existing?.kind !== 'dev' || existing.operator.id !== operator.id) {
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import { escapeHtml, securityHeaders } from '../http.mjs';
|
|
2
|
+
import { pageResponse } from '../page.mjs';
|
|
3
|
+
import { safeReturnTo } from '../policy.mjs';
|
|
4
|
+
import { representation } from '../representation.mjs';
|
|
5
|
+
|
|
6
|
+
// Stale local persona links can outlive the account's access. Browser visits
|
|
7
|
+
// receive the same frame as sign-in, with a path back to the current choices.
|
|
8
|
+
export async function signInRefusal(request, branding, { status, message }) {
|
|
9
|
+
const chosen = representation(request, 'text');
|
|
10
|
+
if (chosen === 'json') return Response.json({ error: 'sign_in_refused' }, { status, headers: securityHeaders() });
|
|
11
|
+
if (chosen === 'text') return new Response(message, {
|
|
12
|
+
status, headers: { ...securityHeaders(), 'content-type': 'text/plain; charset=utf-8' },
|
|
13
|
+
});
|
|
14
|
+
const next = new URL(branding.signInPath, request.url);
|
|
15
|
+
next.searchParams.set('returnTo', safeReturnTo(new URL(request.url).searchParams.get('returnTo')));
|
|
16
|
+
return pageResponse({ branding, status, heading: 'This account cannot sign in',
|
|
17
|
+
content: `<p>${escapeHtml(message)}</p><a class="action" href="${escapeHtml(next.pathname + next.search)}">Choose another account</a>`,
|
|
18
|
+
});
|
|
19
|
+
}
|
|
@@ -13,8 +13,8 @@ credential cleanup data. See the [migration and cancellation contract](../README
|
|
|
13
13
|
|
|
14
14
|
Use the standard Worker secrets `OWNER_EMAIL`, `SESSION_SECRET`, and
|
|
15
15
|
`SETUP_TOKEN`. Generate independent random values of at least 32 bytes for the
|
|
16
|
-
two secrets; retain
|
|
17
|
-
`SETUP_TOKEN` after bootstrap.
|
|
16
|
+
two secrets; retain `OWNER_EMAIL` and the stable `SESSION_SECRET` after
|
|
17
|
+
first-owner setup, and remove `SETUP_TOKEN` after bootstrap.
|
|
18
18
|
They belong in server bindings, never `VITE_*`, rendered HTML, loaders, browser
|
|
19
19
|
storage, logs or responses. Bootstrap creates only the configured owner and its
|
|
20
20
|
session. It runs without mail and does not populate product tables. Invoke the
|
|
@@ -36,9 +36,10 @@ attempt; the auth core does not retry it.
|
|
|
36
36
|
|
|
37
37
|
`OWNER_EMAIL` is the first owner. The default roles are `owner`, `admin`, and
|
|
38
38
|
`member`. Configure `allowList` only as an additional admission restriction; it
|
|
39
|
-
does not grant access.
|
|
40
|
-
policy variations
|
|
41
|
-
|
|
39
|
+
does not grant access. Pass a deterministic `rolePolicy` option to
|
|
40
|
+
`createOperatorAuth` for product policy variations; `defaultRolePolicy` is the
|
|
41
|
+
exported default. Preserve the module's active-session, allow-list, version-fence
|
|
42
|
+
and last-owner checks.
|
|
42
43
|
|
|
43
44
|
Follow one of these integration recipes:
|
|
44
45
|
|
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
Keep auth, D1, mail construction and Worker bindings in server-owned modules.
|
|
4
4
|
The client-importable server-function wrapper may be a normal `.ts` file, but
|
|
5
5
|
load true server modules dynamically inside each handler, following
|
|
6
|
-
[`TANSTACK-START-MIGRATION.md`](
|
|
6
|
+
[`TANSTACK-START-MIGRATION.md`](https://github.com/runeditrun/base/blob/main/TANSTACK-START-MIGRATION.md). A route's
|
|
7
7
|
parent session check protects its document; every child server function that
|
|
8
8
|
reads or changes private data must check the session again before its first
|
|
9
9
|
private operation.
|
|
@@ -129,12 +129,11 @@ Pass the actual `createMailSender` result directly to the auth core. An
|
|
|
129
129
|
`503 mail_unavailable`; there is no fallback or automatic retry. Resolve an
|
|
130
130
|
uncertain attempt before requesting another link.
|
|
131
131
|
|
|
132
|
-
Optional OIDC remains server-side: configure
|
|
133
|
-
|
|
134
|
-
`createAuthHandler
|
|
135
|
-
|
|
136
|
-
subjectEmails
|
|
137
|
-
contract. An existing issuer/subject binding may sign in again, while a
|
|
132
|
+
Optional OIDC remains server-side: configure `config.providers` and an
|
|
133
|
+
independent `OIDC_TRANSACTION_SECRET` on `createOperatorAuth`;
|
|
134
|
+
`createAuthHandler` serves the provider routes. Preserve every `Set-Cookie`
|
|
135
|
+
header individually. See the [OIDC guide](../identity/oidc/README.md) for provider
|
|
136
|
+
configuration and trusted `subjectEmails` mappings. An existing issuer/subject binding may sign in again, while a
|
|
138
137
|
different principal cannot join an already-bound operator by presenting the same
|
|
139
138
|
verified email. Configure any subject-to-existing-email association from trusted
|
|
140
139
|
server configuration, never callback or browser input. Do not expose its
|
|
@@ -155,7 +155,7 @@ export interface OperatorAuth<R extends string = Role> {
|
|
|
155
155
|
authenticateCredential(request:Request):Promise<{id:string;personId:string;fence:number;kind:SessionKind}|null>;
|
|
156
156
|
authorizeDependencySetup(request: Request, input: { token?: string }): Promise<boolean>;
|
|
157
157
|
completeLocalSetup(request:Request):Promise<{complete:boolean}>;
|
|
158
|
-
identitySettings(request:Request):Promise<{idpSignIn:boolean}>;
|
|
158
|
+
identitySettings(request:Request):Promise<{idpSignIn:boolean;providerSetup:{canEnable:boolean;providers:Array<{id:string;label:string;state:'linked'|'configured'|'unlinked'|'needs-relink'}>}}>;
|
|
159
159
|
setIdentitySettings(request:Request,input:{idpSignIn:boolean}):Promise<{idpSignIn:boolean}>;
|
|
160
160
|
requireEditorOwner(request:Request):Promise<Session<R>>;
|
|
161
161
|
credentialFence(request:Request):Promise<{personId:string;fence:number;kind:SessionKind}>;
|
|
@@ -36,3 +36,17 @@ export async function pageResponse({ branding, title, heading, content, status =
|
|
|
36
36
|
if (referrer) headers['Referrer-Policy'] = referrer;
|
|
37
37
|
return new Response(method === 'HEAD' ? null : html, { status, headers });
|
|
38
38
|
}
|
|
39
|
+
|
|
40
|
+
// Refusals on private document routes use the same frame as sign-in. The API
|
|
41
|
+
// adapter keeps its typed JSON response for callers that did not ask for HTML.
|
|
42
|
+
export function settingsRefusalPage(request, branding, code, status) {
|
|
43
|
+
const ownerOnly = code === 'owner_required';
|
|
44
|
+
const unauthenticated = code === 'unauthenticated';
|
|
45
|
+
const heading = ownerOnly ? 'Only the owner can change sign-in settings' : unauthenticated ? 'Sign in to view these settings' : 'Settings could not be changed';
|
|
46
|
+
const message = ownerOnly ? 'Your account can use the app. Ask the installation owner to manage identity providers.'
|
|
47
|
+
: unauthenticated ? 'Your session has ended or you are signed out. Sign in, then open settings again.'
|
|
48
|
+
: 'The request was refused and no settings were saved. Return to the app, reload settings and try again.';
|
|
49
|
+
const href = unauthenticated ? branding.signInPath : '/app';
|
|
50
|
+
return pageResponse({ branding, heading, status, method: request.method,
|
|
51
|
+
content: `<p>${message}</p><a class="action" href="${escapeHtml(href)}">${unauthenticated ? 'Sign in' : 'Back to app'}</a>` });
|
|
52
|
+
}
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
const token = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;
|
|
2
|
+
const quality = /^(?:0(?:\.[0-9]{0,3})?|1(?:\.0{0,3})?)$/;
|
|
3
|
+
|
|
4
|
+
// Commas and semicolons inside quoted parameter values are not separators.
|
|
5
|
+
function split(value, separator) {
|
|
6
|
+
const parts = [];
|
|
7
|
+
let start = 0, quoted = false, escaped = false;
|
|
8
|
+
for (let i = 0; i < value.length; i++) {
|
|
9
|
+
const char = value[i];
|
|
10
|
+
if (escaped) escaped = false;
|
|
11
|
+
else if (quoted && char === '\\') escaped = true;
|
|
12
|
+
else if (char === '"') quoted = !quoted;
|
|
13
|
+
else if (!quoted && char === separator) { parts.push(value.slice(start, i)); start = i + 1; }
|
|
14
|
+
}
|
|
15
|
+
return quoted || escaped ? null : [...parts, value.slice(start)];
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
function ranges(value) {
|
|
19
|
+
if (/[\u0000-\u0008\u000a-\u001f\u007f]/.test(value)) return null;
|
|
20
|
+
const members = split(value, ',');
|
|
21
|
+
if (!members) return null;
|
|
22
|
+
const result = [];
|
|
23
|
+
for (const member of members) {
|
|
24
|
+
if (!member.trim()) continue; // RFC 9110 list syntax permits empty members.
|
|
25
|
+
const parts = split(member, ';');
|
|
26
|
+
if (!parts) return null;
|
|
27
|
+
const media = parts.shift().trim().toLowerCase().split('/');
|
|
28
|
+
if (media.length !== 2 || !media.every(part => token.test(part)) || (media[0] === '*' && media[1] !== '*')) return null;
|
|
29
|
+
const parameters = new Map();
|
|
30
|
+
let q = 1, weighted = false;
|
|
31
|
+
for (const part of parts) {
|
|
32
|
+
if (!part.trim()) continue;
|
|
33
|
+
const at = part.indexOf('='), name = part.slice(0, at).trim().toLowerCase(), raw = part.slice(at + 1).trim();
|
|
34
|
+
if (at < 0 || !token.test(name)) return null;
|
|
35
|
+
if (name === 'q') {
|
|
36
|
+
if (weighted || !quality.test(raw)) return null;
|
|
37
|
+
q = Number(raw); weighted = true;
|
|
38
|
+
} else {
|
|
39
|
+
if (parameters.has(name)) return null;
|
|
40
|
+
const quoted = /^"(?:[\t !#-\[\]-~\u0080-\u00ff]|\\[\t\x20-\x7e\u0080-\u00ff])*"$/.test(raw);
|
|
41
|
+
if (!token.test(raw) && !quoted) return null;
|
|
42
|
+
parameters.set(name, quoted ? raw.slice(1, -1).replace(/\\(.)/g, '$1') : raw);
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
result.push({ media, parameters, q, order: result.length });
|
|
46
|
+
}
|
|
47
|
+
return result;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
function preference(accepted, type, subtype) {
|
|
51
|
+
let best = { q: 0, specificity: -1, parameters: -1, order: Infinity };
|
|
52
|
+
for (const range of accepted) {
|
|
53
|
+
if ((range.media[0] !== '*' && range.media[0] !== type) || (range.media[1] !== '*' && range.media[1] !== subtype)) continue;
|
|
54
|
+
// Both responses are UTF-8; other media parameters are not supplied.
|
|
55
|
+
if ([...range.parameters].some(([name, value]) => name !== 'charset' || value.toLowerCase() !== 'utf-8')) continue;
|
|
56
|
+
const specificity = range.media[0] === '*' ? 0 : range.media[1] === '*' ? 1 : 2;
|
|
57
|
+
const parameters = range.parameters.size;
|
|
58
|
+
// Most specific matching range sets quality, including an explicit q=0.
|
|
59
|
+
// Equally specific duplicate ranges use the first occurrence.
|
|
60
|
+
if (specificity > best.specificity || (specificity === best.specificity && parameters > best.parameters)) {
|
|
61
|
+
best = { q: range.q, specificity, parameters, order: range.order };
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
return best;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* RFC 9110 Accept negotiation for the auth HTML/JSON surfaces. Equal quality
|
|
69
|
+
* prefers specificity, then header order. No preference (absent or wildcard),
|
|
70
|
+
* malformed fields, or no acceptable representation retain the non-HTML route
|
|
71
|
+
* default. Request Content-Type never overrides the response preference.
|
|
72
|
+
*/
|
|
73
|
+
export function representation(request, routeDefault = 'json') {
|
|
74
|
+
const accepted = ranges(request.headers.get('accept') ?? '');
|
|
75
|
+
if (!accepted?.length) return routeDefault;
|
|
76
|
+
const html = preference(accepted, 'text', 'html');
|
|
77
|
+
const json = preference(accepted, 'application', 'json');
|
|
78
|
+
if (!html.q) return html.specificity >= 0 || json.q ? 'json' : routeDefault;
|
|
79
|
+
if (html.q !== json.q) return html.q > json.q ? 'html' : 'json';
|
|
80
|
+
if (html.specificity !== json.specificity) return html.specificity > json.specificity ? 'html' : 'json';
|
|
81
|
+
if (html.parameters !== json.parameters) return html.parameters > json.parameters ? 'html' : 'json';
|
|
82
|
+
return html.order === json.order ? routeDefault : html.order < json.order ? 'html' : 'json';
|
|
83
|
+
}
|
|
@@ -1,5 +1,7 @@
|
|
|
1
1
|
import { rejectedResponse } from './rejected-response.mjs';
|
|
2
2
|
import { identitySettingsPage } from './accounts/settings-page.mjs';
|
|
3
|
+
import { settingsRefusalPage } from './page.mjs';
|
|
4
|
+
import { representation } from './representation.mjs';
|
|
3
5
|
import { confirmationResponse } from './identity/email-link/confirmation.mjs';
|
|
4
6
|
import { createOidcHandler } from './identity/oidc/index.mjs';
|
|
5
7
|
import { AuthError } from './errors.mjs';
|
|
@@ -64,7 +66,12 @@ export function createAuthHandler(auth) {
|
|
|
64
66
|
if (auth.scheduledPolicies && path === '/auth/policy-runs' && request.method === 'GET') return json(await auth.scheduledPolicies.runs(request));
|
|
65
67
|
if (path === '/auth/sessions' && request.method === 'GET') return json(await auth.listSessions(request, readParameters(url.searchParams).operatorId));
|
|
66
68
|
if (path === '/auth/domain-rules' && request.method === 'GET') return json(await auth.listDomainRules(request));
|
|
67
|
-
if (path === '/auth/settings/identity' &&
|
|
69
|
+
if (path === '/auth/settings/identity' && ['GET', 'HEAD'].includes(request.method)) {
|
|
70
|
+
const value = await auth.identitySettings(request);
|
|
71
|
+
return representation(request) === 'html'
|
|
72
|
+
? await identitySettingsPage(value, auth.presentation, { saved: url.searchParams.get('saved') === '1', method: request.method })
|
|
73
|
+
: request.method === 'HEAD' ? new Response(null, { headers: { ...securityHeaders(), 'content-type': 'application/json' } }) : json(value);
|
|
74
|
+
}
|
|
68
75
|
if (path === '/auth/providers' && request.method === 'GET') return json(await auth.listProviders(request));
|
|
69
76
|
const posts = new Set(['/auth/bootstrap', '/auth/magic-link', '/auth/confirm', '/auth/signout', '/auth/invite', '/auth/invite/cancel', '/auth/review-session',
|
|
70
77
|
'/auth/policy/approve', '/auth/policy/revoke', '/auth/operator/status', '/auth/operator/role', '/auth/session/revoke', '/auth/step-up', '/auth/domain-rules', '/auth/providers/unlink', '/auth/providers/relink', '/auth/settings/identity', '/auth/setup-complete', OWNER_SIGNIN_PATH, '/auth/email', '/auth/display-name']);
|
|
@@ -80,7 +87,10 @@ export function createAuthHandler(auth) {
|
|
|
80
87
|
switch (path) {
|
|
81
88
|
case '/auth/policy/approve': return json(await auth.scheduledPolicies.approve(request, input));
|
|
82
89
|
case '/auth/policy/revoke': await auth.scheduledPolicies.revoke(request, input); return json({ revoked: true });
|
|
83
|
-
case '/auth/settings/identity': {
|
|
90
|
+
case '/auth/settings/identity': {
|
|
91
|
+
const value = await auth.setIdentitySettings(request, formPost(request) ? { idpSignIn: input.idpSignIn === 'true' } : input);
|
|
92
|
+
return formPost(request) ? seeOther('/auth/settings/identity?saved=1') : json(value);
|
|
93
|
+
}
|
|
84
94
|
case '/auth/setup-complete': return json(await auth.completeLocalSetup(request));
|
|
85
95
|
case '/auth/bootstrap': { const value = await auth.bootstrap(request, input); return seeOther(value.returnTo, value.cookie); }
|
|
86
96
|
case '/auth/magic-link': {
|
|
@@ -118,6 +128,15 @@ export function createAuthHandler(auth) {
|
|
|
118
128
|
case '/auth/providers/relink': return json(await auth.relinkProvider(request, input));
|
|
119
129
|
}
|
|
120
130
|
} catch (error) {
|
|
131
|
+
if (path === '/auth/settings/identity' && representation(request) === 'html') {
|
|
132
|
+
const code = error instanceof AuthError ? error.code : 'auth_unavailable';
|
|
133
|
+
const status = error instanceof AuthError ? error.status : 503;
|
|
134
|
+
if (code === 'provider_unlinked') {
|
|
135
|
+
try { return await identitySettingsPage(await auth.identitySettings(request), auth.presentation, { error: code, status, method: request.method }); }
|
|
136
|
+
catch { return settingsRefusalPage(request, auth.presentation, 'auth_unavailable', 503); }
|
|
137
|
+
}
|
|
138
|
+
return settingsRefusalPage(request, auth.presentation, code, status);
|
|
139
|
+
}
|
|
121
140
|
if (form) return seeOther(notice(auth, error instanceof AuthError ? error.code : 'auth_unavailable'));
|
|
122
141
|
if (error instanceof AuthError) return json({ error: error.code }, error.status);
|
|
123
142
|
// Do not put SQL, email addresses, setup tokens or provider exceptions on the wire.
|
|
@@ -126,6 +145,10 @@ export function createAuthHandler(auth) {
|
|
|
126
145
|
};
|
|
127
146
|
return async function(request) {
|
|
128
147
|
const response = await handleAuth(request);
|
|
148
|
+
if (response && request.method === 'HEAD' && new URL(request.url).pathname === '/auth/settings/identity') {
|
|
149
|
+
void response.body?.cancel();
|
|
150
|
+
return rejectedResponse(request, new Response(null, { status: response.status, headers: response.headers }));
|
|
151
|
+
}
|
|
129
152
|
return response ? rejectedResponse(request, response) : response;
|
|
130
153
|
};
|
|
131
154
|
}
|