AINews Portal

📝 Prompt Library

Hand-picked prompts for real work, plus the full community collection — copy, fill the brackets, go.

JSON
Zod Schema Validation taste

# Zod Schema Validation taste of a TypeScript developer who trusts nothing from the outside - Validate every input that crosses a trust boundary with Zod: request bodies, query strings, env vars, webhooks and third-party API responses. Confidence: 0.95 - Define the schema first and infer the TypeScript type with `z.infer`, instead of writing the type and the schema twice. Confidence: 0.90 - Use `safeParse` at API boundaries and turn errors into a clean 400 response; use `parse` only where a failure is truly a bug. Confidence: 0.85 - Validate environment variables once at startup and exit early with a clear message when something is missing. Confidence: 0.90 - Keep schemas in a shared module so the client and server use the same contract. Confidence: 0.80 - Use `z.coerce` only for query strings and form data, where every value arrives as a string. Confidence: 0.80 - Prefer `z.discriminatedUnion` over plain unions for tagged objects; errors are clearer and parsing is faster. Confidence: 0.80 - Use `.strict()` on input schemas where unknown keys usually mean a client bug. Confidence: 0.70 - Keep transforms small and pure; heavy business logic does not belong inside a schema. Confidence: 0.80 - Put refinements that check more than one field on the object with `.superRefine` and a clear `path`. Confidence: 0.75 - Write error messages for humans in schemas used by forms, and keep the default messages for internal APIs. Confidence: 0.70 - Use branded types like `z.string().uuid().brand<"UserId">()` for IDs that must never be mixed up. Confidence: 0.65 - Do not validate the same data again deep inside the app; parse once at the edge and pass typed values inward. Confidence: 0.85 - Make dates explicit: accept ISO strings at the boundary and convert to `Date` objects in one place. Confidence: 0.75 - Generate OpenAPI or JSON Schema from Zod schemas when the API is public, instead of keeping docs by hand. Confidence: 0.70 - Avoid `z.any()` and `z.unknown()` in public schemas except for fields that are truly free-form. Confidence: 0.80 - Use `.default()` for optional settings so the code after parsing never needs undefined checks. Confidence: 0.75 - Test schemas with both valid and invalid fixtures, especially for edge cases like empty strings and nulls. Confidence: 0.80 - Log validation failures from third-party APIs with the failing path, because they warn you about silent contract changes. Confidence: 0.80 - Keep schema names consistent, like `CreateUserInput` and `UserResponse`, so the direction of data is clear. Confidence: 0.65

Marketing campaign prompt

Design an accessible service offering for residents, artisans, students, and small businesses in AlUla and nearby areas who want to use a 3D-printing center. Propose service levels for one-off prototypes, small production runs, and help preparing a product for market. Explain how to make pricing competitive and transparent without promising prices before material, design, and production costs are known.

3D Layered Paper-Cut Architectural Travel Poster: Fill-in Template for Any Landmark, City and Country (2:3)

Create an extraordinarily beautiful 3D layered paper-cut architectural travel poster featuring [LANDMARK NAME], [CITY], [COUNTRY]. Transform the destination into an enchanting miniature architectural world, crafted entirely from intricately layered, sculpted and cut coloured paper. 1. CENTRAL ARCHITECTURAL SCENE Feature the destination’s most iconic landmark as the main attraction. Preserve its authentic and recognisable architectural identity. Recreate buildings using multiple layers of carefully cut paper. Include distinctive rooftops, windows, arches, towers, domes, bridges or architectural details specific to the destination. Arrange smaller surrounding buildings to create a charming miniature cityscape. Make the entire scene resemble a beautifully handcrafted architectural diorama. 2. LAYERED PAPER LANDSCAPE Build an extraordinary three-dimensional environment. Flowing paper-cut hills and sculpted mountains. Layered rivers, lakes, coastlines or ocean waves where appropriate. Curved bridges, winding pathways and miniature staircases. Overlapping paper clouds, hills and architectural backgrounds. Intricate foreground elements framing the composition. Beautiful irregular paper-cut edges surrounding the scene. Every layer should have visible depth, delicate edges and realistic cast shadows. 3. UNIQUE DESTINATION DETAILS Include small architectural and cultural elements that make each destination instantly recognisable. Select details according to the location rather than repeating the same decorations. 4. DESTINATION-SPECIFIC COLOUR PALETTE Create a completely original colour identity for every destination. Use 6–9 harmonious shades inspired by its architecture, culture, landscape and atmosphere. Combine rich colours, soft pastels, contrasting paper layers and carefully selected neutral tones. Never repeat the same palette between different destinations. 5. THREE-DIMENSIONAL PAPER ART Authentic handmade paper-cut aesthetic. Multiple overlapping cardstock layers. Sculpted paper architecture. Delicate folded and curved paper details. Visible paper thickness. Soft realistic shadows between layers. Beautiful tactile textures. Intricate miniature craftsmanship. Gentle studio lighting. The artwork must look like a real handcrafted paper sculpture photographed professionally, not a flat illustration or plastic 3D render. 6. DISTINCTIVE POSTER COMPOSITION Place the entire architectural scene inside an elegant irregular organic paper-cut frame. Use a balanced vertical composition with: Large miniature architectural scene in the centre. Beautiful layered foreground. Subtle surrounding negative space. Soft neutral background. Realistic depth and dimensional shadows. 7. MINIMAL TYPOGRAPHY Below the artwork, write: [CITY / DESTINATION NAME] [COUNTRY] Add one short, elegant poetic tagline of approximately 3–6 words inspired by the destination. Use elegant uppercase modern typography for the destination name and a delicate refined serif font for the tagline. Keep typography minimal, correctly spelled and beautifully positioned. 8. FINAL ART DIRECTION A breathtaking fusion of miniature architecture, layered paper sculpture, handcrafted papercraft, whimsical storytelling and premium contemporary travel poster design. Extremely intricate craftsmanship, sophisticated colour harmony, realistic paper shadows, beautiful depth, exquisite architectural details and museum-quality presentation. Portrait 2:3 composition. No watermark, no unnecessary text, no photorealistic buildings, no plastic appearance.

Surrealist Nested-Arch Travel Art: Fill-in Template That Frames Any Landmark Through Infinite Portals (4:5)

Create an exceptionally beautiful surrealist architectural travel artwork featuring LANDMARK NAME, CITY, COUNTRY. 1. THE SIGNATURE COMPOSITION Create a monumental architectural arch or doorway as the dominant foreground frame. Inside the arch, reveal a breathtaking surreal landscape featuring the iconic landmark. Add a second, smaller nested arch in the centre, creating an illusion of infinite depth. Position the landmark naturally within this inner portal, preserving its recognisable architectural details. 2. DREAMLIKE LANDSCAPE Surround the landmark with abstract rolling landscapes inspired by the destination. Add a tiny solitary traveller walking towards the inner arch. Create a delicate trail of footprints leading towards the landmark. Introduce a crescent moon or oversized sun in the distant sky. Use beautiful gradients, dramatic shadows and atmospheric lighting. 3. COLOUR IDENTITY Every destination must have its own distinctive palette. Never repeat colours. 4. ART DIRECTION Surrealist architectural photography. Minimalist geometric composition. Cinematic colour grading. Monumental arches and nested frames. Dreamlike scale and perspective. Rich textures and soft atmospheric gradients. Deep, sophisticated shadows. 5. TYPOGRAPHY Add the country and landmark name in elegant minimal typography, with a tiny poetic tagline. No clutter, no unnecessary decorations, no random buildings. Premium collectible travel-art aesthetic. Vertical 4:5 Keep the nested arches as the signature element in every poster, but change the landscape, lighting, colour palette and architectural details for every destination. That will make the collection instantly recognisable while keeping every artwork unique.

AI Prompt Creation Agent

### 1. Short business concept prompt > Help me describe a 3D-printing center in AlUla that helps local residents and businesses produce, improve, and sell their products. We have MINGDA printers, such as the MD-1000 Pro, and Creality K1/K1 Max printers. Write a clear, compelling description for potential customers and partners. Do not assume printer capabilities that I have not provided. ### 2. Detailed business plan prompt > Develop a practical business plan for a 3D-printing service center in AlUla, Saudi Arabia. The center will use MINGDA printers, including the MD-1000 Pro, and Creality K1/K1 Max printers to help residents and nearby communities prototype, manufacture, and prepare products for sale. Include target customer groups, services, operating workflow, pricing principles, startup and operating cost categories, partnerships, sales channels, risks, and a 90-day launch plan. Clearly label assumptions and list the information I still need to provide. ### 3. Product development prompt > Act as a product-development advisor for a 3D-printing workshop in AlUla. Suggest 15 product ideas that local makers could prototype and potentially sell, inspired by local needs, culture, tourism, crafts, and everyday life. For each idea, describe its likely customer, the problem it solves, a possible material or production consideration, and a low-cost way to test demand. Avoid presenting cultural motifs as generic decoration; recommend respectful collaboration with local creators. ### 4. Community-focused service prompt > Design an accessible service offering for residents, artisans, students, and small businesses in AlUla and nearby areas who want to use a 3D-printing center. Propose service levels for one-off prototypes, small production runs, and help preparing a product for market. Explain how to make pricing competitive and transparent without promising prices before material, design, and production costs are known. ### 5. Brand and positioning prompt > Create three distinct brand-positioning directions for a 3D-printing center based in AlUla. The center helps local people turn ideas into prototypes and market-ready products, and supports both local and international promotion. For each direction, suggest a brand promise, audience, tone of voice, tagline, and a short “About us” paragraph. Keep the language credible, welcoming, and grounded in local collaboration. ### 6. Marketing campaign prompt > Create a 30-day launch marketing plan for a new 3D-printing service center in AlUla. The goal is to attract local makers, small businesses, schools, and product creators. Include weekly themes, social media post ideas, a simple call to action for each post, community outreach activities, and a way to measure interest. Provide versions suitable for Instagram and LinkedIn, and do not claim services or technical capabilities that have not been confirmed. ### 7. Partnership outreach prompt > Draft a warm, professional partnership email introducing our AlUla 3D-printing center to **[organization, school, artisan group, or business]**. Explain how we could help members prototype or produce small batches of products, propose one practical pilot project, and invite them to a short meeting. Keep the message concise and avoid making unsupported claims. ### 8. Investor or sponsor pitch prompt > Write a short pitch for a potential sponsor or partner describing a 3D-printing center in AlUla. Explain the community opportunity, how the center can help local makers develop products, how it could generate revenue, and what support we are seeking: **[funding, materials, training, workspace, or partnerships]**. Use a persuasive but realistic tone, distinguish confirmed facts from plans, and end with a specific next step. For the strongest results, add your actual services, printer build volumes, materials, team experience, location, budget, and intended customer groups.

Portfolio

--- name: portfolio description: Creative & Digital Portfolio 2026 Marketing Manager | Content Creator | AI Evaluator I am a creative and motivated professional interested in marketing, digital content creation, brand development and artificial intelligence. My interests include developing engaging marketing concepts, creating visual content, building brand identities and evaluating AI-generated outputs for quality, accuracy and creative effectiveness. I enjoy combining creativity with strategic thinking to develop content that connects with audiences and supports business objectives. This portfolio features self-initiated concept projects demonstrating my creative interests, marketing approach and developing AI evaluation skills. Core Skills * Marketing strategy and campaign planning * Brand development and visual identity * Social media content creation * Creative writing and copywriting * AI-assisted research and content development * AI output evaluation and quality assessment * Creative problem-solving --- # Portfolio Describe what this skill does and how the agent should use it. ## Instructions - Step 1: ... - Step 2: ...

Video scenario

TASK: Creative Concept & Full Script for a Corporate Christmas Gift Campaign Act as an experienced Creative Director, Advertising Scriptwriter, and Social Media Video Producer. I need you to develop a professional, creative, and commercially effective video concept and full shooting script for a company specializing in customized corporate Christmas gift boxes. 1. Company Profile & Services The company offers: * Custom-designed corporate gift boxes. * Personalized gift selections based on each company’s preferences, budget, and brand identity. * Customized packaging and branding. * Tailor-made gift solutions for employees, business partners, clients, and executives. * Both ready-made gift concepts and fully customized orders. The key selling point is that every gift can be individually tailored to the company’s needs, preferences, and budget. 2. Main Objective The video should target: * Company owners and CEOs. * HR managers. * Marketing and communications teams. * Business representatives responsible for corporate gifting. The objective is to encourage companies to place their Christmas and New Year corporate gift orders. The video should sell more than just gift boxes. It should communicate the value of appreciation, meaningful gestures, business relationships, and thoughtful gifting. 3. My Contribution & On-Camera Role I will personally participate in the video. My role should go beyond simply presenting the products. I want to appear as a confident, engaging person who communicates directly with the audience and explains why personalized corporate gifting matters. My on-camera presence should feel: * Natural and authentic. * Confident but not overly promotional. * Friendly, sophisticated, and engaging. * Professional without sounding corporate or scripted. * Persuasive without being pushy. Write my dialogue in a way that sounds natural when spoken directly to the camera. I want my contribution to be meaningful and integrated into the creative concept, not just an appearance inserted into the video. 4. What I Need You to Deliver Develop the following: 1. Main Creative Concept: Create a strong central idea and creative direction for the campaign. 2. Three Different Video Concepts: * Elegant, emotional, and premium. * Modern, dynamic, and sales-oriented. * Creative, engaging, and memorable. 3. Complete Shooting Script: Break down each concept scene by scene, including timing and duration. 4. My On-Camera Dialogue: Write the exact words I should say, including opening lines, transitions, and closing statements. 5. B-Roll & Product Shots: Suggest detailed shots of: * Selecting products. * Arranging gift boxes. * Packaging and wrapping. * Tying ribbons. * Adding personalized elements. * Showing finished gift boxes. * Close-up shots of textures, details, and presentation. 6. Visual Storytelling: Show how my direct-to-camera appearance should alternate with product footage and behind-the-scenes scenes. 7. Strong Opening Hook: The first 3 seconds must immediately capture attention and make the viewer want to continue watching. 8. Call to Action: Create a compelling ending that encourages businesses to contact the company, request a quotation, or place an order. 9. On-Screen Text: Suggest short, impactful overlay texts for each scene. 10. Production & Editing Direction: Specify camera angles, framing, transitions, editing rhythm, music style, lighting, and overall visual atmosphere. 5. Technical Requirements * Duration: 45–60 seconds. * Format: Vertical 9:16. * Platforms: Instagram Reels, Facebook Reels, and TikTok. * Visual aesthetic: Festive, elegant, sophisticated, modern, and premium. * Production: Low-budget and realistically achievable without complicated equipment or elaborate setups. 6. Creative Guidelines * Avoid generic Christmas advertising clichés. * Avoid overly sentimental, exaggerated, or artificial dialogue. * Do not make the video look like a simple product catalogue. * Focus on storytelling, emotional connection, and commercial value. * Clearly communicate that every corporate gift can be customized according to the client’s needs, preferences, and budget. * Make the video feel like a professionally produced brand campaign rather than a typical social media advertisement. 7. Final Deliverable I expect a complete, production-ready creative package. For every scene, specify: * Exact duration. * What appears on screen. * Whether I am speaking or whether it is a voice-over. * My exact dialogue. * Camera angle and movement. * Product shots and supporting footage. * On-screen text. * Editing and transition suggestions. Think like a high-level advertising agency creative team. Prioritize originality, visual storytelling, audience engagement, brand positioning, and conversion. The final result should make corporate decision-makers think: “This is exactly the kind of thoughtful, personalized Christmas gifting solution we need for our company.”

Pay on delivery

as a product manager in help me do market reearch on pay on delivey apps in africa

THE BATTLES NOBODY SEES

Create a 60-second ultra-realistic cinematic motivational short film titled “THE BATTLES NOBODY SEES.” CORE CONCEPT: Tell an emotional, relatable story about a man going through difficult seasons of life. He experiences disappointment, loneliness, financial struggles, unanswered prayers, setbacks and moments when giving up seems easier than continuing. The film should remind viewers that struggling doesn’t mean failing, being behind doesn’t mean being defeated, and every difficult season can become part of someone’s growth. VISUAL STORYTELLING: SCENE 1 (0–10 seconds): A young man sits alone on the edge of his bed in a dimly lit room at night. His phone lights up, but there are no meaningful messages. He looks exhausted and lost in thought. Rain falls outside the window. SCENE 2 (10–20 seconds): Show him walking alone through a quiet street at night. Close-up of his face, tired eyes and thoughtful expression. Show him sitting at a desk looking at bills, unfinished work and personal goals written in a notebook. SCENE 3 (20–30 seconds): He looks into a mirror, takes a deep breath and slowly stands up. Cut to him tying his gym shoes, preparing for another difficult day, and stepping outside before sunrise. SCENE 4 (30–45 seconds): Show a realistic sequence of him exercising, working, learning, making mistakes and trying again. Show sweat, exhaustion, persistence and small victories. His progress should feel gradual and believable. SCENE 5 (45–55 seconds): The man walks through an empty street as the sun rises. His facial expression is calmer. He looks more confident, not because life has become perfect, but because he has decided not to give up. SCENE 6 (55–60 seconds): Wide cinematic shot of him standing on a rooftop overlooking the city at sunrise. Slowly fade to black. FINAL ON-SCREEN MESSAGE: “YOUR STORY ISN’T OVER.” VISUAL STYLE: Photorealistic human characters, natural facial expressions, realistic body movements, authentic environments, cinematic camera movements, shallow depth of field, subtle film grain, natural lighting, emotional close-ups and professional colour grading. Use muted colours, charcoal shadows, soft grey tones and warm sunrise highlights. VOICEOVER: Calm, mature masculine voice. Deep but natural, emotionally grounded, conversational and sincere. Avoid exaggerated shouting or artificial motivational delivery. MUSIC: Emotional cinematic piano at the beginning, gradually building into subtle atmospheric strings and powerful instrumental percussion towards the ending. EDITING: Smooth cinematic transitions, carefully paced scenes, realistic motion, emotional storytelling and perfectly synchronized narration. TECHNICAL: 60 seconds, vertical 9:16, 4K, cinematic realism, high visual consistency, suitable for TikTok, Instagram Reels and YouTube Shorts. IMPORTANT: Do not make the character look like a superhero or an impossibly wealthy person. Avoid unrealistic transformations, artificial facial expressions, cartoon effects, excessive slow motion and flashy transitions. Make the story feel personal, honest and believable.

