diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000..85c5429 --- /dev/null +++ b/.dockerignore @@ -0,0 +1,7 @@ +.git +.superpowers +.playwright-cli +data +docs +node_modules +*.db diff --git a/.gitea/workflows/ci.yml b/.gitea/workflows/ci.yml new file mode 100644 index 0000000..baa77d5 --- /dev/null +++ b/.gitea/workflows/ci.yml @@ -0,0 +1,190 @@ +name: CI + +# Image build for ins-landing-page, following dynamic-qr's pipeline (build container, DinD, one +# moving tag per profile, per-branch run queue, guarded microk8s rollout, notifications). The k8s +# manifests live in k8s/ and are applied by hand (README "Kubernetes"); CI only rolls the +# Deployment so it pulls the new image, and only from main. Tests run inside the Dockerfile's +# `test` stage, so a failing test stops the image from being pushed. +# +# Tags: main -> ins-landing-page-prd-latest; dev -> ins-landing-page-dev-latest. + +on: + push: + branches: + - main + - dev + +# Do NOT add workflow `concurrency`: Gitea keeps one waiting run per group and cancels the rest. +# Runs queue per branch in the "Wait for older runs" step instead (scripts/waitForOlderRuns.sh). + +jobs: + build: + runs-on: ubuntu-latest + container: + image: gitea.containerverse.dev/solvway/maven-custom-21:latest + credentials: + username: ${{ secrets.PACKAGE_USER }} + password: ${{ secrets.PACKAGE_RW_KEY }} + env: + _REGISTRY: gitea.containerverse.dev + _REGISTRY_PREFIX: solvway + _REPO_NAME: ins-landing-page + _IMAGE_NAME: ins-landing-page + # Images are built against the DinD sidecar (no host docker socket), without TLS. + DOCKER_HOST: tcp://docker:2375 + DOCKER_TLS_VERIFY: "" + # Push a single manifest, not a manifest list with a provenance attestation. + BUILDX_NO_DEFAULT_ATTESTATIONS: "1" + steps: + - name: Checkout + uses: actions/checkout@v4 + + - name: Wait for older runs of this branch + timeout-minutes: 125 + env: + GITEA_TOKEN: ${{ github.token }} + GITEA_API: ${{ github.server_url }}/api/v1 + GITEA_REPO: ${{ github.repository }} + GITEA_BRANCH: ${{ github.ref_name }} + RUN_NUMBER: ${{ github.run_number }} + # Values reach scripts through env:, never as ${{ }} inside run:. + run: | + "$GITHUB_WORKSPACE/scripts/waitForOlderRuns.sh" "$RUN_NUMBER" + + - name: Docker build & push + env: + REGISTRY_USER: ${{ secrets.PACKAGE_USER }} + REGISTRY_PASSWORD: ${{ secrets.PACKAGE_RW_KEY }} + BRANCH: ${{ github.ref_name }} + run: | + case "$BRANCH" in + main) PROFILE=prd ;; + dev) PROFILE=dev ;; + *) echo "Refusing unexpected branch name"; exit 1 ;; + esac + IMAGE_REF="$_REGISTRY/$_REGISTRY_PREFIX/$_IMAGE_NAME:$_REPO_NAME-$PROFILE-latest" + printf '%s' "$REGISTRY_PASSWORD" | docker login "$_REGISTRY" -u "$REGISTRY_USER" --password-stdin + docker build --pull -f Dockerfile --target test . + docker build -f Dockerfile -t "$IMAGE_REF" . + docker push "$IMAGE_REF" + echo "Pushed $IMAGE_REF" + + - name: Rollout to microk8s + if: ${{ github.ref_name == 'main' }} + env: + DEPLOY_USER: ${{ secrets.DRONECICD_SSH_USERNAME }} + DEPLOY_HOST: ${{ secrets.DRONECICD_SSH_HOST }} + DEPLOY_SSH_KEY: ${{ secrets.DRONECICD_SSH_KEY }} + SHA: ${{ github.sha }} + # Same guard as babyboo's emitGuardedRollout.sh: annotate first, and skip when the + # Deployment already runs a newer commit (by committer time), so an older run never rolls + # back a newer image. A missing Deployment (manifests not applied yet) is skipped, not failed. + run: | + case "$SHA" in *[!0-9a-f]*|'') echo "Refusing unexpected sha"; exit 1 ;; esac + COMMIT_TIME="$(git log -1 --format=%ct "$SHA")" + case "$COMMIT_TIME" in ''|*[!0-9]*) echo "cannot resolve the commit time of $SHA"; exit 1 ;; esac + mkdir -p /root/.ssh && chmod 700 /root/.ssh + printf '%s' "$DEPLOY_SSH_KEY" > /root/.ssh/id_rsa + chmod 600 /root/.ssh/id_rsa + ssh -i /root/.ssh/id_rsa -o StrictHostKeyChecking=no "${DEPLOY_USER}@${DEPLOY_HOST}" 'bash -s' </dev/null 2>&1; then + echo "ins-landing-page/ins-landing-page not found: apply k8s/ first (README). Skipping rollout." + exit 0 + fi + cur=\$(k -n ins-landing-page get deployment/ins-landing-page -o 'go-template={{with .metadata.annotations}}{{index . "ins-landing-page/deployed-commit-time"}}{{end}}') + case "\$cur" in ''|*[!0-9]*) cur=0 ;; esac + if [ "\$cur" -gt $COMMIT_TIME ]; then + echo "Skip: ins-landing-page runs a newer commit (commit time \$cur > $COMMIT_TIME)" + else + k -n ins-landing-page annotate --overwrite deployment/ins-landing-page ins-landing-page/deployed-commit-time=$COMMIT_TIME ins-landing-page/deployed-commit=$SHA + ./krrd.sh ins-landing-page ins-landing-page + fi + EOF + + - name: Telegram notification + if: always() + # Uses github.actor (the authenticated pusher) β€” always populated, so the + # "Commit by " problem from the Drone setup cannot happen here. + env: + TG_TOKEN: ${{ secrets.TELEGRAM_TOKEN }} + TG_TO: ${{ secrets.TELEGRAM_TO }} + BUILD_STATUS: ${{ job.status }} + ACTOR: ${{ github.actor }} + REPO: ${{ github.repository }} + BRANCH: ${{ github.ref_name }} + RUN_NUMBER: ${{ github.run_number }} + COMMIT_MSG: ${{ github.event.head_commit.message }} + RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }} + run: | + if [ "$BUILD_STATUS" = "success" ]; then + HEAD="βœ… Build #${RUN_NUMBER} of \`${REPO}\` succeeded." + else + HEAD="❌ Build #${RUN_NUMBER} of \`${REPO}\` failed." + fi + TEXT="$(printf '%s\n\nπŸ“ Pushed by %s on `%s`:\n\n```\n%s\n```\n\n🌐 %s' \ + "$HEAD" "$ACTOR" "$BRANCH" "$COMMIT_MSG" "$RUN_URL")" + curl -sS "https://api.telegram.org/bot${TG_TOKEN}/sendMessage" \ + --data-urlencode "chat_id=${TG_TO}" \ + --data-urlencode "parse_mode=Markdown" \ + --data-urlencode "text=${TEXT}" >/dev/null + + - name: Microsoft Teams notification + if: always() + # Independent of the Telegram step: both run on every build regardless of + # the other's outcome. Posts an Adaptive Card, which both Teams Workflows + # webhooks and legacy incoming webhooks accept. + env: + TEAMS_WEBHOOK_URL: ${{ secrets.MICROSOFT_TEAMS_WEBHOOK_URL }} + BUILD_STATUS: ${{ job.status }} + ACTOR: ${{ github.actor }} + REPO: ${{ github.repository }} + BRANCH: ${{ github.ref_name }} + RUN_NUMBER: ${{ github.run_number }} + COMMIT_MSG: ${{ github.event.head_commit.message }} + RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }} + run: | + if [ -z "$TEAMS_WEBHOOK_URL" ]; then + echo "MICROSOFT_TEAMS_WEBHOOK_URL not set β€” skipping." + exit 0 + fi + if [ "$BUILD_STATUS" = "success" ]; then + HEAD="βœ… Build #${RUN_NUMBER} of ${REPO} succeeded." + COLOR="Good" + else + HEAD="❌ Build #${RUN_NUMBER} of ${REPO} failed." + COLOR="Attention" + fi + # JSON-escape without relying on jq being in the build image. + json_escape() { + printf '%s' "$1" | tr -d '\r' \ + | sed -e 's/\\/\\\\/g' -e 's/"/\\"/g' -e 's/\t/\\t/g' \ + | awk 'NR > 1 { printf "\\n" } { printf "%s", $0 }' + } + BODY="$(cat < --docker-password= + k apply -f k8s/ + k -n ins-landing-page rollout status deployment/ins-landing-page + +Updates: every push to `main` runs the tests and builds `gitea.containerverse.dev/solvway/ins-landing-page:ins-landing-page-prd-latest`. CI then runs `./krrd.sh ins-landing-page ins-landing-page` on the deploy host. Manifest changes are applied by hand (`k apply -f k8s/`). + +CI needs the same repository secrets as dynamic-qr: `PACKAGE_USER`, `PACKAGE_RW_KEY`, `DRONECICD_SSH_*`, `TELEGRAM_*` and, optionally, `MICROSOFT_TEAMS_WEBHOOK_URL`. They come from the `solvway` org once the repo is transferred there. + +## Exporting leads + +To CSV, from the running pod: + +```bash +microk8s kubectl -n ins-landing-page exec deploy/ins-landing-page -- node --disable-warning=ExperimentalWarning -e " +const {DatabaseSync}=require('node:sqlite'); +const rows=new DatabaseSync(process.env.DB_PATH,{readOnly:true}).prepare('SELECT * FROM leads ORDER BY id').all(); +const q=v=>v==null?'':'\"'+String(v).replace(/^[=+\-@]/,\"'\$&\").replace(/\"/g,'\"\"')+'\"'; +if(rows.length)console.log(Object.keys(rows[0]).join(',')); +for(const r of rows)console.log(Object.values(r).map(q).join(',')); +" > leads.csv +``` + +Prefer the CSV export above. The database runs in WAL mode, so copying only `leads.db` can miss the newest leads; if you copy the file, copy `leads.db-wal` with it. + +Columns: `id, created_at (UTC), name, email, phone, company, service, referrer, utm_source, utm_medium, utm_campaign`. + +Leads contain personal data (PDPA). Keep exported files out of shared drives and delete them when done. diff --git a/docs/superpowers/specs/2026-12-01-ins-landing-page-design.md b/docs/superpowers/specs/2026-12-01-ins-landing-page-design.md index 25cde4f..45b7f68 100644 --- a/docs/superpowers/specs/2026-12-01-ins-landing-page-design.md +++ b/docs/superpowers/specs/2026-12-01-ins-landing-page-design.md @@ -39,3 +39,17 @@ Admin portal, email notifications, CAPTCHA, analytics, CMS. ## Left to the builder Visual styling, exact section copy wording (from source site), field length limits. + +## Revision 2026-12-01: hotel technology brief from the page owner + +The page owner supplied a new brief. It replaces the page content and form; storage and deployment are unchanged. + +- Audience: hotel, resort, serviced-apartment and co-living decision-makers. Positioning: "One partner for the connected hotel." +- Five services: WiFi Managed Services (Infinity OneBox), Cloud IP PABX (CloudExt), GRE IPTV, Digital Signage, QR Door Locks. Process: Design, Supply, Install, Manage. +- Sections: sticky header, hero with form, trust strip, services, how we work, why Infinity, FAQ, final CTA with a second form, footer. Optional "Meet us at" badge, disabled by default. +- Form fields, exactly: full name, work email, phone/WhatsApp, company (all required); service interested in (optional select). Free email providers (gmail, yahoo, hotmail, etc.) are rejected with a friendly message, on the page and on the server. +- No statistics or client claims; unknown facts use `[PLACEHOLDER]` with a code comment. +- Contact: +6019 365 6987, John.goh@infinitynetworks.com.my. +- Google Fonts allowed (owner request). Floating WhatsApp/call button on mobile. +- Decision (user, 2026-12-01): keep the existing database endpoint instead of the brief's `action="#"` placeholder. +- Schema: `industry` and `message` columns replaced by `service`. The local database held only throwaway test data and is recreated. diff --git a/k8s/00-namespace.yaml b/k8s/00-namespace.yaml new file mode 100644 index 0000000..bd0dcaf --- /dev/null +++ b/k8s/00-namespace.yaml @@ -0,0 +1,4 @@ +apiVersion: v1 +kind: Namespace +metadata: + name: ins-landing-page diff --git a/k8s/40-app.yaml b/k8s/40-app.yaml new file mode 100644 index 0000000..deddf0a --- /dev/null +++ b/k8s/40-app.yaml @@ -0,0 +1,95 @@ +# Leads live in a SQLite file on this volume. ReadWriteOnce + 1 replica + Recreate: SQLite has a +# single writer, so two pods must never hold the file at once (not even during a rollout). +apiVersion: v1 +kind: PersistentVolumeClaim +metadata: + name: ins-landing-page-data + namespace: ins-landing-page +spec: + storageClassName: longhorn + accessModes: + - ReadWriteOnce + resources: + requests: + storage: 1Gi +--- +apiVersion: v1 +kind: Service +metadata: + name: ins-landing-page + namespace: ins-landing-page +spec: + selector: + app: ins-landing-page + ports: + - name: http + port: 3000 +--- +apiVersion: apps/v1 +kind: Deployment +metadata: + name: ins-landing-page + namespace: ins-landing-page +spec: + replicas: 1 + strategy: + type: Recreate + selector: + matchLabels: + app: ins-landing-page + template: + metadata: + labels: + app: ins-landing-page + spec: + imagePullSecrets: + - name: regcred + terminationGracePeriodSeconds: 10 + securityContext: + runAsNonRoot: true + runAsUser: 1000 # the image's `node` user + runAsGroup: 1000 + fsGroup: 1000 # so the app can write to the Longhorn volume + containers: + - name: ins-landing-page + # One moving tag per profile (CI); the rollout restarts the pod to pull it. + image: gitea.containerverse.dev/solvway/ins-landing-page:ins-landing-page-prd-latest + imagePullPolicy: Always + env: + - name: PORT + value: "3000" + - name: DB_PATH + value: /data/leads.db + ports: + - name: http + containerPort: 3000 + volumeMounts: + - name: data + mountPath: /data + readinessProbe: + httpGet: + path: / + port: http + periodSeconds: 10 + livenessProbe: + httpGet: + path: / + port: http + initialDelaySeconds: 10 + periodSeconds: 30 + failureThreshold: 3 + resources: + requests: + cpu: 20m + memory: 48Mi + limits: + memory: 192Mi + securityContext: + allowPrivilegeEscalation: false + readOnlyRootFilesystem: true + capabilities: + drop: ["ALL"] + volumes: + - name: data + persistentVolumeClaim: + claimName: ins-landing-page-data diff --git a/k8s/50-gateway.yaml b/k8s/50-gateway.yaml new file mode 100644 index 0000000..8de5d21 --- /dev/null +++ b/k8s/50-gateway.yaml @@ -0,0 +1,124 @@ +# Served by Traefik through the Gateway API (GatewayClass `traefik`), the same way as dynamic-qr. +# Cloudflare connects to the origin over HTTPS: port 8443 is Traefik's `websecure` entry point +# (host port 443), 8000 its `web` entry point (host port 80), which only redirects to HTTPS. +# +# Let's Encrypt certificate via cert-manager (ClusterIssuer `lets-encrypt`, HTTP-01). The solver +# pod runs in this namespace and is allowed in by k8s/60-network-policy.yaml. +apiVersion: cert-manager.io/v1 +kind: Certificate +metadata: + name: ins-landing-page-tls + namespace: ins-landing-page +spec: + secretName: ins-landing-page-tls + issuerRef: + group: cert-manager.io + kind: ClusterIssuer + name: lets-encrypt + dnsNames: + - ins-landing.containerverse.dev + usages: + - digital signature + - key encipherment +--- +apiVersion: gateway.networking.k8s.io/v1 +kind: Gateway +metadata: + name: ins-landing-page + namespace: ins-landing-page +spec: + gatewayClassName: traefik + listeners: + - name: http + protocol: HTTP + port: 8000 + allowedRoutes: + namespaces: + from: Same + - name: websecure + protocol: HTTPS + port: 8443 + hostname: ins-landing.containerverse.dev + tls: + mode: Terminate + certificateRefs: + - kind: Secret + group: "" + name: ins-landing-page-tls + allowedRoutes: + namespaces: + from: Same +--- +# Plain HTTP: permanent redirect to HTTPS. +apiVersion: gateway.networking.k8s.io/v1 +kind: HTTPRoute +metadata: + name: https-redirect + namespace: ins-landing-page +spec: + parentRefs: + - name: ins-landing-page + sectionName: http + hostnames: + - ins-landing.containerverse.dev + rules: + - matches: + - path: + type: PathPrefix + value: / + filters: + - type: RequestRedirect + requestRedirect: + scheme: https + port: 443 + statusCode: 301 +--- +# The lead form is public; the honeypot only stops naive bots. Limit form posts per visitor so a +# script cannot fill the volume. depth: 1 takes the right-most X-Forwarded-For entry, which +# Cloudflare sets to the visitor (Traefik keeps that header only from Cloudflare's ranges). +apiVersion: traefik.io/v1alpha1 +kind: Middleware +metadata: + name: lead-rate-limit + namespace: ins-landing-page +spec: + rateLimit: + average: 5 + period: 1m + burst: 5 + sourceCriterion: + ipStrategy: + depth: 1 +--- +apiVersion: gateway.networking.k8s.io/v1 +kind: HTTPRoute +metadata: + name: ins-landing-page + namespace: ins-landing-page +spec: + parentRefs: + - name: ins-landing-page + sectionName: websecure + hostnames: + - ins-landing.containerverse.dev + rules: + - matches: + - path: + type: Exact + value: /api/leads + filters: + - type: ExtensionRef + extensionRef: + group: traefik.io + kind: Middleware + name: lead-rate-limit + backendRefs: + - name: ins-landing-page + port: 3000 + - matches: + - path: + type: PathPrefix + value: / + backendRefs: + - name: ins-landing-page + port: 3000 diff --git a/k8s/60-network-policy.yaml b/k8s/60-network-policy.yaml new file mode 100644 index 0000000..68d7aa9 --- /dev/null +++ b/k8s/60-network-policy.yaml @@ -0,0 +1,61 @@ +# Ingress rules for namespace ins-landing-page (enforced by Calico). Everything is denied unless +# a policy below allows it. The kubelet's probes come from the pod's own node, which Calico always +# allows, so they need no rule. +apiVersion: networking.k8s.io/v1 +kind: NetworkPolicy +metadata: + name: default-deny-ingress + namespace: ins-landing-page +spec: + podSelector: {} + policyTypes: + - Ingress +--- +# Traefik (MicroK8s ingress addon, namespace `ingress`) to the app. +apiVersion: networking.k8s.io/v1 +kind: NetworkPolicy +metadata: + name: app-from-traefik + namespace: ins-landing-page +spec: + podSelector: + matchLabels: + app: ins-landing-page + policyTypes: + - Ingress + ingress: + - from: + - namespaceSelector: + matchLabels: + kubernetes.io/metadata.name: ingress + podSelector: + matchLabels: + app.kubernetes.io/name: traefik + ports: + - protocol: TCP + port: 3000 +--- +# cert-manager's HTTP-01 solver pod: Traefik must reach it, or the certificate cannot be issued +# or renewed. +apiVersion: networking.k8s.io/v1 +kind: NetworkPolicy +metadata: + name: acme-solver-from-traefik + namespace: ins-landing-page +spec: + podSelector: + matchLabels: + acme.cert-manager.io/http01-solver: "true" + policyTypes: + - Ingress + ingress: + - from: + - namespaceSelector: + matchLabels: + kubernetes.io/metadata.name: ingress + podSelector: + matchLabels: + app.kubernetes.io/name: traefik + ports: + - protocol: TCP + port: 8089 diff --git a/package.json b/package.json new file mode 100644 index 0000000..9adc55a --- /dev/null +++ b/package.json @@ -0,0 +1,9 @@ +{ + "name": "ins-landing-page", + "private": true, + "engines": { "node": ">=22.13" }, + "scripts": { + "start": "node server.js", + "test": "node --test" + } +} diff --git a/public/index.html b/public/index.html new file mode 100644 index 0000000..c58ec3f --- /dev/null +++ b/public/index.html @@ -0,0 +1,541 @@ + + + + + +Hotel Technology, One Partner | Infinity Networks Security + + + + + + + + + + + + + + + +
+ +
+ +
+
+ + +
+
+ +

