Compare commits

...

19 Commits
v2.0.0 ... main

Author SHA1 Message Date
f83b2870f2 release 2.0.9: scope=ninja + api.cal.com egress declaration
Re-declares allowed_hosts (bug: the pre-fix `ninja plugin bump` stripped it
on the 2.0.7->2.0.8 bump, so the published 2.0.8 reached no egress consent
gate and Cal.com calls were denied at runtime). Sets scope=ninja and drops
the stray private flag to match the registry's @ninja/calcomblock entry.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-09 09:53:35 +08:00
de02dfb0ee bump to 2.0.8 2026-07-09 09:40:36 +08:00
bd7f9fad15 fix: flat absolute routes + declare api.cal.com egress (2.0.7)
Register the chi routes as flat absolute paths (httpBase+"/slots" …)
instead of a nested r.Route mount: the wasm host forwards the full
original path with no prefix strip, so the nested mount's RoutePath
rebasing never matched and 404'd the entire HTTP surface.

Declare allowed_hosts = ["api.cal.com"] so the ADR-0023 install consent
dialog asks the admin to grant egress; without it every Cal.com call was
denied at runtime (ABI_ERROR_CODE_EGRESS_DENIED, no egress grant).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-09 09:38:31 +08:00
5a138b9ac8 Add plugin.mod 2026-07-09 09:25:20 +08:00
29c17440a5 bump to 2.0.7 2026-07-09 09:24:14 +08:00
6ec3353b12 bump to 2.0.7 2026-07-09 09:23:39 +08:00
0d56f6adf1 feat(calcom): route Cal.com egress through host OutboundHTTP (ADR 0023)
Under wasm the guest has no network, so every Cal.com v2 call was dying at
"dial tcp: lookup api.cal.com". Thread deps.OutboundHTTP (http.RoundTripper)
from NewCalcomRouter onto CalcomHandler.rt and into NewCalcomClient, building
the client with Transport: rt. A nil rt (native/DESCRIBE/test) falls back to
the default transport, so bundled/httptest paths are unchanged.

Declare allowed_hosts = ["api.cal.com"] (deny-by-default; admin-granted at
install per the Phase 3 consent gate) and bump pluginsdk v0.2.4 -> v0.2.5 for
CoreServices.OutboundHTTP. Bump 2.0.5 -> 2.0.6.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-08 08:57:10 +08:00
f597fa8b52 chore(web): rebuild dist bundle for v2.0.5 captchaEnabled editor
The v2.0.5 captchaEnabled editor toggle (fe5d117) changed web/src but never
rebuilt the committed web/dist. Rebuild so the shipped bundle matches source.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-08 08:57:02 +08:00
fe5d11754a feat(editor): expose the captchaEnabled toggle — v2.0.5
The schema declares captchaEnabled (x-editor checkbox) but the custom
MF editor replaces schema-driven rendering and never drew a control for
it, so the captcha gate could not be enabled through the visual editor
at all. Add the switch beside Show Timezone. pnpm build-script approval
for esbuild (package.json onlyBuiltDependencies) so the editor bundle
rebuilds non-interactively.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-08 00:15:30 +08:00
3967fa955a fix: rebuild admin claims from trusted headers — v2.0.4
Context does not cross the wasm ABI, so requireAdmin's
auth.GetUserFromContext only sees claims if the guest rebuilds them from
the host-stamped X-Bn-Verified-* headers. 2.0.3 never mounted
auth.TrustedHeaderMiddleware, so every admin endpoint (settings save,
event-types, test, rotate) returned 401 for real admins — the settings
panel could not store the Cal.com API key. Mount the middleware on the
router and pin the contract with a header-driven test (viewer headers
must reach requireAdmin and 403, never 401): the existing admin tests
injected claims straight into context, which is exactly the path wasm
does not have.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-08 00:03:28 +08:00
7c7bceb9d7 fix!: absolute routes + live captcha requirement — v2.0.3
Two wasm-era regressions fixed:

Routes: the wasm host forwards the FULL request path with no prefix
strip, but every route was registered relative — the plugin's entire
HTTP surface (slots/book/cancel/date-grid/admin) 404'd at runtime on
every instance since 2.0.0. All routes now register under
/api/plugins/calcomblock (testplugin's httpBase convention), pinned by
a route-matching test.

Captcha requirement: blockConfig was hardcoded nil (no capability
exposed published block content), so bookingRequiresCaptcha always
reported false — the widget never rendered and the gate never ran.
publishedBlockResolver now answers it via pluginsdk v0.2.4's
content.published_block_configs: any currently-published calcom:booking
block matching the posted username+eventTypeSlug with
captchaEnabled=true demands the host-stamped X-Bn-Verified-Captcha
header; an empty config username applies to any posted username.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-07 23:47:59 +08:00
c1f8fe8a2c chore: v2.0.2 — host-verified captcha via X-Bn-Verified-Captcha
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-07 23:18:09 +08:00
7e9265c6a7 feat!: captcha via host-stamped X-Bn-Verified-Captcha; drop block/core entirely
SetCaptchaServer was .so-era injection — nothing wasm-side ever called
it, so the verifier was permanently nil and captcha-enabled booking
blocks failed closed on every submission. A guest can't hold the host's
stateful captcha server; the host now verifies+consumes the cap-token
before dispatch and stamps the unforgeable X-Bn-Verified-Captcha
trusted header (pluginsdk v0.2.2 auth.CaptchaVerified). Fail-closed
semantics preserved: no stamp = reject.

Deletes the last block/core import (captcha) and the test-side PoW
solver; go.mod no longer requires core.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-07 23:00:10 +08:00
28b50128d9 chore: bump pluginsdk to v0.2.1
Picks up the render package move-in (BlockNote renderer now reads
embed-resolver/human-proof context keys from pluginsdk/blocks) and
keeps the check-safety 2c fleet version anchor satisfied.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-07 20:34:04 +08:00
d5b158e0bf chore: pluginsdk v0.2.0 (P3 host-composed chrome)
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-07 14:56:28 +08:00
324a2e6fe0 chore: migrate from block/core to block/pluginsdk (keep core for captcha)
Rewrite imports for plugin, blocks, templates, auth, settings, crypto, and
rbac packages from git.dev.alexdunmow.com/block/core/* to
git.dev.alexdunmow.com/block/pluginsdk/* across all Go files. The captcha
package stays on block/core, so the repo keeps both requires.

go.mod: add pluginsdk v0.1.0; bump core v0.20.2 -> v0.20.3 (satisfies the
check-safety core-version gate); transitive churn pgx v5.9.2 -> v5.10.0 and
x/mod v0.34.0 -> v0.37.0 from go mod tidy.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-07 11:03:57 +08:00
4fff9ead8c bump to 2.0.1 2026-07-06 00:00:54 +08:00
f8f70fcbf0 chore: bump block/core to v0.20.2 (fleet standard, check-safety 2c)
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-06 00:00:49 +08:00
c0f8209e88 chore: rename dev host localdev.blockninjacms.com -> blockninja.dev 2026-07-05 20:50:21 +08:00
20 changed files with 387 additions and 208 deletions

View File

@ -5,8 +5,8 @@ import (
"context"
"time"
"git.dev.alexdunmow.com/block/core/blocks"
"git.dev.alexdunmow.com/block/core/settings"
"git.dev.alexdunmow.com/block/pluginsdk/blocks"
"git.dev.alexdunmow.com/block/pluginsdk/settings"
)
// renderSettings is the SettingsManager available to CalcomBookingFunc, which

64
block_resolver.go Normal file
View File

@ -0,0 +1,64 @@
package main
import (
"context"
"strings"
)
// httpBase is the prefix the host mounts the plugin HTTP handler at; the wasm
// host forwards full paths, so every route registers under it.
const httpBase = "/api/plugins/calcomblock"
// publishedConfigsSource is the slice of content.Content the resolver needs
// (satisfied by deps.Content).
type publishedConfigsSource interface {
PublishedBlockConfigs(ctx context.Context, blockKey string) ([]map[string]any, error)
}
// publishedBlockResolver answers CalcomBookingRequiresCaptcha from published
// block content served by the host (content.published_block_configs) — the
// server-authoritative source, never the POST body/blockId. A config with an
// empty username applies to any posted username (it falls back to the
// plugin's default account), erring toward requiring captcha.
type publishedBlockResolver struct {
source publishedConfigsSource
}
func (r publishedBlockResolver) CalcomBookingRequiresCaptcha(ctx context.Context, username, eventTypeSlug string) (bool, error) {
configs, err := r.source.PublishedBlockConfigs(ctx, "calcom:booking")
if err != nil {
return false, err
}
for _, cfg := range configs {
if !configBool(cfg["captchaEnabled"]) {
continue
}
if !configFieldMatches(cfg["eventTypeSlug"], eventTypeSlug, false) {
continue
}
if configFieldMatches(cfg["username"], username, true) {
return true, nil
}
}
return false, nil
}
func configBool(v any) bool {
switch b := v.(type) {
case bool:
return b
case string:
return strings.EqualFold(strings.TrimSpace(b), "true")
default:
return false
}
}
func configFieldMatches(cfgValue any, posted string, emptyMatchesAny bool) bool {
s, _ := cfgValue.(string)
s = strings.TrimSpace(s)
if s == "" {
return emptyMatchesAny
}
return strings.EqualFold(s, strings.TrimSpace(posted))
}

69
block_resolver_test.go Normal file
View File

@ -0,0 +1,69 @@
package main
import (
"context"
"errors"
"testing"
)
type fakeConfigsSource struct {
configs []map[string]any
err error
gotKey string
}
func (f *fakeConfigsSource) PublishedBlockConfigs(_ context.Context, blockKey string) ([]map[string]any, error) {
f.gotKey = blockKey
return f.configs, f.err
}
func TestPublishedBlockResolverRequiresCaptchaOnMatch(t *testing.T) {
src := &fakeConfigsSource{configs: []map[string]any{
{"username": "other", "eventTypeSlug": "30min", "captchaEnabled": true},
{"username": "Alice", "eventTypeSlug": "30min", "captchaEnabled": true},
}}
r := publishedBlockResolver{source: src}
got, err := r.CalcomBookingRequiresCaptcha(context.Background(), "alice", "30min")
if err != nil || !got {
t.Fatalf("RequiresCaptcha = %v, %v; want true (case-insensitive username match)", got, err)
}
if src.gotKey != "calcom:booking" {
t.Fatalf("queried block key %q, want calcom:booking", src.gotKey)
}
}
func TestPublishedBlockResolverNoRequirementWhenDisabledOrUnmatched(t *testing.T) {
src := &fakeConfigsSource{configs: []map[string]any{
{"username": "alice", "eventTypeSlug": "30min", "captchaEnabled": false},
{"username": "alice", "eventTypeSlug": "60min", "captchaEnabled": true},
}}
r := publishedBlockResolver{source: src}
if got, _ := r.CalcomBookingRequiresCaptcha(context.Background(), "alice", "30min"); got {
t.Fatal("RequiresCaptcha = true; want false (disabled for 30min, 60min doesn't match)")
}
}
func TestPublishedBlockResolverEmptyConfigUsernameMatchesAny(t *testing.T) {
// A block may omit username (falls back to the plugin's default account);
// the requirement then applies to the event type for any posted username —
// erring toward requiring captcha, never stripping it.
src := &fakeConfigsSource{configs: []map[string]any{
{"eventTypeSlug": "30min", "captchaEnabled": true},
}}
r := publishedBlockResolver{source: src}
if got, _ := r.CalcomBookingRequiresCaptcha(context.Background(), "whoever", "30min"); !got {
t.Fatal("RequiresCaptcha = false; want true (config without username applies to any)")
}
}
func TestPublishedBlockResolverPropagatesError(t *testing.T) {
src := &fakeConfigsSource{err: errors.New("hostcall failed")}
r := publishedBlockResolver{source: src}
if _, err := r.CalcomBookingRequiresCaptcha(context.Background(), "alice", "30min"); err == nil {
t.Fatal("expected error to propagate (caller decides fail-open policy)")
}
}

View File

@ -38,10 +38,14 @@ type CalcomClient struct {
baseURL string
}
// NewCalcomClient builds a client with the standard 30s HTTP timeout.
func NewCalcomClient(apiKey string) *CalcomClient {
// NewCalcomClient builds a client with the standard 30s HTTP timeout. rt is the
// host-mediated egress transport (deps.OutboundHTTP, ADR 0023) — under wasm the
// guest has no network, so every Cal.com request must ride it. A nil rt falls
// back to http.DefaultTransport, keeping native/DESCRIBE and httptest paths
// working (tests reach their fake server by overriding calcomBaseURL).
func NewCalcomClient(apiKey string, rt http.RoundTripper) *CalcomClient {
return &CalcomClient{
http: &http.Client{Timeout: 30 * time.Second},
http: &http.Client{Transport: rt, Timeout: 30 * time.Second},
apiKey: apiKey,
baseURL: calcomBaseURL,
}

9
go.mod
View File

@ -3,11 +3,11 @@ module git.dev.alexdunmow.com/block/calcomblock
go 1.26.4
require (
git.dev.alexdunmow.com/block/core v0.18.2
git.dev.alexdunmow.com/block/pluginsdk v0.2.5
github.com/a-h/templ v0.3.1020
github.com/go-chi/chi/v5 v5.3.0
github.com/google/uuid v1.6.0
github.com/jackc/pgx/v5 v5.9.2
github.com/jackc/pgx/v5 v5.10.0
github.com/nyaruka/phonenumbers v1.8.0
)
@ -16,7 +16,8 @@ require (
github.com/BurntSushi/toml v1.6.0 // indirect
github.com/jackc/pgpassfile v1.0.0 // indirect
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect
golang.org/x/mod v0.34.0 // indirect
golang.org/x/text v0.36.0 // indirect
golang.org/x/mod v0.37.0 // indirect
golang.org/x/net v0.56.0 // indirect
golang.org/x/text v0.38.0 // indirect
google.golang.org/protobuf v1.36.11 // indirect
)

26
go.sum
View File

@ -1,7 +1,7 @@
connectrpc.com/connect v1.20.0 h1:6TNDAB+WeNd2uolWNlYczB5E0KNNaVMNUEx8JEUsPmQ=
connectrpc.com/connect v1.20.0/go.mod h1:A2ygJrukXwWy32vkCAAHNVguZrqZ+jeZ9rGRnGR4dN4=
git.dev.alexdunmow.com/block/core v0.18.2 h1:+3OfZ424yoc1k1CucXYARk8TBkh8Z693HRkhf5Ci2wU=
git.dev.alexdunmow.com/block/core v0.18.2/go.mod h1:GGuUu826AoJepC/hKLGJ7BX3PQaDss9ueCT0se6Ao2w=
git.dev.alexdunmow.com/block/pluginsdk v0.2.5 h1:01d+5stAywSENScafnNKyMc2ZM5GGFt+hCBKuKTFJW4=
git.dev.alexdunmow.com/block/pluginsdk v0.2.5/go.mod h1:Z+eG+WZxAP0jfreLqlGcc0kkWKt8RWevzWyWn8d+dhM=
github.com/BurntSushi/toml v1.6.0 h1:dRaEfpa2VI55EwlIW72hMRHdWouJeRF7TPYhI+AUQjk=
github.com/BurntSushi/toml v1.6.0/go.mod h1:ukJfTF/6rtPPRCnwkur4qwRxa8vTRFBF0uk2lLoLwho=
github.com/a-h/templ v0.3.1020 h1:ypAT/L5ySWEnZ6Zft/5yfoWXYYkhFNvEFOeeqecg4tw=
@ -19,8 +19,8 @@ github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsI
github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg=
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 h1:iCEnooe7UlwOQYpKFhBabPMi4aNAfoODPEFNiAnClxo=
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761/go.mod h1:5TJZWKEWniPve33vlWYSoGYefn3gLQRzjfDlhSJ9ZKM=
github.com/jackc/pgx/v5 v5.9.2 h1:3ZhOzMWnR4yJ+RW1XImIPsD1aNSz4T4fyP7zlQb56hw=
github.com/jackc/pgx/v5 v5.9.2/go.mod h1:mal1tBGAFfLHvZzaYh77YS/eC6IX9OWbRV1QIIM0Jn4=
github.com/jackc/pgx/v5 v5.10.0 h1:VhSvgU2jSli8o3AqIEOTJr7rZwAEUVo4E4XhR94Zfr0=
github.com/jackc/pgx/v5 v5.10.0/go.mod h1:mal1tBGAFfLHvZzaYh77YS/eC6IX9OWbRV1QIIM0Jn4=
github.com/jackc/puddle/v2 v2.2.2 h1:PR8nw+E/1w0GLuRFSmiioY6UooMp6KJv0/61nB7icHo=
github.com/jackc/puddle/v2 v2.2.2/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4=
github.com/nyaruka/phonenumbers v1.8.0 h1:TrXNJmbwcAHajzDqin3mLWw57vqLUA6ZjVdeNds0heQ=
@ -32,12 +32,18 @@ github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UV
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
golang.org/x/mod v0.34.0 h1:xIHgNUUnW6sYkcM5Jleh05DvLOtwc6RitGHbDk4akRI=
golang.org/x/mod v0.34.0/go.mod h1:ykgH52iCZe79kzLLMhyCUzhMci+nQj+0XkbXpNYtVjY=
golang.org/x/sync v0.20.0 h1:e0PTpb7pjO8GAtTs2dQ6jYa5BWYlMuX047Dco/pItO4=
golang.org/x/sync v0.20.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0=
golang.org/x/text v0.36.0 h1:JfKh3XmcRPqZPKevfXVpI1wXPTqbkE5f7JA92a55Yxg=
golang.org/x/text v0.36.0/go.mod h1:NIdBknypM8iqVmPiuco0Dh6P5Jcdk8lJL0CUebqK164=
github.com/tetratelabs/wazero v1.12.0 h1:DuWcpNu/FzgEXgGBDp8J1Spc+CWOvvtvVyjKlaZopYU=
github.com/tetratelabs/wazero v1.12.0/go.mod h1:LvKtzl2RqO4gyF27BiXU+nKAjcV8f38U+kP/q2vgxh0=
golang.org/x/mod v0.37.0 h1:vF1DjpVEshcIqoEaauuHebaLk1O1forxjxBaVn884JQ=
golang.org/x/mod v0.37.0/go.mod h1:m8S8VeM9r4dzDwjrKO0a1sZP3YjeMamRRlD+fmR2Q/0=
golang.org/x/net v0.56.0 h1:Rw8j/hFzGvJUZwNBXnAtf5sVDVt+65SK2C7IxCxZt5o=
golang.org/x/net v0.56.0/go.mod h1:D3Ku6r+V6JROoZK144D2XfMHFcMq/0zSfLelVTCFKec=
golang.org/x/sync v0.21.0 h1:HLII4xRRTtCRkxYp4HNFF0Js/Og6q2i++KXbg0gHCwM=
golang.org/x/sync v0.21.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0=
golang.org/x/sys v0.46.0 h1:noSf2Fq6F8DBgS+LysIkx7rIExoNHJsxOAtPp4rthXw=
golang.org/x/sys v0.46.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
golang.org/x/text v0.38.0 h1:sXmwo9DwP3OK9EZ7PqAdaooSGozfl/3a6/xJcbzPRhE=
golang.org/x/text v0.38.0/go.mod h1:YXZt3QhHUKYT53r2lLKFIVi6Ao1jdzrTR/KQ09qyxF4=
google.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE=
google.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=

View File

@ -15,30 +15,14 @@ import (
"sync"
"time"
"git.dev.alexdunmow.com/block/core/auth"
"git.dev.alexdunmow.com/block/core/captcha"
"git.dev.alexdunmow.com/block/core/plugin"
"git.dev.alexdunmow.com/block/core/rbac"
"git.dev.alexdunmow.com/block/pluginsdk/auth"
"git.dev.alexdunmow.com/block/pluginsdk/plugin"
"git.dev.alexdunmow.com/block/pluginsdk/rbac"
"git.dev.alexdunmow.com/block/calcomblock/internal/helpers"
"github.com/go-chi/chi/v5"
"github.com/nyaruka/phonenumbers"
)
// captchaVerifier is the shared Cap (trycap.dev) proof-of-work verifier, built
// once from the per-instance secret and injected at server startup via
// SetCaptchaServer — mirroring SetNotifyFn. It is nil when the instance captcha
// secret failed to load: an enabled booking block then FAILS CLOSED (rejects
// rather than allowing an unverified booking through). Read directly by
// HandleCreateBooking; the mailing-list / block-form handlers hold the same
// server on their struct, but the plugin HTTP mount is generic so a package
// seam is the established injection point here.
var captchaVerifier *captcha.Server
// SetCaptchaServer wires the CMS's shared captcha server into the Cal.com
// booking handler. Called once at server startup from server.go. Safe to pass
// nil (captcha then unavailable → enabled blocks fail closed).
func SetCaptchaServer(s *captcha.Server) { captchaVerifier = s }
// blockContentResolver answers the server-authoritative question "does a
// booking for this Cal.com username + event-type slug require a captcha token?"
// by scanning currently-published block content — NEVER a client-supplied
@ -267,6 +251,10 @@ type CalcomHandler struct {
// trusting the POST body. nil in editor-preview / direct-handler unit tests,
// where blockCaptchaEnabled reports false.
blockConfig blockContentResolver
// rt is the host-mediated egress transport (deps.OutboundHTTP, ADR 0023)
// every Cal.com client is built with. nil in native/DESCRIBE/test builds,
// where NewCalcomClient falls back to the default transport.
rt http.RoundTripper
}
// NewCalcomHandler creates a new Cal.com handler. appURL is the externally
@ -281,6 +269,11 @@ func NewCalcomHandler(settings *SettingsManager, limiter *RateLimiter, appURL st
// and encrypt the Cal.com API key + webhook secret.
func NewCalcomRouter(deps plugin.CoreServices) http.Handler {
r := chi.NewRouter()
// Context does not cross the wasm ABI: requireAdmin's claims exist only if
// the guest rebuilds them from the host-stamped X-Bn-Verified-* headers.
// Without this middleware every admin endpoint 401s for real admins (the
// settings panel could not save the API key — 2.0.3 regression).
r.Use(auth.TrustedHeaderMiddleware)
// Settings persistence goes through the SDK settings capabilities: under the
// wasm sandbox the plugin's Postgres role cannot touch the CMS `settings`
// table (public schema) directly, so the host performs the DB work.
@ -293,38 +286,48 @@ func NewCalcomRouter(deps plugin.CoreServices) http.Handler {
limiter := NewRateLimiter(bookingsPerHourPerIP)
helpers.StartCleanupLoop(context.Background(), 15*time.Minute, limiter.SweepStale)
h := NewCalcomHandler(settings, limiter, deps.AppURL)
// blockConfig scans published block content for the server-authoritative
// captcha requirement (CalcomBookingRequiresCaptcha over page_block_snapshots
// in the public schema). No wasm-ABI capability exposes that today, and the
// sandboxed plugin role cannot read it via SQL, so it is left nil:
// bookingRequiresCaptcha then reports false and the baseline honeypot +
// per-IP rate limit still apply. Restoring server-authoritative captcha
// enforcement needs a future core capability that exposes published-block
// content across the wasm ABI (tracked as a follow-up).
h.blockConfig = nil
// Route every Cal.com call through the host-mediated egress transport. nil
// under native/DESCRIBE builds (deps has no host); the client then uses the
// default transport, which only the non-wasm paths can reach.
h.rt = deps.OutboundHTTP
// blockConfig resolves the server-authoritative captcha requirement from
// published block content via the content.published_block_configs
// capability (pluginsdk >= v0.2.4) — the sandboxed plugin role cannot read
// page_block_snapshots itself. deps.Content is nil in native/DESCRIBE
// builds; blockConfig then stays nil and bookingRequiresCaptcha reports
// false (honeypot + per-IP rate limit remain the baseline).
if deps.Content != nil {
h.blockConfig = publishedBlockResolver{source: deps.Content}
}
// Routes are registered ABSOLUTE on a flat chi router: the wasm host forwards
// the FULL original path (r.URL.Path, no prefix strip), so the guest matches
// on the complete path. A nested r.Route(httpBase, …) instead relies on chi
// Mount's RoutePath rebasing, which the raw-path forwarder never populates —
// mirror testplugin's httpBase convention (flat + absolute) so the surface
// resolves regardless of how the host mounts the forwarder.
// Public booking endpoints — reachable by anonymous visitors.
r.Get("/slots", h.HandleGetSlots)
r.Get("/form", h.HandleGetForm)
r.Post("/book", h.HandleCreateBooking)
r.Post("/cancel", h.HandleCancelBooking)
r.Get("/reset", h.HandleReset)
r.Get("/date-grid", h.HandleGetDateGrid)
r.Get(httpBase+"/slots", h.HandleGetSlots)
r.Get(httpBase+"/form", h.HandleGetForm)
r.Post(httpBase+"/book", h.HandleCreateBooking)
r.Post(httpBase+"/cancel", h.HandleCancelBooking)
r.Get(httpBase+"/reset", h.HandleReset)
r.Get(httpBase+"/date-grid", h.HandleGetDateGrid)
// Webhook receiver — HMAC-verified inside the handler, so no admin gate.
wh := NewWebhookHandler(settings, slog.Default())
r.Post("/webhook", wh.Handle)
r.Post(httpBase+"/webhook", wh.Handle)
// Admin endpoints — gated by requireAdmin. The plugin HTTP mount has no
// outer admin middleware, so this is the only line keeping the API key
// + webhook secret + Cal.com proxy out of attackers' hands.
r.Group(func(admin chi.Router) {
admin.Use(requireAdmin)
admin.Get("/settings", h.HandleGetSettings)
admin.Post("/settings", h.HandleSaveSettings)
admin.Post("/settings/rotate-webhook-secret", h.HandleRotateWebhookSecret)
admin.Post("/test", h.HandleTestConnection)
admin.Get("/event-types", h.HandleListEventTypes)
admin.Get(httpBase+"/settings", h.HandleGetSettings)
admin.Post(httpBase+"/settings", h.HandleSaveSettings)
admin.Post(httpBase+"/settings/rotate-webhook-secret", h.HandleRotateWebhookSecret)
admin.Post(httpBase+"/test", h.HandleTestConnection)
admin.Get(httpBase+"/event-types", h.HandleListEventTypes)
})
return r
@ -380,8 +383,8 @@ func resetEventTZCache() {
// type's pinned availability schedule when one is set, else the account's
// default schedule. Returns "" when any hop fails — callers then fall down
// the site-setting ladder rather than guessing.
func fetchEventTimezone(ctx context.Context, apiKey, username, eventType string) string {
client := NewCalcomClient(apiKey)
func fetchEventTimezone(ctx context.Context, rt http.RoundTripper, apiKey, username, eventType string) string {
client := NewCalcomClient(apiKey, rt)
schedules, err := client.ListSchedules(ctx)
if err != nil || len(schedules) == 0 {
log.Printf("calcom: list schedules for %s/%s: %v", username, eventType, err)
@ -416,7 +419,7 @@ func fetchEventTimezone(ctx context.Context, apiKey, username, eventType string)
func (h *CalcomHandler) eventLocation(ctx context.Context, apiKey, username, eventType string) (*time.Location, string) {
tz := peekEventTZ(username, eventType)
if tz == "" && apiKey != "" && username != "" && eventType != "" {
if tz = fetchEventTimezone(ctx, apiKey, username, eventType); tz != "" {
if tz = fetchEventTimezone(ctx, h.rt, apiKey, username, eventType); tz != "" {
storeEventTZ(username, eventType, tz)
}
}
@ -463,7 +466,7 @@ func (h *CalcomHandler) HandleGetSlots(w http.ResponseWriter, r *http.Request) {
}
dayEnd := dayStart.AddDate(0, 0, 1)
client := NewCalcomClient(apiKey)
client := NewCalcomClient(apiKey, h.rt)
slotsResp, err := client.GetSlots(
r.Context(),
username,
@ -559,7 +562,7 @@ func (h *CalcomHandler) HandleGetForm(w http.ResponseWriter, r *http.Request) {
var bookingFields []BookingField
if apiKeyErr == nil && apiKey != "" && username != "" && eventType != "" {
client := NewCalcomClient(apiKey)
client := NewCalcomClient(apiKey, h.rt)
et, etErr := client.GetEventType(r.Context(), username, eventType)
if etErr != nil {
// Fall back to default fields so a transient Cal.com error doesn't
@ -697,13 +700,16 @@ func (h *CalcomHandler) HandleCreateBooking(w http.ResponseWriter, r *http.Reque
// authoritative source is whether any currently-published calcom:booking
// block for this username+eventType has captchaEnabled=true — resolved from
// published content, never the POST body/blockId — so a bot cannot strip the
// requirement by omitting or forging blockId. When captcha IS required we
// fail CLOSED: a nil shared captcha server (instance secret failed at
// startup) rejects rather than allows. On failure we render the same error
// partial as other validation failures (not a 500), so the visitor can
// re-solve and retry.
// requirement by omitting or forging blockId. Verification is HOST-side: a
// guest cannot hold the host's stateful captcha server, so the host consumes
// the cap-token and stamps the unforgeable X-Bn-Verified-Captcha trusted
// header (pluginsdk/auth). When captcha IS required we fail CLOSED: no
// stamp (invalid token, or the instance captcha server failed at startup)
// rejects rather than allows. On failure we render the same error partial
// as other validation failures (not a 500), so the visitor can re-solve
// and retry.
if h.bookingRequiresCaptcha(r.Context(), username, eventType) {
if captchaVerifier == nil || !captchaVerifier.VerifyRequest(r) {
if !auth.CaptchaVerified(r.Header) {
h.renderError(w, "Captcha check failed, please try again.", blockID, false)
return
}
@ -721,7 +727,7 @@ func (h *CalcomHandler) HandleCreateBooking(w http.ResponseWriter, r *http.Reque
}
payload := routeBookingForm(r.Form, region)
client := NewCalcomClient(apiKey)
client := NewCalcomClient(apiKey, h.rt)
br := BookingRequest{
EventTypeSlug: eventType,
Username: username,
@ -834,7 +840,7 @@ func (h *CalcomHandler) HandleCancelBooking(w http.ResponseWriter, r *http.Reque
return
}
client := NewCalcomClient(apiKey)
client := NewCalcomClient(apiKey, h.rt)
if err := client.CancelBooking(r.Context(), uid, "Cancelled by attendee"); err != nil {
// Full technical cause stays server-side; the visitor sees curated copy.
log.Printf("calcom: cancel booking %q: %v", uid, err)
@ -950,7 +956,7 @@ func (h *CalcomHandler) HandleGetSettings(w http.ResponseWriter, r *http.Request
// have no cached username. Fire /me once on the first settings load and
// persist the result so subsequent loads are cache-hits.
if username == "" && apiKey != "" {
client := NewCalcomClient(apiKey)
client := NewCalcomClient(apiKey, h.rt)
if me, err := client.GetMe(ctx); err != nil {
log.Printf("calcom: backfill /me in HandleGetSettings: %v", err)
} else {
@ -1012,7 +1018,7 @@ func (h *CalcomHandler) HandleSaveSettings(w http.ResponseWriter, r *http.Reques
// ask the admin to type their own username. Best-effort: if /me is
// down or rate-limited, the save still succeeds and the admin can
// refresh later via Test Connection.
client := NewCalcomClient(req.APIKey)
client := NewCalcomClient(req.APIKey, h.rt)
if me, err := client.GetMe(ctx); err != nil {
log.Printf("calcom: /me lookup after save: %v", err)
} else if err := h.settings.SetUsername(ctx, me.Username); err != nil {
@ -1076,7 +1082,7 @@ func (h *CalcomHandler) HandleListEventTypes(w http.ResponseWriter, r *http.Requ
return
}
username := r.URL.Query().Get("username")
client := NewCalcomClient(apiKey)
client := NewCalcomClient(apiKey, h.rt)
ets, err := client.ListEventTypes(r.Context(), username)
if err != nil {
log.Printf("calcom: list event types: %v", err)
@ -1099,7 +1105,7 @@ func (h *CalcomHandler) HandleTestConnection(w http.ResponseWriter, r *http.Requ
return
}
client := NewCalcomClient(apiKey)
client := NewCalcomClient(apiKey, h.rt)
ets, err := client.ListEventTypes(r.Context(), "")
if err != nil {
log.Printf("calcom: test connection: %v", err)

View File

@ -2,22 +2,18 @@ package main
import (
"context"
"crypto/sha256"
"encoding/hex"
"errors"
"fmt"
"io"
"net/http"
"net/http/httptest"
"net/url"
"strconv"
"strings"
"sync/atomic"
"testing"
"github.com/google/uuid"
"git.dev.alexdunmow.com/block/core/captcha"
"git.dev.alexdunmow.com/block/pluginsdk/auth"
)
// fakeBlockResolver is an in-memory blockContentResolver so the booking handler
@ -46,7 +42,7 @@ func (f fakeBlockResolver) CalcomBookingRequiresCaptcha(_ context.Context, usern
// block for username "alice" / eventType "30min" carries the given
// captchaEnabled flag, plus a persisted API key so the booking flow reaches the
// Cal.com call. The requirement is keyed on username+eventType, NOT a blockId —
// so the booking form may post any blockId (or none) without affecting it.
// see fakeBlockResolver.
func newCalcomCaptchaHandler(t *testing.T, captchaEnabled bool) *CalcomHandler {
t.Helper()
h, _ := newTestHandler()
@ -59,12 +55,6 @@ func newCalcomCaptchaHandler(t *testing.T, captchaEnabled bool) *CalcomHandler {
return h
}
// newCalcomTestCaptchaServer builds a captcha.Server with a low PoW difficulty
// so the challenge solves quickly in tests.
func newCalcomTestCaptchaServer() *captcha.Server {
return captcha.New([]byte("calcom-captcha-test-secret"), captcha.WithChallenge(4, 8, 2))
}
// captchaBookingForm builds a booking POST body that passes every cheap
// validation (name+email present, valid email) so the only thing standing
// between the request and the Cal.com call is the captcha check. blockID is
@ -84,10 +74,18 @@ func captchaBookingForm(blockID string) url.Values {
return v
}
func postCaptchaBooking(h *CalcomHandler, form url.Values) *httptest.ResponseRecorder {
// postCaptchaBooking submits the form. captchaHeader is the raw value of the
// host-stamped X-Bn-Verified-Captcha trusted header ("" = host stamped
// nothing: no valid cap-token crossed the host, or the instance captcha
// server was unavailable). Guests never see raw tokens — the host verifies
// and consumes them before dispatch (pluginsdk/auth/trustedheaders.go).
func postCaptchaBooking(h *CalcomHandler, form url.Values, captchaHeader string) *httptest.ResponseRecorder {
req := httptest.NewRequest(http.MethodPost, "/book", strings.NewReader(form.Encode()))
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
req.Header.Set("X-Forwarded-For", "198.51.100.7") // TEST-NET-2, isolated bucket
if captchaHeader != "" {
req.Header.Set(auth.HeaderVerifiedCaptcha, captchaHeader)
}
rec := httptest.NewRecorder()
h.HandleCreateBooking(rec, req)
return rec
@ -108,60 +106,55 @@ func fakeCalcomServer(t *testing.T) (*httptest.Server, *atomic.Int32) {
return srv, &bookings
}
func TestCalcomBooking_CaptchaEnabled_RejectsWithoutToken(t *testing.T) {
func TestCalcomBooking_CaptchaEnabled_RejectsWithoutVerifiedHeader(t *testing.T) {
fake, bookings := fakeCalcomServer(t)
withCalcomBaseURL(t, fake.URL)
h := newCalcomCaptchaHandler(t, true)
SetCaptchaServer(newCalcomTestCaptchaServer())
t.Cleanup(func() { SetCaptchaServer(nil) })
rec := postCaptchaBooking(h, captchaBookingForm(uuid.NewString())) // no cap-token
rec := postCaptchaBooking(h, captchaBookingForm(uuid.NewString()), "") // host stamped nothing
if got := bookings.Load(); got != 0 {
t.Fatalf("Cal.com booking created %d times; want 0 (missing captcha token must be rejected)", got)
t.Fatalf("Cal.com booking created %d times; want 0 (missing verified-captcha header must be rejected)", got)
}
if !strings.Contains(rec.Body.String(), "aptcha") {
t.Fatalf("expected captcha error fragment, got: %s", rec.Body.String())
}
}
func TestCalcomBooking_CaptchaEnabled_RejectsInvalidToken(t *testing.T) {
func TestCalcomBooking_CaptchaEnabled_RejectsNonCanonicalHeaderValue(t *testing.T) {
fake, bookings := fakeCalcomServer(t)
withCalcomBaseURL(t, fake.URL)
h := newCalcomCaptchaHandler(t, true)
SetCaptchaServer(newCalcomTestCaptchaServer())
t.Cleanup(func() { SetCaptchaServer(nil) })
form := captchaBookingForm(uuid.NewString())
form.Set("cap-token", "not-a-real-token")
rec := postCaptchaBooking(h, form)
// Only the exact host-stamped value "1" counts; anything else reads as
// unverified (auth.CaptchaVerified).
rec := postCaptchaBooking(h, captchaBookingForm(uuid.NewString()), "true")
if got := bookings.Load(); got != 0 {
t.Fatalf("Cal.com booking created %d times; want 0 (invalid token rejected)", got)
t.Fatalf("Cal.com booking created %d times; want 0 (non-canonical header value rejected)", got)
}
if !strings.Contains(rec.Body.String(), "aptcha") {
t.Fatalf("expected captcha error fragment, got: %s", rec.Body.String())
}
}
func TestCalcomBooking_CaptchaEnabled_ProceedsWithValidToken(t *testing.T) {
func TestCalcomBooking_CaptchaEnabled_ProceedsWithVerifiedHeader(t *testing.T) {
fake, bookings := fakeCalcomServer(t)
withCalcomBaseURL(t, fake.URL)
srv := newCalcomTestCaptchaServer()
h := newCalcomCaptchaHandler(t, true)
SetCaptchaServer(srv)
t.Cleanup(func() { SetCaptchaServer(nil) })
token := mintCalcomCaptchaToken(t, srv)
// A real widget still posts the cap-token field; the HOST consumes it and
// stamps the header. The guest must trust the header and never forward the
// raw token to Cal.com.
form := captchaBookingForm(uuid.NewString())
form.Set("cap-token", token)
rec := postCaptchaBooking(h, form)
form.Set("cap-token", "host-already-consumed-this")
rec := postCaptchaBooking(h, form, "1")
if got := bookings.Load(); got != 1 {
t.Fatalf("Cal.com booking created %d times; want 1 (valid token must pass captcha)", got)
t.Fatalf("Cal.com booking created %d times; want 1 (host-verified captcha must pass)", got)
}
if rec.Code != http.StatusOK {
t.Fatalf("status = %d; want 200 (body=%s)", rec.Code, rec.Body.String())
@ -172,16 +165,13 @@ func TestCalcomBooking_CaptchaEnabled_ProceedsWithValidToken(t *testing.T) {
}
}
func TestCalcomBooking_CaptchaDisabled_TokenNotRequired(t *testing.T) {
func TestCalcomBooking_CaptchaDisabled_HeaderNotRequired(t *testing.T) {
fake, bookings := fakeCalcomServer(t)
withCalcomBaseURL(t, fake.URL)
h := newCalcomCaptchaHandler(t, false)
// A non-nil server would still reject if enforcement wrongly kicked in; nil
// proves the disabled path never touches the verifier.
SetCaptchaServer(nil)
rec := postCaptchaBooking(h, captchaBookingForm(uuid.NewString())) // no cap-token
rec := postCaptchaBooking(h, captchaBookingForm(uuid.NewString()), "") // no header
if got := bookings.Load(); got != 1 {
t.Fatalf("Cal.com booking created %d times; want 1 (captcha disabled)", got)
@ -194,21 +184,22 @@ func TestCalcomBooking_CaptchaDisabled_TokenNotRequired(t *testing.T) {
}
}
func TestCalcomBooking_CaptchaEnabled_FailsClosedWhenServerNil(t *testing.T) {
// TestCalcomBooking_CaptchaEnabled_FailsClosedWithoutHostStamp pins the
// fail-closed contract: a request that carries a cap-token but NO host stamp
// (instance captcha server down, or the token was invalid/replayed host-side)
// must be rejected — the guest never verifies tokens itself.
func TestCalcomBooking_CaptchaEnabled_FailsClosedWithoutHostStamp(t *testing.T) {
fake, bookings := fakeCalcomServer(t)
withCalcomBaseURL(t, fake.URL)
h := newCalcomCaptchaHandler(t, true)
// nil captcha server: the instance secret failed at startup. An enabled
// block must reject rather than allow the booking through unverified.
SetCaptchaServer(nil)
form := captchaBookingForm(uuid.NewString())
form.Set("cap-token", "anything")
rec := postCaptchaBooking(h, form)
rec := postCaptchaBooking(h, form, "")
if got := bookings.Load(); got != 0 {
t.Fatalf("Cal.com booking created %d times; want 0 (fail closed on nil server)", got)
t.Fatalf("Cal.com booking created %d times; want 0 (fail closed without host stamp)", got)
}
if !strings.Contains(rec.Body.String(), "aptcha") {
t.Fatalf("expected captcha error fragment, got: %s", rec.Body.String())
@ -232,11 +223,9 @@ func TestCalcomBooking_CaptchaBypass_BlockIdCannotStripRequirement(t *testing.T)
withCalcomBaseURL(t, fake.URL)
h := newCalcomCaptchaHandler(t, true) // published block requires captcha
SetCaptchaServer(newCalcomTestCaptchaServer())
t.Cleanup(func() { SetCaptchaServer(nil) })
// No valid cap-token; the requirement must not depend on blockId.
rec := postCaptchaBooking(h, captchaBookingForm(tc.blockID))
// No host stamp; the requirement must not depend on blockId.
rec := postCaptchaBooking(h, captchaBookingForm(tc.blockID), "")
if got := bookings.Load(); got != 0 {
t.Fatalf("Cal.com booking created %d times; want 0 (captcha requirement must not depend on blockId)", got)
@ -252,7 +241,7 @@ func TestCalcomBooking_CaptchaBypass_BlockIdCannotStripRequirement(t *testing.T)
// deliberate choice for the requirement lookup: a resolver (DB) error is logged
// and treated as "not required", so a transient DB blip cannot block every
// booking site-wide. The honeypot + per-IP rate limit remain the baseline
// protection. (This is distinct from the nil-captcha-server path, which fails
// protection. (This is distinct from the missing-host-stamp path, which fails
// CLOSED when a block IS known to require captcha.)
func TestCalcomBooking_CaptchaRequirement_ResolverErrorFailsOpen(t *testing.T) {
fake, bookings := fakeCalcomServer(t)
@ -263,10 +252,8 @@ func TestCalcomBooking_CaptchaRequirement_ResolverErrorFailsOpen(t *testing.T) {
t.Fatalf("SetAPIKey: %v", err)
}
h.blockConfig = fakeBlockResolver{err: errors.New("db unavailable")}
SetCaptchaServer(newCalcomTestCaptchaServer())
t.Cleanup(func() { SetCaptchaServer(nil) })
rec := postCaptchaBooking(h, captchaBookingForm("")) // no cap-token
rec := postCaptchaBooking(h, captchaBookingForm(""), "") // no host stamp
if got := bookings.Load(); got != 1 {
t.Fatalf("Cal.com booking created %d times; want 1 (resolver error → captcha not enforced; honeypot + rate limit still apply)", got)
}
@ -274,67 +261,3 @@ func TestCalcomBooking_CaptchaRequirement_ResolverErrorFailsOpen(t *testing.T) {
t.Fatalf("status = %d; want 200 (body=%s)", rec.Code, rec.Body.String())
}
}
// ---------------------------------------------------------------------------
// captcha PoW helpers — local copies of the (unexported) core/captcha PRNG so
// the test can solve a challenge and mint a real verification token. Mirrors
// the helpers in internal/handlers/captcha_challenge_test.go.
// ---------------------------------------------------------------------------
func mintCalcomCaptchaToken(t *testing.T, srv *captcha.Server) string {
t.Helper()
ch, err := srv.CreateChallenge()
if err != nil {
t.Fatalf("CreateChallenge: %v", err)
}
intSols := solveCalcomChallenge(ch.Token, ch.Challenge.C, ch.Challenge.S, ch.Challenge.D)
sols := make([]string, len(intSols))
for i, n := range intSols {
sols[i] = strconv.Itoa(n)
}
rd := srv.Redeem(ch.Token, sols)
if !rd.Success || rd.Token == "" {
t.Fatalf("Redeem failed: %+v", rd)
}
return rd.Token
}
func solveCalcomChallenge(token string, c, s, d int) []int {
sols := make([]int, c)
for i := 1; i <= c; i++ {
salt := calcomPRNG(token+strconv.Itoa(i), s)
target := calcomPRNG(token+strconv.Itoa(i)+"d", d)
for n := 0; ; n++ {
sum := sha256.Sum256([]byte(salt + strconv.Itoa(n)))
h := hex.EncodeToString(sum[:])
if len(h) >= len(target) && h[:len(target)] == target {
sols[i-1] = n
break
}
}
}
return sols
}
func calcomPRNG(seed string, length int) string {
const mask = 0xFFFFFFFF
state := calcomFNV1a(seed)
var b strings.Builder
for b.Len() < length {
state ^= (state << 13) & mask
state ^= state >> 17
state ^= (state << 5) & mask
state &= mask
fmt.Fprintf(&b, "%08x", state)
}
return b.String()[:length]
}
func calcomFNV1a(s string) uint32 {
var h uint32 = 2166136261
for _, ch := range s {
h ^= uint32(ch)
h = (h + (h << 1) + (h << 4) + (h << 7) + (h << 8) + (h << 24)) & 0xFFFFFFFF
}
return h
}

View File

@ -15,7 +15,7 @@ import (
"testing"
"time"
"git.dev.alexdunmow.com/block/core/auth"
"git.dev.alexdunmow.com/block/pluginsdk/auth"
"github.com/go-chi/chi/v5"
"github.com/google/uuid"
)
@ -28,7 +28,7 @@ func newTestRouter(t *testing.T) http.Handler {
t.Helper()
settings, _ := newTestSettings()
limiter := NewRateLimiter(bookingsPerHourPerIP)
h := NewCalcomHandler(settings, limiter, "https://test.localdev.blockninjacms.com")
h := NewCalcomHandler(settings, limiter, "https://test.blockninja.dev")
r := chi.NewRouter()
r.Get("/slots", h.HandleGetSlots)
@ -1275,7 +1275,7 @@ func TestHandleCancelBooking_RateLimited(t *testing.T) {
if err := settings.SetAPIKey(context.Background(), "cal_live_test"); err != nil {
t.Fatalf("SetAPIKey: %v", err)
}
h := NewCalcomHandler(settings, NewRateLimiter(1), "https://test.localdev.blockninjacms.com")
h := NewCalcomHandler(settings, NewRateLimiter(1), "https://test.blockninja.dev")
doCancel := func() *httptest.ResponseRecorder {
form := url.Values{"blockId": {"b1"}, "uid": {"some-uid"}}

View File

@ -59,7 +59,7 @@ func newTestSettings() (*SettingsManager, *fakeQuerier) {
// — handy for tests that need to drive HandleCreateBooking.
func newTestHandler() (*CalcomHandler, *fakeQuerier) {
s, q := newTestSettings()
return NewCalcomHandler(s, NewRateLimiter(bookingsPerHourPerIP), "https://test.localdev.blockninjacms.com"), q
return NewCalcomHandler(s, NewRateLimiter(bookingsPerHourPerIP), "https://test.blockninja.dev"), q
}
// TestWriteServerError_DoesNotLeakInternalError verifies that writeServerError

View File

@ -6,7 +6,7 @@
// init (hence wasmguest.Serve) before any ABI hook call. main is never called.
package main
import "git.dev.alexdunmow.com/block/core/plugin/wasmguest"
import "git.dev.alexdunmow.com/block/pluginsdk/plugin/wasmguest"
func init() { wasmguest.Serve(Registration) }

View File

@ -1,9 +1,10 @@
[plugin]
name = "calcomblock"
display_name = "Cal.com Booking"
scope = "@ninja"
version = "2.0.0"
scope = "ninja"
version = "2.0.9"
description = "Embeddable Cal.com booking calendar block with custom styling, timezone-aware slot windowing, honeypot + captcha + rate-limited public booking endpoints, and webhook receiver."
kind = "plugin"
categories = ["forms"]
tags = ["calcom", "booking", "calendar", "scheduling", "appointments"]
allowed_hosts = ["api.cal.com"]

View File

@ -5,9 +5,9 @@ import (
"io/fs"
"net/http"
"git.dev.alexdunmow.com/block/core/blocks"
"git.dev.alexdunmow.com/block/core/plugin"
"git.dev.alexdunmow.com/block/core/templates"
"git.dev.alexdunmow.com/block/pluginsdk/blocks"
"git.dev.alexdunmow.com/block/pluginsdk/plugin"
"git.dev.alexdunmow.com/block/pluginsdk/templates"
)
//go:embed all:web/dist/assets

View File

@ -4,9 +4,9 @@ import (
"io/fs"
"net/http"
"git.dev.alexdunmow.com/block/core/blocks"
"git.dev.alexdunmow.com/block/core/plugin"
"git.dev.alexdunmow.com/block/core/templates"
"git.dev.alexdunmow.com/block/pluginsdk/blocks"
"git.dev.alexdunmow.com/block/pluginsdk/plugin"
"git.dev.alexdunmow.com/block/pluginsdk/templates"
)
// Registration is the compile-time plugin registration for the Cal.com Booking block.

63
router_paths_test.go Normal file
View File

@ -0,0 +1,63 @@
package main
import (
"net/http"
"net/http/httptest"
"testing"
"git.dev.alexdunmow.com/block/pluginsdk/auth"
"git.dev.alexdunmow.com/block/pluginsdk/plugin"
"github.com/go-chi/chi/v5"
"github.com/google/uuid"
)
// TestRouterMatchesAbsolutePluginPaths pins the wasm routing contract: the
// host forwards the FULL request path (/api/plugins/calcomblock/...) to the
// guest with no prefix strip, so every route must be registered absolute.
// Relative registrations 404 the plugin's entire HTTP surface at runtime —
// exactly the regression that shipped in 2.0.02.0.2.
func TestRouterMatchesAbsolutePluginPaths(t *testing.T) {
router, ok := NewCalcomRouter(plugin.CoreServices{}).(chi.Routes)
if !ok {
t.Fatal("NewCalcomRouter no longer returns a chi router")
}
for _, tc := range []struct{ method, path string }{
{http.MethodGet, "/api/plugins/calcomblock/reset"},
{http.MethodGet, "/api/plugins/calcomblock/slots"},
{http.MethodGet, "/api/plugins/calcomblock/date-grid"},
{http.MethodPost, "/api/plugins/calcomblock/book"},
{http.MethodPost, "/api/plugins/calcomblock/cancel"},
{http.MethodGet, "/api/plugins/calcomblock/event-types"},
} {
rctx := chi.NewRouteContext()
if !router.Match(rctx, tc.method, tc.path) {
t.Errorf("%s %s does not match any route — must be registered at the absolute plugin path", tc.method, tc.path)
}
}
}
// TestRouterRebuildsClaimsFromTrustedHeaders pins the wasm identity contract:
// context does not cross the ABI, so the ONLY way requireAdmin can see the
// caller is for the router to rebuild claims from the host-stamped
// X-Bn-Verified-* headers (auth.TrustedHeaderMiddleware). 2.0.3 shipped
// without it — every admin endpoint 401'd for real admins. A viewer-role
// header must reach requireAdmin and be rejected 403 (claims seen), never
// 401 (claims lost); no handler runs, so empty CoreServices is safe.
func TestRouterRebuildsClaimsFromTrustedHeaders(t *testing.T) {
router := NewCalcomRouter(plugin.CoreServices{})
req := httptest.NewRequest(http.MethodGet, "/api/plugins/calcomblock/settings", nil)
req.Header.Set(auth.HeaderVerifiedUserID, uuid.NewString())
req.Header.Set(auth.HeaderVerifiedEmail, "viewer@example.test")
req.Header.Set(auth.HeaderVerifiedRole, "viewer")
rec := httptest.NewRecorder()
router.ServeHTTP(rec, req)
if rec.Code == http.StatusUnauthorized {
t.Fatalf("viewer trusted headers yielded 401 — TrustedHeaderMiddleware is not mounted, claims never reach requireAdmin")
}
if rec.Code != http.StatusForbidden {
t.Errorf("viewer trusted headers: expected 403 from requireAdmin, got %d (body %q)", rec.Code, rec.Body.String())
}
}

View File

@ -8,8 +8,8 @@ import (
"strings"
"time"
"git.dev.alexdunmow.com/block/core/crypto"
"git.dev.alexdunmow.com/block/core/settings"
"git.dev.alexdunmow.com/block/pluginsdk/crypto"
"git.dev.alexdunmow.com/block/pluginsdk/settings"
"git.dev.alexdunmow.com/block/calcomblock/internal/db"
"git.dev.alexdunmow.com/block/calcomblock/internal/helpers"

View File

@ -383,6 +383,29 @@ function CalcomBlockEditor({ content, onChange }) {
}),
],
}),
/* @__PURE__ */ jsxRuntimeExports.jsxs("div", {
className: "flex items-center justify-between rounded-lg border p-3",
children: [
/* @__PURE__ */ jsxRuntimeExports.jsxs("div", {
className: "space-y-0.5",
children: [
/* @__PURE__ */ jsxRuntimeExports.jsx(Label, { children: t("calcom.editor.captchaEnabled.label", "Enable captcha") }),
/* @__PURE__ */ jsxRuntimeExports.jsx("p", {
className: "text-xs text-muted-foreground",
children: t(
"calcom.editor.captchaEnabled.help",
"Require visitors to solve a privacy-friendly proof-of-work captcha before booking (spam protection).",
),
}),
],
}),
/* @__PURE__ */ jsxRuntimeExports.jsx(Switch, {
"checked": getBool("captchaEnabled", false),
"onCheckedChange": (v) => handleFieldChange("captchaEnabled", v),
"aria-label": t("calcom.editor.captchaEnabled.label", "Enable captcha"),
}),
],
}),
],
}),
],