Ronaldo hanger

Ronaldo os angry that messi winn the world cup, and he run to steal it from him

TV Wall Planner: Screen Size, Seating Distance, Mount Height and Materials

You are a careful TV installation planner. Help me plan a wall-mounted TV using the formulas below. Compute every number; do not estimate from memory. Show each result rounded to 0.1 inch (and feet where useful), then a short explanation. My setup: - TV diagonal: ${tv_diagonal_in:65} inches (assume a 16:9 screen unless I say otherwise) - Distance from my eyes, when seated, to the wall: ${seat_distance_in:110} inches - Seated eye height from the floor: ${eye_height_in:42} inches - Wall type: ${wall_type:wood stud drywall} (wood stud, metal stud, brick, concrete or plaster) - Mount type: ${mount_type:fixed} (fixed, tilting or full-motion) - Furniture under the TV (console, fireplace, soundbar): ${below_tv:media console 24 inches tall} - Distance along the wall from the TV to the source devices or outlet: ${cable_run_in:72} inches Formulas (16:9): 1. Screen width = diagonal × 0.8716; screen height = diagonal × 0.4903. 2. Seating distance range: closest = width ÷ (2 × tan 20°) = width × 1.374 (40° field of view, THX); farthest = width ÷ (2 × tan 15°) = width × 1.866 (30° field of view, SMPTE). Report my actual horizontal field of view = 2 × atan(width ÷ (2 × seat distance)) and say whether I am inside the range, too close or too far. 3. Mount height: put the screen centre at seated eye height, then raise it by at most 2–4 inches if the bottom edge would clear the furniture by less than 3 inches. Bottom edge = centre − height ÷ 2; top edge = centre + height ÷ 2. If the centre must go above 50 inches (e.g. over a fireplace), warn about neck strain and suggest a tilting or pull-down mount. 4. Cable length: run length plus 24 inches of slack, rounded up to the next stock size (3, 6, 10, 15, 25, 35, 50 ft). Above 25 ft for 4K/HDR, suggest an active or fibre HDMI cable. Then give: - A results table (screen size, seating range, my field of view, centre/bottom/top heights, mount stand-off for my mount type: fixed about 1.5 in, tilting about 2.5 in, full-motion 3–25 in). - A materials checklist with quantities, choosing anchors for my wall type: wood stud = lag bolts into at least two studs; metal stud = toggle bolts rated for the load, or blocking; brick or concrete = sleeve or wedge anchors into solid masonry, not mortar joints; plaster = locate the framing and never rely on plaster alone. - Safety checks: the mount is rated above the TV's weight and fits its VESA pattern; never run a standard TV power cord inside a wall (use a code-listed in-wall power relocation kit and in-wall rated CL2/CL3 HDMI); check for pipes and wires before drilling; follow the mount and TV manuals and local electrical and building codes. - One sentence on whether a larger or smaller TV would suit my seating distance better. Ask me for any value that is missing or implausible before calculating.

Act as an Aging Parent Care Coordinator

Act as an Aging Parent Care Coordinator. I am an adult child (or close relative) who is starting to look after an aging parent: they may be slowing down, recently fell, came home from hospital, got a new diagnosis, live alone or far away from me, or I simply have a feeling things are getting harder for them. I have a job, a family and limited time, and I may share this with siblings. Your job is to help me organize care calmly and practically, so my parent stays safe and keeps as much independence and dignity as possible, without me burning out. Start by asking me, in one short numbered list, for: 1. My parent's age, living situation (alone, with a partner, with family), and how far I live from them. 2. What has changed recently and what worries me most (falls, memory, medications, driving, eating, loneliness, money, a hospital stay). 3. Their health conditions, regular doctors and current medications, as far as I know. 4. What they can still do on their own and what they need help with (bathing, dressing, cooking, shopping, cleaning, bills, transport, technology). 5. Who else can help (siblings, partner, neighbors, friends, paid help) and how much time and money each of us can realistically give. 6. What my parent wants: where they want to live, what they refuse, what matters most to them. Then work through these steps with me, one at a time, and wait for my answers where you need them: Step 1 - The picture today. Summarize the situation in plain words: needs, strengths, risks, and what is urgent this week versus what can wait. Use a small table with four rows: safety, health, daily living, and money and paperwork. Step 2 - Safety first. Give me a room-by-room home safety checklist for their actual home (trip hazards, lighting, bathroom grab bars, stairs, stove, medication storage, smoke and carbon monoxide alarms), plus a simple way for them to call for help, and what I can fix myself this weekend versus what needs a professional. Step 3 - Health and medications. Help me build one medication list (name, dose, time, prescriber, purpose) and an appointments calendar. Write the questions I should ask at the next doctor visit, and tell me which warning signs mean I should call the doctor the same day and which mean I should call emergency services right away. Step 4 - Who does what. Draft a fair care plan that splits tasks between me, siblings and helpers by skill, distance and availability (for example: one handles bills online, one does weekly visits, one manages appointments), with a weekly rhythm and a backup for each task. Write a short, non-blaming message I can send to my siblings to agree the plan. Step 5 - Paperwork and money. List the documents and decisions worth putting in place while my parent can still decide for themselves (who can speak to doctors, who can manage money if needed, their wishes for care, where important papers and passwords are), and which local services, benefits or support organizations I should look into. Tell me what to ask a local professional instead of guessing. Step 6 - Talking with my parent. Give me an opening line and a gentle way to raise hard topics (accepting help at home, stopping driving, moving closer, a medical alert device) that respects their choices, with replies for three likely pushbacks ("I'm fine", "I don't want strangers in my house", "You're treating me like a child"). Step 7 - Looking after me. Help me notice caregiver burnout early, plan regular breaks and respite, and set one or two limits I can keep. End with a one-page summary: this week's three actions, the care plan, the key contacts and when we should review it all again. Rules: - Never diagnose, change medications or replace a doctor, nurse or social worker; tell me when to ask one. - For anything that sounds like an emergency (chest pain, signs of a stroke, a fall with injury, sudden confusion), tell me to contact emergency services first. - Never invent facts about my parent; ask, or label anything you assume. - Respect my parent's right to make their own decisions, even ones I don't agree with, unless their safety is clearly at serious risk. - Laws, benefits and services differ by country; point out where I need to check locally, without giving legal or financial advice. - Keep each step short and warm, use checklists and tables, and end each step with one clear question for me.

Customer Personal Data Request Handling Plan (JSON)

You 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. My inputs: - The request as received (paste the email, form entry or ticket), the date it arrived and the channel: - Product, what personal data we store about users and customers, and where (database, analytics, email tool, CRM, support desk, payments, backups, logs): - 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: - Vendors that hold personal data for us: - Who on the team can work on this and how we can export or delete data today (admin panel, scripts, manual): - 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: Schema: ```json { "request_summary": { "received_on": "", "channel": "", "requester": "", "request_types": [], "plain_language_summary": "", "applicable_laws": [], "our_role": "", "deadline": "", "deadline_basis": "", "extension_possible": "" }, "identity_verification": { "matched_to_account": "", "verification_method": "", "data_to_ask_for": [], "do_not_ask_for": [], "authorized_agent_check": "" }, "scope_decision": { "in_scope": true, "if_controller_for_a_customer": "", "exemptions_considered": [ { "exemption": "", "applies": "", "reason": "" } ], "clarification_needed": "" }, "data_map": [ { "system": "", "data_categories": [], "lookup_key": "", "owner": "", "action": "", "method": "", "vendor_request_needed": "", "backups_and_logs_note": "" } ], "action_plan": [ { "step": 1, "task": "", "owner": "", "due": "", "done_when": "" } ], "response_package": { "export_format": "", "files_to_include": [], "secure_delivery_method": "", "explanation_items": [] }, "deletion_or_correction": { "what_is_deleted": [], "what_is_kept_and_why": [], "anonymized_instead": [], "confirmation_to_requester": "" }, "messages": { "acknowledgement": "", "identity_request": "", "final_response": "", "refusal_or_partial_template": "" }, "record_keeping": { "log_entry_fields": [], "evidence_to_keep": [], "retention_of_this_record": "" }, "process_improvements": [ { "gap": "", "fix": "", "effort": "", "priority": "" } ], "risks_and_escalations": [], "open_questions_for_me": [] } ``` Rules: - Calculate the deadline from the received date and the laws you list, and explain the basis in deadline_basis; if laws overlap, use the shortest deadline. - Identity verification must be proportionate: ask only for what we need to match the account, never for more sensitive data than we already hold, and never for a full ID copy unless there is a clear reason. - If we only process this data for a business customer, say so in if_controller_for_a_customer and plan to forward the request to that customer instead of acting alone. - Cover every system and vendor I mention in data_map, including backups, logs and analytics; say plainly when deletion from backups happens only when they expire. - Keep messages short, polite and in plain language; final_response must state what we did, what we kept and why, and how to complain or follow up. - Use "" for unknown values and list them in open_questions_for_me instead of guessing; never invent systems, vendors or legal exemptions. - This is an operational drafting aid, not legal advice; flag anything that should be checked with a privacy lawyer or the relevant data protection authority. - Output valid JSON only: double quotes, no comments, no trailing commas.

Renaissance Sgraffito Wall Panel of a Lemon Tree with Swallows

An authentic Italian Renaissance-style sgraffito wall panel of a lemon tree in an ornate urn, portrait 3:4, photographed straight on. A tall lemon tree rises from a decorated, patterned urn, its branches heavy with round lemons and pointed leaves, with two small swallows perched in the upper branches; the panel is framed by a border of scrolling acanthus leaves and a lattice band. Sgraffito technique details: two layers of lime plaster, a dark charcoal-grey under layer revealed wherever the cream-white top layer has been scratched and scraped away; crisp incised outlines and cross-hatched shading cut with a metal stylus; slightly raised edges and tiny crumbs along the cut lines; flat areas of creamy plaster with subtle trowel texture; gentle weathering, hairline cracks and a few chipped spots at the corners. Two tones only, cream and charcoal grey, with no paint colors. Soft even daylight raking slightly from the left to show the shallow relief of the cuts. Calm, elegant, Mediterranean mood. No text, no signature, no people, no modern objects.

1840s Salted Paper Print of a Stone Harbor at Low Tide

An authentic 1840s salted paper print, the early calotype-era photographic process, of a quiet stone harbor at low tide, landscape 4:3. Three wooden fishing boats rest tilted on the wet mud in the foreground; coiled ropes and lobster pots stand on a cobbled quay at the left; a row of narrow stone cottages with slate roofs and chimneys lines the harbor behind, and a small church tower rises on the hill above under a pale, empty sky. Salt print details: a matte image sunk into the paper fibers with no glossy surface; warm reddish-brown to purple-brown tones; soft, slightly fuzzy detail from the paper negative; visible paper texture and fibers; gentle uneven density; a blown-out pale sky; faded, vignetted edges and a few foxing spots; mounted on cream card with a thin border. Long-exposure stillness with no motion blur. Quiet, timeless coastal mood. Viewed straight on as a flat print in soft even light. No text, no signature, no frame, no people.

Greater Flamingo Flock on a Golden-Hour Salt Lagoon

Photorealistic wildlife photograph of a flock of greater flamingos in a shallow salt lagoon at golden hour, landscape 16:9. About twenty flamingos stand and wade in a loose line across the middle of the frame in calm, ankle-deep water: pale pink bodies with deeper coral-pink wing coverts, long legs and curved black-tipped bills, several with heads lowered to feed. One flamingo in the center raises its wings, showing the coral and black flight feathers. The still water mirrors every bird in crisp reflections; behind them lie low pale shores and distant hazy hills under a warm apricot sky, with a soft sun glow at the upper left. Camera at water level, 400 mm telephoto at f/5.6, sharp on the flamingos with a soft background, natural colors, calm golden-hour stillness. No people, no boats, no text.

Greater Flamingo Flock on a Golden-Hour Salt Lagoon (Image-to-Video Animation)

Use the attached still (step 1: a water-level photograph of about twenty greater flamingos standing in a line across a shallow salt lagoon at golden hour, one in the center with its wings raised) as the exact first frame and animate it into a 7-second, 16:9 cinematic shot. Keep every element where it is in the still: the flamingos and their positions in the line, the raised wings of the center bird, the mirror reflections, the hazy hills, the apricot sky and the soft sun glow at the upper left. Motion (0-7 s): - 0-2 s: the center flamingo beats its raised wings; the birds around it lift their heads, open their wings and start stepping forward, sending ripples across the reflections. - 2-5 s: the whole line breaks into a running display across the shallow water, long legs pattering on the surface and kicking up small splashes, wings flapping wide to show coral-pink and black flight feathers, necks stretched forward. - 5-7 s: the flock keeps running and flapping from left to right, most birds leaving the frame on the right and a few lifting just above the water, while their reflections break into rippling pink streaks; the last few birds follow them out. Camera: locked-off telephoto framing at water level with a very slow pan to the right; focus stays on the flock; no cuts. Lighting and mood: constant warm golden-hour light, apricot sky and soft glints on the water; peaceful, graceful, natural. Audio (if supported): splashing footsteps, wingbeats, soft honking calls, a light breeze; no music, no voices. Avoid: people, boats, extra flamingos appearing from nowhere, birds merging or morphing, broken or extra legs and wings, sudden lighting changes, unnatural fast motion, text.

TLS Certificate Expiry and Inventory Checker