One partner for the connected hotel.

+

WiFi, phones, in-room TV, signage and door locks, designed, installed and managed by one local team so yours can focus on guests.

+
    +
  • One accountable partner instead of five vendors
  • +
  • Cloud-managed, so updates and fixes happen remotely
  • +
  • Local support team in Malaysia
  • +
+
+
+

Get a free consultation

+

Tell us about your property. It takes under a minute.

+ +
+
+ + +

+
+
+ + +

+
+
+ + +

+
+
+ + +

+
+
+ + +
+ + + + + +

A specialist will call or WhatsApp you within [PLACEHOLDER: 1 business day] to understand your property.

+

We only use your details to respond to this enquiry.

+
+
+
+
+ +
+
    +
  • Certified with LG Β· Samsung Β· Philips
  • +
  • Design β€’ Supply β€’ Install β€’ Manage
  • +
  • Malaysian-based local support
  • +
+
+ +
+
+
+

Services

+

Everything your guests touch, handled by one team

+

Pick one service or bring them all together. Either way, you get one point of contact.

+
+
+
+ +

WiFi Managed Services

+

Infinity OneBox

+

Fast, reliable WiFi in every room and back office, monitored around the clock so problems are fixed before guests complain.

+
+
+ +

Cloud IP PABX

+

CloudExt