View File

@ -3,7 +3,7 @@ const exportSet = new Set(["Module", "__esModule", "default", "_export_sfc"]);
let moduleMap = {
"./editor": () => {
dynamicLoadingCss(["style-Bs2zy9jQ.css"], false, "./editor");
return __federation_import("./__federation_expose_Editor-BDCHVRx7.js").then((module) => (Object.keys(module).every((item) => exportSet.has(item)) ? () => module.default : () => module));
return __federation_import("./__federation_expose_Editor-DbTTOPh9.js").then((module) => (Object.keys(module).every((item) => exportSet.has(item)) ? () => module.default : () => module));
},
"./settings": () => {
dynamicLoadingCss(["style-Bs2zy9jQ.css"], false, "./settings");

View File

@ -318,6 +318,20 @@ function CalcomBlockEditor({ content, onChange }: BlockEditorProps) {
aria-label={t("calcom.editor.showTimezone.label", "Show Timezone Selector")}
/>
</div>
<div className="flex items-center justify-between rounded-lg border p-3">
<div className="space-y-0.5">
<Label>{t("calcom.editor.captchaEnabled.label", "Enable captcha")}</Label>
<p className="text-xs text-muted-foreground">
{t("calcom.editor.captchaEnabled.help", "Require visitors to solve a privacy-friendly proof-of-work captcha before booking (spam protection).")}
</p>
</div>
<Switch
checked={getBool("captchaEnabled", false)}
onCheckedChange={(v) => handleFieldChange("captchaEnabled", v)}
aria-label={t("calcom.editor.captchaEnabled.label", "Enable captcha")}
/>
</div>
</CardContent>
</Card>

View File

@ -18,5 +18,10 @@
"react-dom": "^18.3.1",
"typescript": "^5.9.3",
"vite": "^6.4.1"
},
"pnpm": {
"onlyBuiltDependencies": [
"esbuild"
]
}
}