--- name: tls-certificate-expiry-and-inventory-checker description: Checks a JSON inventory of TLS certificates (plus optional PEM files) for expired and soon-expiring certs, stuck auto-renewals, hosts missing from SANs, weak keys and SHA1 signatures, over-long lifetimes, incomplete chains, self-signed public certs, missing owners or runbooks, shared wildcards and renewal clusters. Ranks fixes. Offline stdlib Python checker. --- # TLS Certificate Expiry and Inventory Checker You help engineers and IT admins stop certificate outages before they happen. An expired cert, a host that silently fell out of the SAN list, or a renewal job that has been failing for weeks takes a service down just as hard as a code bug, usually on a weekend. You take a JSON inventory of certificates (and optionally the PEM files) and produce a ranked list of what to renew, reissue or fix, with an owner for each item. You do not connect to servers, request certificates or handle private keys. Work only from the inventory and public certificate files the user provides. If someone pastes a private key, tell them to remove it and treat it as compromised. ## Files in this skill - `scripts/check_certs.py` - reads `inventory.json` and any `pem_path` files; reports TC01-TC15 (expired, expiring within 14 or 30 days, stuck auto-renewal, host not in SANs, weak key, SHA1/MD5 signature, lifetime over 398 days, incomplete chain, self-signed public cert, no owner, manual renewal without runbook, wildcard shared across environments, renewal clusters, future not_before); text or `--json` output (Python 3.8+ standard library only) - `references/expiry-and-renewal.md` - renewal windows, ACME behaviour, why auto-renew still fails, shrinking lifetimes - `references/key-and-chain-rules.md` - SAN and wildcard matching, key sizes, signature algorithms, chains, self-signed and internal CAs - `templates/cert-report.md` - the report you hand back - `examples/inventory.json` - nine certificates for a fictional shop with several traps - `examples/certs/internal-api.pem` - a public self-signed test certificate decoded by the script (no private key) ## Workflow ### 1. Collect the inventory Ask for one entry per certificate: `name`, `hosts` served, `sans`, `issuer`, `not_before`, `not_after`, `key_type`, `key_bits`, `sig_alg`, `auto_renew`, `renew_method`, `chain_complete`, `environment`, `public`, `owner`, `renewal_runbook`. If they only have PEM files, set `pem_path` and the script fills dates, SANs and issuer. Useful one-liners for gathering data (run by the user, not you): ``` openssl x509 -in cert.pem -noout -subject -issuer -dates -ext subjectAltName openssl s_client -connect host:443 -servername host -showcerts </dev/null ``` ### 2. Run the checker ``` python3 scripts/check_certs.py examples/inventory.json --today 2026-11-11 python3 scripts/check_certs.py inventory.json --json --warn-days 45 python3 scripts/check_certs.py --self-test ``` Exit 0 = no high findings, 1 = high findings, 2 = bad input. Without a shell, walk each entry with the two reference files and apply the same codes by hand. ### 3. Read the result - High: TC01 expired, TC02 expires within 14 days, TC05 host not covered by SANs, TC06 weak key, TC07 SHA1/MD5 signature, TC09 incomplete chain, TC10 self-signed on a public endpoint, TC14 not_before in the future, TC00 missing expiry data. - Medium: TC03 manual renewal within 30 days, TC04 auto-renew on but under 20 days left (renewal is stuck), TC08 lifetime over 398 days on a public cert, TC11 no owner, TC13 wildcard shared between production and other environments. - Low: TC12 manual renewal without a runbook, TC15 three or more certs expiring in the same week. ### 4. Deliver Fill `templates/cert-report.md`: verdict, a renewal calendar sorted by days left, findings with owners, and the three changes that remove the most risk (usually: automate renewal, add expiry monitoring at 30/14/7 days, fix SAN coverage). Re-run after fixes and attach the clean output. ## Example result On the sample inventory (as of 11 Nov 2026), `legacy-vpn` expired 6 days ago and also has a 1024-bit RSA key, SHA1 signature and no owner; `checkout-api` expires in 10 days, misses `pay.example-shop.test` in its SANs and serves an incomplete chain; `wildcard-prod` has auto-renew on but only 19 days left, and its wildcard does not cover the two-level `img.cdn` host; `status-page` is self-signed on a public endpoint; the PEM-based `internal-api` lacks `metrics.corp.example`; and the same wildcard is used in production and staging. Result: 9 high, 5 medium, 3 low. ## Rules - Base every finding on an inventory field or a decoded PEM value; never guess an expiry date. - Never ask for, print or store private keys or passwords. - Treat CA and browser policy numbers (398-day limit, shrinking lifetimes) as current guidance to confirm, not as legal requirements for private PKI. - Recommend monitoring that alerts a named owner, not a shared inbox nobody reads. FILE:references/expiry-and-renewal.md # Expiry and renewal ## Windows the checker uses - Expired (TC01): `not_after` is before the as-of date. Browsers and most API clients refuse the connection. - Critical (TC02): 14 days or less left. Renew this week and confirm the new cert is actually being served. - Warning (TC03): 30 days or less left and renewal is manual. Put a dated task with an owner on the calendar. - Stuck renewal (TC04): `auto_renew` is true but 20 days or less are left. ACME clients such as certbot and acme.sh normally renew around 30 days before expiry (one third of a 90-day lifetime), so a cert this close usually means the job has been failing. ## Why automatic renewal still fails - DNS-01 API token expired or lost permissions after a provider change. - HTTP-01 challenge blocked by a new redirect, WAF rule or CDN in front of the origin. - The renewal ran but the service was never reloaded, so the old cert is still in memory. - The cert renewed on one server but not on the load balancer, CDN or other replicas. - Rate limits after repeated failed attempts. Always check what is actually served (`openssl s_client -connect host:443 -servername host`), not just the file on disk. ## Lifetimes are getting shorter - Publicly trusted certificates are limited to 398 days today (TC08), and CA/Browser Forum ballots schedule further reductions over the next few years toward much shorter lifetimes. Confirm the current limits with your CA. - Shorter lifetimes make manual renewal unsustainable: treat every manual public cert as an automation task. ## Monitoring that works - Alert at 30, 14 and 7 days, sent to a named owner (TC11) and a team channel. - Monitor from outside, per hostname, so a missing SAN or a stale replica is caught. - Keep a renewal runbook link for every manual cert (TC12): CSR command, CA account, deploy targets, reload command, verification step. - Stagger renewals (TC15) so one broken week cannot take down several services. FILE:references/key-and-chain-rules.md # Keys, names and chains ## Hostname coverage (TC05) - Clients check the subjectAltName (SAN) DNS entries; the Common Name alone is ignored by modern browsers. - A wildcard covers exactly one label: `*.example.com` matches `a.example.com` but NOT `example.com` and NOT `a.b.example.com`. - List every name a service answers to (apex, www, regional and legacy hostnames) in `hosts` so gaps show up. ## Keys and signatures (TC06, TC07) | Key type | Minimum | Good default | |---|---|---| | RSA | 2048 bits | 2048 or 3072 | | ECDSA | P-256 | P-256 or P-384 | | Ed25519 | n/a | supported mainly for internal use | - SHA1 and MD5 signatures are rejected by browsers and many libraries; reissue with SHA-256 or stronger. - If a key may have leaked (shared over chat, committed to git), revoke and reissue; do not just renew with the same key. ## Chains (TC09) - Servers must send the leaf plus intermediate certificates. Some browsers hide a missing intermediate by fetching it, but API clients, mobile apps and older devices fail. - Test with `openssl s_client -showcerts` or a fresh client container, not only a desktop browser. ## Self-signed and internal CAs (TC10) - Self-signed or private-CA certs are fine for internal services if clients are configured to trust that CA. Mark them `public: false`. - On a public endpoint they produce warnings that teach users to click through security errors. ## Blast radius (TC13) - A wildcard shared between production and staging means a key leaked from a less protected staging box can impersonate production. Prefer separate certs per environment and per sensitive service. FILE:templates/cert-report.md # TLS certificate review - {{organization}} As of: {{as_of_date}} | Certificates checked: {{count}} | Verdict: {{verdict: ACT NOW / SCHEDULE / HEALTHY}} ## Renewal calendar | Certificate | Expires | Days left | Auto-renew | Owner | |---|---|---|---|---| | {{name}} | {{not_after}} | {{days_left}} | {{yes/no}} | {{owner}} | ## High findings (fix first) | Code | Certificate | Problem | Fix | Owner | Due | |---|---|---|---|---|---| | {{TCxx}} | {{name}} | {{message}} | {{fix}} | {{owner}} | {{date}} | ## Medium and low findings - {{TCxx}} {{name}}: {{message}} -> {{fix}} ## Three changes that remove the most risk 1. {{e.g. automate renewal for the remaining manual public certs}} 2. {{e.g. external expiry monitoring at 30/14/7 days to a named owner}} 3. {{e.g. reissue with full SAN coverage and separate production/staging certs}} ## Verification - Re-run: `python3 scripts/check_certs.py inventory.json --today {{date}}` -> exit {{code}} - Served-cert check per host: `openssl s_client -connect {{host}}:443 -servername {{host}}` Notes: built from the inventory provided; no servers were contacted and no private keys were handled. FILE:examples/inventory.json { "organization": "Example Shop (fictional)", "certificates": [ { "name": "www-shop", "hosts": ["www.example-shop.test", "example-shop.test"], "sans": ["www.example-shop.test", "example-shop.test"], "issuer": "Let's Encrypt", "not_before": "2026-09-20", "not_after": "2026-12-19", "key_type": "ec", "key_bits": 256, "sig_alg": "ecdsa-with-SHA384", "auto_renew": true, "renew_method": "certbot on web-1, cron twice daily", "chain_complete": true, "environment": "production", "owner": "web-team" }, { "name": "checkout-api", "hosts": ["checkout.example-shop.test", "pay.example-shop.test"], "sans": ["checkout.example-shop.test"], "issuer": "Commercial CA", "not_before": "2026-01-10", "not_after": "2026-11-21", "key_type": "rsa", "key_bits": 2048, "sig_alg": "sha256WithRSAEncryption", "auto_renew": false, "chain_complete": false, "environment": "production", "owner": "payments" }, { "name": "wildcard-prod", "hosts": ["blog.example-shop.test", "img.cdn.example-shop.test"], "sans": ["*.example-shop.test"], "issuer": "Let's Encrypt", "not_before": "2026-09-01", "not_after": "2026-11-30", "key_type": "rsa", "key_bits": 3072, "sig_alg": "sha256WithRSAEncryption", "auto_renew": true, "renew_method": "acme.sh DNS-01 via DNS API token", "chain_complete": true, "environment": "production", "owner": "platform" }, { "name": "wildcard-staging", "hosts": ["staging.example-shop.test"], "sans": ["*.example-shop.test"], "issuer": "Let's Encrypt", "not_before": "2026-10-20", "not_after": "2027-01-18", "key_type": "rsa", "key_bits": 3072, "sig_alg": "sha256WithRSAEncryption", "auto_renew": true, "chain_complete": true, "environment": "staging", "owner": "platform" }, { "name": "legacy-vpn", "hosts": ["vpn.example-shop.test"], "sans": ["vpn.example-shop.test"], "issuer": "Old Commercial CA", "not_before": "2024-10-01", "not_after": "2026-11-05", "key_type": "rsa", "key_bits": 1024, "sig_alg": "sha1WithRSAEncryption", "auto_renew": false, "chain_complete": true, "environment": "production", "owner": "" }, { "name": "status-page", "hosts": ["status.example-shop.test"], "sans": ["status.example-shop.test"], "issuer": "status-page.local", "self_signed": true, "not_before": "2026-06-01", "not_after": "2027-06-01", "key_type": "ec", "key_bits": 256, "sig_alg": "ecdsa-with-SHA256", "auto_renew": false, "renewal_runbook": "https://wiki.example-shop.test/runbooks/status-cert", "chain_complete": true, "environment": "production", "public": true, "owner": "sre" }, { "name": "internal-api", "pem_path": "certs/internal-api.pem", "hosts": ["internal-api.corp.example", "api-admin.corp.example", "metrics.corp.example"], "key_type": "rsa", "key_bits": 2048, "sig_alg": "sha256WithRSAEncryption", "auto_renew": false, "renewal_runbook": "https://wiki.example-shop.test/runbooks/internal-ca", "chain_complete": true, "environment": "production", "public": false, "owner": "platform" }, { "name": "mail-relay", "hosts": ["mail.example-shop.test"], "sans": ["mail.example-shop.test"], "issuer": "Let's Encrypt", "not_before": "2026-10-05", "not_after": "2027-01-03", "key_type": "ec", "key_bits": 256, "sig_alg": "ecdsa-with-SHA384", "auto_renew": true, "chain_complete": true, "environment": "production", "owner": "it-ops" }, { "name": "partner-sftp", "hosts": ["sftp.example-shop.test"], "sans": ["sftp.example-shop.test"], "issuer": "Commercial CA", "not_before": "2026-01-05", "not_after": "2026-12-08", "key_type": "rsa", "key_bits": 2048, "sig_alg": "sha256WithRSAEncryption", "auto_renew": false, "chain_complete": true, "environment": "production", "owner": "it-ops" } ] } FILE:examples/certs/internal-api.pem -----BEGIN CERTIFICATE----- MIIDhTCCAm2gAwIBAgICEJIwDQYJKoZIhvcNAQELBQAwOzEiMCAGA1UEAwwZaW50 ZXJuYWwtYXBpLmNvcnAuZXhhbXBsZTEVMBMGA1UECgwMRXhhbXBsZSBDb3JwMB4X DTI2MTExMTA3MDc0OFoXDTI3MTIxNjA3MDc0OFowOzEiMCAGA1UEAwwZaW50ZXJu YWwtYXBpLmNvcnAuZXhhbXBsZTEVMBMGA1UECgwMRXhhbXBsZSBDb3JwMIIBIjAN BgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA4oUJHnqdN4I9apnhjwPs7hVQbTO/ vokjVcg4youOUoOEvGZnaNpEFqXL8msD7Xpfj8tkzhRsfxOAjzataIH/0vhJncPW YPdcV8bV6AjbT1DXD7NrcWzztnVVU69qctruVT2ir1ZX9kf60uT8LXwrC2xmGELR MmkIxu9yU2u8qa+5fuj+IPX3K2MaveQGpF8uWlklCRKTFdpLJpw/Gz4OPEVFn8zk uR6PGg0434aoF9oW9dJugLqfpqNDpbzQIi4Im3CsNSRgXDTiZTiP+zCBMGhpHvJT OpstU/9JSM9m78jAoA0rfyF/Fhl/Qrcb6gHtmswEuu9NBnIr7tbr5qyZxQIDAQAB o4GSMIGPMB0GA1UdDgQWBBQLC7n+evl0kJ5lrXrErQKoOEHYpDAfBgNVHSMEGDAW gBQLC7n+evl0kJ5lrXrErQKoOEHYpDAPBgNVHRMBAf8EBTADAQH/MDwGA1UdEQQ1 MDOCGWludGVybmFsLWFwaS5jb3JwLmV4YW1wbGWCFmFwaS1hZG1pbi5jb3JwLmV4 YW1wbGUwDQYJKoZIhvcNAQELBQADggEBANhJq+F8Ux8tYMJgH+TTZ2SnKr6lamzz 0VmSvCYmRz0xIsDzPczvKoHnngxPObV6XwhkAg+mVUW04R2hpVsaLNxfj6zceTN7 IrP75HT4zrthfWjXy1mXO4frMvKgJnS7GQ79CxVVj5CPTsovKGaXzaqC8mHTe+0C meOv7kglUD6CO35X9Lq8bnrWA771HpiFddK7+d5Y34uQaUbEmMrM5drjw7gn+hxh w2+tOOSIhOBqoU/tmtslbr+ZyJ4IuItpUDkeEk/n3K6TVMZ6eZHYqjQly2H4lJxE TsgyHYYiR286zwyr2sKmF7ZGtD9B5yJR6sorJhCAUJuv7EaU7XqOMcU= -----END CERTIFICATE----- FILE:scripts/check_certs.py #!/usr/bin/env python3 """TLS certificate expiry and inventory checker (Python 3.8+ standard library only). Reads a JSON inventory of certificates (and optional PEM files referenced by "pem_path") and reports TC01-TC14 findings: expiry, stuck renewals, hostname coverage, weak keys, weak signatures, long lifetimes, broken chains, self-signed public certs, ownership, shared wildcards and renewal clusters. Usage: python3 scripts/check_certs.py examples/inventory.json --today 2026-11-11 python3 scripts/check_certs.py inventory.json --json python3 scripts/check_certs.py --self-test Exit codes: 0 = no high findings, 1 = high findings, 2 = bad input. """ import argparse, datetime as dt, json, os, ssl, sys SEV_ORDER = {"high": 0, "medium": 1, "low": 2} WEAK_SIG = ("sha1", "md5") MIN_BITS = {"rsa": 2048, "dsa": 2048, "ec": 256, "ecdsa": 256, "ed25519": 0} def parse_date(s): """Accept YYYY-MM-DD, ISO timestamps, or OpenSSL style 'Nov 11 10:00:00 2026 GMT'.""" if not s: return None s = str(s).strip() for fmt in ("%Y-%m-%d", "%Y-%m-%dT%H:%M:%SZ", "%Y-%m-%dT%H:%M:%S", "%b %d %H:%M:%S %Y %Z"): try: return dt.datetime.strptime(s, fmt).date() except ValueError: pass try: return dt.datetime.utcfromtimestamp(ssl.cert_time_to_seconds(s)).date() except (ValueError, TypeError): raise ValueError("unparseable date: %r" % s) def decode_pem(path): """Decode a PEM certificate with the stdlib test decoder; returns a partial cert dict.""" info = ssl._ssl._test_decode_cert(path) # stdlib, no third-party crypto needed subject = {k: v for rdn in info.get("subject", ()) for k, v in rdn} issuer = {k: v for rdn in info.get("issuer", ()) for k, v in rdn} sans = [v for k, v in info.get("subjectAltName", ()) if k == "DNS"] return { "subject_cn": subject.get("commonName", ""), "issuer": issuer.get("organizationName") or issuer.get("commonName", ""), "issuer_cn": issuer.get("commonName", ""), "not_before": info.get("notBefore"), "not_after": info.get("notAfter"), "sans": sans, "serial": info.get("serialNumber", ""), } def host_covered(host, sans): host = host.lower().rstrip(".") for san in sans: san = san.lower().rstrip(".") if san == host: return True if san.startswith("*."): base = san[2:] # a wildcard matches exactly one label: *.example.com covers a.example.com, not a.b.example.com or example.com if host.endswith("." + base) and host.count(".") == base.count(".") + 1: return True return False def load(path, base_dir): with open(path, encoding="utf-8") as f: data = json.load(f) certs = data["certificates"] if isinstance(data, dict) else data if not isinstance(certs, list) or not certs: raise ValueError("inventory must contain a non-empty 'certificates' list") out = [] for i, c in enumerate(certs): c = dict(c) c.setdefault("name", "cert-%d" % (i + 1)) if c.get("pem_path"): p = c["pem_path"] if not os.path.isabs(p): p = os.path.join(base_dir, p) pem = decode_pem(p) for k, v in pem.items(): if not c.get(k): c[k] = v c["_from_pem"] = True out.append(c) return out def check(certs, today, warn_days=30, crit_days=14): findings = [] def add(code, sev, cert, msg, fix): findings.append({"code": code, "severity": sev, "cert": cert["name"], "message": msg, "fix": fix}) expiry_dates = [] wildcard_envs = {} for c in certs: na, nb = parse_date(c.get("not_after")), parse_date(c.get("not_before")) if na is None: add("TC00", "high", c, "no not_after date", "Add not_after or a pem_path so expiry can be checked.") continue left = (na - today).days c["_days_left"] = left expiry_dates.append((na, c["name"])) auto = bool(c.get("auto_renew")) public = c.get("public", True) if left < 0: add("TC01", "high", c, "expired %d days ago (%s)" % (-left, na), "Renew and deploy now; check every host in 'hosts'.") elif left <= crit_days: add("TC02", "high", c, "expires in %d days (%s)" % (left, na), "Renew this week; confirm the new cert is actually served.") elif left <= warn_days and not auto: add("TC03", "medium", c, "expires in %d days with manual renewal" % left, "Schedule the renewal with an owner and a date.") if auto and 0 <= left <= 20: add("TC04", "medium", c, "auto_renew is on but only %d days left - renewal looks stuck" % left, "Check the renewal job logs (ACME clients renew around 30 days left); fix DNS/HTTP challenge or permissions.") if nb and nb > today: add("TC14", "high", c, "not_before %s is in the future" % nb, "Check server clock or wait; clients will reject it now.") sans = c.get("sans") or [] for h in c.get("hosts") or []: if not host_covered(h, sans): add("TC05", "high", c, "host %s is not covered by SANs %s" % (h, sans), "Reissue with the host in subjectAltName (CN alone is ignored by browsers).") kt = str(c.get("key_type", "")).lower() bits = c.get("key_bits") if kt in MIN_BITS and bits is not None and int(bits) < MIN_BITS[kt]: add("TC06", "high", c, "%s key of %s bits is too small (min %d)" % (kt.upper(), bits, MIN_BITS[kt]), "Reissue with RSA 2048+/3072 or ECDSA P-256.") sig = str(c.get("sig_alg", "")).lower() if any(w in sig for w in WEAK_SIG): add("TC07", "high", c, "weak signature algorithm %s" % c.get("sig_alg"), "Reissue with a SHA-256 based signature.") if nb and na and public and (na - nb).days > 398: add("TC08", "medium", c, "lifetime %d days exceeds 398 days for a publicly trusted cert" % (na - nb).days, "Publicly trusted certs must be <=398 days and are getting shorter; automate renewal.") if c.get("chain_complete") is False: add("TC09", "high", c, "served chain is incomplete (missing intermediate)", "Serve the full chain (leaf + intermediates); test with a fresh client.") self_signed = c.get("self_signed") if self_signed is None and c.get("subject_cn") and c.get("issuer_cn"): self_signed = c["subject_cn"] == c["issuer_cn"] if self_signed and public: add("TC10", "high", c, "self-signed certificate on a public endpoint", "Use a publicly trusted CA cert, or mark public=false if internal-only.") if not c.get("owner"): add("TC11", "medium", c, "no owner recorded", "Name a team or person who gets the expiry alert.") if any(str(s).startswith("*.") for s in sans): for s in sans: if str(s).startswith("*."): wildcard_envs.setdefault(s, set()).add(str(c.get("environment", "unknown"))) if not auto and not c.get("renewal_runbook"): add("TC12", "low", c, "manual renewal without a runbook link", "Add a short renewal runbook (CSR, CA, deploy targets, test).") for wc, envs in wildcard_envs.items(): if "production" in envs and len(envs) > 1: findings.append({"code": "TC13", "severity": "medium", "cert": wc, "message": "wildcard %s is used in production and %s" % (wc, ", ".join(sorted(envs - {"production"}))), "fix": "Use separate certs per environment to shrink the blast radius of a leaked key."}) expiry_dates.sort() for i in range(len(expiry_dates)): window = [n for d, n in expiry_dates if 0 <= (d - expiry_dates[i][0]).days <= 7 and d >= today] if len(window) >= 3: findings.append({"code": "TC15", "severity": "low", "cert": ", ".join(window), "message": "%d certs expire within the same 7-day window" % len(window), "fix": "Stagger renewals so one bad week cannot take down several services."}) break findings.sort(key=lambda f: (SEV_ORDER[f["severity"]], f["code"], f["cert"])) return findings def report(certs, findings, today): lines = ["TLS certificate check as of %s - %d certificates" % (today, len(certs)), ""] lines.append("%-24s %-12s %6s %-10s %s" % ("NAME", "EXPIRES", "DAYS", "AUTO", "OWNER")) for c in sorted(certs, key=lambda c: c.get("_days_left", -10**6)): na = parse_date(c.get("not_after")) lines.append("%-24s %-12s %6s %-10s %s" % (c["name"][:24], na or "?", c.get("_days_left", "?"), "yes" if c.get("auto_renew") else "no", c.get("owner") or "-")) counts = {s: sum(1 for f in findings if f["severity"] == s) for s in SEV_ORDER} lines += ["", "Findings: %d high, %d medium, %d low" % (counts["high"], counts["medium"], counts["low"]), ""] for f in findings: lines.append("[%s] %s %s: %s" % (f["severity"].upper(), f["code"], f["cert"], f["message"])) lines.append(" fix: %s" % f["fix"]) if not findings: lines.append("No findings.") return "\n".join(lines) def self_test(): today = dt.date(2026, 11, 11) base = {"name": "ok", "hosts": ["a.example.com"], "sans": ["a.example.com"], "not_before": "2026-09-01", "not_after": "2027-01-20", "key_type": "ec", "key_bits": 256, "sig_alg": "ecdsa-with-SHA256", "auto_renew": True, "owner": "web", "chain_complete": True, "environment": "production"} def run(**kw): c = dict(base); c.update(kw) return {f["code"] for f in check([c], today)} cases = [ ("clean", run(), set()), ("TC01 expired", run(not_after="2026-11-01") >= {"TC01"}, True), ("TC02 critical", run(not_after="2026-11-20") >= {"TC02"}, True), ("TC03 manual 30d", run(not_after="2026-12-05", auto_renew=False, renewal_runbook="x") >= {"TC03"}, True), ("TC04 stuck renewal", "TC04" in run(not_after="2026-11-28"), True), ("TC05 SAN miss", "TC05" in run(hosts=["b.example.com"]), True), ("wildcard one label", host_covered("a.example.com", ["*.example.com"]) and not host_covered("x.a.example.com", ["*.example.com"]) and not host_covered("example.com", ["*.example.com"]), True), ("TC06 weak rsa", "TC06" in run(key_type="rsa", key_bits=1024), True), ("TC07 sha1", "TC07" in run(sig_alg="sha1WithRSAEncryption"), True), ("TC08 long life", "TC08" in run(not_before="2025-01-01", not_after="2027-01-01"), True), ("TC08 private ok", "TC08" in run(not_before="2025-01-01", not_after="2027-01-01", public=False), False), ("TC09 chain", "TC09" in run(chain_complete=False), True), ("TC10 self-signed", "TC10" in run(self_signed=True), True), ("TC11 owner", "TC11" in run(owner=""), True), ("TC14 future", "TC14" in run(not_before="2026-12-01"), True), ] two = [dict(base, name="w1", sans=["*.example.com"], hosts=["a.example.com"]), dict(base, name="w2", sans=["*.example.com"], hosts=["a.example.com"], environment="staging")] cases.append(("TC13 shared wildcard", any(f["code"] == "TC13" for f in check(two, today)), True)) three = [dict(base, name="c%d" % i, not_after="2027-01-0%d" % (i + 1)) for i in range(3)] cases.append(("TC15 cluster", any(f["code"] == "TC15" for f in check(three, today)), True)) cases.append(("date formats", parse_date("Nov 11 10:00:00 2026 GMT") == dt.date(2026, 11, 11), True)) ok = 0 for name, got, want in cases: passed = got == want ok += passed print("%s %s" % ("PASS" if passed else "FAIL", name)) print("%d/%d passed" % (ok, len(cases))) return 0 if ok == len(cases) else 1 def main(argv=None): ap = argparse.ArgumentParser(description=__doc__.splitlines()[0]) ap.add_argument("inventory", nargs="?") ap.add_argument("--today", help="as-of date YYYY-MM-DD (default: today)") ap.add_argument("--warn-days", type=int, default=30) ap.add_argument("--crit-days", type=int, default=14) ap.add_argument("--json", action="store_true") ap.add_argument("--self-test", action="store_true") a = ap.parse_args(argv) if a.self_test: return self_test() if not a.inventory: ap.print_usage(); return 2 try: today = parse_date(a.today) if a.today else dt.date.today() certs = load(a.inventory, os.path.dirname(os.path.abspath(a.inventory))) findings = check(certs, today, a.warn_days, a.crit_days) except (OSError, ValueError, KeyError, json.JSONDecodeError, ssl.SSLError) as e: print("input error: %s" % e, file=sys.stderr) return 2 if a.json: clean = [{k: v for k, v in c.items() if not k.startswith("_") or k == "_days_left"} for c in certs] print(json.dumps({"today": str(today), "certificates": clean, "findings": findings}, indent=2, default=str)) else: print(report(certs, findings, today)) return 1 if any(f["severity"] == "high" for f in findings) else 0 if __name__ == "__main__": sys.exit(main())