+

Replace your ageing phone system without ripping it out. Front-desk features, wake-up calls and call reports, all in the cloud.

+
+
+ +

GRE IPTV

+

Works with LG, Samsung, Philips

+

In-room TV with your own welcome screen, and guests can cast from their phones, all over the network you already have.

+
+
+ +

Digital Signage

+

Lobby, meeting rooms, F&B

+

Keep meeting schedules, wayfinding, promotions and menus up to date from one dashboard, with no reprinting.

+
+
+ +

QR Door Locks

+

Hotels, serviced apartments, co-living

+

Contactless entry. Issue or revoke keys remotely, with a full record of who opened which door and when.

+
+
+
+
+ +
+
+
+

How we work

+

From first survey to day-to-day care

+

One team carries your project from start to finish, so nothing falls between vendors.

+
+
    +
  1. Design

    We survey your property and plan around your guests, your building and your budget.

  2. +
  3. Supply

    We source the right equipment, reusing what you already have where it makes sense.

  4. +
  5. Install

    Our engineers install and test on site, scheduled around your occupancy.

  6. +
  7. Manage

    We monitor, update and support everything after go-live, so your team doesn't have to.

  8. +
+
+
+ +
+
+
+
+

Why Infinity

+

Fewer vendors. Fewer headaches.

