prompts.chatprompts.chatprompts.chat
TeamsBotsSkillsPromptsPromptmasters
BookFor KidsDevelopers
Login
CC0 2026 prompts.chat
DeepWikiHow to...DocsAPIPrivacyTermsSupportAboutGitHub
All Tags

Compliance Prompts

10 prompts4 bots
Employee Timesheet and Overtime Checker
Skill

Checks a small team's timesheets pre-payroll: splits each week into regular, overtime and double-time hours under your daily and weekly rules, estimates pay, and flags missing punches, overlaps, duplicates, short breaks, short rest, over-max weeks and too many days in a row. Offline stdlib Python.

---
name: employee-timesheet-and-overtime-checker
description: Checks a small team's timesheets pre-payroll: splits each week into regular, overtime and double-time hours under your daily and weekly rules, estimates pay, and flags missing punches, overlaps, duplicates, short breaks, short rest, over-max weeks and too many days in a row. Offline stdlib Python.
---

# Employee Timesheet and Overtime Checker

You help small business owners, shop and restaurant managers, office managers and payroll admins check a week or two of timesheets before they run payroll. Timesheet mistakes are expensive in both directions: a missing clock-out or a duplicate row pays the wrong amount, overtime that is not paid becomes a wage claim, and short breaks or short rest between a closing and an opening shift can break working-time rules. You turn the raw export into a clear hours-and-pay table and a short list of things to fix or confirm.

You work only on the files the user gives you, on their machine. You never decide what the law is where they are: you apply the rules they confirm, say clearly that the bundled defaults are only an example, and suggest checking local labour rules, the employment contracts or a payroll provider for anything unclear. You do not judge employees; findings are data questions to check with the person and their manager.

## Files in this skill

- `scripts/timesheet_check.py` - reads a timesheet CSV (and optional employees and rules files), splits hours per employee and week into regular, overtime and double time with daily and weekly thresholds, estimates gross pay, and reports findings TS01-TS11 by severity; `--json` for tooling, `--self-test` runs 20 checks (Python 3.8+ standard library only)
- `references/overtime-and-working-time-rules.md` - how the hours are split, what each rule key means, examples of rule sets people commonly configure, and what the script does not handle
- `references/fixing-timesheet-problems.md` - what each finding usually means, how to confirm and correct it, and how to prevent it next time
- `templates/payroll-check-report.md` - the summary you hand back before payroll
- `examples/timesheet.csv`, `examples/employees.csv`, `examples/rules.json` - a fictional shop week with five people and planted problems (missing clock-out, duplicate row, overlap, short break, closing-then-opening, a 49-hour week)

## Workflow

### 1. Confirm the rules first
Before running anything, ask which rules apply and fill `rules.json`:
- week start day and pay period;
- overtime thresholds (daily and/or weekly hours), multipliers and any double-time threshold;
- break rules (break required after how many hours, minimum minutes, paid or unpaid);
- minimum rest between shifts, maximum weekly hours and maximum days in a row;
- which employees are not eligible for overtime (salaried or exempt) and their hourly rates.
If the user does not know, run with the defaults but label every result "example rules" and list the questions in the report.

### 2. Prepare the files
- `timesheet.csv`: `employee,date,start,end,break_minutes[,note]`, date `YYYY-MM-DD`, times `HH:MM` 24 h. An end time earlier than the start means an overnight shift counted on the start date. Most clock systems can export this; rename columns if needed.
- `employees.csv` (optional): `employee,hourly_rate[,overtime_eligible]`.
- Names must match exactly between files.

### 3. Run the check
```
python3 scripts/timesheet_check.py examples/timesheet.csv --rules examples/rules.json --employees examples/employees.csv
python3 scripts/timesheet_check.py timesheet.csv --rules rules.json --employees employees.csv --json > check.json
python3 scripts/timesheet_check.py --self-test
```
Exit 0 = no high findings, 1 = high findings to fix before payroll, 2 = bad input. Without a shell, follow `references/overtime-and-working-time-rules.md` by hand for each employee and week.

### 4. Triage the findings
- High (fix before payroll): TS01 missing or unreadable time (the row was skipped, so pay is too low), TS02 overlapping shifts (double counting or a wrong date), TS08 over the weekly maximum.
- Medium (confirm with the manager): TS04 duplicate row (counted once), TS05 very long shift, TS06 missing or short break, TS07 short rest between shifts, TS09 too many days in a row.
- Low (information): TS10 no pay rate, TS11 overnight shift.
Use `references/fixing-timesheet-problems.md` for the likely cause and the fix. Never "correct" a time yourself: list the question for the employee or manager, then re-run after they confirm.

### 5. Report
Fill `templates/payroll-check-report.md`: rules used, hours and pay table, overtime total and cost, findings with the exact question to ask, and anything the script does not cover (shift premiums, holiday pay, tips, on-call, travel time, local rounding rules).

## Rules
- Overtime is never counted twice: hours already paid as daily overtime or double time do not count toward the weekly regular threshold.
- Pay estimates are gross base pay only, before taxes, premiums, allowances and deductions.
- Keep personal data private: do not upload timesheets, and share only the report with people who need it.

FILE:references/overtime-and-working-time-rules.md
# How timesheet_check.py splits hours and applies rules

## Worked time
worked hours = (end - start) - break. An end at or before the start is an overnight shift (end + 24 h), counted on the start date. Rows with a missing or unreadable time are skipped and reported as TS01, so the employee's total is too low until fixed.

## Splitting a week (no double counting)
For each employee and week (week_start in rules), day by day in date order:
1. Double time = hours above daily_dt_after (if set).
2. Daily overtime = remaining hours above daily_ot_after (if set).
3. The rest is regular, until the week's regular hours reach weekly_ot_after; regular hours beyond that move to overtime.
Employees with overtime_eligible = no get all hours as regular.
Pay estimate = rate x (regular + overtime x ot_multiplier + double time x dt_multiplier).

Example (daily 8 / weekly 40): Mon 8, Tue 8, Wed 10, Thu 8, Fri 9, Sat 5 = 48 h. Daily overtime 2 + 1 = 3 h; regular would be 45, so 5 more hours move to overtime: 40 regular, 8 overtime.

## Rule keys
| key | meaning | default |
|---|---|---|
| week_start | first day of the work week | monday |
| daily_ot_after | overtime after this many hours in a day (null = no daily overtime) | null |
| daily_dt_after | double time after this many hours in a day (null = none) | null |
| weekly_ot_after | overtime after this many regular hours in a week (null = none) | 40 |
| ot_multiplier / dt_multiplier | pay multipliers | 1.5 / 2.0 |
| break_required_after_hours / min_break_minutes | a break of at least N minutes for shifts longer than H hours | 6 / 30 |
| min_rest_hours | minimum rest between two shifts on different days | 11 |
| max_weekly_hours | flag weeks above this total | 48 |
| max_shift_hours | flag a start-to-end span above this (often a typo) | 14 |
| max_days_in_a_row | flag runs of consecutive working days above this | 6 |

## Rule sets people commonly configure (check your own law and contracts)
- Weekly-only overtime: weekly_ot_after 40, daily keys null (a common US federal-style setup).
- Daily and weekly overtime with double time: daily_ot_after 8, daily_dt_after 12, weekly_ot_after 40 (used in some US states).
- Working-time limits without statutory overtime pay: weekly_ot_after null or per contract, min_rest_hours 11, max_weekly_hours 48 (European working-time style; the 48 h is often an average over several months, which this weekly check does not average).
These are examples to start a conversation, not legal advice.

## Not handled
Averaging periods, seventh-day rules, shift or night premiums, holiday and sick pay, on-call and travel time, split-shift premiums, tips, minimum wage checks, time rounding policies, and multi-rate employees. Mention any that apply and handle them separately.

FILE:references/fixing-timesheet-problems.md
# Findings: likely causes and fixes

| code | finding | likely cause | how to confirm and fix | prevent next time |
|---|---|---|---|---|
| TS01 | missing or unreadable time | forgot to clock out, app crash, manual edit | ask the employee and manager for the real time; add it and re-run | clock-out reminders; manager reviews open punches daily |
| TS02 | overlapping shifts | wrong date on an overnight shift, double entry, two locations | compare with the rota and the till/door logs; fix the date or delete the duplicate | one clock-in at a time per person |
| TS03 | break longer than the shift | break entered in hours or the wrong column | confirm the real break and correct it | validate break fields in the export |
| TS04 | duplicate row | double import or edit | the script counts it once; delete it at the source | import each period once |
| TS05 | very long shift | typo in the end time or a missing clock-out the next day | confirm with the employee; if real, check rest and maximum rules | alert on shifts over the limit |
| TS06 | break missing or short | busy shift, break not recorded | ask whether a break was taken; some places owe a penalty for missed breaks | schedule breaks on the rota |
| TS07 | short rest between shifts | closing then opening ("clopening") | confirm; adjust the rota; check whether local rules require a premium | rota checks before publishing |
| TS08 | over the weekly maximum | extra cover, missing staff | confirm the hours are real and any opt-out or averaging agreement | plan cover earlier |
| TS09 | too many days in a row | cover for absence | confirm a day off is scheduled | rota checks |
| TS10 | no pay rate | new hire, name spelled differently | add the employee or fix the name | one employee list as the source of names |
| TS11 | overnight shift | night work | confirm the start date is right | none needed |

When you report a finding, give the exact question to ask, for example: "Priya, on Wed 18 Nov you clocked in at 09:00 but there is no clock-out. What time did you finish?"

FILE:templates/payroll-check-report.md
# Payroll check: {{business}} - pay period {{period}}

Prepared {{date}}. Rules used: {{rules_summary}} ({{confirmed_or_example}} rules).

## Summary
- Employees: {{employee_count}} | shifts: {{shift_count}}
- Overtime and double-time hours: {{ot_hours}} (estimated cost {{ot_cost}})
- Estimated gross base pay: {{gross_pay}}
- Fix before payroll: {{high_count}} high findings | confirm: {{medium_count}} medium

## Hours and pay
(paste the table from timesheet_check.py)

## Fix before payroll
| employee | date | finding | question to ask | owner |
|---|---|---|---|---|
| {{employee}} | {{date}} | {{code and issue}} | {{exact question}} | {{manager}} |

## Confirm with managers
- {{finding and question}}

## Not covered by this check
- {{premiums, holiday pay, tips, averaging periods, local rounding rules}}

## Rota suggestions
- {{for example: avoid closing-then-opening shifts; schedule breaks on 8 h shifts}}

FILE:examples/timesheet.csv
employee,date,start,end,break_minutes,note
Maya Torres,2026-11-16,07:00,15:30,30,
Maya Torres,2026-11-17,07:00,15:30,30,
Maya Torres,2026-11-18,07:00,17:30,30,stock delivery
Maya Torres,2026-11-19,07:00,15:30,30,
Maya Torres,2026-11-20,07:00,16:30,30,
Maya Torres,2026-11-21,08:00,13:00,0,Saturday cover
Jonah Reed,2026-11-16,12:00,20:30,30,
Jonah Reed,2026-11-17,12:00,23:00,30,closing
Jonah Reed,2026-11-18,07:00,15:00,30,opening after closing
Jonah Reed,2026-11-19,12:00,20:30,15,
Jonah Reed,2026-11-20,12:00,20:30,30,
Jonah Reed,2026-11-20,12:00,20:30,30,
Priya Nair,2026-11-16,09:00,17:00,45,
Priya Nair,2026-11-17,09:00,17:00,45,
Priya Nair,2026-11-18,09:00,,45,forgot to clock out
Priya Nair,2026-11-19,09:00,19:00,45,
Priya Nair,2026-11-20,09:00,17:00,45,
Sam Okafor,2026-11-17,22:00,06:30,30,night stock count
Sam Okafor,2026-11-18,06:00,10:00,0,
Sam Okafor,2026-11-19,18:00,23:00,0,
Lena Fischer,2026-11-16,08:00,16:00,30,
Lena Fischer,2026-11-17,08:00,18:00,60,
Lena Fischer,2026-11-18,08:00,18:00,60,
Lena Fischer,2026-11-19,08:00,18:00,60,
Lena Fischer,2026-11-20,08:00,18:00,60,
Lena Fischer,2026-11-21,08:00,14:00,30,

FILE:examples/employees.csv
employee,hourly_rate,overtime_eligible
Maya Torres,19.50,yes
Jonah Reed,17.00,yes
Priya Nair,24.00,yes
Sam Okafor,18.25,yes
Lena Fischer,32.00,no

FILE:examples/rules.json
{
  "name": "Example shop rules (illustrative only, set yours from local law and contracts)",
  "week_start": "monday",
  "daily_ot_after": 8,
  "daily_dt_after": 12,
  "weekly_ot_after": 40,
  "ot_multiplier": 1.5,
  "dt_multiplier": 2.0,
  "break_required_after_hours": 6,
  "min_break_minutes": 30,
  "min_rest_hours": 11,
  "max_weekly_hours": 48,
  "max_shift_hours": 14,
  "max_days_in_a_row": 6
}

FILE:scripts/timesheet_check.py
#!/usr/bin/env python3
"""timesheet_check.py - check a team's timesheets and work out regular, overtime and double-time hours.

Reads shift rows, applies your overtime and working-time rules (daily and weekly
thresholds, multipliers, breaks, rest between shifts, weekly maximum, days in a
row), estimates pay per employee and week, and flags data errors and rule
breaches before payroll. Standard library only.

Usage:
  python3 timesheet_check.py TIMESHEET.csv [--rules RULES.json] [--employees EMPLOYEES.csv] [--json]
  python3 timesheet_check.py --self-test

TIMESHEET.csv columns: employee,date,start,end,break_minutes[,note]
  date YYYY-MM-DD, start/end HH:MM (24 h). An end earlier than the start is an overnight shift
  (counted on the start date).
EMPLOYEES.csv columns: employee,hourly_rate[,overtime_eligible]  (overtime_eligible: yes/no, default yes)
RULES.json keys (all optional, defaults in DEFAULT_RULES): week_start (monday..sunday),
  daily_ot_after, daily_dt_after, weekly_ot_after (hours or null), ot_multiplier, dt_multiplier,
  break_required_after_hours, min_break_minutes, min_rest_hours, max_weekly_hours,
  max_shift_hours, max_days_in_a_row.
Exit codes: 0 no high findings, 1 high findings, 2 bad input.
The default rules are an example, not the law where you are: set them from your local labour rules and contracts.
"""
import csv, datetime as dt, json, sys
from collections import defaultdict

DEFAULT_RULES = {
    "week_start": "monday",
    "daily_ot_after": None,          # e.g. 8 where daily overtime applies
    "daily_dt_after": None,          # e.g. 12 where daily double time applies
    "weekly_ot_after": 40,
    "ot_multiplier": 1.5,
    "dt_multiplier": 2.0,
    "break_required_after_hours": 6,
    "min_break_minutes": 30,
    "min_rest_hours": 11,
    "max_weekly_hours": 48,
    "max_shift_hours": 14,
    "max_days_in_a_row": 6,
}
DAYS = ["monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday"]
SEV = {"TS01": "high", "TS02": "high", "TS03": "high", "TS04": "medium", "TS05": "medium", "TS06": "medium",
       "TS07": "medium", "TS08": "high", "TS09": "medium", "TS10": "low", "TS11": "low"}
NAMES = {"TS01": "missing or unreadable time", "TS02": "overlapping shifts", "TS03": "break longer than the shift",
         "TS04": "duplicate row", "TS05": "very long shift (typo?)", "TS06": "required break missing or short",
         "TS07": "short rest between shifts", "TS08": "over the weekly maximum", "TS09": "too many days in a row",
         "TS10": "no pay rate", "TS11": "overnight shift (check the date)"}


class InputError(Exception):
    pass


def parse_time(s):
    try:
        h, m = s.strip().split(":")
        h, m = int(h), int(m)
        if not (0 <= h <= 24 and 0 <= m < 60) or (h == 24 and m):
            raise ValueError
        return h * 60 + m
    except (ValueError, AttributeError):
        return None


def load_rules(path):
    rules = dict(DEFAULT_RULES)
    if path:
        with open(path, encoding="utf-8") as f:
            user = json.load(f)
        unknown = set(user) - set(DEFAULT_RULES) - {"name", "notes"}
        if unknown:
            raise InputError("unknown rule keys: " + ", ".join(sorted(unknown)))
        rules.update({k: v for k, v in user.items() if k in DEFAULT_RULES})
    if str(rules["week_start"]).lower() not in DAYS:
        raise InputError("week_start must be a weekday name")
    for k in ("ot_multiplier", "dt_multiplier"):
        if not isinstance(rules[k], (int, float)) or rules[k] < 1:
            raise InputError(k + " must be a number >= 1")
    return rules


def load_employees(path):
    emp = {}
    if not path:
        return emp
    with open(path, newline="", encoding="utf-8") as f:
        for i, row in enumerate(csv.DictReader(f), start=2):
            row = {k.strip(): (v or "").strip() for k, v in row.items()}
            try:
                rate = float(row.get("hourly_rate", ""))
            except ValueError:
                raise InputError("employees line %d: hourly_rate must be a number" % i)
            emp[row["employee"]] = {"rate": rate, "ot": row.get("overtime_eligible", "yes").lower() not in ("no", "n", "false", "0")}
    return emp


def load_shifts(path):
    shifts, findings = [], []
    with open(path, newline="", encoding="utf-8") as f:
        r = csv.DictReader(f)
        need = {"employee", "date", "start", "end", "break_minutes"}
        if not r.fieldnames or not need.issubset({h.strip() for h in r.fieldnames}):
            raise InputError("timesheet needs columns employee,date,start,end,break_minutes")
        seen = set()
        for i, row in enumerate(r, start=2):
            row = {k.strip(): (v or "").strip() for k, v in row.items() if k}
            if not any(row.values()):
                continue
            e = row["employee"]
            key = (e, row["date"], row["start"], row["end"])
            if key in seen:
                findings.append(("TS04", e, row["date"], "line %d repeats an earlier row; counted once" % i))
                continue
            seen.add(key)
            try:
                day = dt.date.fromisoformat(row["date"])
            except ValueError:
                findings.append(("TS01", e, row["date"], "line %d: date is not YYYY-MM-DD; row skipped" % i)); continue
            s, en = parse_time(row["start"]), parse_time(row["end"])
            if s is None or en is None:
                findings.append(("TS01", e, row["date"], "line %d: start or end missing/unreadable (%r-%r); row skipped" % (i, row["start"], row["end"]))); continue
            try:
                brk = int(row["break_minutes"] or 0)
            except ValueError:
                findings.append(("TS01", e, row["date"], "line %d: break_minutes is not a whole number; treated as 0" % i)); brk = 0
            overnight = en <= s
            if overnight:
                en += 24 * 60
                findings.append(("TS11", e, row["date"], "line %d: %s-%s crosses midnight; counted on %s" % (i, row["start"], row["end"], row["date"])))
            start = dt.datetime.combine(day, dt.time()) + dt.timedelta(minutes=s)
            end = dt.datetime.combine(day, dt.time()) + dt.timedelta(minutes=en)
            span = (en - s)
            if brk > span:
                findings.append(("TS03", e, row["date"], "line %d: break %d min is longer than the %d-min shift; worked time set to 0" % (i, brk, span)))
                brk = span
            shifts.append({"employee": e, "date": day, "start": start, "end": end, "break": brk,
                           "hours": (span - brk) / 60.0, "span_h": span / 60.0, "line": i, "note": row.get("note", "")})
    return shifts, findings