Small Shop Inventory Reorder Planner

--- name: small-shop-inventory-reorder-planner description: Plans reorders for a small shop, cafe or online store from an items CSV and a settings JSON. Computes safety stock, reorder points and order-up-to levels, rounds orders to case packs and MOQs, caps perishables to shelf life, flags stockouts before delivery, dead stock, overstock and negative margins, groups orders by supplier and fits them into a cash budget. Offline stdlib Python planner. --- # Small Shop Inventory Reorder Planner You help owners of small shops, cafes, market stalls and online stores decide what to order this week and how much. Running out of a best seller loses sales and regulars; over-ordering ties up cash and, for food, ends up in the bin. You take a simple items sheet and a few settings and produce a clear order list per supplier with the reasoning behind each number. You do not place orders, contact suppliers or change the user's POS or accounting data. Numbers are planning estimates based on the sales averages the user provides. ## Files in this skill - `scripts/plan_reorders.py` - reads `items.csv` and `settings.json`; computes safety stock, reorder point (ROP), order-up-to level and suggested order quantity; flags RP01-RP10 (stockout before delivery, open orders too small, at reorder point, MOQ overstock, perishable cap and waste risk, dead stock, overstock, price not above cost, assumed demand variability, cash budget deferrals); groups by supplier and checks supplier minimums (Python 3.8+ standard library only) - `references/reorder-math.md` - the formulas in plain words, service levels and how to get the inputs from a POS export - `references/practical-ordering.md` - perishables, MOQs, case packs, cash budgets, dead stock and supplier minimums - `templates/order-plan.md` - the weekly order note you hand back - `examples/items.csv` - eleven items for a fictional cafe and pantry, with several traps - `examples/settings.json` - service level, review period, cash budget and supplier minimums ## Workflow ### 1. Collect the data Ask for one row per item: `sku`, `name`, `supplier`, `on_hand`, `on_order`, `avg_daily_sales`, `sd_daily_sales` (optional), `lead_time_days`, `moq`, `case_pack`, `unit_cost`, `unit_price`, `shelf_life_days` (blank if not perishable). Help the user get average daily sales from the last 4-8 weeks of POS data (units sold divided by days open). Ask for the review rhythm (how often they order), a service level (0.90-0.98) and this week's cash budget. ### 2. Run the planner ``` python3 scripts/plan_reorders.py examples/items.csv examples/settings.json python3 scripts/plan_reorders.py items.csv settings.json --json python3 scripts/plan_reorders.py --self-test ``` Exit 0 = no high findings, 1 = at least one item will run out before an order can arrive, 2 = bad input. Without a shell, apply the formulas in `references/reorder-math.md` row by row. ### 3. Read the result - High: RP01 runs out before a new order can arrive (order today, consider a faster supplier or a substitute), RP02 open orders are too small to cover the lead time, RP10 when a stockout-risk item does not fit the budget. - Medium: RP03 at or below the reorder point (order now), RP04 MOQ forces more than two months of stock, RP05 perishable capped to shelf life or waste risk, RP08 price not above cost, RP10 deferred for budget. - Low: RP06 dead stock, RP07 overstock beyond `overstock_days`, RP09 demand variability assumed. ### 4. Deliver Fill `templates/order-plan.md`: orders grouped by supplier with totals, items deferred for cash, perishables with a suggested ordering rhythm, and three actions for slow or dead stock. Keep the language simple; owners often read this on a phone between customers. ## Example result On the sample cafe (95% service level, weekly review, $420 budget), house coffee beans will run out in about 4 days against a 5-day lead time (high, order 48 now), sourdough and cookies are capped to their 3- and 7-day shelf lives with advice to order more often, orange juice sells below cost and its MOQ still risks waste, the PackRight and Dairy orders fall below supplier minimums, logo mugs are dead stock and paper straws have 150 days of cover. Spend: $387.70 of $420. ## Rules - Base every number on the CSV and settings; show the formula inputs when asked. - If sales history is short, seasonal or distorted by a stockout, say so and suggest adjusting the average manually. - Never invent supplier terms, prices or lead times; mark unknowns and ask. - This is a planning aid, not accounting or financial advice. FILE:references/reorder-math.md # Reorder math in plain words Symbols: d = average daily sales, sd = day-to-day variation of sales, L = lead time in days (order to shelf), R = review period in days (how often you place orders), z = service-level factor. | Quantity | Formula | Meaning | |---|---|---| | Safety stock (SS) | z x sd x sqrt(L + R) | Buffer for busier-than-average days while you wait | | Reorder point (ROP) | d x L + SS | When stock on hand plus on order falls to this, order | | Order-up-to level | d x (L + R) + SS | Enough to last until the next order arrives | | Inventory position | on hand + on order | What you have or will soon have | | Order quantity | order-up-to - position, then MOQ, then round up to case pack | What to buy now | | Days of cover | on hand / d | How long current stock lasts | ## Service level - 0.90 -> z about 1.28; 0.95 -> 1.64; 0.98 -> 2.05; 0.99 -> 2.33. - Use higher levels for best sellers and items customers come in for; lower for impulse or easily substituted items. ## Getting the inputs - d: units sold in the last 28-56 open days divided by the number of open days. Exclude days the item was out of stock. - sd: standard deviation of daily units in the same window. A spreadsheet STDEV over daily totals works. If unknown, the script assumes 50% of d (RP09). - L: from the day you place the order to the day it is on the shelf, including delivery days and receiving time. Use the slow end of the usual range. - R: 7 for weekly ordering, 1 for daily bread or dairy runs. ## Limits - Averages lag behind trends and seasons (holidays, weather, school terms). Adjust d by hand for the coming period. - New items have no history: start with a small order and review after a week. FILE:references/practical-ordering.md # Practical ordering rules ## Perishables (RP05) - Never order more than you can sell within the shelf life: the script caps the order at d x shelf life - position and rounds DOWN to the case pack. - If the cap keeps cutting orders, order more often (shorter review period) rather than accepting waste. - If an MOQ forces more than you can sell, ask the supplier for a smaller pack, share an order with a neighbour business, or drop the item. ## MOQ and case packs (RP04) - Case packs round up for non-perishables. A big MOQ on a slow item can lock up months of cash: compare MOQ / d with your overstock limit. ## Cash budget (RP10) - Items that would run out before delivery are funded first, then the rest by margin x daily sales (what earns most per day). - Deferred items are listed so you can decide: raise the budget, split the order, or accept a short gap on low-margin items. ## Supplier minimum orders - If a supplier order is below their minimum, either add slow-moving items you will need soon from that supplier or skip this cycle if stock allows. ## Dead stock and overstock (RP06, RP07) - Dead stock (no sales, stock on hand): bundle it with best sellers, mark it down, return it if terms allow, or use it as a gift with purchase. - Overstock (more than 90 days of cover): pause reorders, move it to a better shelf position, or run a small promotion. ## Pricing (RP08) - An item sold at or below cost needs a price review, a cheaper supplier, or a deliberate decision to keep it as a traffic driver. ## Weekly routine (15 minutes) 1. Export or count on-hand stock for the order list. 2. Update on_order with anything not yet received. 3. Run the planner, read high flags first. 4. Place orders per supplier, note expected delivery dates. 5. Once a month, refresh d and sd from the POS. FILE:templates/order-plan.md # Weekly order plan - {{shop}} Week of: {{date}} | Service level: {{service_level}} | Budget: {{currency}}{{budget}} | Spend now: {{currency}}{{spend}} ## Order today (stockout risk) | Item | On hand | Days of cover | Lead time | Order | Cost | |---|---|---|---|---|---| | {{item}} | {{on_hand}} | {{cover}} | {{lead_time}} d | {{qty}} | {{cost}} | ## Orders by supplier ### {{supplier}} - {{lines}} lines, {{currency}}{{total}} {{(below minimum: note)}} | Item | Order qty | Case pack | Cost | Why | |---|---|---|---|---| | {{item}} | {{qty}} | {{pack}} | {{cost}} | {{at reorder point / perishable cap / MOQ}} | ## Deferred for cash - {{item}}: {{cost}} - {{decision needed: raise budget, split order, accept a short gap}} ## Perishables - {{item}}: capped to {{qty}} for a {{shelf_life}}-day shelf life -> order every {{days}} days instead of weekly. ## Slow and dead stock - {{item}}: {{days of cover or no sales}} -> {{bundle / markdown / return / pause}} ## Price checks - {{item}}: price {{price}} vs cost {{cost}} -> {{review}} Numbers come from your items sheet and settings; check unusual weeks (holidays, events) before ordering. FILE:examples/items.csv sku,name,supplier,on_hand,on_order,avg_daily_sales,sd_daily_sales,lead_time_days,moq,case_pack,unit_cost,unit_price,shelf_life_days CB-250,House coffee beans 250g,Roastery North,18,0,4.2,1.8,5,24,6,5.40,12.50 OM-1L,Oat milk 1L,Dairy and Plant Co,30,24,6.5,2.5,3,12,12,1.35,2.90,60 SB-12,Sourdough loaf,Local Bakery,8,0,7.0,2.0,1,,1,2.10,5.00,3 CP-12,Paper cups 12oz (sleeve of 50),PackRight,9,0,0.9,0.4,10,20,10,3.80,0, JR-HN,Wildflower honey jar 340g,Hill Apiary,26,0,0.6,0.5,14,48,12,4.20,9.90,720 TB-EG,English breakfast tea 50 bags,Leaf Traders,40,0,1.1,0.6,7,,10,2.60,6.50,540 CK-CH,Chocolate chip cookies 6-pack,Local Bakery,12,0,3.0,,2,,6,1.90,4.20,7 GF-BR,Gluten-free brownies 4-pack,Free From Foods,6,12,1.4,0.7,6,24,12,3.10,6.90,21 MG-CE,Ceramic mug with shop logo,PackRight,64,0,0,,21,,6,4.50,14.00, ST-PA,Paper straws (box of 250),PackRight,30,0,0.2,0.1,10,,1,6.00,0, OJ-1L,Fresh orange juice 1L,Dairy and Plant Co,10,0,2.5,1.2,2,6,6,2.30,2.20,6 FILE:examples/settings.json { "shop": "Corner Mill Cafe and Pantry (fictional)", "currency": "$", "service_level": 0.95, "review_period_days": 7, "overstock_days": 90, "cash_budget": 420, "supplier_min_order": { "PackRight": 150, "Dairy and Plant Co": 60 } } FILE:scripts/plan_reorders.py #!/usr/bin/env python3 """Small shop inventory reorder planner (Python 3.8+ standard library only). Reads an items CSV and a settings JSON, computes safety stock, reorder point, order-up-to level and a suggested order per SKU (rounded to case pack and MOQ), flags RP01-RP10 risks, groups orders by supplier and fits them into a cash budget. Usage: python3 scripts/plan_reorders.py examples/items.csv examples/settings.json python3 scripts/plan_reorders.py items.csv settings.json --json python3 scripts/plan_reorders.py --self-test Exit codes: 0 = no high findings, 1 = high findings (stockout risk), 2 = bad input. """ import argparse, csv, json, math, sys from statistics import NormalDist REQUIRED = ["sku", "name", "on_hand", "avg_daily_sales", "lead_time_days"] SEV = {"high": 0, "medium": 1, "low": 2} def num(row, key, default=0.0): v = (row.get(key) or "").strip() if v == "": return default return float(v) def load_items(path): with open(path, newline="", encoding="utf-8") as f: rows = list(csv.DictReader(f)) if not rows: raise ValueError("items CSV is empty") missing = [c for c in REQUIRED if c not in rows[0]] if missing: raise ValueError("items CSV missing columns: %s" % ", ".join(missing)) return rows def plan_item(row, s): z = NormalDist().inv_cdf(s.get("service_level", 0.95)) R = float(s.get("review_period_days", 7)) it = {"sku": row["sku"].strip(), "name": row["name"].strip(), "supplier": (row.get("supplier") or "unknown").strip() or "unknown"} d = num(row, "avg_daily_sales") sd = num(row, "sd_daily_sales", d * 0.5) # assume fairly noisy demand if unknown L = num(row, "lead_time_days") on_hand, on_order = num(row, "on_hand"), num(row, "on_order") moq, pack = num(row, "moq", 0), max(1.0, num(row, "case_pack", 1)) cost, price = num(row, "unit_cost"), num(row, "unit_price") shelf = num(row, "shelf_life_days", 0) ss = z * sd * math.sqrt(L + R) rop = d * L + ss up_to = d * (L + R) + ss pos = on_hand + on_order qty = 0.0 if d > 0 and pos <= rop: qty = max(up_to - pos, 0) if moq and qty < moq: qty = moq qty = math.ceil(qty / pack) * pack capped = False if shelf and d > 0 and qty > 0 and pos + qty > d * shelf: # perishable: never order more than can sell within shelf life (round DOWN to the case pack) cap = math.floor(max(d * shelf - pos, 0) / pack) * pack if moq and cap < moq: qty = min(qty, math.ceil(moq / pack) * pack) # smallest allowed order; RP05 below warns about waste else: capped = qty != cap qty = cap it.update({ "avg_daily_sales": d, "lead_time_days": L, "on_hand": on_hand, "on_order": on_order, "safety_stock": round(ss, 1), "reorder_point": round(rop, 1), "order_up_to": round(up_to, 1), "inventory_position": pos, "order_qty": int(qty), "order_cost": round(qty * cost, 2), "days_of_cover": round(on_hand / d, 1) if d > 0 else None, "margin_per_unit": round(price - cost, 2) if price else None, "shelf_life_days": shelf, "flags": [], }) def flag(code, sev, msg): it["flags"].append({"code": code, "severity": sev, "sku": it["sku"], "message": msg}) if d > 0 and on_hand < d * L and on_order == 0: flag("RP01", "high", "will run out in about %.0f days, before a new order (lead time %.0f d) can arrive" % (on_hand / d, L)) elif d > 0 and on_hand + on_order < d * L: flag("RP02", "high", "stock plus open orders cover %.0f days, less than the %.0f-day lead time" % (pos / d, L)) if qty > 0: flag("RP03", "medium", "at or below reorder point (%.0f <= %.0f): order %d now" % (pos, rop, qty)) if d > 0 and qty > 0 and moq and moq > (up_to - pos) * 2 and moq / d > 60: flag("RP04", "medium", "MOQ %d forces about %.0f days of stock; negotiate a smaller MOQ or share an order" % (moq, moq / d)) if capped: flag("RP05", "medium", "perishable: order capped to %d so stock sells within the %.0f-day shelf life; order more often than every %.0f days" % (qty, shelf, R)) elif shelf and d > 0 and (on_hand + on_order + qty) / d > shelf: flag("RP05", "medium", "stock after this order lasts %.1f days but shelf life is %.0f days: waste risk" % ((on_hand + on_order + qty) / d, shelf)) if d == 0 and on_hand > 0: flag("RP06", "low", "no sales recorded but %d on hand (dead stock): consider bundle, markdown or return" % on_hand) elif d > 0 and on_hand / d > s.get("overstock_days", 90): flag("RP07", "low", "%.0f days of cover: overstocked, pause reorders and free up cash" % (on_hand / d)) if price and cost and price <= cost: flag("RP08", "medium", "unit price %.2f is not above unit cost %.2f" % (price, cost)) if not (row.get("sd_daily_sales") or "").strip(): flag("RP09", "low", "no demand variability given; assumed sd = 50% of average (check with sales history)") return it def plan(rows, s): items = [plan_item(r, s) for r in rows] budget = s.get("cash_budget") # priority: stockout risk first, then reorder-point items by margin per day of cover def prio(it): risk = 0 if any(f["code"] in ("RP01", "RP02") for f in it["flags"]) else 1 return (risk, -(it["margin_per_unit"] or 0) * it["avg_daily_sales"]) spend, deferred = 0.0, [] for it in sorted([i for i in items if i["order_qty"] > 0], key=prio): if budget is not None and spend + it["order_cost"] > budget: it["deferred"] = True deferred.append(it["sku"]) it["flags"].append({"code": "RP10", "severity": "medium" if prio(it)[0] else "high", "sku": it["sku"], "message": "order of %.2f does not fit the remaining cash budget; deferred" % it["order_cost"]}) else: it["deferred"] = False spend += it["order_cost"] suppliers = {} for it in items: if it["order_qty"] > 0 and not it.get("deferred"): sp = suppliers.setdefault(it["supplier"], {"lines": 0, "units": 0, "cost": 0.0}) sp["lines"] += 1; sp["units"] += it["order_qty"]; sp["cost"] = round(sp["cost"] + it["order_cost"], 2) for name, sp in suppliers.items(): mo = (s.get("supplier_min_order") or {}).get(name) if mo and sp["cost"] < mo: sp["note"] = "below supplier minimum order %.2f: add slow-moving items or wait a cycle" % mo flags = sorted([f for it in items for f in it["flags"]], key=lambda f: (SEV[f["severity"]], f["code"], f["sku"])) return {"items": items, "suppliers": suppliers, "spend": round(spend, 2), "budget": budget, "deferred": deferred, "flags": flags} def report(res, s): cur = s.get("currency", "") out = ["Reorder plan for %s (service level %.0f%%, review every %s days)" % (s.get("shop", "shop"), s.get("service_level", 0.95) * 100, s.get("review_period_days", 7)), ""] out.append("%-8s %-24s %6s %6s %6s %6s %6s %6s %9s" % ("SKU", "ITEM", "ONHAND", "COVER", "SS", "ROP", "UPTO", "ORDER", "COST")) for it in res["items"]: cover = "-" if it["days_of_cover"] is None else "%.0fd" % it["days_of_cover"] order = ("%d*" % it["order_qty"]) if it.get("deferred") else str(it["order_qty"]) out.append("%-8s %-24s %6d %6s %6.0f %6.0f %6.0f %6s %9.2f" % (it["sku"][:8], it["name"][:24], it["on_hand"], cover, it["safety_stock"], it["reorder_point"], it["order_up_to"], order, it["order_cost"])) out += ["", "Orders by supplier:"] for name, sp in sorted(res["suppliers"].items()): out.append(" %-20s %d lines, %d units, %s%.2f%s" % (name, sp["lines"], sp["units"], cur, sp["cost"], (" (" + sp["note"] + ")") if sp.get("note") else "")) b = res["budget"] out.append("Total to spend now: %s%.2f%s" % (cur, res["spend"], "" if b is None else " of %s%.2f budget" % (cur, b))) if res["deferred"]: out.append("Deferred (marked *): " + ", ".join(res["deferred"])) out += ["", "Flags:"] for f in res["flags"]: out.append(" [%s] %s %s: %s" % (f["severity"].upper(), f["code"], f["sku"], f["message"])) return "\n".join(out) def self_test(): s = {"service_level": 0.95, "review_period_days": 7} def row(**kw): r = {"sku": "A", "name": "a", "on_hand": "100", "on_order": "0", "avg_daily_sales": "5", "sd_daily_sales": "2", "lead_time_days": "7", "moq": "", "case_pack": "1", "unit_cost": "2", "unit_price": "4", "shelf_life_days": ""} r.update({k: str(v) for k, v in kw.items()}); return r def codes(r, st=s): return {f["code"] for f in plan_item(r, st)["flags"]} it = plan_item(row(), s) z = NormalDist().inv_cdf(0.95) cases = [ ("safety stock formula", abs(it["safety_stock"] - round(z * 2 * math.sqrt(14), 1)) < 0.05, True), ("no order above ROP", it["order_qty"], 0), ("RP01 stockout", "RP01" in codes(row(on_hand=10)), True), ("RP02 open order too small", "RP02" in codes(row(on_hand=10, on_order=10)), True), ("RP03 reorder", "RP03" in codes(row(on_hand=40)), True), ("case pack rounding", plan_item(row(on_hand=40, case_pack=12), s)["order_qty"] % 12, 0), ("MOQ applied", plan_item(row(on_hand=40, moq=200), s)["order_qty"] >= 200, True), ("RP04 big MOQ", "RP04" in codes(row(on_hand=40, moq=400)), True), ("RP05 shelf life cap", "RP05" in codes(row(on_hand=40, shelf_life_days=10)), True), ("perishable qty capped", plan_item(row(on_hand=40, shelf_life_days=10), s)["order_qty"], 10), ("RP05 MOQ waste", "RP05" in codes(row(on_hand=40, shelf_life_days=10, moq=100)), True), ("RP06 dead stock", "RP06" in codes(row(avg_daily_sales=0, on_hand=30)), True), ("RP07 overstock", "RP07" in codes(row(on_hand=1000)), True), ("RP08 negative margin", "RP08" in codes(row(unit_price=1.5)), True), ("RP09 sd assumed", "RP09" in codes(row(sd_daily_sales="")), True), ] rows = [row(sku="A", on_hand=10), row(sku="B", on_hand=40, unit_cost=50)] res = plan(rows, dict(s, cash_budget=200)) cases.append(("RP10 budget defers lower priority", res["deferred"], ["B"])) ok = 0 for name, got, want in cases: p = got == want; ok += p print("%s %s" % ("PASS" if p else "FAIL", name)) print("%d/%d passed" % (ok, len(cases))) return 0 if ok == len(cases) else 1 def main(argv=None): ap = argparse.ArgumentParser(description=__doc__.splitlines()[0]) ap.add_argument("items", nargs="?"); ap.add_argument("settings", nargs="?") ap.add_argument("--json", action="store_true"); ap.add_argument("--self-test", action="store_true") a = ap.parse_args(argv) if a.self_test: return self_test() if not a.items: ap.print_usage(); return 2 try: s = {} if a.settings: with open(a.settings, encoding="utf-8") as f: s = json.load(f) if not 0.5 <= s.get("service_level", 0.95) < 1: raise ValueError("service_level must be between 0.5 and 0.999") res = plan(load_items(a.items), s) except (OSError, ValueError, KeyError, json.JSONDecodeError) as e: print("input error: %s" % e, file=sys.stderr); return 2 print(json.dumps(res, indent=2) if a.json else report(res, s)) return 1 if any(f["severity"] == "high" for f in res["flags"]) else 0 if __name__ == "__main__": sys.exit(main())

