@hexclave/shared 1.0.2 → 1.0.5
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/dist/ai/unified-prompts/reminders.js +4 -3
- package/dist/ai/unified-prompts/reminders.js.map +1 -1
- package/dist/ai/unified-prompts/skill-site-prompt-parts/ai-setup-prompt.d.ts +3 -1
- package/dist/ai/unified-prompts/skill-site-prompt-parts/ai-setup-prompt.d.ts.map +1 -1
- package/dist/ai/unified-prompts/skill-site-prompt-parts/ai-setup-prompt.js +217 -30
- package/dist/ai/unified-prompts/skill-site-prompt-parts/ai-setup-prompt.js.map +1 -1
- package/dist/ai/unified-prompts/skill-site-prompt-parts/docs-index.d.ts.map +1 -1
- package/dist/ai/unified-prompts/skill-site-prompt-parts/docs-index.js +1 -0
- package/dist/ai/unified-prompts/skill-site-prompt-parts/docs-index.js.map +1 -1
- package/dist/ai/unified-prompts/skill-site-prompt-parts/docs-json.generated.d.ts +18 -6
- package/dist/ai/unified-prompts/skill-site-prompt-parts/docs-json.generated.js +23 -8
- package/dist/ai/unified-prompts/skill-site-prompt-parts/docs-json.generated.js.map +1 -1
- package/dist/ai/unified-prompts/skill-site-prompt-parts/openapi-specs.js +1 -1
- package/dist/ai/unified-prompts/skill-site-prompt-parts/openapi-specs.js.map +1 -1
- package/dist/config/schema.d.ts +63 -63
- package/dist/config/schema.d.ts.map +1 -1
- package/dist/config/schema.js +5 -5
- package/dist/config/schema.js.map +1 -1
- package/dist/config-authoring.d.ts +4 -4
- package/dist/config-authoring.d.ts.map +1 -1
- package/dist/config-authoring.js +2 -2
- package/dist/config-authoring.js.map +1 -1
- package/dist/config-rendering.d.ts +4 -4
- package/dist/config-rendering.d.ts.map +1 -1
- package/dist/config-rendering.js +19 -18
- package/dist/config-rendering.js.map +1 -1
- package/dist/esm/ai/unified-prompts/reminders.js +4 -3
- package/dist/esm/ai/unified-prompts/reminders.js.map +1 -1
- package/dist/esm/ai/unified-prompts/skill-site-prompt-parts/ai-setup-prompt.d.ts +3 -1
- package/dist/esm/ai/unified-prompts/skill-site-prompt-parts/ai-setup-prompt.d.ts.map +1 -1
- package/dist/esm/ai/unified-prompts/skill-site-prompt-parts/ai-setup-prompt.js +216 -31
- package/dist/esm/ai/unified-prompts/skill-site-prompt-parts/ai-setup-prompt.js.map +1 -1
- package/dist/esm/ai/unified-prompts/skill-site-prompt-parts/docs-index.d.ts.map +1 -1
- package/dist/esm/ai/unified-prompts/skill-site-prompt-parts/docs-index.js +1 -0
- package/dist/esm/ai/unified-prompts/skill-site-prompt-parts/docs-index.js.map +1 -1
- package/dist/esm/ai/unified-prompts/skill-site-prompt-parts/docs-json.generated.d.ts +18 -6
- package/dist/esm/ai/unified-prompts/skill-site-prompt-parts/docs-json.generated.js +23 -8
- package/dist/esm/ai/unified-prompts/skill-site-prompt-parts/docs-json.generated.js.map +1 -1
- package/dist/esm/ai/unified-prompts/skill-site-prompt-parts/openapi-specs.js +1 -1
- package/dist/esm/ai/unified-prompts/skill-site-prompt-parts/openapi-specs.js.map +1 -1
- package/dist/esm/config/schema.d.ts +63 -63
- package/dist/esm/config/schema.d.ts.map +1 -1
- package/dist/esm/config/schema.js +5 -5
- package/dist/esm/config/schema.js.map +1 -1
- package/dist/esm/config-authoring.d.ts +4 -4
- package/dist/esm/config-authoring.d.ts.map +1 -1
- package/dist/esm/config-authoring.js +2 -2
- package/dist/esm/config-authoring.js.map +1 -1
- package/dist/esm/config-rendering.d.ts +4 -4
- package/dist/esm/config-rendering.d.ts.map +1 -1
- package/dist/esm/config-rendering.js +15 -14
- package/dist/esm/config-rendering.js.map +1 -1
- package/dist/esm/helpers/vault/client-side.d.ts.map +1 -1
- package/dist/esm/helpers/vault/client-side.js.map +1 -1
- package/dist/esm/helpers/vault/server-side.d.ts.map +1 -1
- package/dist/esm/helpers/vault/server-side.js.map +1 -1
- package/dist/esm/hexclave-config-file.d.ts +15 -0
- package/dist/esm/hexclave-config-file.d.ts.map +1 -0
- package/dist/esm/{stack-config-file.js → hexclave-config-file.js} +7 -7
- package/dist/esm/hexclave-config-file.js.map +1 -0
- package/dist/esm/hooks/use-async-callback.js +1 -1
- package/dist/esm/hooks/use-async-external-store.js +1 -1
- package/dist/esm/hooks/use-strict-memo.js +1 -1
- package/dist/esm/interface/admin-metrics.d.ts +8 -8
- package/dist/esm/interface/admin-metrics.js.map +1 -1
- package/dist/esm/interface/client-interface.js +2 -2
- package/dist/esm/interface/client-interface.js.map +1 -1
- package/dist/esm/interface/conversations.d.ts +32 -32
- package/dist/esm/interface/crud/current-user.d.ts +9 -9
- package/dist/esm/interface/crud/email-outbox.d.ts +200 -200
- package/dist/esm/interface/crud/products.d.ts +13 -13
- package/dist/esm/interface/crud/products.d.ts.map +1 -1
- package/dist/esm/interface/crud/project-api-keys.d.ts +4 -4
- package/dist/esm/interface/crud/project-permissions.js +5 -5
- package/dist/esm/interface/crud/project-permissions.js.map +1 -1
- package/dist/esm/interface/crud/projects.d.ts +36 -36
- package/dist/esm/interface/crud/team-member-profiles.d.ts +18 -18
- package/dist/esm/interface/crud/team-permissions.js +5 -5
- package/dist/esm/interface/crud/team-permissions.js.map +1 -1
- package/dist/esm/interface/crud/transactions.d.ts +6 -6
- package/dist/esm/interface/crud/transactions.d.ts.map +1 -1
- package/dist/esm/interface/crud/users.d.ts +12 -12
- package/dist/esm/interface/page-component-versions.js +107 -107
- package/dist/esm/interface/page-component-versions.js.map +1 -1
- package/dist/esm/interface/webhooks.d.ts +2 -2
- package/dist/esm/known-errors.d.ts +2 -2
- package/dist/esm/known-errors.js +4 -4
- package/dist/esm/known-errors.js.map +1 -1
- package/dist/esm/schema-fields.d.ts +17 -7
- package/dist/esm/schema-fields.d.ts.map +1 -1
- package/dist/esm/schema-fields.js +26 -16
- package/dist/esm/schema-fields.js.map +1 -1
- package/dist/esm/sessions.d.ts +7 -7
- package/dist/esm/utils/crypto.d.ts.map +1 -1
- package/dist/esm/utils/crypto.js.map +1 -1
- package/dist/esm/utils/currency-constants.d.ts +6 -0
- package/dist/esm/utils/currency-constants.d.ts.map +1 -1
- package/dist/esm/utils/currency-constants.js.map +1 -1
- package/dist/esm/utils/dev-env-state-path.d.ts +3 -3
- package/dist/esm/utils/dev-env-state-path.d.ts.map +1 -1
- package/dist/esm/utils/dev-env-state-path.js +4 -4
- package/dist/esm/utils/dev-env-state-path.js.map +1 -1
- package/dist/esm/utils/errors.js +2 -2
- package/dist/esm/utils/errors.js.map +1 -1
- package/dist/esm/utils/esbuild.d.ts.map +1 -1
- package/dist/esm/utils/esbuild.js +0 -1
- package/dist/esm/utils/esbuild.js.map +1 -1
- package/dist/esm/utils/featurebase.d.ts +3 -3
- package/dist/esm/utils/featurebase.d.ts.map +1 -1
- package/dist/esm/utils/featurebase.js +15 -15
- package/dist/esm/utils/featurebase.js.map +1 -1
- package/dist/esm/utils/fs.js +6 -6
- package/dist/esm/utils/fs.js.map +1 -1
- package/dist/esm/utils/globals.d.ts.map +1 -1
- package/dist/esm/utils/globals.js +10 -10
- package/dist/esm/utils/globals.js.map +1 -1
- package/dist/esm/utils/jwt.d.ts.map +1 -1
- package/dist/esm/utils/jwt.js +3 -3
- package/dist/esm/utils/jwt.js.map +1 -1
- package/dist/esm/utils/redirect-urls.d.ts +3 -3
- package/dist/esm/utils/redirect-urls.d.ts.map +1 -1
- package/dist/esm/utils/redirect-urls.js +5 -5
- package/dist/esm/utils/redirect-urls.js.map +1 -1
- package/dist/esm/utils/urls.js.map +1 -1
- package/dist/helpers/vault/client-side.d.ts.map +1 -1
- package/dist/helpers/vault/client-side.js.map +1 -1
- package/dist/helpers/vault/server-side.d.ts.map +1 -1
- package/dist/helpers/vault/server-side.js.map +1 -1
- package/dist/hexclave-config-file.d.ts +15 -0
- package/dist/hexclave-config-file.d.ts.map +1 -0
- package/dist/{stack-config-file.js → hexclave-config-file.js} +8 -8
- package/dist/hexclave-config-file.js.map +1 -0
- package/dist/hooks/use-async-callback.js +1 -1
- package/dist/hooks/use-async-external-store.js +1 -1
- package/dist/hooks/use-strict-memo.js +1 -1
- package/dist/interface/admin-metrics.d.ts +8 -8
- package/dist/interface/admin-metrics.js.map +1 -1
- package/dist/interface/client-interface.js +2 -2
- package/dist/interface/client-interface.js.map +1 -1
- package/dist/interface/conversations.d.ts +32 -32
- package/dist/interface/crud/current-user.d.ts +9 -9
- package/dist/interface/crud/email-outbox.d.ts +200 -200
- package/dist/interface/crud/products.d.ts +13 -13
- package/dist/interface/crud/products.d.ts.map +1 -1
- package/dist/interface/crud/project-api-keys.d.ts +4 -4
- package/dist/interface/crud/project-permissions.js +5 -5
- package/dist/interface/crud/project-permissions.js.map +1 -1
- package/dist/interface/crud/projects.d.ts +36 -36
- package/dist/interface/crud/team-member-profiles.d.ts +18 -18
- package/dist/interface/crud/team-permissions.js +5 -5
- package/dist/interface/crud/team-permissions.js.map +1 -1
- package/dist/interface/crud/transactions.d.ts +6 -6
- package/dist/interface/crud/transactions.d.ts.map +1 -1
- package/dist/interface/crud/users.d.ts +12 -12
- package/dist/interface/page-component-versions.js +107 -107
- package/dist/interface/page-component-versions.js.map +1 -1
- package/dist/interface/webhooks.d.ts +2 -2
- package/dist/known-errors.d.ts +2 -2
- package/dist/known-errors.js +4 -4
- package/dist/known-errors.js.map +1 -1
- package/dist/schema-fields.d.ts +17 -7
- package/dist/schema-fields.d.ts.map +1 -1
- package/dist/schema-fields.js +26 -16
- package/dist/schema-fields.js.map +1 -1
- package/dist/sessions.d.ts +7 -7
- package/dist/utils/crypto.d.ts.map +1 -1
- package/dist/utils/crypto.js.map +1 -1
- package/dist/utils/currency-constants.d.ts +6 -0
- package/dist/utils/currency-constants.d.ts.map +1 -1
- package/dist/utils/currency-constants.js.map +1 -1
- package/dist/utils/dev-env-state-path.d.ts +3 -3
- package/dist/utils/dev-env-state-path.d.ts.map +1 -1
- package/dist/utils/dev-env-state-path.js +5 -5
- package/dist/utils/dev-env-state-path.js.map +1 -1
- package/dist/utils/errors.js +2 -2
- package/dist/utils/errors.js.map +1 -1
- package/dist/utils/esbuild.d.ts.map +1 -1
- package/dist/utils/esbuild.js +0 -1
- package/dist/utils/esbuild.js.map +1 -1
- package/dist/utils/featurebase.d.ts +3 -3
- package/dist/utils/featurebase.d.ts.map +1 -1
- package/dist/utils/featurebase.js +15 -15
- package/dist/utils/featurebase.js.map +1 -1
- package/dist/utils/fs.js.map +1 -1
- package/dist/utils/globals.d.ts.map +1 -1
- package/dist/utils/globals.js +10 -10
- package/dist/utils/globals.js.map +1 -1
- package/dist/utils/jwt.d.ts.map +1 -1
- package/dist/utils/jwt.js +3 -3
- package/dist/utils/jwt.js.map +1 -1
- package/dist/utils/redirect-urls.d.ts +3 -3
- package/dist/utils/redirect-urls.d.ts.map +1 -1
- package/dist/utils/redirect-urls.js +5 -5
- package/dist/utils/redirect-urls.js.map +1 -1
- package/dist/utils/urls.js.map +1 -1
- package/package.json +2 -1
- package/src/ai/image-limits.ts +62 -0
- package/src/ai/llms/llms.ts +36 -0
- package/src/ai/unified-prompts/reminders.ts +27 -0
- package/src/ai/unified-prompts/skill-site-prompt-parts/ai-setup-prompt.ts +1047 -0
- package/src/ai/unified-prompts/skill-site-prompt-parts/brain.ts +5 -0
- package/src/ai/unified-prompts/skill-site-prompt-parts/cli-help.ts +5 -0
- package/src/ai/unified-prompts/skill-site-prompt-parts/config-docs.ts +5 -0
- package/src/ai/unified-prompts/skill-site-prompt-parts/custom-components-instructions.ts +5 -0
- package/src/ai/unified-prompts/skill-site-prompt-parts/dashboard-instructions.ts +5 -0
- package/src/ai/unified-prompts/skill-site-prompt-parts/docs-index.ts +80 -0
- package/src/ai/unified-prompts/skill-site-prompt-parts/docs-json.generated.ts +322 -0
- package/src/ai/unified-prompts/skill-site-prompt-parts/openapi-specs.ts +5 -0
- package/src/ai/unified-prompts/skill-site-prompt-parts/sdk-interface-source.ts +5 -0
- package/src/ai/unified-prompts/skill-site-prompt.ts +72 -0
- package/src/apps/apps-config.ts +177 -0
- package/src/apps/apps-ui.tsx +112 -0
- package/src/config/README.md +154 -0
- package/src/config/db-sync-mappings.ts +2293 -0
- package/src/config/format.ts +388 -0
- package/src/config/migrate-catalogs-to-product-lines.ts +475 -0
- package/src/config/schema-fuzzer.test.ts +377 -0
- package/src/config/schema.ts +1507 -0
- package/src/config-authoring.test.ts +52 -0
- package/src/config-authoring.ts +37 -0
- package/src/config-rendering.ts +142 -0
- package/src/crud.tsx +275 -0
- package/src/global.d.ts +1 -0
- package/src/helpers/emails.ts +250 -0
- package/src/helpers/init-prompt.ts +39 -0
- package/src/helpers/password.ts +16 -0
- package/src/helpers/production-mode.ts +58 -0
- package/src/helpers/support-sla.test.ts +124 -0
- package/src/helpers/support-sla.ts +93 -0
- package/src/helpers/vault/client-side.ts +92 -0
- package/src/helpers/vault/server-side.ts +153 -0
- package/src/hexclave-config-file.ts +120 -0
- package/src/hooks/use-async-callback.tsx +43 -0
- package/src/hooks/use-async-external-store.tsx +24 -0
- package/src/hooks/use-hash.tsx +14 -0
- package/src/hooks/use-hover.tsx +88 -0
- package/src/hooks/use-strict-memo.tsx +157 -0
- package/src/index.ts +17 -0
- package/src/interface/admin-interface.ts +1043 -0
- package/src/interface/admin-metrics.ts +214 -0
- package/src/interface/client-interface.test.ts +765 -0
- package/src/interface/client-interface.ts +2586 -0
- package/src/interface/conversations.ts +109 -0
- package/src/interface/crud/analytics.ts +11 -0
- package/src/interface/crud/connected-accounts.ts +52 -0
- package/src/interface/crud/contact-channels.ts +74 -0
- package/src/interface/crud/current-user.ts +72 -0
- package/src/interface/crud/email-outbox.ts +263 -0
- package/src/interface/crud/email-templates.ts +50 -0
- package/src/interface/crud/emails.ts +22 -0
- package/src/interface/crud/internal-api-keys.ts +69 -0
- package/src/interface/crud/invoices.ts +36 -0
- package/src/interface/crud/items.ts +24 -0
- package/src/interface/crud/notification-preferences.ts +33 -0
- package/src/interface/crud/oauth-providers.ts +91 -0
- package/src/interface/crud/products.ts +42 -0
- package/src/interface/crud/project-api-keys.ts +100 -0
- package/src/interface/crud/project-permissions.ts +118 -0
- package/src/interface/crud/projects.ts +229 -0
- package/src/interface/crud/session-replays.ts +85 -0
- package/src/interface/crud/sessions.ts +66 -0
- package/src/interface/crud/sign-up-rules.ts +12 -0
- package/src/interface/crud/svix-token.ts +20 -0
- package/src/interface/crud/team-invitation-details.ts +22 -0
- package/src/interface/crud/team-invitation.ts +35 -0
- package/src/interface/crud/team-member-profiles.ts +61 -0
- package/src/interface/crud/team-memberships.ts +56 -0
- package/src/interface/crud/team-permissions.ts +119 -0
- package/src/interface/crud/teams.ts +142 -0
- package/src/interface/crud/transactions.ts +131 -0
- package/src/interface/crud/users.ts +185 -0
- package/src/interface/handler-urls.ts +74 -0
- package/src/interface/page-component-versions.ts +1702 -0
- package/src/interface/server-interface.ts +1146 -0
- package/src/interface/webhooks.ts +28 -0
- package/src/known-errors.tsx +2031 -0
- package/src/local-emulator.ts +5 -0
- package/src/payments/payment-methods.ts +167 -0
- package/src/payments/stripe-limits.ts +18 -0
- package/src/plans.ts +107 -0
- package/src/schema-fields.ts +944 -0
- package/src/sessions.ts +310 -0
- package/src/utils/api-keys.tsx +122 -0
- package/src/utils/arrays.tsx +248 -0
- package/src/utils/auth-methods.ts +8 -0
- package/src/utils/base64.tsx +24 -0
- package/src/utils/booleans.tsx +34 -0
- package/src/utils/browser-compat.tsx +17 -0
- package/src/utils/bytes.tsx +280 -0
- package/src/utils/caches.tsx +280 -0
- package/src/utils/cel-fields.ts +92 -0
- package/src/utils/cloud-hosts.tsx +92 -0
- package/src/utils/compile-time.tsx +11 -0
- package/src/utils/country-codes.ts +39 -0
- package/src/utils/crypto.tsx +174 -0
- package/src/utils/currencies.tsx +53 -0
- package/src/utils/currency-constants.tsx +51 -0
- package/src/utils/dates.tsx +246 -0
- package/src/utils/dev-env-state-path.ts +14 -0
- package/src/utils/dom.tsx +7 -0
- package/src/utils/env.tsx +117 -0
- package/src/utils/errors.tsx +284 -0
- package/src/utils/esbuild.tsx +235 -0
- package/src/utils/featurebase.tsx +247 -0
- package/src/utils/fs.tsx +33 -0
- package/src/utils/functions.tsx +22 -0
- package/src/utils/geo.tsx +16 -0
- package/src/utils/globals.tsx +48 -0
- package/src/utils/hashes.tsx +52 -0
- package/src/utils/html.tsx +60 -0
- package/src/utils/http.tsx +91 -0
- package/src/utils/ips.tsx +47 -0
- package/src/utils/json.tsx +200 -0
- package/src/utils/jsx-editable-transpiler.test.ts +156 -0
- package/src/utils/jsx-editable-transpiler.tsx +401 -0
- package/src/utils/jwt.tsx +170 -0
- package/src/utils/locks.tsx +71 -0
- package/src/utils/maps.tsx +407 -0
- package/src/utils/math.tsx +18 -0
- package/src/utils/monkey-patch.tsx +29 -0
- package/src/utils/node-http.tsx +47 -0
- package/src/utils/numbers.tsx +82 -0
- package/src/utils/oauth.tsx +9 -0
- package/src/utils/objects.tsx +581 -0
- package/src/utils/paginated-lists.test.ts +1039 -0
- package/src/utils/paginated-lists.tsx +479 -0
- package/src/utils/passkey.tsx +1 -0
- package/src/utils/promises.tsx +540 -0
- package/src/utils/proxies.tsx +212 -0
- package/src/utils/react.tsx +308 -0
- package/src/utils/redirect-urls.tsx +299 -0
- package/src/utils/regex.tsx +10 -0
- package/src/utils/results.tsx +411 -0
- package/src/utils/sentry.tsx +20 -0
- package/src/utils/stores.tsx +238 -0
- package/src/utils/strings.nicify.test.ts +253 -0
- package/src/utils/strings.tsx +723 -0
- package/src/utils/telemetry.tsx +37 -0
- package/src/utils/turnstile-browser.ts +106 -0
- package/src/utils/turnstile-flow.test.ts +101 -0
- package/src/utils/turnstile-flow.ts +266 -0
- package/src/utils/turnstile.ts +34 -0
- package/src/utils/typed-arrays.tsx +17 -0
- package/src/utils/types.tsx +208 -0
- package/src/utils/unicode.tsx +24 -0
- package/src/utils/urls.tsx +411 -0
- package/src/utils/uuids.tsx +47 -0
- package/dist/esm/stack-config-file.d.ts +0 -15
- package/dist/esm/stack-config-file.d.ts.map +0 -1
- package/dist/esm/stack-config-file.js.map +0 -1
- package/dist/stack-config-file.d.ts +0 -15
- package/dist/stack-config-file.d.ts.map +0 -1
- package/dist/stack-config-file.js.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"jwt.d.ts","names":[],"sources":["../../../src/utils/jwt.tsx"],"mappings":";;;iBAsBsB,UAAA,CAAW,OAAA;EAC/B,GAAA;AAAA,IACD,OAAA;;;;;;;;;;;;;;;;;;;aAF+B,IAAA,CAAA,UAAA;EAAA;AAAA;;;;;;;;;;iBAeV,OAAA,CAAQ,OAAA;EAC5B,MAAA;EACA,QAAA;EACA,OAAA;EACA,cAAA;AAAA,IACD,OAAA;AAAA,iBAaqB,SAAA,CAAU,OAAA;EAC9B,cAAA;EACA,GAAA;AAAA,IACD,OAAA,CAAA,IAAA,CAAA,UAAA;AAAA,KAYW,UAAA;EACV,GAAA;EACA,GAAA;EACA,GAAA;EACA,GAAA;EACA,CAAA;EACA,CAAA;EACA,CAAA;AAAA;;;;AAPF;iBAgCsB,cAAA,CAAe,OAAA;EACnC,QAAA;AAAA,IACE,OAAA,CAAQ,UAAA;AAAA,
|
|
1
|
+
{"version":3,"file":"jwt.d.ts","names":[],"sources":["../../../src/utils/jwt.tsx"],"mappings":";;;iBAsBsB,UAAA,CAAW,OAAA;EAC/B,GAAA;AAAA,IACD,OAAA;;;;;;;;;;;;;;;;;;;aAF+B,IAAA,CAAA,UAAA;EAAA;AAAA;;;;;;;;;;iBAeV,OAAA,CAAQ,OAAA;EAC5B,MAAA;EACA,QAAA;EACA,OAAA;EACA,cAAA;AAAA,IACD,OAAA;AAAA,iBAaqB,SAAA,CAAU,OAAA;EAC9B,cAAA;EACA,GAAA;AAAA,IACD,OAAA,CAAA,IAAA,CAAA,UAAA;AAAA,KAYW,UAAA;EACV,GAAA;EACA,GAAA;EACA,GAAA;EACA,GAAA;EACA,CAAA;EACA,CAAA;EACA,CAAA;AAAA;;;;AAPF;iBAgCsB,cAAA,CAAe,OAAA;EACnC,QAAA;AAAA,IACE,OAAA,CAAQ,UAAA;AAAA,KA0BA,SAAA;EACV,GAAA;EACA,GAAA;EACA,GAAA;EACA,GAAA;EACA,CAAA;EACA,CAAA;AAAA;AAAA,iBAEoB,eAAA,CAAgB,WAAA,EAAa,UAAA,KAAe,OAAA;EAAU,IAAA,EAAM,SAAA;AAAA;AAAA,iBAsBlE,SAAA,CAAU,OAAA;EACxB,MAAA;AAAA"}
|
package/dist/esm/utils/jwt.js
CHANGED
|
@@ -11,7 +11,7 @@ import elliptic from "elliptic";
|
|
|
11
11
|
import { JOSEError } from "jose/errors";
|
|
12
12
|
|
|
13
13
|
//#region src/utils/jwt.tsx
|
|
14
|
-
function
|
|
14
|
+
function getHexclaveServerSecret() {
|
|
15
15
|
const STACK_SERVER_SECRET = getEnvVariable("STACK_SERVER_SECRET");
|
|
16
16
|
try {
|
|
17
17
|
jose.base64url.decode(STACK_SERVER_SECRET);
|
|
@@ -71,7 +71,7 @@ async function getPrivateJwkFromDerivedSecret(derivedSecret, kid) {
|
|
|
71
71
|
async function getPrivateJwks(options) {
|
|
72
72
|
const getHashOfJwkInfo = (type) => jose.base64url.encode(crypto.createHash("sha256").update(JSON.stringify([
|
|
73
73
|
type,
|
|
74
|
-
|
|
74
|
+
getHexclaveServerSecret(),
|
|
75
75
|
{ audience: options.audience }
|
|
76
76
|
])).digest());
|
|
77
77
|
const perAudienceSecret = getHashOfJwkInfo("stack-jwk-audience-secret");
|
|
@@ -91,7 +91,7 @@ async function getPublicJwkSet(privateJwks) {
|
|
|
91
91
|
}
|
|
92
92
|
function oldGetPerAudienceSecret(options) {
|
|
93
93
|
if (options.audience === "kid") throw new HexclaveAssertionError("You cannot use the 'kid' audience for a per-audience secret, see comment below in jwt.tsx");
|
|
94
|
-
return jose.base64url.encode(crypto.createHash("sha256").update(JSON.stringify([
|
|
94
|
+
return jose.base64url.encode(crypto.createHash("sha256").update(JSON.stringify([getHexclaveServerSecret(), options.audience])).digest());
|
|
95
95
|
}
|
|
96
96
|
function oldGetKid(options) {
|
|
97
97
|
return jose.base64url.encode(crypto.createHash("sha256").update(JSON.stringify([options.secret, "kid"])).digest()).slice(0, 12);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"jwt.js","names":[],"sources":["../../../src/utils/jwt.tsx"],"sourcesContent":["import crypto from \"crypto\";\nimport elliptic from \"elliptic\";\nimport * as jose from \"jose\";\nimport { JOSEError } from \"jose/errors\";\nimport { encodeBase64Url } from \"./bytes\";\nimport { getEnvVariable } from \"./env\";\nimport { HexclaveAssertionError, errorToNiceString } from \"./errors\";\nimport { globalVar } from \"./globals\";\nimport { pick } from \"./objects\";\nimport { Result } from \"./results\";\nimport { nicify } from \"./strings\";\n\nfunction
|
|
1
|
+
{"version":3,"file":"jwt.js","names":[],"sources":["../../../src/utils/jwt.tsx"],"sourcesContent":["import crypto from \"crypto\";\nimport elliptic from \"elliptic\";\nimport * as jose from \"jose\";\nimport { JOSEError } from \"jose/errors\";\nimport { encodeBase64Url } from \"./bytes\";\nimport { getEnvVariable } from \"./env\";\nimport { HexclaveAssertionError, errorToNiceString } from \"./errors\";\nimport { globalVar } from \"./globals\";\nimport { pick } from \"./objects\";\nimport { Result } from \"./results\";\nimport { nicify } from \"./strings\";\n\nfunction getHexclaveServerSecret() {\n const STACK_SERVER_SECRET = getEnvVariable(\"STACK_SERVER_SECRET\");\n try {\n jose.base64url.decode(STACK_SERVER_SECRET);\n } catch (e) {\n throw new HexclaveAssertionError(\"STACK_SERVER_SECRET is not valid. Please use the generateKeys script to generate a new secret.\", { cause: e });\n }\n return STACK_SERVER_SECRET;\n}\n\nexport async function getJwtInfo(options: {\n jwt: string,\n}) {\n try {\n if (typeof options.jwt !== \"string\") return Result.error({ error: \"JWT input is not a string!\", stringifiedInput: nicify(options.jwt) });\n if (!options.jwt.startsWith(\"ey\")) return Result.error({ error: \"Input is a string, but not a JWT!\", input: options.jwt });\n const decodedJwt = jose.decodeJwt(options.jwt);\n return Result.ok({ payload: decodedJwt });\n } catch (e) {\n return Result.error({\n exception: errorToNiceString(e),\n });\n }\n}\n\nexport async function signJWT(options: {\n issuer: string,\n audience: string,\n payload: any,\n expirationTime?: string,\n}) {\n const privateJwks = await getPrivateJwks({ audience: options.audience });\n const privateKey = await jose.importJWK(privateJwks[0]);\n\n return await new jose.SignJWT(options.payload)\n .setProtectedHeader({ alg: \"ES256\", kid: privateJwks[0].kid })\n .setIssuer(options.issuer)\n .setIssuedAt()\n .setAudience(options.audience)\n .setExpirationTime(options.expirationTime || \"5m\")\n .sign(privateKey);\n}\n\nexport async function verifyJWT(options: {\n allowedIssuers: string[],\n jwt: string,\n}) {\n const decodedJwt = jose.decodeJwt(options.jwt);\n const audience = decodedJwt.aud;\n if (!audience || typeof audience !== \"string\") {\n throw new JOSEError(\"Invalid JWT audience\");\n }\n\n const jwkSet = jose.createLocalJWKSet(await getPublicJwkSet(await getPrivateJwks({ audience })));\n const verified = await jose.jwtVerify(options.jwt, jwkSet, { issuer: options.allowedIssuers });\n return verified.payload;\n}\n\nexport type PrivateJwk = {\n kty: \"EC\",\n alg: \"ES256\",\n crv: \"P-256\",\n kid: string,\n d: string,\n x: string,\n y: string,\n};\nasync function getPrivateJwkFromDerivedSecret(derivedSecret: string, kid: string): Promise<PrivateJwk> {\n const secretHash = await globalVar.crypto.subtle.digest(\"SHA-256\", jose.base64url.decode(derivedSecret));\n const priv = new Uint8Array(secretHash);\n\n const ec = new elliptic.ec('p256');\n const key = ec.keyFromPrivate(priv);\n const publicKey = key.getPublic();\n\n return {\n kty: 'EC',\n crv: 'P-256',\n alg: 'ES256',\n kid: kid,\n d: encodeBase64Url(priv),\n x: encodeBase64Url(publicKey.getX().toBuffer()),\n y: encodeBase64Url(publicKey.getY().toBuffer()),\n };\n}\n\n/**\n * Returns a list of valid private JWKs for the given audience, with the first one taking precedence when signing new\n * JWTs.\n */\nexport async function getPrivateJwks(options: {\n audience: string,\n}): Promise<PrivateJwk[]> {\n const getHashOfJwkInfo = (type: string) => jose.base64url.encode(\n crypto\n .createHash('sha256')\n .update(JSON.stringify([type, getHexclaveServerSecret(), {\n audience: options.audience,\n }]))\n .digest()\n );\n // NOTE (Hexclave rebrand): do NOT rename these \"stack-*\" literals. They are hashed into the\n // per-audience JWT signing secret and key id (kid); renaming them would rotate every project's\n // JWKS and invalidate all already-issued access tokens. Internal constants, never user-visible.\n const perAudienceSecret = getHashOfJwkInfo(\"stack-jwk-audience-secret\");\n const perAudienceKid = getHashOfJwkInfo(\"stack-jwk-kid\").slice(0, 12);\n\n const oldPerAudienceSecret = oldGetPerAudienceSecret({ audience: options.audience });\n const oldPerAudienceKid = oldGetKid({ secret: oldPerAudienceSecret });\n\n return [\n // TODO next-release: make this not take precedence; then, in the release after that, remove it entirely\n await getPrivateJwkFromDerivedSecret(oldPerAudienceSecret, oldPerAudienceKid),\n\n await getPrivateJwkFromDerivedSecret(perAudienceSecret, perAudienceKid),\n ];\n}\n\nexport type PublicJwk = {\n kty: \"EC\",\n alg: \"ES256\",\n crv: \"P-256\",\n kid: string,\n x: string,\n y: string,\n};\nexport async function getPublicJwkSet(privateJwks: PrivateJwk[]): Promise<{ keys: PublicJwk[] }> {\n return {\n keys: privateJwks.map(jwk => pick(jwk, [\"kty\", \"alg\", \"crv\", \"x\", \"y\", \"kid\"])),\n };\n}\n\nfunction oldGetPerAudienceSecret(options: {\n audience: string,\n}) {\n if (options.audience === \"kid\") {\n throw new HexclaveAssertionError(\"You cannot use the 'kid' audience for a per-audience secret, see comment below in jwt.tsx\");\n }\n return jose.base64url.encode(\n crypto\n .createHash('sha256')\n // TODO we should prefix a string like \"stack-audience-secret\" before we hash so you can't use `getKid(...)` to get the secret for eg. the \"kid\" audience if the same secret value is used\n // Sadly doing this modification is a bit annoying as we need to leave the old keys to be valid for a little longer\n .update(JSON.stringify([getHexclaveServerSecret(), options.audience]))\n .digest()\n );\n};\n\nexport function oldGetKid(options: {\n secret: string,\n}) {\n return jose.base64url.encode(\n crypto\n .createHash('sha256')\n .update(JSON.stringify([options.secret, \"kid\"])) // TODO see above in getPerA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Q,aAAa,MACvB,OAAM,IAAI,uBAAuB,4FAA4F;AAE/H,QAAO,KAAK,UAAU,OACpB,OACG,WAAW,SAAS,CAGpB,OAAO,KAAK,UAAU,CAAC,yBAAyB,EAAE,QAAQ,SAAS,CAAC,CAAC,CACrE,QAAQ,CACZ;;AAGH,SAAgB,UAAU,SAEvB;AACD,QAAO,KAAK,UAAU,OACpB,OACG,WAAW,SAAS,CACpB,OAAO,KAAK,UAAU,CAAC,QAAQ,QAAQ,MAAM,CAAC,CAAC,CAC/C,QAAQ,CACZ,CAAC,MAAM,GAAG,GAAG"}
|
|
@@ -7,20 +7,20 @@ declare function getHostedHandlerTrustedDomain(options: {
|
|
|
7
7
|
projectId: string;
|
|
8
8
|
hostedHandlerDomainSuffix?: string;
|
|
9
9
|
hostedHandlerUrlTemplate?: string;
|
|
10
|
-
|
|
10
|
+
hexclavePortPrefix?: string;
|
|
11
11
|
}): string;
|
|
12
12
|
declare function getHostedHandlerUrlFromConfig(options: {
|
|
13
13
|
projectId: string;
|
|
14
14
|
hostedPath: string;
|
|
15
15
|
hostedHandlerDomainSuffix?: string;
|
|
16
16
|
hostedHandlerUrlTemplate?: string;
|
|
17
|
-
|
|
17
|
+
hexclavePortPrefix?: string;
|
|
18
18
|
}): string;
|
|
19
19
|
declare function getImplicitlyTrustedDomainsForProject(options: {
|
|
20
20
|
projectId: string;
|
|
21
21
|
hostedHandlerDomainSuffix?: string;
|
|
22
22
|
hostedHandlerUrlTemplate?: string;
|
|
23
|
-
|
|
23
|
+
hexclavePortPrefix?: string;
|
|
24
24
|
}): string[];
|
|
25
25
|
declare function isAcceptedNativeAppUrl(urlOrString: string): boolean;
|
|
26
26
|
declare function validateRedirectUrl(urlOrString: string | URL, config: TrustedDomainConfig): boolean;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"redirect-urls.d.ts","names":[],"sources":["../../../src/utils/redirect-urls.tsx"],"mappings":";KAGK,mBAAA;EACH,cAAA;EACA,cAAA;AAAA;AAAA,iBAgCc,6BAAA,CAA8B,OAAA;EAC5C,SAAA;EACA,yBAAA;EACA,wBAAA;EACA,
|
|
1
|
+
{"version":3,"file":"redirect-urls.d.ts","names":[],"sources":["../../../src/utils/redirect-urls.tsx"],"mappings":";KAGK,mBAAA;EACH,cAAA;EACA,cAAA;AAAA;AAAA,iBAgCc,6BAAA,CAA8B,OAAA;EAC5C,SAAA;EACA,yBAAA;EACA,wBAAA;EACA,kBAAA;AAAA;AAAA,iBAQc,6BAAA,CAA8B,OAAA;EAC5C,SAAA;EACA,UAAA;EACA,yBAAA;EACA,wBAAA;EACA,kBAAA;AAAA;AAAA,iBA0Bc,qCAAA,CAAsC,OAAA;EACpD,SAAA;EACA,yBAAA;EACA,wBAAA;EACA,kBAAA;AAAA;AAAA,iBA0Ec,sBAAA,CAAuB,WAAA;AAAA,iBASvB,mBAAA,CACd,WAAA,WAAsB,GAAA,EACtB,MAAA,EAAQ,mBAAA;AAAA,iBAYM,sBAAA,CAAuB,aAAA,UAAuB,cAAA"}
|
|
@@ -8,9 +8,9 @@ const hostedHandlerPathPlaceholder = "{hostedPath}";
|
|
|
8
8
|
const defaultPorts = new Map([["https:", "443"], ["http:", "80"]]);
|
|
9
9
|
const hostedHandlerTemplateProjectIdA = "00000000-0000-4000-8000-000000000000";
|
|
10
10
|
const hostedHandlerTemplateProjectIdB = "11111111-1111-4111-8111-111111111111";
|
|
11
|
-
function
|
|
11
|
+
function replaceHexclavePortPrefix(input, hexclavePortPrefix) {
|
|
12
12
|
if (input == null) return void 0;
|
|
13
|
-
return
|
|
13
|
+
return hexclavePortPrefix ? input.replace(/\$\{NEXT_PUBLIC_HEXCLAVE_PORT_PREFIX:-81\}/g, hexclavePortPrefix) : input;
|
|
14
14
|
}
|
|
15
15
|
function getHostedHandlerUrlFromTemplate(template, projectId, hostedPath) {
|
|
16
16
|
return template.replaceAll(hostedHandlerProjectIdPlaceholder, projectId).replaceAll(hostedHandlerPathPlaceholder, hostedPath);
|
|
@@ -30,9 +30,9 @@ function getHostedHandlerTrustedDomain(options) {
|
|
|
30
30
|
})).origin;
|
|
31
31
|
}
|
|
32
32
|
function getHostedHandlerUrlFromConfig(options) {
|
|
33
|
-
const configuredTemplate =
|
|
33
|
+
const configuredTemplate = replaceHexclavePortPrefix(options.hostedHandlerUrlTemplate, options.hexclavePortPrefix);
|
|
34
34
|
return configuredTemplate == null ? (() => {
|
|
35
|
-
const domainSuffix =
|
|
35
|
+
const domainSuffix = replaceHexclavePortPrefix(options.hostedHandlerDomainSuffix, options.hexclavePortPrefix) ?? defaultHostedHandlerDomainSuffix;
|
|
36
36
|
if (!domainSuffix.startsWith(".")) throw new HexclaveAssertionError("The hosted handler domain suffix must start with a dot.", {
|
|
37
37
|
domainSuffix,
|
|
38
38
|
hint: "Set NEXT_PUBLIC_STACK_HOSTED_HANDLER_DOMAIN_SUFFIX to a value like '.built-with-stack-auth.com'."
|
|
@@ -149,7 +149,7 @@ function getTrustedParentDomain(currentDomain, trustedDomains) {
|
|
|
149
149
|
trustedDomains: getImplicitlyTrustedDomainsForProject({
|
|
150
150
|
projectId,
|
|
151
151
|
hostedHandlerUrlTemplate: "http://{projectId}.localhost:${NEXT_PUBLIC_HEXCLAVE_PORT_PREFIX:-81}09/{hostedPath}",
|
|
152
|
-
|
|
152
|
+
hexclavePortPrefix: "92"
|
|
153
153
|
})
|
|
154
154
|
})).toBe(true);
|
|
155
155
|
});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"redirect-urls.js","names":[],"sources":["../../../src/utils/redirect-urls.tsx"],"sourcesContent":["import { HexclaveAssertionError, captureError } from \"./errors\";\nimport { createUrlIfValid, isLocalhost, matchHostnamePattern } from \"./urls\";\n\ntype TrustedDomainConfig = {\n allowLocalhost?: boolean,\n trustedDomains: readonly (string | null | undefined)[],\n};\n\nconst defaultHostedHandlerDomainSuffix = \".built-with-stack-auth.com\";\nconst hostedHandlerProjectIdPlaceholder = \"{projectId}\";\nconst hostedHandlerPathPlaceholder = \"{hostedPath}\";\nconst defaultPorts = new Map<string, string>([['https:', '443'], ['http:', '80']]);\nconst hostedHandlerTemplateProjectIdA = \"00000000-0000-4000-8000-000000000000\";\nconst hostedHandlerTemplateProjectIdB = \"11111111-1111-4111-8111-111111111111\";\n\nfunction replaceStackPortPrefix(input: string | undefined, stackPortPrefix: string | undefined): string | undefined {\n if (input == null) return undefined;\n return stackPortPrefix ? input.replace(/\\$\\{NEXT_PUBLIC_HEXCLAVE_PORT_PREFIX:-81\\}/g, stackPortPrefix) : input;\n}\n\nfunction getHostedHandlerUrlFromTemplate(template: string, projectId: string, hostedPath: string): string {\n return template\n .replaceAll(hostedHandlerProjectIdPlaceholder, projectId)\n .replaceAll(hostedHandlerPathPlaceholder, hostedPath);\n}\n\nfunction assertHostedHandlerTemplateHasProjectOrigin(template: string): void {\n const projectUrlA = new URL(getHostedHandlerUrlFromTemplate(template, hostedHandlerTemplateProjectIdA, \"handler\"));\n const projectUrlB = new URL(getHostedHandlerUrlFromTemplate(template, hostedHandlerTemplateProjectIdB, \"handler\"));\n if (projectUrlA.origin === projectUrlB.origin || !projectUrlA.hostname.includes(hostedHandlerTemplateProjectIdA)) {\n throw new HexclaveAssertionError(\"The hosted handler URL template must put {projectId} in the hostname.\", {\n hostedHandlerUrlTemplate: template,\n hint: \"Use a project-specific origin like 'https://{projectId}.built-with-stack-auth.com/{hostedPath}', not a shared-origin path like 'https://example.com/{projectId}/{hostedPath}'.\",\n });\n }\n}\n\nexport function getHostedHandlerTrustedDomain(options: {\n projectId: string,\n hostedHandlerDomainSuffix?: string,\n hostedHandlerUrlTemplate?: string,\n stackPortPrefix?: string,\n}): string {\n return new URL(getHostedHandlerUrlFromConfig({\n ...options,\n hostedPath: \"handler\",\n })).origin;\n}\n\nexport function getHostedHandlerUrlFromConfig(options: {\n projectId: string,\n hostedPath: string,\n hostedHandlerDomainSuffix?: string,\n hostedHandlerUrlTemplate?: string,\n stackPortPrefix?: string,\n}): string {\n const configuredTemplate = replaceStackPortPrefix(options.hostedHandlerUrlTemplate, options.stackPortPrefix);\n return configuredTemplate == null\n ? (() => {\n const domainSuffix = replaceStackPortPrefix(options.hostedHandlerDomainSuffix, options.stackPortPrefix) ?? defaultHostedHandlerDomainSuffix;\n if (!domainSuffix.startsWith(\".\")) {\n throw new HexclaveAssertionError(\"The hosted handler domain suffix must start with a dot.\", {\n domainSuffix,\n hint: \"Set NEXT_PUBLIC_STACK_HOSTED_HANDLER_DOMAIN_SUFFIX to a value like '.built-with-stack-auth.com'.\",\n });\n }\n return `https://${options.projectId}${domainSuffix}/${options.hostedPath}`;\n })()\n : (() => {\n if (!configuredTemplate.includes(hostedHandlerProjectIdPlaceholder) || !configuredTemplate.includes(hostedHandlerPathPlaceholder)) {\n throw new HexclaveAssertionError(\"The hosted handler URL template must contain {projectId} and {hostedPath}.\", {\n hostedHandlerUrlTemplate: configuredTemplate,\n hint: \"Set NEXT_PUBLIC_STACK_HOSTED_HANDLER_URL_TEMPLATE to a value like 'https://{projectId}.built-with-stack-auth.com/{hostedPath}'.\",\n });\n }\n assertHostedHandlerTemplateHasProjectOrigin(configuredTemplate);\n return getHostedHandlerUrlFromTemplate(configuredTemplate, options.projectId, options.hostedPath);\n })();\n}\n\nexport function getImplicitlyTrustedDomainsForProject(options: {\n projectId: string,\n hostedHandlerDomainSuffix?: string,\n hostedHandlerUrlTemplate?: string,\n stackPortPrefix?: string,\n}): string[] {\n return [getHostedHandlerTrustedDomain(options)];\n}\n\nfunction normalizePort(url: URL): string {\n const port = url.port || defaultPorts.get(url.protocol) || '';\n return port ? `${url.hostname}:${port}` : url.hostname;\n}\n\nfunction isDefaultPort(url: URL): boolean {\n return !url.port ||\n (url.protocol === 'https:' && url.port === '443') ||\n (url.protocol === 'http:' && url.port === '80');\n}\n\nfunction portsMatch(url1: URL, url2: URL): boolean {\n return normalizePort(url1) === normalizePort(url2);\n}\n\nfunction parseWildcardUrlPattern(pattern: string): { protocol: string, hostPattern: string } | null {\n const protocolSeparatorIndex = pattern.indexOf(\"://\");\n if (protocolSeparatorIndex === -1) return null;\n\n const protocol = `${pattern.slice(0, protocolSeparatorIndex)}:`;\n const hostAndPath = pattern.slice(protocolSeparatorIndex + \"://\".length);\n const pathStartIndex = hostAndPath.indexOf(\"/\");\n const hostPattern = pathStartIndex === -1 ? hostAndPath : hostAndPath.slice(0, pathStartIndex);\n if (hostPattern === \"\") return null;\n return { protocol, hostPattern };\n}\n\nfunction hostPatternWithoutPort(hostPattern: string): string {\n if (!hostPatternHasExplicitPort(hostPattern)) {\n return hostPattern;\n }\n const portSeparatorIndex = hostPattern.lastIndexOf(\":\");\n return hostPattern.slice(0, portSeparatorIndex);\n}\n\nfunction hostPatternHasExplicitPort(hostPattern: string): boolean {\n const portSeparatorIndex = hostPattern.lastIndexOf(\":\");\n if (portSeparatorIndex === -1) {\n return false;\n }\n const port = hostPattern.slice(portSeparatorIndex + 1);\n return port === \"*\" || (port !== \"\" && [...port].every(char => char >= \"0\" && char <= \"9\"));\n}\n\nfunction matchesTrustedDomain(testUrl: URL, pattern: string): boolean {\n const baseUrl = createUrlIfValid(pattern);\n\n if (baseUrl != null && !pattern.includes('*')) {\n return baseUrl.protocol === testUrl.protocol &&\n baseUrl.hostname === testUrl.hostname &&\n portsMatch(baseUrl, testUrl);\n }\n\n const parsedPattern = parseWildcardUrlPattern(pattern);\n if (parsedPattern == null) {\n captureError(\"invalid-redirect-domain\", new HexclaveAssertionError(\"Invalid domain pattern\", { pattern }));\n return false;\n }\n\n if (testUrl.protocol !== parsedPattern.protocol) {\n return false;\n }\n\n const hasPortInPattern = hostPatternHasExplicitPort(parsedPattern.hostPattern);\n return hasPortInPattern\n ? matchHostnamePattern(parsedPattern.hostPattern, normalizePort(testUrl))\n : matchHostnamePattern(parsedPattern.hostPattern, testUrl.hostname) && isDefaultPort(testUrl);\n}\n\nexport function isAcceptedNativeAppUrl(urlOrString: string): boolean {\n const url = createUrlIfValid(urlOrString);\n if (!url) return false;\n\n // Legacy scheme accepted indefinitely; baked into already-shipped Swift SDK binaries.\n return url.protocol === 'stack-auth-mobile-oauth-url:'\n || url.protocol === 'hexclave-mobile-oauth-url:';\n}\n\nexport function validateRedirectUrl(\n urlOrString: string | URL,\n config: TrustedDomainConfig,\n): boolean {\n const url = createUrlIfValid(urlOrString);\n if (!url) return false;\n\n if (config.allowLocalhost === true && isLocalhost(url)) {\n return true;\n }\n\n return config.trustedDomains.some(domain => domain != null && matchesTrustedDomain(url, domain));\n}\n\nexport function getTrustedParentDomain(currentDomain: string, trustedDomains: readonly (string | null | undefined)[]): string | null {\n const hostPatterns = trustedDomains\n .filter((domain): domain is string => domain != null)\n .map((domain) => {\n const url = createUrlIfValid(domain);\n if (url != null && !domain.includes(\"*\")) {\n return url.hostname.toLowerCase();\n }\n const parsedPattern = parseWildcardUrlPattern(domain);\n return parsedPattern == null ? null : hostPatternWithoutPort(parsedPattern.hostPattern).toLowerCase();\n })\n .filter((domain): domain is string => domain != null);\n\n const parts = currentDomain.toLowerCase().split('.');\n for (let i = parts.length - 2; i >= 0; i--) {\n const parentDomain = parts.slice(i).join('.');\n if (hostPatterns.includes(parentDomain) && hostPatterns.includes(`**.${parentDomain}`)) {\n return parentDomain;\n }\n }\n\n return null;\n}\n\nimport.meta.vitest?.test(\"validateRedirectUrl matches exact and wildcard trusted domains\", ({ expect }) => {\n expect(validateRedirectUrl(\"https://example.com\", {\n allowLocalhost: false,\n trustedDomains: [\"https://example.com\"],\n })).toBe(true);\n expect(validateRedirectUrl(\"https://api.example.com\", {\n allowLocalhost: false,\n trustedDomains: [\"https://*.example.com\"],\n })).toBe(true);\n expect(validateRedirectUrl(\"https://api.v2.example.com\", {\n allowLocalhost: false,\n trustedDomains: [\"https://*.example.com\"],\n })).toBe(false);\n});\n\nimport.meta.vitest?.test(\"validateRedirectUrl trusts implicit hosted handler domains\", ({ expect }) => {\n const projectId = \"12345678-1234-4234-8234-123456789abc\";\n expect(validateRedirectUrl(`https://${projectId}.built-with-stack-auth.com/anything`, {\n allowLocalhost: false,\n trustedDomains: getImplicitlyTrustedDomainsForProject({ projectId }),\n })).toBe(true);\n expect(validateRedirectUrl(\"https://other-project.built-with-stack-auth.com/anything\", {\n allowLocalhost: false,\n trustedDomains: getImplicitlyTrustedDomainsForProject({ projectId }),\n })).toBe(false);\n expect(validateRedirectUrl(`http://${projectId}.localhost:9209/anything`, {\n allowLocalhost: false,\n trustedDomains: getImplicitlyTrustedDomainsForProject({\n projectId,\n hostedHandlerUrlTemplate: \"http://{projectId}.localhost:${NEXT_PUBLIC_HEXCLAVE_PORT_PREFIX:-81}09/{hostedPath}\",\n stackPortPrefix: \"92\",\n }),\n })).toBe(true);\n});\n\nimport.meta.vitest?.test(\"getImplicitlyTrustedDomainsForProject rejects shared-origin hosted templates\", ({ expect }) => {\n expect(() => getImplicitlyTrustedDomainsForProject({\n projectId: \"12345678-1234-4234-8234-123456789abc\",\n hostedHandlerUrlTemplate: \"https://host.example.com/{projectId}/{hostedPath}\",\n })).toThrowErrorMatchingInlineSnapshot(`\n [HexclaveAssertionError: The hosted handler URL template must put {projectId} in the hostname.\n\n This is likely an error in Hexclave. Please make sure you are running the newest version and report it.]\n `);\n});\n\nimport.meta.vitest?.test(\"validateRedirectUrl respects default and explicit ports\", ({ expect }) => {\n expect(validateRedirectUrl(\"https://example.com:443/path\", {\n allowLocalhost: false,\n trustedDomains: [\"https://example.com\"],\n })).toBe(true);\n expect(validateRedirectUrl(\"http://api.example.com:3000\", {\n allowLocalhost: false,\n trustedDomains: [\"http://*.example.com:3000\"],\n })).toBe(true);\n expect(validateRedirectUrl(\"http://api.example.com\", {\n allowLocalhost: false,\n trustedDomains: [\"http://*.example.com:3000\"],\n })).toBe(false);\n expect(validateRedirectUrl(\"http://api.example.com:1234\", {\n allowLocalhost: false,\n trustedDomains: [\"http://*.example.com:*\"],\n })).toBe(true);\n});\n\nimport.meta.vitest?.test(\"validateRedirectUrl respects localhost allowance and invalid patterns\", ({ expect }) => {\n const originalConsoleError = console.error;\n console.error = () => {};\n try {\n expect(validateRedirectUrl(\"http://localhost:3000\", {\n allowLocalhost: true,\n trustedDomains: [],\n })).toBe(true);\n expect(validateRedirectUrl(\"http://localhost:3000\", {\n allowLocalhost: false,\n trustedDomains: [],\n })).toBe(false);\n expect(validateRedirectUrl(\"https://example.com\", {\n allowLocalhost: false,\n trustedDomains: [\"not a url\"],\n })).toBe(false);\n } finally {\n console.error = originalConsoleError;\n }\n});\n\nimport.meta.vitest?.test(\"getTrustedParentDomain ignores empty entries and strips ports\", ({ expect }) => {\n expect(getTrustedParentDomain(\"app.example.com\", [\n null,\n undefined,\n \"https://example.com\",\n \"https://**.example.com:*\",\n ])).toBe(\"example.com\");\n});\n"],"mappings":";;;;AAQA,MAAM,mCAAmC;AACzC,MAAM,oCAAoC;AAC1C,MAAM,+BAA+B;AACrC,MAAM,eAAe,IAAI,IAAoB,CAAC,CAAC,UAAU,MAAM,EAAE,CAAC,SAAS,KAAK,CAAC,CAAC;AAClF,MAAM,kCAAkC;AACxC,MAAM,kCAAkC;AAExC,SAAS,uBAAuB,OAA2B,iBAAyD;AAClH,KAAI,SAAS,KAAM,QAAO;AAC1B,QAAO,kBAAkB,MAAM,QAAQ,+CAA+C,gBAAgB,GAAG;;AAG3G,SAAS,gCAAgC,UAAkB,WAAmB,YAA4B;AACxG,QAAO,SACJ,WAAW,mCAAmC,UAAS,CACvD,WAAW,8BAA8B,WAAW;;AAGzD,SAAS,4CAA4C,UAAwB;CAC3E,MAAM,cAAc,IAAI,IAAI,gCAAgC,UAAU,iCAAiC,UAAU,CAAC;CAClH,MAAM,cAAc,IAAI,IAAI,gCAAgC,UAAU,iCAAiC,UAAU,CAAC;AAClH,KAAI,YAAY,WAAW,YAAY,UAAU,CAAC,YAAY,SAAS,SAAS,gCAAgC,CAC9G,OAAM,IAAI,uBAAuB,yEAAyE;EACxG,0BAA0B;EAC1B,MAAM;EACP,CAAC;;AAIN,SAAgB,8BAA8B,SAKnC;AACT,QAAO,IAAI,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,gBAAgB;GAChB,gBAAgB,EAAE;GACnB,CAAC,CAAC,CAAC,KAAK,KAAK;AACd,SAAO,oBAAoB,yBAAyB;GAClD,gBAAgB;GAChB,gBAAgB,EAAE;GACnB,CAAC,CAAC,CAAC,KAAK,MAAM;AACf,SAAO,oBAAoB,uBAAuB;GAChD,gBAAgB;GAChB,gBAAgB,CAAC,YAAY;GAC9B,CAAC,CAAC,CAAC,KAAK,MAAM;WACP;AACR,UAAQ,QAAQ;;EAElB;CAEF,SAAW,KAAC,kEAAsE,EAAA,aAAW;AAC3F,QAAO,uBAAuB,mBAAmB;EAC/C;EACA;EACA;EACA;EACD,CAAC,CAAC,CAAC,KAAK,cAAc;EACvB"}
|
|
1
|
+
{"version":3,"file":"redirect-urls.js","names":[],"sources":["../../../src/utils/redirect-urls.tsx"],"sourcesContent":["import { HexclaveAssertionError, captureError } from \"./errors\";\nimport { createUrlIfValid, isLocalhost, matchHostnamePattern } from \"./urls\";\n\ntype TrustedDomainConfig = {\n allowLocalhost?: boolean,\n trustedDomains: readonly (string | null | undefined)[],\n};\n\nconst defaultHostedHandlerDomainSuffix = \".built-with-stack-auth.com\";\nconst hostedHandlerProjectIdPlaceholder = \"{projectId}\";\nconst hostedHandlerPathPlaceholder = \"{hostedPath}\";\nconst defaultPorts = new Map<string, string>([['https:', '443'], ['http:', '80']]);\nconst hostedHandlerTemplateProjectIdA = \"00000000-0000-4000-8000-000000000000\";\nconst hostedHandlerTemplateProjectIdB = \"11111111-1111-4111-8111-111111111111\";\n\nfunction replaceHexclavePortPrefix(input: string | undefined, hexclavePortPrefix: string | undefined): string | undefined {\n if (input == null) return undefined;\n return hexclavePortPrefix ? input.replace(/\\$\\{NEXT_PUBLIC_HEXCLAVE_PORT_PREFIX:-81\\}/g, hexclavePortPrefix) : input;\n}\n\nfunction getHostedHandlerUrlFromTemplate(template: string, projectId: string, hostedPath: string): string {\n return template\n .replaceAll(hostedHandlerProjectIdPlaceholder, projectId)\n .replaceAll(hostedHandlerPathPlaceholder, hostedPath);\n}\n\nfunction assertHostedHandlerTemplateHasProjectOrigin(template: string): void {\n const projectUrlA = new URL(getHostedHandlerUrlFromTemplate(template, hostedHandlerTemplateProjectIdA, \"handler\"));\n const projectUrlB = new URL(getHostedHandlerUrlFromTemplate(template, hostedHandlerTemplateProjectIdB, \"handler\"));\n if (projectUrlA.origin === projectUrlB.origin || !projectUrlA.hostname.includes(hostedHandlerTemplateProjectIdA)) {\n throw new HexclaveAssertionError(\"The hosted handler URL template must put {projectId} in the hostname.\", {\n hostedHandlerUrlTemplate: template,\n hint: \"Use a project-specific origin like 'https://{projectId}.built-with-stack-auth.com/{hostedPath}', not a shared-origin path like 'https://example.com/{projectId}/{hostedPath}'.\",\n });\n }\n}\n\nexport function getHostedHandlerTrustedDomain(options: {\n projectId: string,\n hostedHandlerDomainSuffix?: string,\n hostedHandlerUrlTemplate?: string,\n hexclavePortPrefix?: string,\n}): string {\n return new URL(getHostedHandlerUrlFromConfig({\n ...options,\n hostedPath: \"handler\",\n })).origin;\n}\n\nexport function getHostedHandlerUrlFromConfig(options: {\n projectId: string,\n hostedPath: string,\n hostedHandlerDomainSuffix?: string,\n hostedHandlerUrlTemplate?: string,\n hexclavePortPrefix?: string,\n}): string {\n const configuredTemplate = replaceHexclavePortPrefix(options.hostedHandlerUrlTemplate, options.hexclavePortPrefix);\n return configuredTemplate == null\n ? (() => {\n const domainSuffix = replaceHexclavePortPrefix(options.hostedHandlerDomainSuffix, options.hexclavePortPrefix) ?? defaultHostedHandlerDomainSuffix;\n if (!domainSuffix.startsWith(\".\")) {\n throw new HexclaveAssertionError(\"The hosted handler domain suffix must start with a dot.\", {\n domainSuffix,\n hint: \"Set NEXT_PUBLIC_STACK_HOSTED_HANDLER_DOMAIN_SUFFIX to a value like '.built-with-stack-auth.com'.\",\n });\n }\n return `https://${options.projectId}${domainSuffix}/${options.hostedPath}`;\n })()\n : (() => {\n if (!configuredTemplate.includes(hostedHandlerProjectIdPlaceholder) || !configuredTemplate.includes(hostedHandlerPathPlaceholder)) {\n throw new HexclaveAssertionError(\"The hosted handler URL template must contain {projectId} and {hostedPath}.\", {\n hostedHandlerUrlTemplate: configuredTemplate,\n hint: \"Set NEXT_PUBLIC_STACK_HOSTED_HANDLER_URL_TEMPLATE to a value like 'https://{projectId}.built-with-stack-auth.com/{hostedPath}'.\",\n });\n }\n assertHostedHandlerTemplateHasProjectOrigin(configuredTemplate);\n return getHostedHandlerUrlFromTemplate(configuredTemplate, options.projectId, options.hostedPath);\n })();\n}\n\nexport function getImplicitlyTrustedDomainsForProject(options: {\n projectId: string,\n hostedHandlerDomainSuffix?: string,\n hostedHandlerUrlTemplate?: string,\n hexclavePortPrefix?: string,\n}): string[] {\n return [getHostedHandlerTrustedDomain(options)];\n}\n\nfunction normalizePort(url: URL): string {\n const port = url.port || defaultPorts.get(url.protocol) || '';\n return port ? `${url.hostname}:${port}` : url.hostname;\n}\n\nfunction isDefaultPort(url: URL): boolean {\n return !url.port ||\n (url.protocol === 'https:' && url.port === '443') ||\n (url.protocol === 'http:' && url.port === '80');\n}\n\nfunction portsMatch(url1: URL, url2: URL): boolean {\n return normalizePort(url1) === normalizePort(url2);\n}\n\nfunction parseWildcardUrlPattern(pattern: string): { protocol: string, hostPattern: string } | null {\n const protocolSeparatorIndex = pattern.indexOf(\"://\");\n if (protocolSeparatorIndex === -1) return null;\n\n const protocol = `${pattern.slice(0, protocolSeparatorIndex)}:`;\n const hostAndPath = pattern.slice(protocolSeparatorIndex + \"://\".length);\n const pathStartIndex = hostAndPath.indexOf(\"/\");\n const hostPattern = pathStartIndex === -1 ? hostAndPath : hostAndPath.slice(0, pathStartIndex);\n if (hostPattern === \"\") return null;\n return { protocol, hostPattern };\n}\n\nfunction hostPatternWithoutPort(hostPattern: string): string {\n if (!hostPatternHasExplicitPort(hostPattern)) {\n return hostPattern;\n }\n const portSeparatorIndex = hostPattern.lastIndexOf(\":\");\n return hostPattern.slice(0, portSeparatorIndex);\n}\n\nfunction hostPatternHasExplicitPort(hostPattern: string): boolean {\n const portSeparatorIndex = hostPattern.lastIndexOf(\":\");\n if (portSeparatorIndex === -1) {\n return false;\n }\n const port = hostPattern.slice(portSeparatorIndex + 1);\n return port === \"*\" || (port !== \"\" && [...port].every(char => char >= \"0\" && char <= \"9\"));\n}\n\nfunction matchesTrustedDomain(testUrl: URL, pattern: string): boolean {\n const baseUrl = createUrlIfValid(pattern);\n\n if (baseUrl != null && !pattern.includes('*')) {\n return baseUrl.protocol === testUrl.protocol &&\n baseUrl.hostname === testUrl.hostname &&\n portsMatch(baseUrl, testUrl);\n }\n\n const parsedPattern = parseWildcardUrlPattern(pattern);\n if (parsedPattern == null) {\n captureError(\"invalid-redirect-domain\", new HexclaveAssertionError(\"Invalid domain pattern\", { pattern }));\n return false;\n }\n\n if (testUrl.protocol !== parsedPattern.protocol) {\n return false;\n }\n\n const hasPortInPattern = hostPatternHasExplicitPort(parsedPattern.hostPattern);\n return hasPortInPattern\n ? matchHostnamePattern(parsedPattern.hostPattern, normalizePort(testUrl))\n : matchHostnamePattern(parsedPattern.hostPattern, testUrl.hostname) && isDefaultPort(testUrl);\n}\n\nexport function isAcceptedNativeAppUrl(urlOrString: string): boolean {\n const url = createUrlIfValid(urlOrString);\n if (!url) return false;\n\n // Legacy scheme accepted indefinitely; baked into already-shipped Swift SDK binaries.\n return url.protocol === 'stack-auth-mobile-oauth-url:'\n || url.protocol === 'hexclave-mobile-oauth-url:';\n}\n\nexport function validateRedirectUrl(\n urlOrString: string | URL,\n config: TrustedDomainConfig,\n): boolean {\n const url = createUrlIfValid(urlOrString);\n if (!url) return false;\n\n if (config.allowLocalhost === true && isLocalhost(url)) {\n return true;\n }\n\n return config.trustedDomains.some(domain => domain != null && matchesTrustedDomain(url, domain));\n}\n\nexport function getTrustedParentDomain(currentDomain: string, trustedDomains: readonly (string | null | undefined)[]): string | null {\n const hostPatterns = trustedDomains\n .filter((domain): domain is string => domain != null)\n .map((domain) => {\n const url = createUrlIfValid(domain);\n if (url != null && !domain.includes(\"*\")) {\n return url.hostname.toLowerCase();\n }\n const parsedPattern = parseWildcardUrlPattern(domain);\n return parsedPattern == null ? null : hostPatternWithoutPort(parsedPattern.hostPattern).toLowerCase();\n })\n .filter((domain): domain is string => domain != null);\n\n const parts = currentDomain.toLowerCase().split('.');\n for (let i = parts.length - 2; i >= 0; i--) {\n const parentDomain = parts.slice(i).join('.');\n if (hostPatterns.includes(parentDomain) && hostPatterns.includes(`**.${parentDomain}`)) {\n return parentDomain;\n }\n }\n\n return null;\n}\n\nimport.meta.vitest?.test(\"validateRedirectUrl matches exact and wildcard trusted domains\", ({ expect }) => {\n expect(validateRedirectUrl(\"https://example.com\", {\n allowLocalhost: false,\n trustedDomains: [\"https://example.com\"],\n })).toBe(true);\n expect(validateRedirectUrl(\"https://api.example.com\", {\n allowLocalhost: false,\n trustedDomains: [\"https://*.example.com\"],\n })).toBe(true);\n expect(validateRedirectUrl(\"https://api.v2.example.com\", {\n allowLocalhost: false,\n trustedDomains: [\"https://*.example.com\"],\n })).toBe(false);\n});\n\nimport.meta.vitest?.test(\"validateRedirectUrl trusts implicit hosted handler domains\", ({ expect }) => {\n const projectId = \"12345678-1234-4234-8234-123456789abc\";\n expect(validateRedirectUrl(`https://${projectId}.built-with-stack-auth.com/anything`, {\n allowLocalhost: false,\n trustedDomains: getImplicitlyTrustedDomainsForProject({ projectId }),\n })).toBe(true);\n expect(validateRedirectUrl(\"https://other-project.built-with-stack-auth.com/anything\", {\n allowLocalhost: false,\n trustedDomains: getImplicitlyTrustedDomainsForProject({ projectId }),\n })).toBe(false);\n expect(validateRedirectUrl(`http://${projectId}.localhost:9209/anything`, {\n allowLocalhost: false,\n trustedDomains: getImplicitlyTrustedDomainsForProject({\n projectId,\n hostedHandlerUrlTemplate: \"http://{projectId}.localhost:${NEXT_PUBLIC_HEXCLAVE_PORT_PREFIX:-81}09/{hostedPath}\",\n hexclavePortPrefix: \"92\",\n }),\n })).toBe(true);\n});\n\nimport.meta.vitest?.test(\"getImplicitlyTrustedDomainsForProject rejects shared-origin hosted templates\", ({ expect }) => {\n expect(() => getImplicitlyTrustedDomainsForProject({\n projectId: \"12345678-1234-4234-8234-123456789abc\",\n hostedHandlerUrlTemplate: \"https://host.example.com/{projectId}/{hostedPath}\",\n })).toThrowErrorMatchingInlineSnapshot(`\n [HexclaveAssertionError: The hosted handler URL template must put {projectId} in the hostname.\n\n This is likely an error in Hexclave. Please make sure you are running the newest version and report it.]\n `);\n});\n\nimport.meta.vitest?.test(\"validateRedirectUrl respects default and explicit ports\", ({ expect }) => {\n expect(validateRedirectUrl(\"https://example.com:443/path\", {\n allowLocalhost: false,\n trustedDomains: [\"https://example.com\"],\n })).toBe(true);\n expect(validateRedirectUrl(\"http://api.example.com:3000\", {\n allowLocalhost: false,\n trustedDomains: [\"http://*.example.com:3000\"],\n })).toBe(true);\n expect(validateRedirectUrl(\"http://api.example.com\", {\n allowLocalhost: false,\n trustedDomains: [\"http://*.example.com:3000\"],\n })).toBe(false);\n expect(validateRedirectUrl(\"http://api.example.com:1234\", {\n allowLocalhost: false,\n trustedDomains: [\"http://*.example.com:*\"],\n })).toBe(true);\n});\n\nimport.meta.vitest?.test(\"validateRedirectUrl respects localhost allowance and invalid patterns\", ({ expect }) => {\n const originalConsoleError = console.error;\n console.error = () => {};\n try {\n expect(validateRedirectUrl(\"http://localhost:3000\", {\n allowLocalhost: true,\n trustedDomains: [],\n })).toBe(true);\n expect(validateRedirectUrl(\"http://localhost:3000\", {\n allowLocalhost: false,\n trustedDomains: [],\n })).toBe(false);\n expect(validateRedirectUrl(\"https://example.com\", {\n allowLocalhost: false,\n trustedDomains: [\"not a url\"],\n })).toBe(false);\n } finally {\n console.error = originalConsoleError;\n }\n});\n\nimport.meta.vitest?.test(\"getTrustedParentDomain ignores empty entries and strips ports\", ({ expect }) => {\n expect(getTrustedParentDomain(\"app.example.com\", [\n null,\n undefined,\n \"https://example.com\",\n \"https://**.example.com:*\",\n ])).toBe(\"example.com\");\n});\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@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"urls.js","names":[],"sources":["../../../src/utils/urls.tsx"],"sourcesContent":["import { generateSecureRandomString } from \"./crypto\";\nimport { templateIdentity } from \"./strings\";\n\nexport function createUrlIfValid(...args: ConstructorParameters<typeof URL>) {\n try {\n return new URL(...args);\n } catch (e) {\n return null;\n }\n}\nimport.meta.vitest?.test(\"createUrlIfValid\", ({ expect }) => {\n // Test with valid URLs\n expect(createUrlIfValid(\"https://example.com\")).toBeInstanceOf(URL);\n expect(createUrlIfValid(\"https://example.com/path?query=value#hash\")).toBeInstanceOf(URL);\n expect(createUrlIfValid(\"/path\", \"https://example.com\")).toBeInstanceOf(URL);\n\n // Test with invalid URLs\n expect(createUrlIfValid(\"\")).toBeNull();\n expect(createUrlIfValid(\"not a url\")).toBeNull();\n expect(createUrlIfValid(\"http://\")).toBeNull();\n});\n\nexport function isValidUrl(url: string) {\n return !!createUrlIfValid(url);\n}\nimport.meta.vitest?.test(\"isValidUrl\", ({ expect }) => {\n // Test with valid URLs\n expect(isValidUrl(\"https://example.com\")).toBe(true);\n expect(isValidUrl(\"http://localhost:3000\")).toBe(true);\n expect(isValidUrl(\"ftp://example.com\")).toBe(true);\n\n // Test with invalid URLs\n expect(isValidUrl(\"\")).toBe(false);\n expect(isValidUrl(\"not a url\")).toBe(false);\n expect(isValidUrl(\"http://\")).toBe(false);\n});\n\nexport function isValidHostname(hostname: string) {\n // Basic validation\n if (!hostname || hostname.startsWith('.') || hostname.endsWith('.') || hostname.includes('..')) {\n return false;\n }\n\n const url = createUrlIfValid(`https://${hostname}`);\n if (!url) return false;\n return url.hostname === hostname;\n}\nimport.meta.vitest?.test(\"isValidHostname\", ({ expect }) => {\n // Test with valid hostnames\n expect(isValidHostname(\"example.com\")).toBe(true);\n expect(isValidHostname(\"localhost\")).toBe(true);\n expect(isValidHostname(\"sub.domain.example.com\")).toBe(true);\n expect(isValidHostname(\"127.0.0.1\")).toBe(true);\n\n // Test with invalid hostnames\n expect(isValidHostname(\"\")).toBe(false);\n expect(isValidHostname(\"example.com/path\")).toBe(false);\n expect(isValidHostname(\"https://example.com\")).toBe(false);\n expect(isValidHostname(\"example com\")).toBe(false);\n});\n\nexport function isValidHostnameWithWildcards(hostname: string) {\n // Empty hostnames are invalid\n if (!hostname) return false;\n\n // Check if it contains wildcards\n const hasWildcard = hostname.includes('*');\n\n if (!hasWildcard) {\n // If no wildcards, validate as a normal hostname\n return isValidHostname(hostname);\n }\n\n // Basic validation checks that apply even with wildcards\n // - Hostname cannot start or end with a dot\n if (hostname.startsWith('.') || hostname.endsWith('.')) {\n return false;\n }\n\n // - No consecutive dots\n if (hostname.includes('..')) {\n return false;\n }\n\n // For wildcard validation, check that non-wildcard parts contain valid characters\n // Replace wildcards with a valid placeholder to check the rest\n const testHostname = hostname.replace(/\\*+/g, 'wildcard');\n\n // Check if the resulting string would be a valid hostname\n if (!/^[a-zA-Z0-9.-]+$/.test(testHostname)) {\n return false;\n }\n\n // Additional check: ensure the pattern makes sense\n // Check each segment between wildcards\n const segments = hostname.split(/\\*+/);\n for (let i = 0; i < segments.length; i++) {\n const segment = segments[i];\n if (segment === '') continue; // Empty segments are OK (consecutive wildcards)\n\n // First segment can't start with dot\n if (i === 0 && segment.startsWith('.')) {\n return false;\n }\n\n // Last segment can't end with dot\n if (i === segments.length - 1 && segment.endsWith('.')) {\n return false;\n }\n\n // No segment should have consecutive dots\n if (segment.includes('..')) {\n return false;\n }\n }\n\n return true;\n}\nimport.meta.vitest?.test(\"isValidHostnameWithWildcards\", ({ expect }) => {\n // Test with valid regular hostnames\n expect(isValidHostnameWithWildcards(\"example.com\")).toBe(true);\n expect(isValidHostnameWithWildcards(\"localhost\")).toBe(true);\n expect(isValidHostnameWithWildcards(\"sub.domain.example.com\")).toBe(true);\n\n // Test with valid wildcard hostnames\n expect(isValidHostnameWithWildcards(\"*.example.com\")).toBe(true);\n expect(isValidHostnameWithWildcards(\"a-*.example.com\")).toBe(true);\n expect(isValidHostnameWithWildcards(\"*.*.org\")).toBe(true);\n expect(isValidHostnameWithWildcards(\"**.example.com\")).toBe(true);\n expect(isValidHostnameWithWildcards(\"sub.**.com\")).toBe(true);\n expect(isValidHostnameWithWildcards(\"*-api.*.com\")).toBe(true);\n\n // Test with invalid hostnames\n expect(isValidHostnameWithWildcards(\"\")).toBe(false);\n expect(isValidHostnameWithWildcards(\"example.com/path\")).toBe(false);\n expect(isValidHostnameWithWildcards(\"https://example.com\")).toBe(false);\n expect(isValidHostnameWithWildcards(\"example com\")).toBe(false);\n expect(isValidHostnameWithWildcards(\".example.com\")).toBe(false);\n expect(isValidHostnameWithWildcards(\"example.com.\")).toBe(false);\n expect(isValidHostnameWithWildcards(\"example..com\")).toBe(false);\n expect(isValidHostnameWithWildcards(\"*.example..com\")).toBe(false);\n});\n\nexport function matchHostnamePattern(pattern: string, hostname: string): boolean {\n // If no wildcards, it's an exact match\n if (!pattern.includes('*')) {\n return pattern === hostname;\n }\n\n // Convert the pattern to a regex\n // First, escape all regex special characters except *\n let regexPattern = pattern.replace(/[.+?^${}()|[\\]\\\\]/g, '\\\\$&');\n\n // Use a placeholder for ** to handle it separately from single *\n const doubleWildcardPlaceholder = '\\x00DOUBLE_WILDCARD\\x00';\n regexPattern = regexPattern.replace(/\\*\\*/g, doubleWildcardPlaceholder);\n\n // Replace single * with a pattern that matches anything except dots\n regexPattern = regexPattern.replace(/\\*/g, '[^.]*');\n\n // Replace the double wildcard placeholder with a pattern that matches anything including dots\n regexPattern = regexPattern.replace(new RegExp(doubleWildcardPlaceholder, 'g'), '.*');\n\n // Anchor the pattern to match the entire hostname\n regexPattern = '^' + regexPattern + '$';\n\n try {\n const regex = new RegExp(regexPattern);\n return regex.test(hostname);\n } catch {\n return false;\n }\n}\nimport.meta.vitest?.test(\"matchHostnamePattern\", ({ expect }) => {\n // Test exact matches\n expect(matchHostnamePattern(\"example.com\", \"example.com\")).toBe(true);\n expect(matchHostnamePattern(\"example.com\", \"other.com\")).toBe(false);\n\n // Test single wildcard matches\n expect(matchHostnamePattern(\"*.example.com\", \"api.example.com\")).toBe(true);\n expect(matchHostnamePattern(\"*.example.com\", \"www.example.com\")).toBe(true);\n expect(matchHostnamePattern(\"*.example.com\", \"example.com\")).toBe(false);\n expect(matchHostnamePattern(\"*.example.com\", \"api.v2.example.com\")).toBe(false);\n\n // Test double wildcard matches\n expect(matchHostnamePattern(\"**.example.com\", \"api.example.com\")).toBe(true);\n expect(matchHostnamePattern(\"**.example.com\", \"api.v2.example.com\")).toBe(true);\n expect(matchHostnamePattern(\"**.example.com\", \"a.b.c.example.com\")).toBe(true);\n expect(matchHostnamePattern(\"**.example.com\", \"example.com\")).toBe(false);\n\n // Test complex patterns\n expect(matchHostnamePattern(\"api-*.example.com\", \"api-v1.example.com\")).toBe(true);\n expect(matchHostnamePattern(\"api-*.example.com\", \"api-v2.example.com\")).toBe(true);\n expect(matchHostnamePattern(\"api-*.example.com\", \"api.example.com\")).toBe(false);\n expect(matchHostnamePattern(\"*.*.org\", \"mail.example.org\")).toBe(true);\n expect(matchHostnamePattern(\"*.*.org\", \"example.org\")).toBe(false);\n});\n\nexport function getHardcodedFallbackUrls(primaryBaseUrl: string): string[] {\n // `defaultBaseUrl` in `@stackframe/*` SDK builds is `https://api.stack-auth.com`\n // (see `packages/template/src/lib/stack-app/apps/implementations/common.ts`).\n // The `@hexclave/*` mirror packages will get this rewritten to the hexclave\n // hostname by `scripts/rewrite-packages-to-hexclave.ts` in a follow-up PR; both\n // branches below stay listed so either build resolves its own fallback set.\n if (primaryBaseUrl === \"https://api.stack-auth.com\") {\n return [\"https://api1.stack-auth.com\", \"https://api2.stack-auth.com\"];\n }\n if (primaryBaseUrl === \"https://api.dev.stack-auth.com\") {\n return [\"https://api1.dev.stack-auth.com\", \"https://api2.dev.stack-auth.com\"];\n }\n if (primaryBaseUrl === \"https://api.hexclave.com\") {\n return [\"https://api1.hexclave.com\", \"https://api2.hexclave.com\"];\n }\n if (primaryBaseUrl === \"https://api.dev.hexclave.com\") {\n return [\"https://api1.dev.hexclave.com\", \"https://api2.dev.hexclave.com\"];\n }\n const localhostMatch = primaryBaseUrl.match(/^http:\\/\\/localhost:(\\d+)02$/);\n if (localhostMatch) {\n return [`http://localhost:${localhostMatch[1]}10`];\n }\n return [];\n}\n\nexport function getDefaultApiUrls(primaryBaseUrl: string): string[] {\n return [primaryBaseUrl, ...getHardcodedFallbackUrls(primaryBaseUrl)];\n}\n\nexport function isLocalhost(urlOrString: string | URL) {\n const url = createUrlIfValid(urlOrString);\n if (!url) return false;\n if (url.hostname === \"localhost\" || url.hostname.endsWith(\".localhost\")) return true;\n if (url.hostname.match(/^127\\.\\d+\\.\\d+\\.\\d+$/)) return true;\n if (url.hostname === \"[::1]\" || url.hostname === \"::1\") return true;\n return false;\n}\nimport.meta.vitest?.test(\"isLocalhost\", ({ expect }) => {\n // Test with localhost URLs\n expect(isLocalhost(\"http://localhost\")).toBe(true);\n expect(isLocalhost(\"https://localhost:8080\")).toBe(true);\n expect(isLocalhost(\"http://sub.localhost\")).toBe(true);\n expect(isLocalhost(\"http://127.0.0.1\")).toBe(true);\n expect(isLocalhost(\"http://127.1.2.3\")).toBe(true);\n expect(isLocalhost(\"http://[::1]\")).toBe(true);\n\n // Test with non-localhost URLs\n expect(isLocalhost(\"https://example.com\")).toBe(false);\n expect(isLocalhost(\"http://192.168.1.1\")).toBe(false);\n expect(isLocalhost(\"http://10.0.0.1\")).toBe(false);\n\n // Test with URL objects\n expect(isLocalhost(new URL(\"http://localhost\"))).toBe(true);\n expect(isLocalhost(new URL(\"https://example.com\"))).toBe(false);\n\n // Test with invalid URLs\n expect(isLocalhost(\"not a url\")).toBe(false);\n expect(isLocalhost(\"\")).toBe(false);\n});\n\nexport function isRelative(url: string) {\n const randomDomain = `${generateSecureRandomString()}.stack-auth.example.com`;\n const u = createUrlIfValid(url, `https://${randomDomain}`);\n if (!u) return false;\n if (u.host !== randomDomain) return false;\n if (u.protocol !== \"https:\") return false;\n return true;\n}\nimport.meta.vitest?.test(\"isRelative\", ({ expect }) => {\n // We can't easily mock generateSecureRandomString in this context\n // but we can still test the function's behavior\n\n // Test with relative URLs\n expect(isRelative(\"/\")).toBe(true);\n expect(isRelative(\"/path\")).toBe(true);\n expect(isRelative(\"/path?query=value#hash\")).toBe(true);\n\n // Test with absolute URLs\n expect(isRelative(\"https://example.com\")).toBe(false);\n expect(isRelative(\"http://example.com\")).toBe(false);\n expect(isRelative(\"//example.com\")).toBe(false);\n\n // Note: The implementation treats empty strings and invalid URLs as relative\n // This is because they can be resolved against a base URL\n expect(isRelative(\"\")).toBe(true);\n expect(isRelative(\"not a url\")).toBe(true);\n});\n\nexport function getRelativePart(url: URL) {\n return url.pathname + url.search + url.hash;\n}\nimport.meta.vitest?.test(\"getRelativePart\", ({ expect }) => {\n // Test with various URLs\n expect(getRelativePart(new URL(\"https://example.com\"))).toBe(\"/\");\n expect(getRelativePart(new URL(\"https://example.com/path\"))).toBe(\"/path\");\n expect(getRelativePart(new URL(\"https://example.com/path?query=value\"))).toBe(\"/path?query=value\");\n expect(getRelativePart(new URL(\"https://example.com/path#hash\"))).toBe(\"/path#hash\");\n expect(getRelativePart(new URL(\"https://example.com/path?query=value#hash\"))).toBe(\"/path?query=value#hash\");\n\n // Test with different domains but same paths\n const url1 = new URL(\"https://example.com/path?query=value#hash\");\n const url2 = new URL(\"https://different.com/path?query=value#hash\");\n expect(getRelativePart(url1)).toBe(getRelativePart(url2));\n});\n\n/**\n * A template literal tag that returns a URL.\n *\n * Any values passed are encoded.\n */\nexport function url(strings: TemplateStringsArray | readonly string[], ...values: (string | number | boolean)[]): URL {\n return new URL(urlString(strings, ...values));\n}\nimport.meta.vitest?.test(\"url\", ({ expect }) => {\n // Test with no interpolation\n expect(url`https://example.com`).toBeInstanceOf(URL);\n expect(url`https://example.com`.href).toBe(\"https://example.com/\");\n\n // Test with string interpolation\n expect(url`https://example.com/${\"path\"}`).toBeInstanceOf(URL);\n expect(url`https://example.com/${\"path\"}`.pathname).toBe(\"/path\");\n\n // Test with number interpolation\n expect(url`https://example.com/${42}`).toBeInstanceOf(URL);\n expect(url`https://example.com/${42}`.pathname).toBe(\"/42\");\n\n // Test with boolean interpolation\n expect(url`https://example.com/${true}`).toBeInstanceOf(URL);\n expect(url`https://example.com/${true}`.pathname).toBe(\"/true\");\n\n // Test with special characters in interpolation\n expect(url`https://example.com/${\"path with spaces\"}`).toBeInstanceOf(URL);\n expect(url`https://example.com/${\"path with spaces\"}`.pathname).toBe(\"/path%20with%20spaces\");\n\n // Test with multiple interpolations\n expect(url`https://example.com/${\"path\"}?query=${\"value\"}`).toBeInstanceOf(URL);\n expect(url`https://example.com/${\"path\"}?query=${\"value\"}`.pathname).toBe(\"/path\");\n expect(url`https://example.com/${\"path\"}?query=${\"value\"}`.search).toBe(\"?query=value\");\n});\n\n\n/**\n * A template literal tag that returns a URL string.\n *\n * Any values passed are encoded.\n */\nexport function urlString(strings: TemplateStringsArray | readonly string[], ...values: (string | number | boolean)[]): string {\n return templateIdentity(strings, ...values.map(encodeURIComponent));\n}\nimport.meta.vitest?.test(\"urlString\", ({ expect }) => {\n // Test with no interpolation\n expect(urlString`https://example.com`).toBe(\"https://example.com\");\n\n // Test with string interpolation\n expect(urlString`https://example.com/${\"path\"}`).toBe(\"https://example.com/path\");\n\n // Test with number interpolation\n expect(urlString`https://example.com/${42}`).toBe(\"https://example.com/42\");\n\n // Test with boolean interpolation\n expect(urlString`https://example.com/${true}`).toBe(\"https://example.com/true\");\n\n // Test with special characters in interpolation\n expect(urlString`https://example.com/${\"path with spaces\"}`).toBe(\"https://example.com/path%20with%20spaces\");\n expect(urlString`https://example.com/${\"?&=\"}`).toBe(\"https://example.com/%3F%26%3D\");\n\n // Test with multiple interpolations\n expect(urlString`https://example.com/${\"path\"}?query=${\"value\"}`).toBe(\"https://example.com/path?query=value\");\n expect(urlString`https://example.com/${\"path\"}?query=${\"value with spaces\"}`).toBe(\"https://example.com/path?query=value%20with%20spaces\");\n});\n\nexport function isChildUrl(parentUrl: URL, maybeChildUrl: URL) {\n return parentUrl.origin === maybeChildUrl.origin\n && isChildPath(parentUrl.pathname, maybeChildUrl.pathname)\n && [...parentUrl.searchParams].every(([key, value]) => maybeChildUrl.searchParams.get(key) === value)\n && (!parentUrl.hash || parentUrl.hash === maybeChildUrl.hash);\n}\nimport.meta.vitest?.test(\"isChildUrl\", ({ expect }) => {\n // true\n expect(isChildUrl(new URL(\"https://abc.com/\"), new URL(\"https://abc.com/\"))).toBe(true);\n expect(isChildUrl(new URL(\"https://abc.com/\"), new URL(\"https://abc.com/path\"))).toBe(true);\n expect(isChildUrl(new URL(\"https://abc.com/\"), new URL(\"https://abc.com/path?query=value\"))).toBe(true);\n expect(isChildUrl(new URL(\"https://abc.com/\"), new URL(\"https://abc.com/path?query=value#hash\"))).toBe(true);\n\n // false\n expect(isChildUrl(new URL(\"https://abc.com\"), new URL(\"https://example.com\"))).toBe(false);\n expect(isChildUrl(new URL(\"https://abc.com/\"), new URL(\"https://example.com/path\"))).toBe(false);\n expect(isChildUrl(new URL(\"https://abc.com/\"), new URL(\"https://example.com/path?query=value\"))).toBe(false);\n expect(isChildUrl(new URL(\"https://abc.com/\"), new URL(\"https://example.com/path?query=value#hash\"))).toBe(false);\n expect(isChildUrl(new URL(\"https://example.com\"), new URL(\"https://abc.com/path?query=value#hash\"))).toBe(false);\n expect(isChildUrl(new URL(\"https://example.com?query=value123\"), new URL(\"https://example.com/path?query=value#hash\"))).toBe(false);\n});\n\nexport function isChildPath(parentPath: string, maybeChildPath: string) {\n parentPath = parentPath.endsWith(\"/\") ? parentPath : parentPath + \"/\";\n maybeChildPath = maybeChildPath.endsWith(\"/\") ? maybeChildPath : maybeChildPath + \"/\";\n return maybeChildPath.startsWith(parentPath);\n}\nimport.meta.vitest?.test(\"isSubPath\", ({ expect }) => {\n expect(isChildPath(\"/\", \"/\")).toBe(true);\n expect(isChildPath(\"/\", \"/path\")).toBe(true);\n expect(isChildPath(\"/path\", \"/\")).toBe(false);\n expect(isChildPath(\"/path\", \"/path\")).toBe(true);\n expect(isChildPath(\"/path/\", \"/path\")).toBe(true);\n expect(isChildPath(\"/path\", \"/path/\")).toBe(true);\n expect(isChildPath(\"/path/\", \"/path/\")).toBe(true);\n expect(isChildPath(\"/path\", \"/path/abc\")).toBe(true);\n expect(isChildPath(\"/path/\", \"/path/abc\")).toBe(true);\n expect(isChildPath(\"/path\", \"/path-abc\")).toBe(false);\n expect(isChildPath(\"/path\", \"/path-abc/\")).toBe(false);\n expect(isChildPath(\"/path/\", \"/path-abc\")).toBe(false);\n expect(isChildPath(\"/path/\", \"/path-abc/\")).toBe(false);\n});\n"],"mappings":";;;;AAGA,SAAgB,iBAAiB,GAAG,MAAyC;AAC3E,KAAI;AACF,SAAO,IAAI,IAAI,GAAG,KAAK;UAChB,GAAG;AACV,SAAO;;;CAGX,SAAW,KAAC,qBAAc,EAAA,aAAsB;AAE9C,QAAO,iBAAiB,sBAAsB,CAAC,CAAC,eAAe,IAAI;AACnE,QAAO,iBAAiB,4CAA4C,CAAC,CAAC,eAAe,IAAI;AACzF,QAAO,iBAAiB,SAAS,sBAAsB,CAAC,CAAC,eAAe,IAAI;AAG5E,QAAO,iBAAiB,GAAG,CAAC,CAAC,UAAU;AACvC,QAAO,iBAAiB,YAAY,CAAC,CAAC,UAAU;AAChD,QAAO,iBAAiB,UAAU,CAAC,CAAC,UAAU;EAC9C;AAEF,SAAgB,WAAW,KAAa;AACtC,QAAO,CAAC,CAAC,iBAAiB,IAAI;;CAEhC,SAAW,KAAC,eAAc,EAAA,aAAgB;AAExC,QAAO,WAAW,sBAAsB,CAAC,CAAC,KAAK,KAAK;AACpD,QAAO,WAAW,wBAAwB,CAAC,CAAC,KAAK,KAAK;AACtD,QAAO,WAAW,oBAAoB,CAAC,CAAC,KAAK,KAAK;AAGlD,QAAO,WAAW,GAAG,CAAC,CAAC,KAAK,MAAM;AAClC,QAAO,WAAW,YAAY,CAAC,CAAC,KAAK,MAAM;AAC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QAAO,YAAY,UAAU,YAAY,CAAC,CAAC,KAAK,KAAK;AACrD,QAAO,YAAY,SAAS,YAAY,CAAC,CAAC,KAAK,MAAM;AACrD,QAAO,YAAY,SAAS,aAAa,CAAC,CAAC,KAAK,MAAM;AACtD,QAAO,YAAY,UAAU,YAAY,CAAC,CAAC,KAAK,MAAM;AACtD,QAAO,YAAY,UAAU,aAAa,CAAC,CAAC,KAAK,MAAM;EACvD"}
|
|
1
|
+
{"version":3,"file":"urls.js","names":[],"sources":["../../../src/utils/urls.tsx"],"sourcesContent":["import { generateSecureRandomString } from \"./crypto\";\nimport { templateIdentity } from \"./strings\";\n\nexport function createUrlIfValid(...args: ConstructorParameters<typeof URL>) {\n try {\n return new URL(...args);\n } catch (e) {\n return null;\n }\n}\nimport.meta.vitest?.test(\"createUrlIfValid\", ({ expect }) => {\n // Test with valid URLs\n expect(createUrlIfValid(\"https://example.com\")).toBeInstanceOf(URL);\n expect(createUrlIfValid(\"https://example.com/path?query=value#hash\")).toBeInstanceOf(URL);\n expect(createUrlIfValid(\"/path\", \"https://example.com\")).toBeInstanceOf(URL);\n\n // Test with invalid URLs\n expect(createUrlIfValid(\"\")).toBeNull();\n expect(createUrlIfValid(\"not a url\")).toBeNull();\n expect(createUrlIfValid(\"http://\")).toBeNull();\n});\n\nexport function isValidUrl(url: string) {\n return !!createUrlIfValid(url);\n}\nimport.meta.vitest?.test(\"isValidUrl\", ({ expect }) => {\n // Test with valid URLs\n expect(isValidUrl(\"https://example.com\")).toBe(true);\n expect(isValidUrl(\"http://localhost:3000\")).toBe(true);\n expect(isValidUrl(\"ftp://example.com\")).toBe(true);\n\n // Test with invalid URLs\n expect(isValidUrl(\"\")).toBe(false);\n expect(isValidUrl(\"not a url\")).toBe(false);\n expect(isValidUrl(\"http://\")).toBe(false);\n});\n\nexport function isValidHostname(hostname: string) {\n // Basic validation\n if (!hostname || hostname.startsWith('.') || hostname.endsWith('.') || hostname.includes('..')) {\n return false;\n }\n\n const url = createUrlIfValid(`https://${hostname}`);\n if (!url) return false;\n return url.hostname === hostname;\n}\nimport.meta.vitest?.test(\"isValidHostname\", ({ expect }) => {\n // Test with valid hostnames\n expect(isValidHostname(\"example.com\")).toBe(true);\n expect(isValidHostname(\"localhost\")).toBe(true);\n expect(isValidHostname(\"sub.domain.example.com\")).toBe(true);\n expect(isValidHostname(\"127.0.0.1\")).toBe(true);\n\n // Test with invalid hostnames\n expect(isValidHostname(\"\")).toBe(false);\n expect(isValidHostname(\"example.com/path\")).toBe(false);\n expect(isValidHostname(\"https://example.com\")).toBe(false);\n expect(isValidHostname(\"example com\")).toBe(false);\n});\n\nexport function isValidHostnameWithWildcards(hostname: string) {\n // Empty hostnames are invalid\n if (!hostname) return false;\n\n // Check if it contains wildcards\n const hasWildcard = hostname.includes('*');\n\n if (!hasWildcard) {\n // If no wildcards, validate as a normal hostname\n return isValidHostname(hostname);\n }\n\n // Basic validation checks that apply even with wildcards\n // - Hostname cannot start or end with a dot\n if (hostname.startsWith('.') || hostname.endsWith('.')) {\n return false;\n }\n\n // - No consecutive dots\n if (hostname.includes('..')) {\n return false;\n }\n\n // For wildcard validation, check that non-wildcard parts contain valid characters\n // Replace wildcards with a valid placeholder to check the rest\n const testHostname = hostname.replace(/\\*+/g, 'wildcard');\n\n // Check if the resulting string would be a valid hostname\n if (!/^[a-zA-Z0-9.-]+$/.test(testHostname)) {\n return false;\n }\n\n // Additional check: ensure the pattern makes sense\n // Check each segment between wildcards\n const segments = hostname.split(/\\*+/);\n for (let i = 0; i < segments.length; i++) {\n const segment = segments[i];\n if (segment === '') continue; // Empty segments are OK (consecutive wildcards)\n\n // First segment can't start with dot\n if (i === 0 && segment.startsWith('.')) {\n return false;\n }\n\n // Last segment can't end with dot\n if (i === segments.length - 1 && segment.endsWith('.')) {\n return false;\n }\n\n // No segment should have consecutive dots\n if (segment.includes('..')) {\n return false;\n }\n }\n\n return true;\n}\nimport.meta.vitest?.test(\"isValidHostnameWithWildcards\", ({ expect }) => {\n // Test with valid regular hostnames\n expect(isValidHostnameWithWildcards(\"example.com\")).toBe(true);\n expect(isValidHostnameWithWildcards(\"localhost\")).toBe(true);\n expect(isValidHostnameWithWildcards(\"sub.domain.example.com\")).toBe(true);\n\n // Test with valid wildcard hostnames\n expect(isValidHostnameWithWildcards(\"*.example.com\")).toBe(true);\n expect(isValidHostnameWithWildcards(\"a-*.example.com\")).toBe(true);\n expect(isValidHostnameWithWildcards(\"*.*.org\")).toBe(true);\n expect(isValidHostnameWithWildcards(\"**.example.com\")).toBe(true);\n expect(isValidHostnameWithWildcards(\"sub.**.com\")).toBe(true);\n expect(isValidHostnameWithWildcards(\"*-api.*.com\")).toBe(true);\n\n // Test with invalid hostnames\n expect(isValidHostnameWithWildcards(\"\")).toBe(false);\n expect(isValidHostnameWithWildcards(\"example.com/path\")).toBe(false);\n expect(isValidHostnameWithWildcards(\"https://example.com\")).toBe(false);\n expect(isValidHostnameWithWildcards(\"example com\")).toBe(false);\n expect(isValidHostnameWithWildcards(\".example.com\")).toBe(false);\n expect(isValidHostnameWithWildcards(\"example.com.\")).toBe(false);\n expect(isValidHostnameWithWildcards(\"example..com\")).toBe(false);\n expect(isValidHostnameWithWildcards(\"*.example..com\")).toBe(false);\n});\n\nexport function matchHostnamePattern(pattern: string, hostname: string): boolean {\n // If no wildcards, it's an exact match\n if (!pattern.includes('*')) {\n return pattern === hostname;\n }\n\n // Convert the pattern to a regex\n // First, escape all regex special characters except *\n let regexPattern = pattern.replace(/[.+?^${}()|[\\]\\\\]/g, '\\\\$&');\n\n // Use a placeholder for ** to handle it separately from single *\n const doubleWildcardPlaceholder = '\\x00DOUBLE_WILDCARD\\x00';\n regexPattern = regexPattern.replace(/\\*\\*/g, doubleWildcardPlaceholder);\n\n // Replace single * with a pattern that matches anything except dots\n regexPattern = regexPattern.replace(/\\*/g, '[^.]*');\n\n // Replace the double wildcard placeholder with a pattern that matches anything including dots\n regexPattern = regexPattern.replace(new RegExp(doubleWildcardPlaceholder, 'g'), '.*');\n\n // Anchor the pattern to match the entire hostname\n regexPattern = '^' + regexPattern + '$';\n\n try {\n const regex = new RegExp(regexPattern);\n return regex.test(hostname);\n } catch {\n return false;\n }\n}\nimport.meta.vitest?.test(\"matchHostnamePattern\", ({ expect }) => {\n // Test exact matches\n expect(matchHostnamePattern(\"example.com\", \"example.com\")).toBe(true);\n expect(matchHostnamePattern(\"example.com\", \"other.com\")).toBe(false);\n\n // Test single wildcard matches\n expect(matchHostnamePattern(\"*.example.com\", \"api.example.com\")).toBe(true);\n expect(matchHostnamePattern(\"*.example.com\", \"www.example.com\")).toBe(true);\n expect(matchHostnamePattern(\"*.example.com\", \"example.com\")).toBe(false);\n expect(matchHostnamePattern(\"*.example.com\", \"api.v2.example.com\")).toBe(false);\n\n // Test double wildcard matches\n expect(matchHostnamePattern(\"**.example.com\", \"api.example.com\")).toBe(true);\n expect(matchHostnamePattern(\"**.example.com\", \"api.v2.example.com\")).toBe(true);\n expect(matchHostnamePattern(\"**.example.com\", \"a.b.c.example.com\")).toBe(true);\n expect(matchHostnamePattern(\"**.example.com\", \"example.com\")).toBe(false);\n\n // Test complex patterns\n expect(matchHostnamePattern(\"api-*.example.com\", \"api-v1.example.com\")).toBe(true);\n expect(matchHostnamePattern(\"api-*.example.com\", \"api-v2.example.com\")).toBe(true);\n expect(matchHostnamePattern(\"api-*.example.com\", \"api.example.com\")).toBe(false);\n expect(matchHostnamePattern(\"*.*.org\", \"mail.example.org\")).toBe(true);\n expect(matchHostnamePattern(\"*.*.org\", \"example.org\")).toBe(false);\n});\n\nexport function getHardcodedFallbackUrls(primaryBaseUrl: string): string[] {\n // `defaultBaseUrl` in `@stackframe/*` SDK builds is `https://api.stack-auth.com`\n // (see `packages/template/src/lib/hexclave-app/apps/implementations/common.ts`).\n // The `@hexclave/*` mirror packages will get this rewritten to the hexclave\n // hostname by `scripts/rewrite-packages-to-hexclave.ts` in a follow-up PR; both\n // branches below stay listed so either build resolves its own fallback set.\n if (primaryBaseUrl === \"https://api.stack-auth.com\") {\n return [\"https://api1.stack-auth.com\", \"https://api2.stack-auth.com\"];\n }\n if (primaryBaseUrl === \"https://api.dev.stack-auth.com\") {\n return [\"https://api1.dev.stack-auth.com\", \"https://api2.dev.stack-auth.com\"];\n }\n if (primaryBaseUrl === \"https://api.hexclave.com\") {\n return [\"https://api1.hexclave.com\", \"https://api2.hexclave.com\"];\n }\n if (primaryBaseUrl === \"https://api.dev.hexclave.com\") {\n return [\"https://api1.dev.hexclave.com\", \"https://api2.dev.hexclave.com\"];\n }\n const localhostMatch = primaryBaseUrl.match(/^http:\\/\\/localhost:(\\d+)02$/);\n if (localhostMatch) {\n return [`http://localhost:${localhostMatch[1]}10`];\n }\n return [];\n}\n\nexport function getDefaultApiUrls(primaryBaseUrl: string): string[] {\n return [primaryBaseUrl, ...getHardcodedFallbackUrls(primaryBaseUrl)];\n}\n\nexport function isLocalhost(urlOrString: string | URL) {\n const url = createUrlIfValid(urlOrString);\n if (!url) return false;\n if (url.hostname === \"localhost\" || url.hostname.endsWith(\".localhost\")) return true;\n if (url.hostname.match(/^127\\.\\d+\\.\\d+\\.\\d+$/)) return true;\n if (url.hostname === \"[::1]\" || url.hostname === \"::1\") return true;\n return false;\n}\nimport.meta.vitest?.test(\"isLocalhost\", ({ expect }) => {\n // Test with localhost URLs\n expect(isLocalhost(\"http://localhost\")).toBe(true);\n expect(isLocalhost(\"https://localhost:8080\")).toBe(true);\n expect(isLocalhost(\"http://sub.localhost\")).toBe(true);\n expect(isLocalhost(\"http://127.0.0.1\")).toBe(true);\n expect(isLocalhost(\"http://127.1.2.3\")).toBe(true);\n expect(isLocalhost(\"http://[::1]\")).toBe(true);\n\n // Test with non-localhost URLs\n expect(isLocalhost(\"https://example.com\")).toBe(false);\n expect(isLocalhost(\"http://192.168.1.1\")).toBe(false);\n expect(isLocalhost(\"http://10.0.0.1\")).toBe(false);\n\n // Test with URL objects\n expect(isLocalhost(new URL(\"http://localhost\"))).toBe(true);\n expect(isLocalhost(new URL(\"https://example.com\"))).toBe(false);\n\n // Test with invalid URLs\n expect(isLocalhost(\"not a url\")).toBe(false);\n expect(isLocalhost(\"\")).toBe(false);\n});\n\nexport function isRelative(url: string) {\n const randomDomain = `${generateSecureRandomString()}.stack-auth.example.com`;\n const u = createUrlIfValid(url, `https://${randomDomain}`);\n if (!u) return false;\n if (u.host !== randomDomain) return false;\n if (u.protocol !== \"https:\") return false;\n return true;\n}\nimport.meta.vitest?.test(\"isRelative\", ({ expect }) => {\n // We can't easily mock generateSecureRandomString in this context\n // but we can still test the function's behavior\n\n // Test with relative URLs\n expect(isRelative(\"/\")).toBe(true);\n expect(isRelative(\"/path\")).toBe(true);\n expect(isRelative(\"/path?query=value#hash\")).toBe(true);\n\n // Test with absolute URLs\n expect(isRelative(\"https://example.com\")).toBe(false);\n expect(isRelative(\"http://example.com\")).toBe(false);\n expect(isRelative(\"//example.com\")).toBe(false);\n\n // Note: The implementation treats empty strings and invalid URLs as relative\n // This is because they can be resolved against a base URL\n expect(isRelative(\"\")).toBe(true);\n expect(isRelative(\"not a url\")).toBe(true);\n});\n\nexport function getRelativePart(url: URL) {\n return url.pathname + url.search + url.hash;\n}\nimport.meta.vitest?.test(\"getRelativePart\", ({ expect }) => {\n // Test with various URLs\n expect(getRelativePart(new URL(\"https://example.com\"))).toBe(\"/\");\n expect(getRelativePart(new URL(\"https://example.com/path\"))).toBe(\"/path\");\n expect(getRelativePart(new URL(\"https://example.com/path?query=value\"))).toBe(\"/path?query=value\");\n expect(getRelativePart(new URL(\"https://example.com/path#hash\"))).toBe(\"/path#hash\");\n expect(getRelativePart(new URL(\"https://example.com/path?query=value#hash\"))).toBe(\"/path?query=value#hash\");\n\n // Test with different domains but same paths\n const url1 = new URL(\"https://example.com/path?query=value#hash\");\n const url2 = new URL(\"https://different.com/path?query=value#hash\");\n expect(getRelativePart(url1)).toBe(getRelativePart(url2));\n});\n\n/**\n * A template literal tag that returns a URL.\n *\n * Any values passed are encoded.\n */\nexport function url(strings: TemplateStringsArray | readonly string[], ...values: (string | number | boolean)[]): URL {\n return new URL(urlString(strings, ...values));\n}\nimport.meta.vitest?.test(\"url\", ({ expect }) => {\n // Test with no interpolation\n expect(url`https://example.com`).toBeInstanceOf(URL);\n expect(url`https://example.com`.href).toBe(\"https://example.com/\");\n\n // Test with string interpolation\n expect(url`https://example.com/${\"path\"}`).toBeInstanceOf(URL);\n expect(url`https://example.com/${\"path\"}`.pathname).toBe(\"/path\");\n\n // Test with number interpolation\n expect(url`https://example.com/${42}`).toBeInstanceOf(URL);\n expect(url`https://example.com/${42}`.pathname).toBe(\"/42\");\n\n // Test with boolean interpolation\n expect(url`https://example.com/${true}`).toBeInstanceOf(URL);\n expect(url`https://example.com/${true}`.pathname).toBe(\"/true\");\n\n // Test with special characters in interpolation\n expect(url`https://example.com/${\"path with spaces\"}`).toBeInstanceOf(URL);\n expect(url`https://example.com/${\"path with spaces\"}`.pathname).toBe(\"/path%20with%20spaces\");\n\n // Test with multiple interpolations\n expect(url`https://example.com/${\"path\"}?query=${\"value\"}`).toBeInstanceOf(URL);\n expect(url`https://example.com/${\"path\"}?query=${\"value\"}`.pathname).toBe(\"/path\");\n expect(url`https://example.com/${\"path\"}?query=${\"value\"}`.search).toBe(\"?query=value\");\n});\n\n\n/**\n * A template literal tag that returns a URL string.\n *\n * Any values passed are encoded.\n */\nexport function urlString(strings: TemplateStringsArray | readonly string[], ...values: (string | number | boolean)[]): string {\n return templateIdentity(strings, ...values.map(encodeURIComponent));\n}\nimport.meta.vitest?.test(\"urlString\", ({ expect }) => {\n // Test with no interpolation\n expect(urlString`https://example.com`).toBe(\"https://example.com\");\n\n // Test with string interpolation\n expect(urlString`https://example.com/${\"path\"}`).toBe(\"https://example.com/path\");\n\n // Test with number interpolation\n expect(urlString`https://example.com/${42}`).toBe(\"https://example.com/42\");\n\n // Test with boolean interpolation\n expect(urlString`https://example.com/${true}`).toBe(\"https://example.com/true\");\n\n // Test with special characters in interpolation\n expect(urlString`https://example.com/${\"path with spaces\"}`).toBe(\"https://example.com/path%20with%20spaces\");\n expect(urlString`https://example.com/${\"?&=\"}`).toBe(\"https://example.com/%3F%26%3D\");\n\n // Test with multiple interpolations\n expect(urlString`https://example.com/${\"path\"}?query=${\"value\"}`).toBe(\"https://example.com/path?query=value\");\n expect(urlString`https://example.com/${\"path\"}?query=${\"value with spaces\"}`).toBe(\"https://example.com/path?query=value%20with%20spaces\");\n});\n\nexport function isChildUrl(parentUrl: URL, maybeChildUrl: URL) {\n return parentUrl.origin === maybeChildUrl.origin\n && isChildPath(parentUrl.pathname, maybeChildUrl.pathname)\n && [...parentUrl.searchParams].every(([key, value]) => maybeChildUrl.searchParams.get(key) === value)\n && (!parentUrl.hash || parentUrl.hash === maybeChildUrl.hash);\n}\nimport.meta.vitest?.test(\"isChildUrl\", ({ expect }) => {\n // true\n expect(isChildUrl(new URL(\"https://abc.com/\"), new URL(\"https://abc.com/\"))).toBe(true);\n expect(isChildUrl(new URL(\"https://abc.com/\"), new URL(\"https://abc.com/path\"))).toBe(true);\n expect(isChildUrl(new URL(\"https://abc.com/\"), new URL(\"https://abc.com/path?query=value\"))).toBe(true);\n expect(isChildUrl(new URL(\"https://abc.com/\"), new URL(\"https://abc.com/path?query=value#hash\"))).toBe(true);\n\n // false\n expect(isChildUrl(new URL(\"https://abc.com\"), new URL(\"https://example.com\"))).toBe(false);\n expect(isChildUrl(new URL(\"https://abc.com/\"), new URL(\"https://example.com/path\"))).toBe(false);\n expect(isChildUrl(new URL(\"https://abc.com/\"), new URL(\"https://example.com/path?query=value\"))).toBe(false);\n expect(isChildUrl(new URL(\"https://abc.com/\"), new URL(\"https://example.com/path?query=value#hash\"))).toBe(false);\n expect(isChildUrl(new URL(\"https://example.com\"), new URL(\"https://abc.com/path?query=value#hash\"))).toBe(false);\n expect(isChildUrl(new URL(\"https://example.com?query=value123\"), new URL(\"https://example.com/path?query=value#hash\"))).toBe(false);\n});\n\nexport function isChildPath(parentPath: string, maybeChildPath: string) {\n parentPath = parentPath.endsWith(\"/\") ? parentPath : parentPath + \"/\";\n maybeChildPath = maybeChildPath.endsWith(\"/\") ? maybeChildPath : maybeChildPath + \"/\";\n return maybeChildPath.startsWith(parentPath);\n}\nimport.meta.vitest?.test(\"isSubPath\", ({ expect }) => {\n expect(isChildPath(\"/\", \"/\")).toBe(true);\n expect(isChildPath(\"/\", \"/path\")).toBe(true);\n expect(isChildPath(\"/path\", \"/\")).toBe(false);\n expect(isChildPath(\"/path\", \"/path\")).toBe(true);\n expect(isChildPath(\"/path/\", \"/path\")).toBe(true);\n expect(isChildPath(\"/path\", \"/path/\")).toBe(true);\n expect(isChildPath(\"/path/\", \"/path/\")).toBe(true);\n expect(isChildPath(\"/path\", \"/path/abc\")).toBe(true);\n expect(isChildPath(\"/path/\", \"/path/abc\")).toBe(true);\n expect(isChildPath(\"/path\", \"/path-abc\")).toBe(false);\n expect(isChildPath(\"/path\", \"/path-abc/\")).toBe(false);\n expect(isChildPath(\"/path/\", \"/path-abc\")).toBe(false);\n expect(isChildPath(\"/path/\", \"/path-abc/\")).toBe(false);\n});\n"],"mappings":";;;;AAGA,SAAgB,iBAAiB,GAAG,MAAyC;AAC3E,KAAI;AACF,SAAO,IAAI,IAAI,GAAG,KAAK;UAChB,GAAG;AACV,SAAO;;;CAGX,SAAW,KAAC,qBAAc,EAAA,aAAsB;AAE9C,QAAO,iBAAiB,sBAAsB,CAAC,CAAC,eAAe,IAAI;AACnE,QAAO,iBAAiB,4CAA4C,CAAC,CAAC,eAAe,IAAI;AACzF,QAAO,iBAAiB,SAAS,sBAAsB,CAAC,CAAC,eAAe,IAAI;AAG5E,QAAO,iBAAiB,GAAG,CAAC,CAAC,UAAU;AACvC,QAAO,iBAAiB,YAAY,CAAC,CAAC,UAAU;AAChD,QAAO,iBAAiB,UAAU,CAAC,CAAC,UAAU;EAC9C;AAEF,SAAgB,WAAW,KAAa;AACtC,QAAO,CAAC,CAAC,iBAAiB,IAAI;;CAEhC,SAAW,KAAC,eAAc,EAAA,a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AS,QAAQ,CAAC,CAAC,KAAK,KAAK;AAChD,QAAO,YAAY,UAAU,QAAQ,CAAC,CAAC,KAAK,KAAK;AACjD,QAAO,YAAY,SAAS,SAAS,CAAC,CAAC,KAAK,KAAK;AACjD,QAAO,YAAY,UAAU,SAAS,CAAC,CAAC,KAAK,KAAK;AAClD,QAAO,YAAY,SAAS,YAAY,CAAC,CAAC,KAAK,KAAK;AACpD,QAAO,YAAY,UAAU,YAAY,CAAC,CAAC,KAAK,KAAK;AACrD,QAAO,YAAY,SAAS,YAAY,CAAC,CAAC,KAAK,MAAM;AACrD,QAAO,YAAY,SAAS,aAAa,CAAC,CAAC,KAAK,MAAM;AACtD,QAAO,YAAY,UAAU,YAAY,CAAC,CAAC,KAAK,MAAM;AACtD,QAAO,YAAY,UAAU,aAAa,CAAC,CAAC,KAAK,MAAM;EACvD"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"client-side.d.ts","names":[],"sources":["../../../src/helpers/vault/client-side.ts"],"mappings":";;
|
|
1
|
+
{"version":3,"file":"client-side.d.ts","names":[],"sources":["../../../src/helpers/vault/client-side.ts"],"mappings":";;AAuBA;;iBAAsB,OAAA,CAAQ,MAAA,UAAgB,GAAA,WAAW,OAAA;;;;iBAWnC,YAAA,CAAa,MAAA,UAAgB,GAAA,UAAa,KAAA,WAAa,OAAA;;;AAA7E;iBAcsB,YAAA,CAAa,MAAA,UAAgB,GAAA,UAAa,cAAA,WAAsB,OAAA"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"client-side.js","names":[],"sources":["../../../src/helpers/vault/client-side.ts"],"sourcesContent":["import { decodeBase64, encodeBase64 } from \"../../utils/bytes\";\nimport { decrypt, encrypt, hash, iteratedHash } from \"../../utils/crypto\";\n\nconst hashPurpose = \"stack-data-vault-client-side-encryption-key-hash\";\nconst encryptionSecretPurpose = \"stack-data-vault-client-side-encryption-value-encryption-key-hash\";\nconst encryptionValuePurpose = \"stack-data-vault-client-side-encryption-value-encryption-value-encryption\";\n\n\nasync function getDerivedKey(secret: string, key: string) {\n return await iteratedHash({\n purpose: encryptionSecretPurpose,\n extra: secret,\n value: key,\n iterations: 100_000,\n });\n}\n\n/**\n * Use to hash the key so the server cannot infer it.\n */\nexport async function hashKey(secret: string, key: string) {\n return encodeBase64(await hash({\n purpose: hashPurpose,\n extra: secret,\n value: await getDerivedKey(secret, key),\n }));\n}\n\n/**\n * Use to encrypt the value so that the server cannot read the value without knowing the key.\n */\nexport async function encryptValue(secret: string, key: string, value: string) {\n const valueEncryptionDerivedKey = await getDerivedKey(secret, key);\n\n const bytes = await encrypt({\n purpose: encryptionValuePurpose,\n secret: valueEncryptionDerivedKey,\n value: new TextEncoder().encode(value)\n });\n return encodeBase64(bytes);\n}\n\n/**\n * Use to decrypt the value. See encryptValue.\n */\nexport async function decryptValue(secret: string, key: string, encryptedValue: string) {\n const valueEncryptionDerivedKey = await getDerivedKey(secret, key);\n\n const bytesResult = await decrypt({\n purpose: encryptionValuePurpose,\n secret: valueEncryptionDerivedKey,\n cipher: decodeBase64(encryptedValue),\n });\n if (bytesResult.status === \"error\") throw new Error(\"Data vault client-side decryption failed. Are you sure you're using the correct secret?\", { cause: bytesResult.error });\n return new TextDecoder().decode(bytesResult.data);\n}\n\n\nimport.meta.vitest?.describe(\"encryptValue & decryptValue\", () => {\n import.meta.vitest?.it(\"should encrypt and decrypt a value\", async ({ expect }) => {\n const secret = \"test-secret\";\n const value = \"test-value\";\n const encrypted = await encryptValue(secret, \"key\", value);\n const decrypted = await decryptValue(secret, \"key\", encrypted);\n expect(decrypted).toEqual(value);\n });\n\n import.meta.vitest?.it(\"should not decrypt a value with a different secret\", async ({ expect }) => {\n const secret = \"test-secret\";\n const value = \"test-value\";\n const encrypted = await encryptValue(secret, \"key\", value);\n await expect(decryptValue(\"different-secret\", \"key\", encrypted)).rejects.toThrow();\n });\n\n import.meta.vitest?.it(\"should not decrypt a value with a different key\", async ({ expect }) => {\n const secret = \"test-secret\";\n const value = \"test-value\";\n const encrypted = await encryptValue(secret, \"key\", value);\n await expect(decryptValue(secret, \"different-key\", encrypted)).rejects.toThrow();\n });\n\n import.meta.vitest?.it(\"should not decrypt a value if the cipher was tampered with\", async ({ expect }) => {\n const secret = \"test-secret\";\n const value = \"test-value\";\n const encrypted = await encryptValue(secret, \"key\", value);\n const tampered = encrypted + \"7\";\n await expect(decryptValue(secret, \"key\", tampered)).rejects.toThrow();\n });\n});\n"],"mappings":";;;;;;
|
|
1
|
+
{"version":3,"file":"client-side.js","names":[],"sources":["../../../src/helpers/vault/client-side.ts"],"sourcesContent":["import { decodeBase64, encodeBase64 } from \"../../utils/bytes\";\nimport { decrypt, encrypt, hash, iteratedHash } from \"../../utils/crypto\";\n\n// NOTE (Hexclave rebrand): do NOT rename these \"stack-*\" purpose tags. They are mixed into the\n// vault's key derivation and value encryption; renaming any of them would make every\n// previously-stored vault value undecryptable. Internal constants, never user-visible.\nconst hashPurpose = \"stack-data-vault-client-side-encryption-key-hash\";\nconst encryptionSecretPurpose = \"stack-data-vault-client-side-encryption-value-encryption-key-hash\";\nconst encryptionValuePurpose = \"stack-data-vault-client-side-encryption-value-encryption-value-encryption\";\n\n\nasync function getDerivedKey(secret: string, key: string) {\n return await iteratedHash({\n purpose: encryptionSecretPurpose,\n extra: secret,\n value: key,\n iterations: 100_000,\n });\n}\n\n/**\n * Use to hash the key so the server cannot infer it.\n */\nexport async function hashKey(secret: string, key: string) {\n return encodeBase64(await hash({\n purpose: hashPurpose,\n extra: secret,\n value: await getDerivedKey(secret, key),\n }));\n}\n\n/**\n * Use to encrypt the value so that the server cannot read the value without knowing the key.\n */\nexport async function encryptValue(secret: string, key: string, value: string) {\n const valueEncryptionDerivedKey = await getDerivedKey(secret, key);\n\n const bytes = await encrypt({\n purpose: encryptionValuePurpose,\n secret: valueEncryptionDerivedKey,\n value: new TextEncoder().encode(value)\n });\n return encodeBase64(bytes);\n}\n\n/**\n * Use to decrypt the value. See encryptValue.\n */\nexport async function decryptValue(secret: string, key: string, encryptedValue: string) {\n const valueEncryptionDerivedKey = await getDerivedKey(secret, key);\n\n const bytesResult = await decrypt({\n purpose: encryptionValuePurpose,\n secret: valueEncryptionDerivedKey,\n cipher: decodeBase64(encryptedValue),\n });\n if (bytesResult.status === \"error\") throw new Error(\"Data vault client-side decryption failed. Are you sure you're using the correct secret?\", { cause: bytesResult.error });\n return new TextDecoder().decode(bytesResult.data);\n}\n\n\nimport.meta.vitest?.describe(\"encryptValue & decryptValue\", () => {\n import.meta.vitest?.it(\"should encrypt and decrypt a value\", async ({ expect }) => {\n const secret = \"test-secret\";\n const value = \"test-value\";\n const encrypted = await encryptValue(secret, \"key\", value);\n const decrypted = await decryptValue(secret, \"key\", encrypted);\n expect(decrypted).toEqual(value);\n });\n\n import.meta.vitest?.it(\"should not decrypt a value with a different secret\", async ({ expect }) => {\n const secret = \"test-secret\";\n const value = \"test-value\";\n const encrypted = await encryptValue(secret, \"key\", value);\n await expect(decryptValue(\"different-secret\", \"key\", encrypted)).rejects.toThrow();\n });\n\n import.meta.vitest?.it(\"should not decrypt a value with a different key\", async ({ expect }) => {\n const secret = \"test-secret\";\n const value = \"test-value\";\n const encrypted = await encryptValue(secret, \"key\", value);\n await expect(decryptValue(secret, \"different-key\", encrypted)).rejects.toThrow();\n });\n\n import.meta.vitest?.it(\"should not decrypt a value if the cipher was tampered with\", async ({ expect }) => {\n const secret = \"test-secret\";\n const value = \"test-value\";\n const encrypted = await encryptValue(secret, \"key\", value);\n const tampered = encrypted + \"7\";\n await expect(decryptValue(secret, \"key\", tampered)).rejects.toThrow();\n });\n});\n"],"mappings":";;;;;;AAMA,MAAM,cAAc;AACpB,MAAM,0BAA0B;AAChC,MAAM,yBAAyB;AAG/B,eAAe,cAAc,QAAgB,KAAa;AACxD,QAAO,8CAAmB;EACxB,SAAS;EACT,OAAO;EACP,OAAO;EACP,YAAY;EACb,CAAC;;;;;AAMJ,eAAsB,QAAQ,QAAgB,KAAa;AACzD,+CAA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,GAC7B,IACqB,CAAC,CAAC,QAAQ,SAAS;GACrE;EACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"server-side.d.ts","names":[],"sources":["../../../src/helpers/vault/server-side.ts"],"mappings":";
|
|
1
|
+
{"version":3,"file":"server-side.d.ts","names":[],"sources":["../../../src/helpers/vault/server-side.ts"],"mappings":";iBA4HsB,cAAA,CAAe,KAAA,WAAa,OAAA;;;;iBAgB5B,cAAA,CAAe,SAAA,EAAW,OAAA,CAAQ,UAAA,QAAkB,cAAA,KAAgB,OAAA"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"server-side.js","names":["KMSClient","DescribeKeyCommand","CreateKeyCommand","CreateAliasCommand","GenerateDataKeyCommand","DecryptCommand","Result"],"sources":["../../../src/helpers/vault/server-side.ts"],"sourcesContent":["import {\n CreateAliasCommand,\n CreateKeyCommand,\n DecryptCommand,\n DescribeKeyCommand,\n GenerateDataKeyCommand,\n KMSClient\n} from \"@aws-sdk/client-kms\";\nimport { decodeBase64, encodeBase64 } from \"../../utils/bytes\";\nimport { decrypt, encrypt } from \"../../utils/crypto\";\nimport { getEnvVariable } from \"../../utils/env\";\nimport { Result } from \"../../utils/results\";\n\n\nasync function getAwsCredentials() {\n // 1. Vercel OIDC: Vercel injects an OIDC token that can be exchanged for AWS credentials\n const vercelRoleArn = getEnvVariable(\"STACK_AWS_VERCEL_OIDC_ROLE_ARN\", \"\");\n if (vercelRoleArn) {\n const { awsCredentialsProvider } = await import(\"@vercel/functions/oidc\");\n return awsCredentialsProvider({ roleArn: vercelRoleArn });\n }\n\n // 2. GCP Workload Identity Federation: Cloud Run gets a GCP ID token from the metadata server,\n // then exchanges it for temporary AWS credentials via STS AssumeRoleWithWebIdentity.\n // Requires:\n // - An OIDC identity provider in AWS IAM (issuer: https://accounts.google.com)\n // - An IAM role with a trust policy allowing the GCP service account\n // - STACK_AWS_GCP_WIF_ROLE_ARN set to that role's ARN\n // - STACK_AWS_GCP_WIF_AUDIENCE set to the audience configured in the AWS OIDC provider\n const gcpWifRoleArn = getEnvVariable(\"STACK_AWS_GCP_WIF_ROLE_ARN\", \"\");\n if (gcpWifRoleArn) {\n const { fromWebToken } = await import(\"@aws-sdk/credential-provider-web-identity\");\n const audience = getEnvVariable(\"STACK_AWS_GCP_WIF_AUDIENCE\", \"sts.amazonaws.com\");\n // Return a provider that fetches a fresh GCP ID token on each invocation.\n // GCP metadata tokens expire after ~1h, so we can't bake a single token into the closure.\n return async () => {\n return await fromWebToken({\n roleArn: gcpWifRoleArn,\n roleSessionName: \"stack-backend-cloudrun\",\n webIdentityToken: await fetchGcpIdToken(audience),\n })();\n };\n }\n\n // 3. Static credentials: fallback for self-hosted / local development\n return {\n accessKeyId: getEnvVariable(\"STACK_AWS_ACCESS_KEY_ID\"),\n secretAccessKey: getEnvVariable(\"STACK_AWS_SECRET_ACCESS_KEY\"),\n };\n}\n\n/**\n * Fetches a GCP ID token from the metadata server (available on Cloud Run, GCE, GKE).\n * The token is a Google-signed JWT with the specified audience, suitable for\n * AWS STS AssumeRoleWithWebIdentity.\n */\nasync function fetchGcpIdToken(audience: string): Promise<string> {\n const metadataUrl = `http://metadata.google.internal/computeMetadata/v1/instance/service-accounts/default/identity?audience=${encodeURIComponent(audience)}`;\n const response = await fetch(metadataUrl, {\n headers: { \"Metadata-Flavor\": \"Google\" },\n });\n if (!response.ok) {\n throw new Error(`Failed to fetch GCP ID token: ${response.status} ${await response.text()}`);\n }\n return await response.text();\n}\n\nlet kmsClientCache: KMSClient | undefined;\n\nasync function getKmsClient() {\n if (!kmsClientCache) {\n kmsClientCache = new KMSClient({\n region: getEnvVariable(\"STACK_AWS_REGION\"),\n endpoint: getEnvVariable(\"STACK_AWS_KMS_ENDPOINT\"),\n credentials: await getAwsCredentials(),\n });\n }\n return kmsClientCache;\n}\n\nasync function getOrCreateKekId(): Promise<string> {\n const id = \"alias/stack-data-vault-server-side-kek\";\n const kms = await getKmsClient();\n try {\n const describeResult = await kms.send(new DescribeKeyCommand({ KeyId: id }));\n if (describeResult.KeyMetadata?.KeyId) return describeResult.KeyMetadata.KeyId;\n } catch (e) {\n if (e instanceof Error && e.name !== \"NotFoundException\") {\n throw e;\n }\n }\n const { KeyMetadata } = await kms.send(new CreateKeyCommand({\n KeyUsage: \"ENCRYPT_DECRYPT\",\n Description: \"DataVault KEK\"\n }));\n await kms.send(new CreateAliasCommand({ AliasName: id, TargetKeyId: KeyMetadata!.KeyId! }));\n return id;\n}\n\nasync function genDEK() {\n const kekId = await getOrCreateKekId();\n const kms = await getKmsClient();\n const out = await kms.send(new GenerateDataKeyCommand({ KeyId: kekId, KeySpec: \"AES_256\" }));\n if (!out.Plaintext || !out.CiphertextBlob) throw new Error(\"GenerateDataKey failed\");\n return {\n dekBytes: out.Plaintext,\n edkBytes: out.CiphertextBlob,\n };\n}\n\nasync function unwrapDEK(edk_b64: string) {\n const edkBytes = decodeBase64(edk_b64);\n const kms = await getKmsClient();\n const out = await kms.send(new DecryptCommand({ CiphertextBlob: edkBytes }));\n if (!out.Plaintext) throw new Error(\"KMS Decrypt failed\");\n return {\n dekBytes: out.Plaintext,\n edkBytes,\n };\n}\n\nexport async function encryptWithKms(value: string) {\n const { dekBytes, edkBytes } = await genDEK();\n try {\n const ciphertext = await encrypt({\n purpose: \"stack-data-vault-server-side-encryption\",\n secret: dekBytes,\n value: new TextEncoder().encode(value),\n });\n return { edkBase64: encodeBase64(edkBytes), ciphertextBase64: encodeBase64(ciphertext) };\n } finally {\n dekBytes.fill(0);\n }\n}\n\nexport async function decryptWithKms(encrypted: Awaited<ReturnType<typeof encryptWithKms>>) {\n const { dekBytes } = await unwrapDEK(encrypted.edkBase64);\n try {\n const value = Result.orThrow(await decrypt({\n purpose: \"stack-data-vault-server-side-encryption\",\n secret: dekBytes,\n cipher: decodeBase64(encrypted.ciphertextBase64),\n }));\n return new TextDecoder().decode(value);\n } finally {\n dekBytes.fill(0);\n }\n}\n"],"mappings":";;;;;;;;;AAcA,eAAe,oBAAoB;CAEjC,MAAM,uDAA+B,kCAAkC,GAAG;AAC1E,KAAI,eAAe;EACjB,MAAM,EAAE,2BAA2B,MAAM,OAAO;AAChD,SAAO,uBAAuB,EAAE,SAAS,eAAe,CAAC;;CAU3D,MAAM,uDAA+B,8BAA8B,GAAG;AACtE,KAAI,eAAe;EACjB,MAAM,EAAE,iBAAiB,MAAM,OAAO;EACtC,MAAM,kDAA0B,8BAA8B,oBAAoB;AAGlF,SAAO,YAAY;AACjB,UAAO,MAAM,aAAa;IACxB,SAAS;IACT,iBAAiB;IACjB,kBAAkB,MAAM,gBAAgB,SAAS;IAClD,CAAC,EAAE;;;AAKR,QAAO;EACL,oDAA4B,0BAA0B;EACtD,wDAAgC,8BAA8B;EAC/D;;;;;;;AAQH,eAAe,gBAAgB,UAAmC;CAChE,MAAM,cAAc,0GAA0G,mBAAmB,SAAS;CAC1J,MAAM,WAAW,MAAM,MAAM,aAAa,EACxC,SAAS,EAAE,mBAAmB,UAAU,EACzC,CAAC;AACF,KAAI,CAAC,SAAS,GACZ,OAAM,IAAI,MAAM,iCAAiC,SAAS,OAAO,GAAG,MAAM,SAAS,MAAM,GAAG;AAE9F,QAAO,MAAM,SAAS,MAAM;;AAG9B,IAAI;AAEJ,eAAe,eAAe;AAC5B,KAAI,CAAC,eACH,kBAAiB,IAAIA,8BAAU;EAC7B,+CAAuB,mBAAmB;EAC1C,iDAAyB,yBAAyB;EAClD,aAAa,MAAM,mBAAmB;EACvC,CAAC;AAEJ,QAAO;;AAGT,eAAe,mBAAoC;
|
|
1
|
+
{"version":3,"file":"server-side.js","names":["KMSClient","DescribeKeyCommand","CreateKeyCommand","CreateAliasCommand","GenerateDataKeyCommand","DecryptCommand","Result"],"sources":["../../../src/helpers/vault/server-side.ts"],"sourcesContent":["import {\n CreateAliasCommand,\n CreateKeyCommand,\n DecryptCommand,\n DescribeKeyCommand,\n GenerateDataKeyCommand,\n KMSClient\n} from \"@aws-sdk/client-kms\";\nimport { decodeBase64, encodeBase64 } from \"../../utils/bytes\";\nimport { decrypt, encrypt } from \"../../utils/crypto\";\nimport { getEnvVariable } from \"../../utils/env\";\nimport { Result } from \"../../utils/results\";\n\n\nasync function getAwsCredentials() {\n // 1. Vercel OIDC: Vercel injects an OIDC token that can be exchanged for AWS credentials\n const vercelRoleArn = getEnvVariable(\"STACK_AWS_VERCEL_OIDC_ROLE_ARN\", \"\");\n if (vercelRoleArn) {\n const { awsCredentialsProvider } = await import(\"@vercel/functions/oidc\");\n return awsCredentialsProvider({ roleArn: vercelRoleArn });\n }\n\n // 2. GCP Workload Identity Federation: Cloud Run gets a GCP ID token from the metadata server,\n // then exchanges it for temporary AWS credentials via STS AssumeRoleWithWebIdentity.\n // Requires:\n // - An OIDC identity provider in AWS IAM (issuer: https://accounts.google.com)\n // - An IAM role with a trust policy allowing the GCP service account\n // - STACK_AWS_GCP_WIF_ROLE_ARN set to that role's ARN\n // - STACK_AWS_GCP_WIF_AUDIENCE set to the audience configured in the AWS OIDC provider\n const gcpWifRoleArn = getEnvVariable(\"STACK_AWS_GCP_WIF_ROLE_ARN\", \"\");\n if (gcpWifRoleArn) {\n const { fromWebToken } = await import(\"@aws-sdk/credential-provider-web-identity\");\n const audience = getEnvVariable(\"STACK_AWS_GCP_WIF_AUDIENCE\", \"sts.amazonaws.com\");\n // Return a provider that fetches a fresh GCP ID token on each invocation.\n // GCP metadata tokens expire after ~1h, so we can't bake a single token into the closure.\n return async () => {\n return await fromWebToken({\n roleArn: gcpWifRoleArn,\n roleSessionName: \"stack-backend-cloudrun\",\n webIdentityToken: await fetchGcpIdToken(audience),\n })();\n };\n }\n\n // 3. Static credentials: fallback for self-hosted / local development\n return {\n accessKeyId: getEnvVariable(\"STACK_AWS_ACCESS_KEY_ID\"),\n secretAccessKey: getEnvVariable(\"STACK_AWS_SECRET_ACCESS_KEY\"),\n };\n}\n\n/**\n * Fetches a GCP ID token from the metadata server (available on Cloud Run, GCE, GKE).\n * The token is a Google-signed JWT with the specified audience, suitable for\n * AWS STS AssumeRoleWithWebIdentity.\n */\nasync function fetchGcpIdToken(audience: string): Promise<string> {\n const metadataUrl = `http://metadata.google.internal/computeMetadata/v1/instance/service-accounts/default/identity?audience=${encodeURIComponent(audience)}`;\n const response = await fetch(metadataUrl, {\n headers: { \"Metadata-Flavor\": \"Google\" },\n });\n if (!response.ok) {\n throw new Error(`Failed to fetch GCP ID token: ${response.status} ${await response.text()}`);\n }\n return await response.text();\n}\n\nlet kmsClientCache: KMSClient | undefined;\n\nasync function getKmsClient() {\n if (!kmsClientCache) {\n kmsClientCache = new KMSClient({\n region: getEnvVariable(\"STACK_AWS_REGION\"),\n endpoint: getEnvVariable(\"STACK_AWS_KMS_ENDPOINT\"),\n credentials: await getAwsCredentials(),\n });\n }\n return kmsClientCache;\n}\n\nasync function getOrCreateKekId(): Promise<string> {\n // NOTE (Hexclave rebrand): do NOT rename this \"stack-*\" alias. It is the AWS KMS key alias for\n // the existing key-encryption key; renaming it would point at a non-existent key and break\n // wrap/unwrap of all stored data keys. Internal infrastructure constant, never user-visible.\n const id = \"alias/stack-data-vault-server-side-kek\";\n const kms = await getKmsClient();\n try {\n const describeResult = await kms.send(new DescribeKeyCommand({ KeyId: id }));\n if (describeResult.KeyMetadata?.KeyId) return describeResult.KeyMetadata.KeyId;\n } catch (e) {\n if (e instanceof Error && e.name !== \"NotFoundException\") {\n throw e;\n }\n }\n const { KeyMetadata } = await kms.send(new CreateKeyCommand({\n KeyUsage: \"ENCRYPT_DECRYPT\",\n Description: \"DataVault KEK\"\n }));\n await kms.send(new CreateAliasCommand({ AliasName: id, TargetKeyId: KeyMetadata!.KeyId! }));\n return id;\n}\n\nasync function genDEK() {\n const kekId = await getOrCreateKekId();\n const kms = await getKmsClient();\n const out = await kms.send(new GenerateDataKeyCommand({ KeyId: kekId, KeySpec: \"AES_256\" }));\n if (!out.Plaintext || !out.CiphertextBlob) throw new Error(\"GenerateDataKey failed\");\n return {\n dekBytes: out.Plaintext,\n edkBytes: out.CiphertextBlob,\n };\n}\n\nasync function unwrapDEK(edk_b64: string) {\n const edkBytes = decodeBase64(edk_b64);\n const kms = await getKmsClient();\n const out = await kms.send(new DecryptCommand({ CiphertextBlob: edkBytes }));\n if (!out.Plaintext) throw new Error(\"KMS Decrypt failed\");\n return {\n dekBytes: out.Plaintext,\n edkBytes,\n };\n}\n\nexport async function encryptWithKms(value: string) {\n const { dekBytes, edkBytes } = await genDEK();\n try {\n const ciphertext = await encrypt({\n // NOTE (Hexclave rebrand): do NOT rename this \"stack-*\" purpose tag — it must match the one\n // used in decryptWithKms below, or already-encrypted values become undecryptable.\n purpose: \"stack-data-vault-server-side-encryption\",\n secret: dekBytes,\n value: new TextEncoder().encode(value),\n });\n return { edkBase64: encodeBase64(edkBytes), ciphertextBase64: encodeBase64(ciphertext) };\n } finally {\n dekBytes.fill(0);\n }\n}\n\nexport async function decryptWithKms(encrypted: Awaited<ReturnType<typeof encryptWithKms>>) {\n const { dekBytes } = await unwrapDEK(encrypted.edkBase64);\n try {\n const value = Result.orThrow(await decrypt({\n purpose: \"stack-data-vault-server-side-encryption\",\n secret: dekBytes,\n cipher: decodeBase64(encrypted.ciphertextBase64),\n }));\n return new TextDecoder().decode(value);\n } finally {\n dekBytes.fill(0);\n }\n}\n"],"mappings":";;;;;;;;;AAcA,eAAe,oBAAoB;CAEjC,MAAM,uDAA+B,kCAAkC,GAAG;AAC1E,KAAI,eAAe;EACjB,MAAM,EAAE,2BAA2B,MAAM,OAAO;AAChD,SAAO,uBAAuB,EAAE,SAAS,eAAe,CAAC;;CAU3D,MAAM,uDAA+B,8BAA8B,GAAG;AACtE,KAAI,eAAe;EACjB,MAAM,EAAE,iBAAiB,MAAM,OAAO;EACtC,MAAM,kDAA0B,8BAA8B,oBAAoB;AAGlF,SAAO,YAAY;AACjB,UAAO,MAAM,aAAa;IACxB,SAAS;IACT,iBAAiB;IACjB,kBAAkB,MAAM,gBAAgB,SAAS;IAClD,CAAC,EAAE;;;AAKR,QA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B;AACpF,QAAO;EACL,UAAU,IAAI;EACd,UAAU,IAAI;EACf;;AAGH,eAAe,UAAU,SAAiB;CACxC,MAAM,kDAAwB,QAAQ;CAEtC,MAAM,MAAM,OADA,MAAM,cAAc,EACV,KAAK,IAAIC,mCAAe,EAAE,gBAAgB,UAAU,CAAC,CAAC;AAC5E,KAAI,CAAC,IAAI,UAAW,OAAM,IAAI,MAAM,qBAAqB;AACzD,QAAO;EACL,UAAU,IAAI;EACd;EACD;;AAGH,eAAsB,eAAe,OAAe;CAClD,MAAM,EAAE,UAAU,aAAa,MAAM,QAAQ;AAC7C,KAAI;EACF,MAAM,aAAa,yCAAc;GAG/B,SAAS;GACT,QAAQ;GACR,OAAO,IAAI,aAAa,CAAC,OAAO,MAAM;GACvC,CAAC;AACF,SAAO;GAAE,kDAAwB,SAAS;GAAE,yDAA+B,WAAW;GAAE;WAChF;AACR,WAAS,KAAK,EAAE;;;AAIpB,eAAsB,eAAe,WAAuD;CAC1F,MAAM,EAAE,aAAa,MAAM,UAAU,UAAU,UAAU;AACzD,KAAI;EACF,MAAM,QAAQC,8BAAO,QAAQ,yCAAc;GACzC,SAAS;GACT,QAAQ;GACR,+CAAqB,UAAU,iBAAiB;GACjD,CAAC,CAAC;AACH,SAAO,IAAI,aAAa,CAAC,OAAO,MAAM;WAC9B;AACR,WAAS,KAAK,EAAE"}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
//#region src/hexclave-config-file.d.ts
|
|
2
|
+
declare const showOnboardingHexclaveConfigValue = "show-onboarding";
|
|
3
|
+
/**
|
|
4
|
+
* Renders a config object into the source text of a `stack.config.ts` file.
|
|
5
|
+
*
|
|
6
|
+
* Browser-safe: kept here (next to `parseHexclaveConfigFileContent`) instead of in
|
|
7
|
+
* `config-rendering.ts` so dashboard client code can render config files
|
|
8
|
+
* without pulling in `fs` / `path`.
|
|
9
|
+
*/
|
|
10
|
+
declare function renderConfigFileContent(config: unknown, importPackage?: string): string;
|
|
11
|
+
type ParsedStackConfig = Record<string, unknown> | typeof showOnboardingHexclaveConfigValue;
|
|
12
|
+
declare function parseHexclaveConfigFileContent(content: string, filePath: string): ParsedStackConfig;
|
|
13
|
+
//#endregion
|
|
14
|
+
export { parseHexclaveConfigFileContent, renderConfigFileContent, showOnboardingHexclaveConfigValue };
|
|
15
|
+
//# sourceMappingURL=hexclave-config-file.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"hexclave-config-file.d.ts","names":[],"sources":["../src/hexclave-config-file.ts"],"mappings":";cAIa,iCAAA;AAAb;;;;;AAWA;;AAXA,iBAWgB,uBAAA,CAAwB,MAAA,WAAiB,aAAA;AAAA,KAmBpD,iBAAA,GAAoB,MAAA,2BAAiC,iCAAA;AAAA,iBA8D1C,8BAAA,CAA+B,OAAA,UAAiB,QAAA,WAAmB,iBAAA"}
|
|
@@ -6,13 +6,13 @@ let _babel_types = require("@babel/types");
|
|
|
6
6
|
_babel_types = require_chunk.__toESM(_babel_types);
|
|
7
7
|
let __config_format_js = require("./config/format.js");
|
|
8
8
|
|
|
9
|
-
//#region src/
|
|
10
|
-
const
|
|
9
|
+
//#region src/hexclave-config-file.ts
|
|
10
|
+
const showOnboardingHexclaveConfigValue = "show-onboarding";
|
|
11
11
|
const DEFAULT_CONFIG_IMPORT_PACKAGE = "@hexclave/js";
|
|
12
12
|
/**
|
|
13
13
|
* Renders a config object into the source text of a `stack.config.ts` file.
|
|
14
14
|
*
|
|
15
|
-
* Browser-safe: kept here (next to `
|
|
15
|
+
* Browser-safe: kept here (next to `parseHexclaveConfigFileContent`) instead of in
|
|
16
16
|
* `config-rendering.ts` so dashboard client code can render config files
|
|
17
17
|
* without pulling in `fs` / `path`.
|
|
18
18
|
*/
|
|
@@ -25,7 +25,7 @@ function renderConfigFileContent(config, importPackage) {
|
|
|
25
25
|
droppedKeys
|
|
26
26
|
});
|
|
27
27
|
if (droppedKeys.length > 0) throw new Error(`Config has conflicting keys that would be dropped during normalization: ${droppedKeys.map((k) => JSON.stringify(k)).join(", ")}`);
|
|
28
|
-
return `${`import type {
|
|
28
|
+
return `${`import type { HexclaveConfig } from "${importPackage ?? DEFAULT_CONFIG_IMPORT_PACKAGE}";`}\n\nexport const config: HexclaveConfig = ${JSON.stringify(normalizedConfig, null, 2)};\n`;
|
|
29
29
|
}
|
|
30
30
|
function unwrapStaticConfigExpression(expression) {
|
|
31
31
|
if (_babel_types.isTSAsExpression(expression) || _babel_types.isTSSatisfiesExpression(expression) || _babel_types.isTSTypeAssertion(expression) || _babel_types.isTSNonNullExpression(expression)) return unwrapStaticConfigExpression(expression.expression);
|
|
@@ -58,7 +58,7 @@ function evaluateStaticConfigExpression(expression) {
|
|
|
58
58
|
}
|
|
59
59
|
throw new Error(`Unsupported config expression: ${unwrapped.type}`);
|
|
60
60
|
}
|
|
61
|
-
function
|
|
61
|
+
function parseHexclaveConfigFileContent(content, filePath) {
|
|
62
62
|
if (content.trim() === "") return {};
|
|
63
63
|
const ast = _babel_parser.parse(content, {
|
|
64
64
|
sourceType: "module",
|
|
@@ -76,7 +76,7 @@ function parseStackConfigFileContent(content, filePath) {
|
|
|
76
76
|
}
|
|
77
77
|
|
|
78
78
|
//#endregion
|
|
79
|
-
exports.
|
|
79
|
+
exports.parseHexclaveConfigFileContent = parseHexclaveConfigFileContent;
|
|
80
80
|
exports.renderConfigFileContent = renderConfigFileContent;
|
|
81
|
-
exports.
|
|
82
|
-
//# sourceMappingURL=
|
|
81
|
+
exports.showOnboardingHexclaveConfigValue = showOnboardingHexclaveConfigValue;
|
|
82
|
+
//# sourceMappingURL=hexclave-config-file.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"hexclave-config-file.js","names":["t","parser"],"sources":["../src/hexclave-config-file.ts"],"sourcesContent":["import * as parser from \"@babel/parser\";\nimport * as t from \"@babel/types\";\nimport { isValidConfig, normalize } from \"./config/format\";\n\nexport const showOnboardingHexclaveConfigValue = \"show-onboarding\";\n\nconst DEFAULT_CONFIG_IMPORT_PACKAGE = \"@hexclave/js\";\n\n/**\n * Renders a config object into the source text of a `stack.config.ts` file.\n *\n * Browser-safe: kept here (next to `parseHexclaveConfigFileContent`) instead of in\n * `config-rendering.ts` so dashboard client code can render config files\n * without pulling in `fs` / `path`.\n */\nexport function renderConfigFileContent(config: unknown, importPackage?: string): string {\n if (!isValidConfig(config)) {\n throw new Error(\"Invalid config: expected a plain object.\");\n }\n\n const droppedKeys: string[] = [];\n const normalizedConfig = normalize(config, {\n onDotIntoNonObject: \"ignore\",\n onDotIntoNull: \"empty-object\",\n droppedKeys,\n });\n if (droppedKeys.length > 0) {\n throw new Error(`Config has conflicting keys that would be dropped during normalization: ${droppedKeys.map(k => JSON.stringify(k)).join(\", \")}`);\n }\n const pkg = importPackage ?? DEFAULT_CONFIG_IMPORT_PACKAGE;\n const importLine = `import type { HexclaveConfig } from \"${pkg}\";`;\n return `${importLine}\\n\\nexport const config: HexclaveConfig = ${JSON.stringify(normalizedConfig, null, 2)};\\n`;\n}\n\ntype ParsedStackConfig = Record<string, unknown> | typeof showOnboardingHexclaveConfigValue;\n\nfunction unwrapStaticConfigExpression(expression: t.Expression): t.Expression {\n if (\n t.isTSAsExpression(expression)\n || t.isTSSatisfiesExpression(expression)\n || t.isTSTypeAssertion(expression)\n || t.isTSNonNullExpression(expression)\n ) {\n return unwrapStaticConfigExpression(expression.expression);\n }\n return expression;\n}\n\nfunction evaluateStaticConfigExpression(expression: t.Expression): unknown {\n const unwrapped = unwrapStaticConfigExpression(expression);\n if (t.isStringLiteral(unwrapped)) return unwrapped.value;\n if (t.isBooleanLiteral(unwrapped)) return unwrapped.value;\n if (t.isNumericLiteral(unwrapped)) return unwrapped.value;\n if (t.isNullLiteral(unwrapped)) return null;\n if (t.isIdentifier(unwrapped) && unwrapped.name === \"undefined\") return undefined;\n if (t.isUnaryExpression(unwrapped) && unwrapped.operator === \"-\" && t.isNumericLiteral(unwrapped.argument)) {\n return -unwrapped.argument.value;\n }\n if (t.isArrayExpression(unwrapped)) {\n return unwrapped.elements.map((element) => {\n if (element == null || t.isSpreadElement(element)) {\n throw new Error(\"Config arrays cannot contain holes or spreads.\");\n }\n return evaluateStaticConfigExpression(element);\n });\n }\n if (t.isObjectExpression(unwrapped)) {\n const result: Record<string, unknown> = {};\n for (const property of unwrapped.properties) {\n if (t.isSpreadElement(property)) {\n throw new Error(\"Config objects cannot contain spreads.\");\n }\n if (property.computed) {\n throw new Error(\"Config object keys cannot be computed.\");\n }\n const key = t.isIdentifier(property.key)\n ? property.key.name\n : t.isStringLiteral(property.key) || t.isNumericLiteral(property.key)\n ? String(property.key.value)\n : null;\n if (key == null) {\n throw new Error(\"Unsupported config object key.\");\n }\n if (t.isObjectMethod(property)) {\n throw new Error(\"Config objects cannot contain methods.\");\n }\n if (!t.isExpression(property.value)) {\n throw new Error(\"Unsupported config object value.\");\n }\n result[key] = evaluateStaticConfigExpression(property.value);\n }\n return result;\n }\n throw new Error(`Unsupported config expression: ${unwrapped.type}`);\n}\n\nexport function parseHexclaveConfigFileContent(content: string, filePath: string): ParsedStackConfig {\n if (content.trim() === \"\") return {};\n const ast = parser.parse(content, {\n sourceType: \"module\",\n plugins: [\"typescript\"],\n });\n\n for (const statement of ast.program.body) {\n if (!t.isExportNamedDeclaration(statement) || !t.isVariableDeclaration(statement.declaration)) {\n continue;\n }\n for (const declaration of statement.declaration.declarations) {\n if (!t.isIdentifier(declaration.id) || declaration.id.name !== \"config\") {\n continue;\n }\n if (declaration.init == null || !t.isExpression(declaration.init)) {\n throw new Error(`Config export in ${filePath} must have an initializer.`);\n }\n return evaluateStaticConfigExpression(declaration.init) as ParsedStackConfig;\n }\n }\n\n throw new Error(`Invalid config in ${filePath}. The file must export a plain \\`config\\` object or \"show-onboarding\".`);\n}\n"],"mappings":";;;;;;;;;AAIA,MAAa,oCAAoC;AAEjD,MAAM,gCAAgC;;;;;;;;AAStC,SAAgB,wBAAwB,QAAiB,eAAgC;AACvF,KAAI,uCAAe,OAAO,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@ -1,8 +1,8 @@
|
|
|
1
1
|
Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
|
|
2
2
|
const require_chunk = require('../chunk-BE-pF4vm.js');
|
|
3
|
+
let ___utils_errors_js = require("../utils/errors.js");
|
|
3
4
|
let react = require("react");
|
|
4
5
|
react = require_chunk.__toESM(react);
|
|
5
|
-
let ___utils_errors_js = require("../utils/errors.js");
|
|
6
6
|
|
|
7
7
|
//#region src/hooks/use-async-callback.tsx
|
|
8
8
|
function useAsyncCallback(callback, deps) {
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
|
|
2
2
|
const require_chunk = require('../chunk-BE-pF4vm.js');
|
|
3
|
-
let react = require("react");
|
|
4
3
|
let ___utils_results_js = require("../utils/results.js");
|
|
4
|
+
let react = require("react");
|
|
5
5
|
|
|
6
6
|
//#region src/hooks/use-async-external-store.tsx
|
|
7
7
|
function useAsyncExternalStore(subscribe) {
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
|
|
2
2
|
const require_chunk = require('../chunk-BE-pF4vm.js');
|
|
3
|
-
let react = require("react");
|
|
4
3
|
let ___utils_results_js = require("../utils/results.js");
|
|
4
|
+
let react = require("react");
|
|
5
5
|
|
|
6
6
|
//#region src/hooks/use-strict-memo.tsx
|
|
7
7
|
const cached = /* @__PURE__ */ new Map();
|