def week_of(day, week_start):
    offset = (day.weekday() - DAYS.index(week_start)) % 7
    return day - dt.timedelta(days=offset)


def analyse(shifts, rules, employees, findings):
    ws = rules["week_start"].lower()
    by_emp = defaultdict(list)
    for s in shifts:
        by_emp[s["employee"]].append(s)
    weeks = []
    for e, ss in sorted(by_emp.items()):
        ss.sort(key=lambda x: x["start"])
        for a, b in zip(ss, ss[1:]):
            if b["start"] < a["end"]:
                findings.append(("TS02", e, b["date"].isoformat(), "lines %d and %d overlap (%s-%s and %s-%s)" % (
                    a["line"], b["line"], a["start"].strftime("%a %H:%M"), a["end"].strftime("%H:%M"), b["start"].strftime("%a %H:%M"), b["end"].strftime("%H:%M"))))
            else:
                rest = (b["start"] - a["end"]).total_seconds() / 3600
                if rules["min_rest_hours"] and rest < rules["min_rest_hours"] and b["date"] != a["date"]:
                    findings.append(("TS07", e, b["date"].isoformat(), "only %.1f h rest between line %d and line %d (minimum %s h)" % (rest, a["line"], b["line"], rules["min_rest_hours"])))
        for s in ss:
            if rules["max_shift_hours"] and s["span_h"] > rules["max_shift_hours"]:
                findings.append(("TS05", e, s["date"].isoformat(), "line %d: %.1f h from start to end (limit %s h); check for a typo" % (s["line"], s["span_h"], rules["max_shift_hours"])))
            if rules["break_required_after_hours"] and s["span_h"] > rules["break_required_after_hours"] and s["break"] < rules["min_break_minutes"]:
                findings.append(("TS06", e, s["date"].isoformat(), "line %d: %.1f h shift with %d min break (needs %d min after %s h)" % (s["line"], s["span_h"], s["break"], rules["min_break_minutes"], rules["break_required_after_hours"])))
        days = sorted({s["date"] for s in ss if s["hours"] > 0})
        run, best, best_end = 1, 1, days[0] if days else None
        for a, b in zip(days, days[1:]):
            run = run + 1 if (b - a).days == 1 else 1
            if run > best:
                best, best_end = run, b
        if rules["max_days_in_a_row"] and best > rules["max_days_in_a_row"]:
            findings.append(("TS09", e, best_end.isoformat(), "%d days in a row without a day off (limit %d)" % (best, rules["max_days_in_a_row"])))
        info = employees.get(e)
        if employees and info is None:
            findings.append(("TS10", e, "", "not in the employees file; pay not estimated"))
        ot_ok = True if info is None else info["ot"]
        by_week = defaultdict(lambda: defaultdict(float))
        for s in ss:
            by_week[week_of(s["date"], ws)][s["date"]] += s["hours"]
        for wk, daymap in sorted(by_week.items()):
            reg = ot = dtm = 0.0
            for day in sorted(daymap):
                h = daymap[day]
                d_dt = max(0.0, h - rules["daily_dt_after"]) if rules["daily_dt_after"] else 0.0
                d_ot = max(0.0, h - d_dt - rules["daily_ot_after"]) if rules["daily_ot_after"] else 0.0
                d_reg = h - d_dt - d_ot
                if rules["weekly_ot_after"] is not None and reg + d_reg > rules["weekly_ot_after"]:
                    over = reg + d_reg - rules["weekly_ot_after"]
                    moved = min(over, d_reg)
                    d_reg -= moved; d_ot += moved
                reg += d_reg; ot += d_ot; dtm += d_dt
            total = reg + ot + dtm
            if not ot_ok:
                reg, ot, dtm = total, 0.0, 0.0
            if rules["max_weekly_hours"] and total > rules["max_weekly_hours"]:
                findings.append(("TS08", e, wk.isoformat(), "%.2f h in the week starting %s (maximum %s h)" % (total, wk.isoformat(), rules["max_weekly_hours"])))
            pay = None
            if info:
                pay = info["rate"] * (reg + ot * rules["ot_multiplier"] + dtm * rules["dt_multiplier"])
            weeks.append({"employee": e, "week_start": wk.isoformat(), "days": len(daymap), "total": round(total, 2),
                          "regular": round(reg, 2), "overtime": round(ot, 2), "double_time": round(dtm, 2),
                          "overtime_eligible": ot_ok, "rate": info["rate"] if info else None,
                          "pay_estimate": round(pay, 2) if pay is not None else None})
    return weeks


def run(ts_path, rules_path=None, emp_path=None):
    rules = load_rules(rules_path)
    employees = load_employees(emp_path)
    shifts, findings = load_shifts(ts_path)
    if not shifts:
        raise InputError("no usable shifts in the timesheet")
    weeks = analyse(shifts, rules, employees, findings)
    findings = [{"code": c, "severity": SEV[c], "issue": NAMES[c], "employee": e, "date": d, "detail": t} for c, e, d, t in findings]
    order = {"high": 0, "medium": 1, "low": 2}
    findings.sort(key=lambda f: (order[f["severity"]], f["code"], f["employee"], f["date"]))
    return {"rules": rules, "weeks": weeks, "findings": findings, "shift_count": len(shifts)}


def report(res):
    r = res["rules"]
    L = ["# Timesheet and overtime check", ""]
    L.append("Rules used: week starts %s; overtime after %s h/day and %s h/week at x%s; double time after %s h/day at x%s; break %s min after %s h; rest %s h; max %s h/week; max %s days in a row." % (
        r["week_start"], r["daily_ot_after"] or "-", r["weekly_ot_after"] if r["weekly_ot_after"] is not None else "-", r["ot_multiplier"],
        r["daily_dt_after"] or "-", r["dt_multiplier"], r["min_break_minutes"], r["break_required_after_hours"], r["min_rest_hours"], r["max_weekly_hours"], r["max_days_in_a_row"]))
    L.append("%d shifts read." % res["shift_count"])
    L.append("")
    L.append("## Hours and pay by employee and week")
    L.append("| employee | week starting | days | total h | regular | overtime | double time | rate | pay estimate |")
    L.append("|---|---|---:|---:|---:|---:|---:|---:|---:|")
    for w in res["weeks"]:
        L.append("| %s | %s | %d | %.2f | %.2f | %.2f | %.2f | %s | %s |" % (w["employee"] + ("" if w["overtime_eligible"] else " (no OT)"), w["week_start"], w["days"],
                 w["total"], w["regular"], w["overtime"], w["double_time"], "%.2f" % w["rate"] if w["rate"] is not None else "-",
                 "{:,.2f}".format(w["pay_estimate"]) if w["pay_estimate"] is not None else "-"))
    tot_pay = sum(w["pay_estimate"] or 0 for w in res["weeks"])
    tot_ot = sum(w["overtime"] + w["double_time"] for w in res["weeks"])
    L.append("")
    L.append("Totals: %.2f overtime/double-time hours; estimated gross pay %s (before taxes, premiums and allowances)." % (tot_ot, "{:,.2f}".format(tot_pay)))
    L.append("")
    L.append("## Findings (%d)" % len(res["findings"]))
    if not res["findings"]:
        L.append("- none")
    for f in res["findings"]:
        L.append("- [%s] %s %s - %s%s: %s" % (f["severity"].upper(), f["code"], f["issue"], f["employee"], (" " + f["date"]) if f["date"] else "", f["detail"]))
    L.append("")
    L.append("Check every high finding with the employee or manager before payroll. Your local labour law and contracts decide the real rules.")
    return "\n".join(L)


def self_test():
    import os, tempfile
    ok = True
    def check(name, cond):
        nonlocal ok
        print(("PASS  " if cond else "FAIL  ") + name); ok = ok and cond
    tmp = tempfile.mkdtemp()
    def write(name, text):
        p = os.path.join(tmp, name); open(p, "w", encoding="utf-8").write(text); return p
    emp = write("e.csv", "employee,hourly_rate,overtime_eligible\nAna,20,yes\nBo,30,no\n")
    week = "employee,date,start,end,break_minutes\n" + "".join("Ana,2026-11-%02d,08:00,17:00,30\n" % d for d in (16, 17, 18, 19, 20))
    res = run(write("a.csv", week), None, emp)
    w = res["weeks"][0]
    check("5 x 8.5 h = 42.5 h total", abs(w["total"] - 42.5) < 1e-9)
    check("weekly OT after 40 h = 2.5 h", abs(w["overtime"] - 2.5) < 1e-9 and abs(w["regular"] - 40) < 1e-9)
    check("pay = 40x20 + 2.5x30", abs(w["pay_estimate"] - 875) < 1e-6)
    rules = write("r.json", json.dumps({"daily_ot_after": 8, "daily_dt_after": 12, "weekly_ot_after": 40}))
    res = run(write("b.csv", "employee,date,start,end,break_minutes\nAna,2026-11-16,06:00,20:00,30\n"), rules, emp)
    w = res["weeks"][0]
    check("13.5 h day with daily rules: 8 reg, 4 OT, 1.5 DT", (w["regular"], w["overtime"], w["double_time"]) == (8.0, 4.0, 1.5))
    res = run(write("c.csv", "employee,date,start,end,break_minutes\nAna,2026-11-16,22:00,06:00,30\n"))
    check("overnight shift counted 7.5 h", abs(res["weeks"][0]["total"] - 7.5) < 1e-9)
    check("overnight shift flagged TS11", any(f["code"] == "TS11" for f in res["findings"]))
    res = run(write("d.csv", "employee,date,start,end,break_minutes\nAna,2026-11-16,08:00,16:00,30\nAna,2026-11-16,15:00,18:00,0\n"))
    check("overlap TS02", any(f["code"] == "TS02" for f in res["findings"]))
    res = run(write("e2.csv", "employee,date,start,end,break_minutes\nAna,2026-11-16,08:00,16:00,30\nAna,2026-11-16,08:00,16:00,30\n"))
    check("duplicate TS04 counted once", any(f["code"] == "TS04" for f in res["findings"]) and abs(res["weeks"][0]["total"] - 7.5) < 1e-9)
    res = run(write("f.csv", "employee,date,start,end,break_minutes\nAna,2026-11-16,08:00,16:30,10\n"))
    check("missing break TS06", any(f["code"] == "TS06" for f in res["findings"]))
    res = run(write("g.csv", "employee,date,start,end,break_minutes\nAna,2026-11-16,14:00,23:00,30\nAna,2026-11-17,06:00,14:00,30\n"))
    check("7 h rest TS07", any(f["code"] == "TS07" for f in res["findings"]))
    res = run(write("h.csv", "employee,date,start,end,break_minutes\nAna,2026-11-16,08:00,,30\nAna,2026-11-17,08:00,16:00,30\n"))
    check("missing end TS01 and row skipped", any(f["code"] == "TS01" for f in res["findings"]) and res["shift_count"] == 1)
    rows = "employee,date,start,end,break_minutes\n" + "".join("Ana,2026-11-%02d,07:00,18:00,30\n" % d for d in range(16, 21))
    res = run(write("i.csv", rows))
    check("52.5 h week TS08", any(f["code"] == "TS08" for f in res["findings"]))
    rows = "employee,date,start,end,break_minutes\n" + "".join("Ana,2026-11-%02d,09:00,13:00,0\n" % d for d in range(10, 18))
    res = run(write("j.csv", rows))
    check("8 days in a row TS09", any(f["code"] == "TS09" for f in res["findings"]))
    res = run(write("k.csv", week.replace("Ana", "Bo")), None, emp)
    check("not OT eligible: all regular", res["weeks"][0]["overtime"] == 0 and abs(res["weeks"][0]["regular"] - 42.5) < 1e-9)
    res = run(write("l.csv", week.replace("Ana", "Cy")), None, emp)
    check("unknown employee TS10, no pay", any(f["code"] == "TS10" for f in res["findings"]) and res["weeks"][0]["pay_estimate"] is None)
    res = run(write("m.csv", "employee,date,start,end,break_minutes\nAna,2026-11-16,08:00,09:00,90\n"))
    check("break longer than shift TS03", any(f["code"] == "TS03" for f in res["findings"]) and res["weeks"][0]["total"] == 0)
    res = run(write("n.csv", "employee,date,start,end,break_minutes\nAna,2026-11-16,08:00,16:00,30\nAna,2026-11-22,08:00,16:00,30\nAna,2026-11-23,08:00,16:00,30\n"))
    check("sunday belongs to the monday week, next monday starts a new week", [w["week_start"] for w in res["weeks"]] == ["2026-11-16", "2026-11-23"])
    rules2 = write("r2.json", json.dumps({"week_start": "sunday"}))
    res = run(write("o.csv", "employee,date,start,end,break_minutes\nAna,2026-11-22,08:00,16:00,30\n"), rules2)
    check("week_start sunday", res["weeks"][0]["week_start"] == "2026-11-22")
    try:
        run(write("p.csv", "employee,date,start\nAna,2026-11-16,08:00\n")); check("missing columns rejected", False)
    except InputError:
        check("missing columns rejected", True)
    try:
        run(write("q.csv", week), write("bad.json", json.dumps({"weekly_overtime": 40}))); check("unknown rule key rejected", False)
    except InputError:
        check("unknown rule key rejected", True)
    print("ALL PASS" if ok else "SOME TESTS FAILED")
    return 0 if ok else 1


def main(argv):
    if "--self-test" in argv:
        return self_test()
    args, opts, i = [], {}, 0
    while i < len(argv):
        a = argv[i]
        if a in ("--rules", "--employees"):
            if i + 1 >= len(argv):
                print(a + " needs a file", file=sys.stderr); return 2
            opts[a] = argv[i + 1]; i += 2; continue
        if a != "--json":
            args.append(a)
        i += 1
    if len(args) != 1:
        print(__doc__, file=sys.stderr); return 2
    try:
        res = run(args[0], opts.get("--rules"), opts.get("--employees"))
    except (InputError, OSError, json.JSONDecodeError) as e:
        print("input error: %s" % e, file=sys.stderr); return 2
    print(json.dumps(res, indent=2, default=str) if "--json" in argv else report(res))
    return 1 if any(f["severity"] == "high" for f in res["findings"]) else 0


if __name__ == "__main__":
    sys.exit(main(sys.argv[1:]))
ComplianceBusinessData Analysis+3
F@f
0
Log PII and Secret Redaction Checker
Skill

Scans plain or JSON-lines logs for data that must never be logged: Luhn-valid cards, IBANs, SSNs, API keys, JWTs, auth headers, passwords, URL tokens, emails, phones, birth dates and public IPs. Masks every value, ranks the loggers to fix and writes a redacted copy. Offline stdlib Python.

---
name: log-pii-and-secret-redaction-checker
description: Scans plain or JSON-lines logs for data that must never be logged: Luhn-valid cards, IBANs, SSNs, API keys, JWTs, auth headers, passwords, URL tokens, emails, phones, birth dates and public IPs. Masks every value, ranks the loggers to fix and writes a redacted copy. Offline stdlib Python.
---

# Log PII and Secret Redaction Checker

You help backend developers, SREs and security or privacy reviewers find personal data and credentials that leaked into application logs, and fix the code that writes them. Logs are copied to log platforms, tickets, chat and laptops, are kept for months and are read by many people, so a card number or bearer token in a debug line is a real incident (PCI DSS, GDPR, leaked credentials). You scan a log sample, explain what was found and where it comes from, and give concrete fixes at the logger, not just a cleaned file.

You work only on the log text the user provides, on their machine. You never print a found secret or personal value in full, never try a found credential, and never upload logs anywhere. Treat any real secret you find as compromised: tell the user to rotate it.

## Files in this skill

- `scripts/log_redaction_check.py` - scans one or more log files (plain text or JSON lines) and prints findings LR01-LR10 grouped by type with masked examples, a ranking of the loggers/components that leak, and DEBUG-level hits; `--redact OUT` writes a redacted copy, `--allow REGEX` skips known safe values, `--json` for tooling, `--self-test` runs 24 checks (Python 3.8+ standard library only)
- `references/detection-rules.md` - every detector, its pattern and validation (Luhn, IBAN mod-97, private IP ranges) and its known false positives
- `references/fixing-leaks-at-the-source.md` - how to stop the leak in code: structured logging, field allowlists, redaction filters for common stacks, and incident steps
- `templates/redaction-report.md` - the report you hand back
- `examples/app.log` - a 25-line mixed text/JSON log from a fictional shop with planted leaks and decoys

## Workflow

### 1. Get a representative sample
Ask for a log excerpt from each service or level that matters (include DEBUG if it is ever enabled in production), ideally a few thousand lines. If the user cannot share logs, have them run the script locally and paste only the report: the report masks values. Ask which values are known safe (system sender addresses, test cards in a sandbox) so you can pass them with `--allow`.

### 2. Run the checker
```
python3 scripts/log_redaction_check.py examples/app.log
python3 scripts/log_redaction_check.py api.log worker.log --allow '^noreply@example\.com$'
python3 scripts/log_redaction_check.py app.log --redact app.redacted.log --json > findings.json
python3 scripts/log_redaction_check.py --self-test
```
Exit 0 = no high findings, 1 = high findings, 2 = bad input. Use `--include-private-ip` when internal addresses also count (for example, office or VPN IPs that identify employees). Without a shell, apply `references/detection-rules.md` by hand: search for the patterns and validate cards with Luhn before reporting them.

### 3. Triage the findings
- High (fix now, usually an incident): LR02 card number, LR03 API key, token, JWT, private key or `Authorization` header value, LR04 password or secret value, LR07 IBAN, LR08 SSN, LR09 token in a URL query string (also leaks through access logs, proxies and the `Referer` header).
- Medium (personal data, needs a lawful reason and retention limit): LR01 email, LR06 phone, LR10 date of birth.
- Low (context dependent): LR05 public IP address, personal data under GDPR when it identifies a user.
- Check every hit before reporting it: decoys such as order numbers, version strings and timestamps can pass a pattern. Mark false positives and re-run with `--allow`.
- Use the "Sources to fix first" table: one logger often causes most of the hits. DEBUG-level hits mean request or payload dumping.

### 4. Fix at the source, then clean up
Follow `references/fixing-leaks-at-the-source.md`: stop logging whole request bodies and headers, log ids instead of values, add a redaction filter as a safety net, and move secrets out of URLs. For high findings, rotate the exposed credentials, purge or restrict the affected logs in every sink (log platform, backups, tickets), and check whether the incident must be reported (PCI DSS, GDPR breach assessment). `--redact` output is for sharing a sample safely, not a substitute for fixing the code.

### 5. Deliver
Fill `templates/redaction-report.md`: scope, counts by severity, a table per finding type with masked examples and source, root causes per logger, code fixes, credentials to rotate, log clean-up steps and a regression check (run the script in CI on a test log, fail on exit 1).