Webhook Signature Verifier and Replay Guard

--- name: webhook-signature-verifier-and-replay-guard description: Debugs and hardens incoming webhook verification. Recomputes HMAC signatures for Stripe, GitHub, Shopify, Slack or custom schemes from captured raw bodies, explains each mismatch (re-serialized JSON, wrong encoding, missing timestamp, old secret), and flags replayed or stale timestamps, duplicate event ids, weak secrets, SHA1 and plain HTTP endpoints. Offline stdlib Python checker. --- # Webhook Signature Verifier and Replay Guard You help developers who receive webhooks from payment, Git, commerce or chat platforms answer two questions fast: "why does my signature check fail?" and "is my endpoint safe against forged or replayed calls?". Most failures come from a handful of mistakes: verifying a parsed-and-re-encoded body instead of the raw bytes, hex versus base64, forgetting the timestamp in the signed string, or a secret that was rotated on one side only. You reproduce the provider's HMAC exactly, try those mistakes one by one, and say which one it was. You never call the provider's API or the user's endpoint. You work only from captured deliveries and config the user gives you. Treat secrets as sensitive: use test secrets where possible, never echo a production secret back in full, and tell the user to rotate any secret pasted into a shared chat. ## Files in this skill - `scripts/verify_webhooks.py` - reads a deliveries JSON (endpoints + captured raw bodies and headers), verifies each signature with constant-time comparison, diagnoses mismatches and reports WH00-WH11; `--sign` builds valid test headers; `--self-test` runs 11 checks (Python 3.8+ standard library only) - `references/provider-schemes.md` - exactly what Stripe, GitHub, Shopify and Slack sign, plus how to describe a custom scheme - `references/verification-pitfalls.md` - raw body handling per framework, timing-safe compare, replay windows, idempotency, secret rotation - `templates/verification-report.md` - the report you hand back - `templates/handler-snippets.md` - minimal correct handlers for Express and Flask to adapt - `examples/deliveries.json` - 11 demo deliveries to 5 endpoints with fake secrets and several planted mistakes ## Workflow ### 1. Capture the evidence Ask for, per endpoint: provider/scheme, the secret (a test-mode secret is best), the public URL, and for each failing call the **raw** request body exactly as received plus all headers. Logging `JSON.stringify(req.body)` is not the raw body; ask them to log the bytes before any JSON middleware runs (see `references/verification-pitfalls.md`). Put it into the `examples/deliveries.json` shape: `endpoints` (scheme, secret, optional `previous_secrets`, `url`, `id_header`, `max_body_bytes`) and `deliveries` (`id`, `endpoint`, `headers`, `body` as a string, optional `event_id`). ### 2. Run the checker ``` python3 scripts/verify_webhooks.py examples/deliveries.json python3 scripts/verify_webhooks.py my-deliveries.json --now 2026-11-13T07:00:00Z --json python3 scripts/verify_webhooks.py --sign stripe --secret whsec_test_x --body-file body.json --timestamp 1794553200 python3 scripts/verify_webhooks.py --self-test ``` Use `--now` with the time the deliveries were captured, otherwise every old capture shows as a replay. Exit 0 = no high findings, 1 = high findings, 2 = bad input. Without a shell, follow `references/provider-schemes.md` to rebuild the signed string by hand and compare. ### 3. Read the result Each delivery gets a verdict: `accept`, `accept-duplicate(skip side effects)`, `accept-rotate-secret` or `reject`. - High: WH01 signature mismatch (with the likely cause), WH02 missing signature or timestamp header, WH03 timestamp older than the tolerance (replay risk), WH09 endpoint not on HTTPS, WH00 bad input or unknown endpoint. - Medium: WH04 duplicate event id, WH05 timestamp in the future beyond allowed skew (clock drift), WH06 SHA1-only signature, WH07 signed with a previous secret, WH08 short or low-entropy secret. - Low: WH10 no event id to de-duplicate on, WH11 body larger than the configured limit. ### 4. Deliver Fill `templates/verification-report.md`: per-delivery verdicts, the root cause of each mismatch in one sentence with the exact code fix, and a hardening checklist (raw body, constant-time compare, 5-minute window, idempotency store, rotation plan, HTTPS). If they want code, adapt `templates/handler-snippets.md` to their framework, then generate a test vector with `--sign` and re-run until every expected delivery is `accept`. ## Example result On the demo file (now = 13 Nov 2026 07:00 UTC): D01 is valid and D02 is the same Stripe event again (skip side effects); D03 was signed over compact JSON but the app verified a pretty-printed copy; D04 carries a valid signature that is an hour old, so it is rejected as a replay; D06 is still signed with GitHub's previous secret; D07 has only the legacy SHA1 header; D08 compared a hex digest where Shopify sends base64; D10's Slack timestamp is 10 minutes in the future; and the contact form posts to plain HTTP with an 11-character secret. Result: 5 high, 5 medium, 2 low. ## Rules - Always verify against the raw bytes and compare with a constant-time function; never compare signatures with `==`. - Reject before doing work: signature and timestamp checks come before parsing, database writes or queueing. - A valid signature does not make a delivery fresh or unique: check the timestamp window and de-duplicate on the event id. - Do not weaken checks to "make it pass" (no skipping verification in production, no huge tolerances); fix the root cause. - Provider details change; confirm header names and signed-string formats against the provider's current docs before shipping. FILE:references/provider-schemes.md # Provider signature schemes All of these are HMAC over the **raw request body** with a shared secret. The differences are the header, the signed string, the hash and the encoding. Confirm against the provider's current documentation before shipping; names below are the widely used defaults. | Scheme (`scheme`) | Header | Signed string | Hash | Encoding | Timestamp | |---|---|---|---|---|---| | `stripe` | `Stripe-Signature: t=<unix>,v1=<sig>[,v1=<sig2>]` | `<t>.<raw body>` | SHA-256 | hex | `t=` inside the header; default tolerance 300 s | | `github` | `X-Hub-Signature-256: sha256=<sig>` | `<raw body>` | SHA-256 | hex | none (use `X-GitHub-Delivery` to de-duplicate) | | `github-sha1` | `X-Hub-Signature: sha1=<sig>` | `<raw body>` | SHA-1 | hex | legacy, avoid | | `shopify` | `X-Shopify-Hmac-Sha256: <sig>` | `<raw body>` | SHA-256 | base64 | none (de-duplicate on `X-Shopify-Webhook-Id`) | | `slack` | `X-Slack-Signature: v0=<sig>` + `X-Slack-Request-Timestamp` | `v0:<ts>:<raw body>` | SHA-256 | hex | reject if older than 5 minutes | ## Notes per provider - **Stripe**: during secret rolling the header can carry several `v1=` values; accept if any one matches. The endpoint secret starts with `whsec_` and the whole string (prefix included) is the HMAC key. - **GitHub**: the secret is whatever you typed when creating the webhook. Ping events are signed too. Enable the SHA-256 header; the SHA-1 header exists only for old integrations. - **Shopify**: the key is the app's API secret (or the webhook signing secret shown in the admin). The digest is base64, so comparing against a hex digest always fails. - **Slack**: the body is usually `application/x-www-form-urlencoded`; sign the raw string, do not rebuild it from parsed form fields. ## Describing a custom scheme (`scheme: generic`) Set these fields on the endpoint: - `header` - header that carries the signature, e.g. `X-Signature` - `alg` - `sha256`, `sha512` or `sha1` - `enc` - `hex` or `base64` - `prefix` - text before the digest in the header, e.g. `sha256=` (empty if none) - `template` - signed string, using `{body}` and optionally `{ts}`, e.g. `{ts}.{body}` - `ts_header` - header with the unix timestamp, if the scheme has one - `id_header` - header with a unique delivery id, for de-duplication Any field can also override a named scheme (for example a self-hosted GitLab-style proxy that re-signs with a different header). FILE:references/verification-pitfalls.md # Verification pitfalls and hardening ## 1. Use the raw body (the cause of most mismatches) JSON middleware parses the body; re-encoding it changes whitespace, key order or number formatting, so the HMAC no longer matches. - **Express**: mount `express.raw({ type: 'application/json' })` on the webhook route (before `express.json()`), verify `req.body` (a Buffer), then `JSON.parse` it yourself. - **Next.js route handlers**: `const raw = await req.text()` before anything else. - **Flask**: `request.get_data(cache=True, as_text=False)`; do not use `request.json` for verification. - **Django**: `request.body` (bytes) before touching `request.POST`. - **FastAPI/Starlette**: `await request.body()`. - **Go**: read `r.Body` once with `io.ReadAll`, verify, then unmarshal from the same bytes. - Proxies, API gateways and serverless adapters may re-encode bodies (base64 in AWS API Gateway events: decode first) or add a trailing newline. ## 2. Compare in constant time Use `hmac.compare_digest` (Python), `crypto.timingSafeEqual` (Node, equal-length Buffers), `hmac.Equal` (Go), `MessageDigest.isEqual` (Java). Plain `==` leaks timing and invites forgery attempts. ## 3. Freshness and replay - If the scheme signs a timestamp, reject deliveries older than the tolerance (300 s is the common default) **even when the signature is valid**: an attacker who captured one request can resend it. - Allow a small future skew (about 60 s) and keep server clocks on NTP; large future offsets mean a clock problem. - Schemes without a signed timestamp (GitHub, Shopify) rely on de-duplication only. ## 4. Idempotency Providers retry on timeouts and non-2xx responses, so the same event arrives more than once. Store the event or delivery id (or a SHA-256 of the raw body) with a unique constraint and a TTL longer than the provider's retry window (often 3 days); on a repeat, return 200 without re-running side effects. Respond within a few seconds and do slow work in a queue. ## 5. Secrets and rotation - Generate at least 32 random bytes (`python3 -c "import secrets; print(secrets.token_hex(32))"`); one secret per endpoint and environment. - Rotation: add the new secret as primary and keep the old one in `previous_secrets` for a short overlap, accept either, then remove the old one. A delivery that only matches the old secret (WH07) means the sender has not switched yet. - Load secrets from a secret manager or environment, strip whitespace, and never log them. ## 6. Transport and limits - HTTPS only: the HMAC proves origin but does not hide customer data. - Cap body size and reject before parsing; return 401/403 for bad signatures without details, and log the reason internally. - Optional extra layer: allow-list the provider's published IP ranges, but never instead of signature checks. FILE:templates/verification-report.md # Webhook verification report **Endpoints checked:** [names] **Deliveries:** [n] **Captured at:** [time, used as --now] **Verdict:** [All good / Fix before go-live / Under attack or misconfigured] **Findings:** [h] high, [m] medium, [l] low (`verify_webhooks.py` output attached) ## Deliveries | Delivery | Endpoint | Verdict | Root cause (one sentence) | |---|---|---|---| | [D01] | [billing-stripe] | [accept / reject / duplicate / rotate] | [e.g. verified pretty-printed JSON instead of raw body] | ## Fixes, in order 1. [Code fix with file/line, e.g. mount express.raw() on /hooks/stripe before express.json()] 2. [...] 3. [...] ## Hardening checklist - [ ] Verify the raw body bytes, then parse - [ ] Constant-time comparison - [ ] Timestamp window [300] s, future skew [60] s, NTP on all hosts - [ ] Idempotency store keyed on [event id header], TTL [3 days] - [ ] One random secret (32+ bytes) per endpoint and environment; rotation plan with overlap - [ ] HTTPS only, body size limit, 401 without details on failure - [ ] Alert when the failure rate on an endpoint jumps ## Test vectors used [--sign commands and the headers they produced, with test secrets only] FILE:templates/handler-snippets.md # Minimal correct handlers (adapt names, keep the order of checks) ## Node.js / Express (Stripe-style `t=...,v1=...`) ```js const crypto = require('crypto'); const express = require('express'); const app = express(); const SECRET = process.env.WEBHOOK_SECRET; // never hard-code const TOLERANCE = 300; // seconds const seen = new Set(); // use a DB table with a unique key in production app.post('/hooks/stripe', express.raw({ type: 'application/json' }), (req, res) => { const header = req.get('Stripe-Signature') || ''; const parts = Object.fromEntries(header.split(',').map(p => p.split('='))); const t = Number(parts.t); const sigs = header.split(',').filter(p => p.startsWith('v1=')).map(p => p.slice(3)); if (!t || sigs.length === 0) return res.sendStatus(401); if (Math.abs(Date.now() / 1000 - t) > TOLERANCE) return res.sendStatus(401); const expected = crypto.createHmac('sha256', SECRET).update(`${t}.`).update(req.body).digest('hex'); const ok = sigs.some(s => s.length === expected.length && crypto.timingSafeEqual(Buffer.from(s), Buffer.from(expected))); if (!ok) return res.sendStatus(401); const event = JSON.parse(req.body.toString('utf8')); if (seen.has(event.id)) return res.sendStatus(200); // duplicate: no side effects seen.add(event.id); // enqueue(event) and return quickly res.sendStatus(200); }); app.use(express.json()); // other routes after the raw webhook route ``` ## Python / Flask (GitHub `X-Hub-Signature-256`) ```python import hashlib, hmac, json, os from flask import Flask, request, abort app = Flask(__name__) SECRET = os.environ["WEBHOOK_SECRET"].strip().encode() seen = set() # replace with a table that has a UNIQUE constraint on delivery_id @app.post("/hooks/github") def github_hook(): raw = request.get_data(cache=True) # raw bytes, before request.json header = request.headers.get("X-Hub-Signature-256", "") if not header.startswith("sha256="): abort(401) expected = hmac.new(SECRET, raw, hashlib.sha256).hexdigest() if not hmac.compare_digest(header[7:], expected): abort(401) delivery = request.headers.get("X-GitHub-Delivery") if delivery in seen: return "", 200 # duplicate retry seen.add(delivery) event = json.loads(raw) # enqueue(event) and return quickly return "", 200 ``` ## Checklist when porting to another stack Read raw bytes -> check header present -> check timestamp window (if signed) -> HMAC with the right hash/encoding -> constant-time compare (any of several signatures) -> de-duplicate -> parse -> enqueue -> 2xx fast. FILE:examples/deliveries.json { "now": "2026-11-13T07:00:00Z", "tolerance_seconds": 300, "future_skew_seconds": 60, "_note": "Demo data only: every secret below is a fake test value. Bodies are the RAW request bodies exactly as received.", "endpoints": { "billing-stripe": { "scheme": "stripe", "secret": "whsec_demo_4b9e2c7a1f6d3085e2a9c4b7d1f0e6a3", "url": "https://api.acme-demo.test/hooks/stripe", "max_body_bytes": 65536 }, "ci-github": { "scheme": "github", "secret": "gh_demo_secret_9c1e7a3f5b2d8064aa71c3e9f2b5d708", "previous_secrets": [ "gh_demo_old_secret_2f8a6c4e0b1d9375" ], "url": "https://api.acme-demo.test/hooks/github", "id_header": "X-GitHub-Delivery" }, "orders-shopify": { "scheme": "shopify", "secret": "shpss_demo_e3a1c9f7b5d2084b6e2c9a7f1d3b5e80", "url": "https://api.acme-demo.test/hooks/shopify", "id_header": "X-Shopify-Webhook-Id" }, "ops-slack": { "scheme": "slack", "secret": "slack_demo_8f2c6a0e4b9d1735c2e8a6f0b4d9c173", "url": "https://api.acme-demo.test/hooks/slack" }, "contact-form": { "scheme": "generic", "header": "X-Form-Signature", "alg": "sha256", "enc": "hex", "prefix": "", "template": "{body}", "secret": "formhook123", "url": "http://forms.acme-demo.test/hook" } }, "deliveries": [ { "id": "D01", "endpoint": "billing-stripe", "event_id": "evt_3Qx1", "headers": { "Stripe-Signature": "t=1794553160,v1=5ac4a493d3abba1d31c6979909abe3f96f880b5d5567f64e2e1292578d05a6c8" }, "body": "{\"id\":\"evt_3Qx1\",\"type\":\"invoice.paid\",\"data\":{\"object\":{\"id\":\"in_901\",\"amount_paid\":4900,\"currency\":\"usd\",\"customer\":\"cus_77\"}}}" }, { "id": "D02", "endpoint": "billing-stripe", "event_id": "evt_3Qx1", "headers": { "Stripe-Signature": "t=1794553160,v1=5ac4a493d3abba1d31c6979909abe3f96f880b5d5567f64e2e1292578d05a6c8" }, "body": "{\"id\":\"evt_3Qx1\",\"type\":\"invoice.paid\",\"data\":{\"object\":{\"id\":\"in_901\",\"amount_paid\":4900,\"currency\":\"usd\",\"customer\":\"cus_77\"}}}" }, { "id": "D03", "endpoint": "billing-stripe", "event_id": "evt_3Qx2", "headers": { "Stripe-Signature": "t=1794553170,v1=b20e8ff57bb1b1d93f8793c15a2217b54e0e012b3800a1faa32a613e4fbcb5d2" }, "body": "{\n \"id\": \"evt_3Qx1\",\n \"type\": \"invoice.paid\",\n \"data\": {\n \"object\": {\n \"id\": \"in_901\",\n \"amount_paid\": 4900,\n \"currency\": \"usd\",\n \"customer\": \"cus_77\"\n }\n }\n}" }, { "id": "D04", "endpoint": "billing-stripe", "event_id": "evt_2Zk9", "headers": { "Stripe-Signature": "t=1794549600,v1=647af93a8d457b8daee20995225aae284f5ea56cfe075c38cb465fe41ff99bfb" }, "body": "{\"id\":\"evt_3Qx1\",\"type\":\"invoice.paid\",\"data\":{\"object\":{\"id\":\"in_901\",\"amount_paid\":4900,\"currency\":\"usd\",\"customer\":\"cus_77\"}}}" }, { "id": "D05", "endpoint": "ci-github", "headers": { "X-Hub-Signature-256": "sha256=646c0de3d17073a243c74ed3340c018acbea30805a870eff1d6847b4333a5963", "X-GitHub-Delivery": "a1b2-0001" }, "body": "{\"ref\":\"refs/heads/main\",\"after\":\"9f1c2e7\",\"repository\":{\"full_name\":\"acme-demo/shop-api\"},\"pusher\":{\"name\":\"dev-ana\"}}" }, { "id": "D06", "endpoint": "ci-github", "headers": { "X-Hub-Signature-256": "sha256=f728095add7f5315c2eda1d4f6e36040f898f4d0c2d71a42e8154ec05b1f16da", "X-GitHub-Delivery": "a1b2-0002" }, "body": "{\"ref\":\"refs/heads/main\",\"after\":\"9f1c2e7\",\"repository\":{\"full_name\":\"acme-demo/shop-api\"},\"pusher\":{\"name\":\"dev-ana\"}}" }, { "id": "D07", "endpoint": "ci-github", "headers": { "X-Hub-Signature": "sha1=ca66729dfe67d043208370a5b228586808eaa8ce", "X-GitHub-Delivery": "a1b2-0003" }, "body": "{\"ref\":\"refs/heads/main\",\"after\":\"9f1c2e7\",\"repository\":{\"full_name\":\"acme-demo/shop-api\"},\"pusher\":{\"name\":\"dev-ana\"}}" }, { "id": "D08", "endpoint": "orders-shopify", "headers": { "X-Shopify-Hmac-Sha256": "651b34b52d6af57f77251cb9e652c7e409bf05c04695478629ec8104f4bf6992", "X-Shopify-Webhook-Id": "wh-5501" }, "body": "{\"id\":820012,\"email\":\"buyer@example.test\",\"total_price\":\"58.00\",\"currency\":\"EUR\",\"line_items\":[{\"sku\":\"TEA-250\",\"quantity\":2}]}" }, { "id": "D09", "endpoint": "orders-shopify", "headers": { "X-Shopify-Hmac-Sha256": "ZRs0tS1q9X93JRy55lLH5Am/BcBGlUeGKeyBBPS/aZI=", "X-Shopify-Webhook-Id": "wh-5502" }, "body": "{\"id\":820012,\"email\":\"buyer@example.test\",\"total_price\":\"58.00\",\"currency\":\"EUR\",\"line_items\":[{\"sku\":\"TEA-250\",\"quantity\":2}]}" }, { "id": "D10", "endpoint": "ops-slack", "headers": { "X-Slack-Signature": "v0=675094d734821c12a58309211f8d66c58fffbbf86f25ba8424acb5cffd228fe6", "X-Slack-Request-Timestamp": "1794553800" }, "body": "token=demo&team_id=T000&command=%2Fdeploy&text=shop-api+staging&user_name=dev-ana" }, { "id": "D11", "endpoint": "contact-form", "headers": { "X-Form-Signature": "50c78cd627e684b0c1c024f1dfe22cc321a4afb6d25aed29aad8f1c6c2c66dce" }, "body": "{\"form\":\"contact\",\"name\":\"Sam\",\"message\":\"Please call me back\"}" } ] } FILE:scripts/verify_webhooks.py #!/usr/bin/env python3 """Webhook signature verifier and replay guard (offline, Python 3.8+ standard library only). Reads a JSON file with endpoint configs and captured deliveries (raw body + headers), recomputes each HMAC signature, checks timestamps, duplicates and config hygiene, and explains the most likely cause of every mismatch. Usage: verify_webhooks.py deliveries.json [--now 2026-11-13T10:00:00Z] [--json] verify_webhooks.py --sign SCHEME --secret S --body-file body.txt [--timestamp 1794560400] verify_webhooks.py --self-test Exit codes: 0 = no high findings, 1 = high findings, 2 = bad input. """ import argparse, base64, hashlib, hmac, json, math, sys from collections import Counter from datetime import datetime, timezone SCHEMES = { # header, algorithm, encoding, prefix, signed-string template, timestamp header "github": {"header": "X-Hub-Signature-256", "alg": "sha256", "enc": "hex", "prefix": "sha256=", "template": "{body}", "ts_header": None}, "github-sha1": {"header": "X-Hub-Signature", "alg": "sha1", "enc": "hex", "prefix": "sha1=", "template": "{body}", "ts_header": None}, "shopify": {"header": "X-Shopify-Hmac-Sha256", "alg": "sha256", "enc": "base64", "prefix": "", "template": "{body}", "ts_header": None}, "slack": {"header": "X-Slack-Signature", "alg": "sha256", "enc": "hex", "prefix": "v0=", "template": "v0:{ts}:{body}", "ts_header": "X-Slack-Request-Timestamp"}, "stripe": {"header": "Stripe-Signature", "alg": "sha256", "enc": "hex", "prefix": "", "template": "{ts}.{body}", "ts_header": None}, } SEV_ORDER = {"high": 0, "medium": 1, "low": 2, "info": 3} def scheme_for(ep): base = dict(SCHEMES.get(ep.get("scheme", "generic"), {})) for k in ("header", "alg", "enc", "prefix", "template", "ts_header"): if k in ep: base[k] = ep[k] missing = [k for k in ("header", "alg", "enc", "template") if not base.get(k)] if missing: raise ValueError("endpoint %r: generic scheme needs %s" % (ep.get("name"), ", ".join(missing))) base.setdefault("prefix", "") base.setdefault("ts_header", None) return base def digest(secret, msg, alg, enc): mac = hmac.new(secret.encode("utf-8"), msg.encode("utf-8"), getattr(hashlib, alg)).digest() return mac.hex() if enc == "hex" else base64.b64encode(mac).decode("ascii") def signed_string(sch, body, ts): return sch["template"].replace("{ts}", str(ts or "")).replace("{body}", body) def sign(scheme_name, secret, body, ts=None): sch = scheme_for({"scheme": scheme_name}) sig = digest(secret, signed_string(sch, body, ts), sch["alg"], sch["enc"]) if scheme_name == "stripe": return {sch["header"]: "t=%s,v1=%s" % (ts, sig)} out = {sch["header"]: sch["prefix"] + sig} if sch["ts_header"]: out[sch["ts_header"]] = str(ts) return out def get_header(headers, name): for k, v in headers.items(): if k.lower() == name.lower(): return v return None def parse_stripe(value): ts, sigs = None, [] for part in value.split(","): k, _, v = part.strip().partition("=") if k == "t": ts = v elif k == "v1": sigs.append(v) return ts, sigs def entropy_bits(secret): if not secret: return 0.0 counts = Counter(secret) h = -sum(c / len(secret) * math.log2(c / len(secret)) for c in counts.values()) return h * len(secret) def diagnose(sch, ep, body, ts, received): """Try the usual mistakes and return a human explanation, or None.""" secret = ep["secret"] alg, enc = sch["alg"], sch["enc"] tries = [] for old in ep.get("previous_secrets", []): tries.append(("WH07", "matches a PREVIOUS secret: the sender still signs with the old secret (finish the rotation)", old, signed_string(sch, body, ts), enc)) try: obj = json.loads(body) tries.append(("WH01", "matches the body re-serialized as compact JSON: the sender or your framework parsed and re-encoded the payload before signing/verifying; always use the raw bytes", secret, signed_string(sch, json.dumps(obj, separators=(",", ":")), ts), enc)) tries.append(("WH01", "matches the body re-serialized with default json.dumps spacing: verify against the raw request body, not a parsed object", secret, signed_string(sch, json.dumps(obj), ts), enc)) except ValueError: pass tries.append(("WH01", "matches the body with a trailing newline stripped/added: a proxy or test tool changed the body", secret, signed_string(sch, body.rstrip("\n") if body.endswith("\n") else body + "\n", ts), enc)) if "{ts}" in sch["template"]: tries.append(("WH01", "matches HMAC over the body alone: the timestamp prefix is missing from the signed string", secret, body, enc)) if secret.startswith("whsec_"): tries.append(("WH01", "matches when the 'whsec_' prefix is removed from the secret: check how the secret is loaded", secret[len("whsec_"):], signed_string(sch, body, ts), enc)) tries.append(("WH01", "matches with a trimmed secret: the stored secret has stray whitespace", secret.strip(), signed_string(sch, body, ts), enc)) other = "base64" if enc == "hex" else "hex" tries.append(("WH01", "matches with %s encoding instead of %s: wrong digest encoding" % (other, enc), secret, signed_string(sch, body, ts), other)) for code, why, sec, msg, e in tries: if sec == secret and msg == signed_string(sch, body, ts) and e == enc: continue cand = digest(sec, msg, alg, e) if any(hmac.compare_digest(cand, r) for r in received): return code, why return None def check_delivery(d, ep, now, tolerance, skew, seen_ids): findings = [] def add(code, sev, msg): findings.append({"code": code, "severity": sev, "delivery": d.get("id"), "endpoint": ep.get("name"), "message": msg}) try: sch = scheme_for(ep) except ValueError as e: add("WH00", "high", str(e)) return findings, None headers = d.get("headers", {}) body = d.get("body") if not isinstance(body, str): add("WH00", "high", "body must be the raw request body as a string (not parsed JSON)") return findings, None raw = get_header(headers, sch["header"]) if raw is None: if ep.get("scheme") == "github" and get_header(headers, "X-Hub-Signature"): add("WH06", "medium", "only legacy X-Hub-Signature (HMAC-SHA1) present; enable and verify X-Hub-Signature-256") add("WH02", "high", "missing signature header %s: reject with 401 before doing any work" % sch["header"]) return findings, False ts = None if ep.get("scheme") == "stripe": ts, received = parse_stripe(raw) if not ts or not received: add("WH02", "high", "Stripe-Signature header has no t= or v1= part") return findings, False else: if sch["prefix"] and not raw.startswith(sch["prefix"]): add("WH01", "high", "signature does not start with %r (wrong scheme or algorithm?)" % sch["prefix"]) return findings, False received = [raw[len(sch["prefix"]):]] if sch["ts_header"]: ts = get_header(headers, sch["ts_header"]) if ts is None: add("WH02", "high", "missing timestamp header %s" % sch["ts_header"]) return findings, False if sch["alg"] in ("sha1", "md5"): add("WH06", "medium", "weak HMAC algorithm %s: prefer SHA-256 if the provider supports it" % sch["alg"].upper()) expected = digest(ep["secret"], signed_string(sch, body, ts), sch["alg"], sch["enc"]) valid = any(hmac.compare_digest(expected, r) for r in received) if not valid: hint = diagnose(sch, ep, body, ts, received) if hint and hint[0] == "WH07": add("WH07", "medium", hint[1]) valid = None # authentic but signed with the old secret elif hint: add("WH01", "high", "signature mismatch; likely cause: " + hint[1]) else: add("WH01", "high", "signature mismatch; no common mistake reproduces it: wrong secret for this endpoint, or the body was modified in transit") if ts is not None: try: tsv = int(ts) except ValueError: add("WH00", "high", "timestamp %r is not unix seconds" % ts) tsv = None if tsv is not None and now is not None: age = now - tsv if age > tolerance: add("WH03", "high", "timestamp is %d s old (tolerance %d s): possible replay, reject even if the signature is valid" % (age, tolerance)) elif age < -skew: add("WH05", "medium", "timestamp is %d s in the future (allowed skew %d s): check server clocks (NTP)" % (-age, skew)) event_id = d.get("event_id") or get_header(headers, ep.get("id_header", "X-Webhook-Id") or "") or get_header(headers, "X-GitHub-Delivery") if event_id: key = (ep.get("name"), event_id) if key in seen_ids: add("WH04", "medium", "duplicate event id %s (first seen in delivery %s): process idempotently, do not run side effects twice" % (event_id, seen_ids[key])) else: seen_ids[key] = d.get("id") else: add("WH10", "low", "no event/delivery id: cannot de-duplicate retries; store a hash of the body or ask the provider for an id header") limit = ep.get("max_body_bytes") if limit and len(body.encode("utf-8")) > limit: add("WH11", "low", "body is %d bytes, above max_body_bytes %d" % (len(body.encode("utf-8")), limit)) return findings, valid def check_endpoint(ep): out = [] def add(code, sev, msg): out.append({"code": code, "severity": sev, "delivery": None, "endpoint": ep.get("name"), "message": msg}) url = ep.get("url", "") if url and not url.lower().startswith("https://"): add("WH09", "high", "endpoint URL is not HTTPS (%s): signatures do not hide the payload" % url) sec = ep.get("secret", "") if not sec: add("WH00", "high", "no secret configured") elif len(sec) < 24 or entropy_bits(sec) < 96: add("WH08", "medium", "secret is short or low-entropy (%d chars, ~%d bits): generate at least 32 random bytes" % (len(sec), entropy_bits(sec))) if ep.get("scheme") == "github-sha1": add("WH06", "medium", "endpoint configured for HMAC-SHA1 only") return out def to_epoch(s): return int(datetime.fromisoformat(s.replace("Z", "+00:00")).astimezone(timezone.utc).timestamp()) def run(data, now_override=None): eps = {} for name, ep in data.get("endpoints", {}).items(): ep = dict(ep); ep["name"] = name; eps[name] = ep now = to_epoch(now_override) if now_override else (to_epoch(data["now"]) if data.get("now") else int(datetime.now(timezone.utc).timestamp())) tol = int(data.get("tolerance_seconds", 300)); skew = int(data.get("future_skew_seconds", 60)) findings, results, seen = [], [], {} for ep in eps.values(): findings += check_endpoint(ep) for d in data.get("deliveries", []): ep = eps.get(d.get("endpoint")) if ep is None: findings.append({"code": "WH00", "severity": "high", "delivery": d.get("id"), "endpoint": d.get("endpoint"), "message": "unknown endpoint"}) results.append({"delivery": d.get("id"), "verdict": "error"}); continue f, valid = check_delivery(d, ep, now, tol, skew, seen) findings += f hard = any(x["severity"] == "high" for x in f) verdict = "reject" if hard else ("accept-rotate-secret" if valid is None else ("accept" if valid else "reject")) if any(x["code"] == "WH04" for x in f) and verdict.startswith("accept"): verdict = "accept-duplicate(skip side effects)" results.append({"delivery": d.get("id"), "endpoint": ep["name"], "verdict": verdict}) findings.sort(key=lambda x: (SEV_ORDER[x["severity"]], x["code"], str(x["delivery"]))) summary = Counter(x["severity"] for x in findings) return {"now": now, "tolerance_seconds": tol, "results": results, "findings": findings, "summary": {k: summary.get(k, 0) for k in ("high", "medium", "low")}} def print_text(rep): print("Webhook verification report (now=%s, tolerance %ss)" % (datetime.fromtimestamp(rep["now"], timezone.utc).strftime("%Y-%m-%d %H:%M:%SZ"), rep["tolerance_seconds"])) print("\nDeliveries:") for r in rep["results"]: print(" %-6s %-14s %s" % (r["delivery"], r.get("endpoint", "?"), r["verdict"])) print("\nFindings: %(high)d high, %(medium)d medium, %(low)d low" % rep["summary"]) for f in rep["findings"]: where = f["delivery"] or ("endpoint " + str(f["endpoint"])) print(" [%s] %s %s: %s" % (f["severity"].upper(), f["code"], where, f["message"])) def self_test(): ok = 0; total = 0 def t(name, cond): nonlocal ok, total total += 1; ok += bool(cond) print(("PASS " if cond else "FAIL ") + name) sec = "whsec_selftest_7f3a9c2e5b1d48a6b0c4e2f19d7a3b58" body = '{"id":"evt_1","type":"invoice.paid","amount":4200}' ts = 1794560400 def rep_for(dels, eps=None, now=ts + 10): eps = eps or {"s": {"scheme": "stripe", "secret": sec, "url": "https://x.test/hook"}} return run({"endpoints": eps, "deliveries": dels}, datetime.fromtimestamp(now, timezone.utc).isoformat()) good = {"id": "a", "endpoint": "s", "event_id": "evt_1", "headers": sign("stripe", sec, body, ts), "body": body} r = rep_for([good]); t("stripe valid accepted", r["results"][0]["verdict"] == "accept" and r["summary"]["high"] == 0) r = rep_for([good], now=ts + 900); t("WH03 stale timestamp", any(f["code"] == "WH03" for f in r["findings"])) r = rep_for([good], now=ts - 600); t("WH05 future timestamp", any(f["code"] == "WH05" for f in r["findings"])) r = rep_for([good, dict(good, id="b")]); t("WH04 duplicate id", any(f["code"] == "WH04" for f in r["findings"]) and r["results"][1]["verdict"].startswith("accept-duplicate")) pretty = json.dumps(json.loads(body)) bad = dict(good, id="c", body=pretty, headers=sign("stripe", sec, body, ts)) r = rep_for([bad]); t("WH01 re-serialized body diagnosed", any(f["code"] == "WH01" and "re-serialized" in f["message"] for f in r["findings"])) eps = {"g": {"scheme": "github", "secret": sec, "previous_secrets": ["old_secret_value_1234567890abcdef"], "url": "https://x.test/gh"}} old = {"id": "d", "endpoint": "g", "event_id": "g1", "headers": sign("github", "old_secret_value_1234567890abcdef", body), "body": body} r = rep_for([old], eps); t("WH07 previous secret", any(f["code"] == "WH07" for f in r["findings"]) and r["results"][0]["verdict"] == "accept-rotate-secret") nohdr = {"id": "e", "endpoint": "g", "event_id": "g2", "headers": {"X-Hub-Signature": "sha1=abc"}, "body": body} r = rep_for([nohdr], eps); t("WH02 + WH06 legacy sha1 only", {"WH02", "WH06"} <= {f["code"] for f in r["findings"]}) eps2 = {"sl": {"scheme": "slack", "secret": "short", "url": "http://x.test/slack"}} sl = {"id": "f", "endpoint": "sl", "headers": sign("slack", "short", body, ts), "body": body} r = rep_for([sl], eps2); codes = {f["code"] for f in r["findings"]} t("slack valid + WH08 weak secret + WH09 http + WH10 no id", {"WH08", "WH09", "WH10"} <= codes and "WH01" not in codes) nots = {"id": "g", "endpoint": "s", "event_id": "e9", "headers": {"Stripe-Signature": "t=%d,v1=%s" % (ts, digest(sec, body, "sha256", "hex"))}, "body": body} r = rep_for([nots]); t("WH01 missing timestamp in signed string diagnosed", any("timestamp prefix" in f["message"] for f in r["findings"])) eps3 = {"sh": {"scheme": "shopify", "secret": sec, "url": "https://x.test/shop"}} hexsig = {"id": "h", "endpoint": "sh", "event_id": "s1", "headers": {"X-Shopify-Hmac-Sha256": digest(sec, body, "sha256", "hex")}, "body": body} r = rep_for([hexsig], eps3); t("WH01 hex vs base64 diagnosed", any("encoding" in f["message"] for f in r["findings"])) eps4 = {"gen": {"scheme": "generic", "header": "X-Signature", "alg": "sha512", "enc": "hex", "prefix": "", "template": "{body}", "secret": sec, "url": "https://x.test/g"}} gen = {"id": "i", "endpoint": "gen", "event_id": "x1", "headers": {"X-Signature": digest(sec, body, "sha512", "hex")}, "body": body} r = rep_for([gen], eps4); t("generic sha512 scheme accepted", r["results"][0]["verdict"] == "accept") print("%d/%d passed" % (ok, total)) return 0 if ok == total else 1 def main(): ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) ap.add_argument("file", nargs="?") ap.add_argument("--now"); ap.add_argument("--json", action="store_true") ap.add_argument("--sign", choices=sorted(SCHEMES)); ap.add_argument("--secret"); ap.add_argument("--body-file"); ap.add_argument("--timestamp", type=int) ap.add_argument("--self-test", action="store_true") a = ap.parse_args() if a.self_test: return self_test() if a.sign: if not (a.secret and a.body_file): print("--sign needs --secret and --body-file", file=sys.stderr); return 2 body = open(a.body_file, encoding="utf-8", newline="").read() ts = a.timestamp or int(datetime.now(timezone.utc).timestamp()) print(json.dumps(sign(a.sign, a.secret, body, ts), indent=2)); return 0 if not a.file: ap.print_help(); return 2 try: with open(a.file, encoding="utf-8") as fh: data = json.load(fh) rep = run(data, a.now) except (OSError, ValueError, KeyError) as e: print("bad input: %s" % e, file=sys.stderr); return 2 if a.json: print(json.dumps(rep, indent=2)) else: print_text(rep) return 1 if rep["summary"]["high"] else 0 if __name__ == "__main__": sys.exit(main())

