@caddis/cli 0.4.92 → 0.4.93
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +4 -0
- package/bundles/antigravity-plugin/agents/debug.md +2 -0
- package/bundles/antigravity-plugin/plugin.json +1 -1
- package/bundles/antigravity-plugin/scripts/__pycache__/caddis_exit.cpython-311.pyc +0 -0
- package/bundles/antigravity-plugin/scripts/__pycache__/caddis_file_lock.cpython-311.pyc +0 -0
- package/bundles/antigravity-plugin/scripts/__pycache__/caddis_frontmatter.cpython-311.pyc +0 -0
- package/bundles/antigravity-plugin/scripts/__pycache__/caddis_redact.cpython-311.pyc +0 -0
- package/bundles/antigravity-plugin/scripts/__pycache__/caddis_roadmap.cpython-311.pyc +0 -0
- package/bundles/antigravity-plugin/scripts/__pycache__/caddis_rows.cpython-311.pyc +0 -0
- package/bundles/antigravity-plugin/scripts/__pycache__/caddis_status.cpython-311.pyc +0 -0
- package/bundles/antigravity-plugin/scripts/__pycache__/caddis_tidy.cpython-311.pyc +0 -0
- package/bundles/antigravity-plugin/scripts/__pycache__/caddis_todo.cpython-311.pyc +0 -0
- package/bundles/antigravity-plugin/scripts/__pycache__/caddis_workstreams.cpython-311.pyc +0 -0
- package/bundles/antigravity-plugin/scripts/__pycache__/caddis_worktree_safety.cpython-311.pyc +0 -0
- package/bundles/antigravity-plugin/scripts/caddis_checkout_guard.py +1 -1
- package/bundles/antigravity-plugin/scripts/caddis_fleet.py +26 -9
- package/bundles/antigravity-plugin/scripts/caddis_guide.json +58 -6
- package/bundles/antigravity-plugin/scripts/caddis_preload_review.py +554 -0
- package/bundles/antigravity-plugin/scripts/caddis_roadmap_run.py +9 -3
- package/bundles/antigravity-plugin/scripts/caddis_run.py +160 -0
- package/bundles/antigravity-plugin/scripts/caddis_spawn.py +17 -1
- package/bundles/antigravity-plugin/scripts/caddis_upstream_check.py +108 -10
- package/bundles/antigravity-plugin/scripts/setup_project_ai.py +65 -1
- package/bundles/antigravity-plugin/skills/_registry.md +3 -1
- package/bundles/antigravity-plugin/skills/brainstorming/SKILL.md +232 -40
- package/bundles/antigravity-plugin/skills/brainstorming/builder-check-prompt.md +25 -0
- package/bundles/antigravity-plugin/skills/feature-plan/SKILL.md +7 -1
- package/bundles/antigravity-plugin/skills/fleet-close/SKILL.md +4 -1
- package/bundles/antigravity-plugin/skills/graph-email/SKILL.md +15 -0
- package/bundles/antigravity-plugin/skills/handoff/SKILL.md +9 -2
- package/bundles/antigravity-plugin/skills/implement/SKILL.md +3 -0
- package/bundles/antigravity-plugin/skills/particle-art/SKILL.md +1 -3
- package/bundles/antigravity-plugin/skills/preload-review/SKILL.md +69 -0
- package/bundles/antigravity-plugin/skills/roadmap/SKILL.md +4 -0
- package/bundles/antigravity-plugin/skills/roadmap/assets/plan-resume-prompt.md +6 -5
- package/bundles/antigravity-plugin/skills/spawn-session/SKILL.md +5 -0
- package/bundles/antigravity-plugin/skills/tdd/SKILL.md +2 -1
- package/bundles/antigravity-plugin/skills/usage-review/SKILL.md +2 -0
- package/bundles/antigravity-plugin-extras/plugin.json +1 -1
- package/bundles/antigravity-plugin-extras/skills/_registry.md +1 -0
- package/bundles/antigravity-plugin-extras/skills/graph-email/SKILL.md +53 -0
- package/bundles/antigravity-plugin-extras/skills/graph-email/email.toml.example +44 -0
- package/bundles/antigravity-plugin-extras/skills/graph-email/scripts/send_email.py +432 -0
- package/bundles/codex/.codex/skills/media/particle-art/SKILL.md +1 -3
- package/bundles/codex/.codex/skills/workflow/brainstorming/SKILL.md +232 -40
- package/bundles/codex/.codex/skills/workflow/brainstorming/builder-check-prompt.md +25 -0
- package/bundles/codex/.codex/skills/workflow/roadmap/SKILL.md +4 -0
- package/bundles/codex/.codex/skills/workflow/roadmap/assets/plan-resume-prompt.md +6 -5
- package/bundles/manifest.json +3 -3
- package/dist/export/assets/export-CMtV-slT.css +1 -0
- package/dist/export/index.html +2 -2
- package/dist/ui/assets/{Activity-DZKPMOeV.js → Activity-BDjet2xd.js} +1 -1
- package/dist/ui/assets/Guide-Czn5sK0f.js +9 -0
- package/dist/ui/assets/Guide-D-Zy4cUT.css +1 -0
- package/dist/ui/assets/{RoadmapTab-DPsiSmIF.js → RoadmapTab-Bd8geyQx.js} +1 -1
- package/dist/ui/assets/index-Bd0Z4jR8.css +1 -0
- package/dist/ui/assets/{index-xl156OCN.js → index-CmngQ8Mk.js} +12 -12
- package/dist/ui/index.html +2 -2
- package/package.json +1 -1
- package/dist/export/assets/export-HxTgj3z2.css +0 -1
- package/dist/ui/assets/Guide-5ZFfL6sl.js +0 -9
- package/dist/ui/assets/Guide-Dnsb-TRd.css +0 -1
- package/dist/ui/assets/index-DGlNAmeA.css +0 -1
- /package/dist/export/assets/{export-B7BBDg5I.js → export-DtlDFN4L.js} +0 -0
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: graph-email
|
|
3
|
+
description: Email a Markdown file via Microsoft Graph or SMTP. Use to email a draft or note.
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
# graph-email
|
|
7
|
+
|
|
8
|
+
Sends one email. The provider is `graph` (Microsoft Graph `sendMail`, client credentials) or `smtp`.
|
|
9
|
+
The body is a Markdown file. The script turns it into simple HTML. It never prints a secret or a token.
|
|
10
|
+
|
|
11
|
+
## One-time setup (per machine)
|
|
12
|
+
|
|
13
|
+
1. Copy `email.toml.example` from this skill folder to `~/.caddis/email.toml`.
|
|
14
|
+
2. Set `provider`, `sender` and `env_file`. For SMTP also set the `[smtp]` table.
|
|
15
|
+
3. Put the secrets in the env file, not in the config file:
|
|
16
|
+
- graph: three keys. The default names are `ALERT_GRAPH_TENANT_ID`, `ALERT_GRAPH_CLIENT_ID`, `ALERT_GRAPH_CLIENT_SECRET`. Change the names in the `[graph]` table if your file uses other names.
|
|
17
|
+
- smtp: one key. The default name is `EMAIL_SMTP_PASSWORD`. Change it with `password_key`.
|
|
18
|
+
4. Check the setup. This sends nothing and prints no secret:
|
|
19
|
+
`python -I scripts/send_email.py --check`
|
|
20
|
+
|
|
21
|
+
Every setting can be overridden. The order is: command-line flag, then environment variable, then the config file.
|
|
22
|
+
The variables are `CADDIS_EMAIL_PROVIDER`, `CADDIS_EMAIL_SENDER`, `CADDIS_EMAIL_ENV_FILE`, `CADDIS_EMAIL_CONFIG`
|
|
23
|
+
and `CADDIS_EMAIL_SMTP_HOST`, `_PORT`, `_SECURITY`, `_USERNAME`, `_TIMEOUT`. The flags are `--provider`, `--sender`,
|
|
24
|
+
`--env-file`, `--config`, `--smtp-host`, `--smtp-port`, `--smtp-security` (`starttls`, `ssl` or `none`),
|
|
25
|
+
`--smtp-username`, `--smtp-timeout`. The old names `GRAPH_EMAIL_ENV_FILE` and `GRAPH_EMAIL_SENDER` still work.
|
|
26
|
+
Secrets can also be set as process environment variables. They win over the env file.
|
|
27
|
+
With smtp security `none`, the script refuses a username or password and exits with code 2. Use `starttls` or `ssl`.
|
|
28
|
+
For a local test relay only, set `allow_insecure_auth = true` (a boolean) in the `[smtp]` table.
|
|
29
|
+
|
|
30
|
+
## Steps
|
|
31
|
+
|
|
32
|
+
1. Write the email as a Markdown file in the project's `comms/` folder (a copy stays in the repo).
|
|
33
|
+
- Put `<!-- email-start -->` before the greeting and `<!-- email-end -->` after the sign-off. Only that part is sent.
|
|
34
|
+
- Write plain, short sentences. No em dashes, no arrows, no emoji, no check marks.
|
|
35
|
+
2. Subject line: `caddis-<app-name> <short subject>`, for example `caddis-myapp Data request for the weekly report`.
|
|
36
|
+
3. Dry run. It sends nothing, needs no credentials and writes `<file>.preview.html`:
|
|
37
|
+
`python -I scripts/send_email.py --dry-run --to x@example.com --subject t --body-file <file.md>`
|
|
38
|
+
Read the preview, then delete it.
|
|
39
|
+
4. Send:
|
|
40
|
+
`python -I scripts/send_email.py --to <address> --subject '<subject>' --body-file <file.md> [--attach <file> ...]`
|
|
41
|
+
`--to` can repeat. Graph HTTP 202 means Graph accepted the mail. An SMTP "accepted" means the server took it.
|
|
42
|
+
Neither proves the inbox received it.
|
|
43
|
+
5. Tell the owner what was sent, to whom, and the subject.
|
|
44
|
+
|
|
45
|
+
## Rules
|
|
46
|
+
|
|
47
|
+
- **Default recipient is the owner's own address.** The owner forwards it. Send to a team only when the owner says so
|
|
48
|
+
in this request. Sending to any other address is an outward action: confirm first.
|
|
49
|
+
- Never put personal data, secrets, payment data or customer text in the body.
|
|
50
|
+
- Errors show the provider, the HTTP or SMTP status code and the error name. Do not retry in a loop.
|
|
51
|
+
- Exit codes: 0 done, 1 provider error, 2 missing or invalid setting.
|
|
52
|
+
|
|
53
|
+
Script: `scripts/send_email.py` in this skill folder (Python 3.11 or later, standard library only).
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
# Example config for the graph-email skill. Copy to ~/.caddis/email.toml and fill in your values.
|
|
2
|
+
#
|
|
3
|
+
# Precedence for every setting: command-line flag, then environment variable, then this file.
|
|
4
|
+
# Secrets (Graph client secret, SMTP password) never go in this file. They come from the process
|
|
5
|
+
# environment or from the env file named by `env_file` below.
|
|
6
|
+
|
|
7
|
+
# Which sender to use: "graph" (Microsoft Graph sendMail) or "smtp". Default: "graph".
|
|
8
|
+
# Env var: CADDIS_EMAIL_PROVIDER. Flag: --provider.
|
|
9
|
+
provider = "graph"
|
|
10
|
+
|
|
11
|
+
# The mailbox or address the mail is sent from.
|
|
12
|
+
# Env var: CADDIS_EMAIL_SENDER. Flag: --sender.
|
|
13
|
+
sender = ""
|
|
14
|
+
|
|
15
|
+
# Path to an env file (KEY=value lines) that holds the secrets. Use a literal string
|
|
16
|
+
# (single quotes) so a Windows path needs no escaping.
|
|
17
|
+
# Env var: CADDIS_EMAIL_ENV_FILE. Flag: --env-file.
|
|
18
|
+
env_file = ""
|
|
19
|
+
|
|
20
|
+
[graph]
|
|
21
|
+
# The NAMES of the keys in the env file (or environment) that hold the values.
|
|
22
|
+
# These are the defaults. Change them only if your env file uses other names.
|
|
23
|
+
tenant_id_key = "ALERT_GRAPH_TENANT_ID"
|
|
24
|
+
client_id_key = "ALERT_GRAPH_CLIENT_ID"
|
|
25
|
+
client_secret_key = "ALERT_GRAPH_CLIENT_SECRET"
|
|
26
|
+
|
|
27
|
+
[smtp]
|
|
28
|
+
# Used when provider = "smtp".
|
|
29
|
+
# Env vars: CADDIS_EMAIL_SMTP_HOST, _PORT, _SECURITY, _USERNAME, _TIMEOUT.
|
|
30
|
+
# Flags: --smtp-host, --smtp-port, --smtp-security, --smtp-username, --smtp-timeout.
|
|
31
|
+
host = ""
|
|
32
|
+
# "starttls" (port 587), "ssl" (port 465) or "none" (port 25, no encryption).
|
|
33
|
+
security = "starttls"
|
|
34
|
+
# With security "none", the script refuses to send a username or password. Set this to true
|
|
35
|
+
# (a boolean, not a string) only for a local test relay. File only: no env var or flag.
|
|
36
|
+
# allow_insecure_auth = false
|
|
37
|
+
# Leave out `port` to use the default for the security mode.
|
|
38
|
+
# port = 587
|
|
39
|
+
# Leave empty if the server needs no login.
|
|
40
|
+
username = ""
|
|
41
|
+
# The NAME of the key that holds the password (in the environment or the env file).
|
|
42
|
+
password_key = "EMAIL_SMTP_PASSWORD"
|
|
43
|
+
# Seconds to wait for the server.
|
|
44
|
+
timeout = 30
|
|
@@ -0,0 +1,432 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""Send one email with Microsoft Graph (sendMail, client credentials) or SMTP.
|
|
3
|
+
|
|
4
|
+
Settings come from three places. The first one that has a value wins:
|
|
5
|
+
1. a command-line flag
|
|
6
|
+
2. an environment variable (CADDIS_EMAIL_*)
|
|
7
|
+
3. the config file ~/.caddis/email.toml (see email.toml.example)
|
|
8
|
+
|
|
9
|
+
Secrets (Graph client secret, SMTP password) are never read from the config file. They come from
|
|
10
|
+
the process environment or from the env file named by `env_file`. The script never prints a
|
|
11
|
+
secret or a token. Errors show the provider, the HTTP or SMTP status code and the error name only.
|
|
12
|
+
|
|
13
|
+
Exit codes: 0 done, 1 provider error, 2 missing or invalid setting.
|
|
14
|
+
Standard library only.
|
|
15
|
+
"""
|
|
16
|
+
from __future__ import annotations
|
|
17
|
+
|
|
18
|
+
import argparse
|
|
19
|
+
import base64
|
|
20
|
+
import html
|
|
21
|
+
import json
|
|
22
|
+
import mimetypes
|
|
23
|
+
import os
|
|
24
|
+
import re
|
|
25
|
+
import smtplib
|
|
26
|
+
import ssl
|
|
27
|
+
import sys
|
|
28
|
+
import urllib.error
|
|
29
|
+
import urllib.parse
|
|
30
|
+
import urllib.request
|
|
31
|
+
from dataclasses import dataclass
|
|
32
|
+
from email.message import EmailMessage
|
|
33
|
+
from pathlib import Path
|
|
34
|
+
|
|
35
|
+
import tomllib
|
|
36
|
+
|
|
37
|
+
PROVIDERS = ("graph", "smtp")
|
|
38
|
+
SECURITY = ("starttls", "ssl", "none")
|
|
39
|
+
SMTP_PORTS = {"starttls": 587, "ssl": 465, "none": 25}
|
|
40
|
+
DEFAULT_GRAPH_KEYS = ("ALERT_GRAPH_TENANT_ID", "ALERT_GRAPH_CLIENT_ID", "ALERT_GRAPH_CLIENT_SECRET")
|
|
41
|
+
DEFAULT_SMTP_PASSWORD_KEY = "EMAIL_SMTP_PASSWORD"
|
|
42
|
+
STYLE = "font-family:Segoe UI,Arial,sans-serif;font-size:14px;line-height:1.5;color:#222"
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
class ConfigError(Exception):
|
|
46
|
+
"""A setting is invalid. The message never holds a secret."""
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
# ---------------------------------------------------------------- markdown
|
|
50
|
+
|
|
51
|
+
def extract_section(md: str) -> str:
|
|
52
|
+
md = re.sub(r"\A---\n.*?\n---\n", "", md, flags=re.DOTALL)
|
|
53
|
+
m = re.search(r"<!-- email-start -->(.*?)<!-- email-end -->", md, flags=re.DOTALL)
|
|
54
|
+
return m.group(1) if m else md
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def inline(text: str) -> str:
|
|
58
|
+
text = html.escape(text)
|
|
59
|
+
text = re.sub(r"\*\*(.+?)\*\*", r"<b>\1</b>", text)
|
|
60
|
+
return re.sub(r"`(.+?)`", r"<code>\1</code>", text)
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def md_to_html(md: str) -> str:
|
|
64
|
+
md = extract_section(md)
|
|
65
|
+
out, para, lines, i = [], [], md.splitlines(), 0
|
|
66
|
+
|
|
67
|
+
def flush():
|
|
68
|
+
if para:
|
|
69
|
+
out.append("<p>" + " ".join(inline(p) for p in para) + "</p>")
|
|
70
|
+
para.clear()
|
|
71
|
+
|
|
72
|
+
def cells(row):
|
|
73
|
+
return [c.strip() for c in row.strip("|").split("|")]
|
|
74
|
+
|
|
75
|
+
while i < len(lines):
|
|
76
|
+
s = lines[i].strip()
|
|
77
|
+
if not s:
|
|
78
|
+
flush()
|
|
79
|
+
elif s == "---":
|
|
80
|
+
flush()
|
|
81
|
+
out.append("<hr>")
|
|
82
|
+
elif s.startswith("#"):
|
|
83
|
+
flush()
|
|
84
|
+
n = min(len(s) - len(s.lstrip("#")), 4)
|
|
85
|
+
out.append(f"<h{n}>{inline(s.lstrip('#').strip())}</h{n}>")
|
|
86
|
+
elif s.startswith("|") and i + 1 < len(lines) and re.match(r"^\|[\s:|-]+\|$", lines[i + 1].strip()):
|
|
87
|
+
flush()
|
|
88
|
+
rows = [s]
|
|
89
|
+
i += 2
|
|
90
|
+
while i < len(lines) and lines[i].strip().startswith("|"):
|
|
91
|
+
rows.append(lines[i].strip())
|
|
92
|
+
i += 1
|
|
93
|
+
i -= 1
|
|
94
|
+
t = '<table style="border-collapse:collapse" border="1" cellpadding="6"><tr>'
|
|
95
|
+
t += "".join(f"<th>{inline(c)}</th>" for c in cells(rows[0])) + "</tr>"
|
|
96
|
+
for r in rows[1:]:
|
|
97
|
+
t += "<tr>" + "".join(f"<td>{inline(c)}</td>" for c in cells(r)) + "</tr>"
|
|
98
|
+
out.append(t + "</table>")
|
|
99
|
+
elif re.match(r"^[-*] ", s):
|
|
100
|
+
flush()
|
|
101
|
+
items = []
|
|
102
|
+
while i < len(lines) and re.match(r"^\s*[-*] ", lines[i]):
|
|
103
|
+
item = re.sub(r"^\s*[-*] ", "", lines[i])
|
|
104
|
+
i += 1
|
|
105
|
+
while (i < len(lines) and lines[i].startswith(" ") and lines[i].strip()
|
|
106
|
+
and not re.match(r"^\s*[-*] ", lines[i])):
|
|
107
|
+
item += " " + lines[i].strip()
|
|
108
|
+
i += 1
|
|
109
|
+
items.append(f"<li>{inline(item)}</li>")
|
|
110
|
+
i -= 1
|
|
111
|
+
out.append("<ul>" + "".join(items) + "</ul>")
|
|
112
|
+
else:
|
|
113
|
+
para.append(s)
|
|
114
|
+
i += 1
|
|
115
|
+
flush()
|
|
116
|
+
return f'<div style="{STYLE}">' + "\n".join(out) + "</div>"
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
# ---------------------------------------------------------------- config
|
|
120
|
+
|
|
121
|
+
@dataclass
|
|
122
|
+
class Config:
|
|
123
|
+
provider: str = "graph"
|
|
124
|
+
sender: str = ""
|
|
125
|
+
env_file: str = ""
|
|
126
|
+
# graph: names of the keys that hold the secrets (not the secrets)
|
|
127
|
+
tenant_key: str = DEFAULT_GRAPH_KEYS[0]
|
|
128
|
+
client_id_key: str = DEFAULT_GRAPH_KEYS[1]
|
|
129
|
+
client_secret_key: str = DEFAULT_GRAPH_KEYS[2]
|
|
130
|
+
# smtp
|
|
131
|
+
smtp_host: str = ""
|
|
132
|
+
smtp_port: int = 0
|
|
133
|
+
smtp_security: str = "starttls"
|
|
134
|
+
smtp_username: str = ""
|
|
135
|
+
smtp_password_key: str = DEFAULT_SMTP_PASSWORD_KEY
|
|
136
|
+
smtp_timeout: float = 30.0
|
|
137
|
+
smtp_allow_insecure_auth: bool = False
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
def config_path(flag: str | None) -> Path:
|
|
141
|
+
chosen = flag or os.environ.get("CADDIS_EMAIL_CONFIG")
|
|
142
|
+
return Path(chosen).expanduser() if chosen else Path.home() / ".caddis" / "email.toml"
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
def read_toml(path: Path) -> dict:
|
|
146
|
+
if not path.is_file():
|
|
147
|
+
return {}
|
|
148
|
+
try:
|
|
149
|
+
return tomllib.loads(path.read_text(encoding="utf-8"))
|
|
150
|
+
except (tomllib.TOMLDecodeError, OSError, UnicodeDecodeError) as e:
|
|
151
|
+
raise ConfigError(f"cannot read config file ({type(e).__name__})") from None
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
def read_env(path: Path) -> dict:
|
|
155
|
+
out = {}
|
|
156
|
+
for line in path.read_text(encoding="utf-8").splitlines():
|
|
157
|
+
line = line.strip()
|
|
158
|
+
if not line or line.startswith("#") or "=" not in line:
|
|
159
|
+
continue
|
|
160
|
+
k, v = line.split("=", 1)
|
|
161
|
+
out[k.strip()] = v.strip().strip('"').strip("'")
|
|
162
|
+
return out
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
def _pick(flag, env_names, file_value, default=""):
|
|
166
|
+
"""flag, then the first set env var, then the config file value, then the default."""
|
|
167
|
+
if flag not in (None, ""):
|
|
168
|
+
return flag
|
|
169
|
+
for name in env_names:
|
|
170
|
+
v = os.environ.get(name)
|
|
171
|
+
if v:
|
|
172
|
+
return v
|
|
173
|
+
if file_value not in (None, ""):
|
|
174
|
+
return file_value
|
|
175
|
+
return default
|
|
176
|
+
|
|
177
|
+
|
|
178
|
+
def _number(value, name, cast):
|
|
179
|
+
try:
|
|
180
|
+
return cast(value)
|
|
181
|
+
except (TypeError, ValueError):
|
|
182
|
+
raise ConfigError(f"{name} must be a number") from None
|
|
183
|
+
|
|
184
|
+
|
|
185
|
+
def load_config(a: argparse.Namespace) -> Config:
|
|
186
|
+
f = read_toml(config_path(a.config))
|
|
187
|
+
g, s = f.get("graph", {}) or {}, f.get("smtp", {}) or {}
|
|
188
|
+
c = Config()
|
|
189
|
+
c.provider = str(_pick(a.provider, ["CADDIS_EMAIL_PROVIDER"], f.get("provider"), "graph")).lower()
|
|
190
|
+
if c.provider not in PROVIDERS:
|
|
191
|
+
raise ConfigError(f"provider must be one of {', '.join(PROVIDERS)}")
|
|
192
|
+
c.sender = _pick(a.sender, ["CADDIS_EMAIL_SENDER", "GRAPH_EMAIL_SENDER"], f.get("sender"))
|
|
193
|
+
c.env_file = _pick(a.env_file, ["CADDIS_EMAIL_ENV_FILE", "GRAPH_EMAIL_ENV_FILE"], f.get("env_file"))
|
|
194
|
+
c.tenant_key = g.get("tenant_id_key") or c.tenant_key
|
|
195
|
+
c.client_id_key = g.get("client_id_key") or c.client_id_key
|
|
196
|
+
c.client_secret_key = g.get("client_secret_key") or c.client_secret_key
|
|
197
|
+
c.smtp_host = _pick(a.smtp_host, ["CADDIS_EMAIL_SMTP_HOST"], s.get("host"))
|
|
198
|
+
c.smtp_security = str(_pick(a.smtp_security, ["CADDIS_EMAIL_SMTP_SECURITY"], s.get("security"),
|
|
199
|
+
"starttls")).lower()
|
|
200
|
+
if c.smtp_security not in SECURITY:
|
|
201
|
+
raise ConfigError(f"smtp security must be one of {', '.join(SECURITY)}")
|
|
202
|
+
port = _pick(a.smtp_port, ["CADDIS_EMAIL_SMTP_PORT"], s.get("port"), SMTP_PORTS[c.smtp_security])
|
|
203
|
+
c.smtp_port = _number(port, "smtp port", int)
|
|
204
|
+
c.smtp_username = _pick(a.smtp_username, ["CADDIS_EMAIL_SMTP_USERNAME"], s.get("username"))
|
|
205
|
+
c.smtp_password_key = s.get("password_key") or c.smtp_password_key
|
|
206
|
+
c.smtp_timeout = _number(_pick(a.smtp_timeout, ["CADDIS_EMAIL_SMTP_TIMEOUT"], s.get("timeout"), 30),
|
|
207
|
+
"smtp timeout", float)
|
|
208
|
+
# Only a real TOML boolean true opts in; a string such as "true" does not.
|
|
209
|
+
c.smtp_allow_insecure_auth = s.get("allow_insecure_auth") is True
|
|
210
|
+
return c
|
|
211
|
+
|
|
212
|
+
|
|
213
|
+
def check_smtp_security(cfg: Config) -> None:
|
|
214
|
+
"""Refuse a login (username or password) over security "none" unless the user opted in.
|
|
215
|
+
|
|
216
|
+
The message names settings only. It never holds a username, a password or a host.
|
|
217
|
+
"""
|
|
218
|
+
if cfg.provider != "smtp" or cfg.smtp_security != "none" or cfg.smtp_allow_insecure_auth:
|
|
219
|
+
return
|
|
220
|
+
if cfg.smtp_username or get_secret(cfg, cfg.smtp_password_key):
|
|
221
|
+
raise ConfigError('smtp security is off and a login is set, so the login would go in clear text; '
|
|
222
|
+
'set security to "starttls" or "ssl"')
|
|
223
|
+
|
|
224
|
+
|
|
225
|
+
def _env_file_values(cfg: Config) -> dict:
|
|
226
|
+
if not cfg.env_file:
|
|
227
|
+
return {}
|
|
228
|
+
try:
|
|
229
|
+
return read_env(Path(cfg.env_file).expanduser())
|
|
230
|
+
except (OSError, UnicodeDecodeError):
|
|
231
|
+
return {}
|
|
232
|
+
|
|
233
|
+
|
|
234
|
+
def get_secret(cfg: Config, key: str) -> str:
|
|
235
|
+
"""The process environment first, then the env file. Never the config file."""
|
|
236
|
+
return os.environ.get(key) or _env_file_values(cfg).get(key, "")
|
|
237
|
+
|
|
238
|
+
|
|
239
|
+
def missing_settings(cfg: Config) -> list[str]:
|
|
240
|
+
"""Names of settings that are not set. Never a value."""
|
|
241
|
+
miss = []
|
|
242
|
+
if not cfg.sender:
|
|
243
|
+
miss.append("sender")
|
|
244
|
+
if cfg.provider == "graph":
|
|
245
|
+
keys = (cfg.tenant_key, cfg.client_id_key, cfg.client_secret_key)
|
|
246
|
+
else:
|
|
247
|
+
if not cfg.smtp_host:
|
|
248
|
+
miss.append("smtp.host")
|
|
249
|
+
keys = (cfg.smtp_password_key,) if cfg.smtp_username else ()
|
|
250
|
+
absent = [k for k in keys if not get_secret(cfg, k)]
|
|
251
|
+
if absent:
|
|
252
|
+
miss.extend(["env_file"] if not cfg.env_file else absent)
|
|
253
|
+
return miss
|
|
254
|
+
|
|
255
|
+
|
|
256
|
+
# ---------------------------------------------------------------- attachments and messages
|
|
257
|
+
|
|
258
|
+
def _ctype(name: str) -> str:
|
|
259
|
+
return mimetypes.guess_type(name)[0] or "application/octet-stream"
|
|
260
|
+
|
|
261
|
+
|
|
262
|
+
def build_graph_payload(subject, html_body, to, attach_paths) -> dict:
|
|
263
|
+
attachments = []
|
|
264
|
+
for p in attach_paths:
|
|
265
|
+
pp = Path(p)
|
|
266
|
+
attachments.append({
|
|
267
|
+
"@odata.type": "#microsoft.graph.fileAttachment", "name": pp.name,
|
|
268
|
+
"contentType": _ctype(pp.name),
|
|
269
|
+
"contentBytes": base64.b64encode(pp.read_bytes()).decode(),
|
|
270
|
+
})
|
|
271
|
+
return {"message": {
|
|
272
|
+
"subject": subject, "body": {"contentType": "HTML", "content": html_body},
|
|
273
|
+
"toRecipients": [{"emailAddress": {"address": t}} for t in to],
|
|
274
|
+
"attachments": attachments}, "saveToSentItems": True}
|
|
275
|
+
|
|
276
|
+
|
|
277
|
+
def build_smtp_message(sender, to, subject, plain, html_body, attach_paths) -> EmailMessage:
|
|
278
|
+
msg = EmailMessage()
|
|
279
|
+
msg["From"], msg["To"], msg["Subject"] = sender, ", ".join(to), subject
|
|
280
|
+
msg.set_content(plain)
|
|
281
|
+
msg.add_alternative(html_body, subtype="html")
|
|
282
|
+
for p in attach_paths:
|
|
283
|
+
pp = Path(p)
|
|
284
|
+
main, _, sub = _ctype(pp.name).partition("/")
|
|
285
|
+
msg.add_attachment(pp.read_bytes(), maintype=main, subtype=sub or "octet-stream", filename=pp.name)
|
|
286
|
+
return msg
|
|
287
|
+
|
|
288
|
+
|
|
289
|
+
# ---------------------------------------------------------------- senders
|
|
290
|
+
|
|
291
|
+
def post(url: str, data: bytes, headers: dict, timeout: float = 30):
|
|
292
|
+
req = urllib.request.Request(url, data=data, headers=headers, method="POST")
|
|
293
|
+
try:
|
|
294
|
+
with urllib.request.urlopen(req, timeout=timeout) as r:
|
|
295
|
+
return r.status, r.read()
|
|
296
|
+
except urllib.error.HTTPError as e:
|
|
297
|
+
return e.code, e.read()
|
|
298
|
+
|
|
299
|
+
|
|
300
|
+
def _err_name(raw: bytes) -> str:
|
|
301
|
+
try:
|
|
302
|
+
err = json.loads(raw or b"{}").get("error", "unknown")
|
|
303
|
+
except (ValueError, AttributeError):
|
|
304
|
+
return "unknown"
|
|
305
|
+
if isinstance(err, dict):
|
|
306
|
+
err = err.get("code", "unknown")
|
|
307
|
+
return str(err) if re.fullmatch(r"[A-Za-z0-9_.-]{1,64}", str(err)) else "unknown"
|
|
308
|
+
|
|
309
|
+
|
|
310
|
+
def send_graph(cfg: Config, a, html_body: str) -> int:
|
|
311
|
+
tenant = get_secret(cfg, cfg.tenant_key)
|
|
312
|
+
tok_url = f"https://login.microsoftonline.com/{urllib.parse.quote(tenant)}/oauth2/v2.0/token"
|
|
313
|
+
form = urllib.parse.urlencode({
|
|
314
|
+
"client_id": get_secret(cfg, cfg.client_id_key), "client_secret": get_secret(cfg, cfg.client_secret_key),
|
|
315
|
+
"scope": "https://graph.microsoft.com/.default", "grant_type": "client_credentials",
|
|
316
|
+
}).encode()
|
|
317
|
+
try:
|
|
318
|
+
status, raw = post(tok_url, form, {"Content-Type": "application/x-www-form-urlencoded"})
|
|
319
|
+
if status != 200:
|
|
320
|
+
print(f"error: provider graph, token request failed, HTTP {status}, {_err_name(raw)}", file=sys.stderr)
|
|
321
|
+
return 1
|
|
322
|
+
token = json.loads(raw)["access_token"]
|
|
323
|
+
payload = build_graph_payload(a.subject, html_body, a.to, a.attach)
|
|
324
|
+
url = f"https://graph.microsoft.com/v1.0/users/{urllib.parse.quote(cfg.sender)}/sendMail"
|
|
325
|
+
status, raw = post(url, json.dumps(payload).encode(),
|
|
326
|
+
{"Authorization": f"Bearer {token}", "Content-Type": "application/json"})
|
|
327
|
+
except (OSError, ValueError, KeyError) as e:
|
|
328
|
+
print(f"error: provider graph, request failed, {type(e).__name__}", file=sys.stderr)
|
|
329
|
+
return 1
|
|
330
|
+
if status == 202:
|
|
331
|
+
print(f"sent: provider graph, HTTP 202 (accepted for delivery) to {', '.join(a.to)} subject '{a.subject}'")
|
|
332
|
+
return 0
|
|
333
|
+
print(f"error: provider graph, sendMail failed, HTTP {status}, {_err_name(raw)}", file=sys.stderr)
|
|
334
|
+
return 1
|
|
335
|
+
|
|
336
|
+
|
|
337
|
+
def send_smtp(cfg: Config, a, html_body: str, plain: str) -> int:
|
|
338
|
+
try:
|
|
339
|
+
msg = build_smtp_message(cfg.sender, a.to, a.subject, plain, html_body, a.attach)
|
|
340
|
+
password = get_secret(cfg, cfg.smtp_password_key) if cfg.smtp_username else ""
|
|
341
|
+
# smtplib's own default context does not check the certificate; this one does.
|
|
342
|
+
ctx = ssl.create_default_context()
|
|
343
|
+
if cfg.smtp_security == "ssl":
|
|
344
|
+
conn = smtplib.SMTP_SSL(cfg.smtp_host, cfg.smtp_port, timeout=cfg.smtp_timeout, context=ctx)
|
|
345
|
+
else:
|
|
346
|
+
conn = smtplib.SMTP(cfg.smtp_host, cfg.smtp_port, timeout=cfg.smtp_timeout)
|
|
347
|
+
with conn as s:
|
|
348
|
+
if cfg.smtp_security == "starttls":
|
|
349
|
+
s.ehlo()
|
|
350
|
+
s.starttls(context=ctx)
|
|
351
|
+
s.ehlo()
|
|
352
|
+
if cfg.smtp_username:
|
|
353
|
+
s.login(cfg.smtp_username, password)
|
|
354
|
+
s.send_message(msg)
|
|
355
|
+
except smtplib.SMTPResponseException as e:
|
|
356
|
+
print(f"error: provider smtp, SMTP {e.smtp_code}, {type(e).__name__}", file=sys.stderr)
|
|
357
|
+
return 1
|
|
358
|
+
except (smtplib.SMTPException, OSError) as e:
|
|
359
|
+
print(f"error: provider smtp, {type(e).__name__}", file=sys.stderr)
|
|
360
|
+
return 1
|
|
361
|
+
print(f"sent: provider smtp, accepted by server for {', '.join(a.to)} subject '{a.subject}'")
|
|
362
|
+
return 0
|
|
363
|
+
|
|
364
|
+
|
|
365
|
+
# ---------------------------------------------------------------- cli
|
|
366
|
+
|
|
367
|
+
def parse_args(argv=None) -> argparse.Namespace:
|
|
368
|
+
ap = argparse.ArgumentParser(description="Send one email with Microsoft Graph or SMTP.")
|
|
369
|
+
ap.add_argument("--to", action="append")
|
|
370
|
+
ap.add_argument("--subject")
|
|
371
|
+
ap.add_argument("--body-file")
|
|
372
|
+
ap.add_argument("--attach", action="append", default=[])
|
|
373
|
+
ap.add_argument("--dry-run", action="store_true", help="write <body>.preview.html, send nothing")
|
|
374
|
+
ap.add_argument("--check", action="store_true", help="validate settings, send nothing, print no secret")
|
|
375
|
+
ap.add_argument("--config", help="config file (default ~/.caddis/email.toml)")
|
|
376
|
+
ap.add_argument("--provider")
|
|
377
|
+
ap.add_argument("--sender")
|
|
378
|
+
ap.add_argument("--env-file")
|
|
379
|
+
ap.add_argument("--smtp-host")
|
|
380
|
+
ap.add_argument("--smtp-port")
|
|
381
|
+
ap.add_argument("--smtp-security")
|
|
382
|
+
ap.add_argument("--smtp-username")
|
|
383
|
+
ap.add_argument("--smtp-timeout")
|
|
384
|
+
a = ap.parse_args(argv)
|
|
385
|
+
if not a.check and not (a.to and a.subject and a.body_file):
|
|
386
|
+
ap.error("--to, --subject and --body-file are required (unless --check)")
|
|
387
|
+
return a
|
|
388
|
+
|
|
389
|
+
|
|
390
|
+
def check(cfg: Config) -> int:
|
|
391
|
+
miss = missing_settings(cfg)
|
|
392
|
+
print(f"provider: {cfg.provider}")
|
|
393
|
+
print(f"sender: {'set' if cfg.sender else 'MISSING'}")
|
|
394
|
+
if cfg.provider == "smtp":
|
|
395
|
+
print(f"smtp: host {'set' if cfg.smtp_host else 'MISSING'}, port {cfg.smtp_port}, "
|
|
396
|
+
f"security {cfg.smtp_security}, login {'yes' if cfg.smtp_username else 'no'}")
|
|
397
|
+
if miss:
|
|
398
|
+
print(f"missing: {', '.join(miss)}")
|
|
399
|
+
return 2
|
|
400
|
+
print("check ok: all settings and credentials are present (nothing sent)")
|
|
401
|
+
return 0
|
|
402
|
+
|
|
403
|
+
|
|
404
|
+
def main(argv=None) -> int:
|
|
405
|
+
a = parse_args(argv)
|
|
406
|
+
if a.dry_run and not a.check:
|
|
407
|
+
body = md_to_html(Path(a.body_file).read_text(encoding="utf-8"))
|
|
408
|
+
out = Path(a.body_file).with_suffix(".preview.html")
|
|
409
|
+
out.write_text(f"<html><body>{body}</body></html>", encoding="utf-8")
|
|
410
|
+
print(f"dry run: preview written to {out}; nothing sent")
|
|
411
|
+
return 0
|
|
412
|
+
try:
|
|
413
|
+
cfg = load_config(a)
|
|
414
|
+
check_smtp_security(cfg)
|
|
415
|
+
except ConfigError as e:
|
|
416
|
+
print(f"error: {e}", file=sys.stderr)
|
|
417
|
+
return 2
|
|
418
|
+
if a.check:
|
|
419
|
+
return check(cfg)
|
|
420
|
+
miss = missing_settings(cfg)
|
|
421
|
+
if miss:
|
|
422
|
+
print(f"error: missing settings for provider {cfg.provider}: {', '.join(miss)}", file=sys.stderr)
|
|
423
|
+
return 2
|
|
424
|
+
md = Path(a.body_file).read_text(encoding="utf-8")
|
|
425
|
+
html_body = md_to_html(md)
|
|
426
|
+
if cfg.provider == "smtp":
|
|
427
|
+
return send_smtp(cfg, a, html_body, extract_section(md).strip())
|
|
428
|
+
return send_graph(cfg, a, html_body)
|
|
429
|
+
|
|
430
|
+
|
|
431
|
+
if __name__ == "__main__":
|
|
432
|
+
sys.exit(main())
|
|
@@ -4,9 +4,7 @@ version: 1.0.0
|
|
|
4
4
|
description: >-
|
|
5
5
|
Zero-dependency animated particle art as a React/Next.js component (spring physics, CSS-variable
|
|
6
6
|
theming, mouse interaction). Use for animated hero art or a living logo, or on "particle animation",
|
|
7
|
-
"
|
|
8
|
-
"constellation", "neural net art", "halftone animation", "ASCII art animation", or "art that reacts
|
|
9
|
-
to mouse".
|
|
7
|
+
"animated letter/logo/initials" or "morphing particles".
|
|
10
8
|
---
|
|
11
9
|
|
|
12
10
|
# Particle Art Generator
|