## Example result
On `examples/app.log` the checker finds 20 hits in 25 lines: 11 high, 7 medium, 2 low.
- High: a full test card number in a DEBUG charge request, a bearer token in dumped headers, a plaintext password from a failed login, a Stripe-style secret key in an error message, an AWS access key in a deploy line, a JWT, an OAuth `code`, a download `token` and an upstream `api_key` in URLs, a checksum-valid IBAN and an SSN.
- Medium: 4 emails (3 distinct), 2 phone numbers and a date of birth in a CRM update.
- Correctly ignored decoys: the masked `4111********1111` card, `cvc=[REDACTED]`, `password=***`, the IBAN-like reference with a bad checksum, the parcel tracking number, the duration in ms, the private `10.0.3.14` and `build 1.2.3.4`.
- With `--allow '^noreply@'` the system sender address drops out (19 hits). `auth` is the leakiest logger (5 hits) and 3 hits sit in DEBUG lines.

## Asking the right questions
- Where do these logs go (log platform, files, third-party APM) and how long are they kept?
- Is DEBUG ever enabled in production, even temporarily?
- Which values are test data (sandbox cards, example.com addresses) and may be allowlisted?
- Who owns each logger in the "Sources to fix first" table?

## Rules

- Never echo a full secret or personal value; quote masked values and line numbers only.
- Any real credential found in logs is compromised: recommend rotation, not just deletion.
- Report patterns, not proof: say that a clean scan does not prove a log is clean (free-text names and addresses are not detected).
- Prefer fixes in code (do not log it) over regex filters; filters are a second line of defense.
- Do not give legal advice; point to the user's DPO or security team for breach-notification decisions.

FILE:references/detection-rules.md
# Detection rules

Each match is checked in this order; a later detector never reports text already claimed by an earlier one. Values that look already masked (`***`, `xxx`, `[REDACTED]`, `<redacted>`, `[FILTERED]`, `null`, empty) are skipped.

| Code | Kind | Severity | Pattern (simplified) | Extra validation |
|---|---|---|---|---|
| LR03 | PRIVATE_KEY | high | `-----BEGIN ... PRIVATE KEY-----` | none |
| LR09 | URL_TOKEN | high | `?` or `&` + `access_token`, `refresh_token`, `id_token`, `token`, `api_key`, `apikey`, `sig`, `signature`, `password`, `session`, `sid`, `code` = value | value must not be masked |
| LR03 | AUTH_HEADER | high | `Authorization`, `X-Api-Key`, `api_key`, `X-Auth-Token` `:`/`=` optional `Bearer`/`Basic`/`Token` + 12+ token chars | none |
| LR03 | JWT | high | `eyJ...` three base64url segments | none |
| LR03 | AWS_KEY | high | `AKIA`/`ASIA` + 16 upper-case letters or digits | none |
| LR03 | API_KEY | high | `sk_`/`rk_`/`pk_` + `live_`/`test_` + 16+ chars, GitHub `ghp_`/`gho_`/`ghu_`/`ghs_`/`ghr_`, Slack `xoxa-`/`xoxb-`/`xoxp-`/`xoxr-` | none |
| LR04 | PASSWORD | high | `password`, `passwd`, `pwd`, `secret`, `client_secret`, `passphrase` + `:`/`=` + value (text or JSON) | value must not be masked |
| LR10 | DOB | medium | `dob`, `date_of_birth`, `birthdate`, `birth_date`, `birthday` + a date | none |
| LR07 | IBAN | high | 2 letters, 2 digits, 11-30 more alphanumerics, spaces allowed every 4 | ISO 13616 mod-97 checksum = 1 |
| LR02 | CARD | high | 13-19 digits, optional single spaces or dashes, not part of a decimal, time or longer number | Luhn checksum, not all the same digit |
| LR08 | SSN | high | `NNN-NN-NNNN` | not 000, 666 or 9xx area; group not 00; serial not 0000 |
| LR01 | EMAIL | medium | `local@domain.tld` | none |
| LR06 | PHONE | medium | `+` country code then 2-4 digit groups | 10-15 digits in total |
| LR05 | IP | low | dotted IPv4 | octets 0-255; private, loopback, link-local and multicast skipped unless `--include-private-ip`; skipped right after `version`, `build`, `release`, `tag`, `v` |

## Known false positives
- **Cards**: about 1 in 10 random 13-19 digit numbers pass Luhn. Order ids, millisecond timestamps and tracking numbers can match; confirm with the field name. Separators inside numbers are only single spaces or dashes.
- **Phones**: only numbers written with a leading `+` are detected, which avoids most ids but misses national formats like `(415) 555-0132` or `0171 2345678`.
- **SSN**: any `123-45-6789` shape, for example some part numbers.
- **IPs**: version strings in other forms (`lib 2.10.0.1`), public IPs of your own servers.
- **URL tokens**: `code=` can be a harmless product code; OAuth authorization codes are short-lived but still must not be logged.

## Known misses
Names, postal addresses, free-text messages, national ids other than US SSN, non-`+` phone numbers, secrets without a known prefix or key name, base64-encoded payloads, and data split across lines. Combine the scan with a code review of what each log call writes.

FILE:references/fixing-leaks-at-the-source.md
# Fixing leaks at the source

## Principles
1. **Log ids, not values.** `user_id=8812` instead of the email; `card_last4=1111` plus a payment id instead of the card; `order_id` instead of the address.
2. **Allowlist fields.** Log a fixed set of fields per event instead of whole objects, request bodies or header maps. Dumping `request.headers` is the most common source of LR03 bearer tokens.
3. **Keep secrets out of URLs.** Send tokens in headers or POST bodies; URLs end up in access logs, proxy logs, browser history and `Referer` headers. For signed download links, log the path without the query string.
4. **Redaction filter as a safety net.** Add one central filter that masks known sensitive keys (`password`, `secret`, `token`, `authorization`, `card*`, `iban`, `ssn`, `dob`) and the patterns in `detection-rules.md`, before logs leave the process.
5. **DEBUG is not a free pass.** Debug logs get turned on in production during incidents. Apply the same rules.

## Stack hints
- **Python logging / structlog**: a `logging.Filter` or structlog processor that rewrites `record.msg`/event dict keys; never `logger.debug("req %s", request.__dict__)`.
- **Node (pino / winston)**: pino `redact: ["req.headers.authorization", "*.password", "card.number"]`; winston custom format.
- **Java (Logback / Log4j2)**: a masking `PatternLayout` converter or `RewritePolicy`; avoid `toString()` of entities with personal fields (exclude them from Lombok `@ToString`).
- **Go (slog / zap)**: implement `LogValuer` on sensitive types to return a masked value.
- **Nginx / load balancers**: custom `log_format` that uses `$uri` instead of `$request_uri` (drops the query string) where tokens appear.
- **Log platform**: add ingest-time masking rules too (Datadog sensitive data scanner, Elastic ingest pipeline, Loki/Vector `redact` transforms).

## When a high finding is real (incident steps)
1. Rotate the exposed credential (API key, token, password) and check its use since the first log line.
2. Fix and deploy the logging code.
3. Purge or restrict the affected logs in every sink: log platform, archives and backups, exported files, tickets and chat pastes.
4. Card data: logging full card numbers is a PCI DSS violation; tell the payments owner.
5. Personal data: record the incident and let the privacy owner decide on breach notification (GDPR art. 33 has a 72-hour clock once a reportable breach is known).

## Regression check
Keep a test log produced by the test suite and run `log_redaction_check.py test.log` in CI; fail the build on exit code 1. Add the known safe values with `--allow` so the check stays quiet until a real leak appears.

FILE:templates/redaction-report.md
# Log redaction review: [service / log source], [date range of sample]

**Scope:** [files, services, levels, number of lines]  **Tool:** `log_redaction_check.py` (output attached, values masked)
**Result:** [n] findings - [h] high, [m] medium, [l] low  **Verdict:** [incident / fix soon / clean sample]

## High findings (act now)
| Code | Type | Hits | Masked example | Line(s) | Source |
|---|---|---|---|---|---|
| [LR03] | [bearer token in headers] | [1] | [to****Nw] | [3] | [auth] |

## Medium and low findings
| Code | Type | Hits | Masked example | Line(s) | Source |
|---|---|---|---|---|---|
| [LR01] | [email] | | | | |

## False positives excluded
- [value pattern, why it is safe, `--allow` used]

## Root causes by logger
1. [logger] - [what it writes, e.g. dumps full request headers at DEBUG]
2. [...]

## Fixes
| Where | Change | Owner |
|---|---|---|
| [auth middleware] | [log user_id only, drop header dump] | [ ] |

## Credentials to rotate
- [key type, where it was found, first seen]

## Log clean-up
- [sinks to purge or restrict, retention changes]

## Regression check
- [CI step running the checker on a test log, fail on exit 1]

_A clean scan does not prove a log is clean: names, addresses and free text are not detected._