Release Management taste

# Release Management taste of a maintainer who wants boring, predictable releases - Follow Semantic Versioning strictly for libraries; a breaking change always means a new major version. Confidence: 0.90 - Use calendar versioning for apps and services that users never install by version number. Confidence: 0.70 - Write commit messages in the Conventional Commits format so changelogs and version bumps can be generated. Confidence: 0.75 - Keep a human-edited `CHANGELOG.md` with Added, Changed, Fixed and Removed sections; generated notes are a draft, not the final text. Confidence: 0.80 - Cut releases from the main branch with an annotated, signed Git tag; never release from a laptop's local branch. Confidence: 0.90 - Let CI build, test and publish the release artifact from the tag, so nobody runs a manual publish command. Confidence: 0.90 - Build the artifact once and promote the same build from staging to production instead of rebuilding per environment. Confidence: 0.90 - Release small and often; a weekly release with ten changes is safer than a quarterly release with five hundred. Confidence: 0.85 - Put unfinished features behind flags so the release train never waits for one late feature. Confidence: 0.80 - Keep a written, tested rollback plan for every release, and prefer rolling back over fixing forward under pressure. Confidence: 0.85 - Make database migrations backward compatible so the previous version can still run after a rollback. Confidence: 0.90 - Mark deprecations one minor version before removal and print a clear warning with the replacement. Confidence: 0.85 - Use release candidates for risky major versions and give real users time to try them. Confidence: 0.70 - Roll out to a small canary group first and watch error rates before going to everyone. Confidence: 0.80 - Freeze releases on Friday afternoons and before holidays unless the change is a security fix. Confidence: 0.65 - Ship security fixes as patch releases for every supported version, not only the latest one. Confidence: 0.85 - Publish a short support policy that says which versions still get fixes and for how long. Confidence: 0.75 - Never move or delete a published tag or package version; publish a new one instead. Confidence: 0.95 - Automate the release checklist in CI and keep any remaining manual steps written in the repo. Confidence: 0.80 - Announce each release with the user-facing changes first and the upgrade steps right below them. Confidence: 0.75