+
+
    +
  • One accountable partnerOne number to call for WiFi, phones, TV, signage and locks.
  • +
  • Lower total costConsolidating vendors cuts duplicated contracts and support fees.
  • +
  • Better guest experienceSystems that work together, so guests notice comfort, not technology.
  • +
  • Cloud-managed, future-readyRemote updates and monitoring, with room to add services later.
  • +
  • Local support in MalaysiaA team in your time zone who can be on site when needed.
  • +
  • Built for multiple propertiesA proven rollout playbook to bring every site up to the same standard.
  • +
+
+ + +
+
+ +
+
+
+

FAQ

+

Questions hotels ask us

+
+
+
+ Can you work with our existing cabling and equipment? +

Often, yes. We survey first and reuse cabling and equipment wherever it is sound. Our cloud phone migration, for example, is designed to avoid a rip-and-replace.

+
+
+ Do you support groups with multiple properties? +

Yes. We use a proven rollout playbook so every property gets the same setup and standard, and everything is managed centrally from the cloud.

+
+
+ How long does installation take? + +

It depends on the size of the property and the services you choose. As a guide, [PLACEHOLDER: typical timeline]. We schedule work around your occupancy to keep disruption to guests low.

+
+
+ Is support local? +

Yes. Our team is based in Malaysia, with offices in Petaling Jaya and Penang.