FILE:examples/app.log
2026-11-18T09:00:01Z INFO [web] GET /health 200 4ms from 10.0.3.14
2026-11-18T09:00:07Z INFO [auth] login ok user_id=8812 email=ana.lima@example.com ip=203.0.113.24
2026-11-18T09:00:09Z DEBUG [auth] request headers {"Authorization": "Bearer tok_9fA2kLm33QpR7xYz81Nw", "Accept": "application/json"}
2026-11-18T09:00:12Z INFO [auth] login failed user=bob.k@example.org password=Summer2026! attempts=2
2026-11-18T09:00:15Z INFO [auth] password reset requested user_id=4410 password=*** (masked)
2026-11-18T09:01:02Z INFO [checkout] order 100244 created total=59.90 items=3
2026-11-18T09:01:03Z DEBUG [payments] charge request card_number=4111 1111 1111 1111 exp=12/28 cvc=[REDACTED]
2026-11-18T09:01:03Z INFO [payments] charge ok card=4111********1111 amount=59.90
2026-11-18T09:01:04Z ERROR [payments] gateway timeout, retrying with key sk_test_51HxT9mQ2eZvKyL0AbCdEf
2026-11-18T09:01:30Z INFO [web] GET /oauth/callback?code=4/0AY0e-g7Qx2mN8&state=af31 302 from 198.51.100.77
2026-11-18T09:02:11Z INFO [web] GET /download/report.pdf?token=a8f3e2c19d7b44&expires=1763456531 200
2026-11-18T09:02:40Z INFO [crm] contact updated name="Ana Lima" phone=+44 20 7946 0958 dob=1990-04-12
2026-11-18T09:03:05Z WARN [payouts] payout to IBAN GB82 WEST 1234 5698 7654 32 delayed
2026-11-18T09:03:06Z INFO [payouts] payout batch 77 ref=DE00370400440532013000 ok
2026-11-18T09:03:59Z INFO [kyc] verification started ssn=123-45-6789 status=pending
2026-11-18T09:04:10Z INFO [deploy] s3 sync using AKIAIOSFODNN7EXAMPLE region=eu-west-1
2026-11-18T09:04:11Z INFO [deploy] build 1.2.3.4 tagged, artifact 8f2e91 uploaded
{"ts":"2026-11-18T09:05:00Z","level":"info","logger":"orders","msg":"order shipped","order_id":100244,"customer_email":"ana.lima@example.com","tracking":"1Z999AA10123456784"}
{"ts":"2026-11-18T09:05:02Z","level":"debug","logger":"orders","msg":"upstream call","url":"https://api.example.net/v2/rates?api_key=k_live_77QhR2sT9w","status":200}
{"ts":"2026-11-18T09:05:09Z","level":"info","logger":"notify","msg":"sms sent","to":"+1 415 555 0132","template":"shipped"}
{"ts":"2026-11-18T09:05:15Z","level":"info","logger":"notify","msg":"email sent","to":"noreply@example.com","template":"digest"}
{"ts":"2026-11-18T09:06:00Z","level":"error","logger":"session","msg":"token expired","jwt":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiI4ODEyIiwiZXhwIjoxNzYzNDU2NTMxfQ.Qm9ndXNTaWduYXR1cmVGb3JEZW1v"}
{"ts":"2026-11-18T09:06:20Z","level":"info","logger":"session","msg":"session refreshed","user_id":8812,"password":"[REDACTED]"}
2026-11-18T09:07:00Z INFO [web] GET /api/users/8812 200 12ms from 10.0.3.14
2026-11-18T09:07:45Z INFO [jobs] nightly export finished rows=18233 duration_ms=1731995000123

FILE:scripts/log_redaction_check.py
#!/usr/bin/env python3
"""Log PII and secret redaction checker (offline, Python 3.8+ standard library only).

Scans plain-text or JSON-lines logs for personal data and secrets that should never be logged:
payment cards (Luhn-checked), IBANs (mod-97 checked), US SSNs, API keys and tokens (AWS, Stripe,
GitHub, Slack, JWT, Authorization headers), passwords in key=value or JSON, tokens in URL query
strings, emails, phone numbers, dates of birth and public IP addresses. Values that are already
masked ("***", "[REDACTED]") are ignored. Every value is masked in the report; nothing is sent
anywhere. Optionally writes a redacted copy of the log.

Usage:
  log_redaction_check.py app.log [more.log ...] [--json] [--redact OUT] [--allow REGEX ...]
                         [--include-private-ip] [--max-examples 3]
  log_redaction_check.py --self-test
Exit codes: 0 = no high findings, 1 = high findings, 2 = bad input.
"""
import argparse, json, re, sys
from collections import Counter, OrderedDict, defaultdict

SEV = {"high": 0, "medium": 1, "low": 2}
REDACTED = re.compile(r"^(\*+.*|x{3,}|\[?redacted(:\w+)?\]?|<redacted>|\[filtered\]|null|none|\"\"|-|)$", re.I)

# code, kind, severity, compiled regex, value group, validator (or None)
def luhn(s):
    d = [int(c) for c in s if c.isdigit()]
    if not 13 <= len(d) <= 19 or len(set(d)) == 1:
        return False
    tot = 0
    for i, n in enumerate(reversed(d)):
        if i % 2:
            n *= 2
            n -= 9 if n > 9 else 0
        tot += n
    return tot % 10 == 0


def iban_ok(s):
    s = s.replace(" ", "")
    if not 15 <= len(s) <= 34:
        return False
    r = s[4:] + s[:4]
    num = "".join(str(int(c, 36)) for c in r)
    return int(num) % 97 == 1


def phone_ok(s):
    return 10 <= sum(c.isdigit() for c in s) <= 15


def public_ip(s, include_private=False):
    parts = s.split(".")
    if len(parts) != 4 or any(not p.isdigit() or int(p) > 255 or (len(p) > 1 and p[0] == "0") for p in parts):
        return False
    a, b = int(parts[0]), int(parts[1])
    private = a in (10, 127, 0) or (a == 172 and 16 <= b <= 31) or (a == 192 and b == 168) or (a == 169 and b == 254) or a >= 224
    return include_private or not private


DETECTORS = [
    ("LR03", "PRIVATE_KEY", "high", re.compile(r"-----BEGIN [A-Z ]*PRIVATE KEY-----"), 0, None),
    ("LR09", "URL_TOKEN", "high", re.compile(r"(?i)[?&](?:access_token|refresh_token|id_token|token|api_key|apikey|sig|signature|password|session|sid|code)=([^&\s\"']+)"), 1, None),
    ("LR03", "AUTH_HEADER", "high", re.compile(r"(?i)\b(?:authorization|x-api-key|api[_-]?key|x-auth-token)\b\"?\s*[:=]\s*\"?(?:bearer\s+|basic\s+|token\s+)?([A-Za-z0-9._~+/=-]{12,})"), 1, None),
    ("LR03", "JWT", "high", re.compile(r"\beyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}"), 0, None),
    ("LR03", "AWS_KEY", "high", re.compile(r"\b(?:AKIA|ASIA)[0-9A-Z]{16}\b"), 0, None),
    ("LR03", "API_KEY", "high", re.compile(r"\b(?:sk|rk|pk)_(?:live|test)_[A-Za-z0-9]{16,}\b|\bgh[pousr]_[A-Za-z0-9]{30,}\b|\bxox[abpr]-[A-Za-z0-9-]{10,}"), 0, None),
    ("LR04", "PASSWORD", "high", re.compile(r"(?i)\b(?:password|passwd|pwd|secret|client_secret|passphrase)\b\"?\s*[:=]\s*\"?([^\s\",&}]*)"), 1, None),
    ("LR10", "DOB", "medium", re.compile(r"(?i)\b(?:dob|date_of_birth|birth_?date|birthday)\b\"?\s*[:=]\s*\"?(\d{4}-\d{2}-\d{2}|\d{1,2}[/.]\d{1,2}[/.]\d{2,4})"), 1, None),
    ("LR07", "IBAN", "high", re.compile(r"\b[A-Z]{2}\d{2}(?: ?[A-Z0-9]{4}){2,7}(?: ?[A-Z0-9]{1,4})?\b"), 0, iban_ok),
    ("LR02", "CARD", "high", re.compile(r"(?<![\d.:-])\d(?:[ -]?\d){12,18}(?![\d.:])"), 0, luhn),
    ("LR08", "SSN", "high", re.compile(r"\b(?!000|666|9\d\d)\d{3}-(?!00)\d{2}-(?!0000)\d{4}\b"), 0, None),
    ("LR01", "EMAIL", "medium", re.compile(r"\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\b"), 0, None),
    ("LR06", "PHONE", "medium", re.compile(r"(?<![\w+])\+\d{1,3}[ .-]?\(?\d{1,4}\)?(?:[ .-]?\d{2,4}){2,4}\b"), 0, phone_ok),
    ("LR05", "IP", "low", re.compile(r"(?<![\d.])(?:\d{1,3}\.){3}\d{1,3}(?![\d.])"), 0, "ip"),
]
TITLES = {"LR01": "email address", "LR02": "payment card number (Luhn valid)", "LR03": "API key, token or credential",
          "LR04": "password or secret value", "LR05": "public IP address", "LR06": "phone number",
          "LR07": "IBAN (checksum valid)", "LR08": "US Social Security number", "LR09": "token in URL query string",
          "LR10": "date of birth"}
VERSION_CTX = re.compile(r"(?i)(version|build|release|ver|tag|\bv)[\s:=]*$")
LEVEL_RE = re.compile(r"\b(TRACE|DEBUG|INFO|WARN|WARNING|ERROR|FATAL)\b\s*[:\-]?\s*\[?([A-Za-z][\w.\-]*)\]?")


def mask(kind, v):
    if kind == "CARD":
        d = re.sub(r"\D", "", v)
        return d[:1] + "*" * (len(d) - 5) + d[-4:]
    if kind == "EMAIL":
        user, _, dom = v.partition("@")
        return user[:1] + "***@" + dom
    if kind == "PRIVATE_KEY":
        return v
    if len(v) <= 6:
        return "*" * len(v)
    return v[:2] + "*" * min(len(v) - 4, 12) + v[-2:]


def source_of(line):
    s = line.strip()
    if s.startswith("{"):
        try:
            o = json.loads(s)
            for k in ("logger", "service", "component", "module", "name"):
                if isinstance(o.get(k), str):
                    return o[k], str(o.get("level", "")).upper()
        except ValueError:
            pass
    m = LEVEL_RE.search(line)
    if m:
        return m.group(2), m.group(1).upper()
    return "-", ""


def scan_line(line, allow=(), include_private_ip=False):
    taken, hits = [], []
    for code, kind, sev, rx, grp, val in DETECTORS:
        for m in rx.finditer(line):
            v = m.group(grp)
            a, b = m.span(grp)
            if v is None or REDACTED.match(v.strip()) or any(x < b and a < y for x, y in taken):
                continue
            if val == "ip":
                if not public_ip(v, include_private_ip) or VERSION_CTX.search(line[max(0, a - 12):a]):
                    continue
            elif val and not val(v):
                continue
            if any(r.search(v) for r in allow):
                continue
            taken.append((a, b))
            hits.append({"code": code, "kind": kind, "severity": sev, "start": a, "end": b, "value": v})
    return sorted(hits, key=lambda h: h["start"])


def redact_line(line, hits):
    out = line
    for h in sorted(hits, key=lambda h: -h["start"]):
        out = out[:h["start"]] + "[REDACTED:%s]" % h["kind"] + out[h["end"]:]
    return out


def scan(named_lines, allow=(), include_private_ip=False, max_examples=3):
    findings, by_code, sources, redacted = [], OrderedDict(), defaultdict(Counter), {}
    distinct = defaultdict(set)
    debug_hits = 0
    total_lines = 0
    for name, lines in named_lines:
        red = []
        for i, line in enumerate(lines, 1):
            total_lines += 1
            hits = scan_line(line, allow, include_private_ip)
            red.append(redact_line(line, hits))
            if not hits:
                continue
            src, level = source_of(line)
            if level in ("DEBUG", "TRACE"):
                debug_hits += len(hits)
            for h in hits:
                c = h["code"]
                by_code.setdefault(c, {"code": c, "severity": h["severity"], "what": TITLES[c], "count": 0, "lines": [], "examples": []})
                e = by_code[c]
                e["count"] += 1
                distinct[c].add(h["value"])
                if len(e["lines"]) < 20:
                    e["lines"].append("%s:%d" % (name, i))
                if len(e["examples"]) < max_examples:
                    e["examples"].append({"where": "%s:%d" % (name, i), "kind": h["kind"], "masked": mask(h["kind"], h["value"]), "source": src})
                sources[src][c] += 1
                findings.append({"file": name, "line": i, "code": c, "kind": h["kind"], "severity": h["severity"], "source": src, "level": level, "masked": mask(h["kind"], h["value"])})
        redacted[name] = red
    for c, e in by_code.items():
        e["distinct_values"] = len(distinct[c])
    summary = sorted(by_code.values(), key=lambda e: (SEV[e["severity"]], e["code"]))
    counts = Counter(f["severity"] for f in findings)
    src_rank = sorted(((s, sum(c.values()), dict(c)) for s, c in sources.items()), key=lambda x: -x[1])
    return {"lines_scanned": total_lines, "findings_total": len(findings), "by_severity": {k: counts.get(k, 0) for k in SEV},
            "summary": summary, "sources": [{"source": s, "hits": n, "codes": c} for s, n, c in src_rank],
            "debug_level_hits": debug_hits, "findings": findings, "redacted": redacted}


def print_text(rep):
    print("Scanned %d lines: %d findings (%d high, %d medium, %d low)" % (rep["lines_scanned"], rep["findings_total"],
          rep["by_severity"]["high"], rep["by_severity"]["medium"], rep["by_severity"]["low"]))
    if not rep["summary"]:
        print("No personal data or secrets found by the detectors (this is not proof the log is clean).")
        return
    print("\nBy type")
    for e in rep["summary"]:
        print("  [%s] %s %-34s %3d hits, %2d distinct  lines %s" % (e["severity"].upper(), e["code"], e["what"], e["count"],
              e["distinct_values"], ", ".join(x.split(":")[-1] for x in e["lines"][:8]) + (" ..." if e["count"] > 8 else "")))
        for x in e["examples"]:
            print("        %s  %-11s %s  (source %s)" % (x["where"], x["kind"], x["masked"], x["source"]))
    print("\nSources to fix first (logger / component)")
    for s in rep["sources"]:
        print("  %-22s %3d  %s" % (s["source"], s["hits"], " ".join("%s=%d" % kv for kv in sorted(s["codes"].items()))))
    if rep["debug_level_hits"]:
        print("\nNote: %d hits are in DEBUG/TRACE lines; check that debug logging is off in production." % rep["debug_level_hits"])


def self_test():
    ok = 0; tests = []
    def t(name, cond):
        tests.append((name, bool(cond)))
    k = lambda line, **kw: [h["kind"] for h in scan_line(line, **kw)]
    t("Luhn-valid card found", k("charge card=4111 1111 1111 1111 ok") == ["CARD"])
    t("Luhn-invalid number ignored", k("order 4111111111111112 shipped") == [])
    t("epoch ms timestamp not a card", k("ts=1731995000123 done") == [])
    t("IBAN mod-97 valid", k("payout to DE89 3704 0044 0532 0130 00") == ["IBAN"])
    t("IBAN bad checksum ignored", k("ref DE00370400440532013000") == [])
    t("AWS access key id", k("using AKIAIOSFODNN7EXAMPLE for s3") == ["AWS_KEY"])
    t("bearer header value", k("Authorization: Bearer abcDEF1234567890xyz") == ["AUTH_HEADER"])
    t("JWT", k("token eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxMjM0In0.c2lnbmF0dXJlLXZhbHVl") == ["JWT"])
    t("password in JSON", k('{"user":"bo","password":"hunter2!"}') == ["PASSWORD"])
    t("masked password ignored", k("password=*** user=bo") == [] and k('"password": "[REDACTED]"') == [])
    t("token in URL query", k("GET /cb?code=abc123&state=x") == ["URL_TOKEN"])
    t("email", k("signup ana.lima@example.com") == ["EMAIL"])
    t("phone needs + and 10-15 digits", k("call +44 20 7946 0958") == ["PHONE"] and k("build +1 2") == [])
    t("SSN", k("ssn 123-45-6789") == ["SSN"])
    t("private IP ignored, public flagged", k("from 10.0.0.5") == [] and k("from 203.0.113.7") == ["IP"])
    t("include private IP flag", k("from 10.0.0.5", include_private_ip=True) == ["IP"])
    t("version string not an IP", k("lib 1.2.3.4.5 loaded") == [])
    t("IP after 'build'/'version' ignored", k("build 1.2.3.4 tagged") == [] and k("version=8.8.8.8") == [])
    t("api_key in URL is a URL token", k("GET /r?api_key=abcdef123456789") == ["URL_TOKEN"])
    t("allowlist", k("mail noreply@example.com", allow=[re.compile(r"^noreply@")]) == [])
    t("date of birth", k("dob=1990-04-12 ok") == ["DOB"])
    rep = scan([("t.log", ["INFO [auth] login ana@example.com", "DEBUG [pay] card 5500 0000 0000 0004", "INFO [web] fine"])])
    t("report counts + severity", rep["findings_total"] == 2 and rep["by_severity"]["high"] == 1 and rep["debug_level_hits"] == 1)
    t("redaction keeps key, hides value", rep["redacted"]["t.log"][1] == "DEBUG [pay] card [REDACTED:CARD]")
    t("masked output never shows full card", "5500000000000004" not in json.dumps(rep["findings"]))
    for name, c in tests:
        print("%s  %s" % ("PASS" if c else "FAIL", name)); ok += c
    print("%d/%d passed" % (ok, len(tests)))
    return 0 if ok == len(tests) else 1


def main():
    ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    ap.add_argument("files", nargs="*"); ap.add_argument("--json", action="store_true")
    ap.add_argument("--redact", metavar="OUT"); ap.add_argument("--allow", action="append", default=[])
    ap.add_argument("--include-private-ip", action="store_true"); ap.add_argument("--max-examples", type=int, default=3)
    ap.add_argument("--self-test", action="store_true")
    a = ap.parse_args()
    if a.self_test:
        return self_test()
    if not a.files:
        ap.print_usage(); return 2
    try:
        allow = [re.compile(x) for x in a.allow]
        named = []
        for f in a.files:
            fh = sys.stdin if f == "-" else open(f, encoding="utf-8", errors="replace")
            named.append((f, fh.read().splitlines()))
    except (OSError, re.error) as e:
        print("error: %s" % e, file=sys.stderr); return 2
    rep = scan(named, allow, a.include_private_ip, a.max_examples)
    if a.redact:
        with open(a.redact, "w", encoding="utf-8") as out:
            for f in a.files:
                out.write("\n".join(rep["redacted"][f]) + "\n")
    red = rep.pop("redacted")
    if a.json:
        print(json.dumps(rep, indent=2))
    else:
        print_text(rep)
        if a.redact:
            print("\nRedacted copy written to %s (%d lines)" % (a.redact, sum(len(v) for v in red.values())))
    return 1 if rep["by_severity"]["high"] else 0


if __name__ == "__main__":
    sys.exit(main())
SecurityComplianceBackend+3
F@f
0
Customer Personal Data Request Handling Plan (JSON)
Text

Turn one incoming GDPR or CCPA access, deletion or correction request into a strict JSON handling plan for a small SaaS team: deadline, proportionate identity check, scope and exemptions, a data map across systems and vendors, action steps, export and deletion details, ready-to-send messages and record keeping.

1You are a privacy operations lead at a small SaaS startup who has handled many customer personal data requests under laws such as the GDPR, UK GDPR and CCPA/CPRA. Using the schema below, turn what I tell you about my product and one incoming request into a complete handling plan as one valid JSON object. Ask me up to 6 short questions first if the inputs are missing, then output ONLY the JSON, with no commentary before or after it.
2
3My inputs:
4- The request as received (paste the email, form entry or ticket), the date it arrived and the channel:
5- Product, what personal data we store about users and customers, and where (database, analytics, email tool, CRM, support desk, payments, backups, logs):
6- Our role for this data (we decide how it is used, or we process it for a business customer who decides) and our main users' countries:
7- Vendors that hold personal data for us:
8- Who on the team can work on this and how we can export or delete data today (admin panel, scripts, manual):
9- Anything special: legal hold, unpaid invoices, an open dispute, an account shared by a team, the requester is a child or acting for someone else:
10
...+87 more lines
SecurityJSONCompliance+4
F@f
0
Vendor Security Questionnaire Answer Pack (YAML)
Text

Turn what your startup really does about security into a reusable YAML answer pack for customer security questionnaires: infrastructure, data protection, access, app security, incidents, continuity, subprocessors, privacy, 15+ honest standard answers with evidence, gaps with interim answers, and open questions.

1You are a startup security and compliance lead who has answered hundreds of customer security questionnaires. Using the schema below, turn what I tell you about my product and company into a reusable security questionnaire answer pack as one valid YAML document. Ask me up to 6 short questions first if the inputs are missing, then output ONLY the YAML, with no commentary before or after it.
2
3My inputs:
4- Product and what customer data it handles (personal data, payment data, health data, files, credentials):
5- Company size, team locations and who owns security:
6- Hosting and key vendors (cloud, database, email, payments, analytics, support tools):
7- Security practices we really have today (SSO, MFA, encryption, backups, logging, code review, pen test, training):
8- Certifications or audits (none, SOC 2 in progress, SOC 2 Type II, ISO 27001, other):
9- The questionnaire or customer that triggered this (paste the questions if you have them):
10
...+88 more lines
SecurityYAMLDocumentation+4
F@f
0
Password Policy and Entropy Checker
Skill

Reviews a password policy config against NIST SP 800-63B-4, covering length minimums, no composition rules or forced expiry, blocklist checks, rate limiting, paste and Unicode support, no hints or security questions, and safe hashing parameters. Estimates the entropy of made-up sample passwords and shows which weak ones the current policy still accepts. Never asks for real passwords. Includes a stdlib Python checker with --self-test.

---
name: password-policy-and-entropy-checker
description: Reviews a password policy config against NIST SP 800-63B-4, covering length minimums, no composition rules or forced expiry, blocklist checks, rate limiting, paste and Unicode support, no hints or security questions, and safe hashing parameters. Estimates the entropy of made-up sample passwords and shows which weak ones the current policy still accepts. Never asks for real passwords. Includes a stdlib Python checker with --self-test.
---

# Password Policy and Entropy Checker

You help developers, IT admins and security reviewers bring a password policy in line with current NIST guidance (SP 800-63B-4, 2025) and explain why the old rules (8 characters, upper+lower+digit+symbol, change every 90 days) produce weak, predictable passwords. You show it with numbers: entropy estimates for made-up sample passwords and a list of weak samples the current policy lets through.

## Files in this skill

- `scripts/pw_policy.py` - checks a policy JSON against NIST SP 800-63B-4 and OWASP hashing minimums and estimates entropy for synthetic samples, masked in the output by default (Python 3 standard library only; no network, nothing stored)
- `references/nist-800-63b-rules.md` - the password requirements (SHALL / SHOULD) with what each means in practice
- `references/entropy-and-hashing.md` - how the two entropy estimates work, their limits, guess-rate assumptions and hashing parameters
- `templates/policy-recommendation.md` - the recommendation you hand back: current vs recommended setting, rationale, rollout plan
- `examples/legacy-portal-policy.json` and `examples/synthetic-samples.txt` - a legacy customer-portal policy and 8 made-up sample passwords

## Workflow

### 1. Collect the policy, never real passwords
Ask for the policy settings (from the identity provider, Active Directory fine-grained policy, framework config such as Django `AUTH_PASSWORD_VALIDATORS`, or the written policy) and convert them to the JSON keys in the script docstring. Ask whether passwords are the only factor or are always combined with MFA (`single_factor`). If the user wants to test strength, ask them to invent samples that look like what users pick. If someone pastes what looks like a real password, do not repeat it, tell them to change it and continue with made-up samples.

### 2. Run the checker
```
python3 scripts/pw_policy.py examples/legacy-portal-policy.json --samples examples/synthetic-samples.txt --context northwind
python3 scripts/pw_policy.py policy.json --samples synthetic.txt --blocklist top-10k.txt --json
python3 scripts/pw_policy.py --self-test
```
`--context` adds the service name, brand and similar words to the blocklist check. Exit code 1 means HIGH findings, 2 means bad input.

### 3. Explain the findings
Start with what changes for users: longer minimum (15 alone, 8 with MFA), no character-class rules, no forced expiry, blocklist rejection with a clear reason. Then the back end: rate limiting, hashing algorithm and parameters, hints and security questions removed. Use the samples table to show that `Password1!`-style passwords pass composition rules while a four-word passphrase is rejected by them. Use `references/nist-800-63b-rules.md` for the exact requirement and `references/entropy-and-hashing.md` when the user asks "how strong is strong enough".

### 4. Deliver
Fill `templates/policy-recommendation.md` with each setting (current, recommended, NIST reference), the hashing migration (rehash on next login) and a rollout plan: new rules apply at the next password change, expiry removed at once, breached-password check at login where possible.

## Example result
For the legacy portal policy with the 8 synthetic samples and `--context northwind`: 11 HIGH, 5 MEDIUM, 2 LOW. HIGH: minimum 8 (needs 15 without MFA), composition rules, 90-day expiry, no blocklist, hints, security questions, and 5 weak samples the policy accepts (Password1!, Summer2025!, Northwind#1, Qwerty123$, P@ssw0rd2026, each ~15-20 bits). MEDIUM: PBKDF2 at 10000 iterations, max length 20, spaces and paste blocked, no strength guidance. The 4-word passphrase (~54 bits) and the 5-word one (~67 bits) are rejected by the current rules but fine under NIST.

## Rules

- Never ask for, store or repeat real passwords, hashes or password files. Work only with made-up samples.
- Entropy numbers are estimates for comparison, not guarantees; say so.
- Quote NIST SHALL vs SHOULD correctly; do not present OWASP hashing numbers as NIST requirements.
- Phishing-resistant MFA or passkeys beat any password rule; recommend them where the risk justifies it.
- Do not recommend weakening a control (e.g. rate limiting) to improve usability without a replacement.
FILE:references/nist-800-63b-rules.md
# NIST SP 800-63B-4 Password Rules (final, 2025)

Section 3.1.1.2 "Password Verifiers" applies to centrally verified passwords (a login form checked by the server). Local unlock PINs are "activation secrets" with different rules (Sec. 3.2.10). SHALL = required, SHOULD = recommended.

| # | Requirement | Level | Script code | In practice |
|---|---|---|---|---|
| 1 | Minimum 15 characters when the password is the only factor; minimum 8 if only used with MFA | SHALL | MIN_LENGTH | Set 15 for password-only logins; 8 is acceptable only if MFA is always enforced |
| 2 | Allow a maximum of at least 64 characters | SHOULD | MAX_LENGTH | Passphrases and password-manager output need room; storage size is fixed by the hash anyway |
| 3 | Accept all printing ASCII characters and space | SHOULD | NO_SPACES | Do not reject `"`, `'`, `<`, spaces; escape correctly instead |
| 4 | Accept Unicode; count each code point as one character | SHOULD | NO_UNICODE | Apply NFC normalization before hashing (NO_NORMALIZATION) |
| 5 | No other composition rules (character-class mixes) | SHALL NOT | COMPOSITION_RULES | Remove "1 upper, 1 digit, 1 symbol" |
| 6 | No periodic forced changes; force a change on evidence of compromise | SHALL NOT | PERIODIC_EXPIRY | Remove 90-day expiry; reset on breach evidence |
| 7 | No hints accessible to unauthenticated users | SHALL NOT | HINTS | Delete stored hints |
| 8 | No knowledge-based authentication / security questions | SHALL NOT | SECURITY_QUESTIONS | Use recovery codes or a verified channel |
| 9 | Verify the entire password, no truncation, no "enter characters 3, 5 and 8" | SHALL | TRUNCATION | Watch out for bcrypt's 72-byte limit (BCRYPT_72_BYTES) |
| - | Compare the full password with a blocklist of common, expected and compromised values; give the reason when rejecting | SHALL | NO_BLOCKLIST, BLOCKLIST_THIN | Breached corpora (e.g. a k-anonymity range API or a downloaded list), dictionary words, service name, username |
| - | Offer guidance to help users choose a strong password, especially after a rejection | SHALL | NO_GUIDANCE | Strength meter and plain-language rejection reasons |
| - | Rate-limit failed attempts: no more than 100 consecutive failures per account (Sec. 3.2.2) | SHALL | NO_RATE_LIMIT | Growing delays, CAPTCHA, risk checks; hard lockouts after 3 tries invite denial of service (LOCKOUT_STRICT) |
| - | Allow password managers and autofill; permit paste | see Sec. 3.1.1.2 | PASTE_BLOCKED | Never block paste on password fields |
| - | Store passwords salted and hashed with a suitable password hashing scheme (Sec. 3.1.1.2, last part) | SHALL | WEAK_STORAGE | Argon2id, scrypt, bcrypt or PBKDF2 with a unique salt; parameters as high as practical |

## Blocklist sizing
NIST notes the blocklist mainly stops online guessing, which is already throttled, so it should cover the passwords an attacker would try before the limit (thousands to a few hundred thousand entries); very large lists mostly frustrate users. Check the whole password, not substrings, but include obvious derivatives of the service name and username.

## Why composition rules and expiry go
Users meet "upper + digit + symbol" with `Password1!`; forced changes produce `Password2!`, `Password3!`. Attack tools model these patterns, so the rules add friction without adding real entropy. Length plus a blocklist does more.

## Sources
- NIST SP 800-63B-4, Digital Identity Guidelines: Authentication and Authenticator Management (July 2025), https://pages.nist.gov/800-63-4/sp800-63b.html
- Appendix A "Strength of Passwords" in the same document
FILE:references/entropy-and-hashing.md
# Entropy Estimates and Password Hashing

## Two estimates
**Charset entropy** = length x log2(pool), pool = 26 lower + 26 upper + 10 digits + 33 symbols (+100 if non-ASCII), counting only the classes used. It is correct for passwords generated at random from that pool and badly overstates human choices: `Password1!` scores 65.7 bits.

**Pattern entropy** (script) approximates how a cracking tool guesses: it walks the password left to right and charges
| Piece | Cost |
|---|---|
| common word from the built-in list (incl. leet like `P@ssw0rd`, context words) | log2(list size) ~ 7.6 bits, +1 if capitalized, +2 if leet |
| year 1950-2039 | log2(90) ~ 6.5 bits |
| keyboard or alphabet run (`qwerty`, `1234`, `zyx`) | log2(26) + log2(length) |
| repeated character (`aaaa`) | one character + log2(count) |
| digits/symbol appended at the end after a word | -1.5 bits (the most common pattern) |
| any other character | log2(pool) |
| passphrase of 3+ words | 12.9 bits per uncommon word (Diceware list of 7776), 1 bit per common word |

The passphrase figure is an upper bound: it holds only if words were picked at random (dice or a generator). "my dog loves pizza" is far weaker. The built-in word list is small; a real cracker uses billions of breached passwords, so treat every estimate as optimistic for human-chosen input.

## Rating scale (pattern bits)
| Bits | Rating | Meaning |
|---|---|---|
| < 28 | very weak | Falls to online guessing or instantly offline |
| 28-35 | weak | Online throttling helps; offline it is minutes |
| 36-59 | fair | OK against online attacks with rate limiting; weak if a fast hash leaks |
| 60-79 | strong | Resists offline attacks on slow hashes |
| >= 80 | very strong | Resists offline attacks on fast hashes |

## Guess rates used for times
- Offline, fast hash (MD5/SHA-x on GPUs): 1e10 guesses per second.
- Offline, slow hash (Argon2id/bcrypt at recommended cost): about 1e4 guesses per second per attacker rig.
- Online with NIST throttling (<= 100 failures per account, then delays): only the first few hundred to thousands of guesses matter, which is why the blocklist is the key online control.
Time shown = median case, 2^(bits-1) / rate.

## Hashing parameters (OWASP Password Storage Cheat Sheet minimums)
| Algorithm | Minimum | Notes |
|---|---|---|
| Argon2id | m = 19456 KiB (19 MiB), t = 2, p = 1 | First choice |
| scrypt | N = 2^17, r = 8, p = 1 | |
| bcrypt | cost 10 | Input limited to 72 bytes; pre-hash with HMAC-SHA256 + base64 or cap the length |
| PBKDF2-HMAC-SHA256 | 600000 iterations | Use where FIPS-140 validated crypto is required |
Every hash needs a unique random salt (>= 16 bytes). An optional pepper (secret key kept outside the database) adds defense in depth. NIST requires salting and a suitable one-way password hashing function; OWASP numbers are a widely used baseline, not a NIST rule.

## Migrating weak hashes
1. Add the new algorithm next to the old one.
2. On successful login, verify with the old hash, then rehash with the new one.
3. For accounts that never log in, wrap the old hash (Argon2id(old_hash)) and mark them, or force a reset after a deadline.
4. Re-check breached-password status at login if your provider supports it.
FILE:templates/policy-recommendation.md
# Password policy recommendation: <system name>

**Scope:** <customer portal / workforce SSO / admin console>   **Factor:** <password only / password + MFA>
**Basis:** NIST SP 800-63B-4 (2025); hashing parameters from the OWASP Password Storage Cheat Sheet
**Summary:** <one sentence: e.g. "Replace complexity and expiry rules with a 15-character minimum and a breached-password blocklist; move hashes to Argon2id.">

## Settings
| Setting | Current | Recommended | NIST | Why |
|---|---|---|---|---|
| Minimum length | <8> | <15 (8 if MFA always on)> | SHALL | <...> |
| Maximum length | <20> | <64 or more> | SHOULD | <...> |
| Composition rules | <upper, lower, digit, symbol> | none | SHALL NOT | <...> |
| Expiry | <90 days> | none; reset on compromise | SHALL NOT | <...> |
| Blocklist | <none> | breached + dictionary + context words, full-password match | SHALL | <...> |
| Spaces / Unicode | <rejected> | accepted, NFC normalized | SHOULD | <...> |
| Paste / password managers | <blocked> | allowed | | <...> |
| Hints / security questions | <yes> | removed | SHALL NOT | <...> |
| Failed attempts | <lock after 3 for 60 min> | throttle, <= 100 consecutive failures | SHALL | <...> |
| Strength guidance | <none> | meter + rejection reason | SHALL | <...> |
| Storage | <PBKDF2-SHA256, 10000> | <Argon2id m=19 MiB t=2 p=1> | SHALL (salted hash) | <...> |

## What the samples show (made-up passwords only)
<Short table or sentence: e.g. "4 of 5 typical patterns (Password1!, Summer2025!) pass today's rules at ~20 bits; a random 4-word passphrase (~54 bits) is rejected today and accepted under the new policy.">

## Rollout
1. <Day 0: remove expiry, allow paste and spaces, enable strength meter>
2. <Week 1: blocklist on new passwords and changes; show the rejection reason>
3. <Week 2: raise minimum length for new passwords; existing users at next change>
4. <Rehash to Argon2id at next login; force reset for dormant accounts after 6 months>
5. <Remove hints and security questions; switch recovery to verified email + recovery codes>

## Communication to users
<2-3 sentences: longer is stronger, passphrases welcome, password managers welcome, no more forced changes>

## Open questions
<MFA coverage, identity provider limits, compliance frameworks that still mention expiry (check current versions; many now follow NIST)>
FILE:examples/legacy-portal-policy.json
{
  "name": "Northwind customer portal (legacy policy)",
  "single_factor": true,
  "min_length": 8,
  "max_length": 20,
  "composition": {"upper": true, "lower": true, "digit": true, "symbol": true},
  "expiry_days": 90,
  "blocklist": {"enabled": false},
  "allow_spaces": false,
  "allow_unicode": false,
  "allow_paste": false,
  "truncate_at": null,
  "hints": true,
  "security_questions": true,
  "strength_guidance": false,
  "rate_limit": {"max_failed_attempts": 3, "lockout_minutes": 60},
  "storage": {"algorithm": "PBKDF2-SHA256", "iterations": 10000, "salted": true}
}
FILE:examples/synthetic-samples.txt
# Made-up sample passwords for the review. NEVER put real passwords in this file.
Password1!
Summer2025!
Northwind#1
Qwerty123$
P@ssw0rd2026
tundra velvet orbit cactus
vT9#qLm2!xR4wZp7
glacier-mango-quietly-violin-ember
FILE:scripts/pw_policy.py
#!/usr/bin/env python3
"""Password policy and entropy checker (Python 3 standard library only).

Checks a password policy config against NIST SP 800-63B-4 (2025) password guidance and estimates
the strength of SYNTHETIC sample passwords. Never use real passwords: samples are masked in the
output unless --show-samples is given, and nothing is stored or sent anywhere.

Policy JSON (all keys optional except min_length):
  {"name": "Customer portal", "single_factor": true,        # password alone, no MFA
   "min_length": 8, "max_length": 20,
   "composition": {"upper": true, "lower": true, "digit": true, "symbol": true},
   "expiry_days": 90,
   "blocklist": {"enabled": true, "breached": true, "context_words": ["acme", "portal"]},
   "allow_spaces": true, "allow_unicode": true, "unicode_normalization": "NFC",
   "allow_paste": true, "truncate_at": null, "hints": false, "security_questions": false,
   "strength_guidance": true,
   "rate_limit": {"max_failed_attempts": 10, "lockout_minutes": 15},
   "storage": {"algorithm": "argon2id", "memory_kib": 19456, "iterations": 2, "salted": true}}
Policy findings (severity):
  HIGH   MIN_LENGTH          < 15 for single-factor passwords, < 8 with MFA (SHALL)
  HIGH   COMPOSITION_RULES   required character classes (SHALL NOT)
  HIGH   PERIODIC_EXPIRY     forced change every N days (SHALL NOT; change only on compromise)
  HIGH   NO_BLOCKLIST        no blocklist check of the full password (SHALL)
  HIGH   HINTS / SECURITY_QUESTIONS   password hints or KBA prompts (SHALL NOT)
  HIGH   TRUNCATION          only part of the password is verified (SHALL verify the whole)
  HIGH   NO_RATE_LIMIT       no throttling of failed attempts (SHALL; at most 100 in a row)
  HIGH   WEAK_STORAGE        plaintext, reversible encryption, MD5/SHA-x or unsalted hashes
  MEDIUM WEAK_KDF_PARAMS     below OWASP minimums (PBKDF2-SHA256 600000, bcrypt cost 10,
                             Argon2id 19 MiB / t=2, scrypt N=2^17)
  MEDIUM BCRYPT_72_BYTES     bcrypt ignores bytes after 72 but max length allows more
  MEDIUM MAX_LENGTH          maximum below 64 (SHOULD allow at least 64)
  MEDIUM NO_SPACES           spaces not accepted (SHOULD accept printing ASCII and space)
  MEDIUM PASTE_BLOCKED       paste / password managers blocked (SHOULD allow)
  MEDIUM NO_GUIDANCE         no strength guidance shown to users (SHALL offer guidance)
  MEDIUM BLOCKLIST_THIN      blocklist without breached passwords or context words
  LOW    NO_UNICODE          Unicode not accepted (SHOULD)
  LOW    NO_NORMALIZATION    Unicode accepted without NFC normalization (SHOULD)
  LOW    LOCKOUT_STRICT      lockout after < 5 attempts: easy denial of service, use throttling
Sample findings:
  HIGH   SAMPLE_WEAK_ACCEPTED  a blocklisted or < 36-bit sample passes the current policy
Entropy (bits): charset = length x log2(pool of character classes used); pattern = a simple
guess-model estimate that charges little for common words, leet, years, keyboard runs, repeats
and passphrase words, and log2(pool) for every other character (per word log2(7776) = 12.9 bits at most). Rating uses the pattern estimate:
< 28 very weak, < 36 weak, < 60 fair, < 80 strong, else very strong.
Usage:
  python3 pw_policy.py policy.json
  python3 pw_policy.py policy.json --samples synthetic.txt [--context northwind,portal] [--blocklist list.txt] [--json]
  python3 pw_policy.py --self-test
Exit code: 0 no HIGH findings, 1 HIGH findings, 2 bad input.
"""
import argparse
import json
import math
import re
import sys
import unicodedata

SEV_ORDER = {"HIGH": 0, "MEDIUM": 1, "LOW": 2}
COMMON = """password passw0rd welcome letmein qwerty qwertz azerty admin administrator login master
dragon monkey sunshine princess football baseball soccer hockey shadow superman batman iloveyou
trustno1 secret summer winter spring autumn fall monday friday january october december love
hello freedom whatever charlie michael jessica jordan pepper ginger cookie chocolate flower
computer internet google apple samsung starwars pokemon matrix killer hunter ranger thunder
tiger lion eagle dolphin falcon soccer liverpool chelsea arsenal barcelona madrid london paris
berlin newyork america canada company office service portal change changeme default guest user
test testing temp temporary access security system server database root toor manager support
student school teacher family mother father daddy mommy baby angel blessed jesus god heaven
money dollar euro bitcoin crypto summer2024 welcome1 password1 password123 abc123 iloveyou1
""".split()
COMMON_SET = set(COMMON)
TOP_BLOCK = set(COMMON) | {"123456", "12345678", "123456789", "1234567890", "111111", "000000",
                           "123123", "654321", "qwerty123", "1q2w3e4r", "zaq12wsx", "p@ssw0rd",
                           "password1!", "welcome123", "admin123", "letmein1", "qwertyuiop"}
LEET = str.maketrans({"@": "a", "4": "a", "0": "o", "1": "i", "!": "i", "3": "e", "$": "s",
                      "5": "s", "7": "t", "+": "t", "8": "b", "9": "g"})
ROWS = ["qwertyuiop", "asdfghjkl", "zxcvbnm", "1234567890", "abcdefghijklmnopqrstuvwxyz", "qwertzuiop", "azertyuiop"]
WORD_BITS = math.log2(7776)


class DataError(ValueError):
    pass


def char_pool(pw):
    pool = 0
    if re.search(r"[a-z]", pw):
        pool += 26
    if re.search(r"[A-Z]", pw):
        pool += 26
    if re.search(r"[0-9]", pw):
        pool += 10
    if re.search(r"[ -/:-@\[-`{-~]", pw):
        pool += 33
    if any(ord(c) > 126 for c in pw):
        pool += 100
    return pool or 1


def class_bits(c):
    if c.islower() and c.isascii():
        return math.log2(26)
    if c.isupper() and c.isascii():
        return math.log2(26)
    if c.isdigit():
        return math.log2(10)
    if ord(c) > 126:
        return math.log2(100)
    return math.log2(33)


def charset_bits(pw):
    return len(pw) * math.log2(char_pool(pw))


def seq_len(s, i):
    """Length of a keyboard/alphabet run (forward or backward) starting at i."""
    best = 1
    low = s.lower()
    for row in ROWS:
        for r in (row, row[::-1]):
            j = r.find(low[i]) if low[i] in r else -1
            if j < 0:
                continue
            n = 1
            while i + n < len(low) and j + n < len(r) and low[i + n] == r[j + n]:
                n += 1
            best = max(best, n)
    return best


def pattern_bits(pw, context=()):
    """Greedy left-to-right guess model. Returns (bits, notes)."""
    notes = []
    vocab = COMMON_SET | {w.lower() for w in context if len(w) >= 3}
    words = [w for w in re.split(r"[\s\-_.]+", pw) if w]
    if len(words) >= 3 and all(re.fullmatch(r"[A-Za-z]{3,}", w) for w in words):
        bits = sum(1.0 if w.lower() in vocab else WORD_BITS for w in words) + math.log2(4)
        notes.append(f"passphrase of {len(words)} words (upper bound if words were picked at random)")
        return min(bits, charset_bits(pw)), notes
    i, bits, low = 0, 0.0, pw.lower()
    brute = math.log2(char_pool(pw))
    while i < len(pw):
        # dictionary word (with leet), longest first
        hit = None
        for L in range(min(len(pw) - i, 14), 3, -1):
            chunk = low[i:i + L]
            plain = chunk.translate(LEET)
            if plain in vocab:
                hit = (L, plain, chunk != plain)
                break
        run = seq_len(pw, i)
        if hit and run < hit[0]:
            L, word, leet = hit
            b = math.log2(len(COMMON)) + (1 if pw[i].isupper() else 0) + (2 if leet else 0)
            notes.append(f"common word '{word}'" + (" (leet)" if leet else ""))
            bits += b
            i += L
            continue
        m = re.match(r"(19[5-9]\d|20[0-3]\d)", pw[i:])
        if m:
            notes.append(f"year {m.group(1)}")
            bits += math.log2(90)
            i += 4
            continue
        n = run
        if n >= 3:
            notes.append(f"keyboard/alphabet run '{pw[i:i + n]}'")
            bits += math.log2(26) + math.log2(n)
            i += n
            continue
        r = 1
        while i + r < len(pw) and pw[i + r] == pw[i]:
            r += 1
        if r >= 3:
            notes.append(f"repeated '{pw[i]}' x{r}")
            bits += class_bits(pw[i]) + math.log2(r)
            i += r
            continue
        bits += brute
        i += 1
    if notes and re.search(r"[0-9!?.]{1,3}$", pw) and len(pw) > 4:
        bits -= 1.5
        notes.append("digits/symbol appended at the end (most common pattern)")
    return max(bits, 0.0), notes


def rating(bits):
    return ("very weak" if bits < 28 else "weak" if bits < 36 else "fair" if bits < 60
            else "strong" if bits < 80 else "very strong")


def crack_time(bits, rate):
    sec = 2 ** (bits - 1) / rate
    for unit, n in (("years", 31557600), ("days", 86400), ("hours", 3600), ("minutes", 60)):
        if sec >= n:
            v = sec / n
            return f"{v:.3g} {unit}" if v < 100 else f"{v:,.0f} {unit}" if v < 1e6 else f"{v:.1e} {unit}"
    return "instant" if sec < 1 else f"{sec:.0f} seconds"


def mask_pw(pw):
    if len(pw) <= 4:
        return "*" * len(pw)
    return pw[:2] + "*" * (len(pw) - 3) + pw[-1:]


def policy_accepts(policy, pw):
    reasons = []
    if len(pw) < int(policy.get("min_length", 0)):
        reasons.append("too short")
    mx = policy.get("max_length")
    if mx and len(pw) > int(mx):
        reasons.append("too long")
    comp = policy.get("composition") or {}
    for key, rx in (("upper", r"[A-Z]"), ("lower", r"[a-z]"), ("digit", r"[0-9]"), ("symbol", r"[^A-Za-z0-9\s]")):
        if comp.get(key) and not re.search(rx, pw):
            reasons.append(f"needs {key}")
    if " " in pw and policy.get("allow_spaces") is False:
        reasons.append("space not allowed")
    if any(ord(c) > 126 for c in pw) and policy.get("allow_unicode") is False:
        reasons.append("unicode not allowed")
    if (policy.get("blocklist") or {}).get("enabled") and pw.lower() in TOP_BLOCK:
        reasons.append("blocklisted")
    return not reasons, reasons


def core_word(low):
    """Strip leading/trailing digits and symbols, undo leet, keep letters: 'P@ssw0rd2026!' -> 'password'."""
    core = re.sub(r"^[\d\W_]+|[\d\W_]+$", "", low)
    return re.sub(r"[^a-z]", "", core.translate(LEET))


def blocklisted(pw, extra=(), context=()):
    low = unicodedata.normalize("NFC", pw).lower()
    if low in TOP_BLOCK or low in extra:
        return "common/breached password"
    core = core_word(low)
    for w in context:
        if w and len(w) >= 3 and w.lower() in core and len(low) - len(w) <= 6:
            return f"based on context word '{w}'"
    if core in COMMON_SET and len(low) - len(core) <= 6:
        return "common word with a few digits/symbols"
    return None


def check_policy(p):
    f = []

    def add(sev, code, msg):
        f.append({"severity": sev, "code": code, "message": msg})
    if "min_length" not in p:
        raise DataError("policy needs min_length")
    single = p.get("single_factor", True)
    mn = int(p["min_length"])
    need = 15 if single else 8
    if mn < need:
        add("HIGH", "MIN_LENGTH", f"minimum {mn} characters; NIST requires >= {need} for passwords used {'alone' if single else 'with MFA'}")
    comp = [k for k, v in (p.get("composition") or {}).items() if v]
    if comp:
        add("HIGH", "COMPOSITION_RULES", f"requires {', '.join(comp)}; composition rules SHALL NOT be imposed (they produce 'Password1!' patterns); rely on length + blocklist")
    if int(p.get("expiry_days") or 0) > 0:
        add("HIGH", "PERIODIC_EXPIRY", f"forced change every {p['expiry_days']} days; SHALL NOT expire periodically, force a change only on evidence of compromise")
    bl = p.get("blocklist") or {}
    if not bl.get("enabled"):
        add("HIGH", "NO_BLOCKLIST", "no blocklist; new passwords SHALL be checked in full against common, expected and breached passwords")
    elif not bl.get("breached") or not bl.get("context_words"):
        miss = [x for x, ok in (("breached passwords", bl.get("breached")), ("context words (service name, username)", bl.get("context_words"))) if not ok]
        add("MEDIUM", "BLOCKLIST_THIN", f"blocklist lacks {' and '.join(miss)}")
    if p.get("hints"):
        add("HIGH", "HINTS", "password hints are stored; SHALL NOT be accessible to unauthenticated users - remove them")
    if p.get("security_questions"):
        add("HIGH", "SECURITY_QUESTIONS", "security questions (KBA) SHALL NOT be used; offer recovery via a verified email/phone or recovery codes")
    if p.get("truncate_at"):
        add("HIGH", "TRUNCATION", f"only the first {p['truncate_at']} characters are checked; the whole password SHALL be verified")
    rl = p.get("rate_limit") or p.get("lockout")
    if not rl:
        add("HIGH", "NO_RATE_LIMIT", "no throttling of failed attempts; SHALL limit to at most 100 consecutive failures per account")
    else:
        n = int(rl.get("max_failed_attempts") or 0)
        if n > 100:
            add("HIGH", "NO_RATE_LIMIT", f"{n} failed attempts allowed; at most 100 consecutive failures")
        elif 0 < n < 5:
            add("LOW", "LOCKOUT_STRICT", f"lockout after {n} attempts lets anyone lock users out; prefer growing delays, CAPTCHA or risk checks before a hard lock")
    st = p.get("storage") or {}
    alg = str(st.get("algorithm", "")).lower().replace("-", "").replace("_", "")
    if not alg:
        add("MEDIUM", "WEAK_STORAGE", "storage algorithm not stated; confirm a salted password hashing function (Argon2id, scrypt, bcrypt, PBKDF2)")
    elif alg in ("plaintext", "plain", "none", "aes", "encrypted", "base64", "md5", "sha1", "sha256", "sha512", "ntlm"):
        add("HIGH", "WEAK_STORAGE", f"{st.get('algorithm')} is not a password hashing function; use Argon2id (or scrypt, bcrypt, PBKDF2) with a unique salt and rehash on next login")
    else:
        if st.get("salted") is False:
            add("HIGH", "WEAK_STORAGE", "hashes are not salted; every password needs a unique random salt")
        it = int(st.get("iterations") or 0)
        if alg.startswith("pbkdf2") and it < 600000:
            add("MEDIUM", "WEAK_KDF_PARAMS", f"PBKDF2 with {it} iterations; OWASP suggests >= 600000 for PBKDF2-HMAC-SHA256")
        if alg == "bcrypt":
            if int(st.get("cost") or 0) < 10:
                add("MEDIUM", "WEAK_KDF_PARAMS", f"bcrypt cost {st.get('cost')}; use >= 10 (tune to ~250 ms)")
            if int(p.get("max_length") or 999) > 72:
                add("MEDIUM", "BCRYPT_72_BYTES", "bcrypt ignores input after 72 bytes; pre-hash (HMAC-SHA256, base64) or switch to Argon2id")
        if alg.startswith("argon2") and (int(st.get("memory_kib") or 0) < 19456 or it < 2):
            add("MEDIUM", "WEAK_KDF_PARAMS", "Argon2id below m=19456 KiB, t=2, p=1 (OWASP minimum)")
        if alg == "scrypt" and int(st.get("n") or 0) < 2 ** 17:
            add("MEDIUM", "WEAK_KDF_PARAMS", "scrypt N below 2^17 (r=8, p=1)")
    mx = p.get("max_length")
    if mx and int(mx) < 64:
        add("MEDIUM", "MAX_LENGTH", f"maximum {mx} characters blocks passphrases and generated passwords; allow at least 64")
    if p.get("allow_spaces") is False:
        add("MEDIUM", "NO_SPACES", "spaces rejected; accept all printing ASCII characters and space so passphrases work")
    if p.get("allow_paste") is False:
        add("MEDIUM", "PASTE_BLOCKED", "paste blocked; allow paste and autofill so password managers work")
    if p.get("strength_guidance") is False:
        add("MEDIUM", "NO_GUIDANCE", "no guidance when a password is rejected; SHALL help users choose (strength meter, reason for rejection)")
    if p.get("allow_unicode") is False:
        add("LOW", "NO_UNICODE", "Unicode rejected; SHOULD accept it (count each code point as one character)")
    elif p.get("allow_unicode") and str(p.get("unicode_normalization", "")).upper() != "NFC":
        add("LOW", "NO_NORMALIZATION", "Unicode accepted without NFC normalization before hashing; the same password typed on two devices may not match")
    return f


def check_samples(policy, samples, extra=(), context=()):
    rows, f = [], []
    ctx = (policy.get("blocklist") or {}).get("context_words") or []
    if isinstance(ctx, bool):
        ctx = []
    ctx = list(ctx) + list(context)
    for pw in samples:
        cb = charset_bits(pw)
        pb, notes = pattern_bits(pw, ctx)
        bl = blocklisted(pw, extra, ctx)
        ok, why = policy_accepts(policy, pw)
        single = policy.get("single_factor", True)
        nist_ok = bl is None and len(pw) >= (15 if single else 8)
        row = {"sample": pw, "length": len(pw), "charset_bits": round(cb, 1), "pattern_bits": round(pb, 1),
               "rating": "very weak" if bl else rating(pb), "blocklist": bl, "policy_accepts": ok,
               "policy_reasons": why, "nist_ok": nist_ok, "notes": notes,
               "offline_fast": crack_time(0 if bl else pb, 1e10), "offline_slow": crack_time(0 if bl else pb, 1e4)}
        rows.append(row)
        if ok and (bl or pb < 36):
            f.append({"severity": "HIGH", "code": "SAMPLE_WEAK_ACCEPTED", "sample": pw,
                      "message": f"sample {{s}} passes the current policy but is {'blocklisted (' + bl + ')' if bl else rating(pb) + f' (~{pb:.0f} bits)'}"})
    return rows, f


def render(policy, findings, rows, show):
    def s(pw):
        return pw if show else mask_pw(pw)
    out = [f"# Password policy review: {policy.get('name', 'policy')}", "",
           f"Basis: NIST SP 800-63B-4 (2025), passwords used {'as the only factor' if policy.get('single_factor', True) else 'with MFA'}",
           f"Findings: {sum(x['severity'] == 'HIGH' for x in findings)} HIGH, {sum(x['severity'] == 'MEDIUM' for x in findings)} MEDIUM, {sum(x['severity'] == 'LOW' for x in findings)} LOW", ""]
    for x in findings:
        msg = x["message"].replace("{s}", s(x["sample"])) if "sample" in x else x["message"]
        out.append(f"- {x['severity']} {x['code']}: {msg}")
    if rows:
        out += ["", "## Synthetic samples" + ("" if show else " (masked; --show-samples to print)"),
                "| Sample | Len | Charset bits | Pattern bits | Rating | Current policy | NIST verdict | Offline fast hash / slow hash |",
                "|---|---|---|---|---|---|---|---|"]
        for r in rows:
            cur = "accepts" if r["policy_accepts"] else "rejects (" + ", ".join(r["policy_reasons"]) + ")"
            nist = "ok" if r["nist_ok"] else ("reject: " + r["blocklist"] if r["blocklist"] else "reject: too short")
            out.append(f"| {s(r['sample'])} | {r['length']} | {r['charset_bits']} | {r['pattern_bits']} | {r['rating']} | {cur} | {nist} | {r['offline_fast']} / {r['offline_slow']} |")
        out += ["", "Charset bits overstate human-chosen passwords; pattern bits are the better guide. Offline times assume 1e10 guesses/s (fast hash) and 1e4 guesses/s (Argon2id/bcrypt), median case."]
    out += ["", "Samples must be made up for the review. Never paste or store real passwords."]
    return "\n".join(out)


def self_test():
    results = []

    def check(name, cond):
        results.append(cond)
        print(("PASS " if cond else "FAIL ") + name)

    def codes(**over):
        p = {"min_length": 15, "max_length": 64, "blocklist": {"enabled": True, "breached": True, "context_words": ["acme"]},
             "allow_spaces": True, "allow_unicode": True, "unicode_normalization": "NFC", "allow_paste": True,
             "strength_guidance": True, "rate_limit": {"max_failed_attempts": 10},
             "storage": {"algorithm": "argon2id", "memory_kib": 19456, "iterations": 2, "salted": True}}
        p.update(over)
        return [x["code"] for x in check_policy(p)]
    check("compliant policy has no findings", codes() == [])
    check("min 8 single factor HIGH", "MIN_LENGTH" in codes(min_length=8))
    check("min 8 with MFA ok", "MIN_LENGTH" not in codes(min_length=8, single_factor=False))
    check("min 6 with MFA HIGH", "MIN_LENGTH" in codes(min_length=6, single_factor=False))
    check("composition HIGH", "COMPOSITION_RULES" in codes(composition={"upper": True, "symbol": True}))
    check("expiry HIGH", "PERIODIC_EXPIRY" in codes(expiry_days=90))
    check("no blocklist HIGH", "NO_BLOCKLIST" in codes(blocklist={"enabled": False}))
    check("thin blocklist MEDIUM", "BLOCKLIST_THIN" in codes(blocklist={"enabled": True}))
    check("hints + KBA HIGH", {"HINTS", "SECURITY_QUESTIONS"} <= set(codes(hints=True, security_questions=True)))
    check("truncation HIGH", "TRUNCATION" in codes(truncate_at=16))
    check("no rate limit HIGH", "NO_RATE_LIMIT" in codes(rate_limit=None))
    check("lockout 3 LOW", "LOCKOUT_STRICT" in codes(rate_limit={"max_failed_attempts": 3}))
    check("sha256 HIGH", "WEAK_STORAGE" in codes(storage={"algorithm": "SHA-256", "salted": True}))
    check("unsalted HIGH", "WEAK_STORAGE" in codes(storage={"algorithm": "pbkdf2-sha256", "iterations": 600000, "salted": False}))
    check("pbkdf2 low iterations MEDIUM", "WEAK_KDF_PARAMS" in codes(storage={"algorithm": "PBKDF2-SHA256", "iterations": 10000}))
    check("bcrypt cost 8 + 72 bytes", {"WEAK_KDF_PARAMS", "BCRYPT_72_BYTES"} <= set(codes(storage={"algorithm": "bcrypt", "cost": 8}, max_length=128)))
    check("max 20 MEDIUM", "MAX_LENGTH" in codes(max_length=20))
    check("spaces/paste/guidance MEDIUM", {"NO_SPACES", "PASTE_BLOCKED", "NO_GUIDANCE"} <= set(codes(allow_spaces=False, allow_paste=False, strength_guidance=False)))
    check("no unicode LOW", "NO_UNICODE" in codes(allow_unicode=False))
    check("no NFC LOW", "NO_NORMALIZATION" in codes(unicode_normalization=None))
    check("charset bits 8 lowercase", abs(charset_bits("abcdefgh") - 8 * math.log2(26)) < 1e-9)
    check("charset pool all classes", char_pool("aA1!") == 95)
    check("leet word cheap", pattern_bits("P@ssw0rd")[0] < 15)
    check("year + word weak", pattern_bits("Summer2025!")[0] < 28)
    check("keyboard run cheap", pattern_bits("qwertyuiop")[0] < 10)
    check("repeat cheap", pattern_bits("aaaaaaaaaa")[0] < 10)
    check("random 16 strong", pattern_bits("vT9#qLm2!xR4wZp7")[0] > 80)
    check("4 random words ~ 53 bits", 50 < pattern_bits("tundra-velvet-orbit-cactus")[0] < 56)
    check("common words passphrase weak", pattern_bits("love summer football")[0] < 10)
    check("blocklisted exact", blocklisted("Password1!") is not None)
    check("context word blocked", blocklisted("Acme2026!", context=["acme"]) is not None)
    check("leet + year blocked", blocklisted("P@ssw0rd2026") is not None)
    check("context word cheap in pattern", pattern_bits("Northwind#1", ["northwind"])[0] < 28)
    check("long random not blocked", blocklisted("vT9#qLm2!xR4wZp7") is None)
    pol = {"min_length": 8, "composition": {"upper": True, "lower": True, "digit": True, "symbol": True}}
    rows, f = check_samples(pol, ["Password1!", "tundra velvet orbit cactus"])
    check("composition policy accepts Password1!", rows[0]["policy_accepts"] and f and f[0]["code"] == "SAMPLE_WEAK_ACCEPTED")
    check("composition policy rejects passphrase", not rows[1]["policy_accepts"] and rows[1]["nist_ok"])
    check("mask hides middle", mask_pw("Password1!") == "Pa*******!")
    check("crack time units", crack_time(0, 1e10) == "instant" and "years" in crack_time(80, 1e10))
    try:
        check_policy({})
        check("missing min_length rejected", False)
    except DataError:
        check("missing min_length rejected", True)
    print(f"{sum(results)}/{len(results)} passed")
    return 0 if all(results) else 1


def main():
    ap = argparse.ArgumentParser(description="Password policy and entropy checker (NIST SP 800-63B-4)")
    ap.add_argument("policy", nargs="?", help="policy JSON")
    ap.add_argument("--samples", help="file with SYNTHETIC sample passwords, one per line (# = comment)")
    ap.add_argument("--blocklist", help="extra blocklist file, one password per line")
    ap.add_argument("--context", default="", help="comma-separated context words (service name, brand, usernames)")
    ap.add_argument("--show-samples", action="store_true", help="print samples unmasked")
    ap.add_argument("--json", action="store_true")
    ap.add_argument("--self-test", action="store_true")
    a = ap.parse_args()
    if a.self_test:
        return self_test()
    if not a.policy:
        ap.error("give a policy JSON or --self-test")
    try:
        with open(a.policy, encoding="utf-8") as fh:
            policy = json.load(fh)
        findings = check_policy(policy)
        rows = []
        if a.samples:
            with open(a.samples, encoding="utf-8") as fh:
                samples = [l.rstrip("\n") for l in fh if l.strip() and not l.startswith("#")]
            extra = set()
            if a.blocklist:
                with open(a.blocklist, encoding="utf-8") as fh:
                    extra = {l.strip().lower() for l in fh if l.strip()}
            rows, sf = check_samples(policy, samples, extra, [w.strip() for w in a.context.split(",") if w.strip()])
            findings += sf
    except (OSError, ValueError, DataError) as e:
        print(f"error: {e}", file=sys.stderr)
        return 2
    findings.sort(key=lambda x: SEV_ORDER[x["severity"]])
    if a.json:
        if not a.show_samples:
            for r in rows:
                r["sample"] = mask_pw(r["sample"])
            for x in findings:
                if "sample" in x:
                    x["sample"] = mask_pw(x["sample"])
                    x["message"] = x["message"].replace("{s}", x["sample"])
        print(json.dumps({"findings": findings, "samples": rows}, indent=2))
    else:
        print(render(policy, findings, rows, a.show_samples))
    return 1 if any(x["severity"] == "HIGH" for x in findings) else 0


if __name__ == "__main__":
    sys.exit(main())
SecurityComplianceAuthentication+1
F@f
0
Restaurant Menu Allergen Matrix Builder (JSON)
Text

Turn a cafe or restaurant menu and recipe notes into a strict JSON allergen package: a dish-by-allergen matrix that never guesses 'free', hidden allergen sources, shared fryer and board cross-contact risks, supplier questions, kitchen controls, staff answer scripts, and safe substitutions.

1{
2 "role": "Food safety consultant who builds clear, auditable allergen information for small restaurants and cafes",
3 "task": "Turn my menu and recipe notes into a single strict JSON allergen package: a dish-by-allergen matrix based only on the ingredients I list, hidden-allergen warnings, cross-contact risks in my kitchen, open questions for suppliers, staff answer scripts, and safe substitution ideas. Never guess that a dish is allergen-free.",
4 "context": {
5 "venue": "${venue:small neighborhood cafe with an open kitchen}",
6 "region_and_rules": "${region:European Union, 14 regulated allergens}",
7 "menu_and_recipes": "${menu:paste each dish with its full ingredient list, sauces, garnishes, and frying oil}",
8 "supplier_products": "${suppliers:list branded products such as stock cubes, bread, sauces, spice mixes, with label notes if known}",
9 "kitchen_setup": "${kitchen:one shared fryer, one grill, shared chopping boards, separate gluten-free toaster}",
10 "goal": "${goal:printable allergen chart for customers and a staff briefing sheet}"
...+110 more lines
JSONRestaurantCompliance+2
F@f
0
Dependency License Audit
Skill

Audits the licenses of your project's dependencies for how you actually ship (SaaS, distributed app or library, or internal tool): normalizes license names to SPDX, resolves OR and AND expressions, flags missing, AGPL, GPL, source-available, and incompatible licenses, and writes a ranked fix plan and notices list. Includes a tested stdlib Python auditor.

---
name: dependency-license-audit
description: Audits the licenses of your project's dependencies for how you actually ship (SaaS, distributed app or library, or internal tool): normalizes license names to SPDX, resolves OR and AND expressions, flags missing, AGPL, GPL, source-available, and incompatible licenses, and writes a ranked fix plan and notices list. Includes a tested stdlib Python auditor.
---

# Dependency License Audit

You help engineering teams find license problems in their dependencies before a release, an acquisition review, or a customer security questionnaire finds them. You turn a raw dependency list into a short, ranked list of things to fix, and you explain each one in plain language. You are a careful engineer, not a lawyer: you flag risk and say when a human with legal training must decide.

## Files in this skill

- `scripts/audit_licenses.py` - normalizes and classifies every dependency license and rates it for the chosen distribution model (Python 3 standard library only)
- `references/license-categories.md` - what permissive, weak copyleft, strong copyleft, network copyleft, and source-available mean in practice, with common SPDX ids
- `references/remediation-playbook.md` - how to fix each kind of finding, from replacing a package to adding notices
- `templates/license-audit-report.md` - the report layout
- `examples/example-saas-audit.md` - a worked audit of a Node.js SaaS backend

## Workflow

### 1. Understand how the project is shipped
Ask, or infer and state as an assumption:
- Project license: proprietary (closed source) or an open source license (SPDX id).
- Distribution: `saas` (users only reach it over a network), `distributed` (mobile or desktop apps, on-prem installs, devices, SDKs, published libraries, container images given to customers), or `internal` (only employees use it).
- Any company policy: always-allowed and always-blocked licenses.
The same dependency can be fine for one model and a blocker for another, so never skip this step.

### 2. Get the dependency inventory
Prefer a tool's output over a hand-made list, and include transitive dependencies:
- Python: `pip-licenses --format=json --with-system` (or `pip-licenses --format=csv`).
- Node.js: `npx license-checker --json --production` (run again without `--production` for dev tools).
- Anything else: a CSV with `name,version,license,scope` exported from an SBOM or the package manager.
Mark build, test, and lint tools as `scope=dev`; they are not shipped, so their findings drop to INFO.

### 3. Run the audit
```bash
python3 scripts/audit_licenses.py deps.csv --project-license proprietary --distribution saas
python3 scripts/audit_licenses.py licenses.json --distribution distributed --deny AGPL-3.0-only
python3 scripts/audit_licenses.py deps.csv --json
```
The script prints severity counts, a table of every package with its normalized license and category, findings with reasons, version-to-version license changes, and the licenses that need text in your third-party notices. Exit code 1 means at least one HIGH finding.

If you cannot run the script, classify each license by hand with `references/license-categories.md` and say so in the report.

### 4. Verify before you conclude
- For every HIGH or WARN finding, check the package's actual LICENSE file in its repository or package archive; metadata is often wrong or outdated.
- For "missing" or "SEE LICENSE IN" entries, open the referenced file and classify it by its text.
- For dual-licensed packages (OR), record which option you choose.
- For packages whose license changed between versions, confirm which version is actually installed (lock file).

### 5. Recommend and report
Use `references/remediation-playbook.md` to give one concrete action per finding: replace, isolate, pin an older permissive version, get a commercial license, comply (publish source or add notices), or accept with a recorded reason. Fill in `templates/license-audit-report.md`, as in `examples/example-saas-audit.md`.

## Rules
- Never say a license "is fine" or "is illegal" as a legal conclusion. Say what the license usually requires and when to ask legal counsel.
- Do not guess a license from a package name or popularity. Unknown stays unknown until someone reads the license text.
- Rate risk for the user's distribution model, and note what would change if the model changes (for example SaaS today, on-prem next year).
- Keep the report short: blockers first, then obligations (notices, source offers), then the clean list as a count.
- Treat the audit as a snapshot; recommend running it in CI on every dependency change.
FILE:references/license-categories.md
# License categories in practice

Severity in the script depends on the category and on how the project is shipped. This page explains the categories in plain language. It is an engineering summary, not legal advice.

## Public domain and near public domain
SPDX: `0BSD`, `Unlicense`, `CC0-1.0`, `MIT-0`, `WTFPL`
- No meaningful obligations. Keeping a notice is still good practice.

## Permissive
SPDX: `MIT`, `ISC`, `BSD-2-Clause`, `BSD-3-Clause`, `Apache-2.0`, `Zlib`, `BSL-1.0` (Boost), `PSF-2.0`, `Python-2.0`, `CC-BY-4.0` (data such as caniuse-lite)
- Use, modify, and ship in closed source products.
- Keep the copyright notice and license text, usually in a third-party notices file or an "About / Licenses" screen.
- Apache-2.0 also requires keeping any NOTICE file, stating significant changes to its files, and includes a patent grant that ends if you sue over patents in that code.
- BSD-3-Clause forbids using the authors' names to promote your product.

## Weak copyleft (file or library level)
SPDX: `LGPL-2.1-*`, `LGPL-3.0-*`, `MPL-2.0`, `EPL-1.0`, `EPL-2.0`, `CDDL-1.0`, `CDDL-1.1`, GPL with a linking exception (for example `GPL-2.0-only WITH Classpath-exception-2.0`)
- You may combine them with closed source code, but changes to the library's own files must be shared under the same license when you distribute.
- LGPL: users must be able to replace the library with their own version. Dynamic linking (shared library, separate jar, npm package) normally makes this easy; static linking or bundling into one binary needs care.
- MPL-2.0: copyleft applies per file. Keep MPL files separate and publish changes to those files.

## Strong copyleft
SPDX: `GPL-2.0-only`, `GPL-2.0-or-later`, `GPL-3.0-only`, `GPL-3.0-or-later`
- If you distribute software that includes or links GPL code, the combined work must be offered under the GPL with its source code.
- Running GPL software on your own servers and letting users reach it over a network is not distribution, so pure SaaS use is usually allowed. Shipping an app, an on-prem installer, a device firmware, or a container image to customers is distribution.
- Version matters: `GPL-2.0-only` code cannot be combined with GPL-3.0 or Apache-2.0 code in one work. `-or-later` gives more room.

## Network copyleft
SPDX: `AGPL-3.0-only`, `AGPL-3.0-or-later`, `SSPL-1.0` (not OSI approved)
- Like the GPL, plus: if users interact with a modified version over a network, you must offer them its source code.
- For a closed source SaaS product this is the most common blocker. Even unmodified use triggers internal reviews at most companies.
- SSPL goes further: offering the software as a service can require releasing the source of your whole service stack.

## Source-available and non-commercial
SPDX or names: `BUSL-1.1` (Business Source License), `Elastic-2.0`, Commons Clause add-ons, `CC-BY-NC-*`, `PolyForm-Noncommercial-1.0.0`
- Source is visible, but use is restricted: often no competing hosted service, no production use above a limit, or no commercial use at all, sometimes until a change date.
- Always needs a review of the exact terms. Many of these switch to an open license after a few years, so an older or newer version may differ.

## Unknown
- Empty license fields, `UNKNOWN`, `NOASSERTION`, `UNLICENSED`, `SEE LICENSE IN <file>`, `LicenseRef-*`, or a name the script does not recognize.
- "No license" means all rights reserved: you have no permission to use it. Find the real terms or replace the package.

## Expressions
- `MIT OR Apache-2.0`: you may choose either; pick the one that suits you and record the choice.
- `MIT AND BSD-3-Clause`: you must follow both; the strictest one sets the category.
- `GPL-2.0-only WITH <exception>`: the exception narrows the copyleft; read it.
FILE:references/remediation-playbook.md
# Remediation playbook

Pick one action per finding and write it down with an owner. Prefer the cheapest action that removes the risk.

## Order of work
1. Unknown and missing licenses (you may have no right to use the code at all).
2. Network copyleft and source-available packages in shipped or hosted code.
3. Strong copyleft in distributed products, and version incompatibilities in open source projects.
4. Weak copyleft obligations (linking, publishing changes).
5. Notices for everything else.

## Actions

### Find the real license
- Open the package's repository and archive, read LICENSE, COPYING, or the header of the main source file.
- Check whether the metadata is just stale (a common case for old packages and forks).
- If there is truly no license, ask the maintainer to add one (link to choosealicense.com in the request) or replace the package.

### Replace the package
- Search for a maintained alternative with a permissive license and similar API.
- Estimate effort in hours and add it to the backlog with the release it blocks.
- For transitive dependencies, look for the direct dependency that pulls it in; a different version or a configuration flag often drops it.

### Pin a version under the old license
- When a project switched from a permissive license to source-available (or the reverse), the old versions keep their old license.
- Pinning is a short-term fix: no security updates. Schedule a proper replacement.

### Isolate it
- Run the copyleft tool as a separate process or service that talks to your code over a command line, HTTP, or a queue, instead of linking it into your code.
- Keep it unmodified if possible. Document the boundary.
- This is a common way to use GPL command line tools, but have legal counsel confirm it for AGPL and SSPL.

### Buy a commercial license
- Many dual-licensed projects (open source plus commercial) sell a license that removes copyleft obligations. Note the price and renewal terms.

### Comply
- Weak copyleft: keep the library as a separate, replaceable file or package; publish any changes to its own files; include its license.
- GPL in a distributed product: only if the whole product can be open source under compatible terms. This is a business decision, not an engineering one.
- AGPL in a hosted service: offer the corresponding source to users of the service, including your changes.

### Accept with a recorded reason
- Dev-only tools (linters, test runners, build tools) that never ship are usually fine. Record "dev only, not distributed".
- Internal-only use of GPL or AGPL tools is usually fine. Record who uses it and that it is not exposed to outside users.

## Third-party notices
- Generate a notices file from the inventory: package, version, license, copyright line, full license text (one copy per distinct license text).
- Include Apache NOTICE files as they are.
- Ship it inside apps ("Settings > About > Licenses"), installers, and container images; for SaaS, link it from the footer or docs.

## Keep it clean
- Run the audit in CI on every change to a lock file and fail the build on HIGH.
- Keep an allow list (for example MIT, BSD, ISC, Apache-2.0) and a deny list (for example AGPL-3.0, SSPL-1.0, BUSL-1.1) agreed with legal counsel, and pass them with `--allow` and `--deny`.
FILE:templates/license-audit-report.md
# Dependency License Audit: <project name>

Date: <YYYY-MM-DD>
Project license: <proprietary | SPDX id>
Distribution: <saas | distributed | internal> (<one line: how users get the software>)
Inventory source: <tool and command, lock file commit>
Packages audited: <n> (<runtime n>, <dev n>)

## Summary
- Blockers (HIGH): <n> - <one line naming them>
- Obligations (WARN): <n> - <one line>
- Notes (INFO): <n>
- Clean (OK): <n>
- Verdict: <ready to ship | ship after fixes | blocked> because <reason>.

## Blockers
| Package | Version | License (as found) | Category | Why it matters for us | Action | Owner | Due |
|---|---|---|---|---|---|---|---|
| | | | | | | | |

## Obligations
| Package | License | What we must do | Done? |
|---|---|---|---|
| | | | |

## Verified by hand
- <package>: metadata said <x>, LICENSE file says <y>.

## Decisions and assumptions
- Dual-licensed packages and the option chosen: <package: option>
- Accepted risks with reason: <package: reason, approved by>
- Assumptions: <for example "the admin dashboard is internal only">

## What changes if we change how we ship
- <for example: "If we ship an on-prem version, readline-sync (GPL-3.0) becomes a blocker.">

## Third-party notices
Licenses that need full text in the notices file: <list>
Notices file location: <path or URL>

## Next audit
Run in CI on every lock file change; full review before <next release or date>.

_This report is an engineering triage, not legal advice. Blockers must be confirmed by legal counsel before relying on any exception._
FILE:examples/example-saas-audit.md
# Example: license audit of a Node.js SaaS backend

## The request
"We're a closed source B2B SaaS. Enterprise customers keep sending security questionnaires asking about open source licenses, and next year we may sell an on-prem version. Here is our dependency export. Anything we should worry about?"

Inventory (`deps.csv`, exported from the lock file, 18 rows):
```
name,version,license,scope
express,4.19.2,MIT,runtime
lodash,4.17.21,MIT,runtime
pg,8.12.0,MIT,runtime
sharp,0.33.4,Apache-2.0,runtime
dompurify,3.1.6,(MPL-2.0 OR Apache-2.0),runtime
ghostscript-wrapper,2.1.0,AGPL-3.0-only,runtime
chart-kit-pro,1.4.0,SEE LICENSE IN LICENSE.md,runtime
readline-sync,1.4.10,GPL-3.0,runtime
mariadb-connector,3.3.1,LGPL-2.1-or-later,runtime
fast-csv-lite,0.9.0,,runtime
redis-om,0.4.3,Business Source License 1.1,runtime
jest,29.7.0,MIT,dev
eslint-plugin-gpl-thing,1.0.2,GPL-2.0-only,dev
argparse,2.0.1,Python-2.0,runtime
tslib,2.6.3,0BSD,runtime
lodash,3.10.1,MIT,runtime
search-client,7.10.2,Apache-2.0,runtime
search-client,8.1.0,Elastic License 2.0,runtime
```

## Script run
```
$ python3 scripts/audit_licenses.py deps.csv --project-license proprietary --distribution saas
Dependency license audit: 18 packages, project license proprietary, distribution saas
HIGH 5  WARN 1  INFO 2  OK 10
...
HIGH  chart-kit-pro@1.4.0           SEE LICENSE IN LICENSE.md    unknown           runtime
HIGH  fast-csv-lite@0.9.0           (missing)                    unknown           runtime
HIGH  redis-om@0.4.3                BUSL-1.1                     source-available  runtime
HIGH  search-client@8.1.0           Elastic-2.0                  source-available  runtime
HIGH  ghostscript-wrapper@2.1.0     AGPL-3.0-only                network-copyleft  runtime
WARN  readline-sync@1.4.10          GPL-3.0-only                 strong-copyleft   runtime
INFO  eslint-plugin-gpl-thing@1.0.2 GPL-2.0-only                 strong-copyleft   dev
INFO  mariadb-connector@3.3.1       LGPL-2.1-or-later            weak-copyleft     runtime
...
Notes:
- search-client: different licenses across versions (Apache-2.0, Elastic-2.0); check which version you ship.
```
Exit code 1 (HIGH findings).

## The report (filled template, shortened)

# Dependency License Audit: acme-api

Project license: proprietary. Distribution: saas (customers use the web app and REST API; nothing is installed on their machines today).
Packages audited: 18 (16 runtime, 2 dev).

### Summary
- Blockers (HIGH): 5 - two packages with no usable license, two source-available packages, one AGPL package.
- Obligations (WARN): 1 - a GPL-3.0 package that is fine for SaaS but blocks the planned on-prem version.
- Verdict: ship after fixes. Nothing here is unusual, and each item has a cheap fix.

### Blockers
| Package | License (as found) | Why it matters for us | Action |
|---|---|---|---|
| chart-kit-pro 1.4.0 | SEE LICENSE IN LICENSE.md | The LICENSE.md is a commercial license that allows use only with a paid key. We have no key on record. | Confirm with the team that bought it, or replace with a permissive charting library. |
| fast-csv-lite 0.9.0 | (missing) | No license means no permission to use. | Ask the maintainer to add a license; meanwhile switch to a maintained CSV parser with MIT terms. |
| redis-om 0.4.3 | BUSL-1.1 | Business Source License limits production use until its change date; terms vary per project. | Read the exact "Additional Use Grant". If it forbids our use, replace or buy a license. |
| search-client 8.1.0 | Elastic-2.0 | Elastic License 2.0 forbids offering the software as a managed service. Version 7.10.2 in the same tree is Apache-2.0. | Check the lock file: which modules import 8.1.0? Pin both to the Apache-2.0 line or move to an Apache-licensed fork. |
| ghostscript-wrapper 2.1.0 | AGPL-3.0-only | We render customer PDFs with it inside the API; AGPL network use requires offering source to users. | Move PDF rendering to a separate, unmodified worker service and have legal counsel confirm, or buy the commercial license. |

### Obligations
| Package | License | What we must do |
|---|---|---|
| readline-sync 1.4.10 | GPL-3.0-only | Fine for SaaS. It becomes a blocker if the on-prem version ships with it. It is only used by an admin CLI script, so remove it from the server image. |
| mariadb-connector 3.3.1 | LGPL-2.1-or-later | Keep it as a normal npm dependency (replaceable); publish changes if we ever patch it. |

### Verified by hand
- dompurify: dual licensed `MPL-2.0 OR Apache-2.0`; we choose Apache-2.0.
- eslint-plugin-gpl-thing: dev only, never shipped. Accepted.

### What changes if we ship on-prem
- readline-sync (GPL-3.0) becomes HIGH, mariadb-connector (LGPL) needs the replaceability check, and Apache-2.0 packages need their NOTICE files in the installer. Rerun with `--distribution distributed` before that release.

### Third-party notices
Licenses that need full text: Apache-2.0, LGPL-2.1-or-later, MIT, Python-2.0. Link the notices page from the app footer.

_Engineering triage, not legal advice._

## Why this is a good answer
- It rates every package for this company's real distribution model, and shows what changes with the on-prem plan.
- It checks the facts the metadata cannot show (the commercial LICENSE.md, the duplicate search-client versions).
- Every blocker has one concrete, cheap action.
FILE:scripts/audit_licenses.py
#!/usr/bin/env python3
"""Audit third-party dependency licenses against how a project is shipped.

Usage:
  python3 audit_licenses.py deps.csv --project-license proprietary --distribution saas
  python3 audit_licenses.py licenses.json --distribution distributed [--json]
  cat deps.csv | python3 audit_licenses.py - [--allow LIC,LIC] [--deny LIC,LIC]

Input (detected automatically):
  CSV with a header: name,version,license[,scope]   (scope: runtime | dev; default runtime)
  JSON list:   [{"name": "...", "version": "...", "license": "...", "scope": "dev"}]
  pip-licenses --format=json:  [{"Name": "...", "Version": "...", "License": "..."}]
  license-checker --json (npm): {"pkg@1.2.3": {"licenses": "MIT"}, ...}
Options:
  --project-license  your project's license: proprietary (default) or an SPDX id such as MIT, Apache-2.0, GPL-3.0-only
  --distribution     saas (network service, default) | distributed (apps, binaries, devices, libraries) | internal
  --allow / --deny   comma-separated SPDX ids that your policy always allows or always blocks
  --json             machine-readable output

License names are normalized to SPDX ids, expressions with OR take the most
permissive option and AND takes the most restrictive one. Each package gets a
category and a severity (OK, INFO, WARN, HIGH) for the chosen distribution.
Dev-only packages are not shipped, so their findings drop to INFO.
Exit code: 0 no HIGH findings, 1 at least one HIGH, 2 usage or input error.
This is an engineering triage aid, not legal advice. Standard library only.
"""
import argparse
import csv
import io
import json
import re
import sys

ALIASES = {  # lowercased common names -> SPDX id
    "mit": "MIT", "mit license": "MIT", "the mit license": "MIT", "expat": "MIT",
    "isc": "ISC", "isc license": "ISC", "isc license (iscl)": "ISC",
    "apache 2.0": "Apache-2.0", "apache-2": "Apache-2.0", "apache 2": "Apache-2.0", "apache2": "Apache-2.0",
    "apache license 2.0": "Apache-2.0", "apache license, version 2.0": "Apache-2.0",
    "apache software license": "Apache-2.0", "apache license version 2.0": "Apache-2.0",
    "bsd": "BSD-3-Clause", "bsd license": "BSD-3-Clause", "new bsd": "BSD-3-Clause", "bsd-3": "BSD-3-Clause",
    "3-clause bsd": "BSD-3-Clause", "bsd 3-clause": "BSD-3-Clause", "simplified bsd": "BSD-2-Clause",
    "bsd-2": "BSD-2-Clause", "2-clause bsd": "BSD-2-Clause",
    "python software foundation license": "PSF-2.0", "psf": "PSF-2.0", "psfl": "PSF-2.0",
    "mozilla public license 2.0 (mpl 2.0)": "MPL-2.0", "mpl 2.0": "MPL-2.0", "mpl-2": "MPL-2.0", "mpl2": "MPL-2.0",
    "gplv2": "GPL-2.0-only", "gpl-2.0": "GPL-2.0-only", "gpl v2": "GPL-2.0-only", "gpl2": "GPL-2.0-only",
    "gplv2+": "GPL-2.0-or-later", "gpl-2.0+": "GPL-2.0-or-later",
    "gplv3": "GPL-3.0-only", "gpl-3.0": "GPL-3.0-only", "gpl v3": "GPL-3.0-only", "gpl3": "GPL-3.0-only",
    "gplv3+": "GPL-3.0-or-later", "gpl-3.0+": "GPL-3.0-or-later", "gpl": "GPL-3.0-or-later",
    "gnu general public license v2 (gplv2)": "GPL-2.0-only", "gnu general public license v3 (gplv3)": "GPL-3.0-only",
    "gnu general public license v2 or later (gplv2+)": "GPL-2.0-or-later",
    "gnu general public license v3 or later (gplv3+)": "GPL-3.0-or-later",
    "lgpl": "LGPL-2.1-or-later", "lgplv2": "LGPL-2.1-only", "lgplv2+": "LGPL-2.1-or-later", "lgpl-2.1": "LGPL-2.1-only",
    "lgplv3": "LGPL-3.0-only", "lgplv3+": "LGPL-3.0-or-later", "lgpl-3.0": "LGPL-3.0-only",
    "gnu lesser general public license v2 (lgplv2)": "LGPL-2.1-only",
    "gnu lesser general public license v3 (lgplv3)": "LGPL-3.0-only",
    "gnu lesser general public license v2 or later (lgplv2+)": "LGPL-2.1-or-later",
    "agpl": "AGPL-3.0-only", "agplv3": "AGPL-3.0-only", "agpl-3.0": "AGPL-3.0-only",
    "gnu affero general public license v3": "AGPL-3.0-only", "gnu affero general public license v3 (agplv3)": "AGPL-3.0-only",
    "eclipse public license 2.0": "EPL-2.0", "epl 2.0": "EPL-2.0", "epl-2": "EPL-2.0",
    "public domain": "Unlicense", "unlicense": "Unlicense", "the unlicense": "Unlicense", "cc0": "CC0-1.0",
    "boost software license 1.0": "BSL-1.0", "zlib license": "Zlib", "zlib": "Zlib",
    "business source license 1.1": "BUSL-1.1", "elastic license 2.0": "Elastic-2.0",
    "server side public license": "SSPL-1.0", "sspl": "SSPL-1.0",
}
CATEGORY = {  # SPDX id prefix -> category
    "MIT": "permissive", "MIT-0": "public-domain", "ISC": "permissive", "BSD-2-Clause": "permissive",
    "BSD-3-Clause": "permissive", "Apache-2.0": "permissive", "PSF-2.0": "permissive", "Python-2.0": "permissive",
    "Zlib": "permissive", "BSL-1.0": "permissive", "X11": "permissive", "BlueOak-1.0.0": "permissive",
    "CC-BY-4.0": "permissive", "CC-BY-3.0": "permissive", "Unicode-DFS-2016": "permissive", "Unicode-3.0": "permissive",
    "0BSD": "public-domain", "Unlicense": "public-domain", "CC0-1.0": "public-domain", "WTFPL": "public-domain",
    "MPL-2.0": "weak-copyleft", "EPL-1.0": "weak-copyleft", "EPL-2.0": "weak-copyleft", "CDDL-1.0": "weak-copyleft",
    "CDDL-1.1": "weak-copyleft", "LGPL-2.1": "weak-copyleft", "LGPL-3.0": "weak-copyleft", "CC-BY-SA-4.0": "weak-copyleft",
    "GPL-2.0": "strong-copyleft", "GPL-3.0": "strong-copyleft",
    "AGPL-3.0": "network-copyleft", "SSPL-1.0": "network-copyleft",
    "BUSL-1.1": "source-available", "Elastic-2.0": "source-available", "Commons-Clause": "source-available",
    "CC-BY-NC-4.0": "source-available", "CC-BY-NC-SA-4.0": "source-available", "PolyForm-Noncommercial-1.0.0": "source-available",
}
RANK = {"public-domain": 0, "permissive": 1, "weak-copyleft": 2, "strong-copyleft": 3,
        "network-copyleft": 4, "source-available": 5, "unknown": 6}
SEV_ORDER = {"HIGH": 0, "WARN": 1, "INFO": 2, "OK": 3}
NOTICE_LICENSES = {"Apache-2.0"}


def unwrap(text):
    """Remove parentheses that wrap the whole expression: '(MIT OR X)' -> 'MIT OR X'."""
    t = text.strip()
    while t.startswith("(") and t.endswith(")"):
        depth = 0
        for i, ch in enumerate(t):
            depth += ch == "("
            depth -= ch == ")"
            if depth == 0 and i < len(t) - 1:
                return t
        t = t[1:-1].strip()
    return t


def normalize(token):
    t = unwrap(token)
    if not t:
        return ""
    key = t.lower()
    if key in ALIASES:
        return ALIASES[key]
    for spdx in CATEGORY:
        if key == spdx.lower() or key.startswith(spdx.lower() + "-") or key == spdx.lower() + "+":
            return t if key.startswith(spdx.lower() + "-") else spdx
    return t


def category_of(spdx):
    if spdx.upper().startswith("LICENSEREF") or spdx.upper().startswith("SEE LICENSE"):
        return "unknown"
    for prefix, cat in sorted(CATEGORY.items(), key=lambda kv: -len(kv[0])):
        if spdx == prefix or spdx.startswith(prefix + "-") or spdx.startswith(prefix + "+"):
            return cat
    return "unknown"


def classify(expr):
    """Return (normalized expression, chosen license, category, exception) for a license expression."""
    raw = (expr or "").strip()
    if not raw or raw.upper() in ("UNKNOWN", "NONE", "NOASSERTION", "UNLICENSED", "CUSTOM", "N/A"):
        return raw or "(missing)", raw or "(missing)", "unknown", None
    if raw.upper().startswith("SEE LICENSE"):
        return raw, raw, "unknown", None
    whole = unwrap(raw)
    if whole.lower() in ALIASES:  # long names such as "... v2 or later (LGPLv2+)" are one license
        spdx = ALIASES[whole.lower()]
        return spdx, spdx, category_of(spdx), None
    text = re.sub(r"\s+", " ", whole.replace("/", " OR ").replace(";", " OR "))
    exception = None
    m = re.search(r"\bWITH\s+([\w.+-]+)", text, re.I)
    if m:
        exception = m.group(1)
        text = text[:m.start()] + text[m.end():]
    if re.search(r"\sor\s", text, re.I) and not re.search(r"\sand\s", text, re.I):
        parts, mode = re.split(r"\s+or\s+", text, flags=re.I), "or"
    elif re.search(r"\sand\s", text, re.I) and not re.search(r"\sor\s", text, re.I):
        parts, mode = re.split(r"\s+and\s+", text, flags=re.I), "and"
    elif re.search(r"\s(or|and)\s", text, re.I):
        parts, mode = re.split(r"\s+(?:or|and)\s+", text, flags=re.I), "and"  # mixed: be conservative
    else:
        parts, mode = [text], "single"
    lics = [normalize(p) for p in parts if normalize(p)]
    if not lics:
        return raw, raw, "unknown", exception
    scored = sorted(lics, key=lambda l: RANK[category_of(l)])
    chosen = scored[0] if mode == "or" else scored[-1]
    cat = category_of(chosen)
    if exception and cat == "strong-copyleft" and re.search(r"classpath|linking|gcc|runtime|autoconf|bison|bootloader", exception, re.I):
        cat = "weak-copyleft"
    joiner = " OR " if mode == "or" else " AND "
    return joiner.join(lics) + (f" WITH {exception}" if exception else ""), chosen, cat, exception


def assess(cat, chosen, distribution, project):
    proj_cat = "proprietary" if project.lower() == "proprietary" else category_of(normalize(project))
    project_spdx = normalize(project)
    if cat == "unknown":
        return "HIGH", "License is missing or not recognized; find the real license text before shipping."
    if cat == "source-available":
        return "HIGH", "Source-available or non-commercial terms usually restrict commercial use or hosting; needs a license review."
    if project_spdx.startswith("GPL-2.0-only") and chosen.startswith("Apache-2.0"):
        return "HIGH", "Apache-2.0 is generally considered incompatible with GPL-2.0-only projects."
    gpl3_family = re.match(r"(A|L)?GPL-3\.0", chosen)
    if project_spdx.startswith("GPL-2.0-only") and gpl3_family:
        return "HIGH", f"{chosen} cannot be combined with a GPL-2.0-only project; the project would need GPL-3.0 terms."
    if re.match(r"GPL-3\.0|AGPL-3\.0", project_spdx) and chosen.startswith("GPL-2.0-only"):
        return "HIGH", "GPL-2.0-only code cannot be relicensed under GPL-3.0; ask upstream for 'or later' terms or replace it."
    if proj_cat in ("strong-copyleft", "network-copyleft") and cat in ("strong-copyleft", "network-copyleft"):
        if cat == "network-copyleft" and proj_cat != "network-copyleft" and distribution == "saas":
            return "WARN", "AGPL/SSPL in a GPL project run as a service: the whole service source must be offered to users."
        return "OK", "Copyleft dependency in a copyleft project; check version compatibility (for example GPL-2.0-only vs GPL-3.0)."
    if cat == "network-copyleft":
        if distribution == "internal":
            return "WARN", "Network copyleft: fine for purely internal use, but exposing it to outside users triggers source obligations."
        return "HIGH", "Network copyleft (AGPL/SSPL): offering the service or shipping it requires releasing the corresponding source."
    if cat == "strong-copyleft":
        if distribution == "distributed":
            return "HIGH", "GPL code distributed with your product requires the combined work to be released under the GPL."
        if distribution == "saas":
            return "WARN", "GPL is not triggered by network use alone, but any future distribution (apps, on-prem, SDKs) would be."
        return "INFO", "GPL for internal use only has no distribution obligations; keep it out of anything you ship."
    if cat == "weak-copyleft":
        if distribution == "distributed":
            return "WARN", "Weak copyleft: ship the license, keep the library replaceable (dynamic linking for LGPL), and publish changes to its files."
        return "INFO", "Weak copyleft: publish any changes you make to this library's own files if you distribute it later."
    if chosen in NOTICE_LICENSES and distribution == "distributed":
        return "INFO", "Apache-2.0: include the license and any NOTICE file in your distribution."
    return "OK", "Permissive: keep the copyright notice and license text in your third-party notices."


def load(text):
    stripped = text.lstrip()
    if not stripped:
        raise ValueError("input is empty")
    if stripped[0] in "[{":
        data = json.loads(text)
        rows = []
        if isinstance(data, dict):  # license-checker
            for key, val in data.items():
                name, _, ver = key.rpartition("@")
                if not name:
                    name, ver = key, ""
                lic = val.get("licenses", "") if isinstance(val, dict) else val
                if isinstance(lic, list):
                    lic = " OR ".join(lic)
                rows.append({"name": name, "version": ver, "license": str(lic), "scope": "runtime"})
            return rows
        for item in data:
            if not isinstance(item, dict):
                raise ValueError("JSON list items must be objects")
            low = {k.lower(): v for k, v in item.items()}
            lic = low.get("license", low.get("licenses", ""))
            if isinstance(lic, list):
                lic = " OR ".join(lic)
            rows.append({"name": str(low.get("name", "")), "version": str(low.get("version", "")),
                         "license": str(lic or ""), "scope": str(low.get("scope", "runtime") or "runtime").lower()})
        return rows
    reader = csv.DictReader(io.StringIO(text))
    fields = [f.strip().lower() for f in (reader.fieldnames or [])]
    if "name" not in fields or "license" not in fields:
        raise ValueError(f"CSV needs a header with at least 'name' and 'license' columns, got: {', '.join(fields) or '(none)'}")
    rows = []
    for r in reader:
        r = {(k or "").strip().lower(): (v or "").strip() for k, v in r.items()}
        if not r.get("name"):
            continue
        rows.append({"name": r["name"], "version": r.get("version", ""), "license": r.get("license", ""),
                     "scope": (r.get("scope") or "runtime").lower()})
    return rows


def audit(rows, args):
    allow = {normalize(x) for x in args.allow.split(",") if x.strip()} if args.allow else set()
    deny = {normalize(x) for x in args.deny.split(",") if x.strip()} if args.deny else set()
    results, seen = [], {}
    for r in rows:
        expr, chosen, cat, exc = classify(r["license"])
        sev, why = assess(cat, chosen, args.distribution, args.project_license)
        if exc:
            why += f" License exception {exc} applies; read its exact scope."
        if chosen in deny:
            sev, why = "HIGH", f"{chosen} is on your deny list."
        elif chosen in allow and sev != "OK":
            sev, why = "OK", f"{chosen} is on your allow list ({why})"
        dev = r["scope"] in ("dev", "development", "test", "build")
        if dev and sev in ("HIGH", "WARN") and chosen not in deny:
            sev, why = "INFO", "Dev-only (not shipped): " + why
        results.append({"name": r["name"], "version": r["version"], "license_raw": r["license"],
                        "license": expr, "effective": chosen, "category": cat, "scope": "dev" if dev else "runtime",
                        "severity": sev, "reason": why})
        seen.setdefault(r["name"].lower(), set()).add(expr)
    notes = []
    for name, lics in seen.items():
        if len(lics) > 1:
            notes.append(f"{name}: different licenses across versions ({', '.join(sorted(lics))}); check which version you ship.")
    results.sort(key=lambda x: (SEV_ORDER[x["severity"]], -RANK[x["category"]], x["name"].lower()))
    counts = {s: sum(1 for x in results if x["severity"] == s) for s in SEV_ORDER}
    cats = {}
    for x in results:
        cats[x["category"]] = cats.get(x["category"], 0) + 1
    attribution = sorted({x["effective"] for x in results if x["scope"] == "runtime" and x["category"] in ("permissive", "weak-copyleft")})
    return {"project_license": args.project_license, "distribution": args.distribution, "packages": len(results),
            "severity_counts": counts, "category_counts": cats, "attribution_licenses": attribution,
            "notes": notes, "results": results}


def print_text(rep):
    print(f"Dependency license audit: {rep['packages']} packages, project license {rep['project_license']}, distribution {rep['distribution']}")
    c = rep["severity_counts"]
    print(f"HIGH {c['HIGH']}  WARN {c['WARN']}  INFO {c['INFO']}  OK {c['OK']}")
    print("Categories: " + ", ".join(f"{k} {v}" for k, v in sorted(rep["category_counts"].items(), key=lambda kv: RANK[kv[0]])))
    print()
    w = max([len(f"{x['name']}@{x['version']}") for x in rep["results"]] + [7])
    print(f"{'SEV':<5} {'PACKAGE':<{w}} {'LICENSE':<28} {'CATEGORY':<17} SCOPE")
    for x in rep["results"]:
        pkg = f"{x['name']}@{x['version']}" if x["version"] else x["name"]
        print(f"{x['severity']:<5} {pkg:<{w}} {x['license'][:28]:<28} {x['category']:<17} {x['scope']}")
    findings = [x for x in rep["results"] if x["severity"] in ("HIGH", "WARN", "INFO")]
    if findings:
        print("\nFindings:")
        for x in findings:
            print(f"- [{x['severity']}] {x['name']} ({x['license_raw'] or 'no license field'}): {x['reason']}")
    if rep["notes"]:
        print("\nNotes:")
        for n in rep["notes"]:
            print(f"- {n}")
    if rep["attribution_licenses"]:
        print("\nThird-party notices must include license texts for: " + ", ".join(rep["attribution_licenses"]))
    print("\nTriage aid only, not legal advice.")


def main():
    p = argparse.ArgumentParser(description="Audit dependency licenses.", add_help=True)
    p.add_argument("path", help="CSV or JSON file, or - for stdin")
    p.add_argument("--project-license", default="proprietary")
    p.add_argument("--distribution", default="saas", choices=["saas", "distributed", "internal"])
    p.add_argument("--allow", default="")
    p.add_argument("--deny", default="")
    p.add_argument("--json", action="store_true")
    args = p.parse_args()
    try:
        text = sys.stdin.read() if args.path == "-" else open(args.path, encoding="utf-8").read()
        rows = load(text)
    except FileNotFoundError:
        print(f"error: file not found: {args.path}", file=sys.stderr)
        return 2
    except (ValueError, json.JSONDecodeError) as e:
        print(f"error: {e}", file=sys.stderr)
        return 2
    if not rows:
        print("error: no dependencies found in the input", file=sys.stderr)
        return 2
    rep = audit(rows, args)
    if args.json:
        print(json.dumps(rep, indent=2))
    else:
        print_text(rep)
    return 1 if rep["severity_counts"]["HIGH"] else 0


if __name__ == "__main__":
    sys.exit(main())
SoftwareComplianceSecurity Audit+2
F@f
0
Oracle Payroll Unsupported Localization Guide
Text

This prompt guides users through the process of implementing Oracle Fusion Cloud Global Payroll in unsupported countries, focusing on localization issues, statutory requirements, and integration with third-party systems. It provides practical steps, best practices, and risk management strategies for successful implementation.

Provide a comprehensive, step-by-step guide for implementing Oracle Fusion Cloud Global Payroll in scenarios where a country’s localization is unsupported by the platform. The guide should cover the following aspects:

- Overview of Oracle Fusion Cloud Global Payroll and the significance of localization in payroll processes.
- Identification and assessment of unsupported countries within Oracle Fusion Cloud.
- Best practices for implementing payroll solutions for unsupported countries, including workaround strategies and customizations.
- Methods for handling statutory and regulatory requirements specific to unsupported countries.
- Integration considerations for combining Oracle Fusion Cloud Payroll with third-party systems or local solutions.
- Testing and validation approaches to ensure compliance and accuracy.
- Risk management and documentation practices throughout the implementation.

Include detailed explanations and recommendations, emphasizing practical steps and potential challenges.

# Steps

1. Introduce Oracle Fusion Cloud Global Payroll and the role of localization.
2. Explain how to determine unsupported countries.
3. Describe options for handling unsupported localizations: custom configurations, manual processes, third-party integrations.
4. Discuss statutory and compliance issues to address.
5. Detail integration techniques and data flow considerations.
6. Outline testing procedures for compliance and functional accuracy.
7. Highlight documentation and risk mitigation strategies.

# Output Format

Deliver the guide in a structured format using numbered or bulleted lists, with clear headings for each section. Use concise, professional language suitable for an audience of payroll implementation specialists and IT professionals.

# Notes

Focus on practical guidance with an emphasis on compliance, customization, and integration challenges unique to unsupported country localizations.
Best PracticesComplianceBusiness
A@ah0sman
0
🛡 Financial Compliance Auditor
Text

Review and ensure compliance of financial reports with capital markets regulations, focusing on neutrality, risk assessment, and legal completeness, outputting the final document in Turkish.

1You are a financial compliance auditor reviewing a previously generated report about a publicly traded company.
2
3YOUR TASK:
4
5- The final output MUST be in Turkish.
6- Ensure full compliance with capital markets regulations and neutral financial communication standards.
7
8STRICT CHECKS:
9
101. Title Compliance:
...+45 more lines
RiskComplianceAudit+3
G@gunebak4n
0
Expert Legal Analyst in Tax and Commercial Law
Text

Act as a seasoned legal expert specializing in tax law and commercial law, providing top-tier corporate compliance and dispute resolution capabilities.

1Act as a legal expert with extensive experience in tax law and commercial law. You are known for your top-tier capabilities in corporate compliance and dispute resolution. Your task is to:
2- Provide in-depth legal analysis and insights on ${topic}.
3- Ensure compliance with all applicable laws and regulations.
4- Develop strategies for effective dispute resolution and risk management.
5- Collaborate with corporate teams to align legal advice with business objectives.
6Rules:
7- Maintain strict confidentiality and data protection.
8- Adhere to the highest ethical standards in all dealings.
ComplianceLegal
F@zhaoliminlawyer
0