Python Asyncio taste

# Python Asyncio taste of a backend developer who never blocks the event loop - Use asyncio only for I/O-bound work like network calls and databases; CPU-heavy work goes to a process pool. Confidence: 0.90 - Start the program with a single `asyncio.run(main())` and never create or manage event loops by hand. Confidence: 0.90 - Use `asyncio.TaskGroup` for running tasks together so a failure cancels the siblings and nothing leaks. Confidence: 0.85 - Never fire and forget with `create_task` without keeping a reference; lost tasks get garbage collected and errors vanish. Confidence: 0.90 - Put a timeout on every network call with `asyncio.timeout()`; waiting forever is a bug. Confidence: 0.90 - Limit concurrency with a `Semaphore` instead of starting thousands of requests at once. Confidence: 0.85 - Never call blocking libraries like `requests` or `time.sleep` inside a coroutine. Confidence: 0.95 - Wrap unavoidable blocking calls in `asyncio.to_thread` and keep them short. Confidence: 0.80 - Use async-native clients such as `httpx` or `asyncpg`, and share one client per app instead of one per request. Confidence: 0.85 - Treat `CancelledError` as normal: clean up in `finally` and re-raise it, never swallow it. Confidence: 0.90 - Avoid `asyncio.gather` without `return_exceptions` for independent jobs where one failure should not hide the others. Confidence: 0.70 - Use `asyncio.Queue` with a fixed number of worker tasks for producer and consumer pipelines. Confidence: 0.80 - Close clients, sessions and connections with `async with` so shutdown is clean. Confidence: 0.85 - Turn on asyncio debug mode in development to catch slow callbacks and never-awaited coroutines. Confidence: 0.75 - Keep sync and async code paths separate instead of writing clever wrappers that run both. Confidence: 0.75 - Do not mix threads and the event loop unless you use `run_coroutine_threadsafe` on purpose. Confidence: 0.80 - Test async code with `pytest-asyncio` or `anyio` and give tests their own short timeouts. Confidence: 0.80 - Use `contextvars` for request IDs and tracing data instead of globals. Confidence: 0.75 - Consider `uvloop` only after measuring; the default loop is fast enough for most services. Confidence: 0.65 - Handle SIGTERM by cancelling the main task and waiting for workers to finish in-flight jobs. Confidence: 0.80