+
+
+ Can I choose just one service? +

Absolutely. Many hotels start with one service, such as WiFi or phones, and add more later. You still get one point of contact.

+
+
+
+
+ +
+
+
+

Free consultation

+

Let's make your hotel easier to run.

+

Tell us what you have today and what's not working. We'll come back with a practical plan, with no obligation.

+
+
+

Get a free consultation

+

Tell us about your property. It takes under a minute.

+
+
+ + +

+
+
+ + +

+
+
+ + +

+
+
+ + +

+
+
+ + +
+ + + + +

A specialist will call or WhatsApp you within [PLACEHOLDER: 1 business day] to understand your property.

+

We only use your details to respond to this enquiry.

+
+
+
+
+
+ + + + + + + + diff --git a/public/logo.png b/public/logo.png new file mode 100644 index 0000000..174ce7a Binary files /dev/null and b/public/logo.png differ diff --git a/scripts/waitForOlderRuns.sh b/scripts/waitForOlderRuns.sh new file mode 100755 index 0000000..445dd61 --- /dev/null +++ b/scripts/waitForOlderRuns.sh @@ -0,0 +1,82 @@ +#!/bin/bash +# Usage: waitForOlderRuns.sh +# Queues deploy runs per branch (openspec ci-pipeline): returns 0 once no OLDER push run of this +# branch is pending, queued or in progress, so runs build and roll out one at a time, in push order. +# Gitea's workflow `concurrency` cannot do this: it keeps one waiting run per group and cancels the +# others, even with cancel-in-progress: false. +# +# It also refuses (exit 1) when a NEWER push run of the branch has already succeeded: that is a manual +# re-run of an old run, which would roll an older image out over a newer one. Push again instead; the +# self-heal (resolveDeployBase.sh) rebuilds whatever the old run missed. +# +# Fails closed: a failed or unreadable API answer counts as "still waiting", and a run still waiting +# after WAIT_TIMEOUT seconds exits 1 rather than build alongside an older run. A refused token (401/403) +# exits 1 at once β€” waiting would only end in the timeout. +# +# ponytail: reads the newest 50 runs of each kind; an older unfinished run beyond them is not seen. A run +# being cancelled (Gitea "cancelling") is reported in_progress by the API but is not matched by the +# status=in_progress filter; both gaps are seconds-to-minutes wide here β€” page the API if that changes. +# +# Env: GITEA_TOKEN, GITEA_API (…/api/v1), GITEA_REPO (owner/name), GITEA_BRANCH β€” for the default fetch. +# WAIT_INTERVAL (s, default 30), WAIT_TIMEOUT (s, default 7200), WAIT_FETCH (a command printing the +# runs JSON; tests replace the API with it). +set -u +own="${1:-}" +if ! [[ "$own" =~ ^[0-9]+$ ]]; then + echo "waitForOlderRuns: own run number must be a number, got '$own'" >&2 + exit 2 +fi +interval="${WAIT_INTERVAL:-30}" +deadline=$(( $(date +%s) + ${WAIT_TIMEOUT:-7200} )) + +fetch() { # $1 = unfinished | succeeded. Prints the runs JSON; exit 3 = token refused, other non-zero = failed. + if [ -n "${WAIT_FETCH:-}" ]; then + "$WAIT_FETCH" "$1" + return + fi + local status=status=success code body + [ "$1" = unfinished ] && status="status=pending&status=queued&status=in_progress" + body="$(mktemp)" + code="$(curl -sS --max-time 20 -o "$body" -w '%{http_code}' -H "Authorization: token $GITEA_TOKEN" \ + "$GITEA_API/repos/$GITEA_REPO/actions/runs?branch=$GITEA_BRANCH&event=push&$status&limit=50")" || code=000 + case "$code" in + 200) cat "$body"; rm -f "$body"; return 0 ;; + 401|403) rm -f "$body"; return 3 ;; + *) rm -f "$body"; return 1 ;; + esac +} + +run_numbers() { # runs JSON on stdin -> its run numbers, one per line. Nested objects carry no run_number. + grep -o '"run_number":[0-9]\+' | cut -d: -f2 +} + +while :; do + json="$(fetch unfinished)"; rc=$? + if [ "$rc" -eq 3 ]; then + echo "Runs API refused the job token (401/403); cannot queue run #$own safely." >&2 + exit 1 + fi + if [ "$rc" -eq 0 ] && [[ "$json" == *'"workflow_runs"'* ]]; then + older="$(printf '%s' "$json" | run_numbers | awk -v own="$own" '$1 < own' | sort -n | tr '\n' ' ')" + if [ -n "$older" ]; then + echo "Run #$own waits for older run(s): ${older% }" + elif done_json="$(fetch succeeded)" && [[ "$done_json" == *'"workflow_runs"'* ]]; then + newer="$(printf '%s' "$done_json" | run_numbers | awk -v own="$own" '$1 > own' | sort -n | tr '\n' ' ')" + if [ -n "$newer" ]; then + echo "Run #$own is older than run(s) ${newer% }, which already deployed; refusing to roll back. Push again instead." >&2 + exit 1 + fi + echo "No older run of this branch is unfinished; starting run #$own." + exit 0 + else + echo "Runs API read failed; run #$own keeps waiting." + fi + else + echo "Runs API read failed; run #$own keeps waiting." + fi + if [ "$(date +%s)" -ge "$deadline" ]; then + echo "Run #$own still waiting after ${WAIT_TIMEOUT:-7200}s; failing rather than building alongside an older run." >&2 + exit 1 + fi + sleep "$interval" +done diff --git a/server.js b/server.js new file mode 100644 index 0000000..bc7c073 --- /dev/null +++ b/server.js @@ -0,0 +1,121 @@ +const http = require('node:http'); +const fs = require('node:fs'); +const path = require('node:path'); +const { DatabaseSync } = require('node:sqlite'); + +const MAX_BODY = 10 * 1024; +const REQUIRED = ['name', 'email', 'phone', 'company']; +const OPTIONAL = ['service', 'referrer', 'utm_source', 'utm_medium', 'utm_campaign']; +const MAX_LEN = { referrer: 500 }; +const EMAIL = /^[^\s@]+@[^\s@]+\.[^\s@]+$/; +const SERVICES = ['WiFi Managed Services', 'Cloud IP PABX', 'GRE IPTV', 'Digital Signage', 'QR Door Locks', 'Not sure yet']; +// matches the domain's first label, so yahoo.com.my, hotmail.co.uk etc. are covered. +// ponytail: fixed list of the common providers; extend if sales sees others slip through. +const FREE_EMAIL = /@(gmail|googlemail|yahoo|ymail|rocketmail|hotmail|outlook|live|msn|icloud|me|mac|aol|protonmail|proton|gmx|yandex|zoho)\.[a-z.]+$/i; +const PAGES = { '/': ['index.html', 'text/html; charset=utf-8'], '/logo.png': ['logo.png', 'image/png'] }; + +function openDb(dbPath) { + fs.mkdirSync(path.dirname(dbPath), { recursive: true }); + const db = new DatabaseSync(dbPath); + // WAL: an export (reader) never blocks inserts. busy_timeout blocks the event loop while waiting, + // ponytail: fine for one low-traffic pod; move to Postgres if this ever needs concurrency. + db.exec('PRAGMA journal_mode = WAL; PRAGMA busy_timeout = 5000;'); + db.exec(`CREATE TABLE IF NOT EXISTS leads ( + id INTEGER PRIMARY KEY, + created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP, + name TEXT NOT NULL, email TEXT NOT NULL, phone TEXT NOT NULL, company TEXT NOT NULL, + service TEXT, referrer TEXT, + utm_source TEXT, utm_medium TEXT, utm_campaign TEXT + )`); + return db; +} + +function validate(lead) { + for (const f of REQUIRED) { + if (typeof lead[f] !== 'string' || !lead[f].trim()) return `${f} is required`; + } + for (const f of [...REQUIRED, ...OPTIONAL]) { + const v = lead[f]; + if (v != null && typeof v !== 'string') return `${f} must be text`; + if (v && v.length > (MAX_LEN[f] || 200)) return `${f} is too long`; + } + if (!EMAIL.test(lead.email.trim())) return 'email is invalid'; + if (FREE_EMAIL.test(lead.email.trim())) return 'Please use your work email address'; + if (lead.service && !SERVICES.includes(lead.service)) return 'service is invalid'; + return null; +} + +function send(res, status, body) { + res.writeHead(status, { 'content-type': 'application/json' }); + res.end(JSON.stringify(body)); +} + +function readBody(req) { + return new Promise((resolve, reject) => { + let size = 0; + const chunks = []; + req.on('data', (c) => { + size += c.length; + // keep draining (not destroy) so the 413 reaches the client; the ingress body limit (nginx default 1m) caps abuse + if (size > MAX_BODY) reject(Object.assign(new Error('too large'), { status: 413 })); + else chunks.push(c); + }); + req.on('end', () => resolve(Buffer.concat(chunks).toString('utf8'))); + req.on('error', reject); + }); +} + +function createServer(dbPath) { + // load static files up front: a missing file fails at startup instead of crashing on a request + const files = {}; + for (const [url, [file, type]] of Object.entries(PAGES)) { + files[url] = { body: fs.readFileSync(path.join(__dirname, 'public', file)), type }; + } + const db = openDb(dbPath); + const insert = db.prepare(`INSERT INTO leads + (name, email, phone, company, service, referrer, utm_source, utm_medium, utm_campaign) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`); + + const server = http.createServer(async (req, res) => { + const url = req.url.split('?')[0]; + + if (req.method === 'GET' && files[url]) { + res.writeHead(200, { 'content-type': files[url].type }); + return res.end(files[url].body); + } + if (req.method === 'POST' && url === '/api/leads') { + let lead; + try { + lead = JSON.parse(await readBody(req)); + } catch (e) { + return send(res, e.status || 400, { error: e.status ? 'Request too large' : 'Invalid request' }); + } + if (!lead || typeof lead !== 'object') return send(res, 400, { error: 'Invalid request' }); + if (lead.website) return send(res, 200, { ok: true }); // honeypot: pretend success, store nothing + const error = validate(lead); + if (error) return send(res, 400, { error }); + try { + const t = (f) => (lead[f] ? lead[f].trim() : null); + insert.run(t('name'), t('email'), t('phone'), t('company'), t('service'), + t('referrer'), t('utm_source'), t('utm_medium'), t('utm_campaign')); + } catch (e) { + console.error('lead insert failed:', e.message); + return send(res, 500, { error: 'Could not save, please try again' }); + } + return send(res, 201, { ok: true }); + } + send(res, 404, { error: 'Not found' }); + }); + server.on('close', () => db.close()); + return server; +} + +module.exports = { createServer }; + +if (require.main === module) { + const port = Number(process.env.PORT ?? 3000); + const server = createServer(process.env.DB_PATH || path.join(__dirname, 'data', 'leads.db')); + server.listen(port, () => console.log(`listening on :${port}`)); + // node as PID 1 ignores SIGTERM by default; exit cleanly so k8s rollouts don't wait 30s + process.on('SIGTERM', () => server.close(() => process.exit(0))); +} diff --git a/server.test.js b/server.test.js new file mode 100644 index 0000000..9800276 --- /dev/null +++ b/server.test.js @@ -0,0 +1,146 @@ +const { test, before, after } = require('node:test'); +const assert = require('node:assert'); +const fs = require('node:fs'); +const os = require('node:os'); +const path = require('node:path'); +const { DatabaseSync } = require('node:sqlite'); +const { createServer } = require('./server'); + +const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'ins-leads-')); +const dbPath = path.join(dir, 'leads.db'); +let server, base; + +before(async () => { + server = createServer(dbPath); + await new Promise((r) => server.listen(0, r)); + base = `http://127.0.0.1:${server.address().port}`; +}); +after(() => { + server.close(); + fs.rmSync(dir, { recursive: true, force: true }); +}); + +const valid = { + name: 'Aisyah Rahman', + email: 'aisyah@seripinang.com.my', + phone: '+60 12-345 6789', + company: 'Hotel Seri Pinang', + service: 'Cloud IP PABX', + utm_source: 'google', + referrer: 'https://www.google.com/', +}; + +const post = (body) => + fetch(`${base}/api/leads`, { + method: 'POST', + headers: { 'content-type': 'application/json', referer: 'https://ads.example.com/' }, + body: typeof body === 'string' ? body : JSON.stringify(body), + }); + +const rows = () => { + const db = new DatabaseSync(dbPath); + const r = db.prepare('SELECT * FROM leads').all(); + db.close(); + return r; +}; + +test('serves the landing page', async () => { + const res = await fetch(`${base}/`); + assert.strictEqual(res.status, 200); + assert.match(res.headers.get('content-type'), /text\/html/); +}); + +test('valid lead is stored', async () => { + const res = await post(valid); + assert.strictEqual(res.status, 201); + const r = rows(); + assert.strictEqual(r.length, 1); + assert.strictEqual(r[0].name, valid.name); + assert.strictEqual(r[0].company, valid.company); + assert.strictEqual(r[0].service, 'Cloud IP PABX'); + assert.strictEqual(r[0].utm_source, 'google'); + assert.strictEqual(r[0].referrer, 'https://www.google.com/'); + assert.ok(r[0].created_at); +}); + +test('missing required field is rejected', async () => { + const before = rows().length; + const res = await post({ ...valid, phone: '' }); + assert.strictEqual(res.status, 400); + assert.ok((await res.json()).error); + assert.strictEqual(rows().length, before); +}); + +test('invalid email is rejected', async () => { + assert.strictEqual((await post({ ...valid, email: 'abc' })).status, 400); +}); + +test('free email providers are rejected with a friendly message', async () => { + for (const email of ['a@gmail.com', 'a@Yahoo.com.my', 'a@hotmail.com', 'a@outlook.com', 'a@icloud.com']) { + const res = await post({ ...valid, email }); + assert.strictEqual(res.status, 400, email); + assert.match((await res.json()).error, /work email/i); + } +}); + +test('unknown service is rejected, missing service is allowed', async () => { + assert.strictEqual((await post({ ...valid, service: 'Plumbing' })).status, 400); + const { service, ...noService } = valid; + assert.strictEqual((await post(noService)).status, 201); +}); + +test('over-long field is rejected', async () => { + assert.strictEqual((await post({ ...valid, name: 'x'.repeat(201) })).status, 400); +}); + +test('non-JSON body is rejected', async () => { + assert.strictEqual((await post('not json')).status, 400); +}); + +test('oversized body is rejected', async () => { + assert.strictEqual((await post({ ...valid, company: 'x'.repeat(11000) })).status, 413); +}); + +test('honeypot submission is accepted but not stored', async () => { + const before = rows().length; + const res = await post({ ...valid, website: 'http://spam.example' }); + assert.strictEqual(res.status, 200); + assert.strictEqual(rows().length, before); +}); + +const { spawn } = require('node:child_process'); + +test('missing page file fails at startup, not on a request', () => { + const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'ins-nopage-')); + fs.copyFileSync(path.join(__dirname, 'server.js'), path.join(tmp, 'server.js')); + const { createServer: create } = require(path.join(tmp, 'server.js')); + assert.throws(() => create(path.join(tmp, 'leads.db')), /ENOENT/); + fs.rmSync(tmp, { recursive: true, force: true }); +}); + +test('insert waits for a lock held by another process (e.g. an export)', async () => { + const lock = spawn(process.execPath, ['--disable-warning=ExperimentalWarning', '-e', ` + const { DatabaseSync } = require('node:sqlite'); + const db = new DatabaseSync(${JSON.stringify(dbPath)}); + db.exec('BEGIN EXCLUSIVE'); + console.log('locked'); + setTimeout(() => { db.exec('COMMIT'); db.close(); }, 500); + `]); + await new Promise((r) => lock.stdout.once('data', r)); + const res = await post(valid); + assert.strictEqual(res.status, 201); +}); + +test('exits promptly on SIGTERM', async () => { + const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'ins-term-')); + const child = spawn(process.execPath, ['--disable-warning=ExperimentalWarning', path.join(__dirname, 'server.js')], { + env: { ...process.env, PORT: '0', DB_PATH: path.join(tmp, 'leads.db') }, + }); + await new Promise((r) => child.stdout.once('data', r)); + const start = Date.now(); + child.kill('SIGTERM'); + const code = await new Promise((r) => child.on('exit', (c) => r(c))); + assert.strictEqual(code, 0); + assert.ok(Date.now() - start < 2000); + fs.rmSync(tmp, { recursive: true, force: true }); +});