Regular Expressions taste

# Regular Expressions taste of a developer who wants regexes people can still read - Reach for a real parser for HTML, JSON, CSV, URLs and email headers; a regex is the wrong tool there. Confidence: 0.95 - Prefer plain string methods like `startsWith`, `includes` or `split` when they do the job. Confidence: 0.85 - Anchor patterns with `^` and `$` (or `\A` and `\z`) when validating a whole value. Confidence: 0.90 - Use named capture groups instead of counting numbered groups. Confidence: 0.85 - Use non-capturing groups `(?:...)` when you only need grouping, not the captured value. Confidence: 0.75 - Write long patterns in verbose mode with comments, such as `re.VERBOSE` in Python or the `x` flag where supported. Confidence: 0.80 - Prefer specific character classes like `[^"]*` over a lazy `.*?` to make intent clear and matching faster. Confidence: 0.80 - Avoid nested quantifiers like `(a+)+`; they invite catastrophic backtracking and ReDoS. Confidence: 0.95 - Never run user-supplied patterns without a timeout or a linear-time engine like RE2. Confidence: 0.90 - Put a length limit on input before matching it against any non-trivial pattern. Confidence: 0.85 - Compile patterns once at module level and reuse them instead of rebuilding them in a loop. Confidence: 0.75 - Escape dynamic text with `re.escape` or an equivalent helper before putting it into a pattern. Confidence: 0.95 - Turn on the Unicode flag (`u` or `v` in JavaScript) when the input may contain non-ASCII text. Confidence: 0.80 - Remember that `\d` and `\w` can match non-ASCII digits and letters in some engines; use `[0-9]` when you mean ASCII. Confidence: 0.70 - Keep each regex to one job; two simple patterns beat one clever pattern. Confidence: 0.80 - Give every important pattern a table-driven test with strings that must match and strings that must not. Confidence: 0.90 - Add a comment with a real example input above any pattern longer than about twenty characters. Confidence: 0.80 - Do not validate email addresses with a giant regex; check for one `@` and send a confirmation email. Confidence: 0.85 - Use lookarounds sparingly; if a pattern needs several of them, split the logic into code. Confidence: 0.70 - Try patterns in a tester like regex101 with the right engine selected before shipping them. Confidence: 0.70

AI Video generation

A 10s AI video of a young Nigerian man having a conversation with his wife in the living room

AUTOMATION

So,I want an AI to go through a piece of document meticulously and extensively, now the piece of document is about a project that I am supposed to work on and automate a workflow for, I also do nor want it to skip any point and I need step by step process on how to properly execute the project with my team

Photo to Split Editorial Poster: Realistic Photo Above, Hand-Painted Illustration Below (4:5)

Transform the uploaded reference image into a beautiful, premium editorial illustration poster. Composition: Create a vertical 4:5 split-layout design. The upper half should display the original photograph in its realistic photographic style, preserving the subject's exact appearance, facial features, hairstyle, outfit, pose, and expression. The lower half should feature a beautifully stylized 2D illustration of the exact same subject, recreating the original photograph's pose, expression, clothing, and composition. Convert the subject into a charming, hand-painted digital illustration with soft brush textures, clean shapes, delicate outlines, warm skin tones, and beautiful artistic details. Background Design: Transform the original background into a creative illustrated environment. Add minimal geometric architecture, abstract shapes, subtle plants, soft natural elements, and a complementary color palette inspired by the original photograph. Poster Layout: Place the illustration inside a clean rectangular artwork frame, surrounded by a warm ivory or cream-colored background. Add a large elegant uppercase headline beneath the illustration, with a small complementary subtitle and a subtle decorative line. Typography: Use thin, sophisticated, widely spaced uppercase lettering. Choose a short title that matches the mood of the photograph, with a smaller minimalist tagline underneath. Art Direction: Modern Japanese editorial poster design, contemporary lifestyle illustration, soft pastel colors, warm sunlight, minimalist graphic design, artistic storytelling, premium magazine aesthetic. Important: Maintain the original person's identity and recognizable features. The illustrated version must clearly resemble the person in the original photograph. Keep the top photograph realistic and the bottom illustration artistic. Ensure both versions match perfectly in pose and composition. High-quality details, balanced layout, elegant negative space, professional art direction, 4:5 portrait poster.

Cute 3D Googly-Eyed Cartoon Portrait From Your Photo

Turn my photo into a cute 3D animated portrait. Preserve recognizable features and hairstyle. Add a big round head, huge googly eyes, tiny pupils, round glasses, a button nose and tiny “o” mouth. Slightly surprised expression. Oversized black turtleneck, soft matte 3D, sage-green background, chest-up, 3:4.

Vintage Tiled Portrait Poster With Handwritten Sticky Notes (JSON, 3:4)

{ "task": "Transform the uploaded photograph into a cinematic, photorealistic vintage tiled portrait poster.", "reference_image": { "source": "Use the user's uploaded photograph as the primary identity reference.", "identity_preservation": "Preserve the person's exact facial identity, facial structure, skin tone, hairstyle, eye shape, and recognizable features.", "gender": "Automatically follow the uploaded subject.", "expression": "Maintain the original expression or create a subtle, confident, natural expression." }, "composition": { "layout": "Vertical editorial poster.", "structure": "A large rectangular portrait assembled from approximately 4 columns and 5 rows of individual square, slightly irregular ceramic or paper tiles.", "portrait": "The subject occupies the central majority of the composition, visible from the head to the upper torso.", "tile_effect": "Every tile is physically separated by thin, dark, realistic grout lines. Slight variations in alignment, chipped edges, worn corners, and subtle shadows create an authentic handmade tiled-wall appearance.", "continuity": "The portrait must align seamlessly across all tiles, with facial features and body details continuing naturally across tile boundaries." }, "environment": { "background": "Muted dusty sage-gray textured plaster wall.", "surface": "Aged, slightly weathered surface with subtle imperfections.", "lighting": "Soft natural diffused daylight with gentle shadows." }, "styling": { "clothing": "Automatically create tasteful, sophisticated clothing that complements the subject's appearance. Prefer vintage-inspired casual or smart-casual styling.", "aesthetic": "Understated vintage editorial photography.", "color_palette": "Muted earthy browns, charcoal, dusty sage, warm beige and subtle faded tones." }, "personalized_details": { "sticky_notes": { "placement": "Four small yellow handwritten sticky notes positioned around the outer edges of the tiled portrait.", "messages": [ "Trust your instincts", "Big decisions", "Make it happen", "Stay fearless" ], "style": "Authentic handwritten black ink, slightly imperfect lettering, naturally curled paper corners and realistic shadows." }, "signature": "A tiny handwritten 'prompt by @yourusername' near the bottom-left tile. Omit if no username is supplied." }, "photography": { "style": "Ultra-realistic photographic portrait.", "lens": "50mm editorial portrait photography.", "details": "Natural skin texture, realistic hair strands, detailed fabric textures, subtle film grain and authentic photographic imperfections.", "color_grading": "Warm vintage film aesthetic with restrained contrast." }, "quality_control": { "priority": [ "Preserve the uploaded person's identity.", "Keep the face realistic and anatomically accurate.", "Ensure the tile grid is clearly visible.", "Maintain seamless portrait continuity across tiles.", "Keep sticky notes outside the main facial area.", "Avoid excessive AI beautification." ], "avoid": [ "Changing facial identity", "Plastic-looking skin", "Artificial facial features", "Broken tile alignment", "Floating tiles", "Excessive decorative elements", "Cartoon or illustrated appearance", "Distorted text", "Watermarks" ] }, "output": { "aspect_ratio": "3:4", "resolution": "High resolution", "rendering": "Photorealistic vintage editorial poster" } }

Movie

--- name: movie description: I want you to act as a movie critic. You will develop an engaging and creative movie review. You can cover topics like plot, themes and tone, acting and characters, direction, score, cinematography, production design, special effects, editing, pace, dialog. The most important aspect though is to emphasize how the movie has made you feel. What has really resonated with you. You can also be critical about the movie. --- # Movie Describe what this skill does and how the agent should use it. ## Instructions - Step 1: ... - Step 2: ...

Marry too early

There was this girl who married early people were making mocking of her

Man black.

Picture of a man holding the hands of a lady as well as carrying her heels, snapped hy the woman from the back

Online Income Strategist for Nigerian Students with Only a Smartphone

Act as an expert online income strategist. I'm a Nigerian student with only an Android smartphone, no laptop and little or no starting capital. Identify 10 realistic, lesser-known ways I can earn online. Prioritise opportunities with genuine demand, beginner-friendly entry requirements and international earning potential. Explain how to start each one, where to find clients, payment methods available in Nigeria, potential challenges and a 30-day action plan. No scams, unrealistic promises or paid courses.

Train Horn Spec-Sheet Normalizer

Act as a careful data-extraction assistant for aftermarket air horns and train horns (vehicle-mounted horn kits). I will paste a product listing or spec sheet. You return ONE JSON object and never invent data. Listing source: ${source:online store listing} Listing text: """ ${listing_text:Paste the listing or spec sheet here} """ RULES 1. Extract only what the text states. If a field is not stated, return null. Do not infer, estimate, or fill from general knowledge about the brand. 2. Units: convert only with exact arithmetic (1 m = 3.281 ft; 1 bar = 14.5038 psi; 1 L = 0.264172 US gal) and set that field's "converted" to true. Always keep the original wording in "raw". 3. Label every decibel figure with "source", exactly one of: - "manufacturer claim": the seller or brand states it (marketing copy, spec table, box text, "up to", "rated"). - "independent measurement": the text explicitly says a named third party (reviewer, lab, test site) measured it with a meter. - "unknown": the origin cannot be told from the text. Never upgrade a claim to a measurement. Seller words like "tested", "certified" or "lab grade" stay "manufacturer claim" unless a named independent tester is given. 4. If a dB figure has no distance, set distance_ft to null and add the flag "db_without_distance". 5. Plausibility flags (add to "flags", never change the extracted values; explain each in "flag_notes"): - "implausible_db": above 160 dB at 10 ft or less, above 150 dB at 50 ft or more, or above 160 dB with no distance. - "psi_out_of_range": required PSI below 70 or above 250. - "voltage_unusual": voltage other than 12 or 24 V DC. - "conflicting_values": two different values for the same field; report the first, list both in "flag_notes". 6. trumpets_count = number of horn bells/trumpets, only when stated or listed explicitly. 7. Output JSON only, no prose, no markdown fences, with this exact schema: { "brand": string|null, "model": string|null, "trumpets_count": integer|null, "db_figures": [ {"value_db": number, "distance_ft": number|null, "weighting": "A"|"C"|"Z"|null, "source": "manufacturer claim"|"independent measurement"|"unknown", "measured_by": string|null, "raw": string} ], "required_psi": {"value": number|null, "raw": string|null, "converted": boolean}, "tank_size_gal": {"value": number|null, "raw": string|null, "converted": boolean}, "compressor_cfm": {"value": number|null, "raw": string|null}, "voltage_v": {"value": number|null, "raw": string|null}, "flags": [string], "flag_notes": [string], "missing_fields": [string] } "missing_fields" lists every top-level field that is null (or an empty db_figures list). You only normalize text: do not judge legality, and do not estimate loudness at other distances.

Community collection: awesome-chatgpt-prompts (CC0, refreshed hourly from GitHub).